make some errors compatible with better-sqlite3

This commit is contained in:
Mikaël Francoeur
2025-07-04 11:17:24 -04:00
parent 7c4bb3d4b9
commit 2a691f5044
8 changed files with 313 additions and 221 deletions

View File

@@ -2,6 +2,28 @@
const { Database: NativeDB } = require("./index.js");
const SqliteError = require("./sqlite-error.js");
const convertibleErrorTypes = { TypeError };
const CONVERTIBLE_ERROR_PREFIX = '[TURSO_CONVERT_TYPE]';
function convertError(err) {
if ((err.code ?? '').startsWith(CONVERTIBLE_ERROR_PREFIX)) {
return createErrorByName(err.code.substring(CONVERTIBLE_ERROR_PREFIX.length), err.message);
}
return new SqliteError(err.message, err.code, err.rawCode);
}
function createErrorByName(name, message) {
const ErrorConstructor = convertibleErrorTypes[name];
if (!ErrorConstructor) {
throw new Error(`unknown error type ${name} from Turso`);
}
return new ErrorConstructor(message);
}
/**
* Database represents a connection that can prepare and execute SQL statements.
*/
@@ -145,7 +167,11 @@ class Database {
* @param {string} sql - The SQL statement string to execute.
*/
exec(sql) {
this.db.exec(sql);
try {
this.db.exec(sql);
} catch (err) {
throw convertError(err);
}
}
/**
@@ -264,8 +290,13 @@ class Statement {
* @returns this - Statement with binded parameters
*/
bind(...bindParameters) {
return this.stmt.bind(bindParameters.flat());
try {
return new Statement(this.stmt.bind(bindParameters.flat()), this.db);
} catch (err) {
throw convertError(err);
}
}
}
module.exports = Database;
module.exports.SqliteError = SqliteError;