@memberjunction/sqlglot-ts 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memberjunction/sqlglot-ts",
3
- "version": "6.3.0-edge.1",
3
+ "version": "6.3.0-edge.3",
4
4
  "description": "TypeScript wrapper for Python's sqlglot SQL transpiler. Manages a local Python FastAPI microservice to provide deterministic SQL dialect conversion.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -44,6 +44,10 @@ FLYWAY_MACRO = "${flyway:defaultSchema}"
44
44
  FLYWAY_SENTINEL = "__mj_flyway_default_schema__"
45
45
 
46
46
 
47
+ # The stock PostgreSQL DATEDIFF generator, kept for units other than day.
48
+ _PG_DATEDIFF_SQL = Postgres.Generator.TRANSFORMS[exp.DateDiff]
49
+
50
+
47
51
  class MJPostgres(Postgres):
48
52
  """PostgreSQL generation with MJ's type/function/boolean conventions baked in."""
49
53
 
@@ -54,6 +58,15 @@ class MJPostgres(Postgres):
54
58
  # JSON_EXTRACT_PATH_TEXT needs a json arg, but MJ stores JSON in text
55
59
  # columns; cast to jsonb and use ->> (single key) / #>> (nested).
56
60
  exp.JSONExtractScalar: lambda self, e: _json_extract_scalar_sql(self, e),
61
+ # SS DATEDIFF(day, s, e) counts date boundaries crossed; the stock PG form is epoch
62
+ # arithmetic over timestamps (fractional days truncated), which disagrees with SS
63
+ # across midnight. Subtracting dates matches SS and the legacy converter (#6348).
64
+ exp.DateDiff: lambda self, e: _datediff_sql(self, e),
65
+ # SS HASHBYTES('SHA2_256'|'SHA2_512', x) parses to SHA2. PG's sha256/sha512 take
66
+ # bytea, so the text argument is encoded first (#6538 item 3).
67
+ exp.SHA2: lambda self, e: _sha2_sql(self, e),
68
+ # SS HASHBYTES('MD5', x) parses to MD5 and returns bytes; PG md5() returns hex text.
69
+ exp.MD5: lambda self, e: f"DECODE(MD5({self.sql(e, 'this')}), 'hex')",
57
70
  }
58
71
  TYPE_MAPPING = {
59
72
  **Postgres.Generator.TYPE_MAPPING,
@@ -93,6 +106,33 @@ class MJPostgres(Postgres):
93
106
  return f"{self.dialect.QUOTE_START}{self.escape_str(restored)}{self.dialect.QUOTE_END}"
94
107
  return super().literal_sql(expression)
95
108
 
109
+ def anonymous_sql(self, expression: exp.Anonymous) -> str:
110
+ # A user function keeps its written name. The stock generator upper-cases an
111
+ # unqualified unknown function (`fnBusinessToday()` → `FNBUSINESSTODAY()`), which
112
+ # PostgreSQL folds to `fnbusinesstoday` and cannot find. A mixed-case name is emitted
113
+ # quoted, the way CodeGen creates it (#6348).
114
+ name = expression.name or ""
115
+ if name and name != name.upper() and name != name.lower():
116
+ quoted = self.sql(exp.to_identifier(name, quoted=True))
117
+ return f"{quoted}({self.format_args(*expression.expressions)})"
118
+ return super().anonymous_sql(expression)
119
+
120
+ def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
121
+ # A SQL Server unique index treats NULLs as equal; PostgreSQL's default does not, so a
122
+ # converted unique index would accept duplicates the source refuses. Every converted
123
+ # unique index keeps SQL Server semantics with NULLS NOT DISTINCT (PG 15+, #5194).
124
+ sql = super().indexparameters_sql(expression)
125
+ if not _is_unique_index_params(expression):
126
+ return sql
127
+ columns = self.expressions(expression, key="columns", flat=True)
128
+ include = self.expressions(expression, key="include", flat=True)
129
+ anchor = f"({columns})" + (f" INCLUDE ({include})" if include else "")
130
+ pos = sql.find(anchor)
131
+ if pos < 0:
132
+ return sql
133
+ end = pos + len(anchor)
134
+ return f"{sql[:end]} NULLS NOT DISTINCT{sql[end:]}"
135
+
96
136
  def datatype_sql(self, expression: exp.DataType) -> str:
97
137
  has_max = any(
98
138
  isinstance(e, exp.DataTypeParam) and isinstance(e.this, exp.Var) and e.name.upper() == "MAX"
@@ -174,6 +214,84 @@ def _json_extract_scalar_sql(self, expression: exp.JSONExtractScalar) -> str:
174
214
  return f"(({this})::jsonb ->> '{key}')"
175
215
 
176
216
 
217
+ def _unwrap_time_str(x: exp.Expression) -> exp.Expression:
218
+ """The T-SQL reader wraps DATEDIFF arguments in TimeStrToTime; the date cast replaces it."""
219
+ return x.this if isinstance(x, exp.TimeStrToTime) else x
220
+
221
+
222
+ def _datediff_sql(self, expression: exp.DateDiff) -> str:
223
+ """`DATEDIFF(day, s, e)` → `(CAST(e AS DATE) - CAST(s AS DATE))`; other units unchanged."""
224
+ unit = (expression.text("unit") or "").upper()
225
+ if unit not in ("DAY", "DD", "D"):
226
+ return _PG_DATEDIFF_SQL(self, expression)
227
+ end = self.sql(_unwrap_time_str(expression.this))
228
+ start = self.sql(_unwrap_time_str(expression.expression))
229
+ return f"(CAST({end} AS DATE) - CAST({start} AS DATE))"
230
+
231
+
232
+ def _sha2_sql(self, expression: exp.SHA2) -> str:
233
+ """SHA2(x, 256|512) → `SHA256|SHA512(CONVERT_TO(x, 'UTF8'))`."""
234
+ length = expression.text("length") or "256"
235
+ fn = "SHA512" if length == "512" else "SHA256"
236
+ return f"{fn}(CONVERT_TO({self.sql(expression, 'this')}, 'UTF8'))"
237
+
238
+
239
+ def _is_unique_index_params(params: exp.IndexParameters) -> bool:
240
+ """True when these index parameters belong to a `CREATE UNIQUE INDEX`."""
241
+ index = params.parent
242
+ if not isinstance(index, exp.Index):
243
+ return False
244
+ if index.args.get("unique"):
245
+ return True
246
+ create = index.parent
247
+ return isinstance(create, exp.Create) and bool(create.args.get("unique"))
248
+
249
+
250
+ # Nodes that produce binary (varbinary) values: HASHBYTES parses to these, and an explicit cast.
251
+ def _is_binary_expr(x: exp.Expression) -> bool:
252
+ x = _unwrap_paren(x)
253
+ if isinstance(x, (exp.SHA2, exp.MD5, exp.SHA)):
254
+ return True
255
+ if isinstance(x, exp.Cast) and x.to is not None and x.to.this in (exp.DataType.Type.VARBINARY, exp.DataType.Type.BINARY):
256
+ return True
257
+ return False
258
+
259
+
260
+ def _convert_style(node: exp.Convert) -> str | None:
261
+ style = node.args.get("style")
262
+ return style.name if isinstance(style, exp.Literal) else None
263
+
264
+
265
+ def _rewrite_binary_convert(node: exp.Expression) -> exp.Expression:
266
+ """SS `CONVERT(VARCHAR(n), <binary>, 2)` → `UPPER(ENCODE(<binary>, 'hex'))`; style 1 adds the
267
+ `0x` prefix. The stock generator reads the style as a DATE format (`TO_CHAR(…, 'YY.MM.DD')`),
268
+ which is wrong for a binary argument (#6538 item 3). Other styles are reported upstream."""
269
+ if not isinstance(node, exp.Convert) or not _is_binary_expr(node.expression):
270
+ return node
271
+ style = _convert_style(node)
272
+ if style not in ("1", "2"):
273
+ return node
274
+ hexed = exp.Upper(this=exp.func("ENCODE", node.expression.copy(), exp.Literal.string("hex")))
275
+ if style == "1":
276
+ hexed = exp.DPipe(this=exp.Literal.string("0x"), expression=hexed)
277
+ return exp.Cast(this=hexed, to=node.this.copy()) if isinstance(node.this, exp.DataType) else hexed
278
+
279
+
280
+ def _unsupported_binary_convert(stmt: exp.Expression) -> bool:
281
+ """A CONVERT of a binary value with a style other than 1/2 has no mechanical PG form."""
282
+ for c in stmt.find_all(exp.Convert):
283
+ if _is_binary_expr(c.expression) and _convert_style(c) not in (None, "1", "2"):
284
+ return True
285
+ return False
286
+
287
+
288
+ def _unique_constraints_nulls_not_distinct(node: exp.Expression) -> exp.Expression:
289
+ """Table-level / ALTER ADD `UNIQUE` constraints keep SQL Server NULL semantics (#5194)."""
290
+ if isinstance(node, exp.UniqueColumnConstraint):
291
+ node.set("nulls", True)
292
+ return node
293
+
294
+
177
295
  def _rewrite_insert_booleans(node: exp.Expression) -> exp.Expression:
178
296
  """In `INSERT INTO t (…cols…) VALUES (…)`, coerce 1/0 → TRUE/FALSE for any column
179
297
  known to be BIT/BOOLEAN (file-level + MJ_EXTRA_BIT_COLS registry). SS seeds bit
@@ -247,11 +365,10 @@ _UPDATE_FROM_KEY = "from_" if "from_" in exp.Update.arg_types else "from"
247
365
 
248
366
 
249
367
  def _update_alias_outer_join(stmt: exp.Update) -> bool:
250
- """True when the self-aliased `UPDATE alias … FROM Target AS alias JOIN …` shape uses
251
- a LEFT/RIGHT/FULL join. `_rewrite_update_from_alias` moves join ON conditions into
252
- WHERE, which is only sound for INNER joins — an outer-join anti-join (`LEFT JOIN o …
253
- WHERE o.ID IS NULL`) would silently become inner-join semantics and update zero rows.
254
- There is no safe mechanical PG rewrite, so these are reported as unhandled instead."""
368
+ """True when the self-aliased `UPDATE alias … FROM Target AS alias JOIN …` shape uses an
369
+ outer join that `_rewrite_update_outer_join` cannot rewrite (RIGHT/FULL/explicit OUTER).
370
+ `_rewrite_update_from_alias` moves join ON conditions into WHERE, which is only sound for
371
+ INNER joins, and the ctid self-join rewrite covers LEFT joins; anything else is reported."""
255
372
  frm = stmt.args.get(_UPDATE_FROM_KEY)
256
373
  tgt = stmt.this
257
374
  if not frm or not isinstance(frm.this, exp.Table) or not isinstance(tgt, exp.Table):
@@ -260,7 +377,65 @@ def _update_alias_outer_join(stmt: exp.Update) -> bool:
260
377
  joins = base.args.get("joins") or []
261
378
  if not base.alias or tgt.name != base.alias or not joins:
262
379
  return False
263
- return any(_is_outer_join(j) for j in joins)
380
+ return any(_is_outer_join(j) for j in joins) and not _left_joins_only(joins)
381
+
382
+
383
+ def _left_joins_only(joins: list) -> bool:
384
+ """True when every outer join is a plain LEFT [OUTER] join (inner joins may sit beside them)."""
385
+ for j in joins:
386
+ side = (j.side or "").upper()
387
+ if side in ("RIGHT", "FULL"):
388
+ return False
389
+ if (j.kind or "").upper() == "OUTER" and side != "LEFT":
390
+ return False
391
+ return True
392
+
393
+
394
+ def _rewrite_update_outer_join(node: exp.Expression) -> exp.Expression:
395
+ """SS `UPDATE a SET a.c = … FROM T AS a LEFT JOIN o ON j WHERE w`
396
+ → PG `UPDATE T AS a SET c = … FROM T AS a_mj LEFT JOIN o ON j' WHERE a.ctid = a_mj.ctid AND w`.
397
+
398
+ PostgreSQL cannot name the target in FROM, and a join ON clause in FROM cannot reference the
399
+ target. Joining a second copy of the target and pinning it to the updated row by `ctid` keeps
400
+ the outer join's semantics (an anti-join `WHERE o.ID IS NULL` still matches the rows it did on
401
+ SQL Server); references to the alias inside the joins move to the copy (#6538 item 2)."""
402
+ if not isinstance(node, exp.Update):
403
+ return node
404
+ frm = node.args.get(_UPDATE_FROM_KEY)
405
+ tgt = node.this
406
+ if not frm or not isinstance(frm.this, exp.Table) or not isinstance(tgt, exp.Table):
407
+ return node
408
+ base = frm.this
409
+ alias = base.alias
410
+ joins = base.args.get("joins") or []
411
+ if not alias or tgt.name != alias or not joins:
412
+ return node
413
+ if not any(_is_outer_join(j) for j in joins) or not _left_joins_only(joins):
414
+ return node
415
+ self_alias = f"{alias}_mj"
416
+ new_target = base.copy()
417
+ new_target.set("joins", None)
418
+ node.set("this", new_target)
419
+ copy_src = base.copy()
420
+ copy_src.set("joins", None)
421
+ copy_src.set("alias", exp.TableAlias(this=exp.to_identifier(self_alias)))
422
+ new_joins = []
423
+ for j in joins:
424
+ jc = j.copy()
425
+ for col in jc.find_all(exp.Column):
426
+ if col.table == alias:
427
+ col.set("table", exp.to_identifier(self_alias))
428
+ new_joins.append(jc)
429
+ copy_src.set("joins", new_joins)
430
+ node.set(_UPDATE_FROM_KEY, exp.From(this=copy_src))
431
+ pin = exp.EQ(this=exp.column("ctid", table=alias), expression=exp.column("ctid", table=self_alias))
432
+ existing = node.args["where"].this if node.args.get("where") else None
433
+ node.set("where", exp.Where(this=exp.And(this=pin, expression=existing) if existing is not None else pin))
434
+ for assign in node.expressions:
435
+ lhs = assign.this if isinstance(assign, exp.EQ) else None
436
+ if isinstance(lhs, exp.Column) and lhs.table == alias:
437
+ lhs.set("table", None)
438
+ return node
264
439
 
265
440
 
266
441
  def _rewrite_update_from_alias(node: exp.Expression) -> exp.Expression:
@@ -1255,6 +1430,154 @@ _ALTER_COLUMN = _re.compile(
1255
1430
  )
1256
1431
 
1257
1432
 
1433
+ # T-SQL `DROP INDEX [IF EXISTS] name ON table` (issue #5955). PostgreSQL has no `ON` clause: an
1434
+ # index lives in its table's schema and is dropped by schema-qualified name. sqlglot 27.x cannot
1435
+ # parse the T-SQL form (a parse-error gap) and 30.x passes it through as invalid PG; both now get
1436
+ # the PG form. One index per statement — a comma list falls through to the existing gap.
1437
+ _DROP_INDEX = _re.compile(
1438
+ r"^\s*DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?(?P<name>\[[^\]]+\]|\"[^\"]+\"|\w+)\s+ON\s+(?P<tbl>[^,;]+?)\s*;?\s*$",
1439
+ _re.IGNORECASE | _re.DOTALL,
1440
+ )
1441
+
1442
+
1443
+ def _transpile_drop_index(txt: str) -> str | None:
1444
+ """`DROP INDEX ix ON s.t` → `DROP INDEX IF EXISTS "s"."ix"`. Returns None for any other shape."""
1445
+ m = _DROP_INDEX.match(_strip_leading_sql_comments(txt))
1446
+ if not m:
1447
+ return None
1448
+ schema_toks = _IDENT_TOKEN.findall(m.group("tbl"))[:-1]
1449
+ prefix = "".join(_ident_token_to_pg(t) + "." for t in schema_toks)
1450
+ name = m.group("name").strip('[]"')
1451
+ return f'DROP INDEX IF EXISTS {prefix}"{name}"'
1452
+
1453
+
1454
+ # CodeGen's core metadata-refresh procs, which an Open App migration calls in its hand region
1455
+ # (issue #5919). PostgreSQL has these functions (CodeGen's support objects or the core
1456
+ # migrations), but with positional, differently named parameters, and the forms the core
1457
+ # migrations install take only an EXCLUDED-schemas list.
1458
+ # Of these, only spUpdateExistingEntityFieldsFromSchema and spDeleteUnneededEntityFields take an
1459
+ # entity-ID list, as their second parameter in every installed form (`p_entityids`).
1460
+ _CORE_REFRESH_PROCS = {
1461
+ "spupdateexistingentitiesfromschema": "spUpdateExistingEntitiesFromSchema",
1462
+ "spupdateexistingentityfieldsfromschema": "spUpdateExistingEntityFieldsFromSchema",
1463
+ "spsetdefaultcolumnwidthwhereneeded": "spSetDefaultColumnWidthWhereNeeded",
1464
+ "spupdateschemainfofromdatabase": "spUpdateSchemaInfoFromDatabase",
1465
+ "spdeleteunneededentityfields": "spDeleteUnneededEntityFields",
1466
+ }
1467
+ _CORE_REFRESH_PROCS_WITH_ENTITY_IDS = {"spUpdateExistingEntityFieldsFromSchema", "spDeleteUnneededEntityFields"}
1468
+ _CORE_EXEC = _re.compile(
1469
+ r"^\s*EXEC(?:UTE)?\s+(?P<schema>\[[^\]]+\]|\"[^\"]+\"|\$\{[\w:]+\}|" + _re.escape(FLYWAY_SENTINEL) + r"|\w+)\s*\.\s*"
1470
+ r"(?P<proc>\[[^\]]+\]|\"[^\"]+\"|\w+)(?P<args>(?:\s+[\s\S]*?)?)\s*;?\s*$",
1471
+ _re.IGNORECASE,
1472
+ )
1473
+ _NAMED_ARG = _re.compile(r"^\s*@(?P<name>\w+)\s*=\s*(?P<value>N?'(?:[^']|'')*'|NULL)\s*$", _re.IGNORECASE)
1474
+
1475
+
1476
+ def _core_schema_ref(tok: str) -> str:
1477
+ """Schema token of a core EXEC → PG: a `${…}` placeholder stays bare (substituted later)."""
1478
+ name = tok.strip().strip('[]"')
1479
+ if name == FLYWAY_SENTINEL:
1480
+ return FLYWAY_MACRO
1481
+ if name.startswith("${"):
1482
+ return name
1483
+ return f'"{name}"'
1484
+
1485
+
1486
+ def _split_exec_args(args: str) -> list[str] | None:
1487
+ """Split `@a='x', @b=N'y'` at top-level commas (outside string literals); None if unbalanced."""
1488
+ parts, cur, in_str = [], "", False
1489
+ for ch in args:
1490
+ if ch == "'":
1491
+ in_str = not in_str
1492
+ if ch == "," and not in_str:
1493
+ parts.append(cur)
1494
+ cur = ""
1495
+ else:
1496
+ cur += ch
1497
+ if in_str:
1498
+ return None
1499
+ if cur.strip():
1500
+ parts.append(cur)
1501
+ return parts
1502
+
1503
+
1504
+ def _transpile_core_refresh_exec(txt: str) -> str | None:
1505
+ """`EXEC <core>.spUpdateExistingEntitiesFromSchema @ExcludedSchemaNames='…'[, @IncludedSchemaNames='…'][, @EntityIDs='…']`
1506
+ (and the other refresh procs in _CORE_REFRESH_PROCS) → a PG call (issue #5919).
1507
+
1508
+ The PG functions are called positionally: first the excluded-schemas list, the one parameter
1509
+ every installed form has, then `@EntityIDs` for the two procs that take it. Dropping
1510
+ `@EntityIDs` would widen the call from the named entities to every entity in the schemas,
1511
+ which for spDeleteUnneededEntityFields deletes more than the source asked. `@IncludedSchemaNames`
1512
+ has no PG counterpart in the installed forms, so the call runs in a DO block that excludes, at
1513
+ apply time, every schema not named in the included list (decision pg.2). Returns None when this
1514
+ is not such a call, an argument is not understood, or `@EntityIDs` is given to a proc that has
1515
+ no such parameter; the caller then reports it.
1516
+ """
1517
+ m = _CORE_EXEC.match(_strip_leading_sql_comments(txt))
1518
+ if not m:
1519
+ return None
1520
+ proc = _CORE_REFRESH_PROCS.get(m.group("proc").strip('[]"').lower())
1521
+ if proc is None:
1522
+ return None
1523
+ raw_args = _split_exec_args(m.group("args") or "")
1524
+ if raw_args is None:
1525
+ return None
1526
+ named: dict[str, str | None] = {}
1527
+ for raw in raw_args:
1528
+ a = _NAMED_ARG.match(raw)
1529
+ if not a:
1530
+ return None
1531
+ key = a.group("name").lower()
1532
+ if key not in ("excludedschemanames", "includedschemanames", "entityids"):
1533
+ return None
1534
+ val = a.group("value")
1535
+ named[key] = None if val.upper() == "NULL" else _unquote_tsql_string(val)
1536
+ target = f'{_core_schema_ref(m.group("schema"))}."{proc}"'
1537
+ excluded = named.get("excludedschemanames")
1538
+ included = named.get("includedschemanames")
1539
+ extra = ""
1540
+ if named.get("entityids") is not None:
1541
+ if proc not in _CORE_REFRESH_PROCS_WITH_ENTITY_IDS:
1542
+ return None
1543
+ extra = ", " + _pg_string(named["entityids"])
1544
+ if not included:
1545
+ arg = "NULL" if excluded is None else _pg_string(excluded)
1546
+ return f"SELECT {target}({arg}{extra})"
1547
+ given = "''" if excluded is None else _pg_string(excluded)
1548
+ return (
1549
+ "DO $mj_refresh$\n"
1550
+ "DECLARE v_excluded TEXT;\n"
1551
+ "BEGIN\n"
1552
+ " -- T-SQL passed an included-schemas list; the PG function takes only an excluded list, so\n"
1553
+ " -- exclude every schema not in the included list, plus the excluded list as given.\n"
1554
+ " SELECT concat_ws(',', NULLIF(" + given + ", ''), string_agg(nspname, ','))\n"
1555
+ " INTO v_excluded\n"
1556
+ " FROM pg_namespace\n"
1557
+ " WHERE lower(nspname) <> ALL (string_to_array(lower(replace(" + _pg_string(included) + ", ' ', '')), ','));\n"
1558
+ f" PERFORM {target}(v_excluded{extra});\n"
1559
+ "END $mj_refresh$"
1560
+ )
1561
+
1562
+
1563
+ # `EXEC sp_refreshview '<schema>.<view>'` — CodeGen writes one after every column change to a view's
1564
+ # table. PostgreSQL has no equivalent (a view's column list is fixed at CREATE), so the converter
1565
+ # cannot carry it: it is reported as a named warning so the view is rebuilt by hand (issue #5649,
1566
+ # decision pg.5), not dropped without a trace.
1567
+ _SP_REFRESHVIEW = _re.compile(
1568
+ r"^\s*EXEC(?:UTE)?\s+(?:\[?sys\]?\.)?\[?sp_refreshview\]?\s+(?:@viewname\s*=\s*)?N?'(?P<view>[^']+)'\s*;?\s*$",
1569
+ _re.IGNORECASE,
1570
+ )
1571
+
1572
+
1573
+ def _refreshview_target(txt: str) -> str | None:
1574
+ """The view named by `EXEC sp_refreshview '<view>'`, or None for any other statement."""
1575
+ m = _SP_REFRESHVIEW.match(_strip_leading_sql_comments(txt))
1576
+ if not m:
1577
+ return None
1578
+ return m.group("view").replace(FLYWAY_SENTINEL, FLYWAY_MACRO)
1579
+
1580
+
1258
1581
  def _transpile_alter_column(txt: str) -> str | None:
1259
1582
  """`ALTER TABLE t ALTER COLUMN c <type> [NOT NULL|NULL]` → PG TYPE change + nullability.
1260
1583
  Returns None if txt isn't an ALTER COLUMN (or its type can't be parsed)."""
@@ -1286,6 +1609,23 @@ def _transpile_alter_column(txt: str) -> str | None:
1286
1609
  return _drop_dependent_views_block(bare_tbl, col) + "\n" + f'ALTER TABLE {tbl_ref} ' + ", ".join(actions)
1287
1610
 
1288
1611
 
1612
+ def _drop_column_prelude(stmt: exp.Expression) -> str:
1613
+ """For `ALTER TABLE t DROP COLUMN c`, the block that drops views depending on t.c first.
1614
+ PostgreSQL refuses to drop a column a view reads (SQL Server drops it and leaves the view
1615
+ stale); CodeGen regenerates the dropped views (#3345 item 3). Empty for any other statement."""
1616
+ if not isinstance(stmt, exp.Alter):
1617
+ return ""
1618
+ tbl = stmt.this
1619
+ if not isinstance(tbl, exp.Table):
1620
+ return ""
1621
+ blocks = [
1622
+ _drop_dependent_views_block(tbl.name, a.this.name)
1623
+ for a in (stmt.args.get("actions") or [])
1624
+ if isinstance(a, exp.Drop) and (a.args.get("kind") or "").upper() == "COLUMN" and a.this is not None
1625
+ ]
1626
+ return "\n".join(blocks)
1627
+
1628
+
1289
1629
  def _drop_dependent_views_block(table: str, col: str) -> str:
1290
1630
  """DO block that drops every view depending on <table>.<col> (CodeGen regenerates them).
1291
1631
  Deterministic and a no-op when nothing depends on the column."""
@@ -1445,6 +1785,45 @@ def _parse_resilient(protected: str) -> list[tuple[exp.Expression | None, str]]:
1445
1785
  _WITH_CHECK_ADD = _re.compile(r"\bWITH\s+(?:NOCHECK|CHECK)\s+(?=ADD\b)", _re.IGNORECASE)
1446
1786
 
1447
1787
 
1788
+ def _delete_cte_target(stmt: exp.Delete) -> exp.CTE | None:
1789
+ """The CTE a `WITH c AS (…) DELETE FROM c …` deletes through, or None for a plain DELETE."""
1790
+ target = stmt.this
1791
+ with_ = stmt.args.get("with")
1792
+ if not isinstance(target, exp.Table) or target.args.get("db") or with_ is None:
1793
+ return None
1794
+ for cte in with_.expressions:
1795
+ if (cte.alias or "").lower() == (target.name or "").lower():
1796
+ return cte
1797
+ return None
1798
+
1799
+
1800
+ def _rewrite_delete_from_cte(stmt: exp.Delete, cte: exp.CTE) -> exp.Delete | None:
1801
+ """T-SQL deletes base-table rows through a single-table CTE (the ROW_NUMBER dedup idiom);
1802
+ PostgreSQL cannot DELETE FROM a CTE (issue #3166). Carry each row's `ctid` out of the CTE
1803
+ and delete from the base table by it:
1804
+ WITH c AS (SELECT ctid AS mj_ctid, … FROM t …) DELETE FROM t WHERE ctid IN (SELECT mj_ctid FROM c WHERE p)
1805
+ Returns None for any CTE whose rows do not map one-to-one onto one table (a join, several
1806
+ FROM tables, DISTINCT, GROUP BY, a set operation); the caller reports those as a gap."""
1807
+ sel = cte.this
1808
+ if not isinstance(sel, exp.Select) or sel.args.get("joins") or sel.args.get("distinct") or sel.args.get("group"):
1809
+ return None
1810
+ from_ = sel.args.get("from")
1811
+ base = from_.this if from_ is not None else None
1812
+ if not isinstance(base, exp.Table) or len(from_.expressions or []) > 0:
1813
+ return None
1814
+ qualifier = base.alias or None
1815
+ sel.select(exp.alias_(exp.column("ctid", table=qualifier), "mj_ctid"), copy=False)
1816
+ inner = exp.select("mj_ctid").from_(exp.to_table(cte.alias))
1817
+ where = stmt.args.get("where")
1818
+ if where is not None:
1819
+ inner = inner.where(where.this)
1820
+ target = base.copy()
1821
+ target.set("alias", None)
1822
+ stmt.set("this", target)
1823
+ stmt.set("where", exp.Where(this=exp.In(this=exp.column("ctid"), query=exp.Subquery(this=inner))))
1824
+ return stmt
1825
+
1826
+
1448
1827
  def _has_computed_column(stmt: exp.Expression) -> bool:
1449
1828
  """True if `stmt` declares a computed/generated column (T-SQL `col AS (expr) [PERSISTED]`).
1450
1829
  Such columns cannot be transpiled mechanically: sqlglot emits `GENERATED ALWAYS AS (...)
@@ -1493,6 +1872,10 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1493
1872
  dropped.append({"kind": "ROUTINE-END", "snippet": tail[:80]})
1494
1873
  continue
1495
1874
  if stmt is None:
1875
+ di = _transpile_drop_index(raw)
1876
+ if di is not None:
1877
+ out.append(di)
1878
+ continue
1496
1879
  unhandled.append({"kind": "parse-error", "snippet": raw.strip()[:80]})
1497
1880
  continue
1498
1881
  # A T-SQL `IF …` statement that the IF-EXISTS envelope did NOT capture (e.g. a
@@ -1566,6 +1949,11 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1566
1949
  txt = stmt.sql(dialect="tsql")
1567
1950
  unhandled.append({"kind": "UPDATE-OUTER-JOIN", "snippet": txt[:80]})
1568
1951
  continue
1952
+ # CONVERT of a binary value (HASHBYTES, a VARBINARY cast) with a style other than 1/2:
1953
+ # no mechanical PG form, and the stock output reads the style as a date format.
1954
+ if _unsupported_binary_convert(stmt):
1955
+ unhandled.append({"kind": "CONVERT-BINARY-STYLE", "snippet": stmt.sql(dialect="tsql")[:80]})
1956
+ continue
1569
1957
  # T-SQL `DELETE TOP (n) FROM t` misparses on BOTH versions into a spurious multi-table
1570
1958
  # DELETE (`DELETE "TOP" AS _t0(n) FROM t`) — invalid PG with no mechanical rewrite (PG
1571
1959
  # would need a ctid/CTE form). The signature is a DELETE carrying a `tables` list (PG puts
@@ -1575,6 +1963,15 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1575
1963
  for t in (stmt.args.get("tables") or [])):
1576
1964
  unhandled.append({"kind": "DELETE-TOP", "snippet": stmt.sql(dialect="tsql")[:80]})
1577
1965
  continue
1966
+ # `WITH c AS (…) DELETE FROM c` — PG cannot delete through a CTE. Rewrite the single-table
1967
+ # form to a ctid delete on the base table; report any other shape (issue #3166).
1968
+ if isinstance(stmt, exp.Delete):
1969
+ cte = _delete_cte_target(stmt)
1970
+ if cte is not None:
1971
+ txt = stmt.sql(dialect="tsql")
1972
+ if _rewrite_delete_from_cte(stmt, cte) is None:
1973
+ unhandled.append({"kind": "DELETE-FROM-CTE", "snippet": txt[:80]})
1974
+ continue
1578
1975
  # Computed/generated columns (`col AS (expr) [PERSISTED]`) can't be transpiled — report
1579
1976
  # (would emit a type-less `GENERATED ALWAYS AS (...) STORED`; see _has_computed_column).
1580
1977
  # Only CREATE/ALTER declare columns — gate on type so the subtree walk skips the huge
@@ -1597,6 +1994,18 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1597
1994
  if ac is not None:
1598
1995
  out.append(ac)
1599
1996
  continue
1997
+ di = _transpile_drop_index(txt)
1998
+ if di is not None:
1999
+ out.append(di)
2000
+ continue
2001
+ cr = _transpile_core_refresh_exec(txt)
2002
+ if cr is not None:
2003
+ out.append(cr)
2004
+ continue
2005
+ rv = _refreshview_target(txt)
2006
+ if rv is not None:
2007
+ dropped.append({"kind": "SP-REFRESHVIEW", "snippet": rv})
2008
+ continue
1600
2009
  # SQL Server batch-control noise — not needed on PG, drop silently.
1601
2010
  if _re.match(r"^\s*(BEGIN\s+TRY|END\s+TRY|BEGIN\s+CATCH|END\s+CATCH|SET\s+NOEXEC|GO)\b", txt, _re.IGNORECASE):
1602
2011
  dropped.append({"kind": "BATCH-CONTROL", "snippet": txt[:80]})
@@ -1648,6 +2057,12 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1648
2057
  elif dk == "TRIGGER":
1649
2058
  unhandled.append({"kind": "DROP-TRIGGER", "snippet": stmt.sql(dialect="tsql")[:80]})
1650
2059
  continue
2060
+ elif dk == "INDEX":
2061
+ # 30.x parses the T-SQL `DROP INDEX ix ON t` and would emit it unchanged.
2062
+ di = _transpile_drop_index(raw or stmt.sql(dialect="tsql"))
2063
+ if di is not None:
2064
+ out.append(di)
2065
+ continue
1651
2066
  if isinstance(stmt, exp.Create) and (stmt.args.get("kind") or "").upper() in (
1652
2067
  "NONCLUSTERED INDEX", "CLUSTERED INDEX"):
1653
2068
  stmt.set("kind", "INDEX") # PG has no CLUSTERED/NONCLUSTERED qualifier
@@ -1659,7 +2074,10 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1659
2074
  # parsed `stmt` is used once here and discarded, so in-place mutation is safe, and the
1660
2075
  # pass ordering is unchanged: each pass still sees the prior pass's edits.
1661
2076
  stmt = (
1662
- stmt.transform(_rewrite_update_from_alias, copy=False) # restructures UPDATE before other rewrites
2077
+ stmt.transform(_rewrite_update_outer_join, copy=False) # LEFT-join self-aliased UPDATE → ctid self-join
2078
+ .transform(_rewrite_update_from_alias, copy=False) # restructures UPDATE before other rewrites
2079
+ .transform(_rewrite_binary_convert, copy=False) # CONVERT(VARCHAR, <binary>, 1|2) → hex text
2080
+ .transform(_unique_constraints_nulls_not_distinct, copy=False) # SS NULL semantics on UNIQUE
1663
2081
  .transform(_rewrite_insert_booleans, copy=False) # seed-INSERT 1/0 → TRUE/FALSE for bit cols
1664
2082
  .transform(_fix_misparsed_table_constraint, copy=False)
1665
2083
  .transform(_rewrite_functions, copy=False)
@@ -1706,7 +2124,8 @@ def _transpile_plain(sql: str, pretty: bool = False) -> tuple[str, list[dict], l
1706
2124
  txt = stmt.sql(dialect="tsql")
1707
2125
  unhandled.append({"kind": "EMPTY-EMISSION", "snippet": txt[:80]})
1708
2126
  continue
1709
- out.append(rendered)
2127
+ prelude = _drop_column_prelude(stmt)
2128
+ out.append(f"{prelude}\n{rendered}" if prelude else rendered)
1710
2129
  # SOFT reconciliation (issue #3252 1d): every parsed statement must land in exactly one
1711
2130
  # bucket. A mismatch means a drop site was missed — surface it as a gap so it is loud and
1712
2131
  # gets artifacts, but NEVER raise (a raise would abort the whole conversion run with zero
@@ -448,12 +448,71 @@ check("guarded INSERT + extprop in one IF body → DO block with INSERT and COMM
448
448
  must_not_contain=["sp_addextendedproperty"])
449
449
 
450
450
  # --- UPDATE…FROM join semantics ------------------------------------------------
451
- check("UPDATE…FROM LEFT JOIN anti-join → unhandled (inner-join rewrite would update 0 rows)",
451
+ check("UPDATE…FROM LEFT JOIN anti-join → ctid self-join keeps outer-join semantics (#6538 item 2)",
452
452
  "UPDATE t SET t.Flag = 1 FROM ${flyway:defaultSchema}.Target AS t "
453
453
  "LEFT JOIN ${flyway:defaultSchema}.Other o ON o.TargetID = t.ID WHERE o.ID IS NULL;",
454
+ must_contain=['UPDATE ${flyway:defaultSchema}."Target" AS "t" SET "Flag" = 1',
455
+ 'FROM ${flyway:defaultSchema}."Target" AS "t_mj"',
456
+ 'LEFT JOIN ${flyway:defaultSchema}."Other" AS "o"',
457
+ 'ON "o"."TargetID" = "t_mj"."ID"',
458
+ '"t"."ctid" = "t_mj"."ctid" AND "o"."ID" IS NULL'],
459
+ expect_unhandled=0)
460
+ check("UPDATE…FROM RIGHT JOIN on a self-aliased target stays a reported gap",
461
+ "UPDATE t SET t.Flag = o.F FROM ${flyway:defaultSchema}.Target AS t "
462
+ "RIGHT JOIN ${flyway:defaultSchema}.Other o ON o.TargetID = t.ID;",
454
463
  must_not_contain=["UPDATE"],
455
464
  expect_unhandled=1)
456
465
 
466
+ # --- #6348 / #6538 item 3: DATEDIFF(day), user function names, HASHBYTES + CONVERT style --------
467
+ check("DATEDIFF(day, s, e) → date subtraction, not epoch arithmetic",
468
+ "SELECT DATEDIFF(day, c.StartDate, c.EndDate) AS Days FROM ${flyway:defaultSchema}.Contract c;",
469
+ must_contain=['(CAST("c"."EndDate" AS DATE) - CAST("c"."StartDate" AS DATE))'],
470
+ must_not_contain=["epoch"])
471
+ check("DATEDIFF(hour, …) keeps the epoch form",
472
+ "SELECT DATEDIFF(hour, c.StartDate, c.EndDate) AS H FROM ${flyway:defaultSchema}.Contract c;",
473
+ must_contain=["epoch", "/ 3600"])
474
+ check("a mixed-case user function keeps its name, quoted",
475
+ "SELECT ${flyway:defaultSchema}.fnBusinessToday() AS a, fnBusinessToday() AS b FROM ${flyway:defaultSchema}.T;",
476
+ must_contain=['${flyway:defaultSchema}."fnBusinessToday"()', '"fnBusinessToday"() AS "b"'],
477
+ must_not_contain=["FNBUSINESSTODAY"])
478
+ check("HASHBYTES SHA2_256 + CONVERT style 2 → upper hex of sha256 over UTF-8 bytes",
479
+ "SELECT CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', t.Body), 2) AS H FROM ${flyway:defaultSchema}.T t;",
480
+ must_contain=["UPPER(ENCODE(SHA256(CONVERT_TO(\"t\".\"Body\", 'UTF8')), 'hex'))"],
481
+ must_not_contain=["TO_CHAR", "YY.MM.DD"])
482
+ check("HASHBYTES SHA2_512 + CONVERT style 1 → 0x-prefixed upper hex",
483
+ "SELECT CONVERT(VARCHAR(130), HASHBYTES('SHA2_512', t.Body), 1) AS H FROM ${flyway:defaultSchema}.T t;",
484
+ must_contain=["'0x' || UPPER(ENCODE(SHA512(CONVERT_TO("],
485
+ must_not_contain=["TO_CHAR"])
486
+ check("HASHBYTES MD5 → bytea of md5",
487
+ "SELECT HASHBYTES('MD5', t.Body) AS H FROM ${flyway:defaultSchema}.T t;",
488
+ must_contain=["DECODE(MD5(\"t\".\"Body\"), 'hex')"])
489
+ check("CONVERT of a binary value with another style stays a reported gap",
490
+ "SELECT CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', t.Body), 0) AS H FROM ${flyway:defaultSchema}.T t;",
491
+ expect_unhandled=1)
492
+ check("CONVERT style 1 on a non-binary value keeps the date format",
493
+ "SELECT CONVERT(VARCHAR(20), t.D, 1) AS X FROM ${flyway:defaultSchema}.T t;",
494
+ must_contain=["TO_CHAR"])
495
+
496
+ # --- #5194: unique indexes and constraints keep SQL Server NULL semantics ------------------------
497
+ check("CREATE UNIQUE INDEX gets NULLS NOT DISTINCT before WHERE",
498
+ "CREATE UNIQUE INDEX UQ_T_A ON ${flyway:defaultSchema}.T (A, B) INCLUDE (C) WHERE A IS NOT NULL;",
499
+ must_contain=['("A", "B") INCLUDE ("C") NULLS NOT DISTINCT WHERE'])
500
+ check("a non-unique index is unchanged",
501
+ "CREATE INDEX IX_T_A ON ${flyway:defaultSchema}.T (A);",
502
+ must_not_contain=["NULLS NOT DISTINCT"])
503
+
504
+ # --- #3345 item 3: DROP COLUMN drops dependent views first ---------------------------------------
505
+ check("ALTER TABLE … DROP COLUMN is preceded by the dependent-view drop block",
506
+ "ALTER TABLE ${flyway:defaultSchema}.T DROP COLUMN OldCol;",
507
+ must_contain=["DO $$", "WHERE tc.relname = 'T' AND a.attname = 'OldCol'",
508
+ 'ALTER TABLE ${flyway:defaultSchema}."T" DROP COLUMN "OldCol"'])
509
+
510
+ # --- #4385: CodeGen's apply-time EntityField Sequence expression survives conversion --------------
511
+ check("EntityField INSERT keeps the COALESCE(MAX(Sequence), 0) + 1 expression",
512
+ "INSERT INTO ${flyway:defaultSchema}.EntityField (ID, EntityID, Name, Sequence) "
513
+ "SELECT 'f1', 'e1', 'Col', COALESCE(MAX(Sequence), 0) + 1 FROM ${flyway:defaultSchema}.EntityField WHERE EntityID = 'e1';",
514
+ must_contain=['COALESCE(MAX("Sequence"), 0) + 1'])
515
+
457
516
  check("UPDATE…FROM with two INNER joins: extra join's ON moves to WHERE once (not duplicated)",
458
517
  "UPDATE uv SET uv.X = b.Y FROM ${flyway:defaultSchema}.UserView AS uv "
459
518
  "INNER JOIN ${flyway:defaultSchema}.A a ON a.ID = uv.AID "
@@ -536,6 +595,43 @@ check("TINYINT → SMALLINT in CREATE TABLE, ADD COLUMN and CAST",
536
595
  must_contain=['"Flags" SMALLINT NOT NULL', 'ADD COLUMN "Level" SMALLINT NULL', 'CAST(1 AS SMALLINT)'],
537
596
  must_not_contain=["TINYINT"])
538
597
 
598
+ # --- DROP INDEX … ON table (issues #5955, #3166) -----------------------------------
599
+ # PostgreSQL has no `DROP INDEX … ON <table>`; the index is dropped by schema-qualified name.
600
+ check("DROP INDEX [ix] ON [schema].[table] → DROP INDEX IF EXISTS schema.ix",
601
+ "DROP INDEX [IX_Foo_Name] ON [${flyway:defaultSchema}].[Foo];",
602
+ must_contain=['DROP INDEX IF EXISTS ${flyway:defaultSchema}."IX_Foo_Name"'],
603
+ must_not_contain=[" ON "])
604
+ check("DROP INDEX IF EXISTS ix ON schema.table → PG form",
605
+ "DROP INDEX IF EXISTS IX_Foo_Name ON __mj.Foo;",
606
+ must_contain=['DROP INDEX IF EXISTS "__mj"."IX_Foo_Name"'],
607
+ must_not_contain=[" ON "])
608
+ check("guarded DROP INDEX (sys.indexes probe) → pg_indexes probe + PG drop",
609
+ "IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_Foo_Name' "
610
+ "AND object_id = OBJECT_ID('[${flyway:defaultSchema}].[Foo]'))\n"
611
+ "BEGIN\n DROP INDEX [IX_Foo_Name] ON [${flyway:defaultSchema}].[Foo];\nEND",
612
+ must_contain=["pg_indexes", 'DROP INDEX IF EXISTS ${flyway:defaultSchema}."IX_Foo_Name"'],
613
+ must_not_contain=[" ON ${flyway"])
614
+
615
+ # --- DELETE through a CTE (issue #3166) -------------------------------------------
616
+ # PG cannot DELETE FROM a CTE. The single-table ROW_NUMBER dedup form deletes from the base
617
+ # table by ctid; a CTE over a join has no one-to-one row mapping and is reported.
618
+ check("WITH c AS (… ROW_NUMBER …) DELETE FROM c → ctid delete on the base table",
619
+ ";WITH d AS (SELECT ID, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY ID) AS rn "
620
+ "FROM [${flyway:defaultSchema}].[Foo]) DELETE FROM d WHERE rn > 1;",
621
+ must_contain=['"ctid" AS "mj_ctid"', 'DELETE FROM ${flyway:defaultSchema}."Foo"',
622
+ '"ctid" IN (SELECT "mj_ctid" FROM "d" WHERE "rn" > 1)'],
623
+ must_not_contain=['DELETE FROM "d"'])
624
+ check("aliased CTE source qualifies ctid with the alias",
625
+ "WITH d AS (SELECT f.ID, ROW_NUMBER() OVER (PARTITION BY f.Name ORDER BY f.ID) AS rn "
626
+ "FROM [__mj].[Foo] f) DELETE FROM d WHERE rn > 1;",
627
+ must_contain=['"f"."ctid" AS "mj_ctid"', 'DELETE FROM "__mj"."Foo"'])
628
+ check("DELETE FROM a CTE over a join → DELETE-FROM-CTE gap",
629
+ "WITH d AS (SELECT f.ID FROM __mj.Foo f JOIN __mj.Bar b ON b.ID = f.BarID) DELETE FROM d;",
630
+ expect_unhandled=1)
631
+ check("a plain DELETE that only reads a CTE is unchanged",
632
+ "WITH d AS (SELECT ID FROM __mj.Bar) DELETE FROM __mj.Foo WHERE ID IN (SELECT ID FROM d);",
633
+ must_contain=['DELETE FROM "__mj"."Foo"'], must_not_contain=["ctid"])
634
+
539
635
  # --- BIT registry survives a poison statement in the same batch -------------------
540
636
  check("poison statement doesn't wipe BIT registration for other tables in its batch",
541
637
  "SELECT FROM FROM;\n"
@@ -892,12 +988,12 @@ check("PK NONCLUSTERED in ALTER ADD folds to plain PRIMARY KEY (valid PG)",
892
988
  expect_unhandled=0)
893
989
  check("UNIQUE CLUSTERED in CREATE TABLE folds to plain UNIQUE (valid PG)",
894
990
  "CREATE TABLE ${flyway:defaultSchema}.T (ID UNIQUEIDENTIFIER NOT NULL, CONSTRAINT UQ_T UNIQUE CLUSTERED (ID));",
895
- must_contain=['UNIQUE ("ID")'],
991
+ must_contain=['UNIQUE NULLS NOT DISTINCT ("ID")'],
896
992
  must_not_contain=['CLUSTERED'],
897
993
  expect_unhandled=0)
898
994
  check("UNIQUE CLUSTERED in ALTER ADD folds to plain UNIQUE (valid PG)",
899
995
  "ALTER TABLE ${flyway:defaultSchema}.T ADD CONSTRAINT UQ_T UNIQUE CLUSTERED (ID);",
900
- must_contain=['UNIQUE ("ID")'],
996
+ must_contain=['UNIQUE NULLS NOT DISTINCT ("ID")'],
901
997
  must_not_contain=['CLUSTERED'],
902
998
  expect_unhandled=0)
903
999
 
@@ -1155,6 +1251,46 @@ def check_exp_attribute_references():
1155
1251
  print(f"ok exp.* attribute references exist in the running sqlglot ({len(referenced)} names checked)")
1156
1252
 
1157
1253
 
1254
+ # --- Core metadata-refresh EXECs in a hand region (issue #5919, decision pg.2) ----------------
1255
+ for _proc in ("spUpdateExistingEntitiesFromSchema", "spUpdateExistingEntityFieldsFromSchema",
1256
+ "spSetDefaultColumnWidthWhereNeeded", "spUpdateSchemaInfoFromDatabase",
1257
+ "spDeleteUnneededEntityFields"):
1258
+ check(f"EXEC [core].[{_proc}] @ExcludedSchemaNames → SELECT core.{_proc}(excluded)",
1259
+ f"EXEC [${{mjSchema}}].[{_proc}] @ExcludedSchemaNames='sys,staging';",
1260
+ must_contain=[f'SELECT ${{mjSchema}}."{_proc}"(\'sys,staging\')'])
1261
+ check(f"EXEC core.{_proc} bare, with @IncludedSchemaNames → DO block excluding the rest",
1262
+ f"EXEC ${{mjSchema}}.{_proc} @ExcludedSchemaNames=N'sys,staging', @IncludedSchemaNames=N'${{flyway:defaultSchema}}';",
1263
+ must_contain=["DO $mj_refresh$",
1264
+ "NULLIF('sys,staging', '')",
1265
+ "string_to_array(lower(replace('${flyway:defaultSchema}', ' ', '')), ',')",
1266
+ f'PERFORM ${{mjSchema}}."{_proc}"(v_excluded);'],
1267
+ must_not_contain=["EXEC", "@IncludedSchemaNames"])
1268
+ for _proc in ("spUpdateExistingEntityFieldsFromSchema", "spDeleteUnneededEntityFields"):
1269
+ check(f"core refresh EXEC passes @EntityIDs to {_proc} as its second argument",
1270
+ f"EXEC [${{mjSchema}}].[{_proc}] @ExcludedSchemaNames='sys', @EntityIDs='a,b';",
1271
+ must_contain=[f'SELECT ${{mjSchema}}."{_proc}"(\'sys\', \'a,b\')'])
1272
+ check("core refresh EXEC with @EntityIDs and @IncludedSchemaNames passes both through the DO block",
1273
+ "EXEC [${mjSchema}].[spDeleteUnneededEntityFields] @ExcludedSchemaNames='sys', @IncludedSchemaNames='app', @EntityIDs='a,b';",
1274
+ must_contain=["DO $mj_refresh$", 'PERFORM ${mjSchema}."spDeleteUnneededEntityFields"(v_excluded, \'a,b\');'])
1275
+ check("core refresh EXEC with @EntityIDs on a proc that has no such parameter stays a reported gap",
1276
+ "EXEC [${mjSchema}].[spUpdateExistingEntitiesFromSchema] @ExcludedSchemaNames='sys', @EntityIDs='a,b';",
1277
+ expect_unhandled=1)
1278
+ check("core refresh EXEC with an unknown argument stays a reported gap",
1279
+ "EXEC [${mjSchema}].[spUpdateExistingEntitiesFromSchema] @Mode='x';",
1280
+ expect_unhandled=1)
1281
+ check("a non-refresh core EXEC is still a reported gap",
1282
+ "EXEC [${mjSchema}].[spDoSomethingElse] @ExcludedSchemaNames='x';",
1283
+ expect_unhandled=1)
1284
+
1285
+ # --- sp_refreshview (issue #5649, decision pg.5): accounted as dropped, never emitted -----------
1286
+ _rv = mj_transpile("EXEC sp_refreshview '${flyway:defaultSchema}.vwFoo';")
1287
+ if _rv["sql"] or _rv["unhandled"] or [d["kind"] for d in _rv["dropped"]] != ["SP-REFRESHVIEW"] \
1288
+ or _rv["dropped"][0]["snippet"] != "${flyway:defaultSchema}.vwFoo":
1289
+ _failures += 1
1290
+ print(f"FAIL sp_refreshview is accounted as an SP-REFRESHVIEW drop naming the view: {_rv}")
1291
+ else:
1292
+ print("ok sp_refreshview is accounted as an SP-REFRESHVIEW drop naming the view")
1293
+
1158
1294
  check_exp_attribute_references()
1159
1295
 
1160
1296