Skip to content

Commit

Permalink
Prevent bind error with undefined/null parameters (#375)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
fb64 committed Mar 31, 2020
1 parent cd66237 commit fa49dae
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/api.js
Expand Up @@ -208,9 +208,11 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
}

/** @typedef {string|number|null|Uint8Array} Database.SqlValue */
/** @typedef {Database.SqlValue[]|Object<string, Database.SqlValue>} Statement.BindParams */
/** @typedef {Database.SqlValue[]|Object<string, Database.SqlValue>|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.
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions test/test_statement.js
Expand Up @@ -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();
};
Expand Down

0 comments on commit fa49dae

Please sign in to comment.