brianc/node-sql

Named parameters

Opened this issue · 3 comments

Is it possible to enable named parameters? For example in MSSQL dialect, generate @userID instead of @1?

As far as I know it is not possible. I'm not even sure what that would look like. How would you specify what the parameter named to be generated should look like? For example in a query like:

var query=table.select().where(table.col.equals("10"))

I'm really not sure, could it look something like this?

var query=table.select().where(table.col.equals("ID"))

and then specify later that ID = 10

query.input('ID', 10)

and then query.values would be an object rather than an array, {ID: 10}

I think it could be useful in a scenario where you inserting (or updating, selecting etc) objects from a json array without having to worry about the positions of your generated parameters.

For example:

var sql = require('sql');

sql.setDialect('mssql');

var post = sql.define({
  name: 'post',
  columns: ['id', 'comment']
});

var aPost =  {
    id: 1, 
    comment: 'One Post'
  };

var insertPosts = post.insert(aPost);

In this case, calling .toQuery() returns this object:

{ 
  text: 'INSERT INTO [post] ([id], [comment]) VALUES (@1, @2)',
  values: [ 1, 'One Post' ] 
}

Instead, it could returning this:

{ 
    text: 'INSERT INTO [post] ([id], [comment]) VALUES (@id, @comment)',
    values: {
              id: 1, 
              comment: 'One Post'
            }
}

And then, you could just iterate an array of objects, replacing it in your database calls

var insertText = post.insert(aPost).toQuery.text;

var posts = [
  {
    id: 1, 
    comment: 'Comment 1', 
    userId: 2
  },
  {
    id: 2,
    comment: 'Comment 2'
  },
  {
    comment: 'Comment 3', 
    id: 3
  }
];

posts.forEach(function(post) {
  myDatabaseConnectio.execute(insertText, post);
}, this);