@memberjunction/sql-converter 5.41.0 → 5.42.0

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.
@@ -0,0 +1,364 @@
1
+ /**
2
+ * MigrationConverter — the split-and-regenerate conversion of a single SQL Server
3
+ * migration into its PostgreSQL `.pg.sql` counterpart.
4
+ *
5
+ * See `plans/pg-migration-architecture/SPLIT_AND_REGENERATE_PROPOSAL.md`.
6
+ *
7
+ * It does NOT try to translate everything. Content is routed by which generator
8
+ * produced it:
9
+ * - Category A (CodeGen objects) → DROPPED; regenerated natively by `mj codegen` on PG.
10
+ * - Category M (mj-sync metadata) → DROPPED; re-seeded by `mj sync push` on PG.
11
+ * - Category B (regular hand DDL/DML) → transpiled via the AST dialect (sqlglot `mj_postgres.py`).
12
+ * - Category C (hand-written procedural SQL) → schema DDL still transpiled; the
13
+ * procedural routines are surfaced as NEEDS-HAND-AUTHORING gaps.
14
+ *
15
+ * The contract of this module is **nothing is dropped silently**: every statement
16
+ * either (a) lands in the transpiled output, (b) is dropped because a generator
17
+ * reproduces it natively on PG (counted + named in `notes`/`droppedObjects`), or
18
+ * (c) is surfaced as a gap (`unhandled` / `handProcedural`, embedded as comments in
19
+ * the output). Gap consumers — a human build engineer or an LLM last-mile pass —
20
+ * work from those artifacts.
21
+ *
22
+ * Classification (TypeScript, this file + MigrationSplitter/MigrationStatementSplitter)
23
+ * is deliberately separated from transpilation (the Python AST dialect), bridged by
24
+ * the `TSQLToPGTranspiler` interface so classification stays unit-testable without
25
+ * a Python runtime.
26
+ */
27
+ import { splitMigration } from './MigrationSplitter.js';
28
+ import { splitByStatement } from './MigrationStatementSplitter.js';
29
+ /** Statement kinds that survive statement-mode classification and flow to the transpiler. */
30
+ const STATEMENT_MODE_KEEP = new Set([
31
+ 'schema-ddl',
32
+ 'comment',
33
+ 'role-setup',
34
+ // Unclassifiable batches are NEVER silently dropped — the AST transpiler either
35
+ // emits them or reports them in `unhandled`.
36
+ 'unknown',
37
+ // Hand routines stay in the stream too: the dialect transpiles any plain DDL around
38
+ // them and routes the routine bodies to `unhandled`, while we flag the file.
39
+ 'hand-procedural',
40
+ ]);
41
+ /** Classify a migration and return the kept T-SQL to transpile — the single classification entry point. */
42
+ export function extractKeptTSQL(sql, fileName) {
43
+ const split = splitMigration(sql, fileName);
44
+ const droppedCodeGenLines = split.codeGenBlock ? split.codeGenBlock.split('\n').length : 0;
45
+ // Baselines and old-style migrations have NO banner but DO contain generated
46
+ // objects (squashed snapshots). Banner-based splitting can't separate them — use
47
+ // statement-level classification instead.
48
+ const stmts = splitByStatement(sql);
49
+ const isUnbanneredSnapshot = split.boundaryMethod === 'no-codegen-block' && stmts.some((s) => s.kind === 'codegen-object');
50
+ if (isUnbanneredSnapshot) {
51
+ return classifyStatementMode(split, stmts, droppedCodeGenLines);
52
+ }
53
+ return classifyBannerMode(split, droppedCodeGenLines);
54
+ }
55
+ /** Banner-split path: feature migrations with (or without) a CodeGen block. */
56
+ function classifyBannerMode(split, droppedCodeGenLines) {
57
+ const has = (k) => split.handAuthoredRegions.some((r) => r.kind === k);
58
+ const handProcedural = split.routing === 'needs-hand-authoring'
59
+ ? split.handAuthoredRegions
60
+ .filter((r) => r.kind === 'hand-procedural')
61
+ .map((r) => `${r.evidence}@${r.line}`)
62
+ : [];
63
+ // Transpile when there is real schema DDL, data DML that isn't an mj-sync seed, or
64
+ // hand-procedural content (whose surrounding DDL must still be emitted — the dialect
65
+ // routes the routine bodies themselves to `unhandled`).
66
+ const translatable = handProcedural.length > 0 || has('schema-ddl') || (has('data-dml') && !has('metadata-sync'));
67
+ // Recover entity-REGISTRATION INSERTs from the dropped CodeGen block. On SQL Server,
68
+ // CodeGen's schema-introspection sprocs (spUpdateExistingEntitiesFromSchema, …) recreate
69
+ // these rows from the live schema, so dropping them is safe. PostgreSQL has no such
70
+ // sprocs (they're T-SQL-only), so a new entity's registration rows have NO other source:
71
+ // dropping them leaves the entity absent from metadata and `mj codegen` then emits no
72
+ // view/sproc for it. The AST transpiler already KEEPS these INSERTs (its _METADATA_TABLES
73
+ // matcher is disabled for exactly this reason) — but a file whose CodeGen output sits
74
+ // below an explicit `-- CODE GEN RUN` banner (e.g. KnowledgeHub) never gets them to the
75
+ // transpiler, because the splitter routes the whole post-banner block to codeGenBlock.
76
+ // Files with no banner (e.g. Magic_Link) keep these registration INSERTs inline already;
77
+ // this recovery makes the bannered case match — and applies to needs-hand files too
78
+ // (e.g. IsComputed_To_EntityField, whose registration rows sit below the banner).
79
+ const recovered = split.codeGenBlock ? recoverEntityRegistrationInserts(split.codeGenBlock) : '';
80
+ const baseTsql = translatable ? split.handAuthored : '';
81
+ const tsql = recovered ? (baseTsql ? `${baseTsql}\nGO\n${recovered}` : recovered) : baseTsql;
82
+ const notes = regenReseedNotes(split, droppedCodeGenLines);
83
+ if (recovered) {
84
+ notes.push('Recovered entity-registration INSERTs from the dropped CodeGen block (no PG-side introspection recreates them).');
85
+ }
86
+ return {
87
+ fileName: split.fileName,
88
+ status: handProcedural.length > 0 ? 'needs-hand-authoring' : tsql ? 'converted' : 'reseed-or-regen-only',
89
+ tsql,
90
+ handProcedural,
91
+ droppedObjects: [],
92
+ notes,
93
+ split,
94
+ droppedCodeGenLines,
95
+ };
96
+ }
97
+ /** Statement-mode path: unbannered snapshots (baselines) classified per GO batch. */
98
+ function classifyStatementMode(split, stmts, droppedCodeGenLines) {
99
+ // BASELINES keep their metadata DML: a baseline is the system's point-in-time
100
+ // metadata source of truth — codegen can't even boot on a fresh PG database without
101
+ // Entity/EntityField rows, and `mj sync push` only owns the curated subset. Dropping
102
+ // the seed here is what forced fresh installs to depend on an external fixture DB.
103
+ // Non-baseline unbannered files keep the drop: their seeds ARE reproduced by sync push.
104
+ const isBaseline = /^B\d/.test(split.fileName);
105
+ const kept = stmts.filter((s) => STATEMENT_MODE_KEEP.has(s.kind) || (isBaseline && s.kind === 'metadata-dml'));
106
+ const hand = stmts.filter((s) => s.kind === 'hand-procedural');
107
+ const unknown = stmts.filter((s) => s.kind === 'unknown');
108
+ const droppedRegen = stmts.filter((s) => s.kind === 'codegen-object' || s.kind === 'grant');
109
+ const droppedMeta = isBaseline ? [] : stmts.filter((s) => s.kind === 'metadata-dml');
110
+ const notes = [
111
+ `Statement-mode (unbannered snapshot): kept ${kept.length} batches ` +
112
+ `(schema DDL/comments/roles${isBaseline ? '/metadata seed' : ''}, ${unknown.length} unclassified → transpiler decides), ` +
113
+ `dropped ${droppedRegen.length} CodeGen objects/grants (regenerated by \`mj codegen\`)` +
114
+ (isBaseline ? '.' : ` and ${droppedMeta.length} metadata DML batches (re-seeded by \`mj sync push\`).`),
115
+ ];
116
+ if (hand.length > 0) {
117
+ notes.push(`⚠ ${hand.length} hand-written routine(s) need a human PG version: ` +
118
+ hand.map((h) => h.evidence).slice(0, 20).join(', '));
119
+ }
120
+ return {
121
+ fileName: split.fileName,
122
+ status: hand.length > 0 ? 'needs-hand-authoring' : 'converted',
123
+ tsql: kept.map((s) => s.sql).join('\nGO\n'),
124
+ handProcedural: hand.map((h) => h.evidence),
125
+ droppedObjects: droppedRegen.map((s) => s.evidence),
126
+ notes,
127
+ split,
128
+ droppedCodeGenLines: droppedRegen.concat(droppedMeta).reduce((n, s) => n + s.sql.split('\n').length, 0),
129
+ };
130
+ }
131
+ /**
132
+ * Convert one SQL Server migration to its PG form via split-and-regenerate.
133
+ * No file I/O — the caller decides whether/where to write `pgSQL`.
134
+ *
135
+ * Classification comes from `extractKeptTSQL` (the single source of truth);
136
+ * transpilation goes through `options.transpiler` (the AST dialect). Throws when
137
+ * kept T-SQL exists but no transpiler was provided — content is never dropped
138
+ * because a backend was missing.
139
+ */
140
+ export async function convertMigration(sql, fileName, options = {}) {
141
+ const kept = extractKeptTSQL(sql, fileName);
142
+ if (!kept.tsql.trim()) {
143
+ return {
144
+ fileName: kept.fileName,
145
+ status: kept.status,
146
+ pgSQL: regenOnlyMarker(kept),
147
+ split: kept.split,
148
+ droppedCodeGenLines: kept.droppedCodeGenLines,
149
+ unhandled: [],
150
+ handProcedural: kept.handProcedural,
151
+ droppedObjects: kept.droppedObjects,
152
+ notes: kept.notes,
153
+ };
154
+ }
155
+ if (!options.transpiler) {
156
+ throw new Error(`convertMigration: ${fileName} has kept T-SQL to translate but no transpiler was provided. ` +
157
+ 'Pass options.transpiler (e.g. MJPostgresTranspiler from @memberjunction/sqlglot-ts).');
158
+ }
159
+ const transpiled = await options.transpiler.transpile(kept.tsql);
160
+ const schema = options.schema ?? '__mj';
161
+ const pgSQL = assemblePgSQL(kept, transpiled, schema, options.includeHeader ?? true);
162
+ return {
163
+ fileName: kept.fileName,
164
+ status: kept.status,
165
+ pgSQL,
166
+ split: kept.split,
167
+ droppedCodeGenLines: kept.droppedCodeGenLines,
168
+ unhandled: transpiled.unhandled,
169
+ handProcedural: kept.handProcedural,
170
+ droppedObjects: kept.droppedObjects,
171
+ notes: kept.notes,
172
+ };
173
+ }
174
+ /** Assemble the final `.pg.sql` text: header, gap comments, transpiled body. */
175
+ function assemblePgSQL(kept, transpiled, schema, includeHeader) {
176
+ const parts = [];
177
+ if (includeHeader)
178
+ parts.push(pgHeader(kept.fileName));
179
+ const gaps = gapComments(kept.handProcedural, transpiled.unhandled);
180
+ if (gaps)
181
+ parts.push(gaps);
182
+ const body = transpiled.sql
183
+ .map((s) => (s.trim().endsWith(';') ? s : `${s};`))
184
+ .join('\n\n');
185
+ parts.push(body);
186
+ // Committed .pg.sql files use the literal schema (Flyway placeholder substitution
187
+ // is not relied on for PG). Replace both the macro and the dialect's internal
188
+ // sentinel, should it ever leak.
189
+ return parts
190
+ .join('\n\n')
191
+ .replaceAll('${flyway:defaultSchema}', schema)
192
+ .replaceAll('__mj_flyway_default_schema__', schema)
193
+ .concat('\n');
194
+ }
195
+ /** The standard committed-`.pg.sql` provenance header. */
196
+ function pgHeader(fileName) {
197
+ return [
198
+ '-- ============================================================================',
199
+ `-- MemberJunction PostgreSQL Migration — ${fileName}`,
200
+ '-- Generated by the split-and-regenerate pipeline (AST dialect transpile of',
201
+ '-- hand-written DDL; CodeGen objects regenerated natively; metadata re-seeded).',
202
+ '-- ============================================================================',
203
+ '',
204
+ 'CREATE EXTENSION IF NOT EXISTS "pgcrypto";',
205
+ 'CREATE SCHEMA IF NOT EXISTS __mj;',
206
+ 'SET search_path TO __mj, public;',
207
+ 'SET standard_conforming_strings = on;',
208
+ ].join('\n');
209
+ }
210
+ /**
211
+ * Render the gap report as SQL comments embedded at the top of the output, so a
212
+ * reviewer (human or LLM last-mile pass) sees exactly what still needs authoring.
213
+ * This is the loud counterpart to the legacy pipeline's silent drops.
214
+ */
215
+ function gapComments(handProcedural, unhandled) {
216
+ if (handProcedural.length === 0 && unhandled.length === 0)
217
+ return '';
218
+ const lines = ['-- ╔══ CONVERSION GAPS — resolve before relying on this migration ══╗'];
219
+ if (handProcedural.length > 0) {
220
+ lines.push(`-- NEEDS HAND-AUTHORING (${handProcedural.length} hand-written routine(s)):`);
221
+ for (const h of handProcedural)
222
+ lines.push(`-- • ${h}`);
223
+ lines.push('-- Author the PostgreSQL equivalent of each routine and add it below.');
224
+ }
225
+ if (unhandled.length > 0) {
226
+ lines.push(`-- UNHANDLED BY THE AST TRANSPILER (${unhandled.length} statement(s)):`);
227
+ unhandled.forEach((u, i) => {
228
+ const snippet = u.snippet.replace(/\s+/g, ' ').trim();
229
+ const truncated = snippet.length > 300 ? `${snippet.slice(0, 300)} …[truncated]` : snippet;
230
+ lines.push(`-- [${i + 1}] (${u.kind}) ${truncated}`);
231
+ });
232
+ lines.push('-- Each statement above was REPORTED, not silently dropped — port it manually.');
233
+ }
234
+ lines.push('-- ╚════════════════════════════════════════════════════════════════╝');
235
+ return lines.join('\n');
236
+ }
237
+ /**
238
+ * The CodeGen-emitted entity-registration tables. These define a new entity in MJ metadata
239
+ * and have no schema-introspection equivalent on PostgreSQL, so they must survive the split.
240
+ * Deliberately excludes base-table seed rows (e.g. the entity's own sample data) and any
241
+ * generated views/sprocs/grants — those ARE regenerated by `mj codegen` on PG.
242
+ */
243
+ const ENTITY_REGISTRATION_TABLES = [
244
+ 'Entity',
245
+ 'EntityField',
246
+ 'EntityFieldValue',
247
+ 'ApplicationEntity',
248
+ 'EntityRelationship',
249
+ 'EntityPermission',
250
+ // AdvancedGeneration field-categorization output (FieldCategoryIcons/Info) — emitted
251
+ // into the CodeGen block on SQL Server; PG codegen runs without AdvancedGeneration,
252
+ // so these rows have no other source on PG (live hit: 12 eSignature settings).
253
+ 'EntitySetting',
254
+ ];
255
+ /**
256
+ * Pull every `INSERT INTO ${flyway:defaultSchema}.<RegistrationTable> …` statement out of a
257
+ * dropped CodeGen block, in original order, and return them GO-separated for the transpiler.
258
+ */
259
+ function recoverEntityRegistrationInserts(codeGenBlock) {
260
+ const tableAlt = ENTITY_REGISTRATION_TABLES.join('|');
261
+ const qualifiedTable = String.raw `\[?\$\{flyway:defaultSchema\}\]?\s*\.\s*\[?(?:${tableAlt})\]?\b`;
262
+ // Three CodeGen shapes target a registration table:
263
+ // (a) a bare `INSERT INTO <schema>.<RegTable> …` (the Entity / ApplicationEntity rows),
264
+ // (b) an idempotent `IF NOT EXISTS (SELECT … FROM <schema>.<RegTable> …) BEGIN INSERT … END`
265
+ // guard (the EntityField / EntityFieldValue / EntityRelationship rows), and
266
+ // (c) a bare `UPDATE <schema>.<RegTable> …` — the AdvancedGeneration curation tail
267
+ // (EntityField.Category / GeneratedFormSection, Entity.Icon). These run as one
268
+ // un-GO'd batch with the EntitySetting INSERTs; PG codegen runs without
269
+ // AdvancedGeneration, so this curation has no other source on PG.
270
+ // The AST transpiler keeps all three (its metadata-drop matcher is disabled and it lowers
271
+ // the IF-EXISTS-BEGIN guard to a PG DO block), so recovering these forms is sufficient.
272
+ const headRe = new RegExp(String.raw `^\s*(?:INSERT\s+INTO\s+${qualifiedTable}` +
273
+ String.raw `|UPDATE\s+${qualifiedTable}` +
274
+ String.raw `|IF\s+(?:NOT\s+)?EXISTS\s*\([^)]*\b(?:${tableAlt})\b)`, 'i');
275
+ // Special date fields (__mj_CreatedAt / __mj_UpdatedAt) for NEW entities must also be
276
+ // recovered: CodeGen emits their ADD/backfill/DEFAULT statements in the dropped block,
277
+ // and PG codegen does NOT reliably re-add them when the recovered EntityField metadata
278
+ // already lists the fields (observed: __mj_CreatedAt added, __mj_UpdatedAt skipped on
279
+ // ClusterAnalysisCluster). Each statement carries an exact provenance comment —
280
+ // `/* SQL text to add special date field … */` — which is the recovery anchor.
281
+ // The anchor is the `/* … */` provenance comment itself, so only `--` line comments
282
+ // (e.g. the `-- CODE GEN RUN` delimiter heading the first batch) are stripped first.
283
+ const specialDateField = /^\s*\/\* SQL text to add special date field/i;
284
+ const afterLineComments = (sql) => sql.replace(/^(?:\s*--[^\n]*\n)*\s*/, '');
285
+ // Classify by our own head-regex against the comment-stripped SQL, NOT the splitter's
286
+ // `kind`: a CodeGen registration statement is preceded by `-- CODE GEN RUN` + a `/* … */`
287
+ // provenance comment, which the statement splitter doesn't strip, so it lands as 'unknown'
288
+ // rather than 'metadata-dml'. We only emit batches whose first real keyword targets a
289
+ // registration table, so misclassification upstream doesn't cause us to miss or over-keep.
290
+ // GO separators are NOT guaranteed inside a CodeGen block — real files contain long
291
+ // GO-less runs where GRANTs, registration INSERTs, and curation UPDATEs share one
292
+ // batch (live hit: eSignature's whole tail headed by a GRANT, dropping the virtual
293
+ // EntityField registrations and EntitySettings with it). CodeGen does, however,
294
+ // prefix every emitted item with a `/* … */` provenance comment at line start —
295
+ // segment on those so each item is classified independently of its batch-mates.
296
+ return splitByStatement(codeGenBlock)
297
+ .flatMap((s) => s.sql.split(/\n(?=\s*\/\*)/))
298
+ .filter((seg) => headRe.test(stripLeadingCommentsAndNoise(seg)) || specialDateField.test(afterLineComments(seg)))
299
+ .map((seg) => truncateAtGeneratedObject(seg))
300
+ .join('\nGO\n');
301
+ }
302
+ /**
303
+ * A registration GO-batch can have a generated-object section (a view/sproc regeneration)
304
+ * appended without a `GO` separator — CodeGen emits the EntityField inserts and the
305
+ * `----- BASE VIEW FOR ENTITY …` / `IF OBJECT_ID(...,'V') DROP VIEW … CREATE VIEW …` block
306
+ * back-to-back in one batch. `splitByStatement` only splits on `GO`, so the whole thing
307
+ * arrives as one statement. Keep only the registration prefix: truncate at the first
308
+ * generated-object boundary (the CodeGen ruler banner, an OBJECT_ID view-existence guard,
309
+ * or a bare DROP/CREATE VIEW/FUNCTION/PROC/TRIGGER / GRANT). Those objects are regenerated
310
+ * natively by `mj codegen` on PG, so dropping them here is exactly what we want.
311
+ */
312
+ function truncateAtGeneratedObject(batch) {
313
+ const boundary = batch.search(/(?:^|\n)\s*(?:-----+\s*BASE (?:VIEW|TABLE)\b|IF\s+OBJECT_ID\s*\(|DROP\s+VIEW\b|CREATE\s+(?:OR\s+(?:ALTER|REPLACE)\s+)?(?:VIEW|FUNCTION|PROC(?:EDURE)?|TRIGGER)\b|GRANT\b)/i);
314
+ return boundary === -1 ? batch : batch.slice(0, boundary);
315
+ }
316
+ /** Strip leading `--` / `/* … *​/` comments, PRINT, and blank lines so the first real keyword is visible. */
317
+ function stripLeadingCommentsAndNoise(batch) {
318
+ let s = batch;
319
+ let changed = true;
320
+ while (changed) {
321
+ changed = false;
322
+ const trimmed = s.replace(/^\s+/, '');
323
+ if (trimmed.startsWith('--')) {
324
+ s = trimmed.replace(/^--[^\n]*\n?/, '');
325
+ changed = true;
326
+ }
327
+ else if (trimmed.startsWith('/*')) {
328
+ const end = trimmed.indexOf('*/');
329
+ s = end === -1 ? '' : trimmed.slice(end + 2);
330
+ changed = true;
331
+ }
332
+ else if (/^PRINT\b/i.test(trimmed)) {
333
+ s = trimmed.replace(/^PRINT[^\n]*\n?/i, '');
334
+ changed = true;
335
+ }
336
+ else {
337
+ s = trimmed;
338
+ }
339
+ }
340
+ return s;
341
+ }
342
+ /** Notes describing the dropped Category-A / re-seeded Category-M content. */
343
+ function regenReseedNotes(split, droppedCodeGenLines) {
344
+ const notes = [];
345
+ if (droppedCodeGenLines > 0) {
346
+ notes.push(`Dropped ${droppedCodeGenLines} lines of CodeGen output — regenerated natively via \`mj codegen\` on PG.`);
347
+ }
348
+ if (split.handAuthoredRegions.some((r) => r.kind === 'metadata-sync')) {
349
+ notes.push('Contains mj-sync metadata — re-seeded via `mj sync push` against PG.');
350
+ }
351
+ return notes;
352
+ }
353
+ /** Marker `.pg.sql` body for files with nothing to translate. */
354
+ function regenOnlyMarker(kept) {
355
+ const lines = [`-- ${kept.fileName} — no DDL to translate.`];
356
+ if (kept.split.codeGenBlock)
357
+ lines.push('-- CodeGen objects are regenerated natively via `mj codegen` on PG.');
358
+ if (kept.split.handAuthoredRegions.some((r) => r.kind === 'metadata-sync')) {
359
+ lines.push('-- Metadata is re-seeded via `mj sync push` against PG.');
360
+ }
361
+ lines.push('');
362
+ return lines.join('\n');
363
+ }
364
+ //# sourceMappingURL=MigrationConverter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MigrationConverter.js","sourceRoot":"","sources":["../src/MigrationConverter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,cAAc,EAAuD,MAAM,wBAAwB,CAAC;AAC7G,OAAO,EAAE,gBAAgB,EAA2C,MAAM,iCAAiC,CAAC;AAwF5G,6FAA6F;AAC7F,MAAM,mBAAmB,GAA+B,IAAI,GAAG,CAAgB;IAC7E,YAAY;IACZ,SAAS;IACT,YAAY;IACZ,gFAAgF;IAChF,6CAA6C;IAC7C,SAAS;IACT,oFAAoF;IACpF,6EAA6E;IAC7E,iBAAiB;CAClB,CAAC,CAAC;AAEH,2GAA2G;AAC3G,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,QAAgB;IAC3D,MAAM,KAAK,GAAG,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAC5C,MAAM,mBAAmB,GAAG,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,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AAC;AAC1B,CAAC"}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * MigrationSplitter — deterministic decomposition of a SQL Server migration into
3
+ * the regions that drive the "split-and-regenerate" PG conversion strategy.
4
+ *
5
+ * See `plans/pg-migration-architecture/SPLIT_AND_REGENERATE_PROPOSAL.md`.
6
+ *
7
+ * The premise: almost all migration content is emitted by one of two MJ
8
+ * generators — CodeGen (SQL objects: views/sprocs/GRANTs/indexes/extended
9
+ * properties) and mj-sync (metadata seed via `DECLARE @x_<hash>; EXEC spCreate…`).
10
+ * Each generator has a FIXED output grammar, so its output is identified
11
+ * deterministically rather than parsed as arbitrary T-SQL. What remains is a
12
+ * small, regular hand-authored remainder plus a rare hand-written procedural
13
+ * residue that must be human-authored for PG.
14
+ *
15
+ * This module performs NO conversion. It only classifies, so the pipeline can
16
+ * route each region: regenerate (CodeGen objects), re-seed/transpile (mj-sync),
17
+ * transpile (regular DDL), or escalate to a human (hand procedural).
18
+ */
19
+ /** What a contiguous region of a migration was produced by / consists of. */
20
+ export type MigrationRegionKind =
21
+ /** Regular hand-authored DDL/DML — CREATE/ALTER TABLE, indexes, constraints, plain INSERT/UPDATE. Transpilable. */
22
+ 'hand-ddl'
23
+ /** Banner-marked CodeGen SQL objects — discard on PG and regenerate natively. */
24
+ | 'codegen-objects'
25
+ /** mj-sync metadata seed — session header or `@x_<hash>` vars. Re-seed via `mj sync push`. */
26
+ | 'metadata-sync'
27
+ /** Real schema DDL — `CREATE/ALTER TABLE`, indexes, constraints. Transpiled. */
28
+ | 'schema-ddl'
29
+ /** Data DML — `INSERT/UPDATE/DELETE`. Transpiled when it isn't part of an mj-sync seed. */
30
+ | 'data-dml'
31
+ /** Hand-written procedural SQL — `CREATE [OR ALTER] PROCEDURE|FUNCTION|TRIGGER` authored by a dev. Needs a human PG version. */
32
+ | 'hand-procedural';
33
+ /** How the CodeGen-block boundary was located. */
34
+ export type BoundaryMethod =
35
+ /** Split at the explicit `-- CODE GEN RUN` delimiter line. */
36
+ 'code-gen-run-delimiter'
37
+ /** Split at the `/*` opener of the first banner-marked CodeGen item. */
38
+ | 'first-item-banner'
39
+ /** No CodeGen block present in the file. */
40
+ | 'no-codegen-block';
41
+ /** File-level routing recommendation derived from the region findings. */
42
+ export type FileRouting =
43
+ /** Hand region is purely regular DDL/DML (plus an optional CodeGen block to drop). Fully automatable. */
44
+ 'transpile-only'
45
+ /** Hand region contains mj-sync metadata blocks needing re-seed or narrow transpile. */
46
+ | 'transpile-plus-reseed'
47
+ /** Hand region contains hand-written procedural SQL — requires a human-authored `.pg.sql`. */
48
+ | 'needs-hand-authoring';
49
+ /** A classified region detected in the hand-authored portion. */
50
+ export interface RegionFinding {
51
+ kind: MigrationRegionKind;
52
+ /** The matched signature (keyword / pattern) that produced this finding. */
53
+ evidence: string;
54
+ /** 1-based line number of the first occurrence. */
55
+ line: number;
56
+ }
57
+ export interface MigrationSplitResult {
58
+ fileName: string;
59
+ totalLines: number;
60
+ /** 1-based line where the CodeGen block starts, or null if there is none. */
61
+ codeGenBoundaryLine: number | null;
62
+ boundaryMethod: BoundaryMethod;
63
+ /** Hand-authored text (everything above the boundary, or the whole file if no boundary). */
64
+ handAuthored: string;
65
+ /** CodeGen block text (everything from the boundary down); '' when there is no block. */
66
+ codeGenBlock: string;
67
+ /**
68
+ * Ordered, de-duplicated entity DISPLAY names whose objects the CodeGen block regenerated
69
+ * — `E(M)` in `INLINE_CODEGEN_BAKING_PLAN.md` §5. This is what the inline baker regenerates
70
+ * natively so PG bakes exactly the entities SS baked (including cascade-only `spDelete`
71
+ * entities). Empty when there is no CodeGen block.
72
+ */
73
+ affectedEntities: string[];
74
+ /** Classification of the hand-authored region (codegen block is excluded — it is always `codegen-objects`). */
75
+ handAuthoredRegions: RegionFinding[];
76
+ routing: FileRouting;
77
+ }
78
+ /**
79
+ * Split a migration into its hand-authored and CodeGen-generated regions and
80
+ * recommend a routing. Pure function — no I/O.
81
+ */
82
+ export declare function splitMigration(sql: string, fileName?: string): MigrationSplitResult;
83
+ /**
84
+ * Parse the ordered, de-duplicated entity display names whose objects a CodeGen
85
+ * block regenerated (`E(M)`). Pure — no I/O. Case-insensitive de-dup, first-seen
86
+ * order and casing preserved. Returns `[]` for an empty/absent block.
87
+ */
88
+ export declare function extractAffectedEntities(codeGenBlock: string): string[];
89
+ //# sourceMappingURL=MigrationSplitter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MigrationSplitter.d.ts","sourceRoot":"","sources":["../src/MigrationSplitter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,6EAA6E;AAC7E,MAAM,MAAM,mBAAmB;AAC7B,mHAAmH;AACjH,UAAU;AACZ,iFAAiF;GAC/E,iBAAiB;AACnB,8FAA8F;GAC5F,eAAe;AACjB,gFAAgF;GAC9E,YAAY;AACd,2FAA2F;GACzF,UAAU;AACZ,gIAAgI;GAC9H,iBAAiB,CAAC;AAEtB,kDAAkD;AAClD,MAAM,MAAM,cAAc;AACxB,8DAA8D;AAC5D,wBAAwB;AAC1B,wEAAwE;GACtE,mBAAmB;AACrB,4CAA4C;GAC1C,kBAAkB,CAAC;AAEvB,0EAA0E;AAC1E,MAAM,MAAM,WAAW;AACrB,yGAAyG;AACvG,gBAAgB;AAClB,wFAAwF;GACtF,uBAAuB;AACzB,8FAA8F;GAC5F,sBAAsB,CAAC;AAE3B,iEAAiE;AACjE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,mBAAmB,CAAC;IAC1B,4EAA4E;IAC5E,QAAQ,EAAE,MAAM,CAAC;IACjB,mDAAmD;IACnD,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,cAAc,EAAE,cAAc,CAAC;IAC/B,4FAA4F;IAC5F,YAAY,EAAE,MAA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