NagaPrajwalith commited on
Commit
bc3415e
·
verified ·
1 Parent(s): 6475e8a

Upload index.html

Browse files
Files changed (1) hide show
  1. index.html +594 -0
index.html ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
6
+ <title>Teradata → Databricks DDL Converter</title>
7
+ <style>
8
+ :root { --bg:#0b1020; --card:#111934; --ink:#eaf0ff; --muted:#9fb2ff; --accent:#7aa2ff; --ok:#35c88a; --warn:#f5c451; --err:#ff6b6b; }
9
+ body { margin:0; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial; background:var(--bg); color:var(--ink); }
10
+ header { padding:20px 24px; border-bottom:1px solid #1d2750; display:flex; justify-content:space-between; align-items:center; }
11
+ h1 { font-size:18px; margin:0; letter-spacing:0.3px;}
12
+ .wrap { max-width:1200px; margin:24px auto; padding:0 16px; display:grid; gap:16px; grid-template-columns: 1fr 1fr; }
13
+ .card { background:var(--card); border:1px solid #1d2750; border-radius:12px; padding:16px; }
14
+ .card h2 { margin:0 0 10px 0; font-size:15px; color:var(--muted); }
15
+ textarea, select, input[type="text"] { width:100%; background:#0c1430; color:var(--ink); border:1px solid #1d2750; border-radius:10px; padding:12px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; font-size:13px; }
16
+ textarea { min-height:240px; resize:vertical; }
17
+ .row { display:grid; grid-template-columns: 1fr 1fr; gap:12px; margin:10px 0 0 0; }
18
+ .pill { display:inline-flex; align-items:center; gap:8px; padding:6px 10px; border:1px solid #26357a; border-radius:999px; color:var(--muted); font-size:12px; background:#0c1430; }
19
+ .btnbar { display:flex; gap:10px; flex-wrap:wrap; }
20
+ button { background:var(--accent); color:#081028; border:0; padding:10px 14px; border-radius:10px; font-weight:600; cursor:pointer; }
21
+ button.secondary { background:#172556; color:var(--ink); border:1px solid #2b3c84; }
22
+ button.ghost { background:transparent; color:var(--muted); border:1px dashed #35489a; }
23
+ pre { white-space:pre-wrap; word-wrap:break-word; background:#0c1430; border:1px solid #1d2750; border-radius:10px; padding:12px; font-size:12.5px; }
24
+ .tag { font-size:12px; padding:2px 8px; border-radius:999px; border:1px solid #26357a; background:#0c1430; color:var(--muted); }
25
+ .ok { color:var(--ok); }
26
+ .warn { color:var(--warn); }
27
+ .err { color:var(--err); }
28
+ .small { font-size:12px; color:var(--muted); }
29
+ .grid-3 { display:grid; grid-template-columns: repeat(3,1fr); gap:10px; }
30
+ .foot { text-align:center; color:var(--muted); padding:12px 0 24px; font-size:12px; }
31
+ a { color:#bcd2ff; }
32
+ .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; }
33
+ .hint { margin-top:8px; font-size:12px; color:var(--muted); }
34
+ .grant-card { border-color:#26357a; }
35
+ .grant-card h2 { color:#a78bfa; }
36
+ .grant-toggle { cursor:pointer; user-select:none; display:flex; align-items:center; gap:8px; }
37
+ .grant-toggle::before { content:'▶'; font-size:10px; transition:transform .2s; }
38
+ .grant-toggle.open::before { transform:rotate(90deg); }
39
+ .grant-body { display:none; margin-top:10px; }
40
+ .grant-body.open { display:block; }
41
+ textarea.grant-tpl { min-height:120px; font-size:12px; }
42
+ pre.grant-out { max-height:350px; overflow:auto; }
43
+ </style>
44
+ </head>
45
+ <body>
46
+ <header>
47
+ <h1>Teradata → Databricks DDL Converter</h1>
48
+ <div class="pill">Heuristics-based recommendation • Delta best practices</div>
49
+ </header>
50
+
51
+ <div class="wrap">
52
+ <div class="card">
53
+ <h2>1) Paste Teradata DDL</h2>
54
+ <textarea id="input" placeholder="Paste Teradata CREATE TABLE/VIEW DDL here…"></textarea>
55
+ <div class="row">
56
+ <div>
57
+ <label class="small">Environment</label>
58
+ <select id="ddlEnv">
59
+ <option value="dev">dev — uc_dev_apac_mdip_01</option>
60
+ <option value="qa">qa — uc_qa_apac_mdip_01</option>
61
+ <option value="prod">prod — uc_prod_apac_mdip_01</option>
62
+ </select>
63
+ </div>
64
+ <div style="display:flex;align-items:end;">
65
+ <span class="tag" id="ddlPreviewTag" style="color:var(--accent);border-color:var(--accent);">Paste DDL to auto-detect schema.table</span>
66
+ </div>
67
+ </div>
68
+ <div class="row">
69
+ <div>
70
+ <label class="small">Recommendation mode</label>
71
+ <select id="recoMode">
72
+ <option value="auto">Auto (analyze & decide)</option>
73
+ <option value="delta">Force Delta table</option>
74
+ <option value="parquet">Force Standard (Parquet) table</option>
75
+ <option value="view">Force View</option>
76
+ </select>
77
+ </div>
78
+ <div>
79
+ <label class="small">Text handling</label>
80
+ <select id="textMode">
81
+ <option value="string">Map CHAR/VARCHAR → STRING (safer)</option>
82
+ <option value="varchar">Keep VARCHAR/CHAR with lengths (ANSI)</option>
83
+ </select>
84
+ </div>
85
+ </div>
86
+ <div class="grid-3" style="margin-top:10px;">
87
+ <label><input id="useCluster" type="checkbox" checked> Use <span class="mono">CLUSTER BY</span> for TD PI/partition</label>
88
+ <label><input id="usePartition" type="checkbox"> Use <span class="mono">PARTITIONED BY</span> instead (big shards)</label>
89
+ <label><input id="emitConstraints" type="checkbox" checked> Emit PK/UNIQUE as NOT ENFORCED</label>
90
+ </div>
91
+ <div class="hint">Tip: If both “Use CLUSTER BY” and “Use PARTITIONED BY” are checked, PARTITIONED BY wins (and CLUSTER BY is added as a comment).</div>
92
+ <div style="margin-top:12px" class="btnbar">
93
+ <button id="convertBtn">Convert</button>
94
+ <button class="secondary" id="sampleBtn">Load sample TD DDL</button>
95
+ <button class="ghost" id="clearBtn">Clear</button>
96
+ </div>
97
+ </div>
98
+
99
+ <div class="card">
100
+ <h2>2) Output — Databricks DDL</h2>
101
+ <div class="row">
102
+ <span class="tag" id="detectedTag">Detected: —</span>
103
+ <span class="tag" id="recommendTag">Recommendation: —</span>
104
+ </div>
105
+ <div style="margin-top:10px;" class="btnbar">
106
+ <button id="downloadSql">Download SQL</button>
107
+ <button class="secondary" id="downloadExplain">Download Explanation</button>
108
+ <button class="ghost" id="copySql">Copy SQL</button>
109
+ </div>
110
+ <pre id="sqlOut" style="margin-top:10px;"></pre>
111
+ </div>
112
+
113
+ <div class="card" style="grid-column:1 / -1;">
114
+ <h2 class="grant-toggle" id="whyToggle" onclick="el('whyToggle').classList.toggle('open'); el('whyBody').classList.toggle('open');">3) What I did & why — click to view</h2>
115
+ <div class="grant-body" id="whyBody">
116
+ <pre id="why"></pre>
117
+ </div>
118
+ </div>
119
+
120
+ <div class="card grant-card" style="grid-column:1 / -1;">
121
+ <h2>4) GRANT Statements</h2>
122
+ <div class="row" style="margin-bottom:10px;">
123
+ <div>
124
+ <label class="small">Environment</label>
125
+ <select id="grantEnv">
126
+ <option value="dev">dev — uc_dev_apac_mdip_01</option>
127
+ <option value="qa">qa — uc_qa_apac_mdip_01</option>
128
+ <option value="prod">prod — uc_prod_apac_mdip_01</option>
129
+ </select>
130
+ </div>
131
+ <div style="display:flex;align-items:end;">
132
+ <span class="tag" id="grantCatalogTag" style="color:#a78bfa;border-color:#a78bfa55;">Catalog: uc_dev_apac_mdip_01</span>
133
+ </div>
134
+ </div>
135
+ <div class="grant-toggle" id="grantToggle" onclick="toggleGrantTpl()">Customize grant template</div>
136
+ <div class="grant-body" id="grantTplBody">
137
+ <label class="small">TABLE grant template (use <code style="color:var(--accent)">table_name</code> as placeholder)</label>
138
+ <textarea class="grant-tpl" id="tableGrantTpl">GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIP.Core.Team`;
139
+ GRANT SELECT, MODIFY ON TABLE table_name TO `svciscpkpi@pepsico.com`;
140
+ GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer`;
141
+ GRANT SELECT, MODIFY ON TABLE table_name TO `svcCViscpkrptprd@pepsico.com`;
142
+ GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.PBNA.TDQKETSPROD.ADB`;
143
+ GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.PBNA.TDQKETS.ADB`;
144
+ GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader`;
145
+ GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor`;</textarea>
146
+ <div style="margin-top:10px;">
147
+ <label class="small">VIEW grant template (use <code style="color:var(--accent)">view_name</code> as placeholder)</label>
148
+ <textarea class="grant-tpl" id="viewGrantTpl">GRANT SELECT ON VIEW view_name TO `Team.App.MDIP.Core.Team`;
149
+ GRANT SELECT ON VIEW view_name TO `svciscpkpi@pepsico.com`;
150
+ GRANT SELECT ON VIEW view_name TO `Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer`;
151
+ GRANT SELECT ON VIEW view_name TO `svcCViscpkrptprd@pepsico.com`;
152
+ GRANT SELECT ON VIEW view_name TO `Team.App.PBNA.TDQKETSPROD.ADB`;
153
+ GRANT SELECT ON VIEW view_name TO `Team.App.PBNA.TDQKETS.ADB`;
154
+ GRANT SELECT ON VIEW view_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader`;
155
+ GRANT SELECT ON VIEW view_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor`;</textarea>
156
+ </div>
157
+ </div>
158
+ <div style="margin-top:10px;" class="btnbar">
159
+ <button class="ghost" id="copyGrants">Copy Grants</button>
160
+ <button class="secondary" id="downloadGrants">Download Grants SQL</button>
161
+ </div>
162
+ <pre class="grant-out" id="grantOut" style="margin-top:10px;"></pre>
163
+ </div>
164
+ </div>
165
+
166
+ <div class="foot">Built for robust Teradata → Databricks migrations. No servers, no dependencies.</div>
167
+
168
+ <script>
169
+ /* ===== Utilities ===== */
170
+ function dl(filename, text) {
171
+ const a = document.createElement('a');
172
+ a.setAttribute('href','data:text/plain;charset=utf-8,'+encodeURIComponent(text));
173
+ a.setAttribute('download', filename);
174
+ a.style.display='none';
175
+ document.body.appendChild(a); a.click(); document.body.removeChild(a);
176
+ }
177
+ function copy(text){ navigator.clipboard.writeText(text||''); }
178
+
179
+ /* ===== Core parsing & mapping ===== */
180
+ const TD_TYPES = [
181
+ 'BYTEINT','SMALLINT','INTEGER','INT','BIGINT',
182
+ 'DECIMAL','NUMERIC','NUMBER',
183
+ 'FLOAT','REAL','DOUBLE','DOUBLE PRECISION',
184
+ 'CHAR','VARCHAR','CLOB','BLOB','VARBYTE','BYTE','LONG VARGRAPHIC','GRAPHIC','VARGRAPHIC',
185
+ 'DATE','TIME','TIMESTAMP','INTERVAL',
186
+ 'BYTE','VARBYTE'
187
+ ];
188
+
189
+ // Map TD data types to Databricks types
190
+ function mapType(tdTypeRaw, textMode, why) {
191
+ const t = tdTypeRaw.trim().replace(/\s+/g,' ').toUpperCase();
192
+ const len = (t.match(/\(([^)]+)\)/)?.[1] || '').trim();
193
+ const base = t.replace(/\(([^)]+)\)/,'').replace(/ CHARACTER SET .+$/,'').replace(/ NOT CASESPECIFIC/g,'').trim();
194
+
195
+ // Note charset/casespecific
196
+ if (/CHARACTER SET\s+UNICODE/i.test(tdTypeRaw)) {
197
+ why.push(`- Found UNICODE charset → Databricks strings are UTF-8 natively; dropping charset clause.`);
198
+ }
199
+ if (/NOT CASESPECIFIC/i.test(tdTypeRaw)) {
200
+ why.push(`- Found NOT CASESPECIFIC → Databricks collations differ; treating as regular text (case-insensitivity handled differently).`);
201
+ }
202
+
203
+ // Numerics
204
+ if (base === 'BYTEINT') return 'TINYINT';
205
+ if (base === 'SMALLINT') return 'SMALLINT';
206
+ if (base === 'INTEGER' || base === 'INT') return 'INT';
207
+ if (base === 'BIGINT') return 'BIGINT';
208
+ if (base === 'DECIMAL' || base === 'NUMERIC' || base === 'NUMBER') {
209
+ const [p,s] = len ? len.split(',').map(x=>x.trim()) : [];
210
+ if (p) return `DECIMAL(${p}${s?','+s:''})`;
211
+ if (base === 'NUMBER') { why.push(`- NUMBER without precision → mapped to INT.`); return 'INT'; }
212
+ return 'DECIMAL(38,18)';
213
+ }
214
+ if (base === 'FLOAT' || base === 'REAL' || base === 'DOUBLE' || base === 'DOUBLE PRECISION') return 'DOUBLE';
215
+
216
+ // Binary / LOB
217
+ if (base === 'BLOB' || base === 'VARBYTE' || base === 'BYTE') return 'BINARY';
218
+
219
+ // Date/Time
220
+ if (base === 'DATE') return 'DATE';
221
+ if (base === 'TIME') { why.push(`- TD TIME mapped to STRING (Databricks TIME exists but portability varies).`); return 'STRING'; }
222
+ if (base.startsWith('TIMESTAMP')) return 'TIMESTAMP'; // drop timezone/format
223
+ if (base.startsWith('INTERVAL')) { why.push(`- TD INTERVAL mapped to STRING (re-model as INT seconds or INTERVAL arithmetic post-load).`); return 'STRING'; }
224
+
225
+ // Textual
226
+ if (base === 'CLOB') return 'STRING';
227
+ if (base === 'CHAR' || base === 'VARCHAR' || base==='GRAPHIC' || base==='VARGRAPHIC' || base==='LONG VARGRAPHIC') {
228
+ if (textMode === 'varchar') {
229
+ const n = (len || '65535').replace(/\s/g,'');
230
+ return `${base==='CHAR'?'CHAR':'VARCHAR'}(${n})`;
231
+ }
232
+ return 'STRING';
233
+ }
234
+
235
+ // Fallback
236
+ why.push(`- Unmapped type "${tdTypeRaw.trim()}" → defaulting to STRING.`);
237
+ return 'STRING';
238
+ }
239
+
240
+ // Try to extract object kind, name, columns, constraints, PI, partitions
241
+ function parseTeradata(ddl) {
242
+ const out = { kind:'unknown', name:'', schema:'', columns:[], constraints:[], primaryIndex:[], partitionBy:[], raw:ddl };
243
+
244
+ // Normalize
245
+ const src = ddl.replace(/--.*$/mg,'').replace(/\/\*[\s\S]*?\*\//g,'').trim();
246
+ const head = src.slice(0, 512).toUpperCase();
247
+
248
+ // Kind detection
249
+ if (/(?:CREATE|REPLACE)\s+VIEW/i.test(src)) out.kind = 'view';
250
+ else if (/CREATE\s+(MULTISET|SET)?\s*VOLATILE\s+TABLE/i.test(src)) out.kind = 'volatile';
251
+ else if (/CREATE\s+(MULTISET|SET)?\s*TABLE/i.test(src)) out.kind = 'table';
252
+
253
+ // Name
254
+ const nameMatch = src.match(/(?:CREATE|REPLACE)\s+(?:MULTISET|SET)?\s*(?:VOLATILE\s+)?(?:TABLE|VIEW)\s+([A-Za-z0-9_$."]+)/i);
255
+ if (nameMatch) {
256
+ const fq = nameMatch[1].replace(/"/g,'');
257
+ out.fqName = fq;
258
+ const parts = fq.split('.');
259
+ out.name = parts.pop();
260
+ out.schema = parts.join('.');
261
+ }
262
+
263
+ // Column list (naive but robust for most TD DDL)
264
+ const colBlockMatch = src.match(/\(([\s\S]*?)\)\s*(?:PRIMARY\s+INDEX|UNIQUE\s+PRIMARY\s+INDEX|PARTITION\s+BY|WITH\s+DATA|ON\s+COMMIT|;)/i) ||
265
+ src.match(/\(([\s\S]*?)\)/);
266
+ if (colBlockMatch) {
267
+ const colBlock = colBlockMatch[1];
268
+ // split by commas not inside parentheses
269
+ const parts = [];
270
+ let buf='', depth=0;
271
+ for (let c of colBlock) {
272
+ if (c==='(') depth++;
273
+ if (c===')') depth--;
274
+ if (c===',' && depth===0) { parts.push(buf); buf=''; }
275
+ else buf += c;
276
+ }
277
+ if (buf.trim()) parts.push(buf);
278
+
279
+ for (const p of parts) {
280
+ const line = p.trim();
281
+ if (!line) continue;
282
+ // Constraint lines (PRIMARY KEY, UNIQUE, CHECK, FOREIGN KEY)
283
+ if (/^(PRIMARY|UNIQUE|CHECK|FOREIGN)\b/i.test(line)) {
284
+ out.constraints.push(line.replace(/\s+/g,' ').trim());
285
+ continue;
286
+ }
287
+ const m = line.match(/^("[^"]+"|[A-Za-z0-9_]+)\s+(.+)$/);
288
+ if (m) {
289
+ const rawName = m[1].trim();
290
+ const hasSpaces = rawName.startsWith('"') && rawName.includes(' ');
291
+ const colName = rawName.replace(/"/g,'');
292
+ const typeAndRest = m[2].trim();
293
+ out.columns.push({ name: colName, tdType: typeAndRest, needsQuoting: hasSpaces });
294
+ }
295
+ }
296
+ }
297
+
298
+ // PI / PARTITION BY
299
+ const piMatch = src.match(/(?:UNIQUE\s+)?PRIMARY\s+INDEX\s*\(([^)]+)\)/i);
300
+ if (piMatch) out.primaryIndex = piMatch[1].split(',').map(s=>s.trim().replace(/"/g,''));
301
+ const partMatch = src.match(/PARTITION\s+BY\s*\(([^)]+)\)/i) || src.match(/PARTITION\s+BY\s+([^\n;]+)/i);
302
+ if (partMatch) out.partitionBy = [partMatch[1].trim()];
303
+
304
+ // Unique/PK constraints elsewhere
305
+ const pkMatch = src.match(/PRIMARY\s+KEY\s*\(([^)]+)\)/i);
306
+ if (pkMatch) out.constraints.push(`PRIMARY KEY (${pkMatch[1]})`);
307
+ const uqMatches = [...src.matchAll(/UNIQUE\s*\(([^)]+)\)/ig)];
308
+ uqMatches.forEach(m=>out.constraints.push(`UNIQUE (${m[1]})`));
309
+
310
+ return out;
311
+ }
312
+
313
+ // Heuristic recommendation
314
+ function recommend(out, mode, why) {
315
+ if (mode !== 'auto') return mode;
316
+ if (out.kind === 'view') return 'view';
317
+ if (out.kind === 'volatile') {
318
+ why.push(`- Volatile table detected → Recommend Delta (temporary analogs are views/temp tables at runtime).`);
319
+ return 'delta';
320
+ }
321
+ // Table heuristics
322
+ const hasKeys = out.constraints.some(c=>/PRIMARY\s+KEY|UNIQUE/i.test(c));
323
+ const mayUpsert = /JOURNAL|FALLBACK|MERGEBLOCKRATIO|MAP\s*=|CHECKSUM/i.test(out.raw);
324
+ const hasPkIdx = out.primaryIndex.length>0;
325
+ // Prefer Delta when:
326
+ if (hasKeys || mayUpsert || hasPkIdx) {
327
+ why.push(`- Keys/PI or TD features implying updates/merges found → Recommend Delta for ACID & MERGE.`);
328
+ return 'delta';
329
+ }
330
+ // Default to Delta anyway (Databricks default & governance)
331
+ why.push(`- No strong signals for Parquet-only; defaulting to Delta for governance, schema evolution, and deletes/merges.`);
332
+ return 'delta';
333
+ }
334
+
335
+ function toDatabricks(out, targetNs, targetName, choice, opts) {
336
+ const why = [];
337
+ const textMode = opts.textMode;
338
+ const emitConstraints = opts.emitConstraints;
339
+ const usePartition = opts.usePartition;
340
+ const useCluster = opts.useCluster;
341
+
342
+ let finalName = (targetName||out.name||'converted_object');
343
+ let fqTarget = targetNs ? `${targetNs}.${finalName}` : finalName;
344
+
345
+ if (out.kind === 'view' || choice === 'view') {
346
+ // Attempt to capture SELECT
347
+ const selMatch = out.raw.match(/AS\s+([\s\S]+)$/i);
348
+ let selectSql = selMatch ? selMatch[1].trim().replace(/;+\s*$/,'') : '-- TODO: Provide SELECT body';
349
+ selectSql = selectSql.replace(/LOCKING\s+ROW\s+FOR\s+ACCESS\s*/gi, '');
350
+ why.push(`- Object is a VIEW → emitting CREATE VIEW IF NOT EXISTS with original SELECT.`);
351
+ if (/LOCKING\s+ROW/i.test(out.raw)) why.push(`- Removed TD "LOCKING ROW FOR ACCESS" (not applicable in Databricks).`);
352
+ const sql = `CREATE VIEW IF NOT EXISTS ${fqTarget} AS
353
+ ${selectSql};`;
354
+ return { sql, why, detected:`VIEW (${out.fqName||out.name||''})`, recommendation:'VIEW' };
355
+ }
356
+
357
+ // Table path
358
+ const cols = out.columns.map(c=>{
359
+ const notnull = /NOT\s+NULL/i.test(c.tdType);
360
+ const tdTypeOnly = c.tdType.replace(/\s+NOT\s+NULL/gi,'').replace(/\s+DEFAULT\s+.+$/i,'').replace(/FORMAT\s+'[^']+'/i,'').replace(/\s+CASESPECIFIC/ig,'').trim();
361
+ const mapped = mapType(tdTypeOnly, textMode, why);
362
+ const colRef = c.needsQuoting ? '`' + c.name + '`' : c.name;
363
+ return ` ${colRef} ${mapped}${notnull?' NOT NULL':''}`;
364
+ });
365
+
366
+ // Table properties for Delta
367
+ const deltaProps = [
368
+ `'delta.autoOptimize.optimizeWrite' = 'true'`,
369
+ `'delta.autoOptimize.autoCompact' = 'true'`,
370
+ `'delta.enableDeletionVectors' = 'true'`,
371
+ `'delta.minReaderVersion' = '3'`,
372
+ `'delta.minWriterVersion' = '7'`,
373
+ `'delta.logRetentionDuration' = '30 days'`,
374
+ `'delta.columnMapping.mode' = 'name'`,
375
+ `'delta.feature.columnMapping' = 'supported'`,
376
+ `'delta.feature.deletionVectors' = 'supported'`,
377
+ `'delta.deletedFileRetentionDuration' = '30 days'`
378
+ ];
379
+
380
+ let body = '';
381
+ let extras = [];
382
+
383
+ // Constraints
384
+ const constraints = [];
385
+ for (const c of out.constraints) {
386
+ if (/PRIMARY\s+KEY\s*\(([^)]+)\)/i.test(c)) {
387
+ const cols = c.match(/\(([^)]+)\)/)[1].split(',').map(x=>x.trim()).join(', ');
388
+ if (emitConstraints) constraints.push(` CONSTRAINT pk_${finalName} PRIMARY KEY (${cols}) NOT ENFORCED`);
389
+ else extras.push(`-- TD PRIMARY KEY(${cols}) → informational only in Databricks`);
390
+ } else if (/UNIQUE\s*\(([^)]+)\)/i.test(c)) {
391
+ const cols = c.match(/\(([^)]+)\)/)[1].split(',').map(x=>x.trim()).join(', ');
392
+ if (emitConstraints) constraints.push(` CONSTRAINT uq_${finalName}_${Math.random().toString(36).slice(2,6)} UNIQUE (${cols}) NOT ENFORCED`);
393
+ else extras.push(`-- TD UNIQUE(${cols}) → record preserved as comment`);
394
+ } else if (/CHECK|FOREIGN\s+KEY/i.test(c)) {
395
+ extras.push(`-- Constraint preserved: ${c}`);
396
+ }
397
+ }
398
+
399
+ // Partition/Cluster mapping from TD PRIMARY INDEX / PARTITION BY
400
+ let partClause = '';
401
+ let clusterClause = '';
402
+ if (out.primaryIndex.length) {
403
+ if (usePartition) {
404
+ partClause = `\nPARTITIONED BY (${out.primaryIndex.join(', ')})`;
405
+ extras.push(`-- TD PRIMARY INDEX mapped to PARTITIONED BY; consider CLUSTER BY for skewed keys.`);
406
+ } else if (useCluster) {
407
+ clusterClause = `\nCLUSTER BY (${out.primaryIndex.join(', ')})`;
408
+ extras.push(`-- TD PRIMARY INDEX → CLUSTER BY (improves locality for joins & filters).`);
409
+ } else {
410
+ extras.push(`-- TD PRIMARY INDEX detected: (${out.primaryIndex.join(', ')})`);
411
+ }
412
+ }
413
+ if (out.partitionBy.length) {
414
+ extras.push(`-- TD PARTITION BY detected: ${out.partitionBy.join(' | ')} (manual translation to Delta partitioning may be required).`);
415
+ }
416
+
417
+ // Choice
418
+ let recommendation = '';
419
+ if (choice === 'delta') {
420
+ recommendation = 'DELTA TABLE';
421
+ body = `CREATE TABLE IF NOT EXISTS ${fqTarget} (
422
+ ${cols.concat(constraints).join(',\n')}
423
+ )
424
+ USING DELTA${partClause}${clusterClause}
425
+ TBLPROPERTIES (
426
+ ${deltaProps.join(',\n ')}
427
+ );`;
428
+ why.push(`- Using Delta for ACID, MERGE/DELETE, schema evolution, OPTIMIZE/ZORDER support.`);
429
+ } else {
430
+ recommendation = 'STANDARD (PARQUET) TABLE';
431
+ body = `CREATE TABLE IF NOT EXISTS ${fqTarget} (
432
+ ${cols.join(',\n')}
433
+ )
434
+ USING PARQUET${partClause}${clusterClause};`;
435
+ if (constraints.length) extras.push(`-- Constraints not emitted for PARQUET; consider Delta if you need constraints/merges.`);
436
+ why.push(`- Using PARQUET only (no Delta features). Suitable for simple append-only staging.`)
437
+ }
438
+
439
+ const sql = [body].concat(extras.length?['\n'+extras.join('\n')]:[]).join('\n');
440
+ const detected = `${(out.kind||'TABLE').toUpperCase()} ${out.fqName?('('+out.fqName+')'):''}`;
441
+
442
+ return { sql, why, detected, recommendation };
443
+ }
444
+
445
+ /* ===== UI glue ===== */
446
+ const el = id=>document.getElementById(id);
447
+ const ENV_CATALOGS = { dev: 'uc_dev_apac_mdip_01', qa: 'uc_qa_apac_mdip_01', prod: 'uc_prod_apac_mdip_01' };
448
+
449
+ let detectedSchema = '';
450
+ let detectedName = '';
451
+
452
+ function autoDetectFromDDL() {
453
+ const ddl = el('input').value;
454
+ const m = ddl.match(/(?:CREATE|REPLACE)\s+(?:MULTISET|SET)?\s*(?:VOLATILE\s+)?(?:TABLE|VIEW)\s+([A-Za-z0-9_$."]+)/i);
455
+ if (m) {
456
+ const fq = m[1].replace(/"/g,'');
457
+ const parts = fq.split('.');
458
+ detectedName = parts.pop();
459
+ detectedSchema = parts.pop() || '';
460
+ } else {
461
+ detectedSchema = '';
462
+ detectedName = '';
463
+ }
464
+ updateDdlPreview();
465
+ }
466
+
467
+ function updateDdlPreview() {
468
+ const catalog = ENV_CATALOGS[el('ddlEnv').value];
469
+ const schema = detectedSchema || '<schema>';
470
+ const name = detectedName || '<table>';
471
+ el('ddlPreviewTag').textContent = `${catalog}.${schema}.${name}`;
472
+ }
473
+
474
+ function syncEnvDropdowns(source) {
475
+ const val = el(source).value;
476
+ el('ddlEnv').value = val;
477
+ el('grantEnv').value = val;
478
+ const cat = ENV_CATALOGS[val];
479
+ el('grantCatalogTag').textContent = 'Catalog: ' + cat;
480
+ updateDdlPreview();
481
+ if (lastGrantTarget) generateGrants(lastGrantTarget, lastGrantIsView);
482
+ }
483
+
484
+ el('ddlEnv').onchange = () => syncEnvDropdowns('ddlEnv');
485
+ el('input').addEventListener('input', autoDetectFromDDL);
486
+ el('input').addEventListener('paste', () => setTimeout(autoDetectFromDDL, 0));
487
+
488
+ el('sampleBtn').onclick = ()=>{
489
+ el('input').value =
490
+ `CREATE MULTISET TABLE AMESAAPAC_P_WORK.TH_WS_SLS_PERF_RPRT_DELTA ,FALLBACK ,
491
+ NO BEFORE JOURNAL,
492
+ NO AFTER JOURNAL,
493
+ CHECKSUM = DEFAULT,
494
+ DEFAULT MERGEBLOCKRATIO,
495
+ MAP = TD_MAP2
496
+ (
497
+ DW_CUST_ID BIGINT,
498
+ CUST_ID VARCHAR(100) CHARACTER SET UNICODE NOT CASESPECIFIC,
499
+ BIC_ZCOPADOC VARCHAR(10) CHARACTER SET UNICODE NOT CASESPECIFIC,
500
+ DW_MTRL_ID BIGINT,
501
+ MTRL_ID VARCHAR(100) CHARACTER SET UNICODE NOT CASESPECIFIC,
502
+ MATL_GRP_4 VARCHAR(3),
503
+ COMP_CODE VARCHAR(4),
504
+ CURTYPE VARCHAR(2),
505
+ PSTNG_DATE DATE FORMAT 'YYYY-MM-DD',
506
+ CALYEAR INTEGER,
507
+ CALMONTH VARCHAR(6) NOT NULL
508
+ )
509
+ PRIMARY INDEX (DW_CUST_ID);`;
510
+ autoDetectFromDDL();
511
+ };
512
+
513
+ el('clearBtn').onclick = ()=>{ el('input').value=''; el('sqlOut').textContent=''; el('why').textContent=''; el('grantOut').textContent=''; el('detectedTag').textContent='Detected: —'; el('recommendTag').textContent='Recommendation: —'; detectedSchema=''; detectedName=''; updateDdlPreview(); };
514
+
515
+ el('convertBtn').onclick = ()=>{
516
+ const ddl = el('input').value.trim();
517
+ if (!ddl) { alert('Please paste Teradata DDL first.'); return; }
518
+ const parsed = parseTeradata(ddl);
519
+ const why = [];
520
+ const mode = el('recoMode').value;
521
+ const decision = recommend(parsed, mode, why);
522
+ const choice = decision;
523
+ const opts = {
524
+ textMode: el('textMode').value,
525
+ emitConstraints: el('emitConstraints').checked,
526
+ usePartition: el('usePartition').checked,
527
+ useCluster: el('useCluster').checked
528
+ };
529
+ const catalog = ENV_CATALOGS[el('ddlEnv').value];
530
+ const schema = detectedSchema || parsed.schema || '';
531
+ const tblName = detectedName || parsed.name || 'converted_object';
532
+ const targetNs = schema ? `${catalog}.${schema}` : catalog;
533
+ const res = toDatabricks(parsed, targetNs, tblName, choice, opts);
534
+ el('sqlOut').textContent = res.sql;
535
+ el('detectedTag').textContent = 'Detected: ' + res.detected;
536
+ el('recommendTag').textContent = 'Recommendation: ' + res.recommendation;
537
+ const fqTarget = `${targetNs}.${tblName}`;
538
+ const isView = (choice === 'view');
539
+ generateGrants(fqTarget, isView);
540
+ const allWhy = why.concat(res.why);
541
+ // Extra notes always helpful
542
+ allWhy.push('\nNotes:');
543
+ allWhy.push('- DATE/TIME FORMAT clauses are removed; normalize formats during ETL.');
544
+ allWhy.push('- TIMESTAMP WITH TIME ZONE is mapped to TIMESTAMP (interpretation depends on workspace settings).');
545
+ allWhy.push('- INTERVAL mapped to STRING; remodel if doing arithmetic.');
546
+ allWhy.push('- Consider OPTIMIZE and ZORDER after large loads.');
547
+ el('why').textContent = allWhy.join('\n');
548
+ };
549
+
550
+ el('copySql').onclick = ()=> copy(el('sqlOut').textContent);
551
+ el('downloadSql').onclick = ()=>{
552
+ const name = (detectedName || 'converted_object') + '.sql';
553
+ dl(name, el('sqlOut').textContent);
554
+ };
555
+ el('downloadExplain').onclick = ()=>{
556
+ const name = (detectedName || 'converted_object') + '_explanation.txt';
557
+ dl(name, el('why').textContent);
558
+ };
559
+
560
+ /* ===== Grant generation ===== */
561
+ let lastGrantTarget = null;
562
+ let lastGrantIsView = false;
563
+
564
+ el('grantEnv').onchange = () => syncEnvDropdowns('grantEnv');
565
+
566
+ function toggleGrantTpl() {
567
+ el('grantToggle').classList.toggle('open');
568
+ el('grantTplBody').classList.toggle('open');
569
+ }
570
+
571
+ function generateGrants(fqTarget, isView) {
572
+ lastGrantTarget = fqTarget;
573
+ lastGrantIsView = isView;
574
+ const catalog = ENV_CATALOGS[el('grantEnv').value];
575
+ const parts = fqTarget.split('.');
576
+ const schemaAndName = parts.length >= 2 ? parts.slice(-2).join('.') : parts.join('.');
577
+ const envTarget = `${catalog}.${schemaAndName}`;
578
+ const tpl = isView ? el('viewGrantTpl').value.trim() : el('tableGrantTpl').value.trim();
579
+ if (!tpl) { el('grantOut').textContent = '-- No grant template defined.'; return; }
580
+ const placeholder = isView ? 'view_name' : 'table_name';
581
+ const lines = tpl.split('\n').map(l => l.trim()).filter(Boolean);
582
+ const header = `-- ========== GRANTS for ${envTarget} ==========`;
583
+ const grants = lines.map(l => l.replace(new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'), 'g'), envTarget));
584
+ el('grantOut').textContent = header + '\n' + grants.join('\n');
585
+ }
586
+
587
+ el('copyGrants').onclick = ()=> copy(el('grantOut').textContent);
588
+ el('downloadGrants').onclick = ()=>{
589
+ const name = (el('targetName').value.trim() || 'converted_object') + '_grants.sql';
590
+ dl(name, el('grantOut').textContent);
591
+ };
592
+ </script>
593
+ </body>
594
+ </html>