@memberjunction/sql-converter 6.3.0-edge.1 → 6.3.0-edge.3

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 (98) hide show
  1. package/README.md +16 -0
  2. package/dist/IncrementalBaker.d.ts +61 -2
  3. package/dist/IncrementalBaker.d.ts.map +1 -1
  4. package/dist/IncrementalBaker.js +103 -11
  5. package/dist/IncrementalBaker.js.map +1 -1
  6. package/dist/MigrationConverter.d.ts +54 -1
  7. package/dist/MigrationConverter.d.ts.map +1 -1
  8. package/dist/MigrationConverter.js +226 -23
  9. package/dist/MigrationConverter.js.map +1 -1
  10. package/dist/MigrationStatementSplitter.d.ts +11 -1
  11. package/dist/MigrationStatementSplitter.d.ts.map +1 -1
  12. package/dist/MigrationStatementSplitter.js +6 -3
  13. package/dist/MigrationStatementSplitter.js.map +1 -1
  14. package/dist/index.d.ts +6 -6
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -3
  17. package/dist/index.js.map +1 -1
  18. package/dist/rules/AlterTableRule.d.ts.map +1 -1
  19. package/dist/rules/AlterTableRule.js +6 -1
  20. package/dist/rules/AlterTableRule.js.map +1 -1
  21. package/dist/rules/BatchConverter.d.ts +16 -0
  22. package/dist/rules/BatchConverter.d.ts.map +1 -1
  23. package/dist/rules/BatchConverter.js +151 -12
  24. package/dist/rules/BatchConverter.js.map +1 -1
  25. package/dist/rules/BitColumnRegistry.d.ts +9 -0
  26. package/dist/rules/BitColumnRegistry.d.ts.map +1 -0
  27. package/dist/rules/BitColumnRegistry.js +111 -0
  28. package/dist/rules/BitColumnRegistry.js.map +1 -0
  29. package/dist/rules/CatalogViewRule.d.ts +6 -0
  30. package/dist/rules/CatalogViewRule.d.ts.map +1 -1
  31. package/dist/rules/CatalogViewRule.js +11 -0
  32. package/dist/rules/CatalogViewRule.js.map +1 -1
  33. package/dist/rules/ConditionalDDLRule.d.ts +6 -0
  34. package/dist/rules/ConditionalDDLRule.d.ts.map +1 -1
  35. package/dist/rules/ConditionalDDLRule.js +30 -0
  36. package/dist/rules/ConditionalDDLRule.js.map +1 -1
  37. package/dist/rules/CreateIndexRule.d.ts +18 -0
  38. package/dist/rules/CreateIndexRule.d.ts.map +1 -1
  39. package/dist/rules/CreateIndexRule.js +47 -14
  40. package/dist/rules/CreateIndexRule.js.map +1 -1
  41. package/dist/rules/CreateTableRule.d.ts.map +1 -1
  42. package/dist/rules/CreateTableRule.js +10 -3
  43. package/dist/rules/CreateTableRule.js.map +1 -1
  44. package/dist/rules/DeclareDmlBlockRule.d.ts +9 -3
  45. package/dist/rules/DeclareDmlBlockRule.d.ts.map +1 -1
  46. package/dist/rules/DeclareDmlBlockRule.js +12 -47
  47. package/dist/rules/DeclareDmlBlockRule.js.map +1 -1
  48. package/dist/rules/DialectHeaderBuilder.d.ts +50 -4
  49. package/dist/rules/DialectHeaderBuilder.d.ts.map +1 -1
  50. package/dist/rules/DialectHeaderBuilder.js +50 -4
  51. package/dist/rules/DialectHeaderBuilder.js.map +1 -1
  52. package/dist/rules/ExpressionHelpers.d.ts +88 -11
  53. package/dist/rules/ExpressionHelpers.d.ts.map +1 -1
  54. package/dist/rules/ExpressionHelpers.js +478 -30
  55. package/dist/rules/ExpressionHelpers.js.map +1 -1
  56. package/dist/rules/FunctionRule.d.ts.map +1 -1
  57. package/dist/rules/FunctionRule.js +7 -5
  58. package/dist/rules/FunctionRule.js.map +1 -1
  59. package/dist/rules/GrantRule.d.ts +12 -1
  60. package/dist/rules/GrantRule.d.ts.map +1 -1
  61. package/dist/rules/GrantRule.js +122 -2
  62. package/dist/rules/GrantRule.js.map +1 -1
  63. package/dist/rules/InsertRule.d.ts +1 -0
  64. package/dist/rules/InsertRule.d.ts.map +1 -1
  65. package/dist/rules/InsertRule.js +156 -9
  66. package/dist/rules/InsertRule.js.map +1 -1
  67. package/dist/rules/PostProcessor.d.ts.map +1 -1
  68. package/dist/rules/PostProcessor.js +43 -26
  69. package/dist/rules/PostProcessor.js.map +1 -1
  70. package/dist/rules/ProcedureToFunctionRule.d.ts +27 -0
  71. package/dist/rules/ProcedureToFunctionRule.d.ts.map +1 -1
  72. package/dist/rules/ProcedureToFunctionRule.js +286 -7
  73. package/dist/rules/ProcedureToFunctionRule.js.map +1 -1
  74. package/dist/rules/SequenceDeduplicator.d.ts +16 -2
  75. package/dist/rules/SequenceDeduplicator.d.ts.map +1 -1
  76. package/dist/rules/SequenceDeduplicator.js +50 -14
  77. package/dist/rules/SequenceDeduplicator.js.map +1 -1
  78. package/dist/rules/StatementClassifier.d.ts +9 -0
  79. package/dist/rules/StatementClassifier.d.ts.map +1 -1
  80. package/dist/rules/StatementClassifier.js +53 -7
  81. package/dist/rules/StatementClassifier.js.map +1 -1
  82. package/dist/rules/SubSplitter.d.ts.map +1 -1
  83. package/dist/rules/SubSplitter.js +95 -2
  84. package/dist/rules/SubSplitter.js.map +1 -1
  85. package/dist/rules/ViewRule.d.ts +0 -2
  86. package/dist/rules/ViewRule.d.ts.map +1 -1
  87. package/dist/rules/ViewRule.js +8 -57
  88. package/dist/rules/ViewRule.js.map +1 -1
  89. package/dist/rules/index.d.ts +6 -4
  90. package/dist/rules/index.d.ts.map +1 -1
  91. package/dist/rules/index.js +4 -3
  92. package/dist/rules/index.js.map +1 -1
  93. package/dist/rules/types.d.ts +12 -2
  94. package/dist/rules/types.d.ts.map +1 -1
  95. package/dist/rules/types.js +7 -0
  96. package/dist/rules/types.js.map +1 -1
  97. package/dist/tsconfig.tsbuildinfo +1 -1
  98. package/package.json +3 -3
@@ -145,6 +145,21 @@ export function StripComments(sql) {
145
145
  export function QuoteConstraintNames(sql) {
146
146
  return TransformCodeOnly(sql, (code) => code.replace(/\bCONSTRAINT\s+(?!IF\s+EXISTS\b)([A-Za-z_]\w*)\b/gi, (match, name) => (/[A-Z]/.test(name) ? `CONSTRAINT "${name}"` : match)));
147
147
  }
148
+ /**
149
+ * Make SQL Server default-constraint drops idempotent on PostgreSQL.
150
+ *
151
+ * PostgreSQL migrations define column defaults inline (`"Col" VARCHAR(20) NOT NULL DEFAULT 'X'`)
152
+ * or via `ALTER COLUMN ... SET DEFAULT ...` without creating named `DF_*` constraint objects.
153
+ * Rewriting `DROP CONSTRAINT "DF_..."` to `DROP CONSTRAINT IF EXISTS "DF_..."` prevents
154
+ * `constraint "DF_..." of relation "..." does not exist` failures while still dropping any
155
+ * explicitly named constraint if one exists.
156
+ */
157
+ export function MakeDropDefaultConstraintIdempotent(sql) {
158
+ return TransformCodeOnly(sql, (code) => code.replace(/\bDROP\s+CONSTRAINT\s+(?!IF\s+EXISTS\b)("?DF_[\w$]+"?)/gi, (_match, name) => {
159
+ const quoted = name.startsWith('"') ? name : `"${name}"`;
160
+ return `DROP CONSTRAINT IF EXISTS ${quoted}`;
161
+ }));
162
+ }
148
163
  /**
149
164
  * Emit a DO-block that drops every overload of a function in a given schema.
150
165
  *
@@ -407,6 +422,21 @@ function buildDateDiffExpr(e, s, extractExpr, useTimestamp) {
407
422
  .replace(/\$E/g, e)
408
423
  .replace(/\$S/g, s);
409
424
  }
425
+ /**
426
+ * DATEDIFF(day, s, e): T-SQL counts the midnight boundaries crossed, which is what PostgreSQL's
427
+ * `date - date` gives, as an integer. DATE and TIMESTAMP operands involve no time zone. A
428
+ * TIMESTAMPTZ operand (most MJ date columns) is cast to a date in the session's time zone, so the
429
+ * count depends on it: `2026-11-01 23:00Z` to `2026-11-02 01:00Z` gives 1 in a UTC session and 0
430
+ * in Asia/Tokyo; it matches T-SQL on UTC values only when the session is in UTC. The old
431
+ * `EXTRACT(DAY FROM (e::TIMESTAMPTZ - s::TIMESTAMPTZ))` lost a day across a daylight-saving change
432
+ * in the session's zone and truncated part days (23:00 → 01:00 gave 0, T-SQL gives 1), issue #5920.
433
+ * TIME expressions have no date part and keep the interval form.
434
+ */
435
+ function dateDiffDays(e, s, useTimestamp) {
436
+ if (!useTimestamp)
437
+ return buildDateDiffExpr(e, s, `EXTRACT(DAY FROM ($E - $S))`, false);
438
+ return `((${e})::date - (${s})::date)`;
439
+ }
410
440
  function convertDateDiff(sql) {
411
441
  const pattern = /\bDATEDIFF\s*\(/gi;
412
442
  let result = '';
@@ -431,7 +461,7 @@ function convertDateDiff(sql) {
431
461
  case 'day':
432
462
  case 'dd':
433
463
  case 'd':
434
- replacement = buildDateDiffExpr(e, s, `EXTRACT(DAY FROM ($E - $S))`, useTimestamp);
464
+ replacement = dateDiffDays(e, s, useTimestamp);
435
465
  break;
436
466
  case 'hour':
437
467
  case 'hh':
@@ -458,7 +488,7 @@ function convertDateDiff(sql) {
458
488
  replacement = buildDateDiffExpr(e, s, `(EXTRACT(YEAR FROM AGE($E, $S)) * 12 + EXTRACT(MONTH FROM AGE($E, $S)))`, useTimestamp);
459
489
  break;
460
490
  default:
461
- replacement = buildDateDiffExpr(e, s, `EXTRACT(DAY FROM ($E - $S))`, useTimestamp);
491
+ replacement = dateDiffDays(e, s, useTimestamp);
462
492
  break;
463
493
  }
464
494
  result += sql.slice(lastIdx, match.index) + replacement;
@@ -762,10 +792,14 @@ export function ConvertTopToLimit(sql) {
762
792
  // Remove TOP N from SELECT clause
763
793
  const before = sql.slice(0, r.start);
764
794
  const after = sql.slice(r.end);
765
- // Find end of this SELECT statement (semicolon, closing paren at depth 0, or end)
795
+ // Find end of this SELECT statement (semicolon, closing paren at depth 0,
796
+ // statement/control-flow boundary on a new line at depth 0, or end)
766
797
  let depth = 0;
767
798
  let endPos = after.length;
799
+ const isProtected = (absPos) => protectedRanges.some(pr => absPos >= pr.start && absPos < pr.end);
768
800
  for (let j = 0; j < after.length; j++) {
801
+ if (isProtected(r.end + j))
802
+ continue;
769
803
  if (after[j] === '(')
770
804
  depth++;
771
805
  else if (after[j] === ')') {
@@ -779,6 +813,13 @@ export function ConvertTopToLimit(sql) {
779
813
  endPos = j;
780
814
  break;
781
815
  }
816
+ else if (after[j] === '\n' && depth === 0) {
817
+ const nextLine = after.slice(j + 1).replace(/^[ \t]+/, '');
818
+ if (/^(?:ELSE|ELSIF|END|IF|RETURN|UPDATE|INSERT|DELETE|SET|DECLARE|BEGIN|COMMIT|ROLLBACK|EXEC|PERFORM|RAISE)\b/i.test(nextLine)) {
819
+ endPos = j;
820
+ break;
821
+ }
822
+ }
782
823
  }
783
824
  const selectBody = after.slice(0, endPos);
784
825
  const rest = after.slice(endPos);
@@ -831,11 +872,205 @@ export function ConvertCastTypes(sql) {
831
872
  export function convertCastTypes(sql) {
832
873
  return ConvertCastTypes(sql);
833
874
  }
875
+ /** Text of `sql` with string-literal contents and comments blanked to spaces, so offsets match `sql`. */
876
+ function maskNonCode(sql) {
877
+ return segmentSQL(sql).map((seg) => {
878
+ if (seg.type === 'code')
879
+ return seg.text;
880
+ if (seg.type === 'comment')
881
+ return seg.text.replace(/[^\n]/g, ' ');
882
+ return seg.text.length >= 2 ? `'${' '.repeat(seg.text.length - 2)}'` : seg.text;
883
+ }).join('');
884
+ }
885
+ /** UUID text, as T-SQL's TRY_CONVERT(UNIQUEIDENTIFIER, …) accepts it. */
886
+ const UUID_TEXT_PATTERN = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$';
887
+ /** Integer TRY_CONVERT targets and the PostgreSQL type each casts to. */
888
+ const TRY_CONVERT_INTEGER_TYPES = {
889
+ INT: 'INTEGER', INTEGER: 'INTEGER', BIGINT: 'BIGINT', SMALLINT: 'SMALLINT', TINYINT: 'SMALLINT',
890
+ };
891
+ /**
892
+ * Convert T-SQL `TRY_CONVERT(type, x[, style])`, which returns NULL where a cast would fail.
893
+ * PostgreSQL has no such function, so each supported target becomes a guarded cast:
894
+ * - uniqueidentifier → `CASE WHEN (x)::text ~* '<uuid pattern>' THEN (x)::uuid END`
895
+ * - int / integer / bigint / smallint / tinyint → `CASE WHEN btrim((x)::text) ~ '^[+-]?[0-9]+$' THEN (x)::<type> END`
896
+ * Any other target is left as written; {@link HasTryConvert} finds it so the caller can report a
897
+ * gap. Before, the call reached PostgreSQL as `"TRY_CONVERT"(UUID, x)` (issue #5799).
898
+ */
899
+ export function ConvertTryConvert(sql) {
900
+ const masked = maskNonCode(sql);
901
+ const pattern = /\bTRY_CONVERT\s*\(/gi;
902
+ let result = '';
903
+ let lastIdx = 0;
904
+ let match;
905
+ while ((match = pattern.exec(masked)) !== null) {
906
+ const openIdx = match.index + match[0].length - 1;
907
+ const close = FindMatchingParen(masked, openIdx);
908
+ if (close < 0)
909
+ break;
910
+ const args = splitTopLevelCommas(sql.slice(openIdx + 1, close)).map((a) => a.trim());
911
+ const target = (args[0] ?? '').toUpperCase().replace(/\s+/g, '');
912
+ const x = args[1];
913
+ let replacement = null;
914
+ if (x && (target === 'UNIQUEIDENTIFIER' || target === 'UUID')) {
915
+ replacement = `CASE WHEN (${x})::text ~* '${UUID_TEXT_PATTERN}' THEN (${x})::uuid END`;
916
+ }
917
+ else if (x && TRY_CONVERT_INTEGER_TYPES[target]) {
918
+ replacement = `CASE WHEN btrim((${x})::text) ~ '^[+-]?[0-9]+$' THEN (${x})::${TRY_CONVERT_INTEGER_TYPES[target]} END`;
919
+ }
920
+ if (replacement === null)
921
+ continue;
922
+ result += sql.slice(lastIdx, match.index) + replacement;
923
+ lastIdx = close + 1;
924
+ pattern.lastIndex = lastIdx;
925
+ }
926
+ return result + sql.slice(lastIdx);
927
+ }
928
+ /** Whether code (not a literal or comment) in `sql` still calls TRY_CONVERT, quoted or not. */
929
+ export function HasTryConvert(sql) {
930
+ return /(?<![\w.])"?TRY_CONVERT"?\s*\(/i.test(maskNonCode(sql));
931
+ }
932
+ /**
933
+ * Add `RECURSIVE` to a `WITH` whose CTE list holds a CTE that reads itself (`FROM name` or
934
+ * `JOIN name` inside its own body). PostgreSQL rejects a self-reference without it, where T-SQL
935
+ * needs no keyword (issue #5799). A `WITH` that is not a CTE list (`WITH (NOLOCK)`, `WITH CHECK`)
936
+ * and one that already says RECURSIVE are left alone.
937
+ */
938
+ export function AddRecursiveToSelfReferencingCtes(sql) {
939
+ const masked = maskNonCode(sql);
940
+ const inserts = [];
941
+ const withPattern = /\bWITH\s+(?!RECURSIVE\b)/gi;
942
+ let match;
943
+ while ((match = withPattern.exec(masked)) !== null) {
944
+ if (cteListReadsItself(masked, match.index + match[0].length))
945
+ inserts.push(match.index + 4);
946
+ }
947
+ let result = sql;
948
+ for (const at of inserts.reverse())
949
+ result = `${result.slice(0, at)} RECURSIVE${result.slice(at)}`;
950
+ return result;
951
+ }
952
+ /** Parse the CTE list starting at `from` in masked SQL; true when one CTE's body names itself. */
953
+ function cteListReadsItself(masked, from) {
954
+ let pos = from;
955
+ for (;;) {
956
+ const head = masked.slice(pos).match(/^\s*"?(\w+)"?\s*/);
957
+ if (!head)
958
+ return false;
959
+ const name = head[1];
960
+ pos += head[0].length;
961
+ if (masked[pos] === '(') {
962
+ const colsEnd = FindMatchingParen(masked, pos);
963
+ if (colsEnd < 0)
964
+ return false;
965
+ pos = colsEnd + 1;
966
+ }
967
+ const as = masked.slice(pos).match(/^\s*AS\s*\(/i);
968
+ if (!as)
969
+ return false;
970
+ const open = pos + as[0].length - 1;
971
+ const close = FindMatchingParen(masked, open);
972
+ if (close < 0)
973
+ return false;
974
+ const body = masked.slice(open + 1, close);
975
+ if (new RegExp(`\\b(?:FROM|JOIN)\\s+"?${EscapeRegExp(name)}"?(?![\\w"])`, 'i').test(body))
976
+ return true;
977
+ const comma = masked.slice(close + 1).match(/^\s*,/);
978
+ if (!comma)
979
+ return false;
980
+ pos = close + 1 + comma[0].length;
981
+ }
982
+ }
983
+ /**
984
+ * Keep SQL Server NULL semantics on converted unique constraints and indexes (#5194): SQL Server
985
+ * treats NULLs as equal in a unique index, PostgreSQL does not unless `NULLS NOT DISTINCT` (PG 15+).
986
+ * - `UNIQUE (cols)` constraints (table-level or `ALTER TABLE … ADD`) → `UNIQUE NULLS NOT DISTINCT (cols)`
987
+ * - `CREATE UNIQUE INDEX … ON t (cols)` → `… ON t (cols) NULLS NOT DISTINCT`
988
+ * Code only; text inside literals and comments is untouched, and a statement that already says
989
+ * NULLS [NOT] DISTINCT is left alone.
990
+ */
991
+ export function AddNullsNotDistinct(sql) {
992
+ return TransformCodeOnly(sql, (code) => {
993
+ if (/\bNULLS\s+(?:NOT\s+)?DISTINCT\b/i.test(code))
994
+ return code;
995
+ if (/^\s*CREATE\s+UNIQUE\s+INDEX\b/i.test(code)) {
996
+ return code.replace(/(\bON\s+\S+?\s*\([^)]*\))/i, '$1 NULLS NOT DISTINCT');
997
+ }
998
+ return code.replace(/\bUNIQUE\s*\(/gi, 'UNIQUE NULLS NOT DISTINCT (');
999
+ });
1000
+ }
1001
+ /** HASHBYTES algorithms with a PostgreSQL builtin; others are left for a person (pgcrypto). */
1002
+ const HASHBYTES_FUNCTIONS = {
1003
+ SHA2_256: (arg) => `sha256(convert_to(${arg}, 'UTF8'))`,
1004
+ SHA2_512: (arg) => `sha512(convert_to(${arg}, 'UTF8'))`,
1005
+ MD5: (arg) => `decode(md5(${arg}), 'hex')`,
1006
+ };
1007
+ /**
1008
+ * Rewrite every call `NAME(…)` in the code of `sql` (outside literals and comments) through
1009
+ * `rewrite`, innermost-last. `rewrite` returns null to leave a call unchanged.
1010
+ */
1011
+ function rewriteCalls(sql, name, rewrite) {
1012
+ const masked = maskNonCode(sql);
1013
+ const re = new RegExp(`\\b${name}\\s*\\(`, 'gi');
1014
+ const hits = [];
1015
+ let m;
1016
+ while ((m = re.exec(masked)) !== null)
1017
+ hits.push(m.index);
1018
+ let out = sql;
1019
+ for (const start of hits.reverse()) {
1020
+ const open = out.indexOf('(', start);
1021
+ const parsed = parseBalancedArgs(out, open);
1022
+ if (!parsed)
1023
+ continue;
1024
+ const replacement = rewrite(parsed.args);
1025
+ if (replacement !== null)
1026
+ out = out.slice(0, start) + replacement + out.slice(parsed.endIdx);
1027
+ }
1028
+ return out;
1029
+ }
1030
+ /**
1031
+ * T-SQL `HASHBYTES('SHA2_256' | 'SHA2_512' | 'MD5', x)` → PostgreSQL `sha256 | sha512(convert_to(x,
1032
+ * 'UTF8'))` / `decode(md5(x), 'hex')` (#6538 item 3). Other algorithms are left unchanged.
1033
+ */
1034
+ export function ConvertHashBytes(sql) {
1035
+ return rewriteCalls(sql, 'HASHBYTES', (args) => {
1036
+ if (args.length !== 2)
1037
+ return null;
1038
+ const alg = args[0].replace(/^N?'|'$/g, '').toUpperCase();
1039
+ const fn = HASHBYTES_FUNCTIONS[alg];
1040
+ return fn ? fn(args[1]) : null;
1041
+ });
1042
+ }
1043
+ /** True when a CONVERT argument is a binary value: a HASHBYTES call or a VARBINARY/BINARY cast. */
1044
+ function isBinaryArgument(arg) {
1045
+ return /^HASHBYTES\s*\(/i.test(arg) || /^CAST\s*\([\s\S]*\bAS\s+"?(?:VAR)?BINARY"?\b/i.test(arg);
1046
+ }
1047
+ /**
1048
+ * T-SQL `CONVERT(VARCHAR(n), <binary>, 1|2)` → `CAST(upper(encode(<binary>, 'hex')) AS VARCHAR(n))`,
1049
+ * `0x`-prefixed for style 1 (#6538 item 3). The generic CONVERT rewrite drops the style, which turns
1050
+ * a hex rendering into PostgreSQL's raw bytea text. Other styles on a binary value are left as they
1051
+ * are for the gap scan to report.
1052
+ */
1053
+ export function ConvertBinaryStyleConvert(sql) {
1054
+ return rewriteCalls(sql, 'CONVERT', (args) => {
1055
+ if (args.length !== 3 || !isBinaryArgument(args[1]))
1056
+ return null;
1057
+ const style = args[2].trim();
1058
+ if (style !== '1' && style !== '2')
1059
+ return null;
1060
+ const hex = `upper(encode(${ConvertHashBytes(args[1])}, 'hex'))`;
1061
+ const value = style === '1' ? `'0x' || ${hex}` : hex;
1062
+ return `CAST(${value} AS ${mapInlineType(args[0].trim())})`;
1063
+ });
1064
+ }
834
1065
  /**
835
1066
  * Convert T-SQL CONVERT(type, expr[, style]) → CAST(expr AS mapped_type).
836
- * Drops the optional style parameter.
1067
+ * Drops the optional style parameter, except for a binary value with style 1 or 2
1068
+ * ({@link ConvertBinaryStyleConvert}). TRY_CONVERT is converted first ({@link ConvertTryConvert}).
837
1069
  */
838
1070
  export function ConvertConvertFunction(sql) {
1071
+ sql = ConvertTryConvert(sql);
1072
+ sql = ConvertBinaryStyleConvert(sql);
1073
+ sql = ConvertHashBytes(sql);
839
1074
  // 3-arg: CONVERT(type, expr, style)
840
1075
  sql = sql.replace(/\bCONVERT\s*\(\s*(\w+(?:\s*\([^)]*\))?)\s*,\s*([^,)]+)\s*,\s*[^)]+\)/gi, (_match, type, expr) => {
841
1076
  return `CAST(${expr.trim()} AS ${mapInlineType(type.trim())})`;
@@ -869,16 +1104,26 @@ function mapInlineType(tsqlType) {
869
1104
  * That bug silently corrupted ISO codes in v5.25 Metadata_Sync and
870
1105
  * caused spCreateStateProvince to hit UQ_StateProvince_ISO3166_2.
871
1106
  *
872
- * Fix: only strip N' in contexts where a string literal *starts* — i.e.
873
- * after a non-quote boundary character (whitespace, punctuation, paren,
874
- * operator, comma, equals, start of line). This leaves N' inside a
875
- * string alone.
1107
+ * Fix: only strip an N that sits in code directly before a string literal opens,
1108
+ * after a boundary character (whitespace, punctuation, paren, operator, comma,
1109
+ * equals, start of input). The scan walks code / string / comment segments, so
1110
+ * text inside a literal is never touched — including an escaped `N''x''` inside
1111
+ * a stored query, which a plain regex read as a prefix (issue #5838).
876
1112
  */
877
1113
  export function RemoveNPrefix(sql) {
878
- // Anchors: start of string, or after one of the "string-start" context chars.
879
- // Whitespace, comma, paren, comparison operators, brackets, semicolon.
880
- return sql.replace(/(^|[\s(,=<>!+\-*\/[;])N'/g, "$1'");
1114
+ let result = '';
1115
+ for (const seg of segmentSQL(sql)) {
1116
+ // A literal right after another literal leaves `result` ending in a quote, which the
1117
+ // pattern cannot match, so no separate check for the previous segment is needed.
1118
+ if (seg.type === 'string' && N_PREFIX_BEFORE_LITERAL.test(result)) {
1119
+ result = result.slice(0, -1);
1120
+ }
1121
+ result += seg.text;
1122
+ }
1123
+ return result;
881
1124
  }
1125
+ /** A code tail ending in the `N` of a unicode-literal prefix: boundary (or start), then `N`. */
1126
+ const N_PREFIX_BEFORE_LITERAL = /(?:^|[\s(,=<>!+\-*\/[;])N$/;
882
1127
  /** @deprecated Use {@link RemoveNPrefix}. */
883
1128
  export function removeNPrefix(sql) {
884
1129
  return RemoveNPrefix(sql);
@@ -1109,38 +1354,170 @@ function splitArgs(body) {
1109
1354
  out.push(cur.trim());
1110
1355
  return out;
1111
1356
  }
1357
+ /**
1358
+ * Parse a T-SQL JSON path literal such as `'$.a.b'`, `N'$.a.b'`, `'strict $.a.b'`,
1359
+ * `'lax $.items[0].name'`, or `'$'` into its mode and PostgreSQL path segments.
1360
+ * Returns `null` when the argument is not a supported string literal path.
1361
+ */
1362
+ function parseJsonPathLiteral(pathLit) {
1363
+ const pm = pathLit.trim().match(/^N?'(.*)'$/s);
1364
+ if (!pm)
1365
+ return null;
1366
+ let body = pm[1].trim();
1367
+ let strict = false;
1368
+ if (/^strict\s+/i.test(body)) {
1369
+ strict = true;
1370
+ body = body.replace(/^strict\s+/i, '');
1371
+ }
1372
+ else if (/^lax\s+/i.test(body)) {
1373
+ body = body.replace(/^lax\s+/i, '');
1374
+ }
1375
+ if (!body.startsWith('$'))
1376
+ return null;
1377
+ const rest = body.slice(1);
1378
+ if (rest.length === 0) {
1379
+ return { strict, segments: [] };
1380
+ }
1381
+ // Support dotted keys (`$.a.b`) and bracketed array indices (`$.items[0].name`).
1382
+ const segments = [];
1383
+ const tokenRe = /\.([^.[\]]+)|\[(\d+)\]/g;
1384
+ let consumed = 0;
1385
+ let tm;
1386
+ while ((tm = tokenRe.exec(rest)) !== null) {
1387
+ if (tm.index !== consumed)
1388
+ return null;
1389
+ segments.push(tm[1] ?? tm[2]);
1390
+ consumed = tm.index + tm[0].length;
1391
+ }
1392
+ if (consumed !== rest.length)
1393
+ return null;
1394
+ return { strict, segments };
1395
+ }
1396
+ /** Format a PostgreSQL `text[]` path literal like `'{scope,searchScopeAccess}'`. */
1397
+ function formatPgJsonPathArray(segments) {
1398
+ const escaped = segments.map(s => s.replace(/'/g, "''"));
1399
+ return `'{${escaped.join(',')}}'`;
1400
+ }
1401
+ /**
1402
+ * Convert the 3rd (`newValue`) argument of T-SQL `JSON_MODIFY(target, path, newValue)`
1403
+ * into a PostgreSQL `jsonb` expression suitable for `jsonb_set(...)`.
1404
+ */
1405
+ function formatJsonModifyValue(rawValue) {
1406
+ const trimmed = rawValue.trim();
1407
+ // Already a jsonb expression (e.g. produced by nested JSON_QUERY('...') -> ('...')::jsonb)
1408
+ if (/::jsonb\s*$/i.test(trimmed)) {
1409
+ return trimmed;
1410
+ }
1411
+ // String literal (with optional T-SQL N prefix if called standalone before RemoveNPrefix)
1412
+ const strMatch = trimmed.match(/^N?('(?:''|[^'])*')$/s);
1413
+ if (strMatch) {
1414
+ return `to_jsonb(${strMatch[1]}::text)`;
1415
+ }
1416
+ // Numeric or boolean literal, or typed SQL expression
1417
+ return `to_jsonb(${trimmed})`;
1418
+ }
1419
+ /** Returns true when character index `pos` falls inside a single-quoted SQL string literal. */
1420
+ function isInsideSqlString(sql, pos) {
1421
+ let inStr = false;
1422
+ for (let i = 0; i < pos; i++) {
1423
+ if (sql[i] === "'") {
1424
+ if (inStr && sql[i + 1] === "'") {
1425
+ i++;
1426
+ }
1427
+ else {
1428
+ inStr = !inStr;
1429
+ }
1430
+ }
1431
+ }
1432
+ return inStr;
1433
+ }
1112
1434
  /**
1113
1435
  * Convert SQL Server JSON functions to PostgreSQL equivalents:
1114
- * JSON_VALUE(expr, '$.a.b') → (expr)::jsonb #>> '{a,b}' (->> for a single segment)
1115
- * ISJSON(expr) = 1 → (expr) IS JSON
1116
- * ISJSON(expr) = 0 → (expr) IS NOT JSON
1117
- * ISJSON(expr) → (expr) IS JSON
1436
+ * JSON_MODIFY(expr, '$.a.b', val) → jsonb_set((expr)::jsonb, '{a,b}', to_jsonb(val), true)::text
1437
+ * JSON_MODIFY(expr, '$.a.b', NULL) → ((expr)::jsonb #- '{a,b}')::text (lax mode deletes key)
1438
+ * JSON_QUERY(expr) → (expr)::jsonb
1439
+ * JSON_QUERY(expr, '$.a.b') → (expr)::jsonb #> '{a,b}' (-> for a single segment)
1440
+ * JSON_VALUE(expr, '$.a.b') → (expr)::jsonb #>> '{a,b}' (->> for a single segment)
1441
+ * ISJSON(expr) = 1 → (expr) IS JSON
1442
+ * ISJSON(expr) = 0 → (expr) IS NOT JSON
1443
+ * ISJSON(expr) → (expr) IS JSON
1118
1444
  * Accepts both bare (`JSON_VALUE(...)`) and already-quoted (`"JSON_VALUE"(...)`) forms,
1119
- * so it is order-independent relative to identifier quoting. PG 16+ provides the IS JSON
1120
- * predicate; JSON_VALUE's `$.`-rooted path is rewritten to jsonb path-extraction operators.
1445
+ * so it is order-independent relative to identifier quoting, and handles arbitrarily nested
1446
+ * calls (e.g., `JSON_MODIFY(CASE WHEN JSON_QUERY(...) IS NULL THEN JSON_MODIFY(..., JSON_QUERY('{}')) ...)`).
1447
+ * PG 16+ provides the IS JSON predicate; `jsonb_set` results are cast to `::text` so they stay
1448
+ * type-compatible with `TEXT` columns and `CASE ... ELSE col END` expressions.
1121
1449
  */
1122
1450
  export function ConvertJsonFunctions(sql) {
1451
+ sql = convertNamedJsonCall(sql, 'JSON_MODIFY', (args, after) => {
1452
+ if (args.length !== 3)
1453
+ return null;
1454
+ const targetExpr = ConvertJsonFunctions(args[0]);
1455
+ const parsedPath = parseJsonPathLiteral(args[1]);
1456
+ if (!parsedPath)
1457
+ return null;
1458
+ const convertedValue = ConvertJsonFunctions(args[2]).trim();
1459
+ if (parsedPath.segments.length === 0) {
1460
+ if (convertedValue.toUpperCase() === 'NULL') {
1461
+ return { replacement: parsedPath.strict ? `'null'::jsonb::text` : 'NULL', consume: 0, after };
1462
+ }
1463
+ return { replacement: `(${formatJsonModifyValue(convertedValue)})::text`, consume: 0, after };
1464
+ }
1465
+ const pgPath = formatPgJsonPathArray(parsedPath.segments);
1466
+ if (convertedValue.toUpperCase() === 'NULL') {
1467
+ if (parsedPath.strict) {
1468
+ return {
1469
+ replacement: `jsonb_set((${targetExpr})::jsonb, ${pgPath}, 'null'::jsonb, true)::text`,
1470
+ consume: 0,
1471
+ after,
1472
+ };
1473
+ }
1474
+ return {
1475
+ replacement: `((${targetExpr})::jsonb #- ${pgPath})::text`,
1476
+ consume: 0,
1477
+ after,
1478
+ };
1479
+ }
1480
+ const valJsonb = formatJsonModifyValue(convertedValue);
1481
+ return {
1482
+ replacement: `jsonb_set((${targetExpr})::jsonb, ${pgPath}, ${valJsonb}, true)::text`,
1483
+ consume: 0,
1484
+ after,
1485
+ };
1486
+ });
1487
+ sql = convertNamedJsonCall(sql, 'JSON_QUERY', (args, after) => {
1488
+ if (args.length < 1 || args.length > 2)
1489
+ return null;
1490
+ const expr = ConvertJsonFunctions(args[0]).trim().replace(/^N('(?:''|[^'])*')$/s, '$1');
1491
+ if (args.length === 1) {
1492
+ return { replacement: `(${expr})::jsonb`, consume: 0, after };
1493
+ }
1494
+ const parsedPath = parseJsonPathLiteral(args[1]);
1495
+ if (!parsedPath)
1496
+ return null;
1497
+ if (parsedPath.segments.length === 0) {
1498
+ return { replacement: `(${expr})::jsonb`, consume: 0, after };
1499
+ }
1500
+ const replacement = parsedPath.segments.length === 1
1501
+ ? `(${expr})::jsonb -> '${parsedPath.segments[0].replace(/'/g, "''")}'`
1502
+ : `(${expr})::jsonb #> ${formatPgJsonPathArray(parsedPath.segments)}`;
1503
+ return { replacement, consume: 0, after };
1504
+ });
1123
1505
  sql = convertNamedJsonCall(sql, 'JSON_VALUE', (args, after) => {
1124
1506
  if (args.length < 2)
1125
1507
  return null;
1126
- const expr = args[0];
1127
- const pathLit = args[1].trim();
1128
- const pm = pathLit.match(/^'(.*)'$/s);
1129
- if (!pm)
1508
+ const expr = ConvertJsonFunctions(args[0]);
1509
+ const parsedPath = parseJsonPathLiteral(args[1]);
1510
+ if (!parsedPath || parsedPath.segments.length === 0)
1130
1511
  return null;
1131
- // Strip leading '$.' / '$' and split into segments.
1132
- const segs = pm[1].replace(/^\$\.?/, '').split('.').filter(s => s.length > 0);
1133
- if (segs.length === 0)
1134
- return null;
1135
- const replacement = segs.length === 1
1136
- ? `(${expr})::jsonb ->> '${segs[0]}'`
1137
- : `(${expr})::jsonb #>> '{${segs.join(',')}}'`;
1512
+ const replacement = parsedPath.segments.length === 1
1513
+ ? `(${expr})::jsonb ->> '${parsedPath.segments[0].replace(/'/g, "''")}'`
1514
+ : `(${expr})::jsonb #>> ${formatPgJsonPathArray(parsedPath.segments)}`;
1138
1515
  return { replacement, consume: 0, after };
1139
1516
  });
1140
1517
  sql = convertNamedJsonCall(sql, 'ISJSON', (args, after) => {
1141
1518
  if (args.length < 1)
1142
1519
  return null;
1143
- const expr = args[0];
1520
+ const expr = ConvertJsonFunctions(args[0]);
1144
1521
  // Look for a trailing `= 1` / `= 0` comparison to fold into IS [NOT] JSON.
1145
1522
  const cmp = after.match(/^\s*=\s*([01])(?![\w.])/);
1146
1523
  if (cmp) {
@@ -1161,7 +1538,7 @@ export function convertJsonFunctions(sql) {
1161
1538
  * characters of the trailing context to also consume (for folding `= 1` etc.).
1162
1539
  */
1163
1540
  function convertNamedJsonCall(sql, name, build) {
1164
- const callRe = new RegExp(`"?${name}"?\\s*\\(`, 'gi');
1541
+ const callRe = new RegExp(`(?<!\\w)"?${name}"?\\s*\\(`, 'gi');
1165
1542
  let result = sql;
1166
1543
  let searchFrom = 0;
1167
1544
  while (true) {
@@ -1169,6 +1546,10 @@ function convertNamedJsonCall(sql, name, build) {
1169
1546
  const m = callRe.exec(result);
1170
1547
  if (!m)
1171
1548
  break;
1549
+ if (isInsideSqlString(result, m.index)) {
1550
+ searchFrom = m.index + m[0].length;
1551
+ continue;
1552
+ }
1172
1553
  const openParen = result.indexOf('(', m.index);
1173
1554
  const close = matchParen(result, openParen);
1174
1555
  if (close < 0) {
@@ -1613,4 +1994,71 @@ export function NeedsHandAuthoring(kind, reason, sql) {
1613
1994
  const commented = sql.trim().split('\n').map((l) => `-- ${l}`).join('\n');
1614
1995
  return `${GAP_MARKER_NEEDS_HAND_AUTHORING}: ${kind} — ${reason}\n${commented}\n`;
1615
1996
  }
1997
+ /**
1998
+ * Add `ON TRUE` after a `LEFT JOIN LATERAL (...)` that has no join condition — PostgreSQL requires
1999
+ * one, T-SQL's `OUTER APPLY` has none. Line-based: tracks paren depth from the LATERAL keyword to the
2000
+ * line that closes it, then inserts `ON TRUE` unless the next line already starts with `ON`.
2001
+ *
2002
+ * Only a LEFT join gets one. This logic used to live in ViewRule and fired on any LATERAL, which put
2003
+ * `ON TRUE` after `CROSS JOIN LATERAL` too — a PostgreSQL syntax error (`syntax error at or near "on"`).
2004
+ *
2005
+ * @param sql - SQL whose `APPLY` clauses have already been rewritten to `LATERAL`.
2006
+ * @returns The SQL with each unconditioned LATERAL join given `ON TRUE`.
2007
+ */
2008
+ export function AddLateralOnTrue(sql) {
2009
+ const lines = sql.split('\n');
2010
+ const result = [];
2011
+ let lateralDepth = 0;
2012
+ let inLateral = false;
2013
+ const needsOnAfter = (i) => !(i + 1 < lines.length ? lines[i + 1].trim().toUpperCase() : '').startsWith('ON ');
2014
+ for (let i = 0; i < lines.length; i++) {
2015
+ result.push(lines[i]);
2016
+ // Detect LEFT JOIN LATERAL block start
2017
+ if (/\bLEFT\s+(?:OUTER\s+)?JOIN\s+LATERAL\b/i.test(lines[i]) && !inLateral) {
2018
+ const rest = lines[i].slice(lines[i].search(/\bLATERAL\b/i));
2019
+ const openCount = [...rest].filter((ch) => ch === '(').length;
2020
+ const closeCount = [...rest].filter((ch) => ch === ')').length;
2021
+ if (openCount > closeCount) {
2022
+ // Multi-line LATERAL: opening paren not closed on this line
2023
+ inLateral = true;
2024
+ lateralDepth = openCount - closeCount;
2025
+ }
2026
+ else if (openCount > 0 && openCount === closeCount && needsOnAfter(i)) {
2027
+ // Single-line LATERAL: fully closed on this line
2028
+ result.push(' ON TRUE');
2029
+ }
2030
+ continue;
2031
+ }
2032
+ // Track multi-line LATERAL depth
2033
+ if (inLateral) {
2034
+ for (const ch of lines[i]) {
2035
+ if (ch === '(')
2036
+ lateralDepth++;
2037
+ else if (ch === ')')
2038
+ lateralDepth--;
2039
+ }
2040
+ if (lateralDepth <= 0) {
2041
+ inLateral = false;
2042
+ if (needsOnAfter(i))
2043
+ result.push(' ON TRUE');
2044
+ }
2045
+ }
2046
+ }
2047
+ return result.join('\n');
2048
+ }
2049
+ /**
2050
+ * Rewrite T-SQL `OUTER APPLY` / `CROSS APPLY` to PostgreSQL LATERAL joins: `OUTER APPLY (...) x`
2051
+ * becomes `LEFT JOIN LATERAL (...) x ON TRUE`, and `CROSS APPLY` becomes `CROSS JOIN LATERAL`.
2052
+ *
2053
+ * @param sql - T-SQL text (views, inline table-valued function bodies).
2054
+ * @returns The rewritten SQL.
2055
+ */
2056
+ export function ConvertApplyToLateral(sql) {
2057
+ if (!/\b(?:OUTER|CROSS)\s+APPLY\b/i.test(sql))
2058
+ return sql;
2059
+ const rewritten = sql
2060
+ .replace(/\bCROSS\s+APPLY\b/gi, 'CROSS JOIN LATERAL')
2061
+ .replace(/\bOUTER\s+APPLY\b/gi, 'LEFT JOIN LATERAL');
2062
+ return AddLateralOnTrue(rewritten);
2063
+ }
1616
2064
  //# sourceMappingURL=ExpressionHelpers.js.map