From fa49dae19af5c710020ad86bffb409e797bbb9df Mon Sep 17 00:00:00 2001 From: Florian Bernard Date: Tue, 31 Mar 2020 17:40:54 +0200 Subject: [PATCH] Prevent bind error with undefined/null parameters (#375) statement.bind(null) initially did not throw an error (and did not bind any parameter either), by chance, because of the way iteration on bind parameters was implemented. Libraries such as https://github.com/typeorm/typeorm came to depend on this undocumented behavior. After the port from coffescript to javascript, calling statement.bind with null started to throw an error, which broke some dependent code. This commit reintroduces the original behavior, documents it, and adds a test for it. --- src/api.js | 13 +++++++------ test/test_statement.js | 8 ++++++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/api.js b/src/api.js index 38c3f729..f2ae0580 100644 --- a/src/api.js +++ b/src/api.js @@ -208,9 +208,11 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { } /** @typedef {string|number|null|Uint8Array} Database.SqlValue */ - /** @typedef {Database.SqlValue[]|Object} Statement.BindParams */ + /** @typedef {Database.SqlValue[]|Object|null} Statement.BindParams + */ - /** Bind values to the parameters, after having reseted the statement + /** Bind values to the parameters, after having reseted the statement. + * If values is null, do nothing and return true. * * SQL statements can have parameters, named *'?', '?NNN', ':VVV', '@VVV', '$VVV'*, * where NNN is a number and VVV a string. @@ -251,10 +253,9 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { throw "Statement closed"; } this["reset"](); - if (Array.isArray(values)) { - return this.bindFromArray(values); - } - return this.bindFromObject(values); + if (Array.isArray(values)) return this.bindFromArray(values); + if (values != null && typeof values === "object") return this.bindFromObject(values); + return true; }; /** Execute the statement, fetching the the next line of result, diff --git a/test/test_statement.js b/test/test_statement.js index 9bdbc7e2..8ac9ef4f 100644 --- a/test/test_statement.js +++ b/test/test_statement.js @@ -65,6 +65,14 @@ exports.test = function(sql, assert){ result = stmt.get({':start':1, ':end':1}); assert.deepEqual(result, ['a',1], "Binding named parameters"); + // Prepare statement, pass null to bind() and check that it works + stmt = db.prepare("SELECT 'bind-with-null'"); + result = stmt.bind(null); + assert.equal(result, true); + stmt.step(); + result = stmt.get(); + assert.equal(result,"bind-with-null") + // Close the database and all associated statements db.close(); };