UNPKG

flint-orm

Version:

Type-safe SQLite ORM for JavaScript

1,443 lines (1,428 loc) 85.6 kB
// @bun var __create = Object.create; var __getProtoOf = Object.getPrototypeOf; var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; function __accessProp(key) { return this[key]; } var __toESMCache_node; var __toESMCache_esm; var __toESM = (mod, isNodeMode, target) => { var canCache = mod != null && typeof mod === "object"; if (canCache) { var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap; var cached = cache.get(mod); if (cached) return cached; } target = mod != null ? __create(__getProtoOf(mod)) : {}; const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; for (let key of __getOwnPropNames(mod)) if (!__hasOwnProp.call(to, key)) __defProp(to, key, { get: __accessProp.bind(mod, key), enumerable: true }); if (canCache) cache.set(mod, to); return to; }; var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); var __returnValue = (v) => v; function __exportSetter(name, newValue) { this[name] = __returnValue.bind(null, newValue); } var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, set: __exportSetter.bind(all, name) }); }; var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); var __require = import.meta.require; // node_modules/@tursodatabase/database-common/dist/bind.js function bindParams(stmt, params) { const len = params?.length; if (len === 0) { return; } if (len === 1) { const param = params[0]; if (isPlainObject(param)) { bindNamedParams(stmt, param); return; } if (Array.isArray(param)) { bindPositionalParams(stmt, [param]); return; } bindValue(stmt, 1, param); return; } bindPositionalParams(stmt, params); } function isPlainObject(obj) { if (!obj || typeof obj !== "object") return false; const proto = Object.getPrototypeOf(obj); return proto === Object.prototype || proto === null; } function bindNamedParams(stmt, paramObj) { const paramCount = stmt.parameterCount(); for (let i = 1;i <= paramCount; i++) { const paramName = stmt.parameterName(i); if (paramName) { const key = paramName.substring(1); const value = paramObj[key]; if (value !== undefined) { bindValue(stmt, i, value); } } } } function bindPositionalParams(stmt, params) { let bindIndex = 1; for (let i = 0;i < params.length; i++) { const param = params[i]; if (Array.isArray(param)) { for (let j = 0;j < param.length; j++) { bindValue(stmt, bindIndex++, param[j]); } } else { bindValue(stmt, bindIndex++, param); } } } function bindValue(stmt, index, value) { stmt.bindAt(index, value); } // node_modules/@tursodatabase/database-common/dist/sqlite-error.js var SqliteError; var init_sqlite_error = __esm(() => { SqliteError = class SqliteError extends Error { name; code; rawCode; constructor(message, code, rawCode) { super(message); this.name = "SqliteError"; this.code = code; this.rawCode = rawCode; Error.captureStackTrace(this, SqliteError); } }; }); // node_modules/@tursodatabase/database-common/dist/types.js var STEP_ROW = 1, STEP_DONE = 2, STEP_IO = 3; // node_modules/@tursodatabase/database-common/dist/compat.js var init_compat = __esm(() => { init_sqlite_error(); }); // node_modules/@tursodatabase/database-common/dist/async-lock.js class AsyncLock { locked; queue; constructor() { this.locked = false; this.queue = []; } async acquire() { if (!this.locked) { this.locked = true; return Promise.resolve(); } else { const block = new Promise((resolve) => { this.queue.push(resolve); }); return block; } } release() { if (this.locked == false) { throw new Error("invalid state: lock was already unlocked"); } const item = this.queue.shift(); if (item != null) { this.locked = true; item(); } else { this.locked = false; } } } // node_modules/@tursodatabase/database-common/dist/promise.js 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); } function isQueryOptions(value) { return value != null && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "queryTimeout"); } function splitBindParameters(bindParameters) { if (bindParameters.length === 0) { return { params: undefined, queryOptions: undefined }; } if (bindParameters.length > 1 && isQueryOptions(bindParameters[bindParameters.length - 1])) { return { params: bindParameters.length === 2 ? bindParameters[0] : bindParameters.slice(0, -1), queryOptions: bindParameters[bindParameters.length - 1] }; } return { params: bindParameters.length === 1 ? bindParameters[0] : bindParameters, queryOptions: undefined }; } function toBindArgs(params) { if (params === undefined) { return []; } return [params]; } class Database { name; readonly; open; memory; inTransaction; db; ioStep; execLock; _inTransaction = false; connected = false; constructor(db, ioStep) { this.db = db; this.execLock = new AsyncLock; this.ioStep = ioStep ?? (async () => {}); Object.defineProperties(this, { name: { get: () => this.db.path }, readonly: { get: () => this.db.readonly }, open: { get: () => this.db.open }, memory: { get: () => this.db.memory }, inTransaction: { get: () => this._inTransaction } }); } async connect() { if (this.connected) { return; } await this.db.connectAsync(); this.connected = true; } prepare(sql) { if (this.connected && !this.open) { throw new TypeError("The database connection is not open"); } if (!sql) { throw new RangeError("The supplied SQL string contains no statements"); } try { if (this.connected) { return new Statement(maybeValue(this.db.prepare(sql)), this.db, this.execLock, this.ioStep); } else { return new Statement(maybePromise(() => this.connect().then(() => this.db.prepare(sql))), this.db, this.execLock, this.ioStep); } } catch (err) { throw convertError(err); } } transaction(fn) { if (typeof fn !== "function") throw new TypeError("Expected first argument to be a function"); const db = this; const wrapTxn = (mode) => { return async (...bindParameters) => { await db.exec("BEGIN " + mode); db._inTransaction = true; try { const result = await fn(...bindParameters); await db.exec("COMMIT"); db._inTransaction = false; return result; } catch (err) { await db.exec("ROLLBACK"); db._inTransaction = false; throw err; } }; }; const properties = { default: { value: wrapTxn("") }, deferred: { value: wrapTxn("DEFERRED") }, immediate: { value: wrapTxn("IMMEDIATE") }, exclusive: { value: wrapTxn("EXCLUSIVE") }, database: { value: this, enumerable: true } }; Object.defineProperties(properties.default.value, properties); Object.defineProperties(properties.deferred.value, properties); Object.defineProperties(properties.immediate.value, properties); Object.defineProperties(properties.exclusive.value, properties); return properties.default.value; } async run(sql, ...bindParameters) { const stmt = await this.prepare(sql); try { return await stmt.run(...bindParameters); } finally { await stmt.close(); } } async get(sql, ...bindParameters) { const stmt = await this.prepare(sql); try { return await stmt.get(...bindParameters); } finally { await stmt.close(); } } async all(sql, ...bindParameters) { const stmt = await this.prepare(sql); try { return await stmt.all(...bindParameters); } finally { await stmt.close(); } } async* iterate(sql, ...bindParameters) { const stmt = await this.prepare(sql); try { yield* stmt.iterate(...bindParameters); } finally { await stmt.close(); } } async pragma(source, options) { if (options == null) options = {}; if (typeof source !== "string") throw new TypeError("Expected first argument to be a string"); if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object"); const pragma = `PRAGMA ${source}`; const stmt = await this.prepare(pragma); try { const results = await stmt.all(); return results; } finally { await stmt.close(); } } backup(filename, options) { throw new Error("not implemented"); } serialize(options) { throw new Error("not implemented"); } function(name, options, fn) { throw new Error("not implemented"); } aggregate(name, options) { throw new Error("not implemented"); } table(name, factory) { throw new Error("not implemented"); } loadExtension(path) { throw new Error("not implemented"); } maxWriteReplicationIndex() { throw new Error("not implemented"); } async exec(sql, queryOptions) { if (!this.open) { throw new TypeError("The database connection is not open"); } await this.execLock.acquire(); const exec = this.db.executor(sql, queryOptions); try { while (true) { const stepResult = exec.stepSync(); if (stepResult === STEP_IO) { await this.io(); continue; } if (stepResult === STEP_DONE) { break; } if (stepResult === STEP_ROW) { continue; } } } finally { exec.reset(); this.execLock.release(); } } interrupt() { throw new Error("not implemented"); } defaultSafeIntegers(toggle) { this.db.defaultSafeIntegers(toggle); } async close() { this.db.close(); } async io() { await this.ioStep(); } } function maybePromise(arg) { let lazy = arg; let promise = null; let value = null; return { apply(fn) { let previous = lazy; lazy = async () => { const result = await previous(); fn(result); return result; }; }, async resolve() { if (promise != null) { return await promise; } let valueResolve, valueReject; promise = new Promise((resolve, reject) => { valueResolve = (x) => { resolve(x); value = x; }; valueReject = reject; }); await lazy().then(valueResolve, valueReject); return await promise; }, must() { if (value == null) { throw new Error(`database must be connected before execution the function`); } return value; } }; } function maybeValue(value) { return { apply(fn) { fn(value); }, resolve() { return Promise.resolve(value); }, must() { return value; } }; } class Statement { stmt; db; execLock; ioStep; constructor(stmt, db, execLock, ioStep) { this.stmt = stmt; this.db = db; this.execLock = execLock; this.ioStep = ioStep; } raw(raw) { this.stmt.apply((s) => s.raw(raw)); return this; } pluck(pluckMode) { this.stmt.apply((s) => s.pluck(pluckMode)); return this; } safeIntegers(toggle) { this.stmt.apply((s) => s.safeIntegers(toggle)); return this; } columns() { return this.stmt.must().columns(); } get source() { throw new Error("not implemented"); } get reader() { return this.stmt.must().columns().length > 0; } get database() { return this.db; } async run(...bindParameters) { let stmt = await this.stmt.resolve(); const { params, queryOptions } = splitBindParameters(bindParameters); stmt.setQueryTimeout(queryOptions); bindParams(stmt, toBindArgs(params)); const totalChangesBefore = this.db.totalChanges(); await this.execLock.acquire(); try { while (true) { const stepResult = await stmt.stepSync(); if (stepResult === STEP_IO) { await this.io(); continue; } if (stepResult === STEP_DONE) { break; } if (stepResult === STEP_ROW) { continue; } } const lastInsertRowid = this.db.lastInsertRowid(); const changes = this.db.totalChanges() === totalChangesBefore ? 0 : this.db.changes(); return { changes, lastInsertRowid }; } finally { stmt.reset(); this.execLock.release(); } } async get(...bindParameters) { let stmt = await this.stmt.resolve(); const { params, queryOptions } = splitBindParameters(bindParameters); stmt.setQueryTimeout(queryOptions); bindParams(stmt, toBindArgs(params)); await this.execLock.acquire(); let row = undefined; try { while (true) { const stepResult = await stmt.stepSync(); if (stepResult === STEP_IO) { await this.io(); continue; } if (stepResult === STEP_DONE) { break; } if (stepResult === STEP_ROW && row === undefined) { row = stmt.row(); continue; } } return row; } finally { stmt.reset(); this.execLock.release(); } } async* iterate(...bindParameters) { let stmt = await this.stmt.resolve(); const { params, queryOptions } = splitBindParameters(bindParameters); stmt.setQueryTimeout(queryOptions); bindParams(stmt, toBindArgs(params)); await this.execLock.acquire(); try { while (true) { const stepResult = await stmt.stepSync(); if (stepResult === STEP_IO) { await this.io(); continue; } if (stepResult === STEP_DONE) { break; } if (stepResult === STEP_ROW) { yield stmt.row(); } } } finally { stmt.reset(); this.execLock.release(); } } async all(...bindParameters) { let stmt = await this.stmt.resolve(); const { params, queryOptions } = splitBindParameters(bindParameters); stmt.setQueryTimeout(queryOptions); bindParams(stmt, toBindArgs(params)); const rows = []; await this.execLock.acquire(); try { while (true) { const stepResult = await stmt.stepSync(); if (stepResult === STEP_IO) { await this.io(); continue; } if (stepResult === STEP_DONE) { break; } if (stepResult === STEP_ROW) { rows.push(stmt.row()); } } return rows; } finally { stmt.reset(); this.execLock.release(); } } async io() { await this.ioStep(); } interrupt() { throw new Error("not implemented"); } bind(...bindParameters) { try { bindParams(this.stmt, bindParameters); return this; } catch (err) { throw convertError(err); } } close() { let stmt; try { stmt = this.stmt.must(); } catch (e) { return; } stmt.finalize(); } } var convertibleErrorTypes, CONVERTIBLE_ERROR_PREFIX = "[TURSO_CONVERT_TYPE]"; var init_promise = __esm(() => { init_sqlite_error(); convertibleErrorTypes = { TypeError }; }); // node_modules/@tursodatabase/database-common/dist/index.js var init_dist = __esm(() => { init_compat(); init_promise(); init_sqlite_error(); }); // node_modules/@tursodatabase/database/index.js import { createRequire } from "module"; function requireNative() { if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { try { nativeBinding = require2(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); } catch (err) { loadErrors.push(err); } } else if (process.platform === "android") { if (process.arch === "arm64") { try { return require2("./turso.android-arm64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-android-arm64"); const bindingPackageVersion = require2("@tursodatabase/database-android-arm64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "arm") { try { return require2("./turso.android-arm-eabi.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-android-arm-eabi"); const bindingPackageVersion = require2("@tursodatabase/database-android-arm-eabi/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)); } } else if (process.platform === "win32") { if (process.arch === "x64") { try { return require2("./turso.win32-x64-msvc.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-win32-x64-msvc"); const bindingPackageVersion = require2("@tursodatabase/database-win32-x64-msvc/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "ia32") { try { return require2("./turso.win32-ia32-msvc.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-win32-ia32-msvc"); const bindingPackageVersion = require2("@tursodatabase/database-win32-ia32-msvc/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "arm64") { try { return require2("./turso.win32-arm64-msvc.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-win32-arm64-msvc"); const bindingPackageVersion = require2("@tursodatabase/database-win32-arm64-msvc/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)); } } else if (process.platform === "darwin") { try { return require2("./turso.darwin-universal.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-darwin-universal"); const bindingPackageVersion = require2("@tursodatabase/database-darwin-universal/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } if (process.arch === "x64") { try { return require2("./turso.darwin-x64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-darwin-x64"); const bindingPackageVersion = require2("@tursodatabase/database-darwin-x64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "arm64") { try { return require2("./turso.darwin-arm64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-darwin-arm64"); const bindingPackageVersion = require2("@tursodatabase/database-darwin-arm64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)); } } else if (process.platform === "freebsd") { if (process.arch === "x64") { try { return require2("./turso.freebsd-x64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-freebsd-x64"); const bindingPackageVersion = require2("@tursodatabase/database-freebsd-x64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "arm64") { try { return require2("./turso.freebsd-arm64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-freebsd-arm64"); const bindingPackageVersion = require2("@tursodatabase/database-freebsd-arm64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)); } } else if (process.platform === "linux") { if (process.arch === "x64") { if (isMusl()) { try { return require2("./turso.linux-x64-musl.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-x64-musl"); const bindingPackageVersion = require2("@tursodatabase/database-linux-x64-musl/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { try { return require2("./turso.linux-x64-gnu.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-x64-gnu"); const bindingPackageVersion = require2("@tursodatabase/database-linux-x64-gnu/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } } else if (process.arch === "arm64") { if (isMusl()) { try { return require2("./turso.linux-arm64-musl.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-arm64-musl"); const bindingPackageVersion = require2("@tursodatabase/database-linux-arm64-musl/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { try { return require2("./turso.linux-arm64-gnu.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-arm64-gnu"); const bindingPackageVersion = require2("@tursodatabase/database-linux-arm64-gnu/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } } else if (process.arch === "arm") { if (isMusl()) { try { return require2("./turso.linux-arm-musleabihf.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-arm-musleabihf"); const bindingPackageVersion = require2("@tursodatabase/database-linux-arm-musleabihf/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { try { return require2("./turso.linux-arm-gnueabihf.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-arm-gnueabihf"); const bindingPackageVersion = require2("@tursodatabase/database-linux-arm-gnueabihf/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } } else if (process.arch === "riscv64") { if (isMusl()) { try { return require2("./turso.linux-riscv64-musl.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-riscv64-musl"); const bindingPackageVersion = require2("@tursodatabase/database-linux-riscv64-musl/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { try { return require2("./turso.linux-riscv64-gnu.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-riscv64-gnu"); const bindingPackageVersion = require2("@tursodatabase/database-linux-riscv64-gnu/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } } else if (process.arch === "ppc64") { try { return require2("./turso.linux-ppc64-gnu.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-ppc64-gnu"); const bindingPackageVersion = require2("@tursodatabase/database-linux-ppc64-gnu/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "s390x") { try { return require2("./turso.linux-s390x-gnu.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-linux-s390x-gnu"); const bindingPackageVersion = require2("@tursodatabase/database-linux-s390x-gnu/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)); } } else if (process.platform === "openharmony") { if (process.arch === "arm64") { try { return require2("./turso.openharmony-arm64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-openharmony-arm64"); const bindingPackageVersion = require2("@tursodatabase/database-openharmony-arm64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "x64") { try { return require2("./turso.openharmony-x64.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-openharmony-x64"); const bindingPackageVersion = require2("@tursodatabase/database-openharmony-x64/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else if (process.arch === "arm") { try { return require2("./turso.openharmony-arm.node"); } catch (e) { loadErrors.push(e); } try { const binding = require2("@tursodatabase/database-openharmony-arm"); const bindingPackageVersion = require2("@tursodatabase/database-openharmony-arm/package.json").version; if (bindingPackageVersion !== "0.6.0-pre.18" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") { throw new Error(`Native binding package version mismatch, expected 0.6.0-pre.18 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`); } return binding; } catch (e) { loadErrors.push(e); } } else { loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)); } } else { loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)); } } var require2, __dirname2, readFileSync, nativeBinding = null, loadErrors, isMusl = () => { let musl = false; if (process.platform === "linux") { musl = isMuslFromFilesystem(); if (musl === null) { musl = isMuslFromReport(); } if (musl === null) { musl = isMuslFromChildProcess(); } } return musl; }, isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-"), isMuslFromFilesystem = () => { try { return readFileSync("/usr/bin/ldd", "utf-8").includes("musl"); } catch { return null; } }, isMuslFromReport = () => { let report = null; if (typeof process.report?.getReport === "function") { process.report.excludeNetwork = true; report = process.report.getReport(); } if (!report) { return null; } if (report.header && report.header.glibcVersionRuntime) { return false; } if (Array.isArray(report.sharedObjects)) { if (report.sharedObjects.some(isFileMusl)) { return true; } } return false; }, isMuslFromChildProcess = () => { try { return require2("child_process").execSync("ldd --version", { encoding: "utf8" }).includes("musl"); } catch (e) { return false; } }, BatchExecutor, Database3, Statement3, EncryptionCipher; var init_database = __esm(() => { require2 = createRequire(import.meta.url); __dirname2 = new URL(".", import.meta.url).pathname; ({ readFileSync } = require2("node:fs")); loadErrors = []; nativeBinding = requireNative(); if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { try { nativeBinding = require2("./turso.wasi.cjs"); } catch (err) { if (process.env.NAPI_RS_FORCE_WASI) { loadErrors.push(err); } } if (!nativeBinding) { try { nativeBinding = require2("@tursodatabase/database-wasm32-wasi"); } catch (err) { if (process.env.NAPI_RS_FORCE_WASI) { loadErrors.push(err); } } } } if (!nativeBinding) { if (loadErrors.length > 0) { throw new Error(`Cannot find native binding. ` + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + "Please try `npm i` again after removing both package-lock.json and node_modules directory.", { cause: loadErrors }); } throw new Error(`Failed to load native binding`); } ({ BatchExecutor, Database: Database3, Statement: Statement3, EncryptionCipher } = nativeBinding); }); // node_modules/@tursodatabase/database/dist/promise.js var exports_promise = {}; __export(exports_promise, { connect: () => connect, SqliteError: () => SqliteError, Database: () => Database4 }); function getCipherValue(cipher) { if (!EncryptionCipher) { throw new Error("Encryption is not supported in this build"); } const cipherMap = { aes128gcm: EncryptionCipher.Aes128Gcm, aes256gcm: EncryptionCipher.Aes256Gcm, aegis256: EncryptionCipher.Aegis256, aegis256x2: EncryptionCipher.Aegis256x2, aegis128l: EncryptionCipher.Aegis128l, aegis128x2: EncryptionCipher.Aegis128x2, aegis128x4: EncryptionCipher.Aegis128x4 }; return cipherMap[cipher]; } async function connect(path, opts = {}) { const db = new Database4(path, opts); await db.connect(); return db; } var Database4; var init_promise2 = __esm(() => { init_dist(); init_database(); Database4 = class Database4 extends Database { constructor(path, opts = {}) { const nativeOpts = { ...opts }; if (opts.encryption) { nativeOpts.encryption = { cipher: getCipherValue(opts.encryption.cipher), hexkey: opts.encryption.hexkey }; } super(new Database3(path, nativeOpts)); } }; }); // src/query/conditions.ts function isColumnDef(value) { return value !== null && typeof value === "object" && "__internal" in value; } function eq(left, valueOrColumn) { if (isColumnDef(valueOrColumn)) { return { type: "eqColumn", left, right: valueOrColumn }; } return { type: "eq", column: left, value: valueOrColumn }; } function and(...conditions) { return { type: "and", conditions }; } function or(...conditions) { return { type: "or", conditions }; } function isIn(column, values) { return { type: "in", column, values }; } function isNotIn(column, values) { return { type: "notIn", column, values }; } function isNull(column) { return { type: "isNull", column }; } function isNotNull(column) { return { type: "isNotNull", column }; } function like(column, pattern) { return { type: "like", column, pattern }; } function glob(column, pattern) { return { type: "glob", column, pattern }; } function between(column, low, high) { return { type: "between", column, low, high }; } function gt(column, value) { return { type: "gt", column, value }; } function gte(column, value) { return { type: "gte", column, value }; } function lt(column, value) { return { type: "lt", column, value }; } function lte(column, value) { return { type: "lte", column, value }; } function neq(column, value) { return { type: "neq", column, value }; } function compileCondition(cond, params) { switch (cond.type) { case "eq": params.push(cond.column.__internal.encode(cond.value)); return `${cond.column.name} = ?`; case "eqColumn": { const leftName = cond.left.__internal.tableName ? `${cond.left.__internal.tableName}.${cond.left.name}` : cond.left.name; const rightName = cond.right.__internal.tableName ? `${cond.right.__internal.tableName}.${cond.right.name}` : cond.right.name; return `${leftName} = ${rightName}`; } case "in": { const encoded = cond.values.map((v) => cond.column.__internal.encode(v)); params.push(...encoded); const placeholders = encoded.map(() => "?").join(", "); return `${cond.column.name} IN (${placeholders})`; } case "notIn": { const encoded = cond.values.map((v) => cond.column.__internal.encode(v)); params.push(...encoded); const placeholders = encoded.map(() => "?").join(", "); return `${cond.column.name} NOT IN (${placeholders})`; } case "isNull": return `${cond.column.name} IS NULL`; case "isNotNull": return `${cond.column.name} IS NOT NULL`; case "like": params.push(cond.pattern); return `${cond.column.name} LIKE ?`; case "glob": params.push(cond.pattern); return `${cond.column.name} GLOB ?`; case "between": params.push(cond.column.__internal.encode(cond.low)); params.push(cond.column.__internal.encode(cond.high)); return `${cond.column.name} BETWEEN ? AND ?`; case "gt": params.push(cond.column.__internal.encode(cond.value)); return `${cond.column.name} > ?`; case "gte": params.push(cond.column.__internal.encode(cond.value)); return `${cond.column.name} >= ?`; case "lt": params.push(cond.column.__internal.encode(cond.value)); return `${cond.column.name} < ?`; case "lte": params.push(cond.column.__internal.encode(cond.value)); return `${cond.column.name} <= ?`; case "neq": params.push(cond.column.__internal.encode(cond.value)); return `${cond.column.name} != ?`; case "and": return cond.conditions.map((c) => compileCondition(c, params)).join(" AND "); case "or": return `(${cond.conditions.map((c) => compileCondition(c, params)).join(" OR ")})`; } } function compileConditions(conditions, params) { if (conditions.length === 0) return "1=1"; return conditions.map((c) => compileCondition(c, params)).join(" AND "); } // src/errors.ts var FlintError, FlintValidationError, FlintQueryError; var init_errors = __esm(() => { FlintError = class FlintError extends Error { constructor(message) { super(message); this.name = "FlintError"; } }; FlintValidationError = class FlintValidationError extends FlintError { constructor(message) { super(message); this.name = "FlintValidationError"; } }; FlintQueryError = class FlintQueryError extends FlintError { originalError; constructor(message, originalError) { super(message); this.name = "FlintQueryError"; this.originalError = originalError; } }; }); // src/query/builder.ts function getCol(tbl, key) { const col = tbl[key]; if (!col) throw new FlintValidationError(`Column "${key}" not found in table`); return col; } function columnEntries(tbl) { return Object.entries(tbl).filter(([k]) => k !== "_" && k !== "__indexes"); } function decodeRow(raw, tbl) { const out = {}; for (const [key, col] of columnEntries(tbl)) { out[key] = col.__internal.decode(raw[col.name]); } return out; } function decodeSelectedRow(raw, tbl, keys) { const out = {}; for (const key of keys) { const col = getCol(tbl, key); out[key] = col.__internal.decode(raw[col.name]); } return out; } function findPKKeys(tbl) { const keys = []; for (const [key, col] of columnEntries(tbl)) { if (col.__internal.isPrimaryKey) keys.push(key); } if (keys.length === 0) { throw new FlintValidationError("Table has no primary key column"); } return keys; } function resolveForeignKeyCondition(parent, parentName, child, childName) { for (const [, col] of columnEntries(child)) { if (col.__internal.referencesTable === parentName && col.__internal.referencesColumn) { const parentCol = getCol(parent, col.__internal.referencesColumn); if (parentCol) { return eq(parentCol, col); } } } throw new FlintValidationError(`No foreign key reference found from "${childName}" to "${parentName}". Use .references() on the child table or provide an explicit condition.`); } function extractColumns(cond) { switch (cond.type) { case "eq": return [cond.column]; case "eqColumn": return [cond.left, cond.right]; case "in": case "notIn": case "isNull": case "isNotNull": case "like": case "glob": case "between": return [cond.column]; case "and": case "or": return cond.conditions.flatMap(extractColumns); default: return []; } } function validateColumnOwnership(conditions, allowedTables, context) { const allowedColumns = new Set(allowedTables.flatMap((t) => columnEntries(t).map(([, c]) => c))); for (const cond of conditions) { const cols = extractColumns(cond); for (const col of cols) { if (!allowedColumns.has(col)) { throw new FlintValidationError(`Column "${col.name}" does not belong to ${context}. ` + `Check that you're using a column from the queried table, not a different table.`); } } } } function resolveColumns(table, selectedColumns, prefix) { if (selectedColumns) { return selectedColumns.map((k) => { const name = getCol(table, k).name; return prefix ? `${prefix}.${name}` : name; }).join(", "); } const entries = columnEntries(table); return entries.map(([, c]) => prefix ? `${prefix}.${c.name}` : c.name).join(", "); } class SelectBuilder { #executor; #tableName; #table; #conditions; #selectedColumns; #orderByClauses; #limitValue; #offsetValue; #distinct; constructor(executor, tableName, table, conditions = [], selectedColumns = null, orderByClauses = [], limitValue = null, offsetValue = null, distinct = false) { this.#executor = executor; this.#tableName = tableName; this.#table = table; this.#conditions = conditions; this.#selectedColumns = selectedColumns; this.#orderByClauses = orderByClauses; this.#limitValue = limitValue; this.#offsetValue = offsetValue; this.#distinct = distinct; } where(condition) { return new SelectBuilder(this.#executor, this.#tableName, this.#table, [...this.#conditions, condition], this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct); } columns(keys) { return new NarrowedSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, keys, this.#orderByClauses, this.#limitValue, this.#offsetValue, this.#distinct); } single() { return new SingleSelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#offsetValue, this.#distinct); } distinct() { return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, this.#offsetValue, true); } orderBy(key, direction = "asc") { const column = getCol(this.#table, key); return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, [...this.#orderByClauses, { column, direction }], this.#limitValue, this.#offsetValue, this.#distinct); } limit(n) { return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, n, this.#offsetValue, this.#distinct); } offset(n) { return new SelectBuilder(this.#executor, this.#tableName, this.#table, this.#conditions, this.#selectedColumns, this.#orderByClauses, this.#limitValue, n, this.#distinct); } toSQL() { validateColumnOwnership(this.#conditions, [this.#table], `SELECT from "${this.#tableName}"`); const cols = resolveColumns(this.#table, this.#selectedColumns); const params = []; const distinct = this.#distinct ? "DISTINCT " : ""; let sql = `SELECT ${distinct}${cols} FROM ${this.#tableName}`; const where = compileConditions(this.#conditions, params); if (where !== "1=1") sql += ` WHERE ${where}`; if (this.#orderByClauses.length > 0) { const orderClauses = this.#orderByClauses.map((o) => `${o.column.name} ${o.direction.toUpperCase()}`).join(", "); sql += ` ORDER BY ${orderClauses}`; } if (this.#limitValue !== null) sql += ` LIMIT ${this.#limitValue}`; if (this.#offsetValue !== null) sql += ` OFFSET ${this.#offsetValue}`; return { sql, params }; } async exec