Skip to content

Commit

Permalink
sqlite: Parse number part of PragmaSignature: NULL_OR_NUMBER as an in…
Browse files Browse the repository at this point in the history
…t32_t

The [SQLite
documentation](https://www.sqlite.org/pragma.html#pragma_optimize) for
`PRAGMA optimize` says:

> To see all optimizations that would have been done without actually
> doing them, run "PRAGMA optimize(-1)".

We parsed the mask as a `uint` (which makes sense for a mask!), but
that precludes us from parsing negative literals and caused `PRAGMA
optimize(-1)` to fail.  Parsing as an `int32_t` admits this statement.

(I chose to use `int32_t` rather than `int` because SQLite uses a
32-bit integer for the mask.)

Annoyingly, SQLite’s internal `sqlite3GetInt32` function doesn’t allow
you to write a negative number with hex strings, so the best way to
flip (almost) all the bits using hex is using the 0x7fffffff literal.
  • Loading branch information
justin-mp committed Feb 24, 2025
1 parent f7bcdbb commit ed138c0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/workerd/api/sql-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,21 @@ async function test(state) {
//
// The following sequence of calls is mentioned by https://www.sqlite.org/lang_analyze.html as how
// one might optmize the query planner.
{
// Dry-run. SQLite's documentation uses -1 as the debug example.
assert.deepEqual(Array.from(sql.exec('PRAGMA optimize(-1);')), [
{ optimize: 'ANALYZE "main"."myTable"' },
{ optimize: 'ANALYZE "main"."_cf_KV"' },
]);
}
{
// Dry-run. This sets all of the bits except for the sign bit because SQLite's optimize
// function doesn't parse hex numbers into negative integers.
assert.deepEqual(Array.from(sql.exec('PRAGMA optimize(0x7fffffff);')), [
{ optimize: 'ANALYZE "main"."myTable"' },
{ optimize: 'ANALYZE "main"."_cf_KV"' },
]);
}
{
let info = [...sql.exec('PRAGMA optimize=0x10002;')];
assert.equal(info.length, 0);
Expand Down
2 changes: 1 addition & 1 deletion src/workerd/util/sqlite.c++
Original file line number Diff line number Diff line change
Expand Up @@ -1057,7 +1057,7 @@ bool SqliteDatabase::isAuthorized(int actionCode,
// Argument is not required
auto val = KJ_UNWRAP_OR(param2, return true);
// val is allowed if it parses to an integer
return val.tryParseAs<uint>() != kj::none;
return val.tryParseAs<int32_t>() != kj::none;
}
case PragmaSignature::NULL_NUMBER_OR_OBJECT_NAME: {
// Argument is not required
Expand Down

0 comments on commit ed138c0

Please sign in to comment.