@happyvertical/sql 0.80.6 → 0.81.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -0
- package/dist/chunks/{schema-manager-a8RlxIE2.js → alter-utils-D7NGXZi0.js} +190 -2
- package/dist/chunks/alter-utils-D7NGXZi0.js.map +1 -0
- package/dist/chunks/{duckdb-D_Wu36JL.js → duckdb-pKOTggPW.js} +44 -20
- package/dist/chunks/duckdb-pKOTggPW.js.map +1 -0
- package/dist/chunks/{sqlite-B4ussRTS.js → sqlite-dbhMszEJ.js} +57 -23
- package/dist/chunks/sqlite-dbhMszEJ.js.map +1 -0
- package/dist/chunks/{sqlite-native-BgiF4301.js → sqlite-native-DrNaIJRO.js} +68 -20
- package/dist/chunks/sqlite-native-DrNaIJRO.js.map +1 -0
- package/dist/chunks/types-uVFHgaSU.js +133 -0
- package/dist/chunks/types-uVFHgaSU.js.map +1 -0
- package/dist/duckdb.d.ts.map +1 -1
- package/dist/index.js +638 -747
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts.map +1 -1
- package/dist/postgres.d.ts.map +1 -1
- package/dist/shared/alter-utils.d.ts +48 -0
- package/dist/shared/alter-utils.d.ts.map +1 -1
- package/dist/shared/transaction-lock.d.ts +54 -0
- package/dist/shared/transaction-lock.d.ts.map +1 -0
- package/dist/shared/types.d.ts +69 -7
- package/dist/shared/types.d.ts.map +1 -1
- package/dist/sqlite-native.d.ts.map +1 -1
- package/dist/sqlite.d.ts +20 -0
- package/dist/sqlite.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/chunks/alter-utils-K7tiuj5L.js +0 -135
- package/dist/chunks/alter-utils-K7tiuj5L.js.map +0 -1
- package/dist/chunks/duckdb-D_Wu36JL.js.map +0 -1
- package/dist/chunks/schema-manager-a8RlxIE2.js.map +0 -1
- package/dist/chunks/sqlite-B4ussRTS.js.map +0 -1
- package/dist/chunks/sqlite-native-BgiF4301.js.map +0 -1
package/README.md
CHANGED
|
@@ -136,6 +136,47 @@ try {
|
|
|
136
136
|
}
|
|
137
137
|
```
|
|
138
138
|
|
|
139
|
+
On the single-connection adapters — SQLite (both the LibSQL and native paths),
|
|
140
|
+
DuckDB and JSON — a connection can only be in one transaction at a time, so
|
|
141
|
+
**transactions are serialized per connection**: an overlapping `transaction()`
|
|
142
|
+
waits for the one in progress instead of interleaving with it. A call that waits
|
|
143
|
+
longer than `transactionQueueTimeout` (30s by default) rejects rather than
|
|
144
|
+
stalling indefinitely.
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
const db = await getDatabase({
|
|
148
|
+
type: 'sqlite',
|
|
149
|
+
url: 'file:app.db',
|
|
150
|
+
transactionQueueTimeout: 60_000, // longer transactions, or heavier bursts
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Two consequences worth knowing:
|
|
155
|
+
|
|
156
|
+
- A `beginTransaction()` handle owns the connection until you commit or roll it
|
|
157
|
+
back. End it in a `finally` — a handle that is never ended holds the
|
|
158
|
+
connection for the life of the process, and every later transaction on it
|
|
159
|
+
fails with the queue timeout.
|
|
160
|
+
- Inside a `transaction()` callback, use the `tx` you were handed. Calling a
|
|
161
|
+
top-level `db.*` method that opens its own transaction makes it wait on the
|
|
162
|
+
connection its own caller is holding.
|
|
163
|
+
|
|
164
|
+
PostgreSQL pools its connections, so transactions there run concurrently and
|
|
165
|
+
never queue.
|
|
166
|
+
|
|
167
|
+
### Identifiers
|
|
168
|
+
|
|
169
|
+
Table and column names are interpolated into SQL rather than bound as
|
|
170
|
+
parameters, so every CRUD method validates them: an identifier must match
|
|
171
|
+
`[a-zA-Z_][a-zA-Z0-9_]*`. Qualified names (`schema.table`), quoted names and
|
|
172
|
+
anything containing whitespace are rejected. Values are always parameterized and
|
|
173
|
+
are unaffected.
|
|
174
|
+
|
|
175
|
+
Note that `buildWhere` treats a condition key carrying an explicit operator
|
|
176
|
+
suffix (`'price >'`, `'name like'`) as SQL expression text and does **not**
|
|
177
|
+
validate it. That is deliberate, and it means those keys must stay
|
|
178
|
+
developer-controlled — never build them from request input.
|
|
179
|
+
|
|
139
180
|
### WHERE Clause Building
|
|
140
181
|
|
|
141
182
|
```typescript
|
|
@@ -445,6 +445,194 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
|
|
|
445
445
|
}
|
|
446
446
|
};
|
|
447
447
|
//#endregion
|
|
448
|
-
|
|
448
|
+
//#region src/shared/alter-utils.ts
|
|
449
|
+
/**
|
|
450
|
+
* Generates an ALTER TABLE ADD COLUMN statement
|
|
451
|
+
*
|
|
452
|
+
* @param table - Table name
|
|
453
|
+
* @param column - Column definition with name
|
|
454
|
+
* @param dialect - Database dialect
|
|
455
|
+
* @returns SQL statement string
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* ```typescript
|
|
459
|
+
* const sql = generateAddColumnStatement('users', {
|
|
460
|
+
* name: 'email',
|
|
461
|
+
* type: 'TEXT',
|
|
462
|
+
* unique: true,
|
|
463
|
+
* notNull: false
|
|
464
|
+
* }, 'sqlite');
|
|
465
|
+
* // Returns: "ALTER TABLE users ADD COLUMN email TEXT UNIQUE"
|
|
466
|
+
* ```
|
|
467
|
+
*/
|
|
468
|
+
function generateAddColumnStatement(table, column, _dialect) {
|
|
469
|
+
const parts = [column.name, column.type];
|
|
470
|
+
if (column.primaryKey) parts.push("PRIMARY KEY");
|
|
471
|
+
if (column.notNull) parts.push("NOT NULL");
|
|
472
|
+
if (column.unique) parts.push("UNIQUE");
|
|
473
|
+
if (column.defaultValue !== void 0) {
|
|
474
|
+
const defaultClause = generateDefaultClause(column.type, column.defaultValue);
|
|
475
|
+
parts.push(`DEFAULT ${defaultClause}`);
|
|
476
|
+
}
|
|
477
|
+
if (column.check) parts.push(`CHECK (${column.check})`);
|
|
478
|
+
if (column.foreignKey) {
|
|
479
|
+
const fk = column.foreignKey;
|
|
480
|
+
const fkParts = [`REFERENCES ${fk.table}(${fk.column})`];
|
|
481
|
+
if (fk.onDelete) fkParts.push(`ON DELETE ${fk.onDelete}`);
|
|
482
|
+
if (fk.onUpdate) fkParts.push(`ON UPDATE ${fk.onUpdate}`);
|
|
483
|
+
parts.push(fkParts.join(" "));
|
|
484
|
+
}
|
|
485
|
+
return `ALTER TABLE ${table} ADD COLUMN ${parts.join(" ")}`;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Generates a DEFAULT clause for a column definition
|
|
489
|
+
*
|
|
490
|
+
* Handles proper formatting and escaping of default values based on column type.
|
|
491
|
+
*
|
|
492
|
+
* @param columnType - SQL column type (TEXT, INTEGER, BOOLEAN, etc.)
|
|
493
|
+
* @param defaultValue - Default value to format
|
|
494
|
+
* @returns Formatted default value string
|
|
495
|
+
*
|
|
496
|
+
* @example
|
|
497
|
+
* ```typescript
|
|
498
|
+
* generateDefaultClause('TEXT', 'hello'); // Returns: "'hello'"
|
|
499
|
+
* generateDefaultClause('INTEGER', 42); // Returns: "42"
|
|
500
|
+
* generateDefaultClause('BOOLEAN', true); // Returns: "true"
|
|
501
|
+
* generateDefaultClause('TEXT', null); // Returns: "NULL"
|
|
502
|
+
* ```
|
|
503
|
+
*/
|
|
504
|
+
function generateDefaultClause(columnType, defaultValue) {
|
|
505
|
+
if (defaultValue === null) return "NULL";
|
|
506
|
+
const typeUpper = columnType.toUpperCase();
|
|
507
|
+
if (typeUpper.includes("TEXT") || typeUpper.includes("CHAR") || typeUpper.includes("VARCHAR") || typeUpper.includes("STRING")) {
|
|
508
|
+
if (defaultValue === "") return "''";
|
|
509
|
+
return `'${String(defaultValue).replace(/'/g, "''")}'`;
|
|
510
|
+
}
|
|
511
|
+
if (typeUpper.includes("BOOL")) return defaultValue ? "true" : "false";
|
|
512
|
+
if (typeUpper.includes("INT") || typeUpper.includes("REAL") || typeUpper.includes("FLOAT") || typeUpper.includes("DOUBLE") || typeUpper.includes("NUMERIC") || typeUpper.includes("DECIMAL")) return String(defaultValue);
|
|
513
|
+
if (typeUpper.includes("JSON")) {
|
|
514
|
+
if (typeof defaultValue === "string") return `'${defaultValue.replace(/'/g, "''")}'`;
|
|
515
|
+
return `'${JSON.stringify(defaultValue).replace(/'/g, "''")}'`;
|
|
516
|
+
}
|
|
517
|
+
if (typeUpper.includes("DATE") || typeUpper.includes("TIME") || typeUpper.includes("TIMESTAMP")) {
|
|
518
|
+
if (defaultValue instanceof Date) return `'${defaultValue.toISOString()}'`;
|
|
519
|
+
return `'${String(defaultValue).replace(/'/g, "''")}'`;
|
|
520
|
+
}
|
|
521
|
+
if (typeof defaultValue === "string") return `'${defaultValue.replace(/'/g, "''")}'`;
|
|
522
|
+
return String(defaultValue);
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Generates a CREATE INDEX statement
|
|
526
|
+
*
|
|
527
|
+
* @param table - Table name
|
|
528
|
+
* @param index - Index definition
|
|
529
|
+
* @returns SQL CREATE INDEX statement
|
|
530
|
+
*
|
|
531
|
+
* @example
|
|
532
|
+
* ```typescript
|
|
533
|
+
* const sql = generateCreateIndexStatement('users', {
|
|
534
|
+
* name: 'idx_users_email',
|
|
535
|
+
* columns: ['email'],
|
|
536
|
+
* unique: true
|
|
537
|
+
* });
|
|
538
|
+
* // Returns: "CREATE UNIQUE INDEX idx_users_email ON users (email)"
|
|
539
|
+
* ```
|
|
540
|
+
*/
|
|
541
|
+
function generateCreateIndexStatement(table, index) {
|
|
542
|
+
const parts = ["CREATE"];
|
|
543
|
+
if (index.unique) parts.push("UNIQUE");
|
|
544
|
+
parts.push("INDEX");
|
|
545
|
+
parts.push(index.name);
|
|
546
|
+
parts.push(`ON ${table}`);
|
|
547
|
+
const columns = index.columns.join(", ");
|
|
548
|
+
parts.push(`(${columns})`);
|
|
549
|
+
if (index.where) parts.push(`WHERE ${index.where}`);
|
|
550
|
+
return parts.join(" ");
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Validates a table name to prevent SQL injection
|
|
554
|
+
*
|
|
555
|
+
* @param tableName - Table name to validate
|
|
556
|
+
* @throws Error if table name contains invalid characters
|
|
557
|
+
*/
|
|
558
|
+
function validateTableName(tableName) {
|
|
559
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) throw new Error(`Invalid table name: ${tableName}. Table names must start with a letter or underscore and contain only alphanumeric characters and underscores.`);
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Validates a column name to prevent SQL injection
|
|
563
|
+
*
|
|
564
|
+
* @param columnName - Column name to validate
|
|
565
|
+
* @throws Error if column name contains invalid characters
|
|
566
|
+
*/
|
|
567
|
+
function validateColumnName(columnName) {
|
|
568
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(columnName)) throw new Error(`Invalid column name: ${columnName}. Column names must start with a letter or underscore and contain only alphanumeric characters and underscores.`);
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Validates every identifier in a column list to prevent SQL injection
|
|
572
|
+
*
|
|
573
|
+
* Column names reaching the CRUD methods come from `Object.keys(data)` and the
|
|
574
|
+
* caller's `conflictColumns`, both of which are interpolated into SQL. They are
|
|
575
|
+
* checked rather than quoted deliberately: the accepted shape has no character
|
|
576
|
+
* that can end an identifier, so quoting adds nothing to safety, and quoting a
|
|
577
|
+
* name on PostgreSQL makes it case-sensitive, which would silently change which
|
|
578
|
+
* column an existing caller addresses.
|
|
579
|
+
*
|
|
580
|
+
* @param columnNames - Column names to validate
|
|
581
|
+
* @throws Error if any column name contains invalid characters
|
|
582
|
+
*/
|
|
583
|
+
function validateColumnNames(columnNames) {
|
|
584
|
+
for (const columnName of columnNames) validateColumnName(columnName);
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Escapes an identifier for interpolation inside double quotes
|
|
588
|
+
*
|
|
589
|
+
* For the positions that already quote the identifier — the DuckDB and JSON
|
|
590
|
+
* upsert statements, which quote to match their schema generator — quoting is
|
|
591
|
+
* what makes the identifier safe, so the only thing that has to be handled is
|
|
592
|
+
* a quote character inside the name. Doubling it is the SQL escape.
|
|
593
|
+
*
|
|
594
|
+
* This is deliberately more permissive than {@link validateColumnName}: those
|
|
595
|
+
* adapters accept column names that are not plain identifiers (`Full Name`,
|
|
596
|
+
* `user-id`, `2024_total`), which matters most for the JSON adapter, whose
|
|
597
|
+
* columns come straight from the keys of whatever JSON it was pointed at.
|
|
598
|
+
* Rejecting them would break working code to fix an injection that quoting
|
|
599
|
+
* already prevents.
|
|
600
|
+
*
|
|
601
|
+
* @param identifier - Identifier to place inside double quotes
|
|
602
|
+
* @returns The identifier with embedded quotes doubled
|
|
603
|
+
* @throws Error if the identifier is empty or contains a NUL byte
|
|
604
|
+
*/
|
|
605
|
+
function escapeQuotedIdentifier(identifier) {
|
|
606
|
+
if (identifier.length === 0 || identifier.includes("\0")) throw new Error(`Invalid column name: ${JSON.stringify(identifier)}. Column names must be non-empty and must not contain a NUL byte.`);
|
|
607
|
+
return identifier.replaceAll("\"", "\"\"");
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Escapes a value for interpolation inside a single-quoted SQL string literal
|
|
611
|
+
*
|
|
612
|
+
* The DuckDB-backed adapters read JSON through `read_json_auto('<path>')`, and
|
|
613
|
+
* a file path is not something an identifier validator can check — paths
|
|
614
|
+
* legitimately contain spaces, dots and, on Linux and macOS, quotes. Doubling
|
|
615
|
+
* the quote is the SQL escape, and it is what keeps a file named `x'.json`
|
|
616
|
+
* from ending the literal and starting a statement.
|
|
617
|
+
*
|
|
618
|
+
* @param value - Value to place inside single quotes
|
|
619
|
+
* @returns The value with embedded single quotes doubled
|
|
620
|
+
* @throws Error if the value contains a NUL byte
|
|
621
|
+
*/
|
|
622
|
+
function escapeStringLiteral(value) {
|
|
623
|
+
if (value.includes("\0")) throw new Error(`Invalid SQL string literal: ${JSON.stringify(value)}. Values must not contain a NUL byte.`);
|
|
624
|
+
return value.replaceAll("'", "''");
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Validates an index name to prevent SQL injection
|
|
628
|
+
*
|
|
629
|
+
* @param indexName - Index name to validate
|
|
630
|
+
* @throws Error if index name contains invalid characters
|
|
631
|
+
*/
|
|
632
|
+
function validateIndexName(indexName) {
|
|
633
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)) throw new Error(`Invalid index name: ${indexName}. Index names must start with a letter or underscore and contain only alphanumeric characters and underscores.`);
|
|
634
|
+
}
|
|
635
|
+
//#endregion
|
|
636
|
+
export { validateColumnName as a, validateTableName as c, formatDbError as d, parseConditionKey as f, generateCreateIndexStatement as i, DatabaseSchemaManager as l, escapeStringLiteral as n, validateColumnNames as o, generateAddColumnStatement as r, validateIndexName as s, escapeQuotedIdentifier as t, buildWhere as u };
|
|
449
637
|
|
|
450
|
-
//# sourceMappingURL=
|
|
638
|
+
//# sourceMappingURL=alter-utils-D7NGXZi0.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alter-utils-D7NGXZi0.js","names":[],"sources":["../../src/shared/utils.ts","../../src/schema-manager.ts","../../src/shared/alter-utils.ts"],"sourcesContent":["/**\n * Shared SQL utilities that work in both browser and Node.js environments\n */\n\nimport type { WhereClause } from './types.js';\n\n/**\n * Formats a database error to include all relevant details\n *\n * Database drivers often include additional properties beyond just `message`:\n * - PostgreSQL: code, detail, hint, severity\n * - DuckDB: may include additional context\n * - SQLite/LibSQL: may include errno, code\n *\n * This function extracts all available error properties to provide\n * better debugging information.\n *\n * @param error - The caught error object\n * @returns Formatted error string with all available error details\n */\nexport function formatDbError(error: unknown): string {\n const dbError = error as {\n message?: string;\n code?: string;\n detail?: string;\n hint?: string;\n severity?: string;\n errno?: number;\n cause?: unknown;\n };\n\n const parts: string[] = [];\n\n if (dbError.message) parts.push(dbError.message);\n if (dbError.code) parts.push(`code=${dbError.code}`);\n if (dbError.detail) parts.push(`detail=${dbError.detail}`);\n if (dbError.hint) parts.push(`hint=${dbError.hint}`);\n if (dbError.severity) parts.push(`severity=${dbError.severity}`);\n if (dbError.errno !== undefined) parts.push(`errno=${dbError.errno}`);\n\n return parts.length > 0 ? parts.join(', ') : String(error);\n}\n\n/**\n * Map of valid SQL operators for use in WHERE clauses\n */\nconst VALID_OPERATORS = {\n '=': '=',\n '>': '>',\n '>=': '>=',\n '<': '<',\n '<=': '<=',\n '!=': '!=',\n like: 'LIKE',\n in: 'IN',\n 'not in': 'NOT IN',\n} as const;\n\nfunction isSimpleSqlIdentifier(field: string): boolean {\n return /^[a-zA-Z0-9_.]+$/.test(field);\n}\n\nexport function parseConditionKey(fullKey: string): {\n field: string;\n operator: string;\n explicitOperator: boolean;\n} {\n const trimmed = fullKey.trim();\n const lower = trimmed.toLowerCase();\n const operators = ['not in', 'like', 'in', '!=', '>=', '<=', '>', '<', '='];\n\n for (const operator of operators) {\n if (lower.endsWith(` ${operator}`)) {\n return {\n field: trimmed.slice(0, -(operator.length + 1)).trim(),\n operator,\n explicitOperator: true,\n };\n }\n }\n\n return { field: trimmed, operator: '=', explicitOperator: false };\n}\n\n/**\n * SQL adapter type for adapter-specific query generation\n */\nexport type SqlAdapterType = 'sqlite' | 'postgres' | 'duckdb' | 'json';\n\n/**\n * Builds a single condition for a WHERE clause\n * @internal\n */\nconst buildCondition = (\n fullKey: string,\n value: any,\n currIndex: { value: number },\n adapterType?: SqlAdapterType,\n): { sql: string; values: any[] } => {\n const { field, operator, explicitOperator } = parseConditionKey(fullKey);\n if (!explicitOperator && !isSimpleSqlIdentifier(field)) {\n throw new Error(`Invalid SQL identifier: ${field}`);\n }\n const sqlOperator =\n VALID_OPERATORS[operator as keyof typeof VALID_OPERATORS] || '=';\n const values: any[] = [];\n\n let sql: string;\n\n if (value === null) {\n sql = `${field} IS ${sqlOperator === '=' ? 'NULL' : 'NOT NULL'}`;\n } else if (\n (sqlOperator === 'IN' || sqlOperator === 'NOT IN') &&\n Array.isArray(value)\n ) {\n if (value.length === 0) {\n throw new Error(`${sqlOperator} requires at least one value`);\n }\n const placeholders = value.map(() => `$${currIndex.value++}`).join(', ');\n sql = `${field} ${sqlOperator} (${placeholders})`;\n values.push(...value);\n } else if (value instanceof Date) {\n // DuckDB/JSON need CAST to TIMESTAMP to prevent ANY type inference (issue #540)\n // SQLite/PostgreSQL handle ISO strings natively without CAST\n const needsCast = adapterType === 'duckdb' || adapterType === 'json';\n if (needsCast) {\n sql = `${field} ${sqlOperator} CAST($${currIndex.value++} AS TIMESTAMP)`;\n } else {\n sql = `${field} ${sqlOperator} $${currIndex.value++}`;\n }\n values.push(value.toISOString());\n } else {\n sql = `${field} ${sqlOperator} $${currIndex.value++}`;\n values.push(value);\n }\n\n return { sql, values };\n};\n\n/**\n * Builds a SQL WHERE clause with parameterized values and flexible operators\n *\n * @param where - Conditions as object (AND-only) or 2D array (OR/AND compound)\n * @param startIndex - Starting index for parameter numbering (default: 1)\n * @param adapterType - Database adapter type. Controls Date handling:\n * - `'duckdb'` / `'json'`: Wraps Date values in `CAST($N AS TIMESTAMP)` to\n * prevent DuckDB ANY-type inference issues.\n * - `'sqlite'` / `'postgres'` / `undefined`: Passes ISO strings directly\n * (these adapters handle ISO timestamp strings natively).\n *\n * Keys with explicit operator suffixes are treated as SQL field/expression\n * text. Keep those keys developer-controlled; do not pass end-user input as a\n * condition key.\n *\n * @returns Object containing the SQL clause and array of values\n *\n * @example Basic Usage (Object format - AND-only):\n * ```typescript\n * buildWhere({\n * 'status': 'active', // equals operator is default\n * 'price >': 100, // greater than\n * 'stock <=': 5, // less than or equal\n * 'category in': ['A', 'B'], // IN clause for arrays\n * 'name like': '%shirt%' // LIKE for pattern matching\n * });\n * ```\n *\n * @example 2D Array Format (OR/AND compound logic):\n * ```typescript\n * // WHERE (status = 'active' AND price > 100) OR (status = 'pending' AND priority = 'high')\n * buildWhere([\n * [{ status: 'active' }, { 'price >': 100 }],\n * [{ status: 'pending' }, { priority: 'high' }]\n * ]);\n * ```\n *\n * @example NULL Handling:\n * ```typescript\n * buildWhere({\n * 'deleted_at': null, // becomes \"deleted_at IS NULL\"\n * 'updated_at !=': null, // becomes \"updated_at IS NOT NULL\"\n * 'status': 'active' // regular comparison\n * });\n * ```\n *\n * @example Common Patterns:\n * ```typescript\n * // Price range\n * buildWhere({\n * 'price >=': 10,\n * 'price <': 100\n * });\n *\n * // Date filtering\n * buildWhere({\n * 'created_at >': startDate,\n * 'created_at <=': endDate,\n * 'deleted_at': null\n * });\n *\n * // Search with LIKE\n * buildWhere({\n * 'title like': '%search%',\n * 'description like': '%search%',\n * 'status': 'published'\n * });\n *\n * // Multiple values with IN\n * buildWhere({\n * 'role in': ['admin', 'editor'],\n * 'active': true,\n * 'last_login !=': null\n * });\n * ```\n *\n * The function handles:\n * - Standard comparisons (=, >, >=, <, <=, !=)\n * - NULL checks (IS NULL, IS NOT NULL)\n * - IN clauses for arrays\n * - LIKE for pattern matching\n * - Object format: Multiple conditions combined with AND\n * - 2D array format: Inner arrays ANDed, outer array ORed\n */\nexport const buildWhere = (\n where: WhereClause,\n startIndex = 1,\n adapterType?: SqlAdapterType,\n) => {\n let sql = '';\n const values: any[] = [];\n const currIndex = { value: startIndex };\n\n // Handle 2D array format for OR/AND compound logic\n if (Array.isArray(where)) {\n if (where.length === 0) {\n return { sql: '', values: [] };\n }\n\n const orGroups: string[] = [];\n\n for (const andGroup of where) {\n if (!Array.isArray(andGroup) || andGroup.length === 0) {\n continue;\n }\n\n const andConditions: string[] = [];\n\n for (const conditionObj of andGroup) {\n for (const [fullKey, value] of Object.entries(conditionObj)) {\n const result = buildCondition(fullKey, value, currIndex, adapterType);\n andConditions.push(result.sql);\n values.push(...result.values);\n }\n }\n\n if (andConditions.length > 0) {\n // Wrap AND group in parentheses\n orGroups.push(`(${andConditions.join(' AND ')})`);\n }\n }\n\n if (orGroups.length > 0) {\n sql = `WHERE ${orGroups.join(' OR ')}`;\n }\n\n return { sql, values };\n }\n\n // Handle object format (original behavior - AND-only)\n if (where && Object.keys(where).length > 0) {\n sql = 'WHERE ';\n for (const [fullKey, value] of Object.entries(where)) {\n const result = buildCondition(fullKey, value, currIndex, adapterType);\n\n if (sql !== 'WHERE ') {\n sql += ' AND ';\n }\n\n sql += result.sql;\n values.push(...result.values);\n }\n }\n\n return { sql, values };\n};\n","/**\n * Schema management and dependency resolution for JSON manifests\n * Moved from SMRT package to SQL package for proper separation of concerns\n */\n\nimport type {\n DatabaseInterface,\n IndexDefinition,\n SchemaDefinition,\n SchemaInitializationOptions,\n TriggerDefinition,\n} from './shared/types.js';\n\n/**\n * Result returned by DatabaseSchemaManager.initializeSchemas()\n *\n * Contains the list of schemas that were successfully initialized,\n * any that were skipped (already up to date), errors encountered,\n * and the total execution time in milliseconds.\n */\nexport interface SchemaInitializationResult {\n initialized: string[];\n skipped: string[];\n errors: Array<{ schema: string; error: string }>;\n executionTime: number;\n}\n\n/**\n * Manages schema initialization from JSON manifests with dependency resolution\n *\n * Handles topological sorting of schema dependencies, table creation,\n * index and trigger setup, and version tracking to avoid redundant re-initialization.\n */\nexport class DatabaseSchemaManager {\n private static initializationLock = new Map<string, Promise<void>>();\n private initializedSchemas = new Set<string>();\n private schemaVersions = new Map<string, string>();\n\n /**\n * Initializes database schemas from a JSON manifest with dependency resolution\n *\n * Schemas are topologically sorted by their declared dependencies and\n * initialized in order. Supports legacy raw-SQL schemas via the `schema` option,\n * JSON manifests via the `manifest` option, and schema overrides for extending\n * base schemas.\n *\n * @param db - Database interface to execute DDL against\n * @param options - Schema initialization options (manifest, overrides, force, debug)\n * @returns Result with lists of initialized/skipped schemas, errors, and execution time\n */\n async initializeSchemas(\n db: DatabaseInterface,\n options: SchemaInitializationOptions,\n ): Promise<SchemaInitializationResult> {\n const startTime = Date.now();\n const result: SchemaInitializationResult = {\n initialized: [],\n skipped: [],\n errors: [],\n executionTime: 0,\n };\n\n try {\n let schemas: Record<string, SchemaDefinition> = {};\n\n // Handle legacy SQL schema format\n if (options.schema) {\n console.log(\n '[schema] Legacy SQL schema provided, converting to manifest format',\n );\n // For legacy support, we'll still use the original syncSchema method\n if (db.syncSchema) {\n await db.syncSchema(options.schema);\n result.initialized.push('legacy-sql');\n }\n result.executionTime = Date.now() - startTime;\n return result;\n }\n\n // Handle JSON manifest format\n if (options.manifest) {\n schemas = { ...options.manifest.schemas };\n }\n\n // Apply schema overrides\n if (options.overrides) {\n schemas = { ...schemas, ...options.overrides };\n }\n\n if (Object.keys(schemas).length === 0) {\n console.warn('[schema] No schemas provided for initialization');\n result.executionTime = Date.now() - startTime;\n return result;\n }\n\n // Build dependency graph\n const dependencyGraph = this.buildDependencyGraph(schemas);\n\n // Get initialization order\n const initializationOrder = this.resolveDependencies(dependencyGraph);\n\n if (options.debug) {\n console.log('[schema] Initialization order:', initializationOrder);\n }\n\n // Initialize schemas in dependency order\n for (const schemaName of initializationOrder) {\n const schema = schemas[schemaName];\n if (!schema) continue;\n\n try {\n await this.initializeSchema(db, schemaName, schema, {\n force: options.force,\n debug: options.debug,\n });\n result.initialized.push(schemaName);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n result.errors.push({ schema: schemaName, error: errorMessage });\n\n if (options.debug) {\n console.error(\n `[schema] Failed to initialize ${schemaName}:`,\n error,\n );\n }\n }\n }\n\n result.executionTime = Date.now() - startTime;\n\n if (options.debug) {\n console.log('[schema] Initialization complete:', result);\n }\n\n return result;\n } catch (error) {\n result.executionTime = Date.now() - startTime;\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n result.errors.push({\n schema: 'dependency-resolution',\n error: errorMessage,\n });\n return result;\n }\n }\n\n /**\n * Initialize a single schema\n */\n private async initializeSchema(\n db: DatabaseInterface,\n schemaName: string,\n schema: SchemaDefinition,\n options: { force?: boolean; debug?: boolean },\n ): Promise<void> {\n const { tableName, version } = schema;\n const lockKey = `${schemaName}:${tableName}`;\n\n // Check if already being initialized\n if (DatabaseSchemaManager.initializationLock.has(lockKey)) {\n await DatabaseSchemaManager.initializationLock.get(lockKey);\n return;\n }\n\n // Check if already initialized and up to date\n if (!options.force && this.isSchemaUpToDate(schemaName, version)) {\n if (options.debug) {\n console.log(`[schema] Skipping ${schemaName} - already up to date`);\n }\n return;\n }\n\n // Create initialization promise\n const initPromise = this.performSchemaInitialization(\n db,\n schemaName,\n schema,\n options,\n );\n DatabaseSchemaManager.initializationLock.set(lockKey, initPromise);\n\n try {\n await initPromise;\n this.markSchemaInitialized(schemaName, version);\n } finally {\n DatabaseSchemaManager.initializationLock.delete(lockKey);\n }\n }\n\n /**\n * Perform the actual schema initialization\n */\n private async performSchemaInitialization(\n db: DatabaseInterface,\n schemaName: string,\n schema: SchemaDefinition,\n options: { force?: boolean; debug?: boolean },\n ): Promise<void> {\n const { tableName, columns, indexes, triggers } = schema;\n\n if (options.debug) {\n console.log(`[schema] Initializing ${schemaName} (${tableName})`);\n }\n\n // Check if table exists\n const tableExists = await db.tableExists(tableName);\n\n if (!tableExists) {\n // Create table\n await this.createTable(db, schema);\n\n // Create indexes\n for (const index of indexes) {\n await this.createIndex(db, tableName, index);\n }\n\n // Create triggers\n for (const trigger of triggers) {\n await this.createTrigger(db, trigger);\n }\n } else if (options.force) {\n // Recreate table if forced\n await db.query(`DROP TABLE IF EXISTS ${tableName}`);\n await this.createTable(db, schema);\n\n for (const index of indexes) {\n await this.createIndex(db, tableName, index);\n }\n\n for (const trigger of triggers) {\n await this.createTrigger(db, trigger);\n }\n } else {\n // Table exists, check for schema changes\n await this.updateSchemaIfNeeded(db, schema);\n }\n }\n\n /**\n * Create table from schema definition\n */\n private async createTable(\n db: DatabaseInterface,\n schema: SchemaDefinition,\n ): Promise<void> {\n const { tableName, columns, foreignKeys } = schema;\n\n const columnDefinitions: string[] = [];\n\n // Add column definitions\n for (const [columnName, columnDef] of Object.entries(columns)) {\n let def = `${columnName} ${columnDef.type}`;\n\n if (columnDef.primaryKey) def += ' PRIMARY KEY';\n if (columnDef.unique && !columnDef.primaryKey) def += ' UNIQUE';\n if (columnDef.notNull) def += ' NOT NULL';\n if (columnDef.defaultValue !== undefined) {\n def += ` DEFAULT ${columnDef.defaultValue}`;\n }\n if (columnDef.check) def += ` CHECK (${columnDef.check})`;\n\n columnDefinitions.push(def);\n }\n\n // Add foreign key constraints\n for (const fk of foreignKeys) {\n let fkDef = `FOREIGN KEY (${fk.column}) REFERENCES ${fk.referencesTable}(${fk.referencesColumn})`;\n if (fk.onDelete) fkDef += ` ON DELETE ${fk.onDelete}`;\n if (fk.onUpdate) fkDef += ` ON UPDATE ${fk.onUpdate}`;\n columnDefinitions.push(fkDef);\n }\n\n const createTableSQL = `CREATE TABLE ${tableName} (\\n ${columnDefinitions.join(',\\n ')}\\n)`;\n await db.query(createTableSQL);\n }\n\n /**\n * Create index from definition\n */\n private async createIndex(\n db: DatabaseInterface,\n tableName: string,\n index: IndexDefinition,\n ): Promise<void> {\n const uniqueClause = index.unique ? 'UNIQUE ' : '';\n const whereClause = index.where ? ` WHERE ${index.where}` : '';\n const createIndexSQL = `CREATE ${uniqueClause}INDEX ${index.name} ON ${tableName} (${index.columns.join(', ')})${whereClause}`;\n\n await db.query(createIndexSQL);\n }\n\n /**\n * Create trigger from definition\n */\n private async createTrigger(\n db: DatabaseInterface,\n trigger: TriggerDefinition,\n ): Promise<void> {\n const conditionClause = trigger.condition\n ? ` WHEN ${trigger.condition}`\n : '';\n const createTriggerSQL = `CREATE TRIGGER ${trigger.name} ${trigger.when} ${trigger.event} ON ${trigger.table}${conditionClause} BEGIN ${trigger.body} END`;\n\n await db.query(createTriggerSQL);\n }\n\n /**\n * Update schema if changes are detected\n */\n private async updateSchemaIfNeeded(\n _db: DatabaseInterface,\n schema: SchemaDefinition,\n ): Promise<void> {\n // For now, just log that update is needed\n // In future, implement ALTER TABLE logic\n console.log(\n `[schema] Schema update logic not yet implemented for ${schema.tableName}`,\n );\n }\n\n /**\n * Build dependency graph from schemas\n */\n private buildDependencyGraph(\n schemas: Record<string, SchemaDefinition>,\n ): Map<string, string[]> {\n const graph = new Map<string, string[]>();\n\n for (const [schemaName, schema] of Object.entries(schemas)) {\n const dependencies = schema.dependencies.filter((dep) =>\n Object.values(schemas).some((s) => s.tableName === dep),\n );\n graph.set(\n schemaName,\n dependencies.map(\n (dep) =>\n Object.entries(schemas).find(\n ([_, s]) => s.tableName === dep,\n )?.[0] || dep,\n ),\n );\n }\n\n return graph;\n }\n\n /**\n * Resolve dependencies using topological sort\n */\n private resolveDependencies(graph: Map<string, string[]>): string[] {\n const resolved: string[] = [];\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n const visit = (node: string) => {\n if (visiting.has(node)) {\n throw new Error(`Circular dependency detected involving ${node}`);\n }\n if (visited.has(node)) return;\n\n visiting.add(node);\n const dependencies = graph.get(node) || [];\n\n for (const dep of dependencies) {\n if (graph.has(dep)) {\n visit(dep);\n }\n }\n\n visiting.delete(node);\n visited.add(node);\n resolved.push(node);\n };\n\n for (const node of graph.keys()) {\n if (!visited.has(node)) {\n visit(node);\n }\n }\n\n return resolved;\n }\n\n /**\n * Check if schema is up to date\n */\n private isSchemaUpToDate(schemaName: string, version: string): boolean {\n return (\n this.initializedSchemas.has(schemaName) &&\n this.schemaVersions.get(schemaName) === version\n );\n }\n\n /**\n * Mark schema as initialized\n */\n private markSchemaInitialized(schemaName: string, version: string): void {\n this.initializedSchemas.add(schemaName);\n this.schemaVersions.set(schemaName, version);\n }\n\n /**\n * Reset initialization state (for testing)\n */\n reset(): void {\n this.initializedSchemas.clear();\n this.schemaVersions.clear();\n DatabaseSchemaManager.initializationLock.clear();\n }\n}\n","/**\n * Shared utilities for ALTER TABLE operations\n *\n * Provides database-agnostic utilities for generating ALTER TABLE statements,\n * handling column definitions, and creating indexes.\n */\n\nimport type { ColumnDefinitionWithName, IndexDefinition } from './types.js';\n\n/**\n * Database dialect type for SQL generation\n */\nexport type DatabaseDialect = 'sqlite' | 'postgres' | 'duckdb';\n\n/**\n * Generates an ALTER TABLE ADD COLUMN statement\n *\n * @param table - Table name\n * @param column - Column definition with name\n * @param dialect - Database dialect\n * @returns SQL statement string\n *\n * @example\n * ```typescript\n * const sql = generateAddColumnStatement('users', {\n * name: 'email',\n * type: 'TEXT',\n * unique: true,\n * notNull: false\n * }, 'sqlite');\n * // Returns: \"ALTER TABLE users ADD COLUMN email TEXT UNIQUE\"\n * ```\n */\nexport function generateAddColumnStatement(\n table: string,\n column: ColumnDefinitionWithName,\n _dialect: DatabaseDialect,\n): string {\n const parts: string[] = [column.name, column.type];\n\n // Primary key\n if (column.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // NOT NULL constraint\n if (column.notNull) {\n parts.push('NOT NULL');\n }\n\n // UNIQUE constraint\n if (column.unique) {\n parts.push('UNIQUE');\n }\n\n // DEFAULT clause\n if (column.defaultValue !== undefined) {\n const defaultClause = generateDefaultClause(\n column.type,\n column.defaultValue,\n );\n parts.push(`DEFAULT ${defaultClause}`);\n }\n\n // CHECK constraint\n if (column.check) {\n parts.push(`CHECK (${column.check})`);\n }\n\n // Foreign key (inline for some databases)\n if (column.foreignKey) {\n const fk = column.foreignKey;\n const fkParts = [`REFERENCES ${fk.table}(${fk.column})`];\n\n if (fk.onDelete) {\n fkParts.push(`ON DELETE ${fk.onDelete}`);\n }\n\n if (fk.onUpdate) {\n fkParts.push(`ON UPDATE ${fk.onUpdate}`);\n }\n\n parts.push(fkParts.join(' '));\n }\n\n const columnDef = parts.join(' ');\n return `ALTER TABLE ${table} ADD COLUMN ${columnDef}`;\n}\n\n/**\n * Generates a DEFAULT clause for a column definition\n *\n * Handles proper formatting and escaping of default values based on column type.\n *\n * @param columnType - SQL column type (TEXT, INTEGER, BOOLEAN, etc.)\n * @param defaultValue - Default value to format\n * @returns Formatted default value string\n *\n * @example\n * ```typescript\n * generateDefaultClause('TEXT', 'hello'); // Returns: \"'hello'\"\n * generateDefaultClause('INTEGER', 42); // Returns: \"42\"\n * generateDefaultClause('BOOLEAN', true); // Returns: \"true\"\n * generateDefaultClause('TEXT', null); // Returns: \"NULL\"\n * ```\n */\nexport function generateDefaultClause(\n columnType: string,\n defaultValue: any,\n): string {\n if (defaultValue === null) {\n return 'NULL';\n }\n\n const typeUpper = columnType.toUpperCase();\n\n // String types - need quotes\n if (\n typeUpper.includes('TEXT') ||\n typeUpper.includes('CHAR') ||\n typeUpper.includes('VARCHAR') ||\n typeUpper.includes('STRING')\n ) {\n // Handle empty strings\n if (defaultValue === '') {\n return \"''\";\n }\n // Escape single quotes\n const escaped = String(defaultValue).replace(/'/g, \"''\");\n return `'${escaped}'`;\n }\n\n // Boolean types\n if (typeUpper.includes('BOOL')) {\n return defaultValue ? 'true' : 'false';\n }\n\n // Numeric types - no quotes\n if (\n typeUpper.includes('INT') ||\n typeUpper.includes('REAL') ||\n typeUpper.includes('FLOAT') ||\n typeUpper.includes('DOUBLE') ||\n typeUpper.includes('NUMERIC') ||\n typeUpper.includes('DECIMAL')\n ) {\n return String(defaultValue);\n }\n\n // JSON types\n if (typeUpper.includes('JSON')) {\n if (typeof defaultValue === 'string') {\n return `'${defaultValue.replace(/'/g, \"''\")}'`;\n }\n return `'${JSON.stringify(defaultValue).replace(/'/g, \"''\")}'`;\n }\n\n // Date/timestamp types\n if (\n typeUpper.includes('DATE') ||\n typeUpper.includes('TIME') ||\n typeUpper.includes('TIMESTAMP')\n ) {\n if (defaultValue instanceof Date) {\n return `'${defaultValue.toISOString()}'`;\n }\n return `'${String(defaultValue).replace(/'/g, \"''\")}'`;\n }\n\n // Default: treat as string\n if (typeof defaultValue === 'string') {\n return `'${defaultValue.replace(/'/g, \"''\")}'`;\n }\n\n return String(defaultValue);\n}\n\n/**\n * Generates a CREATE INDEX statement\n *\n * @param table - Table name\n * @param index - Index definition\n * @returns SQL CREATE INDEX statement\n *\n * @example\n * ```typescript\n * const sql = generateCreateIndexStatement('users', {\n * name: 'idx_users_email',\n * columns: ['email'],\n * unique: true\n * });\n * // Returns: \"CREATE UNIQUE INDEX idx_users_email ON users (email)\"\n * ```\n */\nexport function generateCreateIndexStatement(\n table: string,\n index: IndexDefinition,\n): string {\n const parts: string[] = ['CREATE'];\n\n // UNIQUE modifier\n if (index.unique) {\n parts.push('UNIQUE');\n }\n\n parts.push('INDEX');\n\n // Index name\n parts.push(index.name);\n\n // ON table\n parts.push(`ON ${table}`);\n\n // Column list\n const columns = index.columns.join(', ');\n parts.push(`(${columns})`);\n\n // WHERE clause (partial index)\n if (index.where) {\n parts.push(`WHERE ${index.where}`);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Validates a table name to prevent SQL injection\n *\n * @param tableName - Table name to validate\n * @throws Error if table name contains invalid characters\n */\nexport function validateTableName(tableName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {\n throw new Error(\n `Invalid table name: ${tableName}. Table names must start with a letter or underscore and contain only alphanumeric characters and underscores.`,\n );\n }\n}\n\n/**\n * Validates a column name to prevent SQL injection\n *\n * @param columnName - Column name to validate\n * @throws Error if column name contains invalid characters\n */\nexport function validateColumnName(columnName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(columnName)) {\n throw new Error(\n `Invalid column name: ${columnName}. Column names must start with a letter or underscore and contain only alphanumeric characters and underscores.`,\n );\n }\n}\n\n/**\n * Validates every identifier in a column list to prevent SQL injection\n *\n * Column names reaching the CRUD methods come from `Object.keys(data)` and the\n * caller's `conflictColumns`, both of which are interpolated into SQL. They are\n * checked rather than quoted deliberately: the accepted shape has no character\n * that can end an identifier, so quoting adds nothing to safety, and quoting a\n * name on PostgreSQL makes it case-sensitive, which would silently change which\n * column an existing caller addresses.\n *\n * @param columnNames - Column names to validate\n * @throws Error if any column name contains invalid characters\n */\nexport function validateColumnNames(columnNames: string[]): void {\n for (const columnName of columnNames) {\n validateColumnName(columnName);\n }\n}\n\n/**\n * Escapes an identifier for interpolation inside double quotes\n *\n * For the positions that already quote the identifier — the DuckDB and JSON\n * upsert statements, which quote to match their schema generator — quoting is\n * what makes the identifier safe, so the only thing that has to be handled is\n * a quote character inside the name. Doubling it is the SQL escape.\n *\n * This is deliberately more permissive than {@link validateColumnName}: those\n * adapters accept column names that are not plain identifiers (`Full Name`,\n * `user-id`, `2024_total`), which matters most for the JSON adapter, whose\n * columns come straight from the keys of whatever JSON it was pointed at.\n * Rejecting them would break working code to fix an injection that quoting\n * already prevents.\n *\n * @param identifier - Identifier to place inside double quotes\n * @returns The identifier with embedded quotes doubled\n * @throws Error if the identifier is empty or contains a NUL byte\n */\nexport function escapeQuotedIdentifier(identifier: string): string {\n if (identifier.length === 0 || identifier.includes('\\0')) {\n throw new Error(\n `Invalid column name: ${JSON.stringify(identifier)}. Column names must be non-empty and must not contain a NUL byte.`,\n );\n }\n return identifier.replaceAll('\"', '\"\"');\n}\n\n/**\n * Escapes a value for interpolation inside a single-quoted SQL string literal\n *\n * The DuckDB-backed adapters read JSON through `read_json_auto('<path>')`, and\n * a file path is not something an identifier validator can check — paths\n * legitimately contain spaces, dots and, on Linux and macOS, quotes. Doubling\n * the quote is the SQL escape, and it is what keeps a file named `x'.json`\n * from ending the literal and starting a statement.\n *\n * @param value - Value to place inside single quotes\n * @returns The value with embedded single quotes doubled\n * @throws Error if the value contains a NUL byte\n */\nexport function escapeStringLiteral(value: string): string {\n if (value.includes('\\0')) {\n throw new Error(\n `Invalid SQL string literal: ${JSON.stringify(value)}. Values must not contain a NUL byte.`,\n );\n }\n return value.replaceAll(\"'\", \"''\");\n}\n\n/**\n * Validates an index name to prevent SQL injection\n *\n * @param indexName - Index name to validate\n * @throws Error if index name contains invalid characters\n */\nexport function validateIndexName(indexName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)) {\n throw new Error(\n `Invalid index name: ${indexName}. Index names must start with a letter or underscore and contain only alphanumeric characters and underscores.`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,SAAgB,cAAc,OAAwB;CACpD,MAAM,UAAU;CAUhB,MAAM,QAAkB,CAAC;CAEzB,IAAI,QAAQ,SAAS,MAAM,KAAK,QAAQ,OAAO;CAC/C,IAAI,QAAQ,MAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;CACnD,IAAI,QAA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AAgB,oBAAoB,aAA6B;CAC/D,KAAK,MAAM,cAAc,aACvB,mBAAmB,UAAU;AAEjC;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,YAA4B;CACjE,IAAI,WAAW,WAAW,KAAK,WAAW,SAAS,IAAI,GACrD,MAAM,IAAI,MACR,wBAAwB,KAAK,UAAU,UAAU,EAAE,kEACrD;CAEF,OAAO,WAAW,WAAW,MAAK,MAAI;AACxC;;;;;;;;;;;;;;AAeA,SAAgB,oBAAoB,OAAuB;CACzD,IAAI,MAAM,SAAS,IAAI,GACrB,MAAM,IAAI,MACR,+BAA+B,KAAK,UAAU,KAAK,EAAE,sCACvD;CAEF,OAAO,MAAM,WAAW,KAAK,IAAI;AACnC;;;;;;;AAQA,SAAgB,kBAAkB,WAAyB;CACzD,IAAI,CAAC,2BAA2B,KAAK,SAAS,GAC5C,MAAM,IAAI,MACR,uBAAuB,UAAU,+GACnC;AAEJ"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { n as
|
|
1
|
+
import { a as validateColumnName, c as validateTableName, d as formatDbError, i as generateCreateIndexStatement, l as DatabaseSchemaManager, n as escapeStringLiteral, o as validateColumnNames, r as generateAddColumnStatement, s as validateIndexName, t as escapeQuotedIdentifier, u as buildWhere } from "./alter-utils-D7NGXZi0.js";
|
|
2
2
|
import { t as convertUniqueIndexesToInlineConstraints } from "./duckdb-schema-utils-B-XBP8QF.js";
|
|
3
|
-
import {
|
|
4
|
-
import { NestedTransactionError, resolveSchemas } from "../index.js";
|
|
3
|
+
import { n as resolveSchemas, r as createTransactionLock, t as NestedTransactionError } from "./types-uVFHgaSU.js";
|
|
5
4
|
import { DatabaseError } from "@happyvertical/utils";
|
|
6
5
|
import { readdir } from "node:fs/promises";
|
|
7
6
|
import { basename, extname, join } from "node:path";
|
|
@@ -105,7 +104,8 @@ async function registerJSONFiles(connection, dataDir) {
|
|
|
105
104
|
for (const file of jsonFiles) {
|
|
106
105
|
const filePath = join(dataDir, file);
|
|
107
106
|
const tableName = basename(file, ".json");
|
|
108
|
-
|
|
107
|
+
validateTableName(tableName);
|
|
108
|
+
await connection.run(`CREATE OR REPLACE VIEW ${tableName} AS SELECT * FROM read_json('${escapeStringLiteral(filePath)}', auto_detect=true, format='auto', timestampformat='iso', dateformat='iso')`);
|
|
109
109
|
}
|
|
110
110
|
} catch (error) {
|
|
111
111
|
if (error.code !== "ENOENT") throw new DatabaseError(`Failed to register JSON files from ${dataDir}`, {
|
|
@@ -154,6 +154,7 @@ async function getDatabase(options = {}) {
|
|
|
154
154
|
const writeStrategy = options.writeStrategy || "none";
|
|
155
155
|
const dataDir = options.dataDir || "./data";
|
|
156
156
|
const url = resolveDuckDBUrl(options.url || ":memory:");
|
|
157
|
+
const connectionLock = createTransactionLock("duckdb", options.transactionQueueTimeout);
|
|
157
158
|
/**
|
|
158
159
|
* Inserts one or more records into a table
|
|
159
160
|
*
|
|
@@ -163,12 +164,14 @@ async function getDatabase(options = {}) {
|
|
|
163
164
|
* @throws Error if the insert operation fails
|
|
164
165
|
*/
|
|
165
166
|
const insert = async (table, data) => {
|
|
167
|
+
validateTableName(table);
|
|
166
168
|
const records = Array.isArray(data) ? data : [data];
|
|
167
169
|
if (records.length === 0) return {
|
|
168
170
|
operation: "insert",
|
|
169
171
|
affected: 0
|
|
170
172
|
};
|
|
171
173
|
const keys = Object.keys(records[0]);
|
|
174
|
+
validateColumnNames(keys);
|
|
172
175
|
const values = [];
|
|
173
176
|
let paramIdx = 1;
|
|
174
177
|
const placeholders = records.map((record) => {
|
|
@@ -220,6 +223,7 @@ async function getDatabase(options = {}) {
|
|
|
220
223
|
* @throws Error if the query fails
|
|
221
224
|
*/
|
|
222
225
|
const get = async (table, where) => {
|
|
226
|
+
validateTableName(table);
|
|
223
227
|
const { sql: whereClause, values } = buildWhere(where, 1, "duckdb");
|
|
224
228
|
const sql = `SELECT * FROM ${table} ${whereClause} LIMIT 1`;
|
|
225
229
|
try {
|
|
@@ -243,6 +247,7 @@ async function getDatabase(options = {}) {
|
|
|
243
247
|
* @throws Error if the query fails
|
|
244
248
|
*/
|
|
245
249
|
const list = async (table, where) => {
|
|
250
|
+
validateTableName(table);
|
|
246
251
|
const { sql: whereClause, values } = buildWhere(where, 1, "duckdb");
|
|
247
252
|
const sql = `SELECT * FROM ${table} ${whereClause}`;
|
|
248
253
|
try {
|
|
@@ -266,7 +271,9 @@ async function getDatabase(options = {}) {
|
|
|
266
271
|
* @throws Error if the update operation fails
|
|
267
272
|
*/
|
|
268
273
|
const update = async (table, where, data) => {
|
|
274
|
+
validateTableName(table);
|
|
269
275
|
const keys = Object.keys(data);
|
|
276
|
+
validateColumnNames(keys);
|
|
270
277
|
const setClause = keys.map((key, idx) => `${key} = $${idx + 1}`).join(", ");
|
|
271
278
|
const { sql: whereClause, values: whereValues } = buildWhere(where, keys.length + 1, "duckdb");
|
|
272
279
|
const sql = `UPDATE ${table} SET ${setClause} ${whereClause}`;
|
|
@@ -315,7 +322,8 @@ async function getDatabase(options = {}) {
|
|
|
315
322
|
const values = [];
|
|
316
323
|
const paramIdx = { value: 1 };
|
|
317
324
|
const assignments = keys.map((key) => {
|
|
318
|
-
|
|
325
|
+
const valueExpr = buildDuckDBValueExpression(data[key], values, paramIdx);
|
|
326
|
+
return `"${escapeQuotedIdentifier(key)}" = ${valueExpr}`;
|
|
319
327
|
});
|
|
320
328
|
const { sql: whereClause, values: whereValues } = buildWhere(conflictWhere, paramIdx.value, "duckdb");
|
|
321
329
|
const sql = `UPDATE ${table} SET ${assignments.join(", ")} ${whereClause}`;
|
|
@@ -346,6 +354,7 @@ async function getDatabase(options = {}) {
|
|
|
346
354
|
* @throws Error if the upsert operation fails
|
|
347
355
|
*/
|
|
348
356
|
const upsert = async (table, conflictColumns, data, options) => {
|
|
357
|
+
validateTableName(table);
|
|
349
358
|
const missingColumns = conflictColumns.filter((col) => !(col in data));
|
|
350
359
|
if (missingColumns.length > 0) throw new DatabaseError("Conflict columns missing from data", {
|
|
351
360
|
table,
|
|
@@ -409,11 +418,12 @@ async function getDatabase(options = {}) {
|
|
|
409
418
|
paramIdx++;
|
|
410
419
|
}
|
|
411
420
|
}
|
|
412
|
-
const conflict = conflictColumns.map((col) => `"${col}"`).join(", ");
|
|
413
|
-
const quotedKeys = keys.map((key) => `"${key}"`).join(", ");
|
|
421
|
+
const conflict = conflictColumns.map((col) => `"${escapeQuotedIdentifier(col)}"`).join(", ");
|
|
422
|
+
const quotedKeys = keys.map((key) => `"${escapeQuotedIdentifier(key)}"`).join(", ");
|
|
414
423
|
const quotedUpdateSetParts = keys.map((key, i) => {
|
|
415
424
|
const part = updateSetParts[i];
|
|
416
|
-
|
|
425
|
+
const valueExpr = part.substring(part.indexOf("=") + 1).trim();
|
|
426
|
+
return `"${escapeQuotedIdentifier(key)}" = ${valueExpr}`;
|
|
417
427
|
});
|
|
418
428
|
const sql = `INSERT INTO ${table} (${quotedKeys}) VALUES (${placeholders.join(", ")}) ON CONFLICT(${conflict}) DO UPDATE SET ${quotedUpdateSetParts.join(", ")}`;
|
|
419
429
|
try {
|
|
@@ -517,6 +527,7 @@ async function getDatabase(options = {}) {
|
|
|
517
527
|
* @returns Promise resolving to boolean indicating if the table exists
|
|
518
528
|
*/
|
|
519
529
|
const tableExists = async (tableName) => {
|
|
530
|
+
validateTableName(tableName);
|
|
520
531
|
try {
|
|
521
532
|
await connection.runAndReadAll(`SELECT * FROM ${tableName} LIMIT 1`);
|
|
522
533
|
return true;
|
|
@@ -532,6 +543,7 @@ async function getDatabase(options = {}) {
|
|
|
532
543
|
* @param dataDir - Directory to write JSON file
|
|
533
544
|
*/
|
|
534
545
|
const exportTableToJSON = async (connection, table, dataDir) => {
|
|
546
|
+
validateTableName(table);
|
|
535
547
|
const filePath = join(dataDir, `${table}.json`);
|
|
536
548
|
await connection.run(`COPY (SELECT * FROM ${table}) TO '${filePath}' (FORMAT JSON, ARRAY true)`);
|
|
537
549
|
};
|
|
@@ -932,7 +944,7 @@ async function getDatabase(options = {}) {
|
|
|
932
944
|
* @param callback - Function to execute within transaction
|
|
933
945
|
* @returns Promise resolving to callback result
|
|
934
946
|
*/
|
|
935
|
-
const transaction = async (callback) => {
|
|
947
|
+
const transaction = async (callback) => connectionLock.run(async () => {
|
|
936
948
|
try {
|
|
937
949
|
await connection.run("BEGIN TRANSACTION");
|
|
938
950
|
const result = await callback(createTransactionScope());
|
|
@@ -944,7 +956,7 @@ async function getDatabase(options = {}) {
|
|
|
944
956
|
} catch {}
|
|
945
957
|
throw error;
|
|
946
958
|
}
|
|
947
|
-
};
|
|
959
|
+
});
|
|
948
960
|
/**
|
|
949
961
|
* Builds the transaction-scoped interface handed to a transaction callback.
|
|
950
962
|
*
|
|
@@ -993,18 +1005,30 @@ async function getDatabase(options = {}) {
|
|
|
993
1005
|
* @returns Promise resolving to a TransactionHandle
|
|
994
1006
|
*/
|
|
995
1007
|
const beginTransaction = async () => {
|
|
996
|
-
await
|
|
1008
|
+
const releaseConnection = await connectionLock.acquire();
|
|
1009
|
+
try {
|
|
1010
|
+
await connection.run("BEGIN TRANSACTION");
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
releaseConnection();
|
|
1013
|
+
throw error;
|
|
1014
|
+
}
|
|
997
1015
|
let active = true;
|
|
998
|
-
const
|
|
1016
|
+
const end = async (command) => {
|
|
999
1017
|
if (!active) throw new DatabaseError("Transaction already ended", {});
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1018
|
+
try {
|
|
1019
|
+
await connection.run(command);
|
|
1020
|
+
} catch (error) {
|
|
1021
|
+
try {
|
|
1022
|
+
await connection.run("ROLLBACK");
|
|
1023
|
+
} catch {}
|
|
1024
|
+
throw error;
|
|
1025
|
+
} finally {
|
|
1026
|
+
active = false;
|
|
1027
|
+
releaseConnection();
|
|
1028
|
+
}
|
|
1007
1029
|
};
|
|
1030
|
+
const commit = () => end("COMMIT");
|
|
1031
|
+
const rollback = () => end("ROLLBACK");
|
|
1008
1032
|
const isActive = () => active;
|
|
1009
1033
|
return {
|
|
1010
1034
|
...createTransactionScope(),
|
|
@@ -1048,4 +1072,4 @@ async function getDatabase(options = {}) {
|
|
|
1048
1072
|
//#endregion
|
|
1049
1073
|
export { getDatabase };
|
|
1050
1074
|
|
|
1051
|
-
//# sourceMappingURL=duckdb-
|
|
1075
|
+
//# sourceMappingURL=duckdb-pKOTggPW.js.map
|