@memberjunction/sql-converter 0.0.1 → 5.5.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.
- package/README.md +754 -28
- package/dist/ConversionPipeline.d.ts +31 -0
- package/dist/ConversionPipeline.d.ts.map +1 -0
- package/dist/ConversionPipeline.js +231 -0
- package/dist/ConversionPipeline.js.map +1 -0
- package/dist/DatabaseAuditor.d.ts +22 -0
- package/dist/DatabaseAuditor.d.ts.map +1 -0
- package/dist/DatabaseAuditor.js +115 -0
- package/dist/DatabaseAuditor.js.map +1 -0
- package/dist/LLMFallback.d.ts +13 -0
- package/dist/LLMFallback.d.ts.map +1 -0
- package/dist/LLMFallback.js +11 -0
- package/dist/LLMFallback.js.map +1 -0
- package/dist/SQLFileSplitter.d.ts +48 -0
- package/dist/SQLFileSplitter.d.ts.map +1 -0
- package/dist/SQLFileSplitter.js +212 -0
- package/dist/SQLFileSplitter.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/rules/AlterTableRule.d.ts +23 -0
- package/dist/rules/AlterTableRule.d.ts.map +1 -0
- package/dist/rules/AlterTableRule.js +133 -0
- package/dist/rules/AlterTableRule.js.map +1 -0
- package/dist/rules/BatchConverter.d.ts +37 -0
- package/dist/rules/BatchConverter.d.ts.map +1 -0
- package/dist/rules/BatchConverter.js +561 -0
- package/dist/rules/BatchConverter.js.map +1 -0
- package/dist/rules/CatalogViewRule.d.ts +25 -0
- package/dist/rules/CatalogViewRule.d.ts.map +1 -0
- package/dist/rules/CatalogViewRule.js +294 -0
- package/dist/rules/CatalogViewRule.js.map +1 -0
- package/dist/rules/ConditionalDDLRule.d.ts +50 -0
- package/dist/rules/ConditionalDDLRule.d.ts.map +1 -0
- package/dist/rules/ConditionalDDLRule.js +234 -0
- package/dist/rules/ConditionalDDLRule.js.map +1 -0
- package/dist/rules/CreateIndexRule.d.ts +11 -0
- package/dist/rules/CreateIndexRule.d.ts.map +1 -0
- package/dist/rules/CreateIndexRule.js +66 -0
- package/dist/rules/CreateIndexRule.js.map +1 -0
- package/dist/rules/CreateTableRule.d.ts +42 -0
- package/dist/rules/CreateTableRule.d.ts.map +1 -0
- package/dist/rules/CreateTableRule.js +355 -0
- package/dist/rules/CreateTableRule.js.map +1 -0
- package/dist/rules/DialectHeaderBuilder.d.ts +39 -0
- package/dist/rules/DialectHeaderBuilder.d.ts.map +1 -0
- package/dist/rules/DialectHeaderBuilder.js +66 -0
- package/dist/rules/DialectHeaderBuilder.js.map +1 -0
- package/dist/rules/ExecBlockRule.d.ts +89 -0
- package/dist/rules/ExecBlockRule.d.ts.map +1 -0
- package/dist/rules/ExecBlockRule.js +491 -0
- package/dist/rules/ExecBlockRule.js.map +1 -0
- package/dist/rules/ExpressionHelpers.d.ts +71 -0
- package/dist/rules/ExpressionHelpers.d.ts.map +1 -0
- package/dist/rules/ExpressionHelpers.js +686 -0
- package/dist/rules/ExpressionHelpers.js.map +1 -0
- package/dist/rules/ExtendedPropertyRule.d.ts +16 -0
- package/dist/rules/ExtendedPropertyRule.d.ts.map +1 -0
- package/dist/rules/ExtendedPropertyRule.js +89 -0
- package/dist/rules/ExtendedPropertyRule.js.map +1 -0
- package/dist/rules/FunctionRule.d.ts +20 -0
- package/dist/rules/FunctionRule.d.ts.map +1 -0
- package/dist/rules/FunctionRule.js +374 -0
- package/dist/rules/FunctionRule.js.map +1 -0
- package/dist/rules/GrantRule.d.ts +11 -0
- package/dist/rules/GrantRule.d.ts.map +1 -0
- package/dist/rules/GrantRule.js +60 -0
- package/dist/rules/GrantRule.js.map +1 -0
- package/dist/rules/InsertRule.d.ts +18 -0
- package/dist/rules/InsertRule.d.ts.map +1 -0
- package/dist/rules/InsertRule.js +183 -0
- package/dist/rules/InsertRule.js.map +1 -0
- package/dist/rules/PostProcessor.d.ts +13 -0
- package/dist/rules/PostProcessor.d.ts.map +1 -0
- package/dist/rules/PostProcessor.js +252 -0
- package/dist/rules/PostProcessor.js.map +1 -0
- package/dist/rules/ProcedureToFunctionRule.d.ts +31 -0
- package/dist/rules/ProcedureToFunctionRule.d.ts.map +1 -0
- package/dist/rules/ProcedureToFunctionRule.js +805 -0
- package/dist/rules/ProcedureToFunctionRule.js.map +1 -0
- package/dist/rules/RuleRegistry.d.ts +48 -0
- package/dist/rules/RuleRegistry.d.ts.map +1 -0
- package/dist/rules/RuleRegistry.js +70 -0
- package/dist/rules/RuleRegistry.js.map +1 -0
- package/dist/rules/StatementClassifier.d.ts +11 -0
- package/dist/rules/StatementClassifier.d.ts.map +1 -0
- package/dist/rules/StatementClassifier.js +224 -0
- package/dist/rules/StatementClassifier.js.map +1 -0
- package/dist/rules/SubSplitter.d.ts +18 -0
- package/dist/rules/SubSplitter.d.ts.map +1 -0
- package/dist/rules/SubSplitter.js +211 -0
- package/dist/rules/SubSplitter.js.map +1 -0
- package/dist/rules/TSQLToPostgresRules.d.ts +22 -0
- package/dist/rules/TSQLToPostgresRules.d.ts.map +1 -0
- package/dist/rules/TSQLToPostgresRules.js +59 -0
- package/dist/rules/TSQLToPostgresRules.js.map +1 -0
- package/dist/rules/TriggerRule.d.ts +22 -0
- package/dist/rules/TriggerRule.d.ts.map +1 -0
- package/dist/rules/TriggerRule.js +197 -0
- package/dist/rules/TriggerRule.js.map +1 -0
- package/dist/rules/TypeResolver.d.ts +35 -0
- package/dist/rules/TypeResolver.d.ts.map +1 -0
- package/dist/rules/TypeResolver.js +112 -0
- package/dist/rules/TypeResolver.js.map +1 -0
- package/dist/rules/ViewRule.d.ts +28 -0
- package/dist/rules/ViewRule.d.ts.map +1 -0
- package/dist/rules/ViewRule.js +299 -0
- package/dist/rules/ViewRule.js.map +1 -0
- package/dist/rules/index.d.ts +29 -0
- package/dist/rules/index.d.ts.map +1 -0
- package/dist/rules/index.js +33 -0
- package/dist/rules/index.js.map +1 -0
- package/dist/rules/types.d.ts +123 -0
- package/dist/rules/types.d.ts.map +1 -0
- package/dist/rules/types.js +57 -0
- package/dist/rules/types.js.map +1 -0
- package/dist/types.d.ts +146 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +28 -7
package/README.md
CHANGED
|
@@ -1,45 +1,771 @@
|
|
|
1
1
|
# @memberjunction/sql-converter
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## Overview
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
A production-grade SQL dialect conversion pipeline that converts SQL Server (T-SQL) to PostgreSQL. The pipeline uses a rule-based architecture where each SQL statement type is handled by a specialized conversion rule, producing deterministic, executable PostgreSQL output.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
**Current status:** 0 errors across the v5.0 baseline (273 stored procedures) + 6 incremental migrations. 465 unit tests passing.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
### Key Features
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
- Rule-based conversion with 11 specialized rules
|
|
12
|
+
- Statement classification (27 distinct types)
|
|
13
|
+
- Context-aware conversion (CREATE TABLE column types inform INSERT boolean casting)
|
|
14
|
+
- Ordered output grouping (Tables -> FKs -> Views -> Functions -> Triggers -> Data -> Grants -> Comments)
|
|
15
|
+
- Global post-processing with 25+ transformations
|
|
16
|
+
- Database verification and cross-database audit
|
|
17
|
+
- LLM fallback for unhandled patterns
|
|
15
18
|
|
|
16
|
-
##
|
|
19
|
+
## Architecture
|
|
17
20
|
|
|
18
|
-
|
|
21
|
+
```mermaid
|
|
22
|
+
flowchart TD
|
|
23
|
+
A[SQL Server File] --> B[Preprocess<br/>Flyway placeholders]
|
|
24
|
+
B --> C[Split on GO<br/>Batch separator]
|
|
25
|
+
C --> D[SubSplitter<br/>Compound batches]
|
|
26
|
+
D --> E[StatementClassifier<br/>27 statement types]
|
|
27
|
+
E --> F{Statement Type}
|
|
28
|
+
F -->|SKIP_*| G[Skip / Discard]
|
|
29
|
+
F -->|Convertible| H[Match Rules<br/>by AppliesTo]
|
|
30
|
+
H --> I[PreProcess Phase]
|
|
31
|
+
I --> J{BypassSqlglot?}
|
|
32
|
+
J -->|Yes| K[Rule handles<br/>full conversion]
|
|
33
|
+
J -->|No| L[sqlglot transpile]
|
|
34
|
+
L --> M[PostProcess Phase]
|
|
35
|
+
K --> N[Route to<br/>OutputGroup]
|
|
36
|
+
M --> N
|
|
37
|
+
N --> O[Assemble Groups<br/>in dependency order]
|
|
38
|
+
O --> P[PostProcessor<br/>Global cleanup]
|
|
39
|
+
P --> Q[PostgreSQL Output]
|
|
40
|
+
```
|
|
19
41
|
|
|
20
|
-
##
|
|
42
|
+
## Quick Start
|
|
21
43
|
|
|
22
|
-
|
|
44
|
+
### Installation
|
|
23
45
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
4. Use the configured workflow to publish your actual package
|
|
46
|
+
```bash
|
|
47
|
+
npm install @memberjunction/sql-converter
|
|
48
|
+
```
|
|
28
49
|
|
|
29
|
-
|
|
50
|
+
### CLI Usage
|
|
30
51
|
|
|
31
|
-
|
|
32
|
-
-
|
|
33
|
-
|
|
34
|
-
- Should not be installed as a dependency
|
|
35
|
-
- Exists only for administrative purposes
|
|
52
|
+
```bash
|
|
53
|
+
npx mj sql-convert --source migrations/v5/Baseline.sql --output migrations/pg/Baseline_PG.sql
|
|
54
|
+
```
|
|
36
55
|
|
|
37
|
-
|
|
56
|
+
### Programmatic Usage
|
|
38
57
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
- [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
|
|
58
|
+
```typescript
|
|
59
|
+
import { convertFile, getTSQLToPostgresRules } from '@memberjunction/sql-converter';
|
|
42
60
|
|
|
43
|
-
|
|
61
|
+
const result = convertFile({
|
|
62
|
+
Source: 'path/to/input.sql',
|
|
63
|
+
SourceIsFile: true,
|
|
64
|
+
OutputFile: 'path/to/output.sql',
|
|
65
|
+
Rules: getTSQLToPostgresRules(),
|
|
66
|
+
OnProgress: (msg) => console.log(msg),
|
|
67
|
+
});
|
|
44
68
|
|
|
45
|
-
|
|
69
|
+
console.log(`Converted ${result.Stats.Converted} of ${result.Stats.TotalBatches} batches`);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Pipeline Deep Dive
|
|
73
|
+
|
|
74
|
+
```mermaid
|
|
75
|
+
sequenceDiagram
|
|
76
|
+
participant F as File Input
|
|
77
|
+
participant P as Preprocessor
|
|
78
|
+
participant S as Splitter
|
|
79
|
+
participant SS as SubSplitter
|
|
80
|
+
participant C as Classifier
|
|
81
|
+
participant R as Rules Engine
|
|
82
|
+
participant G as Output Groups
|
|
83
|
+
participant PP as PostProcessor
|
|
84
|
+
participant O as Output
|
|
85
|
+
|
|
86
|
+
F->>P: Raw SQL (replace ${flyway:defaultSchema} with __mj)
|
|
87
|
+
P->>S: Processed SQL
|
|
88
|
+
S->>SS: GO-separated batches
|
|
89
|
+
SS->>C: Sub-split individual statements
|
|
90
|
+
|
|
91
|
+
loop For each statement
|
|
92
|
+
C->>R: StatementType + SQL
|
|
93
|
+
alt SKIP type
|
|
94
|
+
R-->>G: Discard
|
|
95
|
+
else Has matching rule
|
|
96
|
+
R->>R: PreProcess (if defined)
|
|
97
|
+
alt BypassSqlglot = true
|
|
98
|
+
R->>R: PostProcess(original, original, context)
|
|
99
|
+
else BypassSqlglot = false
|
|
100
|
+
R->>R: sqlglot transpile
|
|
101
|
+
R->>R: PostProcess(transpiled, original, context)
|
|
102
|
+
end
|
|
103
|
+
R->>G: Route to appropriate group
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
G->>PP: Assembled output (Tables, FKs, Views, ...)
|
|
108
|
+
PP->>O: Final PostgreSQL SQL
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Rule System
|
|
112
|
+
|
|
113
|
+
### How Rules Work
|
|
114
|
+
|
|
115
|
+
Each rule implements `IConversionRule`:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
interface IConversionRule {
|
|
119
|
+
Name: string; // Display name
|
|
120
|
+
AppliesTo: StatementType[]; // Which statement types
|
|
121
|
+
Priority: number; // Lower = runs first
|
|
122
|
+
BypassSqlglot?: boolean; // Skip sqlglot transpilation
|
|
123
|
+
PreProcess?(sql: string, context: ConversionContext): string;
|
|
124
|
+
PostProcess?(sql: string, originalSQL: string, context: ConversionContext): string;
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Rule Priority Chain
|
|
129
|
+
|
|
130
|
+
```mermaid
|
|
131
|
+
flowchart LR
|
|
132
|
+
A["CreateTableRule<br/>Priority 10"] --> B["ViewRule<br/>Priority 20"]
|
|
133
|
+
B --> C["ProcedureToFunctionRule<br/>Priority 30"]
|
|
134
|
+
C --> D["FunctionRule<br/>Priority 35"]
|
|
135
|
+
D --> E["TriggerRule<br/>Priority 40"]
|
|
136
|
+
E --> F["InsertRule<br/>Priority 50"]
|
|
137
|
+
F --> G["ConditionalDDLRule<br/>Priority 55"]
|
|
138
|
+
G --> H["AlterTableRule<br/>Priority 60"]
|
|
139
|
+
H --> I["CreateIndexRule<br/>Priority 70"]
|
|
140
|
+
I --> J["GrantRule<br/>Priority 80"]
|
|
141
|
+
J --> K["ExtendedPropertyRule<br/>Priority 90"]
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### ConversionContext
|
|
145
|
+
|
|
146
|
+
State accumulated across the pipeline:
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
interface ConversionContext {
|
|
150
|
+
SourceDialect: string; // 'tsql'
|
|
151
|
+
TargetDialect: string; // 'postgres'
|
|
152
|
+
Schema: string; // '__mj'
|
|
153
|
+
TableColumns: Map<string, Map<string, string>>; // table -> column -> PG type
|
|
154
|
+
HandWrittenFunctions: Map<string, string>; // function name -> PG replacement
|
|
155
|
+
CreatedFunctions: Set<string>; // successfully converted functions
|
|
156
|
+
CreatedViews: Set<string>; // successfully converted views
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
```mermaid
|
|
161
|
+
flowchart LR
|
|
162
|
+
CT["CreateTableRule<br/>Populates TableColumns"] --> IR["InsertRule<br/>Reads TableColumns<br/>for boolean casting"]
|
|
163
|
+
P["ProcedureToFunctionRule<br/>Populates CreatedFunctions"] --> GR["GrantRule<br/>Reads CreatedFunctions<br/>to skip invalid grants"]
|
|
164
|
+
V["ViewRule<br/>Populates CreatedViews"] --> GR
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Rule-by-Rule Documentation
|
|
168
|
+
|
|
169
|
+
### 1. CreateTableRule (Priority 10)
|
|
170
|
+
|
|
171
|
+
**Applies to:** `CREATE_TABLE` | **Bypasses sqlglot:** Yes
|
|
172
|
+
|
|
173
|
+
Converts SQL Server CREATE TABLE statements to PostgreSQL DDL.
|
|
174
|
+
|
|
175
|
+
**Conversions:**
|
|
176
|
+
- Bracket identifiers `[schema].[table]` to `schema."table"`
|
|
177
|
+
- SQL Server types to PG types (see Type Mapping table below)
|
|
178
|
+
- `IDENTITY(1,1)` to `GENERATED BY DEFAULT AS IDENTITY`
|
|
179
|
+
- `DEFAULT (NEWSEQUENTIALID())` to `DEFAULT gen_random_uuid()`
|
|
180
|
+
- `DEFAULT (GETUTCDATE())` to `DEFAULT NOW()`
|
|
181
|
+
- `DEFAULT ((0))` for BIT to `DEFAULT FALSE`
|
|
182
|
+
- `DEFAULT ((1))` for BIT to `DEFAULT TRUE`
|
|
183
|
+
- Removes CLUSTERED/NONCLUSTERED, ON [PRIMARY], COLLATE
|
|
184
|
+
- Quotes PascalCase column names
|
|
185
|
+
- Tracks column types in `ConversionContext.TableColumns`
|
|
186
|
+
|
|
187
|
+
**Example:**
|
|
188
|
+
|
|
189
|
+
```sql
|
|
190
|
+
-- Input (T-SQL)
|
|
191
|
+
CREATE TABLE [__mj].[Users] (
|
|
192
|
+
[ID] [uniqueidentifier] NOT NULL DEFAULT (newsequentialid()),
|
|
193
|
+
[Name] [nvarchar](100) NOT NULL,
|
|
194
|
+
[IsActive] [bit] NOT NULL DEFAULT ((1)),
|
|
195
|
+
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([ID])
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
-- Output (PostgreSQL)
|
|
199
|
+
CREATE TABLE __mj."Users" (
|
|
200
|
+
"ID" UUID NOT NULL DEFAULT gen_random_uuid(),
|
|
201
|
+
"Name" VARCHAR(100) NOT NULL,
|
|
202
|
+
"IsActive" BOOLEAN NOT NULL DEFAULT TRUE,
|
|
203
|
+
CONSTRAINT "PK_Users" PRIMARY KEY ("ID")
|
|
204
|
+
);
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### 2. ViewRule (Priority 20)
|
|
208
|
+
|
|
209
|
+
**Applies to:** `CREATE_VIEW` | **Bypasses sqlglot:** Yes
|
|
210
|
+
|
|
211
|
+
Converts CREATE VIEW statements with full expression conversion.
|
|
212
|
+
|
|
213
|
+
**Conversions:**
|
|
214
|
+
- `CREATE [OR ALTER] VIEW` to `CREATE OR REPLACE VIEW`
|
|
215
|
+
- `CROSS APPLY` to `CROSS JOIN LATERAL`
|
|
216
|
+
- `OUTER APPLY` to `LEFT JOIN LATERAL`
|
|
217
|
+
- Adds `ON TRUE` for LEFT JOIN LATERAL without ON clause
|
|
218
|
+
- Wraps LATERAL function calls: `func(args) AS alias` to `(SELECT * FROM func(args)) AS alias`
|
|
219
|
+
- STRING_AGG WITHIN GROUP rewriting
|
|
220
|
+
- All expression helpers (date functions, CHARINDEX, STUFF, etc.)
|
|
221
|
+
- Column reference quoting: `alias.PascalCol` to `alias."PascalCol"`
|
|
222
|
+
- Skips views referencing sys.* tables or flyway
|
|
223
|
+
|
|
224
|
+
### 3. ProcedureToFunctionRule (Priority 30)
|
|
225
|
+
|
|
226
|
+
**Applies to:** `CREATE_PROCEDURE` | **Bypasses sqlglot:** Yes
|
|
227
|
+
|
|
228
|
+
Converts SQL Server stored procedures to PostgreSQL functions.
|
|
229
|
+
|
|
230
|
+
**Conversions:**
|
|
231
|
+
- Parses parameters (name, type, default, OUTPUT flag)
|
|
232
|
+
- Maps SQL Server types to PG types for parameters
|
|
233
|
+
- Replaces `@var` with `p_var` in function body
|
|
234
|
+
- `@@ROWCOUNT` to `_v_row_count`, `@@ERROR` to `0`
|
|
235
|
+
- `WHILE BEGIN...END` to `WHILE...LOOP...END LOOP`
|
|
236
|
+
- `IF BEGIN...END` to `IF...THEN...END IF`
|
|
237
|
+
- `SET @var =` to `p_var :=`
|
|
238
|
+
- Extracts DECLARE statements into PG DECLARE block
|
|
239
|
+
- `INSERTED` to `NEW`, `DELETED` to `OLD`
|
|
240
|
+
- Determines return type (VOID, TABLE row type, SETOF)
|
|
241
|
+
- Wraps in `CREATE OR REPLACE FUNCTION ... $$ LANGUAGE plpgsql;`
|
|
242
|
+
- Skips procedures with sys.* references, temp tables, STRING_SPLIT
|
|
243
|
+
|
|
244
|
+
### 4. FunctionRule (Priority 35)
|
|
245
|
+
|
|
246
|
+
**Applies to:** `CREATE_FUNCTION` | **Bypasses sqlglot:** Yes
|
|
247
|
+
|
|
248
|
+
Converts SQL Server functions (scalar and table-valued) to PostgreSQL.
|
|
249
|
+
|
|
250
|
+
**Features:**
|
|
251
|
+
- Checks for hand-written function replacements first (7 built-in: StripToAlphanumeric, GetProgrammaticName, ToTitleCase, ToProperCase, ExtractVersionComponents, parseEmail, parseDomain, fnInitials)
|
|
252
|
+
- Inline table-valued functions to `RETURNS TABLE(...) AS $$ ... $$ LANGUAGE sql;`
|
|
253
|
+
- Scalar functions to `RETURNS type AS $$ ... $$ LANGUAGE plpgsql;`
|
|
254
|
+
- WITH recursive CTE detection to `WITH RECURSIVE`
|
|
255
|
+
- DECLARE extraction, WHILE/IF conversion, type mapping
|
|
256
|
+
|
|
257
|
+
### 5. TriggerRule (Priority 40)
|
|
258
|
+
|
|
259
|
+
**Applies to:** `CREATE_TRIGGER` | **Bypasses sqlglot:** Yes
|
|
260
|
+
|
|
261
|
+
Converts SQL Server triggers to PostgreSQL trigger functions.
|
|
262
|
+
|
|
263
|
+
**Pattern:**
|
|
264
|
+
|
|
265
|
+
```sql
|
|
266
|
+
-- Input
|
|
267
|
+
CREATE TRIGGER trgAfterUpdate ON [__mj].[Users]
|
|
268
|
+
AFTER UPDATE AS ...
|
|
269
|
+
|
|
270
|
+
-- Output
|
|
271
|
+
CREATE OR REPLACE FUNCTION __mj."trgAfterUpdate_func"() RETURNS TRIGGER AS $$
|
|
272
|
+
BEGIN ... END;
|
|
273
|
+
$$ LANGUAGE plpgsql;
|
|
274
|
+
|
|
275
|
+
CREATE TRIGGER "trgAfterUpdate" AFTER UPDATE ON __mj."Users"
|
|
276
|
+
FOR EACH ROW EXECUTE FUNCTION __mj."trgAfterUpdate_func"();
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
- Special handling for UpdatedAt triggers (common pattern)
|
|
280
|
+
- Skips triggers using TRIGGER_NESTLEVEL() or UPDATE()
|
|
281
|
+
- `INSERTED` to `NEW`, `DELETED` to `OLD`
|
|
282
|
+
|
|
283
|
+
### 6. InsertRule (Priority 50)
|
|
284
|
+
|
|
285
|
+
**Applies to:** `INSERT`, `UPDATE`, `DELETE` | **Bypasses sqlglot:** Yes
|
|
286
|
+
|
|
287
|
+
Converts DML statements with expression helpers.
|
|
288
|
+
|
|
289
|
+
**Order of operations (important for correctness):**
|
|
290
|
+
1. Convert identifiers
|
|
291
|
+
2. Remove N prefix
|
|
292
|
+
3. Remove COLLATE
|
|
293
|
+
4. Convert common functions (BEFORE quoting to avoid quoting function names like LEN)
|
|
294
|
+
5. String concatenation (`+` to `||`)
|
|
295
|
+
6. CHARINDEX, STUFF, CONVERT, IIF, CAST types
|
|
296
|
+
7. Quote PascalCase identifiers
|
|
297
|
+
8. Ensure semicolon
|
|
298
|
+
|
|
299
|
+
### 7. ConditionalDDLRule (Priority 55)
|
|
300
|
+
|
|
301
|
+
**Applies to:** `CONDITIONAL_DDL` | **Bypasses sqlglot:** Yes
|
|
302
|
+
|
|
303
|
+
Converts IF NOT EXISTS conditional DDL patterns.
|
|
304
|
+
|
|
305
|
+
**Two patterns:**
|
|
306
|
+
1. **Conditional Index:** `IF NOT EXISTS (SELECT ... sys.indexes ...) CREATE INDEX` to `CREATE INDEX IF NOT EXISTS`
|
|
307
|
+
2. **DO $$ Block:** `IF NOT EXISTS (...) BEGIN ... END` to `DO $$ BEGIN IF NOT EXISTS (...) THEN ... END IF; END $$;`
|
|
308
|
+
|
|
309
|
+
**Features:**
|
|
310
|
+
- Type conversions (NVARCHAR to VARCHAR, BIT to BOOLEAN, etc.)
|
|
311
|
+
- INFORMATION_SCHEMA casing (PG requires lowercase)
|
|
312
|
+
- PascalCase identifier quoting (skips string literals to avoid corrupting UUIDs)
|
|
313
|
+
|
|
314
|
+
### 8. AlterTableRule (Priority 60)
|
|
315
|
+
|
|
316
|
+
**Applies to:** `FK_CONSTRAINT`, `PK_CONSTRAINT`, `CHECK_CONSTRAINT`, `UNIQUE_CONSTRAINT`, `ENABLE_CONSTRAINT`, `ALTER_TABLE` | **Bypasses sqlglot:** Yes
|
|
317
|
+
|
|
318
|
+
Converts ALTER TABLE statements and constraint definitions.
|
|
319
|
+
|
|
320
|
+
**Conversions:**
|
|
321
|
+
- Identifier conversion, COLLATE removal
|
|
322
|
+
- Type conversions for defaults and columns
|
|
323
|
+
- `GETUTCDATE()` to `NOW()`, `NEWSEQUENTIALID()` to `gen_random_uuid()`
|
|
324
|
+
- Removes CLUSTERED/NONCLUSTERED, ASC/DESC in constraints, ON [PRIMARY]
|
|
325
|
+
- FK constraints: adds `DEFERRABLE INITIALLY DEFERRED`
|
|
326
|
+
- CHECK constraints: adds `NOT VALID`
|
|
327
|
+
- `WITH CHECK CHECK CONSTRAINT` to comment (no-op in PG)
|
|
328
|
+
|
|
329
|
+
### 9. CreateIndexRule (Priority 70)
|
|
330
|
+
|
|
331
|
+
**Applies to:** `CREATE_INDEX` | **Bypasses sqlglot:** Yes
|
|
332
|
+
|
|
333
|
+
Converts CREATE INDEX statements.
|
|
334
|
+
|
|
335
|
+
**Conversions:**
|
|
336
|
+
- Removes CLUSTERED/NONCLUSTERED
|
|
337
|
+
- Removes `WITH (PAD_INDEX = ...)` option blocks
|
|
338
|
+
- Removes ON [filegroup]
|
|
339
|
+
- Removes INCLUDE columns (simplified)
|
|
340
|
+
- Fixes boolean values: `=(1)` to `=TRUE`, `=(0)` to `=FALSE`
|
|
341
|
+
|
|
342
|
+
### 10. GrantRule (Priority 80)
|
|
343
|
+
|
|
344
|
+
**Applies to:** `GRANT`, `REVOKE` | **Bypasses sqlglot:** Yes
|
|
345
|
+
|
|
346
|
+
Converts GRANT and REVOKE statements.
|
|
347
|
+
|
|
348
|
+
**Features:**
|
|
349
|
+
- Adds `FUNCTION` keyword for EXECUTE grants (PG requirement)
|
|
350
|
+
- Skips grants on functions not in `CreatedFunctions` set
|
|
351
|
+
- Skips grants on views (vw*) not in `CreatedViews` set
|
|
352
|
+
- Removes N prefix from strings
|
|
353
|
+
|
|
354
|
+
### 11. ExtendedPropertyRule (Priority 90)
|
|
355
|
+
|
|
356
|
+
**Applies to:** `EXTENDED_PROPERTY` | **Bypasses sqlglot:** Yes
|
|
357
|
+
|
|
358
|
+
Converts `sp_addextendedproperty` calls to PostgreSQL COMMENT statements.
|
|
359
|
+
|
|
360
|
+
**Supports:**
|
|
361
|
+
- Named parameters (`@name=`, `@value=`, etc.)
|
|
362
|
+
- Positional parameters
|
|
363
|
+
- TABLE to `COMMENT ON TABLE`
|
|
364
|
+
- VIEW to `COMMENT ON VIEW`
|
|
365
|
+
- COLUMN to `COMMENT ON COLUMN`
|
|
366
|
+
- PROCEDURE/FUNCTION to commented out (PG needs signature)
|
|
367
|
+
|
|
368
|
+
## Statement Classification
|
|
369
|
+
|
|
370
|
+
The `StatementClassifier` uses pattern matching to assign one of 27 types:
|
|
371
|
+
|
|
372
|
+
| Type | Examples |
|
|
373
|
+
|------|----------|
|
|
374
|
+
| `CREATE_TABLE` | `CREATE TABLE [schema].[name] (...)` |
|
|
375
|
+
| `CREATE_VIEW` | `CREATE VIEW`, `CREATE OR ALTER VIEW` |
|
|
376
|
+
| `CREATE_PROCEDURE` | `CREATE PROC[EDURE]` (unless references sys.*) |
|
|
377
|
+
| `CREATE_FUNCTION` | `CREATE FUNCTION` |
|
|
378
|
+
| `CREATE_TRIGGER` | `CREATE TRIGGER` |
|
|
379
|
+
| `CREATE_INDEX` | `CREATE [UNIQUE] [NONCLUSTERED] INDEX` |
|
|
380
|
+
| `ALTER_TABLE` | `ALTER TABLE ADD COLUMN`, `ALTER TABLE ALTER COLUMN` |
|
|
381
|
+
| `FK_CONSTRAINT` | `ALTER TABLE ADD CONSTRAINT ... FOREIGN KEY` |
|
|
382
|
+
| `PK_CONSTRAINT` | `ALTER TABLE ADD CONSTRAINT ... PRIMARY KEY` |
|
|
383
|
+
| `CHECK_CONSTRAINT` | `ALTER TABLE ADD CONSTRAINT ... CHECK` |
|
|
384
|
+
| `UNIQUE_CONSTRAINT` | `ALTER TABLE ADD CONSTRAINT ... UNIQUE` |
|
|
385
|
+
| `ENABLE_CONSTRAINT` | `ALTER TABLE WITH CHECK CHECK CONSTRAINT` |
|
|
386
|
+
| `INSERT` / `UPDATE` / `DELETE` | DML statements |
|
|
387
|
+
| `GRANT` / `DENY` / `REVOKE` | DCL statements |
|
|
388
|
+
| `CONDITIONAL_DDL` | `IF NOT EXISTS (...) BEGIN ... END` |
|
|
389
|
+
| `EXTENDED_PROPERTY` | `sp_addextendedproperty` |
|
|
390
|
+
| `COMMENT_ONLY` | Pure comment blocks |
|
|
391
|
+
| `SKIP_SESSION` | `SET NUMERIC_ROUNDABORT`, `SET ANSI_PADDING`, etc. |
|
|
392
|
+
| `SKIP_ERROR` | `IF @@ERROR` |
|
|
393
|
+
| `SKIP_SQLSERVER` | SQL Server-specific code |
|
|
394
|
+
| `SKIP_NOCHECK` | `WITH NOCHECK` |
|
|
395
|
+
| `SKIP_PRINT` | `PRINT` statements |
|
|
396
|
+
| `UNKNOWN` | Unclassified statements |
|
|
397
|
+
|
|
398
|
+
## Output Grouping
|
|
399
|
+
|
|
400
|
+
Converted statements are grouped in dependency order:
|
|
401
|
+
|
|
402
|
+
```mermaid
|
|
403
|
+
flowchart TD
|
|
404
|
+
A[DDL: Tables, PKs, Indexes] --> B[Helper Functions fn*]
|
|
405
|
+
B --> C[Views]
|
|
406
|
+
C --> D[Stored Procedures sp*]
|
|
407
|
+
D --> E[Triggers]
|
|
408
|
+
E --> F[Data: INSERT/UPDATE/DELETE]
|
|
409
|
+
F --> G[FK & CHECK Constraints]
|
|
410
|
+
G --> H[Grants]
|
|
411
|
+
H --> I[Comments]
|
|
412
|
+
I --> J[Other / Errors]
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
## Type Mapping Reference
|
|
416
|
+
|
|
417
|
+
| SQL Server | PostgreSQL | Notes |
|
|
418
|
+
|-----------|-----------|-------|
|
|
419
|
+
| `UNIQUEIDENTIFIER` | `UUID` | |
|
|
420
|
+
| `BIT` | `BOOLEAN` | |
|
|
421
|
+
| `INT` | `INTEGER` | |
|
|
422
|
+
| `BIGINT` | `BIGINT` | Unchanged |
|
|
423
|
+
| `SMALLINT` | `SMALLINT` | Unchanged |
|
|
424
|
+
| `TINYINT` | `SMALLINT` | PG has no TINYINT |
|
|
425
|
+
| `FLOAT` | `DOUBLE PRECISION` | |
|
|
426
|
+
| `REAL` | `REAL` | Unchanged |
|
|
427
|
+
| `MONEY` | `NUMERIC(19,4)` | |
|
|
428
|
+
| `SMALLMONEY` | `NUMERIC(10,4)` | |
|
|
429
|
+
| `DECIMAL(p,s)` | `NUMERIC(p,s)` | |
|
|
430
|
+
| `NVARCHAR(n)` | `VARCHAR(n)` | |
|
|
431
|
+
| `NVARCHAR(MAX)` | `TEXT` | |
|
|
432
|
+
| `VARCHAR(MAX)` | `TEXT` | |
|
|
433
|
+
| `NCHAR(n)` | `CHAR(n)` | |
|
|
434
|
+
| `NTEXT` | `TEXT` | |
|
|
435
|
+
| `DATETIME` | `TIMESTAMPTZ` | |
|
|
436
|
+
| `DATETIME2` | `TIMESTAMPTZ` | |
|
|
437
|
+
| `DATETIMEOFFSET` | `TIMESTAMPTZ` | |
|
|
438
|
+
| `SMALLDATETIME` | `TIMESTAMPTZ` | |
|
|
439
|
+
| `IMAGE` | `BYTEA` | |
|
|
440
|
+
| `VARBINARY(n/MAX)` | `BYTEA` | |
|
|
441
|
+
| `XML` | `XML` | Unchanged |
|
|
442
|
+
| `SQL_VARIANT` | `TEXT` | |
|
|
443
|
+
| `HIERARCHYID` | `TEXT` | |
|
|
444
|
+
| `IDENTITY(1,1)` | `GENERATED BY DEFAULT AS IDENTITY` | Column attribute |
|
|
445
|
+
|
|
446
|
+
## Function Mapping Reference
|
|
447
|
+
|
|
448
|
+
| T-SQL Function | PostgreSQL Equivalent |
|
|
449
|
+
|---------------|----------------------|
|
|
450
|
+
| `ISNULL(a, b)` | `COALESCE(a, b)` |
|
|
451
|
+
| `GETUTCDATE()` | `NOW()` |
|
|
452
|
+
| `GETDATE()` | `NOW()` |
|
|
453
|
+
| `SYSDATETIMEOFFSET()` | `NOW()` |
|
|
454
|
+
| `NEWID()` | `gen_random_uuid()` |
|
|
455
|
+
| `NEWSEQUENTIALID()` | `gen_random_uuid()` |
|
|
456
|
+
| `LEN(s)` | `LENGTH(s)` |
|
|
457
|
+
| `SCOPE_IDENTITY()` | `lastval()` |
|
|
458
|
+
| `SUSER_SNAME()` | `current_user` |
|
|
459
|
+
| `CHARINDEX(sub, str)` | `POSITION(sub IN str)` |
|
|
460
|
+
| `STUFF(s, start, len, repl)` | `OVERLAY(s PLACING repl FROM start FOR len)` |
|
|
461
|
+
| `DATEADD(unit, n, date)` | `(date + n * INTERVAL '1 unit')` |
|
|
462
|
+
| `DATEDIFF(day, start, end)` | `EXTRACT(DAY FROM (end::TIMESTAMPTZ - start::TIMESTAMPTZ))` |
|
|
463
|
+
| `DATEPART(unit, date)` | `EXTRACT(field FROM date)` |
|
|
464
|
+
| `CONVERT(type, expr)` | `CAST(expr AS mapped_type)` |
|
|
465
|
+
| `IIF(cond, t, f)` | `CASE WHEN cond THEN t ELSE f END` |
|
|
466
|
+
| `SELECT TOP N` | `SELECT ... LIMIT N` |
|
|
467
|
+
| `'a' + 'b'` (string concat) | `'a' \|\| 'b'` |
|
|
468
|
+
| `N'text'` | `'text'` (prefix removed) |
|
|
469
|
+
| `RAISERROR(msg, n, n)` | `RAISE EXCEPTION msg` |
|
|
470
|
+
|
|
471
|
+
## ExpressionHelpers
|
|
472
|
+
|
|
473
|
+
Shared expression-level converters used across multiple rules:
|
|
474
|
+
|
|
475
|
+
- **`convertIdentifiers`** -- `[schema].[name]` to `schema."name"`
|
|
476
|
+
- **`convertDateFunctions`** -- DATEADD, DATEDIFF, DATEPART with full unit mapping
|
|
477
|
+
- **`convertCharIndex`** -- 2-arg and 3-arg CHARINDEX
|
|
478
|
+
- **`convertStuff`** -- STUFF to OVERLAY
|
|
479
|
+
- **`convertStringConcat`** -- `+` to `||` for string contexts
|
|
480
|
+
- **`convertIIF`** -- Nested IIF with paren-aware argument splitting
|
|
481
|
+
- **`convertTopToLimit`** -- SELECT TOP N to LIMIT N
|
|
482
|
+
- **`convertCastTypes`** -- CAST AS type mappings
|
|
483
|
+
- **`convertConvertFunction`** -- CONVERT(type, expr) to CAST
|
|
484
|
+
- **`removeNPrefix`** -- N'text' to 'text'
|
|
485
|
+
- **`removeCollate`** -- Remove COLLATE clauses
|
|
486
|
+
- **`convertCommonFunctions`** -- ISNULL, GETUTCDATE, NEWID, LEN, etc.
|
|
487
|
+
- **`quotePascalCaseIdentifiers`** -- Quote PascalCase identifiers while preserving strings and comments
|
|
488
|
+
|
|
489
|
+
## PostProcessor
|
|
490
|
+
|
|
491
|
+
Global cleanup pass applied to the complete output. Key transformations:
|
|
492
|
+
|
|
493
|
+
1. **Bracket cleanup** -- Remove remaining `[brackets]` (preserve PG array access)
|
|
494
|
+
2. **Session control removal** -- SET NOEXEC, SET NUMERIC_ROUNDABORT, SET XACT_ABORT
|
|
495
|
+
3. **RAISERROR** to `RAISE EXCEPTION`
|
|
496
|
+
4. **Type name unquoting** -- `"UUID"` to UUID, `"BOOLEAN"` to BOOLEAN, etc.
|
|
497
|
+
5. **Remaining type conversions** -- nvarchar to VARCHAR, uniqueidentifier to UUID
|
|
498
|
+
6. **Boolean fixes** -- `=(1)` to `=TRUE`, `=(0)` to `=FALSE`
|
|
499
|
+
7. **session_replication_role** -- `'DEFAULT'` to `'origin'`
|
|
500
|
+
8. **PL/pgSQL fixes** -- `END\n$$` to `END;\n$$`, empty BEGIN blocks
|
|
501
|
+
9. **FK clause ordering** -- DEFERRABLE after ON DELETE/UPDATE
|
|
502
|
+
10. **LIKE character classes** -- SQL Server patterns to PG regex
|
|
503
|
+
11. **CHECK constraint fixes** -- `len()` to `LENGTH()`, `isjson()` to JSON validation
|
|
504
|
+
12. **INFORMATION_SCHEMA** -- Force lowercase
|
|
505
|
+
13. **Schema-qualified identifiers** -- Quote unquoted PascalCase after `__mj.`
|
|
506
|
+
14. **ISNULL to COALESCE** -- Final pass
|
|
507
|
+
15. **IF OBJECT_ID DROP** to `DROP ... IF EXISTS`
|
|
508
|
+
16. **GRANT EXEC** to `GRANT EXECUTE` with DO $$ wrapper
|
|
509
|
+
17. **CREATE INDEX** to `CREATE INDEX IF NOT EXISTS`
|
|
510
|
+
18. **Long index names** -- Truncate to 63 chars with MD5 hash suffix
|
|
511
|
+
19. **Backslash line fix** -- Fix lines starting with `\` in INSERT string literals
|
|
512
|
+
20. **Excessive blank lines** -- Collapse 4+ blank lines to 3
|
|
513
|
+
|
|
514
|
+
## Extensibility Architecture
|
|
515
|
+
|
|
516
|
+
The converter is built on three extensible subsystems that enable support for new source/target dialect combinations beyond T-SQL → PostgreSQL.
|
|
517
|
+
|
|
518
|
+
### RuleRegistry
|
|
519
|
+
|
|
520
|
+
Central registry for SQL conversion rules. Supports multiple source→target dialect combinations with case-insensitive dialect lookup and automatic priority sorting.
|
|
521
|
+
|
|
522
|
+
```typescript
|
|
523
|
+
import { RuleRegistry } from '@memberjunction/sql-converter';
|
|
524
|
+
|
|
525
|
+
// Register rules for a dialect pair
|
|
526
|
+
RuleRegistry.RegisterAll(myRules);
|
|
527
|
+
|
|
528
|
+
// Retrieve sorted rules for a dialect pair
|
|
529
|
+
const rules = RuleRegistry.GetRules('tsql', 'postgres');
|
|
530
|
+
|
|
531
|
+
// Check available combinations
|
|
532
|
+
const combos = RuleRegistry.GetRegisteredCombinations();
|
|
533
|
+
// [{ Source: 'tsql', Target: 'postgres' }]
|
|
534
|
+
|
|
535
|
+
// Check if rules exist for a combination
|
|
536
|
+
RuleRegistry.HasRules('tsql', 'mysql'); // false
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
| Method | Description |
|
|
540
|
+
|--------|-------------|
|
|
541
|
+
| `Register(rule)` | Register a single rule for its declared `SourceDialect`/`TargetDialect` |
|
|
542
|
+
| `RegisterAll(rules)` | Register multiple rules at once |
|
|
543
|
+
| `GetRules(source, target)` | Get sorted rules (by priority ascending) for a dialect pair |
|
|
544
|
+
| `GetRegisteredCombinations()` | List all registered `{Source, Target}` pairs |
|
|
545
|
+
| `HasRules(source, target)` | Check if rules exist for a combination |
|
|
546
|
+
| `Clear()` | Clear all rules (for testing) |
|
|
547
|
+
|
|
548
|
+
Rules self-register via `SourceDialect` and `TargetDialect` properties on `IConversionRule`. The registry uses case-insensitive matching and returns rules sorted by `Priority` (ascending).
|
|
549
|
+
|
|
550
|
+
### TypeResolver
|
|
551
|
+
|
|
552
|
+
Centralized SQL type resolution that delegates to `@memberjunction/sql-dialect`'s `DataTypeMap` with MJ-specific overrides. All type mapping in the converter goes through this module so knowledge lives in one place.
|
|
553
|
+
|
|
554
|
+
```typescript
|
|
555
|
+
import { resolveType, parseTypeString } from '@memberjunction/sql-converter';
|
|
556
|
+
|
|
557
|
+
// Parse a SQL type string into components
|
|
558
|
+
const parsed = parseTypeString('NVARCHAR(255)');
|
|
559
|
+
// { BaseName: 'NVARCHAR', Length: 255 }
|
|
560
|
+
|
|
561
|
+
// Resolve a T-SQL type to PostgreSQL
|
|
562
|
+
resolveType('UNIQUEIDENTIFIER'); // 'UUID'
|
|
563
|
+
resolveType('NVARCHAR(MAX)'); // 'TEXT'
|
|
564
|
+
resolveType('DECIMAL(18,2)'); // 'NUMERIC(18,2)'
|
|
565
|
+
resolveType('DATETIME'); // 'TIMESTAMPTZ' (MJ override)
|
|
566
|
+
|
|
567
|
+
// Resolve for inline CAST/CONVERT expressions
|
|
568
|
+
resolveInlineType('DATETIME2(7)'); // 'TIMESTAMPTZ'
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
**MJ-specific overrides** (applied before the dialect TypeMap):
|
|
572
|
+
- `DATETIME`, `DATETIME2`, `SMALLDATETIME` → `TIMESTAMPTZ` (MJ stores everything with timezone)
|
|
573
|
+
- `NTEXT` → `TEXT`
|
|
574
|
+
- `SQL_VARIANT`, `HIERARCHYID` → `TEXT`
|
|
575
|
+
|
|
576
|
+
To add support for a new target dialect, add a new branch in the internal `getTypeMap()` function that constructs the dialect's TypeMap.
|
|
577
|
+
|
|
578
|
+
### DialectHeaderBuilder
|
|
579
|
+
|
|
580
|
+
Pluggable interface for generating dialect-specific output file headers. Each target dialect can register a header builder that produces the preamble needed for the converted SQL file.
|
|
581
|
+
|
|
582
|
+
```typescript
|
|
583
|
+
import { registerHeaderBuilder, getHeaderBuilder, DialectHeaderBuilder } from '@memberjunction/sql-converter';
|
|
584
|
+
|
|
585
|
+
// Built-in: PostgreSQL header builder (auto-registered)
|
|
586
|
+
const pgBuilder = getHeaderBuilder('postgres');
|
|
587
|
+
const header = pgBuilder?.BuildHeader('__mj');
|
|
588
|
+
// Generates: CREATE EXTENSION, CREATE SCHEMA, SET search_path, implicit int->bool cast
|
|
589
|
+
|
|
590
|
+
// Register a custom builder for a new dialect
|
|
591
|
+
class MySQLHeaderBuilder implements DialectHeaderBuilder {
|
|
592
|
+
readonly TargetDialect = 'mysql';
|
|
593
|
+
BuildHeader(schema: string): string {
|
|
594
|
+
return `SET NAMES utf8mb4;\nCREATE SCHEMA IF NOT EXISTS \`${schema}\`;\nUSE \`${schema}\`;\n`;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
registerHeaderBuilder(new MySQLHeaderBuilder());
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
The built-in `PostgreSQLHeaderBuilder` generates:
|
|
601
|
+
- `CREATE EXTENSION` for pgcrypto and uuid-ossp
|
|
602
|
+
- Schema creation and `SET search_path`
|
|
603
|
+
- `SET standard_conforming_strings = on`
|
|
604
|
+
- Implicit `INTEGER → BOOLEAN` cast upgrade (for SQL Server BIT compatibility)
|
|
605
|
+
|
|
606
|
+
## Extending the Pipeline
|
|
607
|
+
|
|
608
|
+
### Adding a New Rule (Existing Dialect Pair)
|
|
609
|
+
|
|
610
|
+
1. Create a new file in `src/rules/`:
|
|
611
|
+
|
|
612
|
+
```typescript
|
|
613
|
+
import type { IConversionRule, ConversionContext, StatementType } from './types.js';
|
|
614
|
+
|
|
615
|
+
export class MyNewRule implements IConversionRule {
|
|
616
|
+
Name = 'MyNewRule';
|
|
617
|
+
SourceDialect = 'tsql';
|
|
618
|
+
TargetDialect = 'postgres';
|
|
619
|
+
AppliesTo: StatementType[] = ['SOME_TYPE'];
|
|
620
|
+
Priority = 65; // Between existing rules
|
|
621
|
+
BypassSqlglot = true;
|
|
622
|
+
|
|
623
|
+
PostProcess(sql: string, originalSQL: string, context: ConversionContext): string {
|
|
624
|
+
// Your conversion logic here
|
|
625
|
+
return convertedSQL;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
2. Register it in `TSQLToPostgresRules.ts`:
|
|
631
|
+
|
|
632
|
+
```typescript
|
|
633
|
+
import { MyNewRule } from './MyNewRule.js';
|
|
634
|
+
|
|
635
|
+
export function getTSQLToPostgresRules(): IConversionRule[] {
|
|
636
|
+
return [
|
|
637
|
+
// ... existing rules
|
|
638
|
+
new MyNewRule(), // Insert at correct priority position
|
|
639
|
+
];
|
|
640
|
+
}
|
|
641
|
+
```
|
|
642
|
+
|
|
643
|
+
3. Add tests in `src/__tests__/MyNewRule.test.ts`
|
|
644
|
+
|
|
645
|
+
### Adding Rules for a New Dialect Direction
|
|
646
|
+
|
|
647
|
+
To support a new conversion direction (e.g., T-SQL → MySQL):
|
|
648
|
+
|
|
649
|
+
1. **Create rules** implementing `IConversionRule` with `SourceDialect = 'tsql'` and `TargetDialect = 'mysql'`
|
|
650
|
+
2. **Register rules** with `RuleRegistry.RegisterAll(myMySQLRules)`
|
|
651
|
+
3. **Add a TypeMap** branch in `TypeResolver.getTypeMap()` for the new target dialect
|
|
652
|
+
4. **Register a DialectHeaderBuilder** for the new target via `registerHeaderBuilder()`
|
|
653
|
+
5. **Create a convenience function** like `getTSQLToMySQLRules()` for easy consumption
|
|
654
|
+
|
|
655
|
+
### Adding New Type Mappings
|
|
656
|
+
|
|
657
|
+
Update type mappings in:
|
|
658
|
+
- `TypeResolver` -- centralized type resolution (preferred for new dialects)
|
|
659
|
+
- `CreateTableRule` -- for CREATE TABLE column types
|
|
660
|
+
- `ExpressionHelpers.convertCastTypes()` -- for CAST expressions
|
|
661
|
+
- `ExpressionHelpers.convertConvertFunction()` -- for CONVERT() function
|
|
662
|
+
- `PostProcessor.postProcess()` -- for final cleanup pass
|
|
663
|
+
|
|
664
|
+
## Verification & Cross-Database Audit
|
|
665
|
+
|
|
666
|
+
### Database Verification
|
|
667
|
+
|
|
668
|
+
```typescript
|
|
669
|
+
import { ConversionPipeline } from '@memberjunction/sql-converter';
|
|
670
|
+
|
|
671
|
+
const result = await new ConversionPipeline().Run({
|
|
672
|
+
source: 'input.sql',
|
|
673
|
+
sourceIsFile: true,
|
|
674
|
+
sourceDialect: 'tsql',
|
|
675
|
+
targetDialect: 'postgres',
|
|
676
|
+
verify: true,
|
|
677
|
+
targetConnection: 'postgresql://user:pass@localhost:5432/testdb',
|
|
678
|
+
});
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
### Audit Command
|
|
682
|
+
|
|
683
|
+
```bash
|
|
684
|
+
npx mj sql-audit --source-connection "mssql://..." --target-connection "postgresql://..." --schema __mj
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
Compares source and target databases:
|
|
688
|
+
- Missing objects (tables, views, functions, triggers, indexes)
|
|
689
|
+
- Row count mismatches
|
|
690
|
+
|
|
691
|
+
## Testing
|
|
692
|
+
|
|
693
|
+
### Running Tests
|
|
694
|
+
|
|
695
|
+
```bash
|
|
696
|
+
# All tests
|
|
697
|
+
cd packages/SQLConverter && npm run test
|
|
698
|
+
|
|
699
|
+
# Watch mode
|
|
700
|
+
cd packages/SQLConverter && npm run test:watch
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
### Test Organization
|
|
704
|
+
|
|
705
|
+
```
|
|
706
|
+
src/__tests__/
|
|
707
|
+
StatementClassifier.test.ts # 60+ tests
|
|
708
|
+
SubSplitter.test.ts # 13 tests
|
|
709
|
+
ExpressionHelpers.test.ts # 100+ tests
|
|
710
|
+
BatchConverter.test.ts # 22 tests
|
|
711
|
+
PostProcessor.test.ts # 50+ tests
|
|
712
|
+
SQLFileSplitter.test.ts # 24 tests
|
|
713
|
+
DatabaseAuditor.test.ts # 12 tests
|
|
714
|
+
CreateTableRule.test.ts # 31 tests
|
|
715
|
+
ViewRule.test.ts # 15 tests
|
|
716
|
+
ProcedureToFunctionRule.test.ts # 48 tests
|
|
717
|
+
FunctionRule.test.ts # 20+ tests
|
|
718
|
+
TriggerRule.test.ts # 13 tests
|
|
719
|
+
InsertRule.test.ts # 20 tests
|
|
720
|
+
AlterTableRule.test.ts # 13 tests
|
|
721
|
+
ConditionalDDLRule.test.ts # 20+ tests
|
|
722
|
+
CreateIndexRule.test.ts # 15+ tests
|
|
723
|
+
GrantRule.test.ts # 15+ tests
|
|
724
|
+
ExtendedPropertyRule.test.ts # 8 tests
|
|
725
|
+
TSQLToPostgresRules.test.ts # 10+ tests
|
|
726
|
+
ConversionPipeline.test.ts # 14 tests
|
|
727
|
+
integration.test.ts # Full pipeline against real PG
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
### Adding Test Cases
|
|
731
|
+
|
|
732
|
+
Follow the established pattern:
|
|
733
|
+
|
|
734
|
+
```typescript
|
|
735
|
+
import { describe, it, expect } from 'vitest';
|
|
736
|
+
import { MyRule } from '../rules/MyRule.js';
|
|
737
|
+
import { createConversionContext } from '../rules/types.js';
|
|
738
|
+
|
|
739
|
+
const rule = new MyRule();
|
|
740
|
+
const context = createConversionContext('tsql', 'postgres');
|
|
741
|
+
|
|
742
|
+
function convert(sql: string): string {
|
|
743
|
+
return rule.PostProcess!(sql, sql, context);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
describe('MyRule', () => {
|
|
747
|
+
describe('metadata', () => {
|
|
748
|
+
it('should have the correct name, priority, and applies-to types', () => {
|
|
749
|
+
expect(rule.Name).toBe('MyRule');
|
|
750
|
+
expect(rule.Priority).toBe(65);
|
|
751
|
+
});
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
describe('feature area', () => {
|
|
755
|
+
it('should convert X to Y', () => {
|
|
756
|
+
const result = convert('INPUT SQL');
|
|
757
|
+
expect(result).toContain('EXPECTED OUTPUT');
|
|
758
|
+
});
|
|
759
|
+
});
|
|
760
|
+
});
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
## Dependencies
|
|
764
|
+
|
|
765
|
+
- **`@memberjunction/sqlglot-ts`** -- Python sqlglot wrapper for transpilation fallback
|
|
766
|
+
- **`pg`** (dev) -- PostgreSQL client for integration tests
|
|
767
|
+
- **`vitest`** (dev) -- Test framework
|
|
768
|
+
|
|
769
|
+
## License
|
|
770
|
+
|
|
771
|
+
ISC
|