@memberjunction/sql-converter 5.40.2 → 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.
Files changed (39) hide show
  1. package/dist/IncrementalBaker.d.ts +85 -0
  2. package/dist/IncrementalBaker.d.ts.map +1 -0
  3. package/dist/IncrementalBaker.js +127 -0
  4. package/dist/IncrementalBaker.js.map +1 -0
  5. package/dist/MigrationConverter.d.ts +119 -0
  6. package/dist/MigrationConverter.d.ts.map +1 -0
  7. package/dist/MigrationConverter.js +364 -0
  8. package/dist/MigrationConverter.js.map +1 -0
  9. package/dist/MigrationSplitter.d.ts +89 -0
  10. package/dist/MigrationSplitter.d.ts.map +1 -0
  11. package/dist/MigrationSplitter.js +311 -0
  12. package/dist/MigrationSplitter.js.map +1 -0
  13. package/dist/MigrationStatementSplitter.d.ts +39 -0
  14. package/dist/MigrationStatementSplitter.d.ts.map +1 -0
  15. package/dist/MigrationStatementSplitter.js +123 -0
  16. package/dist/MigrationStatementSplitter.js.map +1 -0
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +4 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/rules/AlterTableRule.d.ts.map +1 -1
  22. package/dist/rules/AlterTableRule.js +8 -3
  23. package/dist/rules/AlterTableRule.js.map +1 -1
  24. package/dist/rules/DeclareDmlBlockRule.d.ts +35 -0
  25. package/dist/rules/DeclareDmlBlockRule.d.ts.map +1 -1
  26. package/dist/rules/DeclareDmlBlockRule.js +95 -0
  27. package/dist/rules/DeclareDmlBlockRule.js.map +1 -1
  28. package/dist/rules/PostProcessor.d.ts.map +1 -1
  29. package/dist/rules/PostProcessor.js +31 -5
  30. package/dist/rules/PostProcessor.js.map +1 -1
  31. package/dist/rules/ProcedureToFunctionRule.d.ts +8 -0
  32. package/dist/rules/ProcedureToFunctionRule.d.ts.map +1 -1
  33. package/dist/rules/ProcedureToFunctionRule.js +31 -3
  34. package/dist/rules/ProcedureToFunctionRule.js.map +1 -1
  35. package/dist/rules/SequenceDeduplicator.d.ts +22 -0
  36. package/dist/rules/SequenceDeduplicator.d.ts.map +1 -1
  37. package/dist/rules/SequenceDeduplicator.js +2 -0
  38. package/dist/rules/SequenceDeduplicator.js.map +1 -1
  39. package/package.json +3 -3
@@ -0,0 +1,85 @@
1
+ import type { TSQLToPGTranspiler, ConversionStatus, UnhandledStatement } from './MigrationConverter.js';
2
+ /** Native PG CodeGen captured for one entity (the return of `generateSingleEntitySQLToSeparateFiles`). */
3
+ export interface CapturedEntitySQL {
4
+ /** Indexes, FK-root helper fns, base view, CRUD sprocs and trigger — with GRANTs inline. */
5
+ sql: string;
6
+ /** Consolidated GRANTs (a duplicate of the inline grants in `sql`; the baker bakes `sql`). */
7
+ permissionsSQL: string;
8
+ }
9
+ /**
10
+ * Live-database capabilities the baker needs, injected by the caller (MJCLI wires these to
11
+ * `@memberjunction/codegen-lib` + a `pg` pool). The working DB must be seeded to the state
12
+ * just BEFORE the migration being baked, and is left CURRENT after each `bakeMigration`.
13
+ */
14
+ export interface BakerWorkingDB {
15
+ /** Execute a transpiled hand-DDL + metadata-DML script against the working DB. */
16
+ apply(sql: string): Promise<void>;
17
+ /** Refresh the in-memory metadata provider so freshly-applied entities/fields are visible. */
18
+ refreshMetadata(): Promise<void>;
19
+ /**
20
+ * Generate native PG CodeGen for one entity (by display name), EXECUTE it against the
21
+ * working DB (keeping the DB current for later migrations), and return the captured SQL.
22
+ */
23
+ captureEntity(entityDisplayName: string): Promise<CapturedEntitySQL>;
24
+ }
25
+ export interface IncrementalBakerOptions {
26
+ transpiler: TSQLToPGTranspiler;
27
+ db: BakerWorkingDB;
28
+ /** Target schema for the baked output and `search_path`. Defaults to `__mj`. */
29
+ schema?: string;
30
+ }
31
+ export interface BakedMigrationResult {
32
+ fileName: string;
33
+ /** Conversion status from `convertMigration` (e.g. needs-hand-authoring surfaces here). */
34
+ status: ConversionStatus;
35
+ /** `E(M)` — entities whose native CodeGen was baked, in committed order. */
36
+ affectedEntities: string[];
37
+ /** The standalone baked `.pg.sql` text. */
38
+ pgSQL: string;
39
+ /** Statements the AST transpiler could not handle (reported, never silently dropped). */
40
+ unhandled: UnhandledStatement[];
41
+ /** Hand-written procedural routines the migration carries (require human PG authoring). */
42
+ handProcedural: string[];
43
+ /**
44
+ * `'baked'` — native CodeGen captured + assembled into `pgSQL`.
45
+ * `'preserved'` — a transpile gap (unhandled statement / hand-procedural) made an auto-bake
46
+ * unsafe, so `pgSQL` is the hand-verified committed file (re-bake mode only).
47
+ */
48
+ mode: 'baked' | 'preserved';
49
+ }
50
+ export declare class IncrementalBaker {
51
+ private readonly opts;
52
+ private readonly schema;
53
+ constructor(opts: IncrementalBakerOptions);
54
+ /**
55
+ * Bake one SS migration against the live working DB. Pure of file I/O — caller writes `pgSQL`.
56
+ * Leaves the working DB current for the next migration in the sequence.
57
+ *
58
+ * RE-BAKE mode (`committedPgSql` provided): advance the working DB by applying the known-good
59
+ * committed `.pg.sql` (balanced DROP+CREATE keeps dependent views consistent and registers new
60
+ * entities), then capture native CodeGen READ-ONLY. A transpile gap (unhandled statement or
61
+ * hand-procedural routine) makes an auto-bake incomplete, so the committed file is preserved
62
+ * (`mode: 'preserved'`). This is the robust path for re-baking the committed post-baseline set.
63
+ *
64
+ * FORWARD mode (no `committedPgSql`): apply the transpiled hand body and execute the capture.
65
+ * Known limitation — a new-entity migration's `ALTER COLUMN` preamble CASCADE-drops dependent
66
+ * metadata views (e.g. `vwApplicationSettings`) that per-entity capture doesn't restore, which
67
+ * corrupts the metadata load mid-sequence; prefer the re-bake path for a full set.
68
+ */
69
+ bakeMigration(ssSql: string, fileName: string, committedPgSql?: string): Promise<BakedMigrationResult>;
70
+ /** Capture native CodeGen for each entity in order; strip volatile headers for determinism. */
71
+ private captureEntities;
72
+ /** Build the standalone baked `.pg.sql`: baked header, hand body, then native CodeGen. */
73
+ private assemble;
74
+ private bakedHeader;
75
+ /** Prepend a search_path set so any unqualified identifiers in the hand body resolve. */
76
+ private withSearchPath;
77
+ }
78
+ /**
79
+ * Strip the native CodeGen header's volatile `-- Generated at: <ISO timestamp>` lines so a
80
+ * re-bake of unchanged input is byte-identical (determinism, plan §7). The deeper fix is a
81
+ * baked-mode flag in `PostgreSQLCodeGenProvider.generateSQLFileHeader` (§6.4); doing it here
82
+ * keeps the change contained to the converter and is provider-agnostic.
83
+ */
84
+ export declare function stripVolatileHeaders(sql: string): string;
85
+ //# sourceMappingURL=IncrementalBaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IncrementalBaker.d.ts","sourceRoot":"","sources":["../src/IncrementalBaker.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAExG,0GAA0G;AAC1G,MAAM,WAAW,iBAAiB;IAChC,4FAA4F;IAC5F,GAAG,EAAE,MAAM,CAAC;IACZ,8FAA8F;IAC9F,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,kFAAkF;IAClF,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClC,8FAA8F;IAC9F,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC;;;OAGG;IACH,aAAa,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CACtE;AAED,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,kBAAkB,CAAC;IAC/B,EAAE,EAAE,cAAc,CAAC;IACnB,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,MAAM,CAAC;IACjB,2FAA2F;IAC3F,MAAM,EAAE,gBAAgB,CAAC;IACzB,4EAA4E;IAC5E,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,yFAAyF;IACzF,SAAS,EAAE,kBAAkB,EAAE,CAAC;IAChC,2FAA2F;IAC3F,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB;;;;OAIG;IACH,IAAI,EAAE,OAAO,GAAG,WAAW,CAAC;CAC7B;AAKD,qBAAa,gBAAgB;IAGf,OAAO,CAAC,QAAQ,CAAC,IAAI;IAFjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEH,IAAI,EAAE,uBAAuB;IAI1D;;;;;;;;;;;;;;OAcG;IACG,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAkC5G,+FAA+F;YACjF,eAAe;IAS7B,0FAA0F;IAC1F,OAAO,CAAC,QAAQ;IAchB,OAAO,CAAC,WAAW;IAgBnB,yFAAyF;IACzF,OAAO,CAAC,cAAc;CAGvB;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKxD"}
@@ -0,0 +1,127 @@
1
+ /**
2
+ * IncrementalBaker — the stateful driver of inline native CodeGen baking (Path C).
3
+ * See `plans/pg-migration-architecture/INLINE_CODEGEN_BAKING_PLAN.md` §4/§6.2.
4
+ *
5
+ * For each SQL Server migration it: transpiles the hand-written DDL + recovers the
6
+ * metadata DML (via `convertMigration`), applies that to a LIVE working PG database,
7
+ * then for each entity the migration's CodeGen block named (`E(M)` — from
8
+ * `MigrationSplitter.extractAffectedEntities`) regenerates the native PG CodeGen
9
+ * objects, executes them against the working DB (so later migrations see current
10
+ * shapes), and bakes the captured SQL inline. The result applies standalone via
11
+ * `mj migrate` with no deploy-time codegen step.
12
+ *
13
+ * This module owns ONLY orchestration + file assembly. The live-database work
14
+ * (apply / refresh-metadata / per-entity generate-and-capture) is injected as a
15
+ * `BakerWorkingDB`, so SQLConverter stays free of a `@memberjunction/codegen-lib`
16
+ * dependency — mirroring how `convertMigration` takes an injected transpiler.
17
+ */
18
+ import { convertMigration } from './MigrationConverter.js';
19
+ const DEFAULT_SCHEMA = '__mj';
20
+ const CODEGEN_SECTION_HEADER = '-- ===================== CodeGen (native PG, baked) =====================';
21
+ export class IncrementalBaker {
22
+ constructor(opts) {
23
+ this.opts = opts;
24
+ this.schema = opts.schema ?? DEFAULT_SCHEMA;
25
+ }
26
+ /**
27
+ * Bake one SS migration against the live working DB. Pure of file I/O — caller writes `pgSQL`.
28
+ * Leaves the working DB current for the next migration in the sequence.
29
+ *
30
+ * RE-BAKE mode (`committedPgSql` provided): advance the working DB by applying the known-good
31
+ * committed `.pg.sql` (balanced DROP+CREATE keeps dependent views consistent and registers new
32
+ * entities), then capture native CodeGen READ-ONLY. A transpile gap (unhandled statement or
33
+ * hand-procedural routine) makes an auto-bake incomplete, so the committed file is preserved
34
+ * (`mode: 'preserved'`). This is the robust path for re-baking the committed post-baseline set.
35
+ *
36
+ * FORWARD mode (no `committedPgSql`): apply the transpiled hand body and execute the capture.
37
+ * Known limitation — a new-entity migration's `ALTER COLUMN` preamble CASCADE-drops dependent
38
+ * metadata views (e.g. `vwApplicationSettings`) that per-entity capture doesn't restore, which
39
+ * corrupts the metadata load mid-sequence; prefer the re-bake path for a full set.
40
+ */
41
+ async bakeMigration(ssSql, fileName, committedPgSql) {
42
+ const conv = await convertMigration(ssSql, fileName, {
43
+ transpiler: this.opts.transpiler,
44
+ schema: this.schema,
45
+ includeHeader: false,
46
+ });
47
+ const handBody = conv.pgSQL.trim();
48
+ const entities = conv.split.affectedEntities;
49
+ const base = {
50
+ fileName,
51
+ status: conv.status,
52
+ affectedEntities: entities,
53
+ unhandled: conv.unhandled,
54
+ handProcedural: conv.handProcedural,
55
+ };
56
+ if (committedPgSql !== undefined) {
57
+ await this.opts.db.apply(committedPgSql); // advance via the known-good committed file
58
+ await this.opts.db.refreshMetadata();
59
+ if (conv.status === 'needs-hand-authoring' || conv.unhandled.length > 0) {
60
+ return { ...base, pgSQL: committedPgSql, mode: 'preserved' };
61
+ }
62
+ const captured = await this.captureEntities(entities);
63
+ return { ...base, pgSQL: this.assemble(fileName, handBody, captured), mode: 'baked' };
64
+ }
65
+ if (handBody) {
66
+ await this.opts.db.apply(this.withSearchPath(handBody));
67
+ }
68
+ await this.opts.db.refreshMetadata();
69
+ const captured = await this.captureEntities(entities);
70
+ return { ...base, pgSQL: this.assemble(fileName, handBody, captured), mode: 'baked' };
71
+ }
72
+ /** Capture native CodeGen for each entity in order; strip volatile headers for determinism. */
73
+ async captureEntities(entities) {
74
+ const captured = [];
75
+ for (const entity of entities) {
76
+ const result = await this.opts.db.captureEntity(entity);
77
+ captured.push(stripVolatileHeaders(result.sql).trim());
78
+ }
79
+ return captured;
80
+ }
81
+ /** Build the standalone baked `.pg.sql`: baked header, hand body, then native CodeGen. */
82
+ assemble(fileName, handBody, captured) {
83
+ const parts = [this.bakedHeader(fileName)];
84
+ if (handBody) {
85
+ parts.push(handBody);
86
+ }
87
+ if (captured.length > 0) {
88
+ parts.push(CODEGEN_SECTION_HEADER);
89
+ parts.push(captured.join('\n\n'));
90
+ }
91
+ // Belt-and-suspenders: convertMigration already substitutes the schema; native capture
92
+ // emits literal `__mj`. Replace any stray macro so the baked file is fully literal.
93
+ return parts.join('\n\n').replaceAll('${flyway:defaultSchema}', this.schema) + '\n';
94
+ }
95
+ bakedHeader(fileName) {
96
+ return [
97
+ '-- ============================================================================',
98
+ `-- MemberJunction PostgreSQL Migration — ${fileName}`,
99
+ '-- Split-and-regenerate with INLINE NATIVE CodeGen baking: hand-written DDL transpiled',
100
+ '-- (AST dialect), metadata DML inline, and CodeGen objects (views/sprocs/triggers/grants)',
101
+ '-- baked natively from `mj codegen`. Applies standalone via `mj migrate` — no deploy codegen.',
102
+ '-- ============================================================================',
103
+ '',
104
+ 'CREATE EXTENSION IF NOT EXISTS "pgcrypto";',
105
+ `CREATE SCHEMA IF NOT EXISTS ${this.schema};`,
106
+ `SET search_path TO ${this.schema}, public;`,
107
+ 'SET standard_conforming_strings = on;',
108
+ ].join('\n');
109
+ }
110
+ /** Prepend a search_path set so any unqualified identifiers in the hand body resolve. */
111
+ withSearchPath(sql) {
112
+ return `SET search_path TO ${this.schema}, public;\n${sql}`;
113
+ }
114
+ }
115
+ /**
116
+ * Strip the native CodeGen header's volatile `-- Generated at: <ISO timestamp>` lines so a
117
+ * re-bake of unchanged input is byte-identical (determinism, plan §7). The deeper fix is a
118
+ * baked-mode flag in `PostgreSQLCodeGenProvider.generateSQLFileHeader` (§6.4); doing it here
119
+ * keeps the change contained to the converter and is provider-agnostic.
120
+ */
121
+ export function stripVolatileHeaders(sql) {
122
+ return sql
123
+ .split('\n')
124
+ .filter((line) => !/^\s*--\s*Generated at:/i.test(line))
125
+ .join('\n');
126
+ }
127
+ //# sourceMappingURL=IncrementalBaker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IncrementalBaker.js","sourceRoot":"","sources":["../src/IncrementalBaker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAuD3D,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,MAAM,sBAAsB,GAAG,2EAA2E,CAAC;AAE3G,MAAM,OAAO,gBAAgB;IAG3B,YAA6B,IAA6B;QAA7B,SAAI,GAAJ,IAAI,CAAyB;QACxD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,cAAc,CAAC;IAC9C,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,aAAa,CAAC,KAAa,EAAE,QAAgB,EAAE,cAAuB;QAC1E,MAAM,IAAI,GAAG,MAAM,gBAAgB,CAAC,KAAK,EAAE,QAAQ,EAAE;YACnD,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU;YAChC,MAAM,EAAE,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,CAAC,QAAgB;QAClC,OAAO;YACL,iFAAiF;YACjF,4CAA4C,QAAQ,EAAE;YACtD,wFAAwF;YACxF,2FAA2F;YAC3F,+FAA+F;YAC/F,iFAAiF;YACjF,EAAE;YACF,4CAA4C;YAC5C,+BAA+B,IAAI,CAAC,MAAM,GAAG;YAC7C,sBAAsB,IAAI,CAAC,MAAM,WAAW;YAC5C,uCAAuC;SACxC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACf,CAAC;IAED,yFAAyF;IACjF,cAAc,CAAC,GAAW;QAChC,OAAO,sBAAsB,IAAI,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC;IAC9D,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,GAAW;IAC9C,OAAO,GAAG;SACP,KAAK,CAAC,IAAI,CAAC;SACX,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,yBAAyB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SACvD,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC"}
@@ -0,0 +1,119 @@
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 { type MigrationSplitResult } from './MigrationSplitter.js';
28
+ export type ConversionStatus =
29
+ /** Category-B content was transpiled into `pgSQL`. */
30
+ 'converted'
31
+ /** File is purely regenerated/re-seeded — no DDL to translate; `pgSQL` is a marker only. */
32
+ | 'reseed-or-regen-only'
33
+ /** File contains hand-written procedural SQL — transpiled DDL is emitted, but a human must author the routines. */
34
+ | 'needs-hand-authoring';
35
+ /** One statement the AST transpiler refused to emit — a reported gap. */
36
+ export interface UnhandledStatement {
37
+ /** What the dialect saw (e.g. 'Command', 'Declare', 'sys-guard'). */
38
+ kind: string;
39
+ /** The offending T-SQL (possibly truncated by the dialect). */
40
+ snippet: string;
41
+ }
42
+ /** Result of transpiling kept T-SQL to PostgreSQL. */
43
+ export interface MJTranspileResult {
44
+ /** The emitted PostgreSQL statements, in order. */
45
+ sql: string[];
46
+ /** Per-statement T-SQL the transpiler refused to emit — the gap report. */
47
+ unhandled: UnhandledStatement[];
48
+ }
49
+ /**
50
+ * The transpiler seam between classification (TS) and AST transpilation (Python
51
+ * sqlglot dialect). Production implementation: `MJPostgresTranspiler` in
52
+ * `@memberjunction/sqlglot-ts`. Tests inject a stub.
53
+ */
54
+ export interface TSQLToPGTranspiler {
55
+ transpile(tsql: string): Promise<MJTranspileResult>;
56
+ }
57
+ /**
58
+ * The kept (T-SQL, NOT yet transpiled) content of a migration after classification —
59
+ * codegen objects and mj-sync metadata dropped, hand-procedural flagged. This is the
60
+ * single source of truth for what survives the split; `convertMigration` consumes it.
61
+ */
62
+ export interface KeptTSQL {
63
+ fileName: string;
64
+ status: ConversionStatus;
65
+ /** The kept SQL-Server SQL to transpile. '' when nothing to keep. */
66
+ tsql: string;
67
+ /** Hand-written routines that need a human PG version (names/evidence). */
68
+ handProcedural: string[];
69
+ /** Names of objects dropped for native regeneration (audit trail; statement mode). */
70
+ droppedObjects: string[];
71
+ /** Human-readable notes describing what was dropped/kept and why. */
72
+ notes: string[];
73
+ /** The underlying banner split (boundary, regions, routing) for transparency. */
74
+ split: MigrationSplitResult;
75
+ /** Lines of Category-A CodeGen output dropped (regenerated natively instead). */
76
+ droppedCodeGenLines: number;
77
+ }
78
+ export interface MigrationConversionResult {
79
+ fileName: string;
80
+ status: ConversionStatus;
81
+ /** The `.pg.sql` body to write. For `reseed-or-regen-only` this is a marker comment. */
82
+ pgSQL: string;
83
+ /** The underlying split (boundary, regions, routing) for transparency/reporting. */
84
+ split: MigrationSplitResult;
85
+ /** Lines of Category-A CodeGen output dropped (regenerated natively instead). */
86
+ droppedCodeGenLines: number;
87
+ /** Per-statement T-SQL the AST dialect refused to emit — also embedded as gap comments in `pgSQL`. */
88
+ unhandled: UnhandledStatement[];
89
+ /** Hand-written routines needing a human PG version — also embedded as gap comments. */
90
+ handProcedural: string[];
91
+ /** Names of objects dropped as codegen-regenerated (audit trail). */
92
+ droppedObjects: string[];
93
+ /** Human-readable notes describing what happened to each category. */
94
+ notes: string[];
95
+ }
96
+ export interface ConvertMigrationOptions {
97
+ /** Target schema substituted for `${flyway:defaultSchema}` in the output (default '__mj'). */
98
+ schema?: string;
99
+ /** Emit the standard `.pg.sql` provenance header (default true). */
100
+ includeHeader?: boolean;
101
+ /**
102
+ * The AST transpiler. Required whenever the migration has kept T-SQL to translate;
103
+ * pure regen/reseed files convert without it.
104
+ */
105
+ transpiler?: TSQLToPGTranspiler;
106
+ }
107
+ /** Classify a migration and return the kept T-SQL to transpile — the single classification entry point. */
108
+ export declare function extractKeptTSQL(sql: string, fileName: string): KeptTSQL;
109
+ /**
110
+ * Convert one SQL Server migration to its PG form via split-and-regenerate.
111
+ * No file I/O — the caller decides whether/where to write `pgSQL`.
112
+ *
113
+ * Classification comes from `extractKeptTSQL` (the single source of truth);
114
+ * transpilation goes through `options.transpiler` (the AST dialect). Throws when
115
+ * kept T-SQL exists but no transpiler was provided — content is never dropped
116
+ * because a backend was missing.
117
+ */
118
+ export declare function convertMigration(sql: string, fileName: string, options?: ConvertMigrationOptions): Promise<MigrationConversionResult>;
119
+ //# sourceMappingURL=MigrationConverter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MigrationConverter.d.ts","sourceRoot":"","sources":["../src/MigrationConverter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAkB,KAAK,oBAAoB,EAA4B,MAAM,wBAAwB,CAAC;AAG7G,MAAM,MAAM,gBAAgB;AAC1B,sDAAsD;AACpD,WAAW;AACb,4FAA4F;GAC1F,sBAAsB;AACxB,mHAAmH;GACjH,sBAAsB,CAAC;AAE3B,yEAAyE;AACzE,MAAM,WAAW,kBAAkB;IACjC,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAC;IACb,+DAA+D;IAC/D,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,sDAAsD;AACtD,MAAM,WAAW,iBAAiB;IAChC,mDAAmD;IACnD,GAAG,EAAE,MAAM,EAAE,CAAC;IACd,2EAA2E;IAC3E,SAAS,EAAE,kBAAkB,EAAE,CAAC;CACjC;AAED;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CACrD;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,gBAAgB,CAAC;IACzB,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAC;IACb,2EAA2E;IAC3E,cAAc,EAAE,M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