
Power Query
- 50 installs
- 836 repo stars
- Updated July 29, 2026
- data-goblin/power-bi-agentic-development
Author, validate, and test Power Query M expressions in semantic model partitions, preserving query folding and previewing partition data.
About
Guidance for writing, validating, and testing Power Query M expressions in semantic model import partitions while preserving query folding. A developer uses it to write or fix partition M code and test it against real data sources.
- Authors and debugs Power Query M partition expressions
- Preserves query folding and previews partition data
Power Query by the numbers
- 50 all-time installs (skills.sh)
- Ranked #929 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/data-goblin/power-bi-agentic-development --skill power-queryAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 50 |
|---|---|
| repo stars | ★ 836 |
| Last updated | July 29, 2026 |
| Repository | data-goblin/power-bi-agentic-development ↗ |
What it does
Author, validate, and test Power Query M expressions in semantic model partitions, preserving query folding and previewing partition data.
Files
Power Query for Semantic Models
Author, validate, and test Power Query M expressions in semantic model import partitions. Covers writing correct M code, preserving query folding, validating expressions, and testing them by executing against real data sources.
Partition Expressions
Each import table in a semantic model has a partition with an M expression defining what data gets loaded during refresh. The expression typically connects to a data source, navigates to a table/view, and applies transformations.
Structure of a Partition Expression
let
Source = Sql.Database(#"SqlEndpoint", #"Database"),
Data = Source{[Schema="dbo", Item="Orders"]}[Data],
#"Removed Columns" = Table.RemoveColumns(Data, {"InternalId"}),
#"Changed Type" = Table.TransformColumnTypes(#"Removed Columns", {{"Amount", Currency.Type}})
in
#"Changed Type"Key elements:
- Parameters:
#"SqlEndpoint",#"Database"are shared M parameters defined at the model level - Navigation:
Source{[Schema="dbo", Item="Orders"]}[Data]navigates to a specific table - Steps: Each step is a named variable in the
let...inchain - Quoted identifiers: Step names with spaces use
#"Step Name"syntax
Extracting Expressions
# Get partition expression from TMDL via fab
fab get "<Workspace>.Workspace/<Model>.SemanticModel" -f \
-q "definition.parts[?path=='definition/tables/<Table>.tmdl'].payload"
# Get shared M parameters
fab get "<Workspace>.Workspace/<Model>.SemanticModel" -f \
-q "definition.parts[?path=='definition/expressions.tmdl'].payload"Writing M Expressions
Query Folding
Query folding is the most important performance concept. The M engine translates compatible steps into native data source queries (e.g., SQL). When folding breaks, subsequent steps run in the mashup engine, pulling all data into memory first.
Steps that typically fold (for SQL sources):
Table.SelectColumns/Table.RemoveColumns->SELECTTable.SelectRows->WHERETable.Sort->ORDER BYTable.FirstN->TOPTable.Group->GROUP BYTable.RenameColumns->ASaliases
Steps that may or may not fold (source-dependent):
Table.TransformColumnTypes-- frequently breaks folding for text-to-numeric/date conversions on SQL Server sources. UseTable.TransformColumnswith explicit conversion functions (e.g.,Number.From) as a more reliable foldable alternative.
Steps that break folding:
Table.AddColumnwith custom M functions (not translatable to SQL)Table.Buffer(forces materialization; preferTable.StopFoldingto stop folding without the memory overhead)Table.LastN(no SQL equivalent without subquery)Table.Combineacross different data sources (cross-database folding within the same SQL Server is possible viaEnableCrossDatabaseFolding)- Complex
eachexpressions with M-specific logic - Any step after a fold-breaking step
Best practice: Apply folding-compatible steps (filter, select, type) early; add custom columns and M-only transforms after all foldable work is done.
Column Pruning and Row Filtering
Remove unused columns and filter rows as early as possible:
let
Source = Sql.Database(SqlEndpoint, Database),
Data = Source{[Schema="dbo", Item="Orders"]}[Data],
// Filter and select BEFORE any custom transforms
#"Filtered" = Table.SelectRows(Data, each [Status] <> "Cancelled"),
#"Selected" = Table.SelectColumns(#"Filtered", {"OrderId", "Date", "Amount", "CustomerId"})
in
#"Selected"These steps fold to SQL: SELECT OrderId, Date, Amount, CustomerId FROM dbo.Orders WHERE Status <> 'Cancelled'
Type Handling
- Apply
Table.TransformColumnTypesearly (folds toCASTin SQL) - Use explicit M types:
Int64.Type,type text,type date,Currency.Type,type logical - Avoid implicit type inference on large datasets
Naming Conventions
- Step names should describe the transformation:
#"Removed Duplicates",#"Filtered Active" - Avoid generic names like
#"Custom1"or#"Step1" - Use quoted identifiers
#"Name"for steps with spaces (Power Query convention)
Validating M Expressions
Two approaches to validate that an M expression is syntactically correct and produces expected results:
1. Execute via the Power Query API (Recommended)
Test the expression by running it against real data. This validates syntax, data source connectivity, and transformation correctness in one step.
The full workflow, run by the bundled examples/execute_m.py:
1. Create or reuse a runner dataflow in the workspace 2. Bind the data source connection to the runner 3. Wrap the expression in a section document, inline parameters 4. Execute via POST /v1/workspaces/{wsId}/dataflows/{dfId}/executeQuery 5. Parse the Arrow response to verify data
MASHUP='section Section1;
shared SqlEndpoint = "myserver.database.windows.net";
shared Database = "MyDB";
shared Result = let
Source = Sql.Database(SqlEndpoint, Database),
Data = Table.FirstN(Source{[Schema="dbo",Item="Orders"]}[Data], 10)
in Data;'
curl -s -o result.bin -X POST ".../executeQuery" \
-H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" \
-d "$(jq -n --arg m "$MASHUP" '{queryName:"Result",customMashupDocument:$m}')"See `references/validation.md` for step-by-step instructions and error handling.
2. Save the Partition via XMLA / TOM
Write the expression back to the model; Analysis Services validates the M syntax on save. This doesn't execute the query but catches structural errors:
- Missing or mismatched
let/in - Undefined step references
- Invalid function calls
- Type mismatches in
TransformColumnTypes
# Edit the TMDL partition source directly and deploy via fab import,
# or use the XMLA endpoint with Tabular Editor or SSMS to modify
# the partition expression on the deployed model.AS returns an error if the expression is malformed. This is faster than a full execute but doesn't catch runtime errors (wrong column names, data source issues).
Choosing a Validation Approach
| Need | Use |
|---|---|
| Full data validation (correct columns, types, values) | Execute via API |
| Quick syntax check | Save to model via XMLA/TOM |
| Step-by-step debugging | Execute with truncated in clause |
| Performance testing (check folding) | Execute with full data, observe timing |
Previewing Partition Steps
See the data at any point in the transformation chain by truncating the let...in:
-- See raw source data (all columns)
in Data;
-- See after column removal
in #"Removed Columns";
-- See final result
in #"Changed Type";Add Table.FirstN(stepName, 100) before the in to limit rows for large tables. See `references/validation.md` for the complete procedure.
Common Patterns
Incremental Refresh Partitions
Incremental refresh partitions use RangeStart and RangeEnd parameters:
let
Source = Sql.Database(#"SqlEndpoint", #"Database"),
Data = Source{[Schema="dbo", Item="Orders"]}[Data],
#"Filtered" = Table.SelectRows(Data, each
[OrderDate] >= #"RangeStart" and [OrderDate] < #"RangeEnd")
in
#"Filtered"When testing, inline concrete date values for RangeStart and RangeEnd.
Lakehouse Sources
let
Source = Lakehouse.Contents(null),
Data = Source{[Id="lakehouse-guid"]}[Data],
Table = Data{[Id="table-name", ItemKind="Table"]}[Data]
in
TableSQL with Native Query
For complex SQL that can't be expressed in M:
let
Source = Sql.Database("server", "db"),
Data = Value.NativeQuery(Source, "SELECT * FROM dbo.MyView WHERE Year = 2024", null, [EnableFolding=true])
in
DataValue.NativeQuery with EnableFolding=true allows subsequent M steps to fold on top of the native query.
References
- `references/validation.md` -- Detailed validation workflow with executeQuery API, step preview, error handling
- `references/best-practices.md` -- Query folding guidance, fold-breaker list, anti-patterns, performance tips
- `examples/execute_m.py` -- Python script to execute M expressions via the Fabric API (CLI tool)
- `examples/preview_partition.py` -- Python script to preview partition data at any step (uses
fab get+execute_m.py) - Power Query M Reference
- Query Folding Guidance
"""Execute a Power Query M expression via the Fabric executeQuery API.
Sends a custom M section document to a runner dataflow and returns the result
as a pandas DataFrame. Handles Arrow response parsing and error detection.
Requires:
- pyarrow (uv run --with pyarrow)
- az CLI authenticated (az login)
- A runner dataflow with data source connections bound
Usage:
uv run --with pyarrow python3 execute_m.py \
--workspace <workspace-id> \
--dataflow <dataflow-id> \
--mashup 'section Section1; shared Result = #table({"A"}, {{"hello"}});'
# Or pipe mashup from stdin:
echo 'section Section1; shared Result = ...' | \
uv run --with pyarrow python3 execute_m.py -w <ws-id> -d <df-id> --stdin
# Output to CSV:
uv run --with pyarrow python3 execute_m.py -w <ws-id> -d <df-id> \
--mashup '...' --output result.csv
"""
# region Imports
import argparse
import io
import json
import subprocess
import sys
import urllib.request
import urllib.error
import pyarrow.ipc as ipc
# endregion
# region Functions
def get_token():
"""Get a Fabric API access token from az CLI.
Returns the access token string.
Raises RuntimeError if az CLI is not authenticated.
"""
result = subprocess.run(
["az", "account", "get-access-token",
"--resource", "https://api.fabric.microsoft.com",
"--query", "accessToken", "-o", "tsv"],
capture_output=True, text=True
)
if result.returncode != 0:
raise RuntimeError(f"az CLI error: {result.stderr.strip()}")
return result.stdout.strip()
def execute_m(ws_id, df_id, token, mashup, query_name="Result"):
"""Execute an M section document and return a pandas DataFrame.
Args:
ws_id: Workspace GUID
df_id: Dataflow GUID (the runner)
token: Bearer token from az CLI
mashup: Full M section document string
query_name: Name of the shared query to execute
Returns:
pandas DataFrame with results, or None on error
"""
url = (
f"https://api.fabric.microsoft.com/v1/workspaces/{ws_id}"
f"/dataflows/{df_id}/executeQuery"
)
body = json.dumps({
"queryName": query_name,
"customMashupDocument": mashup
}).encode()
req = urllib.request.Request(url, data=body, method="POST", headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
})
try:
resp = urllib.request.urlopen(req, timeout=95)
except urllib.error.HTTPError as e:
error_body = e.read().decode()[:500]
print(f"HTTP {e.code}: {error_body}", file=sys.stderr)
return None
content_type = resp.headers.get("Content-Type", "")
if "arrow" not in content_type:
print(f"Unexpected response type: {content_type}", file=sys.stderr)
return None
table = ipc.open_stream(io.BytesIO(resp.read())).read_all()
df = table.to_pandas()
# Check for mashup engine errors in metadata column
if "PQ Arrow Metadata" in df.columns:
meta = df["PQ Arrow Metadata"].dropna()
if len(meta) > 0 and len(df.columns) == 1:
error = json.loads(meta.iloc[0])
print(f"M engine error: {error.get('Error', error)}", file=sys.stderr)
return None
df = df.drop(columns=["PQ Arrow Metadata"])
return df
# endregion
# region Main
def main():
parser = argparse.ArgumentParser(description="Execute Power Query M via Fabric API")
parser.add_argument("-w", "--workspace", required=True, help="Workspace GUID")
parser.add_argument("-d", "--dataflow", required=True, help="Runner dataflow GUID")
parser.add_argument("-m", "--mashup", help="M section document string")
parser.add_argument("--stdin", action="store_true", help="Read mashup from stdin")
parser.add_argument("-q", "--query-name", default="Result", help="Query name (default: Result)")
parser.add_argument("-o", "--output", help="Output file path (.csv or .parquet)")
parser.add_argument("-n", "--head", type=int, help="Print only first N rows")
args = parser.parse_args()
if args.stdin:
mashup = sys.stdin.read()
elif args.mashup:
mashup = args.mashup
else:
parser.error("Provide --mashup or --stdin")
token = get_token()
df = execute_m(args.workspace, args.dataflow, token, mashup, args.query_name)
if df is None:
sys.exit(1)
if args.output:
if args.output.endswith(".parquet"):
df.to_parquet(args.output, index=False)
else:
df.to_csv(args.output, index=False)
print(f"Wrote {len(df)} rows to {args.output}", file=sys.stderr)
else:
display = df.head(args.head) if args.head else df
print(display.to_string(index=False))
print(f"\n({len(df)} rows, {len(df.columns)} columns)", file=sys.stderr)
if __name__ == "__main__":
main()
# endregion
"""Preview a semantic model partition's Power Query result at any step.
Extracts the partition M expression from a semantic model (via fab CLI),
inlines shared parameters, optionally truncates to a specific step,
and executes via the Fabric executeQuery API.
Requires:
- pyarrow (uv run --with pyarrow)
- az CLI authenticated (az login)
- fab CLI installed
- A runner dataflow with the data source connection bound
Usage:
# Preview final result (first 100 rows)
uv run --with pyarrow python3 preview_partition.py \
--workspace <ws-id> --dataflow <df-id> \
--model "MyWorkspace.Workspace/MyModel.SemanticModel" \
--table Orders --limit 100
# Preview a specific step
uv run --with pyarrow python3 preview_partition.py \
--workspace <ws-id> --dataflow <df-id> \
--model "MyWorkspace.Workspace/MyModel.SemanticModel" \
--table Orders --step "Select Columns"
# Output to CSV
uv run --with pyarrow python3 preview_partition.py \
--workspace <ws-id> --dataflow <df-id> \
--model "MyWorkspace.Workspace/MyModel.SemanticModel" \
--table Budget --output budget_preview.csv
"""
# region Imports
import argparse
import re
import subprocess
import sys
# endregion
# region Functions
def fab_get_payload(model_path, tmdl_path):
"""Get a TMDL payload from a semantic model definition via fab CLI.
Args:
model_path: Fabric path like "Workspace.Workspace/Model.SemanticModel"
tmdl_path: Definition part path like "definition/tables/Orders.tmdl"
Returns:
The TMDL content string, or None on error.
"""
result = subprocess.run(
["fab", "get", model_path, "-f",
"-q", f"definition.parts[?path=='{tmdl_path}'].payload"],
capture_output=True, text=True
)
if result.returncode != 0:
print(f"fab error: {result.stderr.strip()}", file=sys.stderr)
return None
# Skip the sensitivity label warning line
lines = result.stdout.strip().split("\n")
payload_lines = [l for l in lines if not l.startswith("!")]
return "\n".join(payload_lines)
def extract_partition_expression(tmdl_content):
"""Extract the M expression from a TMDL partition block.
Args:
tmdl_content: Full TMDL content of a table definition
Returns:
The M let...in expression string, or None if not found.
"""
# Find the partition source block
match = re.search(
r'partition\s+.+?=\s+m\b.*?source\s*=\s*\n(.*?)(?=\n\t\w|\n\w|\Z)',
tmdl_content,
re.DOTALL
)
if not match:
print("Could not find partition expression in TMDL", file=sys.stderr)
return None
# Clean up indentation (TMDL uses tabs)
raw = match.group(1)
lines = raw.split("\n")
cleaned = []
for line in lines:
stripped = line.lstrip("\t")
if stripped and not stripped.startswith("annotation"):
cleaned.append(stripped)
return "\n".join(cleaned).strip()
def extract_parameters(expressions_tmdl):
"""Extract shared M parameters from expressions.tmdl.
Args:
expressions_tmdl: Content of definition/expressions.tmdl
Returns:
Dict of parameter name -> value string.
"""
params = {}
for match in re.finditer(
r'expression\s+(\w+)\s*=\s*"([^"]*)"',
expressions_tmdl
):
params[match.group(1)] = match.group(2)
# Also match datetime parameters
for match in re.finditer(
r'expression\s+(\w+)\s*=\s*(#datetime\([^)]+\))',
expressions_tmdl
):
params[match.group(1)] = match.group(2)
return params
def build_mashup(expression, parameters, step=None, limit=None):
"""Build a section document from a partition expression and parameters.
Args:
expression: The M let...in expression
parameters: Dict of parameter name -> value
step: Optional step name to truncate to
limit: Optional row limit (wraps final step in Table.FirstN)
Returns:
Complete M section document string.
"""
# Build shared parameter declarations
shared_params = []
for name, value in parameters.items():
if value.startswith("#datetime"):
shared_params.append(f'shared {name} = {value};')
else:
shared_params.append(f'shared {name} = "{value}";')
# Truncate to step if specified
if step:
# Find the step in the let block and change the in clause
quoted_step = f'#"{step}"' if " " in step else step
if quoted_step in expression or step in expression:
# Replace the in clause
expression = re.sub(
r'\bin\s+.*$',
f'in {quoted_step}',
expression,
flags=re.DOTALL
)
# Replace #"ParamName" references with unquoted ParamName
# (shared declarations use unquoted identifiers)
for name in parameters:
expression = expression.replace(f'#"{name}"', name)
# Add row limit
if limit:
expression = re.sub(
r'\bin\s+(.+)$',
rf'in Table.FirstN(\1, {limit})',
expression,
flags=re.DOTALL
)
params_block = "\n".join(shared_params)
return f"section Section1;\n{params_block}\nshared Result = {expression};"
# endregion
# region Main
def main():
parser = argparse.ArgumentParser(description="Preview semantic model partition data")
parser.add_argument("-w", "--workspace", required=True, help="Workspace GUID")
parser.add_argument("-d", "--dataflow", required=True, help="Runner dataflow GUID")
parser.add_argument("--model", required=True, help="Fabric path: Workspace.Workspace/Model.SemanticModel")
parser.add_argument("--table", required=True, help="Table name")
parser.add_argument("--step", help="Step name to preview (default: final)")
parser.add_argument("--limit", type=int, default=100, help="Row limit (default: 100)")
parser.add_argument("-o", "--output", help="Output file (.csv or .parquet)")
parser.add_argument("--show-mashup", action="store_true", help="Print the mashup document and exit")
args = parser.parse_args()
# Extract partition expression
table_tmdl = fab_get_payload(args.model, f"definition/tables/{args.table}.tmdl")
if not table_tmdl:
sys.exit(1)
expression = extract_partition_expression(table_tmdl)
if not expression:
sys.exit(1)
# Extract parameters
expr_tmdl = fab_get_payload(args.model, "definition/expressions.tmdl")
parameters = extract_parameters(expr_tmdl) if expr_tmdl else {}
# Build mashup
mashup = build_mashup(expression, parameters, step=args.step, limit=args.limit)
if args.show_mashup:
print(mashup)
return
# Import execute_m from sibling module
sys.path.insert(0, str(__import__("pathlib").Path(__file__).parent))
from execute_m import execute_m, get_token
token = get_token()
df = execute_m(args.workspace, args.dataflow, token, mashup)
if df is None:
sys.exit(1)
step_label = args.step or "final"
print(f"Step: {step_label}", file=sys.stderr)
print(f"Columns ({len(df.columns)}): {list(df.columns)}", file=sys.stderr)
if args.output:
if args.output.endswith(".parquet"):
df.to_parquet(args.output, index=False)
else:
df.to_csv(args.output, index=False)
print(f"Wrote {len(df)} rows to {args.output}", file=sys.stderr)
else:
print(df.to_string(index=False))
print(f"\n({len(df)} rows)", file=sys.stderr)
if __name__ == "__main__":
main()
# endregion
Power Query Best Practices for Semantic Models
Practical guidance for writing performant, maintainable M expressions in semantic model partitions.
Safe Pattern for Writing M
When writing or generating M expressions for import partitions, follow this order to maximize query folding:
let
Source = Sql.Database(SqlEndpoint, Database),
Data = Source{[Schema="dbo", Item="MyTable"]}[Data],
-- 1. Filter rows (folds to WHERE)
Filtered = Table.SelectRows(Data, each [IsActive] = true),
-- 2. Select columns (folds to SELECT)
Selected = Table.SelectColumns(Filtered, {"Id", "Date", "Amount"}),
-- 3. Set types (folds to CAST)
Typed = Table.TransformColumnTypes(Selected, {{"Amount", Currency.Type}}),
-- 4. Sort if needed (folds to ORDER BY)
Sorted = Table.Sort(Typed, {{"Date", Order.Descending}}),
-- 5. Non-foldable transforms LAST
Added = Table.AddColumn(Sorted, "Category", each if [Amount] > 1000 then "High" else "Low")
in
AddedIf the transform logic is too complex for M, use Value.NativeQuery to pass native SQL directly:
let
Source = Sql.Database(SqlEndpoint, Database),
Data = Value.NativeQuery(Source,
"SELECT Id, Date, Amount FROM dbo.MyTable WHERE IsActive = 1",
null, [EnableFolding=true])
in
DataEnableFolding=true allows subsequent M steps to fold on top of the native query result.
Query Folding
Query folding translates M steps into native data source queries (SQL, OData, etc.). When folding works, the data source does the heavy lifting. When it breaks, the mashup engine pulls all data into memory and processes it locally.
Why It Matters
- A folded query against a 10M row table sends
SELECT TOP 1000 ... WHERE ...to SQL Server; fast - A non-folded query pulls all 10M rows into the mashup engine, then filters locally; slow and memory-heavy
- For large tables, broken folding often causes refresh timeouts or out-of-memory errors
Steps That Fold (SQL Sources)
| M Function | SQL Equivalent |
|---|---|
Table.SelectColumns | SELECT col1, col2 |
Table.RemoveColumns | SELECT (excluding columns) |
Table.SelectRows | WHERE |
Table.Sort | ORDER BY |
Table.FirstN | TOP N |
Table.Group | GROUP BY |
Table.TransformColumnTypes | CAST |
Table.RenameColumns | AS alias |
Table.ExpandTableColumn | JOIN |
Table.NestedJoin | JOIN |
Table.Distinct | DISTINCT |
Table.Skip | OFFSET |
Operations That Break Folding
Once folding breaks, all subsequent steps also run locally. This list applies primarily to SQL Server via Sql.Database; other sources may differ.
Table construction / materialization:
Table.Buffer-- forces full data load to memoryList.Buffer-- forces full list load to memoryTable.StopFolding-- explicitly stops folding#tableconstructor,Table.FromList,Table.FromRecords,Table.FromRows,Table.FromValue,Table.FromColumns-- creates table locally
Row position / index operations:
Table.AddIndexColumn-- no SQL row index equivalentTable.LastN/Table.RemoveLastN-- no SQL BOTTOM NTable.Range(mid-range),Table.Repeat,Table.AlternateRows-- no SQL equivalentTable.InsertRows,Table.RemoveRows(by position) -- positional, not predicate-basedTable.ReverseRows-- no SQL row-reverseTable.FindText-- full-text search not translatable
Text functions (inside `Table.TransformColumns` or `Table.AddColumn`):
Text.Proper/ "Capitalize Each Word"Text.Combine(multi-column merge),Text.Insert,Text.Remove,Text.RemoveRangeText.Select,Text.Split,Text.SplitAnyText.BeforeDelimiter,Text.AfterDelimiter,Text.BetweenDelimitersText.PadStart,Text.PadEnd,Text.Reverse,Text.FormatText.ToList,Text.CleanText.Fromwith format/culture arguments
Column splitting / combining:
Table.SplitColumn,Table.CombineColumns, allSplitter.*functions
Pivot / transpose / structure:
Table.Transpose,Table.DemoteHeaders,Table.PromoteHeaders
Fill / imputation:
Table.FillDown,Table.FillUp-- requires stateful row scanning
Error handling:
Table.RemoveRowsWithErrors,Table.SelectRowsWithErrorstry...otherwisein row context
Schema / metadata:
Table.Schema,Table.ColumnNames,Value.Type,Type.Is
Custom functions / iteration:
- User-defined
(x) => ...lambdas in row context Table.TransformRows-- arbitrary M function per rowList.Generate,List.Accumulate-- iterative; no SQL equivalentList.Transformwith complex logic
Record / list / structured columns:
Table.ExpandListColumn,Table.ExpandRecordColumn(except after same-source NestedJoin)Record.*functions,Table.ToRecords,Table.ToRows,Table.ToList,Table.Column
Date/time in row context:
Date.ToText/DateTime.ToText/Duration.ToTextwith format stringsDate.IsInCurrentMonth,Date.IsInCurrentWeekand similar relative date filtersDate.DayOfWeekName,Date.MonthName-- locale-dependent
Miscellaneous:
Table.Profile-- statistical summary; local onlyTable.Max,Table.Min(returning row) -- returns record not tableTable.Contains,Table.ContainsAll,Table.ContainsAny,Table.IsDistinct-- returns boolean
Operations That Sometimes Fold
These fold under certain conditions:
Table.AddColumn-- folds if expression uses only SQL-translatable functions (arithmetic,Text.Upper); breaks with complex M logicTable.TransformColumns-- folds forText.Upper,Text.Lower,Text.Trim,Number.Round; breaks forText.Proper, complex lambdasTable.TransformColumnTypes-- folds for compatible casts (int to decimal); breaks for locale-specific or M-only typesTable.ReplaceValue-- folds with simple literal replacement; breaks with patternsTable.Pivot/Table.Unpivot-- folds on SQL Server (PIVOT/UNPIVOT support); breaks on other sourcesTable.NestedJoin-- folds when both sources are the same SQL connection; breaks across different sourcesTable.Combine/ append -- folds as UNION ALL when all inputs are same SQL sourceTable.SelectRowswithText.Contains-- folds asLIKE '%value%'on SQL ServerTable.Group-- folds with standard aggregations (List.Sum,List.Count,List.Average); breaks with custom functionsValue.NativeQuery-- subsequent steps fold only ifEnableFolding=trueis setText.Start/Text.End-- often fold asLEFT()/RIGHT();Text.Middleoften does notDate.Year,Date.Month,Date.Day-- fold asYEAR(),MONTH(),DAY()Date.AddDays/Date.AddMonths-- fold asDATEADD()
Environmental Fold-Breakers
Not functions, but conditions that prevent folding:
- Merging/appending queries from different data sources
- Incompatible data privacy levels between sources (Data Privacy Firewall intervenes)
- Source is a flat file (CSV, Excel, JSON, XML) -- no query engine
- Source is
Web.Contents/ API -- no SQL engine - Custom SQL without
EnableFolding=true - Any step after a fold-breaking step (chain is broken; cannot re-fold)
Folding Strategy
Rule: Do all foldable work first, then do non-foldable work.
let
Source = Sql.Database(SqlEndpoint, Database),
Data = Source{[Schema="dbo", Item="Orders"]}[Data],
-- FOLDABLE: These translate to SQL
#"Filtered Rows" = Table.SelectRows(Data, each [Year] >= 2023),
#"Selected Columns" = Table.SelectColumns(#"Filtered Rows",
{"OrderId", "Date", "Amount", "CustomerId", "Status"}),
#"Set Types" = Table.TransformColumnTypes(#"Selected Columns", {
{"Amount", Currency.Type}, {"Date", type date}}),
-- NON-FOLDABLE: These run in the mashup engine
#"Added Category" = Table.AddColumn(#"Set Types", "AmountBucket",
each if [Amount] > 10000 then "Large" else "Small", type text)
in
#"Added Category"Verifying Folding
In Power Query Online or Desktop, right-click a step and check "View Native Query". If greyed out, the step doesn't fold.
Programmatically: execute the expression via the executeQuery API. If a query on a large table completes well within the timeout, folding is likely working. If it times out or is slow, folding may be broken.
Column Pruning
Remove columns as early as possible. Every column not removed travels through every subsequent step.
-- Good: remove columns immediately after navigation
Data = Source{[Schema="dbo", Item="Orders"]}[Data],
#"Selected" = Table.SelectColumns(Data, {"OrderId", "Date", "Amount"}),
...
-- Bad: remove columns at the end after all transforms
...
#"Final" = Table.RemoveColumns(#"Transformed", {"Col1", "Col2", "Col3", ...})Early column pruning folds to SQL SELECT, reducing data transfer from the source.
Row Filtering
Filter rows early for the same reason. A Table.SelectRows immediately after navigation folds to WHERE:
Data = Source{[Schema="dbo", Item="Orders"]}[Data],
#"Filtered" = Table.SelectRows(Data, each [IsActive] = true and [Year] >= 2023),This is especially important for incremental refresh, where RangeStart/RangeEnd filters must fold to be effective.
Type Handling
Apply Types Early
Table.TransformColumnTypes folds to CAST in SQL. Apply it right after column selection:
#"Selected" = Table.SelectColumns(Data, {"OrderId", "Date", "Amount"}),
#"Typed" = Table.TransformColumnTypes(#"Selected", {
{"OrderId", Int64.Type},
{"Date", type date},
{"Amount", Currency.Type}
}),Avoid Implicit Type Detection
Never use Table.TransformColumnTypes with Replacer.ReplaceValue or locale-dependent conversions on large datasets. These don't fold and can introduce unexpected nulls.
Common Type Mappings
| M Type | Use for |
|---|---|
Int64.Type | Integer keys, counts |
type text | Strings |
type date | Date-only columns |
type datetime | DateTime columns |
type datetimezone | DateTime with timezone |
Currency.Type | Financial amounts (fixed decimal) |
type logical | Boolean flags |
Percentage.Type | Rates, percentages |
Anti-Patterns
Pulling Entire Tables Then Filtering
-- Anti-pattern: filter after all transforms
Data = Source{[Schema="dbo", Item="BigTable"]}[Data],
#"Added Column" = Table.AddColumn(Data, ...), -- breaks folding
#"Filtered" = Table.SelectRows(#"Added Column", each [Year] >= 2023)
-- Filter runs locally on ALL rowsUsing Table.Buffer Unnecessarily
Table.Buffer forces the entire table into memory. Only use when the same table is referenced multiple times and re-evaluation would be expensive.
Referencing Other Queries
Cross-query references (accessing a column from a different query) break folding and can cause cascading performance issues.
Excessive Step Count
Each step adds overhead. Combine related operations where natural; don't create a separate step for each individual column rename when Table.RenameColumns handles multiples:
-- Good: one step for all renames
#"Renamed" = Table.RenameColumns(Data, {
{"OldName1", "NewName1"},
{"OldName2", "NewName2"}
})
-- Bad: separate step per rename
#"Renamed1" = Table.RenameColumns(Data, {{"OldName1", "NewName1"}}),
#"Renamed2" = Table.RenameColumns(#"Renamed1", {{"OldName2", "NewName2"}})Naming Conventions
- Use descriptive step names:
#"Filtered Active Orders"not#"Custom1" - Use
#"Quoted Identifiers"for steps with spaces (standard Power Query convention) - Parameters:
PascalCasewithout spaces (SqlEndpoint,DatabaseName) - Keep step names consistent with what the Power Query UI would generate
Error Handling
For production partitions, avoid try...otherwise patterns that silently swallow errors. A failed refresh is better than silently loading wrong data.
If error handling is necessary (e.g., optional columns), make it explicit and narrow:
#"Safe Amount" = Table.TransformColumns(Data, {
{"Amount", each try Number.FromText(_) otherwise null, type number}
})Validating Power Query Expressions
Two complementary approaches: execute against real data (comprehensive validation) or save to the model (quick syntax check).
Approach 1: Execute via Power Query API
Full validation that runs the expression and returns actual data. Catches syntax errors, missing columns, data source issues, and type problems.
Prerequisites
- A runner dataflow in the workspace with the data source connection bound
- See the Power Query API section in SKILL.md for creating the runner dataflow and executing expressions
Step 1: Extract the Expression and Parameters
# Get partition expression from TMDL
fab get "<Workspace>.Workspace/<Model>.SemanticModel" -f \
-q "definition.parts[?path=='definition/tables/<Table>.tmdl'].payload"
# Get shared M parameters
fab get "<Workspace>.Workspace/<Model>.SemanticModel" -f \
-q "definition.parts[?path=='definition/expressions.tmdl'].payload"The partition expression is in the partition block of the TMDL. Shared parameters are expression declarations in expressions.tmdl.
Step 2: Build the Mashup Document
Wrap the expression in a section document, inlining parameter values as shared declarations:
section Section1;
shared SqlEndpoint = "myserver.database.windows.net";
shared Database = "MyDatabase";
shared Result = let
Source = Sql.Database(SqlEndpoint, Database),
Data = Source{[Schema="dbo",Item="Orders"]}[Data],
#"Select Columns" = Table.SelectColumns(Data, {"OrderId", "Amount"}),
Limited = Table.FirstN(#"Select Columns", 100)
in Limited;Key points:
- Replace
#"SqlEndpoint"references withSqlEndpoint(the shared declaration) - The
shared Result = ...name must match thequeryNamein the API call - Add
Table.FirstNto limit rows for large tables - For incremental refresh, inline
RangeStartandRangeEndwith concrete date values
Step 3: Execute
TOKEN=$(az account get-access-token \
--resource https://api.fabric.microsoft.com --query accessToken -o tsv)
curl -s -o /tmp/pq_result.bin -X POST \
"https://api.fabric.microsoft.com/v1/workspaces/${WS_ID}/dataflows/${DF_ID}/executeQuery" \
-H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" \
-d "$(jq -n --arg m "$MASHUP" '{queryName:"Result",customMashupDocument:$m}')"Step 4: Read and Validate Results
uv run --with pyarrow python3 -c "
import pyarrow.ipc as ipc, io, json
with open('/tmp/pq_result.bin', 'rb') as f:
table = ipc.open_stream(io.BytesIO(f.read())).read_all()
df = table.to_pandas()
if 'PQ Arrow Metadata' in df.columns:
meta = df['PQ Arrow Metadata'].dropna()
if len(meta) > 0 and len(df.columns) == 1:
error = json.loads(meta.iloc[0])
print('ERROR:', error.get('Error', error))
else:
cols = [c for c in df.columns if c != 'PQ Arrow Metadata']
print(f'Columns: {cols}')
print(df[cols].head(10).to_string(index=False))
print(f'({len(df)} rows, {len(cols)} columns)')
print(f'Types: {dict(df[cols].dtypes)}')
else:
print(f'Columns: {list(df.columns)}')
print(df.head(10).to_string(index=False))
print(f'({len(df)} rows)')
"Common Errors
| Error message | Cause | Fix |
|---|---|---|
Credentials are required to connect to the SQL source | Connection not bound to the runner dataflow | Bind the connection via updateDefinition |
Query name not found | queryName doesn't match shared name in mashup | Ensure both are Result |
Expression.Error: The column '...' was not found | Column name mismatch | Check source table schema |
DataSource.Error: ... could not be reached | Server unreachable or wrong endpoint | Verify connection details |
| Timeout (90 seconds) | Query too expensive | Add Table.FirstN to limit rows |
Approach 2: Save to Model via XMLA/TOM
Analysis Services validates M syntax when a partition expression is saved. This is faster than executing but only catches structural errors; it won't detect wrong column names or data source issues.
Using TMDL editing or Tabular Editor
Edit the partition expression in the TMDL file directly, or use Tabular Editor to modify and deploy:
# Edit the partition expression in the TMDL file
# Open: <Model>.SemanticModel/definition/tables/Orders.tmdl
# Modify the partition expression under the "partition" block, then deploy:
fab import "<Workspace>.Workspace/<Model>.SemanticModel" -i ./<Model>.SemanticModel -fIf the expression has syntax errors, AS returns an error like:
Token Eof expected.
Expression.SyntaxError: Token Literal expected.Using TMDL Files
Edit the partition source = block in the .tmdl file and deploy. The deployment process validates the expression.
What XMLA Validation Catches
- Missing or mismatched
let/inblocks - Undefined step references (e.g., referencing
#"Step3"that doesn't exist) - Invalid M function names
- Syntax errors (missing commas, unbalanced brackets)
- Invalid type names in
TransformColumnTypes
What XMLA Validation Misses
- Wrong column names (the expression is syntactically valid but the column doesn't exist at the source)
- Data source connectivity issues
- Runtime errors (division by zero, type conversion failures on actual data)
- Performance issues (broken query folding)
Step-by-Step Debugging
When an expression fails or produces unexpected results, preview intermediate steps by changing the in clause:
section Section1;
shared SqlEndpoint = "myserver.database.windows.net";
shared Database = "MyDB";
shared Result = let
Source = Sql.Database(SqlEndpoint, Database),
Data = Source{[Schema="dbo",Item="Orders"]}[Data],
#"Filtered" = Table.SelectRows(Data, each [Status] <> "Cancelled"),
#"Selected" = Table.SelectColumns(#"Filtered", {"OrderId", "Amount"})
in Data; -- Change this to inspect different stepsin target | What it shows |
|---|---|
in Source | Table listing from the database |
in Data | All columns from the source table |
in #"Filtered" | After row filtering |
in #"Selected" | After column selection (final) |
For each step, check:
- Column names and count (did a rename/select work?)
- Row count (did a filter apply correctly?)
- Data types (
df.dtypesin Python) - Null counts (
df.isnull().sum()) - Sample values (do they look right?)
Validation Checklist
Before deploying a new or modified partition expression:
1. Syntax: Save to model (XMLA) to catch structural errors 2. Data: Execute via API with Table.FirstN(_, 100) to verify correct columns and values 3. Types: Check df.dtypes matches expected semantic model column types 4. Nulls: Check df.isnull().sum() for unexpected nulls from type casting 5. Row count: Execute without Table.FirstN (or with a large limit) to verify filter logic 6. Folding: For large tables, verify the query completes within 90 seconds (indicates folding is working)