-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtmdl-parser.js
More file actions
896 lines (788 loc) · 32.6 KB
/
tmdl-parser.js
File metadata and controls
896 lines (788 loc) · 32.6 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
/**
* TMDL Parser Module
* Line-by-line state machine parser for TMDL files
* Handles: database.tmdl, model.tmdl, tables/*.tmdl, relationships.tmdl, roles/*.tmdl, expressions.tmdl
*/
class TMDLParser {
constructor() {
this.model = {
database: null,
model: null,
tables: [],
relationships: [],
roles: [],
expressions: []
};
this.errors = [];
}
/**
* Parse all TMDL files from a semantic model definition folder
* @param {Object} files - Map of filename to content
* @returns {Object} Parsed model
*/
parseAll(files) {
// Parse database.tmdl
if (files['database.tmdl']) {
this.model.database = this.parseDatabase(files['database.tmdl']);
}
// Parse model.tmdl
if (files['model.tmdl']) {
this.model.model = this.parseModel(files['model.tmdl']);
}
// Parse relationships.tmdl
if (files['relationships.tmdl']) {
this.model.relationships = this.parseRelationships(files['relationships.tmdl']);
}
// Parse expressions.tmdl
if (files['expressions.tmdl']) {
this.model.expressions = this.parseExpressions(files['expressions.tmdl']);
}
// Parse table files
const tableFiles = Object.keys(files).filter(f => f.startsWith('tables/'));
for (const tableFile of tableFiles) {
try {
const table = this.parseTable(files[tableFile], tableFile);
if (table) {
// Tag auto-date tables for optional filtering
if (/^LocalDateTable_|^DateTableTemplate_/.test(table.name)) {
table._isAutoDate = true;
}
// Tag calc-group tables
if (table.calculationGroup) {
table._isCalcGroup = true;
}
// Tag field-parameter tables (any partition source or column expression uses NAMEOF)
const fpExpressions = [
...table.partitions.map(p => p.source || ''),
...table.columns.map(c => c.expression || '')
];
if (fpExpressions.some(expr => /\bNAMEOF\s*\(/i.test(expr))) {
table._isFieldParameter = true;
}
this.model.tables.push(table);
}
} catch (err) {
this.errors.push({ file: tableFile, line: null, message: err.message });
}
}
// Parse role files
const roleFiles = Object.keys(files).filter(f => f.startsWith('roles/'));
for (const roleFile of roleFiles) {
try {
const role = this.parseRole(files[roleFile], roleFile);
if (role) {
this.model.roles.push(role);
}
} catch (err) {
this.errors.push({ file: roleFile, line: null, message: err.message });
}
}
// Sort tables alphabetically
this.model.tables.sort((a, b) => a.name.localeCompare(b.name));
return this.model;
}
/**
* Parse database.tmdl
*/
parseDatabase(content) {
const result = { name: null, compatibilityLevel: null };
const lines = content.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('database')) {
result.name = this._extractName(trimmed, 'database');
} else if (trimmed.startsWith('compatibilityLevel:')) {
result.compatibilityLevel = trimmed.split(':')[1]?.trim();
}
}
return result;
}
/**
* Parse model.tmdl
*/
parseModel(content) {
const result = { name: null, culture: null, defaultPowerBIDataSourceVersion: null, legacyRedirects: null, returnErrorValuesAsNull: null };
const lines = content.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('model Model')) {
result.name = 'Model';
} else if (trimmed.startsWith('culture:')) {
result.culture = trimmed.split(':')[1]?.trim();
} else if (trimmed.startsWith('defaultPowerBIDataSourceVersion:')) {
result.defaultPowerBIDataSourceVersion = trimmed.split(':')[1]?.trim();
} else if (trimmed.startsWith('legacyRedirects:')) {
result.legacyRedirects = trimmed.split(':')[1]?.trim();
} else if (trimmed.startsWith('returnErrorValuesAsNull:')) {
result.returnErrorValuesAsNull = trimmed.split(':')[1]?.trim();
}
}
return result;
}
/**
* Parse a table .tmdl file using state machine
*/
parseTable(content, fileName) {
const lines = content.split('\n');
const table = {
name: null,
description: null,
isHidden: false,
columns: [],
measures: [],
hierarchies: [],
partitions: [],
calculationGroup: null,
refreshPolicy: null
};
let state = 'IDLE';
let currentObject = null;
let currentExpression = [];
let pendingDescription = null;
let baseIndent = 0;
let expressionIndent = 0;
let inBacktickBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const trimmed = line.trim();
const indent = line.search(/\S/);
// Handle triple-backtick blocks
if (trimmed === '```') {
inBacktickBlock = !inBacktickBlock;
if (state === 'EXPRESSION') {
currentExpression.push(trimmed);
}
continue;
}
if (inBacktickBlock && state === 'EXPRESSION') {
currentExpression.push(line);
continue;
}
// Description comments (/// lines)
if (trimmed.startsWith('///')) {
const descText = trimmed.substring(3).trim();
if (pendingDescription) {
pendingDescription += '\n' + descText;
} else {
pendingDescription = descText;
}
continue;
}
// Skip regular comments
if (trimmed.startsWith('//') || trimmed === '') {
continue;
}
// Top-level: table declaration
if (indent === 0 && trimmed.startsWith('table')) {
this._finishCurrentObject(state, currentObject, currentExpression, table);
table.name = this._extractName(trimmed, 'table');
if (pendingDescription) {
table.description = pendingDescription;
pendingDescription = null;
}
state = 'TABLE_BODY';
baseIndent = 0;
continue;
}
// Object headers at indent level 1 (typically a single tab or spaces)
if (state !== 'IDLE' && indent > 0 && indent <= 4) {
// Check for new object declarations
const objectType = this._detectObjectType(trimmed);
if (objectType) {
// Save previous object
this._finishCurrentObject(state, currentObject, currentExpression, table);
currentExpression = [];
const name = this._extractName(trimmed, objectType);
currentObject = {
type: objectType,
name: name,
description: pendingDescription || null,
properties: {}
};
pendingDescription = null;
baseIndent = indent;
// Check if line contains '=' (expression follows on same line or next)
if (trimmed.includes('=')) {
const eqIndex = trimmed.indexOf('=');
const afterEq = trimmed.substring(eqIndex + 1).trim();
if (afterEq) {
currentExpression.push(afterEq);
}
state = 'EXPRESSION';
expressionIndent = indent + 1;
} else {
state = 'PROPERTIES';
}
continue;
}
}
// Inside expression (multi-line DAX, M, etc.)
if (state === 'EXPRESSION') {
// Expression continues while indent is deeper than object or we're collecting
if (indent > baseIndent || trimmed === '') {
currentExpression.push(line);
continue;
} else {
// Expression ended, process this line as a property or new object
state = 'PROPERTIES';
// Fall through to property handling
}
}
// Properties
if (state === 'PROPERTIES' || state === 'TABLE_BODY') {
// Bare boolean flags (no colon, no value) — e.g. isHidden, isNameInferred
if (indent > baseIndent && /^(isHidden|isNameInferred|isKey|isNullable)$/.test(trimmed)) {
if (currentObject) {
currentObject.properties[trimmed] = 'true';
} else if (state === 'TABLE_BODY') {
if (trimmed === 'isHidden') table.isHidden = true;
}
continue;
}
if (indent > baseIndent && trimmed.includes(':')) {
// Check for 'expression =' or 'source =' which starts a new expression block
if (/^(?:expression|source|sourceExpression)\s*=/.test(trimmed)) {
const afterEq = trimmed.split('=').slice(1).join('=').trim();
if (afterEq) {
currentExpression.push(afterEq);
}
state = 'EXPRESSION';
expressionIndent = indent + 1;
continue;
}
const colonIndex = trimmed.indexOf(':');
const key = trimmed.substring(0, colonIndex).trim();
const value = trimmed.substring(colonIndex + 1).trim();
if (state === 'TABLE_BODY' && !currentObject) {
// Table-level properties
if (key === 'isHidden') {
table.isHidden = value === 'true';
}
} else if (currentObject) {
currentObject.properties[key] = value;
}
continue;
}
// Check for annotation or extendedProperty blocks
if (indent > baseIndent && (trimmed.startsWith('annotation') || trimmed.startsWith('extendedProperty'))) {
// Capture PBI_ResultType for partition refresh state
if (currentObject && trimmed.startsWith('annotation PBI_ResultType =')) {
const val = trimmed.split('=')[1]?.trim().replace(/^['"]|['"]$/g, '');
currentObject.properties.pbiResultType = val;
}
continue;
}
}
// Handle expression start on property lines
if ((state === 'PROPERTIES' || state === 'TABLE_BODY') && currentObject) {
if (indent > baseIndent && trimmed.startsWith('=')) {
const afterEq = trimmed.substring(1).trim();
if (afterEq) {
currentExpression.push(afterEq);
}
state = 'EXPRESSION';
expressionIndent = indent + 1;
continue;
}
}
}
// Finish last object
this._finishCurrentObject(state, currentObject, currentExpression, table);
return table;
}
/**
* Detect object type from a line
*/
_detectObjectType(line) {
const types = ['column', 'measure', 'hierarchy', 'partition', 'calculationGroup', 'calculationItem', 'level', 'role', 'refreshPolicy'];
for (const type of types) {
if (line === type || line.startsWith(type + ' ') || line.startsWith(type + '\t')) {
return type;
}
}
return null;
}
/**
* Finish current object and add to table
*/
_finishCurrentObject(state, currentObject, currentExpression, table) {
if (!currentObject) return;
const expressionText = currentExpression.length > 0
? this._cleanExpression(currentExpression)
: null;
switch (currentObject.type) {
case 'column':
table.columns.push({
name: currentObject.name,
description: currentObject.description,
dataType: currentObject.properties.dataType || null,
formatString: currentObject.properties.formatString || null,
isHidden: currentObject.properties.isHidden === 'true',
sourceColumn: currentObject.properties.sourceColumn || null,
summarizeBy: currentObject.properties.summarizeBy || null,
sortByColumn: currentObject.properties.sortByColumn || null,
displayFolder: currentObject.properties.displayFolder || null,
dataCategory: currentObject.properties.dataCategory || null,
expression: expressionText
});
break;
case 'measure':
table.measures.push({
name: currentObject.name,
description: currentObject.description,
expression: expressionText,
displayFolder: currentObject.properties.displayFolder || null,
formatString: currentObject.properties.formatString || null,
formatStringExpression: currentObject.properties.formatStringExpression || null,
dataCategory: currentObject.properties.dataCategory || null
});
break;
case 'hierarchy':
table.hierarchies.push({
name: currentObject.name,
description: currentObject.description,
levels: [] // Levels are parsed as sub-objects
});
break;
case 'level':
// Add to last hierarchy
if (table.hierarchies.length > 0) {
table.hierarchies[table.hierarchies.length - 1].levels.push({
name: currentObject.name,
column: currentObject.properties.column || null,
ordinal: currentObject.properties.ordinal || null
});
}
break;
case 'partition':
table.partitions.push({
name: currentObject.name,
mode: currentObject.properties.mode || null,
source: expressionText,
sourceType: currentObject.properties.type || null,
lastRefreshState: currentObject.properties.pbiResultType || null
});
break;
case 'calculationGroup':
table.calculationGroup = {
items: [],
precedence: currentObject.properties.precedence != null
? parseInt(currentObject.properties.precedence, 10) : null
};
break;
case 'calculationItem':
if (table.calculationGroup) {
table.calculationGroup.items.push({
name: currentObject.name,
expression: expressionText,
ordinal: currentObject.properties.ordinal != null
? parseInt(currentObject.properties.ordinal, 10) : null,
formatStringExpression: currentObject.properties.formatStringExpression || null
});
}
break;
case 'refreshPolicy':
table.refreshPolicy = {
policyType: currentObject.properties.policyType || null,
rollingWindowGranularity: currentObject.properties.rollingWindowGranularity || null,
rollingWindowPeriods: currentObject.properties.rollingWindowPeriods != null
? parseInt(currentObject.properties.rollingWindowPeriods, 10) : null,
incrementalGranularity: currentObject.properties.incrementalGranularity || null,
incrementalPeriods: currentObject.properties.incrementalPeriods != null
? parseInt(currentObject.properties.incrementalPeriods, 10) : null,
pollingExpression: currentObject.properties.pollingExpression || null,
sourceExpression: expressionText
};
break;
}
}
/**
* Clean a multi-line expression
*/
_cleanExpression(lines) {
if (lines.length === 0) return null;
// Find minimum indentation (excluding empty lines)
const nonEmptyLines = lines.filter(l => l.trim() !== '');
if (nonEmptyLines.length === 0) return null;
const minIndent = Math.min(...nonEmptyLines.map(l => {
const match = l.match(/^(\s*)/);
return match ? match[1].length : 0;
}));
// Remove common indentation
const cleaned = lines.map(l => {
if (l.trim() === '') return '';
return l.substring(Math.min(minIndent, l.search(/\S/) >= 0 ? l.search(/\S/) : 0));
});
// Remove leading/trailing empty lines
while (cleaned.length > 0 && cleaned[0].trim() === '') cleaned.shift();
while (cleaned.length > 0 && cleaned[cleaned.length - 1].trim() === '') cleaned.pop();
return cleaned.join('\n');
}
/**
* Parse relationships.tmdl
*/
parseRelationships(content) {
const relationships = [];
const lines = content.split('\n');
let currentRel = null;
for (const line of lines) {
const trimmed = line.trim();
const indent = line.search(/\S/);
if (indent === 0 && trimmed.startsWith('relationship')) {
if (currentRel) relationships.push(this._finalizeRel(currentRel));
currentRel = {
id: this._extractName(trimmed, 'relationship'),
fromTable: null,
fromColumn: null,
toTable: null,
toColumn: null,
fromCardinality: null,
toCardinality: null,
crossFilteringBehavior: null,
securityFilteringBehavior: null,
isActive: true
};
continue;
}
if (currentRel && indent > 0 && trimmed.includes(':')) {
const colonIndex = trimmed.indexOf(':');
const key = trimmed.substring(0, colonIndex).trim();
const value = trimmed.substring(colonIndex + 1).trim();
switch (key) {
case 'fromColumn':
const fromParts = this._parseColumnRef(value);
currentRel.fromTable = fromParts.table;
currentRel.fromColumn = fromParts.column;
break;
case 'toColumn':
const toParts = this._parseColumnRef(value);
currentRel.toTable = toParts.table;
currentRel.toColumn = toParts.column;
break;
case 'fromCardinality':
currentRel.fromCardinality = value;
break;
case 'toCardinality':
currentRel.toCardinality = value;
break;
case 'crossFilteringBehavior':
currentRel.crossFilteringBehavior = value;
break;
case 'securityFilteringBehavior':
currentRel.securityFilteringBehavior = value;
break;
case 'isActive':
currentRel.isActive = value !== 'false';
break;
}
}
}
if (currentRel) relationships.push(this._finalizeRel(currentRel));
return relationships;
}
_finalizeRel(rel) {
const from = rel.fromCardinality || 'many';
const to = rel.toCardinality || 'one';
rel.cardinality = `${from}:${to}`;
return rel;
}
/**
* Parse a column reference like "'Table Name'.ColumnName" or "Table.Column"
*/
_parseColumnRef(value) {
// Pattern: 'Table Name'.Column or Table.Column
const quotedMatch = value.match(/^'([^']+)'\.(.+)$/);
if (quotedMatch) {
return { table: quotedMatch[1], column: quotedMatch[2].trim() };
}
const dotIndex = value.indexOf('.');
if (dotIndex > 0) {
return {
table: value.substring(0, dotIndex).trim(),
column: value.substring(dotIndex + 1).trim()
};
}
return { table: null, column: value.trim() };
}
/**
* Parse roles/*.tmdl
*/
parseRole(content, fileName) {
const lines = content.split('\n');
const role = {
name: null,
description: null,
modelPermission: null,
tablePermissions: []
};
let currentPermission = null;
let inFilterExpression = false;
let filterLines = [];
for (const line of lines) {
const trimmed = line.trim();
const indent = line.search(/\S/);
if (indent === 0 && trimmed.startsWith('role')) {
role.name = this._extractName(trimmed, 'role');
continue;
}
if (trimmed.startsWith('modelPermission:')) {
role.modelPermission = trimmed.split(':')[1]?.trim();
continue;
}
if (trimmed.startsWith('tablePermission')) {
if (currentPermission) {
if (filterLines.length > 0) {
currentPermission.filterExpression = filterLines.join('\n').trim();
}
role.tablePermissions.push(currentPermission);
}
currentPermission = {
table: this._extractName(trimmed, 'tablePermission'),
filterExpression: null
};
filterLines = [];
inFilterExpression = false;
continue;
}
if (currentPermission && trimmed.startsWith('filterExpression:')) {
const afterColon = trimmed.split(':').slice(1).join(':').trim();
if (afterColon) filterLines.push(afterColon);
inFilterExpression = true;
continue;
}
if (inFilterExpression && indent > 2) {
filterLines.push(trimmed);
continue;
}
if (trimmed.startsWith('///') && !role.description) {
role.description = trimmed.substring(3).trim();
}
}
if (currentPermission) {
if (filterLines.length > 0) {
currentPermission.filterExpression = filterLines.join('\n').trim();
}
role.tablePermissions.push(currentPermission);
}
return role;
}
/**
* Parse expressions.tmdl
*/
parseExpressions(content) {
const expressions = [];
const lines = content.split('\n');
let currentExpr = null;
let exprLines = [];
let inExpression = false;
let inBacktickBlock = false;
for (const line of lines) {
const trimmed = line.trim();
const indent = line.search(/\S/);
// Triple-backtick fence toggle
if (trimmed === '```') {
if (inBacktickBlock) {
// End of backtick block — close current expression body
inBacktickBlock = false;
} else if (currentExpr) {
// Start of backtick block
inBacktickBlock = true;
inExpression = true;
}
continue;
}
if (inBacktickBlock) {
exprLines.push(line);
continue;
}
if (indent === 0 && trimmed.startsWith('expression')) {
if (currentExpr) {
currentExpr.expression = exprLines.join('\n').trim();
expressions.push(currentExpr);
}
currentExpr = {
name: this._extractName(trimmed, 'expression'),
kind: null,
expression: null
};
exprLines = [];
inExpression = false;
// Check for '=' on the same line (may be followed by ``` or inline M)
if (trimmed.includes('=')) {
const afterEq = trimmed.substring(trimmed.indexOf('=') + 1).trim();
if (afterEq && afterEq !== '```') {
exprLines.push(afterEq);
inExpression = true;
} else if (afterEq === '```') {
inBacktickBlock = true;
inExpression = true;
} else {
inExpression = true;
}
}
continue;
}
if (currentExpr) {
if (trimmed.startsWith('kind:')) {
currentExpr.kind = trimmed.split(':')[1]?.trim();
continue;
}
if (trimmed.startsWith('annotation ')) {
// Skip annotation lines inside expressions block
continue;
}
if (indent > 0 && (inExpression || trimmed.startsWith('='))) {
if (trimmed.startsWith('=')) {
const afterEq = trimmed.substring(1).trim();
if (afterEq && afterEq !== '```') {
exprLines.push(afterEq);
} else if (afterEq === '```') {
inBacktickBlock = true;
}
} else {
exprLines.push(trimmed);
}
inExpression = true;
}
}
}
if (currentExpr) {
currentExpr.expression = exprLines.join('\n').trim();
expressions.push(currentExpr);
}
return expressions;
}
/**
* Extract name from a declaration line
* Handles: keyword 'Name With Spaces' and keyword SimpleName
*/
_extractName(line, keyword) {
const afterKeyword = line.substring(keyword.length).trim();
// Remove trailing '=' or content after '='
const eqIndex = afterKeyword.indexOf('=');
const nameStr = eqIndex >= 0 ? afterKeyword.substring(0, eqIndex).trim() : afterKeyword;
// Quoted name
const quotedMatch = nameStr.match(/^'([^']+)'/);
if (quotedMatch) return quotedMatch[1];
// Unquoted name (first word or identifier)
const unquoted = nameStr.split(/\s/)[0];
return unquoted || nameStr;
}
/**
* Extract DAX references from all measures
* @returns {Object} Map of measure name → { measureRefs, columnRefs, tableRefs }
*/
extractAllReferences() {
const refs = {};
for (const table of this.model.tables) {
for (const measure of table.measures) {
if (measure.expression) {
refs[measure.name] = DAXReferenceExtractor.extract(measure.expression);
refs[measure.name].table = table.name;
}
}
// Also extract references from calculated columns
for (const col of table.columns) {
if (col.expression) {
const key = `${table.name}[${col.name}]`;
refs[key] = DAXReferenceExtractor.extract(col.expression);
refs[key].table = table.name;
refs[key].isCalculatedColumn = true;
}
}
}
return refs;
}
}
/**
* DAX Reference Extractor
* Regex-based extraction of table, column, and measure references from DAX
*/
class DAXReferenceExtractor {
/**
* Extract all references from a DAX expression
*/
static extract(dax) {
if (!dax) return { measureRefs: [], columnRefs: [], tableRefs: [] };
const cleaned = this._cleanDAX(dax);
return {
measureRefs: this._extractMeasureRefs(cleaned),
columnRefs: this._extractColumnRefs(cleaned),
tableRefs: this._extractTableRefs(cleaned)
};
}
/**
* Clean DAX by removing comments and string literals
*/
static _cleanDAX(dax) {
let cleaned = dax.replace(/\/\*[\s\S]*?\*\//g, '');
cleaned = cleaned.replace(/\/\/.*/g, '');
cleaned = cleaned.replace(/"[^"]*"/g, '""');
return cleaned;
}
/**
* Extract measure references [MeasureName]
*/
static _extractMeasureRefs(dax) {
const refs = new Set();
const pattern = /(?<!'[^']*)\[([^\]]+)\]/g;
let match;
while ((match = pattern.exec(dax)) !== null) {
// Only standalone [Name] without table prefix
const beforeBracket = dax.substring(Math.max(0, match.index - 1), match.index);
if (beforeBracket !== '.' && !/\w/.test(beforeBracket) && beforeBracket !== "'") {
refs.add(match[1].trim());
}
}
return Array.from(refs);
}
/**
* Extract column references Table[Column] or 'Table Name'[Column]
*/
static _extractColumnRefs(dax) {
const refs = [];
const seen = new Set();
const pattern = /(?:'([^']+)'|(\w+))\[([^\]]+)\]/g;
let match;
while ((match = pattern.exec(dax)) !== null) {
const table = match[1] || match[2];
const column = match[3].trim();
const key = `${table}|${column}`;
if (!seen.has(key)) {
seen.add(key);
refs.push({ table, column });
}
}
return refs;
}
/**
* Build a lookup map of measure name → table name
* @param {Array} tables - Parsed tables from the model
* @returns {Map<string, string>} Map of measureName → tableName
*/
static buildMeasureLookup(tables) {
const lookup = new Map();
for (const table of tables) {
for (const measure of table.measures) {
lookup.set(measure.name, table.name);
}
}
return lookup;
}
/**
* Extract table references from functions like COUNTROWS(Table), ALL(Table)
*/
static _extractTableRefs(dax) {
const refs = new Set();
const pattern = /(?:COUNTROWS|RELATEDTABLE|VALUES|ALL|ALLEXCEPT|ALLSELECTED|ALLNOBLANKROW|REMOVEFILTERS|DISTINCT|SUMMARIZE|SUMMARIZECOLUMNS|ADDCOLUMNS|SELECTCOLUMNS|FILTER|CALCULATETABLE|TOPN|GENERATE|GENERATESERIES|NATURALLEFTOUTERJOIN|NATURALINNERJOIN|CROSSJOIN|UNION|INTERSECT|EXCEPT|TREATAS|LOOKUPVALUE|RELATED|RANKX|SAMPLE|GROUPBY|DATATABLE|WINDOW|OFFSET|INDEX)\s*\(\s*(?:'([^']+)'|(\w+))\s*(?:[,)])/gi;
let match;
while ((match = pattern.exec(dax)) !== null) {
refs.add(match[1] || match[2]);
}
return Array.from(refs);
}
}
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = { TMDLParser, DAXReferenceExtractor };
}