TMDL Authoring
Expert guidance for authoring and editing TMDL (Tabular Model Definition Language) files directly in PBIP projects.
This skill is a last resort. Direct TMDL file editing lacks the validation, atomicity, and DAX query capabilities of the Tabular Editor CLI, Power BI MCP server, or the connect-pbid skill (TOM via PowerShell). Use those tools when available. TMDL editing is appropriate when:
- Working with PBIP files in a Git repo without Power BI Desktop open
- No Tabular Editor CLI or MCP server is installed
- Making quick text-level fixes (descriptions, format strings, display folders) where a full tool chain is overkill
Direct TMDL editing does not validate DAX syntax, check referential integrity, or verify that property values are valid. Errors will only surface when the model is next loaded in Power BI Desktop or deployed via XMLA. Use the pbip-validator agent to check TMDL files for syntax issues, indentation errors, and referential integrity before opening in PBI Desktop.
Validation: tmdl-validate v0.2.0
tmdl-validate supports two modes:
# Single-file mode — validate one .tmdl file (used by PostToolUse hook per edit)
tmdl-validate path/to/tables/Sales.tmdl
# Directory mode — validate the whole model at once (v0.2.0+)
tmdl-validate path/to/Model.SemanticModel/definition
Directory mode adds one critical check not in single-file mode:
M-expression name collision — expressions.tmdl defines named shared expressions (Power Query parameters and queries). If a shared expression has the same name as a table, the model fails to load in Desktop with a silent error. Directory mode detects this.
# Example collision — expression "Sales" collides with table "Sales"
# expressions.tmdl:
expression Sales = ... # ← same name as a table in tables/Sales.tmdl
Fix: rename the shared expression or the table so names are unique across both expressions.tmdl and tables/.
When to use directory mode:
- After bulk renames (tables, shared expressions, parameters)
- After adding new tables or M parameters
- Before any Desktop open or XMLA deploy
- When
pbip-validator reports unexplained load failures
The single-file hook still runs per-edit; add a directory-mode pass as a final pre-commit step.
When to Use This Skill
Activate only when the Tabular Editor CLI, Power BI MCP server, or connect-pbid skill are not available, and tasks involve:
- Editing
.tmdl files directly (measures, columns, tables, relationships)
- Adding or modifying measure definitions in TMDL
- Adding descriptions to columns, measures, or tables
- Fixing
summarizeBy or formatString values
- Understanding TMDL syntax rules (indentation, quoting, property ordering)
- Writing multi-line DAX in TMDL format
- Understanding the difference between
/// descriptions and // comments
Critical
/// (triple-slash) sets the Description property on the object that immediately follows it. A /// line must be immediately followed by a declaration (measure, column, table, etc.) — never by a blank line or another ///. Use // for regular comments.
- Indentation is semantic. TMDL uses tabs for indentation, and depth equals nesting level. Properties of a table are indented one level; properties of a column (which belongs to a table) are indented two levels. Incorrect indentation will break the model.
- Name quoting rules: Only quote names that contain spaces, special characters, or start with a digit. Simple names and underscore-prefixed names are unquoted. See the Name Quoting section for details.
TMDL File Types
| File |
Contents |
Location |
model.tmdl |
Model configuration, ref table entries, query groups, annotations |
definition/ |
database.tmdl |
Compatibility level, model ID |
definition/ |
relationships.tmdl |
All relationships between tables |
definition/ |
expressions.tmdl |
Shared M expressions and parameters |
definition/ |
functions.tmdl |
DAX user-defined functions (reusable parameterized DAX) |
definition/ |
roles/<RoleName>.tmdl |
One file per security role (RLS filters, role members, OLS) |
definition/roles/ |
perspectives/<Name>.tmdl |
One file per perspective (object membership) |
definition/perspectives/ |
dataSources.tmdl |
Legacy data source definitions (if present) |
definition/ |
tables/<Name>.tmdl |
Table definition with columns, measures, hierarchies, partitions |
definition/tables/ |
cultures/<locale>.tmdl |
Linguistic metadata and translations |
definition/cultures/ |
Object Nesting Rules
Objects must be nested inside their correct parent. The validator enforces these rules:
| Object |
Allowed Parent(s) |
column, measure, hierarchy, partition, calculationGroup |
table |
level |
hierarchy |
calculationItem |
calculationGroup |
tablePermission |
role |
columnPermission |
tablePermission |
perspectiveTable |
perspective |
perspectiveColumn, perspectiveMeasure, perspectiveHierarchy |
perspectiveTable |
linguisticMetadata, translation |
cultureInfo |
dataAccessOptions |
model |
formatStringDefinition |
measure, calculationItem |
detailRowsDefinition |
measure, table |
alternateOf |
column |
member |
role |
annotation, extendedProperty |
any object (including queryGroup, function, member) |
ref |
model, table |
Root-level objects (indent 0 only): model, database, table, relationship, role, cultureInfo, perspective, dataSource, expression, queryGroup, function.
Syntax Rules
Indentation
TMDL uses tab-based indentation where depth equals nesting level:
table Product // depth 0: top-level declaration
lineageTag: abc-123 // depth 1: table property
measure '# Products' = // depth 1: measure declaration
COUNTROWS ( // depth 3: DAX expression body (one deeper than properties)
VALUES ( Product[Name] ) // depth 3: continued
) // depth 3: continued
formatString: #,##0 // depth 2: measure property
displayFolder: Measures // depth 2: measure property
lineageTag: def-456 // depth 2: measure property
column 'Product Name' // depth 1: column declaration
dataType: string // depth 2: column property
lineageTag: ghi-789 // depth 2: column property
summarizeBy: none // depth 2: column property
sourceColumn: Product Name // depth 2: column property
annotation SummarizationSetBy = Automatic // depth 2: column annotation
Key rules:
- Use tabs, not spaces
- Table-level objects (columns, measures, hierarchies, partitions) are at depth 1
- Properties of those objects are at depth 2
- Multi-line DAX expression bodies are always 2 levels deeper than the enclosing declaration (depth 3 for measures/columns inside a table; depth 2 for top-level functions; depth 4 for calculationItems)
- Annotations are at the same depth as properties of their parent object, separated by a blank line
Descriptions (///)
Triple-slash sets the Description property on the next declaration. This is native TMDL syntax (not a Tabular Editor extension); the TMDL spec treats /// as first-class description support.
/// Count of distinct products in the current filter context.
measure '# Products' =
COUNTROWS ( VALUES ( Product[Product Name] ) )
formatString: #,##0
lineageTag: abc-123
Rules:
/// must be immediately followed by a declaration on the next line
- No blank line between
/// and the declaration
- Multiple
/// lines concatenate into a single description
/// applies to the next measure, column, table, hierarchy, or level
Common mistake:
// WRONG: blank line between /// and declaration
/// This is a description.
measure 'My Measure' = 1
// WRONG: /// used as a separator comment
///
measure 'My Measure' = 1
// RIGHT: /// immediately before declaration
/// This is a description.
measure 'My Measure' = 1
// RIGHT: // used for regular comments
// This is just a comment, not a description.
measure 'My Measure' = 1
Comments (//)
Double-slash is a regular comment with no semantic effect:
// This is a comment — it does not set any property
measure 'My Measure' = 1
Property Ordering
Properties should follow a consistent order, though TMDL is not strict about it. The conventional order is:
For columns: dataType, isHidden, isKey, displayFolder, lineageTag, summarizeBy, isNameInferred, sourceColumn, sortByColumn, then annotations.
For measures: DAX expression (on the = line or multi-line), formatString or formatStringDefinition, displayFolder, lineageTag, then annotations.
Name Quoting
When to Quote
Use single quotes around names that contain any of these characters:
- Spaces:
'Product Name'
- Dots:
'Sales.Amount'
- Equals:
'Price = Target'
- Colons:
'Date:Key'
- Single quotes (escape by doubling):
'Customer''s Name'
- Other special characters:
'Sales ($)', 'OTD % (Value)', '1) Selected Metric'
- Names starting with a digit:
'4) Selected Period'
When NOT to Quote
Do not quote names that are simple identifiers:
Product (simple word)
_Measures (underscore prefix, no spaces)
Date (simple word)
CgMetricQuantity (PascalCase, no spaces)
Examples
table Product // unquoted: simple name
table _Measures // unquoted: underscore prefix
table 'Budget Rate' // quoted: contains space
table 'Invoice Document Type' // quoted: contains spaces
table '1) Selected Metric' // quoted: starts with digit
table 'On-Time Delivery' // quoted: contains space
Column Definitions
For complete column examples (basic, hidden, key, sortByColumn, description), see references/tmdl-file-examples.md. For full property reference, see references/column-properties.md.
Key column pattern:
column 'Product Name'
dataType: string
displayFolder: 1. Product Hierarchy
lineageTag: abc-123
summarizeBy: none
sourceColumn: Product Name
annotation SummarizationSetBy = Automatic
Measure Definitions
Single-Line DAX
measure '# Products' = COUNTROWS ( VALUES ( Product[Product Name] ) )
formatString: #,##0
displayFolder: Measures
lineageTag: abc-123
Multi-Line DAX
Two syntaxes for multi-line DAX:
1. Indented block (most common) -- expression body indented two levels deeper than the declaration:
2. Triple-backtick block -- DAX enclosed in ``` fences, useful for expressions with complex indentation:
measure Percentage = ```
VAR _Total = CALCULATE( SUM ( 'Table'[Quantitative] ), REMOVEFILTERS ( ) )
RETURN
DIVIDE ( SUM ( 'Table'[Quantitative] ), _Total )
```
formatString: 0.0%;-0.0%;0.0%
lineageTag: abc-123
Indented block syntax (standard approach) -- indented two extra tabs from the measure's parent (table) level:
measure 'Actuals MTD' =
CALCULATE (
[Actuals],
CALCULATETABLE (
DATESMTD ( 'Date'[Date] ),
'Date'[IsDateInScope]
)
)
formatString: #,##0
displayFolder: 2. MTD\Actuals
lineageTag: abc-123
Measure with Description
/// Number of workdays elapsed month-to-date, considering only dates in scope.
measure '# Workdays MTD' =
CALCULATE(
MAX( 'Date'[Workdays MTD] ),
'Date'[IsDateInScope] = TRUE
)
formatString: #,##0
displayFolder: 5. Weekday / Workday\Measures\# Workdays
lineageTag: abc-123
Measure with formatStringDefinition (Dynamic Format)
measure 'Sales Target MTD vs. Actuals (%)' =
Comparison.RelativeToTarget (
[Actuals MTD],
[Sales Target MTD]
)
displayFolder: 2. MTD\Sales Target
lineageTag: abc-123
formatStringDefinition =
FormatString.Comparison.RelativeToTarget (
"SUFFIX",
1,
"ARROWS",
"",
""
)
Note: formatStringDefinition replaces formatString when the format is computed dynamically via a DAX expression (often a calculation group format function).
Other Object Types
For complete examples of calculated columns, roles (RLS/OLS), calculation groups, date table marking, hierarchies, partitions, relationships, shared expressions, and model configuration, see references/tmdl-file-examples.md.
Common Data Quality Patterns
summarizeBy Rules
| Column Type |
Correct summarizeBy |
Reason |
| Keys (surrogate/natural) |
none |
Keys are never aggregated |
| Attributes (names, codes, types) |
none |
Text attributes are never summed |
| Dates |
none |
Dates are never summed |
| Boolean flags |
none |
Flags are never summed |
| Additive numeric facts (amounts, quantities) |
sum |
Default aggregation is SUM |
| Non-additive numeric facts (rates, percentages) |
none |
Cannot be meaningfully summed |
Common fix pattern — changing summarizeBy: sum to summarizeBy: none for key columns:
// Before (wrong - key column should not sum)
column 'Customer Key'
dataType: int64
isHidden
lineageTag: abc-123
summarizeBy: sum
sourceColumn: Customer Key
// After (correct)
column 'Customer Key'
dataType: int64
isHidden
lineageTag: abc-123
summarizeBy: none
sourceColumn: Customer Key
formatString Patterns
| Data Type |
Pattern |
Example |
| Integer |
#,##0 |
1,234 |
| Decimal (2 places) |
#,##0.00 |
1,234.56 |
| Percentage |
#,##0% or 0.00% |
85% or 85.00% |
| Currency |
$#,##0.00 |
$1,234.56 |
| Date |
mm/dd/yyyy or dd/mm/yyyy |
01/15/2024 |
PBI_FormatHint Annotation
Power BI Desktop may add a PBI_FormatHint annotation alongside formatString:
column Amount
dataType: decimal
formatString: #,##0.00
lineageTag: abc-123
summarizeBy: sum
sourceColumn: Amount
annotation SummarizationSetBy = Automatic
annotation PBI_FormatHint = {"isGeneralNumber":true}
Do not fight this annotation. Power BI tooling re-adds it automatically. When setting a formatString, leave any existing PBI_FormatHint in place. If Power BI re-adds a removed PBI_FormatHint, accept it.
Quick Reference
Property Cheat Sheet
For the complete property reference for every object type, see references/object-properties.md.
| Object |
Property |
Values |
Notes |
| Column |
dataType |
string, int64, double, decimal, dateTime, boolean, binary, unknown, variant, automatic |
Required for data columns |
| Column |
summarizeBy |
default, none, sum, min, max, count, average, distinctCount |
Use none for keys/attributes |
| Column |
type |
data, calculated, rowNumber, calculatedTableColumn |
Column type variant |
| Column |
isHidden |
(flag, no value) |
Boolean flags: write the keyword alone on its own line |
| Column |
isKey |
(flag, no value) |
Marks the column as the table's key |
| Column |
isNullable |
(flag, no value) |
Column allows nulls |
| Column |
isUnique |
(flag, no value) |
Column values are unique |
| Column |
isNameInferred |
(flag, no value) |
Name inferred from source |
| Column |
isDefaultLabel |
(flag, no value) |
Default label for the table |
| Column |
isDefaultImage |
(flag, no value) |
Default image for the table |
| Column |
isDataTypeInferred |
(flag, no value) |
Data type inferred from source |
| Column |
isAvailableInMdx |
(flag, no value) |
Available in MDX queries |
| Column |
keepUniqueRows |
(flag, no value) |
Keep unique rows |
| Column |
encodingHint |
default, hash, value |
Storage encoding hint |
| Column |
alignment |
default, left, right, center |
Column alignment |
| Column |
displayFolder |
folder path string |
Use \ for nesting: 1. Year\Quarter |
| Column |
sourceColumn |
source column name |
Must match the Power Query output column |
| Column |
sortByColumn |
column name reference |
Column to sort by (e.g., month name sorted by month number) |
| Column |
expression |
DAX expression |
For calculated columns |
| Measure |
formatString |
format pattern |
e.g., #,##0, 0.00% |
| Measure |
displayFolder |
folder path string |
Use \ for nesting |
| Measure |
formatStringDefinition |
DAX expression block |
Dynamic format string (replaces formatString) |
| Measure |
isHidden |
(flag, no value) |
Hide the measure |
| Measure |
isSimpleMeasure |
(flag, no value) |
Simple implicit-style measure |
| Measure |
dataCategory |
string |
Semantic data category |
| Partition |
mode |
import, directQuery, default, push, dual, directLake |
Storage mode |
| Partition |
sourceType |
query, calculated, none, m, entity, policyRange, calculationGroup, inferred |
Source type |
| Relationship |
crossFilteringBehavior |
oneDirection, bothDirections, automatic |
Cross-filter direction |
| Relationship |
securityFilteringBehavior |
oneDirection, bothDirections, none |
RLS filter direction |
| Relationship |
fromCardinality / toCardinality |
none, one, many |
Cardinality ends |
| Relationship |
isActive |
(flag, no value) |
Active relationship |
| Role |
modelPermission |
none, read, readRefresh, refresh, administrator |
Role permission level |
| Model |
discourageImplicitMeasures |
(flag, no value) |
Disables implicit measures |
| Model |
defaultPowerBIDataSourceVersion |
powerBI_V1, powerBI_V2, powerBI_V3 |
PBI data source version |
| Model |
directLakeBehavior |
automatic, directLakeOnly, directQueryOnly |
Direct Lake mode |
| All |
lineageTag |
GUID |
Unique identifier, do not change existing values |
Indentation Depth Summary
Rule: a multi-line DAX body is always 2 levels deeper than its enclosing object declaration.
| Context |
Depth |
Tabs |
Top-level declaration (table, relationship, expression) |
0 |
0 |
| Table properties, column/measure/hierarchy declarations |
1 |
1 |
| Column/measure properties, hierarchy levels |
2 |
2 |
| DAX body for measure/column declared at depth 1 (inside table) |
3 |
3 |
| Level properties |
3 |
3 |
DAX body for top-level function declared at depth 0 |
2 |
2 |
calculationItem inside calculationGroup (depth 1) |
2 |
2 |
DAX body for calculationItem at depth 2 |
4 |
4 |
Additional Resources
Reference Files
references/object-properties.md - Complete property reference for all 30+ TMDL object types with valid enum values for every property type (dataType, summarizeBy, modeType, crossFilteringBehavior, etc.)
references/column-properties.md - Column-specific property guide with summarizeBy rules, formatString patterns, PBI_FormatHint behavior
references/naming-conventions.md - SQLBI naming conventions, display folder conventions, measure table conventions, and calculation group naming
references/bim-to-tmdl.md - Converting between model.bim (TMSL) and definition/ (TMDL) via Tabular Editor CLI or TOM TmdlSerializer
references/tmdl-file-examples.md - Complete examples for every TMDL file type (model, database, expressions, relationships, roles, perspectives, tables, cultures) including backtick-enclosed expressions, field parameters, calculation groups, and date tables
Fetching Docs
To retrieve current TMDL reference docs, use microsoft_docs_search + microsoft_docs_fetch (MCP) if available, otherwise mslearn search + mslearn fetch (CLI). Search based on the user's request and run multiple searches as needed to ensure sufficient context before proceeding.
Example Model
examples/SpaceParts.SemanticModel/ -- Complete real-world TMDL model (SpaceParts) with 40 tables, 152 measures, 8 calculation groups, 8 RLS roles, 2 perspectives, DAX UDFs (functions.tmdl), shared M expressions, relationships, and cultures. Covers every TMDL file type. Key files to study:
definition/functions.tmdl -- DAX user-defined functions with parameters, types, and multi-line expressions
definition/tables/Z04CG1 - Time Intelligence.tmdl -- Calculation group with triple-backtick DAX
definition/tables/__Measures.tmdl -- Measures table with calculation group references
definition/tables/Invoices.tmdl -- Large fact table (51 measures, 18 columns)
definition/tables/Date.tmdl -- Calculated date table with 42 columns
definition/roles/Account Managers.tmdl -- RLS role with DAX filter expression
definition/relationships.tmdl -- 27 relationships including inactive
definition/expressions.tmdl -- Shared M/Power Query expressions and parameters
definition/perspectives/Measure Selection.tmdl -- Perspective definition
External References
1---2name: powerbi-tmdl3description: Direct TMDL file authoring and BIM-to-TMDL conversion for semantic models in PBIP projects. Automatically invoke when the user asks to "edit TMDL", "add a measure in TMDL", "TMDL syntax", "fix formatString", "fix summarizeBy", "TMDL indentation", "convert BIM to TMDL", "add a column description", "create a calculated column in TMDL", or mentions .tmdl file editing or BIM-to-TMDL migration.4license: MIT5---67# TMDL Authoring89Expert guidance for authoring and editing TMDL (Tabular Model Definition Language) files directly in PBIP projects.1011> **This skill is a last resort.** Direct TMDL file editing lacks the validation, atomicity, and DAX query capabilities of the Tabular Editor CLI, Power BI MCP server, or the `connect-pbid` skill (TOM via PowerShell). Use those tools when available. TMDL editing is appropriate when:12>13> - Working with PBIP files in a Git repo without Power BI Desktop open14> - No Tabular Editor CLI or MCP server is installed15> - Making quick text-level fixes (descriptions, format strings, display folders) where a full tool chain is overkill16>17> Direct TMDL editing does not validate DAX syntax, check referential integrity, or verify that property values are valid. Errors will only surface when the model is next loaded in Power BI Desktop or deployed via XMLA. Use the **`pbip-validator`** agent to check TMDL files for syntax issues, indentation errors, and referential integrity before opening in PBI Desktop.1819## Validation: tmdl-validate v0.2.02021`tmdl-validate` supports two modes:2223```bash24# Single-file mode — validate one .tmdl file (used by PostToolUse hook per edit)25tmdl-validate path/to/tables/Sales.tmdl2627# Directory mode — validate the whole model at once (v0.2.0+)28tmdl-validate path/to/Model.SemanticModel/definition29```3031**Directory mode adds one critical check not in single-file mode:**3233**M-expression name collision** — `expressions.tmdl` defines named shared expressions (Power Query parameters and queries). If a shared expression has the same name as a table, the model fails to load in Desktop with a silent error. Directory mode detects this.3435```36# Example collision — expression "Sales" collides with table "Sales"37# expressions.tmdl:38expression Sales = ... # ← same name as a table in tables/Sales.tmdl39```4041Fix: rename the shared expression or the table so names are unique across both `expressions.tmdl` and `tables/`.4243**When to use directory mode:**44- After bulk renames (tables, shared expressions, parameters)45- After adding new tables or M parameters46- Before any Desktop open or XMLA deploy47- When `pbip-validator` reports unexplained load failures4849The single-file hook still runs per-edit; add a directory-mode pass as a final pre-commit step.5051## When to Use This Skill5253Activate only when the Tabular Editor CLI, Power BI MCP server, or `connect-pbid` skill are not available, and tasks involve:5455- Editing `.tmdl` files directly (measures, columns, tables, relationships)56- Adding or modifying measure definitions in TMDL57- Adding descriptions to columns, measures, or tables58- Fixing `summarizeBy` or `formatString` values59- Understanding TMDL syntax rules (indentation, quoting, property ordering)60- Writing multi-line DAX in TMDL format61- Understanding the difference between `///` descriptions and `//` comments6263## Critical6465- **`///` (triple-slash) sets the `Description` property** on the object that immediately follows it. A `///` line must be immediately followed by a declaration (`measure`, `column`, `table`, etc.) — never by a blank line or another `///`. Use `//` for regular comments.66- **Indentation is semantic.** TMDL uses tabs for indentation, and depth equals nesting level. Properties of a table are indented one level; properties of a column (which belongs to a table) are indented two levels. Incorrect indentation will break the model.67- **Name quoting rules:** Only quote names that contain spaces, special characters, or start with a digit. Simple names and underscore-prefixed names are unquoted. See the Name Quoting section for details.6869## TMDL File Types7071| File | Contents | Location |72|------|----------|----------|73| `model.tmdl` | Model configuration, `ref table` entries, query groups, annotations | `definition/` |74| `database.tmdl` | Compatibility level, model ID | `definition/` |75| `relationships.tmdl` | All relationships between tables | `definition/` |76| `expressions.tmdl` | Shared M expressions and parameters | `definition/` |77| `functions.tmdl` | DAX user-defined functions (reusable parameterized DAX) | `definition/` |78| `roles/<RoleName>.tmdl` | One file per security role (RLS filters, role members, OLS) | `definition/roles/` |79| `perspectives/<Name>.tmdl` | One file per perspective (object membership) | `definition/perspectives/` |80| `dataSources.tmdl` | Legacy data source definitions (if present) | `definition/` |81| `tables/<Name>.tmdl` | Table definition with columns, measures, hierarchies, partitions | `definition/tables/` |82| `cultures/<locale>.tmdl` | Linguistic metadata and translations | `definition/cultures/` |8384## Object Nesting Rules8586Objects must be nested inside their correct parent. The validator enforces these rules:8788| Object | Allowed Parent(s) |89|--------|-------------------|90| `column`, `measure`, `hierarchy`, `partition`, `calculationGroup` | `table` |91| `level` | `hierarchy` |92| `calculationItem` | `calculationGroup` |93| `tablePermission` | `role` |94| `columnPermission` | `tablePermission` |95| `perspectiveTable` | `perspective` |96| `perspectiveColumn`, `perspectiveMeasure`, `perspectiveHierarchy` | `perspectiveTable` |97| `linguisticMetadata`, `translation` | `cultureInfo` |98| `dataAccessOptions` | `model` |99| `formatStringDefinition` | `measure`, `calculationItem` |100| `detailRowsDefinition` | `measure`, `table` |101| `alternateOf` | `column` |102| `member` | `role` |103| `annotation`, `extendedProperty` | any object (including `queryGroup`, `function`, `member`) |104| `ref` | `model`, `table` |105106Root-level objects (indent 0 only): `model`, `database`, `table`, `relationship`, `role`, `cultureInfo`, `perspective`, `dataSource`, `expression`, `queryGroup`, `function`.107108## Syntax Rules109110### Indentation111112TMDL uses **tab-based indentation** where depth equals nesting level:113114```tmdl115table Product // depth 0: top-level declaration116 lineageTag: abc-123 // depth 1: table property117118 measure '# Products' = // depth 1: measure declaration119 COUNTROWS ( // depth 3: DAX expression body (one deeper than properties)120 VALUES ( Product[Name] ) // depth 3: continued121 ) // depth 3: continued122 formatString: #,##0 // depth 2: measure property123 displayFolder: Measures // depth 2: measure property124 lineageTag: def-456 // depth 2: measure property125126 column 'Product Name' // depth 1: column declaration127 dataType: string // depth 2: column property128 lineageTag: ghi-789 // depth 2: column property129 summarizeBy: none // depth 2: column property130 sourceColumn: Product Name // depth 2: column property131132 annotation SummarizationSetBy = Automatic // depth 2: column annotation133```134135**Key rules:**136- Use tabs, not spaces137- Table-level objects (columns, measures, hierarchies, partitions) are at depth 1138- Properties of those objects are at depth 2139- Multi-line DAX expression bodies are always **2 levels deeper than the enclosing declaration** (depth 3 for measures/columns inside a table; depth 2 for top-level functions; depth 4 for calculationItems)140- Annotations are at the same depth as properties of their parent object, separated by a blank line141142### Descriptions (`///`)143144Triple-slash sets the `Description` property on the **next** declaration. This is native TMDL syntax (not a Tabular Editor extension); the TMDL spec treats `///` as first-class description support.145146```tmdl147/// Count of distinct products in the current filter context.148measure '# Products' =149 COUNTROWS ( VALUES ( Product[Product Name] ) )150 formatString: #,##0151 lineageTag: abc-123152```153154**Rules:**155- `///` must be immediately followed by a declaration on the next line156- No blank line between `///` and the declaration157- Multiple `///` lines concatenate into a single description158- `///` applies to the next `measure`, `column`, `table`, `hierarchy`, or `level`159160**Common mistake:**161```tmdl162// WRONG: blank line between /// and declaration163/// This is a description.164165measure 'My Measure' = 1166167// WRONG: /// used as a separator comment168///169measure 'My Measure' = 1170171// RIGHT: /// immediately before declaration172/// This is a description.173measure 'My Measure' = 1174175// RIGHT: // used for regular comments176// This is just a comment, not a description.177measure 'My Measure' = 1178```179180### Comments (`//`)181182Double-slash is a regular comment with no semantic effect:183184```tmdl185// This is a comment — it does not set any property186measure 'My Measure' = 1187```188189### Property Ordering190191Properties should follow a consistent order, though TMDL is not strict about it. The conventional order is:192193**For columns:** `dataType`, `isHidden`, `isKey`, `displayFolder`, `lineageTag`, `summarizeBy`, `isNameInferred`, `sourceColumn`, `sortByColumn`, then annotations.194195**For measures:** DAX expression (on the `=` line or multi-line), `formatString` or `formatStringDefinition`, `displayFolder`, `lineageTag`, then annotations.196197## Name Quoting198199### When to Quote200201Use single quotes around names that contain any of these characters:202- Spaces: `'Product Name'`203- Dots: `'Sales.Amount'`204- Equals: `'Price = Target'`205- Colons: `'Date:Key'`206- Single quotes (escape by doubling): `'Customer''s Name'`207- Other special characters: `'Sales ($)'`, `'OTD % (Value)'`, `'1) Selected Metric'`208- Names starting with a digit: `'4) Selected Period'`209210### When NOT to Quote211212Do not quote names that are simple identifiers:213- `Product` (simple word)214- `_Measures` (underscore prefix, no spaces)215- `Date` (simple word)216- `CgMetricQuantity` (PascalCase, no spaces)217218### Examples219220```tmdl221table Product // unquoted: simple name222table _Measures // unquoted: underscore prefix223table 'Budget Rate' // quoted: contains space224table 'Invoice Document Type' // quoted: contains spaces225table '1) Selected Metric' // quoted: starts with digit226table 'On-Time Delivery' // quoted: contains space227```228229## Column Definitions230231For complete column examples (basic, hidden, key, sortByColumn, description), see **`references/tmdl-file-examples.md`**. For full property reference, see **`references/column-properties.md`**.232233Key column pattern:234235```tmdl236column 'Product Name'237 dataType: string238 displayFolder: 1. Product Hierarchy239 lineageTag: abc-123240 summarizeBy: none241 sourceColumn: Product Name242243 annotation SummarizationSetBy = Automatic244```245246## Measure Definitions247248### Single-Line DAX249250```tmdl251measure '# Products' = COUNTROWS ( VALUES ( Product[Product Name] ) )252 formatString: #,##0253 displayFolder: Measures254 lineageTag: abc-123255```256257### Multi-Line DAX258259Two syntaxes for multi-line DAX:260261**1. Indented block** (most common) -- expression body indented two levels deeper than the declaration:262263**2. Triple-backtick block** -- DAX enclosed in `` ``` `` fences, useful for expressions with complex indentation:264265```tmdl266measure Percentage = ```267 VAR _Total = CALCULATE( SUM ( 'Table'[Quantitative] ), REMOVEFILTERS ( ) )268 RETURN269 DIVIDE ( SUM ( 'Table'[Quantitative] ), _Total )270 ```271 formatString: 0.0%;-0.0%;0.0%272 lineageTag: abc-123273```274275**Indented block syntax** (standard approach) -- indented two extra tabs from the measure's parent (table) level:276277```tmdl278measure 'Actuals MTD' =279 CALCULATE (280 [Actuals],281 CALCULATETABLE (282 DATESMTD ( 'Date'[Date] ),283 'Date'[IsDateInScope]284 )285 )286 formatString: #,##0287 displayFolder: 2. MTD\Actuals288 lineageTag: abc-123289```290291### Measure with Description292293```tmdl294/// Number of workdays elapsed month-to-date, considering only dates in scope.295measure '# Workdays MTD' =296 CALCULATE(297 MAX( 'Date'[Workdays MTD] ),298 'Date'[IsDateInScope] = TRUE299 )300 formatString: #,##0301 displayFolder: 5. Weekday / Workday\Measures\# Workdays302 lineageTag: abc-123303```304305### Measure with formatStringDefinition (Dynamic Format)306307```tmdl308measure 'Sales Target MTD vs. Actuals (%)' =309 Comparison.RelativeToTarget (310 [Actuals MTD],311 [Sales Target MTD]312 )313 displayFolder: 2. MTD\Sales Target314 lineageTag: abc-123315316 formatStringDefinition =317 FormatString.Comparison.RelativeToTarget (318 "SUFFIX",319 1,320 "ARROWS",321 "",322 ""323 )324```325326**Note:** `formatStringDefinition` replaces `formatString` when the format is computed dynamically via a DAX expression (often a calculation group format function).327328## Other Object Types329330For complete examples of calculated columns, roles (RLS/OLS), calculation groups, date table marking, hierarchies, partitions, relationships, shared expressions, and model configuration, see **`references/tmdl-file-examples.md`**.331332333## Common Data Quality Patterns334335### summarizeBy Rules336337| Column Type | Correct `summarizeBy` | Reason |338|-------------|----------------------|--------|339| Keys (surrogate/natural) | `none` | Keys are never aggregated |340| Attributes (names, codes, types) | `none` | Text attributes are never summed |341| Dates | `none` | Dates are never summed |342| Boolean flags | `none` | Flags are never summed |343| Additive numeric facts (amounts, quantities) | `sum` | Default aggregation is SUM |344| Non-additive numeric facts (rates, percentages) | `none` | Cannot be meaningfully summed |345346**Common fix pattern** — changing `summarizeBy: sum` to `summarizeBy: none` for key columns:347348```tmdl349// Before (wrong - key column should not sum)350column 'Customer Key'351 dataType: int64352 isHidden353 lineageTag: abc-123354 summarizeBy: sum355 sourceColumn: Customer Key356357// After (correct)358column 'Customer Key'359 dataType: int64360 isHidden361 lineageTag: abc-123362 summarizeBy: none363 sourceColumn: Customer Key364```365366### formatString Patterns367368| Data Type | Pattern | Example |369|-----------|---------|---------|370| Integer | `#,##0` | 1,234 |371| Decimal (2 places) | `#,##0.00` | 1,234.56 |372| Percentage | `#,##0%` or `0.00%` | 85% or 85.00% |373| Currency | `$#,##0.00` | $1,234.56 |374| Date | `mm/dd/yyyy` or `dd/mm/yyyy` | 01/15/2024 |375376### PBI_FormatHint Annotation377378Power BI Desktop may add a `PBI_FormatHint` annotation alongside `formatString`:379380```tmdl381column Amount382 dataType: decimal383 formatString: #,##0.00384 lineageTag: abc-123385 summarizeBy: sum386 sourceColumn: Amount387388 annotation SummarizationSetBy = Automatic389390 annotation PBI_FormatHint = {"isGeneralNumber":true}391```392393**Do not fight this annotation.** Power BI tooling re-adds it automatically. When setting a `formatString`, leave any existing `PBI_FormatHint` in place. If Power BI re-adds a removed `PBI_FormatHint`, accept it.394395396## Quick Reference397398### Property Cheat Sheet399400For the complete property reference for every object type, see **`references/object-properties.md`**.401402| Object | Property | Values | Notes |403|--------|----------|--------|-------|404| Column | `dataType` | `string`, `int64`, `double`, `decimal`, `dateTime`, `boolean`, `binary`, `unknown`, `variant`, `automatic` | Required for data columns |405| Column | `summarizeBy` | `default`, `none`, `sum`, `min`, `max`, `count`, `average`, `distinctCount` | Use `none` for keys/attributes |406| Column | `type` | `data`, `calculated`, `rowNumber`, `calculatedTableColumn` | Column type variant |407| Column | `isHidden` | (flag, no value) | Boolean flags: write the keyword alone on its own line |408| Column | `isKey` | (flag, no value) | Marks the column as the table's key |409| Column | `isNullable` | (flag, no value) | Column allows nulls |410| Column | `isUnique` | (flag, no value) | Column values are unique |411| Column | `isNameInferred` | (flag, no value) | Name inferred from source |412| Column | `isDefaultLabel` | (flag, no value) | Default label for the table |413| Column | `isDefaultImage` | (flag, no value) | Default image for the table |414| Column | `isDataTypeInferred` | (flag, no value) | Data type inferred from source |415| Column | `isAvailableInMdx` | (flag, no value) | Available in MDX queries |416| Column | `keepUniqueRows` | (flag, no value) | Keep unique rows |417| Column | `encodingHint` | `default`, `hash`, `value` | Storage encoding hint |418| Column | `alignment` | `default`, `left`, `right`, `center` | Column alignment |419| Column | `displayFolder` | folder path string | Use `\` for nesting: `1. Year\Quarter` |420| Column | `sourceColumn` | source column name | Must match the Power Query output column |421| Column | `sortByColumn` | column name reference | Column to sort by (e.g., month name sorted by month number) |422| Column | `expression` | DAX expression | For calculated columns |423| Measure | `formatString` | format pattern | e.g., `#,##0`, `0.00%` |424| Measure | `displayFolder` | folder path string | Use `\` for nesting |425| Measure | `formatStringDefinition` | DAX expression block | Dynamic format string (replaces `formatString`) |426| Measure | `isHidden` | (flag, no value) | Hide the measure |427| Measure | `isSimpleMeasure` | (flag, no value) | Simple implicit-style measure |428| Measure | `dataCategory` | string | Semantic data category |429| Partition | `mode` | `import`, `directQuery`, `default`, `push`, `dual`, `directLake` | Storage mode |430| Partition | `sourceType` | `query`, `calculated`, `none`, `m`, `entity`, `policyRange`, `calculationGroup`, `inferred` | Source type |431| Relationship | `crossFilteringBehavior` | `oneDirection`, `bothDirections`, `automatic` | Cross-filter direction |432| Relationship | `securityFilteringBehavior` | `oneDirection`, `bothDirections`, `none` | RLS filter direction |433| Relationship | `fromCardinality` / `toCardinality` | `none`, `one`, `many` | Cardinality ends |434| Relationship | `isActive` | (flag, no value) | Active relationship |435| Role | `modelPermission` | `none`, `read`, `readRefresh`, `refresh`, `administrator` | Role permission level |436| Model | `discourageImplicitMeasures` | (flag, no value) | Disables implicit measures |437| Model | `defaultPowerBIDataSourceVersion` | `powerBI_V1`, `powerBI_V2`, `powerBI_V3` | PBI data source version |438| Model | `directLakeBehavior` | `automatic`, `directLakeOnly`, `directQueryOnly` | Direct Lake mode |439| All | `lineageTag` | GUID | Unique identifier, do not change existing values |440441### Indentation Depth Summary442443**Rule: a multi-line DAX body is always 2 levels deeper than its enclosing object declaration.**444445| Context | Depth | Tabs |446|---------|-------|------|447| Top-level declaration (`table`, `relationship`, `expression`) | 0 | 0 |448| Table properties, column/measure/hierarchy declarations | 1 | 1 |449| Column/measure properties, hierarchy levels | 2 | 2 |450| DAX body for measure/column declared at depth 1 (inside table) | 3 | 3 |451| Level properties | 3 | 3 |452| DAX body for top-level `function` declared at depth 0 | 2 | 2 |453| `calculationItem` inside `calculationGroup` (depth 1) | 2 | 2 |454| DAX body for `calculationItem` at depth 2 | 4 | 4 |455456## Additional Resources457458### Reference Files459460- **`references/object-properties.md`** - Complete property reference for all 30+ TMDL object types with valid enum values for every property type (dataType, summarizeBy, modeType, crossFilteringBehavior, etc.)461- **`references/column-properties.md`** - Column-specific property guide with `summarizeBy` rules, `formatString` patterns, `PBI_FormatHint` behavior462- **`references/naming-conventions.md`** - SQLBI naming conventions, display folder conventions, measure table conventions, and calculation group naming463- **`references/bim-to-tmdl.md`** - Converting between `model.bim` (TMSL) and `definition/` (TMDL) via Tabular Editor CLI or TOM TmdlSerializer464- **`references/tmdl-file-examples.md`** - Complete examples for every TMDL file type (model, database, expressions, relationships, roles, perspectives, tables, cultures) including backtick-enclosed expressions, field parameters, calculation groups, and date tables465466### Fetching Docs467468To retrieve current TMDL reference docs, use `microsoft_docs_search` + `microsoft_docs_fetch` (MCP) if available, otherwise `mslearn search` + `mslearn fetch` (CLI). Search based on the user's request and run multiple searches as needed to ensure sufficient context before proceeding.469470### Example Model471472- **`examples/SpaceParts.SemanticModel/`** -- Complete real-world TMDL model (SpaceParts) with 40 tables, 152 measures, 8 calculation groups, 8 RLS roles, 2 perspectives, DAX UDFs (functions.tmdl), shared M expressions, relationships, and cultures. Covers every TMDL file type. Key files to study:473 - `definition/functions.tmdl` -- DAX user-defined functions with parameters, types, and multi-line expressions474 - `definition/tables/Z04CG1 - Time Intelligence.tmdl` -- Calculation group with triple-backtick DAX475 - `definition/tables/__Measures.tmdl` -- Measures table with calculation group references476 - `definition/tables/Invoices.tmdl` -- Large fact table (51 measures, 18 columns)477 - `definition/tables/Date.tmdl` -- Calculated date table with 42 columns478 - `definition/roles/Account Managers.tmdl` -- RLS role with DAX filter expression479 - `definition/relationships.tmdl` -- 27 relationships including inactive480 - `definition/expressions.tmdl` -- Shared M/Power Query expressions and parameters481 - `definition/perspectives/Measure Selection.tmdl` -- Perspective definition482483### External References484485- [TMDL overview (Microsoft Learn)](https://learn.microsoft.com/en-us/analysis-services/tmdl/tmdl-overview)486- [TMDL syntax reference (Microsoft Learn)](https://learn.microsoft.com/en-us/analysis-services/tmdl/tmdl-how-to)487- [SQLBI naming conventions](https://www.sqlbi.com/articles/rules-of-the-game-how-to-name-things-in-your-data-model/)