File size: 27,046 Bytes
bc3415e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Teradata β†’ Databricks DDL Converter</title>
<style>
  :root { --bg:#0b1020; --card:#111934; --ink:#eaf0ff; --muted:#9fb2ff; --accent:#7aa2ff; --ok:#35c88a; --warn:#f5c451; --err:#ff6b6b; }
  body { margin:0; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial; background:var(--bg); color:var(--ink); }
  header { padding:20px 24px; border-bottom:1px solid #1d2750; display:flex; justify-content:space-between; align-items:center; }
  h1 { font-size:18px; margin:0; letter-spacing:0.3px;}
  .wrap { max-width:1200px; margin:24px auto; padding:0 16px; display:grid; gap:16px; grid-template-columns: 1fr 1fr; }
  .card { background:var(--card); border:1px solid #1d2750; border-radius:12px; padding:16px; }
  .card h2 { margin:0 0 10px 0; font-size:15px; color:var(--muted); }
  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; }
  textarea { min-height:240px; resize:vertical; }
  .row { display:grid; grid-template-columns: 1fr 1fr; gap:12px; margin:10px 0 0 0; }
  .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; }
  .btnbar { display:flex; gap:10px; flex-wrap:wrap; }
  button { background:var(--accent); color:#081028; border:0; padding:10px 14px; border-radius:10px; font-weight:600; cursor:pointer; }
  button.secondary { background:#172556; color:var(--ink); border:1px solid #2b3c84; }
  button.ghost { background:transparent; color:var(--muted); border:1px dashed #35489a; }
  pre { white-space:pre-wrap; word-wrap:break-word; background:#0c1430; border:1px solid #1d2750; border-radius:10px; padding:12px; font-size:12.5px; }
  .tag { font-size:12px; padding:2px 8px; border-radius:999px; border:1px solid #26357a; background:#0c1430; color:var(--muted); }
  .ok { color:var(--ok); }
  .warn { color:var(--warn); }
  .err { color:var(--err); }
  .small { font-size:12px; color:var(--muted); }
  .grid-3 { display:grid; grid-template-columns: repeat(3,1fr); gap:10px; }
  .foot { text-align:center; color:var(--muted); padding:12px 0 24px; font-size:12px; }
  a { color:#bcd2ff; }
  .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; }
  .hint { margin-top:8px; font-size:12px; color:var(--muted); }
  .grant-card { border-color:#26357a; }
  .grant-card h2 { color:#a78bfa; }
  .grant-toggle { cursor:pointer; user-select:none; display:flex; align-items:center; gap:8px; }
  .grant-toggle::before { content:'β–Ά'; font-size:10px; transition:transform .2s; }
  .grant-toggle.open::before { transform:rotate(90deg); }
  .grant-body { display:none; margin-top:10px; }
  .grant-body.open { display:block; }
  textarea.grant-tpl { min-height:120px; font-size:12px; }
  pre.grant-out { max-height:350px; overflow:auto; }
</style>
</head>
<body>
<header>
  <h1>Teradata β†’ Databricks DDL Converter</h1>
  <div class="pill">Heuristics-based recommendation β€’ Delta best practices</div>
</header>

<div class="wrap">
  <div class="card">
    <h2>1) Paste Teradata DDL</h2>
    <textarea id="input" placeholder="Paste Teradata CREATE TABLE/VIEW DDL here…"></textarea>
    <div class="row">
      <div>
        <label class="small">Environment</label>
        <select id="ddlEnv">
          <option value="dev">dev β€” uc_dev_apac_mdip_01</option>
          <option value="qa">qa β€” uc_qa_apac_mdip_01</option>
          <option value="prod">prod β€” uc_prod_apac_mdip_01</option>
        </select>
      </div>
      <div style="display:flex;align-items:end;">
        <span class="tag" id="ddlPreviewTag" style="color:var(--accent);border-color:var(--accent);">Paste DDL to auto-detect schema.table</span>
      </div>
    </div>
    <div class="row">
      <div>
        <label class="small">Recommendation mode</label>
        <select id="recoMode">
          <option value="auto">Auto (analyze & decide)</option>
          <option value="delta">Force Delta table</option>
          <option value="parquet">Force Standard (Parquet) table</option>
          <option value="view">Force View</option>
        </select>
      </div>
      <div>
        <label class="small">Text handling</label>
        <select id="textMode">
          <option value="string">Map CHAR/VARCHAR β†’ STRING (safer)</option>
          <option value="varchar">Keep VARCHAR/CHAR with lengths (ANSI)</option>
        </select>
      </div>
    </div>
    <div class="grid-3" style="margin-top:10px;">
      <label><input id="useCluster" type="checkbox" checked> Use <span class="mono">CLUSTER BY</span> for TD PI/partition</label>
      <label><input id="usePartition" type="checkbox"> Use <span class="mono">PARTITIONED BY</span> instead (big shards)</label>
      <label><input id="emitConstraints" type="checkbox" checked> Emit PK/UNIQUE as NOT ENFORCED</label>
    </div>
    <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>
    <div style="margin-top:12px" class="btnbar">
      <button id="convertBtn">Convert</button>
      <button class="secondary" id="sampleBtn">Load sample TD DDL</button>
      <button class="ghost" id="clearBtn">Clear</button>
    </div>
  </div>

  <div class="card">
    <h2>2) Output β€” Databricks DDL</h2>
    <div class="row">
      <span class="tag" id="detectedTag">Detected: β€”</span>
      <span class="tag" id="recommendTag">Recommendation: β€”</span>
    </div>
    <div style="margin-top:10px;" class="btnbar">
      <button id="downloadSql">Download SQL</button>
      <button class="secondary" id="downloadExplain">Download Explanation</button>
      <button class="ghost" id="copySql">Copy SQL</button>
    </div>
    <pre id="sqlOut" style="margin-top:10px;"></pre>
  </div>

  <div class="card" style="grid-column:1 / -1;">
    <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>
    <div class="grant-body" id="whyBody">
      <pre id="why"></pre>
    </div>
  </div>

  <div class="card grant-card" style="grid-column:1 / -1;">
    <h2>4) GRANT Statements</h2>
    <div class="row" style="margin-bottom:10px;">
      <div>
        <label class="small">Environment</label>
        <select id="grantEnv">
          <option value="dev">dev β€” uc_dev_apac_mdip_01</option>
          <option value="qa">qa β€” uc_qa_apac_mdip_01</option>
          <option value="prod">prod β€” uc_prod_apac_mdip_01</option>
        </select>
      </div>
      <div style="display:flex;align-items:end;">
        <span class="tag" id="grantCatalogTag" style="color:#a78bfa;border-color:#a78bfa55;">Catalog: uc_dev_apac_mdip_01</span>
      </div>
    </div>
    <div class="grant-toggle" id="grantToggle" onclick="toggleGrantTpl()">Customize grant template</div>
    <div class="grant-body" id="grantTplBody">
      <label class="small">TABLE grant template (use <code style="color:var(--accent)">table_name</code> as placeholder)</label>
      <textarea class="grant-tpl" id="tableGrantTpl">GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIP.Core.Team`;
GRANT SELECT, MODIFY ON TABLE table_name TO `svciscpkpi@pepsico.com`;
GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer`;
GRANT SELECT, MODIFY ON TABLE table_name TO `svcCViscpkrptprd@pepsico.com`;
GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.PBNA.TDQKETSPROD.ADB`;
GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.PBNA.TDQKETS.ADB`;
GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader`;
GRANT SELECT, MODIFY ON TABLE table_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor`;</textarea>
      <div style="margin-top:10px;">
        <label class="small">VIEW grant template (use <code style="color:var(--accent)">view_name</code> as placeholder)</label>
        <textarea class="grant-tpl" id="viewGrantTpl">GRANT SELECT ON VIEW view_name TO `Team.App.MDIP.Core.Team`;
GRANT SELECT ON VIEW view_name TO `svciscpkpi@pepsico.com`;
GRANT SELECT ON VIEW view_name TO `Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer`;
GRANT SELECT ON VIEW view_name TO `svcCViscpkrptprd@pepsico.com`;
GRANT SELECT ON VIEW view_name TO `Team.App.PBNA.TDQKETSPROD.ADB`;
GRANT SELECT ON VIEW view_name TO `Team.App.PBNA.TDQKETS.ADB`;
GRANT SELECT ON VIEW view_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader`;
GRANT SELECT ON VIEW view_name TO `Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor`;</textarea>
      </div>
    </div>
    <div style="margin-top:10px;" class="btnbar">
      <button class="ghost" id="copyGrants">Copy Grants</button>
      <button class="secondary" id="downloadGrants">Download Grants SQL</button>
    </div>
    <pre class="grant-out" id="grantOut" style="margin-top:10px;"></pre>
  </div>
</div>

<div class="foot">Built for robust Teradata β†’ Databricks migrations. No servers, no dependencies.</div>

<script>
/* ===== Utilities ===== */
function dl(filename, text) {
  const a = document.createElement('a');
  a.setAttribute('href','data:text/plain;charset=utf-8,'+encodeURIComponent(text));
  a.setAttribute('download', filename);
  a.style.display='none';
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
}
function copy(text){ navigator.clipboard.writeText(text||''); }

/* ===== Core parsing & mapping ===== */
const TD_TYPES = [
  'BYTEINT','SMALLINT','INTEGER','INT','BIGINT',
  'DECIMAL','NUMERIC','NUMBER',
  'FLOAT','REAL','DOUBLE','DOUBLE PRECISION',
  'CHAR','VARCHAR','CLOB','BLOB','VARBYTE','BYTE','LONG VARGRAPHIC','GRAPHIC','VARGRAPHIC',
  'DATE','TIME','TIMESTAMP','INTERVAL',
  'BYTE','VARBYTE'
];

// Map TD data types to Databricks types
function mapType(tdTypeRaw, textMode, why) {
  const t = tdTypeRaw.trim().replace(/\s+/g,' ').toUpperCase();
  const len = (t.match(/\(([^)]+)\)/)?.[1] || '').trim();
  const base = t.replace(/\(([^)]+)\)/,'').replace(/ CHARACTER SET .+$/,'').replace(/ NOT CASESPECIFIC/g,'').trim();

  // Note charset/casespecific
  if (/CHARACTER SET\s+UNICODE/i.test(tdTypeRaw)) {
    why.push(`- Found UNICODE charset β†’ Databricks strings are UTF-8 natively; dropping charset clause.`);
  }
  if (/NOT CASESPECIFIC/i.test(tdTypeRaw)) {
    why.push(`- Found NOT CASESPECIFIC β†’ Databricks collations differ; treating as regular text (case-insensitivity handled differently).`);
  }

  // Numerics
  if (base === 'BYTEINT') return 'TINYINT';
  if (base === 'SMALLINT') return 'SMALLINT';
  if (base === 'INTEGER' || base === 'INT') return 'INT';
  if (base === 'BIGINT') return 'BIGINT';
  if (base === 'DECIMAL' || base === 'NUMERIC' || base === 'NUMBER') {
    const [p,s] = len ? len.split(',').map(x=>x.trim()) : [];
    if (p) return `DECIMAL(${p}${s?','+s:''})`;
    if (base === 'NUMBER') { why.push(`- NUMBER without precision β†’ mapped to INT.`); return 'INT'; }
    return 'DECIMAL(38,18)';
  }
  if (base === 'FLOAT' || base === 'REAL' || base === 'DOUBLE' || base === 'DOUBLE PRECISION') return 'DOUBLE';

  // Binary / LOB
  if (base === 'BLOB' || base === 'VARBYTE' || base === 'BYTE') return 'BINARY';

  // Date/Time
  if (base === 'DATE') return 'DATE';
  if (base === 'TIME') { why.push(`- TD TIME mapped to STRING (Databricks TIME exists but portability varies).`); return 'STRING'; }
  if (base.startsWith('TIMESTAMP')) return 'TIMESTAMP'; // drop timezone/format
  if (base.startsWith('INTERVAL')) { why.push(`- TD INTERVAL mapped to STRING (re-model as INT seconds or INTERVAL arithmetic post-load).`); return 'STRING'; }

  // Textual
  if (base === 'CLOB') return 'STRING';
  if (base === 'CHAR' || base === 'VARCHAR' || base==='GRAPHIC' || base==='VARGRAPHIC' || base==='LONG VARGRAPHIC') {
    if (textMode === 'varchar') {
      const n = (len || '65535').replace(/\s/g,'');
      return `${base==='CHAR'?'CHAR':'VARCHAR'}(${n})`;
    }
    return 'STRING';
  }

  // Fallback
  why.push(`- Unmapped type "${tdTypeRaw.trim()}" β†’ defaulting to STRING.`);
  return 'STRING';
}

// Try to extract object kind, name, columns, constraints, PI, partitions
function parseTeradata(ddl) {
  const out = { kind:'unknown', name:'', schema:'', columns:[], constraints:[], primaryIndex:[], partitionBy:[], raw:ddl };

  // Normalize
  const src = ddl.replace(/--.*$/mg,'').replace(/\/\*[\s\S]*?\*\//g,'').trim();
  const head = src.slice(0, 512).toUpperCase();

  // Kind detection
  if (/(?:CREATE|REPLACE)\s+VIEW/i.test(src)) out.kind = 'view';
  else if (/CREATE\s+(MULTISET|SET)?\s*VOLATILE\s+TABLE/i.test(src)) out.kind = 'volatile';
  else if (/CREATE\s+(MULTISET|SET)?\s*TABLE/i.test(src)) out.kind = 'table';

  // Name
  const nameMatch = src.match(/(?:CREATE|REPLACE)\s+(?:MULTISET|SET)?\s*(?:VOLATILE\s+)?(?:TABLE|VIEW)\s+([A-Za-z0-9_$."]+)/i);
  if (nameMatch) {
    const fq = nameMatch[1].replace(/"/g,'');
    out.fqName = fq;
    const parts = fq.split('.');
    out.name = parts.pop();
    out.schema = parts.join('.');
  }

  // Column list (naive but robust for most TD DDL)
  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) ||
                        src.match(/\(([\s\S]*?)\)/);
  if (colBlockMatch) {
    const colBlock = colBlockMatch[1];
    // split by commas not inside parentheses
    const parts = [];
    let buf='', depth=0;
    for (let c of colBlock) {
      if (c==='(') depth++;
      if (c===')') depth--;
      if (c===',' && depth===0) { parts.push(buf); buf=''; }
      else buf += c;
    }
    if (buf.trim()) parts.push(buf);

    for (const p of parts) {
      const line = p.trim();
      if (!line) continue;
      // Constraint lines (PRIMARY KEY, UNIQUE, CHECK, FOREIGN KEY)
      if (/^(PRIMARY|UNIQUE|CHECK|FOREIGN)\b/i.test(line)) {
        out.constraints.push(line.replace(/\s+/g,' ').trim());
        continue;
      }
      const m = line.match(/^("[^"]+"|[A-Za-z0-9_]+)\s+(.+)$/);
      if (m) {
        const rawName = m[1].trim();
        const hasSpaces = rawName.startsWith('"') && rawName.includes(' ');
        const colName = rawName.replace(/"/g,'');
        const typeAndRest = m[2].trim();
        out.columns.push({ name: colName, tdType: typeAndRest, needsQuoting: hasSpaces });
      }
    }
  }

  // PI / PARTITION BY
  const piMatch = src.match(/(?:UNIQUE\s+)?PRIMARY\s+INDEX\s*\(([^)]+)\)/i);
  if (piMatch) out.primaryIndex = piMatch[1].split(',').map(s=>s.trim().replace(/"/g,''));
  const partMatch = src.match(/PARTITION\s+BY\s*\(([^)]+)\)/i) || src.match(/PARTITION\s+BY\s+([^\n;]+)/i);
  if (partMatch) out.partitionBy = [partMatch[1].trim()];

  // Unique/PK constraints elsewhere
  const pkMatch = src.match(/PRIMARY\s+KEY\s*\(([^)]+)\)/i);
  if (pkMatch) out.constraints.push(`PRIMARY KEY (${pkMatch[1]})`);
  const uqMatches = [...src.matchAll(/UNIQUE\s*\(([^)]+)\)/ig)];
  uqMatches.forEach(m=>out.constraints.push(`UNIQUE (${m[1]})`));

  return out;
}

// Heuristic recommendation
function recommend(out, mode, why) {
  if (mode !== 'auto') return mode;
  if (out.kind === 'view') return 'view';
  if (out.kind === 'volatile') {
    why.push(`- Volatile table detected β†’ Recommend Delta (temporary analogs are views/temp tables at runtime).`);
    return 'delta';
  }
  // Table heuristics
  const hasKeys = out.constraints.some(c=>/PRIMARY\s+KEY|UNIQUE/i.test(c));
  const mayUpsert = /JOURNAL|FALLBACK|MERGEBLOCKRATIO|MAP\s*=|CHECKSUM/i.test(out.raw);
  const hasPkIdx = out.primaryIndex.length>0;
  // Prefer Delta when:
  if (hasKeys || mayUpsert || hasPkIdx) {
    why.push(`- Keys/PI or TD features implying updates/merges found β†’ Recommend Delta for ACID & MERGE.`);
    return 'delta';
  }
  // Default to Delta anyway (Databricks default & governance)
  why.push(`- No strong signals for Parquet-only; defaulting to Delta for governance, schema evolution, and deletes/merges.`);
  return 'delta';
}

function toDatabricks(out, targetNs, targetName, choice, opts) {
  const why = [];
  const textMode = opts.textMode;
  const emitConstraints = opts.emitConstraints;
  const usePartition = opts.usePartition;
  const useCluster = opts.useCluster;

  let finalName = (targetName||out.name||'converted_object');
  let fqTarget = targetNs ? `${targetNs}.${finalName}` : finalName;

  if (out.kind === 'view' || choice === 'view') {
    // Attempt to capture SELECT
    const selMatch = out.raw.match(/AS\s+([\s\S]+)$/i);
    let selectSql = selMatch ? selMatch[1].trim().replace(/;+\s*$/,'') : '-- TODO: Provide SELECT body';
    selectSql = selectSql.replace(/LOCKING\s+ROW\s+FOR\s+ACCESS\s*/gi, '');
    why.push(`- Object is a VIEW β†’ emitting CREATE VIEW IF NOT EXISTS with original SELECT.`);
    if (/LOCKING\s+ROW/i.test(out.raw)) why.push(`- Removed TD "LOCKING ROW FOR ACCESS" (not applicable in Databricks).`);
    const sql = `CREATE VIEW IF NOT EXISTS ${fqTarget} AS
${selectSql};`;
    return { sql, why, detected:`VIEW (${out.fqName||out.name||''})`, recommendation:'VIEW' };
  }

  // Table path
  const cols = out.columns.map(c=>{
    const notnull = /NOT\s+NULL/i.test(c.tdType);
    const tdTypeOnly = c.tdType.replace(/\s+NOT\s+NULL/gi,'').replace(/\s+DEFAULT\s+.+$/i,'').replace(/FORMAT\s+'[^']+'/i,'').replace(/\s+CASESPECIFIC/ig,'').trim();
    const mapped = mapType(tdTypeOnly, textMode, why);
    const colRef = c.needsQuoting ? '`' + c.name + '`' : c.name;
    return `  ${colRef} ${mapped}${notnull?' NOT NULL':''}`;
  });

  // Table properties for Delta
  const deltaProps = [
    `'delta.autoOptimize.optimizeWrite' = 'true'`,
    `'delta.autoOptimize.autoCompact' = 'true'`,
    `'delta.enableDeletionVectors' = 'true'`,
    `'delta.minReaderVersion' = '3'`,
    `'delta.minWriterVersion' = '7'`,
    `'delta.logRetentionDuration' = '30 days'`,
    `'delta.columnMapping.mode' = 'name'`,
    `'delta.feature.columnMapping' = 'supported'`,
    `'delta.feature.deletionVectors' = 'supported'`,
    `'delta.deletedFileRetentionDuration' = '30 days'`
  ];

  let body = '';
  let extras = [];

  // Constraints
  const constraints = [];
  for (const c of out.constraints) {
    if (/PRIMARY\s+KEY\s*\(([^)]+)\)/i.test(c)) {
      const cols = c.match(/\(([^)]+)\)/)[1].split(',').map(x=>x.trim()).join(', ');
      if (emitConstraints) constraints.push(`  CONSTRAINT pk_${finalName} PRIMARY KEY (${cols}) NOT ENFORCED`);
      else extras.push(`-- TD PRIMARY KEY(${cols}) β†’ informational only in Databricks`);
    } else if (/UNIQUE\s*\(([^)]+)\)/i.test(c)) {
      const cols = c.match(/\(([^)]+)\)/)[1].split(',').map(x=>x.trim()).join(', ');
      if (emitConstraints) constraints.push(`  CONSTRAINT uq_${finalName}_${Math.random().toString(36).slice(2,6)} UNIQUE (${cols}) NOT ENFORCED`);
      else extras.push(`-- TD UNIQUE(${cols}) β†’ record preserved as comment`);
    } else if (/CHECK|FOREIGN\s+KEY/i.test(c)) {
      extras.push(`-- Constraint preserved: ${c}`);
    }
  }

  // Partition/Cluster mapping from TD PRIMARY INDEX / PARTITION BY
  let partClause = '';
  let clusterClause = '';
  if (out.primaryIndex.length) {
    if (usePartition) {
      partClause = `\nPARTITIONED BY (${out.primaryIndex.join(', ')})`;
      extras.push(`-- TD PRIMARY INDEX mapped to PARTITIONED BY; consider CLUSTER BY for skewed keys.`);
    } else if (useCluster) {
      clusterClause = `\nCLUSTER BY (${out.primaryIndex.join(', ')})`;
      extras.push(`-- TD PRIMARY INDEX β†’ CLUSTER BY (improves locality for joins & filters).`);
    } else {
      extras.push(`-- TD PRIMARY INDEX detected: (${out.primaryIndex.join(', ')})`);
    }
  }
  if (out.partitionBy.length) {
    extras.push(`-- TD PARTITION BY detected: ${out.partitionBy.join(' | ')} (manual translation to Delta partitioning may be required).`);
  }

  // Choice
  let recommendation = '';
  if (choice === 'delta') {
    recommendation = 'DELTA TABLE';
    body = `CREATE TABLE IF NOT EXISTS ${fqTarget} (
${cols.concat(constraints).join(',\n')}
)
USING DELTA${partClause}${clusterClause}
TBLPROPERTIES (
  ${deltaProps.join(',\n  ')}
);`;
    why.push(`- Using Delta for ACID, MERGE/DELETE, schema evolution, OPTIMIZE/ZORDER support.`);
  } else {
    recommendation = 'STANDARD (PARQUET) TABLE';
    body = `CREATE TABLE IF NOT EXISTS ${fqTarget} (
${cols.join(',\n')}
)
USING PARQUET${partClause}${clusterClause};`;
    if (constraints.length) extras.push(`-- Constraints not emitted for PARQUET; consider Delta if you need constraints/merges.`);
    why.push(`- Using PARQUET only (no Delta features). Suitable for simple append-only staging.`)
  }

  const sql = [body].concat(extras.length?['\n'+extras.join('\n')]:[]).join('\n');
  const detected = `${(out.kind||'TABLE').toUpperCase()} ${out.fqName?('('+out.fqName+')'):''}`;

  return { sql, why, detected, recommendation };
}

/* ===== UI glue ===== */
const el = id=>document.getElementById(id);
const ENV_CATALOGS = { dev: 'uc_dev_apac_mdip_01', qa: 'uc_qa_apac_mdip_01', prod: 'uc_prod_apac_mdip_01' };

let detectedSchema = '';
let detectedName = '';

function autoDetectFromDDL() {
  const ddl = el('input').value;
  const m = ddl.match(/(?:CREATE|REPLACE)\s+(?:MULTISET|SET)?\s*(?:VOLATILE\s+)?(?:TABLE|VIEW)\s+([A-Za-z0-9_$."]+)/i);
  if (m) {
    const fq = m[1].replace(/"/g,'');
    const parts = fq.split('.');
    detectedName = parts.pop();
    detectedSchema = parts.pop() || '';
  } else {
    detectedSchema = '';
    detectedName = '';
  }
  updateDdlPreview();
}

function updateDdlPreview() {
  const catalog = ENV_CATALOGS[el('ddlEnv').value];
  const schema = detectedSchema || '<schema>';
  const name = detectedName || '<table>';
  el('ddlPreviewTag').textContent = `${catalog}.${schema}.${name}`;
}

function syncEnvDropdowns(source) {
  const val = el(source).value;
  el('ddlEnv').value = val;
  el('grantEnv').value = val;
  const cat = ENV_CATALOGS[val];
  el('grantCatalogTag').textContent = 'Catalog: ' + cat;
  updateDdlPreview();
  if (lastGrantTarget) generateGrants(lastGrantTarget, lastGrantIsView);
}

el('ddlEnv').onchange = () => syncEnvDropdowns('ddlEnv');
el('input').addEventListener('input', autoDetectFromDDL);
el('input').addEventListener('paste', () => setTimeout(autoDetectFromDDL, 0));

el('sampleBtn').onclick = ()=>{
  el('input').value =
`CREATE MULTISET TABLE AMESAAPAC_P_WORK.TH_WS_SLS_PERF_RPRT_DELTA ,FALLBACK ,
     NO BEFORE JOURNAL,
     NO AFTER JOURNAL,
     CHECKSUM = DEFAULT,
     DEFAULT MERGEBLOCKRATIO,
     MAP = TD_MAP2
     (
      DW_CUST_ID BIGINT,
      CUST_ID VARCHAR(100) CHARACTER SET UNICODE NOT CASESPECIFIC,
      BIC_ZCOPADOC VARCHAR(10) CHARACTER SET UNICODE NOT CASESPECIFIC,
      DW_MTRL_ID BIGINT,
      MTRL_ID VARCHAR(100) CHARACTER SET UNICODE NOT CASESPECIFIC,
      MATL_GRP_4 VARCHAR(3),
      COMP_CODE VARCHAR(4),
      CURTYPE VARCHAR(2),
      PSTNG_DATE DATE FORMAT 'YYYY-MM-DD',
      CALYEAR INTEGER,
      CALMONTH VARCHAR(6) NOT NULL
     )
PRIMARY INDEX (DW_CUST_ID);`;
  autoDetectFromDDL();
};

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(); };

el('convertBtn').onclick = ()=>{
  const ddl = el('input').value.trim();
  if (!ddl) { alert('Please paste Teradata DDL first.'); return; }
  const parsed = parseTeradata(ddl);
  const why = [];
  const mode = el('recoMode').value;
  const decision = recommend(parsed, mode, why);
  const choice = decision;
  const opts = {
    textMode: el('textMode').value,
    emitConstraints: el('emitConstraints').checked,
    usePartition: el('usePartition').checked,
    useCluster: el('useCluster').checked
  };
  const catalog = ENV_CATALOGS[el('ddlEnv').value];
  const schema = detectedSchema || parsed.schema || '';
  const tblName = detectedName || parsed.name || 'converted_object';
  const targetNs = schema ? `${catalog}.${schema}` : catalog;
  const res = toDatabricks(parsed, targetNs, tblName, choice, opts);
  el('sqlOut').textContent = res.sql;
  el('detectedTag').textContent = 'Detected: ' + res.detected;
  el('recommendTag').textContent = 'Recommendation: ' + res.recommendation;
  const fqTarget = `${targetNs}.${tblName}`;
  const isView = (choice === 'view');
  generateGrants(fqTarget, isView);
  const allWhy = why.concat(res.why);
  // Extra notes always helpful
  allWhy.push('\nNotes:');
  allWhy.push('- DATE/TIME FORMAT clauses are removed; normalize formats during ETL.');
  allWhy.push('- TIMESTAMP WITH TIME ZONE is mapped to TIMESTAMP (interpretation depends on workspace settings).');
  allWhy.push('- INTERVAL mapped to STRING; remodel if doing arithmetic.');
  allWhy.push('- Consider OPTIMIZE and ZORDER after large loads.');
  el('why').textContent = allWhy.join('\n');
};

el('copySql').onclick = ()=> copy(el('sqlOut').textContent);
el('downloadSql').onclick = ()=>{
  const name = (detectedName || 'converted_object') + '.sql';
  dl(name, el('sqlOut').textContent);
};
el('downloadExplain').onclick = ()=>{
  const name = (detectedName || 'converted_object') + '_explanation.txt';
  dl(name, el('why').textContent);
};

/* ===== Grant generation ===== */
let lastGrantTarget = null;
let lastGrantIsView = false;

el('grantEnv').onchange = () => syncEnvDropdowns('grantEnv');

function toggleGrantTpl() {
  el('grantToggle').classList.toggle('open');
  el('grantTplBody').classList.toggle('open');
}

function generateGrants(fqTarget, isView) {
  lastGrantTarget = fqTarget;
  lastGrantIsView = isView;
  const catalog = ENV_CATALOGS[el('grantEnv').value];
  const parts = fqTarget.split('.');
  const schemaAndName = parts.length >= 2 ? parts.slice(-2).join('.') : parts.join('.');
  const envTarget = `${catalog}.${schemaAndName}`;
  const tpl = isView ? el('viewGrantTpl').value.trim() : el('tableGrantTpl').value.trim();
  if (!tpl) { el('grantOut').textContent = '-- No grant template defined.'; return; }
  const placeholder = isView ? 'view_name' : 'table_name';
  const lines = tpl.split('\n').map(l => l.trim()).filter(Boolean);
  const header = `-- ========== GRANTS for ${envTarget} ==========`;
  const grants = lines.map(l => l.replace(new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'), 'g'), envTarget));
  el('grantOut').textContent = header + '\n' + grants.join('\n');
}

el('copyGrants').onclick = ()=> copy(el('grantOut').textContent);
el('downloadGrants').onclick = ()=>{
  const name = (el('targetName').value.trim() || 'converted_object') + '_grants.sql';
  dl(name, el('grantOut').textContent);
};
</script>
</body>
</html>