@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,131 +1,26 @@
1
- import { SQLDialect, } from './sqlDialect.js';
1
+ import { SQLDialect } from './sqlDialect.js';
2
+ import { ANSI_GRAMMAR, ANSI_LEXICAL, ANSI_WRITE_STATEMENT_KEYWORDS, AnsiWriter } from './dialects/ansi.js';
3
+ import { PostgreSQLSchemaDDL } from './dialects/postgresqlSchemaDDL.js';
2
4
  /**
3
- * PostgreSQL data type mapping.
4
- * Maps SQL Server types to their PostgreSQL equivalents.
5
+ * PostgreSQL lexical rules: `"…"` identifiers, `'…'` / `N'…'` strings with doubled quotes,
6
+ * `E'…'` strings with backslash escapes, `$$…$$` / `$tag$…$tag$` dollar quoting, `--` line
7
+ * comments and nested block comments, `$1` parameters, unquoted names folded to lower case.
8
+ *
9
+ * All from https://www.postgresql.org/docs/current/sql-syntax-lexical.html (4.1.1 identifiers and
10
+ * case folding, 4.1.2.2 escape strings, 4.1.2.4 dollar quoting, 4.1.4 positional parameters,
11
+ * 4.1.5 comments).
5
12
  */
6
- class PostgreSQLDataTypeMap {
7
- MapType(sourceType, sourceLength, sourcePrecision, sourceScale) {
8
- const normalized = sourceType.toUpperCase().trim();
9
- switch (normalized) {
10
- case 'UNIQUEIDENTIFIER':
11
- return { typeName: 'UUID', supportsLength: false, supportsPrecisionScale: false };
12
- case 'NVARCHAR':
13
- return this.mapNVarchar(sourceLength);
14
- case 'VARCHAR':
15
- return this.mapVarchar(sourceLength);
16
- case 'NCHAR':
17
- case 'CHAR':
18
- return { typeName: 'CHAR', supportsLength: true, supportsPrecisionScale: false, defaultLength: sourceLength ?? 1 };
19
- case 'INT':
20
- case 'INTEGER':
21
- return { typeName: 'INTEGER', supportsLength: false, supportsPrecisionScale: false };
22
- case 'BIGINT':
23
- return { typeName: 'BIGINT', supportsLength: false, supportsPrecisionScale: false };
24
- case 'SMALLINT':
25
- return { typeName: 'SMALLINT', supportsLength: false, supportsPrecisionScale: false };
26
- case 'TINYINT':
27
- return { typeName: 'SMALLINT', supportsLength: false, supportsPrecisionScale: false };
28
- case 'BIT':
29
- return { typeName: 'BOOLEAN', supportsLength: false, supportsPrecisionScale: false };
30
- case 'DECIMAL':
31
- case 'NUMERIC':
32
- return { typeName: 'NUMERIC', supportsLength: false, supportsPrecisionScale: true };
33
- case 'FLOAT':
34
- return this.mapFloat(sourcePrecision);
35
- case 'REAL':
36
- return { typeName: 'REAL', supportsLength: false, supportsPrecisionScale: false };
37
- case 'MONEY':
38
- return { typeName: 'NUMERIC(19,4)', supportsLength: false, supportsPrecisionScale: false };
39
- case 'SMALLMONEY':
40
- return { typeName: 'NUMERIC(10,4)', supportsLength: false, supportsPrecisionScale: false };
41
- case 'DATE':
42
- return { typeName: 'DATE', supportsLength: false, supportsPrecisionScale: false };
43
- case 'DATETIME':
44
- case 'DATETIME2':
45
- return { typeName: 'TIMESTAMP', supportsLength: false, supportsPrecisionScale: false };
46
- case 'DATETIMEOFFSET':
47
- return { typeName: 'TIMESTAMPTZ', supportsLength: false, supportsPrecisionScale: false };
48
- case 'SMALLDATETIME':
49
- return { typeName: 'TIMESTAMP(0)', supportsLength: false, supportsPrecisionScale: false };
50
- case 'TIME':
51
- return { typeName: 'TIME', supportsLength: false, supportsPrecisionScale: false };
52
- case 'TEXT':
53
- case 'NTEXT':
54
- return { typeName: 'TEXT', supportsLength: false, supportsPrecisionScale: false };
55
- case 'IMAGE':
56
- return { typeName: 'BYTEA', supportsLength: false, supportsPrecisionScale: false };
57
- case 'VARBINARY':
58
- return { typeName: 'BYTEA', supportsLength: false, supportsPrecisionScale: false };
59
- case 'BINARY':
60
- return { typeName: 'BYTEA', supportsLength: false, supportsPrecisionScale: false };
61
- case 'XML':
62
- return { typeName: 'XML', supportsLength: false, supportsPrecisionScale: false };
63
- // PostgreSQL native types (pass through)
64
- case 'UUID':
65
- return { typeName: 'UUID', supportsLength: false, supportsPrecisionScale: false };
66
- case 'BOOLEAN':
67
- return { typeName: 'BOOLEAN', supportsLength: false, supportsPrecisionScale: false };
68
- case 'TIMESTAMPTZ':
69
- return { typeName: 'TIMESTAMPTZ', supportsLength: false, supportsPrecisionScale: false };
70
- case 'TIMESTAMP':
71
- return { typeName: 'TIMESTAMP', supportsLength: false, supportsPrecisionScale: false };
72
- case 'BYTEA':
73
- return { typeName: 'BYTEA', supportsLength: false, supportsPrecisionScale: false };
74
- case 'JSONB':
75
- return { typeName: 'JSONB', supportsLength: false, supportsPrecisionScale: false };
76
- case 'JSON':
77
- return { typeName: 'JSON', supportsLength: false, supportsPrecisionScale: false };
78
- case 'SERIAL':
79
- return { typeName: 'SERIAL', supportsLength: false, supportsPrecisionScale: false };
80
- case 'BIGSERIAL':
81
- return { typeName: 'BIGSERIAL', supportsLength: false, supportsPrecisionScale: false };
82
- case 'DOUBLE PRECISION':
83
- return { typeName: 'DOUBLE PRECISION', supportsLength: false, supportsPrecisionScale: false };
84
- default:
85
- return { typeName: normalized, supportsLength: false, supportsPrecisionScale: false };
86
- }
87
- }
88
- MapTypeToString(sourceType, sourceLength, sourcePrecision, sourceScale) {
89
- const mapped = this.MapType(sourceType, sourceLength, sourcePrecision, sourceScale);
90
- return formatTypeString(mapped, sourceLength, sourcePrecision, sourceScale);
91
- }
92
- mapNVarchar(length) {
93
- if (length === -1 || length === undefined) {
94
- return { typeName: 'TEXT', supportsLength: false, supportsPrecisionScale: false };
95
- }
96
- return { typeName: 'VARCHAR', supportsLength: true, supportsPrecisionScale: false, defaultLength: length };
97
- }
98
- mapVarchar(length) {
99
- if (length === -1 || length === undefined) {
100
- return { typeName: 'TEXT', supportsLength: false, supportsPrecisionScale: false };
101
- }
102
- return { typeName: 'VARCHAR', supportsLength: true, supportsPrecisionScale: false, defaultLength: length };
103
- }
104
- mapFloat(precision) {
105
- // SQL Server FLOAT(1-24) = REAL, FLOAT(25-53) = DOUBLE PRECISION
106
- if (precision != null && precision <= 24) {
107
- return { typeName: 'REAL', supportsLength: false, supportsPrecisionScale: false };
108
- }
109
- return { typeName: 'DOUBLE PRECISION', supportsLength: false, supportsPrecisionScale: false };
110
- }
111
- }
112
- /**
113
- * Helper to format a MappedType into a full SQL type string.
114
- */
115
- function formatTypeString(mapped, length, precision, scale) {
116
- if (mapped.supportsPrecisionScale && precision != null) {
117
- return scale != null
118
- ? `${mapped.typeName}(${precision},${scale})`
119
- : `${mapped.typeName}(${precision})`;
120
- }
121
- if (mapped.supportsLength) {
122
- const len = length ?? mapped.defaultLength;
123
- if (len != null) {
124
- return len === -1 ? 'TEXT' : `${mapped.typeName}(${len})`;
125
- }
126
- }
127
- return mapped.typeName;
128
- }
13
+ export const POSTGRESQL_LEXICAL = Object.freeze({
14
+ ...ANSI_LEXICAL,
15
+ StringLiterals: Object.freeze([
16
+ Object.freeze({ Prefixes: Object.freeze(['', 'N']), Quote: "'", DoubledQuoteEscape: true, BackslashEscape: false }),
17
+ Object.freeze({ Prefixes: Object.freeze(['E']), Quote: "'", DoubledQuoteEscape: true, BackslashEscape: true }),
18
+ ]),
19
+ DollarQuotedStrings: 'tagged',
20
+ BlockComments: Object.freeze({ Nested: true, ExecutableOpeners: Object.freeze([]) }),
21
+ ParameterPlaceholders: Object.freeze(['dollar-number']),
22
+ UnquotedIdentifierCase: 'lower',
23
+ });
129
24
  /**
130
25
  * PostgreSQL functions caller-supplied SQL may not call: the XML exporters that run SQL given as a
131
26
  * string (`query_to_xml`, `cursor_to_xml`, `table_to_xml`, `schema_to_xml`, `database_to_xml` and
@@ -144,30 +39,42 @@ const POSTGRESQL_CALLER_SQL_FORBIDDEN_FUNCTIONS = [
144
39
  'pg_sleep*'
145
40
  ];
146
41
  /**
147
- * PostgreSQL dialect implementation.
148
- * Uses "double-quote" identifiers, LIMIT/OFFSET pagination, native BOOLEAN, PL/pgSQL functions.
42
+ * PostgreSQL grammar facts: `LIMIT … OFFSET` and `FETCH FIRST` row caps, ORDER BY allowed in
43
+ * CTEs and derived tables, nested WITH, `WITH RECURSIVE`, no hint clause, `LATERAL`.
149
44
  */
150
- export class PostgreSQLDialect extends SQLDialect {
151
- get PlatformKey() {
152
- return 'postgresql';
153
- }
154
- get ParserDialect() {
155
- return 'PostgresQL';
156
- }
157
- get DisplayName() {
158
- return 'PostgreSQL';
159
- }
160
- /** `sql-formatter` ships PostgreSQL under the `postgresql` language key. */
161
- get FormatterLanguage() {
162
- return 'postgresql';
163
- }
164
- /**
165
- * PostgreSQL has no in-row row-size limit (TOAST stores oversized variable-length values
166
- * out-of-line), so {@link MaxInRowSizeBytes} stays `null` (inherited). It does enforce a
167
- * hard 1600-column-per-table cap.
168
- */
169
- get MaxColumnCount() { return 1600; }
170
- // ─── Identifier Quoting ──────────────────────────────────────────
45
+ export const POSTGRESQL_GRAMMAR = Object.freeze({
46
+ ...ANSI_GRAMMAR,
47
+ ParserGrammar: 'PostgresQL',
48
+ DefaultSchema: 'public',
49
+ RowCapForms: Object.freeze(['limit-offset', 'offset-fetch']),
50
+ WriteStatementKeywords: Object.freeze([
51
+ ...ANSI_WRITE_STATEMENT_KEYWORDS,
52
+ 'COPY', 'DO', 'VACUUM', 'REINDEX', 'CLUSTER', 'REFRESH', 'LOCK', 'COMMENT', 'IMPORT', 'SECURITY',
53
+ ]),
54
+ CallerSQLForbiddenFunctions: POSTGRESQL_CALLER_SQL_FORBIDDEN_FUNCTIONS,
55
+ SourceNameIsRowValue: true,
56
+ });
57
+ /**
58
+ * PostgreSQL's column-type names as they appear in `pg_catalog` / `information_schema` /
59
+ * `EntityField.Type`, with both the formal names (`character varying`) and the short or internal
60
+ * aliases (`varchar`, `bpchar`). `tsvector` / `tsquery` serialize as text.
61
+ */
62
+ export const POSTGRESQL_TYPES = Object.freeze({
63
+ BooleanTypeNames: Object.freeze(['bool', 'boolean']),
64
+ StringTypeNames: Object.freeze(['text', 'varchar', 'char', 'character', 'character varying', 'bpchar', 'citext', 'name', 'tsvector', 'tsquery']),
65
+ FixedWidthStringTypeNames: Object.freeze(['char', 'character', 'bpchar']),
66
+ DateTypeNames: Object.freeze(['date', 'time', 'time without time zone', 'time with time zone', 'timestamp', 'timestamptz', 'timestamp with time zone', 'timestamp without time zone']),
67
+ IntegerTypeNames: Object.freeze(['int', 'int2', 'int4', 'int8', 'integer', 'bigint', 'smallint', 'serial', 'bigserial', 'smallserial', 'oid']),
68
+ FloatTypeNames: Object.freeze(['decimal', 'numeric', 'real', 'double precision', 'float4', 'float8']),
69
+ UuidTypeNames: Object.freeze(['uuid']),
70
+ BinaryTypeNames: Object.freeze(['bytea']),
71
+ JsonTypeNames: Object.freeze(['json', 'jsonb', 'xml']),
72
+ CurrencyTypeNames: Object.freeze(['money']),
73
+ IntervalTypeNames: Object.freeze(['interval']),
74
+ NetworkTypeNames: Object.freeze(['inet', 'cidr', 'macaddr', 'macaddr8']),
75
+ });
76
+ /** Writes PostgreSQL: double-quote identifiers, `LIMIT`/`OFFSET`, native booleans, `->>` JSON. */
77
+ export class PostgreSQLWriter extends AnsiWriter {
171
78
  QuoteIdentifier(name) {
172
79
  // Double any embedded double-quote (`"`→`""`) so an identifier from an untrusted source — e.g. an
173
80
  // external entity's remote column/table names, which arrive via remote-schema introspection — cannot
@@ -192,16 +99,6 @@ export class PostgreSQLDialect extends SQLDialect {
192
99
  QuoteColumnAlias(aliasName) {
193
100
  return `"${aliasName.replace(/"/g, '""')}"`;
194
101
  }
195
- /**
196
- * PostgreSQL folds unquoted identifiers to lowercase, so the physical schema an
197
- * unquoted `CREATE SCHEMA __mj_BizAppsCommon` produces is `__mj_bizappscommon`.
198
- * Canonicalize to that lowercase form so the engine's quoted operations target the
199
- * same physical schema as the app's (typically unquoted) migration DDL.
200
- */
201
- CanonicalSchemaName(name) {
202
- return name.toLowerCase();
203
- }
204
- // ─── Pagination ──────────────────────────────────────────────────
205
102
  LimitClause(limit, offset) {
206
103
  const parts = [`LIMIT ${limit}`];
207
104
  if (offset != null) {
@@ -209,13 +106,9 @@ export class PostgreSQLDialect extends SQLDialect {
209
106
  }
210
107
  return { prefix: '', suffix: parts.join(' ') };
211
108
  }
212
- // ─── Literals & Expressions ──────────────────────────────────────
213
109
  BooleanLiteral(value) {
214
110
  return value ? 'true' : 'false';
215
111
  }
216
- BooleanParameterType() {
217
- return 'boolean';
218
- }
219
112
  /**
220
113
  * PostgreSQL has no `ISNULL` keyword; the standard is `COALESCE` (which
221
114
  * SQL Server also supports). PG generated SPs/functions emit COALESCE
@@ -231,545 +124,52 @@ export class PostgreSQLDialect extends SQLDialect {
231
124
  Coalesce(expr, fallback) {
232
125
  return `COALESCE(${expr}, ${fallback})`;
233
126
  }
234
- /**
235
- * PostgreSQL function parameters use a `p_<flat lowercase>` convention
236
- * (no `@`-prefix syntax in PG). This matches the baseline-ported SP names
237
- * (which lowercased SQL Server's PascalCase parameter names without
238
- * separators — e.g. `@CompanyID` → `p_companyid`) and the runtime
239
- * PostgreSQLDataProvider, which calls procs with `p_${field.Name.toLowerCase()}`.
240
- *
241
- * Earlier this used a snake_case transform (`p_company_id`), which
242
- * produced functions the runtime could never invoke. Underscores already
243
- * in the input (e.g. the `_Clear` companion suffix) are preserved.
244
- */
245
- ParameterRef(name) {
246
- return `p_${name.toLowerCase()}`;
247
- }
248
- /**
249
- * PostgreSQL functions use the `DEFAULT <value>` clause for parameter defaults.
250
- */
251
- ParameterDefault(value) {
252
- return ` DEFAULT ${value}`;
253
- }
254
127
  CurrentTimestampUTC() {
255
128
  return "(NOW() AT TIME ZONE 'UTC')";
256
129
  }
257
- AffectedRowCountSQL(dmlStatement, alias) {
258
- // A data-modifying CTE is PostgreSQL's equivalent of @@ROWCOUNT: the statement runs once,
259
- // RETURNING emits one row per affected row, and the outer SELECT counts them.
260
- return `WITH ${this.QuoteIdentifier('__mj_affected')} AS (\n${dmlStatement}\nRETURNING 1\n)\n`
261
- + `SELECT COUNT(*)::int AS ${this.QuoteColumnAlias(alias)} FROM ${this.QuoteIdentifier('__mj_affected')}`;
262
- }
263
- // ─── Type-Name Sets ──────────────────────────────────────────────
264
- // PostgreSQL's column-type names as they appear in `pg_catalog` /
265
- // `information_schema` / `EntityField.Type` for entities backed by PG.
266
- // Includes both the formal name (`character varying`) and the internal
267
- // / short alias (`varchar`, `bpchar`) since both surface depending on
268
- // the metadata source.
269
- static { this._booleanTypeNames = ['bool', 'boolean']; }
270
- // `tsvector` / `tsquery` (full-text search, e.g. CodeGen's `__mj_fts_vector`) serialize as
271
- // text. Without them here they fall through to Int and break GraphQL serialization.
272
- static { this._stringTypeNames = ['text', 'varchar', 'char', 'character', 'character varying', 'bpchar', 'citext', 'name', 'tsvector', 'tsquery']; }
273
- /**
274
- * PG fixed-width / space-padded char types. `character` (without `varying`)
275
- * and `bpchar` are the formal/internal names; `char` is the short alias.
276
- * Note: `character varying` is NOT included — it's variable-width.
277
- */
278
- static { this._fixedWidthStringTypeNames = ['char', 'character', 'bpchar']; }
279
- static { this._dateTypeNames = ['date', 'time', 'time without time zone', 'time with time zone', 'timestamp', 'timestamptz', 'timestamp with time zone', 'timestamp without time zone']; }
280
- static { this._integerTypeNames = ['int', 'int2', 'int4', 'int8', 'integer', 'bigint', 'smallint', 'serial', 'bigserial', 'smallserial', 'oid']; }
281
- static { this._floatTypeNames = ['decimal', 'numeric', 'real', 'double precision', 'float4', 'float8']; }
282
- static { this._uuidTypeNames = ['uuid']; }
283
- static { this._binaryTypeNames = ['bytea']; }
284
- static { this._jsonTypeNames = ['json', 'jsonb', 'xml']; }
285
- static { this._currencyTypeNames = ['money']; }
286
- static { this._intervalTypeNames = ['interval']; }
287
- static { this._networkTypeNames = ['inet', 'cidr', 'macaddr', 'macaddr8']; }
288
- get BooleanTypeNames() { return PostgreSQLDialect._booleanTypeNames; }
289
- get StringTypeNames() { return PostgreSQLDialect._stringTypeNames; }
290
- get FixedWidthStringTypeNames() { return PostgreSQLDialect._fixedWidthStringTypeNames; }
291
- get DateTypeNames() { return PostgreSQLDialect._dateTypeNames; }
292
- get IntegerTypeNames() { return PostgreSQLDialect._integerTypeNames; }
293
- get FloatTypeNames() { return PostgreSQLDialect._floatTypeNames; }
294
- get UuidTypeNames() { return PostgreSQLDialect._uuidTypeNames; }
295
- get BinaryTypeNames() { return PostgreSQLDialect._binaryTypeNames; }
296
- get JsonTypeNames() { return PostgreSQLDialect._jsonTypeNames; }
297
- get CurrencyTypeNames() { return PostgreSQLDialect._currencyTypeNames; }
298
- get IntervalTypeNames() { return PostgreSQLDialect._intervalTypeNames; }
299
- get NetworkTypeNames() { return PostgreSQLDialect._networkTypeNames; }
300
- NewUUID() {
301
- return 'gen_random_uuid()';
302
- }
303
130
  CastToText(expr) {
304
131
  return `CAST(${expr} AS TEXT)`;
305
132
  }
306
- /**
307
- * PostgreSQL-specific Flyway escape. PostgreSQL string concatenation uses
308
- * `||` (not `+`), and TEXT has no length cap — so a simple split with `||`
309
- * suffices and no cast-to-MAX dance is needed (unlike SQL Server, which
310
- * silently truncates `NVARCHAR(N) + NVARCHAR(M)` past 4,000 chars).
311
- * PostgreSQL string literals don't take an `N` prefix either; everything
312
- * is already Unicode.
313
- */
314
- EscapeFlywayStringInterpolation(sql) {
315
- return sql.replaceAll(/\$\{/g, "$$'||'{");
316
- }
317
- CastToUUID(expr) {
318
- return `CAST(${expr} AS UUID)`;
319
- }
320
- /**
321
- * PostgreSQL strict typing requires an explicit `::UUID` cast when
322
- * comparing the empty-GUID sentinel against a UUID-typed column.
323
- * Without it, PG raises "operator does not exist: uuid = text".
324
- */
325
- EmptyUUIDLiteral() {
326
- return `${super.EmptyUUIDLiteral()}::UUID`;
327
- }
328
- // ─── INSERT/UPDATE Return Patterns ───────────────────────────────
329
- ReturnInsertedClause(columns) {
330
- if (columns && columns.length > 0) {
331
- const cols = columns.map(c => `"${c}"`).join(', ');
332
- return `RETURNING ${cols}`;
333
- }
334
- return 'RETURNING *';
335
- }
336
- AutoIncrementPKExpression() {
337
- return 'GENERATED ALWAYS AS IDENTITY';
338
- }
339
- UUIDPKDefault() {
340
- return 'gen_random_uuid()';
341
- }
342
- ScopeIdentityExpression() {
343
- return 'lastval()';
344
- }
345
- RowCountExpression() {
346
- // In PL/pgSQL, use GET DIAGNOSTICS row_count = ROW_COUNT
347
- return 'ROW_COUNT';
348
- }
349
- // ─── Batch & DDL Control ─────────────────────────────────────────
350
- BatchSeparator() {
351
- return ''; // PostgreSQL does not need batch separators
352
- }
353
- CreateSavepointSQL(name) {
354
- return `SAVEPOINT ${name}`;
355
- }
356
- ReleaseSavepointSQL(name) {
357
- return `RELEASE SAVEPOINT ${name}`;
358
- }
359
- RollbackToSavepointSQL(name) {
360
- return `ROLLBACK TO SAVEPOINT ${name}`;
361
- }
362
- /**
363
- * Splits an oversized SQL batch into individual statements on `;`+EOL
364
- * boundaries — but NEVER inside a PostgreSQL dollar-quoted block
365
- * (`$$ … $$` or `$tag$ … $tag$`), whose body legitimately contains
366
- * `;`+newline (DO blocks, PL/pgSQL function bodies, the integration
367
- * view-drop guard `$mj_dropviews$`). A naive `split(/;\s*\n/g)` tears
368
- * those apart. Outside dollar blocks the boundary semantics mirror the
369
- * base `split(/;\s*\n/g)` (a `;` then optional inline whitespace then a
370
- * newline). Each returned statement ends with `;`.
371
- */
372
- SplitStatements(batch) {
373
- const statements = [];
374
- let current = '';
375
- let dollarTag = null; // active dollar-quote tag (e.g. '$$' or '$fn$'), or null
376
- const isTagChar = (c) => (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c === '_';
377
- for (let i = 0; i < batch.length; i++) {
378
- const ch = batch[i];
379
- if (ch === '$') {
380
- // Scan a dollar-quote tag: `$` [A-Za-z0-9_]* `$`.
381
- let j = i + 1;
382
- while (j < batch.length && isTagChar(batch[j]))
383
- j++;
384
- if (batch[j] === '$') {
385
- const tag = batch.slice(i, j + 1);
386
- if (dollarTag === null)
387
- dollarTag = tag; // entering a dollar-quoted block
388
- else if (dollarTag === tag)
389
- dollarTag = null; // matching close → exiting
390
- current += tag;
391
- i = j;
392
- continue;
393
- }
394
- }
395
- if (ch === ';' && dollarTag === null) {
396
- // Boundary = `;` then optional spaces/tabs/CR then a newline — only OUTSIDE a dollar block.
397
- let j = i + 1;
398
- while (j < batch.length && (batch[j] === ' ' || batch[j] === '\t' || batch[j] === '\r'))
399
- j++;
400
- if (j < batch.length && batch[j] === '\n') {
401
- current += ';';
402
- const trimmed = current.trim();
403
- if (trimmed.length > 0)
404
- statements.push(trimmed);
405
- current = '';
406
- i = j; // skip the inline whitespace; the loop's i++ steps past the newline
407
- continue;
408
- }
409
- }
410
- current += ch;
411
- }
412
- const tail = current.trim();
413
- if (tail.length > 0)
414
- statements.push(tail);
415
- return statements.map((s) => (s.endsWith(';') ? s : s + ';'));
416
- }
417
- ExistenceCheckSQL(objectType, schema, name) {
418
- const normalizedType = objectType.toUpperCase();
419
- switch (normalizedType) {
420
- case 'TABLE':
421
- return `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_tables WHERE schemaname = '${schema}' AND tablename = '${name}')`;
422
- case 'VIEW':
423
- return `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_views WHERE schemaname = '${schema}' AND viewname = '${name}')`;
424
- case 'FUNCTION':
425
- return `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = '${schema}' AND p.proname = '${name}')`;
426
- case 'PROCEDURE':
427
- return `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = '${schema}' AND p.proname = '${name}' AND p.prokind = 'p')`;
428
- case 'TRIGGER':
429
- return `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_trigger WHERE tgname = '${name}')`;
430
- default:
431
- return `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid WHERE n.nspname = '${schema}' AND c.relname = '${name}')`;
432
- }
433
- }
434
- CreateOrReplaceSupported(objectType) {
435
- const normalized = objectType.toUpperCase();
436
- return normalized === 'FUNCTION' || normalized === 'VIEW' || normalized === 'PROCEDURE';
437
- }
438
- // ─── Full-Text Search ────────────────────────────────────────────
439
- FullTextSearchPredicate(column, searchTerm) {
440
- return `${column} @@ plainto_tsquery('english', ${searchTerm})`;
441
- }
442
- FullTextIndexDDL(table, columns, _catalog) {
443
- const colList = columns.map(c => `"${c}"`).join(', ');
444
- const cleanTable = table.replace(/"/g, '');
445
- const triggerCols = columns.map(c => `"${c}"`).join(', ');
446
- const lines = [];
447
- // Add tsvector column
448
- lines.push(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS __mj_fts_vector TSVECTOR;`);
449
- lines.push('');
450
- // Create GIN index on the tsvector column
451
- lines.push(`CREATE INDEX IF NOT EXISTS idx_fts_${cleanTable.replace(/\./g, '_')} ON ${table} USING GIN(__mj_fts_vector);`);
452
- lines.push('');
453
- // Create update trigger
454
- lines.push(`CREATE OR REPLACE FUNCTION ${this.extractSchema(table)}.fn_trg_fts_${this.extractName(table)}()`);
455
- lines.push('RETURNS TRIGGER AS $$');
456
- lines.push('BEGIN');
457
- lines.push(` NEW.__mj_fts_vector := to_tsvector('english', ${columns.map(c => `COALESCE(NEW."${c}", '')`).join(" || ' ' || ")});`);
458
- lines.push(' RETURN NEW;');
459
- lines.push('END;');
460
- lines.push('$$ LANGUAGE plpgsql;');
461
- lines.push('');
462
- lines.push(`DROP TRIGGER IF EXISTS trg_fts_${this.extractName(table)} ON ${table};`);
463
- lines.push(`CREATE TRIGGER trg_fts_${this.extractName(table)}`);
464
- lines.push(` BEFORE INSERT OR UPDATE ON ${table}`);
465
- lines.push(` FOR EACH ROW EXECUTE FUNCTION ${this.extractSchema(table)}.fn_trg_fts_${this.extractName(table)}();`);
466
- return lines.join('\n');
467
- }
468
- // ─── CTE / Recursion ─────────────────────────────────────────────
469
- RecursiveCTESyntax() {
470
- return 'WITH RECURSIVE';
471
- }
472
- get AllowsOrderByInCTE() {
473
- return true;
474
- }
475
- get DefaultPagingOrderBy() {
476
- return '1';
477
- }
478
- get SelectListPagingOrderBy() {
479
- return null;
480
- }
481
- get PagingRequiresOrderBy() {
482
- return false;
483
- }
484
- get SupportsEscapeStringLiterals() {
485
- return true;
486
- }
487
- get SupportsDollarQuotedStrings() {
488
- return true;
489
- }
490
- get QueryHintKeyword() {
491
- return null;
492
- }
493
- get CallerSQLForbiddenFunctions() {
494
- return POSTGRESQL_CALLER_SQL_FORBIDDEN_FUNCTIONS;
495
- }
496
133
  StringLiteralPrefix(_text) {
497
134
  return '';
498
135
  }
499
136
  EscapeLikePattern(text) {
500
137
  return text.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_');
501
138
  }
502
- BooleanParameterValue(value) {
503
- return value;
504
- }
505
- // ─── Data Types ──────────────────────────────────────────────────
506
- get TypeMap() {
507
- return new PostgreSQLDataTypeMap();
508
- }
509
- // ─── Parameters ──────────────────────────────────────────────────
510
- ParameterPlaceholder(index) {
511
- return `$${index + 1}`; // PostgreSQL uses 1-based indexing
512
- }
513
139
  ConcatOperator() {
514
140
  return '||';
515
141
  }
516
- // ─── String Functions ────────────────────────────────────────────
517
- StringSplitFunction(value, delimiter) {
518
- return `unnest(string_to_array(${value}, ${delimiter}))`;
519
- }
520
142
  JsonExtract(column, path) {
521
143
  // PostgreSQL JSONB operator for text extraction
522
144
  return `${column}->>'${path}'`;
523
145
  }
524
- // ─── Procedure / Function Calls ──────────────────────────────────
525
- ProcedureCallSyntax(schema, name, params) {
526
- const paramList = params.join(', ');
527
- return `SELECT * FROM ${schema}."${name}"(${paramList})`;
528
- }
529
- // ─── DDL Generation (Schema/Table) ──────────────────────────────
530
- CreateSchemaDDL(schemaName) {
531
- return `CREATE SCHEMA IF NOT EXISTS "${schemaName}";`;
532
- }
533
- // ─── DDL Generation (Conditional/Procedural) ────────────────────
534
146
  DateAddExpression(unit, amount, baseExpr) {
535
147
  const pgUnit = unit.toLowerCase() + 's'; // MINUTE -> minutes, HOUR -> hours, DAY -> days
536
148
  return `${baseExpr} + INTERVAL '${amount} ${pgUnit}'`;
537
149
  }
538
- CreateTableIfNotExistsDDL(schema, tableName, columnsDDL) {
539
- const quotedTable = this.QuoteSchema(schema, tableName);
540
- return [
541
- `CREATE TABLE IF NOT EXISTS ${quotedTable} (`,
542
- columnsDDL,
543
- `);`,
544
- ].join('\n');
545
- }
546
- ConditionalBlock(condition, thenSQL, elseSQL) {
547
- const lines = [
548
- `DO $$`,
549
- `BEGIN`,
550
- ` IF ${condition} THEN`,
551
- ` ${thenSQL};`,
552
- ];
553
- if (elseSQL) {
554
- lines.push(` ELSE`);
555
- lines.push(` ${elseSQL};`);
556
- }
557
- lines.push(` END IF;`);
558
- lines.push(`END $$;`);
559
- return lines.join('\n');
560
- }
561
- RaiseSignalSQL(message) {
562
- return `RAISE NOTICE '${message}'`;
563
- }
564
- // ─── DDL Generation (Schema/Table continued) ────────────────────
565
- AddColumnClause(col) {
566
- const nullable = col.nullable ? 'NULL' : 'NOT NULL';
567
- const defaultExpr = col.defaultValue != null ? ` DEFAULT ${col.defaultValue}` : '';
568
- return `ADD COLUMN "${col.name}" ${col.sqlType} ${nullable}${defaultExpr}`;
569
- }
570
- AlterColumnDDL(quotedTable, options) {
571
- const col = `"${options.columnName}"`;
572
- // PostgreSQL refuses to change a column's type when the old type cannot be
573
- // *implicitly* cast to the new one (e.g. text → boolean, text → integer):
574
- // "column ... cannot be cast automatically to type boolean".
575
- // A `USING <col>::<newtype>` expression makes the conversion explicit. It is
576
- // valid for every type change (a no-op cast when the types already match), so
577
- // we always emit it. SQL Server has no such requirement (handled in its own
578
- // dialect), so this is PG-only.
579
- return (`ALTER TABLE ${quotedTable}\n` +
580
- ` ALTER COLUMN ${col} TYPE ${options.newType} USING ${col}::${options.newType},\n` +
581
- ` ALTER COLUMN ${col} ${options.newNullable ? 'DROP NOT NULL' : 'SET NOT NULL'};`);
582
- }
583
- CommentOnColumn(schema, table, column, comment) {
584
- const escaped = comment.replace(/'/g, "''");
585
- return `COMMENT ON COLUMN "${schema}"."${table}"."${column}" IS '${escaped}';`;
586
- }
587
- FallbackType() {
588
- return 'TEXT';
589
- }
590
- // ─── DDL Generation (Triggers/Indexes) ──────────────────────────
591
- TriggerDDL(options) {
592
- const events = options.events.join(' OR ');
593
- const forEach = options.forEach ?? 'ROW';
594
- const funcName = options.functionName ?? `fn_${options.triggerName}`;
595
- const lines = [];
596
- // PostgreSQL triggers require a companion function
597
- lines.push(`CREATE OR REPLACE FUNCTION ${options.schema}."${funcName}"()`);
598
- lines.push('RETURNS TRIGGER AS $$');
599
- lines.push('BEGIN');
600
- lines.push(` ${options.body}`);
601
- lines.push('END;');
602
- lines.push('$$ LANGUAGE plpgsql;');
603
- lines.push('');
604
- lines.push(`DROP TRIGGER IF EXISTS "${options.triggerName}" ON ${options.schema}."${options.tableName}";`);
605
- lines.push(`CREATE TRIGGER "${options.triggerName}"`);
606
- lines.push(` ${options.timing} ${events} ON ${options.schema}."${options.tableName}"`);
607
- lines.push(` FOR EACH ${forEach}`);
608
- lines.push(` EXECUTE FUNCTION ${options.schema}."${funcName}"();`);
609
- return lines.join('\n');
610
- }
611
- IndexDDL(options) {
612
- const unique = options.unique ? 'UNIQUE ' : '';
613
- const method = options.method ? ` USING ${options.method}` : '';
614
- const cols = options.columns.map(c => `"${c}"`).join(', ');
615
- let ddl = `CREATE ${unique}INDEX IF NOT EXISTS "${options.indexName}" ON ${options.schema}."${options.tableName}"${method}(${cols})`;
616
- if (options.where) {
617
- ddl += ` WHERE ${options.where}`;
618
- }
619
- return ddl;
620
- }
621
- // ─── Permissions ─────────────────────────────────────────────────
622
- GrantPermission(permission, _objectType, schema, object, role) {
623
- return `GRANT ${permission} ON ${schema}."${object}" TO "${role}"`;
150
+ IIF(condition, trueVal, falseVal) {
151
+ return `CASE WHEN ${condition} THEN ${trueVal} ELSE ${falseVal} END`;
624
152
  }
625
- CommentOnObject(objectType, schema, name, comment) {
626
- const escapedComment = comment.replace(/'/g, "''");
627
- const normalizedType = objectType.toUpperCase();
628
- return `COMMENT ON ${normalizedType} ${schema}."${name}" IS '${escapedComment}'`;
153
+ }
154
+ /** PostgreSQL binding through the `pg` driver: `$1` placeholders, native booleans. */
155
+ export class PostgreSQLBinding {
156
+ BooleanParameterValue(value) {
157
+ return value;
629
158
  }
630
- // ─── Schema Introspection ────────────────────────────────────────
631
- SchemaIntrospectionQueries() {
632
- return {
633
- listTables: `
634
- SELECT schemaname AS schema_name, tablename AS table_name
635
- FROM pg_catalog.pg_tables
636
- WHERE schemaname = $1
637
- ORDER BY tablename`,
638
- listColumns: `
639
- SELECT c.column_name, c.data_type, c.character_maximum_length AS max_length,
640
- c.numeric_precision AS precision, c.numeric_scale AS scale,
641
- c.is_nullable, c.column_default AS default_value,
642
- CASE WHEN c.column_default LIKE '%nextval%' THEN true ELSE false END AS is_identity
643
- FROM information_schema.columns c
644
- WHERE c.table_schema = $1 AND c.table_name = $2
645
- ORDER BY c.ordinal_position`,
646
- listConstraints: `
647
- SELECT tc.constraint_name, tc.constraint_type, kcu.column_name
648
- FROM information_schema.table_constraints tc
649
- JOIN information_schema.key_column_usage kcu
650
- ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
651
- WHERE tc.table_schema = $1 AND tc.table_name = $2
652
- ORDER BY tc.constraint_type, kcu.ordinal_position`,
653
- listForeignKeys: `
654
- SELECT
655
- tc.constraint_name AS fk_name,
656
- tc.table_schema AS source_schema,
657
- tc.table_name AS source_table,
658
- kcu.column_name AS source_column,
659
- ccu.table_schema AS target_schema,
660
- ccu.table_name AS target_table,
661
- ccu.column_name AS target_column
662
- FROM information_schema.table_constraints tc
663
- JOIN information_schema.key_column_usage kcu
664
- ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
665
- JOIN information_schema.constraint_column_usage ccu
666
- ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema
667
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = $1
668
- ORDER BY tc.constraint_name`,
669
- listIndexes: `
670
- SELECT
671
- i.relname AS index_name,
672
- ix.indisunique AS is_unique,
673
- am.amname AS type_desc,
674
- a.attname AS column_name,
675
- false AS is_included_column
676
- FROM pg_catalog.pg_index ix
677
- JOIN pg_catalog.pg_class t ON t.oid = ix.indrelid
678
- JOIN pg_catalog.pg_class i ON i.oid = ix.indexrelid
679
- JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
680
- JOIN pg_catalog.pg_am am ON am.oid = i.relam
681
- JOIN pg_catalog.pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
682
- WHERE n.nspname = $1 AND t.relname = $2
683
- ORDER BY i.relname`,
684
- objectExists: `
685
- SELECT EXISTS (
686
- SELECT 1 FROM pg_catalog.pg_class c
687
- JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
688
- WHERE n.nspname = $1 AND c.relname = $2
689
- ) AS exists`,
690
- };
159
+ ParameterPlaceholder(index) {
160
+ return `$${index + 1}`; // PostgreSQL uses 1-based indexing
691
161
  }
692
162
  /**
693
- * PostgreSQL FK-graph query for cascade planning — reads `pg_catalog.pg_constraint`
694
- * (`contype = 'f'`). Returns one row per FK column (via `unnest(conkey, confkey)`, which
695
- * preserves column pairing/order), with `childNullable` (`NOT attnotnull`) and `colCount`
696
- * (`array_length(conkey, 1)`, for composite exclusion). Column aliases and semantics MATCH
697
- * the SQL Server variant so a single caller parses both. `relname`/`attname` preserve the
698
- * quoted mixed-case identifiers MJ creates on PG, so they feed straight into QuoteIdentifier.
699
- * Both parent + child are filtered to `schema`; the schema is embedded as a literal.
163
+ * `$<n>::<type>`: the driver sends untyped text, so the cast gives the server the column's type.
164
+ * @throws Error when `sqlType` is not a plain type name (words with an optional `(n[, m])`, as `timestamp(3) with time zone`, and an optional `[]`).
700
165
  */
701
- ForeignKeyGraphSQL(schema) {
702
- const s = this.QuoteStringLiteral(schema);
703
- // NOTE: deliberately avoids `unnest(...) WITH ORDINALITY` / `LATERAL`. This query is executed
704
- // through PostgreSQLDataProvider.ExecuteSQL, whose autoQuoteIdentifiers tokenizer quotes the
705
- // bare uppercase word `ORDINALITY` (not in its keyword set) → `WITH "ORDINALITY"` → a syntax
706
- // error. Using `= any(con.conkey)` (all-lowercase, autoQuote-safe) resolves the FK column via
707
- // array membership instead. For SINGLE-column FKs (the only ones the planner keeps, colCount=1)
708
- // this yields exactly one correctly-paired row; composite FKs (colCount>1) produce a cross
709
- // product of rows that the caller skips wholesale by fkName — so the mispairing is irrelevant.
710
- return ('SELECT pt.relname AS "parentTable", pa.attname AS "parentRefCol", ct.relname AS "childTable", ' +
711
- 'ca.attname AS "childCol", (NOT ca.attnotnull) AS "childNullable", con.conname AS "fkName", ' +
712
- 'array_length(con.conkey, 1) AS "colCount" ' +
713
- 'FROM pg_catalog.pg_constraint con ' +
714
- 'JOIN pg_catalog.pg_class ct ON ct.oid = con.conrelid ' +
715
- 'JOIN pg_catalog.pg_namespace cn ON cn.oid = ct.relnamespace ' +
716
- 'JOIN pg_catalog.pg_class pt ON pt.oid = con.confrelid ' +
717
- 'JOIN pg_catalog.pg_namespace pn ON pn.oid = pt.relnamespace ' +
718
- 'JOIN pg_catalog.pg_attribute ca ON ca.attrelid = con.conrelid AND ca.attnum = any(con.conkey) ' +
719
- 'JOIN pg_catalog.pg_attribute pa ON pa.attrelid = con.confrelid AND pa.attnum = any(con.confkey) ' +
720
- `WHERE con.contype = 'f' AND cn.nspname = ${s} AND pn.nspname = ${s} ` +
721
- 'ORDER BY con.conname');
722
- }
723
- AtomicBatchScript(statements) {
724
- if (!statements || !statements.length)
725
- return '';
726
- const body = statements.join(';\n');
727
- // No session pragmas (QUOTED_IDENTIFIER/ANSI_NULLS are SQL-Server concepts) and PostgreSQL
728
- // already aborts the whole transaction on any error, so plain BEGIN … COMMIT is all-or-nothing.
729
- return `BEGIN;\n${body};\nCOMMIT;`;
730
- }
731
- // ─── IIF ─────────────────────────────────────────────────────────
732
- IIF(condition, trueVal, falseVal) {
733
- return `CASE WHEN ${condition} THEN ${trueVal} ELSE ${falseVal} END`;
734
- }
735
- // ─── Abstract Type Resolution ─────────────────────────────────────
736
- ResolveAbstractType(options) {
737
- switch (options.type) {
738
- case 'string':
739
- return this.resolveStringType(options.maxLength);
740
- case 'text':
741
- return 'TEXT';
742
- case 'integer':
743
- return 'INTEGER';
744
- case 'bigint':
745
- return 'BIGINT';
746
- case 'decimal':
747
- return `NUMERIC(${options.precision ?? 18},${options.scale ?? 2})`;
748
- case 'boolean':
749
- return 'BOOLEAN';
750
- case 'datetime':
751
- return 'TIMESTAMPTZ';
752
- case 'date':
753
- return 'DATE';
754
- case 'uuid':
755
- return 'UUID';
756
- case 'json':
757
- return 'JSONB';
758
- case 'float':
759
- return 'DOUBLE PRECISION';
760
- case 'time':
761
- return 'TIME';
762
- default:
763
- return this.FallbackType();
764
- }
765
- }
766
- resolveStringType(maxLength) {
767
- if (maxLength != null && maxLength > 0) {
768
- return `VARCHAR(${maxLength})`;
166
+ TypedParameter(index, sqlType) {
167
+ if (sqlType.length > 128 || !/^[A-Za-z_][A-Za-z0-9_ ]*(\(\s*\d+\s*(,\s*\d+\s*)?\))?[A-Za-z0-9_ ]*(\[\])?$/.test(sqlType.trim())) {
168
+ throw new Error(`'${sqlType}' is not a type name a parameter can be cast to.`);
769
169
  }
770
- return 'VARCHAR(255)';
170
+ const placeholder = `$${index + 1}`;
171
+ return { Placeholder: `${placeholder}::${sqlType.trim()}`, Name: placeholder };
771
172
  }
772
- // ─── Error Classification ────────────────────────────────────────
773
173
  IsConnectionError(e) {
774
174
  if (!(e instanceof Error))
775
175
  return false;
@@ -787,18 +187,45 @@ export class PostgreSQLDialect extends SQLDialect {
787
187
  e.message.includes('Connection terminated') ||
788
188
  e.message.includes('connection is insecure'));
789
189
  }
790
- // ─── Private Helpers ─────────────────────────────────────────────
791
- extractSchema(qualifiedName) {
792
- const dotIndex = qualifiedName.indexOf('.');
793
- if (dotIndex === -1)
794
- return 'public';
795
- return qualifiedName.substring(0, dotIndex).replace(/"/g, '');
190
+ }
191
+ /**
192
+ * PostgreSQL dialect implementation.
193
+ * Uses "double-quote" identifiers, LIMIT/OFFSET pagination, native BOOLEAN, PL/pgSQL functions.
194
+ */
195
+ export class PostgreSQLDialect extends SQLDialect {
196
+ constructor() {
197
+ super(...arguments);
198
+ this.writer = Object.freeze(new PostgreSQLWriter());
199
+ this.binding = Object.freeze(new PostgreSQLBinding());
200
+ this.ddl = Object.freeze(new PostgreSQLSchemaDDL(this.writer));
201
+ }
202
+ get PlatformKey() {
203
+ return 'postgresql';
204
+ }
205
+ get DisplayName() {
206
+ return 'PostgreSQL';
207
+ }
208
+ /** `sql-formatter` ships PostgreSQL under the `postgresql` language key. */
209
+ get FormatterLanguage() {
210
+ return 'postgresql';
211
+ }
212
+ get Lexical() {
213
+ return POSTGRESQL_LEXICAL;
214
+ }
215
+ get Grammar() {
216
+ return POSTGRESQL_GRAMMAR;
217
+ }
218
+ get Writer() {
219
+ return this.writer;
220
+ }
221
+ get Types() {
222
+ return POSTGRESQL_TYPES;
223
+ }
224
+ get Binding() {
225
+ return this.binding;
796
226
  }
797
- extractName(qualifiedName) {
798
- const dotIndex = qualifiedName.indexOf('.');
799
- if (dotIndex === -1)
800
- return qualifiedName.replace(/"/g, '');
801
- return qualifiedName.substring(dotIndex + 1).replace(/"/g, '');
227
+ get DDL() {
228
+ return this.ddl;
802
229
  }
803
230
  }
804
231
  //# sourceMappingURL=postgresqlDialect.js.map