@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.
Files changed (107) hide show
  1. package/README.md +16 -0
  2. package/dist/IncrementalBaker.d.ts +85 -7
  3. package/dist/IncrementalBaker.d.ts.map +1 -1
  4. package/dist/IncrementalBaker.js +120 -12
  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 +169 -15
  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 +15 -1
  32. package/dist/rules/CatalogViewRule.js.map +1 -1
  33. package/dist/rules/ConditionalDDLRule.d.ts +32 -0
  34. package/dist/rules/ConditionalDDLRule.d.ts.map +1 -1
  35. package/dist/rules/ConditionalDDLRule.js +111 -6
  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 +144 -5
  53. package/dist/rules/ExpressionHelpers.d.ts.map +1 -1
  54. package/dist/rules/ExpressionHelpers.js +522 -17
  55. package/dist/rules/ExpressionHelpers.js.map +1 -1
  56. package/dist/rules/FunctionRule.d.ts +3 -1
  57. package/dist/rules/FunctionRule.d.ts.map +1 -1
  58. package/dist/rules/FunctionRule.js +49 -7
  59. package/dist/rules/FunctionRule.js.map +1 -1
  60. package/dist/rules/GrantRule.d.ts +12 -1
  61. package/dist/rules/GrantRule.d.ts.map +1 -1
  62. package/dist/rules/GrantRule.js +122 -2
  63. package/dist/rules/GrantRule.js.map +1 -1
  64. package/dist/rules/InsertRule.d.ts +1 -0
  65. package/dist/rules/InsertRule.d.ts.map +1 -1
  66. package/dist/rules/InsertRule.js +161 -10
  67. package/dist/rules/InsertRule.js.map +1 -1
  68. package/dist/rules/PostProcessor.d.ts.map +1 -1
  69. package/dist/rules/PostProcessor.js +50 -27
  70. package/dist/rules/PostProcessor.js.map +1 -1
  71. package/dist/rules/ProcedureToFunctionRule.d.ts +30 -1
  72. package/dist/rules/ProcedureToFunctionRule.d.ts.map +1 -1
  73. package/dist/rules/ProcedureToFunctionRule.js +330 -17
  74. package/dist/rules/ProcedureToFunctionRule.js.map +1 -1
  75. package/dist/rules/ScalarVariableInliner.d.ts +33 -0
  76. package/dist/rules/ScalarVariableInliner.d.ts.map +1 -0
  77. package/dist/rules/ScalarVariableInliner.js +201 -0
  78. package/dist/rules/ScalarVariableInliner.js.map +1 -0
  79. package/dist/rules/SequenceDeduplicator.d.ts +16 -2
  80. package/dist/rules/SequenceDeduplicator.d.ts.map +1 -1
  81. package/dist/rules/SequenceDeduplicator.js +50 -14
  82. package/dist/rules/SequenceDeduplicator.js.map +1 -1
  83. package/dist/rules/StatementClassifier.d.ts +9 -0
  84. package/dist/rules/StatementClassifier.d.ts.map +1 -1
  85. package/dist/rules/StatementClassifier.js +66 -12
  86. package/dist/rules/StatementClassifier.js.map +1 -1
  87. package/dist/rules/SubSplitter.d.ts.map +1 -1
  88. package/dist/rules/SubSplitter.js +102 -6
  89. package/dist/rules/SubSplitter.js.map +1 -1
  90. package/dist/rules/TriggerRule.d.ts +3 -1
  91. package/dist/rules/TriggerRule.d.ts.map +1 -1
  92. package/dist/rules/TriggerRule.js +22 -3
  93. package/dist/rules/TriggerRule.js.map +1 -1
  94. package/dist/rules/ViewRule.d.ts +0 -2
  95. package/dist/rules/ViewRule.d.ts.map +1 -1
  96. package/dist/rules/ViewRule.js +8 -57
  97. package/dist/rules/ViewRule.js.map +1 -1
  98. package/dist/rules/index.d.ts +6 -4
  99. package/dist/rules/index.d.ts.map +1 -1
  100. package/dist/rules/index.js +4 -3
  101. package/dist/rules/index.js.map +1 -1
  102. package/dist/rules/types.d.ts +18 -2
  103. package/dist/rules/types.d.ts.map +1 -1
  104. package/dist/rules/types.js +14 -0
  105. package/dist/rules/types.js.map +1 -1
  106. package/dist/tsconfig.tsbuildinfo +1 -0
  107. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { ConvertIdentifiers, ConvertDateFunctions, ConvertCharIndex, ConvertStringConcat, ConvertTopToLimit, ConvertCastTypes, ConvertIIF, RemoveCollate, ConvertCommonFunctions, EmitDropOverloadsBlock, ConvertBooleanLiteralComparisons, CollectBooleanColumnNames, TransformCodeOnly, } from './ExpressionHelpers.js';
1
+ import { ConvertIdentifiers, ConvertDateFunctions, ConvertCharIndex, ConvertStringConcat, ConvertTopToLimit, ConvertCastTypes, ConvertIIF, RemoveCollate, ConvertCommonFunctions, EmitDropOverloadsBlock, ConvertInRoutineSchema, NeedsHandAuthoring, RoutineSchema, StripComments, ConvertBooleanLiteralComparisons, CollectBooleanColumnNames, TransformCodeOnly, } from './ExpressionHelpers.js';
2
2
  import { ResolveType } from './TypeResolver.js';
3
3
  import { CrudCallPerformLines } from './CrudCallEmitter.js';
4
4
  /**
@@ -39,7 +39,25 @@ export class ProcedureToFunctionRule {
39
39
  this.BypassSqlglot = true;
40
40
  this.BypassJustification = 'T-SQL CREATE PROCEDURE → PG CREATE FUNCTION conversion: parameter renaming (@param → p_param), DECLARE handling, RAISERROR → RAISE EXCEPTION, INSERT...OUTPUT handling, RETURN value semantics, and SETOF return types. This is structural transformation sqlglot does not perform.';
41
41
  }
42
- PostProcess(sql, _originalSQL, context) {
42
+ PostProcess(sql, originalSQL, context) {
43
+ const normalized = sql.replace(/\bCREATE\s+OR\s+ALTER\s+PROC(EDURE)?\b/i, 'CREATE PROC$1');
44
+ const schema = RoutineSchema(normalized);
45
+ // An Open App procedure is converted through the core-schema path only when it is CodeGen
46
+ // CRUD output (spCreate/spUpdate/spDelete), whose shape that path is built for. A hand-written
47
+ // app procedure is left for a person to author rather than run through generic conversion
48
+ // (issue #5364 item 8).
49
+ if (schema && schema.toLowerCase() !== '__mj') {
50
+ const name = StripComments(normalized).match(/\bCREATE\s+PROC(?:EDURE)?\s+\S+?\.\s*\[?"?(\w+)/i)?.[1] ?? '';
51
+ if (!/^sp(?:Create|Update|Delete)\w+$/i.test(name)) {
52
+ return NeedsHandAuthoring('procedure', `${name} is a hand-written procedure in schema ${schema}`, originalSQL);
53
+ }
54
+ const converted = ConvertInRoutineSchema(normalized, (aliased) => this.convertCoreSchemaProcedure(aliased, context));
55
+ return converted ?? NeedsHandAuthoring('procedure', `${name} references the core schema by its literal name`, originalSQL);
56
+ }
57
+ return this.convertCoreSchemaProcedure(normalized, context);
58
+ }
59
+ /** Convert a procedure created in MJ core's `__mj` schema (the shape every pattern below assumes). */
60
+ convertCoreSchemaProcedure(sql, context) {
43
61
  // Extract proc name via regex
44
62
  let procMatch = sql.match(/CREATE\s+PROC(?:EDURE)?\s+\[?__mj\]?\.\[?(\w+)\]?\s*(.*?)(?:\bAS\b)/is);
45
63
  if (!procMatch) {
@@ -69,7 +87,7 @@ export class ProcedureToFunctionRule {
69
87
  // than emit a function PG can't create. Flag for manual review.
70
88
  return `-- SKIPPED (INTENTIONAL): ${procName} — ${paramCount} parameters exceeds PostgreSQL's ${POSTGRESQL_PROCEDURE_PARAM_LIMIT}-argument limit and could not be auto-converted to JSON-arg shape; needs manual handling`;
71
89
  }
72
- const rowReturnsClause = this.determineReturnType(body, procName, context);
90
+ const rowReturnsClause = this.determineReturnType(body, procName, context, paramsBlock);
73
91
  // If the return type references a view that doesn't exist, skip this procedure
74
92
  if (rowReturnsClause.startsWith('-- SKIPPED')) {
75
93
  return rowReturnsClause;
@@ -80,7 +98,13 @@ export class ProcedureToFunctionRule {
80
98
  const returnsClause = outputAsInOut ? 'AS' : rowReturnsClause;
81
99
  const pgParams = this.convertProcParams(paramsBlock, outputAsInOut);
82
100
  const booleanParams = this.extractBooleanParams(paramsBlock);
83
- const pgBody = this.convertProcBody(body, procName, context, booleanParams);
101
+ let pgBody = this.convertProcBody(body, procName, context, booleanParams);
102
+ // A RETURNS TABLE whose columns are real table columns ("ID", "__mj_UpdatedAt") declares OUT
103
+ // variables of the same names, so the UPDATE's `WHERE "ID" = p_ID` becomes ambiguous at run time.
104
+ // Native PG CodeGen resolves it the same way: column references win.
105
+ if (this.baseTableProjectionColumns(body, paramsBlock)) {
106
+ pgBody = `#variable_conflict use_column\n${pgBody}`;
107
+ }
84
108
  // Drop any existing overloads of this function before recreating. PG
85
109
  // dispatches functions by (name, ordered-arg-type-list) — `CREATE OR
86
110
  // REPLACE FUNCTION` only replaces the body when the new signature
@@ -254,14 +278,9 @@ $$ LANGUAGE plpgsql;
254
278
  const param = rawParam.trim();
255
279
  if (!param)
256
280
  continue;
257
- const m = param.match(/@(\w+)\s+([\w(),\s]+?)(?:\s*=\s*(.+?))?(?:\s+OUTPUT|\s+OUT)?\s*$/i);
258
- if (m) {
259
- parsedParams.push({
260
- Name: m[1],
261
- Type: m[2].trim(),
262
- Default: m[3] ?? null,
263
- IsOutput: isOutputParam(param),
264
- });
281
+ const parsed = parseProcParam(param);
282
+ if (parsed) {
283
+ parsedParams.push({ ...parsed, IsOutput: isOutputParam(param) });
265
284
  }
266
285
  }
267
286
  // Second pass: ensure all input params after a default have defaults too (INOUT is an input)
@@ -383,10 +402,6 @@ $$ LANGUAGE plpgsql;
383
402
  });
384
403
  // Remove TABLE variable declarations
385
404
  sql = sql.replace(/DECLARE\s+p_\w+\s+TABLE\s*\([^)]*\)\s*;?/gis, '');
386
- // @@ROWCOUNT → GET DIAGNOSTICS
387
- if (hasRowcount) {
388
- declares.unshift(' _v_row_count INTEGER;');
389
- }
390
405
  // SET p_var = value → p_var := value;
391
406
  sql = sql.replace(/\bSET\s+(p_\w+)\s*=\s*(.+?)(?:;|\s*$)/gim, (_match, varRef, value) => {
392
407
  const trimmedValue = value.trim();
@@ -480,6 +495,11 @@ $$ LANGUAGE plpgsql;
480
495
  if (hasRowcount) {
481
496
  sql = convertRowcountIfBlock(sql);
482
497
  }
498
+ // Declare _v_row_count only if still referenced after rowcount block conversion
499
+ // (IF @@ROWCOUNT = 0 CRUD checks convert directly to PL/pgSQL IF NOT FOUND).
500
+ if (/\b_v_row_count\b/.test(sql)) {
501
+ declares.unshift(' _v_row_count INTEGER;');
502
+ }
483
503
  // Convert standalone SELECT * FROM → RETURN QUERY SELECT * FROM
484
504
  sql = sql.replace(/^(\s+)(SELECT\s+(?:DISTINCT\s+)?\*\s+FROM\s+)/gim, '$1RETURN QUERY $2');
485
505
  // Convert SELECT NULL/p_var AS "ID" → RETURN QUERY SELECT
@@ -561,7 +581,7 @@ $$ LANGUAGE plpgsql;
561
581
  // ---------------------------------------------------------------------------
562
582
  // Return type detection
563
583
  // ---------------------------------------------------------------------------
564
- determineReturnType(body, procName, context) {
584
+ determineReturnType(body, procName, context, paramsBlock = '') {
565
585
  // Check for SELECT * FROM __mj.vwViewName → RETURNS SETOF
566
586
  const viewMatch = body.match(/SELECT\s+(?:\*|[\w\s,.*]+)\s+FROM\s+\[?__mj\]?\.\[?(vw\w+)\]?/i);
567
587
  if (viewMatch) {
@@ -597,6 +617,14 @@ $$ LANGUAGE plpgsql;
597
617
  const colType = this.inferScalarColumnType(scalarMatch[1], body);
598
618
  return `RETURNS TABLE("${scalarMatch[2]}" ${colType}) AS`;
599
619
  }
620
+ // Single-write CodeGen spUpdate (MJ 6.3): returns named columns from the BASE TABLE rather than
621
+ // `SELECT * FROM vwX`. A typed RETURNS TABLE is required — SETOF RECORD needs a column definition
622
+ // list at every call site, which the data provider never supplies.
623
+ const projection = this.baseTableProjectionColumns(body, paramsBlock);
624
+ if (projection) {
625
+ const cols = projection.map((c) => `"${c.Name}" ${c.Type}`).join(', ');
626
+ return `RETURNS TABLE(${cols}) AS`;
627
+ }
600
628
  // If there's any SELECT that returns rows
601
629
  const upperBody = body.toUpperCase();
602
630
  if (/\bSELECT\b/.test(upperBody) && !/SELECT\s+@/.test(upperBody)) {
@@ -604,6 +632,52 @@ $$ LANGUAGE plpgsql;
604
632
  }
605
633
  return 'RETURNS VOID AS';
606
634
  }
635
+ /**
636
+ * The typed result columns of a CRUD procedure that returns named columns from its base table — the
637
+ * single-write `spUpdate` shape CodeGen emits from MJ 6.3:
638
+ *
639
+ * ```sql
640
+ * IF @@ROWCOUNT = 0
641
+ * SELECT TOP 0 [ID], [__mj_CreatedAt], [__mj_UpdatedAt] FROM [__mj].[T] WHERE 1=0
642
+ * ELSE
643
+ * SELECT [ID], [__mj_CreatedAt], [__mj_UpdatedAt] FROM [__mj].[T] WHERE [ID] = @ID
644
+ * ```
645
+ *
646
+ * Types come from what the shape guarantees: the `__mj_*` timestamps are TIMESTAMPTZ, and every
647
+ * other projected column is a primary-key column, which the procedure takes as a parameter of the
648
+ * same name. Returns null when the body is not this shape or any column's type can't be resolved,
649
+ * so the caller falls back to its older handling rather than emitting a guessed type.
650
+ */
651
+ baseTableProjectionColumns(body, paramsBlock) {
652
+ if (!/@@ROWCOUNT/i.test(body))
653
+ return null;
654
+ const select = body.match(/\bSELECT\s+((?:\[\w+\]\s*,\s*)*\[\w+\])\s+FROM\s+\[?__mj\]?\.\[?(?!vw)\w+\]?\s+WHERE\s+(?!1\s*=\s*0)/i);
655
+ if (!select)
656
+ return null;
657
+ const names = [...select[1].matchAll(/\[(\w+)\]/g)].map((m) => m[1]);
658
+ // The CodeGen signature: it always returns the row's new __mj_UpdatedAt. Requiring it keeps a
659
+ // hand-written procedure that happens to select from a table out of this path.
660
+ if (!names.some((n) => /^__mj_UpdatedAt$/i.test(n)))
661
+ return null;
662
+ const params = splitParams(paramsBlock);
663
+ const columns = [];
664
+ for (const name of names) {
665
+ const type = this.projectedColumnType(name, params);
666
+ if (!type)
667
+ return null;
668
+ columns.push({ Name: name, Type: type });
669
+ }
670
+ return columns;
671
+ }
672
+ /** The PG type of one projected column, or null when neither rule in {@link baseTableProjectionColumns} applies. */
673
+ projectedColumnType(name, params) {
674
+ if (/^__mj_(?:CreatedAt|UpdatedAt)$/i.test(name))
675
+ return 'TIMESTAMPTZ';
676
+ const param = params
677
+ .map((p) => p.trim().match(/^@(\w+)\s+([\w]+(?:\s*\(\s*(?:\d+|MAX)\s*(?:,\s*\d+\s*)?\))?)/i))
678
+ .find((m) => m !== null && m[1].toLowerCase() === name.toLowerCase());
679
+ return param ? this.mapType(param[2]) : null;
680
+ }
607
681
  /**
608
682
  * Infer the PG column type for a scalar `SELECT <expr> AS Alias` result set.
609
683
  * `@@ROWCOUNT`, integer literals, and NULL default to INTEGER (the row-count case);
@@ -665,6 +739,27 @@ function convertQualifiedBooleanComparisons(sql, tableColumns) {
665
739
  function hasOutputParams(paramsBlock) {
666
740
  return splitParams(paramsBlock).some(isOutputParam);
667
741
  }
742
+ /**
743
+ * Splits one T-SQL parameter declaration (`@Name type [= default] [OUTPUT|OUT]`) into its name,
744
+ * type and default. Returns null when it is not one: no `@name`, a type with characters other than
745
+ * word characters, parentheses, commas and whitespace, or an `=` with nothing after it. Parsed by
746
+ * hand rather than with one regex, whose overlapping whitespace quantifiers backtrack polynomially.
747
+ */
748
+ function parseProcParam(param) {
749
+ const head = /^@(\w+)\s/.exec(param);
750
+ if (!head)
751
+ return null;
752
+ let rest = param.slice(head[0].length).trim();
753
+ const output = /\s(?:OUTPUT|OUT)$/i.exec(rest);
754
+ if (output)
755
+ rest = rest.slice(0, output.index).trimEnd();
756
+ const eq = rest.indexOf('=');
757
+ const type = (eq === -1 ? rest : rest.slice(0, eq)).trim();
758
+ const defaultValue = eq === -1 ? null : rest.slice(eq + 1).trim();
759
+ if (!type || !/^[\w(),\s]+$/.test(type) || defaultValue === '')
760
+ return null;
761
+ return { Name: head[1], Type: type, Default: defaultValue };
762
+ }
668
763
  /** True when a T-SQL parameter declaration ends with the OUTPUT or OUT keyword. */
669
764
  function isOutputParam(param) {
670
765
  const words = param.trim().split(/\s+/);
@@ -1115,6 +1210,54 @@ function convertBeginTryCatch(sql) {
1115
1210
  sql = sql.replace(/\bEND\s+CATCH\b/gi, 'END');
1116
1211
  return sql;
1117
1212
  }
1213
+ /**
1214
+ * Find the row-returning SELECT of a single-write CRUD rowcount block — the ELSE branch's
1215
+ * `SELECT "ID", "__mj_CreatedAt", "__mj_UpdatedAt" FROM __mj."T" WHERE "ID" = p_ID`, after identifier
1216
+ * and parameter conversion. The `WHERE 1=0` / `TOP 0` branch is skipped: plpgsql returns an empty
1217
+ * set by simply not returning rows.
1218
+ *
1219
+ * @param blockLines - The lines after the `-- Check if the ... was successful` comment.
1220
+ * @returns The statement (no trailing semicolon) and its line index, or null for any other shape.
1221
+ */
1222
+ function findBaseTableReturnSelect(blockLines) {
1223
+ const pattern = /^\s*(SELECT\s+(?:"\w+"\s*,\s*)*"\w+"\s+FROM\s+__mj\."(?!vw)\w+"\s+WHERE\s+(?!1\s*=\s*0\b)[^;]+?)\s*;?\s*$/i;
1224
+ for (let k = 0; k < blockLines.length; k++) {
1225
+ const match = blockLines[k].match(pattern);
1226
+ if (match && /"__mj_UpdatedAt"/i.test(match[1]))
1227
+ return { Select: match[1], Index: k };
1228
+ }
1229
+ return null;
1230
+ }
1231
+ /**
1232
+ * True when the lines before `returnIndex` are exactly an unbraced `IF`'s empty-result branch and its
1233
+ * `ELSE`: one `SELECT … WHERE 1=0` line, then `ELSE`, with only comments and blank lines between.
1234
+ * Anything else (a `BEGIN`, a second statement) means the block is not the CRUD shape.
1235
+ */
1236
+ function isUnbracedEmptyResultIfElse(lines, returnIndex) {
1237
+ const code = lines
1238
+ .slice(0, returnIndex)
1239
+ .map((l) => l.trim())
1240
+ .filter((l) => l !== '' && !l.startsWith('--'));
1241
+ return code.length === 2 && /^SELECT\b.*\bWHERE\s+1\s*=\s*0\s*;?$/i.test(code[0]) && /^ELSE$/i.test(code[1]);
1242
+ }
1243
+ /**
1244
+ * The plpgsql for a CRUD rowcount block, matching what native PostgreSQL CodeGen emits: return nothing
1245
+ * when no row changed, otherwise the changed row.
1246
+ *
1247
+ * @param select - The row-returning SELECT from {@link findBaseTableReturnSelect}.
1248
+ * @returns The replacement lines.
1249
+ */
1250
+ export function BuildRowcountReturnBlock(select) {
1251
+ return [
1252
+ ' GET DIAGNOSTICS _v_row_count = ROW_COUNT;',
1253
+ '',
1254
+ ' IF _v_row_count = 0 THEN',
1255
+ ' RETURN;',
1256
+ ' END IF;',
1257
+ '',
1258
+ ` RETURN QUERY ${select};`,
1259
+ ];
1260
+ }
1118
1261
  /**
1119
1262
  * Convert the MJ CRUD rowcount check pattern to proper plpgsql.
1120
1263
  * Uses a line-based parser to handle varied whitespace/formatting.
@@ -1128,6 +1271,18 @@ function convertRowcountIfBlock(sql) {
1128
1271
  const stripped = lines[i].trim();
1129
1272
  // Detect: -- Check if the update/delete/insert was successful
1130
1273
  const checkMatch = stripped.match(/^--\s*Check if the (update|delete|insert|create) was successful/i);
1274
+ // The single-write spUpdate written by hand, WITHOUT CodeGen's marker comment (V202611140845
1275
+ // restored one that way): its SELECTs name base-table columns. The view-returning and delete
1276
+ // shapes of the uncommented block are tryConvertUncommentedRowcountIf's, below.
1277
+ if (!checkMatch && /^IF\s+_v_row_count\s*=\s*0$/i.test(stripped)) {
1278
+ const rest = lines.slice(i + 1);
1279
+ const found = findBaseTableReturnSelect(rest);
1280
+ if (found && isUnbracedEmptyResultIfElse(rest, found.Index)) {
1281
+ result.push(...BuildRowcountReturnBlock(found.Select));
1282
+ i = i + 1 + found.Index + 1;
1283
+ continue;
1284
+ }
1285
+ }
1131
1286
  if (checkMatch) {
1132
1287
  const opType = checkMatch[1].toLowerCase();
1133
1288
  // Collect the entire IF/ELSE block
@@ -1145,6 +1300,7 @@ function convertRowcountIfBlock(sql) {
1145
1300
  const blockText = blockLines.join('\n');
1146
1301
  const viewMatch = blockText.match(/FROM\s+(__mj\."(vw\w+)")/i);
1147
1302
  const viewRef = viewMatch ? viewMatch[1] : null;
1303
+ const baseReturn = opType !== 'delete' && !viewRef ? findBaseTableReturnSelect(blockLines) : null;
1148
1304
  if (opType === 'delete') {
1149
1305
  // Delete pattern: SELECT NULL/p_ID AS "ID"
1150
1306
  const idMatch = blockText.match(/SELECT\s+(p_\w+)\s+AS/i);
@@ -1167,6 +1323,14 @@ function convertRowcountIfBlock(sql) {
1167
1323
  result.push(` RETURN QUERY SELECT * FROM ${viewRef} WHERE "ID" = p_ID;`);
1168
1324
  result.push(' END IF;');
1169
1325
  }
1326
+ else if (baseReturn) {
1327
+ // Single-write spUpdate (MJ 6.3): an unbraced IF/ELSE whose SELECTs read named columns from
1328
+ // the base table. It has no END of its own, so consume only through the returning SELECT
1329
+ // and let any following lines be processed normally.
1330
+ result.push(...BuildRowcountReturnBlock(baseReturn.Select));
1331
+ i = i + 1 + baseReturn.Index + 1;
1332
+ continue;
1333
+ }
1170
1334
  else {
1171
1335
  // Unknown pattern, keep as-is with GET DIAGNOSTICS
1172
1336
  result.push(' GET DIAGNOSTICS _v_row_count = ROW_COUNT;');
@@ -1177,6 +1341,17 @@ function convertRowcountIfBlock(sql) {
1177
1341
  }
1178
1342
  i = j + 1;
1179
1343
  }
1344
+ else if (/^IF\s+_v_row_count\s*=\s*0\s*$/i.test(stripped)) {
1345
+ const converted = tryConvertUncommentedRowcountIf(lines, i, result);
1346
+ if (converted) {
1347
+ result.push(...converted.replacement);
1348
+ i = converted.nextIdx;
1349
+ }
1350
+ else {
1351
+ result.push(lines[i]);
1352
+ i++;
1353
+ }
1354
+ }
1180
1355
  else {
1181
1356
  result.push(lines[i]);
1182
1357
  i++;
@@ -1184,6 +1359,144 @@ function convertRowcountIfBlock(sql) {
1184
1359
  }
1185
1360
  return result.join('\n');
1186
1361
  }
1362
+ /**
1363
+ * Ensure the last non-empty, non-comment line in `result` ends with a semicolon
1364
+ * before emitting an `IF NOT FOUND THEN` block.
1365
+ */
1366
+ function ensureTrailingSemicolon(result) {
1367
+ for (let k = result.length - 1; k >= 0; k--) {
1368
+ const trimmed = result[k].trim();
1369
+ if (!trimmed || trimmed.startsWith('--'))
1370
+ continue;
1371
+ if (!trimmed.endsWith(';') && !/^(?:BEGIN|THEN|ELSE|LOOP)$/i.test(trimmed)) {
1372
+ result[k] = result[k].trimEnd() + ';';
1373
+ }
1374
+ break;
1375
+ }
1376
+ }
1377
+ /**
1378
+ * Collect a single branch (either a `BEGIN ... END` block or a single SQL statement)
1379
+ * starting at `startIdx`, stopping at `ELSE` when `stopAtElse` is true.
1380
+ */
1381
+ function collectRowcountBranch(lines, startIdx, stopAtElse) {
1382
+ let j = startIdx;
1383
+ while (j < lines.length && (!lines[j].trim() || lines[j].trim().startsWith('--'))) {
1384
+ j++;
1385
+ }
1386
+ if (j >= lines.length)
1387
+ return null;
1388
+ const first = lines[j].trim();
1389
+ const branchLines = [];
1390
+ if (/^BEGIN\b/i.test(first)) {
1391
+ let depth = 1;
1392
+ j++;
1393
+ while (j < lines.length && depth > 0) {
1394
+ const s = lines[j].trim();
1395
+ if (/^BEGIN\b/i.test(s))
1396
+ depth++;
1397
+ else if (/^END\b/i.test(s)) {
1398
+ depth--;
1399
+ if (depth === 0) {
1400
+ j++;
1401
+ break;
1402
+ }
1403
+ }
1404
+ if (s && !s.startsWith('--'))
1405
+ branchLines.push(s);
1406
+ j++;
1407
+ }
1408
+ if (depth !== 0)
1409
+ return null;
1410
+ if (stopAtElse) {
1411
+ let k = j;
1412
+ while (k < lines.length && (!lines[k].trim() || lines[k].trim().startsWith('--'))) {
1413
+ k++;
1414
+ }
1415
+ if (k < lines.length && /^ELSE\b/i.test(lines[k].trim())) {
1416
+ return { stmtText: branchLines.join(' ').trim(), nextIdx: k + 1, hitElse: true };
1417
+ }
1418
+ }
1419
+ return { stmtText: branchLines.join(' ').trim(), nextIdx: j, hitElse: false };
1420
+ }
1421
+ // Single-statement branch (no BEGIN/END)
1422
+ while (j < lines.length) {
1423
+ const s = lines[j].trim();
1424
+ if (!s) {
1425
+ if (branchLines.length > 0 && !stopAtElse)
1426
+ break;
1427
+ j++;
1428
+ continue;
1429
+ }
1430
+ if (s.startsWith('--')) {
1431
+ j++;
1432
+ continue;
1433
+ }
1434
+ if (stopAtElse && /^ELSE\b/i.test(s)) {
1435
+ return { stmtText: branchLines.join(' ').trim(), nextIdx: j + 1, hitElse: true };
1436
+ }
1437
+ if (/^(?:END|IF|RETURN|GRANT|REVOKE|GO)\b/i.test(s)) {
1438
+ break;
1439
+ }
1440
+ if (branchLines.length > 0 && !/^(?:FROM|WHERE|JOIN|LEFT|RIGHT|INNER|OUTER|CROSS|ORDER|GROUP|HAVING|LIMIT|AND|OR|"[^"]+"\s*=)/i.test(s)) {
1441
+ break;
1442
+ }
1443
+ branchLines.push(s);
1444
+ j++;
1445
+ }
1446
+ return branchLines.length > 0
1447
+ ? { stmtText: branchLines.join(' ').trim(), nextIdx: j, hitElse: false }
1448
+ : null;
1449
+ }
1450
+ /**
1451
+ * Convert an uncommented T-SQL `IF @@ROWCOUNT = 0 ... ELSE ...` CRUD check
1452
+ * (already rewritten to `IF _v_row_count = 0`) into PL/pgSQL `IF NOT FOUND THEN ... END IF;`.
1453
+ */
1454
+ function tryConvertUncommentedRowcountIf(lines, startIdx, result) {
1455
+ const indent = lines[startIdx].match(/^(\s*)/)?.[1] ?? ' ';
1456
+ const ifBranch = collectRowcountBranch(lines, startIdx + 1, true);
1457
+ if (!ifBranch || !ifBranch.hitElse)
1458
+ return null;
1459
+ const elseBranch = collectRowcountBranch(lines, ifBranch.nextIdx, false);
1460
+ if (!elseBranch)
1461
+ return null;
1462
+ const ifStmt = ifBranch.stmtText.replace(/;\s*$/, '').trim();
1463
+ const elseStmt = elseBranch.stmtText.replace(/;\s*$/, '').trim();
1464
+ // Pattern 1: Update/Create CRUD returning SETOF view
1465
+ // IF @@ROWCOUNT = 0 SELECT TOP 0 * FROM __mj."vwX" WHERE 1=0 ELSE SELECT * FROM __mj."vwX" WHERE ...
1466
+ const emptyViewMatch = ifStmt.match(/^SELECT\s+(?:TOP\s+0\s+)?\*\s+FROM\s+((?:\w+\.)?"vw\w+")\s+WHERE\s+1\s*=\s*0$/i);
1467
+ const fullSelectMatch = elseStmt.match(/^(SELECT\s+\*\s+FROM\s+(?:\w+\.)?"vw\w+"\s+WHERE\s+[\s\S]+)$/i);
1468
+ if (emptyViewMatch && fullSelectMatch && !/\bTOP\b/i.test(elseStmt)) {
1469
+ ensureTrailingSemicolon(result);
1470
+ return {
1471
+ replacement: [
1472
+ `${indent}IF NOT FOUND THEN`,
1473
+ `${indent} RETURN;`,
1474
+ `${indent}ELSE`,
1475
+ `${indent} RETURN QUERY ${fullSelectMatch[1].trim()};`,
1476
+ `${indent}END IF;`,
1477
+ ],
1478
+ nextIdx: elseBranch.nextIdx,
1479
+ };
1480
+ }
1481
+ // Pattern 2: Delete CRUD returning _result_id UUID
1482
+ // IF @@ROWCOUNT = 0 SELECT NULL AS "ID" ELSE SELECT p_ID AS "ID"
1483
+ const nullIdMatch = ifStmt.match(/^SELECT\s+NULL\s+AS\s+"?(\w+)"?$/i);
1484
+ const varIdMatch = elseStmt.match(/^SELECT\s+(p_\w+)\s+AS\s+"?(\w+)"?$/i);
1485
+ if (nullIdMatch && varIdMatch) {
1486
+ ensureTrailingSemicolon(result);
1487
+ return {
1488
+ replacement: [
1489
+ `${indent}IF NOT FOUND THEN`,
1490
+ `${indent} RETURN QUERY SELECT NULL::UUID AS "_result_id";`,
1491
+ `${indent}ELSE`,
1492
+ `${indent} RETURN QUERY SELECT ${varIdMatch[1]}::UUID AS "_result_id";`,
1493
+ `${indent}END IF;`,
1494
+ ],
1495
+ nextIdx: elseBranch.nextIdx,
1496
+ };
1497
+ }
1498
+ return null;
1499
+ }
1187
1500
  /**
1188
1501
  * Fix multi-line RETURN QUERY SELECT that got split across lines.
1189
1502
  * Ported from Python fix_crud_if_else_pattern().