@memberjunction/sql-converter 6.3.0-edge.0 → 6.3.0-edge.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/IncrementalBaker.d.ts +85 -7
- package/dist/IncrementalBaker.d.ts.map +1 -1
- package/dist/IncrementalBaker.js +120 -12
- package/dist/IncrementalBaker.js.map +1 -1
- package/dist/MigrationConverter.d.ts +54 -1
- package/dist/MigrationConverter.d.ts.map +1 -1
- package/dist/MigrationConverter.js +226 -23
- package/dist/MigrationConverter.js.map +1 -1
- package/dist/MigrationStatementSplitter.d.ts +11 -1
- package/dist/MigrationStatementSplitter.d.ts.map +1 -1
- package/dist/MigrationStatementSplitter.js +6 -3
- package/dist/MigrationStatementSplitter.js.map +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/rules/AlterTableRule.d.ts.map +1 -1
- package/dist/rules/AlterTableRule.js +6 -1
- package/dist/rules/AlterTableRule.js.map +1 -1
- package/dist/rules/BatchConverter.d.ts +16 -0
- package/dist/rules/BatchConverter.d.ts.map +1 -1
- package/dist/rules/BatchConverter.js +169 -15
- package/dist/rules/BatchConverter.js.map +1 -1
- package/dist/rules/BitColumnRegistry.d.ts +9 -0
- package/dist/rules/BitColumnRegistry.d.ts.map +1 -0
- package/dist/rules/BitColumnRegistry.js +111 -0
- package/dist/rules/BitColumnRegistry.js.map +1 -0
- package/dist/rules/CatalogViewRule.d.ts +6 -0
- package/dist/rules/CatalogViewRule.d.ts.map +1 -1
- package/dist/rules/CatalogViewRule.js +15 -1
- package/dist/rules/CatalogViewRule.js.map +1 -1
- package/dist/rules/ConditionalDDLRule.d.ts +32 -0
- package/dist/rules/ConditionalDDLRule.d.ts.map +1 -1
- package/dist/rules/ConditionalDDLRule.js +111 -6
- package/dist/rules/ConditionalDDLRule.js.map +1 -1
- package/dist/rules/CreateIndexRule.d.ts +18 -0
- package/dist/rules/CreateIndexRule.d.ts.map +1 -1
- package/dist/rules/CreateIndexRule.js +47 -14
- package/dist/rules/CreateIndexRule.js.map +1 -1
- package/dist/rules/CreateTableRule.d.ts.map +1 -1
- package/dist/rules/CreateTableRule.js +10 -3
- package/dist/rules/CreateTableRule.js.map +1 -1
- package/dist/rules/DeclareDmlBlockRule.d.ts +9 -3
- package/dist/rules/DeclareDmlBlockRule.d.ts.map +1 -1
- package/dist/rules/DeclareDmlBlockRule.js +12 -47
- package/dist/rules/DeclareDmlBlockRule.js.map +1 -1
- package/dist/rules/DialectHeaderBuilder.d.ts +50 -4
- package/dist/rules/DialectHeaderBuilder.d.ts.map +1 -1
- package/dist/rules/DialectHeaderBuilder.js +50 -4
- package/dist/rules/DialectHeaderBuilder.js.map +1 -1
- package/dist/rules/ExpressionHelpers.d.ts +144 -5
- package/dist/rules/ExpressionHelpers.d.ts.map +1 -1
- package/dist/rules/ExpressionHelpers.js +522 -17
- package/dist/rules/ExpressionHelpers.js.map +1 -1
- package/dist/rules/FunctionRule.d.ts +3 -1
- package/dist/rules/FunctionRule.d.ts.map +1 -1
- package/dist/rules/FunctionRule.js +49 -7
- package/dist/rules/FunctionRule.js.map +1 -1
- package/dist/rules/GrantRule.d.ts +12 -1
- package/dist/rules/GrantRule.d.ts.map +1 -1
- package/dist/rules/GrantRule.js +122 -2
- package/dist/rules/GrantRule.js.map +1 -1
- package/dist/rules/InsertRule.d.ts +1 -0
- package/dist/rules/InsertRule.d.ts.map +1 -1
- package/dist/rules/InsertRule.js +161 -10
- package/dist/rules/InsertRule.js.map +1 -1
- package/dist/rules/PostProcessor.d.ts.map +1 -1
- package/dist/rules/PostProcessor.js +50 -27
- package/dist/rules/PostProcessor.js.map +1 -1
- package/dist/rules/ProcedureToFunctionRule.d.ts +30 -1
- package/dist/rules/ProcedureToFunctionRule.d.ts.map +1 -1
- package/dist/rules/ProcedureToFunctionRule.js +330 -17
- package/dist/rules/ProcedureToFunctionRule.js.map +1 -1
- package/dist/rules/ScalarVariableInliner.d.ts +33 -0
- package/dist/rules/ScalarVariableInliner.d.ts.map +1 -0
- package/dist/rules/ScalarVariableInliner.js +201 -0
- package/dist/rules/ScalarVariableInliner.js.map +1 -0
- package/dist/rules/SequenceDeduplicator.d.ts +16 -2
- package/dist/rules/SequenceDeduplicator.d.ts.map +1 -1
- package/dist/rules/SequenceDeduplicator.js +50 -14
- package/dist/rules/SequenceDeduplicator.js.map +1 -1
- package/dist/rules/StatementClassifier.d.ts +9 -0
- package/dist/rules/StatementClassifier.d.ts.map +1 -1
- package/dist/rules/StatementClassifier.js +66 -12
- package/dist/rules/StatementClassifier.js.map +1 -1
- package/dist/rules/SubSplitter.d.ts.map +1 -1
- package/dist/rules/SubSplitter.js +102 -6
- package/dist/rules/SubSplitter.js.map +1 -1
- package/dist/rules/TriggerRule.d.ts +3 -1
- package/dist/rules/TriggerRule.d.ts.map +1 -1
- package/dist/rules/TriggerRule.js +22 -3
- package/dist/rules/TriggerRule.js.map +1 -1
- package/dist/rules/ViewRule.d.ts +0 -2
- package/dist/rules/ViewRule.d.ts.map +1 -1
- package/dist/rules/ViewRule.js +8 -57
- package/dist/rules/ViewRule.js.map +1 -1
- package/dist/rules/index.d.ts +6 -4
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +4 -3
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/types.d.ts +18 -2
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +14 -0
- package/dist/rules/types.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +3 -3
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Expression-level conversion helpers shared across multiple rules.
|
|
3
|
-
*
|
|
4
|
-
* convert_charindex, convert_stuff, convert_string_concat, convert_iif,
|
|
5
|
-
*
|
|
3
|
+
* Started as a port of the Python converter (convert_identifiers, convert_date_functions,
|
|
4
|
+
* convert_charindex, convert_stuff, convert_string_concat, convert_iif, convert_top_to_limit,
|
|
5
|
+
* etc.); later helpers were written here directly and have no Python counterpart.
|
|
6
6
|
*/
|
|
7
7
|
import { ResolveInlineType } from './TypeResolver.js';
|
|
8
|
+
import { GAP_MARKER_NEEDS_HAND_AUTHORING } from './types.js';
|
|
8
9
|
/**
|
|
9
10
|
* Split SQL into segments of code, string literals, and comments.
|
|
10
11
|
* String literals (single-quoted, with '' escaping) and comments (-- and block)
|
|
@@ -144,6 +145,21 @@ export function StripComments(sql) {
|
|
|
144
145
|
export function QuoteConstraintNames(sql) {
|
|
145
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)));
|
|
146
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
|
+
}
|
|
147
163
|
/**
|
|
148
164
|
* Emit a DO-block that drops every overload of a function in a given schema.
|
|
149
165
|
*
|
|
@@ -406,6 +422,21 @@ function buildDateDiffExpr(e, s, extractExpr, useTimestamp) {
|
|
|
406
422
|
.replace(/\$E/g, e)
|
|
407
423
|
.replace(/\$S/g, s);
|
|
408
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
|
+
}
|
|
409
440
|
function convertDateDiff(sql) {
|
|
410
441
|
const pattern = /\bDATEDIFF\s*\(/gi;
|
|
411
442
|
let result = '';
|
|
@@ -430,7 +461,7 @@ function convertDateDiff(sql) {
|
|
|
430
461
|
case 'day':
|
|
431
462
|
case 'dd':
|
|
432
463
|
case 'd':
|
|
433
|
-
replacement =
|
|
464
|
+
replacement = dateDiffDays(e, s, useTimestamp);
|
|
434
465
|
break;
|
|
435
466
|
case 'hour':
|
|
436
467
|
case 'hh':
|
|
@@ -457,7 +488,7 @@ function convertDateDiff(sql) {
|
|
|
457
488
|
replacement = buildDateDiffExpr(e, s, `(EXTRACT(YEAR FROM AGE($E, $S)) * 12 + EXTRACT(MONTH FROM AGE($E, $S)))`, useTimestamp);
|
|
458
489
|
break;
|
|
459
490
|
default:
|
|
460
|
-
replacement =
|
|
491
|
+
replacement = dateDiffDays(e, s, useTimestamp);
|
|
461
492
|
break;
|
|
462
493
|
}
|
|
463
494
|
result += sql.slice(lastIdx, match.index) + replacement;
|
|
@@ -560,7 +591,10 @@ export function ConvertStringConcat(sql, tableColumns) {
|
|
|
560
591
|
const startsWithPlus = /^\s*\+/.test(newCode);
|
|
561
592
|
const endsWithPlus = /\+\s*$/.test(newCode);
|
|
562
593
|
if (startsWithPlus || endsWithPlus) {
|
|
563
|
-
|
|
594
|
+
// A `+` whose right operand is a numeric literal is arithmetic even between two string
|
|
595
|
+
// literals: the code between them can span a whole recursive-CTE member, where
|
|
596
|
+
// `p."RelativeDepth" + 1` became `|| 1` (issue #5364 item 6).
|
|
597
|
+
newCode = newCode.replace(/\+(?!\s*\d)/g, '||');
|
|
564
598
|
}
|
|
565
599
|
}
|
|
566
600
|
else if (prevIsString) {
|
|
@@ -758,10 +792,14 @@ export function ConvertTopToLimit(sql) {
|
|
|
758
792
|
// Remove TOP N from SELECT clause
|
|
759
793
|
const before = sql.slice(0, r.start);
|
|
760
794
|
const after = sql.slice(r.end);
|
|
761
|
-
// Find end of this SELECT statement (semicolon, closing paren at depth 0,
|
|
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)
|
|
762
797
|
let depth = 0;
|
|
763
798
|
let endPos = after.length;
|
|
799
|
+
const isProtected = (absPos) => protectedRanges.some(pr => absPos >= pr.start && absPos < pr.end);
|
|
764
800
|
for (let j = 0; j < after.length; j++) {
|
|
801
|
+
if (isProtected(r.end + j))
|
|
802
|
+
continue;
|
|
765
803
|
if (after[j] === '(')
|
|
766
804
|
depth++;
|
|
767
805
|
else if (after[j] === ')') {
|
|
@@ -775,6 +813,13 @@ export function ConvertTopToLimit(sql) {
|
|
|
775
813
|
endPos = j;
|
|
776
814
|
break;
|
|
777
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
|
+
}
|
|
778
823
|
}
|
|
779
824
|
const selectBody = after.slice(0, endPos);
|
|
780
825
|
const rest = after.slice(endPos);
|
|
@@ -827,11 +872,205 @@ export function ConvertCastTypes(sql) {
|
|
|
827
872
|
export function convertCastTypes(sql) {
|
|
828
873
|
return ConvertCastTypes(sql);
|
|
829
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
|
+
}
|
|
830
1065
|
/**
|
|
831
1066
|
* Convert T-SQL CONVERT(type, expr[, style]) → CAST(expr AS mapped_type).
|
|
832
|
-
* 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}).
|
|
833
1069
|
*/
|
|
834
1070
|
export function ConvertConvertFunction(sql) {
|
|
1071
|
+
sql = ConvertTryConvert(sql);
|
|
1072
|
+
sql = ConvertBinaryStyleConvert(sql);
|
|
1073
|
+
sql = ConvertHashBytes(sql);
|
|
835
1074
|
// 3-arg: CONVERT(type, expr, style)
|
|
836
1075
|
sql = sql.replace(/\bCONVERT\s*\(\s*(\w+(?:\s*\([^)]*\))?)\s*,\s*([^,)]+)\s*,\s*[^)]+\)/gi, (_match, type, expr) => {
|
|
837
1076
|
return `CAST(${expr.trim()} AS ${mapInlineType(type.trim())})`;
|
|
@@ -865,16 +1104,26 @@ function mapInlineType(tsqlType) {
|
|
|
865
1104
|
* That bug silently corrupted ISO codes in v5.25 Metadata_Sync and
|
|
866
1105
|
* caused spCreateStateProvince to hit UQ_StateProvince_ISO3166_2.
|
|
867
1106
|
*
|
|
868
|
-
* Fix: only strip N
|
|
869
|
-
* after a
|
|
870
|
-
*
|
|
871
|
-
*
|
|
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).
|
|
872
1112
|
*/
|
|
873
1113
|
export function RemoveNPrefix(sql) {
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
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;
|
|
877
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$/;
|
|
878
1127
|
/** @deprecated Use {@link RemoveNPrefix}. */
|
|
879
1128
|
export function removeNPrefix(sql) {
|
|
880
1129
|
return RemoveNPrefix(sql);
|
|
@@ -934,13 +1183,28 @@ const PASCAL_QUOTE_KEYWORDS = new Set([
|
|
|
934
1183
|
*/
|
|
935
1184
|
export function QuotePascalCaseIdentifiers(sql) {
|
|
936
1185
|
return TransformCodeOnly(sql, (code) => {
|
|
937
|
-
return code.replace(/(?<!")(?<!\w)([A-Z]\w*)(?!")(?!\w)/g, (match, word) => {
|
|
938
|
-
if (PASCAL_QUOTE_KEYWORDS.has(word.toUpperCase()))
|
|
1186
|
+
return code.replace(/(?<!")(?<!\w)([A-Z]\w*)(?!")(?!\w)/g, (match, word, offset, whole) => {
|
|
1187
|
+
if (PASCAL_QUOTE_KEYWORDS.has(word.toUpperCase()) && !IsKeywordNamedColumn(word, whole, offset))
|
|
939
1188
|
return match;
|
|
940
1189
|
return `"${word}"`;
|
|
941
1190
|
});
|
|
942
1191
|
});
|
|
943
1192
|
}
|
|
1193
|
+
/**
|
|
1194
|
+
* True when a word that is also a SQL keyword or built-in (`Length`, `Precision`, `Action`) is
|
|
1195
|
+
* being used as a column: written in mixed case, as MJ column names are, and followed by `=` the way
|
|
1196
|
+
* an `UPDATE ... SET Length=100` assignment or a `WHERE Precision = 0` comparison uses it.
|
|
1197
|
+
*
|
|
1198
|
+
* Keywords in T-SQL source are upper-case by convention, so a mixed-case spelling directly followed
|
|
1199
|
+
* by `=` is a column. Without this check CodeGen's `UPDATE EntityField SET ... Length=100,
|
|
1200
|
+
* Precision=0` kept those two names bare while quoting every other column, and PostgreSQL folded
|
|
1201
|
+
* them to `length` / `precision` (`column "length" does not exist`) — issue #5364 item 5.
|
|
1202
|
+
*/
|
|
1203
|
+
export function IsKeywordNamedColumn(word, text, offset) {
|
|
1204
|
+
if (word === word.toUpperCase())
|
|
1205
|
+
return false;
|
|
1206
|
+
return /^\s*=(?![=>])/.test(text.slice(offset + word.length));
|
|
1207
|
+
}
|
|
944
1208
|
/** @deprecated Use {@link QuotePascalCaseIdentifiers}. */
|
|
945
1209
|
export function quotePascalCaseIdentifiers(sql) {
|
|
946
1210
|
return QuotePascalCaseIdentifiers(sql);
|
|
@@ -1420,4 +1684,245 @@ function splitTopLevelValues(s) {
|
|
|
1420
1684
|
out.push(cur);
|
|
1421
1685
|
return out;
|
|
1422
1686
|
}
|
|
1687
|
+
/**
|
|
1688
|
+
* T-SQL built-in functions that PostgreSQL also has, keyed by upper-cased T-SQL name and mapped to
|
|
1689
|
+
* the PostgreSQL spelling. Renamed ones carry the PG name (`LEN` → `LENGTH`).
|
|
1690
|
+
*/
|
|
1691
|
+
const BUILTIN_FUNCTION_NAMES = new Map([
|
|
1692
|
+
['UPPER', 'UPPER'], ['LOWER', 'LOWER'], ['LTRIM', 'LTRIM'], ['RTRIM', 'RTRIM'], ['TRIM', 'TRIM'],
|
|
1693
|
+
['LEN', 'LENGTH'], ['LENGTH', 'LENGTH'], ['DATALENGTH', 'OCTET_LENGTH'], ['SUBSTRING', 'SUBSTRING'],
|
|
1694
|
+
['REPLACE', 'REPLACE'], ['LEFT', 'LEFT'], ['RIGHT', 'RIGHT'], ['REVERSE', 'REVERSE'], ['CONCAT', 'CONCAT'],
|
|
1695
|
+
['COALESCE', 'COALESCE'], ['ISNULL', 'COALESCE'], ['NULLIF', 'NULLIF'],
|
|
1696
|
+
['ABS', 'ABS'], ['ROUND', 'ROUND'], ['FLOOR', 'FLOOR'], ['CEILING', 'CEILING'], ['POWER', 'POWER'],
|
|
1697
|
+
['SQRT', 'SQRT'], ['SIGN', 'SIGN'],
|
|
1698
|
+
['MAX', 'MAX'], ['MIN', 'MIN'], ['COUNT', 'COUNT'], ['SUM', 'SUM'], ['AVG', 'AVG'],
|
|
1699
|
+
]);
|
|
1700
|
+
/**
|
|
1701
|
+
* Unquote T-SQL built-in function calls that identifier quoting turned into quoted identifiers:
|
|
1702
|
+
* `"UPPER"("Code")` → `UPPER("Code")`, `"LEN"(x)` → `LENGTH(x)`.
|
|
1703
|
+
*
|
|
1704
|
+
* The PascalCase quoting passes each keep their own keyword list, and a built-in missing from one of
|
|
1705
|
+
* them came out quoted. PostgreSQL resolves a quoted name case-sensitively, so `"UPPER"` names no
|
|
1706
|
+
* function (`function UPPER(character) does not exist`) — issue #5364 item 1.
|
|
1707
|
+
*
|
|
1708
|
+
* Only an unqualified call matches: SQL Server requires a user-defined scalar function to be called
|
|
1709
|
+
* schema-qualified (`dbo.fn(...)`), so a bare quoted name followed by `(` can only be a built-in.
|
|
1710
|
+
* String literals and comments are left untouched.
|
|
1711
|
+
*/
|
|
1712
|
+
export function UnquoteBuiltinFunctionCalls(sql) {
|
|
1713
|
+
return TransformCodeOnly(sql, (code) => code.replace(/(?<![.\w"])"([A-Za-z_]+)"(\s*\()/g, (match, name, paren) => {
|
|
1714
|
+
const pgName = BUILTIN_FUNCTION_NAMES.get(name.toUpperCase());
|
|
1715
|
+
return pgName ? `${pgName}${paren}` : match;
|
|
1716
|
+
}));
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Convert the argument of a T-SQL `OBJECT_ID('schema.Object')` to the text `to_regclass` parses:
|
|
1720
|
+
* brackets removed, the object name double-quoted (MJ object names are case-sensitive PascalCase),
|
|
1721
|
+
* the schema left unquoted so it folds to lowercase like the schema `CREATE SCHEMA` produced.
|
|
1722
|
+
*/
|
|
1723
|
+
function objectIdArgToRegclass(arg) {
|
|
1724
|
+
const parts = arg
|
|
1725
|
+
.split('.')
|
|
1726
|
+
.map((p) => p.trim().replace(/^\[(.*)\]$/, '$1').replace(/^"(.*)"$/, '$1'))
|
|
1727
|
+
.filter((p) => p.length > 0);
|
|
1728
|
+
const name = parts.pop() ?? '';
|
|
1729
|
+
const quotedName = `"${name.replace(/"/g, '""')}"`;
|
|
1730
|
+
return parts.length > 0 ? `${parts[parts.length - 1]}.${quotedName}` : quotedName;
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Convert T-SQL `OBJECT_ID('[schema].[Table]'[, 'U'])` (bare or already quoted as `"OBJECT_ID"`) to
|
|
1734
|
+
* PostgreSQL `to_regclass('schema."Table"')`. Both return NULL for a missing object, and the
|
|
1735
|
+
* regclass result compares directly with `pg_constraint.conrelid` — issue #5364 item 1.
|
|
1736
|
+
* The optional object-type argument has no `to_regclass` counterpart and is dropped.
|
|
1737
|
+
*/
|
|
1738
|
+
export function ConvertObjectIdCalls(sql) {
|
|
1739
|
+
return sql.replace(/(?<![.\w"])"?OBJECT_ID"?\s*\(\s*N?'([^']+)'\s*(?:,\s*N?'[^']*'\s*)?\)/gi, (_m, arg) => `to_regclass('${objectIdArgToRegclass(arg).replace(/'/g, "''")}')`);
|
|
1740
|
+
}
|
|
1741
|
+
/** Regex metacharacters that must be escaped when a LIKE pattern becomes a POSIX regex. */
|
|
1742
|
+
const REGEX_META = /[.*+?^${}()|\\]/;
|
|
1743
|
+
/**
|
|
1744
|
+
* Translate a T-SQL LIKE pattern that uses a character class (`[...]` / `[^...]`) into an
|
|
1745
|
+
* equivalent POSIX regular expression, or return null when the pattern has no class.
|
|
1746
|
+
* `%` → `.*`, `_` → `.`, a class is kept as-is (T-SQL and POSIX share `[a-z]`/`[^a-z]` syntax),
|
|
1747
|
+
* everything else is matched literally. The regex is anchored, and a leading/trailing `.*` is
|
|
1748
|
+
* dropped because an unanchored regex already means "anywhere".
|
|
1749
|
+
*/
|
|
1750
|
+
function likePatternToRegex(pattern) {
|
|
1751
|
+
if (!/\[[^\]]+\]/.test(pattern))
|
|
1752
|
+
return null;
|
|
1753
|
+
let body = '';
|
|
1754
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
1755
|
+
const ch = pattern[i];
|
|
1756
|
+
if (ch === '[') {
|
|
1757
|
+
const close = pattern.indexOf(']', i + 1);
|
|
1758
|
+
if (close < 0)
|
|
1759
|
+
return null;
|
|
1760
|
+
// A backslash inside a POSIX bracket expression is literal, so the class copies verbatim.
|
|
1761
|
+
body += pattern.slice(i, close + 1);
|
|
1762
|
+
i = close;
|
|
1763
|
+
}
|
|
1764
|
+
else if (ch === '%') {
|
|
1765
|
+
// `%%` matches what `%` does; one `.*` keeps the anchor trimming below working.
|
|
1766
|
+
if (!body.endsWith('.*'))
|
|
1767
|
+
body += '.*';
|
|
1768
|
+
}
|
|
1769
|
+
else if (ch === '_') {
|
|
1770
|
+
body += '.';
|
|
1771
|
+
}
|
|
1772
|
+
else {
|
|
1773
|
+
body += REGEX_META.test(ch) ? `\\${ch}` : ch;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
let anchored = `^${body}$`;
|
|
1777
|
+
if (anchored.startsWith('^.*'))
|
|
1778
|
+
anchored = anchored.slice(3);
|
|
1779
|
+
if (anchored.endsWith('.*$'))
|
|
1780
|
+
anchored = anchored.slice(0, -3);
|
|
1781
|
+
return anchored;
|
|
1782
|
+
}
|
|
1783
|
+
/**
|
|
1784
|
+
* Convert `[NOT] LIKE '<pattern with [...] class>'` to the POSIX regex operators `~` / `!~`.
|
|
1785
|
+
*
|
|
1786
|
+
* PostgreSQL LIKE has no character classes, so `"Code" NOT LIKE '%[^A-Z0-9_-]%'` searches for the
|
|
1787
|
+
* literal text `[^A-Z0-9_-]` and a CHECK built on it accepts every value — the constraint is lost
|
|
1788
|
+
* without an error (issue #5364 item 2). The regex form keeps it: `"Code" !~ '[^A-Z0-9_-]'`.
|
|
1789
|
+
*
|
|
1790
|
+
* The match is case-sensitive, like the converted LIKE and `=` comparisons around it; a SQL Server
|
|
1791
|
+
* database under a case-insensitive collation matched classes case-insensitively. A LIKE with an
|
|
1792
|
+
* ESCAPE clause is left alone, since its escape character changes how the pattern reads.
|
|
1793
|
+
*/
|
|
1794
|
+
export function ConvertLikeCharacterClasses(sql) {
|
|
1795
|
+
const segments = segmentSQL(sql);
|
|
1796
|
+
for (let i = 0; i + 1 < segments.length; i++) {
|
|
1797
|
+
const code = segments[i];
|
|
1798
|
+
const literal = segments[i + 1];
|
|
1799
|
+
if (code.type !== 'code' || literal.type !== 'string')
|
|
1800
|
+
continue;
|
|
1801
|
+
const op = code.text.match(/\b(NOT\s+)?LIKE\s*$/i);
|
|
1802
|
+
if (!op || op.index === undefined)
|
|
1803
|
+
continue;
|
|
1804
|
+
const after = segments[i + 2];
|
|
1805
|
+
if (after && after.type === 'code' && /^\s*ESCAPE\b/i.test(after.text))
|
|
1806
|
+
continue;
|
|
1807
|
+
const pattern = literal.text.slice(1, -1).replace(/''/g, "'");
|
|
1808
|
+
const regex = likePatternToRegex(pattern);
|
|
1809
|
+
if (regex === null)
|
|
1810
|
+
continue;
|
|
1811
|
+
code.text = code.text.slice(0, op.index) + (op[1] ? '!~ ' : '~ ');
|
|
1812
|
+
literal.text = `'${regex.replace(/'/g, "''")}'`;
|
|
1813
|
+
}
|
|
1814
|
+
return segments.map((s) => s.text).join('');
|
|
1815
|
+
}
|
|
1816
|
+
/** MJ core's schema — the only schema the routine rules' patterns are written against. */
|
|
1817
|
+
const CORE_SCHEMA = '__mj';
|
|
1818
|
+
/** The schema a `CREATE [OR ALTER] PROCEDURE|FUNCTION|TRIGGER <schema>.<name>` routine is created in. */
|
|
1819
|
+
export function RoutineSchema(sql) {
|
|
1820
|
+
const m = StripComments(sql).match(/\bCREATE\s+(?:OR\s+ALTER\s+)?(?:PROC(?:EDURE)?|FUNCTION|TRIGGER)\s+(?:\[([^\]]+)\]|"([^"]+)"|([\w$]+))\s*\./i);
|
|
1821
|
+
return m ? (m[1] ?? m[2] ?? m[3]) : null;
|
|
1822
|
+
}
|
|
1823
|
+
/**
|
|
1824
|
+
* Convert a routine with a converter whose patterns are written against MJ core's `__mj` schema,
|
|
1825
|
+
* when the routine lives in another schema (an Open App's `__mj_BizAppsAccounting`).
|
|
1826
|
+
*
|
|
1827
|
+
* The procedure and trigger rules match `[__mj].[spX]` and emit `__mj."X"` throughout. Rather than
|
|
1828
|
+
* re-deriving each of those patterns, the routine's own schema is renamed to `__mj` on the way in
|
|
1829
|
+
* and back on the way out, so an Open App routine takes exactly the path a core routine does.
|
|
1830
|
+
* Before this, every Open App CRUD procedure and trigger fell through to "SKIPPED" and the
|
|
1831
|
+
* converted migration installed tables and views but no routines (issue #5364 item 8).
|
|
1832
|
+
*
|
|
1833
|
+
* Returns null when the routine also names the literal core schema (`__mj.X`) anywhere outside
|
|
1834
|
+
* comments, string literals included (a RAISERROR message that mentions `__mj.` counts): the
|
|
1835
|
+
* rename back could not tell its own references from core's, so the caller must not convert it
|
|
1836
|
+
* this way. Placeholder references (`${mjSchema}.X`) are unaffected and stay distinct.
|
|
1837
|
+
*/
|
|
1838
|
+
export function ConvertInRoutineSchema(sql, convert) {
|
|
1839
|
+
const schema = RoutineSchema(sql);
|
|
1840
|
+
if (!schema || schema.toLowerCase() === CORE_SCHEMA)
|
|
1841
|
+
return convert(sql);
|
|
1842
|
+
const code = StripComments(sql);
|
|
1843
|
+
if (/(?:\[__mj\]|"__mj"|(?<![\w$])__mj)\s*\./i.test(code))
|
|
1844
|
+
return null;
|
|
1845
|
+
const own = new RegExp(`(?:\\[${EscapeRegExp(schema)}\\]|"${EscapeRegExp(schema)}"|(?<![\\w$])${EscapeRegExp(schema)})(\\s*\\.)`, 'gi');
|
|
1846
|
+
const aliased = TransformCodeOnly(sql, (c) => c.replace(own, (_m, dot) => `${CORE_SCHEMA}${dot}`));
|
|
1847
|
+
const converted = convert(aliased);
|
|
1848
|
+
return TransformCodeOnly(converted, (c) => c.replace(/(?<![\w$"])__mj(\s*\.)/g, (_m, dot) => `${schema}${dot}`))
|
|
1849
|
+
.replace(/'__mj'::regnamespace/g, () => `'${schema}'::regnamespace`);
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* Comment out a routine the converter cannot produce, under the needs-hand-authoring gap marker,
|
|
1853
|
+
* keeping every line of the source so a person can author the PostgreSQL version from it.
|
|
1854
|
+
* Every line is prefixed — a multi-line routine with only its first line commented leaves the
|
|
1855
|
+
* rest as live T-SQL in a PostgreSQL file (issue #5364 item 7).
|
|
1856
|
+
*/
|
|
1857
|
+
export function NeedsHandAuthoring(kind, reason, sql) {
|
|
1858
|
+
const commented = sql.trim().split('\n').map((l) => `-- ${l}`).join('\n');
|
|
1859
|
+
return `${GAP_MARKER_NEEDS_HAND_AUTHORING}: ${kind} — ${reason}\n${commented}\n`;
|
|
1860
|
+
}
|
|
1861
|
+
/**
|
|
1862
|
+
* Add `ON TRUE` after a `LEFT JOIN LATERAL (...)` that has no join condition — PostgreSQL requires
|
|
1863
|
+
* one, T-SQL's `OUTER APPLY` has none. Line-based: tracks paren depth from the LATERAL keyword to the
|
|
1864
|
+
* line that closes it, then inserts `ON TRUE` unless the next line already starts with `ON`.
|
|
1865
|
+
*
|
|
1866
|
+
* Only a LEFT join gets one. This logic used to live in ViewRule and fired on any LATERAL, which put
|
|
1867
|
+
* `ON TRUE` after `CROSS JOIN LATERAL` too — a PostgreSQL syntax error (`syntax error at or near "on"`).
|
|
1868
|
+
*
|
|
1869
|
+
* @param sql - SQL whose `APPLY` clauses have already been rewritten to `LATERAL`.
|
|
1870
|
+
* @returns The SQL with each unconditioned LATERAL join given `ON TRUE`.
|
|
1871
|
+
*/
|
|
1872
|
+
export function AddLateralOnTrue(sql) {
|
|
1873
|
+
const lines = sql.split('\n');
|
|
1874
|
+
const result = [];
|
|
1875
|
+
let lateralDepth = 0;
|
|
1876
|
+
let inLateral = false;
|
|
1877
|
+
const needsOnAfter = (i) => !(i + 1 < lines.length ? lines[i + 1].trim().toUpperCase() : '').startsWith('ON ');
|
|
1878
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1879
|
+
result.push(lines[i]);
|
|
1880
|
+
// Detect LEFT JOIN LATERAL block start
|
|
1881
|
+
if (/\bLEFT\s+(?:OUTER\s+)?JOIN\s+LATERAL\b/i.test(lines[i]) && !inLateral) {
|
|
1882
|
+
const rest = lines[i].slice(lines[i].search(/\bLATERAL\b/i));
|
|
1883
|
+
const openCount = [...rest].filter((ch) => ch === '(').length;
|
|
1884
|
+
const closeCount = [...rest].filter((ch) => ch === ')').length;
|
|
1885
|
+
if (openCount > closeCount) {
|
|
1886
|
+
// Multi-line LATERAL: opening paren not closed on this line
|
|
1887
|
+
inLateral = true;
|
|
1888
|
+
lateralDepth = openCount - closeCount;
|
|
1889
|
+
}
|
|
1890
|
+
else if (openCount > 0 && openCount === closeCount && needsOnAfter(i)) {
|
|
1891
|
+
// Single-line LATERAL: fully closed on this line
|
|
1892
|
+
result.push(' ON TRUE');
|
|
1893
|
+
}
|
|
1894
|
+
continue;
|
|
1895
|
+
}
|
|
1896
|
+
// Track multi-line LATERAL depth
|
|
1897
|
+
if (inLateral) {
|
|
1898
|
+
for (const ch of lines[i]) {
|
|
1899
|
+
if (ch === '(')
|
|
1900
|
+
lateralDepth++;
|
|
1901
|
+
else if (ch === ')')
|
|
1902
|
+
lateralDepth--;
|
|
1903
|
+
}
|
|
1904
|
+
if (lateralDepth <= 0) {
|
|
1905
|
+
inLateral = false;
|
|
1906
|
+
if (needsOnAfter(i))
|
|
1907
|
+
result.push(' ON TRUE');
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
return result.join('\n');
|
|
1912
|
+
}
|
|
1913
|
+
/**
|
|
1914
|
+
* Rewrite T-SQL `OUTER APPLY` / `CROSS APPLY` to PostgreSQL LATERAL joins: `OUTER APPLY (...) x`
|
|
1915
|
+
* becomes `LEFT JOIN LATERAL (...) x ON TRUE`, and `CROSS APPLY` becomes `CROSS JOIN LATERAL`.
|
|
1916
|
+
*
|
|
1917
|
+
* @param sql - T-SQL text (views, inline table-valued function bodies).
|
|
1918
|
+
* @returns The rewritten SQL.
|
|
1919
|
+
*/
|
|
1920
|
+
export function ConvertApplyToLateral(sql) {
|
|
1921
|
+
if (!/\b(?:OUTER|CROSS)\s+APPLY\b/i.test(sql))
|
|
1922
|
+
return sql;
|
|
1923
|
+
const rewritten = sql
|
|
1924
|
+
.replace(/\bCROSS\s+APPLY\b/gi, 'CROSS JOIN LATERAL')
|
|
1925
|
+
.replace(/\bOUTER\s+APPLY\b/gi, 'LEFT JOIN LATERAL');
|
|
1926
|
+
return AddLateralOnTrue(rewritten);
|
|
1927
|
+
}
|
|
1423
1928
|
//# sourceMappingURL=ExpressionHelpers.js.map
|