@memberjunction/sql-dialect 6.2.0-edge.6 → 6.2.0-edge.7

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 (86) hide show
  1. package/README.md +280 -91
  2. package/dist/dialectFactory.d.ts +34 -14
  3. package/dist/dialectFactory.d.ts.map +1 -1
  4. package/dist/dialectFactory.js +101 -25
  5. package/dist/dialectFactory.js.map +1 -1
  6. package/dist/dialects/ansi.d.ts +55 -0
  7. package/dist/dialects/ansi.d.ts.map +1 -0
  8. package/dist/dialects/ansi.js +136 -0
  9. package/dist/dialects/ansi.js.map +1 -0
  10. package/dist/dialects/baseSchemaDDL.d.ts +78 -0
  11. package/dist/dialects/baseSchemaDDL.d.ts.map +1 -0
  12. package/dist/dialects/baseSchemaDDL.js +63 -0
  13. package/dist/dialects/baseSchemaDDL.js.map +1 -0
  14. package/dist/dialects/databricksQueryDialect.d.ts +41 -0
  15. package/dist/dialects/databricksQueryDialect.d.ts.map +1 -0
  16. package/dist/dialects/databricksQueryDialect.js +103 -0
  17. package/dist/dialects/databricksQueryDialect.js.map +1 -0
  18. package/dist/dialects/mysqlQueryDialect.d.ts +46 -0
  19. package/dist/dialects/mysqlQueryDialect.d.ts.map +1 -0
  20. package/dist/dialects/mysqlQueryDialect.js +117 -0
  21. package/dist/dialects/mysqlQueryDialect.js.map +1 -0
  22. package/dist/dialects/oracleQueryDialect.d.ts +42 -0
  23. package/dist/dialects/oracleQueryDialect.d.ts.map +1 -0
  24. package/dist/dialects/oracleQueryDialect.js +92 -0
  25. package/dist/dialects/oracleQueryDialect.js.map +1 -0
  26. package/dist/dialects/postgresqlSchemaDDL.d.ts +112 -0
  27. package/dist/dialects/postgresqlSchemaDDL.d.ts.map +1 -0
  28. package/dist/dialects/postgresqlSchemaDDL.js +590 -0
  29. package/dist/dialects/postgresqlSchemaDDL.js.map +1 -0
  30. package/dist/dialects/snowflakeQueryDialect.d.ts +41 -0
  31. package/dist/dialects/snowflakeQueryDialect.d.ts.map +1 -0
  32. package/dist/dialects/snowflakeQueryDialect.js +94 -0
  33. package/dist/dialects/snowflakeQueryDialect.js.map +1 -0
  34. package/dist/dialects/sqlServerSchemaDDL.d.ts +83 -0
  35. package/dist/dialects/sqlServerSchemaDDL.d.ts.map +1 -0
  36. package/dist/dialects/sqlServerSchemaDDL.js +507 -0
  37. package/dist/dialects/sqlServerSchemaDDL.js.map +1 -0
  38. package/dist/facets/dialectBinding.d.ts +26 -0
  39. package/dist/facets/dialectBinding.d.ts.map +1 -0
  40. package/dist/facets/dialectBinding.js +2 -0
  41. package/dist/facets/dialectBinding.js.map +1 -0
  42. package/dist/facets/dialectGrammar.d.ts +82 -0
  43. package/dist/facets/dialectGrammar.d.ts.map +1 -0
  44. package/dist/facets/dialectGrammar.js +2 -0
  45. package/dist/facets/dialectGrammar.js.map +1 -0
  46. package/dist/facets/dialectKey.d.ts +9 -0
  47. package/dist/facets/dialectKey.d.ts.map +1 -0
  48. package/dist/facets/dialectKey.js +2 -0
  49. package/dist/facets/dialectKey.js.map +1 -0
  50. package/dist/facets/dialectLexicalRules.d.ts +102 -0
  51. package/dist/facets/dialectLexicalRules.d.ts.map +1 -0
  52. package/dist/facets/dialectLexicalRules.js +2 -0
  53. package/dist/facets/dialectLexicalRules.js.map +1 -0
  54. package/dist/facets/dialectSchemaDDL.d.ts +213 -0
  55. package/dist/facets/dialectSchemaDDL.d.ts.map +1 -0
  56. package/dist/facets/dialectSchemaDDL.js +2 -0
  57. package/dist/facets/dialectSchemaDDL.js.map +1 -0
  58. package/dist/facets/dialectTypes.d.ts +31 -0
  59. package/dist/facets/dialectTypes.d.ts.map +1 -0
  60. package/dist/facets/dialectTypes.js +2 -0
  61. package/dist/facets/dialectTypes.js.map +1 -0
  62. package/dist/facets/dialectWriter.d.ts +59 -0
  63. package/dist/facets/dialectWriter.d.ts.map +1 -0
  64. package/dist/facets/dialectWriter.js +2 -0
  65. package/dist/facets/dialectWriter.js.map +1 -0
  66. package/dist/index.d.ts +21 -5
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +13 -4
  69. package/dist/index.js.map +1 -1
  70. package/dist/postgresqlDialect.d.ts +57 -152
  71. package/dist/postgresqlDialect.d.ts.map +1 -1
  72. package/dist/postgresqlDialect.js +110 -683
  73. package/dist/postgresqlDialect.js.map +1 -1
  74. package/dist/queryDialect.d.ts +42 -0
  75. package/dist/queryDialect.d.ts.map +1 -0
  76. package/dist/queryDialect.js +25 -0
  77. package/dist/queryDialect.js.map +1 -0
  78. package/dist/sqlDialect.d.ts +121 -212
  79. package/dist/sqlDialect.d.ts.map +1 -1
  80. package/dist/sqlDialect.js +710 -29
  81. package/dist/sqlDialect.js.map +1 -1
  82. package/dist/sqlServerDialect.d.ts +54 -120
  83. package/dist/sqlServerDialect.d.ts.map +1 -1
  84. package/dist/sqlServerDialect.js +124 -594
  85. package/dist/sqlServerDialect.js.map +1 -1
  86. package/package.json +4 -2
@@ -1,20 +1,151 @@
1
+ import { QueryDialect } from './queryDialect.js';
1
2
  /**
2
- * Abstract base class for SQL dialect implementations.
3
+ * Abstract base class for the dialects of the platforms MJ itself runs on.
3
4
  *
4
- * Encapsulates ALL database-specific SQL syntax patterns into a single,
5
- * testable abstraction. This is a pure string/logic layer with zero
6
- * database driver dependencies.
5
+ * A {@link QueryDialect} (lexical rules, grammar facts, writer, types, binding) plus the
6
+ * {@link DDL} facet MJ needs to create and run its own schema. Every member below is kept for
7
+ * existing callers and delegates to one of the facets. This is a pure string/logic layer with
8
+ * zero database driver dependencies.
7
9
  */
8
- export class SQLDialect {
10
+ export class SQLDialect extends QueryDialect {
11
+ /** The dialect key, which for a platform dialect is its {@link PlatformKey}. */
12
+ get Key() {
13
+ return this.PlatformKey;
14
+ }
15
+ /**
16
+ * Returns the dialect name used by node-sql-parser for AST parsing.
17
+ * SQL Server: 'TransactSQL', PostgreSQL: 'PostgresQL', etc.
18
+ */
19
+ get ParserDialect() {
20
+ const grammar = this.Grammar.ParserGrammar;
21
+ if (grammar === null) {
22
+ throw new Error(`The ${this.PlatformKey} dialect declares no node-sql-parser grammar.`);
23
+ }
24
+ return grammar;
25
+ }
26
+ // ─── Identifier Quoting ──────────────────────────────────────────
27
+ /**
28
+ * Quotes a database identifier (table name, column name, etc.).
29
+ * SQL Server: [name], PostgreSQL: "name"
30
+ */
31
+ QuoteIdentifier(name) {
32
+ return this.Writer.QuoteIdentifier(name);
33
+ }
34
+ /**
35
+ * Produces a schema-qualified object reference.
36
+ * SQL Server: [schema].[object], PostgreSQL: schema."object"
37
+ */
38
+ QuoteSchema(schema, object) {
39
+ return this.Writer.QuoteSchema(schema, object);
40
+ }
41
+ /**
42
+ * Quotes a column alias used in `SELECT ... AS <alias>`. SQL Server is
43
+ * case-insensitive and accepts a bare identifier; PostgreSQL folds
44
+ * unquoted identifiers to lowercase, so we must quote the alias when the
45
+ * caller cares about preserving case (e.g. matching a TypeScript property
46
+ * name in the result row).
47
+ */
48
+ QuoteColumnAlias(aliasName) {
49
+ return this.Writer.QuoteColumnAlias(aliasName);
50
+ }
51
+ /**
52
+ * Canonicalizes a SCHEMA name to the form the platform actually stores when
53
+ * the name appears UNQUOTED in DDL. PostgreSQL folds unquoted identifiers to
54
+ * lowercase, so `__mj_BizAppsCommon` physically becomes `__mj_bizappscommon`;
55
+ * SQL Server is case-insensitive and stores the name as-given. Routing every
56
+ * schema CREATE/DROP/USE through this keeps the engine's (quoted) operations
57
+ * aligned with what unquoted migration DDL produces — so a mixed-case schema
58
+ * name can't split into two physical schemas (one quoted-mixed, one folded-lowercase).
59
+ */
60
+ CanonicalSchemaName(name) {
61
+ return this.DDL.CanonicalSchemaName(name);
62
+ }
9
63
  /**
10
64
  * Quotes a value as a SQL string literal. Both SQL Server and PostgreSQL
11
- * use single quotes with `''` doubling to escape internal apostrophes —
12
- * this is concrete in the base class so callers don't reinvent the
13
- * `value.replace(/'/g, "''")` pattern. Subclasses may override if a
14
- * future dialect needs a different escape rule.
65
+ * use single quotes with `''` doubling to escape internal apostrophes.
66
+ * Use this instead of reinventing the `value.replace(/'/g, "''")` pattern;
67
+ * the dialect's writer owns the escape rule.
15
68
  */
16
69
  QuoteStringLiteral(value) {
17
- return `'${value.replace(/'/g, "''")}'`;
70
+ return this.Writer.QuoteStringLiteral(value);
71
+ }
72
+ /**
73
+ * The prefix a string literal holding `text` needs so the database keeps every character, or
74
+ * `''` when a plain literal does. SQL Server: `N` when the text has characters outside ASCII,
75
+ * which a plain literal would lose to the database code page. PostgreSQL: always `''`.
76
+ */
77
+ StringLiteralPrefix(text) {
78
+ return this.Writer.StringLiteralPrefix(text);
79
+ }
80
+ /**
81
+ * Escapes the characters a `LIKE` pattern treats specially, so `text` matches literally with
82
+ * the platform's default escape rules (no `ESCAPE` clause). Quotes are not escaped here; the
83
+ * caller still doubles them for the string literal.
84
+ * SQL Server: `[`, `%` and `_` become `[[]`, `[%]` and `[_]`. PostgreSQL: `\`, `%` and `_`
85
+ * are escaped with a backslash.
86
+ */
87
+ EscapeLikePattern(text) {
88
+ return this.Writer.EscapeLikePattern(text);
89
+ }
90
+ /**
91
+ * The value to bind for a boolean query parameter. SQL Server: `1` / `0` (BIT),
92
+ * PostgreSQL: `true` / `false`.
93
+ */
94
+ BooleanParameterValue(value) {
95
+ return this.Binding.BooleanParameterValue(value);
96
+ }
97
+ // ─── Pagination ──────────────────────────────────────────────────
98
+ /**
99
+ * Returns pagination SQL fragments.
100
+ * SQL Server uses TOP (prefix) or OFFSET/FETCH (suffix).
101
+ * PostgreSQL uses LIMIT/OFFSET (suffix).
102
+ */
103
+ LimitClause(limit, offset) {
104
+ return this.Writer.LimitClause(limit, offset);
105
+ }
106
+ // ─── Literals & Expressions ──────────────────────────────────────
107
+ /**
108
+ * Returns a boolean literal for the platform.
109
+ * SQL Server: "1"/"0", PostgreSQL: "true"/"false"
110
+ */
111
+ BooleanLiteral(value) {
112
+ return this.Writer.BooleanLiteral(value);
113
+ }
114
+ /**
115
+ * Returns the SQL type token for a boolean parameter in a stored-procedure /
116
+ * function signature. Used by codegen when emitting tolerant-SP `_Clear`
117
+ * companion parameters and other boolean-typed params.
118
+ *
119
+ * SQL Server: `bit` (BIT type, 0/1)
120
+ * PostgreSQL: `boolean` (BOOLEAN type, TRUE/FALSE)
121
+ *
122
+ * Hardcoding `bit` everywhere worked on SQL Server but produced sprocs
123
+ * that PG rejected as `operator does not exist: boolean = integer` when
124
+ * the generated CASE compared a `bit`-declared parameter with `= 1`.
125
+ */
126
+ BooleanParameterType() {
127
+ return this.DDL.BooleanParameterType();
128
+ }
129
+ /**
130
+ * Returns the current UTC timestamp expression.
131
+ * SQL Server: GETUTCDATE(), PostgreSQL: NOW() AT TIME ZONE 'UTC'
132
+ */
133
+ CurrentTimestampUTC() {
134
+ return this.Writer.CurrentTimestampUTC();
135
+ }
136
+ /**
137
+ * Wraps a single DML statement so the number of rows it affected comes back as a one-row,
138
+ * one-column result set — the portable way to read an affected-row count without relying on a
139
+ * driver-specific `rowsAffected` field.
140
+ *
141
+ * SQL Server appends `SELECT @@ROWCOUNT`. PostgreSQL has no `@@ROWCOUNT` at all, so it wraps
142
+ * the statement in a data-modifying CTE and counts the `RETURNING` rows.
143
+ *
144
+ * `dmlStatement` must be exactly one INSERT/UPDATE/DELETE and carry no trailing semicolon:
145
+ * the PostgreSQL form is a CTE, which cannot wrap a statement batch.
146
+ */
147
+ AffectedRowCountSQL(dmlStatement, alias) {
148
+ return this.DDL.AffectedRowCountSQL(dmlStatement, alias);
18
149
  }
19
150
  /**
20
151
  * Wraps an expression in the dialect's lowercase function — used for
@@ -30,7 +161,7 @@ export class SQLDialect {
30
161
  * dialect-aware SQL surface in one place per the SQLDialect contract.
31
162
  */
32
163
  LowerCase(expr) {
33
- return `LOWER(${expr})`;
164
+ return this.Writer.LowerCase(expr);
34
165
  }
35
166
  /**
36
167
  * A syntax briefing for this dialect, composed ENTIRELY from this class's
@@ -73,6 +204,42 @@ export class SQLDialect {
73
204
  `- NULL literal: ${this.NullLiteral}`,
74
205
  ].join('\n');
75
206
  }
207
+ // ─── Type-Name Sets (single source of truth for SQL ↔ category mapping) ──
208
+ //
209
+ // Each dialect declares the SQL type names it uses for each conceptual
210
+ // category. Cross-dialect predicates (`IsBooleanSQLType`, `IsStringSQLType`,
211
+ // etc. — see ./typeClassification.ts) union these lists so callers can
212
+ // classify any type name without knowing which platform produced it.
213
+ //
214
+ // Adding a new dialect = implementing these getters + registering with the
215
+ // classification module. NEVER hardcode lists of SQL type names in
216
+ // call sites — use the predicates.
217
+ //
218
+ // Returned names MUST be lowercase, trimmed, and match the strings that
219
+ // appear in `EntityField.Type` for that platform (i.e. what the platform's
220
+ // `information_schema` / `sys.columns` reports).
221
+ /** SQL type names this dialect uses for boolean columns. */
222
+ get BooleanTypeNames() {
223
+ return this.Types.BooleanTypeNames;
224
+ }
225
+ /** SQL type names this dialect uses for variable-length character / text columns. */
226
+ get StringTypeNames() {
227
+ return this.Types.StringTypeNames;
228
+ }
229
+ /**
230
+ * Subset of {@link StringTypeNames} that represents **fixed-width** /
231
+ * space-padded character types. SQL Server `char`/`nchar` and PostgreSQL
232
+ * `char`/`bpchar`/`character` (without `varying`) all right-pad stored
233
+ * values with spaces up to the declared length and return that padding
234
+ * in result sets. Variable-width types (`varchar`, `nvarchar`, `text`,
235
+ * etc.) do not.
236
+ *
237
+ * Used by `BaseEntity` to rtrim padding on load so dirty-checks and
238
+ * downstream consumers see the logical value, not the storage form.
239
+ */
240
+ get FixedWidthStringTypeNames() {
241
+ return this.Types.FixedWidthStringTypeNames;
242
+ }
76
243
  /**
77
244
  * Maximum string length usable in an INDEX KEY column (PRIMARY KEY / UNIQUE constraint) on this
78
245
  * dialect. A PK string column wider than this can't be indexed, so callers (e.g. the integration
@@ -82,7 +249,7 @@ export class SQLDialect {
82
249
  * length, so it keeps the no-cap default.
83
250
  */
84
251
  get MaxKeyStringLength() {
85
- return Number.MAX_SAFE_INTEGER;
252
+ return this.DDL.MaxKeyStringLength;
86
253
  }
87
254
  /**
88
255
  * Maximum bytes that can be stored in-row for a single row, or `null` when the dialect has no
@@ -92,14 +259,14 @@ export class SQLDialect {
92
259
  * Default: `null` (no in-row size limit).
93
260
  */
94
261
  get MaxInRowSizeBytes() {
95
- return null;
262
+ return this.DDL.MaxInRowSizeBytes;
96
263
  }
97
264
  /**
98
265
  * Hard maximum number of columns per table, or `null` when effectively unbounded for our purposes.
99
266
  * SQL Server: 1024. PostgreSQL: 1600. Default: `null`.
100
267
  */
101
268
  get MaxColumnCount() {
102
- return null;
269
+ return this.DDL.MaxColumnCount;
103
270
  }
104
271
  /**
105
272
  * Minimum in-row byte footprint of a column of the given raw SQL type. Off-row-capable
@@ -107,8 +274,59 @@ export class SQLDialect {
107
274
  * their full size. Only meaningful for dialects that report a {@link MaxInRowSizeBytes}.
108
275
  * Default: 24 (a conservative off-row-pointer floor).
109
276
  */
110
- EstimateInRowBytes(_rawSqlType) {
111
- return 24;
277
+ EstimateInRowBytes(rawSqlType) {
278
+ return this.DDL.EstimateInRowBytes(rawSqlType);
279
+ }
280
+ /** SQL type names this dialect uses for date / time / timestamp columns. */
281
+ get DateTypeNames() {
282
+ return this.Types.DateTypeNames;
283
+ }
284
+ /** SQL type names this dialect uses for integer columns (int, bigint, smallint, …). */
285
+ get IntegerTypeNames() {
286
+ return this.Types.IntegerTypeNames;
287
+ }
288
+ /** SQL type names this dialect uses for floating-point / decimal columns. */
289
+ get FloatTypeNames() {
290
+ return this.Types.FloatTypeNames;
291
+ }
292
+ /** SQL type names this dialect uses for UUID / uniqueidentifier columns. */
293
+ get UuidTypeNames() {
294
+ return this.Types.UuidTypeNames;
295
+ }
296
+ /** SQL type names this dialect uses for binary blob columns (image, bytea, varbinary). */
297
+ get BinaryTypeNames() {
298
+ return this.Types.BinaryTypeNames;
299
+ }
300
+ /** SQL type names this dialect uses for JSON / XML structured columns. */
301
+ get JsonTypeNames() {
302
+ return this.Types.JsonTypeNames;
303
+ }
304
+ /** SQL type names this dialect uses for fixed-precision currency columns. */
305
+ get CurrencyTypeNames() {
306
+ return this.Types.CurrencyTypeNames;
307
+ }
308
+ /** SQL type names this dialect uses for interval / duration columns. */
309
+ get IntervalTypeNames() {
310
+ return this.Types.IntervalTypeNames;
311
+ }
312
+ /** SQL type names this dialect uses for network address columns (inet, cidr, …). */
313
+ get NetworkTypeNames() {
314
+ return this.Types.NetworkTypeNames;
315
+ }
316
+ /**
317
+ * Returns a new UUID generation expression.
318
+ * SQL Server: NEWID(), PostgreSQL: gen_random_uuid()
319
+ */
320
+ NewUUID() {
321
+ return this.DDL.NewUUID();
322
+ }
323
+ /**
324
+ * Returns the platform's n-ary null-coalescing expression. SQL Server and
325
+ * PostgreSQL both spell this `COALESCE(...)`; the dialect's writer owns
326
+ * the spelling.
327
+ */
328
+ Coalesce(expr, fallback) {
329
+ return this.Writer.Coalesce(expr, fallback);
112
330
  }
113
331
  /**
114
332
  * Returns the dialect's literal representation of NULL as it would
@@ -118,7 +336,7 @@ export class SQLDialect {
118
336
  * should route through this rather than hard-coding the string.
119
337
  */
120
338
  get NullLiteral() {
121
- return 'NULL';
339
+ return this.Writer.NullLiteral;
122
340
  }
123
341
  /**
124
342
  * Returns true if `value` is the dialect's representation of a NULL
@@ -131,6 +349,31 @@ export class SQLDialect {
131
349
  return false;
132
350
  return value.trim().toUpperCase() === this.NullLiteral.toUpperCase();
133
351
  }
352
+ /**
353
+ * Returns the parameter-reference syntax used by this dialect's
354
+ * stored-procedure / function bodies.
355
+ * SQL Server: `@MyName`, PostgreSQL functions: `p_my_name`.
356
+ * Codegen should call this rather than hard-coding `'@' + name`.
357
+ */
358
+ ParameterRef(name) {
359
+ return this.DDL.ParameterRef(name);
360
+ }
361
+ /**
362
+ * Returns the default-value clause appended to a parameter declaration.
363
+ * SQL Server: ` = NULL` (or ` = 0`, etc.), PostgreSQL: ` DEFAULT NULL`.
364
+ * `value` should be a SQL literal already formatted by the caller (e.g.
365
+ * the dialect's NullLiteral, a quoted string, a numeric literal).
366
+ */
367
+ ParameterDefault(value) {
368
+ return this.DDL.ParameterDefault(value);
369
+ }
370
+ /**
371
+ * Returns a CAST-to-text expression.
372
+ * SQL Server: CAST(expr AS NVARCHAR(MAX)), PostgreSQL: CAST(expr AS TEXT)
373
+ */
374
+ CastToText(expr) {
375
+ return this.Writer.CastToText(expr);
376
+ }
134
377
  /**
135
378
  * Returns a CAST to a bounded-width string type. Used when the result
136
379
  * needs to be comparable against an indexed column (SQL Server cannot
@@ -143,8 +386,14 @@ export class SQLDialect {
143
386
  * width to match the cap on indexable string columns in SQL Server.
144
387
  */
145
388
  CastToBoundedString(expr, maxLength = 450) {
146
- const sqlType = this.ResolveAbstractType({ type: 'string', maxLength });
147
- return `CAST(${expr} AS ${sqlType})`;
389
+ return this.DDL.CastToBoundedString(expr, maxLength);
390
+ }
391
+ /**
392
+ * Returns a CAST-to-UUID expression.
393
+ * SQL Server: CAST(expr AS UNIQUEIDENTIFIER), PostgreSQL: CAST(expr AS UUID)
394
+ */
395
+ CastToUUID(expr) {
396
+ return this.DDL.CastToUUID(expr);
148
397
  }
149
398
  /**
150
399
  * Returns the empty-GUID sentinel literal
@@ -155,7 +404,52 @@ export class SQLDialect {
155
404
  * the explicit cast their grammar requires.
156
405
  */
157
406
  EmptyUUIDLiteral() {
158
- return `'00000000-0000-0000-0000-000000000000'`;
407
+ return this.DDL.EmptyUUIDLiteral();
408
+ }
409
+ // ─── INSERT/UPDATE Return Patterns ───────────────────────────────
410
+ /**
411
+ * Returns the clause used to get inserted values back.
412
+ * SQL Server: OUTPUT INSERTED.col1, INSERTED.col2
413
+ * PostgreSQL: RETURNING col1, col2
414
+ */
415
+ ReturnInsertedClause(columns) {
416
+ return this.DDL.ReturnInsertedClause(columns);
417
+ }
418
+ /**
419
+ * Returns the auto-increment PK expression for DDL.
420
+ * SQL Server: IDENTITY(1,1), PostgreSQL: GENERATED ALWAYS AS IDENTITY
421
+ */
422
+ AutoIncrementPKExpression() {
423
+ return this.DDL.AutoIncrementPKExpression();
424
+ }
425
+ /**
426
+ * Returns the default expression for a UUID primary key.
427
+ * SQL Server: NEWSEQUENTIALID(), PostgreSQL: gen_random_uuid()
428
+ */
429
+ UUIDPKDefault() {
430
+ return this.DDL.UUIDPKDefault();
431
+ }
432
+ /**
433
+ * Returns the expression to get the last inserted identity value.
434
+ * SQL Server: SCOPE_IDENTITY(), PostgreSQL: lastval()
435
+ */
436
+ ScopeIdentityExpression() {
437
+ return this.DDL.ScopeIdentityExpression();
438
+ }
439
+ /**
440
+ * Returns the row count variable/expression for the last statement.
441
+ * SQL Server: @@ROWCOUNT, PostgreSQL: (via GET DIAGNOSTICS or FOUND)
442
+ */
443
+ RowCountExpression() {
444
+ return this.DDL.RowCountExpression();
445
+ }
446
+ // ─── Batch & DDL Control ─────────────────────────────────────────
447
+ /**
448
+ * Returns the batch separator for the platform.
449
+ * SQL Server: "GO", PostgreSQL: "" (none needed)
450
+ */
451
+ BatchSeparator() {
452
+ return this.DDL.BatchSeparator();
159
453
  }
160
454
  /**
161
455
  * Splits an oversized SQL batch into individual statements on `;`+EOL
@@ -172,11 +466,109 @@ export class SQLDialect {
172
466
  * legitimately contain `;`+newline.
173
467
  */
174
468
  SplitStatements(batch) {
175
- return batch
176
- .split(/;\s*\n/g)
177
- .map((s) => s.trim())
178
- .filter((s) => s.length > 0)
179
- .map((s) => (s.endsWith(';') ? s : s + ';'));
469
+ return this.DDL.SplitStatements(batch);
470
+ }
471
+ /**
472
+ * Returns SQL to check if a database object exists.
473
+ * @param objectType - "TABLE", "VIEW", "FUNCTION", "PROCEDURE", "TRIGGER"
474
+ * @param schema - Schema name
475
+ * @param name - Object name
476
+ */
477
+ ExistenceCheckSQL(objectType, schema, name) {
478
+ return this.DDL.ExistenceCheckSQL(objectType, schema, name);
479
+ }
480
+ /**
481
+ * Whether the platform supports CREATE OR REPLACE for a given object type.
482
+ * PostgreSQL supports it for FUNCTION, VIEW. SQL Server does not.
483
+ */
484
+ CreateOrReplaceSupported(objectType) {
485
+ return this.DDL.CreateOrReplaceSupported(objectType);
486
+ }
487
+ // ─── Full-Text Search ────────────────────────────────────────────
488
+ /**
489
+ * Returns a full-text search predicate expression.
490
+ * SQL Server: CONTAINS(column, searchTerm)
491
+ * PostgreSQL: column @@ plainto_tsquery('english', searchTerm)
492
+ */
493
+ FullTextSearchPredicate(column, searchTerm) {
494
+ return this.DDL.FullTextSearchPredicate(column, searchTerm);
495
+ }
496
+ /**
497
+ * Returns DDL to create a full-text index.
498
+ * SQL Server: FULLTEXT CATALOG + FULLTEXT INDEX
499
+ * PostgreSQL: tsvector column + GIN index
500
+ */
501
+ FullTextIndexDDL(table, columns, catalog) {
502
+ return this.DDL.FullTextIndexDDL(table, columns, catalog);
503
+ }
504
+ // ─── CTE / Recursion ─────────────────────────────────────────────
505
+ /**
506
+ * Returns the recursive CTE syntax keyword.
507
+ * SQL Server: "WITH", PostgreSQL: "WITH RECURSIVE"
508
+ */
509
+ RecursiveCTESyntax() {
510
+ const keyword = this.Grammar.RecursiveKeyword;
511
+ return keyword === null ? 'WITH' : `WITH ${keyword}`;
512
+ }
513
+ /**
514
+ * Whether the platform allows ORDER BY inside CTE definitions without
515
+ * TOP, OFFSET, or FOR XML.
516
+ * SQL Server: false (ORDER BY in CTEs is illegal without TOP/OFFSET/FOR XML)
517
+ * PostgreSQL: true (ORDER BY in CTEs is always legal)
518
+ */
519
+ get AllowsOrderByInCTE() {
520
+ return this.Grammar.AllowsOrderByInCTE;
521
+ }
522
+ /**
523
+ * Default ORDER BY expression for paging when no user-specified ORDER BY exists.
524
+ * SQL Server: '(SELECT NULL)', PostgreSQL: '1'
525
+ */
526
+ get DefaultPagingOrderBy() {
527
+ return this.Grammar.DefaultPagingOrderBy;
528
+ }
529
+ /**
530
+ * The ORDER BY expression for paging a set operation (`UNION` / `INTERSECT` / `EXCEPT`) or a
531
+ * `SELECT DISTINCT` that has no ORDER BY of its own, on a platform that only accepts select-list
532
+ * items there. `null` when {@link DefaultPagingOrderBy} is accepted for those shapes too.
533
+ * SQL Server: '1' (the first column), PostgreSQL: null
534
+ */
535
+ get SelectListPagingOrderBy() {
536
+ return this.Grammar.SelectListPagingOrderBy;
537
+ }
538
+ /**
539
+ * Whether skipping rows for a page needs an ORDER BY (`OFFSET … FETCH` does on SQL Server).
540
+ * When true, a page taken from a derived table is ordered by {@link DefaultPagingOrderBy}.
541
+ * SQL Server: true, PostgreSQL: false
542
+ */
543
+ get PagingRequiresOrderBy() {
544
+ return this.Grammar.PagingRequiresOrderBy;
545
+ }
546
+ /** {@inheritDoc SQLParserDialect.SupportsEscapeStringLiterals} */
547
+ get SupportsEscapeStringLiterals() {
548
+ return this.Lexical.StringLiterals.some(form => form.BackslashEscape && form.Prefixes.some(prefix => prefix.toUpperCase() === 'E'));
549
+ }
550
+ /** {@inheritDoc SQLParserDialect.SupportsDollarQuotedStrings} */
551
+ get SupportsDollarQuotedStrings() {
552
+ return this.Lexical.DollarQuotedStrings !== 'none';
553
+ }
554
+ /** {@inheritDoc SQLParserDialect.QueryHintKeyword} */
555
+ get QueryHintKeyword() {
556
+ return this.Grammar.QueryHintKeyword;
557
+ }
558
+ /** {@inheritDoc SQLParserDialect.CallerSQLForbiddenFunctions} */
559
+ get CallerSQLForbiddenFunctions() {
560
+ return this.Grammar.CallerSQLForbiddenFunctions;
561
+ }
562
+ /** {@inheritDoc SQLParserDialect.UnseparatedStatementKeywords} */
563
+ get UnseparatedStatementKeywords() {
564
+ return this.Grammar.UnseparatedStatementKeywords ?? [];
565
+ }
566
+ // ─── Data Types ──────────────────────────────────────────────────
567
+ /**
568
+ * Returns the data type mapping for this dialect.
569
+ */
570
+ get TypeMap() {
571
+ return this.DDL.TypeMap;
180
572
  }
181
573
  /**
182
574
  * Convenience: maps a SQL Server type to this dialect's equivalent.
@@ -190,6 +582,71 @@ export class SQLDialect {
190
582
  MapDataTypeToString(sqlServerType, length, precision, scale) {
191
583
  return this.TypeMap.MapTypeToString(sqlServerType, length, precision, scale);
192
584
  }
585
+ // ─── Parameters ──────────────────────────────────────────────────
586
+ /**
587
+ * Returns a parameter placeholder for the given index.
588
+ * SQL Server: @p0, @p1, ... PostgreSQL: $1, $2, ...
589
+ */
590
+ ParameterPlaceholder(index) {
591
+ return this.Binding.ParameterPlaceholder(index);
592
+ }
593
+ /**
594
+ * Returns the string concatenation operator.
595
+ * SQL Server: "+", PostgreSQL: "||"
596
+ */
597
+ ConcatOperator() {
598
+ const operator = this.Writer.ConcatOperator();
599
+ if (operator === null) {
600
+ throw new Error(`The ${this.PlatformKey} dialect has no string concatenation operator.`);
601
+ }
602
+ return operator;
603
+ }
604
+ // ─── String Functions ────────────────────────────────────────────
605
+ /**
606
+ * Returns a STRING_SPLIT or equivalent expression.
607
+ * SQL Server: STRING_SPLIT(value, delimiter)
608
+ * PostgreSQL: string_to_array(value, delimiter) or regexp_split_to_table
609
+ */
610
+ StringSplitFunction(value, delimiter) {
611
+ return this.DDL.StringSplitFunction(value, delimiter);
612
+ }
613
+ /**
614
+ * Returns a JSON value extraction expression.
615
+ * SQL Server: JSON_VALUE(column, path)
616
+ * PostgreSQL: column->>'path' or jsonb_extract_path_text
617
+ */
618
+ JsonExtract(column, path) {
619
+ return this.Writer.JsonExtract(column, path);
620
+ }
621
+ // ─── Migration Emission ──────────────────────────────────────────
622
+ /**
623
+ * Splits `${...}` inside SQL string literals so Flyway doesn't treat
624
+ * them as placeholders. Each `${name}` becomes a concat-split that
625
+ * round-trips back to `${name}` at execution but contains no adjacent
626
+ * `${` in the file text. Form is platform-specific (concat operator,
627
+ * truncation rules) — see each dialect's implementation.
628
+ */
629
+ EscapeFlywayStringInterpolation(sql) {
630
+ return this.DDL.EscapeFlywayStringInterpolation(sql);
631
+ }
632
+ // ─── Procedure / Function Calls ──────────────────────────────────
633
+ /**
634
+ * Returns the SQL syntax for calling a stored procedure or function.
635
+ * SQL Server: EXEC [schema].[name] @p0, @p1
636
+ * PostgreSQL: SELECT * FROM schema.name($1, $2)
637
+ */
638
+ ProcedureCallSyntax(schema, name, params) {
639
+ return this.DDL.ProcedureCallSyntax(schema, name, params);
640
+ }
641
+ // ─── DDL Generation (Schema/Table) ──────────────────────────────
642
+ /**
643
+ * Returns CREATE SCHEMA IF NOT EXISTS SQL.
644
+ * SQL Server: IF NOT EXISTS (...) EXEC('CREATE SCHEMA [name]'); GO
645
+ * PostgreSQL: CREATE SCHEMA IF NOT EXISTS "name";
646
+ */
647
+ CreateSchemaDDL(schemaName) {
648
+ return this.DDL.CreateSchemaDDL(schemaName);
649
+ }
193
650
  /**
194
651
  * Cap a column type if it cannot be used in a UNIQUE/index constraint.
195
652
  * SQL Server: NVARCHAR(MAX) → NVARCHAR(450) (MAX columns cannot be indexed).
@@ -197,7 +654,127 @@ export class SQLDialect {
197
654
  * Override in platform-specific dialects.
198
655
  */
199
656
  CapIndexableType(rawSqlType) {
200
- return rawSqlType;
657
+ return this.DDL.CapIndexableType(rawSqlType);
658
+ }
659
+ /**
660
+ * Returns the ADD COLUMN clause for ALTER TABLE.
661
+ * SQL Server: ADD [colName] type NULL DEFAULT ...
662
+ * PostgreSQL: ADD COLUMN "colName" type NULL DEFAULT ...
663
+ */
664
+ AddColumnClause(col) {
665
+ return this.DDL.AddColumnClause(col);
666
+ }
667
+ /**
668
+ * Returns ALTER COLUMN clause(s) for type/nullability changes.
669
+ * SQL Server: ALTER TABLE t ALTER COLUMN [col] newType NULL/NOT NULL;
670
+ * PostgreSQL: ALTER TABLE t ALTER COLUMN "col" TYPE newType, ALTER COLUMN "col" SET/DROP NOT NULL;
671
+ */
672
+ AlterColumnDDL(quotedTable, options) {
673
+ return this.DDL.AlterColumnDDL(quotedTable, options);
674
+ }
675
+ /**
676
+ * Returns description metadata SQL for a column.
677
+ * SQL Server: EXEC sp_addextendedproperty with @level2type = 'COLUMN'
678
+ * PostgreSQL: COMMENT ON COLUMN schema."table"."column" IS '...';
679
+ *
680
+ * This extends CommentOnObject to support the 3-part column reference
681
+ * that CommentOnObject doesn't handle.
682
+ */
683
+ CommentOnColumn(schema, table, column, comment) {
684
+ return this.DDL.CommentOnColumn(schema, table, column, comment);
685
+ }
686
+ /**
687
+ * Returns the platform's fallback type for unknown/unmapped abstract types.
688
+ * SQL Server: NVARCHAR(MAX)
689
+ * PostgreSQL: TEXT
690
+ */
691
+ FallbackType() {
692
+ return this.DDL.FallbackType();
693
+ }
694
+ /**
695
+ * Resolves an abstract schema field type to a concrete SQL type string.
696
+ * Used by SchemaEngine for DDL generation from platform-agnostic definitions.
697
+ * SQL Server: 'string' -> 'NVARCHAR(255)', 'boolean' -> 'BIT'
698
+ * PostgreSQL: 'string' -> 'VARCHAR(255)', 'boolean' -> 'BOOLEAN'
699
+ */
700
+ ResolveAbstractType(options) {
701
+ return this.DDL.ResolveAbstractType(options);
702
+ }
703
+ // ─── DDL Generation (Conditional/Procedural) ────────────────────
704
+ /**
705
+ * Returns a date/time arithmetic expression.
706
+ * SQL Server: DATEADD(MINUTE, 30, GETUTCDATE())
707
+ * PostgreSQL: (NOW() AT TIME ZONE 'UTC') + INTERVAL '30 minutes'
708
+ *
709
+ * @param unit - Time unit
710
+ * @param amount - Number of units to add (can be negative)
711
+ * @param baseExpr - Base timestamp expression (e.g., from CurrentTimestampUTC())
712
+ */
713
+ DateAddExpression(unit, amount, baseExpr) {
714
+ return this.Writer.DateAddExpression(unit, amount, baseExpr);
715
+ }
716
+ /**
717
+ * Returns a full CREATE TABLE wrapped in a "create if not exists" guard.
718
+ * SQL Server: IF NOT EXISTS (sys.tables check) BEGIN CREATE TABLE ... END;
719
+ * PostgreSQL: CREATE TABLE IF NOT EXISTS ...;
720
+ *
721
+ * @param schema - Schema name
722
+ * @param tableName - Table name
723
+ * @param columnsDDL - The column definitions (everything between the parentheses)
724
+ */
725
+ CreateTableIfNotExistsDDL(schema, tableName, columnsDDL) {
726
+ return this.DDL.CreateTableIfNotExistsDDL(schema, tableName, columnsDDL);
727
+ }
728
+ /**
729
+ * Returns a conditional IF/ELSE block in platform-appropriate procedural SQL.
730
+ * SQL Server: IF (condition) BEGIN thenSQL END ELSE BEGIN elseSQL END
731
+ * PostgreSQL: DO $$ BEGIN IF condition THEN thenSQL; ELSE elseSQL; END IF; END $$;
732
+ *
733
+ * @param condition - SQL boolean condition
734
+ * @param thenSQL - SQL to execute when condition is true
735
+ * @param elseSQL - Optional SQL to execute when condition is false
736
+ */
737
+ ConditionalBlock(condition, thenSQL, elseSQL) {
738
+ return this.DDL.ConditionalBlock(condition, thenSQL, elseSQL);
739
+ }
740
+ /**
741
+ * Returns a non-fatal signal/notice statement detectable in CLI output.
742
+ * Used for signaling conditions (e.g., "lock held") without aborting the script.
743
+ * SQL Server: RAISERROR('message', 16, 1) — appears in sqlcmd stdout
744
+ * PostgreSQL: RAISE NOTICE 'message' — appears in psql stderr
745
+ *
746
+ * Note: For PostgreSQL, this must be used inside a ConditionalBlock (DO $$ context).
747
+ *
748
+ * @param message - Signal message to emit (used for detection in CLI output)
749
+ */
750
+ RaiseSignalSQL(message) {
751
+ return this.DDL.RaiseSignalSQL(message);
752
+ }
753
+ // ─── DDL Generation (Triggers/Indexes) ──────────────────────────
754
+ /**
755
+ * Generates trigger DDL for the platform.
756
+ */
757
+ TriggerDDL(options) {
758
+ return this.DDL.TriggerDDL(options);
759
+ }
760
+ /**
761
+ * Generates index DDL for the platform.
762
+ */
763
+ IndexDDL(options) {
764
+ return this.DDL.IndexDDL(options);
765
+ }
766
+ // ─── Permissions ─────────────────────────────────────────────────
767
+ /**
768
+ * Returns a GRANT statement for the platform.
769
+ */
770
+ GrantPermission(permission, objectType, schema, object, role) {
771
+ return this.DDL.GrantPermission(permission, objectType, schema, object, role);
772
+ }
773
+ /**
774
+ * Returns a COMMENT ON statement (PostgreSQL) or sp_addextendedproperty (SQL Server).
775
+ */
776
+ CommentOnObject(objectType, schema, name, comment) {
777
+ return this.DDL.CommentOnObject(objectType, schema, name, comment);
201
778
  }
202
779
  // ─── DDL Generation (Idempotent, single-statement) ──────────────
203
780
  //
@@ -216,7 +793,7 @@ export class SQLDialect {
216
793
  * @param columnsBody - The column/constraint lines that go between the parentheses
217
794
  */
218
795
  CreateTableIfAbsent(fullTable, columnsBody) {
219
- return `CREATE TABLE IF NOT EXISTS ${fullTable} (\n${columnsBody}\n);`;
796
+ return this.DDL.CreateTableIfAbsent(fullTable, columnsBody);
220
797
  }
221
798
  /**
222
799
  * CommentOnObject that is safe to re-run (no error if the description already exists).
@@ -225,7 +802,7 @@ export class SQLDialect {
225
802
  * SQL Server overrides to guard sp_addextendedproperty with a fn_listextendedproperty check.
226
803
  */
227
804
  CommentOnObjectIfAbsent(objectType, schema, name, comment) {
228
- return this.CommentOnObject(objectType, schema, name, comment) + ';';
805
+ return this.DDL.CommentOnObjectIfAbsent(objectType, schema, name, comment);
229
806
  }
230
807
  /**
231
808
  * CommentOnColumn that is safe to re-run. Default returns the standard statement
@@ -233,7 +810,111 @@ export class SQLDialect {
233
810
  * SQL Server overrides to guard sp_addextendedproperty.
234
811
  */
235
812
  CommentOnColumnIfAbsent(schema, table, column, comment) {
236
- return this.CommentOnColumn(schema, table, column, comment);
813
+ return this.DDL.CommentOnColumnIfAbsent(schema, table, column, comment);
814
+ }
815
+ // ─── Schema Introspection ────────────────────────────────────────
816
+ /**
817
+ * Returns platform-specific schema introspection queries.
818
+ */
819
+ SchemaIntrospectionQueries() {
820
+ return this.DDL.SchemaIntrospectionQueries();
821
+ }
822
+ /**
823
+ * Returns a ready-to-run (no bind parameters) query that enumerates the foreign-key graph
824
+ * of a single schema, for FK-cascade planning (e.g. Open-App metadata teardown).
825
+ *
826
+ * Unlike {@link SchemaIntrospectionQueries}.`listForeignKeys` (a placeholder template), this
827
+ * embeds the schema literal directly (via {@link QuoteStringLiteral}) so it can be executed
828
+ * with `ExecuteSQL(sql)` on any provider without a dialect-specific bind convention. It also
829
+ * returns two extra columns the cascade planner needs:
830
+ *
831
+ * - `childNullable` — whether the referencing (child) column allows NULL, which decides
832
+ * `UPDATE … SET NULL` (nullable) vs. `DELETE` + recurse (NOT NULL).
833
+ * - `colCount` — the number of columns in the FK constraint, so a caller can exclude
834
+ * composite FKs (`colCount > 1`).
835
+ *
836
+ * Every row is one FK column. Column aliases are IDENTICAL across dialects:
837
+ * `parentTable, parentRefCol, childTable, childCol, childNullable, fkName, colCount`
838
+ * (both the referenced/parent and referencing/child tables are within `schema`).
839
+ *
840
+ * @param schema the schema whose intra-schema FK edges to enumerate (e.g. `__mj`)
841
+ */
842
+ ForeignKeyGraphSQL(schema) {
843
+ return this.DDL.ForeignKeyGraphSQL(schema);
844
+ }
845
+ /**
846
+ * Wraps a list of statements in ONE all-or-nothing transaction batch for this platform, ready to
847
+ * run as a single `ExecuteSQL(script)` call. Owns the platform-specific session/transaction setup
848
+ * so callers don't sniff `PlatformKey` themselves:
849
+ *
850
+ * - **SQL Server**: `SET QUOTED_IDENTIFIER ON` / `SET ANSI_NULLS ON` (required for UPDATE/DELETE
851
+ * against tables with filtered / computed-column indexes or indexed views — Msg 1934 otherwise)
852
+ * + `SET XACT_ABORT ON` (any failure rolls the whole batch back) + `BEGIN/COMMIT TRANSACTION`.
853
+ * - **PostgreSQL**: plain `BEGIN … COMMIT` — no session pragmas (`QUOTED_IDENTIFIER`/`ANSI_NULLS`
854
+ * are SQL-Server concepts) and PostgreSQL already aborts the whole transaction on any error.
855
+ *
856
+ * Returns an empty string for an empty statement list (nothing to run).
857
+ *
858
+ * @param statements individual SQL statements (each WITHOUT a trailing `;`)
859
+ */
860
+ AtomicBatchScript(statements) {
861
+ return this.DDL.AtomicBatchScript(statements);
862
+ }
863
+ // ─── Null Handling ───────────────────────────────────────────────
864
+ /**
865
+ * Returns the platform's two-argument null-coalescing expression.
866
+ * SQL Server: `ISNULL(expr, fallback)`, PostgreSQL: `COALESCE(expr, fallback)`.
867
+ * The dialect's writer declares the keyword.
868
+ */
869
+ IsNull(expr, fallback) {
870
+ return this.Writer.IsNull(expr, fallback);
871
+ }
872
+ // ─── Error Classification ───────────────────────────────────────
873
+ /**
874
+ * Returns true if the given error represents an infrastructure-level
875
+ * connection failure (timeout, refused, pool closed, etc.) as opposed to
876
+ * a query-level error (bad SQL, constraint violation).
877
+ *
878
+ * Each dialect implements this using its driver's structured error types:
879
+ * - SQL Server (mssql): `error.name === 'ConnectionError'`
880
+ * - PostgreSQL (pg): Node.js network error codes on plain `Error`
881
+ *
882
+ * Used by GenericDatabaseProvider to re-throw connection errors from
883
+ * RunView/RunQuery instead of swallowing them into `{ Success: false }`.
884
+ */
885
+ IsConnectionError(e) {
886
+ return this.Binding.IsConnectionError(e);
887
+ }
888
+ /**
889
+ * Returns an IIF/CASE equivalent expression.
890
+ * SQL Server: IIF(condition, trueVal, falseVal)
891
+ * PostgreSQL: CASE WHEN condition THEN trueVal ELSE falseVal END
892
+ */
893
+ IIF(condition, trueVal, falseVal) {
894
+ return this.Writer.IIF(condition, trueVal, falseVal);
895
+ }
896
+ // ─── Nested transactions (savepoints) ────────────────────────────
897
+ /**
898
+ * SQL that marks a nested transaction savepoint. SQL Server:
899
+ * `SAVE TRANSACTION name`. PostgreSQL: `SAVEPOINT name`.
900
+ */
901
+ CreateSavepointSQL(name) {
902
+ return this.DDL.CreateSavepointSQL(name);
903
+ }
904
+ /**
905
+ * SQL that discards a savepoint after a nested commit, or `null` when the
906
+ * platform has no release (SQL Server savepoints live until the outer TX
907
+ * ends). PostgreSQL: `RELEASE SAVEPOINT name`.
908
+ */
909
+ ReleaseSavepointSQL(name) {
910
+ return this.DDL.ReleaseSavepointSQL(name);
911
+ }
912
+ /**
913
+ * SQL that undoes work after a savepoint. SQL Server:
914
+ * `ROLLBACK TRANSACTION name`. PostgreSQL: `ROLLBACK TO SAVEPOINT name`.
915
+ */
916
+ RollbackToSavepointSQL(name) {
917
+ return this.DDL.RollbackToSavepointSQL(name);
237
918
  }
238
919
  }
239
920
  //# sourceMappingURL=sqlDialect.js.map