Skip to content

Model#raw does not handle RawBuilders and ReferenceBuilders #1077

@olavim

Description

@olavim

Model.raw works differently from the raw helper function. With raw I can do the following:

const query = Movie.query().debug()
  .where(raw('?? = ?', [ref('id'), 1])) // Find movies with id = 1
  .then(() => {})

/* debug output:
{ 
  method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 1 ],
  __knexQueryUid: 'f44e58c4-76af-43d2-8227-f504999beac9',
  sql: 'select "movies".* from "movies" where "id" = ?' 
}
*/

SQL is fine.

With Movie.raw, however, I get gibberish:

Movie.query().debug()
  .where(Movie.raw('?? = ?', [ref('id'), 1]))
  .then(() => {})

/* debug output:
{ 
  method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 1 ],
  __knexQueryUid: 'eb69c0b7-b0e8-48b9-818d-3dd600276df2',
  sql: 'select "movies".* from "movies" where "id" as "_expr", "id" as "columnName",  as "access" as "_reference", "id" as "_column",  as "_table",  as "_cast", "false" as "_toJson",  as "_as" = ?' 
}
*/

Having identical behaviour is important when developing plugins/mixins. I don't want to have an additional dependency on objection, which is why I need to use Model.raw instead of the helper function.

I have worked around this in my code by calling .toKnexRaw (when it exists) on values passed to Model.raw:

const colRef = ref('id').toKnexRaw(Movie.knex());
Movie.query().debug()
  .where(Movie.raw('?? = ?', [colRef, 1]))
  .then(() => {})

/* debug output:
{ 
  method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 1 ],
  __knexQueryUid: '4e60177e-645b-4dc5-9e37-b3f27b3f852c',
  sql: 'select "movies".* from "movies" where "id" = ?' 
}
*/

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions