rockdai / sql-bricks

Transparent, Schemaless SQL Generation
http://csnw.github.io/sql-bricks
MIT License
210 stars 25 forks source link

Converting Object column with arrary to in clause #131

Open doshisunny opened 2 years ago

doshisunny commented 2 years ago

I was trying to implement this is my use case so I was wondering if its possible to add support for this. Here is the scenario: I am trying to pass dynamic object to where clause which has list of values for some of the properties. So if I pass data like this select().from('person').where({last_name: 'Rubble', codes: ['ABC' , 'XYZ'}).toString(); it will convert to // SELECT * FROM person WHERE last_name = 'Rubble' and codes in ('ABC' , 'XYZ')

Reason for me to use it like this is due to I have dynamic input for table name and column values so this way it will be able to generate clause dynamically.

But current support is only for equal operator and not in clause. https://github.com/CSNW/sql-bricks/blob/a004a72c17bc0010366bbd8cfeb5f1590db16c4e/sql-bricks.js#L975-L981

So above instead of expressions.push(sql.equal(col, obj[col])); I tried using is clause conditionally and it works fine.

  function objToEquals(obj) {
    var expressions = [];
    for (var col in obj) {
      if (!Array.isArray(obj[col])) {
        expressions.push(sql.equal(col, obj[col]))
      } else {
        expressions.push(sql.in(col, obj[col]))
      }
    }
    return expressions;
  }

Is it possible to support this?

I am also open to creating PR.