Vincit / objection.js

An SQL-friendly ORM for Node.js
https://vincit.github.io/objection.js
MIT License
7.24k stars 636 forks source link

Cast text column to integer for the PostgreSQL #592

Closed AndriyGd closed 6 years ago

AndriyGd commented 6 years ago

I tried to use join with different type columns as "text" and 'integer' For converting text to integer I using native method PostgreSQL named 'cast'.

My query.

let task = await Plst.query().select('ECO1', 'STZW', 'STPA', 'KLAR', 'PNUM', 'a.ATTE', 'FZ_TFZU_1')
                                .leftOuterJoin('ATST as a', 'cast(PLST.FZ_TFZU_1 as int)', 'a.ATNU')
                                .where('PLST.PNUM', '=', req)
                                .andWhere('PLST.GPR1', '>', 0)
                                .andWhere('PLST.WALO', '=', 0);  

But I'm got exception.

{ error: syntax error at or near "as"
    at Connection.parseE (D:\project\demo-test\node_modules\pg\lib\connection.js:546:11)
    at Connection.parseMessage (D:\project\demo-test\node_modules\pg\lib\connection.js:371:19)
    at Socket.<anonymous> (D:\project\demo-test\node_modules\pg\lib\connection.js:114:22)
    at emitOne (events.js:115:13)
    at Socket.emit (events.js:210:7)
    at addChunk (_stream_readable.js:266:12)
    at readableAddChunk (_stream_readable.js:253:11)
    at Socket.Readable.push (_stream_readable.js:211:10)
    at TCP.onread (net.js:585:20)}

...the sql

select "ECO1", "STZW", "STPA", "KLAR", "PNUM", "a"."ATTE", "FZ_TFZU_1" 
from "public"."PLST" 
left outer join "ATST" as "a" on "cast(PLST"."FZ_TFZU_1" as "int)" = "a"."ATNU" 
where "PLST"."PNUM" = 3271 
and "PLST"."GPR1" > 0 
and "PLST"."WALO" = 0

How may be resolved this issue.

koskimas commented 6 years ago

Objection and knex escape all inputs to prevent SQL injection attacks. You need to use raw:

const { raw } = require('objection');

let task = await Plst.query()
  .select('ECO1', 'STZW', 'STPA', 'KLAR', 'PNUM', 'a.ATTE', 'FZ_TFZU_1')
  .leftOuterJoin('ATST as a', raw('cast(PLST.FZ_TFZU_1 as int)'), 'a.ATNU')
  .where('PLST.PNUM', '=', req)
  .andWhere('PLST.GPR1', '>', 0)
  .andWhere('PLST.WALO', '=', 0); 
AndriyGd commented 6 years ago

Thanks a lot. It has helped for me.