Skip to content

feat: attach SQLite's result code to thrown errors - #649

Merged
lovasoa merged 4 commits into
sql-js:masterfrom
colinhacks:error-codes
Nov 17, 2026
Merged

lovasoa merged 4 commits into
sql-js:masterfrom
colinhacks:error-codes

Conversation

@colinhacks

@colinhacks colinhacks commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

An SQLite error is thrown as an Error carrying only the message, so telling a constraint violation from any other failure means matching the message text.

This sets two properties on the error handleError throws, named as better-sqlite3 (code) and node:sqlite (errcode) name them:

  • code: the name of SQLite's extended result code, such as "SQLITE_CONSTRAINT_UNIQUE"
  • errcode: its number, such as 2067
try {
  db.run("INSERT INTO users (email) VALUES ('a@example.com')");
} catch (e) {
  e.message; // "UNIQUE constraint failed: users.email"
  e.code;    // "SQLITE_CONSTRAINT_UNIQUE"
  e.errcode; // 2067
}

The code comes from sqlite3_extended_errcode, so a unique, not-null, check, foreign key or primary key violation each has its own. If the connection's code doesn't match the failing call's (the Database constructor calls handleError before this.db is set), the call's own return code is used. The names come from SQLite's constants, which are now generated at build time by running the bundled sqlite3.h through the C preprocessor (scripts/constants.cjs) and exposed as SQL.constants, so they follow each SQLite upgrade. The properties are set with bracket notation so Closure keeps their names in the optimized builds.

Errors thrown as strings ("Database closed", "Statement closed") are unchanged.

Tests in test/test_errors.js cover each constraint kind, a syntax error, SQLITE_RANGE from binding too many parameters, an error from a prepared statement, and SQLITE_NOTADB.

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.
Copilot AI balanced review requested due to automatic review settings November 16, 2026 21:27

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Comment thread src/api.js Outdated
Comment on lines +84 to +136
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"
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we have to maintain this mapping on our side ? No way to get it from sqlite directly ? How do we keep it up to date ? Does it never change between sqlite versions ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SQLite has no function that returns a code's name. The closest is sqlite3_errstr, which gives the English text ("constraint failed"). The numbers don't change between versions either. Per https://www.sqlite.org/rescode.html the names and values of existing codes are fixed, but new extended codes do get added now and then.

So I dropped the hand-written table. scripts/result-codes.cjs now generates it at build time from the sqlite3.h of the amalgamation being compiled, and it goes in as a second --pre-js before api.js. Bumping SQLite in the Makefile picks up any new codes with nothing to edit (5e2eec8).

@lovasoa lovasoa Nov 17, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we try to make this more robust ? And expose all sqlite constants without picking.

My agent suggests

constants.json: sqlite3.h extract.cjs
	clang --preprocess --language=c -dM $< | node extract.cjs > $@
const fs = require('node:fs');

const macros = Object.fromEntries(
  [...fs.readFileSync(0, 'utf8').matchAll(/^#define (SQLITE_\w+) (.+)$/gm)]
    .map(([, name, expr]) => [name, expr])
);

const values = {};

function get(name) {
  if (name in values) return values[name];

  const expr = macros[name].replace(/\bSQLITE_\w+\b/g, n => `(${get(n)})`);
  const value = Function(`return (${expr})`)();

  if (!Number.isSafeInteger(value)) throw Error('not an integer');
  return values[name] = value;
}

for (const name of Object.keys(macros)) {
  try { get(name); } catch { /* non-numeric macro */ }
}

console.log(JSON.stringify(values, null, 2));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in b6b10bb, mostly as your agent wrote it. scripts/constants.cjs reads emcc -E -dM -x c sqlite3.h and evaluates every SQLITE_* macro that comes out as an integer. That's 494 on 3.54.1 (strings, casts and empty macros are skipped). They're exposed frozen as SQL.constants, so e.errcode === SQL.constants.SQLITE_CONSTRAINT_UNIQUE works.

Some names were still needed for e.code, since numbers collide across groups (SQLITE_ERROR and SQLITE_INTEGER are both 1). Those come from sqlite3.h's own beginning-of-error-codes / end-of-error-codes markers plus every macro defined as (SQLITE_<one of those> | (n<<8)). No names are listed by hand.

I went with constants as the property name. Happy to rename it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh sorry i see. Good for me

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.
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.
@lovasoa

lovasoa commented Nov 17, 2026

Copy link
Copy Markdown
Member

Ok, it's good for me now. But one last thing : do you want to type our throwing functions with @throws in jsdoc now that we throw structured errors ? That makes it more discoverable. Otherwise I fear most people (and agents) will just never know about the structured errors and keep parsing strings anyway.

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.
@colinhacks

Copy link
Copy Markdown
Contributor Author

Yes, added in ce73cdd. There's a SqliteError typedef with code and errcode and a short example, and @throws {SqliteError} on every public method that can throw one (the Database constructor, run, exec, each, prepare, close, create_function, create_aggregate, and the statement's bind, step, get, getAsObject, run, plus the iterator's next). The string throws for a freed statement or a dead iterator are tagged separately as {String}. Checked that npm run doc renders the typedef page and links each Throws entry to it.

@lovasoa
lovasoa merged commit 027c2d0 into sql-js:master Nov 17, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants