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