mysqljs / mysql

A pure node.js JavaScript Client implementing the MySQL protocol.
MIT License
18.31k stars 2.53k forks source link

Proposal for named parameters binding #133

Closed Koc closed 13 years ago

Koc commented 13 years ago

It would be nice support this

conn.query('INSERT INTO table1 SER field1 = :field1, field2 = :field2 ON DUPLICATE KEY UPDATE field2 = :field2', {field1: 1, field2: 2});
felixge commented 13 years ago

Nice: yes. But a little too high-level for this driver, so I'm probably not adding this for now.

ghost commented 10 years ago

While waiting for this feature :

/**
 * Return array with modified instruction as first entry, and indexed anonymous parameters as second entry,  that can be intepreted by node-mysql mysql driver
 * @param {string} sqlCommandSring Instruction's raw content
 * @param {object} binds Named parameters plain object
 * @returns {Array}
 */
var getStatement = function( sqlCommandSring, binds )
{
    var indexedBinds = [];

    var commandFoundedBinds = sqlCommandSring.match(/(:[a-zA-Z_]+)/g);

    commandFoundedBinds.forEach(function(bindString, index)
    {
        var clean_name = bindString.replace(/:/, "");

        if( binds.hasOwnProperty(clean_name) )
        {
            var rgx = new RegExp("("+ bindString +")");

            sqlCommandSring = sqlCommandSring.replace(rgx, "?");

            indexedBinds.push( binds[ clean_name ] );
        }
    });

    return [ sqlCommandSring, indexedBinds ];
};

Usage :

var stmt = getStatement("INSERT INTO table1 SER field1 = :field1, field2 = :field2 ON DUPLICATE KEY UPDATE field2 = :field2", {field1: 1, field2: 2});
connection.execute( stmt[0], stmt[1], function(err, res)
{
    console.log( res );
});

Returns :

[
    "INSERT INTO table1 SER field1 = ?, field2 = ? ON DUPLICATE KEY UPDATE field2 = ?",
    [
        1,
        2,
        2
    ]
]

Very basic, can be enhanced

sidorares commented 10 years ago

I created module to transform query with named placeholders + parameters hash into unnamed + array

See similar discussion in node-mysql2 https://github.com/sidorares/node-mysql2/issues/117

Example:

var mysql = require('mysql');
var toUnnamed = require('named-placeholders')();

var q = toUnnamed('select 1+:test', { test: 123});
var sql = q[0];
var parameters = q[1];
mysl.createConnection().query(sql, parameters);

Not sure if it should belong to core driver (maybe should, most other mysql clients expose pdo-style parameters).

pihvi commented 8 years ago

Here's a library for this also supporting ?? syntax:

var sql = require('yesql').mysql

var selectById = sql('SELECT * from ::table_name WHERE id = :id;')
connection.query(selectById({id: 5, table_name: 'pokemon'}), callback)
pupudu commented 6 years ago

@felixge Is this still a no no for this library? (since it's been almost 7 years)

dougwilson commented 6 years ago

The module is part of the mysqljs org. Use it when you need it.