{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/validate.ts","../src/fk.ts","../src/schema.ts","../src/where.ts","../src/context.ts","../src/values.ts","../src/sql.ts","../src/order-by.ts","../src/stringify.ts","../src/set.ts","../src/pragmas.ts","../src/database.ts","../src/cache.ts","../src/logger.ts","../src/idx.ts"],"sourcesContent":["/**\n * @module @takinprofit/sqlitex\n *\n * A type-safe SQLite query builder and database wrapper for Node.js\n *\n * Features:\n * - Type-safe SQL template literals\n * - Prepared statement caching\n * - JSON column support\n * - Strongly typed table schemas\n * - SQL query composition\n * - Full SQLite PRAGMA configuration\n *\n * @example\n * ```ts\n * import { DB } from '@takinprofit/sqlitex'\n *\n * const db = new DB({ location: ':memory:' })\n *\n * // Type-safe queries\n * const users = db.sql<{id: number}>`\n *   SELECT * FROM users\n *   WHERE id = ${'$id'}\n * `\n * const result = users.get({ id: 1 })\n * ```\n *\n * @see {@link https://github.com/takinprofit/sqlitex/blob/main/README.md|Documentation}\n */\nexport type { ValidationError } from \"#validate\"\nexport * from \"#types\"\nexport { Sql, raw } from \"#sql\"\nexport type { XStatementSync } from \"#sql\"\n\nexport type { DeferrableStatus, FKAction, ForeignKeyDef } from \"#fk\"\n\nexport { PragmaDefaults } from \"#pragmas\"\nexport type {\n\tJournalMode,\n\tJournalModes,\n\tSynchronousMode,\n\tSynchronousModes,\n\tTempStore,\n\tTempStores,\n\tLockingMode,\n\tLockingModes,\n} from \"#pragmas\"\n\nexport { DB } from \"#database\"\n\nexport * from \"#logger\"\nexport * from \"#errors\"\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\nimport type { StatementSync } from \"node:sqlite\"\nimport type { Sql, XStatementSync } from \"#sql\"\nimport type { CacheStats, StatementCacheOptions } from \"#cache\"\nimport type { PragmaConfig } from \"#pragmas\"\nimport type { Logger } from \"#logger\"\nimport type { Primitive } from \"type-fest\"\nimport type { ForeignKeyDef } from \"#fk\"\n\n/**\n * Configuration options for database cleanup operations when closing the connection.\n */\nexport interface CleanupPragmas {\n\t/** Runs PRAGMA optimize to optimize the database */\n\toptimize?: boolean\n\n\t/** Runs PRAGMA shrink_memory to release memory back to the system */\n\tshrinkMemory?: boolean\n\n\t/** WAL checkpoint mode to run before closing */\n\twalCheckpoint?: \"PASSIVE\" | \"FULL\" | \"RESTART\" | \"TRUNCATE\"\n}\n\n/**\n * Configuration options for database initialization.\n */\nexport interface DBOptions {\n\t/** Database file path or \":memory:\" for in-memory database */\n\tlocation?: string | \":memory:\"\n\n\tallowExtension?: boolean\n\n\t/** Statement cache configuration - boolean to use defaults or detailed options */\n\tstatementCache?: boolean | StatementCacheOptions\n\n\t/** SQLite PRAGMA settings */\n\tpragma?: PragmaConfig\n\n\t/** Runtime environment affecting default PRAGMA settings */\n\tenvironment?: \"development\" | \"testing\" | \"production\"\n\n\t/** Custom logger implementation */\n\tlogger?: Logger\n\n\t/** SQL formatting configuration */\n\tformat?: FormatterConfig\n}\n\n/**\n * Function type for SQL template literal tag\n */\nexport type SqlFn<P extends DataRow> = (\n\tstrings: TemplateStringsArray,\n\t...params: SqlTemplateValues<P>\n) => Sql<P>\n\nexport interface IDatabase {\n\tprepareStatement(sql: string): StatementSync\n\tsql<P extends DataRow, R = unknown>(\n\t\tstrings: TemplateStringsArray,\n\t\t...params: SqlTemplateValues<P>\n\t): XStatementSync<P, R>\n\texec(sql: string): void\n\tbackup(filename: string): void\n\trestore(filename: string): void\n\tgetCacheStats(): CacheStats | undefined\n\tclearStatementCache(): void\n\tclose(pragmas?: CleanupPragmas): void\n}\n\nexport const COMPARISON_OPERATORS = [\n\t\"=\",\n\t\"!=\",\n\t\">\",\n\t\"<\",\n\t\">=\",\n\t\"<=\",\n\t\"LIKE\",\n\t\"NOT LIKE\",\n\t\"IN\",\n\t\"NOT IN\",\n\t\"IS\",\n\t\"IS NOT\",\n] as const\n\nexport const LOGICAL_OPERATORS = [\"AND\", \"OR\"] as const\n\nexport type ComparisonOperator = (typeof COMPARISON_OPERATORS)[number]\nexport type LogicalOperator = (typeof LOGICAL_OPERATORS)[number]\n\n/**\n * A row of data from a database query, or a row of data to be inserted, or a row of data used for query conditions.\n */\n// biome-ignore lint/suspicious/noExplicitAny: <explanation>\nexport type DataRow = { [key: string]: any }\n\nexport type RawValue = { type: \"__x_literal__\"; value: string }\n\n// Update isLiteral type guard\nexport function isRawValue(value: unknown): value is RawValue {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\tObject.hasOwn(value, \"type\") &&\n\t\t(value as RawValue).type === \"__x_literal__\"\n\t)\n}\n\n/**\n * Represents a parameter operator that references a property of type P\n */\nexport type ParameterOperator<P extends DataRow> = `$${keyof P & string}`\n\n// Step 2: Get keys of non-primitive values\nexport type NonPrimitiveKeys<T> = {\n\t[K in keyof T]: T[K] extends Primitive ? never : K\n}[keyof T]\n\n/**\n * Represents a parameter operator that converts a property to JSON\n * Only allows non-primitive values to be converted to JSON\n */\nexport type ToJson<P extends DataRow> =\n\t`$${NonPrimitiveKeys<P> & string}${\"->json\"}`\n\n/**\n * Represents a parameter operator that parses a property from JSON\n * Only allows non-primitive values to be parsed from JSON\n */\nexport type FromJson<P extends DataRow> =\n\t`$${NonPrimitiveKeys<P> & string}${\"<-json\"}` // only supports json_extract\n\n/**\n * Union type of all possible parameter operators\n */\nexport type ParamValue<P extends DataRow> =\n\t| ParameterOperator<P>\n\t| ToJson<P>\n\t| FromJson<P>\n\nexport type SqlTemplateValue<P extends DataRow, R = P> =\n\t| ParamValue<P>\n\t| SqlContext<P, R>\n\t| RawValue\n\t// biome-ignore lint/suspicious/noExplicitAny: <explanation>\n\t| XStatementSync<any, any>\n/**\n * Parameter values and contexts that can be used in SQL template literals\n */\nexport type SqlTemplateValues<P extends DataRow, R = P> = Array<\n\tSqlTemplateValue<P, R>\n>\n\n/**\n * Configuration for SQL formatting\n */\nexport type FormatterConfig =\n\t| false\n\t| {\n\t\t\t/** Indentation string (default: two spaces) */\n\t\t\tindent?: string\n\n\t\t\t/** Case for SQL keywords */\n\t\t\treservedWordCase?: \"upper\" | \"lower\"\n\n\t\t\t/** Lines between queries */\n\t\t\tlinesBetweenQueries?: number | \"preserve\"\n\t  }\n\n/**\n * Options for initializing SQL builder\n */\nexport type SqlOptions<P extends DataRow, R = P> = {\n\tstrings: readonly string[]\n\tparamOperators: SqlTemplateValues<P, R>\n\tformatterConfig?: FormatterConfig\n\tgeneratedSql?: string\n}\n\nexport type ValueType<P extends DataRow> = ParameterOperator<P> | ToJson<P>\n\nexport type SetOptions<P extends DataRow> =\n\t| { [K in keyof P]?: ValueType<P> | RawValue }\n\t| [\"*\", { jsonColumns: (keyof P)[] }]\n\t| \"*\"\n\nexport type InsertOptions<P extends DataRow> =\n\t| ValueType<P>[]\n\t| \"*\"\n\t| [\"*\", { jsonColumns?: (keyof P)[]; batch?: boolean }]\n\nexport type ColumnOptions<P extends DataRow> =\n\t| (\n\t\t\t| keyof P\n\t\t\t| `${NonPrimitiveKeys<P> & string}${\"<-json\"}`\n\t\t\t| `${NonPrimitiveKeys<P> & string}${\"->json\"}`\n\t  )[]\n\t| \"*\"\n\n// Core SQL context type\nexport type SqlContext<P extends DataRow, R = P> = Partial<{\n\tcolumns: ColumnOptions<P>\n\tvalues: InsertOptions<P>\n\tset: SetOptions<P>\n\twhere: WhereClause<P>\n\torderBy: Partial<Record<keyof P, \"ASC\" | \"DESC\">>\n\tlimit: number\n\toffset: number\n\treturning: (keyof R)[] | \"*\" | [\"*\", { jsonColumns?: (keyof R)[] }]\n\tschema: Schema<P>\n}>\n\nexport type SingleWhereCondition<P extends DataRow> =\n\t| `${keyof P & string} ${ComparisonOperator} $${keyof P & string}`\n\t| `${keyof P & string} IS NULL`\n\t| `${keyof P & string} IS NOT NULL`\n\t| [keyof P & string, ComparisonOperator, RawValue] // New tuple format for RawValue\n// Recursive type to enforce alternating condition/operator pattern\nexport type ExtendedWhereCondition<P extends DataRow> =\n\t| [SingleWhereCondition<P>, LogicalOperator, SingleWhereCondition<P>]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\t| [\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t\t\tLogicalOperator,\n\t\t\tSingleWhereCondition<P>,\n\t  ]\n\n/**\n * Represents a WHERE clause condition for SQL queries with strongly-typed column references and parameter bindings.\n * Supports single conditions and compound conditions with logical operators (AND/OR).\n * @example\n * // Single condition\n * const where: WhereClause<User> = \"age > $minAge\"\n *\n * // Compound condition\n * const where: WhereClause<User> = [\"age > $minAge\", \"AND\", \"isActive = $active\"]\n */\nexport type WhereClause<P extends DataRow> =\n\t| SingleWhereCondition<P>\n\t| ExtendedWhereCondition<P>\n\n/**\n * SQLite column constraints for table definitions\n */\nexport type BaseConstraint =\n\t| \"PRIMARY KEY\"\n\t| \"AUTOINCREMENT\"\n\t| \"UNIQUE\"\n\t| `CHECK(${string})`\n\t| `CHECK (${string})` // Support both with and without space\n\t| `FOREIGN KEY REFERENCES ${string} (${string})`\n\t| `DEFAULT ${string}`\n\t| \"NOT NULL\"\n/**\n * SQLite storage classes (data types)\n * @see https://www.sqlite.org/datatype3.html\n */\nexport type DataType = \"TEXT\" | \"INTEGER\" | \"REAL\" | \"BLOB\"\n\n/**\n * Patterns for combining data types with constraints based on nullability\n * @template T Field type\n * @template D SQLite data type\n */\nexport type ConstraintPatterns<T, D extends DataType> = undefined extends T\n\t?\n\t\t\t| `${D} ${BaseConstraint}`\n\t\t\t| `${D} ${BaseConstraint} ${Exclude<BaseConstraint, \"NOT NULL\">}`\n\t\t\t| `${D} ${BaseConstraint} ${Exclude<BaseConstraint, \"NOT NULL\">} ${Exclude<BaseConstraint, \"NOT NULL\">}`\n\t:\n\t\t\t| `${D} ${BaseConstraint}`\n\t\t\t| `${D} ${BaseConstraint} ${BaseConstraint}`\n\t\t\t| `${D} ${BaseConstraint} ${BaseConstraint} ${BaseConstraint}`\n\n/**\n * Maps TypeScript types to valid SQLite column definitions with constraints\n * @template T The TypeScript type to map\n */\nexport type ValidColumnTypeMap<T> = T extends string\n\t? ConstraintPatterns<T, \"TEXT\"> | \"TEXT\"\n\t: T extends number\n\t\t?\n\t\t\t\t| ConstraintPatterns<T, \"INTEGER\">\n\t\t\t\t| ConstraintPatterns<T, \"REAL\">\n\t\t\t\t| \"INTEGER\"\n\t\t\t\t| \"REAL\"\n\t\t: T extends boolean\n\t\t\t? ConstraintPatterns<T, \"INTEGER\"> | \"INTEGER\"\n\t\t\t: T extends bigint\n\t\t\t\t? ConstraintPatterns<T, \"INTEGER\"> | \"INTEGER\"\n\t\t\t\t: T extends object | unknown[]\n\t\t\t\t\t?\n\t\t\t\t\t\t\t| ConstraintPatterns<T, \"TEXT\">\n\t\t\t\t\t\t\t| ConstraintPatterns<T, \"BLOB\">\n\t\t\t\t\t\t\t| \"BLOB\"\n\t\t\t\t\t\t\t| \"TEXT\"\n\t\t\t\t\t: never\n\n/**\n * Type-safe column definitions for a table\n * @template T Table row type\n */\nexport type Schema<T extends DataRow> = {\n\t[K in keyof T]?: ValidColumnTypeMap<T[K]>\n} & { $$foreignKeys?: ForeignKeyDef<T>[] }\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * SQLite primary result codes (least significant 8 bits)\n * @see https://www.sqlite.org/rescode.html\n */\nexport enum SqlitePrimaryResultCode {\n\tSQLITE_OK = 0,\n\tSQLITE_ERROR = 1,\n\tSQLITE_INTERNAL = 2,\n\tSQLITE_PERM = 3,\n\tSQLITE_ABORT = 4,\n\tSQLITE_BUSY = 5,\n\tSQLITE_LOCKED = 6,\n\tSQLITE_NOMEM = 7,\n\tSQLITE_READONLY = 8,\n\tSQLITE_INTERRUPT = 9,\n\tSQLITE_IOERR = 10,\n\tSQLITE_CORRUPT = 11,\n\tSQLITE_NOTFOUND = 12,\n\tSQLITE_FULL = 13,\n\tSQLITE_CANTOPEN = 14,\n\tSQLITE_PROTOCOL = 15,\n\tSQLITE_SCHEMA = 17,\n\tSQLITE_CONSTRAINT = 19,\n\tSQLITE_MISMATCH = 20,\n\tSQLITE_MISUSE = 21,\n}\n\n/**\n * Maps error codes to their type strings for better error reporting\n */\nexport const SqliteErrorTypes = {\n\t[SqlitePrimaryResultCode.SQLITE_OK]: \"OK\",\n\t[SqlitePrimaryResultCode.SQLITE_ERROR]: \"ERROR\",\n\t[SqlitePrimaryResultCode.SQLITE_INTERNAL]: \"INTERNAL_ERROR\",\n\t[SqlitePrimaryResultCode.SQLITE_PERM]: \"PERMISSION_DENIED\",\n\t[SqlitePrimaryResultCode.SQLITE_ABORT]: \"OPERATION_ABORTED\",\n\t[SqlitePrimaryResultCode.SQLITE_BUSY]: \"DATABASE_BUSY\",\n\t[SqlitePrimaryResultCode.SQLITE_LOCKED]: \"DATABASE_LOCKED\",\n\t[SqlitePrimaryResultCode.SQLITE_NOMEM]: \"OUT_OF_MEMORY\",\n\t[SqlitePrimaryResultCode.SQLITE_READONLY]: \"DATABASE_READONLY\",\n\t[SqlitePrimaryResultCode.SQLITE_INTERRUPT]: \"OPERATION_INTERRUPTED\",\n\t[SqlitePrimaryResultCode.SQLITE_IOERR]: \"IO_ERROR\",\n\t[SqlitePrimaryResultCode.SQLITE_CORRUPT]: \"DATABASE_CORRUPT\",\n\t[SqlitePrimaryResultCode.SQLITE_NOTFOUND]: \"NOT_FOUND\",\n\t[SqlitePrimaryResultCode.SQLITE_FULL]: \"DATABASE_FULL\",\n\t[SqlitePrimaryResultCode.SQLITE_CANTOPEN]: \"CANNOT_OPEN\",\n\t[SqlitePrimaryResultCode.SQLITE_PROTOCOL]: \"PROTOCOL_ERROR\",\n\t[SqlitePrimaryResultCode.SQLITE_SCHEMA]: \"SCHEMA_CHANGED\",\n\t[SqlitePrimaryResultCode.SQLITE_CONSTRAINT]: \"CONSTRAINT_VIOLATION\",\n\t[SqlitePrimaryResultCode.SQLITE_MISMATCH]: \"TYPE_MISMATCH\",\n\t[SqlitePrimaryResultCode.SQLITE_MISUSE]: \"LIBRARY_MISUSE\",\n} as const\n\nexport type SqliteErrorType =\n\t(typeof SqliteErrorTypes)[keyof typeof SqliteErrorTypes]\n\n/**\n * Error interface for node:sqlite errors\n */\nexport interface NodeSqliteErrorData {\n\tcode: string\n\terrcode: number\n\terrstr: string\n\tmessage: string\n\terrorType: SqliteErrorType\n\toriginalError?: Error\n}\n\n/**\n * Custom error class for node:sqlite errors with enhanced type information\n */\nexport class NodeSqliteError extends Error implements NodeSqliteErrorData {\n\tpublic readonly errorType: SqliteErrorType\n\n\tconstructor(\n\t\tpublic readonly code: string,\n\t\tpublic readonly errcode: number,\n\t\tpublic readonly errstr: string,\n\t\tmessage: string,\n\t\tpublic readonly originalError?: Error\n\t) {\n\t\tsuper(message)\n\t\tthis.name = \"NodeSqliteError\"\n\t\tthis.errorType =\n\t\t\tSqliteErrorTypes[errcode as keyof typeof SqliteErrorTypes] || \"ERROR\"\n\t\tObject.setPrototypeOf(this, NodeSqliteError.prototype)\n\t}\n\n\t/**\n\t * Gets the primary result code (least significant 8 bits)\n\t */\n\tgetPrimaryResultCode(): SqlitePrimaryResultCode {\n\t\treturn this.errcode & 0xff\n\t}\n\n\toverride toString(): string {\n\t\treturn `NodeSqliteError: [${this.errorType}] ${this.message} (code: ${this.code}, errcode: ${this.errcode})`\n\t}\n\n\tstatic fromNodeSqlite(\n\t\terror: Error & {\n\t\t\t\t\tcode?: string\n\t\t\terrcode?: number\n\t\t\terrstr?: string\n\t\t}\n\t): NodeSqliteError {\n\t\treturn new NodeSqliteError(\n\t\t\terror.code || \"ERR_SQLITE_ERROR\",\n\t\t\terror.errcode || SqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\terror.errstr || \"unknown error\",\n\t\t\terror.message,\n\t\t\terror\n\t\t)\n\t}\n}\n\nexport function isNodeSqliteError(error: unknown): error is NodeSqliteError {\n\treturn (\n\t\terror instanceof NodeSqliteError ||\n\t\t(error instanceof Error &&\n\t\t\t\"code\" in error &&\n\t\t\t\"errcode\" in error &&\n\t\t\t\"errstr\" in error &&\n\t\t\terror.code === \"ERR_SQLITE_ERROR\")\n\t)\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n/**\n * Represents a validation error with a message and optional path indicating where the error occurred.\n * @property _validation_error - Internal flag to identify validation errors\n * @property message - Human-readable error message\n * @property path - Optional path indicating where the error occurred (e.g. \"user.name\")\n */\nexport type ValidationError = {\n\t_validation_error: true\n\tmessage: string\n\tpath?: string\n}\n\nexport const isValidationErr = (value: unknown): value is ValidationError => {\n\treturn (\n\t\ttypeof value === \"object\" && value !== null && \"_validation_error\" in value\n\t)\n}\n\nexport const isValidationErrs = (value: unknown): value is ValidationError[] =>\n\tArray.isArray(value) && value.length > 0 && value.every(isValidationErr)\n\nexport const validationErr = ({\n\tmsg: message,\n\tpath,\n}: {\n\tmsg: string\n\tpath?: string\n}): ValidationError => ({\n\t_validation_error: true,\n\tmessage,\n\tpath,\n})\n","import { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors.js\"\nimport { validationErr, type ValidationError } from \"#validate.js\"\n\n// biome-ignore lint/suspicious/noExplicitAny: <explanation>\ntype DataRow = { [key: string]: any }\n\nexport type DeferrableStatus =\n\t| \"NOT DEFERRABLE\"\n\t| \"NOT DEFERRABLE INITIALLY DEFERRED\"\n\t| \"NOT DEFERRABLE INITIALLY IMMEDIATE\"\n\t| \"DEFERRABLE INITIALLY IMMEDIATE\"\n\t| \"DEFERRABLE INITIALLY DEFERRED\"\n\t| \"DEFERRABLE\"\n\nexport type KeyList<T extends DataRow> =\n\t| keyof T\n\t| `${keyof T & string},${keyof T & string}`\n\t| `${keyof T & string},${keyof T & string},${keyof T & string}`\n\n// Foreign key actions from SQLite spec\nexport type FKAction =\n\t| \"NO ACTION\"\n\t| \"RESTRICT\"\n\t| \"SET NULL\"\n\t| \"SET DEFAULT\"\n\t| \"CASCADE\"\n\nexport type ForeignKeyDef<T extends DataRow> = {\n\tkey: KeyList<T>\n\treferences: { table: string; columns: string[] }\n\tonDelete?: FKAction\n\tonUpdate?: FKAction\n\tdeferrable?: DeferrableStatus\n}\n\nfunction validateKeyList<T extends DataRow>(key: unknown): ValidationError[] {\n\tif (typeof key !== \"string\") {\n\t\treturn [validationErr({ msg: \"Key must be a string\" })]\n\t}\n\n\tconst keys = key.split(\",\").map(k => k.trim())\n\tif (keys.length > 3) {\n\t\treturn [\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Maximum of 3 keys allowed in foreign key constraint\",\n\t\t\t}),\n\t\t]\n\t}\n\n\treturn []\n}\n\nexport function validateForeignKeys<T extends DataRow>(\n\tvalue: unknown\n): ValidationError[] {\n\tif (!value || typeof value !== \"object\") {\n\t\treturn [validationErr({ msg: \"Foreign key must be an object\" })]\n\t}\n\n\tconst errors: ValidationError[] = []\n\tconst foreignKey = value as ForeignKeyDef<T>\n\n\t// Validate key\n\terrors.push(...validateKeyList(foreignKey.key))\n\n\t// Validate references\n\tif (!foreignKey.references) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"References is required\",\n\t\t\t\tpath: \"references\",\n\t\t\t})\n\t\t)\n\t} else {\n\t\tif (typeof foreignKey.references.table !== \"string\") {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Referenced table must be a string\",\n\t\t\t\t\tpath: \"references.table\",\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\n\t\tif (!Array.isArray(foreignKey.references.columns)) {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Referenced columns must be an array\",\n\t\t\t\t\tpath: \"references.columns\",\n\t\t\t\t})\n\t\t\t)\n\t\t} else if (foreignKey.references.columns.length > 3) {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Maximum of 3 referenced columns allowed\",\n\t\t\t\t\tpath: \"references.columns\",\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\n\t// Validate actions\n\tif (foreignKey.onDelete && !isValidAction(foreignKey.onDelete)) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Invalid ON DELETE action\",\n\t\t\t\tpath: \"onDelete\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (foreignKey.onUpdate && !isValidAction(foreignKey.onUpdate)) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Invalid ON UPDATE action\",\n\t\t\t\tpath: \"onUpdate\",\n\t\t\t})\n\t\t)\n\t}\n\n\t// Validate deferrable\n\tif (foreignKey.deferrable && !isValidDeferrable(foreignKey.deferrable)) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Invalid deferrable status\",\n\t\t\t\tpath: \"deferrable\",\n\t\t\t})\n\t\t)\n\t}\n\n\treturn errors\n}\n\nfunction isValidAction(action: string): action is FKAction {\n\treturn [\n\t\t\"NO ACTION\",\n\t\t\"RESTRICT\",\n\t\t\"SET NULL\",\n\t\t\"SET DEFAULT\",\n\t\t\"CASCADE\",\n\t].includes(action)\n}\n\nfunction isValidDeferrable(status: string): status is DeferrableStatus {\n\treturn [\n\t\t\"NOT DEFERRABLE\",\n\t\t\"DEFERRABLE INITIALLY IMMEDIATE\",\n\t\t\"DEFERRABLE INITIALLY DEFERRED\",\n\t].includes(status)\n}\n\nexport function isForeignKeys<T extends DataRow>(\n\tvalue: unknown\n): value is ForeignKeyDef<T> {\n\treturn validateForeignKeys<T>(value).length === 0\n}\n\nexport function buildForeignKeyStatement<T extends DataRow>(\n\tforeignKeys: ForeignKeyDef<T>[]\n): string {\n\tif (!foreignKeys?.length) {\n\t\treturn \"\"\n\t}\n\n\treturn foreignKeys\n\t\t.map(fk => {\n\t\t\tconst key = fk.key as string\n\t\t\tconst keyColumns = key.split(\",\").map(k => k.trim())\n\t\t\tconst refColumns = fk.references.columns\n\n\t\t\tif (keyColumns.length !== refColumns.length) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_FOREIGN_KEY\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Column count mismatch\",\n\t\t\t\t\t`Foreign key columns count (${keyColumns.length}) does not match referenced columns count (${refColumns.length})`,\n\t\t\t\t\tundefined\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tlet sql = `FOREIGN KEY(${keyColumns.join(\", \")}) REFERENCES ${fk.references.table}(${refColumns.join(\", \")})`\n\n\t\t\tif (fk.onDelete) {\n\t\t\t\tsql += ` ON DELETE ${fk.onDelete}`\n\t\t\t}\n\n\t\t\tif (fk.onUpdate) {\n\t\t\t\tsql += ` ON UPDATE ${fk.onUpdate}`\n\t\t\t}\n\n\t\t\tif (fk.deferrable) {\n\t\t\t\tsql += ` ${fk.deferrable}`\n\t\t\t}\n\n\t\t\treturn sql\n\t\t})\n\t\t.join(\",\\n  \")\n}\n","import { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors.js\"\nimport { buildForeignKeyStatement, validateForeignKeys } from \"#fk.js\"\nimport type { DataRow, Schema } from \"#types\"\nimport { validationErr, type ValidationError } from \"#validate\"\n\nconst columnRegex = /^(TEXT|INTEGER|REAL|BLOB)(\\s+.+)?$/\n\nexport function validateSchema<T extends DataRow>(\n\tvalue: unknown\n): ValidationError[] {\n\tif (!value || typeof value !== \"object\") {\n\t\treturn [validationErr({ msg: \"Columns must be an object\" })]\n\t}\n\n\tconst errors: ValidationError[] = []\n\tconst columns = value as Record<string, unknown>\n\n\tfor (const [key, def] of Object.entries(columns)) {\n\t\tif (key === \"$$foreignKeys\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (typeof def !== \"string\") {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: `Column '${key}' definition must be a string`,\n\t\t\t\t\tpath: key,\n\t\t\t\t})\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!columnRegex.test(def.trim())) {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: `Invalid column definition format for '${key}'`,\n\t\t\t\t\tpath: key,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\n\tif (\"$$foreignKeys\" in columns) {\n\t\t// Validate the foreign keys array\n\t\tconst fks = columns.$$foreignKeys\n\t\tif (!Array.isArray(fks)) {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Foreign keys must be an array\",\n\t\t\t\t\tpath: \"$$foreignKeys\",\n\t\t\t\t})\n\t\t\t)\n\t\t} else {\n\t\t\tfks.forEach((fk, idx) => {\n\t\t\t\tconst fkErrors = validateForeignKeys(fk)\n\t\t\t\terrors.push(\n\t\t\t\t\t...fkErrors.map(err => ({\n\t\t\t\t\t\t...err,\n\t\t\t\t\t\tpath: `$$foreignKeys[${idx}].${err.path || \"\"}`,\n\t\t\t\t\t}))\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\t}\n\n\treturn errors\n}\n\nexport function isValidSchema<T extends DataRow>(\n\tvalue: unknown\n): value is Schema<T> {\n\treturn validateSchema<T>(value).length === 0\n}\n\nexport function buildSchema<T extends DataRow>(columns: Schema<T>): string {\n\tconst errors = validateSchema<T>(columns)\n\tif (errors.length > 0) {\n\t\tthrow new NodeSqliteError(\n\t\t\t\"ERR_SQLITE_COLUMNS\",\n\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\"Invalid column definitions\",\n\t\t\terrors.map(e => e.message).join(\"\\n\"),\n\t\t\tundefined\n\t\t)\n\t}\n\n\tconst columnDefs = Object.entries(columns)\n\t\t.filter(([key]) => key !== \"$$foreignKeys\")\n\t\t.map(([name, def]) => `${name} ${String(def).trim()}`)\n\n\tconst foreignKeys = columns.$$foreignKeys\n\t\t? buildForeignKeyStatement(columns.$$foreignKeys)\n\t\t: null\n\n\tconst allDefs = foreignKeys ? [...columnDefs, foreignKeys] : columnDefs\n\n\treturn `(\\n  ${allDefs.join(\",\\n  \")}\\n)`\n}\n","import {\n\tCOMPARISON_OPERATORS,\n\tLOGICAL_OPERATORS,\n\ttype RawValue,\n\ttype ComparisonOperator,\n\ttype DataRow,\n\ttype LogicalOperator,\n\tisRawValue,\n\ttype WhereClause,\n} from \"#types\"\nimport { validationErr, type ValidationError } from \"#validate.js\"\n\nexport function validateWhereClause<P extends DataRow>(\n\twhere: WhereClause<P>\n): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tif (typeof where === \"string\") {\n\t\treturn validateSingleCondition(where)\n\t}\n\n\t// Handle tuple format for RawValue\n\tif (\n\t\tArray.isArray(where) &&\n\t\twhere.length === 3 &&\n\t\t!LOGICAL_OPERATORS.includes(where[1] as (typeof LOGICAL_OPERATORS)[number])\n\t) {\n\t\tconst [column, operator, value] = where\n\t\tif (\n\t\t\ttypeof column !== \"string\" ||\n\t\t\t!COMPARISON_OPERATORS.includes(operator as ComparisonOperator) ||\n\t\t\t!isRawValue(value)\n\t\t) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Invalid RawValue condition format\",\n\t\t\t\t\tpath: \"\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(where)) {\n\t\treturn [\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Where clause must be a string, array, or RawValue condition\",\n\t\t\t}),\n\t\t]\n\t}\n\n\t// Check for minimum length and odd number of elements for logical combinations\n\tif (where.length < 3 || where.length % 2 === 0) {\n\t\treturn [\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Where array must have odd number of elements with minimum length 3\",\n\t\t\t}),\n\t\t]\n\t}\n\n\t// Validate conditions and operators alternate correctly\n\tfor (let i = 0; i < where.length; i++) {\n\t\tif (i % 2 === 0) {\n\t\t\t// Should be condition\n\t\t\tif (Array.isArray(where[i])) {\n\t\t\t\t// Handle RawValue condition\n\t\t\t\tconst condition = where[i] as [string, ComparisonOperator, RawValue]\n\t\t\t\tif (condition.length !== 3 || !isRawValue(condition[2])) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\tmsg: `Invalid RawValue condition at position ${i}`,\n\t\t\t\t\t\t\tpath: `[${i}]`,\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst conditionErrors = validateSingleCondition(where[i] as string)\n\t\t\t\terrors.push(...conditionErrors)\n\t\t\t}\n\t\t} else if (!LOGICAL_OPERATORS.includes(where[i] as LogicalOperator)) {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: `Invalid logical operator at position ${i}`,\n\t\t\t\t\tpath: `[${i}]`,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\n\treturn errors\n}\n\nfunction validateSingleCondition<P extends DataRow>(\n\tcondition: string\n): ValidationError[] {\n\tconst pattern = new RegExp(\n\t\t`^[\\\\w]+\\\\s+(${COMPARISON_OPERATORS.join(\"|\")})\\\\s+\\\\$[\\\\w->json]+$|^[\\\\w]+\\\\s+IS(\\\\s+NOT)?\\\\s+NULL$`\n\t)\n\n\tif (!pattern.test(condition)) {\n\t\treturn [\n\t\t\tvalidationErr({\n\t\t\t\tmsg: `Invalid condition format: ${condition}`,\n\t\t\t\tpath: condition,\n\t\t\t}),\n\t\t]\n\t}\n\n\treturn []\n}\n\nexport function buildWhereStatement<P extends DataRow>(\n\twhere: WhereClause<P>,\n\tparams?: P\n): { sql: string; parameterOperators: string[] } {\n\tconst paramOps: string[] = []\n\n\tif (typeof where === \"string\") {\n\t\t// Extract parameter names from where clause\n\t\tconst matches = where.match(/\\$\\w+/g) || []\n\t\tparamOps.push(...matches)\n\t\treturn {\n\t\t\tsql: `WHERE ${where}`,\n\t\t\tparameterOperators: paramOps,\n\t\t}\n\t}\n\n\t// Handle RawValue tuple format\n\tif (\n\t\tArray.isArray(where) &&\n\t\twhere.length === 3 &&\n\t\t!LOGICAL_OPERATORS.includes(where[1] as (typeof LOGICAL_OPERATORS)[number])\n\t) {\n\t\tconst [column, operator, value] = where\n\t\treturn {\n\t\t\tsql: `WHERE ${column} ${operator} ${(value as RawValue).value}`,\n\t\t\tparameterOperators: [],\n\t\t}\n\t}\n\n\t// Handle array case\n\tconst conditions = where\n\t\t.map((part, i) => {\n\t\t\tif (i % 2 === 0) {\n\t\t\t\tif (Array.isArray(part)) {\n\t\t\t\t\t// Handle RawValue condition\n\t\t\t\t\tconst [column, operator, value] = part\n\t\t\t\t\treturn `${column} ${operator} ${value.value}`\n\t\t\t\t}\n\t\t\t\tconst matches = (part as string).match(/\\$\\w+/g) || []\n\t\t\t\tparamOps.push(...matches)\n\t\t\t\t// Handle JSON operator\n\t\t\t\tif ((part as string).includes(\"->json\")) {\n\t\t\t\t\treturn (part as string).replace(/\\$([\\w]+)->json/, \"jsonb($$$1)\")\n\t\t\t\t}\n\t\t\t\treturn part\n\t\t\t}\n\t\t\treturn ` ${part} `\n\t\t})\n\t\t.join(\"\")\n\n\treturn {\n\t\tsql: `WHERE ${conditions}`,\n\t\tparameterOperators: paramOps,\n\t}\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport { validateSchema } from \"#schema.js\"\nimport { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors\"\nimport {\n\ttype ColumnOptions,\n\tisRawValue,\n\ttype SqlContext,\n\ttype DataRow,\n\ttype WhereClause,\n} from \"#types\"\nimport { validationErr, type ValidationError } from \"#validate\"\nimport { validateWhereClause } from \"#where\"\n\nexport function validateSqlContext<P extends DataRow, R = P>(\n\tvalue: unknown\n): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn [validationErr({ msg: \"SqlContext must be an object\" })]\n\t}\n\n\tconst context = value as Record<string, unknown>\n\n\tfor (const key in context) {\n\t\tswitch (key) {\n\t\t\tcase \"values\": {\n\t\t\t\tconst valueErrors = validateInsertOrSetOptions<P>(context[key])\n\t\t\t\tif (valueErrors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...valueErrors.map(err => ({\n\t\t\t\t\t\t\t...err,\n\t\t\t\t\t\t\tpath: `values${err.path ? `.${err.path}` : \"\"}`,\n\t\t\t\t\t\t}))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"set\": {\n\t\t\t\tconst setErrors = validateSetOptions<P>(context[key])\n\t\t\t\tif (setErrors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...setErrors.map(err => ({\n\t\t\t\t\t\t\t...err,\n\t\t\t\t\t\t\tpath: `set${err.path ? `.${err.path}` : \"\"}`,\n\t\t\t\t\t\t}))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"columns\": {\n\t\t\t\tconst value = context[key]\n\t\t\t\tif (value !== \"*\" && !Array.isArray(value)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\tmsg: \"columns must be '*' or an array\",\n\t\t\t\t\t\t\tpath: \"columns\",\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t} else if (Array.isArray(value)) {\n\t\t\t\t\tif (!value.every(item => typeof item === \"string\")) {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\tmsg: \"columns array must contain only strings\",\n\t\t\t\t\t\t\t\tpath: \"columns\",\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\t// Validate format of each column spec\n\t\t\t\t\tvalue.forEach((col, index) => {\n\t\t\t\t\t\tif (!isValidColumnSpec(col)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\t\tmsg: \"Invalid column format\",\n\t\t\t\t\t\t\t\t\tpath: `columns[${index}]`,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase \"where\": {\n\t\t\t\tconst whereErrors = validateWhereClause<P>(\n\t\t\t\t\tcontext[key] as WhereClause<P>\n\t\t\t\t)\n\t\t\t\tif (whereErrors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...whereErrors.map(err => ({\n\t\t\t\t\t\t\t...err,\n\t\t\t\t\t\t\tpath: `where${err.path ? `.${err.path}` : \"\"}`,\n\t\t\t\t\t\t}))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase \"orderBy\": {\n\t\t\t\tconst orderErrors = validateOrderByClause(context[key])\n\t\t\t\tif (orderErrors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...orderErrors.map(err => ({\n\t\t\t\t\t\t\t...err,\n\t\t\t\t\t\t\tpath: `orderBy${err.path ? `.${err.path}` : \"\"}`,\n\t\t\t\t\t\t}))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase \"limit\":\n\t\t\tcase \"offset\":\n\t\t\t\tif (typeof context[key] !== \"number\") {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\tmsg: `${key} must be a number`,\n\t\t\t\t\t\t\tpath: key,\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase \"schema\": {\n\t\t\t\tconst columnErrors = validateSchema<P>(context[key])\n\t\t\t\tif (columnErrors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...columnErrors.map(err => ({\n\t\t\t\t\t\t\t...err,\n\t\t\t\t\t\t\tpath: `schema${err.path ? `.${err.path}` : \"\"}`,\n\t\t\t\t\t\t}))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase \"returning\": {\n\t\t\t\tconst value = context[key]\n\t\t\t\tif (value !== \"*\" && !Array.isArray(value)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\tmsg: \"returning must be '*' or an array\",\n\t\t\t\t\t\t\tpath: \"returning\",\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t} else if (Array.isArray(value)) {\n\t\t\t\t\t// Check for [\"*\", { jsonColumns: [...] }] format\n\t\t\t\t\tif (value.length === 2 && value[0] === \"*\") {\n\t\t\t\t\t\tconst config = value[1]\n\t\t\t\t\t\tif (!isJsonColumns(config)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\t\tmsg: \"jsonColumns must be a non-empty array of strings\",\n\t\t\t\t\t\t\t\t\tpath: \"returning[1]\",\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Regular column array validation\n\t\t\t\t\t\tif (!value.every(item => typeof item === \"string\")) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\t\tmsg: \"returning array must contain only strings\",\n\t\t\t\t\t\t\t\t\tpath: \"returning\",\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Check for duplicates\n\t\t\t\t\t\tconst seen = new Set<string>()\n\t\t\t\t\t\tconst duplicates = value.filter(item => {\n\t\t\t\t\t\t\tif (seen.has(item)) {\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tseen.add(item)\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t})\n\t\t\t\t\t\tif (duplicates.length > 0) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\t\tmsg: `Duplicate columns in RETURNING clause: ${duplicates.join(\", \")}`,\n\t\t\t\t\t\t\t\t\tpath: \"returning\",\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\terrors.push(\n\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\tmsg: `Unknown property: ${key}`,\n\t\t\t\t\t\tpath: key,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t}\n\t}\n\n\treturn errors\n}\n\nfunction isValidColumnSpec(value: string): boolean {\n\treturn (\n\t\t!value.includes(\" \") && // No spaces allowed\n\t\t(value.endsWith(\"->json\") ||\n\t\t\tvalue.endsWith(\"<-json\") ||\n\t\t\t!value.includes(\"->\")) // Basic column or JSON operation\n\t)\n}\n\nfunction validateInsertOrSetOptions<P extends DataRow>(\n\tvalue: unknown\n): ValidationError[] {\n\tif (value === \"*\") {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\treturn [validationErr({ msg: \"Must be '*' or an array\" })]\n\t}\n\n\t// Check if it's a tuple with configuration\n\tif (value.length === 2 && value[0] === \"*\") {\n\t\tconst [, config] = value\n\t\tif (typeof config !== \"object\" || config === null) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Second element must be a configuration object\",\n\t\t\t\t\tpath: \"[1]\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\t// Check for at least one valid config option\n\t\tif (!(\"jsonColumns\" in config) && !(\"batch\" in config)) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Configuration must include either jsonColumns or batch\",\n\t\t\t\t\tpath: \"[1]\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\tif (\n\t\t\t\"jsonColumns\" in config &&\n\t\t\t(!Array.isArray(config.jsonColumns) ||\n\t\t\t\t!config.jsonColumns.every((col: unknown) => typeof col === \"string\"))\n\t\t) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"jsonColumns must be an array of strings\",\n\t\t\t\t\tpath: \"[1].jsonColumns\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\tif (\"batch\" in config && typeof config.batch !== \"boolean\") {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"batch must be a boolean value\",\n\t\t\t\t\tpath: \"[1].batch\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\treturn []\n\t}\n\n\t// Validate parameter operators array\n\tconst errors: ValidationError[] = []\n\tvalue.forEach((item, index) => {\n\t\tif (typeof item !== \"string\") {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Parameter operator must be a string\",\n\t\t\t\t\tpath: `[${index}]`,\n\t\t\t\t})\n\t\t\t)\n\t\t} else if (!isValidValueType(item)) {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Invalid parameter operator format\",\n\t\t\t\t\tpath: `[${index}]`,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t})\n\n\treturn errors\n}\n\nfunction validateOrderByClause(value: unknown): ValidationError[] {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn [\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"orderBy must be an object\",\n\t\t\t}),\n\t\t]\n\t}\n\n\tconst errors: ValidationError[] = []\n\tfor (const [key, direction] of Object.entries(value)) {\n\t\tif (direction !== \"ASC\" && direction !== \"DESC\") {\n\t\t\terrors.push(\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Order direction must be 'ASC' or 'DESC'\",\n\t\t\t\t\tpath: key,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\n\treturn errors\n}\n\nfunction isValidValueType(value: string): boolean {\n\treturn (\n\t\tvalue.startsWith(\"$\") &&\n\t\t(value.includes(\".toJson\") ? value.endsWith(\".toJson\") : true)\n\t)\n}\n\nexport function isSqlContext<P extends DataRow, R = P>(\n\tvalue: unknown\n): value is SqlContext<P, R> {\n\treturn validateSqlContext<P>(value).length === 0\n}\n\ntype ContextValidationError = {\n\ttype: \"DUPLICATE_CLAUSE\" | \"INCOMPATIBLE_CLAUSE\" | \"INVALID_COMBINATION\"\n\tmessage: string\n\tclauses?: string[]\n}\n\nexport function validateContextCombination<P extends DataRow, R = P>(\n\tcontexts: SqlContext<P, R>[]\n): ContextValidationError[] {\n\tconst errors: ContextValidationError[] = []\n\n\t// Track which clauses we've seen\n\tconst seenClauses = new Set<keyof SqlContext<P>>()\n\n\t// These clauses can only appear once\n\tconst uniqueClauses = new Set([\n\t\t\"values\",\n\t\t\"set\",\n\t\t\"returning\",\n\t\t\"limit\",\n\t\t\"offset\",\n\t])\n\n\t// Track clause combinations that don't make sense together\n\tconst incompatiblePairs = new Map([\n\t\t[\"values\", new Set([\"set\"])],\n\t\t[\"set\", new Set([\"values\"])],\n\t])\n\n\t// Check for duplicate clauses and track what we've seen\n\tfor (const context of contexts) {\n\t\tfor (const [clause, value] of Object.entries(context)) {\n\t\t\tif (value === undefined) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst clauseKey = clause as keyof SqlContext<P, R>\n\n\t\t\t// Check if this is a unique clause that we've seen before\n\t\t\tif (uniqueClauses.has(clauseKey) && seenClauses.has(clauseKey)) {\n\t\t\t\terrors.push({\n\t\t\t\t\ttype: \"DUPLICATE_CLAUSE\",\n\t\t\t\t\tmessage: `Clause \"${clause}\" cannot appear multiple times in a SQL statement`,\n\t\t\t\t\tclauses: [clause],\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Check for incompatible clause combinations\n\t\t\tconst incompatibleWith = incompatiblePairs.get(clause)\n\t\t\tif (incompatibleWith) {\n\t\t\t\tfor (const otherClause of incompatibleWith) {\n\t\t\t\t\tif (seenClauses.has(otherClause as keyof SqlContext<P, R>)) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\ttype: \"INCOMPATIBLE_CLAUSE\",\n\t\t\t\t\t\t\tmessage: `Clauses \"${clause}\" and \"${otherClause}\" cannot be used together`,\n\t\t\t\t\t\t\tclauses: [clause, otherClause],\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tseenClauses.add(clauseKey)\n\t\t}\n\t}\n\n\treturn errors\n}\n\nexport function combineContexts<P extends DataRow, R = P>(\n\tcontexts: SqlContext<P, R>[]\n): SqlContext<P, R> {\n\t// First validate the combination\n\tconst errors = validateContextCombination(contexts)\n\tif (errors.length > 0) {\n\t\tthrow new NodeSqliteError(\n\t\t\t\"ERR_SQLITE_CONTEXT\",\n\t\t\tSqlitePrimaryResultCode.SQLITE_MISUSE,\n\t\t\t\"Invalid SQL context combination\",\n\t\t\terrors.map(e => e.message).join(\"\\n\"),\n\t\t\tundefined\n\t\t)\n\t}\n\n\t// Helper function to combine where clauses safely\n\tconst combineWhereClauses = (\n\t\tclause1: WhereClause<P> | undefined,\n\t\tclause2: WhereClause<P> | undefined\n\t): WhereClause<P> | undefined => {\n\t\tif (!clause1) {\n\t\t\treturn clause2\n\t\t}\n\t\tif (!clause2) {\n\t\t\treturn clause1\n\t\t}\n\n\t\tconst clause1Array = Array.isArray(clause1) ? clause1 : [clause1]\n\t\tconst clause2Array = Array.isArray(clause2) ? clause2 : [clause2]\n\n\t\t// Ensure we're not exceeding the maximum allowed conditions\n\t\treturn [...clause1Array, \"AND\", ...clause2Array] as WhereClause<P>\n\t}\n\n\t// Helper function to combine orderBy clauses safely\n\tconst combineOrderByClauses = (\n\t\torderBy1: Partial<Record<keyof P, \"ASC\" | \"DESC\">> | undefined,\n\t\torderBy2: Partial<Record<keyof P, \"ASC\" | \"DESC\">> | undefined\n\t): Partial<Record<keyof P, \"ASC\" | \"DESC\">> | undefined => {\n\t\tif (!orderBy1) {\n\t\t\treturn orderBy2\n\t\t}\n\t\tif (!orderBy2) {\n\t\t\treturn orderBy1\n\t\t}\n\n\t\treturn {\n\t\t\t...orderBy1,\n\t\t\t...orderBy2,\n\t\t} as Partial<Record<keyof P, \"ASC\" | \"DESC\">>\n\t}\n\n\treturn contexts.reduce<SqlContext<P, R>>(\n\t\t(combined, current) => {\n\t\t\t// Create new object with explicit property assignments\n\t\t\tconst result: SqlContext<P, R> = {}\n\n\t\t\t// Assign values from combined if they exist\n\t\t\t// sourcery skip: use-braces\n\t\t\tif (combined.values !== undefined) result.values = combined.values\n\t\t\tif (combined.set !== undefined) result.set = combined.set\n\t\t\tif (combined.limit !== undefined) result.limit = combined.limit\n\t\t\tif (combined.offset !== undefined) result.offset = combined.offset\n\t\t\tif (combined.returning !== undefined)\n\t\t\t\tresult.returning = combined.returning\n\n\t\t\t// Assign values from current if they exist\n\t\t\tif (current.values !== undefined) result.values = current.values\n\t\t\tif (current.set !== undefined) result.set = current.set\n\t\t\tif (current.limit !== undefined) result.limit = current.limit\n\t\t\tif (current.offset !== undefined) result.offset = current.offset\n\t\t\tif (current.returning !== undefined) result.returning = current.returning\n\n\t\t\t// Handle special cases with combine functions\n\t\t\tresult.where = combineWhereClauses(combined.where, current.where)\n\t\t\tresult.orderBy = combineOrderByClauses(combined.orderBy, current.orderBy)\n\n\t\t\treturn result\n\t\t},\n\t\t{} as SqlContext<P, R>\n\t)\n}\n\nexport function buildColsStatement<P extends DataRow>(\n\tcols: ColumnOptions<P>\n): string {\n\tif (cols === \"*\") {\n\t\treturn \"*\"\n\t}\n\n\t// Handle array of column specifications\n\tif (Array.isArray(cols)) {\n\t\t// Remove duplicates while preserving order\n\t\tconst seen = new Set<string>()\n\t\treturn cols\n\t\t\t.filter(col => {\n\t\t\t\tconst colStr = String(col)\n\t\t\t\tif (seen.has(colStr)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tseen.add(colStr)\n\t\t\t\treturn true\n\t\t\t})\n\t\t\t.map(col => {\n\t\t\t\tif (typeof col === \"string\") {\n\t\t\t\t\tif (col.endsWith(\"->json\")) {\n\t\t\t\t\t\tconst columnName = col.slice(0, -6)\n\t\t\t\t\t\treturn `jsonb(${columnName})`\n\t\t\t\t\t}\n\t\t\t\t\tif (col.endsWith(\"<-json\")) {\n\t\t\t\t\t\tconst columnName = col.slice(0, -6)\n\t\t\t\t\t\treturn `json_extract(${columnName}, '$') as ${columnName}`\n\t\t\t\t\t}\n\t\t\t\t\treturn col\n\t\t\t\t}\n\t\t\t\treturn String(col)\n\t\t\t})\n\t\t\t.join(\", \")\n\t}\n\n\tthrow new NodeSqliteError(\n\t\t\"ERR_SQLITE_PARAM\",\n\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\"Invalid columns format\",\n\t\t\"Columns must be '*' or an array of columns\",\n\t\tundefined\n\t)\n}\n\nexport function validateSetOptions<P extends DataRow>(\n\tvalue: unknown\n): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\t// Handle \"*\" case\n\tif (value === \"*\") {\n\t\treturn []\n\t}\n\n\t// Handle [\"*\", { jsonColumns: [...] }] case\n\tif (Array.isArray(value)) {\n\t\tif (value.length !== 2 || value[0] !== \"*\") {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Array format must be ['*', { jsonColumns: [...] }]\",\n\t\t\t\t\tpath: \"\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\tconst [, config] = value\n\t\tif (!config || typeof config !== \"object\" || !(\"jsonColumns\" in config)) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"Second element must be an object with jsonColumns\",\n\t\t\t\t\tpath: \"[1]\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\tconst { jsonColumns } = config\n\t\tif (!Array.isArray(jsonColumns) || jsonColumns.length === 0) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"jsonColumns must be a non-empty array\",\n\t\t\t\t\tpath: \"[1].jsonColumns\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\tif (!jsonColumns.every(col => typeof col === \"string\")) {\n\t\t\treturn [\n\t\t\t\tvalidationErr({\n\t\t\t\t\tmsg: \"jsonColumns must contain only strings\",\n\t\t\t\t\tpath: \"[1].jsonColumns\",\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\n\t\treturn []\n\t}\n\n\t// Handle object format\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst entries = Object.entries(value)\n\n\t\tfor (const [key, val] of entries) {\n\t\t\tif (isRawValue(val)) {\n\t\t\t\t// RawValue is always valid\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (typeof val !== \"string\") {\n\t\t\t\terrors.push(\n\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\tmsg: `Value for '${key}' must be a string parameter or RawValue`,\n\t\t\t\t\t\tpath: key,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Validate parameter format\n\t\t\tif (val.startsWith(\"$\")) {\n\t\t\t\t// Check for ->json format\n\t\t\t\tif (val.endsWith(\"->json\")) {\n\t\t\t\t\tconst paramPart = val.slice(1, -6)\n\t\t\t\t\tif (!paramPart) {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\tmsg: \"Invalid JSON parameter format\",\n\t\t\t\t\t\t\t\tpath: key,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Regular parameter\n\t\t\t\t\tconst paramPart = val.slice(1)\n\t\t\t\t\tif (!paramPart) {\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\t\t\tmsg: \"Invalid parameter format\",\n\t\t\t\t\t\t\t\tpath: key,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrors.push(\n\t\t\t\t\tvalidationErr({\n\t\t\t\t\t\tmsg: \"Value must start with $ or be a RawValue\",\n\t\t\t\t\t\tpath: key,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\treturn errors\n\t}\n\n\treturn [\n\t\tvalidationErr({\n\t\t\tmsg: \"SET must be an object, '*', or ['*', { jsonColumns: [...] }]\",\n\t\t\tpath: \"\",\n\t\t}),\n\t]\n}\n\nexport const isJsonColumns = (\n\tvalue: unknown\n): value is { jsonColumns: string[] } =>\n\ttypeof value === \"object\" &&\n\tvalue !== null &&\n\tArray.isArray((value as { jsonColumns: unknown }).jsonColumns) &&\n\t(value as { jsonColumns: unknown[] }).jsonColumns.length > 0 &&\n\t(value as { jsonColumns: unknown[] }).jsonColumns.every(\n\t\tcol => typeof col === \"string\"\n\t)\n","// noinspection t\n\nimport { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors\"\nimport type { DataRow, InsertOptions } from \"#types\"\n\ntype BuildSqlResult = {\n\tcolumns: string[]\n\tplaceholders: string[]\n\tparameterOperators: string[]\n\tisMulti?: boolean\n\titemCount?: number\n}\n\nfunction buildSqlComponents<P extends DataRow>(\n\toptions: InsertOptions<P>,\n\tparams: P | P[]\n): BuildSqlResult {\n\t// Handle batch operations\n\tif (Array.isArray(params) || params instanceof Set) {\n\t\tconst items = Array.from(params)\n\t\tif (items.length === 0) {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Empty data set\",\n\t\t\t\t\"Cannot insert empty array or set\",\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\n\t\tconst firstItem = items[0]\n\t\tconst columns = Object.keys(firstItem)\n\n\t\t// Handle * with batch config\n\t\tif (Array.isArray(options) && options[0] === \"*\" && options.length === 2) {\n\t\t\tconst [, config] = options\n\t\t\tconst jsonColumns = new Set(\n\t\t\t\ttypeof config === \"object\" && \"jsonColumns\" in config\n\t\t\t\t\t? config.jsonColumns\n\t\t\t\t\t: []\n\t\t\t)\n\n\t\t\t// Generate unique parameter names and placeholders for each row\n\t\t\tconst placeholderRows = items.map((_, rowIndex) => {\n\t\t\t\tconst rowPlaceholders = columns.map(col =>\n\t\t\t\t\tjsonColumns.has(col)\n\t\t\t\t\t\t? `jsonb($${col}_${rowIndex})`\n\t\t\t\t\t\t: `$${col}_${rowIndex}`\n\t\t\t\t)\n\t\t\t\treturn `(${rowPlaceholders.join(\", \")})`\n\t\t\t})\n\n\t\t\tconst paramOps = items.flatMap((_, rowIndex) =>\n\t\t\t\tcolumns.map(col => `$${col}_${rowIndex}`)\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\tcolumns,\n\t\t\t\tplaceholders: placeholderRows,\n\t\t\t\tparameterOperators: paramOps,\n\t\t\t\tisMulti: true,\n\t\t\t\titemCount: items.length,\n\t\t\t}\n\t\t}\n\n\t\t// Handle simple * for batch\n\t\tif (options === \"*\") {\n\t\t\tconst placeholderRows = items.map((_, rowIndex) => {\n\t\t\t\tconst rowPlaceholders = columns.map(col => `$${col}_${rowIndex}`)\n\t\t\t\treturn `(${rowPlaceholders.join(\", \")})`\n\t\t\t})\n\n\t\t\tconst paramOps = items.flatMap((_, rowIndex) =>\n\t\t\t\tcolumns.map(col => `$${col}_${rowIndex}`)\n\t\t\t)\n\n\t\t\treturn {\n\t\t\t\tcolumns,\n\t\t\t\tplaceholders: placeholderRows,\n\t\t\t\tparameterOperators: paramOps,\n\t\t\t\tisMulti: true,\n\t\t\t\titemCount: items.length,\n\t\t\t}\n\t\t}\n\t}\n\n\t// Handle single record operations (rest of the code remains the same)\n\tif (options === \"*\") {\n\t\tconst columns = Object.keys(params as P)\n\t\tconst paramOps = columns.map(k => `$${k}`)\n\t\treturn {\n\t\t\tcolumns,\n\t\t\tplaceholders: paramOps,\n\t\t\tparameterOperators: paramOps,\n\t\t}\n\t}\n\n\tif (Array.isArray(options) && options[0] === \"*\" && options.length === 2) {\n\t\tconst [, config] = options\n\n\t\tif (!config || typeof config !== \"object\") {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Invalid configuration\",\n\t\t\t\t\"Second element must be a configuration object\",\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\n\t\tif (\n\t\t\t\"batch\" in config &&\n\t\t\tconfig.batch &&\n\t\t\t!Array.isArray(params) &&\n\t\t\t!(params instanceof Set)\n\t\t) {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Invalid parameters\",\n\t\t\t\t\"Expected array or Set when using batch\",\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\n\t\tif (\"jsonColumns\" in config) {\n\t\t\tconst jsonColumns = new Set(config.jsonColumns)\n\t\t\tconst columns = Object.keys(params as P)\n\t\t\tconst paramOps = columns.map(k => `$${k}`)\n\n\t\t\treturn {\n\t\t\t\tcolumns,\n\t\t\t\tplaceholders: columns.map(col =>\n\t\t\t\t\tjsonColumns.has(col) ? `jsonb($${col})` : `$${col}`\n\t\t\t\t),\n\t\t\t\tparameterOperators: paramOps,\n\t\t\t}\n\t\t}\n\n\t\tthrow new NodeSqliteError(\n\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\"Invalid configuration\",\n\t\t\t\"Configuration must include jsonColumns for single record\",\n\t\t\tundefined\n\t\t)\n\t}\n\n\t// Handle explicit column array (remains the same)\n\tif (Array.isArray(options)) {\n\t\tconst columns: string[] = []\n\t\tconst placeholders: string[] = []\n\t\tconst paramOps: string[] = []\n\n\t\tfor (const op of options) {\n\t\t\tif (typeof op !== \"string\") {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Invalid parameter format\",\n\t\t\t\t\t`Parameter must be a string but got ${typeof op}`,\n\t\t\t\t\tundefined\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst match = op.match(/^\\$([^->]+)(->json)?$/)\n\t\t\tif (!match) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Invalid parameter format\",\n\t\t\t\t\t`Parameter \"${op}\" must be in format $column or $column->json`,\n\t\t\t\t\tundefined\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst column = match[1]\n\t\t\tcolumns.push(column)\n\t\t\tparamOps.push(op)\n\n\t\t\tif (op.endsWith(\"->json\")) {\n\t\t\t\tplaceholders.push(`jsonb($${column})`)\n\t\t\t} else {\n\t\t\t\tplaceholders.push(`$${column}`)\n\t\t\t}\n\t\t}\n\n\t\treturn { columns, placeholders, parameterOperators: paramOps }\n\t}\n\n\tthrow new NodeSqliteError(\n\t\t\"ERR_SQLITE_PARAM\",\n\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\"Invalid format\",\n\t\t\"Must be '*', an array of parameters, or a configuration tuple\",\n\t\tundefined\n\t)\n}\n\nexport function buildValuesStatement<P extends DataRow>(\n\tvalues: InsertOptions<P>,\n\tparams: P | P[]\n): { sql: string; parameterOperators: string[] } {\n\tconst result = buildSqlComponents(values, params)\n\n\tif (\n\t\tresult.isMulti &&\n\t\tresult.itemCount &&\n\t\tArray.isArray(result.placeholders)\n\t) {\n\t\treturn {\n\t\t\tsql: `(${result.columns.join(\", \")}) VALUES\\n  ${result.placeholders.join(\",\\n  \")}`,\n\t\t\tparameterOperators: result.parameterOperators,\n\t\t}\n\t}\n\n\treturn {\n\t\tsql: `(${result.columns.join(\", \")}) VALUES (${result.placeholders})`,\n\t\tparameterOperators: result.parameterOperators,\n\t}\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// noinspection t\n\n// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// noinspection t\n\nimport {\n\tbuildColsStatement,\n\tisJsonColumns,\n\tisSqlContext,\n\tvalidateContextCombination,\n\tvalidateSqlContext,\n} from \"#context\"\nimport { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors\"\nimport { buildValuesStatement } from \"#values\"\nimport type {\n\tStatementResultingChanges,\n\tStatementSync,\n\tSupportedValueType,\n} from \"node:sqlite\"\nimport {\n\tisRawValue,\n\ttype SqlOptions,\n\ttype DataRow,\n\ttype RawValue,\n\ttype SqlContext,\n\ttype SqlTemplateValue,\n} from \"#types\"\nimport { buildWhereStatement } from \"#where.js\"\nimport sqlFormatter from \"@sqltools/formatter\"\nimport { buildOrderByStatement } from \"#order-by\"\nimport { buildSchema } from \"#schema\"\nimport type { Config } from \"@sqltools/formatter/lib/core/types\"\nimport stringify from \"#stringify\"\nimport { buildSetStatement } from \"#set.js\"\n\nfunction toSupportedValue(value: unknown): SupportedValueType {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"number\" ||\n\t\ttypeof value === \"bigint\" ||\n\t\tvalue instanceof Uint8Array\n\t) {\n\t\treturn value as SupportedValueType\n\t}\n\tif (typeof value === \"object\") {\n\t\treturn stringify(value) // Use stringify for objects\n\t}\n\treturn String(value)\n}\n\nexport const raw = (\n\tstrings: TemplateStringsArray,\n\t...values: (string | number | boolean | bigint | null)[]\n) => {\n\t// Add validation\n\tfor (const value of values) {\n\t\tif (typeof value === \"object\" && value !== null) {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Invalid parameter\",\n\t\t\t\t\"Raw SQL values must be primitives (string | number | boolean | bigint | null)\",\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\ttype: \"__x_literal__\" as const,\n\t\tvalue: String.raw(strings, ...values),\n\t} as RawValue\n}\n\nexport class Sql<P extends DataRow, RET = P> {\n\treadonly strings: readonly string[]\n\treadonly paramOperators = new Set<SqlTemplateValue<P, RET>>()\n\treadonly formatterConfig?: Readonly<Config> | false\n\n\t#contextOperators = new Set<string>()\n\n\t#params: P = {} as P\n\n\tget params(): P {\n\t\treturn this.#params\n\t}\n\n\tget contextOperators(): Set<string> {\n\t\treturn this.#contextOperators\n\t}\n\n\tconstructor({\n\t\tstrings,\n\t\tparamOperators,\n\t\tformatterConfig,\n\t}: SqlOptions<P, RET>) {\n\t\tthis.strings = strings\n\n\t\tfor (const op of paramOperators) {\n\t\t\tthis.paramOperators.add(op)\n\t\t}\n\n\t\tif (formatterConfig === false) {\n\t\t\tthis.formatterConfig = false\n\t\t} else {\n\t\t\tthis.formatterConfig = {\n\t\t\t\tindent: \"  \",\n\t\t\t\treservedWordCase: \"upper\",\n\t\t\t\tlinesBetweenQueries: 1,\n\t\t\t\t...formatterConfig,\n\t\t\t\tlanguage: \"sql\",\n\t\t\t}\n\t\t}\n\t}\n\n\t#fmt(sql: string): string {\n\t\tif (this.formatterConfig) {\n\t\t\treturn sqlFormatter.format(sql, this.formatterConfig)\n\t\t}\n\t\treturn sql\n\t}\n\n\t#contextToSql(context: SqlContext<P, RET>): string {\n\t\tconst parts: string[] = []\n\n\t\tif (context.columns) {\n\t\t\tparts.push(buildColsStatement(context.columns))\n\t\t}\n\n\t\tif (context.schema) {\n\t\t\tparts.push(buildSchema(context.schema))\n\t\t\tparts[parts.length - 1] += \";\" // Add semicolon after table creation\n\t\t}\n\n\t\tif (context.values) {\n\t\t\tconst result = buildValuesStatement(context.values, this.#params)\n\t\t\tfor (const op of result.parameterOperators) {\n\t\t\t\tthis.#contextOperators.add(op)\n\t\t\t}\n\t\t\tparts.push(result.sql)\n\t\t}\n\n\t\tif (context.set) {\n\t\t\tconst result = buildSetStatement(context.set, this.#params)\n\t\t\tfor (const op of result.parameterOperators) {\n\t\t\t\tthis.#contextOperators.add(op)\n\t\t\t}\n\t\t\tconst setParts = result.sql.split(\"\\n\")\n\t\t\tif (setParts.length > 1) {\n\t\t\t\tparts.push(setParts[0])\n\t\t\t\tparts.push(...setParts.slice(1).map(p => `  ${p}`))\n\t\t\t} else {\n\t\t\t\tparts.push(result.sql)\n\t\t\t}\n\t\t}\n\t\tif (context.where) {\n\t\t\tconst result = buildWhereStatement(context.where, this.#params)\n\t\t\tparts.push(result.sql)\n\t\t\tfor (const op of result.parameterOperators) {\n\t\t\t\tthis.#contextOperators.add(op)\n\t\t\t}\n\t\t}\n\n\t\tif (context.orderBy) {\n\t\t\tparts.push(buildOrderByStatement(context.orderBy))\n\t\t}\n\n\t\tif (context.limit !== undefined) {\n\t\t\tparts.push(`LIMIT ${context.limit}`)\n\t\t\tif (context.offset !== undefined) {\n\t\t\t\tparts.push(`OFFSET ${context.offset}`)\n\t\t\t}\n\t\t} else if (context.offset !== undefined) {\n\t\t\tparts.push(\"LIMIT -1\")\n\t\t\tparts.push(`OFFSET ${context.offset}`)\n\t\t}\n\n\t\tif (context.returning) {\n\t\t\tif (context.returning === \"*\") {\n\t\t\t\tparts.push(\"RETURNING *\")\n\t\t\t} else if (Array.isArray(context.returning)) {\n\t\t\t\tif (\n\t\t\t\t\tcontext.returning.length === 2 &&\n\t\t\t\t\tcontext.returning[0] === \"*\" &&\n\t\t\t\t\tisJsonColumns(context.returning[1])\n\t\t\t\t) {\n\t\t\t\t\t// Handle JSON columns case\n\t\t\t\t\tconst config = context.returning[1]\n\t\t\t\t\tconst jsonColumns = new Set(config.jsonColumns || [])\n\t\t\t\t\tconst allColumns = new Set(Object.keys(this.#params))\n\n\t\t\t\t\tconst returningColumns = Array.from(allColumns).map(col =>\n\t\t\t\t\t\tjsonColumns.has(col) ? `json_extract(${col}, '$') as ${col}` : col\n\t\t\t\t\t)\n\t\t\t\t\tparts.push(`RETURNING ${returningColumns.join(\", \")}`)\n\t\t\t\t} else {\n\t\t\t\t\t// Handle regular column array case\n\t\t\t\t\tparts.push(`RETURNING ${context.returning.join(\", \")}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn parts.join(\"\\n\")\n\t}\n\n\tget sql(): string {\n\t\tlet result = this.strings[0]\n\n\t\tlet i = 0\n\t\tfor (const op of this.paramOperators) {\n\t\t\tif (isXStatementSync(op)) {\n\t\t\t\t// Handle interpolated SQL statement\n\t\t\t\tresult += op.sql.sql\n\t\t\t} else if (isSqlContext<P, RET>(op)) {\n\t\t\t\tresult += this.#contextToSql(op)\n\t\t\t} else if (isRawValue(op)) {\n\t\t\t\tresult += op.value\n\t\t\t} else if (typeof op === \"string\") {\n\t\t\t\tif (op.endsWith(\"->json\")) {\n\t\t\t\t\tconst paramName = op.split(\"->\")[0].substring(1)\n\t\t\t\t\tresult += `jsonb($${paramName})`\n\t\t\t\t} else if (op.endsWith(\"<-json\")) {\n\t\t\t\t\tconst paramName = op.split(\"<-\")[0].substring(1)\n\t\t\t\t\tresult += `json_extract(${paramName}, '$')`\n\t\t\t\t} else {\n\t\t\t\t\tresult += op\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult += this.strings[i + 1]\n\t\t\ti++\n\t\t}\n\n\t\treturn result\n\t}\n\n\tget hasJsonColumns(): boolean {\n\t\tconst { sql } = this\n\t\treturn (\n\t\t\tsql.includes(\"json_extract\") ||\n\t\t\tsql.includes(\"json(\") ||\n\t\t\tsql.includes(\"jsonb(\") ||\n\t\t\tsql.includes(\"json_array\") ||\n\t\t\tsql.includes(\"json_object\") ||\n\t\t\tsql.includes(\"json_type\") ||\n\t\t\tsql.includes(\"json_valid\") ||\n\t\t\tsql.includes(\"json_patch\") ||\n\t\t\tsql.includes(\"json_group_array\") ||\n\t\t\tsql.includes(\"json_group_object\") ||\n\t\t\tsql.includes(\"json_tree\") ||\n\t\t\tsql.includes(\"json_each\") ||\n\t\t\tsql.includes(\"->\") ||\n\t\t\tsql.includes(\"->>\")\n\t\t)\n\t}\n\n\t#gatherParameterOperators() {\n\t\tconst operators = new Set<SqlTemplateValue<P, RET>>()\n\t\tfor (const op of this.paramOperators) {\n\t\t\tif (isXStatementSync(op)) {\n\t\t\t\t// need to call this to populate the context operators\n\t\t\t\top.sql.sql\n\t\t\t\tfor (const contextOp of op.sql.paramOperators) {\n\t\t\t\t\toperators.add(contextOp as SqlTemplateValue<P, RET>)\n\t\t\t\t}\n\n\t\t\t\tfor (const contextOp of op.sql.contextOperators) {\n\t\t\t\t\toperators.add(contextOp as SqlTemplateValue<P, RET>)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn operators\n\t}\n\n\t#toNamedParams(): Record<string, SupportedValueType> {\n\t\tconst namedParams: Record<string, SupportedValueType> = {}\n\t\tconst operators = new Set([\n\t\t\t...this.paramOperators,\n\t\t\t...this.#contextOperators,\n\t\t])\n\n\t\tfor (const op of this.#gatherParameterOperators()) {\n\t\t\toperators.add(op)\n\t\t}\n\n\t\t// Handle batch params\n\t\tif (Array.isArray(this.#params) || this.#params instanceof Set) {\n\t\t\tconst items = Array.isArray(this.#params)\n\t\t\t\t? this.#params\n\t\t\t\t: Array.from(this.#params)\n\t\t\tfor (let index = 0; index < items.length; index++) {\n\t\t\t\tconst row = items[index]\n\t\t\t\tfor (const [key, value] of Object.entries(row)) {\n\t\t\t\t\tconst operator = operators.has(`$${key}->json`)\n\t\t\t\t\t\t? `$${key}_${index}->json`\n\t\t\t\t\t\t: `$${key}_${index}`\n\n\t\t\t\t\tif (operator.endsWith(\"->json\")) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof value !== \"object\" &&\n\t\t\t\t\t\t\t!Array.isArray(value) &&\n\t\t\t\t\t\t\tvalue !== null\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\t\t\t\"Invalid parameter\",\n\t\t\t\t\t\t\t\t`Parameter '${key}' must be an object or array for JSON conversion`,\n\t\t\t\t\t\t\t\tundefined\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnamedParams[`$${key}_${index}`] = stringify(value)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnamedParams[`$${key}_${index}`] = toSupportedValue(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn namedParams\n\t\t}\n\n\t\t// Handle single record params\n\t\tfor (const op of operators) {\n\t\t\tif (typeof op !== \"string\" || op.endsWith(\"<-json\")) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst paramName = op.split(\"->\")[0].substring(1)\n\t\t\tconst value = (this.#params as P)[paramName]\n\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Missing parameter\",\n\t\t\t\t\t`Parameter '${paramName}' is undefined`,\n\t\t\t\t\tundefined\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (op.endsWith(\"->json\")) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof value !== \"object\" &&\n\t\t\t\t\t!Array.isArray(value) &&\n\t\t\t\t\tvalue !== null\n\t\t\t\t) {\n\t\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\t\"Invalid parameter\",\n\t\t\t\t\t\t`Parameter '${paramName}' must be an object or array for JSON conversion`,\n\t\t\t\t\t\tundefined\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tnamedParams[`$${paramName}`] = stringify(value)\n\t\t\t} else {\n\t\t\t\tnamedParams[`$${paramName}`] = toSupportedValue(value)\n\t\t\t}\n\t\t}\n\t\treturn namedParams\n\t}\n\n\tprepare(params: P): {\n\t\tsql: string\n\t\tnamedParams: Record<string, SupportedValueType>\n\t\thasJsonColumns: boolean\n\t} {\n\t\tthis.#params = params\n\n\t\t// Convert Set to array just for context filtering\n\t\tconst contexts = Array.from([\n\t\t\t...this.paramOperators,\n\t\t\t...this.#gatherParameterOperators(),\n\t\t]).filter(\n\t\t\top =>\n\t\t\t\ttypeof op === \"object\" &&\n\t\t\t\t!Array.isArray(op) &&\n\t\t\t\t!isRawValue(op) &&\n\t\t\t\t!isXStatementSync(op)\n\t\t)\n\n\t\tconst validationErrors = contexts.flatMap(context =>\n\t\t\tvalidateSqlContext<P, RET>(context)\n\t\t)\n\n\t\tif (validationErrors.length > 0) {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_CONTEXT\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_MISUSE,\n\t\t\t\t\"Invalid SQL context\",\n\t\t\t\tvalidationErrors.map(e => e.message).join(\"\\n\"),\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\n\t\tconst combinationErrors = validateContextCombination<P, RET>(\n\t\t\tcontexts as SqlContext<P, RET>[]\n\t\t)\n\n\t\tif (combinationErrors.length > 0) {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_CONTEXT\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_MISUSE,\n\t\t\t\t\"Invalid SQL context combination\",\n\t\t\t\tcombinationErrors.map(e => e.message).join(\"\\n\"),\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tsql: this.#fmt(this.sql),\n\t\t\tnamedParams: this.#toNamedParams(),\n\t\t\thasJsonColumns: this.hasJsonColumns,\n\t\t}\n\t}\n}\ntype SingleRow<P extends DataRow> = {\n\t[K in keyof P]: P[K]\n}\n\n// Type for values params that can be single row or multiple rows\ntype ValuesParam<P extends DataRow> =\n\t| SingleRow<P>\n\t| SingleRow<P>[]\n\t| Set<SingleRow<P>>\n\n/**\n * Interface for prepared SQL statements with type safety and chaining support.\n * @template P Type of parameters object\n * @template RET Type of returned rows\n */\nexport interface XStatementSync<P extends DataRow, RET = unknown> {\n\t/** Execute query and return all result rows */\n\tall<R = RET>(params?: ValuesParam<P>): R[]\n\n\t/** Execute query and return an iterator over result rows */\n\titer<R = RET>(params?: ValuesParam<P>): Iterator<R> & Iterable<R>\n\n\t/** Execute query and return a generator that yields result rows */\n\trows<R = RET>(params?: ValuesParam<P>): Generator<R>\n\n\t/** Execute query and return first result row or undefined */\n\tget<R = RET>(params?: ValuesParam<P>): R | undefined\n\n\t/** Execute query and return statement result info */\n\trun(params?: ValuesParam<P>): StatementResultingChanges\n\n\t/** Get SQL with parameters expanded */\n\texpandedSQL: string | undefined\n\n\t/** Get original SQL source */\n\tsourceSQL: (params?: ValuesParam<P>) => string\n\n\treadonly sql: Sql<P, RET>\n\n\t__x_statement_sync__: true\n}\n\nfunction looksLikeJSON(value: unknown): value is string {\n\tif (typeof value !== \"string\") {\n\t\treturn false\n\t}\n\tconst data = value.trim()\n\treturn (\n\t\t// Only objects and arrays\n\t\t(data.startsWith(\"{\") && data.endsWith(\"}\")) ||\n\t\t(data.startsWith(\"[\") && data.endsWith(\"]\"))\n\t)\n}\n\n/**\n * Helper function to parse JSON columns in result rows\n */\nexport function parseJsonColumns(row: DataRow): DataRow {\n\tconst result = { ...row }\n\n\t// Handle every field in the row that's a string and try to parse it\n\tfor (const [key, value] of Object.entries(result)) {\n\t\tif (looksLikeJSON(value)) {\n\t\t\ttry {\n\t\t\t\tresult[key] = JSON.parse(value)\n\t\t\t} catch {\n\t\t\t\t// Keep original value if parsing fails\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\ntype CreateXStatementSyncProps<P extends DataRow, R = P> = {\n\tbuild: (params: P) => {\n\t\tstmt: StatementSync\n\t\tnamedParams: Record<string, SupportedValueType>\n\t\thasJsonColumns: boolean\n\t}\n\tprepare: (sql: string) => StatementSync\n\tsql: Sql<P, R>\n}\n\nconst createErrorMessage = <P extends DataRow>(\n\terror: unknown,\n\tparams?: P | P[]\n) => {\n\tlet paramStr = \"\"\n\n\tif (Array.isArray(params) && params.length > 1) {\n\t\tconst item1 = params[0]\n\t\tconst item2 = params[1]\n\n\t\tparamStr = `{${Object.keys(item1).join(\", \")}, ...} + ${Object.keys(\n\t\t\titem2\n\t\t).join(\", \")}`\n\t} else if (typeof params === \"object\") {\n\t\tparamStr = stringify(params)\n\t} else {\n\t\tparamStr = String(params)\n\t}\n\treturn error instanceof Error\n\t\t? `${error.message}: params: ${paramStr}`\n\t\t: `${String(error)}: params: ${paramStr}`\n}\n\nexport const isXStatementSync = <P extends DataRow, R>(\n\tvalue: unknown\n): value is XStatementSync<P, R> => {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\tObject.hasOwn(value, \"get\") &&\n\t\tObject.hasOwn(value, \"all\") &&\n\t\tObject.hasOwn(value, \"run\") &&\n\t\tObject.hasOwn(value, \"iter\") &&\n\t\tObject.hasOwn(value, \"rows\") &&\n\t\tObject.hasOwn(value, \"sourceSQL\") &&\n\t\tObject.hasOwn(value, \"expandedSQL\") &&\n\t\tObject.hasOwn(value, \"__x_statement_sync__\") &&\n\t\t// biome-ignore lint/suspicious/noExplicitAny: <explanation>\n\t\t(value as any).__x_statement_sync__ === true\n\t)\n}\n\n/**\n * Creates a type-safe prepared statement\n */\n// Update the factory function\nexport function createXStatementSync<P extends DataRow, RET = unknown>(\n\tprops: CreateXStatementSyncProps<P, RET>\n): XStatementSync<P, RET> {\n\tlet currentStatement: StatementSync | undefined\n\treturn {\n\t\tget sql() {\n\t\t\treturn props.sql\n\t\t},\n\n\t\tall<R = RET>(params: ValuesParam<P> = {} as P) {\n\t\t\ttry {\n\t\t\t\tconst { stmt, namedParams, hasJsonColumns } = props.build(params as P)\n\t\t\t\tcurrentStatement = stmt\n\t\t\t\tconst results = stmt.all(namedParams)\n\t\t\t\tif (!results || !results.length) {\n\t\t\t\t\t// No results case\n\t\t\t\t\treturn (Array.isArray(results) ? [] : undefined) as R\n\t\t\t\t}\n\n\t\t\t\tif (!hasJsonColumns) {\n\t\t\t\t\treturn results as R\n\t\t\t\t}\n\n\t\t\t\tif (Array.isArray(results)) {\n\t\t\t\t\t// Array results case\n\t\t\t\t\treturn results.map(row => parseJsonColumns(row as DataRow)) as R\n\t\t\t\t}\n\n\t\t\t\tif (typeof results === \"object\") {\n\t\t\t\t\t// Single object result case\n\t\t\t\t\treturn parseJsonColumns(results as DataRow) as R\n\t\t\t\t}\n\n\t\t\t\t// Primitive value case\n\t\t\t\treturn results as R\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_QUERY\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Query execution failed\",\n\t\t\t\t\tcreateErrorMessage(error, params)\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\tget<R = RET>(params: ValuesParam<P> = {} as P) {\n\t\t\ttry {\n\t\t\t\tconst { stmt, namedParams, hasJsonColumns } = props.build(params as P)\n\t\t\t\tcurrentStatement = stmt\n\t\t\t\tconst row = stmt.get(namedParams)\n\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn undefined\n\t\t\t\t}\n\n\t\t\t\tif (!hasJsonColumns) {\n\t\t\t\t\treturn row as R\n\t\t\t\t}\n\n\t\t\t\treturn parseJsonColumns(row as DataRow) as R\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_QUERY\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Query execution failed\",\n\t\t\t\t\tcreateErrorMessage(error, params)\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\trun(params: ValuesParam<P> = {} as P) {\n\t\t\ttry {\n\t\t\t\tconst { stmt, namedParams } = props.build(params as P)\n\t\t\t\tcurrentStatement = stmt\n\t\t\t\treturn stmt.run(namedParams)\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_MUTATE\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Mutation failed\",\n\t\t\t\t\tcreateErrorMessage(error, params)\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\titer<R = RET>(params: ValuesParam<P> = {} as P): Iterable<R> & Iterator<R> {\n\t\t\ttry {\n\t\t\t\tconst { stmt, namedParams, hasJsonColumns } = props.build(params as P)\n\t\t\t\tcurrentStatement = stmt\n\t\t\t\tconst baseIterator = stmt.iterate(namedParams)\n\n\t\t\t\treturn {\n\t\t\t\t\t// Iterator protocol\n\t\t\t\t\tnext(): IteratorResult<R> {\n\t\t\t\t\t\tconst result = baseIterator.next()\n\t\t\t\t\t\tif (result.done) {\n\t\t\t\t\t\t\treturn { done: true, value: undefined }\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\t\tvalue: hasJsonColumns\n\t\t\t\t\t\t\t\t? (parseJsonColumns(result.value as DataRow) as R)\n\t\t\t\t\t\t\t\t: (result.value as R),\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\n\t\t\t\t\t// Iterable protocol\n\t\t\t\t\t[Symbol.iterator]() {\n\t\t\t\t\t\treturn this\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_QUERY\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Query execution failed\",\n\t\t\t\t\tcreateErrorMessage(error, params)\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\t*rows<R = RET>(params: ValuesParam<P> = {} as P): Generator<R> {\n\t\t\ttry {\n\t\t\t\tconst { stmt, namedParams, hasJsonColumns } = props.build(params as P)\n\t\t\t\tcurrentStatement = stmt\n\t\t\t\tconst iterator = stmt.iterate(namedParams)\n\n\t\t\t\tlet result = iterator.next()\n\t\t\t\twhile (!result.done) {\n\t\t\t\t\tconst value = hasJsonColumns\n\t\t\t\t\t\t? (parseJsonColumns(result.value as DataRow) as R)\n\t\t\t\t\t\t: (result.value as R)\n\t\t\t\t\tyield value\n\t\t\t\t\tresult = iterator.next()\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_QUERY\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Query execution failed\",\n\t\t\t\t\tcreateErrorMessage(error, params)\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\tsourceSQL(params: ValuesParam<P> = {} as P) {\n\t\t\ttry {\n\t\t\t\tconst { stmt } = props.build(params as P)\n\n\t\t\t\treturn stmt.sourceSQL\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_QUERY\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\t\"Failed to get expanded SQL\",\n\t\t\t\t\tcreateErrorMessage(error, params)\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\n\t\tget expandedSQL() {\n\t\t\treturn currentStatement?.expandedSQL\n\t\t},\n\n\t\t__x_statement_sync__: true,\n\t}\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport type { DataRow } from \"#types\"\nimport { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors\"\n\nexport function buildOrderByStatement<P extends DataRow>(\n\torderBy?: Partial<Record<keyof P, \"ASC\" | \"DESC\">>\n): string {\n\tif (!orderBy || Object.keys(orderBy).length === 0) {\n\t\tthrow new NodeSqliteError(\n\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\"Invalid orderBy configuration\",\n\t\t\t\"OrderBy must be a non-empty object with column names as keys and 'ASC' or 'DESC' as values\",\n\t\t\tundefined\n\t\t)\n\t}\n\n\tconst orderClauses = Object.entries(orderBy).map(([column, direction]) => {\n\t\tif (direction !== \"ASC\" && direction !== \"DESC\") {\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Invalid sort direction\",\n\t\t\t\t`Sort direction must be 'ASC' or 'DESC', got '${direction}'`,\n\t\t\t\tundefined\n\t\t\t)\n\t\t}\n\t\treturn `${column} ${direction}`\n\t})\n\n\treturn `ORDER BY ${orderClauses.join(\", \")}`\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\ntype Options = {\n\tdepthLimit: number\n\tedgesLimit: number\n}\n\nconst LIMIT_REPLACE_NODE = \"[...]\"\nconst CIRCULAR_REPLACE_NODE = \"[Circular]\"\n\nconst arr: [any, string | number, any, PropertyDescriptor?][] = []\nconst replacerStack: [any, string | number, any][] = []\n\nfunction defaultOptions(): Options {\n\treturn {\n\t\tdepthLimit: Number.MAX_SAFE_INTEGER,\n\t\tedgesLimit: Number.MAX_SAFE_INTEGER,\n\t}\n}\n\n// Regular stringify\nfunction stringify(\n\tobj: any,\n\treplacer?: (key: string, value: any) => any,\n\tspacer?: string | number,\n\toptions?: Options\n): string {\n\toptions = options ?? defaultOptions()\n\n\tdecirc(obj, \"\", 0, [], undefined, 0, options)\n\tlet res: string\n\ttry {\n\t\tif (replacerStack.length === 0) {\n\t\t\tres = JSON.stringify(obj, replacer, spacer)\n\t\t} else {\n\t\t\tres = JSON.stringify(obj, replaceGetterValues(replacer), spacer)\n\t\t}\n\t} catch (_) {\n\t\treturn JSON.stringify(\n\t\t\t\"[unable to serialize, circular reference is too complex to analyze]\"\n\t\t)\n\t} finally {\n\t\twhile (arr.length !== 0) {\n\t\t\tconst part = arr.pop()!\n\t\t\tif (part.length === 4) {\n\t\t\t\tObject.defineProperty(part[0], part[1], part[3]!)\n\t\t\t} else {\n\t\t\t\tpart[0][part[1]] = part[2]\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}\n\nfunction setReplace(\n\treplace: string,\n\tval: any,\n\tk: string | number,\n\tparent: any\n): void {\n\tconst propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)\n\tif (propertyDescriptor?.get !== undefined) {\n\t\tif (propertyDescriptor.configurable) {\n\t\t\tObject.defineProperty(parent, k, { value: replace })\n\t\t\tarr.push([parent, k, val, propertyDescriptor])\n\t\t} else {\n\t\t\treplacerStack.push([val, k, replace])\n\t\t}\n\t} else {\n\t\tparent[k] = replace\n\t\tarr.push([parent, k, val])\n\t}\n}\n\nfunction decirc(\n\tval: any,\n\tk: string | number,\n\tedgeIndex: number,\n\tstack: any[],\n\tparent: any,\n\tdepth: number,\n\toptions: Options\n): void {\n\tdepth += 1\n\tif (typeof val === \"object\" && val !== null) {\n\t\tfor (let i = 0; i < stack.length; i++) {\n\t\t\tif (stack[i] === val) {\n\t\t\t\tsetReplace(CIRCULAR_REPLACE_NODE, val, k, parent)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\ttypeof options.depthLimit !== \"undefined\" &&\n\t\t\tdepth > options.depthLimit\n\t\t) {\n\t\t\tsetReplace(LIMIT_REPLACE_NODE, val, k, parent)\n\t\t\treturn\n\t\t}\n\n\t\tif (\n\t\t\ttypeof options.edgesLimit !== \"undefined\" &&\n\t\t\tedgeIndex + 1 > options.edgesLimit\n\t\t) {\n\t\t\tsetReplace(LIMIT_REPLACE_NODE, val, k, parent)\n\t\t\treturn\n\t\t}\n\n\t\tstack.push(val)\n\t\t// Optimize for Arrays. Big arrays could kill the performance otherwise!\n\t\tif (Array.isArray(val)) {\n\t\t\tfor (let i = 0; i < val.length; i++) {\n\t\t\t\tdecirc(val[i], i, i, stack, val, depth, options)\n\t\t\t}\n\t\t} else {\n\t\t\tconst keys = Object.keys(val)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key = keys[i]\n\t\t\t\tdecirc(val[key], key, i, stack, val, depth, options)\n\t\t\t}\n\t\t}\n\t\tstack.pop()\n\t}\n}\n\n// Stable-stringify\nfunction compareFunction(a: string, b: string): number {\n\tif (a < b) {\n\t\treturn -1\n\t}\n\tif (a > b) {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunction deterministicStringify(\n\tobj: any,\n\treplacer?: (key: string, value: any) => any,\n\tspacer?: string | number,\n\toptions?: Options\n): string {\n\toptions = options ?? defaultOptions()\n\n\tconst tmp = deterministicDecirc(obj, \"\", 0, [], undefined, 0, options) || obj\n\tlet res: string\n\ttry {\n\t\tif (replacerStack.length === 0) {\n\t\t\tres = JSON.stringify(tmp, replacer, spacer)\n\t\t} else {\n\t\t\tres = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)\n\t\t}\n\t} catch (_) {\n\t\treturn JSON.stringify(\n\t\t\t\"[unable to serialize, circular reference is too complex to analyze]\"\n\t\t)\n\t} finally {\n\t\twhile (arr.length !== 0) {\n\t\t\tconst part = arr.pop()!\n\t\t\tif (part.length === 4) {\n\t\t\t\tObject.defineProperty(part[0], part[1], part[3]!)\n\t\t\t} else {\n\t\t\t\tpart[0][part[1]] = part[2]\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}\n\nfunction deterministicDecirc(\n\tval: any,\n\tk: string | number,\n\tedgeIndex: number,\n\tstack: any[],\n\tparent: any,\n\tdepth: number,\n\toptions: Options\n): any {\n\tdepth += 1\n\tif (typeof val === \"object\" && val !== null) {\n\t\tfor (let i = 0; i < stack.length; i++) {\n\t\t\tif (stack[i] === val) {\n\t\t\t\tsetReplace(CIRCULAR_REPLACE_NODE, val, k, parent)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tif (typeof val.toJSON === \"function\") {\n\t\t\t\treturn\n\t\t\t}\n\t\t} catch (_) {\n\t\t\treturn\n\t\t}\n\n\t\tif (\n\t\t\ttypeof options.depthLimit !== \"undefined\" &&\n\t\t\tdepth > options.depthLimit\n\t\t) {\n\t\t\tsetReplace(LIMIT_REPLACE_NODE, val, k, parent)\n\t\t\treturn\n\t\t}\n\n\t\tif (\n\t\t\ttypeof options.edgesLimit !== \"undefined\" &&\n\t\t\tedgeIndex + 1 > options.edgesLimit\n\t\t) {\n\t\t\tsetReplace(LIMIT_REPLACE_NODE, val, k, parent)\n\t\t\treturn\n\t\t}\n\n\t\tstack.push(val)\n\t\tif (Array.isArray(val)) {\n\t\t\tfor (let i = 0; i < val.length; i++) {\n\t\t\t\tdeterministicDecirc(val[i], i, i, stack, val, depth, options)\n\t\t\t}\n\t\t} else {\n\t\t\tconst tmp: Record<string, any> = {}\n\t\t\tconst keys = Object.keys(val).sort(compareFunction)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key = keys[i]\n\t\t\t\tdeterministicDecirc(val[key], key, i, stack, val, depth, options)\n\t\t\t\ttmp[key] = val[key]\n\t\t\t}\n\t\t\tif (typeof parent !== \"undefined\") {\n\t\t\t\tarr.push([parent, k, val])\n\t\t\t\tparent[k] = tmp\n\t\t\t} else {\n\t\t\t\treturn tmp\n\t\t\t}\n\t\t}\n\t\tstack.pop()\n\t}\n}\n\nfunction replaceGetterValues(\n\treplacer?: (key: string, value: any) => any\n): (key: string, value: any) => any {\n\treplacer = replacer ?? ((_, v) => v)\n\n\treturn function (this: unknown, key: string, val: any): any {\n\t\tif (replacerStack.length > 0) {\n\t\t\tfor (let i = 0; i < replacerStack.length; i++) {\n\t\t\t\tconst part = replacerStack[i]\n\t\t\t\tif (part[1] === key && part[0] === val) {\n\t\t\t\t\tval = part[2]\n\t\t\t\t\treplacerStack.splice(i, 1)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn replacer!.call(this, key, val)\n\t}\n}\n\nstringify.stable = deterministicStringify\nstringify.stableStringify = deterministicStringify\n\nexport { stringify as default, deterministicStringify, stringify }\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport { validateSetOptions } from \"#context\"\nimport { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors.js\"\nimport { isRawValue, type SetOptions, type DataRow } from \"#types\"\n\n// In values.ts\nexport function buildSetStatement<P extends DataRow>(\n\tset: SetOptions<P>,\n\tparams: P\n): { sql: string; parameterOperators: string[] } {\n\t// Validate the set options first\n\tconst errors = validateSetOptions(set)\n\tif (errors.length > 0) {\n\t\tthrow new NodeSqliteError(\n\t\t\t\"ERR_SQLITE_PARAM\",\n\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\"Invalid SET options\",\n\t\t\terrors.map(e => e.message).join(\"\\n\"),\n\t\t\tundefined\n\t\t)\n\t}\n\n\t// Handle star format\n\tif (set === \"*\") {\n\t\tconst columns = Object.keys(params)\n\t\tconst paramOps = columns.map(k => `$${k}`)\n\t\treturn {\n\t\t\tsql: `SET ${columns.map((col, i) => `${col} = ${paramOps[i]}`).join(\", \")}`,\n\t\t\tparameterOperators: paramOps,\n\t\t}\n\t}\n\n\t// Handle array format with jsonColumns\n\tif (Array.isArray(set)) {\n\t\tconst [, config] = set\n\t\tconst jsonColumns = new Set(config.jsonColumns)\n\t\tconst columns = Object.keys(params)\n\t\tconst paramOps = columns.map(k => `$${k}`)\n\n\t\tconst setPairs = columns.map((col, i) => {\n\t\t\tif (jsonColumns.has(col)) {\n\t\t\t\treturn `${col} = jsonb(${paramOps[i]})`\n\t\t\t}\n\t\t\treturn `${col} = ${paramOps[i]}`\n\t\t})\n\n\t\treturn {\n\t\t\tsql: `SET ${setPairs.join(\", \")}`,\n\t\t\tparameterOperators: paramOps,\n\t\t}\n\t}\n\n\t// Handle object format\n\tconst entries = Object.entries(set)\n\tconst paramOps: string[] = []\n\tconst setPairs: string[] = []\n\n\tfor (const [col, value] of entries) {\n\t\tif (isRawValue(value)) {\n\t\t\tsetPairs.push(`${col} = ${value.value}`)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (typeof value === \"string\") {\n\t\t\t// Must be a ValueType (ParameterOperator or ToJson) at this point\n\t\t\t// since validation passed\n\t\t\tif (value.endsWith(\"->json\")) {\n\t\t\t\t// Handle ToJson case\n\t\t\t\tconst paramName = value.slice(1, -6)\n\t\t\t\tparamOps.push(`$${paramName}`)\n\t\t\t\tsetPairs.push(`${col} = jsonb($${paramName})`)\n\t\t\t} else {\n\t\t\t\t// Handle ParameterOperator case\n\t\t\t\tconst paramName = value.slice(1)\n\t\t\t\tparamOps.push(`$${paramName}`)\n\t\t\t\tsetPairs.push(`${col} = $${paramName}`)\n\t\t\t}\n\t\t}\n\t\t// No else needed - validation would have caught invalid types\n\t}\n\n\treturn {\n\t\tsql: `SET ${setPairs.join(\", \")}`,\n\t\tparameterOperators: paramOps,\n\t}\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport { validationErr, type ValidationError } from \"./validate\"\n\n/**\n * SQLite journal mode settings\n * @see https://www.sqlite.org/pragma.html#pragma_journal_mode\n */\nexport const JournalModes = [\n\t\"DELETE\",\n\t\"TRUNCATE\",\n\t\"PERSIST\",\n\t\"MEMORY\",\n\t\"WAL\",\n\t\"OFF\",\n] as const\nexport type JournalMode = (typeof JournalModes)[number]\n\n/**\n * Synchronization settings for transaction safety\n * @see https://www.sqlite.org/pragma.html#pragma_synchronous\n */\nexport const SynchronousModes = [\"OFF\", \"NORMAL\", \"FULL\", \"EXTRA\"] as const\nexport type SynchronousMode = (typeof SynchronousModes)[number]\n\n/**\n * Temporary storage location settings\n * @see https://www.sqlite.org/pragma.html#pragma_temp_store\n */\nexport const TempStores = [\"DEFAULT\", \"FILE\", \"MEMORY\"] as const\nexport type TempStore = (typeof TempStores)[number]\n\n/**\n * Database locking mode settings\n * @see https://www.sqlite.org/pragma.html#pragma_locking_mode\n */\nexport const LockingModes = [\"NORMAL\", \"EXCLUSIVE\"] as const\nexport type LockingMode = (typeof LockingModes)[number]\n\n/**\n * SQLite PRAGMA configuration options\n */\nexport type PragmaConfig = Partial<{\n\t/** Journal mode for transaction logging */\n\tjournalMode: JournalMode\n\n\t/** Level of transaction synchronization */\n\tsynchronous: SynchronousMode\n\n\t/** Database cache size in kilobytes */\n\tcacheSize: number\n\n\t/** Memory-mapped I/O size in bytes */\n\tmmapSize: number\n\n\t/** Temporary storage location */\n\ttempStore: TempStore\n\n\t/** Database locking mode */\n\tlockingMode: LockingMode\n\n\t/** Busy handler timeout in milliseconds */\n\tbusyTimeout: number\n\n\t/** Enable/disable foreign key constraints */\n\tforeignKeys: boolean\n\n\t/** Write-ahead log auto-checkpoint size */\n\twalAutocheckpoint: number\n\n\t/** Allow/disallow untrusted schema loads */\n\ttrustedSchema: boolean\n}>\n\nexport function validatePragmaConfig(config: unknown): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tif (typeof config !== \"object\" || config === null) {\n\t\treturn [validationErr({ msg: \"PragmaConfig must be an object\" })]\n\t}\n\n\tconst pragmaConfig = config as Record<string, unknown>\n\n\tif (\n\t\t\"journalMode\" in pragmaConfig &&\n\t\t!JournalModes.includes(pragmaConfig.journalMode as JournalMode)\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: `Invalid journal mode: ${pragmaConfig.journalMode}`,\n\t\t\t\tpath: \"journalMode\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"synchronous\" in pragmaConfig &&\n\t\t!SynchronousModes.includes(pragmaConfig.synchronous as SynchronousMode)\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: `Invalid synchronous mode: ${pragmaConfig.synchronous}`,\n\t\t\t\tpath: \"synchronous\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"tempStore\" in pragmaConfig &&\n\t\t!TempStores.includes(pragmaConfig.tempStore as TempStore)\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: `Invalid temp store: ${pragmaConfig.tempStore}`,\n\t\t\t\tpath: \"tempStore\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"lockingMode\" in pragmaConfig &&\n\t\t!LockingModes.includes(pragmaConfig.lockingMode as LockingMode)\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: `Invalid locking mode: ${pragmaConfig.lockingMode}`,\n\t\t\t\tpath: \"lockingMode\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"cacheSize\" in pragmaConfig &&\n\t\ttypeof pragmaConfig.cacheSize !== \"number\"\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"cacheSize must be a number\",\n\t\t\t\tpath: \"cacheSize\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\"mmapSize\" in pragmaConfig && typeof pragmaConfig.mmapSize !== \"number\") {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"mmapSize must be a number\",\n\t\t\t\tpath: \"mmapSize\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"busyTimeout\" in pragmaConfig &&\n\t\ttypeof pragmaConfig.busyTimeout !== \"number\"\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"busyTimeout must be a number\",\n\t\t\t\tpath: \"busyTimeout\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"foreignKeys\" in pragmaConfig &&\n\t\ttypeof pragmaConfig.foreignKeys !== \"boolean\"\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"foreignKeys must be a boolean\",\n\t\t\t\tpath: \"foreignKeys\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"walAutocheckpoint\" in pragmaConfig &&\n\t\ttypeof pragmaConfig.walAutocheckpoint !== \"number\"\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"walAutocheckpoint must be a number\",\n\t\t\t\tpath: \"walAutocheckpoint\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (\n\t\t\"trustedSchema\" in pragmaConfig &&\n\t\ttypeof pragmaConfig.trustedSchema !== \"boolean\"\n\t) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"trustedSchema must be a boolean\",\n\t\t\t\tpath: \"trustedSchema\",\n\t\t\t})\n\t\t)\n\t}\n\n\treturn errors\n}\n\n/**\n * Default pragma configurations for different environments\n */\nexport const PragmaDefaults: Record<\n\t\"development\" | \"testing\" | \"production\",\n\tPragmaConfig\n> = {\n\t/**\n\t * Development environment defaults - optimized for development workflow\n\t */\n\tdevelopment: {\n\t\tjournalMode: \"WAL\",\n\t\tsynchronous: \"NORMAL\",\n\t\tcacheSize: -64000, // 64MB cache\n\t\ttempStore: \"MEMORY\",\n\t\tmmapSize: 64000000, // 64MB mmap\n\t\tlockingMode: \"NORMAL\",\n\t\tbusyTimeout: 5000,\n\t\tforeignKeys: true,\n\t\twalAutocheckpoint: 1000,\n\t\ttrustedSchema: true,\n\t},\n\n\t/**\n\t * Testing environment defaults - optimized for in-memory testing\n\t */\n\ttesting: {\n\t\tjournalMode: \"WAL\",\n\t\tsynchronous: \"OFF\", // Less durable but faster for testing\n\t\tcacheSize: -32000, // 32MB cache is enough for testing\n\t\ttempStore: \"MEMORY\",\n\t\tlockingMode: \"EXCLUSIVE\", // Reduce lock conflicts\n\t\tbusyTimeout: 5000,\n\t\tforeignKeys: true,\n\t\twalAutocheckpoint: 1000,\n\t\ttrustedSchema: true,\n\t},\n\n\t/**\n\t * Production environment defaults - optimized for durability and performance\n\t */\n\tproduction: {\n\t\tjournalMode: \"WAL\",\n\t\tsynchronous: \"NORMAL\",\n\t\tcacheSize: -64000, // 64MB cache\n\t\ttempStore: \"MEMORY\",\n\t\tmmapSize: 268435456, // 256MB mmap\n\t\tlockingMode: \"NORMAL\",\n\t\tbusyTimeout: 10000,\n\t\tforeignKeys: true,\n\t\twalAutocheckpoint: 1000,\n\t\ttrustedSchema: false, // Safer default for production\n\t},\n}\n\n/**\n * Generates SQLite PRAGMA statements from configuration\n */\nexport function getPragmaStatements(config: PragmaConfig): string[] {\n\tconst statements: string[] = []\n\n\tif (config.journalMode) {\n\t\tstatements.push(`PRAGMA journal_mode=${config.journalMode};`)\n\t}\n\n\tif (config.synchronous) {\n\t\tstatements.push(`PRAGMA synchronous=${config.synchronous};`)\n\t}\n\n\tif (config.cacheSize !== undefined) {\n\t\tstatements.push(`PRAGMA cache_size=${config.cacheSize};`)\n\t}\n\n\tif (config.mmapSize !== undefined) {\n\t\tstatements.push(`PRAGMA mmap_size=${config.mmapSize};`)\n\t}\n\n\tif (config.tempStore) {\n\t\tstatements.push(`PRAGMA temp_store=${config.tempStore};`)\n\t}\n\n\tif (config.lockingMode) {\n\t\tstatements.push(`PRAGMA locking_mode=${config.lockingMode};`)\n\t}\n\n\tif (config.busyTimeout !== undefined) {\n\t\tstatements.push(`PRAGMA busy_timeout=${config.busyTimeout};`)\n\t}\n\n\tif (config.foreignKeys !== undefined) {\n\t\tstatements.push(`PRAGMA foreign_keys=${config.foreignKeys ? \"ON\" : \"OFF\"};`)\n\t}\n\n\tif (config.walAutocheckpoint !== undefined) {\n\t\tstatements.push(`PRAGMA wal_autocheckpoint=${config.walAutocheckpoint};`)\n\t}\n\n\tif (config.trustedSchema !== undefined) {\n\t\tstatements.push(\n\t\t\t`PRAGMA trusted_schema=${config.trustedSchema ? \"ON\" : \"OFF\"};`\n\t\t)\n\t}\n\n\treturn statements\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport { DatabaseSync, type StatementSync } from \"node:sqlite\"\nimport {\n\tNodeSqliteError,\n\tSqlitePrimaryResultCode,\n\tisNodeSqliteError,\n} from \"#errors\"\nimport {\n\tcreateStatementCache,\n\ttype StatementCache,\n\ttype CacheStats,\n} from \"#cache\"\nimport { join } from \"node:path\"\nimport {\n\ttype PragmaConfig,\n\tPragmaDefaults,\n\tgetPragmaStatements,\n} from \"#pragmas\"\nimport { tmpdir } from \"node:os\"\nimport { accessSync, renameSync, unlinkSync } from \"node:fs\"\nimport { type Logger, NoopLogger } from \"#logger\"\nimport { createXStatementSync, Sql } from \"#sql\"\nimport type {\n\tCleanupPragmas,\n\tDataRow,\n\tDBOptions,\n\tFormatterConfig,\n\tSqlTemplateValues,\n} from \"#types\"\nimport { buildIndexStatement, type IndexDef } from \"#idx.js\"\nimport stringify from \"#stringify.js\"\n\n/**\n * Type-safe SQLite database wrapper with prepared statement caching, SQL template literals,\n * and JSON support.\n */\nexport class DB {\n\t#db: DatabaseSync\n\treadonly #statementCache?: StatementCache\n\treadonly #location: string\n\treadonly #logger: Logger\n\treadonly #formatConfig?: FormatterConfig | false\n\t/**\n\t * Creates a new database connection with optional configuration.\n\t * @param options Database configuration options\n\t * @throws {NodeSqliteError} If database cannot be opened or initialized\n\t */\n\n\tconstructor(options: DBOptions = {}) {\n\t\tconst location = options.location ?? \":memory:\"\n\t\tthis.#location = location\n\t\tthis.#logger = options.logger ?? new NoopLogger()\n\t\tthis.#formatConfig = options.format\n\n\t\tthis.#logger.debug(\"Initializing database\", { location })\n\n\t\ttry {\n\t\t\tthis.#db = new DatabaseSync(location, { open: true, allowExtension: options?.allowExtension ?? false })\n\t\t\tthis.#logger.info(\"Database opened successfully\", { location })\n\n\t\t\t// Configure pragmas based on environment and custom settings\n\t\t\tconst environment = options.environment || \"development\"\n\t\t\tthis.#logger.debug(\"Configuring pragmas\", { environment })\n\n\t\t\tconst defaultPragmas = PragmaDefaults[environment]\n\t\t\tconst customPragmas = options.pragma || {}\n\t\t\tconst finalPragmas: PragmaConfig = {\n\t\t\t\t...defaultPragmas,\n\t\t\t\t...customPragmas,\n\t\t\t}\n\t\t\tthis.#configurePragmas(finalPragmas)\n\n\t\t\t// Initialize statement cache if enabled\n\t\t\tif (options.statementCache) {\n\t\t\t\tthis.#logger.debug(\"Initializing statement cache\")\n\t\t\t\tif (typeof options.statementCache === \"object\") {\n\t\t\t\t\tthis.#statementCache = createStatementCache(options.statementCache)\n\t\t\t\t\tthis.#logger.debug(\n\t\t\t\t\t\t\"Created statement cache with custom options\",\n\t\t\t\t\t\toptions.statementCache\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tthis.#statementCache = createStatementCache({ maxSize: 1000 })\n\t\t\t\t\tthis.#logger.debug(\"Created statement cache with default options\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch (error) {\n\t\t\tthis.#logger.error(\"Failed to initialize database\", error)\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_OPEN\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_CANTOPEN,\n\t\t\t\t\"Cannot open database\",\n\t\t\t\t`Failed to open database at ${location}`,\n\t\t\t\terror instanceof Error ? error : undefined\n\t\t\t)\n\t\t}\n\t}\n\t/**\n\t* Returns the underlying DatabaseSync instance\n\t\n\t\n\t*/ \n\n\tget nativeDb(): DatabaseSync {\n\t\treturn this.#db\n\t}\n\t/**\n\t * Prepares an SQL statement with optional caching.\n\t * @param sql The SQL statement to prepare\n\t * @returns Prepared statement\n\t * @throws {NodeSqliteError} If statement preparation fails\n\t */\n\n\tprepareStatement(sql: string): StatementSync {\n\t\tthis.#logger.debug(\"Preparing statement\", { sql })\n\t\ttry {\n\t\t\tif (this.#statementCache) {\n\t\t\t\tconst cached = this.#statementCache.get(sql)\n\t\t\t\tif (cached) {\n\t\t\t\t\tthis.#logger.trace(\"Statement cache hit\", { sql })\n\t\t\t\t\treturn cached\n\t\t\t\t}\n\t\t\t\tthis.#logger.trace(\"Statement cache miss\", { sql })\n\t\t\t}\n\n\t\t\tconst stmt = this.#db.prepare(sql)\n\t\t\tthis.#logger.trace(\"Statement prepared successfully\", { sql })\n\n\t\t\tif (this.#statementCache) {\n\t\t\t\tthis.#statementCache.set(sql, stmt)\n\t\t\t\tthis.#logger.trace(\"Statement cached\", { sql })\n\t\t\t}\n\n\t\t\treturn stmt\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.#statementCache &&\n\t\t\t\terror instanceof Error &&\n\t\t\t\terror.message.toLowerCase().includes(\"memory\")\n\t\t\t) {\n\t\t\t\tthis.#logger.warn(\"Memory pressure detected, clearing statement cache\")\n\t\t\t\tthis.#statementCache.clear()\n\t\t\t}\n\n\t\t\tthis.#logger.error(\"Failed to prepare statement\", { sql, error })\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_PREPARE\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Failed to prepare statement\",\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\terror instanceof Error ? error : undefined\n\t\t\t)\n\t\t}\n\t}\n\t/**\n\t * Creates a type-safe SQL query builder using template literals.\n\t * @param strings SQL template strings\n\t * @param params SQL template parameters and contexts\n\t * @returns Type-safe statement executor\n\t */\n\tsql<P extends DataRow, R = P>(\n\t\tstrings: TemplateStringsArray,\n\t\t...params: SqlTemplateValues<P, R>\n\t) {\n\t\tconst builder = new Sql<P, R>({\n\t\t\tstrings,\n\t\t\tparamOperators: params,\n\t\t\tformatterConfig: this.#formatConfig,\n\t\t})\n\t\treturn createXStatementSync<P, R>({\n\t\t\tbuild: finalParams => {\n\t\t\t\tconst { sql, namedParams, hasJsonColumns } =\n\t\t\t\t\tbuilder.prepare(finalParams)\n\n\t\t\t\tconst stmt = this.prepareStatement(sql)\n\n\t\t\t\treturn { stmt, namedParams, hasJsonColumns }\n\t\t\t},\n\t\t\tprepare: sql => this.prepareStatement(sql),\n\t\t\tsql: builder,\n\t\t})\n\t}\n\n\tcreateIndex<T extends DataRow>(def: IndexDef<T>): void {\n\t\tthis.#logger.debug(\"Creating index\", stringify(def))\n\t\tconst stmt = buildIndexStatement(def)\n\t\tthis.exec(stmt)\n\t\tthis.#logger.info(\"Index created successfully\", stringify(def))\n\t}\n\n\t/**\n\t * Creates a backup of the database.\n\t * @param filename Path where backup will be saved\n\t * @throws {NodeSqliteError} If backup creation fails\n\t */\n\n\tbackup(filename: string): void {\n\t\tthis.#logger.info(\"Starting database backup\", { filename })\n\t\ttry {\n\t\t\tthis.#db.exec(`VACUUM INTO '${filename}'`)\n\t\t\tthis.#logger.info(\"Database backup completed successfully\", {\n\t\t\t\tfilename,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.#logger.error(\"Backup failed\", { filename, error })\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_BACKUP\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_CANTOPEN,\n\t\t\t\t\"Cannot create backup file\",\n\t\t\t\t`Failed to create backup at ${filename}. Check permissions and ensure directory exists.`,\n\t\t\t\terror instanceof Error ? error : undefined\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Restores database from a backup file.\n\t * @param filename Path to backup file\n\t * @throws {NodeSqliteError} If restore fails or file is inaccessible\n\t */\n\n\trestore(filename: string): void {\n\t\tthis.#logger.info(\"Starting database restore\", { filename })\n\t\ttry {\n\t\t\tif (this.#location === \":memory:\") {\n\t\t\t\tthis.#logger.error(\"Cannot restore in-memory database\")\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_RESTORE\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_MISUSE,\n\t\t\t\t\t\"Cannot restore in-memory database\",\n\t\t\t\t\t\"Restore operation is not supported for in-memory databases\",\n\t\t\t\t\tundefined\n\t\t\t\t)\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\taccessSync(filename)\n\t\t\t} catch (error) {\n\t\t\t\tthis.#logger.error(\"Backup file inaccessible\", { filename, error })\n\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\"ERR_SQLITE_CANTOPEN\",\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_CANTOPEN,\n\t\t\t\t\t\"Cannot open backup file\",\n\t\t\t\t\t`Failed to restore from ${filename}. File may not exist or be inaccessible.`,\n\t\t\t\t\terror instanceof Error ? error : undefined\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tthis.#logger.debug(\"Creating temporary backup\")\n\t\t\tthis.close()\n\n\t\t\tconst tempBackup = join(tmpdir(), `temp-${Date.now()}.db`)\n\t\t\ttry {\n\t\t\t\trenameSync(this.#location, tempBackup)\n\t\t\t\tthis.#logger.debug(\"Created temporary backup\", { tempBackup })\n\n\t\t\t\trenameSync(filename, this.#location)\n\t\t\t\tthis.#logger.debug(\"Moved new database into place\")\n\n\t\t\t\tthis.#db = new DatabaseSync(this.#location, { open: true })\n\t\t\t\tthis.#logger.debug(\"Opened restored database\")\n\n\t\t\t\tunlinkSync(tempBackup)\n\t\t\t\tthis.#logger.debug(\"Removed temporary backup\")\n\n\t\t\t\tthis.#logger.info(\"Database restore completed successfully\")\n\t\t\t} catch (error) {\n\t\t\t\tthis.#logger.error(\"Restore failed, attempting rollback\", { error })\n\t\t\t\tif (error instanceof Error && error.message.includes(\"ENOENT\")) {\n\t\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\t\"ERR_SQLITE_CANTOPEN\",\n\t\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_CANTOPEN,\n\t\t\t\t\t\t\"Cannot open backup file\",\n\t\t\t\t\t\t`Failed to restore from ${filename}`,\n\t\t\t\t\t\terror\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow error instanceof NodeSqliteError\n\t\t\t\t? error\n\t\t\t\t: NodeSqliteError.fromNodeSqlite(\n\t\t\t\t\t\terror instanceof Error ? error : new Error(String(error))\n\t\t\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Executes raw SQL directly.\n\t * @param sql SQL statement to execute\n\t * @throws {NodeSqliteError} If execution fails\n\t */\n\n\texec(sql: string): void {\n\t\ttry {\n\t\t\tthis.#logger.debug(\"Executing raw SQL\", { sql })\n\t\t\tthis.#db.exec(sql)\n\t\t\tthis.#logger.trace(\"Raw SQL executed successfully\", { sql })\n\t\t} catch (error) {\n\t\t\tthis.#logger.error(\"Raw SQL execution failed\", { sql, error })\n\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\"ERR_SQLITE_EXEC\",\n\t\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\t\"Execution failed\",\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\terror instanceof Error ? error : undefined\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Retrieves prepared statement cache statistics.\n\t * @returns Cache statistics if caching is enabled, undefined otherwise\n\t */\n\n\tgetCacheStats(): CacheStats | undefined {\n\t\tthis.#logger.debug(\"Retrieving cache statistics\")\n\t\treturn this.#statementCache?.getStats()\n\t}\n\n\t/**\n\t * Clears the prepared statement cache if enabled.\n\t */\n\n\tclearStatementCache(): void {\n\t\tif (this.#statementCache) {\n\t\t\tthis.#logger.debug(\"Clearing statement cache\")\n\t\t\tthis.#statementCache.clear()\n\t\t\tthis.#logger.debug(\"Statement cache cleared\")\n\t\t}\n\t}\n\n\t/**\n\t * Closes database connection and optionally runs cleanup pragmas.\n\t * @param pragmas Optional cleanup operations to perform before closing\n\t */\n\tclose(pragmas?: CleanupPragmas): void {\n\t\tthis.#logger.info(\"Closing database connection\", pragmas)\n\n\t\ttry {\n\t\t\tif (pragmas) {\n\t\t\t\tif (pragmas.optimize) {\n\t\t\t\t\tthis.#db.exec(\"PRAGMA optimize;\")\n\t\t\t\t}\n\t\t\t\tif (pragmas.shrinkMemory) {\n\t\t\t\t\tthis.#db.exec(\"PRAGMA shrink_memory;\")\n\t\t\t\t}\n\t\t\t\tif (pragmas.walCheckpoint) {\n\t\t\t\t\tthis.#db.exec(`PRAGMA wal_checkpoint(${pragmas.walCheckpoint});`)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.#logger.error(\"Error executing cleanup pragmas\", error)\n\t\t} finally {\n\t\t\tthis.clearStatementCache()\n\t\t\tthis.#db.close()\n\t\t\tthis.#logger.info(\"Database connection closed\")\n\t\t}\n\t}\n\n\t/**\n\t * Configures database pragmas.\n\t * @param config PRAGMA configuration settings\n\t * @throws {NodeSqliteError} If pragma configuration fails\n\t * @private\n\t */\n\n\t#configurePragmas(config: PragmaConfig): void {\n\t\ttry {\n\t\t\tthis.#logger.debug(\"Configuring pragmas\", config)\n\t\t\tconst statements = getPragmaStatements(config)\n\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tthis.#logger.trace(\"Executing pragma statement\", { stmt })\n\t\t\t\tthis.#db.exec(stmt)\n\t\t\t}\n\n\t\t\tthis.#logger.debug(\"Pragma configuration completed\")\n\t\t} catch (error) {\n\t\t\tthis.#logger.error(\"Failed to configure pragmas\", { error })\n\t\t\tif (isNodeSqliteError(error)) {\n\t\t\t\tif (\n\t\t\t\t\tNodeSqliteError.fromNodeSqlite(error).getPrimaryResultCode() ===\n\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_BUSY\n\t\t\t\t) {\n\t\t\t\t\tthrow new NodeSqliteError(\n\t\t\t\t\t\t\"ERR_SQLITE_BUSY\",\n\t\t\t\t\t\tSqlitePrimaryResultCode.SQLITE_BUSY,\n\t\t\t\t\t\t\"Database is locked while configuring pragmas\",\n\t\t\t\t\t\t\"Failed to configure database pragmas: database is locked\",\n\t\t\t\t\t\terror\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthrow NodeSqliteError.fromNodeSqlite(\n\t\t\t\terror instanceof Error ? error : new Error(String(error))\n\t\t\t)\n\t\t}\n\t}\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nimport type { StatementSync } from \"node:sqlite\"\n\ninterface CacheItem<V> {\n\tvalue: V\n\texpiry?: number\n}\n\nexport type Options<K, V> = {\n\treadonly maxAge?: number\n\treadonly maxSize: number\n\tonEviction?: (key: K, value: V) => void\n}\n\n// We'll create a base class that doesn't extend Map to avoid the iterator issues\nexport class LRUBase<K, V> {\n\t#size = 0\n\t#cache = new Map<K, CacheItem<V>>()\n\t#oldCache = new Map<K, CacheItem<V>>()\n\t#maxSize: number\n\t#maxAge: number\n\t#onEviction?: (key: K, value: V) => void\n\n\tconstructor(options: Options<K, V>) {\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError(\"`maxSize` must be a number greater than 0\")\n\t\t}\n\n\t\tif (typeof options.maxAge === \"number\" && options.maxAge === 0) {\n\t\t\tthrow new TypeError(\"`maxAge` must be a number greater than 0\")\n\t\t}\n\n\t\tthis.#maxSize = options.maxSize\n\t\tthis.#maxAge = options.maxAge || Number.POSITIVE_INFINITY\n\t\tthis.#onEviction = options.onEviction\n\t}\n\n\tprotected get cache(): Map<K, CacheItem<V>> {\n\t\treturn this.#cache\n\t}\n\n\tprotected get oldCache(): Map<K, CacheItem<V>> {\n\t\treturn this.#oldCache\n\t}\n\n\t#emitEvictions(cache: Map<K, CacheItem<V>>): void {\n\t\tif (typeof this.#onEviction !== \"function\") {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const [key, item] of cache) {\n\t\t\tthis.#onEviction(key, item.value)\n\t\t}\n\t}\n\n\t#deleteIfExpired(key: K, item: CacheItem<V>): boolean {\n\t\tif (typeof item.expiry === \"number\" && item.expiry <= Date.now()) {\n\t\t\tif (typeof this.#onEviction === \"function\") {\n\t\t\t\tthis.#onEviction(key, item.value)\n\t\t\t}\n\n\t\t\treturn this.delete(key)\n\t\t}\n\n\t\treturn false\n\t}\n\n\t#getOrDeleteIfExpired(key: K, item: CacheItem<V>): V | undefined {\n\t\tconst deleted = this.#deleteIfExpired(key, item)\n\t\tif (deleted === false) {\n\t\t\treturn item.value\n\t\t}\n\t\treturn undefined\n\t}\n\n\t#getItemValue(key: K, item: CacheItem<V>): V | undefined {\n\t\treturn item.expiry ? this.#getOrDeleteIfExpired(key, item) : item.value\n\t}\n\n\t#peek(key: K, cache: Map<K, CacheItem<V>>): V | undefined {\n\t\tconst item = cache.get(key)\n\t\tif (!item) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn this.#getItemValue(key, item)\n\t}\n\n\t#set(key: K, value: CacheItem<V>): void {\n\t\tthis.#cache.set(key, value)\n\t\tthis.#size++\n\n\t\tif (this.#size >= this.#maxSize) {\n\t\t\tthis.#size = 0\n\t\t\tthis.#emitEvictions(this.#oldCache)\n\t\t\tthis.#oldCache = this.#cache\n\t\t\tthis.#cache = new Map()\n\t\t}\n\t}\n\n\t#moveToRecent(key: K, item: CacheItem<V>): void {\n\t\tthis.#oldCache.delete(key)\n\t\tthis.#set(key, item)\n\t}\n\n\t*#entriesAscending(): IterableIterator<[K, CacheItem<V>]> {\n\t\tfor (const item of this.#oldCache) {\n\t\t\tconst [key, value] = item\n\t\t\tif (!this.#cache.has(key)) {\n\t\t\t\tconst deleted = this.#deleteIfExpired(key, value)\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield item\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.#cache) {\n\t\t\tconst [key, value] = item\n\t\t\tconst deleted = this.#deleteIfExpired(key, value)\n\t\t\tif (deleted === false) {\n\t\t\t\tyield item\n\t\t\t}\n\t\t}\n\t}\n\n\tget(key: K): V | undefined {\n\t\tif (this.#cache.has(key)) {\n\t\t\tconst item = this.#cache.get(key)\n\t\t\tif (!item) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\treturn this.#getItemValue(key, item)\n\t\t}\n\n\t\tif (this.#oldCache.has(key)) {\n\t\t\tconst item = this.#oldCache.get(key)\n\t\t\tif (!item) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\tif (this.#deleteIfExpired(key, item) === false) {\n\t\t\t\tthis.#moveToRecent(key, item)\n\t\t\t\treturn item.value\n\t\t\t}\n\t\t}\n\t\treturn undefined\n\t}\n\n\tset(key: K, value: V, options: { maxAge?: number } = {}): this {\n\t\tconst maxAge = options.maxAge ?? this.#maxAge\n\n\t\tconst expiry =\n\t\t\ttypeof maxAge === \"number\" && maxAge !== Number.POSITIVE_INFINITY\n\t\t\t\t? Date.now() + maxAge\n\t\t\t\t: undefined\n\n\t\tif (this.#cache.has(key)) {\n\t\t\tthis.#cache.set(key, {\n\t\t\t\tvalue,\n\t\t\t\texpiry,\n\t\t\t})\n\t\t} else {\n\t\t\tthis.#set(key, { value, expiry })\n\t\t}\n\n\t\treturn this\n\t}\n\n\thas(key: K): boolean {\n\t\tif (this.#cache.has(key)) {\n\t\t\tconst item = this.#cache.get(key)\n\t\t\tif (!item) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn !this.#deleteIfExpired(key, item)\n\t\t}\n\n\t\tif (this.#oldCache.has(key)) {\n\t\t\tconst item = this.#oldCache.get(key)\n\t\t\tif (!item) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn !this.#deleteIfExpired(key, item)\n\t\t}\n\n\t\treturn false\n\t}\n\n\tpeek(key: K): V | undefined {\n\t\tif (this.#cache.has(key)) {\n\t\t\treturn this.#peek(key, this.#cache)\n\t\t}\n\n\t\tif (this.#oldCache.has(key)) {\n\t\t\treturn this.#peek(key, this.#oldCache)\n\t\t}\n\t\treturn undefined\n\t}\n\n\tdelete(key: K): boolean {\n\t\tconst deleted = this.#cache.delete(key)\n\t\tif (deleted) {\n\t\t\tthis.#size--\n\t\t}\n\n\t\treturn this.#oldCache.delete(key) || deleted\n\t}\n\n\tclear(): void {\n\t\tthis.#cache.clear()\n\t\tthis.#oldCache.clear()\n\t\tthis.#size = 0\n\t}\n\n\tresize(maxSize: number): void {\n\t\tif (!(maxSize && maxSize > 0)) {\n\t\t\tthrow new TypeError(\"`maxSize` must be a number greater than 0\")\n\t\t}\n\n\t\tconst items = [...this.#entriesAscending()]\n\t\tconst removeCount = items.length - maxSize\n\t\tif (removeCount < 0) {\n\t\t\tthis.#cache = new Map(items)\n\t\t\tthis.#oldCache = new Map()\n\t\t\tthis.#size = items.length\n\t\t} else {\n\t\t\tif (removeCount > 0) {\n\t\t\t\tthis.#emitEvictions(new Map(items.slice(0, removeCount)))\n\t\t\t}\n\n\t\t\tthis.#oldCache = new Map(items.slice(removeCount))\n\t\t\tthis.#cache = new Map()\n\t\t\tthis.#size = 0\n\t\t}\n\n\t\tthis.#maxSize = maxSize\n\t}\n\n\t*entriesDescending(): IterableIterator<[K, V]> {\n\t\tconst cacheItems = [...this.#cache]\n\t\tfor (let i = cacheItems.length - 1; i >= 0; --i) {\n\t\t\tconst item = cacheItems[i]\n\t\t\tif (item) {\n\t\t\t\tconst [key, value] = item\n\t\t\t\tconst deleted = this.#deleteIfExpired(key, value)\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst oldItems = [...this.#oldCache]\n\t\tfor (let i = oldItems.length - 1; i >= 0; --i) {\n\t\t\tconst item = oldItems[i]\n\t\t\tif (item) {\n\t\t\t\tconst [key, value] = item\n\t\t\t\tif (!this.#cache.has(key)) {\n\t\t\t\t\tconst deleted = this.#deleteIfExpired(key, value)\n\t\t\t\t\tif (deleted === false) {\n\t\t\t\t\t\tyield [key, value.value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t*entriesAscending(): IterableIterator<[K, V]> {\n\t\tfor (const [key, value] of this.#entriesAscending()) {\n\t\t\tyield [key, value.value]\n\t\t}\n\t}\n\n\tget size(): number {\n\t\tif (!this.#size) {\n\t\t\treturn this.#oldCache.size\n\t\t}\n\n\t\tlet oldCacheSize = 0\n\t\tfor (const key of this.#oldCache.keys()) {\n\t\t\tif (!this.#cache.has(key)) {\n\t\t\t\toldCacheSize++\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this.#size + oldCacheSize, this.#maxSize)\n\t}\n\n\tget maxSize(): number {\n\t\treturn this.#maxSize\n\t}\n}\n\n// Create a proxy class that delegates to Map for iterator methods\nexport default class QuickLRU<K, V> implements Map<K, V> {\n\treadonly #base: LRUBase<K, V>\n\treadonly #map: Map<K, V>\n\n\tconstructor(options: Options<K, V>) {\n\t\tthis.#base = new LRUBase(options)\n\t\tthis.#map = new Map()\n\t}\n\n\tclear(): void {\n\t\tthis.#base.clear()\n\t\tthis.#map.clear()\n\t}\n\n\tdelete(key: K): boolean {\n\t\treturn this.#base.delete(key)\n\t}\n\n\tforEach(\n\t\tcallbackfn: (value: V, key: K, map: Map<K, V>) => void,\n\t\tthisArg?: unknown\n\t): void {\n\t\tthis.#map.forEach(callbackfn, thisArg)\n\t}\n\n\tget(key: K): V | undefined {\n\t\treturn this.#base.get(key)\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this.#base.has(key)\n\t}\n\n\tset(key: K, value: V): this {\n\t\tthis.#base.set(key, value)\n\t\tthis.#map.set(key, value)\n\t\treturn this\n\t}\n\n\tget size(): number {\n\t\treturn this.#base.size\n\t}\n\n\tget maxSize(): number {\n\t\treturn this.#base.maxSize\n\t}\n\n\tpeek(key: K): V | undefined {\n\t\treturn this.#base.peek(key)\n\t}\n\n\tresize(maxSize: number): void {\n\t\tthis.#base.resize(maxSize)\n\t}\n\n\t*entriesAscending(): IterableIterator<[K, V]> {\n\t\tyield* this.#base.entriesAscending()\n\t}\n\n\t*entriesDescending(): IterableIterator<[K, V]> {\n\t\tyield* this.#base.entriesDescending()\n\t}\n\n\t// Delegate Map iterator methods to the internal Map instance\n\tentries() {\n\t\treturn this.#map.entries()\n\t}\n\n\tkeys() {\n\t\treturn this.#map.keys()\n\t}\n\n\tvalues() {\n\t\treturn this.#map.values()\n\t}\n\n\t[Symbol.iterator]() {\n\t\treturn this.#map[Symbol.iterator]()\n\t}\n\n\tget [Symbol.toStringTag](): string {\n\t\treturn \"QuickLRU\"\n\t}\n}\n\n// Define the cache options schema\nexport interface StatementCacheOptions {\n\tmaxSize: number\n\tmaxAge?: number\n}\n\nexport interface StatementCache {\n\tget(sql: string): StatementSync | undefined\n\tset(sql: string, statement: StatementSync): void\n\tdelete(sql: string): void\n\tclear(): void\n\tgetStats(): CacheStats\n}\n\nexport interface CacheStats {\n\thits: number\n\tmisses: number\n\tsize: number\n\tevictions: number\n\ttotalQueries: number\n}\n\nclass EnhancedStatementCache implements StatementCache {\n\tprivate cache: QuickLRU<string, StatementSync>\n\tprivate stats: CacheStats = {\n\t\thits: 0,\n\t\tmisses: 0,\n\t\tsize: 0,\n\t\tevictions: 0,\n\t\ttotalQueries: 0,\n\t}\n\n\tconstructor(options: StatementCacheOptions) {\n\t\tthis.cache = new QuickLRU({\n\t\t\tmaxSize: options.maxSize,\n\t\t\tmaxAge: options.maxAge,\n\t\t\tonEviction: () => {\n\t\t\t\tthis.stats.evictions++\n\t\t\t},\n\t\t})\n\t}\n\n\tget(sql: string): StatementSync | undefined {\n\t\tthis.stats.totalQueries++\n\t\tconst stmt = this.cache.get(sql)\n\t\tif (stmt) {\n\t\t\tthis.stats.hits++\n\t\t} else {\n\t\t\tthis.stats.misses++\n\t\t}\n\t\treturn stmt\n\t}\n\n\tset(sql: string, statement: StatementSync): void {\n\t\tthis.cache.set(sql, statement)\n\t\tthis.stats.size = this.cache.size\n\t}\n\n\tdelete(sql: string): void {\n\t\tthis.cache.delete(sql)\n\t\tthis.stats.size = this.cache.size\n\t}\n\n\tclear(): void {\n\t\tthis.cache.clear()\n\t\tthis.stats.size = 0\n\t}\n\n\tgetStats(): CacheStats {\n\t\treturn { ...this.stats }\n\t}\n}\n\nexport function createStatementCache(options?: StatementCacheOptions) {\n\tif (!options) {\n\t\treturn undefined\n\t}\n\n\tif (options.maxSize <= 0) {\n\t\t// Add runtime validation since we removed schema validation\n\t\tthrow new TypeError(\"maxSize must be a positive number\")\n\t}\n\n\tif (\n\t\toptions.maxAge !== undefined &&\n\t\t(options.maxAge <= 0)\n\t) {\n\t\tthrow new TypeError(\"maxAge must be a positive number\")\n\t}\n\n\treturn new EnhancedStatementCache(options)\n}\n","// Copyright 2025 Takin Profit. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\nexport enum LogLevel {\n\tERROR = \"error\",\n\tWARN = \"warn\",\n\tINFO = \"info\",\n\tDEBUG = \"debug\",\n\tTRACE = \"trace\",\n}\n\nexport type LogFn = (message: string, ...meta: unknown[]) => void\n\nexport interface Logger {\n\terror: LogFn\n\twarn: LogFn\n\tinfo: LogFn\n\tdebug: LogFn\n\ttrace: LogFn\n}\n\nexport interface LogMessage {\n\tlevel: LogLevel\n\tmessage: string\n\ttimestamp: string\n\tmeta?: unknown[]\n}\n\n/**\n * Default logger that writes to console with timestamps\n */\nexport class ConsoleLogger implements Logger {\n\t#minLevel: LogLevel\n\n\tconstructor(minLevel: LogLevel = LogLevel.INFO) {\n\t\tthis.#minLevel = minLevel\n\t}\n\n\t#shouldLog(level: LogLevel): boolean {\n\t\tconst levels = Object.values(LogLevel)\n\t\treturn levels.indexOf(level) <= levels.indexOf(this.#minLevel)\n\t}\n\n\t#formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\tmeta: unknown[] = []\n\t): LogMessage {\n\t\treturn {\n\t\t\tlevel,\n\t\t\tmessage,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmeta: meta.length > 0 ? meta : undefined,\n\t\t}\n\t}\n\n\terror(message: string, ...meta: unknown[]): void {\n\t\tif (this.#shouldLog(LogLevel.ERROR)) {\n\t\t\tconsole.error(this.#formatMessage(LogLevel.ERROR, message, meta))\n\t\t}\n\t}\n\n\twarn(message: string, ...meta: unknown[]): void {\n\t\tif (this.#shouldLog(LogLevel.WARN)) {\n\t\t\tconsole.warn(this.#formatMessage(LogLevel.WARN, message, meta))\n\t\t}\n\t}\n\n\tinfo(message: string, ...meta: unknown[]): void {\n\t\tif (this.#shouldLog(LogLevel.INFO)) {\n\t\t\tconsole.info(this.#formatMessage(LogLevel.INFO, message, meta))\n\t\t}\n\t}\n\n\tdebug(message: string, ...meta: unknown[]): void {\n\t\tif (this.#shouldLog(LogLevel.DEBUG)) {\n\t\t\tconsole.debug(this.#formatMessage(LogLevel.DEBUG, message, meta))\n\t\t}\n\t}\n\n\ttrace(message: string, ...meta: unknown[]): void {\n\t\tif (this.#shouldLog(LogLevel.TRACE)) {\n\t\t\tconsole.trace(this.#formatMessage(LogLevel.TRACE, message, meta))\n\t\t}\n\t}\n}\n\n/**\n * No-op logger that does nothing\n */\nexport class NoopLogger implements Logger {\n\terror = () => {}\n\twarn = () => {}\n\tinfo = () => {}\n\tdebug = () => {}\n\ttrace = () => {}\n}\n","import { NodeSqliteError, SqlitePrimaryResultCode } from \"#errors.js\"\nimport type { DataRow } from \"#types.js\"\nimport { validationErr, type ValidationError } from \"#validate.js\"\n\ntype IndexColumn<T extends DataRow> =\n\t`${keyof T & string}${\"\" | \" ASC\" | \" DESC\"}${\"\" | ` COLLATE ${string}`}`\n\ntype WhereExpr = `WHERE ${string}`\n\ntype IndexName = `${string}_idx` | `idx_${string}`\n\ntype IndexOptions = {\n\tunique?: boolean\n\tifNotExists?: boolean\n}\n\nexport type IndexDef<T extends DataRow> = {\n\tname: IndexName\n\ttableName: string\n\tcolumns: IndexColumn<T>[] | [`${keyof T & string}(${string})`]\n\twhere?: WhereExpr\n\toptions?: IndexOptions\n}\n\nexport function validateIndexDef<T extends DataRow>(\n\tdef: IndexDef<T>\n): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tif (!def.name.endsWith(\"_idx\") && !def.name.startsWith(\"idx_\")) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Index name must end with '_idx' or start with 'idx_'\",\n\t\t\t\tpath: \"name\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (!def.tableName) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Table name is required\",\n\t\t\t\tpath: \"tableName\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (!Array.isArray(def.columns) || def.columns.length === 0) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"Index must have at least one column\",\n\t\t\t\tpath: \"columns\",\n\t\t\t})\n\t\t)\n\t}\n\n\tif (def.where && !def.where.startsWith(\"WHERE \")) {\n\t\terrors.push(\n\t\t\tvalidationErr({\n\t\t\t\tmsg: \"WHERE clause must start with 'WHERE'\",\n\t\t\t\tpath: \"where\",\n\t\t\t})\n\t\t)\n\t}\n\n\treturn errors\n}\n\nexport function buildIndexStatement<T extends DataRow>(\n\tdef: IndexDef<T>\n): string {\n\tconst errors = validateIndexDef(def)\n\tif (errors.length > 0) {\n\t\tthrow new NodeSqliteError(\n\t\t\t\"ERR_SQLITE_INDEX\",\n\t\t\tSqlitePrimaryResultCode.SQLITE_ERROR,\n\t\t\t\"Invalid index definition\",\n\t\t\terrors.map(e => e.message).join(\"\\n\"),\n\t\t\tundefined\n\t\t)\n\t}\n\n\t// Extract expressions from column definitions\n\tconst columns = def.columns\n\t\t.map(col => {\n\t\t\tconst match =\n\t\t\t\ttypeof col === \"string\" ? col.match(/^(\\w+)\\((.*)\\)$/) : null\n\t\t\treturn match ? match[2] : col\n\t\t})\n\t\t.join(\", \")\n\n\tconst unique = def.options?.unique ? \"UNIQUE \" : \"\"\n\tconst ifNotExists = def.options?.ifNotExists ? \"IF NOT EXISTS \" : \"\"\n\tconst where = def.where ? `\\n  ${def.where}` : \"\"\n\n\treturn `CREATE ${unique}INDEX ${ifNotExists}${def.name} ON ${def.tableName} (${columns})${where}`\n}\n\nexport function createIndexName(\n\tprefix: string,\n\t...columns: string[]\n): IndexName {\n\treturn `idx_${prefix}_${columns.join(\"_\")}` as IndexName\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;ACwEO,IAAMA,uBAAuB;EACnC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGM,IAAMC,oBAAoB;EAAC;EAAO;;AAclC,SAASC,WAAWC,OAAc;AACxC,SACC,OAAOA,UAAU,YACjBA,UAAU,QACVC,OAAOC,OAAOF,OAAO,MAAA,KACpBA,MAAmBG,SAAS;AAE/B;AAPgBJ;;;AC7FT,IAAKK,0BAAAA,0BAAAA,0BAAAA;;;;;;;;;;;;;;;;;;;;;SAAAA;;AA0BL,IAAMC,mBAAmB;EAC/B,CAAA,CAAA,GAAqC;EACrC,CAAA,CAAA,GAAwC;EACxC,CAAA,CAAA,GAA2C;EAC3C,CAAA,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B,KAAKzB,IAAAA;MACf;AAEA,WAAK,QAAQ1B,MAAM,gCAAA;IACpB,SAASc,OAAO;AACf,WAAK,QAAQA,MAAM,+BAA+B;QAAEA;MAAM,CAAA;AAC1D,UAAI8D,kBAAkB9D,KAAAA,GAAQ;AAC7B,YACCC,gBAAgBkD,eAAenD,KAAAA,EAAO+D,qBAAoB,MAC1D7D,wBAAwB8D,aACvB;AACD,gBAAM,IAAI/D,gBACT,mBACAC,wBAAwB8D,aACxB,gDACA,4DACAhE,KAAAA;QAEF;AACA,cAAMA;MACP;AACA,YAAMC,gBAAgBkD,eACrBnD,iBAAiBI,QAAQJ,QAAQ,IAAII,MAAMiB,OAAOrB,KAAAA,CAAAA,CAAAA;IAEpD;EACD;AACD;","names":["COMPARISON_OPERATORS","LOGICAL_OPERATORS","isRawValue","value","Object","hasOwn","type","SqlitePrimaryResultCode","SqliteErrorTypes","NodeSqliteError","Error","errorType","code","errcode","errstr","message","originalError","name","Object","setPrototypeOf","prototype","getPrimaryResultCode","toString","fromNodeSqlite","error","isNodeSqliteError","validationErr","msg","message","path","_validation_error","validateKeyList","key","validationErr","msg","keys","split","map","k","trim","length","validateForeignKeys","value","errors","foreignKey","push","references","path","table","Array","isArray","columns","onDelete","isValidAction","onUpdate","deferrable","isValidDeferrable","action","includes","status","buildForeignKeyStatement","foreignKeys","length","map","fk","key","keyColumns","split","k","trim","refColumns","references","columns","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","undefined","sql","join","table","onDelete","onUpdate","deferrable","columnRegex","validateSchema","value","validationErr","msg","errors","columns","key","def","Object","entries","push","path","test","trim","fks","$$foreignKeys","Array","isArray","forEach","fk","idx","fkErrors","validateForeignKeys","map","err","buildSchema","columns","errors","validateSchema","length","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","map","e","message","join","undefined","columnDefs","Object","entries","filter","key","name","def","String","trim","foreignKeys","$$foreignKeys","buildForeignKeyStatement","allDefs","validateWhereClause","where","errors","validateSingleCondition","Array","isArray","length","LOGICAL_OPERATORS","includes","column","operator","value","COMPARISON_OPERATORS","isRawValue","validationErr","msg","path","i","condition","push","conditionErrors","pattern","RegExp","join","test","buildWhereStatement","params","paramOps","matches","match","sql","parameterOperators","conditions","map","part","replace","validateSqlContext","value","errors","Array","isArray","validationErr","msg","context","key","valueErrors","validateInsertOrSetOptions","length","push","map","err","path","setErrors","validateSetOptions","every","item","forEach","col","index","isValidColumnSpec","whereErrors","validateWhereClause","orderErrors","validateOrderByClause","columnErrors","validateSchema","config","isJsonColumns","seen","Set","duplicates","filter","has","add","join","includes","endsWith","jsonColumns","batch","isValidValueType","direction","Object","entries","startsWith","isSqlContext","validateContextCombination","contexts","seenClauses","uniqueClauses","incompatiblePairs","Map","clause","undefined","clauseKey","type","message","clauses","incompatibleWith","get","otherClause","buildColsStatement","cols","Array","isArray","seen","Set","filter","col","colStr","String","has","add","map","endsWith","columnName","slice","join","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","undefined","validateSetOptions","value","errors","length","validationErr","msg","path","config","jsonColumns","every","entries","Object","key","val","isRawValue","push","startsWith","paramPart","isJsonColumns","buildSqlComponents","options","params","Array","isArray","Set","items","from","length","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","undefined","firstItem","columns","Object","keys","config","jsonColumns","placeholderRows","map","_","rowIndex","rowPlaceholders","col","has","join","paramOps","flatMap","placeholders","parameterOperators","isMulti","itemCount","k","batch","op","match","column","push","endsWith","buildValuesStatement","values","result","sql","buildOrderByStatement","orderBy","Object","keys","length","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","undefined","orderClauses","entries","map","column","direction","join","LIMIT_REPLACE_NODE","CIRCULAR_REPLACE_NODE","arr","replacerStack","defaultOptions","depthLimit","Number","MAX_SAFE_INTEGER","edgesLimit","stringify","obj","replacer","spacer","options","decirc","undefined","res","length","JSON","replaceGetterValues","_","part","pop","Object","defineProperty","setReplace","replace","val","k","parent","propertyDescriptor","getOwnPropertyDescriptor","get","configurable","value","push","edgeIndex","stack","depth","i","Array","isArray","keys","key","compareFunction","a","b","deterministicStringify","tmp","deterministicDecirc","toJSON","sort","v","splice","call","stable","stableStringify","buildSetStatement","set","params","errors","validateSetOptions","length","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","map","e","message","join","undefined","columns","Object","keys","paramOps","k","sql","col","i","parameterOperators","Array","isArray","config","jsonColumns","Set","setPairs","has","entries","value","isRawValue","push","endsWith","paramName","slice","toSupportedValue","value","Uint8Array","stringify","String","raw","strings","values","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","undefined","type","Sql","paramOperators","Set","formatterConfig","params","contextOperators","op","add","indent","reservedWordCase","linesBetweenQueries","language","sql","sqlFormatter","format","context","parts","columns","push","buildColsStatement","schema","buildSchema","length","result","buildValuesStatement","parameterOperators","set","buildSetStatement","setParts","split","slice","map","p","where","buildWhereStatement","orderBy","buildOrderByStatement","limit","offset","returning","Array","isArray","isJsonColumns","config","jsonColumns","allColumns","Object","keys","returningColumns","from","col","has","join","i","isXStatementSync","isSqlContext","isRawValue","endsWith","paramName","substring","hasJsonColumns","includes","operators","contextOp","namedParams","items","index","row","key","entries","operator","prepare","contexts","filter","validationErrors","flatMap","validateSqlContext","SQLITE_MISUSE","e","message","combinationErrors","validateContextCombination","looksLikeJSON","data","trim","startsWith","parseJsonColumns","JSON","parse","createErrorMessage","error","paramStr","item1","item2","Error","hasOwn","__x_statement_sync__","createXStatementSync","props","currentStatement","all","stmt","build","results","get","run","iter","baseIterator","iterate","next","done","Symbol","iterator","rows","sourceSQL","expandedSQL","PragmaDefaults","development","journalMode","synchronous","cacheSize","tempStore","mmapSize","lockingMode","busyTimeout","foreignKeys","walAutocheckpoint","trustedSchema","testing","production","getPragmaStatements","config","statements","push","undefined","LRUBase","Map","options","maxSize","TypeError","maxAge","Number","POSITIVE_INFINITY","onEviction","cache","oldCache","key","item","value","expiry","Date","now","delete","deleted","undefined","get","set","has","peek","clear","resize","items","removeCount","length","slice","entriesDescending","cacheItems","i","oldItems","entriesAscending","size","oldCacheSize","keys","Math","min","QuickLRU","forEach","callbackfn","thisArg","entries","values","Symbol","iterator","toStringTag","EnhancedStatementCache","stats","hits","misses","evictions","totalQueries","sql","stmt","statement","getStats","createStatementCache","LogLevel","ConsoleLogger","minLevel","level","levels","Object","values","indexOf","message","meta","timestamp","Date","toISOString","length","undefined","error","console","warn","info","debug","trace","NoopLogger","validateIndexDef","def","errors","name","endsWith","startsWith","push","validationErr","msg","path","tableName","Array","isArray","columns","length","where","buildIndexStatement","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_ERROR","map","e","message","join","undefined","col","match","unique","options","ifNotExists","DB","options","location","logger","NoopLogger","format","debug","DatabaseSync","open","allowExtension","info","environment","defaultPragmas","PragmaDefaults","customPragmas","pragma","finalPragmas","statementCache","createStatementCache","maxSize","error","NodeSqliteError","SqlitePrimaryResultCode","SQLITE_CANTOPEN","Error","undefined","nativeDb","prepareStatement","sql","cached","get","trace","stmt","prepare","set","message","toLowerCase","includes","warn","clear","SQLITE_ERROR","String","strings","params","builder","Sql","paramOperators","formatterConfig","createXStatementSync","build","finalParams","namedParams","hasJsonColumns","createIndex","def","stringify","buildIndexStatement","exec","backup","filename","restore","SQLITE_MISUSE","accessSync","close","tempBackup","join","tmpdir","Date","now","renameSync","unlinkSync","fromNodeSqlite","getCacheStats","getStats","clearStatementCache","pragmas","optimize","shrinkMemory","walCheckpoint","config","statements","getPragmaStatements","isNodeSqliteError","getPrimaryResultCode","SQLITE_BUSY"]}