Skip to content

Incorrect value index when using where(sql(...)) #130

Description

@w33ble

I ran in to an issue when using multiple .where(...) methods with nested sql(...) methods. Here's a pretty simple example:

const query = sql.select('*')
    .from('user')
    .join('comments').on({ 'comment.user_id': 'user.id' })
    .where({ 'user.id': 1 })
    .where(sql('comment.published = $', true))
    .where({ 'user.active': true })
    .orderBy('comment.created_at')

Using this with .toString() works fine, but as the docs point out, this string shouldn't be used to execute queries as the values are not properly escaped. When using .toParams(), the result is close, but the indexes in the statement are incorrectly numbered. Here's the output:

{
  text: 'SELECT * FROM "user" INNER JOIN comments ON comment.user_id = "user".id WHERE "user".id = $1 AND comment.published = $2 AND "user".active = $4 ORDER BY comment.created_at',
  values: [ 1, true, true ]
}

Note that the indexes are $1, $2, and $4, and there is no $3. As a result, when passing the text and values into the pg client, you get an error. It only seems to happen if you call .where(...) after you call .where(sql(...)), and it keeps getting worse if you have multiple .where(sql(...)) calls.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions