From 174937fe2623cb718bae2516f28fbf2792aeb132 Mon Sep 17 00:00:00 2001 From: Colin McDonnell <3084745+colinhacks@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:23:16 -0800 Subject: [PATCH 1/4] feat: attach SQLite's result code to thrown errors An SQLite error was thrown as an Error with only its message, so a caller had to match the text to tell a constraint violation from any other failure. Set code to the name of SQLite's extended result code and errcode to its number, as other SQLite bindings do. --- src/api.js | 74 ++++++++++++++++++++++++++++++++++++- src/exported_functions.json | 1 + test/test_errors.js | 49 ++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 2 deletions(-) diff --git a/src/api.js b/src/api.js index 30d59d09..470af2de 100644 --- a/src/api.js +++ b/src/api.js @@ -80,6 +80,60 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { var SQLITE_INSERT = 18; var SQLITE_UPDATE = 23; var SQLITE_DELETE = 9; + // var - Result code names, primary and extended, by number + var SQLITE_CODE_NAMES = { + 0: "SQLITE_OK", 256: "SQLITE_OK_LOAD_PERMANENTLY", + 512: "SQLITE_OK_SYMLINK", 1: "SQLITE_ERROR", + 257: "SQLITE_ERROR_MISSING_COLLSEQ", 513: "SQLITE_ERROR_RETRY", + 769: "SQLITE_ERROR_SNAPSHOT", 1025: "SQLITE_ERROR_RESERVESIZE", + 1281: "SQLITE_ERROR_KEY", 1537: "SQLITE_ERROR_UNABLE", + 2: "SQLITE_INTERNAL", 3: "SQLITE_PERM", 4: "SQLITE_ABORT", + 516: "SQLITE_ABORT_ROLLBACK", 5: "SQLITE_BUSY", 6: "SQLITE_LOCKED", + 7: "SQLITE_NOMEM", 8: "SQLITE_READONLY", + 264: "SQLITE_READONLY_RECOVERY", 520: "SQLITE_READONLY_CANTLOCK", + 776: "SQLITE_READONLY_ROLLBACK", 1032: "SQLITE_READONLY_DBMOVED", + 1288: "SQLITE_READONLY_CANTINIT", 1544: "SQLITE_READONLY_DIRECTORY", + 9: "SQLITE_INTERRUPT", 10: "SQLITE_IOERR", 266: "SQLITE_IOERR_READ", + 522: "SQLITE_IOERR_SHORT_READ", 778: "SQLITE_IOERR_WRITE", + 1034: "SQLITE_IOERR_FSYNC", 1290: "SQLITE_IOERR_DIR_FSYNC", + 1546: "SQLITE_IOERR_TRUNCATE", 1802: "SQLITE_IOERR_FSTAT", + 2058: "SQLITE_IOERR_UNLOCK", 2314: "SQLITE_IOERR_RDLOCK", + 2570: "SQLITE_IOERR_DELETE", 2826: "SQLITE_IOERR_BLOCKED", + 3082: "SQLITE_IOERR_NOMEM", 3338: "SQLITE_IOERR_ACCESS", + 3594: "SQLITE_IOERR_CHECKRESERVEDLOCK", 3850: "SQLITE_IOERR_LOCK", + 4106: "SQLITE_IOERR_CLOSE", 4362: "SQLITE_IOERR_DIR_CLOSE", + 4618: "SQLITE_IOERR_SHMOPEN", 4874: "SQLITE_IOERR_SHMSIZE", + 5130: "SQLITE_IOERR_SHMLOCK", 5386: "SQLITE_IOERR_SHMMAP", + 5642: "SQLITE_IOERR_SEEK", 5898: "SQLITE_IOERR_DELETE_NOENT", + 6154: "SQLITE_IOERR_MMAP", 6410: "SQLITE_IOERR_GETTEMPPATH", + 6666: "SQLITE_IOERR_CONVPATH", 6922: "SQLITE_IOERR_VNODE", + 7178: "SQLITE_IOERR_AUTH", 7434: "SQLITE_IOERR_BEGIN_ATOMIC", + 7690: "SQLITE_IOERR_COMMIT_ATOMIC", + 7946: "SQLITE_IOERR_ROLLBACK_ATOMIC", 8202: "SQLITE_IOERR_DATA", + 8458: "SQLITE_IOERR_CORRUPTFS", 8714: "SQLITE_IOERR_IN_PAGE", + 8970: "SQLITE_IOERR_BADKEY", 9226: "SQLITE_IOERR_CODEC", + 11: "SQLITE_CORRUPT", 267: "SQLITE_CORRUPT_VTAB", + 523: "SQLITE_CORRUPT_SEQUENCE", 779: "SQLITE_CORRUPT_INDEX", + 12: "SQLITE_NOTFOUND", 13: "SQLITE_FULL", 14: "SQLITE_CANTOPEN", + 270: "SQLITE_CANTOPEN_NOTEMPDIR", 526: "SQLITE_CANTOPEN_ISDIR", + 782: "SQLITE_CANTOPEN_FULLPATH", 1038: "SQLITE_CANTOPEN_CONVPATH", + 1294: "SQLITE_CANTOPEN_DIRTYWAL", 1550: "SQLITE_CANTOPEN_SYMLINK", + 15: "SQLITE_PROTOCOL", 16: "SQLITE_EMPTY", 17: "SQLITE_SCHEMA", + 18: "SQLITE_TOOBIG", 19: "SQLITE_CONSTRAINT", + 275: "SQLITE_CONSTRAINT_CHECK", 531: "SQLITE_CONSTRAINT_COMMITHOOK", + 787: "SQLITE_CONSTRAINT_FOREIGNKEY", + 1043: "SQLITE_CONSTRAINT_FUNCTION", 1299: "SQLITE_CONSTRAINT_NOTNULL", + 1555: "SQLITE_CONSTRAINT_PRIMARYKEY", + 1811: "SQLITE_CONSTRAINT_TRIGGER", 2067: "SQLITE_CONSTRAINT_UNIQUE", + 2323: "SQLITE_CONSTRAINT_VTAB", 20: "SQLITE_MISMATCH", + 21: "SQLITE_MISUSE", 22: "SQLITE_NOLFS", 23: "SQLITE_AUTH", + 279: "SQLITE_AUTH_USER", 24: "SQLITE_FORMAT", 25: "SQLITE_RANGE", + 26: "SQLITE_NOTADB", 27: "SQLITE_NOTICE", + 283: "SQLITE_NOTICE_RECOVER_WAL", + 539: "SQLITE_NOTICE_RECOVER_ROLLBACK", 795: "SQLITE_NOTICE_RBU", + 28: "SQLITE_WARNING", 284: "SQLITE_WARNING_AUTOINDEX", + 100: "SQLITE_ROW", 101: "SQLITE_DONE" + }; // var - cwrap function var sqlite3_open = cwrap("sqlite3_open", "number", ["string", "number"]); var sqlite3_close_v2 = cwrap("sqlite3_close_v2", "number", ["number"]); @@ -139,6 +193,11 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { ); var sqlite3_step = cwrap("sqlite3_step", "number", ["number"]); var sqlite3_errmsg = cwrap("sqlite3_errmsg", "string", ["number"]); + var sqlite3_extended_errcode = cwrap( + "sqlite3_extended_errcode", + "number", + ["number"] + ); var sqlite3_column_count = cwrap( "sqlite3_column_count", "number", @@ -1258,16 +1317,27 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { }; /** Analyze a result code, return null if no error occured, and throw - an error with a descriptive message otherwise + an error with a descriptive message otherwise. The error's `code` is the + name of SQLite's extended result code (such as + `"SQLITE_CONSTRAINT_UNIQUE"`), and its `errcode` is that code's number. @nodoc */ Database.prototype.handleError = function handleError(returnCode) { var errmsg; + var errcode; + var err; if (returnCode === SQLITE_OK) { return null; } errmsg = sqlite3_errmsg(this.db); - throw new Error(errmsg); + errcode = sqlite3_extended_errcode(this.db); + if ((errcode & 0xff) !== (returnCode & 0xff)) { + errcode = returnCode; + } + err = new Error(errmsg); + err["code"] = SQLITE_CODE_NAMES[errcode]; + err["errcode"] = errcode; + throw err; }; /** Returns the number of changed rows (modified, inserted or deleted) diff --git a/src/exported_functions.json b/src/exported_functions.json index d61b648a..b4fdce96 100644 --- a/src/exported_functions.json +++ b/src/exported_functions.json @@ -8,6 +8,7 @@ "_sqlite3_exec", "_sqlite3_free", "_sqlite3_errmsg", +"_sqlite3_extended_errcode", "_sqlite3_changes", "_sqlite3_prepare_v2", "_sqlite3_sql", diff --git a/test/test_errors.js b/test/test_errors.js index 4dbf15d3..33bf2766 100644 --- a/test/test_errors.js +++ b/test/test_errors.js @@ -51,6 +51,55 @@ exports.test = function(sql, assert) { assert.throws(function(){ stmt.run([3]); }, "Statements shouldn't be able to execute after the database is closed"); + + // Errors carry SQLite's extended result code, by name and by number + var codeOf = function(fn) { + try { + fn(); + } catch (e) { + return [e.code, e.errcode]; + } + assert.fail("Expected an error"); + }; + db = new sql.Database(); + db.run("PRAGMA foreign_keys = ON"); + db.run("CREATE TABLE parent (id INTEGER PRIMARY KEY)"); + db.run("CREATE TABLE child (id INTEGER PRIMARY KEY," + + " parent INTEGER REFERENCES parent(id), name TEXT NOT NULL UNIQUE," + + " age INTEGER CHECK (age >= 0))"); + db.run("INSERT INTO child (id, name) VALUES (1, 'a')"); + + assert.deepEqual(codeOf(function() { + db.run("INSERT INTO child (id, name) VALUES (1, 'b')"); + }), ["SQLITE_CONSTRAINT_PRIMARYKEY", 1555], "A primary key violation"); + assert.deepEqual(codeOf(function() { + db.run("INSERT INTO child (name) VALUES ('a')"); + }), ["SQLITE_CONSTRAINT_UNIQUE", 2067], "A unique violation"); + assert.deepEqual(codeOf(function() { + db.run("INSERT INTO child (name) VALUES (NULL)"); + }), ["SQLITE_CONSTRAINT_NOTNULL", 1299], "A not null violation"); + assert.deepEqual(codeOf(function() { + db.run("INSERT INTO child (name, age) VALUES ('c', -1)"); + }), ["SQLITE_CONSTRAINT_CHECK", 275], "A check violation"); + assert.deepEqual(codeOf(function() { + db.run("INSERT INTO child (name, parent) VALUES ('d', 9)"); + }), ["SQLITE_CONSTRAINT_FOREIGNKEY", 787], "A foreign key violation"); + assert.deepEqual(codeOf(function() { + db.exec("SELEC 1"); + }), ["SQLITE_ERROR", 1], "A syntax error"); + assert.deepEqual(codeOf(function() { + db.prepare("SELECT ?").bind([1, 2]); + }), ["SQLITE_RANGE", 25], "Binding too many parameters"); + var insert = db.prepare("INSERT INTO child (name) VALUES (?)"); + assert.deepEqual(codeOf(function() { + insert.run(["a"]); + }), ["SQLITE_CONSTRAINT_UNIQUE", 2067], "A failing prepared statement"); + insert.free(); + db.close(); + + assert.deepEqual(codeOf(function() { + new sql.Database([1, 2, 3]).exec("SELECT * FROM sqlite_master"); + }), ["SQLITE_NOTADB", 26], "Opening something that is not a database"); }; if (module == require.main) { From 5e2eec81113d4786c94fceb355daba6f2edc0ea7 Mon Sep 17 00:00:00 2001 From: Colin McDonnell <3084745+colinhacks@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:46:43 -0800 Subject: [PATCH 2/4] build: generate the result code names from sqlite3.h The table of result code names is written at build time from the header of the SQLite being compiled, so it follows each SQLite upgrade without a hand-maintained copy. --- Makefile | 8 +++++- scripts/result-codes.cjs | 32 +++++++++++++++++++++++ src/api.js | 55 +--------------------------------------- 3 files changed, 40 insertions(+), 55 deletions(-) create mode 100644 scripts/result-codes.cjs diff --git a/Makefile b/Makefile index def33582..44ac9b70 100644 --- a/Makefile +++ b/Makefile @@ -75,9 +75,10 @@ BITCODE_FILES = out/sqlite3.o out/extension-functions.o OUTPUT_WRAPPER_FILES = src/shell-pre.js src/shell-post.js -SOURCE_API_FILES = src/api.js +SOURCE_API_FILES = out/result-codes.js src/api.js EMFLAGS_PRE_JS_FILES = \ + --pre-js out/result-codes.js \ --pre-js src/api.js MODULE_API_JSON_FILES = src/exported_functions.json src/exported_runtime_methods.json src/incoming_module_api.json @@ -189,6 +190,11 @@ out/sqlite3.o: sqlite-src/$(SQLITE_AMALGAMATION) Makefile # Generate llvm bitcode $(EMCC) $(SQLITE_COMPILATION_FLAGS) -c sqlite-src/$(SQLITE_AMALGAMATION)/sqlite3.c -o $@ +# The names of SQLite's result codes, read from the header of the SQLite being compiled +out/result-codes.js: sqlite-src/$(SQLITE_AMALGAMATION) scripts/result-codes.cjs + mkdir -p out + node scripts/result-codes.cjs sqlite-src/$(SQLITE_AMALGAMATION)/sqlite3.h $@ + # Since the extension-functions.c includes other headers in the sqlite_amalgamation, we declare that this depends on more than just extension-functions.c out/extension-functions.o: sqlite-src/$(SQLITE_AMALGAMATION) src/legacy-functions.c Makefile mkdir -p out diff --git a/scripts/result-codes.cjs b/scripts/result-codes.cjs new file mode 100644 index 00000000..0d297312 --- /dev/null +++ b/scripts/result-codes.cjs @@ -0,0 +1,32 @@ +"use strict"; + +// Writes the names of SQLite's result codes, keyed by number, as read from +// the sqlite3.h the build compiles, so the table always matches the bundled +// SQLite. Usage: node scripts/result-codes.cjs +const fs = require("node:fs"); +const process = require("node:process"); + +const [header, output] = process.argv.slice(2); +const source = fs.readFileSync(header, "utf8"); + +// The primary result codes are the block from SQLITE_OK to SQLITE_DONE. +const start = source.indexOf("#define SQLITE_OK "); +const end = source.indexOf("\n", source.indexOf("#define SQLITE_DONE ")); +const codes = new Map(); +const primary = /^#define (SQLITE_[A-Z_]+) +(\d+)/gm; +for (const [, name, value] of source.slice(start, end).matchAll(primary)) { + codes.set(name, Number(value)); +} +// Every extended result code is written as a primary one with a byte above it. +const extended = /^#define (SQLITE_[A-Z_]+) +\((SQLITE_[A-Z]+) *\| *\((\d+) *<< *8\)\)/gm; +for (const [, name, base, shift] of source.matchAll(extended)) { + if (!codes.has(base)) throw new Error(`${name}: unknown result code ${base}`); + codes.set(name, codes.get(base) | (Number(shift) << 8)); +} +if (!codes.has("SQLITE_CONSTRAINT_UNIQUE")) { + throw new Error(`no result codes found in ${header}`); +} + +const entries = [...codes].map(([name, value]) => ` ${value}: ${JSON.stringify(name)}`); +fs.writeFileSync(output, `// Generated from ${header} by scripts/result-codes.cjs.\n` + + `var SQLITE_CODE_NAMES = {\n${entries.join(",\n")}\n};\n`); diff --git a/src/api.js b/src/api.js index 470af2de..d01e9cbe 100644 --- a/src/api.js +++ b/src/api.js @@ -1,5 +1,6 @@ /* global FS + SQLITE_CODE_NAMES HEAP8 Module _malloc @@ -80,60 +81,6 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { var SQLITE_INSERT = 18; var SQLITE_UPDATE = 23; var SQLITE_DELETE = 9; - // var - Result code names, primary and extended, by number - var SQLITE_CODE_NAMES = { - 0: "SQLITE_OK", 256: "SQLITE_OK_LOAD_PERMANENTLY", - 512: "SQLITE_OK_SYMLINK", 1: "SQLITE_ERROR", - 257: "SQLITE_ERROR_MISSING_COLLSEQ", 513: "SQLITE_ERROR_RETRY", - 769: "SQLITE_ERROR_SNAPSHOT", 1025: "SQLITE_ERROR_RESERVESIZE", - 1281: "SQLITE_ERROR_KEY", 1537: "SQLITE_ERROR_UNABLE", - 2: "SQLITE_INTERNAL", 3: "SQLITE_PERM", 4: "SQLITE_ABORT", - 516: "SQLITE_ABORT_ROLLBACK", 5: "SQLITE_BUSY", 6: "SQLITE_LOCKED", - 7: "SQLITE_NOMEM", 8: "SQLITE_READONLY", - 264: "SQLITE_READONLY_RECOVERY", 520: "SQLITE_READONLY_CANTLOCK", - 776: "SQLITE_READONLY_ROLLBACK", 1032: "SQLITE_READONLY_DBMOVED", - 1288: "SQLITE_READONLY_CANTINIT", 1544: "SQLITE_READONLY_DIRECTORY", - 9: "SQLITE_INTERRUPT", 10: "SQLITE_IOERR", 266: "SQLITE_IOERR_READ", - 522: "SQLITE_IOERR_SHORT_READ", 778: "SQLITE_IOERR_WRITE", - 1034: "SQLITE_IOERR_FSYNC", 1290: "SQLITE_IOERR_DIR_FSYNC", - 1546: "SQLITE_IOERR_TRUNCATE", 1802: "SQLITE_IOERR_FSTAT", - 2058: "SQLITE_IOERR_UNLOCK", 2314: "SQLITE_IOERR_RDLOCK", - 2570: "SQLITE_IOERR_DELETE", 2826: "SQLITE_IOERR_BLOCKED", - 3082: "SQLITE_IOERR_NOMEM", 3338: "SQLITE_IOERR_ACCESS", - 3594: "SQLITE_IOERR_CHECKRESERVEDLOCK", 3850: "SQLITE_IOERR_LOCK", - 4106: "SQLITE_IOERR_CLOSE", 4362: "SQLITE_IOERR_DIR_CLOSE", - 4618: "SQLITE_IOERR_SHMOPEN", 4874: "SQLITE_IOERR_SHMSIZE", - 5130: "SQLITE_IOERR_SHMLOCK", 5386: "SQLITE_IOERR_SHMMAP", - 5642: "SQLITE_IOERR_SEEK", 5898: "SQLITE_IOERR_DELETE_NOENT", - 6154: "SQLITE_IOERR_MMAP", 6410: "SQLITE_IOERR_GETTEMPPATH", - 6666: "SQLITE_IOERR_CONVPATH", 6922: "SQLITE_IOERR_VNODE", - 7178: "SQLITE_IOERR_AUTH", 7434: "SQLITE_IOERR_BEGIN_ATOMIC", - 7690: "SQLITE_IOERR_COMMIT_ATOMIC", - 7946: "SQLITE_IOERR_ROLLBACK_ATOMIC", 8202: "SQLITE_IOERR_DATA", - 8458: "SQLITE_IOERR_CORRUPTFS", 8714: "SQLITE_IOERR_IN_PAGE", - 8970: "SQLITE_IOERR_BADKEY", 9226: "SQLITE_IOERR_CODEC", - 11: "SQLITE_CORRUPT", 267: "SQLITE_CORRUPT_VTAB", - 523: "SQLITE_CORRUPT_SEQUENCE", 779: "SQLITE_CORRUPT_INDEX", - 12: "SQLITE_NOTFOUND", 13: "SQLITE_FULL", 14: "SQLITE_CANTOPEN", - 270: "SQLITE_CANTOPEN_NOTEMPDIR", 526: "SQLITE_CANTOPEN_ISDIR", - 782: "SQLITE_CANTOPEN_FULLPATH", 1038: "SQLITE_CANTOPEN_CONVPATH", - 1294: "SQLITE_CANTOPEN_DIRTYWAL", 1550: "SQLITE_CANTOPEN_SYMLINK", - 15: "SQLITE_PROTOCOL", 16: "SQLITE_EMPTY", 17: "SQLITE_SCHEMA", - 18: "SQLITE_TOOBIG", 19: "SQLITE_CONSTRAINT", - 275: "SQLITE_CONSTRAINT_CHECK", 531: "SQLITE_CONSTRAINT_COMMITHOOK", - 787: "SQLITE_CONSTRAINT_FOREIGNKEY", - 1043: "SQLITE_CONSTRAINT_FUNCTION", 1299: "SQLITE_CONSTRAINT_NOTNULL", - 1555: "SQLITE_CONSTRAINT_PRIMARYKEY", - 1811: "SQLITE_CONSTRAINT_TRIGGER", 2067: "SQLITE_CONSTRAINT_UNIQUE", - 2323: "SQLITE_CONSTRAINT_VTAB", 20: "SQLITE_MISMATCH", - 21: "SQLITE_MISUSE", 22: "SQLITE_NOLFS", 23: "SQLITE_AUTH", - 279: "SQLITE_AUTH_USER", 24: "SQLITE_FORMAT", 25: "SQLITE_RANGE", - 26: "SQLITE_NOTADB", 27: "SQLITE_NOTICE", - 283: "SQLITE_NOTICE_RECOVER_WAL", - 539: "SQLITE_NOTICE_RECOVER_ROLLBACK", 795: "SQLITE_NOTICE_RBU", - 28: "SQLITE_WARNING", 284: "SQLITE_WARNING_AUTOINDEX", - 100: "SQLITE_ROW", 101: "SQLITE_DONE" - }; // var - cwrap function var sqlite3_open = cwrap("sqlite3_open", "number", ["string", "number"]); var sqlite3_close_v2 = cwrap("sqlite3_close_v2", "number", ["number"]); From b6b10bb8c89489b462f715d33bcb4a39ac6d315b Mon Sep 17 00:00:00 2001 From: Colin McDonnell <3084745+colinhacks@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:22:00 -0800 Subject: [PATCH 3/4] feat: expose SQLite's constants, read through the preprocessor Every integer constant sqlite3.h defines is evaluated from the C preprocessor's macro list at build time and exposed as SQL.constants. The result code names on thrown errors come from the same list, using the beginning-of-error-codes and end-of-error-codes markers in sqlite3.h. --- Makefile | 11 +++++---- scripts/constants.cjs | 52 ++++++++++++++++++++++++++++++++++++++++ scripts/result-codes.cjs | 32 ------------------------- src/api.js | 13 ++++++++-- test/test_errors.js | 10 ++++++++ 5 files changed, 79 insertions(+), 39 deletions(-) create mode 100644 scripts/constants.cjs delete mode 100644 scripts/result-codes.cjs diff --git a/Makefile b/Makefile index 44ac9b70..5a09435d 100644 --- a/Makefile +++ b/Makefile @@ -75,10 +75,10 @@ BITCODE_FILES = out/sqlite3.o out/extension-functions.o OUTPUT_WRAPPER_FILES = src/shell-pre.js src/shell-post.js -SOURCE_API_FILES = out/result-codes.js src/api.js +SOURCE_API_FILES = out/constants.js src/api.js EMFLAGS_PRE_JS_FILES = \ - --pre-js out/result-codes.js \ + --pre-js out/constants.js \ --pre-js src/api.js MODULE_API_JSON_FILES = src/exported_functions.json src/exported_runtime_methods.json src/incoming_module_api.json @@ -190,10 +190,11 @@ out/sqlite3.o: sqlite-src/$(SQLITE_AMALGAMATION) Makefile # Generate llvm bitcode $(EMCC) $(SQLITE_COMPILATION_FLAGS) -c sqlite-src/$(SQLITE_AMALGAMATION)/sqlite3.c -o $@ -# The names of SQLite's result codes, read from the header of the SQLite being compiled -out/result-codes.js: sqlite-src/$(SQLITE_AMALGAMATION) scripts/result-codes.cjs +# SQLite's integer constants, as the C preprocessor reads the header of the SQLite being compiled +out/constants.js: sqlite-src/$(SQLITE_AMALGAMATION) scripts/constants.cjs mkdir -p out - node scripts/result-codes.cjs sqlite-src/$(SQLITE_AMALGAMATION)/sqlite3.h $@ + $(EMCC) -E -dM -x c sqlite-src/$(SQLITE_AMALGAMATION)/sqlite3.h | node scripts/constants.cjs sqlite-src/$(SQLITE_AMALGAMATION)/sqlite3.h > $@.tmp + mv $@.tmp $@ # Since the extension-functions.c includes other headers in the sqlite_amalgamation, we declare that this depends on more than just extension-functions.c out/extension-functions.o: sqlite-src/$(SQLITE_AMALGAMATION) src/legacy-functions.c Makefile diff --git a/scripts/constants.cjs b/scripts/constants.cjs new file mode 100644 index 00000000..0cbe309d --- /dev/null +++ b/scripts/constants.cjs @@ -0,0 +1,52 @@ +"use strict"; + +// Writes every integer constant sqlite3.h defines, and the names of its result +// codes, as a script the build runs before src/api.js. +// Usage: emcc -E -dM -x c sqlite3.h | node scripts/constants.cjs sqlite3.h +// The macros come from the C preprocessor on stdin; the header itself is read +// only for the comments that mark where its primary result codes are. +const fs = require("node:fs"); +const process = require("node:process"); + +const macros = Object.fromEntries( + [...fs.readFileSync(0, "utf8").matchAll(/^#define (SQLITE_\w+) (.+)$/gm)] + .map(([, name, expr]) => [name, expr]) +); + +const constants = {}; +function get(name) { + if (name in constants) return constants[name]; + const expr = macros[name].replace(/\bSQLITE_\w+\b/g, (n) => `(${get(n)})`); + // Integer arithmetic alone: anything else (a string, a cast, a function) + // is not a constant JavaScript can hold. + if (!/^(?:0[xX][\da-fA-F]+|[\s\d()|&^~<>+*/-])*$/.test(expr)) throw new Error(`${name} is not an integer`); + const value = Function(`return (${expr})`)(); + if (!Number.isSafeInteger(value)) throw new Error(`${name} is not an integer`); + constants[name] = value; + return value; +} +for (const name of Object.keys(macros)) { + try { + get(name); + } catch { + // Not an integer constant. + } +} + +// The primary result codes are between sqlite3.h's beginning-of-error-codes +// and end-of-error-codes comments, and each extended one is defined as a +// primary one with a byte above it. +const header = fs.readFileSync(process.argv[2], "utf8"); +const block = /\/\* beginning-of-error-codes \*\/([\s\S]*?)\/\* end-of-error-codes \*\//.exec(header); +if (!block) throw new Error("no error codes found in " + process.argv[2]); +const primary = new Set([...block[1].matchAll(/^#define (SQLITE_\w+)/gm)].map(([, name]) => name)); +const resultCodes = Object.keys(constants).filter((name) => { + if (primary.has(name)) return true; + const base = /^\(\s*(SQLITE_\w+)\s*\|/.exec(macros[name]); + return base !== null && primary.has(base[1]); +}); +if (!resultCodes.includes("SQLITE_CONSTRAINT_UNIQUE")) throw new Error("no extended result codes found"); + +process.stdout.write("// Generated from sqlite3.h by scripts/constants.cjs.\n" + + `var SQLITE_CONSTANTS = ${JSON.stringify(constants, null, 4)};\n` + + `var SQLITE_RESULT_CODES = ${JSON.stringify(resultCodes, null, 4)};\n`); diff --git a/scripts/result-codes.cjs b/scripts/result-codes.cjs deleted file mode 100644 index 0d297312..00000000 --- a/scripts/result-codes.cjs +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; - -// Writes the names of SQLite's result codes, keyed by number, as read from -// the sqlite3.h the build compiles, so the table always matches the bundled -// SQLite. Usage: node scripts/result-codes.cjs -const fs = require("node:fs"); -const process = require("node:process"); - -const [header, output] = process.argv.slice(2); -const source = fs.readFileSync(header, "utf8"); - -// The primary result codes are the block from SQLITE_OK to SQLITE_DONE. -const start = source.indexOf("#define SQLITE_OK "); -const end = source.indexOf("\n", source.indexOf("#define SQLITE_DONE ")); -const codes = new Map(); -const primary = /^#define (SQLITE_[A-Z_]+) +(\d+)/gm; -for (const [, name, value] of source.slice(start, end).matchAll(primary)) { - codes.set(name, Number(value)); -} -// Every extended result code is written as a primary one with a byte above it. -const extended = /^#define (SQLITE_[A-Z_]+) +\((SQLITE_[A-Z]+) *\| *\((\d+) *<< *8\)\)/gm; -for (const [, name, base, shift] of source.matchAll(extended)) { - if (!codes.has(base)) throw new Error(`${name}: unknown result code ${base}`); - codes.set(name, codes.get(base) | (Number(shift) << 8)); -} -if (!codes.has("SQLITE_CONSTRAINT_UNIQUE")) { - throw new Error(`no result codes found in ${header}`); -} - -const entries = [...codes].map(([name, value]) => ` ${value}: ${JSON.stringify(name)}`); -fs.writeFileSync(output, `// Generated from ${header} by scripts/result-codes.cjs.\n` - + `var SQLITE_CODE_NAMES = {\n${entries.join(",\n")}\n};\n`); diff --git a/src/api.js b/src/api.js index d01e9cbe..a4778ff7 100644 --- a/src/api.js +++ b/src/api.js @@ -1,6 +1,7 @@ /* global FS - SQLITE_CODE_NAMES + SQLITE_CONSTANTS + SQLITE_RESULT_CODES HEAP8 Module _malloc @@ -24,6 +25,8 @@ * @typedef {{Database:Database, Statement:Statement}} SqlJs * @property {Database} Database A class that represents an SQLite database * @property {Statement} Statement The prepared statement class + * @property {Object} constants Every integer constant of + * SQLite's C API, by name, such as `SQLITE_CONSTRAINT_UNIQUE` */ /** @@ -81,6 +84,11 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { var SQLITE_INSERT = 18; var SQLITE_UPDATE = 23; var SQLITE_DELETE = 9; + // var - The name of each result code, primary and extended, by number + var resultCodeNames = {}; + SQLITE_RESULT_CODES.forEach(function nameResultCode(name) { + resultCodeNames[SQLITE_CONSTANTS[name]] = name; + }); // var - cwrap function var sqlite3_open = cwrap("sqlite3_open", "number", ["string", "number"]); var sqlite3_close_v2 = cwrap("sqlite3_close_v2", "number", ["number"]); @@ -1282,7 +1290,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { errcode = returnCode; } err = new Error(errmsg); - err["code"] = SQLITE_CODE_NAMES[errcode]; + err["code"] = resultCodeNames[errcode]; err["errcode"] = errcode; throw err; }; @@ -1734,4 +1742,5 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { // export Database to Module Module["Database"] = Database; + Module["constants"] = Object.freeze(SQLITE_CONSTANTS); }; diff --git a/test/test_errors.js b/test/test_errors.js index 33bf2766..8b7ef4d3 100644 --- a/test/test_errors.js +++ b/test/test_errors.js @@ -84,6 +84,16 @@ exports.test = function(sql, assert) { assert.deepEqual(codeOf(function() { db.run("INSERT INTO child (name, parent) VALUES ('d', 9)"); }), ["SQLITE_CONSTRAINT_FOREIGNKEY", 787], "A foreign key violation"); + var err = null; + try { + db.run("INSERT INTO child (name) VALUES ('a')"); + } catch (e) { + err = e; + } + assert.strictEqual(err.errcode, sql.constants.SQLITE_CONSTRAINT_UNIQUE, + "An error's code is one of the module's constants"); + assert.strictEqual(sql.constants.SQLITE_OPEN_READWRITE, 2, + "The module has SQLite's other constants too"); assert.deepEqual(codeOf(function() { db.exec("SELEC 1"); }), ["SQLITE_ERROR", 1], "A syntax error"); From ce73cdd73e27e95ec9b6a29220c9decfa475bbd0 Mon Sep 17 00:00:00 2001 From: Colin McDonnell <3084745+colinhacks@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:41:43 -0800 Subject: [PATCH 4/4] docs: document the SQLite errors each method throws A SqliteError typedef names the code and errcode properties, and each method that throws one says so with @throws, so the structured error shows in the generated documentation. --- src/api.js | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/src/api.js b/src/api.js index a4778ff7..d95a9e6b 100644 --- a/src/api.js +++ b/src/api.js @@ -29,6 +29,25 @@ * SQLite's C API, by name, such as `SQLITE_CONSTRAINT_UNIQUE` */ +/** + * An error SQLite returned, thrown as an `Error` whose message is SQLite's. + * Its `code` and `errcode` say which error it was, so it can be told apart + * without reading the message. + * @typedef {Error} SqliteError + * @property {string} code The name of SQLite's extended result code, such as + * `"SQLITE_CONSTRAINT_UNIQUE"` + * @property {number} errcode The number of that code, such as `2067`, which + * is `SQL.constants.SQLITE_CONSTRAINT_UNIQUE` + * @example + * try { + * db.run("INSERT INTO users (email) VALUES ('a@example.com')"); + * } catch (e) { + * if (e.code === "SQLITE_CONSTRAINT_UNIQUE") { + * // the email is taken + * } + * } + */ + /** * @typedef {Object} SqlJsConfig * @property {function(string):string} [locateFile] @@ -354,7 +373,8 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { * @param {Statement.BindParams} values The values to bind * @return {boolean} true if it worked - * @throws {String} SQLite Error + * @throws {SqliteError} If SQLite fails to bind a value + * @throws {String} If the statement was freed */ Statement.prototype.bind = function bind(values) { if (!this.stmt) { @@ -372,7 +392,8 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { that can be retrieved with {@link Statement.get}. @return {boolean} true if a row of result available - @throws {String} SQLite Error + @throws {SqliteError} If SQLite fails to run the statement + @throws {String} If the statement was freed */ Statement.prototype.step = function step() { if (!this.stmt) { @@ -452,6 +473,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { Enable BigInt support var stmt = db.prepare("SELECT * FROM test"); while (stmt.step()) console.log(stmt.get(null, {useBigInt: true})); + @throws {SqliteError} If SQLite fails to bind or to run the statement */ Statement.prototype.get = function get(params, config) { config = config || {}; @@ -518,6 +540,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { stmt.step(); // Execute the statement console.log(stmt.getAsObject()); // Will print {nbr:5, data: Uint8Array([1,2,3]), null_value:null} + @throws {SqliteError} If SQLite fails to bind or to run the statement */ Statement.prototype.getAsObject = function getAsObject(params, config) { var values = this.get(params, config); @@ -554,6 +577,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { Bind the values, execute the statement, ignoring the rows it returns, and resets it @param {Statement.BindParams} [values] Value to bind to the statement + @throws {SqliteError} If SQLite fails to bind or to run the statement */ Statement.prototype.run = function run(values) { if (values != null) { @@ -777,7 +801,8 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { /** Prepare the next available SQL statement @return {StatementIterator.StatementIteratorResult} - @throws {String} SQLite error or invalid iterator error + @throws {SqliteError} If SQLite fails to prepare the next statement + @throws {String} If the iterator is no longer valid */ StatementIterator.prototype.next = function next() { if (this.sqlPtr === null) { @@ -867,6 +892,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { * one stored in the byte array passed in first argument * @param {Array} data An array of bytes representing * an SQLite database file + * @throws {SqliteError} If SQLite cannot open the database */ function Database(data) { this.filename = "dbfile_" + (0xffffffff * Math.random() >>> 0); @@ -899,6 +925,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { ); @return {Database} The database object (useful for method chaining) + @throws {SqliteError} If SQLite fails to prepare or to run the SQL */ Database.prototype.run = function run(sql, params) { if (!this.db) { @@ -989,6 +1016,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { you **cannot** provide an sql string that contains several statements (separated by `;`). This limitation does not apply to params as an object. * @return {Array} The results of each statement + * @throws {SqliteError} If SQLite fails to prepare or to run the SQL */ Database.prototype.exec = function exec(sql, params, config) { if (!this.db) { @@ -1065,6 +1093,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { db.each("SELECT name,age FROM users WHERE age >= $majority", {$majority:18}, function (row){console.log(row.name + " is a grown-up.")} ); + @throws {SqliteError} If SQLite fails to prepare or to run the SQL */ // eslint-disable-next-line max-len Database.prototype.each = function each(sql, params, callback, done, config) { @@ -1093,7 +1122,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { (`?`, `:VVV`, `:AAA`, `@AAA`) @param {Statement.BindParams} [params] values to bind to placeholders @return {Statement} the resulting statement - @throws {String} SQLite error + @throws {SqliteError} If SQLite fails to prepare the SQL */ Database.prototype.prepare = function prepare(sql, params) { var sqlPtr = stringToNewUTF8(sql); @@ -1249,6 +1278,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { * * Databases **must** be closed when you're finished with them, or the * memory consumption will grow forever + * @throws {SqliteError} If SQLite cannot close the database */ Database.prototype.close = function close() { // do nothing if db is null or already closed @@ -1397,6 +1427,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { SQL statements. @param {function(any)} func the actual function to be executed. @return {Database} The database object. Useful for method chaining + @throws {SqliteError} If SQLite refuses to register the function */ Database.prototype.create_function = function create_function( name, @@ -1464,6 +1495,7 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() { will be used as the final value. @return {Database} The database object. Useful for method chaining @template T + @throws {SqliteError} If SQLite refuses to register the function */ Database.prototype.create_aggregate = function create_aggregate( name,