/semantic-models:power-queryfrom semantic-models
Helps author, validate, and test Power Query M expressions for semantic model partitions. Covers writing correct M code, preserving query folding, validating expressions, and testing against data sources.
Ships in semantic-models. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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.
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.
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:
SqlEndpoint, Database are shared M parameters defined at the model levelsource{[Schema = "dbo", Item = "Orders"]}[Data] navigates to a specific tablelet...in chain, named in snake_case (see Naming below)# 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"
Name every step, let variable, custom function and function argument in lowercase snake_case:
letters, digits and underscores, starting with a letter (added_column, filtered_active,
fn_clean_text). A snake_case name is a plain identifier, so every reference to it is bare. A name
with a space has to be written #"Added Column" at its definition and at every reference.
removed_duplicates), not the position (custom1, step1).type, error, each, in, let, if, try, meta,
null, section and shared still need #"...", so write typed or errors_removed.SqlEndpoint, DatabaseName). RangeStart and
RangeEnd keep that exact spelling: incremental refresh looks them up by name.Existing M. Whenever you read or edit an expression that names a step, variable or function
with a space (#"Added Custom", #"fn Clean Text"), rename it to snake_case (added_custom,
fn_clean_text) in the same edit:
in clause. M is case-sensitive, and one missed reference fails the whole query with
The name 'x' wasn't recognized.expressions.tmdl, also rename its declaration
(expression 'fn Clean Text' becomes expression fn_clean_text) and every caller: search the
whole definition/ folder for the old #"..." form.These names are owned outside the expression and keep their spaces:
"Order Date") and field access ([Order Date],
[#"Week & Year"]) name model columns; renaming them changes the model.#"Dim Customer". That is
the model table's name: rename it only through a model rename (pbip:pbip), when asked.M is laid out by microsoft/powerquery-formatter,
the formatter behind the VS Code Power Query extension, run through formatter/format_m.js with
the house layout: 4-space indent, 60-character lines, short lines over packed ones. Run it over
every M expression you write or edit:
# First use on a machine: install it (node_modules is gitignored)
( cd "${CLAUDE_PLUGIN_ROOT}/skills/power-query/formatter" && npm install )
FMT="${CLAUDE_PLUGIN_ROOT}/skills/power-query/formatter/format_m.js"
node "$FMT" "<Model>.SemanticModel/definition/tables/Orders.tmdl" # in place
node "$FMT" --check "<Model>.SemanticModel/definition" # list unformatted M, write nothing
echo 'let a=1 in a' | node "$FMT" - # a snippet, to stdout
.tmdl file it formats shared expression blocks, M partition source blocks and
refresh-policy expressions. DAX, one-line parameters and text literals that span lines stay as
they are, and a block fenced in ``` keeps its fences.package.json pins its version. Rerun the samples before raising it.The layout, so M written by hand already matches:
let puts one binding per line and in on its own line, however short, and so does
anything that holds a let (a function, an each, a call around it).= in records: [Schema = "dbo", Item = "Orders"].each body moves under each. A step whose value is a long if starts it on the next
line, with if ... then, else if ... then and else each on a line of their own and each
value indented under it. A long &, and or or chain puts one operand per line, operator
first.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 -> AS aliasesSteps that may or may not fold (source-dependent):
Table.TransformColumnTypes -- frequently breaks folding for text-to-numeric/date conversions on SQL Server sources. Use Table.TransformColumns with explicit conversion functions (e.g., Number.From) as a more reliable foldable alternative.Steps that break folding:
Table.AddColumn with custom M functions (not translatable to SQL)Table.Buffer (forces materialization; prefer Table.StopFolding to stop folding without the memory overhead)Table.LastN (no SQL equivalent without subquery)Table.Combine across different data sources (cross-database folding within the same SQL Server is possible via EnableCrossDatabaseFolding)each expressions with M-specific logicBest practice: Apply folding-compatible steps (filter, select, type) early; add custom columns and M-only transforms after all foldable work is done.
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'
Table.TransformColumnTypes early (folds to CAST in SQL)Int64.Type, type text, type date, Currency.Type, type logicalTwo approaches to validate that an M expression is syntactically correct and produces expected results:
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:
POST /v1/workspaces/{wsId}/dataflows/{dfId}/executeQueryMASHUP='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.
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:
let/inTransformColumnTypes# 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).
| 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 |
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.
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.
let
source = Lakehouse.Contents(null),
lakehouse = source{[Id = "lakehouse-guid"]}[Data],
data = lakehouse{
[Id = "table-name", ItemKind = "Table"]
}[Data]
in
data
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
data
Value.NativeQuery with EnableFolding=true allows subsequent M steps to fold on top of the native query.
references/validation.md -- Detailed validation workflow with executeQuery API, step preview, error handlingreferences/best-practices.md -- Query folding guidance, fold-breaker list, anti-patterns, performance tipsexamples/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)formatter/format_m.js -- formats M in .tmdl, .pq and .m files, or stdin, in the house layout (see Formatting)examples/execute_m.py (opens in a new tab)examples/preview_partition.py (opens in a new tab)formatter/format_m.js (opens in a new tab)formatter/package-lock.json (opens in a new tab)formatter/package.json (opens in a new tab)references/best-practices.md (opens in a new tab)references/validation.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
power-query, m-language, semantic-model, partition-expressions
9 skills in this plugin
/date-tableDrop a complete date dimension into a PBIP semantic model, an extended DimDate (58 columns of calendar, ISO week, fiscal and to-date flags) from a bundled Power Query function, plus the "Dates Selected" title measure. Invoke when the user asks to "add a date table", "add a calendar table", "create DimDate", "mark as date table", "add a fiscal calendar" or wants a title showing the selected period./dax-optimisationDAX performance optimization for semantic models. Automatically invoke when the user asks to "optimize DAX", "fix slow DAX", "DAX performance", "tune a measure", "debug a measure", "DAX anti-patterns", or mentions slow queries, server timings, or a visual that is slower than its DAX query./npx claudepluginhub insightfulanalytics/pbi_agentic_dev --plugin semantic-modelsOther plugins' skills for the same job