Skip to content

Raw query with named substitution parameters gets quoted parameters #4494

Closed

Description

@czardoz

I'm using sequelize to perform a simple raw query:

    var queryStr = 'SELECT * FROM :tableName WHERE :deletionColumn > 0 LIMIT :limit;';

    return self.connection.query(queryStr, {
        replacements: {
            tableName: self.name,
            deletionColumn: self.options.deletionColumn,
            limit: self.options.limit
        }
    }).then(function (rowsToDelete) {
        _.each(rowsToDelete, function (row) {
            log.debug('Preparing to delete row: ', row);
        });
    });

The resulting query however, is (from the sequelize logs):

Executing (default): SELECT * FROM 'test' WHERE 'deleted' > 0 LIMIT 421;

The generated query is invalid (table name must not be quoted).

Are there any options I can pass that'll disable the quoting?
I'm using MySQL 5.6 here.

Activity

  1. janmeier commented on Sep 16, 2015

    @janmeier
    Member

    This is not possible currently

    First we'd need to come up with a syntax for this - any suggestions @czardoz ?

  2. added
    type: feature
    good first issue
    on Sep 16, 2015
  3. czardoz commented on Sep 16, 2015

    @czardoz
    Author

    Coming up with new syntax might not be necessary.

    Something like this should work too:

         replacements: {
                tableName: {value: self.name, quote: false}
            }
    

    Edit: Apologies for the bad formatting, I'm typing on my phone

  4. janmeier commented on Sep 16, 2015

    @janmeier
    Member

    Yeah, that coudl work as well :)

    PR welcome

  5. mickhansen commented on Sep 17, 2015

    @mickhansen
    Contributor

    Hmm, but the value of tableName could be a JSON object that needs to be inserted as JSON.
    We probably want to use $ prefixed keys.

  6. mickhansen commented on Sep 17, 2015

    @mickhansen
    Contributor

    This change would also not make a lot of room for introducing proper prepared queries later, perhaps a different identifier than : for tables/identifiers? Not sure what other libraries do for this type of stuff? Some research might be warranted.

  7. janmeier commented on Sep 17, 2015

    @janmeier
    Member

    I do remember we previously had support for using ?? as unescaped with unnamed replacement - but that won't work since :: has a different meaning in postgres

  8. czardoz commented on Sep 17, 2015

    @czardoz
    Author

    This is a pretty uncommon use case (I think), and I am not sure if this needs to be implemented at all. I've currently worked around this using Mustache, and it works just fine. The documentation should definitely be updated to point this out though.

  9. alitaheri commented on Oct 13, 2015

    @alitaheri
    Contributor

    guys come on, don't we already have a familiar syntax for this: sequelize.col('deleted') 😁

  10. janmeier commented on Oct 13, 2015

    @janmeier
    Member

    @subjectix Quoting columns is not the issue - its not quoting everything else

  11. alitaheri commented on Oct 13, 2015

    @alitaheri
    Contributor

    From what I get, we need some way to escape from quoting. I wasn't explicitly referring to col I was referring to the pattern. we can add a feature like: sequelize.unquote('tableOrColumnOrFunction') that we can use like:

    replacements: {
        tableName: sequelize.unquote('tableName')
    }

    The unquote function will return an instance of a function we can check with instanceof and not quote the result if it's string only sanitize it.

  12. janmeier commented on Oct 20, 2015

    @janmeier
    Member

    @subjectix Actually we already have sequelize.literal which might be usefull here - we'd just need to implement support for that in the format method then

  13. alitaheri commented on Oct 20, 2015

    @alitaheri
    Contributor

    Good idea! I didn't know that 😁

  14. eraye1 commented on Apr 8, 2016

    @eraye1

    Is there a solution to this?

  15. 12 remaining items

  16. robin-dunn commented on Dec 24, 2019

    @robin-dunn

    Would also like to see this feature implemented.

  17. added
    status: understood
    on Jan 16, 2020
  18. repodevs commented on Jun 13, 2020

    @repodevs

    Is there anyone working on this issue?

  19. aayushmall commented on Jul 17, 2020

    @aayushmall

    Any update on this issue, as I also need something like this with sequelize, having dynamic table names from the input.

  20. guhkun13 commented on Apr 5, 2021

    @guhkun13

    think I found it . You can combine between backquote string and double string

    Example :
    table_name = 'users'

    db.default.query( `SELECT name FROM ${table_name} ` + " WHERE age= :age" { replacements: { age: 24, }, type: QueryTypes.SELECT, } )

    noted that i use backquote `` until FROM table_name part, and the rest i used double quote like usual.

  21. czardoz commented on Apr 5, 2021

    @czardoz
    Author
  22. guhkun13 commented on Apr 6, 2021

    @guhkun13

    really appreciate the reminder,
    and so, is there any safe solution ?

    [update]
    so my new approach is using conditional statement, to call another function that corresponds to the table name, so i avoid using raw query as sugggested.
    i think it's more "micro", and dynamic enough to add custom things on the corresponds function.

    but then,
    I need to do something like :
    " select * from users where email = 'something' and id not in (select user_id from users_banned) "

    i did not find (yet) how to do this without using raw sql...
    any help would be very appreciated

  23. meSmashsta commented on Apr 28, 2021

    @meSmashsta

    Guys, it's 2021, where are we with this? :'(

  24. meSmashsta commented on Apr 28, 2021

    @meSmashsta

    For those wandering souls just like me, I manually escaped them like so :'(

    1. First I check if the column my user want to order is valid
    2. If valid interpolate it in the query string else throw an error
    const { Sequelize } = require('sequelize');
    const sequelize = new Sequelize('postgres://postgres:postgres@localhost:5432/test_db');
    
    const orderByColumn = 'username';
    const columns = Object.keys(Agent.rawAttributes);
    const isColumnPartOfModel = columns.indexOf(orderByColumn) != -1;
    if (!isColumnPartOfModel) {
        throw new Error('Unknown column');
    }
    const orderByDirection = 'ASC';
    const validDirections = ['ASC', 'DESC'];
    if (orderByDirection.indexOf(orderByDirection) === -1) {
        throw new Error('Ordering direction is not valid');
    }
    sequelize.query(`SELECT * FROM players ORDER BY ${orderByColumn} ${orderByDirection}`);
  25. guhkun13 commented on Apr 29, 2021

    @guhkun13

    for the steps, i prefer to separate the process of validation and actions (controller).

    1. using middleware to validate input (im using express-validator); columnName, orderDirection, etc.
      by doing that, controller only accept 'validated data'
    2. then in controller, u can query it in ORM way. in my experience, it's a bit faster than using raw query (cmiiw)
  26. AZS-99 commented on Aug 24, 2021

    @AZS-99

    Almost 7 years and still nothing .... Any update on this apart from the cricket in the background?

  27. rscottlundgren commented on Aug 9, 2022

    @rscottlundgren

    @czardoz - Is this issue still "up for grabs"? It's been open for awhile and it would be cool for me to have my first issue be something that's both older and seemingly impactful. Please let me know!

  28. ephys commented on Oct 3, 2022

    @ephys
    Member

    Feature #14299 should be able to cover the use cases discussed in this issue:

    sequelize.query(sql`SELECT * FROM ${sql.identifier(tableName)} WHERE ${sql.identifier(deletionColumn)} > 0 LIMIT :limit;`, {
      replacements: { limit },
    })
  29. Villva-vinoth commented on Nov 25, 2024

    @Villva-vinoth

    await sequelize.query(create role :username,{
    type:QueryTypes.RAW,
    replacements:{username:data.user_name},
    transaction
    })

    Is there any body help to fix this
    create role 'admin'

    i m still getting the issue quote and thanks in advance

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

    good first issuestatus: understoodtype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions