Knex: Select calculated column?

Created on 18 Dec 2014  ·  3Comments  ·  Source: knex/knex

I'm trying to write a query using the postgresql earthdistance extension and I want to return a calculated column, but I keep getting an error about: missing FROM-clause entry for table "670906,-79". This is presumably because the parser thinks that a dot separates a table-name from a column-name, but in my case I'm performing a calculation (see example query below). Is there a way to work around this?

Possibly unhandled error: missing FROM-clause entry for table "670906,-79"
    at Connection.parseE (/usr/local/lib/node_modules/pg/lib/connection.js:534:11)
    at Connection.parseMessage (/usr/local/lib/node_modules/pg/lib/connection.js:361:17)
    at Socket.<anonymous> (/usr/local/lib/node_modules/pg/lib/connection.js:105:22)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:764:14)
    at Socket.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:426:10)
    at emitReadable (_stream_readable.js:422:5)
    at readableAddChunk (_stream_readable.js:165:9)
    at Socket.Readable.push (_stream_readable.js:127:10)
  var columns = [
    'id',
    '(earth_distance(ll_to_earth(lat, lng), ll_to_earth(43.670906, -79.393331)) as distance)'
  ];
  var result = knex
    .select(columns)
    .from('stores')
    .whereRaw('earth_box(ll_to_earth(43.670906, -79.393331), ?) @> ll_to_earth(lat, lng)', [radiusInStatuteMiles])
question

Most helpful comment

You should use knex.raw for your calculated column, so it does not get quoted. The following should work:

var columns = [
  'id',
  knex.raw('earth_distance(ll_to_earth(lat, lng), ll_to_earth(43.670906, -79.393331)) as distance')
];
var result = knex
.select(columns)
.from('stores')
.whereRaw('earth_box(ll_to_earth(43.670906, -79.393331), ?) @> ll_to_earth(lat, lng)', [radiusInStatuteMiles])

All 3 comments

You should use knex.raw for your calculated column, so it does not get quoted. The following should work:

var columns = [
  'id',
  knex.raw('earth_distance(ll_to_earth(lat, lng), ll_to_earth(43.670906, -79.393331)) as distance')
];
var result = knex
.select(columns)
.from('stores')
.whereRaw('earth_box(ll_to_earth(43.670906, -79.393331), ?) @> ll_to_earth(lat, lng)', [radiusInStatuteMiles])

Thanks! Exactly what I needed. Somehow didn't think of using knex.raw.

You're welcome!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mishitpatel picture mishitpatel  ·  3Comments

nklhrstv picture nklhrstv  ·  3Comments

tjwebb picture tjwebb  ·  3Comments

legomind picture legomind  ·  3Comments

olaferlandsen picture olaferlandsen  ·  3Comments