Skip to content

Commit fa49dae

Browse files
authored
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.
1 parent cd66237 commit fa49dae

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

src/api.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,11 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
208208
}
209209

210210
/** @typedef {string|number|null|Uint8Array} Database.SqlValue */
211-
/** @typedef {Database.SqlValue[]|Object<string, Database.SqlValue>} Statement.BindParams */
211+
/** @typedef {Database.SqlValue[]|Object<string, Database.SqlValue>|null} Statement.BindParams
212+
*/
212213

213-
/** Bind values to the parameters, after having reseted the statement
214+
/** Bind values to the parameters, after having reseted the statement.
215+
* If values is null, do nothing and return true.
214216
*
215217
* SQL statements can have parameters, named *'?', '?NNN', ':VVV', '@VVV', '$VVV'*,
216218
* where NNN is a number and VVV a string.
@@ -251,10 +253,9 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
251253
throw "Statement closed";
252254
}
253255
this["reset"]();
254-
if (Array.isArray(values)) {
255-
return this.bindFromArray(values);
256-
}
257-
return this.bindFromObject(values);
256+
if (Array.isArray(values)) return this.bindFromArray(values);
257+
if (values != null && typeof values === "object") return this.bindFromObject(values);
258+
return true;
258259
};
259260

260261
/** Execute the statement, fetching the the next line of result,

test/test_statement.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ exports.test = function(sql, assert){
6565
result = stmt.get({':start':1, ':end':1});
6666
assert.deepEqual(result, ['a',1], "Binding named parameters");
6767

68+
// Prepare statement, pass null to bind() and check that it works
69+
stmt = db.prepare("SELECT 'bind-with-null'");
70+
result = stmt.bind(null);
71+
assert.equal(result, true);
72+
stmt.step();
73+
result = stmt.get();
74+
assert.equal(result,"bind-with-null")
75+
6876
// Close the database and all associated statements
6977
db.close();
7078
};

0 commit comments

Comments
 (0)