ripbi-core 0.3.4

Static analysis engine for Power BI semantic models: TMDL and PBIR ingestion, DAX reference extraction, dependency graph, and reachability
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
//! Format-agnostic tabular AST: the normalized shape every source format
//! (TMDL, TMSL `model.bim`, `.pbix` `DataModelSchema`) is parsed into.
//!
//! The types here are plain data with no parsing or I/O behaviour. Their only logic is
//! the expression enumeration at the bottom of this module
//! ([`TabularDatabase::dax_expressions`] and [`TabularDatabase::m_expressions`]), which
//! is the single place that knows where expressions live. The graph layer consumes those
//! two functions instead of walking the AST itself, so a new expression-bearing field
//! cannot be silently omitted from reachability analysis.
//!
//! Name-based lookup lives in the [`index`] submodule; the handle accessors on
//! [`TabularDatabase`] ([`table`](TabularDatabase::table),
//! [`column`](TabularDatabase::column), … and [`object_id`](TabularDatabase::object_id))
//! turn the handles it hands out back into borrowed AST nodes.
//!
//! String fields hold names with their original casing and compare case-sensitively.
//! Case-insensitive comparison is the job of [`crate::identity::NameKey`], which these
//! names are converted into when they become graph nodes.

pub mod index;

use crate::identity::{NameKey, ObjectId};
use crate::model::index::{
    ColumnHandle, ExpressionHandle, FunctionHandle, HierarchyHandle, MeasureHandle, Resolved,
    TableHandle,
};

/// Normalized semantic model, regardless of source format (TMDL, model.bim,
/// .pbix DataModelSchema). Downstream code never branches on source format.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TabularDatabase {
    /// Model name, when the source format records one.
    pub name: Option<String>,
    /// Tables in source order.
    pub tables: Vec<Table>,
    /// Relationships between table columns.
    pub relationships: Vec<Relationship>,
    /// Row-level-security roles.
    pub roles: Vec<Role>,
    /// Model-level shared M expressions (TMDL expressions.tmdl / TMSL
    /// model.expressions): Power Query parameters and shared queries.
    pub expressions: Vec<SharedExpression>,
    /// User-defined DAX functions (TOM functions). Names are model-global.
    pub functions: Vec<Function>,
}

/// A table and everything defined on it.
///
/// A calculation-group table carries its synthetic columns (the group's field column
/// and its ordinal column) in `columns` like any other table; nothing distinguishes
/// them structurally from data columns.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Table {
    /// Table name.
    pub name: String,
    /// Columns in source order.
    pub columns: Vec<Column>,
    /// Measures whose home table this is.
    pub measures: Vec<Measure>,
    /// Partitions supplying the table's rows.
    pub partitions: Vec<Partition>,
    /// The table's incremental refresh policy (TOM refreshPolicy), when configured.
    pub refresh_policy: Option<RefreshPolicy>,
    /// User-defined hierarchies.
    pub hierarchies: Vec<Hierarchy>,
    /// Calendars (TOM calendars) binding groups of the table's columns.
    pub calendars: Vec<Calendar>,
    /// In TOM a calculation group is a property of a table.
    pub calculation_group: Option<CalculationGroup>,
    /// DAX defaultDetailRowsDefinition (drillthrough detail rows).
    pub detail_rows_expression: Option<String>,
    /// Hidden from report authors; hidden objects are still live if referenced.
    pub is_hidden: bool,
    /// Engine-private (TOM isPrivate): reserved for the engine, never authored
    /// against. Display-only metadata — never liveness.
    pub is_private: bool,
    /// An engine-generated auto date/time table serving one date column
    /// (TOM annotation `__PBI_LocalDateTable`; name-prefix fallback). Hidden
    /// machinery a report cannot author against directly. Display-only
    /// metadata — never liveness; the graph layer reads it for the
    /// auto-date/time verdict
    /// ([`DependencyGraph::auto_date_time_tables`](crate::graph::DependencyGraph::auto_date_time_tables)).
    pub is_local_date_table: bool,
    /// The engine-generated date table template the `LocalDateTable_*` family
    /// is derived from (TOM annotation `__PBI_TemplateDateTable`; name-prefix
    /// fallback). Display-only metadata — never liveness; see
    /// [`Self::is_local_date_table`].
    pub is_template_date_table: bool,
}

impl Table {
    /// A calculated table is a table whose partition source is DAX.
    ///
    /// There is no flag for this in TOM, and none here: the partition decides.
    ///
    /// # Examples
    ///
    /// ```
    /// use ripbi_core::{Partition, PartitionSource, Table};
    ///
    /// let top_products = Table {
    ///     name: "Top Products".to_string(),
    ///     partitions: vec![Partition {
    ///         name: "Top Products".to_string(),
    ///         source: PartitionSource::Calculated {
    ///             expression: "TOPN(10, Products, Products[Sales])".to_string(),
    ///         },
    ///     }],
    ///     ..Default::default()
    /// };
    /// assert!(top_products.is_calculated());
    ///
    /// // An imported table is not, however it was loaded.
    /// let imported = Table {
    ///     name: "Products".to_string(),
    ///     partitions: vec![Partition {
    ///         name: "Products".to_string(),
    ///         source: PartitionSource::M { expression: "Sql.Database(...)".to_string() },
    ///     }],
    ///     ..Default::default()
    /// };
    /// assert!(!imported.is_calculated());
    /// ```
    pub fn is_calculated(&self) -> bool {
        self.partitions
            .iter()
            .any(|partition| matches!(partition.source, PartitionSource::Calculated { .. }))
    }
}

/// A column of a table.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Column {
    /// Column name.
    pub name: String,
    /// How the column's values are produced.
    pub kind: ColumnKind,
    /// Hidden from report authors; hidden objects are still live if referenced.
    pub is_hidden: bool,
    /// Name of another column in the same table (TOM sortByColumn).
    /// Liveness edge: a used column keeps its sort-by column alive.
    pub sort_by_column: Option<String>,
    /// Names of other columns in the same table (TOM groupByColumns).
    /// Liveness edge: a used column keeps its group-by columns alive.
    pub group_by_columns: Vec<String>,
    /// Column variations (TOM variations): bindings of this column to
    /// hierarchies on other tables — for auto date/time, the engine's hidden
    /// `LocalDateTable_*` machinery.
    pub variations: Vec<Variation>,
}

/// A column variation (TOM variation): the model's declaration that the owning
/// column is served by a hierarchy on another table — for auto date/time, a
/// hidden relationship to an engine-generated `LocalDateTable_*`.
///
/// Report bindings written against the varied column resolve through this
/// declaration: the graph joins the referenced relationship or hierarchy
/// instead of guessing which of a column's relationships is the variation.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Variation {
    /// Variation name (the TMDL descriptor name, e.g. `Variation`).
    pub name: String,
    /// Whether this is the column's default variation (TOM isDefault; TMDL
    /// writes the key only when true).
    pub is_default: bool,
    /// Name of the TOM relationship realizing this variation — for auto
    /// date/time, the hidden relationship from the owning column to the date
    /// table's key column. TMDL relationship names are GUIDs.
    pub relationship: Option<String>,
    /// The table-qualified default hierarchy (TOM defaultHierarchy), e.g.
    /// `LocalDateTable_x.'Date Hierarchy'` — where report bindings on the
    /// varied column land.
    pub default_hierarchy: Option<HierarchyRef>,
}

/// A table-qualified reference to a hierarchy defined on another table.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HierarchyRef {
    /// Name of the table owning the hierarchy.
    pub table: String,
    /// Hierarchy name in that table.
    pub hierarchy: String,
}

/// How a column's values are produced.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ColumnKind {
    /// Sourced from the partition query (TOM dataColumn). The default.
    #[default]
    Data,
    /// DAX-defined column (TOM calculatedColumn).
    Calculated {
        /// DAX expression evaluated per row.
        expression: String,
    },
    /// Column of a calculated table (TOM calculatedTableColumn);
    /// materialized by the table's DAX partition, no own expression.
    CalculatedTableColumn,
}

/// A DAX measure.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Measure {
    /// Measure name; unique across the whole model, not just its home table.
    pub name: String,
    /// The measure's DAX expression.
    pub expression: String,
    /// Hidden from report authors; hidden objects are still live if referenced.
    pub is_hidden: bool,
    /// Dynamic format string (DAX).
    pub format_string_expression: Option<String>,
    /// DAX detailRowsDefinition (drillthrough detail rows).
    pub detail_rows_expression: Option<String>,
    /// KPI attached to this measure.
    pub kpi: Option<Kpi>,
}

/// KPI expressions are DAX and can be the sole reference keeping an object alive.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Kpi {
    /// DAX expression for the KPI target value.
    pub target_expression: Option<String>,
    /// DAX expression for the KPI status.
    pub status_expression: Option<String>,
    /// DAX expression for the KPI trend.
    pub trend_expression: Option<String>,
}

/// A partition supplying a table's rows.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Partition {
    /// Partition name.
    pub name: String,
    /// The partition's source query and its language.
    pub source: PartitionSource,
}

/// A partition's source query, discriminated by query language.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PartitionSource {
    /// Power Query (TOM m).
    M {
        /// M expression text.
        expression: String,
    },
    /// DAX — this is what makes a table a calculated table (TOM calculated).
    Calculated {
        /// DAX expression producing the table.
        expression: String,
    },
    /// Legacy native query partition (TOM query).
    Query {
        /// Native query text, in the data source's own dialect.
        query: String,
    },
    /// entity (DirectLake), inferred, future kinds — schema drift never panics;
    /// the raw kind string is kept for diagnostics.
    Other {
        /// The source kind as written in the model, when one was present.
        kind: Option<String>,
    },
}

impl Default for PartitionSource {
    /// An unparsed source is `Other`, never a query language, so an unrecognized
    /// partition can never be mistaken for DAX or M by the expression enumeration.
    fn default() -> Self {
        PartitionSource::Other { kind: None }
    }
}

/// A table's incremental refresh policy (TMDL refreshPolicy / TOM refreshPolicy).
///
/// Only the expressions are modeled. The policy's ranges, periods, and offsets
/// cannot consume a model object, so they are skipped as Tier-1 metadata — but
/// both expression properties are evaluated at refresh time, where deleting
/// what they reference breaks refresh (see [`crate::m`] and
/// [`DaxExpressionKind::ChangeDetection`]).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RefreshPolicy {
    /// Policy type as written (TOM policyType, e.g. `basicRefreshPolicy`).
    /// Diagnostics only.
    pub policy_type: Option<String>,
    /// The policy's source expression (TOM sourceExpression): the M query new
    /// policy-range partitions are created from, filtered by the
    /// RangeStart/RangeEnd parameters.
    pub source_expression: Option<String>,
    /// The change-detection expression (TOM pollingExpression): evaluated per
    /// partition at refresh time to decide whether the partition has new data.
    pub change_detection: Option<String>,
}

/// A relationship between a column of one table and a column of another.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Relationship {
    /// TMDL relationship names are GUIDs; kept for diagnostics only.
    pub name: Option<String>,
    /// Table on the "from" (typically many) side.
    pub from_table: String,
    /// Key column in `from_table`.
    pub from_column: String,
    /// Table on the "to" (typically one) side.
    pub to_table: String,
    /// Key column in `to_table`.
    pub to_column: String,
    /// Active relationships keep both key columns alive while either endpoint
    /// table is reachable; inactive ones are live only when a live DAX
    /// reference (`USERELATIONSHIP`) activates them — otherwise the
    /// relationship and its key columns are all findings.
    pub is_active: bool,
}

impl Default for Relationship {
    /// `is_active` defaults to `true`, matching TOM: the flag is omitted from the
    /// source for active relationships. A derived `Default` would make every
    /// relationship built field-by-field silently inactive.
    fn default() -> Self {
        Self {
            name: None,
            from_table: String::new(),
            from_column: String::new(),
            to_table: String::new(),
            to_column: String::new(),
            is_active: true,
        }
    }
}

/// A user-defined hierarchy on a table.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Hierarchy {
    /// Hierarchy name.
    pub name: String,
    /// Levels from coarsest to finest, in source order.
    pub levels: Vec<HierarchyLevel>,
    /// Hidden from report authors; hidden objects are still live if referenced.
    pub is_hidden: bool,
}

/// One level of a hierarchy.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HierarchyLevel {
    /// Level name; may differ from the underlying column name.
    pub name: String,
    /// Column name in the owning table.
    pub column: String,
}

/// A row-level-security role.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Role {
    /// Role name.
    pub name: String,
    /// Per-table permissions granted by this role.
    pub table_permissions: Vec<TablePermission>,
}

/// A role's permission on one table.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TablePermission {
    /// Target table name.
    pub table: String,
    /// DAX row filter; None = metadata-only permission.
    pub filter_expression: Option<String>,
}

/// The calculation group defined on a table.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CalculationGroup {
    /// Calculation items in source order.
    pub items: Vec<CalculationItem>,
    /// DAX evaluated when no calculation item is selected (TOM noSelectionExpression).
    pub no_selection_expression: Option<String>,
    /// Dynamic format string (DAX) for the no-selection case.
    pub no_selection_format_string_expression: Option<String>,
    /// DAX evaluated when multiple items are selected or the selection is empty
    /// (TOM multipleOrEmptySelectionExpression).
    pub multiple_or_empty_selection_expression: Option<String>,
    /// Dynamic format string (DAX) for the multiple-or-empty-selection case.
    pub multiple_or_empty_selection_format_string_expression: Option<String>,
}

/// One item of a calculation group.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CalculationItem {
    /// Item name.
    pub name: String,
    /// The item's DAX expression, typically wrapping SELECTEDMEASURE().
    pub expression: String,
    /// Dynamic format string (DAX) applied when this item is selected.
    pub format_string_expression: Option<String>,
}

/// A model-level shared M expression: a Power Query parameter or shared query.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SharedExpression {
    /// Expression name, as referenced from other M queries.
    pub name: String,
    /// M expression text.
    pub expression: String,
    /// The column this parameter's view-time values are bound from — TMDL
    /// `parameterValuesColumn: Table.Column` on a dynamic M query parameter.
    /// The binding keeps the column alive (the graph links the expression to
    /// it structurally). The column side carries only an anonymous marker
    /// extended property, so this property is the binding's authoritative
    /// half; `None` for parameters and shared queries without a binding.
    pub parameter_values_column: Option<ParameterValuesColumn>,
}

/// The `Table.Column` a dynamic M query parameter binds its view-time values
/// from — the parameter-to-column binding of a dynamic M parameter.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ParameterValuesColumn {
    /// Name of the table owning the bound column.
    pub table: String,
    /// Name of the bound column.
    pub column: String,
}

/// A user-defined DAX function (TOM function). Referenced from DAX by name;
/// its body can be the sole reference keeping another object alive — and the
/// function itself can be dead.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Function {
    /// Function name; model-global, as referenced from DAX.
    pub name: String,
    /// The function's DAX body.
    pub expression: String,
    /// Hidden from report authors; hidden objects are still live if referenced.
    pub is_hidden: bool,
}

/// A calendar (TOM calendar) defined on a table, binding groups of its columns.
///
/// Modeled minimally — the name and the bound column names — which is all a static
/// source file can contribute to liveness: a referenced calendar keeps its bound
/// columns alive.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Calendar {
    /// Calendar name.
    pub name: String,
    /// Names of the columns (in the owning table) the calendar binds.
    pub columns: Vec<String>,
}

/// Handle dereferencing: turning a positional handle from
/// [`ModelIndex`](index::ModelIndex) back into the object it points at.
///
/// Every accessor goes through `.get()` and returns [`Option`]. A handle is only
/// meaningful against the database its index was built from, and a handle from a
/// different or since-mutated database is a normal miss, never a panic.
impl TabularDatabase {
    /// The table a handle points at, or `None` if the handle is stale.
    pub fn table(&self, h: TableHandle) -> Option<&Table> {
        self.tables.get(h.0)
    }

    /// The column a handle points at, or `None` if either index is out of range.
    pub fn column(&self, h: ColumnHandle) -> Option<&Column> {
        self.tables.get(h.table)?.columns.get(h.column)
    }

    /// The measure a handle points at, or `None` if either index is out of range.
    pub fn measure(&self, h: MeasureHandle) -> Option<&Measure> {
        self.tables.get(h.table)?.measures.get(h.measure)
    }

    /// The hierarchy a handle points at, or `None` if either index is out of range.
    pub fn hierarchy(&self, h: HierarchyHandle) -> Option<&Hierarchy> {
        self.tables.get(h.table)?.hierarchies.get(h.hierarchy)
    }

    /// The shared M expression a handle points at, or `None` if the handle is stale.
    pub fn shared_expression(&self, h: ExpressionHandle) -> Option<&SharedExpression> {
        self.expressions.get(h.0)
    }

    /// The user-defined function a handle points at, or `None` if the handle is stale.
    pub fn function(&self, h: FunctionHandle) -> Option<&Function> {
        self.functions.get(h.0)
    }

    /// The stable graph-node identity of a resolved reference.
    ///
    /// Names come from the objects themselves, so the id carries the model's own
    /// casing for display; [`ObjectId`] still compares case-insensitively.
    pub fn object_id(&self, r: Resolved) -> Option<ObjectId> {
        match r {
            Resolved::Column(h) => {
                let table = self.tables.get(h.table)?;
                let column = table.columns.get(h.column)?;
                Some(ObjectId::Column {
                    table: NameKey::new(table.name.as_str()),
                    column: NameKey::new(column.name.as_str()),
                })
            }
            Resolved::Measure(h) => {
                let table = self.tables.get(h.table)?;
                let measure = table.measures.get(h.measure)?;
                Some(ObjectId::Measure {
                    table: NameKey::new(table.name.as_str()),
                    measure: NameKey::new(measure.name.as_str()),
                })
            }
        }
    }
}

/// Which property of its owner a DAX expression came from — model-side or
/// report-side.
///
/// The graph layer matches on this to decide what kind of edge a discovered
/// reference produces; the two enumerations ([`TabularDatabase::dax_expressions`]
/// and [`crate::report::ReportModel::dax_expressions`]) guarantee every variant
/// has exactly one production site.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DaxExpressionKind {
    /// A measure's own expression.
    Measure,
    /// A measure's dynamic format string.
    MeasureFormatString,
    /// A measure's detail-rows (drillthrough) expression.
    MeasureDetailRows,
    /// A KPI's target expression.
    KpiTarget,
    /// A KPI's status expression.
    KpiStatus,
    /// A KPI's trend expression.
    KpiTrend,
    /// A calculated column's expression.
    CalculatedColumn,
    /// The DAX partition expression that materializes a calculated table.
    CalculatedTable,
    /// An incremental refresh policy's change-detection expression (TOM
    /// pollingExpression): evaluated per partition at refresh time, so deleting
    /// what it references breaks refresh.
    ChangeDetection,
    /// A table's default detail-rows (drillthrough) expression.
    TableDetailRows,
    /// A role's row-level-security filter on one table.
    RlsFilter,
    /// A calculation item's expression.
    CalculationItem,
    /// A calculation item's dynamic format string.
    CalculationItemFormatString,
    /// A calculation group's no-selection expression.
    CalculationGroupNoSelection,
    /// A calculation group's no-selection dynamic format string.
    CalculationGroupNoSelectionFormatString,
    /// A calculation group's multiple-or-empty-selection expression.
    CalculationGroupMultipleOrEmptySelection,
    /// A calculation group's multiple-or-empty-selection dynamic format string.
    CalculationGroupMultipleOrEmptySelectionFormatString,
    /// A user-defined function's body.
    Function,
    /// A report-level measure's own expression (reportExtensions.json).
    ReportMeasure,
    /// A report-level measure's dynamic format string.
    ReportMeasureFormatString,
}

/// The model or report object an enumerated expression belongs to.
///
/// Names are borrowed from the AST, so enumerating a model's expressions
/// allocates nothing. Call [`to_object_id`](ExpressionOwner::to_object_id) to
/// materialize a graph node key — once per node the graph actually creates, rather
/// than once per expression.
///
/// The variants are exactly the objects that can own an expression, which is why
/// there is no hierarchy here: hierarchies reference columns but define no DAX.
/// The one report-side variant is the report-level measure, whose DAX body is an
/// expression source the model knows nothing about (see
/// [`crate::report::ReportModel::dax_expressions`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExpressionOwner<'a> {
    /// A table, owning its detail-rows expression.
    Table {
        /// Table name.
        table: &'a str,
    },
    /// A calculated column.
    Column {
        /// Owning table.
        table: &'a str,
        /// Column name.
        column: &'a str,
    },
    /// A measure, owning its expression, format string, detail rows, and KPI.
    Measure {
        /// Home table.
        table: &'a str,
        /// Measure name.
        measure: &'a str,
    },
    /// A partition, owning its M or DAX source query.
    Partition {
        /// Owning table.
        table: &'a str,
        /// Partition name.
        partition: &'a str,
    },
    /// A security role, owning its row-level-security filters.
    Role {
        /// Role name.
        role: &'a str,
    },
    /// A calculation item.
    CalculationItem {
        /// Calculation group table.
        table: &'a str,
        /// Calculation item name.
        item: &'a str,
    },
    /// A model-level shared M expression.
    Expression {
        /// Expression name.
        name: &'a str,
    },
    /// A user-defined DAX function.
    Function {
        /// Function name.
        name: &'a str,
    },
    /// A report-level measure (reportExtensions.json), owning its expression and
    /// dynamic format string. Lives in the report, not the model.
    ReportMeasure {
        /// Measure name, report-scoped.
        measure: &'a str,
    },
}

impl ExpressionOwner<'_> {
    /// The owner's stable graph-node identity, allocating the owned name keys.
    #[must_use]
    pub fn to_object_id(&self) -> ObjectId {
        match *self {
            ExpressionOwner::Table { table } => ObjectId::Table {
                table: NameKey::new(table),
            },
            ExpressionOwner::Column { table, column } => ObjectId::Column {
                table: NameKey::new(table),
                column: NameKey::new(column),
            },
            ExpressionOwner::Measure { table, measure } => ObjectId::Measure {
                table: NameKey::new(table),
                measure: NameKey::new(measure),
            },
            ExpressionOwner::Partition { table, partition } => ObjectId::Partition {
                table: NameKey::new(table),
                partition: NameKey::new(partition),
            },
            ExpressionOwner::Role { role } => ObjectId::Role {
                role: NameKey::new(role),
            },
            ExpressionOwner::CalculationItem { table, item } => ObjectId::CalculationItem {
                table: NameKey::new(table),
                item: NameKey::new(item),
            },
            ExpressionOwner::Expression { name } => ObjectId::Expression {
                name: NameKey::new(name),
            },
            ExpressionOwner::Function { name } => ObjectId::Function {
                name: NameKey::new(name),
            },
            ExpressionOwner::ReportMeasure { measure } => ObjectId::ReportMeasure {
                measure: NameKey::new(measure),
            },
        }
    }
}

/// Borrowed view of one DAX expression owned by a model object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DaxExpressionRef<'a> {
    /// The object the expression belongs to — the source node of any edge derived
    /// from references found in `text`.
    pub owner: ExpressionOwner<'a>,
    /// Which property of `owner` this expression is.
    pub kind: DaxExpressionKind,
    /// Context table for unqualified-column resolution by the lexer.
    pub home_table: Option<&'a str>,
    /// The expression text, borrowed from the model.
    pub text: &'a str,
}

/// Borrowed view of one M expression owned by a model object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MExpressionRef<'a> {
    /// The object the expression belongs to: a partition or a shared expression.
    pub owner: ExpressionOwner<'a>,
    /// The expression text, borrowed from the model.
    pub text: &'a str,
}

impl TabularDatabase {
    /// Every DAX expression in the model, with its owner and home-table context.
    ///
    /// Order follows model order (tables, then each table's measures, columns,
    /// partitions, refresh-policy change detection, table-level expressions,
    /// calculation items and their group's selection expressions, then roles,
    /// then functions), so the result is deterministic for a given model and
    /// diffable across runs.
    ///
    /// Owners borrow their names, so this allocates only the returned `Vec`.
    #[must_use]
    pub fn dax_expressions(&self) -> Vec<DaxExpressionRef<'_>> {
        let mut out = Vec::new();

        for table in &self.tables {
            let home = Some(table.name.as_str());

            for measure in &table.measures {
                let owner = ExpressionOwner::Measure {
                    table: &table.name,
                    measure: &measure.name,
                };
                let kpi = measure.kpi.as_ref();
                let sources = [
                    (DaxExpressionKind::Measure, Some(&measure.expression)),
                    (
                        DaxExpressionKind::MeasureFormatString,
                        measure.format_string_expression.as_ref(),
                    ),
                    (
                        DaxExpressionKind::MeasureDetailRows,
                        measure.detail_rows_expression.as_ref(),
                    ),
                    (
                        DaxExpressionKind::KpiTarget,
                        kpi.and_then(|kpi| kpi.target_expression.as_ref()),
                    ),
                    (
                        DaxExpressionKind::KpiStatus,
                        kpi.and_then(|kpi| kpi.status_expression.as_ref()),
                    ),
                    (
                        DaxExpressionKind::KpiTrend,
                        kpi.and_then(|kpi| kpi.trend_expression.as_ref()),
                    ),
                ];
                for (kind, text) in sources {
                    if let Some(text) = text {
                        out.push(DaxExpressionRef {
                            owner,
                            kind,
                            home_table: home,
                            text,
                        });
                    }
                }
            }

            for column in &table.columns {
                if let ColumnKind::Calculated { expression } = &column.kind {
                    out.push(DaxExpressionRef {
                        owner: ExpressionOwner::Column {
                            table: &table.name,
                            column: &column.name,
                        },
                        kind: DaxExpressionKind::CalculatedColumn,
                        home_table: home,
                        text: expression,
                    });
                }
            }

            for partition in &table.partitions {
                if let PartitionSource::Calculated { expression } = &partition.source {
                    // The home table is the calculated table itself. Unqualified columns
                    // in a calculated-table expression usually belong to the source
                    // table, so this is conservative: it can only add candidate edges.
                    out.push(DaxExpressionRef {
                        owner: ExpressionOwner::Partition {
                            table: &table.name,
                            partition: &partition.name,
                        },
                        kind: DaxExpressionKind::CalculatedTable,
                        home_table: home,
                        text: expression,
                    });
                }
            }

            // A change-detection expression is evaluated per partition at refresh
            // time, so the policy references what deleting would break. The owner is
            // each partition the policy refreshes, which keeps the ordinary rule
            // intact: a dead table's policy keeps nothing alive.
            if let Some(text) = table
                .refresh_policy
                .as_ref()
                .and_then(|policy| policy.change_detection.as_ref())
            {
                for partition in &table.partitions {
                    out.push(DaxExpressionRef {
                        owner: ExpressionOwner::Partition {
                            table: &table.name,
                            partition: &partition.name,
                        },
                        kind: DaxExpressionKind::ChangeDetection,
                        home_table: home,
                        text,
                    });
                }
            }

            if let Some(text) = &table.detail_rows_expression {
                out.push(DaxExpressionRef {
                    owner: ExpressionOwner::Table { table: &table.name },
                    kind: DaxExpressionKind::TableDetailRows,
                    home_table: home,
                    text,
                });
            }

            if let Some(group) = &table.calculation_group {
                for item in &group.items {
                    let owner = ExpressionOwner::CalculationItem {
                        table: &table.name,
                        item: &item.name,
                    };
                    out.push(DaxExpressionRef {
                        owner,
                        kind: DaxExpressionKind::CalculationItem,
                        home_table: home,
                        text: item.expression.as_str(),
                    });
                    if let Some(text) = &item.format_string_expression {
                        out.push(DaxExpressionRef {
                            owner,
                            kind: DaxExpressionKind::CalculationItemFormatString,
                            home_table: home,
                            text,
                        });
                    }
                }

                // Group-level selection expressions. The calc group is a property of
                // its table in TOM, so — like detail rows — the table is the owner and
                // the kind is what discriminates.
                let group_owner = ExpressionOwner::Table { table: &table.name };
                let sources = [
                    (
                        DaxExpressionKind::CalculationGroupNoSelection,
                        group.no_selection_expression.as_ref(),
                    ),
                    (
                        DaxExpressionKind::CalculationGroupNoSelectionFormatString,
                        group.no_selection_format_string_expression.as_ref(),
                    ),
                    (
                        DaxExpressionKind::CalculationGroupMultipleOrEmptySelection,
                        group.multiple_or_empty_selection_expression.as_ref(),
                    ),
                    (
                        DaxExpressionKind::CalculationGroupMultipleOrEmptySelectionFormatString,
                        group
                            .multiple_or_empty_selection_format_string_expression
                            .as_ref(),
                    ),
                ];
                for (kind, text) in sources {
                    if let Some(text) = text {
                        out.push(DaxExpressionRef {
                            owner: group_owner,
                            kind,
                            home_table: home,
                            text,
                        });
                    }
                }
            }
        }

        for role in &self.roles {
            for permission in &role.table_permissions {
                if let Some(text) = &permission.filter_expression {
                    // The row context of an RLS filter is the table it is applied to,
                    // not anything owned by the role.
                    out.push(DaxExpressionRef {
                        owner: ExpressionOwner::Role { role: &role.name },
                        kind: DaxExpressionKind::RlsFilter,
                        home_table: Some(permission.table.as_str()),
                        text,
                    });
                }
            }
        }

        for function in &self.functions {
            // A function body has no row context of its own: unqualified `[Name]`
            // references inside it can only be measures.
            out.push(DaxExpressionRef {
                owner: ExpressionOwner::Function {
                    name: &function.name,
                },
                kind: DaxExpressionKind::Function,
                home_table: None,
                text: &function.expression,
            });
        }

        out
    }

    /// Every M expression: M partitions, a refresh policy's expressions, and
    /// shared model expressions.
    ///
    /// `Query` and `Other` partition sources are not M and are excluded. The
    /// policy's `sourceExpression` is M by definition; its change-detection
    /// expression is handed to both lexers — the M side resolves the tables and
    /// shared expressions it reads (polling by shared-query name is the
    /// documented custom pattern), while the DAX side ([`TabularDatabase::dax_expressions`])
    /// resolves its measure references.
    #[must_use]
    pub fn m_expressions(&self) -> Vec<MExpressionRef<'_>> {
        let mut out = Vec::new();

        for table in &self.tables {
            for partition in &table.partitions {
                if let PartitionSource::M { expression } = &partition.source {
                    out.push(MExpressionRef {
                        owner: ExpressionOwner::Partition {
                            table: &table.name,
                            partition: &partition.name,
                        },
                        text: expression,
                    });
                }
            }

            // Same per-partition ownership as the DAX side: the policy speaks
            // for the partitions it refreshes, and a partition that does not
            // exist cannot vouch for anything.
            if let Some(policy) = &table.refresh_policy {
                let texts = [
                    policy.source_expression.as_ref(),
                    policy.change_detection.as_ref(),
                ];
                for text in texts.into_iter().flatten() {
                    for partition in &table.partitions {
                        out.push(MExpressionRef {
                            owner: ExpressionOwner::Partition {
                                table: &table.name,
                                partition: &partition.name,
                            },
                            text,
                        });
                    }
                }
            }
        }

        for expression in &self.expressions {
            out.push(MExpressionRef {
                owner: ExpressionOwner::Expression {
                    name: &expression.name,
                },
                text: expression.expression.as_str(),
            });
        }

        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    fn table_id(table: &str) -> ObjectId {
        ObjectId::Table {
            table: NameKey::new(table),
        }
    }

    fn column_id(table: &str, column: &str) -> ObjectId {
        ObjectId::Column {
            table: NameKey::new(table),
            column: NameKey::new(column),
        }
    }

    fn measure_id(table: &str, measure: &str) -> ObjectId {
        ObjectId::Measure {
            table: NameKey::new(table),
            measure: NameKey::new(measure),
        }
    }

    fn partition_id(table: &str, partition: &str) -> ObjectId {
        ObjectId::Partition {
            table: NameKey::new(table),
            partition: NameKey::new(partition),
        }
    }

    fn calc_item_id(table: &str, item: &str) -> ObjectId {
        ObjectId::CalculationItem {
            table: NameKey::new(table),
            item: NameKey::new(item),
        }
    }

    fn expression_id(name: &str) -> ObjectId {
        ObjectId::Expression {
            name: NameKey::new(name),
        }
    }

    fn function_id(name: &str) -> ObjectId {
        ObjectId::Function {
            name: NameKey::new(name),
        }
    }

    fn role_id(role: &str) -> ObjectId {
        ObjectId::Role {
            role: NameKey::new(role),
        }
    }

    fn partition(name: &str, source: PartitionSource) -> Partition {
        Partition {
            name: name.to_string(),
            source,
        }
    }

    /// `(kind, owner, home_table, text)` for every DAX expression, in order.
    fn dax_tuples(db: &TabularDatabase) -> Vec<(DaxExpressionKind, ObjectId, Option<&str>, &str)> {
        db.dax_expressions()
            .into_iter()
            .map(|e| (e.kind, e.owner.to_object_id(), e.home_table, e.text))
            .collect()
    }

    /// `(owner, text)` for every M expression, in order.
    fn m_tuples(db: &TabularDatabase) -> Vec<(ObjectId, &str)> {
        db.m_expressions()
            .into_iter()
            .map(|e| (e.owner.to_object_id(), e.text))
            .collect()
    }

    fn owners(db: &TabularDatabase) -> Vec<ObjectId> {
        dax_tuples(db)
            .into_iter()
            .map(|(_, owner, _, _)| owner)
            .collect()
    }

    /// Exercises every [`DaxExpressionKind`] exactly once, plus two objects that
    /// must contribute nothing on their own: a `Data` column and a metadata-only
    /// table permission. The M partition contributes no DAX of its own — its
    /// `ChangeDetection` entry is the refresh policy's, not the M query.
    fn every_kind_fixture() -> TabularDatabase {
        TabularDatabase {
            name: Some("Contoso".to_string()),
            tables: vec![
                Table {
                    name: "Sales".to_string(),
                    columns: vec![
                        Column {
                            name: "Amount".to_string(),
                            kind: ColumnKind::Data,
                            ..Default::default()
                        },
                        Column {
                            name: "Margin".to_string(),
                            kind: ColumnKind::Calculated {
                                expression: "'Sales'[Amount] * 0.2".to_string(),
                            },
                            ..Default::default()
                        },
                    ],
                    measures: vec![Measure {
                        name: "Total Sales".to_string(),
                        expression: "SUM('Sales'[Amount])".to_string(),
                        is_hidden: false,
                        format_string_expression: Some("\"#,##0\"".to_string()),
                        detail_rows_expression: Some("SELECTCOLUMNS('Sales')".to_string()),
                        kpi: Some(Kpi {
                            target_expression: Some("[Budget]".to_string()),
                            status_expression: Some("IF([Total Sales] > 0, 1, -1)".to_string()),
                            trend_expression: Some("[Total Sales] - [Prior]".to_string()),
                        }),
                    }],
                    partitions: vec![partition(
                        "Sales-Part1",
                        PartitionSource::M {
                            expression: "let Source = Sql.Database() in Source".to_string(),
                        },
                    )],
                    refresh_policy: Some(RefreshPolicy {
                        policy_type: Some("basicRefreshPolicy".to_string()),
                        source_expression: Some(
                            "let Source = Sql.Database(Server, DB) in Source".to_string(),
                        ),
                        change_detection: Some(
                            "EVALUATE ROW(\"Bookmark\", [Total Sales])".to_string(),
                        ),
                    }),
                    detail_rows_expression: Some(
                        "SELECTCOLUMNS('Sales', \"A\", [Amount])".to_string(),
                    ),
                    ..Default::default()
                },
                Table {
                    name: "Top Products".to_string(),
                    partitions: vec![partition(
                        "Top Products",
                        PartitionSource::Calculated {
                            expression: "TOPN(10, 'Product', [Total Sales])".to_string(),
                        },
                    )],
                    ..Default::default()
                },
                Table {
                    name: "Time Intelligence".to_string(),
                    calculation_group: Some(CalculationGroup {
                        items: vec![CalculationItem {
                            name: "YTD".to_string(),
                            expression: "TOTALYTD(SELECTEDMEASURE(), 'Date'[Date])".to_string(),
                            format_string_expression: Some("\"#,##0;;\"".to_string()),
                        }],
                        no_selection_expression: Some("SELECTEDMEASURE()".to_string()),
                        no_selection_format_string_expression: Some(
                            "SELECTEDMEASUREFORMATSTRING()".to_string(),
                        ),
                        multiple_or_empty_selection_expression: Some(
                            "ERROR(\"Pick one item\")".to_string(),
                        ),
                        multiple_or_empty_selection_format_string_expression: Some(
                            "\"General\"".to_string(),
                        ),
                    }),
                    ..Default::default()
                },
            ],
            functions: vec![Function {
                name: "Sales.NetPrice".to_string(),
                expression: "(price: SCALAR) => price * (1 - [Discount Pct])".to_string(),
                is_hidden: false,
            }],
            roles: vec![Role {
                name: "Reader".to_string(),
                table_permissions: vec![
                    TablePermission {
                        table: "Sales".to_string(),
                        filter_expression: Some("'Sales'[Amount] > 0".to_string()),
                    },
                    TablePermission {
                        table: "Top Products".to_string(),
                        filter_expression: None,
                    },
                ],
            }],
            ..Default::default()
        }
    }

    fn m_fixture() -> TabularDatabase {
        TabularDatabase {
            tables: vec![Table {
                name: "Sales".to_string(),
                partitions: vec![
                    partition(
                        "Sales-M",
                        PartitionSource::M {
                            expression: "let Source = Sql.Database(Server) in Source".to_string(),
                        },
                    ),
                    partition(
                        "Sales-Native",
                        PartitionSource::Query {
                            query: "SELECT * FROM dbo.Sales".to_string(),
                        },
                    ),
                    partition(
                        "Sales-Lake",
                        PartitionSource::Other {
                            kind: Some("entity".to_string()),
                        },
                    ),
                ],
                ..Default::default()
            }],
            expressions: vec![
                SharedExpression {
                    name: "Server".to_string(),
                    expression: "\"contoso.database.windows.net\"".to_string(),
                    ..Default::default()
                },
                SharedExpression {
                    name: "Database".to_string(),
                    expression: "\"AdventureWorks\"".to_string(),
                    ..Default::default()
                },
            ],
            ..Default::default()
        }
    }

    mod expression_views {
        use super::*;

        /// Both expression views must stay `Copy`, which is only possible while every
        /// field borrows. It is the structural guarantee that enumerating a model's
        /// expressions allocates nothing but the returned `Vec` — adding an owned
        /// field (an `ObjectId`, a `String`) breaks this and reintroduces a
        /// per-expression allocation on the graph layer's hot path.
        #[test]
        fn are_copy_so_enumeration_borrows_everything() {
            fn assert_copy<T: Copy>() {}
            assert_copy::<DaxExpressionRef<'_>>();
            assert_copy::<MExpressionRef<'_>>();
            assert_copy::<ExpressionOwner<'_>>();
        }
    }

    /// A calculated table is one whose partition source is DAX. There is no flag in
    /// TOM and none here, so every other source kind — including ones this crate does
    /// not recognize — must read as not calculated.
    mod is_calculated {
        use super::*;

        fn table_with(source: Option<PartitionSource>) -> Table {
            Table {
                name: "Anything".to_string(),
                partitions: source.into_iter().map(|s| partition("P", s)).collect(),
                ..Default::default()
            }
        }

        #[rstest]
        #[case::dax_partition(
            Some(PartitionSource::Calculated { expression: "TOPN(10, 'Sales')".to_string() }),
            true
        )]
        #[case::m_partition(
            Some(PartitionSource::M { expression: "let Source = Sql.Database() in Source".to_string() }),
            false
        )]
        #[case::native_query(
            Some(PartitionSource::Query { query: "SELECT * FROM dbo.Sales".to_string() }),
            false
        )]
        #[case::direct_lake_entity(
            Some(PartitionSource::Other { kind: Some("entity".to_string()) }),
            false
        )]
        #[case::unknown_future_source(Some(PartitionSource::Other { kind: None }), false)]
        #[case::no_partitions(None, false)]
        fn follows_the_partition_source(
            #[case] source: Option<PartitionSource>,
            #[case] expected: bool,
        ) {
            assert_eq!(table_with(source).is_calculated(), expected);
        }

        #[test]
        fn is_true_when_only_one_of_several_partitions_is_dax() {
            let mixed = Table {
                name: "Sales".to_string(),
                partitions: vec![
                    partition(
                        "Sales-2023",
                        PartitionSource::Query {
                            query: "SELECT * FROM dbo.Sales".to_string(),
                        },
                    ),
                    partition(
                        "Sales-2024",
                        PartitionSource::Calculated {
                            expression: "FILTER('Raw', TRUE())".to_string(),
                        },
                    ),
                ],
                ..Default::default()
            };

            assert!(
                mixed.is_calculated(),
                "one DAX partition makes the table calculated"
            );
        }
    }

    mod defaults {
        use super::*;

        /// TMDL omits the flag for active relationships, so a relationship built
        /// field-by-field must come out active. A derived `Default` would silently
        /// make every one of them inactive.
        #[test]
        fn a_relationship_is_active() {
            assert!(Relationship::default().is_active);
        }

        #[test]
        fn a_relationship_has_no_other_content() {
            assert_eq!(
                Relationship::default(),
                Relationship {
                    name: None,
                    from_table: String::new(),
                    from_column: String::new(),
                    to_table: String::new(),
                    to_column: String::new(),
                    is_active: true,
                }
            );
        }

        /// An unparsed source must never be mistaken for a query language, or schema
        /// drift would feed junk to the DAX lexer.
        #[test]
        fn a_partition_source_is_other_with_no_kind() {
            assert_eq!(
                PartitionSource::default(),
                PartitionSource::Other { kind: None }
            );
        }

        #[test]
        fn a_partition_carries_the_default_source() {
            assert_eq!(
                Partition::default().source,
                PartitionSource::Other { kind: None }
            );
        }

        #[test]
        fn a_column_kind_is_data() {
            assert_eq!(ColumnKind::default(), ColumnKind::Data);
        }

        #[test]
        fn a_column_carries_the_default_kind() {
            assert_eq!(Column::default().kind, ColumnKind::Data);
        }
    }

    mod dax_expressions {
        use super::*;

        #[test]
        fn enumerates_every_kind_with_exact_owner_home_and_text() {
            let db = every_kind_fixture();

            assert_eq!(
                dax_tuples(&db),
                vec![
                    (
                        DaxExpressionKind::Measure,
                        measure_id("Sales", "Total Sales"),
                        Some("Sales"),
                        "SUM('Sales'[Amount])",
                    ),
                    (
                        DaxExpressionKind::MeasureFormatString,
                        measure_id("Sales", "Total Sales"),
                        Some("Sales"),
                        "\"#,##0\"",
                    ),
                    (
                        DaxExpressionKind::MeasureDetailRows,
                        measure_id("Sales", "Total Sales"),
                        Some("Sales"),
                        "SELECTCOLUMNS('Sales')",
                    ),
                    (
                        DaxExpressionKind::KpiTarget,
                        measure_id("Sales", "Total Sales"),
                        Some("Sales"),
                        "[Budget]",
                    ),
                    (
                        DaxExpressionKind::KpiStatus,
                        measure_id("Sales", "Total Sales"),
                        Some("Sales"),
                        "IF([Total Sales] > 0, 1, -1)",
                    ),
                    (
                        DaxExpressionKind::KpiTrend,
                        measure_id("Sales", "Total Sales"),
                        Some("Sales"),
                        "[Total Sales] - [Prior]",
                    ),
                    (
                        DaxExpressionKind::CalculatedColumn,
                        column_id("Sales", "Margin"),
                        Some("Sales"),
                        "'Sales'[Amount] * 0.2",
                    ),
                    (
                        DaxExpressionKind::ChangeDetection,
                        partition_id("Sales", "Sales-Part1"),
                        Some("Sales"),
                        "EVALUATE ROW(\"Bookmark\", [Total Sales])",
                    ),
                    (
                        DaxExpressionKind::TableDetailRows,
                        table_id("Sales"),
                        Some("Sales"),
                        "SELECTCOLUMNS('Sales', \"A\", [Amount])",
                    ),
                    (
                        DaxExpressionKind::CalculatedTable,
                        partition_id("Top Products", "Top Products"),
                        Some("Top Products"),
                        "TOPN(10, 'Product', [Total Sales])",
                    ),
                    (
                        DaxExpressionKind::CalculationItem,
                        calc_item_id("Time Intelligence", "YTD"),
                        Some("Time Intelligence"),
                        "TOTALYTD(SELECTEDMEASURE(), 'Date'[Date])",
                    ),
                    (
                        DaxExpressionKind::CalculationItemFormatString,
                        calc_item_id("Time Intelligence", "YTD"),
                        Some("Time Intelligence"),
                        "\"#,##0;;\"",
                    ),
                    (
                        DaxExpressionKind::CalculationGroupNoSelection,
                        table_id("Time Intelligence"),
                        Some("Time Intelligence"),
                        "SELECTEDMEASURE()",
                    ),
                    (
                        DaxExpressionKind::CalculationGroupNoSelectionFormatString,
                        table_id("Time Intelligence"),
                        Some("Time Intelligence"),
                        "SELECTEDMEASUREFORMATSTRING()",
                    ),
                    (
                        DaxExpressionKind::CalculationGroupMultipleOrEmptySelection,
                        table_id("Time Intelligence"),
                        Some("Time Intelligence"),
                        "ERROR(\"Pick one item\")",
                    ),
                    (
                        DaxExpressionKind::CalculationGroupMultipleOrEmptySelectionFormatString,
                        table_id("Time Intelligence"),
                        Some("Time Intelligence"),
                        "\"General\"",
                    ),
                    (
                        DaxExpressionKind::RlsFilter,
                        role_id("Reader"),
                        Some("Sales"),
                        "'Sales'[Amount] > 0",
                    ),
                    (
                        DaxExpressionKind::Function,
                        function_id("Sales.NetPrice"),
                        None,
                        "(price: SCALAR) => price * (1 - [Discount Pct])",
                    ),
                ]
            );
        }

        #[test]
        fn enumerates_one_expression_per_populated_site() {
            assert_eq!(dax_tuples(&every_kind_fixture()).len(), 18);
        }

        /// `ObjectId` equality is case-insensitive, so the tuple assertion above
        /// cannot catch an owner built from a lowercased or rewritten name.
        #[test]
        fn owners_preserve_source_casing() {
            let db = every_kind_fixture();
            let displayed: Vec<String> = owners(&db).iter().map(ObjectId::to_string).collect();

            assert_eq!(
                displayed,
                vec![
                    "'Sales'[Total Sales]",
                    "'Sales'[Total Sales]",
                    "'Sales'[Total Sales]",
                    "'Sales'[Total Sales]",
                    "'Sales'[Total Sales]",
                    "'Sales'[Total Sales]",
                    "'Sales'[Margin]",
                    "partition 'Sales'[Sales-Part1]",
                    "table 'Sales'",
                    "partition 'Top Products'[Top Products]",
                    "calculation item 'Time Intelligence'[YTD]",
                    "calculation item 'Time Intelligence'[YTD]",
                    "table 'Time Intelligence'",
                    "table 'Time Intelligence'",
                    "table 'Time Intelligence'",
                    "table 'Time Intelligence'",
                    "role 'Reader'",
                    "function 'Sales.NetPrice'",
                ]
            );
        }

        #[rstest]
        #[case::a_data_column(column_id("Sales", "Amount"))]
        fn excludes(#[case] unwanted: ObjectId) {
            let db = every_kind_fixture();

            assert!(
                !owners(&db).contains(&unwanted),
                "{unwanted} owns no DAX and must not be enumerated"
            );
        }

        #[test]
        fn excludes_m_partition_text() {
            let db = every_kind_fixture();

            assert!(
                !dax_tuples(&db)
                    .iter()
                    .any(|(_, _, _, text)| text.starts_with("let Source")),
                "an M query must never be handed to the DAX lexer"
            );
        }

        /// The policy speaks for each partition it refreshes: the same text is
        /// enumerated once per partition, under that partition's owner.
        #[test]
        fn a_change_detection_expression_is_emitted_once_per_partition() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    partitions: vec![
                        partition(
                            "Sales-2023",
                            PartitionSource::M {
                                expression: "let Source = 1 in Source".to_string(),
                            },
                        ),
                        partition(
                            "Sales-2024",
                            PartitionSource::M {
                                expression: "let Source = 2 in Source".to_string(),
                            },
                        ),
                    ],
                    refresh_policy: Some(RefreshPolicy {
                        change_detection: Some("[Total Sales]".to_string()),
                        ..Default::default()
                    }),
                    ..Default::default()
                }],
                ..Default::default()
            };

            let found = dax_tuples(&db);
            assert_eq!(found.len(), 2);
            assert!(found.iter().all(|(kind, _, _, text)| *kind
                == DaxExpressionKind::ChangeDetection
                && *text == "[Total Sales]"));
            let owners: Vec<ObjectId> = found.into_iter().map(|(_, owner, _, _)| owner).collect();
            assert!(owners.contains(&partition_id("Sales", "Sales-2023")));
            assert!(owners.contains(&partition_id("Sales", "Sales-2024")));
        }

        /// A policy on a partition-less table has nothing to vouch for.
        #[test]
        fn a_change_detection_expression_without_partitions_is_not_emitted() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    refresh_policy: Some(RefreshPolicy {
                        change_detection: Some("[Total Sales]".to_string()),
                        ..Default::default()
                    }),
                    ..Default::default()
                }],
                ..Default::default()
            };

            assert_eq!(db.dax_expressions().len(), 0);
        }

        /// The fixture's role filters one table and holds metadata-only permission on
        /// another; only the filtered one is an expression.
        #[test]
        fn emits_one_filter_for_a_role_with_one_filtered_permission() {
            let db = every_kind_fixture();

            assert_eq!(
                dax_tuples(&db)
                    .iter()
                    .filter(|(kind, _, _, _)| *kind == DaxExpressionKind::RlsFilter)
                    .count(),
                1
            );
        }

        #[test]
        fn excludes_metadata_only_permissions() {
            let db = every_kind_fixture();

            assert!(
                !dax_tuples(&db).iter().any(|(kind, _, home, _)| {
                    *kind == DaxExpressionKind::RlsFilter && *home == Some("Top Products")
                }),
                "a permission with no filter expression contributes nothing"
            );
        }

        #[test]
        fn is_empty_for_a_model_with_no_dax() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Sales".to_string(),
                    columns: vec![Column {
                        name: "Amount".to_string(),
                        ..Default::default()
                    }],
                    partitions: vec![partition(
                        "Sales",
                        PartitionSource::M {
                            expression: "let Source = 1 in Source".to_string(),
                        },
                    )],
                    ..Default::default()
                }],
                ..Default::default()
            };

            assert_eq!(db.dax_expressions().len(), 0);
        }

        /// Order is model order, so a run is deterministic and diffable.
        #[test]
        fn preserves_model_order_within_a_table() {
            let db = every_kind_fixture();
            let kinds: Vec<DaxExpressionKind> =
                db.dax_expressions().iter().map(|e| e.kind).collect();

            assert_eq!(
                kinds,
                vec![
                    DaxExpressionKind::Measure,
                    DaxExpressionKind::MeasureFormatString,
                    DaxExpressionKind::MeasureDetailRows,
                    DaxExpressionKind::KpiTarget,
                    DaxExpressionKind::KpiStatus,
                    DaxExpressionKind::KpiTrend,
                    DaxExpressionKind::CalculatedColumn,
                    DaxExpressionKind::ChangeDetection,
                    DaxExpressionKind::TableDetailRows,
                    DaxExpressionKind::CalculatedTable,
                    DaxExpressionKind::CalculationItem,
                    DaxExpressionKind::CalculationItemFormatString,
                    DaxExpressionKind::CalculationGroupNoSelection,
                    DaxExpressionKind::CalculationGroupNoSelectionFormatString,
                    DaxExpressionKind::CalculationGroupMultipleOrEmptySelection,
                    DaxExpressionKind::CalculationGroupMultipleOrEmptySelectionFormatString,
                    DaxExpressionKind::RlsFilter,
                    DaxExpressionKind::Function,
                ]
            );
        }

        #[test]
        fn follows_table_and_measure_declaration_order() {
            let measure = |name: &str, expression: &str| Measure {
                name: name.to_string(),
                expression: expression.to_string(),
                ..Default::default()
            };
            let db = TabularDatabase {
                tables: vec![
                    Table {
                        name: "Zebra".to_string(),
                        measures: vec![measure("M2", "2"), measure("M1", "1")],
                        ..Default::default()
                    },
                    Table {
                        name: "Apple".to_string(),
                        measures: vec![measure("M3", "3")],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            };

            let found: Vec<(ObjectId, &str)> = db
                .dax_expressions()
                .into_iter()
                .map(|e| (e.owner.to_object_id(), e.text))
                .collect();

            assert_eq!(
                found,
                vec![
                    (measure_id("Zebra", "M2"), "2"),
                    (measure_id("Zebra", "M1"), "1"),
                    (measure_id("Apple", "M3"), "3"),
                ]
            );
        }
    }

    mod m_expressions {
        use super::*;

        #[test]
        fn covers_m_partitions_and_shared_expressions_with_exact_owner_and_text() {
            let db = m_fixture();

            assert_eq!(
                m_tuples(&db),
                vec![
                    (
                        partition_id("Sales", "Sales-M"),
                        "let Source = Sql.Database(Server) in Source",
                    ),
                    (expression_id("Server"), "\"contoso.database.windows.net\""),
                    (expression_id("Database"), "\"AdventureWorks\""),
                ]
            );
        }

        #[rstest]
        #[case::a_native_query_partition(partition_id("Sales", "Sales-Native"))]
        #[case::an_unrecognized_source_partition(partition_id("Sales", "Sales-Lake"))]
        fn excludes(#[case] unwanted: ObjectId) {
            let db = m_fixture();

            assert!(
                !m_tuples(&db)
                    .into_iter()
                    .any(|(owner, _)| owner == unwanted),
                "{unwanted} holds no M and must not be enumerated"
            );
        }

        /// A native query is neither M nor DAX, so it reaches no lexer at all.
        #[test]
        fn leaves_native_query_partitions_out_of_the_dax_enumeration_too() {
            assert_eq!(m_fixture().dax_expressions().len(), 0);
        }

        #[test]
        fn is_empty_for_a_model_with_no_m() {
            let db = TabularDatabase {
                tables: vec![Table {
                    name: "Top Products".to_string(),
                    partitions: vec![partition(
                        "Top Products",
                        PartitionSource::Calculated {
                            expression: "TOPN(10, 'Product')".to_string(),
                        },
                    )],
                    ..Default::default()
                }],
                ..Default::default()
            };

            assert_eq!(db.m_expressions().len(), 0);
        }

        /// The policy's expressions ride the M pipeline per partition: the
        /// source names the query pipeline it partitions, change detection may
        /// name the shared query it polls. Change detection is deliberately
        /// double-tracked — the DAX side resolves its measure references.
        #[test]
        fn refresh_policy_expressions_flow_through_the_m_enumeration() {
            let db = every_kind_fixture();

            assert_eq!(
                m_tuples(&db),
                vec![
                    (
                        partition_id("Sales", "Sales-Part1"),
                        "let Source = Sql.Database() in Source",
                    ),
                    (
                        partition_id("Sales", "Sales-Part1"),
                        "let Source = Sql.Database(Server, DB) in Source",
                    ),
                    (
                        partition_id("Sales", "Sales-Part1"),
                        "EVALUATE ROW(\"Bookmark\", [Total Sales])",
                    ),
                ]
            );
        }
    }
}