@happyvertical/sql 0.112.0 → 0.112.2

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.
Files changed (51) hide show
  1. package/AGENT.md +65 -3
  2. package/README.md +146 -19
  3. package/dist/aggregate-expression.d.ts +77 -3
  4. package/dist/aggregate-expression.d.ts.map +1 -1
  5. package/dist/aggregate.d.ts +3 -2
  6. package/dist/aggregate.d.ts.map +1 -1
  7. package/dist/chunks/{duckdb-CpeXdf0i.js → duckdb-DCV4JFWK.js} +23 -52
  8. package/dist/chunks/duckdb-DCV4JFWK.js.map +1 -0
  9. package/dist/chunks/{postgres-dialect-DIy5f5YR.js → postgres-dialect-CaNhva-C.js} +28 -328
  10. package/dist/chunks/postgres-dialect-CaNhva-C.js.map +1 -0
  11. package/dist/chunks/query-Dz0TZ0pY.js +970 -0
  12. package/dist/chunks/query-Dz0TZ0pY.js.map +1 -0
  13. package/dist/chunks/{schema-manager-tfASrb_b.js → schema-manager-psLzQ2yh.js} +471 -18
  14. package/dist/chunks/schema-manager-psLzQ2yh.js.map +1 -0
  15. package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js → sqlite-connection-cache-BycfrYfi.js} +2 -2
  16. package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js.map → sqlite-connection-cache-BycfrYfi.js.map} +1 -1
  17. package/dist/chunks/{sqlite-BdM-nAQD.js → sqlite-nNhv0FMq.js} +22 -22
  18. package/dist/chunks/sqlite-nNhv0FMq.js.map +1 -0
  19. package/dist/chunks/{sqlite-native-DngobJtv.js → sqlite-native-CZGNm9zh.js} +40 -37
  20. package/dist/chunks/sqlite-native-CZGNm9zh.js.map +1 -0
  21. package/dist/doctor.d.ts.map +1 -1
  22. package/dist/duckdb.d.ts.map +1 -1
  23. package/dist/index.d.ts +3 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +44 -77
  26. package/dist/index.js.map +1 -1
  27. package/dist/json.d.ts.map +1 -1
  28. package/dist/pglite.js +2 -2
  29. package/dist/query.d.ts +3 -0
  30. package/dist/query.d.ts.map +1 -1
  31. package/dist/query.js +3 -3
  32. package/dist/schema-manager.d.ts.map +1 -1
  33. package/dist/shared/alter-utils.d.ts +43 -7
  34. package/dist/shared/alter-utils.d.ts.map +1 -1
  35. package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
  36. package/dist/shared/postgres-dialect.d.ts.map +1 -1
  37. package/dist/shared/types.d.ts +1 -0
  38. package/dist/shared/types.d.ts.map +1 -1
  39. package/dist/shared/utils.d.ts +12 -1
  40. package/dist/shared/utils.d.ts.map +1 -1
  41. package/dist/sqlite-native.d.ts.map +1 -1
  42. package/dist/sqlite.d.ts.map +1 -1
  43. package/metadata.json +4 -4
  44. package/package.json +4 -4
  45. package/dist/chunks/duckdb-CpeXdf0i.js.map +0 -1
  46. package/dist/chunks/postgres-dialect-DIy5f5YR.js.map +0 -1
  47. package/dist/chunks/query-i6IIkNhF.js +0 -564
  48. package/dist/chunks/query-i6IIkNhF.js.map +0 -1
  49. package/dist/chunks/schema-manager-tfASrb_b.js.map +0 -1
  50. package/dist/chunks/sqlite-BdM-nAQD.js.map +0 -1
  51. package/dist/chunks/sqlite-native-DngobJtv.js.map +0 -1
@@ -1,4 +1,355 @@
1
1
  import { DatabaseError } from "@happyvertical/utils";
2
+ //#region src/shared/alter-utils.ts
3
+ /**
4
+ * Generates an ALTER TABLE ADD COLUMN statement
5
+ *
6
+ * @param table - Table name
7
+ * @param column - Column definition with name
8
+ * @param dialect - Database dialect
9
+ * @returns SQL statement string
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * const sql = generateAddColumnStatement('users', {
14
+ * name: 'email',
15
+ * type: 'TEXT',
16
+ * unique: true,
17
+ * notNull: false
18
+ * }, 'sqlite');
19
+ * // Returns: "ALTER TABLE users ADD COLUMN email TEXT UNIQUE"
20
+ * ```
21
+ */
22
+ function generateAddColumnStatement(table, column, dialect) {
23
+ const parts = [renderSchemaIdentifier(column.name, dialect, { quoteIdentifiers: true }), column.type];
24
+ if (column.primaryKey) parts.push("PRIMARY KEY");
25
+ if (column.notNull) parts.push("NOT NULL");
26
+ if (column.unique) parts.push("UNIQUE");
27
+ if (column.defaultValue !== void 0) {
28
+ const defaultClause = generateDefaultClause(column.type, column.defaultValue);
29
+ parts.push(`DEFAULT ${defaultClause}`);
30
+ }
31
+ if (column.check) parts.push(`CHECK (${column.check})`);
32
+ if (column.foreignKey) {
33
+ const fk = column.foreignKey;
34
+ const fkParts = [`REFERENCES ${renderSchemaIdentifier(fk.table, dialect, { quoteIdentifiers: true })}(${renderIdentifierList(fk.column, dialect, { quoteIdentifiers: true })})`];
35
+ if (fk.onDelete) fkParts.push(`ON DELETE ${fk.onDelete}`);
36
+ if (fk.onUpdate) fkParts.push(`ON UPDATE ${fk.onUpdate}`);
37
+ parts.push(fkParts.join(" "));
38
+ }
39
+ const columnDef = parts.join(" ");
40
+ return `ALTER TABLE ${renderSchemaIdentifier(table, dialect, { quoteIdentifiers: true })} ADD COLUMN ${columnDef}`;
41
+ }
42
+ /**
43
+ * Generates a DEFAULT clause for a column definition
44
+ *
45
+ * Handles proper formatting and escaping of default values based on column type.
46
+ *
47
+ * @param columnType - SQL column type (TEXT, INTEGER, BOOLEAN, etc.)
48
+ * @param defaultValue - Default value to format
49
+ * @returns Formatted default value string
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * generateDefaultClause('TEXT', 'hello'); // Returns: "'hello'"
54
+ * generateDefaultClause('INTEGER', 42); // Returns: "42"
55
+ * generateDefaultClause('BOOLEAN', true); // Returns: "true"
56
+ * generateDefaultClause('TEXT', null); // Returns: "NULL"
57
+ * ```
58
+ */
59
+ function generateDefaultClause(columnType, defaultValue) {
60
+ if (defaultValue === null) return "NULL";
61
+ const typeUpper = columnType.toUpperCase();
62
+ if (typeUpper.includes("TEXT") || typeUpper.includes("CHAR") || typeUpper.includes("VARCHAR") || typeUpper.includes("STRING")) {
63
+ if (defaultValue === "") return "''";
64
+ return `'${String(defaultValue).replace(/'/g, "''")}'`;
65
+ }
66
+ if (typeUpper.includes("BOOL")) return defaultValue ? "true" : "false";
67
+ if (typeUpper.includes("INT") || typeUpper.includes("REAL") || typeUpper.includes("FLOAT") || typeUpper.includes("DOUBLE") || typeUpper.includes("NUMERIC") || typeUpper.includes("DECIMAL")) return String(defaultValue);
68
+ if (typeUpper.includes("JSON")) {
69
+ if (typeof defaultValue === "string") return `'${defaultValue.replace(/'/g, "''")}'`;
70
+ return `'${JSON.stringify(defaultValue).replace(/'/g, "''")}'`;
71
+ }
72
+ if (typeUpper.includes("DATE") || typeUpper.includes("TIME") || typeUpper.includes("TIMESTAMP")) {
73
+ if (defaultValue instanceof Date) return `'${defaultValue.toISOString()}'`;
74
+ return `'${String(defaultValue).replace(/'/g, "''")}'`;
75
+ }
76
+ if (typeof defaultValue === "string") return `'${defaultValue.replace(/'/g, "''")}'`;
77
+ return String(defaultValue);
78
+ }
79
+ /**
80
+ * Generates a CREATE INDEX statement
81
+ *
82
+ * @param table - Table name
83
+ * @param index - Index definition
84
+ * @returns SQL CREATE INDEX statement
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const sql = generateCreateIndexStatement('users', {
89
+ * name: 'idx_users_email',
90
+ * columns: ['email'],
91
+ * unique: true
92
+ * });
93
+ * // Returns: "CREATE UNIQUE INDEX idx_users_email ON users (email)"
94
+ * ```
95
+ */
96
+ function generateCreateIndexStatement(table, index, dialect) {
97
+ const parts = ["CREATE"];
98
+ if (index.unique) parts.push("UNIQUE");
99
+ parts.push("INDEX");
100
+ parts.push(renderSchemaIdentifier(index.name, dialect, { quoteIdentifiers: true }));
101
+ parts.push(`ON ${renderSchemaIdentifier(table, dialect, { quoteIdentifiers: true })}`);
102
+ const columns = index.columns.map((column) => renderIndexTerm(column, dialect, { quoteIdentifiers: true })).join(", ");
103
+ parts.push(`(${columns})`);
104
+ if (index.where) parts.push(`WHERE ${index.where}`);
105
+ return parts.join(" ");
106
+ }
107
+ /**
108
+ * Validates a table name to prevent SQL injection
109
+ *
110
+ * The argument must be a primitive string. `RegExp.prototype.test` coerces its
111
+ * argument with `toString`, so an object whose `toString` returns a valid name
112
+ * on the call the validator makes and a different one on the call the caller's
113
+ * `${table}` interpolation makes would pass here and then reach SQL. Rejecting
114
+ * non-strings up front closes that gap: the value validated is the value
115
+ * interpolated, because a primitive string cannot observe how many times it is
116
+ * read.
117
+ *
118
+ * @param tableName - Table name to validate
119
+ * @throws Error if the value is not a string or contains invalid characters
120
+ */
121
+ function validateTableName(tableName) {
122
+ if (typeof tableName !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) throw new Error(`Invalid table name: ${tableName}. Table names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`);
123
+ }
124
+ /**
125
+ * Validates a column name to prevent SQL injection
126
+ *
127
+ * Rejects non-strings for the same reason as {@link validateTableName}: a value
128
+ * whose `toString` differs between the validation read and the interpolation
129
+ * read would otherwise slip a different identifier into SQL than the one
130
+ * checked here.
131
+ *
132
+ * @param columnName - Column name to validate
133
+ * @throws Error if the value is not a string or contains invalid characters
134
+ */
135
+ function validateColumnName(columnName) {
136
+ if (typeof columnName !== "string" || !isColumnIdentifier(columnName)) throw new Error(`Invalid column name: ${columnName}. Column names must be a plain identifier starting with a letter or underscore, or an explicitly double-quoted identifier.`);
137
+ }
138
+ /** Branch-base plain-name contract for adapter addIndex (not raw SQL terms). */
139
+ function validatePlainColumnName(columnName) {
140
+ if (typeof columnName !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(columnName)) throw new Error(`Invalid column name: ${columnName}. Column names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`);
141
+ }
142
+ /**
143
+ * Validates every identifier in a column list to prevent SQL injection
144
+ *
145
+ * Column names reaching the CRUD methods come from `Object.keys(data)` and the
146
+ * caller's `conflictColumns`, both of which are interpolated into SQL. The
147
+ * accepted shape has no character that can end an identifier. Adapters may
148
+ * render a validated name bare, or quote it under an adapter-specific contract.
149
+ * PostgreSQL upsert uses {@link quotePostgresColumnName}, which canonicalizes
150
+ * the name before quoting so its established unquoted case-folding semantics
151
+ * do not change.
152
+ *
153
+ * @param columnNames - Column names to validate
154
+ * @throws Error if any column name contains invalid characters
155
+ */
156
+ function validateColumnNames(columnNames) {
157
+ for (const columnName of columnNames) validateColumnName(columnName);
158
+ }
159
+ /**
160
+ * Quotes a validated column name using PostgreSQL's historic case semantics.
161
+ *
162
+ * PostgreSQL folds every unquoted identifier to lowercase. The CRUD API has
163
+ * always accepted mixed-case inputs while rendering them unquoted, so quoting
164
+ * the caller's spelling directly would silently change which physical column
165
+ * is addressed. Validate the existing plain-identifier contract first, then
166
+ * lowercase before quoting: `mixedCase` still addresses `mixedcase`, while a
167
+ * reserved word such as `end` is no longer parsed as SQL syntax.
168
+ *
169
+ * Explicit double-delimited input preserves its physical spelling.
170
+ *
171
+ * @param columnName - Plain or explicitly delimited column name for PostgreSQL
172
+ * @returns A double-quoted identifier, folding only undelimited input
173
+ * @throws Error if the column name is outside the CRUD identifier contract
174
+ */
175
+ function quotePostgresColumnName(columnName) {
176
+ validateColumnName(columnName);
177
+ return renderIdentifier(columnName, "postgres", { quoteIdentifiers: true });
178
+ }
179
+ /**
180
+ * Escapes an identifier for interpolation inside double quotes
181
+ *
182
+ * For the positions that already quote the identifier — the DuckDB and JSON
183
+ * upsert statements, which quote to match their schema generator — quoting is
184
+ * what makes the identifier safe, so the only thing that has to be handled is
185
+ * a quote character inside the name. Doubling it is the SQL escape.
186
+ *
187
+ * This is deliberately more permissive than {@link validateColumnName}: those
188
+ * adapters accept column names that are not plain identifiers (`Full Name`,
189
+ * `user-id`, `2024_total`), which matters most for the JSON adapter, whose
190
+ * columns come straight from the keys of whatever JSON it was pointed at.
191
+ * Rejecting them would break working code to fix an injection that quoting
192
+ * already prevents.
193
+ *
194
+ * @param identifier - Identifier to place inside SQL identifier quotes
195
+ * @param quote - Identifier delimiter (double quote, or SQLite backtick)
196
+ * @returns The identifier with embedded delimiter characters doubled
197
+ * @throws Error if the identifier is empty or contains a NUL byte
198
+ */
199
+ function escapeQuotedIdentifier(identifier, quote = "\"") {
200
+ const value = String(identifier);
201
+ if (value.length === 0 || value.includes("\0")) throw new Error(`Invalid column name: ${JSON.stringify(value)}. Column names must be non-empty and must not contain a NUL byte.`);
202
+ return value.replaceAll(quote, quote + quote);
203
+ }
204
+ /**
205
+ * Escapes a value for interpolation inside a single-quoted SQL string literal
206
+ *
207
+ * The DuckDB-backed adapters read JSON through `read_json_auto('<path>')`, and
208
+ * a file path is not something an identifier validator can check — paths
209
+ * legitimately contain spaces, dots and, on Linux and macOS, quotes. Doubling
210
+ * the quote is the SQL escape, and it is what keeps a file named `x'.json`
211
+ * from ending the literal and starting a statement.
212
+ *
213
+ * @param value - Value to place inside single quotes
214
+ * @returns The value with embedded single quotes doubled
215
+ * @throws Error if the value contains a NUL byte
216
+ */
217
+ function escapeStringLiteral(value) {
218
+ const text = String(value);
219
+ if (text.includes("\0")) throw new Error(`Invalid SQL string literal: ${JSON.stringify(text)}. Values must not contain a NUL byte.`);
220
+ return text.replaceAll("'", "''");
221
+ }
222
+ /**
223
+ * Validates an index name to prevent SQL injection
224
+ *
225
+ * @param indexName - Index name to validate
226
+ * @throws Error if index name contains invalid characters
227
+ */
228
+ function validateIndexName(indexName) {
229
+ if (typeof indexName !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(indexName)) throw new Error(`Invalid index name: ${indexName}. Index names must be a string that starts with a letter or underscore and contains only alphanumeric characters and underscores.`);
230
+ }
231
+ /** Numeric SQL tokens accepted by the original WHERE/aggregate character grammar.
232
+ * This is a bounded compatibility exception, never a general expression channel.
233
+ */
234
+ function isLegacyNumericSqlToken(value) {
235
+ return typeof value === "string" && /^(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[0-9][0-9_]*(?:\.[0-9_]*)?|\.[0-9][0-9_]*)(?:[eE][0-9][0-9_]*)?)$/.test(value);
236
+ }
237
+ /** Parse identifiers, never SQL. Dots outside double quotes delimit qualifiers. */
238
+ function identifierParts(identifier) {
239
+ if (typeof identifier !== "string" || !identifier || identifier.includes("\0")) throw new Error(`Invalid SQL identifier: ${identifier}`);
240
+ const parts = [];
241
+ let position = 0;
242
+ while (position < identifier.length) {
243
+ const rest = identifier.slice(position);
244
+ const match = rest.startsWith("\"") ? /^"((?:[^"]|"")+)"(?=\.|$)/.exec(rest) : /^([A-Za-z0-9_]+)(?=\.|$)/.exec(rest);
245
+ if (!match) throw new Error(`Invalid SQL identifier: ${identifier}`);
246
+ const exact = rest.startsWith("\"");
247
+ parts.push({
248
+ name: exact ? match[1].replaceAll("\"\"", "\"") : match[1],
249
+ exact
250
+ });
251
+ position += match[0].length;
252
+ if (position < identifier.length) {
253
+ position += 1;
254
+ if (position === identifier.length) throw new Error(`Invalid SQL identifier: ${identifier}`);
255
+ }
256
+ }
257
+ return parts;
258
+ }
259
+ function isColumnIdentifier(identifier) {
260
+ try {
261
+ const parts = identifierParts(identifier);
262
+ return parts.length === 1 && (parts[0].exact || /^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier));
263
+ } catch {
264
+ return false;
265
+ }
266
+ }
267
+ /** Quote a physical name without interpreting delimiters or dots. */
268
+ function quoteLiteralIdentifier(identifier) {
269
+ return quotePhysicalIdentifier(identifier, "\"");
270
+ }
271
+ /** SQLite identifiers must not fall back to double-quoted string literals. */
272
+ function quoteSqliteLiteralIdentifier(identifier) {
273
+ return quotePhysicalIdentifier(identifier, "`");
274
+ }
275
+ function quotePhysicalIdentifier(identifier, quote) {
276
+ if (typeof identifier !== "string") throw new Error(`Invalid SQL identifier: ${identifier}`);
277
+ return `${quote}${escapeQuotedIdentifier(identifier, quote)}${quote}`;
278
+ }
279
+ /** SQLite CRUD column (one validated identifier). */
280
+ function quoteSqliteColumnName(column) {
281
+ validateColumnName(column);
282
+ return renderIdentifier(column, "sqlite", { quoteIdentifiers: true });
283
+ }
284
+ /** DuckDB/JSON CRUD column, or an already-resolved literal physical name. */
285
+ function quoteDuckDBColumnName(column, literal = false) {
286
+ if (literal) return quoteLiteralIdentifier(column);
287
+ validateColumnName(column);
288
+ return renderIdentifier(column, "duckdb", { quoteIdentifiers: true });
289
+ }
290
+ /** Shared rendering for qualified WHERE/aggregate identifiers. */
291
+ function renderIdentifier(identifier, dialect, options = {}) {
292
+ return identifierParts(identifier).map(({ name, exact }) => {
293
+ if (!options.quoteIdentifiers && !exact && !IDENTIFIER_KEYWORDS.has(name.toLowerCase())) return name;
294
+ const physical = dialect === "postgres" && !exact ? name.toLowerCase() : name;
295
+ return dialect === "sqlite" ? quoteSqliteLiteralIdentifier(physical) : quoteLiteralIdentifier(physical);
296
+ }).join(".");
297
+ }
298
+ /** Previously raw index terms may be expressions or ordered SQL, not just names. */
299
+ function renderIndexTerm(term, dialect, options = {}) {
300
+ const component = "(?:[A-Za-z_][A-Za-z0-9_]*|\"(?:[^\"]|\"\")+\")";
301
+ const plain = new RegExp(`^${component}(?:\\.${component})*$`);
302
+ return typeof term === "string" && plain.test(term) ? renderIdentifier(term, dialect, options) : term;
303
+ }
304
+ /** DDL names historically accepted SQLite's alternate identifier delimiters.
305
+ * Normalize names only here; strict CRUD/WHERE keep their existing input syntax.
306
+ */
307
+ function renderSchemaIdentifier(identifier, dialect, options = {}) {
308
+ if (typeof identifier !== "string") throw new Error(`Invalid SQL identifier: ${identifier}`);
309
+ const parts = [];
310
+ let position = 0;
311
+ while (position < identifier.length) {
312
+ const match = /^(?:([A-Za-z0-9_]+)|"((?:[^"]|"")+)"|`((?:[^`]|``)+)`|\[([^\]]+)\]|'((?:[^']|'')+)')(?=\.|$)/.exec(identifier.slice(position));
313
+ if (!match) throw new Error(`Invalid SQL identifier: ${identifier}`);
314
+ if (match[1] !== void 0) parts.push(match[1]);
315
+ else {
316
+ const name = match[2] !== void 0 ? match[2].replaceAll("\"\"", "\"") : match[3] !== void 0 ? match[3].replaceAll("``", "`") : match[4] !== void 0 ? match[4] : match[5].replaceAll("''", "'");
317
+ parts.push(quoteLiteralIdentifier(name));
318
+ }
319
+ position += match[0].length;
320
+ if (position < identifier.length) {
321
+ position += 1;
322
+ if (position === identifier.length) throw new Error(`Invalid SQL identifier: ${identifier}`);
323
+ }
324
+ }
325
+ return renderIdentifier(parts.join("."), dialect, options);
326
+ }
327
+ /** FK lists contain identifiers, with commas outside explicit quotes only. */
328
+ function renderIdentifierList(list, dialect, options = {}) {
329
+ if (typeof list !== "string") throw new Error(`Invalid SQL identifier list: ${list}`);
330
+ const parts = [];
331
+ let closingQuote;
332
+ let start = 0;
333
+ for (let index = 0; index < list.length; index += 1) {
334
+ const char = list[index];
335
+ if (closingQuote) {
336
+ if (char === closingQuote) if (closingQuote !== "]" && list[index + 1] === closingQuote) index += 1;
337
+ else closingQuote = void 0;
338
+ } else if (char === "\"" || char === "'" || char === "`" || char === "[") closingQuote = char === "[" ? "]" : char;
339
+ else if (char === ",") {
340
+ parts.push(list.slice(start, index));
341
+ start = index + 1;
342
+ }
343
+ }
344
+ parts.push(list.slice(start));
345
+ return parts.map((part) => {
346
+ const name = part.trim();
347
+ const offset = part.indexOf(name);
348
+ return part.slice(0, offset) + renderSchemaIdentifier(name, dialect, options) + part.slice(offset + name.length);
349
+ }).join(",");
350
+ }
351
+ var IDENTIFIER_KEYWORDS = new Set("abort action add after all alter always analyse analyze and any array as asc asymmetric attach autoincrement before begin between both by cascade case cast check collate column commit conflict constraint create cross current current_catalog current_date current_role current_time current_timestamp current_user database default deferrable deferred delete desc describe detach distinct do drop each else end escape except exclude exclusive exists explain fail false fetch filter first following for foreign from full generated glob grant group groups having if ignore immediate in index indexed initially inner insert instead intersect into is isnull join key lambda last lateral leading left like limit localtime localtimestamp match materialized natural no not nothing notnull null nulls of offset on only or order others outer over partition pivot pivot_longer pivot_wider placing plan pragma preceding primary qualify query raise range recursive references regexp reindex release rename replace restrict returning right rollback row rows savepoint select session_user set show some summarize symmetric system_user table temp temporary then ties to trailing transaction trigger true unbounded union unique unpivot update user using vacuum values variadic view virtual when where window with without".split(" "));
352
+ //#endregion
2
353
  //#region src/shared/utils.ts
3
354
  /**
4
355
  * Shared SQL utilities that work in both browser and Node.js environments
@@ -272,9 +623,6 @@ var VALID_OPERATORS = {
272
623
  in: "IN",
273
624
  "not in": "NOT IN"
274
625
  };
275
- function isSimpleSqlIdentifier(field) {
276
- return /^[a-zA-Z0-9_.]+$/.test(field);
277
- }
278
626
  /**
279
627
  * Marks a condition key as caller-authored SQL text.
280
628
  *
@@ -378,10 +726,17 @@ function parseConditionKey(fullKey) {
378
726
  * Builds a single condition for a WHERE clause
379
727
  * @internal
380
728
  */
381
- var buildCondition = (fullKey, value, currIndex, adapterType) => {
729
+ var buildCondition = (fullKey, value, currIndex, adapterType, options = {}) => {
382
730
  const { key, isRaw } = unwrapRawKey(fullKey);
383
- const { field, operator } = parseConditionKey(key);
384
- if (!isRaw && !isSimpleSqlIdentifier(field)) throw new Error(`Invalid SQL identifier: ${field}. Condition keys must be plain identifiers; wrap developer-authored SQL expressions in raw().`);
731
+ const parsed = parseConditionKey(key);
732
+ const operator = parsed.operator;
733
+ let field = parsed.field;
734
+ if (!isRaw && !isLegacyNumericSqlToken(field)) try {
735
+ field = renderIdentifier(field, adapterType, options);
736
+ } catch (error) {
737
+ if (!(error instanceof Error) || !error.message.startsWith("Invalid SQL identifier:")) throw error;
738
+ throw new Error(`${error.message}. Condition keys must be plain identifiers; wrap developer-authored SQL expressions in raw().`);
739
+ }
385
740
  const sqlOperator = VALID_OPERATORS[operator] || "=";
386
741
  const values = [];
387
742
  let sql;
@@ -394,7 +749,8 @@ var buildCondition = (fullKey, value, currIndex, adapterType) => {
394
749
  } else if (value === null) sql = `${field} IS ${sqlOperator === "=" ? "NULL" : "NOT NULL"}`;
395
750
  else if ((sqlOperator === "IN" || sqlOperator === "NOT IN") && Array.isArray(value)) {
396
751
  if (value.length === 0) throw new Error(`${sqlOperator} requires at least one value`);
397
- sql = `${field} ${sqlOperator} (${value.map(() => `$${currIndex.value++}`).join(", ")})`;
752
+ const placeholders = value.map(() => `$${currIndex.value++}`).join(", ");
753
+ sql = `${field} ${sqlOperator} (${placeholders})`;
398
754
  values.push(...value);
399
755
  } else if (value instanceof Date) {
400
756
  if (adapterType === "duckdb" || adapterType === "json") sql = `${field} ${sqlOperator} CAST($${currIndex.value++} AS TIMESTAMP)${sqlOperator === "LIKE" ? " ESCAPE '\\'" : ""}`;
@@ -505,7 +861,7 @@ var buildCondition = (fullKey, value, currIndex, adapterType) => {
505
861
  * - Object format: Multiple conditions combined with AND
506
862
  * - 2D array format: Inner arrays ANDed, outer array ORed
507
863
  */
508
- var buildWhere = (where, startIndex = 1, adapterType) => {
864
+ var buildWhere = (where, startIndex = 1, adapterType, options = {}) => {
509
865
  let sql = "";
510
866
  const values = [];
511
867
  const currIndex = { value: startIndex };
@@ -519,7 +875,7 @@ var buildWhere = (where, startIndex = 1, adapterType) => {
519
875
  if (!Array.isArray(andGroup) || andGroup.length === 0) continue;
520
876
  const andConditions = [];
521
877
  for (const conditionObj of andGroup) for (const [fullKey, value] of Object.entries(conditionObj)) {
522
- const result = buildCondition(fullKey, value, currIndex, adapterType);
878
+ const result = buildCondition(fullKey, value, currIndex, adapterType, options);
523
879
  andConditions.push(result.sql);
524
880
  values.push(...result.values);
525
881
  }
@@ -534,7 +890,7 @@ var buildWhere = (where, startIndex = 1, adapterType) => {
534
890
  if (where && Object.keys(where).length > 0) {
535
891
  sql = "WHERE ";
536
892
  for (const [fullKey, value] of Object.entries(where)) {
537
- const result = buildCondition(fullKey, value, currIndex, adapterType);
893
+ const result = buildCondition(fullKey, value, currIndex, adapterType, options);
538
894
  if (sql !== "WHERE ") sql += " AND ";
539
895
  sql += result.sql;
540
896
  values.push(...result.values);
@@ -545,6 +901,103 @@ var buildWhere = (where, startIndex = 1, adapterType) => {
545
901
  values
546
902
  };
547
903
  };
904
+ /** Adapter-owned WHERE policy: quote every identifier component. */
905
+ var buildAdapterWhere = (where, startIndex, adapterType) => buildWhere(where, startIndex, adapterType, { quoteIdentifiers: true });
906
+ /**
907
+ * Rewrites executable positional parameters while preserving SQL text inside
908
+ * literals, identifiers and comments. Extracted from the PostgreSQL adapter's
909
+ * existing question-mark lexer so native SQLite and PostgreSQL use one policy.
910
+ * SQLite's bracket/backtick identifiers are enabled only for that dialect:
911
+ * PostgreSQL brackets can instead contain executable array subscript binds.
912
+ */
913
+ function rewriteSqlParameters(sql, dialect, replace) {
914
+ let output = "";
915
+ let position = 0;
916
+ const copyQuoted = (quote, escaped = false) => {
917
+ output += sql[position++];
918
+ while (position < sql.length) {
919
+ const char = sql[position++];
920
+ output += char;
921
+ if (escaped && char === "\\" && position < sql.length) output += sql[position++];
922
+ else if (char === quote) if (quote !== "]" && sql[position] === quote) output += sql[position++];
923
+ else break;
924
+ }
925
+ };
926
+ const copyUntil = (end) => {
927
+ const endIndex = sql.indexOf(end, position + end.length);
928
+ const after = endIndex < 0 ? sql.length : endIndex + end.length;
929
+ output += sql.slice(position, after);
930
+ position = after;
931
+ };
932
+ while (position < sql.length) {
933
+ const char = sql[position];
934
+ const next = sql[position + 1];
935
+ if (dialect === "postgres" && (char === "E" || char === "e") && next === "'") {
936
+ output += char;
937
+ position += 1;
938
+ copyQuoted("'", true);
939
+ continue;
940
+ }
941
+ if (char === "'" || char === "\"" || dialect === "sqlite" && char === "`") {
942
+ copyQuoted(char);
943
+ continue;
944
+ }
945
+ if (dialect === "sqlite" && char === "[") {
946
+ copyQuoted("]");
947
+ continue;
948
+ }
949
+ if (char === "-" && next === "-") {
950
+ const endIndex = sql.slice(position).search(/[\r\n]/);
951
+ const after = endIndex < 0 ? sql.length : position + endIndex + 1;
952
+ output += sql.slice(position, after);
953
+ position = after;
954
+ continue;
955
+ }
956
+ if (char === "/" && next === "*") {
957
+ if (dialect === "sqlite") copyUntil("*/");
958
+ else {
959
+ const start = position;
960
+ position += 2;
961
+ let depth = 1;
962
+ while (position < sql.length && depth > 0) {
963
+ const pair = sql.slice(position, position + 2);
964
+ if (pair === "/*") {
965
+ depth += 1;
966
+ position += 2;
967
+ } else if (pair === "*/") {
968
+ depth -= 1;
969
+ position += 2;
970
+ } else position += 1;
971
+ }
972
+ output += sql.slice(start, position);
973
+ }
974
+ continue;
975
+ }
976
+ if (char === "$" && !/[\w$\u0080-\uFFFF]/.test(sql[position - 1] ?? "")) {
977
+ if (dialect === "postgres") {
978
+ const tag = sql.slice(position).match(/^\$[A-Za-z_]\w*\$|^\$\$/);
979
+ if (tag) {
980
+ copyUntil(tag[0]);
981
+ continue;
982
+ }
983
+ }
984
+ const numbered = /^\$(\d+)/.exec(sql.slice(position));
985
+ if (numbered) {
986
+ output += replace(numbered[0], Number(numbered[1]));
987
+ position += numbered[0].length;
988
+ continue;
989
+ }
990
+ }
991
+ if (char === "?" && next !== "|" && next !== "&") {
992
+ output += replace("?");
993
+ position += 1;
994
+ continue;
995
+ }
996
+ output += char;
997
+ position += 1;
998
+ }
999
+ return output;
1000
+ }
548
1001
  //#endregion
549
1002
  //#region src/schema-manager.ts
550
1003
  /**
@@ -666,7 +1119,7 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
666
1119
  for (const index of indexes) await this.createIndex(db, tableName, index);
667
1120
  for (const trigger of triggers) await this.createTrigger(db, trigger);
668
1121
  } else if (options.force) {
669
- await db.query(`DROP TABLE IF EXISTS ${tableName}`);
1122
+ await db.query(`DROP TABLE IF EXISTS ${renderSchemaIdentifier(tableName)}`);
670
1123
  await this.createTable(db, schema);
671
1124
  for (const index of indexes) await this.createIndex(db, tableName, index);
672
1125
  for (const trigger of triggers) await this.createTrigger(db, trigger);
@@ -679,7 +1132,7 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
679
1132
  const { tableName, columns, foreignKeys } = schema;
680
1133
  const columnDefinitions = [];
681
1134
  for (const [columnName, columnDef] of Object.entries(columns)) {
682
- let def = `${columnName} ${columnDef.type}`;
1135
+ let def = `${renderSchemaIdentifier(columnName)} ${columnDef.type}`;
683
1136
  if (columnDef.primaryKey) def += " PRIMARY KEY";
684
1137
  if (columnDef.unique && !columnDef.primaryKey) def += " UNIQUE";
685
1138
  if (columnDef.notNull) def += " NOT NULL";
@@ -688,12 +1141,12 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
688
1141
  columnDefinitions.push(def);
689
1142
  }
690
1143
  for (const fk of foreignKeys) {
691
- let fkDef = `FOREIGN KEY (${fk.column}) REFERENCES ${fk.referencesTable}(${fk.referencesColumn})`;
1144
+ let fkDef = `FOREIGN KEY (${renderIdentifierList(fk.column)}) REFERENCES ${renderSchemaIdentifier(fk.referencesTable)}(${renderIdentifierList(fk.referencesColumn)})`;
692
1145
  if (fk.onDelete) fkDef += ` ON DELETE ${fk.onDelete}`;
693
1146
  if (fk.onUpdate) fkDef += ` ON UPDATE ${fk.onUpdate}`;
694
1147
  columnDefinitions.push(fkDef);
695
1148
  }
696
- const createTableSQL = `CREATE TABLE ${tableName} (\n ${columnDefinitions.join(",\n ")}\n)`;
1149
+ const createTableSQL = `CREATE TABLE ${renderSchemaIdentifier(tableName)} (\n ${columnDefinitions.join(",\n ")}\n)`;
697
1150
  await db.query(createTableSQL);
698
1151
  }
699
1152
  /**
@@ -702,7 +1155,7 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
702
1155
  async createIndex(db, tableName, index) {
703
1156
  const uniqueClause = index.unique ? "UNIQUE " : "";
704
1157
  const whereClause = index.where ? ` WHERE ${index.where}` : "";
705
- const createIndexSQL = `CREATE ${uniqueClause}INDEX ${index.name} ON ${tableName} (${index.columns.join(", ")})${whereClause}`;
1158
+ const createIndexSQL = `CREATE ${uniqueClause}INDEX ${renderSchemaIdentifier(index.name)} ON ${renderSchemaIdentifier(tableName)} (${index.columns.map((column) => renderIndexTerm(column)).join(", ")})${whereClause}`;
706
1159
  await db.query(createIndexSQL);
707
1160
  }
708
1161
  /**
@@ -710,7 +1163,7 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
710
1163
  */
711
1164
  async createTrigger(db, trigger) {
712
1165
  const conditionClause = trigger.condition ? ` WHEN ${trigger.condition}` : "";
713
- const createTriggerSQL = `CREATE TRIGGER ${trigger.name} ${trigger.when} ${trigger.event} ON ${trigger.table}${conditionClause} BEGIN ${trigger.body} END`;
1166
+ const createTriggerSQL = `CREATE TRIGGER ${renderSchemaIdentifier(trigger.name)} ${trigger.when} ${trigger.event} ON ${renderSchemaIdentifier(trigger.table)}${conditionClause} BEGIN ${trigger.body} END`;
714
1167
  await db.query(createTriggerSQL);
715
1168
  }
716
1169
  /**
@@ -773,6 +1226,6 @@ var DatabaseSchemaManager = class DatabaseSchemaManager {
773
1226
  }
774
1227
  };
775
1228
  //#endregion
776
- export { raw as a, wrapDatabaseError as c, parseConditionKey as i, buildWhere as n, resolveInsertColumns as o, formatDbError as r, unwrapRawKey as s, DatabaseSchemaManager as t };
1229
+ export { validateColumnNames as C, validateTableName as E, validateColumnName as S, validatePlainColumnName as T, quoteLiteralIdentifier as _, parseConditionKey as a, quoteSqliteLiteralIdentifier as b, rewriteSqlParameters as c, escapeStringLiteral as d, generateAddColumnStatement as f, quoteDuckDBColumnName as g, isLegacyNumericSqlToken as h, formatDbError as i, unwrapRawKey as l, identifierParts as m, buildAdapterWhere as n, raw as o, generateCreateIndexStatement as p, buildWhere as r, resolveInsertColumns as s, DatabaseSchemaManager as t, wrapDatabaseError as u, quotePostgresColumnName as v, validateIndexName as w, renderIdentifier as x, quoteSqliteColumnName as y };
777
1230
 
778
- //# sourceMappingURL=schema-manager-tfASrb_b.js.map
1231
+ //# sourceMappingURL=schema-manager-psLzQ2yh.js.map