-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtableau.py
More file actions
1638 lines (1387 loc) · 59.1 KB
/
tableau.py
File metadata and controls
1638 lines (1387 loc) · 59.1 KB
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tableau adapter for importing Tableau .tds/.twb/.tdsx/.twbx datasource definitions."""
import re
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from dataclasses import dataclass
from pathlib import Path
from sidemantic.adapters.base import BaseAdapter
from sidemantic.core.dimension import Dimension
from sidemantic.core.metric import Metric
from sidemantic.core.model import Model
from sidemantic.core.relationship import Relationship
from sidemantic.core.segment import Segment
from sidemantic.core.semantic_graph import SemanticGraph
# --- Type mapping ---
_DATATYPE_MAP: dict[str, str] = {
"string": "categorical",
"integer": "numeric",
"real": "numeric",
"date": "time",
"datetime": "time",
"boolean": "boolean",
}
_DATATYPE_GRANULARITY: dict[str, str] = {
"date": "day",
"datetime": "hour",
}
# --- Aggregation mapping (case-insensitive via .lower()) ---
_AGGREGATION_MAP: dict[str, str] = {
"sum": "sum",
"avg": "avg",
"count": "count",
"countd": "count_distinct",
"min": "min",
"max": "max",
"median": "median",
}
_PASSTHROUGH_AGGS: set[str] = {"attr", "none", "user"}
# --- Formula patterns ---
_FIELD_REF_RE = re.compile(r"\[([^\]]+)\]")
_LOD_RE = re.compile(r"\{\s*(?:FIXED|INCLUDE|EXCLUDE)\b", re.IGNORECASE)
_TABLE_CALC_FUNCS: set[str] = {
"RUNNING_SUM",
"RUNNING_AVG",
"RUNNING_COUNT",
"RUNNING_MIN",
"RUNNING_MAX",
"LOOKUP",
"INDEX",
"FIRST",
"LAST",
"SIZE",
"WINDOW_SUM",
"WINDOW_AVG",
"WINDOW_MIN",
"WINDOW_MAX",
"WINDOW_COUNT",
"WINDOW_MEDIAN",
"WINDOW_STDEV",
"WINDOW_VAR",
"PREVIOUS_VALUE",
"RANK",
"RANK_DENSE",
"RANK_MODIFIED",
"RANK_PERCENTILE",
"RANK_UNIQUE",
}
# Regex for function calls: FUNC_NAME(...)
_FUNC_CALL_RE = re.compile(r"\b([A-Z_]+)\s*\(", re.IGNORECASE)
# --- Formula replacement patterns ---
# Each is (pattern, replacement_func_or_str)
_ZN_RE = re.compile(r"\bZN\s*\(", re.IGNORECASE)
_IFNULL_RE = re.compile(r"\bIFNULL\s*\(", re.IGNORECASE)
_IIF_RE = re.compile(r"\bIIF\s*\(", re.IGNORECASE)
_IF_THEN_RE = re.compile(
r"\bIF\s+(.+?)\s+THEN\s+(.+?)(?:\s+ELSEIF\s+(.+?)\s+THEN\s+(.+?))*\s+(?:ELSE\s+(.+?)\s+)?END\b",
re.IGNORECASE | re.DOTALL,
)
_CONTAINS_RE = re.compile(r"\bCONTAINS\s*\(", re.IGNORECASE)
_DATETRUNC_RE = re.compile(r"\bDATETRUNC\s*\(", re.IGNORECASE)
_COUNTD_RE = re.compile(r"\bCOUNTD\s*\(", re.IGNORECASE)
_LEN_RE = re.compile(r"\bLEN\s*\(", re.IGNORECASE)
_ISNULL_RE = re.compile(r"\bISNULL\s*\(", re.IGNORECASE)
_COMMENT_RE = re.compile(r"//[^\n]*", re.MULTILINE)
_DATEADD_RE = re.compile(r"\bDATEADD\s*\(", re.IGNORECASE)
_MID_RE = re.compile(r"\bMID\s*\(", re.IGNORECASE)
_FIND_RE = re.compile(r"\bFIND\s*\(", re.IGNORECASE)
_SIMPLE_SQL_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
# Simple function renames (Tableau name -> SQL name)
_SIMPLE_RENAMES: list[tuple[re.Pattern, str]] = [
(re.compile(r"\bMID\s*\(", re.IGNORECASE), "SUBSTRING("),
(re.compile(r"\bFIND\s*\(", re.IGNORECASE), "STRPOS("),
(re.compile(r"\bSTARTSWITH\s*\(", re.IGNORECASE), "STARTS_WITH("),
(re.compile(r"\bENDSWITH\s*\(", re.IGNORECASE), "ENDS_WITH("),
(re.compile(r"\bCHAR\s*\(", re.IGNORECASE), "CHR("),
(re.compile(r"\bMAKEDATE\s*\(", re.IGNORECASE), "MAKE_DATE("),
(re.compile(r"\bMAKETIME\s*\(", re.IGNORECASE), "MAKE_TIME("),
(re.compile(r"\bMAKEDATETIME\s*\(", re.IGNORECASE), "MAKE_TIMESTAMP("),
]
# Tableau-specific functions that need balanced-paren-aware wrapping
_TABLEAU_CAST_FUNCS: dict[str, str] = {
"INT": "CAST({arg} AS INTEGER)",
"FLOAT": "CAST({arg} AS DOUBLE)",
"STR": "CAST({arg} AS VARCHAR)",
}
# Regex to detect Tableau-only functions that have no SQL equivalent
_TABLEAU_ONLY_FUNCS: set[str] = {
"ISMEMBEROF",
"USERNAME",
"USERDOMAIN",
"FULLNAME",
"ISFULLDATETIME",
"RAWSQLAGG_REAL",
"RAWSQLAGG_STR",
"RAWSQL_REAL",
"RAWSQL_STR",
"RAWSQL_INT",
"RAWSQL_BOOL",
"RAWSQL_DATE",
"RAWSQL_DATETIME",
}
def _has_lod_or_table_calc(formula: str) -> bool:
"""Check if formula contains LOD expressions or table calculations."""
if _LOD_RE.search(formula):
return True
for match in _FUNC_CALL_RE.finditer(formula):
func_name = match.group(1).upper()
if func_name in _TABLE_CALC_FUNCS or func_name in _TABLEAU_ONLY_FUNCS:
return True
return False
def _find_matching_paren(s: str, open_pos: int) -> int:
"""Find the position of the matching closing paren, handling nesting.
Args:
s: The string to search in
open_pos: Position of the opening '('
Returns:
Position of the matching ')' or -1 if not found
"""
depth = 0
in_string = False
string_char = None
i = open_pos
while i < len(s):
c = s[i]
if in_string:
if c == string_char:
# Check for doubled-quote escape ('' or "")
if i + 1 < len(s) and s[i + 1] == string_char:
i += 2 # Skip the escaped pair
continue
in_string = False
elif c in ("'", '"'):
in_string = True
string_char = c
elif c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth == 0:
return i
i += 1
return -1
def _replace_func_balanced(text: str, func_re: re.Pattern, template: str) -> str:
"""Replace a function call using balanced-paren matching.
template uses {arg} for the extracted argument.
"""
result = text
offset = 0
for m in func_re.finditer(text):
start = m.start() + offset
open_paren = start + len(m.group(0)) - 1 # position of '('
adjusted = result
close_paren = _find_matching_paren(adjusted, open_paren)
if close_paren == -1:
continue
arg = adjusted[open_paren + 1 : close_paren].strip()
replacement = template.format(arg=arg)
result = adjusted[:start] + replacement + adjusted[close_paren + 1 :]
offset = len(result) - len(text)
# Re-scan from scratch since positions shifted
return _replace_func_balanced(result, func_re, template)
return result
def _replace_field_refs(formula: str) -> str:
"""Replace [FieldName] references with quoted column names, skipping string literals.
Handles Tableau's qualified names: [table].[column] -> column
Skips brackets inside string literals (single or double quoted).
"""
result = []
i = 0
in_string = False
string_char = None
while i < len(formula):
c = formula[i]
if in_string:
if c == string_char:
if i + 1 < len(formula) and formula[i + 1] == string_char:
# Doubled-quote escape: append both and skip
result.append(c)
result.append(formula[i + 1])
i += 2
else:
result.append(c)
in_string = False
i += 1
else:
result.append(c)
i += 1
continue
if c in ("'", '"'):
in_string = True
string_char = c
result.append(c)
i += 1
continue
if c == "[":
# Find matching ]
end = formula.find("]", i + 1)
if end == -1:
result.append(c)
i += 1
continue
field_name = formula[i + 1 : end]
# Check if next char starts another bracket reference (qualified name)
# e.g. [table].[column]
if end + 2 < len(formula) and formula[end + 1] == "." and formula[end + 2] == "[":
end2 = formula.find("]", end + 3)
if end2 != -1:
field_name = formula[end + 3 : end2]
i = end2 + 1
else:
i = end + 1
else:
i = end + 1
result.append(_quote_identifier_if_needed(_normalize_column_name(field_name)))
continue
result.append(c)
i += 1
return "".join(result)
def _convert_double_quotes(text: str) -> str:
"""Convert Tableau double-quoted string literals to SQL single quotes.
Tableau uses "hello" for strings, SQL uses 'hello'. Double quotes in SQL
mean identifiers. Must skip brackets (already processed) and single-quoted
strings.
"""
result = []
i = 0
while i < len(text):
c = text[i]
if c == "'":
# Single-quoted string: pass through as-is
result.append(c)
i += 1
while i < len(text):
result.append(text[i])
if text[i] == "'" and (i + 1 >= len(text) or text[i + 1] != "'"):
i += 1
break
i += 1
elif c == '"':
# Double-quoted string: convert to single quotes
# Escape any apostrophes inside, and preserve escaped "" as literal "
result.append("'")
i += 1
while i < len(text):
if text[i] == '"':
if i + 1 < len(text) and text[i + 1] == '"':
# Escaped double quote "" -> literal " in single-quoted string
result.append('"')
i += 2
else:
result.append("'")
i += 1
break
elif text[i] == "'":
# Apostrophe inside string: escape for SQL single-quoted literal
result.append("''")
i += 1
else:
result.append(text[i])
i += 1
else:
result.append(c)
i += 1
return "".join(result)
def _strip_comments(text: str) -> str:
"""Strip // line comments while preserving // inside string literals.
E.g. '://' in a string is NOT a comment start.
Handles doubled-quote escapes ('') inside string literals.
"""
result = []
i = 0
while i < len(text):
c = text[i]
if c in ("'", '"'):
# Inside a string literal: pass through until matching quote
quote = c
result.append(c)
i += 1
while i < len(text):
if text[i] == quote:
if i + 1 < len(text) and text[i + 1] == quote:
# Doubled-quote escape: append both and skip
result.append(text[i])
result.append(text[i + 1])
i += 2
else:
# End of string
result.append(text[i])
i += 1
break
else:
result.append(text[i])
i += 1
elif c == "/" and i + 1 < len(text) and text[i + 1] == "/":
# Skip until end of line
while i < len(text) and text[i] != "\n":
i += 1
else:
result.append(c)
i += 1
return "".join(result)
def _split_args_balanced(text: str) -> list[str]:
"""Split comma-separated arguments respecting parentheses and string literals."""
args = []
depth = 0
current = []
in_string = False
string_char = None
for c in text:
if in_string:
current.append(c)
if c == string_char:
in_string = False
elif c in ("'", '"'):
in_string = True
string_char = c
current.append(c)
elif c == "(":
depth += 1
current.append(c)
elif c == ")":
depth -= 1
current.append(c)
elif c == "," and depth == 0:
args.append("".join(current).strip())
current = []
else:
current.append(c)
if current:
args.append("".join(current).strip())
return args
def _translate_iif(text: str) -> str:
"""Translate IIF(cond, then, else) using balanced-paren argument parsing."""
result = text
for m in _IIF_RE.finditer(text):
start = m.start()
open_paren = m.end() - 1
close_paren = _find_matching_paren(result, open_paren)
if close_paren == -1:
continue
inner = result[open_paren + 1 : close_paren]
args = _split_args_balanced(inner)
if len(args) >= 3:
cond, then_val, else_val = args[0], args[1], args[2]
replacement = f"CASE WHEN {cond} THEN {then_val} ELSE {else_val} END"
result = result[:start] + replacement + result[close_paren + 1 :]
# Restart since positions shifted
return _translate_iif(result)
return result
def _convert_string_concat(text: str) -> str:
"""Convert Tableau's + string concatenation to SQL ||.
Replaces + with || when at least one adjacent operand is a string-producing
expression: a string literal ('...') or a CAST(... AS VARCHAR) result.
Only matches VARCHAR casts (not INTEGER/DOUBLE) to avoid breaking arithmetic.
"""
result = text
prev = None
while prev != result:
prev = result
# 'string' + ... or ... + 'string'
result = re.sub(r"('\s*)\+(\s*)", r"\1||\2", result)
result = re.sub(r"(\s*)\+(\s*')", r"\1||\2", result)
# CAST(... AS VARCHAR) + ... (only VARCHAR, not INTEGER/DOUBLE)
result = re.sub(r"(AS\s+VARCHAR\)\s*)\+(\s*)", r"\1||\2", result, flags=re.IGNORECASE)
return result
def _translate_formula(formula: str | None) -> tuple[str | None, bool]:
"""Translate Tableau calc formula to SQL.
Returns:
(translated_sql, is_translatable) - if is_translatable is False,
the raw formula is returned as-is and should be stored in metadata.
"""
if formula is None:
return (None, True)
# Check for untranslatable constructs
if _has_lod_or_table_calc(formula):
return (formula, False)
# Strip // comments before translation (they can contain IF/THEN keywords)
# Must be string-aware to preserve '://' inside string literals
result = _strip_comments(formula).strip()
# Convert Tableau double-quoted string literals to SQL single quotes
result = _convert_double_quotes(result)
# Replace [Field] references with quoted column names (string-literal-aware)
result = _replace_field_refs(result)
# ZN(x) -> COALESCE(x, 0)
result = _replace_func_balanced(result, _ZN_RE, "COALESCE({arg}, 0)")
# IFNULL(x,y) -> COALESCE(x,y)
result = _IFNULL_RE.sub("COALESCE(", result)
# ISNULL(x) -> (x IS NULL)
result = _replace_func_balanced(result, _ISNULL_RE, "({arg} IS NULL)")
# IIF(c, t, f) -> CASE WHEN c THEN t ELSE f END (balanced-paren aware)
result = _translate_iif(result)
# IF c THEN t ELSE e END -> CASE WHEN c THEN t ELSE e END
# Apply repeatedly for nested IF blocks
prev = None
while prev != result:
prev = result
result = _IF_THEN_RE.sub(_if_to_case, result)
# CONTAINS(s, sub) -> s LIKE '%' || sub || '%' (balanced-paren aware)
result = _translate_contains(result)
# DATETRUNC('g', d) -> DATE_TRUNC('g', d)
result = _DATETRUNC_RE.sub("DATE_TRUNC(", result)
# COUNTD(x) -> COUNT(DISTINCT x)
result = _replace_func_balanced(result, _COUNTD_RE, "COUNT(DISTINCT {arg})")
# LEN(s) -> LENGTH(s)
result = _LEN_RE.sub("LENGTH(", result)
# INT/FLOAT/STR(x) -> CAST(x AS TYPE) with balanced parens
for func_name, template in _TABLEAU_CAST_FUNCS.items():
func_re = re.compile(rf"\b{func_name}\s*\(", re.IGNORECASE)
result = _replace_func_balanced(result, func_re, template)
# DATEADD('unit', n, date) -> date_add(date, INTERVAL (n) unit) (balanced-paren aware)
result = _translate_dateadd(result)
# Simple function renames (MID->SUBSTRING, FIND->STRPOS, etc.)
for pattern, replacement in _SIMPLE_RENAMES:
result = pattern.sub(replacement, result)
# Tableau uses + for string concatenation; SQL uses ||
# Convert + to || when adjacent to a string literal ('...')
result = _convert_string_concat(result)
return (result, True)
def _translate_contains(text: str) -> str:
"""Translate CONTAINS(s, sub) -> s LIKE '%' || sub || '%' with balanced args."""
result = text
for m in _CONTAINS_RE.finditer(text):
start = m.start()
open_paren = m.end() - 1
close_paren = _find_matching_paren(result, open_paren)
if close_paren == -1:
continue
inner = result[open_paren + 1 : close_paren]
args = _split_args_balanced(inner)
if len(args) >= 2:
s, sub = args[0], args[1]
replacement = f"{s} LIKE '%' || {sub} || '%'"
result = result[:start] + replacement + result[close_paren + 1 :]
return _translate_contains(result)
return result
def _translate_dateadd(text: str) -> str:
"""Translate DATEADD('unit', n, date) -> date_add(date, INTERVAL (n) unit) with balanced args."""
result = text
for m in _DATEADD_RE.finditer(text):
start = m.start()
open_paren = m.end() - 1
close_paren = _find_matching_paren(result, open_paren)
if close_paren == -1:
continue
inner = result[open_paren + 1 : close_paren]
args = _split_args_balanced(inner)
if len(args) >= 3:
unit = args[0].strip().strip("'\"").lower()
amount = args[1].strip()
date_expr = args[2].strip()
replacement = f"date_add({date_expr}, INTERVAL ({amount}) {unit})"
result = result[:start] + replacement + result[close_paren + 1 :]
return _translate_dateadd(result)
return result
def _if_to_case(match: re.Match) -> str:
"""Convert IF/THEN/ELSE/END to CASE WHEN."""
full = match.group(0)
# Simple IF c THEN t ELSE e END
# Use a simpler approach: replace IF with CASE WHEN, THEN stays, ELSE stays, END stays
result = re.sub(r"\bIF\b", "CASE WHEN", full, count=1, flags=re.IGNORECASE)
result = re.sub(r"\bELSEIF\b", "WHEN", result, flags=re.IGNORECASE)
return result
def _strip_brackets(name: str) -> str:
"""Strip Tableau bracket notation: [public].[orders] -> public.orders"""
return name.replace("[", "").replace("]", "")
def _normalize_column_name(name: str) -> str:
"""Normalize Tableau column name.
[calc_revenue] -> calc_revenue
[orders].[amount] -> amount (take last part for qualified names)
[none:Column Name:nk] -> Column Name (extract from colon-qualified format)
"""
stripped = _strip_brackets(name)
# Handle Tableau colon-qualified format: aggregation:name:qualifier
# e.g. "none:Burst Out Set list:nk"
if ":" in stripped:
parts = stripped.split(":")
if len(parts) >= 2:
# The column name is the middle part(s)
return ":".join(parts[1:-1]) if len(parts) > 2 else parts[1]
# For qualified names like orders.amount, take the last part
if "." in stripped:
return stripped.rsplit(".", 1)[-1]
return stripped
def _extract_table_name(relation_elem: ET.Element) -> str | None:
"""Extract qualified table name from a <relation type="table"> element."""
table_attr = relation_elem.get("table")
if table_attr:
return _strip_brackets(table_attr)
return None
# Namespace prefixes commonly used in Tableau XML files
_TABLEAU_NS_PREFIXES = [
"user",
"_.fcp.ObjectModelEncapsulateLegacy",
"_.fcp.ObjectModelTableType",
"_.fcp.SchemaViewerObjectModel",
]
# Regex to strip namespace-prefixed attributes (user:foo='bar' -> user_foo='bar')
# Only targets attribute positions (preceded by whitespace)
_NS_ATTR_RE = re.compile(r"(?<=\s)(\w[\w.]*):([\w][\w-]*)(?==)")
def _parse_tableau_xml(xml_path: Path) -> ET.Element:
"""Parse Tableau XML, handling undeclared namespace prefixes.
Tableau files use namespace-prefixed attributes (e.g. user:ui-builder)
without always declaring them. This causes ET.parse to fail with
"unbound prefix". We handle this by injecting namespace declarations
into the root element on retry.
"""
try:
tree = ET.parse(xml_path)
return tree.getroot()
except ET.ParseError:
content = xml_path.read_text(encoding="utf-8")
# Replace namespace-prefixed attributes with underscored versions
content = _NS_ATTR_RE.sub(r"\1_\2", content)
return ET.fromstring(content)
def _is_relation_tag(tag: str) -> bool:
"""Check if an XML tag name represents a relation element.
Handles plain 'relation', namespace-URI format '{uri}relation',
and Tableau's dotted format '_.fcp.ObjectModelEncapsulateLegacy.false...relation'.
"""
if tag == "relation":
return True
if tag.endswith("}relation"):
return True
# Tableau uses ...relation suffix for legacy/modern variants
if tag.endswith("relation") and ("." in tag or ":" in tag):
return True
return False
def _find_relation_element(connection: ET.Element) -> ET.Element | None:
"""Find the <relation> element inside a connection, handling namespace prefixes.
Tableau files may use namespace-prefixed relation tags like
<_.fcp.ObjectModelEncapsulateLegacy.false...relation>. This function
searches direct children first, preferring the '.false...' variant
(legacy format), then falls back to any relation with a type attribute.
"""
# Prefer logical-layer collections when both a physical fallback table and a
# collection relation are present.
for child in connection:
if _is_relation_tag(child.tag) and child.get("type") == "collection":
return child
# Direct child first (most common case)
rel = connection.find("relation")
if rel is not None:
return rel
# Search direct children for namespaced relation elements
# Prefer the .false... variant (legacy format, more complete)
candidates = []
for child in connection:
if _is_relation_tag(child.tag) and child.get("type"):
if ".false" in child.tag:
return child # Prefer legacy format
candidates.append(child)
if candidates:
return candidates[0]
return None
def _extract_join_columns(expr: ET.Element) -> list[tuple[str, str]]:
"""Extract all (left, right) column pairs from a join expression.
Handles simple equality (op='='), compound conditions (op='AND'),
and nested structures. Returns all predicates so multi-column joins
are fully preserved.
"""
op = expr.get("op", "")
sub_exprs = expr.findall("expression")
if op == "=" and len(sub_exprs) >= 2:
left = _strip_brackets(sub_exprs[0].get("op", ""))
right = _strip_brackets(sub_exprs[1].get("op", ""))
if left and right:
return [(left, right)]
return []
if op.upper() == "AND" and sub_exprs:
# Compound condition: collect ALL equality clauses
pairs = []
for child in sub_exprs:
pairs.extend(_extract_join_columns(child))
return pairs
return []
@dataclass
class _JoinInfo:
"""Internal representation of a parsed join."""
right_table: str
right_table_qualified: str
join_type: str # inner, left, right, full, cross
column_pairs: list[tuple[str, str]] # [(left_col, right_col), ...]
@dataclass
class _CollectionInfo:
"""Ordered table info for Tableau logical-layer collections."""
tables: list[tuple[str, str]]
@property
def base_table_name(self) -> str | None:
return self.tables[0][0] if self.tables else None
@property
def base_table_qualified(self) -> str | None:
return self.tables[0][1] if self.tables else None
@property
def table_map(self) -> dict[str, str]:
return dict(self.tables)
@dataclass
class _ObjectGraphJoin:
"""Join edge extracted from a Tableau object-graph."""
first_table: str
second_table: str
column_pairs: list[tuple[str, str]] # [(first_field, second_field), ...]
@dataclass
class _ObjectGraphInfo:
"""Structured object-graph output for logical-layer datasources."""
relationships: list[Relationship]
joins: list[_ObjectGraphJoin]
def _quote_sql_identifier(identifier: str) -> str:
"""Quote a SQL identifier for generated Tableau-derived SQL."""
return '"' + identifier.replace('"', '""') + '"'
_NUMERIC_LITERAL_RE = re.compile(r"^-?\d+(\.\d+)?$")
def _quote_identifier_if_needed(identifier: str) -> str:
"""Quote a raw Tableau field name when it is not a simple SQL identifier.
Passes through numeric literals and already-quoted identifiers unchanged.
"""
if identifier.startswith('"') and identifier.endswith('"'):
return identifier
if _NUMERIC_LITERAL_RE.match(identifier):
return identifier
if _SIMPLE_SQL_IDENTIFIER_RE.match(identifier):
return identifier
if "." in identifier:
return _quote_column_reference(identifier)
return _quote_sql_identifier(identifier)
def _quote_column_reference(column_name: str) -> str:
"""Quote a possibly-qualified column reference.
Passes through numeric literals unchanged.
"""
stripped = _strip_brackets(column_name)
if _NUMERIC_LITERAL_RE.match(stripped):
return stripped
parts = stripped.split(".")
return ".".join(_quote_identifier_if_needed(part) for part in parts if part)
def _quote_table_reference(table_name: str) -> str:
"""Quote a possibly-qualified table reference."""
parts = _strip_brackets(table_name).split(".")
return ".".join(_quote_sql_identifier(part) for part in parts if part)
def _normalize_parent_name(name: str | None) -> str | None:
"""Normalize a Tableau parent-name/table identifier to its logical table name."""
if not name:
return None
stripped = _strip_brackets(name)
return stripped.rsplit(".", 1)[-1]
class TableauAdapter(BaseAdapter):
"""Adapter for importing Tableau .tds/.twb/.tdsx/.twbx datasource definitions.
Transforms Tableau definitions into Sidemantic format:
- Data sources -> Models
- Columns with role=dimension -> Dimensions
- Columns with role=measure -> Metrics
- Drill paths -> Dimension hierarchies
- Joins -> Relationships
- Groups -> Segments
"""
def parse(self, source: str | Path) -> SemanticGraph:
"""Parse Tableau files into semantic graph.
Args:
source: Path to .tds/.twb/.tdsx/.twbx file or directory
Returns:
Semantic graph with imported models
"""
graph = SemanticGraph()
source_path = Path(source)
if source_path.is_dir():
for file_path in sorted(source_path.rglob("*")):
if file_path.suffix.lower() in (".tds", ".twb"):
file_graph = self._parse_xml(file_path)
for model in file_graph.models.values():
graph.add_model(model)
elif file_path.suffix.lower() in (".tdsx", ".twbx"):
file_graph = self._unzip_and_parse(file_path)
for model in file_graph.models.values():
graph.add_model(model)
elif source_path.suffix.lower() in (".tdsx", ".twbx"):
graph = self._unzip_and_parse(source_path)
else:
graph = self._parse_xml(source_path)
return graph
def _parse_xml(self, xml_path: Path) -> SemanticGraph:
"""Parse a .tds or .twb XML file."""
graph = SemanticGraph()
root = _parse_tableau_xml(xml_path)
if root.tag == "datasource":
model = self._parse_datasource(root)
if model:
graph.add_model(model)
elif root.tag == "workbook":
datasources = root.find("datasources")
if datasources is not None:
for ds_elem in datasources.findall("datasource"):
# Skip the Parameters datasource
name = ds_elem.get("formatted-name") or ds_elem.get("name") or ""
if name.lower() == "parameters":
continue
model = self._parse_datasource(ds_elem)
if model:
graph.add_model(model)
return graph
def _parse_datasource(self, ds_elem: ET.Element) -> Model | None:
"""Parse a single <datasource> element into a Model."""
# Extract name
name = ds_elem.get("formatted-name") or ds_elem.get("name") or ds_elem.get("caption")
if not name:
return None
# Extract table reference and join info
table = None
sql = None
relationships: list[Relationship] = []
collection_info: _CollectionInfo | None = None
connection = ds_elem.find("connection")
if connection is not None:
relation = _find_relation_element(connection)
if relation is not None:
rel_type = relation.get("type")
if rel_type == "table":
table = _extract_table_name(relation)
elif rel_type == "join":
base_table, joins = self._parse_relation_tree(relation)
if joins:
sql = self._build_join_sql(base_table, joins)
relationships = self._extract_relationships(joins)
else:
table = base_table
elif rel_type == "text":
# Custom SQL
sql = relation.text or relation.get("table")
elif rel_type == "collection":
collection_info = self._parse_collection(relation)
table = collection_info.base_table_qualified
# Build metadata lookup from <metadata-records> before object-graph parsing so
# collection sources can build a projected joined SQL model.
metadata_lookup = self._build_metadata_lookup(ds_elem)
# Parse object-graph for relationships (Tableau 2020.2+ data model)
# The object-graph is a sibling of <connection>, not inside it
object_graph = self._parse_object_graph(ds_elem)
if collection_info and object_graph.joins:
sql = self._build_collection_sql(collection_info, object_graph.joins, metadata_lookup)
table = None if sql else collection_info.base_table_qualified
relationships = object_graph.relationships
elif not relationships and object_graph.relationships:
relationships = object_graph.relationships
# Parse columns
dimensions: list[Dimension] = []
metrics: list[Metric] = []
seen_column_names: set[str] = set()
for col_elem in ds_elem.findall("column"):
result = self._parse_column(col_elem, metadata_lookup)
if result is None:
continue
seen_column_names.add(result.name)
if isinstance(result, Dimension):
dimensions.append(result)
elif isinstance(result, Metric):
metrics.append(result)
# Import orphan columns from metadata-records (physical columns with no
# explicit <column> element, i.e. never customized by the user in Tableau)
self._import_orphan_metadata_columns(metadata_lookup, seen_column_names, dimensions, metrics)
# Apply drill-path hierarchies
self._apply_drill_paths(ds_elem, dimensions)
# Parse groups as segments
segments = self._parse_groups_as_segments(ds_elem)
# Determine primary key
primary_key = self._infer_primary_key(dimensions, metrics, metadata_lookup, collection_info)
if collection_info and sql:
sql = self._inject_collection_primary_key_sql(
sql,
primary_key,
collection_info,
metadata_lookup,
)
primary_key = "__tableau_pk"
model = Model(
name=name,
table=table,
sql=sql,
primary_key=primary_key,
dimensions=dimensions,
metrics=metrics,
relationships=relationships,
segments=segments,
)
return model
def _parse_column(
self,
col_elem: ET.Element,
metadata_lookup: dict[str, dict],
) -> Dimension | Metric | None:
"""Parse a single <column> element into a Dimension or Metric."""
raw_name = col_elem.get("name")
if not raw_name:
return None
col_name = _normalize_column_name(raw_name)
role = col_elem.get("role")
datatype = col_elem.get("datatype")
caption = col_elem.get("caption")
hidden = col_elem.get("hidden", "").lower() == "true"
aggregation = col_elem.get("aggregation")
# Check for calculated field
calc_elem = col_elem.find("calculation")
formula = None
if calc_elem is not None:
formula = calc_elem.get("formula")
# Try metadata lookup for additional type info
meta_info = metadata_lookup.get(raw_name, {})
if not datatype:
datatype = meta_info.get("local_type")
if not aggregation:
aggregation = meta_info.get("aggregation")
# Translate formula if present
sql_expr = None
is_translatable = True
metadata = None
if formula:
sql_expr, is_translatable = _translate_formula(formula)
if not is_translatable:
metadata = {"tableau_formula": formula}
# Untranslatable formulas (LOD, table calcs) produce non-queryable fields
# with NULL sql to prevent raw Tableau syntax in generated SQL
if not is_translatable:
hidden = True