diff --git a/localizedContent/es/content/features/code-actions.md b/localizedContent/es/content/features/code-actions.md index e97fef7bd..26081c5d5 100644 --- a/localizedContent/es/content/features/code-actions.md +++ b/localizedContent/es/content/features/code-actions.md @@ -122,7 +122,7 @@ Las acciones de código siguientes aparecerán con puntos verde azulado debajo d | DR011 | [Reescribir con ISBLANK](xref:DR011) | En lugar de comparar una expresión con [`BLANK()`](https://dax.guide/BLANK), usa la función [`ISBLANK`](https://dax.guide/ISBLANK). Ejemplo:
`IF([Sales] = BLANK(), [Budget], [Sales])` -> `IF(ISBLANK([Sales], [Budget], [Sales])` | | DR012 | [Eliminar BLANK innecesario](xref:DR012) | Algunas funciones de DAX, como [`IF`](https://dax.guide/IF) y [`SWITCH`](https://dax.guide/SWITCH), ya devuelven `BLANK()` cuando la condición es falsa, así que no hace falta especificar `BLANK()` explícitamente. Ejemplo:
`IF(a > b, a, BLANK())` -> `IF(a > b, a)` | | DR013 | [Simplificar la lógica negada](xref:DR013) | Cuando se niega una expresión lógica, suele ser más legible reescribirla usando el operador negado. Ejemplo:
`NOT(a = b)` -> `a <> b` | -| DR014 | [Simplificar con IN](xref:DR014) | Reescriba los predicados compuestos (comparaciones de igualdad de una misma expresión combinadas con [`OR`](https://dax.guide/OR) o [`\|\|`](https://dax.guide/op/or/)) con el operador [`IN`](https://dax.guide/IN). Ejemplo:
\`a = 1 \\ | +| DR014 | [Simplificar con IN](xref:DR014) | Reescriba los predicados compuestos (comparaciones de igualdad de una misma expresión combinadas con [`OR`](https://dax.guide/OR) o [`\|\|`](https://dax.guide/op/or/)) con el operador [`IN`](https://dax.guide/IN). Ejemplo:
`a = 1 \|\| a = 2 \|\| a = 100` -> `a IN { 1, 2, 100 }` | ### Reescrituras diff --git a/localizedContent/es/content/features/te-cli/includes/te-cli-preview-notice.md b/localizedContent/es/content/features/te-cli/includes/te-cli-preview-notice.md new file mode 100644 index 000000000..791c29254 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/includes/te-cli-preview-notice.md @@ -0,0 +1,2 @@ +> [!IMPORTANT] +> The Tabular Editor CLI is in **Limited Public Preview**. It is offered for evaluation with a Tabular Editor account; no license is required during preview. Commands, flags, and outputs may change before general availability. **The preview build stops functioning after 2026-09-30.** We recommend against using the CLI in production CI/CD pipelines during preview. Please refer to our license agreement. diff --git a/localizedContent/es/content/features/te-cli/te-cli-auth.md b/localizedContent/es/content/features/te-cli/te-cli-auth.md new file mode 100644 index 000000000..054f1fdb9 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-auth.md @@ -0,0 +1,226 @@ +--- +uid: te-cli-auth +title: Authentication and Connections +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Authentication and Connections + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI authenticates to Power BI Service, Microsoft Fabric, and Azure Analysis Services using the same Power BI Desktop client ID that Tabular Editor 3 uses. Tokens are cached locally so you authenticate once and re-run commands silently until the refresh token expires (typically 90 days). + +## Authentication methods + +The CLI supports the full Azure Identity credential chain: + +| Method | When to use | `--auth` value | +| ---------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------- | +| Interactive browser | Local development - opens the system browser | `interactive` (default) | +| Service principal (client secret) | Automation, CI/CD, headless / SSH / WSL | `spn` (with `-u / -p / -t`) or `env` | +| Service principal (certificate) | Automation with certificate-based auth | `spn` (with `-u / -t / --certificate`) | +| Environment variables | `AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET` / `AZURE_TENANT_ID` | `env` | +| Managed identity | Azure VMs, Azure Container Apps, Azure Functions | `managed-identity` | + +> [!NOTE] +> `--auth` is a **global** option, available on every `te` command - not just `te auth login`. Pass it to [`te deploy`](xref:te-cli-commands#deploy), [`te refresh`](xref:te-cli-commands#refresh), [`te query`](xref:te-cli-commands#query), [`te connect`](xref:te-cli-commands#connect), or any other command that connects to a remote endpoint, to override the default chain for that invocation. The default (`auto`) tries environment credentials first, then falls back to the cached or interactive browser login. + +For headless, SSH, WSL, or devcontainer scenarios, use a service principal - `te auth login -u -p -t ` (or `--certificate`). The login is cached, so subsequent commands acquire tokens silently with `--auth auto`. + +## `te auth login` + +Authenticate and cache the result for subsequent commands: + +```bash +# Browser-based interactive login (default) +te auth login + +# Service principal with client secret +te auth login -u "$AZURE_CLIENT_ID" -p "$AZURE_CLIENT_SECRET" -t "$AZURE_TENANT_ID" + +# Service principal - read secret from stdin +echo "$AZURE_CLIENT_SECRET" | te auth login -u "$AZURE_CLIENT_ID" -p - -t "$AZURE_TENANT_ID" + +# Service principal with certificate +te auth login -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --certificate ./sp.pfx --certificate-password "$CERT_PASSWORD" + +# Managed identity (Azure-hosted) +te auth login --identity +``` + +After a successful service-principal login the CLI **caches the credentials** so every subsequent `te` command can acquire tokens silently - no need to re-pass `-u / -p / -t` or set the `AZURE_CLIENT_*` environment variables. Pass `--save=false` for a one-shot login that doesn't update the cache, or run `te auth logout` to clear it. + +> [!WARNING] +> Passing secrets directly on the command line exposes them to process listings and shell history. Prefer the `AZURE_CLIENT_SECRET` environment variable, or pipe the secret via stdin with `-p -`. + +## `te auth status` + +Display the current authentication state without opening a browser: + +```bash +te auth status +te auth status --output-format json +``` + +This returns an exit code of `0` when a valid session exists, `1` when not logged in or expired. + +## `te auth logout` + +Clear all cached credentials: + +```bash +te auth logout +``` + +## Credential storage + +The CLI stores access/refresh tokens and service-principal records in the **OS-native secure store** by default. A `0600` file fallback is selected automatically only when the OS keystore is unavailable (e.g., headless Linux without libsecret/D-Bus). + +| Platform | Backend | Storage location | +| --------------------------------- | --------------------------------------------- | -------------------------------------------------------------- | +| Windows | DPAPI | Per-user, managed by MSAL | +| Linux | libsecret (system keyring) | Per-user, managed by MSAL | +| macOS | Keychain | Service `com.tabulareditor.cli.*`, account `te-msal-cache.bin` | +| Any (fallback) | `0600` file | `~/.te-cli/te-msal-cache.bin` and per-key `.bin` blobs | + +Interactive browser and service-principal flows share the same cache; MSAL's account model distinguishes them - there are no separate `auth-record*.json` sidecar files. Run any command with `--debug` to see which backend was selected at startup. + +`te auth logout` clears every cached record (both the MSAL token cache and any SPN blobs) regardless of which backend is in use. + +## `te connect` - set the active connection + +`te connect` persists an active connection for the current terminal session. Subsequent commands that take `-s` / `-d` can omit them: + +```bash +# Remote workspace +te connect my-workspace my-model + +# Local TMDL folder, .bim file, or .SemanticModel container +te connect ./my-model + +# Connect to a running Power BI Desktop instance (Windows only) +te connect --local + +# Show the active connection +te connect + +# Clear the active connection (and any workspace mirror) +te connect --clear +``` + +Active-connection state is per-terminal-session: opening a new terminal starts fresh. + +### Workspace mode (`-w` / `--workspace`) + +`te connect -w ` pairs a primary source with a secondary mirror so every subsequent `--save` writes to both. Use it to keep a local working copy of a remote model in sync, or to push local edits to a workspace as you save: + +```bash +# Mirror remote workspace ↔ local TMDL folder +te connect Finance "Revenue Model" -w ./revenue-model + +# Mirror local source ↔ remote workspace (initial deploy + auto-redeploy on save) +te connect ./revenue-model -w Finance "Revenue Model" +``` + +Save order is always **local first, then remote**, so the on-disk copy reflects the latest user change even if the server push fails. See @te-cli-commands#workspace-mode-w--workspace for `--workspace-format`, overwrite semantics, and clearing the mirror. + +## Connecting to different clouds + +The CLI detects the correct scope from the server URL for: + +- Power BI Service and Fabric (commercial, US Gov, China, Germany clouds) +- Azure Analysis Services (`asazure://...`) +- Local SSAS (`localhost`, named instances - Windows only) + +Pass an XMLA endpoint, workspace name, or `powerbi://` URL as `--server`: + +```bash +te connect "powerbi://api.powerbi.com/v1.0/myorg/Finance" "Revenue Model" +te connect "powerbi://api.powerbi.com/v1.0/SpaceParts/Finance" "Revenue Model" +te connect "asazure://westeurope.asazure.windows.net/myaas" "MyModel" +te connect localhost "AdventureWorks" +``` + +## Connection profiles + +For repeated use of the same connection - especially when you deploy to multiple environments - save named profiles: + +```bash +# Save remote and local profiles +te profile set prod -s my-workspace -d my-model --description "Production" +te profile set dev --model ./model --description "Local dev TMDL" + +# List and inspect +te profile list +te profile show prod + +# Use a profile as the active connection +te connect --profile prod + +# One-shot use without changing the active connection +te deploy ./model --profile staging --force +``` + +Profiles can also carry behavioral overrides that take effect whenever the profile is active: + +```bash +# In dev, disable the BPA gate on deploy and loosen validation +te profile set dev --bpa-on-deploy false --validate-on-mutation false + +# In prod, force auto-format before any mutation +te profile set prod --auto-format true +``` + +See @te-cli-config for the full list of overridable behaviors. + +## Non-interactive authentication + +For CI/CD pipelines, agents, or any unattended context, avoid interactive flows by combining: + +- The `--non-interactive` global flag (fails fast instead of prompting). +- One of the non-interactive auth methods: `env`, `managed-identity`, or explicit service principal credentials. + +Environment-based example for a pipeline: + +```bash +export AZURE_CLIENT_ID="your-app-id" +export AZURE_CLIENT_SECRET="your-client-secret" +export AZURE_TENANT_ID="your-tenant-id" + +te deploy ./model -s my-workspace -d my-model \ + --auth env \ + --non-interactive \ + --force \ + --ci github +``` + +See @te-cli-cicd for complete GitHub Actions and Azure DevOps Pipelines examples. + +## Authentication environment variables + +The CLI honors the standard Azure.Identity environment variables when you use `--auth env` (and as part of the `auto` chain): + +| Variable | Purpose | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `AZURE_CLIENT_ID` | Service principal application ID. | +| `AZURE_CLIENT_SECRET` | Service principal client secret. Used together with `AZURE_CLIENT_ID` and `AZURE_TENANT_ID`. | +| `AZURE_TENANT_ID` | Service principal tenant (directory) ID. | +| `AZURE_CLIENT_CERTIFICATE_PATH` | Path to a PEM or PKCS12 certificate file for certificate-based service principal auth. Used together with `AZURE_CLIENT_ID` and `AZURE_TENANT_ID`. | +| `AZURE_AUTHORITY_HOST` | Override the authority host for sovereign clouds (e.g., `login.microsoftonline.us`, `login.partner.microsoftonline.cn`, `login.microsoftonline.de`). Defaults to the commercial cloud. | + +For CLI-specific environment variables (config paths, debug logging, TE2 compatibility), see @te-cli-config. + +## Next steps + +- @te-cli-commands - what you can do once connected. +- @te-cli-config - configuration and profile behavior. +- @te-cli-cicd - pipeline examples using service principals and managed identity. diff --git a/localizedContent/es/content/features/te-cli/te-cli-automation.md b/localizedContent/es/content/features/te-cli/te-cli-automation.md new file mode 100644 index 000000000..9ff078182 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-automation.md @@ -0,0 +1,193 @@ +--- +uid: te-cli-automation +title: Automation and Scripting +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Automation and Scripting + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI is composable; every command supports structured output, disables interactive prompts on demand, and returns predictable exit codes. The same primitives work equally well for shell pipelines, Python scripts, PowerShell automation, and agent-driven workflows. + +## Structured output + +Use `--output-format` to switch any command between text (human-readable) and machine-readable formats: + +| Format | Use for | Notes | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `text` (default) | Human-readable use | Plain text on stdout regardless of whether the stream is a TTY or piped. | +| `json` | Machine-readable use | Always valid JSON to stdout. Use `--error-format json` if you also want machine-readable errors on stderr. | +| `csv` | Tabular results (`query`, `bpa run`, `bpa rules`, `vertipaq`, `validate`, `test`, `refresh`, `profile list`, `session list`, `find`, `replace`, `get`, `ls`) | RFC 4180 escaping. | +| `tmsl` (alias `bim`) | Whole-object TMSL/BIM serialization | Accepted by `te get` and `te ls`. | +| `tmdl` | Whole-object TMDL serialization | Accepted by `te get` only (single object). | + +```bash +te ls --output-format json +te query -q "EVALUATE VALUES('Date'[Year])" --output-format csv +te bpa run --output-format json +``` + +> [!NOTE] +> `--output-format` and `--error-format` are independent. Setting `--output-format json` does _not_ switch stderr to JSON; pass `--error-format json` for that. There is no automatic format switching when stdout is redirected - the default is always `text` unless you ask otherwise. + +## Non-interactive mode + +Add `--non-interactive` to any command to disable confirmation prompts, credential picklists, and guided wizards. If the command needs input it cannot resolve from flags, environment, or config, it exits non-zero with an actionable error instead of hanging. + +```bash +te deploy ./model --non-interactive --force --ci github +``` + +## Exit codes + +Every `te` command exits with a predictable status code so callers can branch on success or failure without parsing stdout. + +| Exit | Meaning | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `0` | Success. | +| `1` | Generic failure - invalid arguments, command failed, validation errors, auth failure, BPA gate failed at severity ≥ error. | +| `2` | Used by `te diff` to indicate models differ (distinct from `0` identical and non-zero errors). | + +Combine exit codes with `--ci ` annotations and `--trx ` to surface rich failure information in CI - see @te-cli-cicd. + +## Errors on stderr + +Errors, warnings, and the preview banner are written to **stderr**; structured data is written to **stdout**. This means you can pipe JSON safely without it being contaminated by progress indicators or diagnostic messages: + +```bash +te ls --output-format json | jq '.[] | .name' +te vertipaq --output-format json > stats.json +``` + +## Python + +Python is a natural host for orchestrating CLI calls from data pipelines, notebooks, or test harnesses. Invoke `te` with `subprocess.run`, request JSON, and parse stdout: + +```python +import json +import subprocess + +def query(server: str, database: str, dax: str) -> list[dict]: + result = subprocess.run( + ["te", "query", + "-s", server, + "-d", database, + "-q", dax, + "--output-format", "json", + "--non-interactive"], + check=True, + capture_output=True, + text=True, + ) + return json.loads(result.stdout) + +rows = query("Finance", "Revenue Model", "EVALUATE TOPN(10, 'Sales')") +for row in rows: + print(row) +``` + +To capture structured errors from stderr: + +```python +import json +import subprocess + +result = subprocess.run( + ["te", "deploy", "./model", + "-s", "Finance", "-d", "Revenue", + "--output-format", "json", "--non-interactive", "--force"], + capture_output=True, text=True, +) + +if result.returncode != 0: + try: + err = json.loads(result.stderr.strip().splitlines()[-1]) + print("Deploy failed:", err.get("error"), "- hint:", err.get("hint")) + except json.JSONDecodeError: + print("Deploy failed:\n", result.stderr) +``` + +## PowerShell + +PowerShell handles JSON natively. `te` is a regular console binary that works directly in PowerShell pipelines (see @te-cli-migrate if you're porting from the older `TabularEditor.exe` CLI): + +```powershell +$rows = te query -s Finance -d Revenue -q "EVALUATE TOPN(10, 'Sales')" --output-format json --non-interactive + | ConvertFrom-Json + +$rows | Format-Table + +# Check exit code after the pipeline +if ($LASTEXITCODE -ne 0) { + Write-Error "Query failed with exit $LASTEXITCODE" + exit $LASTEXITCODE +} +``` + +Read secrets from the environment rather than passing them as plaintext: + +```powershell +$env:AZURE_CLIENT_ID = "your-app-id" +$env:AZURE_CLIENT_SECRET = "your-client-secret" +$env:AZURE_TENANT_ID = "your-tenant-id" + +te deploy ./model ` + -s my-workspace -d my-model ` + --auth env --non-interactive --force --ci vsts +``` + +## Bash + +Compose commands with pipes and `jq`. The CLI's text output is colorized for humans, but switching to `--output-format json` gives you a clean shape to work with: + +```bash +# Count measures per table +te ls --type measure --output-format json \ + | jq -r '.[] | .table' \ + | sort | uniq -c | sort -rn +``` + +```bash +# Fail the shell script if BPA finds any errors +te bpa run --fail-on error --output-format json > bpa.json \ + || { echo "BPA gate failed"; jq '.violations' bpa.json; exit 1; } +``` + +## Composability example + +Generating a refresh TMSL script and version-controlling it is three commands: + +```bash +te connect MyWorkspace MyModel +te refresh --type full --dry-run > refresh.tmsl +cat refresh.tmsl +``` + +The resulting TMSL can be reviewed in a pull request, committed, executed by the CLI (`te refresh --type full`), handed to a DBA, or applied by any XMLA-compatible tool. The CLI becomes a building block rather than a black box. + +## Useful patterns + +A handful of small idioms that come up often when composing `te` commands in scripts or pipelines: + +- **Idempotent creates and removes.** `te add Sales/Marker -t Measure -i "0" --if-not-exists --save` and `te rm Sales/OldMeasure --if-exists --save` both exit `0` whether or not the object existed - safe to re-run in CI. +- **Dry-run diffs.** `te replace` is dry-run by default; add `--save` only when you're satisfied with the preview. +- **Emit TMSL for review.** `te deploy ./model --xmla deploy.tmsl` produces the deployment script without touching the server - useful for DBA review or manual apply. +- **Path-only output.** `te ls --paths-only` and `te find --paths-only` emit one object path per line, ideal for piping to `xargs`, `te get`, or `te set`. The model-level containers (`te ls Measures`, `te ls Columns`) compose well with this for whole-model sweeps. +- **Benchmarking queries.** `te query --trace --cold --runs 5` runs a DAX query with cold cache, five iterations, and captures FE/SE trace events. +- **Step timings in CI logs.** Long-running commands (`te deploy`, `te refresh`, `te script`, `te validate`) include a `durationMs` field in JSON output - useful for surfacing per-step timings in pipeline summaries. + +## Related pages + +- @te-cli-cicd - pipeline-specific patterns and YAML examples. +- @te-cli-commands - full command reference. +- @te-cli-interactive - when interactive mode fits better than scripting. diff --git a/localizedContent/es/content/features/te-cli/te-cli-cicd.md b/localizedContent/es/content/features/te-cli/te-cli-cicd.md new file mode 100644 index 000000000..d39da955b --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-cicd.md @@ -0,0 +1,235 @@ +--- +uid: te-cli-cicd +title: CI/CD Integration +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# CI/CD Integration + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI is designed for unattended execution in continuous integration and delivery pipelines. A single binary, structured output, non-interactive mode, native CI annotations for GitHub Actions and Azure DevOps, and VSTEST-compatible test results make it a natural replacement for ad-hoc TE2 invocations. + +> [!WARNING] +> **Do not use the CLI in production pipelines during Limited Public Preview.** Two preview-specific risks apply to pipeline owners: +> +> - **Hard expiry.** The preview binary stops functioning on **2026-09-30** - any pipeline depending on it will fail on that date, regardless of your release calendar. +> - **No backwards-compatibility guarantee.** Commands, flags, output shapes, and exit codes may change between preview builds, so pipeline steps may need updating when you refresh the vendored binary. +> +> Build and evaluate in non-production pipelines, and share feedback in the public [TabularEditor/CLI](https://github.com/TabularEditor/CLI) repository so the GA version matches your needs. + +## What makes the CLI CI-friendly + +- **Single self-contained binary.** No runtime install, no `TabularEditor.exe`, no `start /wait`. +- **`--non-interactive` global flag.** Disables every prompt; fails fast with actionable errors. +- **`--force`** on mutating commands (`te deploy`, `te refresh`) skips confirmation prompts. +- **`--ci vsts` / `--ci github`.** Emit native pipeline annotations to stderr. +- **`--trx `.** Produce VSTEST results consumable by Azure DevOps test publishing. +- **Structured errors.** `--output-format json` emits `{"error": "...", "hint": "..."}` to stderr so pipeline steps can fail with a useful message. + +## Adding the CLI to your repo + +During Limited Public Preview, the CLI is gated behind sign-in on [tabulareditor.com](https://tabulareditor.com/download-tabular-editor-cli), so pipelines cannot fetch the archive from a public URL. The simplest reproducible approach is to commit the binary that matches your runner into your repository and reference it from each pipeline step. + +A common layout: + +``` +your-repo/ +└── tools/ + └── te/ + ├── te # Linux / macOS binary (needs chmod +x at runtime) + └── te.exe # Windows binary +``` + +Place the **extracted** binary - not the archive - so the pipeline can call it directly. Pick the build that matches your runner OS/arch; see @te-cli-install for the filename table. The self-contained binary is ~70 MB; consider Git LFS if your repo is sensitive to size. + +> [!NOTE] +> Committing the binary also pins the CLI version to whatever you checked in, which is desirable for CI reproducibility. To upgrade, replace the binary in `tools/te/` and commit it - the commit message is your version log. Keep in mind that the preview binary still expires on **2026-09-30** regardless of when you committed it, so a vendored copy is not a permanent dependency - plan to refresh it (and re-validate your pipeline against the new API surface) on preview-build cadence. + +## GitHub Actions + +A complete deploy + test workflow. The example assumes the Linux `te` binary is committed at `tools/te/te`, and a service principal is stored in repository secrets (`AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_TENANT_ID`). + +```yaml +name: Deploy semantic model + +on: + push: + branches: [main] + +jobs: + deploy: + runs-on: ubuntu-latest + env: + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + steps: + - uses: actions/checkout@v4 + + - name: Set up Tabular Editor CLI + run: | + chmod +x ./tools/te/te + echo "$GITHUB_WORKSPACE/tools/te" >> $GITHUB_PATH + + - name: Validate + run: te validate ./model --ci github --trx validate.trx + + - name: Best Practice Analyzer (gate) + run: te bpa run ./model --fail-on error --ci github --trx bpa.trx + + - name: Deploy + run: | + te deploy ./model \ + -s "${{ vars.WORKSPACE }}" \ + -d "${{ vars.MODEL }}" \ + --auth env \ + --non-interactive \ + --force \ + --ci github + + - name: Regression tests + run: | + te test run \ + -s "${{ vars.WORKSPACE }}" \ + -d "${{ vars.MODEL }}" \ + --auth env --non-interactive \ + --ci github --trx tests.trx + + - name: Publish test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: trx-results + path: '*.trx' +``` + +## Azure DevOps Pipelines + +The Azure DevOps Pipelines equivalent of the GitHub Actions workflow above. The example assumes `te.exe` is committed at `tools\te\te.exe`. `--ci vsts` emits `##vso[...]` commands that the pipeline interprets as errors, warnings, and task-status updates. + +```yaml +trigger: + - main + +pool: + vmImage: 'windows-latest' + +variables: + - group: 'te-cli-secrets' # Contains AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID + +steps: + - checkout: self + + - powershell: Write-Host "##vso[task.prependpath]$(Build.SourcesDirectory)\tools\te" + displayName: 'Set up Tabular Editor CLI' + + - script: te validate ./model --ci vsts --trx validate.trx + displayName: 'Validate' + + - script: te bpa run ./model --fail-on error --ci vsts --trx bpa.trx + displayName: 'BPA gate' + + - script: | + te deploy ./model ^ + -s "$(WORKSPACE)" -d "$(MODEL)" ^ + --auth env --non-interactive --force --ci vsts + displayName: 'Deploy' + env: + AZURE_CLIENT_ID: $(AZURE_CLIENT_ID) + AZURE_CLIENT_SECRET: $(AZURE_CLIENT_SECRET) + AZURE_TENANT_ID: $(AZURE_TENANT_ID) + + - script: te test run -s "$(WORKSPACE)" -d "$(MODEL)" --auth env --non-interactive --ci vsts --trx tests.trx + displayName: 'Regression tests' + env: + AZURE_CLIENT_ID: $(AZURE_CLIENT_ID) + AZURE_CLIENT_SECRET: $(AZURE_CLIENT_SECRET) + AZURE_TENANT_ID: $(AZURE_TENANT_ID) + + - task: PublishTestResults@2 + condition: always() + inputs: + testResultsFormat: 'VSTest' + testResultsFiles: '*.trx' +``` + +## BPA gate patterns + +`te deploy` and `te save` run the Best Practice Analyzer as a pre-flight gate by default. Three behaviors are worth determining up-front: + +- **Enforce** - the default. Pipeline fails if BPA finds violations at severity ≥ error. Pair with `--fail-on warning` on a standalone `te bpa run` step if you want warnings to fail too. +- **Auto-fix** - `--fix-bpa` applies `fixExpression`s in memory for the deployed artifact. Source files are not modified. Useful when the source of truth lives in the model and you want deploys to normalize style without developer intervention. +- **Bypass** - `--skip-bpa` disables the gate for a single command. Useful for emergency hotfixes; not recommended as a default. + +```bash +# Treat warnings as failures in PR validation +te bpa run ./model --fail-on warning --ci github --trx bpa.trx + +# Auto-fix during deploy (source unchanged) +te deploy ./model -s my-ws -d my-model --fix-bpa --force --ci github + +# Emergency bypass +te deploy ./model -s my-ws -d my-model --skip-bpa --force --ci github +``` + +See @te-cli-config for controlling the BPA gate globally via `bpa.onDeploy` / `bpa.onSave` config keys. + +## Refresh patterns + +Refresh in pipelines is typically a follow-up step after deployment. Use `--non-interactive` and pick a deterministic `--type`: + +```bash +# Full refresh of the whole model after deploy +te refresh -s my-ws -d my-model --type full --non-interactive + +# Refresh a single fact table (e.g., daily incremental pipeline) +te refresh -s my-ws -d my-model --table Sales --type full --non-interactive + +# Recalculate only (useful after calculation-group changes) +te refresh -s my-ws -d my-model --type calculate --non-interactive +``` + +For incremental refresh workflows, combine `--apply-refresh-policy`, `--effective-date `, and `--partition ` flags. See @te-cli-commands for details. + +## Artifact patterns + +Emit TMSL or XMLA as an artifact without deploying, so DBAs or a later job can review or apply it: + +```bash +# Produce the XMLA/TMSL script that would deploy - do not deploy +te deploy ./model -s my-ws -d my-model --xmla deploy.tmsl --force + +# Produce the TMSL refresh command - do not execute +te refresh -s my-ws -d my-model --type full --dry-run > refresh.tmsl +``` + +Commit these artifacts to git, upload them to the pipeline's artifact storage, or pass them between jobs. They're plain text and diff cleanly in pull requests. + +## Secret handling + +| Approach | When to use | Notes | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Service principal via env vars (`AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET` / `AZURE_TENANT_ID`, `--auth env`) | General CI/CD | Map pipeline secrets to environment variables at the step or job level. Never pass secrets in command arguments. | +| Service principal via `te auth login` once per job (`echo $SECRET \| te auth login -u $ID -p - -t $TENANT`) | Multi-step jobs | The login is cached, so subsequent `te` commands acquire tokens silently - no need to set `AZURE_CLIENT_*` for every step or re-pass `-u/-p/-t`. Pipe the secret via stdin rather than interpolating it. | +| Managed identity (`--auth managed-identity`) | Azure VMs, Container Apps, Azure Functions | No secrets to manage. Preferred in Azure-hosted environments. | +| Certificate (`--certificate `) | Enterprise scenarios with cert rotation | Mount the certificate as a secure file step; pass `--certificate-password` via env. | + +> [!WARNING] +> Do not echo secrets or the output of `te auth status` to pipeline logs. The CLI writes warnings to stderr when secrets are passed on the command line - respect those warnings in CI. + +## Related pages + +- @te-cli-auth - authentication methods in detail. +- @te-cli-config - configuration and profile overrides. +- @te-cli-automation - general scripting patterns. +- @te-cli-migrate - migrating an existing TE2-based pipeline. diff --git a/localizedContent/es/content/features/te-cli/te-cli-commands.md b/localizedContent/es/content/features/te-cli/te-cli-commands.md new file mode 100644 index 000000000..4a92314e5 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-commands.md @@ -0,0 +1,889 @@ +--- +uid: te-cli-commands +title: Referencia de comandos +author: Peer Grønnerup +updated: 2026-05-12 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Referencia de comandos + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +Esta página ofrece una breve descripción y un ejemplo por comando. Todos los comandos aceptan `--help` para consultar la documentación completa de las opciones: + +```bash +te deploy --help # Help for a single command +te bpa run --help # Help for a command with subcommands +``` + +> [!NOTE] +> Durante la versión preliminar, la salida de `--help` de la CLI es la referencia definitiva de parámetros y opciones. El contenido de esta página se ha seleccionado manualmente y puede quedarse atrás respecto a `--help` cuando se añadan novedades entre versiones preliminares. + +## Rutas de objeto + +El direccionamiento de objetos en la CLI usa una única gramática compartida por todos los comandos. En la referencia siguiente aparecen dos tipos de ruta: + +- **``**: identifica **exactamente un** objeto o contenedor. Lo usan los comandos que operan sobre un único destino: `te get`, `te set`, `te add`, `te rm`, `te mv`, `te format -p`, `te deps`, `te macro run --on`. +- **``**: identifica **cero o más** objetos y admite comodines. Lo usan los comandos que operan sobre un conjunto: `te ls`, `te bpa run --path` y otros comandos de tipo inspección. + +Ambas formas de ruta comparten las mismas reglas de sintaxis; solo se diferencian en dos puntos: + +- Las rutas de filtro permiten comodines `*`; las rutas de objeto no. +- Las rutas de objeto permiten el sufijo entre corchetes de DAX (por ejemplo, `Sales[Amount]`); las rutas de filtro no. + +### Segmentos y separadores + +Una ruta es una secuencia de **segmentos** separados por barras. Cada segmento nombra un único paso: una tabla, un objeto hijo o una palabra clave de contenedor. + +- `Sales` — un segmento +- `Sales/Revenue` — dos segmentos +- `Roles/Admin/Members/bob` — cuatro segmentos + +La entrada vacía y `.` significan «la raíz del modelo»: el punto de partida implícito para las rutas de filtro y el sujeto explícito de las consultas del tipo `te get .`. + +### Uso de comillas + +La mayoría de los nombres de segmentos funcionan tal cual. Pon un segmento entre comillas cuando su nombre contenga espacios, barras, corchetes o cualquier carácter que, de otro modo, se interpretaría como sintaxis. La CLI sigue las convenciones de comillas de DAX, por lo que el uso de comillas en las rutas de `te` coincide con lo que escribirías dentro de una expresión DAX: + +| Forma | Uso | Regla de escape | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `'Net Sales'` | Tablas y objetos con nombre con espacios. | Duplica la comilla simple (`'Bob''s'` → `Bob's`). | +| `"Net Sales"` | Igual que arriba; conveniente entre distintos shells cuando es engorroso escapar comillas simples. | Duplica la comilla doble (`"He said ""hi"""` → `He said "hi"`). | +| `[Sales Amount]` | Un sufijo entre corchetes al estilo DAX en una tabla (`'Sales'[Sales Amount]`) o una referencia global al modelo solo entre corchetes (`[Total Sales]`). Solo en rutas de objeto. | Duplica el corchete de cierre (`[foo]]bar]` → `foo]bar`). | + +Dentro de los segmentos entre comillas, `*` se trata como un carácter literal, no como un comodín. Por tanto, `'Sa*'` coincide con una tabla cuyo nombre es exactamente `Sa*`. + +### Referencias al estilo DAX (solo rutas de objeto) + +Se aceptan dos formas con sintaxis DAX en cualquier lugar donde se admita un ``: + +- **`'Table'[Member]`** — equivalente a `Table/Member`. El sufijo entre corchetes hace que las coincidencias ambiguas se resuelvan a favor de columnas y medidas frente a jerarquías/particiones. +- **`[Member]`** — una medida o columna _independiente_, sin tabla delante. Busca en todo el modelo una medida o columna con ese nombre. Las medidas tienen prioridad cuando existen tanto la medida como la columna. + +```bash +te get "'Sales'[Amount]" # Same as te get Sales/Amount +te get "'Net Sales'[Sales Amount]" # Spaced names via DAX form +te get "[Total Sales]" # Model-wide measure-or-column lookup +``` + +### Contenedores y palabras clave + +Varios nombres funcionan como palabras clave de contenedor. Una palabra clave puede usarse sola (para enumerar todo el contenedor) o aparecer dentro de una ruta (para entrar en esa subcolección del elemento padre actual). + +| Palabra clave | Ámbito | Significado | +| -------------------------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------- | +| `Tables`, `Medidas`, `Columns`, `Hierarchies`, `Particiones` | Modelo | Todos los objetos de ese tipo en todo el modelo. | +| `Relaciones`, `Roles`, `Perspectives`, `Cultures`, `DataSources`, `Expressions`, `CalculationGroups`, `Functions`, `Annotations` | Modelo | Contenedores a nivel de modelo. | +| `Medidas`, `Columns`, `Hierarchies`, `Particiones`, `Calendars`, `CalculationItems` | Tabla | Subcontenedores dentro de una tabla. | +| `Levels` | Jerarquía | Niveles de una jerarquía. | +| `Members`, `TablePermissions` (alias `Permissions`) | Rol | Elementos hijos de un rol. | + +Algunos ejemplos muestran en qué se diferencian las rutas simples y las rutas con ámbito de contenedor: + +```bash +te get Sales/Revenue # Measure or column on Sales +te get Sales/Measures/Revenue # Same, container-scoped - disambiguates if other kinds share the name +te get Sales/Geography/Levels/Year # Specific level of a hierarchy +te get Roles/Admin/Members/bob@example.com # Role member +te get Sales/refreshPolicy # Refresh-policy sub-object on a table +te get "Measures/Revenue/KPI" # KPI sub-object of a measure +``` + +Pon un segmento entre comillas para forzar la coincidencia literal del nombre cuando el nombre real de un objeto coincide con una palabra clave. La tabla cuyo nombre literal es `Tables` es `'Tables'` y se accede con `te get "'Tables'"`. + +### Comodines en rutas de filtro + +Las rutas de filtro añaden un único carácter comodín - `*` - que coincide con cualquier secuencia de caracteres dentro de un solo segmento (codicioso, de un solo segmento). Los comodines permiten que `te ls` y comandos similares acoten los resultados. + +```bash +te ls 'Sa*' # Tables whose name starts with Sa +te ls 'Sales/*Amount' # Children of Sales whose name ends with Amount +te ls '*/Amount' # An Amount column/measure across every table +te ls 'Roles/Re*/Members' # Members of every role matching Re* +``` + +Una ruta de filtro con **N segmentos** produce resultados con **N niveles de profundidad**; los comodines nunca amplían automáticamente un nivel más allá de lo que hayas escrito. El atajo de un solo segmento `te ls Sales` es la excepción: un nombre de tabla sin calificar y sin comodines se expande a los elementos secundarios directos de la tabla para ajustarse a la intención de "muéstrame qué hay en Sales". En cambio, `te ls Sa*` devuelve solo las tablas coincidentes, sin expansión. + +El sufijo entre corchetes de DAX se rechaza en las rutas de filtro; pon entre comillas los nombres que contengan `[` y `]` si necesitas que coincidan literalmente. + +### Errores y sugerencias + +Los segmentos mal escritos generan un error contextual con una sugerencia de "quizás quisiste decir" cuando la CLI puede deducir lo que querías decir. Las rutas a las que les falta el elemento padre fallan antes de la comprobación del elemento hoja, así que los mensajes señalan el segmento que realmente está mal. Los contenedores vacíos (por ejemplo, `te ls Hierarchies` en un modelo sin jerarquías) muestran un simple mensaje de "no hay nada aquí" en lugar de un error. + +## Opciones globales + +Estas opciones están disponibles en todos los comandos y se pueden usar antes o después del nombre del subcomando. + +| Opción | Descripción | +| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-m, --model ` | Ruta al modelo semántico (carpeta TMDL, archivo `.bim` o carpeta de TE). | +| `-s, --server ` | Nombre del Workspace o punto de conexión (p. ej., `MyWorkspace`, `powerbi://...`, `asazure://...`, `localhost`). | +| `-d, --database ` | Nombre del modelo semántico en el Workspace. | +| `--local` | Conecta a una instancia de Power BI Desktop en ejecución local (solo Windows). | +| `--auth ` | Método de autenticación: `auto`, `interactive`, `spn`, `env`, `managed-identity` (predeterminado: `auto`). | +| `--output-format ` | Formato de Stdout: `text` (predeterminado), `json`, `csv`, `tmsl` (alias `bim`), `tmdl`. `csv` se respeta en los comandos que emiten datos tabulares; `tmsl`/`tmdl` solo se respeta en `te get` y `te ls` para la serialización de objetos completos. Los comandos rechazan los formatos que no admiten. | +| `--error-format ` | Formato de stderr para errores, advertencias y sugerencias: `text` (predeterminado) o `json`. Para cualquier otro valor, se usa `text`. Es independiente de `--output-format`, así que puedes combinar stdout en JSON con errores en texto sin formato (o viceversa). | +| `--recent [N]` | Usa un modelo que hayas usado recientemente. Sin valor = selector interactivo; `N` = el N-ésimo más reciente (1 = el último usado). | +| `--non-interactive` | Desactiva todas las indicaciones interactivas. Finaliza con un error accionable si falta algún dato obligatorio. | +| `--debug` | Habilita el registro de depuración en stderr (cadenas de conexión, flujo de autenticación, tiempos). | + +En los comandos que leen un modelo, el orden de resolución es: + +el argumento posicional `` → la opción global `--model` → `--server`/`--database` (remoto) → conexión activa de `te connect` → `--recent`. + +## E/S del modelo + +### load + +Carga un modelo semántico y muestra un resumen del modelo: nombre, nivel de compatibilidad y recuentos generales de objetos (tablas, medidas, columnas). + +```bash +te load ./model # TMDL folder +te load model.bim # BIM file +te load -s MyWorkspace -d MyModel # Remote workspace +``` + +### save + +Guarda un modelo en disco. Úsalo para escribir en archivos locales un modelo de un Workspace remoto, convertir formatos o guardar de nuevo las ediciones en el origen. + +`te save` acepta: + +- `-o, --output-path ` - archivo o carpeta de destino. **Opcional** - si se omite, `te save` vuelve a escribir en la ubicación de origen y conserva el formato original. +- `--serialization ` - `tmdl`, `bim`, `te-folder`, `pbip`, `database.json`. De forma predeterminada, se deduce a partir del modelo cargado (origen BIM → BIM, TMDL `SemanticModel/` → TMDL en `definition/`). +- `--force` - omite la validación y sobrescribe la salida existente. Algunos rechazos (contenedores ambiguos, raíces de proyecto con varios `SemanticModel`) siguen ocurriendo incluso con `--force`. +- `--skip-bpa` - omite por completo el control de BPA. +- `--fix-bpa` - corrige automáticamente las infracciones de BPA cuando las reglas definen una expresión de corrección. +- `--bpa-rules ` - repetible; reemplaza `bpa.rules` de la configuración de la CLI solo en este guardado. Las reglas integradas siguen aplicándose a menos que `bpa.builtInRules` sea `false`. +- `--skip-validation` - omite el análisis semántico y la validación de DAX para descargas rápidas en modo passthrough. +- `--supporting-files` - genera archivos auxiliares de Fabric (`.platform`, `definition.pbism`). + +```bash +te save # Save back to source (no -o needed) +te save ./model.bim -o ./tmdl-out # Convert BIM to TMDL +te save -o ./project --serialization pbip # Save as a PBIP project +te save -o ./out -s my-workspace -d my-model --skip-validation # Fast download +``` + +> [!TIP] +> Use `te save -o -s -d ` para descargar un modelo remoto a disco. Combínalo con `--skip-validation` para obtener el passthrough más rápido cuando solo necesites los bytes (sin análisis semántico de DAX). + +### open + +Abre un modelo en la aplicación de escritorio de Tabular Editor 3. **Solo para Windows** (requiere que TE3 esté instalado). + +```bash +te open ./my-model +``` + +### init + +Crea un nuevo modelo semántico vacío en la ruta especificada. + +```bash +te init ./new-model +``` + +## Edición del modelo + +### set + +Establece una propiedad en un objeto del modelo. Acepta un argumento ``. + +`te set` acepta: + +- `-q ` - nombre de la propiedad (por ejemplo, `expression`, `formatString`, `description`, `isHidden`). +- `-i ` - valor (usa `-` para leer desde stdin). +- `--save` / `--save-to ` - guarda los cambios. + +```bash +te set Sales/Amount -q expression -i "SUM(Sales[Amt])" --save +te set "'Net Sales'[Sales Amount]" -q formatString -i "#,0" --save # DAX form with spaced names +te set Sales -q isHidden -i true --save +``` + +### agregar + +Agrega un objeto al modelo. Especifica un `` para el nuevo objeto (el elemento padre ya debe existir; el segmento final es el nuevo nombre) y el tipo mediante `-t` / `--type`. Las relaciones mantienen su sintaxis abreviada (`Sales[Key]->Dim[Key]`). + +`te add` acepta: + +- `-t, --type `: tipo de objeto. Valores comunes: `Table`, `Measure`, `Column`, `CalculatedColumn`, `Hierarchy`, `Role`, `Perspective`, `Culture`, `CalculationGroup`, `CalculationItem`. Se admite el autocompletado con la tecla Tab; la lista completa se puede obtener ejecutando `te add --help`. +- `--if-not-exists` - sale con código `0` sin error si el objeto ya existe. Úsalo en canalizaciones de CI/CD idempotentes. + +```bash +te add Sales/Revenue -t Measure -i "SUM(Sales[Amount])" --save +te add Sales -t Table --save +te add "Sales[ProdKey]->Product[ProdKey]" --save # Relationship shorthand +te add Sales/MarketingFlag -t CalculatedColumn -i "Sales[Amount] > 1000" --if-not-exists --save +te add Perspectives/Default/Sales --save # Include Sales in the Default perspective +te add Roles/Reader -t Role --save # New role at the model level +``` + +En las tablas vinculadas a datos, `te add` también admite la detección del esquema desde orígenes SQL, Lakehouse o Warehouse. Consulta `te add --help` para ver `--source`, `--endpoint`, `--source-table`, `--columns`, etc. + +### rm + +Elimina un objeto. De forma predeterminada, comprueba las dependencias para evitar romper referencias existentes. + +`te rm` acepta: + +- `` — argumento posicional: el objeto que se va a eliminar. +- `--force` — omite la comprobación de objetos dependientes. +- `--if-exists` — sale con código `0` sin error si el objeto no existe. Úsalo en canalizaciones de CI/CD idempotentes. +- `--dry-run` — muestra una vista previa de la eliminación sin aplicarla. +- `--save` — guarda el cambio en el modelo cargado. + +```bash +te rm Sales/Revenue --save +te rm "'Sales'[Revenue]" --save # DAX form +te rm Sales/Revenue --dry-run # Preview only +te rm Sales/OldMeasure --if-exists --save # Idempotent +``` + +### mv + +Mueve o renombra un objeto del modelo. Tanto el origen como el destino son argumentos ``. + +```bash +te mv Sales/Revenue Finance/Revenue --save # Move measure to another table +te mv Sales/Revenue Sales/TotalRevenue --save # Rename measure +``` + +### replace + +Busca y reemplaza texto en los objetos del modelo. Simulación de forma predeterminada; añade `--save` para aplicar. + +`te replace` acepta: + +- `--in ` — ámbito: `names`, `expressions`, `descriptions`, `displayFolders`, `formatStrings`, `annotations`, `all` (predeterminado: `all`). +- `--regex` — trata el patrón de búsqueda como una expresión regular. +- `--case-sensitive` — habilita la coincidencia que distingue entre mayúsculas y minúsculas. +- `--dry-run` - previsualiza los cambios sin aplicarlos. Comportamiento predeterminado. +- `--save` - guarda la modificación en la ubicación de origen. Incompatible con `--revert` y `--stage`. +- `--save-to ` - guarda en una ruta diferente (implica `--save`). +- `--serialization ` - serialización del modelo: `tmdl`, `bim`, `te-folder`. +- `--force` - guarda incluso si la sustitución introduce errores de validación de DAX. + +`--in expressions` recorre todas las propiedades que contienen expresiones: + +- **Medida**: `Expression`, `DetailRowsExpression` +- **KPI**: `TargetExpression`, `StatusExpression`, `TrendExpression` +- **Partición**: M de origen y M de sondeo +- **Permiso de tabla**: `FilterExpression` +- **Grupo de cálculo**: expresiones de selección +- **Columna calculada**: expresión DAX + +Al añadir al modelo nuevas propiedades basadas en expresiones, se muestran automáticamente. + +```bash +te replace "OldTable" "NewTable" --in expressions --save +te replace "SUM" "SUMX" --regex --in expressions --save +``` + +## Inspección + +### ls + +Enumera objetos con una navegación similar a la del sistema de archivos. Acepta un argumento `` que admite comodines. Tanto los contenedores de nivel de modelo (`Tables`, `Measures`, `Columns`, `Hierarchies`, `Relationships`, `Roles`, `Perspectives`, `Cultures`) como los contenedores con ámbito de tabla (`Sales/Measures`, `Sales/Columns`, …) se admiten. + +`te ls` acepta: + +- `--type ` - limita a un tipo de objeto (`table`, `measure`, `column`, `hierarchy`, `partition`, `relationship`, `role`, `perspective`, `culture`). Sin ``, esto equivale a escribir la palabra clave del contenedor correspondiente. +- `--paths-only` - emite una ruta de objeto por línea, ideal para pasarlo a `xargs`, `te get` o `te set`. +- `--no-multiline` - contrae las celdas multilínea (normalmente expresiones DAX o M) a una sola línea y las trunca para que las filas sigan siendo fáciles de recorrer en tablas anchas. Solo afecta a la salida de texto; la salida JSON/CSV/TMSL no se ve afectada. +- `--output-format tmsl` (alias `bim`) - genera los objetos coincidentes como un script TMSL/BIM. Útil para `te ls Tables --output-format bim > tables.json`. `--output-format tmdl` no es compatible con `ls` (TMDL solo admite un único objeto; usa `te get`). + +```bash +te ls # All tables in the model +te ls Sales # All children of Sales (columns + measures + hierarchies + partitions) +te ls Sales/Measures # Just Sales's measures +te ls 'Sales/*Amount' # Children of Sales whose name ends with Amount +te ls 'Sa*' # Tables whose name starts with Sa (no auto-expansion) +te ls '*/Amount' # An Amount column/measure across every table +te ls 'Roles/Re*/Members' # Members of every role matching Re* +te ls Sales/Geography/Levels # All levels of the Geography hierarchy +te ls "'Net Sales'/'Sales Amount'" # Quote names containing spaces +te ls Measures --paths-only # One Table/Measure per line for piping +te ls --type measure # Same as `te ls Measures` +te ls Measures --no-multiline # Wide table with column dividers, single-line DAX +te ls Tables --output-format bim > tables.json # All tables emitted as TMSL/BIM +``` + +### get + +Obtiene las propiedades de un objeto del modelo. Acepta un ``. + +`te get` acepta: + +- `-q, --query ` - obtiene una única propiedad (por ejemplo, `expression`, `formatString`). +- `-t, --type ` - desambigua cuando la ruta coincide con varios elementos secundarios de una tabla (p. ej., una columna y una jerarquía con el mismo nombre). Valores: `Measure`, `Column`, `CalculatedColumn`, `Hierarchy`, `Calendar`, `Partition`, `CalculationItem`. +- `--output-format tmsl` (alias `bim`) - genera el objeto resuelto como JSON TMSL/BIM. +- `--output-format tmdl` - genera el objeto resuelto como TMDL (solo objetos con nombre). + +`te get` y `te ls` comparten un único catálogo de descriptores, por lo que todas las propiedades aparecen igual en todos los formatos: la tabla de texto y las salidas JSON y CSV muestran el mismo conjunto, y al agregar una propiedad nueva al modelo queda expuesta en todas partes. + +```bash +te get Sales/Amount -q expression # Print DAX +te get "'Sales'[Amount]" # DAX form: same as Sales/Amount +te get "[Total Sales]" # Lone-bracket: model-wide measure-or-column +te get "'Net Sales'[Sales Amount]" -q expression # DAX form with spaced names +te get "Sales/Revenue/KPI" # KPI sub-object of a measure +te get Sales --output-format tmdl # Emit the table as TMDL +te get Sales --output-format bim # Emit the table as TMSL/BIM +te get Model -q description +``` + +### find + +Busca texto en todos los objetos del modelo. + +`te find` acepta: + +- `--in ` - igual que en `te replace` (valor predeterminado: `all`). +- `--regex`, `--case-sensitive`, `--paths-only`. +- `--no-multiline` - contrae el contexto de coincidencia multilínea a una sola línea. Solo para la salida de texto. + +`--in expressions` abarca todos los `IExpressionObject` del modelo, incluidas las `TargetExpression` / `StatusExpression` / `TrendExpression` de los KPI, la `DetailRowsExpression` de la medida, el M de origen/sondeo de la partición, la `FilterExpression` de los permisos de tabla y las expresiones `MultipleOrEmptySelection` / `NoSelection` del grupo de cálculo; así, un literal como `123` definido en el objetivo de un KPI aparece igual que el cuerpo de una medida. + +```bash +te find "CALCULATE" --in expressions +te find "Revenue" --in names +te find "CALCULATE" --in expressions --paths-only | xargs -I{} te get {} -q expression +``` + +### diff + +Compara dos modelos para detectar diferencias estructurales. Devuelve los siguientes códigos de salida: `0` = idéntico, `1` = diferencias encontradas, `2` = error. + +```bash +te diff ./model-v1 ./model-v2 +te diff old.bim new.bim +``` + +### deps + +Analiza las dependencias ascendentes y descendentes de un objeto, o detecta objetos sin usar en todo el modelo. La forma de un solo objeto acepta un ``. + +`te deps` admite: + +- `--unused` - enumera las medidas, las columnas calculadas y **todas las columnas de datos** a las que no hace referencia ninguna expresión DAX y que no se usan en ninguna relación, nivel de jerarquía, ordenación por columna, variación, base de AlternateOf ni rol de tiempo de calendario. Cada resultado muestra `(hidden)` en modo de texto y un campo `isHidden` en JSON. +- `--hidden` - limita `--unused` a solo los objetos ocultos. Los objetos ocultos y sin usar son los candidatos más seguros para eliminar, porque ningún elemento visible para el usuario depende de ellos. + +```bash +te deps Sales/Revenue # Upstream + downstream for one object +te deps "'Sales'[Revenue]" # DAX form is accepted everywhere a is +te deps --unused # All unused measures and columns +te deps --unused --hidden # Only hidden, unused objects +``` + +## Análisis y calidad + +### validate + +Valida las expresiones del modelo, la integridad del esquema y los errores de TOM. + +`te validate` admite: + +- `--ci ` - emite anotaciones de CI en stderr: `vsts` o `github`. +- `--trx ` - escribe los resultados en un archivo `.trx` de VSTEST. + +```bash +te validate ./model +te validate --ci github --trx results.trx +``` + +### bpa run + +Ejecuta reglas de Best Practice Analyzer contra un modelo. + +`te bpa run` admite: + +- `` - argumento posicional: ruta al modelo (alternativa a la opción global `--model`). +- `-r, --rules ` - ruta(s) o URL(s) a archivo(s) de reglas BPA en formato JSON. Se puede repetir. Sustituye la capa de reglas de usuario en esta invocación: consulta [Orígenes y resolución de reglas](#rule-sources-and-resolution) más abajo. +- `--no-model-rules` - excluye las reglas de BPA incrustadas en las anotaciones del modelo. +- `--no-defaults` - excluye las reglas predeterminadas de BPA integradas. +- `--vpax ` - carga estadísticas del Analizador VertiPaq desde un archivo `.vpax` para habilitar reglas compatibles con VPA. +- `--vpa-rules` - incluir reglas integradas compatibles con VPA (requiere `--vpax` o un modelo preanotado). +- `--allow-external-rules` - permitir obtener archivos de reglas de BPA desde direcciones URL incrustadas en las anotaciones del modelo. +- `--rule ` - ejecutar solo regla(s) específicas por ID. Se puede repetir. +- `--path ` - limitar el análisis a las tablas que contengan los objetos coincidentes. Acepta nombres literales, palabras clave de contenedor y comodines (por ejemplo, `'Sales'`, `'Sa*'`, `'Sales/Medidas'`, `'*/Amount'`). +- `--fix` - aplicar expresiones de corrección para corregir automáticamente las infracciones cuando sea posible. +- `--save` - volver a guardar el modelo en el origen después de aplicar las correcciones. +- `--save-to ` - guardar el modelo en una ruta diferente después de aplicar las correcciones. +- `--serialization ` - serialización del modelo: `tmdl`, `bim`, `te-folder`. +- `--fail-on ` - umbral de fallo: `error` (predeterminado) o `warning`. Sale con el código `1` cuando las infracciones alcanzan el umbral. +- `--ci ` - emitir comandos de registro de CI a stderr: `vsts` (Azure DevOps), `github` (GitHub Actions). +- `--trx ` - escribir los resultados como un archivo `.trx` de VSTEST en la PATH especificada. +- `--no-multiline` - contraer el contenido de varias líneas de las celdas de la tabla de infracciones en una sola línea. Solo salida de texto. + +```bash +te bpa run --fail-on error --ci github +te bpa run --fix --save +te bpa run --rule PERF_UNUSED_HIDDEN_COLUMN +te bpa run --path Sales # Tables touched by the Sales filter only +te bpa run --path 'Sa*' # Wildcard - every table starting with Sa +te bpa run --path Sales/Measures # Path filter applied to the matched tables +``` + +#### Orígenes de las reglas y su resolución + +Cada invocación de `te bpa run` reúne reglas de tres capas independientes: + +1. **Reglas de usuario** - se aplica exactamente un origen, en este orden de prioridad: + - `-r, --rules `: acepta una PATH de archivo o una URL (prioridad más alta) + - La variable de entorno `TE_BPA_RULES` + - la matriz `bpa.rules` de la configuración de la CLI (`~/.config/te/config.json`) +2. **Reglas integradas predeterminadas** - se cargan a menos que se pase `--no-defaults` o que [`bpa.builtInRules`](xref:te-cli-config#built-in-bpa-rules) sea `false` en la configuración. Se omiten las reglas integradas individuales incluidas en `bpa.disabledBuiltInRuleIds`. +3. **Reglas integradas en el modelo** - reglas en la anotación `BestPracticeAnalyzer_Rules` del modelo; se cargan a menos que se pase `--no-model-rules`. Se omiten las anotaciones de URL externas, a menos que también pases `--allow-external-rules`. + +Se eliminan los ID de reglas duplicados (las reglas del usuario prevalecen sobre las integradas). Después se eliminan los ID de reglas de la anotación `BestPracticeAnalyzer_IgnoreRules` del modelo. + +La línea `Rules loaded:` de la salida atribuye cada capa que contribuye, por ejemplo: + +``` +Rules loaded: 41 from 1 file(s) from bpa.rules config + built-in defaults + model annotations +``` + +### reglas de bpa + +Administra colecciones de reglas de BPA: enumera, inspecciona, inicializa y activa o desactiva reglas en tu archivo local de reglas o en las anotaciones del modelo. Las reglas integradas son de solo lectura; para omitir una sin perder el resto, usa `te bpa rules disable` (no edites directamente el conjunto integrado). + +Subcomandos: + +| Subcomando | Propósito | +| ------------------------------- | ------------------------------------------------------------------------------------------- | +| `add [model]` | Agrega una nueva regla de BPA. | +| [`disable`](#bpa-rules-disable) | Desactiva una regla de BPA integrada para el usuario actual. | +| [`enable`](#bpa-rules-enable) | Vuelve a activar una regla de BPA integrada que se había desactivado antes. | +| `ignore [model]` | Agrega una regla a la lista de ignorados del modelo. | +| [`init`](#bpa-rules-init) | Crea un archivo vacío de reglas de BPA en la ruta PATH resuelta. | +| [`list`](#bpa-rules-list) | Enumera las reglas de BPA de todos los orígenes con su estado. | +| `rm [model]` | Elimina una regla de BPA. | +| `set [model]` | Actualiza las propiedades de una regla del BPA. | +| `unignore [model]` | Elimina una regla de la lista de reglas ignoradas del modelo. | + +Todos los subcomandos de `te bpa rules` aceptan: + +- `--rules-file `: ruta a un archivo JSON de reglas del BPA. De forma predeterminada, se usa la primera entrada existente de `bpa.rules` en la configuración de la CLI (`~/.config/te/config.json`) o la variable de entorno `TE_BPA_RULES`. +- `--model-rules`: opera sobre las reglas incrustadas en la anotación del modelo en lugar de un archivo. + +> [!IMPORTANT] +> `te bpa rules set` y `te bpa rules rm` se niegan a modificar los ID de reglas integradas. Si intentas hacerlo, el comando finaliza con el código `1` y te indica que uses `te bpa rules disable`. Para personalizar el comportamiento de una regla integrada, deshabilita la regla integrada y agrega una copia personalizada con un identificador distinto: +> +> ```bash +> te bpa rules disable TE3_BUILT_IN_DATE_TABLE_EXISTS +> te bpa rules add MY_DATE_TABLE_EXISTS +> ``` + +#### bpa rules list + +Muestra las reglas de todos los orígenes (integradas, de usuario y del modelo). + +`te bpa rules list` acepta: + +- (predeterminado) Solo las reglas activas. +- `--all`: incluye las reglas deshabilitadas e ignoradas. +- `--disabled`: solo los ID de reglas integradas que el usuario ha deshabilitado mediante `te bpa rules disable`. +- `--ignored`: solo las reglas cuyos ID aparecen en `BestPracticeAnalyzer_IgnoreRules` en el modelo. +- `--no-defaults`: excluye las reglas integradas de la salida. + +```bash +te bpa rules list # Active rules +te bpa rules list --all # Include disabled and ignored rules +te bpa rules list --ignored +``` + +Las reglas integradas deshabilitadas se marcan con un marcador `[disabled]` junto al ID de la regla. + +#### bpa rules init + +Crea un archivo de reglas del BPA vacío (`[]`) en el PATH configurado. Úsalo una vez antes de ejecutar `te bpa rules set` / `te bpa rules rm` sobre una ruta que todavía no existe. + +`te bpa rules init` acepta: + +- `--force`: sobrescribe un archivo existente con `[]`. Es obligatorio si el archivo de destino ya existe. +- `--rules-file ` - ruta del archivo de destino. Puede aparecer antes o después del subcomando `init`. + +Resolución de rutas (PATH; se usa la primera coincidencia): `--rules-file` → variable de entorno `TE_BPA_RULES` → primera entrada de `bpa.rules[]` en la configuración de tu CLI → `./BPARules.json` (directorio de trabajo actual). + +```bash +te bpa rules init +te bpa rules init --rules-file ./MyRules.json +te bpa rules init --force +``` + +#### bpa rules disable + +Deshabilita una regla BPA integrada específica. El identificador de la regla se agrega a `bpa.disabledBuiltInRuleIds` en la configuración de tu CLI. Las ejecuciones posteriores del gate (deploy, save, mutation) y `te bpa run` omiten la regla deshabilitada. + +El comando es idempotente: ejecutar `disable` sobre una regla ya deshabilitada finaliza correctamente sin modificar la configuración. Finaliza con el código `1` si `` no es una regla BPA integrada; usa `te bpa rules list` para ver los identificadores válidos de reglas BPA integradas. + +```bash +te bpa rules disable TE3_BUILT_IN_DATE_TABLE_EXISTS +``` + +#### bpa rules enable + +Vuelve a habilitar una regla BPA integrada deshabilitada anteriormente al quitar el identificador de la regla de `bpa.disabledBuiltInRuleIds`. Finaliza con el código `1` si la regla no está deshabilitada actualmente. + +```bash +te bpa rules enable TE3_BUILT_IN_DATE_TABLE_EXISTS +``` + +### vertipaq + +Analiza las estadísticas de almacenamiento de VertiPaq. + +`te vertipaq` acepta: + +- `--columns`, `--relationships`, `--partitions`, `--all`. +- `--export ` - exporta las estadísticas de VertiPaq a un archivo `.vpax` para analizarlas sin conexión. +- `--import ` - carga un archivo `.vpax` exportado previamente y lo analiza sin conexión. +- `--obfuscate` - ofusca nombres y expresiones en el VPAX exportado. +- `--top `, `--stats`, `--annotate`, `--save`. + +```bash +te vertipaq # Columns by size (default) +te vertipaq --all # Tables, columns, relationships, partitions +te vertipaq --export stats.vpax +te vertipaq --import stats.vpax # Analyze offline +``` + +### format + +Da formato a expresiones DAX o M/Power Query. + +`te format` acepta: + +- `-e, --expression ` - da formato a una sola expresión en línea. +- `-p, --path ` - da formato a una medida o columna específica mediante su ruta. +- `--lang ` - valor predeterminado: `dax`. +- `--save` / `--save-to` - guarda las expresiones formateadas. + +```bash +te format --save # Format all DAX +te format -p Sales/Amount --save # Single measure +te format -e "SUM ( Sales[Amount] )" # Inline +te format --lang m --save # Format M +``` + +## Ejecución + +### consulta + +Ejecuta una consulta DAX contra un modelo implementado. + +`te query` admite: + +- `-q, --query ` - consulta en línea. +- `--file ` - consulta desde un archivo. +- `--limit ` - valor predeterminado: 100. +- `-o, --output-file ` - escribe los resultados en un archivo (`.csv`, `.tsv`, `.json`, `.dax`). +- `--trace`, `--cold`, `--plan`, `--runs ` - seguimiento del rendimiento y pruebas comparativas. +- `--no-validate` - omite la validación semántica de DAX previa a la ejecución. + +```bash +te query -q "EVALUATE TOPN(5, 'Sales')" -s my-ws -d my-model +te query --file query.dax --output-format json +``` + +### script + +Ejecuta uno o varios C# Scripts contra un modelo semántico. La CLI usa el mismo host de scripts que Tabular Editor 3 Desktop, así que un script que se ejecuta en TE3 se ejecuta aquí sin cambios. + +`te script` admite: + +- `-S, --script ` - archivo `.cs` / `.csx` (repetible). +- `-e, --expression ` - C# en línea (usa `-` para stdin). +- `--save` / `--save-to` / `--serialization`. +- `--dry-run`, `--timeout `. + +```bash +te script --script fix.cs --save +te script -e "Info(Model.Tables.Count)" +echo "Info(Model.Name);" | te script -e - +``` + +> [!IMPORTANT] +> Dos detalles de comportamiento que conviene conocer si vas a portar un script antiguo: +> +> - **No hay selección interactiva en los scripts de la CLI.** Los asistentes de TE3 Desktop `SelectMeasure()`, `SelectTable()`, `SelectColumn()`, `SelectObject()` y `SelectObjects()` lanzan `NotSupportedException` cuando se invocan desde `te script` - la CLI no tiene interfaz de usuario para mostrar una ventana emergente. Resuelve previamente el/los objeto(s) fuera del script y pásalos, o encapsula la llamada en `try/catch` si el script se comparte con TE3. +> - **Las directivas `using` predeterminadas coinciden con las de TE3 Desktop.** Los scripts que usan `DataTable`, `File`, `StringBuilder` o `Regex` deben incluir explícitamente la directiva correspondiente `using System.Data;` / `using System.IO;` / `using System.Text;` / `using System.Text.RegularExpressions;`. + +> [!NOTE] +> **Símbolos del preprocesador para scripts compartidos entre hosts.** Los scripts compilados por `te script` tienen definido el símbolo `TECLI`. En los scripts de TE3 Desktop se define `TE3` en su lugar, además de símbolos acotados por versión como `TE3_3_10_OR_GREATER` ... `TE3_3_X_OR_GREATER` para la versión menor actual de TE3. TE2 no define ninguno de los dos símbolos. Úselos para escribir scripts portátiles: +> +> ```csharp +> #if TECLI +> // CLI-only code - no UI calls +> Info($"Running under the CLI on {Environment.OSVersion.Platform}"); +> #elif TE3 +> // TE3 Desktop-only code - UI APIs available +> ShowMessage("Hello from TE3"); +> #else +> // TE2 (legacy) - neither TECLI nor TE3 is defined +> Info("Hello from TE2"); +> #endif +> +> #if TE3_3_15_OR_GREATER +> // Gated on a specific TE3 minor version +> #endif +> ``` +> +> Consulta @csharp-scripts para conocer el panorama general del scripting entre versiones. + +### macro + +Administra y ejecuta macros desde un archivo JSON de macros (normalmente `MacroActions.json`). El archivo de macros se determina en este orden: `--macros ` → la variable de entorno `TE_MACROS_PATH` → `macros` en la configuración de la CLI → `./MacroActions.json`. + +Subcomandos: + +| Subcomando | Propósito | +| -------------------------------- | --------------------------------------------------------------------- | +| `list` | Listar macros. | +| [`run `](#macro-run) | Ejecutar una macro. | +| `add ` | Agregar una macro. | +| `set ` | Actualizar las propiedades de la macro. | +| `rm ` | Eliminar una macro. | +| `sort` | Ordenar y reasignar los identificadores. | +| [`init`](#macro-init) | Crear un archivo de macros vacío en la ruta resuelta. | + +#### macro init + +Crea un archivo de macros vacío (`{"Actions":[]}`) en la ruta configurada. Úsalo una sola vez cuando el archivo de macros resultante aún no exista. + +`te macro init` acepta: + +- `--force` - sobrescribe un archivo existente. Obligatorio si el destino ya existe. +- `--macros ` - ruta del archivo de destino. Puede aparecer antes o después del subcomando `init`. + +```bash +te macro init +te macro init --macros ./project-macros.json +te macro init --force +``` + +#### macro run + +Ejecuta una macro. Las macros que emiten tablas mediante `dataTable.Output()` muestran una salida con formato en la terminal, por lo que las macros de consulta de estilo DAX funcionan igual en `te macro run` que en TE3. + +`te macro run` acepta: + +- `--on ` - establece el contexto de selección de la macro en un único objeto con nombre (una tabla, una medida, una columna, …). Equivale a hacer clic con el botón derecho en ese objeto en TE3 e invocar la macro desde el menú contextual. +- `--save` / `--save-to` - guarda cualquier cambio que realice la macro. + +```bash +te macro run "Hide all measures" +te macro run "Format DAX" --on Sales/Revenue --save +te macro run "Format DAX" --on "'Net Sales'[Sales Amount]" --save # DAX form works in --on too +``` + +## Implementación y actualización + +### deploy + +Implementa un modelo semántico en Power BI, Fabric o Azure Analysis Services. + +`te deploy` acepta: + +- `-s, --server` / `-d, --database` - Workspace y modelo de destino. +- `--deploy-full` - sobrescribir + conexiones + particiones + expresiones compartidas + roles + miembros de roles. +- `--deploy-connections` +- `--deploy-partitions` +- `--skip-refresh-policy` +- `--deploy-roles` +- `--deploy-role-members` +- `--deploy-shared-expressions` +- `--create-only` +- `--xmla ` - genera un script XMLA/TMSL en lugar de realizar el despliegue (`-` para stdout). +- `--skip-bpa` - omite por completo el control de BPA. +- `--fix-bpa` - corrige automáticamente las infracciones de BPA cuando las reglas definan una expresión de corrección. +- `--bpa-rules ` - se puede repetir; anula `bpa.rules` de la configuración de tu CLI solo para este despliegue. Las reglas integradas siguen aplicándose a menos que `bpa.builtInRules` sea `false`. +- `--force` - omite la confirmación interactiva (necesario para CI). +- `--ci ` - `vsts` o `github`. +- `--profile ` - uso puntual de un perfil de @te-cli-auth guardado. + +```bash +te deploy ./model -s my-workspace -d my-model --force --ci github +te deploy ./model --xmla script.tmsl # Generate TMSL only +te deploy ./model --profile staging --force +``` + +> [!IMPORTANT] +> `te deploy` ejecuta el Best Practice Analyzer como control previo antes de realizar el despliegue. En modo interactivo, se muestran un resumen y un mensaje de confirmación, con **`n` como opción segura predeterminada**. En CI, pasa `--force` para omitir la confirmación. Consulta @te-cli-config para la configuración del control de BPA. + +### refresh + +Inicia una actualización de datos en un modelo implementado. + +`te refresh` admite: + +- `--type ` - `full`, `dataonly`, `automatic`, `calculate`, `clearvalues`, `defragment`, `add` (predeterminado: `automatic`). +- `--table ` - actualiza tabla(s) específicas; se puede repetir. +- `--partition ` - actualiza partición(es) específicas. +- `--apply-refresh-policy` - aplica la política de actualización para determinar qué particiones se actualizan con la actualización incremental. +- `--effective-date ` - establece la fecha efectiva que usa la política de actualización. +- `--max-parallelism ` - establece el número máximo de particiones que se pueden actualizar en paralelo. +- `--dry-run` - muestra el script TMSL sin ejecutarlo. +- `--no-progress`, `--trace [path]`. + +```bash +te refresh --type full # Full refresh +te refresh --table Sales --type full # Single table +te refresh --type full --dry-run > refresh.tmsl # Emit TMSL only +``` + +### incremental-refresh + +Gestiona las políticas de actualización para la actualización incremental de las tablas. + +```bash +te incremental-refresh show +``` + +Los subcomandos adicionales (`set`, `remove`, `apply`) están documentados en `te incremental-refresh --help`. + +## Pruebas + +### test run + +Ejecuta un conjunto de pruebas de aserción de DAX contra un modelo desplegado. + +`te test run` admite: + +- `--suite ` - directorio de la suite de pruebas (predeterminado: `.te-tests/`). +- `--tag ` - solo las pruebas con esta etiqueta. +- `--fail-on ` - `error` (predeterminado) o `warning`. +- `--ci `, `--trx ` - anotaciones de CI y salida TRX. + +```bash +te test run --ci github --trx results.trx +te test run --tag revenue +``` + +### test init / spec / use / list / snapshot / compare + +Los subcomandos adicionales permiten crear la estructura de las pruebas, imprimir el formato de la especificación de aserciones, cambiar la suite activa, listar las suites, capturar instantáneas y comparar modelos. Consulta `te test --help` para más detalles. + +```bash +te test init --example # Scaffold an example suite +te test spec # Print the full assertion format reference +te test init --from-model --model ./my-model # Generate stubs from your measures +``` + +## Conexión y autenticación + +### connect + +Establece (o muestra) la conexión activa para la sesión actual del terminal. Consulta @te-cli-auth. + +```bash +te connect # Show current active connection +te connect my-workspace my-model # Remote +te connect ./model # Local +te connect --local # Power BI Desktop (Windows) +te connect --profile prod # Activate a saved profile +te connect --clear # Clear the active connection (and any workspace mirror) +``` + +#### Modo del área de trabajo (`-w` / `--workspace`) + +Empareja un origen principal con un destino secundario para que cada `--save` posterior sincronice el modelo entre ambos. Útil para mantener una copia de trabajo local de un Workspace remoto o para enviar los cambios locales a un Workspace al guardar. + +- `te connect -w ./src` - el origen principal es remoto; `./src` recibe una exportación inicial de TMDL y refleja cada guardado. +- `te connect ./src -w ` - el origen principal es local; un despliegue inicial envía el modelo al Workspace, y los guardados posteriores lo vuelven a desplegar automáticamente. +- `--workspace-format ` - elige el formato en disco al sincronizarlo con una carpeta o archivo (por ejemplo, `-w ./model.bim` deduce BIM). +- `--force`: obligatorio cuando el destino ya existe (carpeta no vacía o base de datos existente). Sin él, `te connect` muestra un prompt interactivo `y/n`, con `n` como opción segura predeterminada. + +Una vez activado, `te set --save`, `te rm --save`, `te script --save`, etc. guardan de forma transparente en ambos destinos. El orden de guardado siempre es **primero local y después remoto**, para que la copia en disco refleje el último cambio del usuario aunque falle el envío al servidor. Borra la réplica con `te connect --clear`. + +```bash +te connect Finance "Revenue Model" -w ./revenue-model # Mirror remote → local TMDL +te connect ./revenue-model -w Finance "Revenue Model" # Mirror local → remote +``` + +### auth login / status / logout + +Administra la autenticación almacenada en caché. Consulta @te-cli-auth. + +### profile list / show / set / remove + +Administra perfiles de conexión con nombre. Consulta @te-cli-auth. + +## Configuración + +### config show / paths / init / set + +Consulta y administra la configuración de la CLI y las sobrescrituras de PATH de TE3. Consulta @te-cli-config. + +```bash +te config show # Display all settings +te config paths # Resolved TE3 file paths +te config init # Create default config +te config set autoFormat true +``` + +### license + +`te license` está reservado para la versión GA y no está disponible en esta versión preliminar. El comando sigue integrado con el analizador, por lo que los scripts existentes que lo invocan no darán error durante el análisis, pero todos los subcomandos finalizan con el código de salida `1` y mensajes de "no está disponible en esta versión preliminar". Consulta el [aviso de versión preliminar](xref:te-cli#preview-notice) en la página de información general para conocer el panorama más amplio de licencias. + +### migrate + +Guía de referencia que muestra cómo las opciones heredadas de la CLI de Tabular Editor 2 se corresponden con la nueva CLI. Útil como referencia rápida mientras migras una canalización basada en TE2. Consulta @te-cli-migrate para ver la guía de migración completa. + +```bash +te migrate # Full flag mapping table +te migrate -A # Look up a single TE2 flag +te migrate --output-format json # Machine-readable mapping +``` + +## Shell + +### interactive + +Inicia una sesión REPL guiada con un prompt adaptado al modelo. Consulta @te-cli-interactive. + +```bash +te interactive # Connect later +te interactive ./model # Start with a local model +te interactive -s MyWorkspace -d MyModel # Start with a remote model +``` + +Las comillas y las referencias de estilo DAX funcionan igual que fuera de la sesión - consulta la sección [Rutas de objetos](#object-paths) de arriba y @te-cli-interactive para más detalles sobre la división de argv con reconocimiento de corchetes dentro del REPL. + +### completion + +Genera un script de autocompletado para el shell. Consulta @te-cli-install. + +```bash +te completion bash +te completion zsh +te completion pwsh +``` + +## Códigos de salida + +| Código de salida | Significado | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `0` | Éxito. | +| `1` | Fallo genérico (argumentos no válidos, fallo del comando, errores de validación, fallo de autenticación, el BPA gate falló con una gravedad ≥ error). | +| `2` | Diff distinto de cero (`te diff`): los modelos difieren. | + +Para un control detallado en las canalizaciones de CI, combina los códigos de salida con las anotaciones `--ci ` y los archivos de resultados `--trx`; consulta @te-cli-cicd. + +## Páginas relacionadas + +- @te-cli - información general y contexto. +- @te-cli-install - instalación y configuración de la CLI. +- @te-cli-auth - autenticación y administración de conexiones. +- @te-cli-config - archivo de configuración, BPA gate y comportamiento tras la mutación. +- @te-cli-migrate - mapeo de opciones TE2 → TE3. diff --git a/localizedContent/es/content/features/te-cli/te-cli-config.md b/localizedContent/es/content/features/te-cli/te-cli-config.md new file mode 100644 index 000000000..226405a52 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-config.md @@ -0,0 +1,258 @@ +--- +uid: te-cli-config +title: Configuración personalizada +author: Peer Grønnerup +updated: 2026-04-20 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Configuración personalizada + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +La CLI de Tabular Editor lee una configuración opcional desde un archivo JSON. La configuración controla tres cosas: + +- **PATH de archivos** — donde la CLI lee las macros, las reglas de BPA y (opcionalmente) el ejecutable de TE3 Desktop, y donde escribe el registro de consultas. +- **Valores predeterminados de comportamiento** — umbrales de BPA, formato automático y validación. +- **Perfiles de conexión guardados** — la lista de perfiles con nombre entre los que puedes alternar. + +La CLI es independiente: no lee ni escribe en ningún PATH de instalación de la versión de escritorio de Tabular Editor 3. Los archivos de reglas de BPA y de macros deben definirse explícitamente en esta configuración (o inicializarse cuando haga falta con `te bpa rules init` / `te macro init`). + +La mayoría de los usuarios no necesitan editar el archivo de configuración directamente: `te config show`, `te config set ` y `te profile set` cubren las operaciones habituales. + +## Ubicación del archivo de configuración + +Se comprueban las siguientes ubicaciones en este orden: + +1. La variable de entorno `$TE_CONFIG` (si está definida y el archivo existe). +2. `~/.config/te/config.json` (en Windows, `%USERPROFILE%\.config\te\config.json`). +3. Si no hay archivo de configuración, la CLI usa los valores predeterminados integrados. + +`TE_CONFIG` se tiene en cuenta de forma coherente en todas las operaciones del archivo de configuración: `te config show`, `te config set`, `te config init` y `te config paths` leen y escriben en el PATH resuelto. Está pensado principalmente para pruebas, instalaciones mediante scripts y configuración por entorno. + +Para crear una configuración predeterminada: + +```bash +te config init # Create config at TE_CONFIG (or ~/.config/te/config.json) +te config init --force # Overwrite existing config +``` + +## Ver la configuración + +```bash +te config show # Display all settings +te config show --output-format json # Machine-readable +te config paths # Show resolved macros and BPA rule paths +``` + +Usa `te config paths` para ver qué archivos usará realmente la CLI para las macros y las reglas de BPA. Es útil para depurar por qué faltan archivos de datos. La salida muestra dos filas: `macros` (la ruta del archivo de macros resuelta o `[not set]`) y `bpa.rules` (el primer archivo de reglas de BPA existente resuelto por el resolvedor de rutas, o `[not set]`). + +> [!NOTE] +> `te config paths` emite campos `null` explícitamente en el modo `--output-format json` (por ejemplo, `{"macros": null, "bpa": {"rules": null}}`). Informar de los resultados de la resolución es precisamente el propósito del comando, así que `null` es una respuesta significativa: «se intentó, pero no se resolvió nada». `te config show --output-format json` elimina los campos `null` de forma predeterminada, así que quienes lo consuman deberían parsearlo de forma tolerante. + +## Configurar valores + +```bash +te config set autoFormat true +te config set bpa.onDeploy false +te config set hidePreviewNotice true +te config set macros null # Clear a path override +``` + +Las claves desconocidas provocan que el comando finalice con el código de salida `1` y un error que enumera las claves válidas. + +Si no existe ningún archivo de configuración, `te config set` crea uno automáticamente en la ruta resuelta (`$TE_CONFIG` si está establecido; de lo contrario, `~/.config/te/config.json`) antes de aplicar el cambio. + +> [!NOTE] +> Puedes establecer cualquier clave del esquema mediante `te config set`, incluidas las claves anidadas mediante rutas con puntos (`bpa.onDeploy`, `formatOptions.useSqlBiDaxFormatter`, etc.). La única excepción es `formatVersion`, que la CLI administra automáticamente. Ejecuta `te config paths` para encontrar el archivo de configuración si prefieres editar el JSON directamente. + +## Esquema completo + +El esquema completo de configuración JSON con todas las claves en sus valores predeterminados. Úsalo como referencia al editar directamente el archivo de configuración o al buscar la ruta con puntos para una llamada a `te config set`. + +```json +{ + "formatVersion": 1, + "macros": null, + "autoFormat": false, + "validateOnMutation": true, + "vertipaqOnRefresh": false, + + "bpa": { + "rules": null, + "onDeploy": true, + "onSave": true, + "onMutation": false, + "builtInRules": true, + "disabledBuiltInRuleIds": null + }, + + "interactiveEditMode": "stage", + + "formatOptions": { + "useSemicolons": false, + "shortFormat": false, + "skipSpaceAfterFunction": false, + "useSqlBiDaxFormatter": false + }, + + "hidePreviewNotice": false, + "spinner": true, + "debug": false, + "disableTelemetry": false, + + "queryLog": null, + "te3ExePath": null, + + "profiles": {} +} +``` + +### Rutas de archivo + +Configúralas en tu configuración para evitar pasar las mismas rutas en cada comando. Las opciones específicas de cada comando y las variables de entorno prevalecen sobre los valores de configuración; consulta [Prioridad de resolución de rutas](#path-resolution-priority) más abajo. + +| Clave | Significado | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `macros` | Ruta explícita a un archivo JSON de macros (normalmente `MacroActions.json`). La resuelve cualquier comando `te macro`. Apunta a un archivo compartido (un recurso compartido de red, un archivo local del repositorio o incluso el archivo de escritorio de TE3) para reutilizar el mismo conjunto de macros en distintos equipos y entre la CLI y TE3 Desktop. | +| `bpa.rules` | Lista ordenada de rutas o URL a archivos de reglas de BPA. `te bpa run` y la compuerta de implementación/guardado cargan **todas** las entradas existentes; `te bpa rules list` y `te config paths` usan la primera entrada existente. Los valores separados por comas en `te config set bpa.rules ...` se separan en el arreglo. | +| `te3ExePath` | Ruta explícita al ejecutable de Tabular Editor 3 Desktop (`TabularEditor.exe`). `te open` lo usa **solo** para iniciar la aplicación de escritorio; puedes dejarlo sin configurar en Linux/macOS o cuando no uses `te open`. Si no está configurado, `te open` recurre a una búsqueda en `PATH`. | +| `queryLog` | Ruta a un archivo de registro en el que cada invocación de `te query` añade el texto de la consulta y los metadatos de ejecución. Útil para mantener registros de auditoría o analizar patrones de consulta a lo largo del tiempo. Admite `~` para el directorio personal (p. ej., `~/.config/te/queries.log`). | + +### Prioridad de resolución de rutas + +Para cada archivo proporcionado por el usuario (macros, reglas de BPA), la CLI resuelve la ruta en este orden: + +1. **Opción de línea de comandos** - `--macros ` para comandos de macros; `--bpa-rules ` para la compuerta de implementación/guardado; `--rules-file ` para los subcomandos de `te bpa rules`. +2. **Variable de entorno** - `TE_MACROS_PATH` para macros, `TE_BPA_RULES` para reglas de BPA. +3. **Configuración de la CLI** - `macros` para macros, la primera entrada existente de `bpa.rules[]` para reglas de BPA. + +La CLI no detecta automáticamente ninguna ubicación de instalación de TE3; configúralas explícitamente. Para empezar con un archivo predeterminado en el directorio de trabajo actual, ejecuta `te macro init` (crea `./MacroActions.json`) o `te bpa rules init` (crea `./BPARules.json`). + +Ejecuta `te config paths` para ver qué archivo resolvió realmente la CLI. + +### Valores predeterminados de comportamiento + +Toda la configuración relacionada con BPA está en el objeto `bpa` y se referencia mediante claves con puntos en `te config set`. + +| Clave | Predeterminado | Descripción | +| ---------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `autoFormat` | `false` | Ejecuta DAX Formatter sobre las expresiones modificadas después de `te add` / `te set` / `te mv` / `te macro run`. Usa el formateador interno de forma predeterminada; puedes optar por el servicio web de SQL BI mediante `formatOptions.useSqlBiDaxFormatter`. | +| `validateOnMutation` | `true` | Después de un comando de modificación (`add`, `set`, `mv`, `replace --save`, `macro run`), comprueba que todas las referencias `Table[Column]` del modelo se sigan resolviendo. Detecta referencias huérfanas introducidas por cambios de nombre o eliminaciones antes de llegar al despliegue. | +| `bpa.onMutation` | `false` | Ejecuta un análisis de BPA acotado después de cada comando de modificación (`set`, `add`, `mv`, `rm`, `macro run`). Solo se comprueban los objetos de la tabla afectada, no los de todo el modelo; útil para obtener retroalimentación rápida durante ediciones iterativas. | +| `bpa.onDeploy` | `true` | Ejecuta el control de BPA antes de que se ejecute `te deploy`. El despliegue se cancela si alguna regla se activa con una severidad ≥ error. Omítelo en una invocación concreta con `--skip-bpa`, o corrígelo automáticamente con `--fix-bpa`. | +| `bpa.onSave` | `true` | Ejecuta el control de BPA antes de que `te save -o` escriba en disco. Omítelo en una invocación concreta con `--skip-bpa` o `--force`. | +| `bpa.builtInRules` | `true` | Incluye el conjunto depurado de reglas integradas de BPA cada vez que se ejecute el control. Configúralo en `false` para ignorar por completo las reglas integradas; entonces el control ejecutará solo las reglas configuradas mediante `bpa.rules` y cualquier regla incrustada en el modelo. | +| `bpa.disabledBuiltInRuleIds` | `null` | ID de reglas integradas individuales que se excluirán de la puerta de calidad. Este valor se modifica mediante `te bpa rules disable ` / `te bpa rules enable `; es preferible usar esos comandos en lugar de editar el arreglo directamente. | +| `vertipaqOnRefresh` | `false` | Tras una actualización correcta (`full`, `dataonly`, `automatic` o `add`), ejecuta automáticamente el análisis de VertiPaq para mostrar estadísticas de almacenamiento de las tablas actualizadas. Útil para detectar de inmediato regresiones inesperadas de cardinalidad o memoria. | +| `interactiveEditMode` | `stage` | Comportamiento predeterminado para las mutaciones en memoria dentro de `te interactive`. `stage` mantiene las mutaciones en memoria hasta que se invoca `save` (la opción más segura); `save` escribe en el origen después de cada comando que modifica el estado (úsese con cuidado en orígenes remotos: cada `set` desencadena una escritura XMLA); `revert` descarta las mutaciones después de cada comando, a menos que se haya pasado `--save` o `--stage`. Las marcas `--save` / `--revert` / `--stage` por comando siempre prevalecen. | +| `disableTelemetry` | `false` | Desactiva la telemetría de uso anónima. La CLI recopila datos básicos de uso de comandos (nombre del comando, código de salida y duración) para orientar la priorización de funciones. La CLI nunca recopila el contenido del modelo, PATH ni el texto de las consultas. | + +```bash +te config set bpa.rules "/etc/te/team.json,/etc/te/strict.json" +te config set bpa.onDeploy true +te config set bpa.builtInRules false +te config set bpa.disabledBuiltInRuleIds "TE3_BUILT_IN_DATE_TABLE_EXISTS,TE3_BUILT_IN_HIDE_FOREIGN_KEYS" +``` + +### Opciones de formato + +Se aplica siempre que la CLI invoque un formateador de DAX (para `te format` y, cuando está habilitado, para `autoFormat` en las mutaciones). La CLI incluye un formateador propio que funciona completamente sin conexión; activa el servicio web de SQL BI [daxformatter.com](https://www.daxformatter.com) mediante `formatOptions.useSqlBiDaxFormatter` si necesitas ese estilo o quieres igualar el comportamiento de TE2 o TE3 con "Use daxformatter.com..." activado. + +| Clave | Predeterminado | Descripción | +| -------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `formatOptions.useSemicolons` | `false` | Usa `;` como separador de listas (según la configuración regional europea/de la UE). El valor predeterminado `,` coincide con la configuración regional en-US. | +| `formatOptions.shortFormat` | `false` | Prefiere un formato corto, de una sola línea, cuando sea posible, en lugar del diseño predeterminado de varias líneas. | +| `formatOptions.skipSpaceAfterFunction` | `false` | Omite el espacio entre el nombre de una función y su paréntesis de apertura (por ejemplo, `SUM(x)` en lugar de `SUM (x)`). | +| `formatOptions.useSqlBiDaxFormatter` | `false` | Formatea DAX con el servicio web [SQL BI daxformatter.com](https://www.daxformatter.com) en lugar del formateador interno. Requiere acceso a Internet. El formateador interno (predeterminado) funciona sin conexión y coincide con la configuración predeterminada de Tabular Editor 3 Desktop. | + +### Visualización + +Ajustes que controlan la salida del terminal de la CLI y el nivel de detalle de los diagnósticos. + +| Clave | Predeterminado | Descripción | +| ------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| `hidePreviewNotice` | `false` | Suprime el banner amarillo de vista previa. **Se ignora cuando faltan menos de 14 días para el vencimiento.** | +| `spinner` | `true` | Muestra indicadores de progreso animados en el terminal. Desactivar para CI. | +| `debug` | `false` | Activa siempre el registro de depuración (equivale a pasar `--debug`). | + +### Perfiles + +Los perfiles de conexión guardados se almacenan bajo la clave `profiles`. No los edites a mano; usa `te profile set / remove / list`. Consulta @te-cli-auth para la gestión de perfiles. + +Los perfiles pueden incluir **anulaciones** que sustituyen los valores predeterminados de comportamiento anteriores siempre que el perfil esté activo. Así, un perfil de desarrollo puede relajar la validación y el BPA, mientras que uno de producción los mantiene estrictos: + +```bash +te profile set dev --validate-on-mutation false --bpa-on-deploy false +te profile set prod --auto-format true +``` + +## Control BPA + +El control BPA es la red de seguridad que impide que se guarde o se despliegue un modelo con infracciones de reglas. Se ejecuta automáticamente con los siguientes comandos: + +- `te deploy` ejecuta el control, a menos que se pase `--skip-bpa` o que `bpa.onDeploy` sea `false`. +- `te save` ejecuta el control, a menos que se pase `--skip-bpa` (o `--force`) o que `bpa.onSave` sea `false`. +- `te add`, `te set`, `te mv`, `te macro run` ejecutan el control solo cuando `bpa.onMutation` es `true`. + +El control carga las reglas de BPA desde `bpa.rules` y, de forma predeterminada, el conjunto de reglas integrado (controlado por `bpa.builtInRules`). Las reglas integradas pueden excluirse individualmente mediante `bpa.disabledBuiltInRuleIds`; se administran con `te bpa rules disable ` / `te bpa rules enable `. + +Cuando el control se activa y encuentra infracciones con gravedad ≥ `error`, el comando falla con el código de salida `1` y un resumen de las infracciones. Opciones para resolverlo: + +- `--fix-bpa` - aplica en memoria la `fixExpression` de la regla al artefacto que se va a desplegar o guardar; los archivos fuente no se modifican. +- `--skip-bpa` - desactiva el control solo para este comando. +- `--bpa-rules ` - repetible; sobrescribe `bpa.rules` para esta única invocación de `te deploy` o `te save`. Las reglas integradas siguen aplicándose salvo que `bpa.builtInRules` sea `false`. + +Ejecuta `te bpa run` de forma independiente para previsualizar el comportamiento del control sin desplegar: + +```bash +te bpa run ./model --fail-on error +te bpa run ./model --fix --save # Apply fixes to the source +``` + +### Reglas de BPA integradas + +La CLI incluye un único conjunto canónico de reglas de BPA integradas, incrustado como recurso JSON. Las reglas integradas son de solo lectura: `te bpa rules set` y `te bpa rules rm` se niegan a modificar los ID integrados y remiten a los usuarios a `te bpa rules disable` en su lugar. Para personalizar el comportamiento de una regla integrada, cópiala en tu archivo local de reglas como una regla nueva con un ID distinto y deshabilita la regla integrada. + +Tanto `bpa.builtInRules` como `bpa.disabledBuiltInRuleIds` se aplican de forma coherente a la validación de implementación/guardado/mutación **y** al comando manual `te bpa run`: si deshabilitas una regla una vez con `te bpa rules disable`, queda excluida en todas partes. + +## Comportamiento tras la mutación + +Cuando ejecutas un comando que modifica (`te add`, `te set`, `te mv`, `te replace --save`, `te macro run`), la CLI realiza estas comprobaciones automáticamente: + +1. **Los errores de TOM** siempre se muestran. Un DAX o M no válidos en medidas, columnas, particiones o elementos de cálculo siempre hacen que el comando falle. +2. **La validación del esquema** (`validateOnMutation`, valor predeterminado `true`) comprueba que las referencias `Table[Column]` en DAX sigan resolviéndose y verifica la consistencia de los metadatos. +3. **Formato automático de DAX** (`autoFormat`, valor predeterminado `false`) da formato a cualquier expresión afectada por la mutación mediante el DAX Formatter integrado cuando está habilitado. +4. **BPA tras la mutación** (`bpa.onMutation`, valor predeterminado `false`) ejecuta BPA después de la mutación cuando está habilitado, y muestra una advertencia o hace que el comando falle según `--fail-on`. + +Deshabilita una comprobación con `te config set false`, o limita esa relajación a un entorno concreto mediante un perfil. + +## Variables de entorno + +Usa las siguientes variables de entorno específicas de la CLI para PATH, comportamiento y diagnósticos. Para las variables de autenticación de Azure (`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_CERTIFICATE_PATH`, etc.), consulta @te-cli-auth. + +| Variable | Propósito | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `TE_CONFIG` | Ruta de acceso a un archivo de configuración alternativo. Se respeta en todas las operaciones de `te config` (`show`, `set`, `init`, `paths`). | +| `TE_MACROS_PATH` | Anula la ruta del archivo de macros (segundo en el orden de resolución; ver arriba). La leen los comandos `te macro`. | +| `TE_BPA_RULES` | Anula la lista de archivos/URL de reglas de BPA utilizada por los subcomandos `te bpa run` y `te bpa rules`. | +| `TE_BPA_CONFIG` | Anula la ruta de acceso a la configuración del gate de BPA (`.te-bpa.json`) que lee el gate de despliegue/guardado. | +| `TE3_EXE_PATH` | Ruta al binario de escritorio de Tabular Editor 3. Se usa **solo** con `te open`; puedes dejarla sin definir en Linux/macOS o si no usas `te open`. Si no se especifica, se usa la búsqueda en `PATH`. | +| `TE_DEBUG` | Establece el valor en `1` para habilitar el registro de depuración globalmente (igual que `--debug` o `debug: true` en la configuración). | +| `NO_SPINNER` | Establece el valor en `1` o `true` para desactivar los indicadores de progreso animados (alternativa a `spinner: false` en la configuración). | +| `CI` | Se detecta automáticamente. Cuando vale `1` o `true`, la CLI desactiva el spinner y cambia a una salida de texto sin formato. La mayoría de los runners de CI lo configuran automáticamente. | +| `TE_SESSION` | Sobrescribe el identificador de sesión por terminal que se usa para el estado de la conexión activa. Útil para ejecutar varias sesiones aisladas de la CLI dentro del mismo shell, por ejemplo, en trabajos de matriz de CI en paralelo. | +| `TE_COMPAT` | Establécela en `te2` para forzar el modo de compatibilidad con TE2; consulta @te-cli-migrate. | + +## Páginas relacionadas + +- @te-cli-auth - perfiles, autenticación y almacenamiento de credenciales. +- @te-cli-commands - subcomandos de `te config`. +- @te-cli-cicd - configuración del gate de BPA para pipelines. diff --git a/localizedContent/es/content/features/te-cli/te-cli-install.md b/localizedContent/es/content/features/te-cli/te-cli-install.md new file mode 100644 index 000000000..11c270639 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-install.md @@ -0,0 +1,201 @@ +--- +uid: te-cli-install +title: Installation and Setup +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Installation and Setup + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI ships as a single self-contained executable named `te` (`te.exe` on Windows). It has no external runtime dependencies. + +## Descargar + +1. Sign in at [tabulareditor.com](https://tabulareditor.com/download-tabular-editor-cli) with a Tabular Editor account. +2. Download the archive for your platform and architecture: + + | Platform | 64-bit (Intel/AMD) | ARM64 | Archive | + | -------- | ---------------------------------------------- | -------------------------------------------------------- | --------- | + | Windows | `te-win-x64.zip` | `te-win-arm64.zip` | `.zip` | + | macOS | `te-osx-x64.tar.gz` (Intel) | `te-osx-arm64.tar.gz` (Apple Silicon) | `.tar.gz` | + | Linux | `te-linux-x64.tar.gz` | `te-linux-arm64.tar.gz` | `.tar.gz` | + + Pick the ARM64 build on Apple Silicon Macs (M1 and newer), Windows on ARM devices, and ARM-based Linux servers (including AWS Graviton, Azure Ampere, and Raspberry Pi 64-bit). Pick the `x64` build on everything else. + +## Install + +Unzip the archive into a folder of your choice and add that folder to `PATH` so you can invoke `te` from any working directory. + +### Windows (PowerShell) + +#### x64 + +```powershell +Expand-Archive te-win-x64.zip -DestinationPath "$env:LOCALAPPDATA\Programs\te" +[Environment]::SetEnvironmentVariable( + "PATH", + [Environment]::GetEnvironmentVariable("PATH", "User") + ";$env:LOCALAPPDATA\Programs\te", + "User") +``` + +#### ARM64 + +```powershell +Expand-Archive te-win-arm64.zip -DestinationPath "$env:LOCALAPPDATA\Programs\te" +[Environment]::SetEnvironmentVariable( + "PATH", + [Environment]::GetEnvironmentVariable("PATH", "User") + ";$env:LOCALAPPDATA\Programs\te", + "User") +``` + +### macOS + +#### Apple Silicon (ARM64) + +```bash +mkdir -p ~/.local/bin +tar -xzf te-osx-arm64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc +``` + +#### Intel (x64) + +```bash +mkdir -p ~/.local/bin +tar -xzf te-osx-x64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc +``` + +On macOS, the binary is signed with our Apple Developer ID and notarized by Apple, so the first run completes without a "cannot verify developer" Gatekeeper warning. Network access on first run is recommended so Gatekeeper can fetch the notarization ticket; offline first-runs may briefly prompt before being unblocked once network returns. + +### Linux + +#### x64 + +```bash +mkdir -p ~/.local/bin +tar -xzf te-linux-x64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc +``` + +#### ARM64 + +```bash +mkdir -p ~/.local/bin +tar -xzf te-linux-arm64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc +``` + +> [!NOTE] +> The PATH change takes effect in **new** shell sessions. To run `te` in the shell where you ran the install, open a new terminal, or reload your profile: `source ~/.bashrc` / `source ~/.zshrc` on macOS/Linux, or close and reopen PowerShell on Windows. + +## Verify + +Check the installed version and list available commands: + +```bash +te --version +te --help +``` + +`te --help` prints a colorized help index grouping commands by family. Every subcommand accepts `--help` for detailed usage: + +```bash +te deploy --help +te bpa run --help +``` + +## Hide the preview banner + +The CLI prints a yellow preview banner on stderr by default. To suppress it run: + +```bash +te config set hidePreviewNotice true +``` + +> [!WARNING] +> The banner reappears on every command within **14 days of the preview end date** (2026-09-30), regardless of `hidePreviewNotice`. This ensures you have visible warning before the CLI stops functioning. + +## Shell completion + +The CLI provides tab-completion scripts for **Bash**, **Zsh**, and **PowerShell**. Pick the block that matches your shell — each one installs the completion persistently for new shell sessions. + +### Bash (macOS/Linux) + +```bash +mkdir -p ~/.local/share/bash-completion/completions +te completion bash > ~/.local/share/bash-completion/completions/te +``` + +### Zsh (macOS/Linux) + +```zsh +mkdir -p ~/.zfunc +te completion zsh > ~/.zfunc/_te +echo 'fpath=(~/.zfunc $fpath); autoload -U compinit; compinit' >> ~/.zshrc +``` + +### PowerShell (Windows/macOS/Linux) + +```powershell +Add-Content $PROFILE 'te completion pwsh | Out-String | Invoke-Expression' +``` + +Open a new shell session for completion to take effect. + +Completion covers subcommands, global flags, and model paths (where tab-completion against the filesystem is meaningful). + +## Cross-platform feature matrix + +Most features are identical across platforms. A handful depend on Windows-only transports: + +| Feature | Windows | macOS / Linux | +| ---------------------------------------------------------------------------------------------- | ------- | ------------- | +| Load/save BIM and TMDL | Yes | Yes | +| Deploy to Power BI / Fabric / Azure Analysis Services | Yes | Yes | +| Best Practice Analyzer and VertiPaq Analyzer | Yes | Yes | +| C# scripting | Yes | Yes | +| DAX queries against cloud models | Yes | Yes | +| Authentication: browser, device-code, service principal, env, managed identity | Yes | Yes | +| Connect to local SSAS instance (TCP transport) | Yes | **No** | +| Connect to Power BI Desktop (named-pipe transport) | Yes | **No** | + +> [!IMPORTANT] +> Local SSAS and Power BI Desktop connections rely on Windows-only transport protocols. All cloud-based workflows (Power BI Service, Fabric, Azure Analysis Services) work on every platform. + +## Updating + +To update to a newer preview build, download the latest archive and overwrite the previous installation. Configuration and cached credentials are stored outside the install folder (see and ) and are preserved across updates. + +## Uninstalling + +1. Delete the install folder. +2. Remove the PATH entry. +3. (Optional) Clear cached credentials and config: + - Run `te auth logout` first - it removes all cached tokens and SPN records from the active backend (OS keystore or file fallback). + - Delete `~/.config/te/` (config and saved profiles). + - Delete `~/.te-cli/` (residual cache files; only present when the file fallback was in use, or as legacy from older CLI builds). + - To also purge the OS-native keystore entries - usually unnecessary, since `te auth logout` already clears them - see: + - **Windows:** Credential Manager → Windows Credentials → entries named `com.tabulareditor.cli...` or `te-cli`. + - **Linux:** `secret-tool search Component te-cli` and `secret-tool clear ...`, or use seahorse. + - **macOS:** Keychain Access → search for `com.tabulareditor.cli`. + +## Next steps + +- @te-cli-auth - authenticate to Power BI, Fabric, or Azure Analysis Services. +- @te-cli-commands - full command reference. +- @te-cli-interactive - guided REPL mode. diff --git a/localizedContent/es/content/features/te-cli/te-cli-interactive.md b/localizedContent/es/content/features/te-cli/te-cli-interactive.md new file mode 100644 index 000000000..c264d93f0 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-interactive.md @@ -0,0 +1,98 @@ +--- +uid: te-cli-interactive +title: Interactive Mode +author: Peer Grønnerup +updated: 2026-05-12 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Interactive Mode + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +Interactive mode is a guided read-eval-print loop (REPL) for exploring a model from the terminal. It's the gentlest on-ramp for users who are new to command lines, and a convenient workspace for ad-hoc sessions against a single model. + +## Starting a session + +To Start a session run any of these commands: + +```bash +te interactive # Start and connect to a model later +te interactive ./model # Start with a local model +te interactive -s MyWorkspace -d MyModel # Start with a remote model +``` + +The session prints a welcome banner, shows the active model, and opens you at a model-aware prompt: + +![Tabular Editor CLI interactive mode session](~/content/assets/images/features/cli/cli-interactive-mode.png) + +If no model is set, the prompt is just `te>` - simply use `connect` for connection picker, `connect ` or `connect ` to connect to one. + +## Commands inside the session + +Once a REPL has started, every `te` subcommand is available **without the `te` prefix**: + +``` +ls tables +get "Sales/Revenue" -q expression +query -q "EVALUATE TOPN(5, 'Sales')" +bpa run --fail-on error +``` + +Each command accepts `--help` the same way it does outside the session: + +``` +deploy --help +``` + +## Quoting and DAX-style paths + +The REPL line splitter recognises the same quoting forms as [object paths](xref:te-cli-commands#object-paths) so DAX-shaped references are interpreted as a single argument: + +- `'...'` and `"..."` - single- and double-quoted segments. The quote characters are stripped, doubled quotes escape a literal occurrence. +- `[...]` - bracketed segment. **Brackets are preserved** in the resulting argument so a path like `'Internet Sales'[Sales Amount]` reaches the command as one token that the path parser can re-interpret as a DAX reference. Doubled closing brackets (`]]`) stay verbatim for the same reason. + +``` +get 'Internet Sales'[Sales Amount] # One argument, DAX form +get [Total Sales] # Lone-bracket model-wide lookup +ls 'Net Sales'/'Sales Amount' # Quoted segments with a slash separator +``` + +Unterminated groups absorb to end of line, so a stray opening quote or bracket fails with an explicit error rather than splitting silently. + +## Built-in REPL commands + +These are handled by the REPL itself, not the regular command tree: + +| Command | Purpose | +| ---------------------- | ------------------------------------------------- | +| `help` or `?` | List available commands. | +| `status` or `pwd` | Show the active model/connection. | +| `clear` or `cls` | Clear the screen. | +| `exit`, `quit`, or `q` | Exit interactive mode. | + +## Guided prompts + +When interactive mode is active, commands that need missing input prompt for it instead of failing. Running `auth` without a subcommand opens a picker for Login / Status / Logout; running `deploy` without `--force` shows a summary and asks for confirmation (`n` is the safe default). + +To disable prompts for a single command inside the session, pass `--non-interactive`. + +## When to use interactive vs. non-interactive + +- **Interactive mode** is best for exploration, learning the CLI, one-off bulk edits against a single model, and demos. +- **Non-interactive mode** (the default outside `te interactive`) is what you reach for when scripting, automating, or running in CI. See @te-cli-automation and @te-cli-cicd. + +The two share the same command tree - anything you run inside `te interactive` can be pasted into a shell script by prefixing it with `te`. + +## Related pages + +- @te-cli-commands - full command reference. +- @te-cli-auth - connect to workspaces and manage profiles. +- @te-cli-automation - when to leave interactive mode. diff --git a/localizedContent/es/content/features/te-cli/te-cli-limitations.md b/localizedContent/es/content/features/te-cli/te-cli-limitations.md new file mode 100644 index 000000000..0feb35178 --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-limitations.md @@ -0,0 +1,90 @@ +--- +uid: te-cli-limitations +title: Limitaciones conocidas +author: Peer Grønnerup +updated: 2026-05-20 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Limitaciones conocidas + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +En esta página se enumeran las limitaciones conocidas de la CLI de Tabular Editor (`te`) para que puedas planificar en consecuencia y evitar errores habituales. Se actualiza con cada versión; si encuentras un problema que no figura aquí, abre una incidencia en el repositorio público [TabularEditor/CLI](https://github.com/TabularEditor/CLI). + +> [!NOTE] +> Las limitaciones se agrupan por área. Cada entrada describe la restricción y, cuando existe, una solución alternativa o la alternativa recomendada compatible con la CLI. + +## Scripts + +La CLI ejecuta C# Scripts (`te script`) sobre el mismo objeto `Model` que usas en Tabular Editor 2 y 3, pero funciona como un host de consola sin interfaz gráfica. Todo lo que dependa de una interfaz de usuario de Windows Forms, de la selección del Explorador TOM o de un servicio en ejecución del lado de la interfaz (registro de macros, DAX Formatter en línea, Analizador VertiPaq en tiempo real) se comporta de forma diferente; por lo general, queda vacío, no hace nada o devuelve un error. + +| Limitación | Notas / Solución alternativa | +| -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **`System.Windows.Forms` no se ha cargado** | La CLI usa una compilación multiplataforma de `TOMWrapper` que elimina todo el código acoplado a WinForms; el ensamblado de WinForms nunca se carga en el AppDomain. Los scripts que hacen referencia a tipos de `System.Windows.Forms` (`MessageBox`, `Form`, selectores de archivos, cuadros de diálogo personalizados, …) no se pueden compilar. Reestructura cualquier interacción con la interfaz de usuario en argumentos del script, variables de entorno o stdin. | +| **`Selected.` devuelve un enumerable vacío** | `Selected.Tables`, `Selected.Measures`, `Selected.Columns`, `Selected.Hierarchies`, etc. no devuelven nada en la CLI: no hay error de compilación ni de ejecución; simplemente no hay filas. Sustituye por búsquedas explícitas: `Model.AllMeasures.Where(...)`, `Model.Tables["Sales"].Measures`, o pasa rutas de objetos mediante `te script --args`. | +| **`Selected.` genera un error en tiempo de ejecución** | `Selected.Table`, `Selected.Measure`, `Selected.Column`, `Selected.Hierarchy`, etc. devuelven un error porque requieren exactamente un objeto seleccionado de ese tipo y la selección de la CLI siempre está vacía. Haz referencia al objeto directamente, por ejemplo, `Model.Tables["Sales"]`. | +| **`Selected.ActivePerspectives` y `Selected.ActiveCulture`** | Siempre devuelven una colección vacía y `null`, respectivamente. Establece la perspectiva o la configuración regional explícitamente en el script si es necesario. | +| **Los cuadros de diálogo `Select` lanzan `NotSupportedException`** | `SelectTable`, `SelectColumn`, `SelectMeasure`, `SelectObject`, `SelectObjects` (y todas las sobrecargas) devuelven el siguiente error: _"Los cuadros de diálogo de selección de objetos … no están disponibles en los scripts de la CLI. Preselecciona el objeto por nombre o por ruta antes de ejecutar el script."_ Resuelve los objetivos de antemano a partir de los argumentos del script, la configuración o consultando el modelo. | +| **`Info` / `Warning` / `Error` / `Output` escriben en la consola** | Estos siguen funcionando, pero se envían a stdout/stderr en lugar de abrir un cuadro de diálogo. Nunca bloquean ni muestran un aviso para "ignorar más ventanas emergentes". Se pueden usar con seguridad en CI. | +| **`ShowPrompt(...)` siempre devuelve `Cancel`** | No es posible realizar una confirmación interactiva. Decide la respuesta de antemano mediante argumentos del script o la configuración. | +| **`SuspendWaitForm` / `WaitFormVisible` no hacen nada** | El indicador giratorio de "Please wait" es un elemento de la interfaz de TE3. `WaitFormVisible` es una bandera configurable sin efecto Visual, y `SuspendWaitForm` se ignora silenciosamente; los scripts existentes siguen compilando. | +| **`host.Macro(...)` / `CustomAction(...)` lanzan un error** | La CLI no carga `%APPDATA%/TabularEditor3/MacroActions.json`, por lo que invocar una macro desde dentro de un script devuelve un error. Inserta la lógica de la macro en línea o llama directamente al archivo de script subyacente de la macro. | +| **`table.GetCardinality()` / `column.GetTotalSize()` devuelven 0** | Los auxiliares de cardinalidad de VertiPaq dentro del script no tienen un VPA en vivo en el host de la CLI. Para obtener estadísticas de VPA, carga explícitamente un VPAX y usa `host.Vpa.*`, o ejecuta [`te vertipaq`](xref:te-cli-commands#vertipaq). | + +## Best Practice Analyzer + +| Limitación | Notas / Solución alternativa | +| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Las fuentes de reglas de BPA deben ser URL HTTPS o rutas de archivos locales** | Solo se aceptan las URL `https://` y las rutas de archivo locales sin esquema. `http://` se reconoce, pero se rechaza deliberadamente en tiempo de carga con un error claro; como las reglas de BPA son expresiones de reglas ejecutables, obtenerlas a través de un canal no autenticado supondría un riesgo de manipulación. Otros esquemas de URL (`file://`, `ftp://`, …) no se admiten. Se aplica tanto a `te bpa run --rules` como a la lista de reglas configurada mediante [`te config set`](xref:te-cli-commands#config-show--paths--init--set). | +| **La validación de las URL de las reglas se realiza en el gate, no en `te config set`** | Un error tipográfico como `http://` lo acepta `te config set` y solo sale a la luz cuando BPA se ejecuta realmente. Después de editar las fuentes de reglas configuradas, ejecuta `te bpa run` (o `te validate`) una vez para comprobar que cada URL se carga correctamente. | +| **`--rules` no desactiva las reglas integradas** | Cuando se pasa `te bpa run --rules `, las reglas proporcionadas sustituyen las entradas de [`bpa.rules`](xref:te-cli-commands#config-show--paths--init--set) y `TE_BPA_RULES` para esa invocación, pero los valores predeterminados integrados siguen cargándose también. Para ejecutar solo el archivo de reglas explícito, pasa también `--no-defaults`. | +| **No hay ninguna opción por invocación para omitir la configuración de `bpa.rules`** | Una vez configurado `bpa.rules`, cada `te bpa run` carga esas reglas además de las integradas. Actualmente no hay ninguna opción para omitir los archivos de reglas configurados en una sola ejecución. Solución alternativa: pasa `--rules ` explícitamente; esta opción sustituye por completo `bpa.rules` y `TE_BPA_RULES` para esa invocación. | + +## Validación + +| Limitación | Notas / Solución alternativa | +| ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **`te validate` no puede corregir automáticamente las infracciones de Code Action** | `te validate` genera un Report de infracciones de Code Action, pero no ofrece ningún parámetro de la CLI para aplicar la corrección sugerida. Aplica la corrección en Tabular Editor 3, o usa `te bpa run --fix` para el subconjunto de Code Actions que se solapan con las reglas de BPA. | + +## E/S del modelo + +| Limitación | Notas / Solución alternativa | +| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **`--serialization` no puede combinar una serialización con un contenedor PBIP** | La opción `--serialization` en [`te save`](xref:te-cli-commands#save) trata `bim`, `tmdl`, `te-folder` y `pbip` como mutuamente excluyentes, por lo que actualmente no se puede generar un contenedor PBIP alrededor de un modelo serializado con TMSL (`.bim`). Guarda TMDL dentro de un contenedor PBIP, o guarda `.bim` fuera de un contenedor PBIP. | + +## Autenticación + +| Limitación | Notas / Solución alternativa | +| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Solo una identidad almacenada en caché por método de autenticación** | La CLI almacena en caché una identidad UPN (interactiva) y una identidad SPN (entidad de servicio) a la vez. Cambiar a otro usuario o inquilino con el mismo método de autenticación requiere `te auth logout` y después volver a ejecutar `te auth login`, lo que invalida la caché anterior. | + +## Entrada en la línea de comandos + +| Limitación | Notas / Solución alternativa | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Las rutas de objetos DAX con espacios deben ir entre comillas del shell** | Cuando el nombre de una tabla o columna contiene espacios, toda la referencia al objeto DAX debe ir entre comillas del shell desde el terminal: `te get "'My Table'[My Column]"`. Sin las comillas externas, el shell divide la ruta en varios argumentos y el análisis sintáctico falla. Dentro de [`te interactive`](xref:te-cli-interactive) no se necesitan comillas del shell porque el REPL recibe la entrada sin procesar antes de que el shell la divida en argumentos. | + +## Paridad con TE2 + +| Limitación | Notas / Solución alternativa | +| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **`te schemacheck` todavía no se ha implementado** | La opción `-SC` / `-SCHEMACHECK` de TE2 no tiene hoy por hoy ningún equivalente en `te`; la detección de deriva del esquema con respecto a las Data source de origen está prevista para una versión futura. Consulta @te-cli-migrate para ver la tabla completa de equivalencias de opciones entre TE2 y `te`. | + +## Enviar un Report de una limitación no documentada + +Si algún comportamiento te sorprende y no aparece aquí, abre una incidencia en [TabularEditor/CLI](https://github.com/TabularEditor/CLI/issues) e incluye el comando que ejecutaste, la salida que viste y la salida que esperabas. Las limitaciones confirmadas se añaden a esta página en la siguiente versión. + +## Páginas relacionadas + +- @csharp-scripts - referencia completa de C# Script (UI y CLI). +- @script-helper-methods - lista de los métodos auxiliares de `ScriptHost` y su comportamiento en la CLI. +- @te-cli-commands - referencia completa de comandos de la CLI. +- @te-cli-automation - patrones para usar la CLI en scripts y canalizaciones. diff --git a/localizedContent/es/content/features/te-cli/te-cli-migrate.md b/localizedContent/es/content/features/te-cli/te-cli-migrate.md new file mode 100644 index 000000000..6ae97fa4f --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli-migrate.md @@ -0,0 +1,111 @@ +--- +uid: te-cli-migrate +title: Migrating from the TE2 Command Line +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Migrating from the TE2 Command Line + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +Teams with existing build pipelines that invoke `TabularEditor.exe` with TE2-style flags (`-S`, `-A`, `-D`, `-O`, `-C`, etc.) can adopt the new CLI incrementally. The Tabular Editor CLI accepts both command shapes: the new subcommand-based form (`te deploy`, `te bpa run`, …) and the legacy TE2 flag syntax, via a built-in compatibility layer. + +For the legacy TE2 Windows command-line reference, see @command-line-options. + +## How TE2 compatibility works + +TE2 compatibility mode is activated in any of three ways: + +1. **Binary name.** Rename `te` to `te2` (or symlink it) and the CLI runs in TE2-exact mode. This is the drop-in replacement path: swap `TabularEditor.exe` for `te2` in your existing pipeline and the same arguments work. +2. **Environment variable.** Set `TE_COMPAT=te2` before invoking `te` to force TE2 mode. +3. **Auto-detection.** If the first argument isn't a `te` subcommand (`load`, `deploy`, …) and at least one recognized TE2 flag appears somewhere in the argument list, the CLI auto-routes to TE2 mode. This means most existing TE2 invocations work without any changes. + +```bash +# All three are equivalent - each runs in TE2 mode +./te2 Model.bim -S fix.csx -D "localhost\tabular" MyDB -O +TE_COMPAT=te2 te Model.bim -S fix.csx -D "localhost\tabular" MyDB -O +te Model.bim -S fix.csx -D "localhost\tabular" MyDB -O +``` + +> [!NOTE] +> TE2 mode runs the same `Load → Scripts → Schema Check → Save → BPA → Deploy → TRX` pipeline as `TabularEditor.exe`, including context-sensitive flag behavior (e.g., `-S` after `-D` means `-SHARED`, not `-SCRIPT`). + +## The migrate command + +Use `te migrate` as a live reference for how TE2 flags map to the new CLI. It prints a colorized table of every known TE2 flag, its status (supported, renamed, planned), and the equivalent `te` command. + +```bash +te migrate # Full flag mapping table +te migrate -A # Look up a single flag +te migrate --output-format json # Machine-readable mapping +``` + +Refer to the output of the `te migrate` command for the current mapping that reflects the CLI version you have installed. + +## Flag mapping (curated subset) + +A non-exhaustive summary of the most commonly used flags. Run `te migrate` for the full list. + +| TE2 flag | New CLI equivalent | Notes | +| ------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `file` (positional) | `te ` or global `--model` | First positional arg on most commands. | +| `server`, `database` | `te connect ` or `te deploy ` | Server is no longer a global positional. | +| `-L` / `-LOCAL` | `te connect --local` | Windows only. | +| `-S` / `-SCRIPT` | `te script -s ` or `-e "code"` | Supports multiple scripts, inline code, and stdin. | +| `-A` / `-ANALYZE` | `te bpa run --rules ` | Supports `--fail-on`, `--fix`, multiple rule files. | +| `-AX` / `-ANALYZEX` | `te bpa run --rules ` (without `--model-rules`) | Excluding model-embedded rules is the new default. | +| `-B` / `-BIM` | `te save -o --serialization bim` | | +| `-F` / `-FOLDER` | `te save -o --serialization te-folder` | After `-D`, TE2's `-F` means `-FULL` - see `--deploy-full`. | +| `-TMDL` | `te save -o --serialization tmdl` | TMDL is the default save format. | +| `-D` / `-DEPLOY` | `te deploy ` | Separate command with named options. | +| `-O` / `-OVERWRITE` | (default) or `--create-only` to opt out | Overwrite is the default in the new CLI. | +| `-C` / `-CONNECTIONS` | `te deploy --deploy-connections` | | +| `-P` / `-PARTITIONS` | `te deploy --deploy-partitions` | | +| `-Y` / `-SKIPPOLICY` | `te deploy --deploy-partitions --skip-refresh-policy` | Requires `--deploy-partitions`. | +| `-SHARED` | `te deploy --deploy-shared-expressions` | After `-D`, TE2's `-S` means `-SHARED`. | +| `-R` / `-ROLES` | `te deploy --deploy-roles` | | +| `-M` / `-MEMBERS` | `te deploy --deploy-role-members` | | +| `-FULL` (after `-D`) | `te deploy --deploy-full` | Equivalent to overwrite + connections + partitions + shared + roles + role-members. | +| `-X` / `-XMLA ` | `te deploy ... --xmla ` | Use `-` for stdout. | +| `-V` / `-VSTS` | `--ci vsts` on `validate`, `bpa run`, `deploy` | Emits `##vso[...]` annotations to stderr. | +| `-G` / `-GITHUB` | `--ci github` | Emits `::error::` / `::warning::` annotations. | +| `-T` / `-TRX ` | `--trx ` on `validate`, `bpa run`, `test run` | VSTEST `.trx` file for Azure DevOps test publishing. | +| `-W` / `-WARN` | (default) | Warnings always reported in deploy results. | +| `-E` / `-ERR` | (default) | Deploy returns non-zero exit on DAX errors. | +| `-SC` / `-SCHEMACHECK` | _Not yet implemented._ | TE2 schema check connects to actual data sources. Different from `te validate` (DAX semantic validation, no data source connection). | +| `-L` / `-LOGIN ` (after `-D`) | `te auth login -u -p -t ` | Use service principal or env-based credentials. The login is cached, so subsequent commands acquire tokens silently - see @te-cli-auth. | + +## Migration playbook + +The recommended path from a TE2-based pipeline to the new CLI: + +1. **Drop-in replacement.** Replace `TabularEditor.exe` with `te` (or `te2`) in your existing pipeline. Verify the pipeline still runs - TE2 compatibility handles most invocations unchanged. +2. **Replace flags incrementally.** Convert one flag group at a time: + - Start with `-A` / `-AX` → `te bpa run` to pick up richer BPA output (`--fail-on`, `--fix`, `--trx`). + - Then `-D` → `te deploy` for fine-grained deploy control. + - Finally `-V` / `-G` → `--ci vsts` / `--ci github`. +3. **Switch to non-interactive CI flags.** Add `--non-interactive --ci ` to every `te` command and remove any `start /wait` wrappers - the new CLI is a regular console binary and doesn't need them. +4. **Adopt service principal auth.** Replace `-D -L ` with `te auth login -u ... -p ... -t ...` or an environment-credential pipeline step. See @te-cli-auth. + +## Important differences + +- **BPA gate on deploy.** `te deploy` now runs BPA as a pre-flight gate by default. Use `--skip-bpa` to preserve the old behavior, or `--fix-bpa` to auto-fix violations before deploy. See @te-cli-config. +- **Interactive confirmation on deploy.** `te deploy` prompts for confirmation by default (with `n` as the safe default answer). CI pipelines must pass `--force`. +- **Structured output.** Every command supports `--output-format json` for machine-readable output - see @te-cli-automation. +- **No `start /wait` needed.** The new CLI is a regular console binary; invoke it directly in shell scripts, PowerShell, and CI tasks. +- **Cross-platform.** The CLI runs on Windows, macOS, and Linux. Local SSAS and Power BI Desktop connections remain Windows-only. + +## Related pages + +- @command-line-options - the legacy TE2 command-line reference. +- @te-cli-commands - the new CLI's full command reference. +- @te-cli-cicd - pipeline examples for GitHub Actions and Azure DevOps. diff --git a/localizedContent/es/content/features/te-cli/te-cli.md b/localizedContent/es/content/features/te-cli/te-cli.md new file mode 100644 index 000000000..c3c43e33c --- /dev/null +++ b/localizedContent/es/content/features/te-cli/te-cli.md @@ -0,0 +1,112 @@ +--- +uid: te-cli +title: Tabular Editor CLI (Limited Public Preview) +author: Peer Grønnerup +updated: 2026-05-12 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Tabular Editor CLI (Limited Public Preview) + +The Tabular Editor CLI (`te`) is a cross-platform command-line interface for Power BI and Analysis Services semantic models. It runs on Windows, macOS, and Linux as a single self-contained executable and is based on the same foundation that powers Tabular Editor 3. + +With the Tabular Editor CLI you can inspect, edit, validate, deploy, refresh, and test semantic models from a terminal - against local TMDL or BIM files, Power BI Desktop, or semantic models in Fabric and Power BI Service workspaces. + +Unlike the Windows-only `TabularEditor.exe` command-line options (TE2) - which was designed primarily to automate C# scripts and macros from a desktop binary - `te` is a purpose-built, cross-platform CLI with structured output, predictable exit codes, and an interactive shell. This unlocks scenarios that our existing [TE2 CLI](xref:command-line-options) can't cover well: terminal-driven model work on macOS and Linux, AI agents driving model changes directly, and clean drop-in for any modern CI runner. + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +## Built for three audiences + +Three design pillars run through every command: + +- **Structured output** — JSON, CSV, TMDL, TMSL alongside default human-readable text. +- **Non-interactive mode** — a global `--non-interactive` flag that disables prompts and fails fast. +- **Clear errors** — written to stderr with predictable exit codes. + +Together they make the same binary work well for three very different audiences: + +- **Humans** - scripting bulk edits, exploring a model from the terminal, composing commands in shell pipelines. +- **AI agents** - token-lean JSON, machine-parseable error shapes, exit codes that signal success or failure without parsing stdout. +- **CI/CD pipelines** - non-interactive execution, GitHub Actions and Azure DevOps annotations, VSTEST-compatible test results. + +## What the CLI can do + +The CLI organizes more than 50 commands into 10 families. Each family maps to a concrete stage of the semantic-model lifecycle. + +See @te-cli-commands for a full command reference with syntax, options, and examples for each command. Click any example command in the table to jump straight to its reference entry. + +| Family | What it does | Example commands | +| ------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Model I/O](xref:te-cli-commands#model-io) | Load, save, convert, initialize models | [`te load`](xref:te-cli-commands#load), [`te save`](xref:te-cli-commands#save), [`te init`](xref:te-cli-commands#init) | +| [Model Editing](xref:te-cli-commands#model-editing) | Get/set properties, add/remove/move objects | [`te set`](xref:te-cli-commands#set), [`te add`](xref:te-cli-commands#add), [`te rm`](xref:te-cli-commands#rm), [`te mv`](xref:te-cli-commands#mv) | +| [Inspection](xref:te-cli-commands#inspection) | List objects, search, diff, dependency analysis | [`te ls`](xref:te-cli-commands#ls), [`te find`](xref:te-cli-commands#find), [`te diff`](xref:te-cli-commands#diff), [`te deps`](xref:te-cli-commands#deps) | +| [Analysis & Quality](xref:te-cli-commands#analysis-and-quality) | Validate, run BPA, format DAX, analyze storage | [`te validate`](xref:te-cli-commands#validate), [`te bpa run`](xref:te-cli-commands#bpa-run), [`te format`](xref:te-cli-commands#format), [`te vertipaq`](xref:te-cli-commands#vertipaq) | +| [Execution](xref:te-cli-commands#execution) | Run DAX queries, C# scripts, macros | [`te query`](xref:te-cli-commands#query), [`te script`](xref:te-cli-commands#script), [`te macro`](xref:te-cli-commands#macro) | +| [Deployment & Refresh](xref:te-cli-commands#deployment-and-refresh) | Deploy to workspace, trigger refresh, incremental refresh | [`te deploy`](xref:te-cli-commands#deploy), [`te refresh`](xref:te-cli-commands#refresh), [`te incremental-refresh`](xref:te-cli-commands#incremental-refresh) | +| [Testing](xref:te-cli-commands#testing) | Assertion tests, snapshots, A/B comparison | [`te test run`](xref:te-cli-commands#test-run) | +| [Connection & Authentication](xref:te-cli-commands#connection-and-auth) | Connect to workspaces, manage authentication and profiles | [`te connect`](xref:te-cli-commands#connect), [`te auth`](xref:te-cli-commands#auth-login--status--logout), [`te profile`](xref:te-cli-commands#profile-list--show--set--remove) | +| [Configuration](xref:te-cli-commands#configuration) | Settings and licensing | [`te config`](xref:te-cli-commands#config-show--paths--init--set) | +| [Shell](xref:te-cli-commands#shell) | Interactive mode, shell completions | [`te interactive`](xref:te-cli-commands#interactive), [`te completion`](xref:te-cli-commands#completion) | + +## Getting started + +1. **Sign up or sign in** at [tabulareditor.com](https://tabulareditor.com/download-tabular-editor-cli) with a Tabular Editor account. +2. **Download and install** - see @te-cli-install for Windows, macOS, and Linux instructions. +3. **Authenticate** - run `te auth login` to connect to Power BI or Fabric. See @te-cli-auth. +4. **Run your first command** - `te --help` lists every command; `te --help` shows detailed options. + +A first look at a live model takes two commands: + +```bash +te auth login +te ls -s MyWorkspace -d MyModel +``` + +![Tabular Editor CLI te ls example output](~/content/assets/images/features/cli/cli-command-ls.png) + +## Preview notice + +Every command prints a yellow preview banner on stderr by default: + +![Tabular Editor CLI preview notice banner](~/content/assets/images/features/cli/cli-preview-notice.png) + +To hide the preview notice, simply run: + +```bash +te config set hidePreviewNotice true +``` + +> [!WARNING] +> The banner reappears on every command within **14 days of the preview end date** (2026-09-30), regardless of `hidePreviewNotice`. This ensures you have visible warning before the CLI stops functioning. + +## License outlook + +During Limited Public Preview, the CLI does not require a license; you only need a Tabular Editor account to download it. At General Availability (GA) the CLI will require a license; pricing is still being finalized and will be announced ahead of GA. + +## Feedback and community + +During the preview, bug reports, feature requests, and general discussion happen in the public [TabularEditor/CLI](https://github.com/TabularEditor/CLI) repository on GitHub: + +- **Issues** - report bugs, request features, and track known problems. +- **Discussions** - ask questions, share feedback, and swap usage tips with other early adopters. + +The repository does not host the CLI source code; it exists to give the community a public place to reach us during the preview. + +## Next steps + +- @te-cli-install - download, install, verify. +- @te-cli-auth - authenticate to Power BI, Fabric, and Azure Analysis Services. +- @te-cli-commands - full command reference. +- @te-cli-config - configuration file and path overrides. +- @te-cli-interactive - guided REPL mode for new users. +- @te-cli-automation - structured output, scripting patterns for Python, PowerShell, and Bash. +- @te-cli-cicd - GitHub Actions and Azure DevOps pipeline examples. +- @te-cli-migrate - migrating from the Tabular Editor 2 command line. diff --git a/localizedContent/es/content/how-tos/scripting-dynamic-linq-vs-csharp.md b/localizedContent/es/content/how-tos/scripting-dynamic-linq-vs-csharp.md index 67083c45e..551543cc9 100644 --- a/localizedContent/es/content/how-tos/scripting-dynamic-linq-vs-csharp.md +++ b/localizedContent/es/content/how-tos/scripting-dynamic-linq-vs-csharp.md @@ -11,7 +11,7 @@ applies_to: full: true --- -# En qué se diferencia Dynamic LINQ de LINQ de C\\# +# En qué se diferencia Dynamic LINQ de LINQ de C\# Los C# Scripts usan LINQ estándar de C# con expresiones lambda. Las reglas de Best Practice Analyzer (BPA) y los filtros del árbol del Explorador usan [Dynamic LINQ](https://dynamic-linq.net/expression-language), un lenguaje de expresiones basado en cadenas con una sintaxis diferente. Este artículo es una guía de traducción entre ambos. diff --git a/localizedContent/es/content/how-tos/scripting-filter-query-linq.md b/localizedContent/es/content/how-tos/scripting-filter-query-linq.md index 1e15fdff5..ad3fac761 100644 --- a/localizedContent/es/content/how-tos/scripting-filter-query-linq.md +++ b/localizedContent/es/content/how-tos/scripting-filter-query-linq.md @@ -151,7 +151,7 @@ En las expresiones de reglas de BPA, la sintaxis difiere de la de LINQ en C#. Dy | --------------------------------------------- | ----------------------------------------------------------- | | `m.IsHidden` | `IsHidden` | | `m.DataType == DataType.String` | `DataType = "String"` | -| `&&` / \`\\ | `and` / `or` / `not` | +| `&&` / `\|\|` / `!` | `and` / `or` / `not` | | `==` / `!=` | `=` / `!=` o `<>` | | `table.Columns.Count(c => c.IsHidden)` | `Columns.Count(IsHidden)` | | `table.Medidas.Any(m => m.IsHidden)` | `Medidas.Any(IsHidden)` | diff --git a/localizedContent/es/content/references/preferences.md b/localizedContent/es/content/references/preferences.md index 5f4562805..8c13f1e8f 100644 --- a/localizedContent/es/content/references/preferences.md +++ b/localizedContent/es/content/references/preferences.md @@ -714,7 +714,7 @@ Define prefijos aceptables para nombres de variables (p. ej., `_`, `__`, `var_`, Define prefijos aceptables para nombres de columnas temporales (p. ej., `@`, `_`, `x`, `x_`). Las acciones de código sugerirán añadir estos prefijos a los nombres de columnas temporales que no sigan la convención. -## Editor SQL / Editor M / Editor de C\\\# +## Editor SQL / Editor M / Editor C\# ![Marcador de posición: captura de pantalla de las páginas de preferencias de los editores SQL/M/C#] diff --git a/localizedContent/es/content/security/terms.md b/localizedContent/es/content/security/terms.md new file mode 100644 index 000000000..e5133dcea --- /dev/null +++ b/localizedContent/es/content/security/terms.md @@ -0,0 +1,22 @@ +--- +uid: terms +title: Terms and Conditions +author: Søren Toft Joensen +updated: 2026-05-29 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + full: true + - product: TE CLI + full: true +--- + +# Terms and Conditions + +Please find the latest version of our terms and conditions below: + +- [Commercial Terms & Conditions](https://tabulareditor.com/commercial-terms) +- [Tabular Editor 3 EULA](https://tabulareditor.com/eula-te3) +- [Tabular Editor CLI EULA](https://tabulareditor.com/eula-cli) diff --git a/localizedContent/es/content/security/third-party-notices.md b/localizedContent/es/content/security/third-party-notices.md index 1e8a6dbdf..e36a2b673 100644 --- a/localizedContent/es/content/security/third-party-notices.md +++ b/localizedContent/es/content/security/third-party-notices.md @@ -379,11 +379,9 @@ Esta licencia regula el uso del software adjunto. Si usas el software, aceptas e ## Licencia para Snowflake.Data - ``` - Licencia Apache - Versión 2.0, enero de 2004 - http://www.apache.org/licenses/ - ``` + Licencia Apache + Versión 2.0, enero de 2004 + http://www.apache.org/licenses/ TÉRMINOS Y CONDICIONES PARA EL USO, LA REPRODUCCIÓN Y LA DISTRIBUCIÓN @@ -560,14 +558,14 @@ FIN DE LOS TÉRMINOS Y CONDICIONES APÉNDICE: Cómo aplicar la Licencia Apache a su trabajo. - Para aplicar la Licencia Apache a su trabajo, adjunte el siguiente - aviso estándar, sustituyendo los campos entre llaves "{}" - por su propia información identificativa. (No incluya - las llaves). El texto debe incluirse con la sintaxis de - comentario adecuada para el formato del archivo. También recomendamos que - el nombre del archivo o de la clase y la descripción de su finalidad se incluyan en la - misma "página impresa" que el aviso de copyright para facilitar - la identificación en archivos de terceros. + Para aplicar la Licencia Apache a su trabajo, adjunte el siguiente + aviso estándar, sustituyendo los campos entre llaves "{}" + por su propia información identificativa. (No incluya + las llaves). El texto debe incluirse con la sintaxis de + comentario adecuada para el formato del archivo. También recomendamos que + el nombre del archivo o de la clase y la descripción de su finalidad se incluyan en la + misma "página impresa" que el aviso de copyright para facilitar + la identificación en archivos de terceros. Copyright (c) 2017 Snowflake Computing Inc. Todos los derechos reservados. @@ -575,9 +573,7 @@ Con licencia bajo la Licencia Apache, Versión 2.0 (la "Licencia"); no podrá usar este archivo salvo en cumplimiento de la Licencia. Puede obtener una copia de la Licencia en - ``` - http://www.apache.org/licenses/LICENSE-2.0 - ``` + http://www.apache.org/licenses/LICENSE-2.0 Salvo que lo exija la legislación aplicable o se acuerde por escrito, el software distribuido bajo la Licencia se distribuye "TAL CUAL", @@ -589,11 +585,9 @@ las limitaciones bajo la Licencia. ## Licencia para Dynamic-LINQ.net - ``` - Licencia Apache - Versión 2.0, enero de 2004 - http://www.apache.org/licenses/ - ``` + Licencia Apache + Versión 2.0, enero de 2004 + http://www.apache.org/licenses/ TÉRMINOS Y CONDICIONES DE USO, REPRODUCCIÓN Y DISTRIBUCIÓN @@ -770,14 +764,14 @@ FIN DE LOS TÉRMINOS Y CONDICIONES APÉNDICE: Cómo aplicar la Licencia Apache a su obra. - Para aplicar la Licencia Apache a su obra, adjunte el siguiente - aviso estándar, con los campos entre corchetes "[]" - sustituidos por su propia información identificativa. (No incluya - los corchetes). El texto debe ir incluido en la sintaxis de - comentario adecuada para el formato del archivo. También recomendamos que - se incluya un nombre de archivo o de clase y una descripción del propósito en la - misma "página impresa" que el aviso de copyright, para facilitar - la identificación en archivos de terceros. + Para aplicar la Licencia Apache a su obra, adjunte el siguiente + aviso estándar, con los campos entre corchetes "[]" + sustituidos por su propia información identificativa. (No incluya + los corchetes). El texto debe ir incluido en la sintaxis de + comentario adecuada para el formato del archivo. También recomendamos que + se incluya un nombre de archivo o de clase y una descripción del propósito en la + misma "página impresa" que el aviso de copyright, para facilitar + la identificación en archivos de terceros. Copyright [2016] [Stef Heyenrath] @@ -785,9 +779,7 @@ Con licencia conforme a la Licencia Apache, Versión 2.0 (la "Licencia"); no podrá usar este archivo salvo en cumplimiento de la Licencia. Puede obtener una copia de la Licencia en - ``` - http://www.apache.org/licenses/LICENSE-2.0 - ``` + http://www.apache.org/licenses/LICENSE-2.0 Salvo que lo exija la legislación aplicable o se acuerde por escrito, el software distribuido bajo la Licencia se distribuye "TAL CUAL", diff --git a/localizedContent/es/content/tutorials/udfs.md b/localizedContent/es/content/tutorials/udfs.md index ac7a3bec6..7fa073a60 100644 --- a/localizedContent/es/content/tutorials/udfs.md +++ b/localizedContent/es/content/tutorials/udfs.md @@ -317,11 +317,12 @@ Tabular Editor 3 detecta automáticamente cualquier comentario y lo muestra corr ## Limitaciones -- Las UDFs son actualmente una funcionalidad en versión preliminar y pueden tener limitaciones en determinados escenarios de despliegue - No todos los entornos de Power BI admiten UDFs (requiere compilaciones específicas) - Las UDFs no pueden ser recursivas (llamarse a sí mismas) -- Las UDFs no admiten parámetros opcionales, parámetros con valores predeterminados ni sobrecarga de parámetros + +> [!NOTE] +> A partir de junio de 2026, las UDF están [disponibles de forma general](https://community.fabric.microsoft.com/t5/Power-BI-Updates-Blog/DAX-User-Defined-Functions-Generally-Available/ba-p/5185738). Como parte de esto, las UDF ahora admiten expresiones predeterminadas y parámetros opcionales. Sin embargo, Tabular Editor 3 muestra actualmente un mensaje de error incorrecto cuando se usa la sintaxis de la expresión predeterminada. Este problema se corregirá en nuestra próxima actualización de Tabular Editor 3. --- -Las UDFs en Tabular Editor 3 proporcionan una forma potente de crear código DAX reutilizable y fácil de mantener. Si sigues estas directrices y buenas prácticas, podrás crear una biblioteca de funciones que mejorará la coherencia de tu modelo y reducirá el tiempo de desarrollo. \ No newline at end of file +Las UDFs en Tabular Editor 3 proporcionan una forma potente de crear código DAX reutilizable y fácil de mantener. Si sigues estas directrices y buenas prácticas, podrás crear una biblioteca de funciones que mejorará la coherencia de tu modelo y reducirá el tiempo de desarrollo. diff --git a/localizedContent/zh/content/features/CSharpScripts/Advanced/script-add-databricks-metadata-descriptions.md b/localizedContent/zh/content/features/CSharpScripts/Advanced/script-add-databricks-metadata-descriptions.md index 57b515550..c5bca6a96 100644 --- a/localizedContent/zh/content/features/CSharpScripts/Advanced/script-add-databricks-metadata-descriptions.md +++ b/localizedContent/zh/content/features/CSharpScripts/Advanced/script-add-databricks-metadata-descriptions.md @@ -15,13 +15,13 @@ applies_to: ## 脚本用途 -本脚本为 Tabular Editor x Databricks 系列的一部分而创建。 在 Unity Catalog 中,可以为表和列添加描述性注释。 此脚本可复用这些信息,自动补全语义模型中的表和列说明。

+该脚本作为 Tabular Editor x Databricks 系列的一部分编写。 在 Unity Catalog 中,可以为表和列添加描述性注释。 此脚本可复用这些信息,自动补全语义模型中的表和列说明。

> [!NOTE] > 此脚本需要 Databricks ODBC 驱动程序。 我们推荐新版 [Databricks ODBC Driver](https://www.databricks.com/spark/odbc-drivers-download),它将取代旧版 Simba Spark ODBC Driver。 脚本会自动检测已安装的驱动程序,并据此使用相应驱动程序。 每次运行脚本时,都会提示你输入 Databricks 个人访问令牌。 这是用于向 Databricks 进行身份验证所必需的。 -该脚本会使用 Unity Catalog 中的 information_schema 表来检索关系信息,因此你可能需要向 Databricks 管理员再次确认,确保自己有权限查询这些表。

+该脚本会使用 Unity Catalog 中的 information_schema 表来获取关系信息,因此你可能需要与 Databricks 管理员再次确认,确保自己有权限查询这些表。

## 脚本 diff --git a/localizedContent/zh/content/features/CSharpScripts/Advanced/script-create-databricks-relationships.md b/localizedContent/zh/content/features/CSharpScripts/Advanced/script-create-databricks-relationships.md index 8cca4dd29..e3fefe785 100644 --- a/localizedContent/zh/content/features/CSharpScripts/Advanced/script-create-databricks-relationships.md +++ b/localizedContent/zh/content/features/CSharpScripts/Advanced/script-create-databricks-relationships.md @@ -21,7 +21,7 @@ applies_to: > 此脚本需要 Databricks ODBC 驱动程序。 我们推荐使用新版 [Databricks ODBC Driver](https://www.databricks.com/spark/odbc-drivers-download),它将取代旧版 Simba Spark ODBC Driver。 该脚本会自动检测已安装的驱动程序,并自动使用相应的驱动程序。 每次运行该脚本时,都会提示用户输入 Databricks 个人访问令牌。 这用于对 Databricks 进行身份验证。 -该脚本使用 Unity Catalog 中的 information_schema 表来检索关系信息,因此你可能需要向 Databricks 管理员再次确认,确保自己有权限查询这些表。

+该脚本会使用 Unity Catalog 中的 information_schema 表来检索关系信息,因此您可能需要再与 Databricks 管理员确认一下,确保您有权限查询这些表。

## 脚本 diff --git a/localizedContent/zh/content/features/Semantic-Model/direct-lake-sql-model.md b/localizedContent/zh/content/features/Semantic-Model/direct-lake-sql-model.md index 3c5956055..4e38be0e0 100644 --- a/localizedContent/zh/content/features/Semantic-Model/direct-lake-sql-model.md +++ b/localizedContent/zh/content/features/Semantic-Model/direct-lake-sql-model.md @@ -22,10 +22,10 @@ applies_to: SQL 语义模型上的 Direct Lake 可通过 SQL 端点直接连接到存储在 [Fabric 中的 OneLake](https://learn.microsoft.com/en-us/fabric/onelake/onelake-overview) 中的数据源。 > [!IMPORTANT] -> 自 [Tabular Editor 3.22.0](../../references/release-notes/3_22_0.md) 起,Tabular Editor 3 已支持 OneLake 上的 Direct Lake,并在大多数场景下建议使用。 更多信息请参阅我们的 [Direct Lake 指南](xref:direct-lake-guidance)。 +> 自 [Tabular Editor 3.22.0](../../references/release-notes/3_22_0.md) 起,Tabular Editor 3 支持在 OneLake 上使用 Direct Lake,且在大多数情况下建议采用此方式。 更多信息请参阅我们的 [Direct Lake 指南](xref:direct-lake-guidance)。 -Tabular Editor 3 可以创建并连接此类模型。 如需教程,请参阅我们的博客文章:[Direct Lake 语义模型:如何在 Tabular Editor 中使用](https://blog.tabulareditor.com/2023/09/26/fabric-direct-lake-with-tabular-editor-part-2-creation/)。 -Tabular Editor 3 可以通过 Lakehouse 和 Warehouse 的 SQL 端点创建 Direct Lake 语义模型。 +Tabular Editor 3 可以创建并连接此类模型。 有关本主题的教程,请参阅我们的博客文章:[Direct Lake 语义模型:如何在 Tabular Editor 中使用它们](https://blog.tabulareditor.com/2023/09/26/fabric-direct-lake-with-tabular-editor-part-2-creation/)。 +Tabular Editor 3 可以通过 Lakehouse 和 Warehouse SQL Endpoint 创建 Direct Lake 语义模型。 Tabular Editor 2 可以连接到 Direct Lake 语义模型,但不提供用于创建新表或 Direct Lake 语义模型的内置功能。 这需要手动完成,或使用 C# Script 来实现。 @@ -42,27 +42,27 @@ Tabular Editor 2 可以连接到 Direct Lake 语义模型,但不提供用于 使用该复选框可确保设置 Direct Lake 特有的属性与注释,并将表的导入限制为 Direct Lake 支持的数据源。 > [!NOTE] -> SQL 上的 Direct Lake 模型目前使用的排序规则与常规 Power BI 导入语义模型所用的不同。 这可能会导致在查询模型或在 DAX 代码中引用对象名称时得到不同的结果。 +> 基于 SQL 的 Direct Lake 模型当前使用的排序规则与常规 Power BI 导入语义模型不同。 这可能会导致在查询模型或在 DAX 代码中引用对象名称时得到不同的结果。 > 更多信息见 Kurt Buhler 的这篇博文:[Power BI 中区分大小写的模型:影响与注意事项](https://data-goblins.com/power-bi/case-specific)。 > [!IMPORTANT] -> 从 [Tabular Editor 3.22.0](../../references/release-notes/3_22_0.md) 开始,“新建模型”对话框中已移除 Direct Lake 复选框。 如果在 SQL 上使用 Direct Lake,则必须[手动将模型的排序规则设置为与 Fabric Warehouse 的排序规则一致](xref:direct-lake-guidance#collation)。 +> 从 [Tabular Editor 3.22.0](../../references/release-notes/3_22_0.md) 开始,“新建模型”对话框中已移除 Direct Lake 复选框。 如果在 SQL 上使用 Direct Lake,你必须[手动将模型的排序规则设置为与 Fabric Warehouse 的排序规则一致](xref:direct-lake-guidance#collation)。 ## 为新模型和表导入设定框架 -Tabular Editor 3(3.15.0 或更高版本)会在首次部署时自动对模型执行框架化(刷新)。 这是为了确保 Direct Lake 模式已启用——否则模型会自动回退到 DirectQuery。 +Tabular Editor 3(3.15.0 或更高版本)会在首次部署时自动对模型执行框架化(刷新)。 这是为了确保启用 Direct Lake 模式;否则模型会自动回退到 DirectQuery。 -此外,导入新表后,Tabular Editor 3(3.15.0 或更高版本)会在下一次保存时对模型执行框架化(刷新)。 该首选项位于 **Tools > Preferences > Model Deployment > Data Refresh** 下。 +此外,在导入新表后,Tabular Editor 3(3.15.0 或更高版本)会在你下次保存模型时对模型进行 framing(刷新)。 该首选项位于 **Tools > Preferences > Model Deployment > Data Refresh** 下。 ## 识别 Direct Lake 模型 -Tabular Editor 顶部标题栏会显示该 Tabular Editor 实例当前打开的模型类型。 此外,TOM Explorer 会显示每张表的类型和模式(Import、DirectQuery、Dual 或 Direct Lake)。 如果模型混用了多种表模式,标题栏将显示“混合”。 目前,Direct Lake on SQL 模型无法包含处于 Import、DirectQuery 或 Dual 模式的表。 +Tabular Editor 顶部的标题栏会显示该 Tabular Editor 实例中当前打开的是哪种类型的模型。 此外,TOM Explorer 会显示每张表的类型和模式(Import、DirectQuery、Dual 或 Direct Lake)。 如果模型混用了多种表模式,标题栏将显示“混合”。 目前,Direct Lake on SQL 模型无法包含处于 Import、DirectQuery 或 Dual 模式的表。 ## 将 Direct Lake 模型转换为导入模式 -下面的 C# Script 会将现有模型转换为导入模式。 如果你的模型对数据延迟的要求并不需要 Direct Lake,或者你想避开 Direct Lake 模型的限制,但已经在 Fabric 中开始构建该模型,那么这会很有用。 +下面的 C# Script 会将现有模型转换为导入模式。 如果你的模型对数据延迟的要求不高,无需 Direct Lake,或者你想避开 Direct Lake 模型的限制,但已经在 Fabric 中开始构建 Direct Lake 模型,那么这会很有用。 -当 Tabular Editor 通过 XMLA endpoint 连接到语义模型时,即可运行该脚本。 不过,Microsoft 不支持直接将更改保存回 Power BI/Fabric Workspace。 为规避这一限制,建议使用“Model > Deploy...”选项。 这样就可以将新转换的模型作为 Workspace 中的一个新实体进行部署。 +当 Tabular Editor 通过 XMLA endpoint 连接到语义模型后,即可运行该脚本。 不过,Microsoft 不支持直接将更改保存回 Power BI/Fabric Workspace。 为规避这一限制,建议使用“Model > Deploy...”选项。 这样就可以将新转换的模型作为 Workspace 中的一个新实体进行部署。 > [!NOTE] > 部署新转换的导入模式模型后,你需要指定用于访问 Lakehouse 的凭据,才能将数据刷新到模型中。 diff --git a/localizedContent/zh/content/features/Semantic-Model/semantic-model-types.md b/localizedContent/zh/content/features/Semantic-Model/semantic-model-types.md index 2b1f8b4b1..348341866 100644 --- a/localizedContent/zh/content/features/Semantic-Model/semantic-model-types.md +++ b/localizedContent/zh/content/features/Semantic-Model/semantic-model-types.md @@ -19,7 +19,7 @@ applies_to: # 语义模型类型 -Tabular Editor 可与多种不同的模型类型配合使用。 下面概述了哪些模型类型可与 Tabular Editor 配合使用,以及每种模型类型可用的功能。 +Tabular Editor 支持多种不同的模型类型。 下面概述了哪些模型类型可与 Tabular Editor 一起使用,以及每种模型类型可使用哪些功能。 | 模型类型 | 导入 | DirectQuery | OneLake 上的 Direct Lake | SQL 上的 Direct Lake | .pbix | .pbip | | -------------------------------------- | -- | ----------- | --------------------------------------- | ------------------------------------------ | --------------------- | --------------------- | @@ -60,7 +60,7 @@ Tabular Editor 可与多种不同的模型类型配合使用。 下面概述了 > 2025 年六月发布的 Power BI Desktop 版本已解除对第三方工具的所有建模限制。 在此之前,许多建模操作都不受支持。 见 [Power BI Desktop 限制](xref:desktop-limitations)。 > [!TIP] -> 有关 Direct Lake 模型限制的更多详细信息,请参阅 Microsoft 的 [Direct Lake 文档](https://learn.microsoft.com/en-us/fabric/fundamentals/direct-lake-overview) +> 如需了解 Direct Lake 模型限制的更多详细信息,请参阅 Microsoft 的 [Direct Lake 文档](https://learn.microsoft.com/en-us/fabric/fundamentals/direct-lake-overview) ## 不受支持的语义模型类型 diff --git a/localizedContent/zh/content/features/Useful-script-snippets.md b/localizedContent/zh/content/features/Useful-script-snippets.md index 9057ab04b..c2a1ee247 100644 --- a/localizedContent/zh/content/features/Useful-script-snippets.md +++ b/localizedContent/zh/content/features/Useful-script-snippets.md @@ -19,7 +19,7 @@ applies_to: # 实用脚本片段 -这里汇总了一些简短的脚本片段,帮助你快速上手 Tabular Editor 的 [高级脚本功能](/Advanced-Scripting)。 其中很多脚本都适合保存为 [自定义操作](/Custom-Actions),这样你就可以通过上下文菜单轻松复用它们。' +这里汇总了一些小脚本片段,帮助你快速上手 Tabular Editor 的 [高级脚本功能](/Advanced-Scripting)。 其中很多脚本都适合保存为 [自定义操作](/Custom-Actions),这样你就可以通过上下文菜单轻松复用它们。' 另外,也别忘了看看我们的脚本库 @csharp-script-library,里面有更多贴近实际场景的示例,展示了你可以如何利用 Tabular Editor 的脚本功能。 @@ -57,7 +57,7 @@ foreach(var c in Selected.Columns) ## 生成时间智能度量值 -首先,为各个时间智能聚合分别创建自定义操作。 例如: +首先,为每项时间智能聚合创建自定义操作。 例如: ```csharp // 为每个选中的度量值创建一个 TOTALYTD 度量值。 diff --git a/localizedContent/zh/content/features/ai-assistant.md b/localizedContent/zh/content/features/ai-assistant.md index 810693019..051c02060 100644 --- a/localizedContent/zh/content/features/ai-assistant.md +++ b/localizedContent/zh/content/features/ai-assistant.md @@ -20,12 +20,12 @@ applies_to: # AI 助手 -AI 助手是一款基于聊天的界面,面向 AI 辅助的语义模型开发,旨在帮助你更快地创建语义模型。 它采用企业级设计,可让你完全掌控发送给 AI 的内容,并内置同意管理,让你可以放心使用 AI 助手。 AI 助手已通过独立的安全渗透测试。 详情请访问 [Tabular Editor 信任中心](https://trust.tabulareditor.com)。 它可以浏览模型元数据、编写并执行 DAX 查询、生成 C# Script、运行 Best Practice Analyzer 检查、查询 VertiPaq分析器统计信息,并搜索 Tabular Editor 知识库。 +AI 助手是一款基于聊天的界面,面向 AI 辅助的语义模型开发,旨在帮助你更快创建语义模型。 它采用企业级设计,可让你完全掌控发送给 AI 的内容,并内置同意管理,让你可以放心使用 AI 助手。 AI 助手已通过独立的安全渗透测试。 详情请访问 [Tabular Editor 信任中心](https://trust.tabulareditor.com)。 它可以浏览模型元数据、编写并执行 DAX 查询、生成 C# Script、运行 Best Practice Analyzer 检查、查询 VertiPaq分析器统计信息,并搜索 Tabular Editor 知识库。 AI 助手采用自带密钥 BYOK 模式。 你只需从受支持的提供商中选择一个并提供其 API 密钥,助手就会直接通过该提供商的 API 运行。 > [!NOTE] -> AI 助手自 Tabular Editor 3.26.0 起处于公开预览阶段。 我们欢迎你反馈使用体验,帮助我们持续改进。 +> 从 Tabular Editor 3.26.0 开始,AI 助手处于公共预览阶段。 我们欢迎你反馈使用体验,帮助我们持续改进。 ![AI Assistant First Pane on Open](~/content/assets/images/ai-assistant/ai-assistant-panel-first-open.png) @@ -63,7 +63,7 @@ AI 助手采用自带密钥 BYOK 模式。 你只需从受支持的提供商中 ### Anthropic -选择 **Anthropic** 作为提供商,然后输入你的 API 密钥。 默认模型是 **claude-sonnet-4-6**。 你可以将模型名称更改为你账号下可用的任意 Anthropic 模型。 +选择 **Anthropic** 作为提供商,然后输入你的 API 密钥。 默认模型是 **claude-sonnet-4-6**。 你可以将模型名称更改为你账户中可用的任意 Anthropic 模型。 ![AI 助手 Anthropic 配置](~/content/assets/images/ai-assistant/ai-assistant-anthropic-config.png) @@ -144,7 +144,7 @@ az cognitiveservices account deployment list --name "" --resource > 本地模型的响应质量取决于模型规模以及你的硬件配置。 更大的模型通常能产生更好的结果,但需要更多 RAM 和性能更强的 GPU。 AI Assistant 的工具调用能力需要使用支持 OpenAI 兼容格式函数调用的模型。 > [!TIP] -> 我们建议选择参数量_至少_为 30 十亿、理想情况下至少为 100 十亿的模型。 例如,Qwen3.5-122B-A10B 模型在我们的内部测试中表现良好。 +> 我们建议选择参数量_至少_为 30B 的模型,但理想情况下至少应有 100B 参数。 例如,Qwen3.5-122B-A10B 模型在我们的内部测试中表现良好。 ### 使用 Microsoft Foundry @@ -187,7 +187,7 @@ AI 助手可以访问你的模型上下文,并能执行以下操作: - **模型探索**:查询模型元数据,包括表、列、度量值、关系及其属性 - **DAX 查询编写**:生成 DAX 查询并对你在连接模式下连接的模型执行,结果集会直接在聊天中返回 -- **C# 脚本生成**:生成用于修改模型的 C# Script,并在新的编辑器窗口中打开。 当你在聊天中点击 **Execute** 时,默认会显示 [预览更改](xref:csharp-scripts#running-scripts-with-preview) 对话框,让你在接受前先审阅所有模型元数据更改。 你也可以在编辑器中打开脚本,并从脚本工具栏运行它,可选择是否启用预览。 模型元数据更改可通过 **Ctrl+Z** 撤销 +- **C# Script 生成**:创建用于修改模型的 C# Script,并在新的编辑器窗口中打开。 当你在聊天中点击 **Execute** 时,默认会显示 [预览更改](xref:csharp-scripts#running-scripts-with-preview) 对话框,让你在接受前先审阅所有模型元数据更改。 你也可以在编辑器中打开脚本,并从脚本工具栏运行它,可选择是否启用预览。 模型元数据更改可通过 **Ctrl+Z** 撤销 - **Best Practice Analyzer**:运行 BPA 分析,查看规则违规情况,并创建或修改 BPA 规则 - **VertiPaq分析器**:查询内存使用统计信息和列的基数 - **文档访问**:读取并修改已打开的文档,例如 DAX 脚本和 DAX 查询 @@ -199,7 +199,7 @@ AI 助手可以访问你的模型上下文,并能执行以下操作: ## 对话 -AI 助手支持多个并行对话。 每个对话都会维护各自的信息历史记录和上下文。 +AI 助手支持多个同时进行的对话。 每个对话都会维护各自的信息历史记录和上下文。 - 对话会跨会话保留,并存储在本地的 `%LocalAppData%\TabularEditor3\AI\Conversations\` 中 - 标题会在首次交流后自动生成。 你可以手动重命名对话 @@ -216,13 +216,13 @@ AI 助手支持多个并行对话。 每个对话都会维护各自的信息历 ![AI Assistant Generate C# Script](~/content/assets/images/ai-assistant/ai-assistant-generate-c-sharp-script.png) -当你在聊天中执行 C# Script 时,**脚本预览**对话框会并排显示该脚本对模型元数据所做的所有更改的差异对比。 你可以接受这些更改,或将其撤销。 详见[使用预览运行脚本](xref:csharp-scripts#run-c-scripts-with-preview)。 +当你从聊天中执行 C# Script 时,**脚本预览**对话框会并排显示该脚本对模型元数据所做的所有更改的差异对比。 你可以接受这些更改,或将其撤销。 详见[使用预览运行脚本](xref:csharp-scripts#run-c-scripts-with-preview)。 ![脚本预览 - 模型更改](~/content/assets/images/preview-script-changes.png) ## 自定义指令 -自定义指令是一组指令,用于引导 AI 助手在特定任务中的行为。 它们会根据意图识别自动启用,也可以手动调用。 +自定义指令是一组用于在特定任务中引导 AI 助手行为的指令。 它们会根据意图识别自动启用,也可以手动调用。 ### 内置自定义指令 @@ -247,7 +247,7 @@ AI 助手包含以下内置自定义指令: ### 添加自己的自定义指令 -你可以通过将 `.md` 文件放到 `%LocalAppData%\TabularEditor3\AI\CustomInstructions\` 来创建自定义指令。 每个文件都需要包含 YAML front matter,用于定义指令的元数据: +你可以将 `.md` 文件放到 `%LocalAppData%\TabularEditor3\AI\CustomInstructions\` 中,以创建自定义指令。 每个文件都需要包含 YAML front matter,用于定义指令的元数据: ```yaml --- @@ -287,7 +287,7 @@ triggers: ## 同意 -AI 助手在向 AI 提供商发送数据之前会先征求你的同意。 同意按特定数据类型进行限定: +AI 助手在将数据发送给 AI 提供商之前会先请求你的许可。 同意按特定数据类型进行限定: | 同意类别 | 说明 | | --------- | ------------------------------- | @@ -298,7 +298,7 @@ AI 助手在向 AI 提供商发送数据之前会先征求你的同意。 同意 | 编辑 BPA 规则 | 创建或修改 Best Practice Analyzer 规则 | | 读取宏 | 读取宏定义 | -当 AI 助手首次需要访问某种数据类型时,将弹出同意对话框。 你可以选择同意的持续时间: +当 AI 助手首次需要访问某种数据类型时,会显示一个同意对话框。 你可以选择同意的持续时间: | 选项 | 范围 | | ---- | --------------------------------------------------------- | @@ -311,7 +311,7 @@ AI 助手在向 AI 提供商发送数据之前会先征求你的同意。 同意 ### 管理同意项 -你可以在 **Tools > 偏好 > AI Assistant > AI Consents** 中查看并重置你的同意选项。 每个同意类别都会显示其当前状态。 点击 **Reset** 可撤销处于“Always allowed”状态的同意,并将其恢复为“Ask when needed”。 +你可以在 **工具 > 偏好 > AI 助手 > AI 同意** 中查看并重置你的同意选择。 每个同意类别都会显示其当前状态。 点击 **Reset** 可撤销处于“Always allowed”状态的同意,并将其恢复为“Ask when needed”。 ![AI Assistant Consent Settings](~/content/assets/images/ai-assistant/ai-assistant-consent-reset.png) @@ -376,7 +376,7 @@ AI 助手在向 AI 提供商发送数据之前会先征求你的同意。 同意 ## 局限性 -- 需要你自行提供 API 密钥。 不包含内置 API 密钥 +- 需要用户提供 API 密钥。 不包含内置 API 密钥 - AI 的响应取决于所选模型及提供商的能力 - 最大上下文窗口为 200,000 个 token - AI 助手不能替代你对 DAX 和语义模型设计基础的理解 diff --git a/localizedContent/zh/content/features/code-actions.md b/localizedContent/zh/content/features/code-actions.md index fc9cb88aa..f5c5a0a8b 100644 --- a/localizedContent/zh/content/features/code-actions.md +++ b/localizedContent/zh/content/features/code-actions.md @@ -22,7 +22,7 @@ applies_to: Tabular Editor 3.18.0 引入了一项名为 **代码操作** 的新功能。 该功能默认启用,但你可以在 **工具 > 偏好** 对话框中,依次进入 **文本编辑器 > DAX编辑器 > 代码操作** 将其禁用。 -代码操作是一项提升效率的功能,会在不打扰你的情况下,为你提供改进 DAX 代码的建议。 你只需单击一次即可应用这些建议。 代码操作还让你能轻松执行常见的代码重构操作。 +代码操作是一项提升效率的功能,会以低干扰的方式提供改进 DAX 代码的建议。 你只需单击一次即可应用这些建议。 代码操作还让你能轻松执行常见的代码重构操作。 代码操作分为三个不同的类别: @@ -35,14 +35,14 @@ Tabular Editor 3.18.0 引入了一项名为 **代码操作** 的新功能。 该 - 在可能的情况下简化复杂表达式 - 删除冗余或不必要的代码 - 应用一致的格式和命名规范 -3. **重写**:这些是用于重构 DAX 代码的建议。 它们不一定是改进,但在进行较大规模的代码重构时通常很有用。 示例包括: +3. **重写**:这类建议用于重构你的 DAX 代码。 它们不一定是改进,但在进行较大规模的代码重构时通常很有用。 示例包括: - 将 DAX “语法糖”改写为更冗长但更明确的代码 - 重命名某个变量或扩展列的所有出现位置 - 格式化代码 ## 如何使用代码操作 -新增了 **显示代码操作** 命令及其对应的工具栏/菜单按钮,默认键盘快捷键为 `Ctrl+.`。 这个命令会显示当前光标位置可用的代码操作: +新增了命令 **显示代码操作** 及其对应的工具栏/菜单按钮,默认快捷键为 `Ctrl+.`。 这个命令会显示当前光标位置可用的代码操作: ![代码操作调用菜单](~/content/assets/images/features/code-action-invoke-menu.png) @@ -50,7 +50,7 @@ Tabular Editor 3.18.0 引入了一项名为 **代码操作** 的新功能。 该 ![代码操作重构子菜单](~/content/assets/images/features/code-action-refactor-submenu.png) -最后,当光标位于包含可用操作的代码分段上时,编辑器左侧边距会显示灯泡或螺丝刀图标。 点击该图标也会打开代码操作菜单: +最后,当光标位于有适用操作的代码分段上时,编辑器左侧边距会显示灯泡或螺丝刀图标。 点击该图标也会打开代码操作菜单: ![代码操作边距](~/content/assets/images/features/code-action-margin.png) @@ -60,15 +60,15 @@ Tabular Editor 3.18.0 引入了一项名为 **代码操作** 的新功能。 该 ## 代码操作指示器 -在代码编辑器中,**改进** 和 **可读性** 代码操作也会以视觉标识显示。 这样你就能快速判断代码中哪些部分可以改进,或提升可读性。 +在代码编辑器中,**改进** 和 **可读性** 代码操作也会以视觉标识显示。 这让你可以快速判断代码中哪些部分还能改进,或变得更易读。 -- **改进** 会以橙色圆点显示在代码分段前几个字符的下方(除非该代码分段已显示橙色警告波浪线)。 当光标移到该代码分段上时,左侧边距会显示一个 _灯泡_ 图标。 -- **可读性** 操作会以蓝绿色圆点显示在代码分段前几个字符的下方。 当光标移到该代码分段上时,左侧边距会显示一个 _螺丝刀_ 图标。 +- **改进**会在代码分段开头的前几个字符下方以橙色圆点标示(除非该代码分段已显示橙色警告波浪线)。 当光标移到该代码分段上时,左侧边距会显示一个 _灯泡_ 图标。 +- **可读性**操作会在代码分段前几个字符下方显示蓝绿色圆点。 当光标移到该代码分段上时,左侧边距会显示一个 _螺丝刀_ 图标。 - **重写**本身不会在代码中显示任何视觉标记;但当光标放在包含可用重写的代码分段上时,左侧边距会出现 _螺丝刀_ 图标。 ## 应用到所有出现处 -某些代码操作可应用于当前 DAX 表达式、DAX 脚本或 DAX 查询中的所有出现位置,而不仅仅是光标下的代码分段。 在这种情况下,该代码操作会显示在“代码操作”菜单中,并在操作描述后追加 " (All occurrences)"。 点击该操作后,将把更改应用于文档中的所有出现处。 +某些代码操作可以应用于当前 DAX 表达式、DAX 脚本或 DAX 查询中的所有出现位置,而不只是光标所在的代码分段。 在这种情况下,该代码操作会显示在“代码操作”菜单中,并在操作描述后追加 " (All occurrences)"。 点击该操作后,将把更改应用于文档中的所有出现处。 例如,在下方截图中,**为变量添加“_”前缀**这个操作可以应用到文档中的所有出现位置(即所有变量),而不只是光标所在的 `totalSales` 变量: @@ -84,45 +84,45 @@ Tabular Editor 3.18.0 引入了一项名为 **代码操作** 的新功能。 该 以下代码操作会在适用代码的前两个字符下方显示橙色圆点;当光标位于该代码分段上时,左侧边距还会出现灯泡图标: -| ID | 名称 | 描述 | -| ----- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| DI001 | [删除未使用的变量](xref:DI001) | 应删除未在任何地方被引用的变量。 示例:
`VAR a = 1 VAR b = 2 RETURN a` -> `VAR a = 1 RETURN a` | -| DI002 | [删除所有未使用的变量](xref:DI002) | 应删除 VAR 变量块中在 `RETURN` 部分未被使用的变量(无论直接使用还是通过其他变量间接使用)。 示例:
`VAR a = 1 VAR b = a RETURN 123` -> `123` | -| DI003 | [移除表名](xref:DI003) | 度量值引用中不应包含表名,因为引用度量值时表名是多余的。 此外,这样做也能让度量值引用与列引用更容易区分。 示例:
`Sales[Total Sales]` -> `[Total Sales]` | -| DI004 | [添加表名](xref:DI004) | 列引用应包含表名,以避免歧义,并让列引用与度量值引用更容易区分。 示例:
`SUM([SalesAmount])` -> `SUM(Sales[SalesAmount])` | -| DI005 | [将表筛选 FILTER 重写为标量谓词](xref:DI005) | DAX 中一种常见的反模式是:在 [`CALCULATE`](https://dax.guide/CALCULATE) 的筛选参数中使用 `FILTER` 对整张表进行筛选,而实际上只需筛选该表中的一个或多个列即可。 示例:
`CALCULATE([Total Sales], FILTER(Products, Products[Color] = "Red"))` -> `CALCULATE([Total Sales], KEEPFILTERS(Products[Color] = "Red"))`
此代码操作支持原始表达式的多种变体。 | -| DI006 | [将多列筛选拆分为多个筛选](xref:DI006) | 当使用 `AND`(或等效的 `&&` 运算符)将多个列组合起来筛选表时,通常可通过为每一列分别指定筛选条件来获得更好的性能。 示例:
`CALCULATE(..., Products[Color] = "Red" && Products[Size] = "Large")` -> `CALCULATE(..., Products[Color] = "Red", Products[Size] = "Large")` | -| DI007 | [简化 SWITCH 语句](xref:DI007) | 对于 [`SWITCH`](https://dax.guide/SWITCH) 语句,如果其 **<Expression>** 参数指定为 `TRUE()`,并且所有 **<Value>** 参数都是对同一个 VAR 变量/度量值的简单比较,则可以简化。 示例:
`SWITCH(TRUE(), a = 1, ..., a = 2, ...)` -> `SWITCH(a, 1, ..., 2, ...)` | -| DI008 | [移除多余的 CALCULATE](xref:DI008) | 如果 [`CALCULATE`](https://dax.guide/CALCULATE) 并非必需——例如它不会修改筛选语境,或即使省略也会发生隐式语境转换——则应将其移除。 示例:
`CALCULATE([Total Sales])` -> `[Total Sales]`
`AVERAGEX(Product, CALCULATE([Total Sales]))` -> `AVERAGEX(Product, [Total Sales])`

当 `CALCULATE` / `CALCULATETABLE` 的第一个参数是 DAX 变量时,此规则同样适用,例如:
`VAR x = [Total Sales] RETURN CALCULATE(x, Product[Color] = "Red")` ->
`VAR x = [Total Sales] RETURN x` | -| DI009 | [避免使用 CALCULATE 简写语法](xref:DI009) | 示例:
`[Total Sales](Products[Color] = "Red")` -> `CALCULATE([Total Sales], Products[Color] = "Red")` | -| DI010 | [使用 MIN/MAX 代替 IF](xref:DI010) | 当条件表达式用于返回两个值中的最小值或最大值时,使用 [`MIN`](https://dax.guide/MIN) 或 [`MAX`](https://dax.guide/MAX) 函数会更高效、更简洁。 示例:
`IF(a > b, a, b)` -> `MAX(a, b)` | -| DI011 | [使用 ISEMPTY 代替 COUNTROWS](xref:DI011) | 检查表是否为空时,使用 [`ISEMPTY`](https://dax.guide/ISEMPTY) 函数比统计表的行数更高效。 示例:
`COUNTROWS(Products) = 0` -> `ISEMPTY(Products)` | -| DI012 | [使用 DIVIDE 代替除法](xref:DI012) | 当在除法的分母中使用任意表达式时,建议使用 [`DIVIDE`](https://dax.guide/DIVIDE) 而不是除法运算符,以避免出现除以零错误。 示例:
`x / y` -> `DIVIDE(x, y)` | -| DI013 | [使用除法运算符代替 DIVIDE](xref:DI013) | 当 [`DIVIDE`](https://dax.guide/DIVIDE) 的第 2 个参数是非零常量时,使用除法运算符更高效。 示例:
`DIVIDE(x, 2)` -> `x / 2` | -| DI014 | [用 DIVIDE 代替 IFERROR](xref:DI014) | 当除法的分母为零时,使用 [`DIVIDE`](https://dax.guide/DIVIDE) 函数而不是 [`IFERROR`](https://dax.guide/IFERROR) 来提供替代结果。 示例:
`IFERROR(x / y, 0)` -> `DIVIDE(x, y, 0)` | -| DI015 | [用 DIVIDE 替换 IF](xref:DI015) | 使用 [`DIVIDE`](https://dax.guide/DIVIDE) 函数而不是 [`IF`](https://dax.guide/IF),可更轻松地检查分母是否为零或空白。 示例:
`IF(y <> 0, x / y)` -> `DIVIDE(x, y)` | -| DI016 | 使用正确的 UDF 语法 | 用户定义函数表达式要使用正确的语法。 示例:
`(x, y) => x + y` | +| ID | 名称 | 描述 | +| ----- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| DI001 | [删除未使用的变量](xref:DI001) | 未在任何地方被引用的变量应删除。 示例:
`VAR a = 1 VAR b = 2 RETURN a` -> `VAR a = 1 RETURN a` | +| DI002 | [删除所有未使用的变量](xref:DI002) | 在 VAR 变量块中,凡是在 `RETURN` 部分未被使用的变量(无论是直接使用,还是通过其他变量间接使用)都应删除。 示例:
`VAR a = 1 VAR b = a RETURN 123` -> `123` | +| DI003 | [移除表名](xref:DI003) | 度量值引用中不应包含表名,因为引用度量值时表名是多余的。 此外,这样做也能让度量值引用与列引用更容易区分。 示例:
`Sales[Total Sales]` -> `[Total Sales]` | +| DI004 | [添加表名](xref:DI004) | 列引用应包含表名,以避免歧义,并更容易将列引用与度量值引用区分开来。 示例:
`SUM([SalesAmount])` -> `SUM(Sales[SalesAmount])` | +| DI005 | [将表筛选 FILTER 重写为标量谓词](xref:DI005) | DAX 中一个常见的反模式是,在 [`CALCULATE`](https://dax.guide/CALCULATE) 的筛选器参数中筛选整张表,而实际上只需筛选该表中的一个或多个列即可。 示例:
`CALCULATE([Total Sales], FILTER(Products, Products[Color] = "Red"))` -> `CALCULATE([Total Sales], KEEPFILTERS(Products[Color] = "Red"))`
此代码操作支持原始表达式的多种变体。 | +| DI006 | [将多列筛选拆分为多个筛选](xref:DI006) | 当使用 `AND`(或等效的 `&&` 运算符)将多个列组合起来筛选表时,通常可通过为每一列分别指定筛选条件来获得更好的性能。 示例:
`CALCULATE(..., Products[Color] = "Red" && Products[Size] = "Large")` -> `CALCULATE(..., Products[Color] = "Red", Products[Size] = "Large")` | +| DI007 | [简化 SWITCH 语句](xref:DI007) | 将 `TRUE()` 指定为 **<Expression>** 参数,且所有 **<Value>** 参数都是对同一 VAR 变量/度量值进行简单比较的 [`SWITCH`](https://dax.guide/SWITCH) 语句,可以简化。 示例:
`SWITCH(TRUE(), a = 1, ..., a = 2, ...)` -> `SWITCH(a, 1, ..., 2, ...)` | +| DI008 | [移除多余的 CALCULATE](xref:DI008) | 如果 [`CALCULATE`](https://dax.guide/CALCULATE) 并非必需——例如它不会修改筛选语境,或即使省略也会发生隐式语境转换——则应将其移除。 示例:
`CALCULATE([Total Sales])` -> `[Total Sales]`
`AVERAGEX(Product, CALCULATE([Total Sales]))` -> `AVERAGEX(Product, [Total Sales])`

如果 `CALCULATE` / `CALCULATETABLE` 的第一个参数是 DAX 变量,也同样适用,例如:
`VAR x = [Total Sales] RETURN CALCULATE(x, Product[Color] = "Red")` ->
`VAR x = [Total Sales] RETURN x` | +| DI009 | [避免使用 CALCULATE 简写语法](xref:DI009) | 示例:
`[Total Sales](Products[Color] = "Red")` -> `CALCULATE([Total Sales], Products[Color] = "Red")` | +| DI010 | [使用 MIN/MAX 代替 IF](xref:DI010) | 当使用条件表达式返回两个值中的较小值或较大值时,使用 [`MIN`](https://dax.guide/MIN) 或 [`MAX`](https://dax.guide/MAX) 函数会更高效,也更简洁。 示例:
`IF(a > b, a, b)` -> `MAX(a, b)` | +| DI011 | [使用 ISEMPTY 代替 COUNTROWS](xref:DI011) | 检查表是否为空时,使用 [`ISEMPTY`](https://dax.guide/ISEMPTY) 函数比统计表的行数更高效。 示例:
`COUNTROWS(Products) = 0` -> `ISEMPTY(Products)` | +| DI012 | [使用 DIVIDE 代替除法](xref:DI012) | 当分母为任意表达式时,应使用 [`DIVIDE`](https://dax.guide/DIVIDE) 而不是除法运算符,以避免除以零错误。 示例:
`x / y` -> `DIVIDE(x, y)` | +| DI013 | [使用除法运算符代替 DIVIDE](xref:DI013) | 当 [`DIVIDE`](https://dax.guide/DIVIDE) 的第 2 个参数是非零常量时,使用除法运算符会更高效。 示例:
`DIVIDE(x, 2)` -> `x / 2` | +| DI014 | [用 DIVIDE 代替 IFERROR](xref:DI014) | 除法的分母为零时,如果要提供替代结果,使用 [`DIVIDE`](https://dax.guide/DIVIDE) 函数,而不是 [`IFERROR`](https://dax.guide/IFERROR)。 示例:
`IFERROR(x / y, 0)` -> `DIVIDE(x, y, 0)` | +| DI015 | [用 DIVIDE 替换 IF](xref:DI015) | 如果想更轻松地检查分母是否为零或空白,使用 [`DIVIDE`](https://dax.guide/DIVIDE) 函数,而不是 [`IF`](https://dax.guide/IF)。 示例:
`IF(y <> 0, x / y)` -> `DIVIDE(x, y)` | +| DI016 | 使用正确的 UDF 语法 | 用户定义函数表达式应使用正确的语法。 示例:
`(x, y) => x + y` | ### 可读性 将光标置于代码分段上时,下面的代码操作会在适用代码的前两个字符下方显示青绿色圆点,并在左侧边距显示螺丝刀图标 -| ID | 名称 | 描述 | -| ----- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| DR001 | [转换为标量谓词](xref:DR001) | 列筛选器可以更简洁地写成标量谓词,而无需显式使用 [`FILTER`](https://dax.guide/FILTER) 函数。 示例:
`FILTER(ALL(Products[Color]), Products[Color] = "Red")` -> `Products[Color] = "Red"`
`FILTER(VALUES(Products[Color]), Products[Color] = "Red")` -> `KEEPFILTERS(Products[Color] = "Red")` | -| DR002 | [使用聚合函数而非迭代器函数](xref:DR002) | 在可能的情况下,使用聚合函数而不是迭代器函数,以简化代码。 示例:
`SUMX(Products, Products[SalesAmount])` -> `SUM(Products[SalesAmount])` | -| DR003 | [使用 VALUES 而非 SUMMARIZE](xref:DR003) | 当 [`SUMMARIZE`](https://dax.guide/SUMMARIZE) 仅指定一列,且该列属于第一个参数指定的表时,可使用 [`VALUES`](https://dax.guide/VALUES) 将代码写得更简洁。 示例:
`SUMMARIZE(Products, Products[Color])` -> `VALUES(Products[Color])` | -| DR004 | [为 VAR 变量添加前缀](xref:DR004) | 变量应使用一致的命名规范。 建议使用前缀,例如下划线。 你可以配置要使用的前缀,以匹配你偏好的风格。 示例:
`VAR totalSales = SUM(Sales[SalesAmount])` -> `VAR _totalSales = SUM(Sales[SalesAmount])` | -| DR005 | [为临时列设置前缀](xref:DR005) | 建议为临时列使用统一的前缀,以便更轻松地将其与基础列或度量值区分开来。 你可以配置要使用的前缀,以符合你偏好的风格。 示例:
`ADDCOLUMNS(Product, "SalesByProd", [Sales])` -> `ADDCOLUMNS(Product, "@SalesByProd", [Sales])` | -| DR006 | [将常量聚合移入 VAR 变量](xref:DR006) | 当聚合函数在迭代器或标量谓词中使用时,该聚合会为迭代中的每一行产生相同的结果。 因此,可以将该聚合移到迭代之外的 DAX VAR 变量中。 示例:
`CALCULATE(..., 'Date'[Date] = MAX('Date'[Date]))` ->
`VAR _maxDate = MAX('Date'[Date]) RETURN CALCULATE(..., 'Date'[Date] = _maxDate)` | -| DR007 | [简化 1 变量块](xref:DR007) | 仅包含一个 VAR 变量的变量块可通过将表达式直接移到该块的 `RETURN` 部分来简化。 这假定该变量只被引用一次,且没有任何上下文修饰符。 示例:
`VAR _result = [Sales] * 1.25 RETURN _result` -> `[Sales] * 1.25` | -| DR008 | [简化多变量 VAR 块](xref:DR008) | 对于包含多个变量的 VAR 变量块,若每个变量都只是对度量值的简单引用,并且每个变量在 `RETURN` 部分仅使用一次且不带任何上下文修饰符,则应简化该变量块。 示例:
`VAR _sales = [Sales] VAR _cost = [Cost] RETURN _sales - _cost` -> `[Sales] - [Cost]` | -| DR009 | [使用 DISTINCTCOUNT 重写](xref:DR009) | 要统计列中不同值的数量,不要使用 `COUNTROWS(DISTINCT(T[c])`,而应使用 [`DISTINCTCOUNT`](https://dax.guide/DISTINCTCOUNT) 函数。 | -| DR010 | [使用 COALESCE 重写](xref:DR010) | 若要在 `RETURN` 中从一组表达式中返回第一个非空白值,不要使用 `IF`,而应使用 [`COALESCE`](https://dax.guide/COALESCE) 函数。 示例:
`IF(ISBLANK([Sales]), [Sales2], [Sales])` -> `COALESCE([Sales], [Sales2])` | -| DR011 | [使用 ISBLANK 重写](xref:DR011) | 不要将表达式与 [`BLANK()`](https://dax.guide/BLANK) 进行比较,而应使用 [`ISBLANK`](https://dax.guide/ISBLANK) 函数。 示例:
`IF([Sales] = BLANK(), [Budget], [Sales])` -> `IF(ISBLANK([Sales], [Budget], [Sales])` | -| DR012 | [移除不必要的 BLANK](xref:DR012) | 某些 DAX 函数,例如 [`IF`](https://dax.guide/IF) 和 [`SWITCH`](https://dax.guide/SWITCH),在条件不成立时已经会返回 `BLANK()`,因此无需显式指定 `BLANK()`。 示例:
`IF(a > b, a, BLANK())` -> `IF(a > b, a)` | -| DR013 | [简化取反逻辑](xref:DR013) | 对逻辑表达式取反时,通常改用对应的否定运算符来重写,这样更易读。 示例:
`NOT(a = b)` -> `a <> b` | -| DR014 | [使用 IN 简化](xref:DR014) | 使用 [`IN`](https://dax.guide/IN) 运算符来重写复合谓词(即针对同一表达式的相等比较,并通过 [`OR`](https://dax.guide/OR) 或 [`\\|\\|`](https://dax.guide/op/or/) 进行组合)。 示例:
`a = 1 \\|\\| a = 2 \\|\\| a = 100` -> `a IN { 1, 2, 100 }` | +| ID | 名称 | 描述 | +| ----- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| DR001 | [转换为标量谓词](xref:DR001) | 列筛选可以更简洁地写成标量谓词,而无需显式使用 [`FILTER`](https://dax.guide/FILTER) 函数。 示例:
`FILTER(ALL(Products[Color]), Products[Color] = "Red")` -> `Products[Color] = "Red"`
`FILTER(VALUES(Products[Color]), Products[Color] = "Red")` -> `KEEPFILTERS(Products[Color] = "Red")` | +| DR002 | [使用聚合函数而非迭代器函数](xref:DR002) | 在可能的情况下,使用聚合函数而不是迭代器函数,以简化代码。 示例:
`SUMX(Products, Products[SalesAmount])` -> `SUM(Products[SalesAmount])` | +| DR003 | [使用 VALUES 而非 SUMMARIZE](xref:DR003) | 当 [`SUMMARIZE`](https://dax.guide/SUMMARIZE) 只指定一个列,且该列属于第一个参数指定的表时,可改用 [`VALUES`](https://dax.guide/VALUES) 让代码更简洁。 示例:
`SUMMARIZE(Products, Products[Color])` -> `VALUES(Products[Color])` | +| DR004 | [为 VAR 变量添加前缀](xref:DR004) | 变量应使用一致的命名规范。 建议使用前缀,例如下划线。 你可以配置要使用的前缀,以匹配你偏好的风格。 示例:
`VAR totalSales = SUM(Sales[SalesAmount])` -> `VAR _totalSales = SUM(Sales[SalesAmount])` | +| DR005 | [为临时列设置前缀](xref:DR005) | 建议为临时列使用统一的前缀,以便更轻松地将其与基础列或度量值区分开来。 你可以配置要使用的前缀,以符合你偏好的风格。 示例:
`ADDCOLUMNS(Product, "SalesByProd", [Sales])` -> `ADDCOLUMNS(Product, "@SalesByProd", [Sales])` | +| DR006 | [将常量聚合移入 VAR 变量](xref:DR006) | 当聚合函数在迭代器或标量谓词中使用时,该聚合会为迭代中的每一行产生相同的结果。 因此,可以将该聚合移到迭代之外的 DAX VAR 变量中。 示例:
`CALCULATE(..., 'Date'[Date] = MAX('Date'[Date]))` ->
`VAR _maxDate = MAX('Date'[Date]) RETURN CALCULATE(..., 'Date'[Date] = _maxDate)` | +| DR007 | [简化 1 变量块](xref:DR007) | 仅包含一个 VAR 变量的变量块可通过将表达式直接移到该块的 `RETURN` 部分来简化。 这假定该变量只被引用一次,且没有任何上下文修饰符。 示例:
`VAR _result = [Sales] * 1.25 RETURN _result` -> `[Sales] * 1.25` | +| DR008 | [简化多变量 VAR 块](xref:DR008) | 如果一个 VAR 变量块包含多个变量,且每个变量都只是简单的度量值引用,并且在 `RETURN` 部分仅使用一次且不带任何上下文修饰符,则应将该变量块简化。 示例:
`VAR _sales = [Sales] VAR _cost = [Cost] RETURN _sales - _cost` -> `[Sales] - [Cost]` | +| DR009 | [使用 DISTINCTCOUNT 重写](xref:DR009) | 要统计列中不同值的数量,不要使用 `COUNTROWS(DISTINCT(T[c])`,而应使用 [`DISTINCTCOUNT`](https://dax.guide/DISTINCTCOUNT) 函数。 | +| DR010 | [使用 COALESCE 重写](xref:DR010) | 不要使用 `IF` 从一组表达式中返回第一个非空白值,而应使用 [`COALESCE`](https://dax.guide/COALESCE) 函数。 示例:
`IF(ISBLANK([Sales]), [Sales2], [Sales])` -> `COALESCE([Sales], [Sales2])` | +| DR011 | [使用 ISBLANK 重写](xref:DR011) | 与其将表达式同 [`BLANK()`](https://dax.guide/BLANK) 进行比较,不如使用 [`ISBLANK`](https://dax.guide/ISBLANK) 函数。 示例:
`IF([Sales] = BLANK(), [Budget], [Sales])` -> `IF(ISBLANK([Sales], [Budget], [Sales])` | +| DR012 | [移除不必要的 BLANK](xref:DR012) | 某些 DAX 函数(例如 [`IF`](https://dax.guide/IF) 和 [`SWITCH`](https://dax.guide/SWITCH))在条件为 false 时本身就会返回 `BLANK()`,因此无需显式指定 `BLANK()`。 示例:
`IF(a > b, a, BLANK())` -> `IF(a > b, a)` | +| DR013 | [简化取反逻辑](xref:DR013) | 当逻辑表达式取反时,通常用取反后的运算符重写该表达式会更易读。 示例:
`NOT(a = b)` -> `a <> b` | +| DR014 | [使用 IN 简化](xref:DR014) | 使用 [`IN`](https://dax.guide/IN) 运算符来重写复合谓词(即针对同一表达式的相等比较,并通过 [`OR`](https://dax.guide/OR) 或 [`\|\|`](https://dax.guide/op/or/) 进行组合)。 示例:
`a = 1 \|\| a = 2 \|\| a = 100` -> `a IN { 1, 2, 100 }` | ### 重写 @@ -131,14 +131,14 @@ Tabular Editor 3.18.0 引入了一项名为 **代码操作** 的新功能。 该 | ID | 名称 | 描述 | | ----- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | RW001 | [使用 CALCULATE 重写 TOTALxTD](xref:RW001) | [`TOTALMTD`](https://dax.guide/TOTALMTD)、[`TOTALQTD`](https://dax.guide/TOTALQTD) 和 [`TOTALYTD`](https://dax.guide/TOTALYTD) 等函数都可以使用 [`CALCULATE`](https://dax.guide/CALCULATE) 函数重写。这样表达力更强,也提供了更高的灵活性。 示例:
`TOTALYTD([Total Sales], 'Date'[Date])` -> `CALCULATE([Total Sales], DATESYTD('Date'[Date]))` | -| RW002 | [使用 FILTER 重写](xref:RW002) | `CALCULATE` 的筛选参数中的标量谓词可以使用 `FILTER` 重写。 例如,当你需要添加更复杂的筛选逻辑时,这会很有用。 示例:
`CALCULATE(..., Products[Color] = "Red")` -> `CALCULATE(..., FILTER(ALL(Products[Color]), Products[Color] = "Red"))` | +| RW002 | [使用 FILTER 重写](xref:RW002) | `CALCULATE` 的筛选器参数中的标量谓词可以用 `FILTER` 改写。 例如,当你需要添加更复杂的筛选逻辑时,这会很有用。 示例:
`CALCULATE(..., Products[Color] = "Red")` -> `CALCULATE(..., FILTER(ALL(Products[Color]), Products[Color] = "Red"))` | | RW003 | [反转 IF](xref:RW003) | 为了提高可读性,有时反转 `IF` 语句会很有帮助。 示例:
`IF(a < b, "B is greater", "A is greater")` -> `IF(a > b, "A is greater", "B is greater")` | ## 自定义代码操作 -你可以在 **工具 > 偏好** 对话框中,依次进入 **文本编辑器 > DAX编辑器 > 代码操作**,来自定义代码操作的行为。 在这里,你可以开启或关闭该功能,并为某些代码操作配置其他选项,例如用于变量名和扩展列的前缀。 +你可以在 **工具 > 偏好** 对话框中,依次进入 **文本编辑器 > DAX编辑器 > 代码操作**,自定义代码操作的行为。 在这里,你可以开启或关闭该功能,并为某些代码操作配置其他选项,例如用于变量名和扩展列的前缀。 -我们计划在未来版本中为此界面添加更多配置选项,例如提供单独开启或关闭各个代码操作的选项。 敬请期待! +我们计划在未来版本中为此界面添加更多配置选项,例如提供可单独启用或禁用各个代码操作的选项。 敬请期待! ![代码操作偏好](~/content/assets/images/code-actions-preferences.png) diff --git a/localizedContent/zh/content/features/semantic-bridge-metric-view-object-model.md b/localizedContent/zh/content/features/semantic-bridge-metric-view-object-model.md index 4b92c9465..a7389e58b 100644 --- a/localizedContent/zh/content/features/semantic-bridge-metric-view-object-model.md +++ b/localizedContent/zh/content/features/semantic-bridge-metric-view-object-model.md @@ -30,17 +30,17 @@ SUMMARY: Overview of the Metric View object model built into the Semantic Bridge > 这里的对象模型明显缺少 TOMWrapper 中提供的许多便捷功能,而这些功能你可能已经在用于操作 Tabular 模型的 C# Script 中用过并熟悉。 > 如[语义桥的限制](xref:semantic-bridge#public-preview-limitations)中所述,我们目前仅支持 Metric View v0.1 的元数据。 -Semantic Bridge 包含一个用于表示 Databricks Metric View 的对象模型。 +Semantic Bridge 包含一个对象模型,用于表示 Databricks Metric View。 这使你可以通过 C# Script 以编程方式处理 Metric View,类似于通过 TOMWrapper 操作 Tabular 模型。 -除 [导入 GUI](xref:semantic-bridge#interface) 外,所有对 Metric View 的访问与交互都需通过 C# Script 进行。 +除 [导入 GUI](xref:semantic-bridge#interface) 之外,对 Metric View 的所有访问与交互都通过 C# Script 完成。 本文档中的所有内容均指你将在 [C# Script](xref:csharp-scripts) 中使用的 C# 代码。 ## 加载并访问 Metric View -你可以使用 [`SemanticBridge.MetricView.Load`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Load_System_String_) 或 [`SemanticBridge.MetricView.Deserialize`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Deserialize_System_String_) 来加载 Metric View。 +你可以通过 [`SemanticBridge.MetricView.Load`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Load_System_String_) 或 [`SemanticBridge.MetricView.Deserialize`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Deserialize_System_String_) 来加载 Metric View。 这会将反序列化后的 Metric View 存储在 [`SemanticBridge.MetricView.Model`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Model) 中。 该属性返回一个 [`View`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.MetricView.View) 对象,它是 Metric View 对象图的根对象。 @@ -53,7 +53,7 @@ var view = SemanticBridge.MetricView.Model; Output($"Metric View version: {view.Version}\r\nSource: {view.Source}"); ``` -与 Tabular 模型类似,但不同于你在 C# Script 中常见的大多数其他对象,Metric View 会在多次脚本执行之间保持持久化。 +与 Tabular 模型类似,但不同于你在 C# Script 中常见的多数其他对象,Metric View 会在多次脚本执行之间保持持久化。 这意味着你只需加载一次指标视图,后续脚本执行时即可引用它,而无需每次都重新加载。 任意时刻只会加载一个指标视图;如上所述,所有脚本都可以通过 `SemanticBridge.MetricView.Model` 访问它。 这种行为类似于 C# Script 中的表格模型,它始终可以直接通过 `Model` 访问。 @@ -71,7 +71,7 @@ Output($"Metric View version: {view.Version}\r\nSource: {view.Source}"); | [`度量值`](xref:TabularEditor.SemanticBridge.Platforms.Databricks.MetricView.Measure) | 表示业务逻辑的聚合定义 | > [!NOTE] -> 在对象模型中,我们遵循 C# 的命名约定,因此对象模型中的所有类型和属性名称都使用 `PascalCase`。 +> 在对象模型中,我们遵循 C# 命名约定,因此对象模型中的所有类型名和属性名均使用 `PascalCase`。 > 指标视图 YAML 规范遵循 `snake_case` 的命名约定。 > 总体而言,我们主要关注作为 Semantic Bridge 组件的 C# 对象模型。 > 除了更改大小写之外,我们不会改变 YAML 中的任何命名约定。 @@ -108,7 +108,7 @@ Output(sb.ToString()); 如果 `Source` 不是一个 3 段式表或视图引用,则会被翻译为一个包含内嵌 SQL 查询的 M 分区,并将整个 `Source` 字符串作为 SQL 查询。 在翻译时会忽略 `Filter` 属性。 -为了评估验证规则,会先检查 `View`,然后按顺序验证各个集合:先是 `Joins`,然后是 `Dimensions`,最后是 `Measures`。 +为评估验证规则,会先检查 `View`,然后按顺序验证各个集合:先是 `Joins`,再是 `Dimensions`,最后是 `Measures`。 事实表 `Source` 的验证是在 `View` 对象的验证规则中完成的。 ### 联接 @@ -140,7 +140,7 @@ Output(sb.ToString()); #### `Join` 翻译与验证 -不支持嵌套的 `Join`,也就是说,只能翻译严格的星型架构。 +不支持嵌套 `Join`,也就是说,只能转换严格的星型架构。 仅支持对使用 `On` 的单字段等值联接进行翻译。 每个 `Join` 都会成为表格模型中的一张表,并且会按照与 `View.Source` 属性相同的规则定义一个 M 分区。 @@ -220,7 +220,7 @@ Output(sb.ToString()); 我们会尝试识别 SQL 表达式中引用的所有字段;如果这些字段尚未作为 Metric View 的 `Dimension` 存在,则将其作为 `DataColumn` 添加到表格模型中。 > [!WARNING] -> SQL 和 DAX 是两种不同的语言,语义也不同。 +> SQL 和 DAX 是不同的语言,语义也不同。 > 自动翻译得到的度量值,可能无法在 Databricks Metric View 和表格模型中表达完全相同的计算逻辑。 > 你需要自己验证所有代码是否按预期工作。 @@ -228,7 +228,7 @@ Output(sb.ToString()); ## Using 指令 -在 C# Script 中使用 Metric View 对象模型时,你可能需要添加 using 指令,以避免与 Tabular Object Model 中名称相同或相近的类型发生命名冲突。 +在 C# Script 中使用 Metric View 对象模型时,你可能需要添加 using 指令,以避免与 Tabular Object Model 中同名或名称相近的类型发生命名冲突。 我们建议为命名空间设置别名: ```csharp diff --git a/localizedContent/zh/content/features/semantic-bridge-metric-view-validation.md b/localizedContent/zh/content/features/semantic-bridge-metric-view-validation.md index 040a232a5..9d4c6c4b9 100644 --- a/localizedContent/zh/content/features/semantic-bridge-metric-view-validation.md +++ b/localizedContent/zh/content/features/semantic-bridge-metric-view-validation.md @@ -41,13 +41,13 @@ SUMMARY: Describes the validation framework for Metric Views in the Semantic Bri 第一阶段和第三阶段是自动的,并且在语义桥内部完成;第二阶段则可以让你提供自己的验证规则。 -验证是一个过程:将一组验证规则逐一应用于 Metric View 中的所有对象,并对其进行评估。 +验证是一个过程:针对 Metric View 中的所有对象,逐一评估一组验证规则。 每条验证规则都只针对一种指标视图对象类型,例如 `Join` 或 `Measure`。 验证完成后,所有由规则违规产生的诊断信息都会返回给你,方便你进行后续处理。 ## 验证规则的构成 -验证规则都是 [`IMetricViewValidationRule`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.Interfaces.IMetricViewValidationRule.html) 的实例。 +所有验证规则都是 [`IMetricViewValidationRule`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.Interfaces.IMetricViewValidationRule.html) 的实例。 与其深入研究那个接口,不如通过这些辅助方法来理解和使用验证规则: - [`MakeValidationRuleForDimension`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService.html#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_MakeValidationRuleForDimension_System_String_System_String_System_String_System_Func_TabularEditor_SemanticBridge_Platforms_Databricks_MetricView_Dimension_System_Boolean__) @@ -56,7 +56,7 @@ SUMMARY: Describes the validation framework for Metric Views in the Semantic Bri - [`MakeValidationRuleForView`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService.html#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_MakeValidationRuleForView_System_String_System_String_System_String_System_Func_TabularEditor_SemanticBridge_Platforms_Databricks_MetricView_View_System_Boolean__) - [`MakeValidationRule`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService.html#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_MakeValidationRule__1_System_String_System_String_System_Func___0_TabularEditor_SemanticBridge_Platforms_Databricks_Validation_IReadOnlyValidationContext_System_Collections_Generic_IEnumerable_TabularEditor_SemanticBridge_Orchestration_DiagnosticMessage___) -前四个都是专门用于为其名称对应的对象类型创建规则的方法。 +前四个都是专用规则,用于为其名称所对应的对象类型创建规则。 它们提供了一个更简化的接口,你只需要提供: - `name`:用于标识该规则的简短唯一名称 @@ -110,7 +110,7 @@ var myRule = SemanticBridge.MetricView.MakeValidationRuleForDimension( Output(SemanticBridge.MetricView.Validate([myRule])); ``` -你可以看到,定义为 Metric View 维度的其中一个字段的名称中带有下划线。 +可以看到,定义为 Metric View 维度的某个字段名称中包含下划线。 运行脚本时,在按照我们定义的规则完成验证后,你会看到一条诊断信息。 你可以查看诊断信息中提供的详细内容: @@ -166,10 +166,10 @@ Output(SemanticBridge.MetricView.Validate([myRule])); 建议创建更多简单规则,而不是更少但更复杂的规则。 验证过程非常轻量,即使规则很多,也无需担心性能问题。 -例如,如果你想确保 Metric View 维度名称不采用 `camelCased`、不采用 `kebab-cased`,也不采用 `snake_cased`,最好分别创建三条规则,而不是试图在一条规则中检查所有这些条件。 +例如,如果你想确保 Metric View 维度名称不是 `camelCased`、不是 `kebab-cased`,也不是 `snake_cased`,最好分别创建三条规则,而不是试图在一条规则中同时检查这些条件。 这样每条规则都能保持简单,信息也会更具体,因此更容易采取相应措施。 -一般来说,一旦某条规则已经能捕获某个特定问题,最好保持不动,而不是去编辑它。 +一般来说,一旦某条规则能够捕获某个特定问题,最好就保持不变,而不是继续编辑它。 如果你发现该规则遗漏了你想捕获的某个条件,只需新增一条小而简单的规则来覆盖这个新条件即可。 你可以在一个 C# Script 中保存许多不同的规则,以便在不同的 Metric View 之间复用。 diff --git a/localizedContent/zh/content/features/semantic-bridge.md b/localizedContent/zh/content/features/semantic-bridge.md index 004a0a336..bf7f70ad2 100644 --- a/localizedContent/zh/content/features/semantic-bridge.md +++ b/localizedContent/zh/content/features/semantic-bridge.md @@ -54,12 +54,12 @@ Semantic Bridge 是一个语义模型编译器,能够将语义模型的结构 2. Databricks 主机名。 用于在为 Databricks 源系统生成的 M 分区中提供正确的参数。 3. Databricks 的 HTTP 路径。 - 这用于在为 Databricks 源系统生成的 M 分区中提供正确的参数。 + 这是为了在为 Databricks 源系统生成的 M 分区中提供正确的参数。 如果你只是测试翻译功能,最后两项可以先用占位值填写,但在将数据刷新到你的 Tabular 模型之前,需要先修正 M 分区定义。 填写完详细信息后,点击 **确定**。 -Semantic Bridge 会将你的 Metric View 转换为 Tabular,并为你创建所有 TOM 对象。 +Semantic Bridge 会将您的 Metric View 转换为 Tabular,并为您创建所有 TOM 对象。 ![导入对话框中的 Databricks 详细信息](~/content/assets/images/features/semantic-bridge/semantic-bridge-metric-view-details.png) @@ -81,7 +81,7 @@ Semantic Bridge 会将你的 Metric View 转换为 Tabular,并为你创建所 ![包含问题的导入成功通知](~/content/assets/images/features/semantic-bridge/semantic-bridge-import-success-with-issues.png) -如果你点击 **查看诊断信息**,就能看到一份信息列表,用于说明翻译过程中出现的问题。 +如果您点击 **查看诊断信息**,就会看到一份信息列表,用于描述翻译中存在的问题。 这些诊断信息也可以在之后通过 C# Script 输出出来查看: ```csharp @@ -104,12 +104,12 @@ SemanticBridge.MetricView.ImportDiagnostics.Output(); 1. 从磁盘读取 YAML 文件 2. 对 YAML 进行反序列化 3. 验证反序列化后的 YAML 是否为有效的 Metric View -4. 如果它是有效的 Metric View,就将其保存为当前已加载的 Metric View,就像你与已加载的 Tabular 模型交互一样。 +4. 如果它是有效的 Metric View,就将其保存为当前加载的 Metric View,类似于您与已加载的 Tabular 模型交互的方式。 如果它不是有效的 Metric View,流程将在此停止,并会提供信息。 5. 分析 Metric View,并尝试将其转换为一种中间表示 6. 尝试将中间表示转换为 Tabular 模型 -上述导入 GUI 会为你处理这一切,但你也可以使用 C# Script 自定义流程中的不同步骤,并以编程方式操作 Metric View,就像你平时操作 Tabular 模型一样。 +上文所述的导入 GUI 会为您处理这些工作;不过,您也可以使用 C# Script 来自定义流程中的不同步骤,并以编程方式操作 Metric View,就像您平时操作 Tabular 模型一样。 具体来说,你可以 - 使用 [`SemanticBridge.MetricView.Load`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService.html#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Load_System_String_) 从磁盘加载 Metric View:加载后可在 C# Script 中通过 [`SemanticBridge.MetricView.Model`](/api/TabularEditor.SemanticBridge.Platforms.Databricks.DatabricksMetricViewService.html#TabularEditor_SemanticBridge_Platforms_Databricks_DatabricksMetricViewService_Model) 访问,但不会将结构导入 Tabular 模型 @@ -139,17 +139,17 @@ SemanticBridge.MetricView.ImportDiagnostics.Output(); - `filter`:用于 Metric View 的 SQL 筛选表达式 公开预览版不支持任何 v1.1 元数据。 -在反序列化 Metric View 时,任何 v1.1 元数据都会被静默忽略,因此在 C# Script 中将不可见,也不会以任何方式影响翻译为 Tabular 的结果。 +在对 Metric View 进行反序列化时,任何 v1.1 元数据都会被静默忽略,因此这些元数据在 C# Script 中不可见,也不会以任何方式影响翻译到 Tabular。 > [!WARNING] -> 由于 v1.1 元数据会被静默忽略,将 Metric View 反序列化后再序列化会导致这些元数据丢失。 +> 由于 v1.1 元数据会被静默忽略,因此你反序列化后再序列化的 Metric View 将缺少这些元数据。 > 注意不要在 C# Script 中覆盖 v1.1 源 YAML 文件,否则会移除所有 v1.1 元数据。 ### 从 SQL 翻译的限制 Metric View 在 SQL 表达式之上提供了一个结构化层,因此翻译 Metric View 的一部分工作是在 Tabular 模型中将 SQL 转换为 DAX 和 M。 -- 不支持在 Metric View 的 `joins` 中嵌套 `joins`。 +- 不支持在 Metric View `joins` 中使用嵌套 `joins`。 换句话说,翻译仅支持严格的星型架构;不支持雪花模型 - 不支持使用 `using` 作为联接条件的 Metric View `joins`;仅支持通过 `on` 属性在单个键字段上进行等值联接。 - 包含 SQL 表达式的 Metric View `dimensions` 不会翻译为 M 或 DAX;它们会以 Tabular 模型计算列的形式呈现,并将其 SQL 表达式注释掉 @@ -159,7 +159,7 @@ Metric View 在 SQL 表达式之上提供了一个结构化层,因此翻译 Me > [!WARNING] > 注意,SQL 和 DAX 是不同的语言,语义也不同。 -> 我们无法保证翻译后的度量值在 Metric View SQL 与我们生成的 Tabular DAX 之间具有完全一致的行为。 +> 我们无法保证转换后的度量值在 Metric View SQL 与我们生成的 Tabular DAX 中的行为完全一致。 > 定义在事实表字段上的基础聚合通常表现一致;而定义在维度表字段上的聚合更可能产生非预期结果。 ### 连接 @@ -169,7 +169,7 @@ Metric View 在 SQL 表达式之上提供了一个结构化层,因此翻译 Me ### C# API -C# 接口的设计旨在优化自动翻译工作流。 +该 C# 接口在设计时针对自动翻译工作流进行了优化。 因此,与当前加载的 Metric View 交互的支持较为有限,某些类型的操作也比较繁琐。 ## 命名法附录 @@ -186,9 +186,9 @@ C# 接口的设计旨在优化自动翻译工作流。 ### 定义 - _语义模型_:单独使用时,始终指通用概念——用于支撑报表与分析的数据、元数据与业务逻辑的集合。 - 只有在其前面紧跟“Fabric”或“Power BI”时,它才指该平台中的那种工件类型:具体而言,是以 TMDL 或 BIM 保存、并使用 M 和 DAX 的 Tabular 模型;为尽可能避免这种混淆,我们通常更倾向于用“Tabular 模型”来指代 Power BI / Fabric 语义模型,因为 Tabular 模型不仅用于 Power BI / Fabric,也用于 Analysis Services Tabular。 + 仅当其前面紧跟“Fabric”或“Power BI”时,它才指该平台中的那种项目类型——具体而言,是以 TMDL 或 BIM 保存、并使用 M 和 DAX 的 Tabular 模型。为尽可能避免混淆,我们通常更倾向于用“Tabular 模型”来指代 Power BI / Fabric 的语义模型,因为 Tabular 模型不仅用于 Power BI / Fabric,也用于 Analysis Services Tabular。 - _平台_:具有语义层、并承载通用语义模型的技术解决方案。 - Databricks Metric Views 代表一个平台;Fabric / Power BI 代表一个平台;Analysis Services Tabular 是一个平台;Analysis Services Multidimensional 也是一个平台——但 Semantic Bridge 目前还不支持它。 + Databricks Metric Views 是一种平台;Fabric / Power BI 是一种平台;Analysis Services Tabular 是一种平台;Analysis Services Multidimensional 也是一种平台,但 Semantic Bridge 目前不支持它。 - _序列化格式_:一种将语义模型以文本形式表示并存储到磁盘上的方式。 TMDL 和 TMSL (.bim) 是 Power BI 语义模型的两种序列化格式;YAML 是 Databricks Metric View 的序列化格式。 - _对象模型_:语义模型在内存中的表示形式。我们通过 Semantic Bridge 在 Tabular Editor 中对它进行操作——既可以通过 GUI 操作,也可以通过 C# Script。 @@ -207,11 +207,11 @@ C# 接口的设计旨在优化自动翻译工作流。 ### Metric Views 与 Tabular 模型中的常见通用术语 对于可能不熟悉 Metric Views 或 Tabular 模型的用户,我们在下方提供了一份不完整的术语对照表。 -我们根据 YAML 中的表示来引用 Metric View 对象的名称;而对 Tabular,我们则以 TMDL/TMSL 中的对象类型名称为准。 +我们对 Metric View 对象的称呼基于它们在 YAML 中的表示;对 Tabular 对象的称呼则基于该对象类型在 TMDL/TMSL 中的名称。 | 通用术语 | Tabular 中的名称 | Metric View 中的名称 | 描述 | 备注 | | ----- | ------------ | ---------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | -| 事实表 | 表 | `source` | 用于存放维度外键以及可聚合的数值字段的表 | 一个 Metric View 只有一个事实表,它没有名称,并在 YAML 中作为根级 `source` 属性来表示。 Tabular 模型不会区分表的类型:某个表是否为事实表只能通过推断才能确定 | +| 事实表 | 表 | `source` | 用于存放维度外键以及可聚合的数值字段的表 | 一个 Metric View 只有一个未命名的事实表,并在 YAML 中表示为根级 `source` 属性。 Tabular 模型不会区分表的类型:某个表是否为事实表只能通过推断才能确定 | | 维度 | 表 | `join` | 用于存放描述性属性以及一个主键的表,事实表通过该主键与其关联 | Tabular 模型同样不会区分,因此“维度”的角色也只能像事实表一样通过推断得出。 | | 分区 | 分区 | `source`(仅用于 `join`) | 用于数据管理的对象,保存表中的一部分数据 | Tabular 模型中的表可以有多个分区,并且至少要有一个分区。 如上所述,Metric View 的事实表完全以 `source` 的形式定义;但 Metric View 的 `join` 也有一个 `source` 属性,其作用大致类似于分区 | | 字段 | 列 | 维度 | 表格中的一列 | | diff --git a/localizedContent/zh/content/features/te-cli/includes/te-cli-preview-notice.md b/localizedContent/zh/content/features/te-cli/includes/te-cli-preview-notice.md new file mode 100644 index 000000000..791c29254 --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/includes/te-cli-preview-notice.md @@ -0,0 +1,2 @@ +> [!IMPORTANT] +> The Tabular Editor CLI is in **Limited Public Preview**. It is offered for evaluation with a Tabular Editor account; no license is required during preview. Commands, flags, and outputs may change before general availability. **The preview build stops functioning after 2026-09-30.** We recommend against using the CLI in production CI/CD pipelines during preview. Please refer to our license agreement. diff --git a/localizedContent/zh/content/features/te-cli/te-cli-auth.md b/localizedContent/zh/content/features/te-cli/te-cli-auth.md new file mode 100644 index 000000000..054f1fdb9 --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-auth.md @@ -0,0 +1,226 @@ +--- +uid: te-cli-auth +title: Authentication and Connections +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Authentication and Connections + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI authenticates to Power BI Service, Microsoft Fabric, and Azure Analysis Services using the same Power BI Desktop client ID that Tabular Editor 3 uses. Tokens are cached locally so you authenticate once and re-run commands silently until the refresh token expires (typically 90 days). + +## Authentication methods + +The CLI supports the full Azure Identity credential chain: + +| Method | When to use | `--auth` value | +| ---------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------- | +| Interactive browser | Local development - opens the system browser | `interactive` (default) | +| Service principal (client secret) | Automation, CI/CD, headless / SSH / WSL | `spn` (with `-u / -p / -t`) or `env` | +| Service principal (certificate) | Automation with certificate-based auth | `spn` (with `-u / -t / --certificate`) | +| Environment variables | `AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET` / `AZURE_TENANT_ID` | `env` | +| Managed identity | Azure VMs, Azure Container Apps, Azure Functions | `managed-identity` | + +> [!NOTE] +> `--auth` is a **global** option, available on every `te` command - not just `te auth login`. Pass it to [`te deploy`](xref:te-cli-commands#deploy), [`te refresh`](xref:te-cli-commands#refresh), [`te query`](xref:te-cli-commands#query), [`te connect`](xref:te-cli-commands#connect), or any other command that connects to a remote endpoint, to override the default chain for that invocation. The default (`auto`) tries environment credentials first, then falls back to the cached or interactive browser login. + +For headless, SSH, WSL, or devcontainer scenarios, use a service principal - `te auth login -u -p -t ` (or `--certificate`). The login is cached, so subsequent commands acquire tokens silently with `--auth auto`. + +## `te auth login` + +Authenticate and cache the result for subsequent commands: + +```bash +# Browser-based interactive login (default) +te auth login + +# Service principal with client secret +te auth login -u "$AZURE_CLIENT_ID" -p "$AZURE_CLIENT_SECRET" -t "$AZURE_TENANT_ID" + +# Service principal - read secret from stdin +echo "$AZURE_CLIENT_SECRET" | te auth login -u "$AZURE_CLIENT_ID" -p - -t "$AZURE_TENANT_ID" + +# Service principal with certificate +te auth login -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --certificate ./sp.pfx --certificate-password "$CERT_PASSWORD" + +# Managed identity (Azure-hosted) +te auth login --identity +``` + +After a successful service-principal login the CLI **caches the credentials** so every subsequent `te` command can acquire tokens silently - no need to re-pass `-u / -p / -t` or set the `AZURE_CLIENT_*` environment variables. Pass `--save=false` for a one-shot login that doesn't update the cache, or run `te auth logout` to clear it. + +> [!WARNING] +> Passing secrets directly on the command line exposes them to process listings and shell history. Prefer the `AZURE_CLIENT_SECRET` environment variable, or pipe the secret via stdin with `-p -`. + +## `te auth status` + +Display the current authentication state without opening a browser: + +```bash +te auth status +te auth status --output-format json +``` + +This returns an exit code of `0` when a valid session exists, `1` when not logged in or expired. + +## `te auth logout` + +Clear all cached credentials: + +```bash +te auth logout +``` + +## Credential storage + +The CLI stores access/refresh tokens and service-principal records in the **OS-native secure store** by default. A `0600` file fallback is selected automatically only when the OS keystore is unavailable (e.g., headless Linux without libsecret/D-Bus). + +| Platform | Backend | Storage location | +| --------------------------------- | --------------------------------------------- | -------------------------------------------------------------- | +| Windows | DPAPI | Per-user, managed by MSAL | +| Linux | libsecret (system keyring) | Per-user, managed by MSAL | +| macOS | Keychain | Service `com.tabulareditor.cli.*`, account `te-msal-cache.bin` | +| Any (fallback) | `0600` file | `~/.te-cli/te-msal-cache.bin` and per-key `.bin` blobs | + +Interactive browser and service-principal flows share the same cache; MSAL's account model distinguishes them - there are no separate `auth-record*.json` sidecar files. Run any command with `--debug` to see which backend was selected at startup. + +`te auth logout` clears every cached record (both the MSAL token cache and any SPN blobs) regardless of which backend is in use. + +## `te connect` - set the active connection + +`te connect` persists an active connection for the current terminal session. Subsequent commands that take `-s` / `-d` can omit them: + +```bash +# Remote workspace +te connect my-workspace my-model + +# Local TMDL folder, .bim file, or .SemanticModel container +te connect ./my-model + +# Connect to a running Power BI Desktop instance (Windows only) +te connect --local + +# Show the active connection +te connect + +# Clear the active connection (and any workspace mirror) +te connect --clear +``` + +Active-connection state is per-terminal-session: opening a new terminal starts fresh. + +### Workspace mode (`-w` / `--workspace`) + +`te connect -w ` pairs a primary source with a secondary mirror so every subsequent `--save` writes to both. Use it to keep a local working copy of a remote model in sync, or to push local edits to a workspace as you save: + +```bash +# Mirror remote workspace ↔ local TMDL folder +te connect Finance "Revenue Model" -w ./revenue-model + +# Mirror local source ↔ remote workspace (initial deploy + auto-redeploy on save) +te connect ./revenue-model -w Finance "Revenue Model" +``` + +Save order is always **local first, then remote**, so the on-disk copy reflects the latest user change even if the server push fails. See @te-cli-commands#workspace-mode-w--workspace for `--workspace-format`, overwrite semantics, and clearing the mirror. + +## Connecting to different clouds + +The CLI detects the correct scope from the server URL for: + +- Power BI Service and Fabric (commercial, US Gov, China, Germany clouds) +- Azure Analysis Services (`asazure://...`) +- Local SSAS (`localhost`, named instances - Windows only) + +Pass an XMLA endpoint, workspace name, or `powerbi://` URL as `--server`: + +```bash +te connect "powerbi://api.powerbi.com/v1.0/myorg/Finance" "Revenue Model" +te connect "powerbi://api.powerbi.com/v1.0/SpaceParts/Finance" "Revenue Model" +te connect "asazure://westeurope.asazure.windows.net/myaas" "MyModel" +te connect localhost "AdventureWorks" +``` + +## Connection profiles + +For repeated use of the same connection - especially when you deploy to multiple environments - save named profiles: + +```bash +# Save remote and local profiles +te profile set prod -s my-workspace -d my-model --description "Production" +te profile set dev --model ./model --description "Local dev TMDL" + +# List and inspect +te profile list +te profile show prod + +# Use a profile as the active connection +te connect --profile prod + +# One-shot use without changing the active connection +te deploy ./model --profile staging --force +``` + +Profiles can also carry behavioral overrides that take effect whenever the profile is active: + +```bash +# In dev, disable the BPA gate on deploy and loosen validation +te profile set dev --bpa-on-deploy false --validate-on-mutation false + +# In prod, force auto-format before any mutation +te profile set prod --auto-format true +``` + +See @te-cli-config for the full list of overridable behaviors. + +## Non-interactive authentication + +For CI/CD pipelines, agents, or any unattended context, avoid interactive flows by combining: + +- The `--non-interactive` global flag (fails fast instead of prompting). +- One of the non-interactive auth methods: `env`, `managed-identity`, or explicit service principal credentials. + +Environment-based example for a pipeline: + +```bash +export AZURE_CLIENT_ID="your-app-id" +export AZURE_CLIENT_SECRET="your-client-secret" +export AZURE_TENANT_ID="your-tenant-id" + +te deploy ./model -s my-workspace -d my-model \ + --auth env \ + --non-interactive \ + --force \ + --ci github +``` + +See @te-cli-cicd for complete GitHub Actions and Azure DevOps Pipelines examples. + +## Authentication environment variables + +The CLI honors the standard Azure.Identity environment variables when you use `--auth env` (and as part of the `auto` chain): + +| Variable | Purpose | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `AZURE_CLIENT_ID` | Service principal application ID. | +| `AZURE_CLIENT_SECRET` | Service principal client secret. Used together with `AZURE_CLIENT_ID` and `AZURE_TENANT_ID`. | +| `AZURE_TENANT_ID` | Service principal tenant (directory) ID. | +| `AZURE_CLIENT_CERTIFICATE_PATH` | Path to a PEM or PKCS12 certificate file for certificate-based service principal auth. Used together with `AZURE_CLIENT_ID` and `AZURE_TENANT_ID`. | +| `AZURE_AUTHORITY_HOST` | Override the authority host for sovereign clouds (e.g., `login.microsoftonline.us`, `login.partner.microsoftonline.cn`, `login.microsoftonline.de`). Defaults to the commercial cloud. | + +For CLI-specific environment variables (config paths, debug logging, TE2 compatibility), see @te-cli-config. + +## Next steps + +- @te-cli-commands - what you can do once connected. +- @te-cli-config - configuration and profile behavior. +- @te-cli-cicd - pipeline examples using service principals and managed identity. diff --git a/localizedContent/zh/content/features/te-cli/te-cli-automation.md b/localizedContent/zh/content/features/te-cli/te-cli-automation.md new file mode 100644 index 000000000..9ff078182 --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-automation.md @@ -0,0 +1,193 @@ +--- +uid: te-cli-automation +title: Automation and Scripting +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Automation and Scripting + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI is composable; every command supports structured output, disables interactive prompts on demand, and returns predictable exit codes. The same primitives work equally well for shell pipelines, Python scripts, PowerShell automation, and agent-driven workflows. + +## Structured output + +Use `--output-format` to switch any command between text (human-readable) and machine-readable formats: + +| Format | Use for | Notes | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `text` (default) | Human-readable use | Plain text on stdout regardless of whether the stream is a TTY or piped. | +| `json` | Machine-readable use | Always valid JSON to stdout. Use `--error-format json` if you also want machine-readable errors on stderr. | +| `csv` | Tabular results (`query`, `bpa run`, `bpa rules`, `vertipaq`, `validate`, `test`, `refresh`, `profile list`, `session list`, `find`, `replace`, `get`, `ls`) | RFC 4180 escaping. | +| `tmsl` (alias `bim`) | Whole-object TMSL/BIM serialization | Accepted by `te get` and `te ls`. | +| `tmdl` | Whole-object TMDL serialization | Accepted by `te get` only (single object). | + +```bash +te ls --output-format json +te query -q "EVALUATE VALUES('Date'[Year])" --output-format csv +te bpa run --output-format json +``` + +> [!NOTE] +> `--output-format` and `--error-format` are independent. Setting `--output-format json` does _not_ switch stderr to JSON; pass `--error-format json` for that. There is no automatic format switching when stdout is redirected - the default is always `text` unless you ask otherwise. + +## Non-interactive mode + +Add `--non-interactive` to any command to disable confirmation prompts, credential picklists, and guided wizards. If the command needs input it cannot resolve from flags, environment, or config, it exits non-zero with an actionable error instead of hanging. + +```bash +te deploy ./model --non-interactive --force --ci github +``` + +## Exit codes + +Every `te` command exits with a predictable status code so callers can branch on success or failure without parsing stdout. + +| Exit | Meaning | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `0` | Success. | +| `1` | Generic failure - invalid arguments, command failed, validation errors, auth failure, BPA gate failed at severity ≥ error. | +| `2` | Used by `te diff` to indicate models differ (distinct from `0` identical and non-zero errors). | + +Combine exit codes with `--ci ` annotations and `--trx ` to surface rich failure information in CI - see @te-cli-cicd. + +## Errors on stderr + +Errors, warnings, and the preview banner are written to **stderr**; structured data is written to **stdout**. This means you can pipe JSON safely without it being contaminated by progress indicators or diagnostic messages: + +```bash +te ls --output-format json | jq '.[] | .name' +te vertipaq --output-format json > stats.json +``` + +## Python + +Python is a natural host for orchestrating CLI calls from data pipelines, notebooks, or test harnesses. Invoke `te` with `subprocess.run`, request JSON, and parse stdout: + +```python +import json +import subprocess + +def query(server: str, database: str, dax: str) -> list[dict]: + result = subprocess.run( + ["te", "query", + "-s", server, + "-d", database, + "-q", dax, + "--output-format", "json", + "--non-interactive"], + check=True, + capture_output=True, + text=True, + ) + return json.loads(result.stdout) + +rows = query("Finance", "Revenue Model", "EVALUATE TOPN(10, 'Sales')") +for row in rows: + print(row) +``` + +To capture structured errors from stderr: + +```python +import json +import subprocess + +result = subprocess.run( + ["te", "deploy", "./model", + "-s", "Finance", "-d", "Revenue", + "--output-format", "json", "--non-interactive", "--force"], + capture_output=True, text=True, +) + +if result.returncode != 0: + try: + err = json.loads(result.stderr.strip().splitlines()[-1]) + print("Deploy failed:", err.get("error"), "- hint:", err.get("hint")) + except json.JSONDecodeError: + print("Deploy failed:\n", result.stderr) +``` + +## PowerShell + +PowerShell handles JSON natively. `te` is a regular console binary that works directly in PowerShell pipelines (see @te-cli-migrate if you're porting from the older `TabularEditor.exe` CLI): + +```powershell +$rows = te query -s Finance -d Revenue -q "EVALUATE TOPN(10, 'Sales')" --output-format json --non-interactive + | ConvertFrom-Json + +$rows | Format-Table + +# Check exit code after the pipeline +if ($LASTEXITCODE -ne 0) { + Write-Error "Query failed with exit $LASTEXITCODE" + exit $LASTEXITCODE +} +``` + +Read secrets from the environment rather than passing them as plaintext: + +```powershell +$env:AZURE_CLIENT_ID = "your-app-id" +$env:AZURE_CLIENT_SECRET = "your-client-secret" +$env:AZURE_TENANT_ID = "your-tenant-id" + +te deploy ./model ` + -s my-workspace -d my-model ` + --auth env --non-interactive --force --ci vsts +``` + +## Bash + +Compose commands with pipes and `jq`. The CLI's text output is colorized for humans, but switching to `--output-format json` gives you a clean shape to work with: + +```bash +# Count measures per table +te ls --type measure --output-format json \ + | jq -r '.[] | .table' \ + | sort | uniq -c | sort -rn +``` + +```bash +# Fail the shell script if BPA finds any errors +te bpa run --fail-on error --output-format json > bpa.json \ + || { echo "BPA gate failed"; jq '.violations' bpa.json; exit 1; } +``` + +## Composability example + +Generating a refresh TMSL script and version-controlling it is three commands: + +```bash +te connect MyWorkspace MyModel +te refresh --type full --dry-run > refresh.tmsl +cat refresh.tmsl +``` + +The resulting TMSL can be reviewed in a pull request, committed, executed by the CLI (`te refresh --type full`), handed to a DBA, or applied by any XMLA-compatible tool. The CLI becomes a building block rather than a black box. + +## Useful patterns + +A handful of small idioms that come up often when composing `te` commands in scripts or pipelines: + +- **Idempotent creates and removes.** `te add Sales/Marker -t Measure -i "0" --if-not-exists --save` and `te rm Sales/OldMeasure --if-exists --save` both exit `0` whether or not the object existed - safe to re-run in CI. +- **Dry-run diffs.** `te replace` is dry-run by default; add `--save` only when you're satisfied with the preview. +- **Emit TMSL for review.** `te deploy ./model --xmla deploy.tmsl` produces the deployment script without touching the server - useful for DBA review or manual apply. +- **Path-only output.** `te ls --paths-only` and `te find --paths-only` emit one object path per line, ideal for piping to `xargs`, `te get`, or `te set`. The model-level containers (`te ls Measures`, `te ls Columns`) compose well with this for whole-model sweeps. +- **Benchmarking queries.** `te query --trace --cold --runs 5` runs a DAX query with cold cache, five iterations, and captures FE/SE trace events. +- **Step timings in CI logs.** Long-running commands (`te deploy`, `te refresh`, `te script`, `te validate`) include a `durationMs` field in JSON output - useful for surfacing per-step timings in pipeline summaries. + +## Related pages + +- @te-cli-cicd - pipeline-specific patterns and YAML examples. +- @te-cli-commands - full command reference. +- @te-cli-interactive - when interactive mode fits better than scripting. diff --git a/localizedContent/zh/content/features/te-cli/te-cli-cicd.md b/localizedContent/zh/content/features/te-cli/te-cli-cicd.md new file mode 100644 index 000000000..d39da955b --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-cicd.md @@ -0,0 +1,235 @@ +--- +uid: te-cli-cicd +title: CI/CD Integration +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# CI/CD Integration + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI is designed for unattended execution in continuous integration and delivery pipelines. A single binary, structured output, non-interactive mode, native CI annotations for GitHub Actions and Azure DevOps, and VSTEST-compatible test results make it a natural replacement for ad-hoc TE2 invocations. + +> [!WARNING] +> **Do not use the CLI in production pipelines during Limited Public Preview.** Two preview-specific risks apply to pipeline owners: +> +> - **Hard expiry.** The preview binary stops functioning on **2026-09-30** - any pipeline depending on it will fail on that date, regardless of your release calendar. +> - **No backwards-compatibility guarantee.** Commands, flags, output shapes, and exit codes may change between preview builds, so pipeline steps may need updating when you refresh the vendored binary. +> +> Build and evaluate in non-production pipelines, and share feedback in the public [TabularEditor/CLI](https://github.com/TabularEditor/CLI) repository so the GA version matches your needs. + +## What makes the CLI CI-friendly + +- **Single self-contained binary.** No runtime install, no `TabularEditor.exe`, no `start /wait`. +- **`--non-interactive` global flag.** Disables every prompt; fails fast with actionable errors. +- **`--force`** on mutating commands (`te deploy`, `te refresh`) skips confirmation prompts. +- **`--ci vsts` / `--ci github`.** Emit native pipeline annotations to stderr. +- **`--trx `.** Produce VSTEST results consumable by Azure DevOps test publishing. +- **Structured errors.** `--output-format json` emits `{"error": "...", "hint": "..."}` to stderr so pipeline steps can fail with a useful message. + +## Adding the CLI to your repo + +During Limited Public Preview, the CLI is gated behind sign-in on [tabulareditor.com](https://tabulareditor.com/download-tabular-editor-cli), so pipelines cannot fetch the archive from a public URL. The simplest reproducible approach is to commit the binary that matches your runner into your repository and reference it from each pipeline step. + +A common layout: + +``` +your-repo/ +└── tools/ + └── te/ + ├── te # Linux / macOS binary (needs chmod +x at runtime) + └── te.exe # Windows binary +``` + +Place the **extracted** binary - not the archive - so the pipeline can call it directly. Pick the build that matches your runner OS/arch; see @te-cli-install for the filename table. The self-contained binary is ~70 MB; consider Git LFS if your repo is sensitive to size. + +> [!NOTE] +> Committing the binary also pins the CLI version to whatever you checked in, which is desirable for CI reproducibility. To upgrade, replace the binary in `tools/te/` and commit it - the commit message is your version log. Keep in mind that the preview binary still expires on **2026-09-30** regardless of when you committed it, so a vendored copy is not a permanent dependency - plan to refresh it (and re-validate your pipeline against the new API surface) on preview-build cadence. + +## GitHub Actions + +A complete deploy + test workflow. The example assumes the Linux `te` binary is committed at `tools/te/te`, and a service principal is stored in repository secrets (`AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_TENANT_ID`). + +```yaml +name: Deploy semantic model + +on: + push: + branches: [main] + +jobs: + deploy: + runs-on: ubuntu-latest + env: + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + steps: + - uses: actions/checkout@v4 + + - name: Set up Tabular Editor CLI + run: | + chmod +x ./tools/te/te + echo "$GITHUB_WORKSPACE/tools/te" >> $GITHUB_PATH + + - name: Validate + run: te validate ./model --ci github --trx validate.trx + + - name: Best Practice Analyzer (gate) + run: te bpa run ./model --fail-on error --ci github --trx bpa.trx + + - name: Deploy + run: | + te deploy ./model \ + -s "${{ vars.WORKSPACE }}" \ + -d "${{ vars.MODEL }}" \ + --auth env \ + --non-interactive \ + --force \ + --ci github + + - name: Regression tests + run: | + te test run \ + -s "${{ vars.WORKSPACE }}" \ + -d "${{ vars.MODEL }}" \ + --auth env --non-interactive \ + --ci github --trx tests.trx + + - name: Publish test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: trx-results + path: '*.trx' +``` + +## Azure DevOps Pipelines + +The Azure DevOps Pipelines equivalent of the GitHub Actions workflow above. The example assumes `te.exe` is committed at `tools\te\te.exe`. `--ci vsts` emits `##vso[...]` commands that the pipeline interprets as errors, warnings, and task-status updates. + +```yaml +trigger: + - main + +pool: + vmImage: 'windows-latest' + +variables: + - group: 'te-cli-secrets' # Contains AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID + +steps: + - checkout: self + + - powershell: Write-Host "##vso[task.prependpath]$(Build.SourcesDirectory)\tools\te" + displayName: 'Set up Tabular Editor CLI' + + - script: te validate ./model --ci vsts --trx validate.trx + displayName: 'Validate' + + - script: te bpa run ./model --fail-on error --ci vsts --trx bpa.trx + displayName: 'BPA gate' + + - script: | + te deploy ./model ^ + -s "$(WORKSPACE)" -d "$(MODEL)" ^ + --auth env --non-interactive --force --ci vsts + displayName: 'Deploy' + env: + AZURE_CLIENT_ID: $(AZURE_CLIENT_ID) + AZURE_CLIENT_SECRET: $(AZURE_CLIENT_SECRET) + AZURE_TENANT_ID: $(AZURE_TENANT_ID) + + - script: te test run -s "$(WORKSPACE)" -d "$(MODEL)" --auth env --non-interactive --ci vsts --trx tests.trx + displayName: 'Regression tests' + env: + AZURE_CLIENT_ID: $(AZURE_CLIENT_ID) + AZURE_CLIENT_SECRET: $(AZURE_CLIENT_SECRET) + AZURE_TENANT_ID: $(AZURE_TENANT_ID) + + - task: PublishTestResults@2 + condition: always() + inputs: + testResultsFormat: 'VSTest' + testResultsFiles: '*.trx' +``` + +## BPA gate patterns + +`te deploy` and `te save` run the Best Practice Analyzer as a pre-flight gate by default. Three behaviors are worth determining up-front: + +- **Enforce** - the default. Pipeline fails if BPA finds violations at severity ≥ error. Pair with `--fail-on warning` on a standalone `te bpa run` step if you want warnings to fail too. +- **Auto-fix** - `--fix-bpa` applies `fixExpression`s in memory for the deployed artifact. Source files are not modified. Useful when the source of truth lives in the model and you want deploys to normalize style without developer intervention. +- **Bypass** - `--skip-bpa` disables the gate for a single command. Useful for emergency hotfixes; not recommended as a default. + +```bash +# Treat warnings as failures in PR validation +te bpa run ./model --fail-on warning --ci github --trx bpa.trx + +# Auto-fix during deploy (source unchanged) +te deploy ./model -s my-ws -d my-model --fix-bpa --force --ci github + +# Emergency bypass +te deploy ./model -s my-ws -d my-model --skip-bpa --force --ci github +``` + +See @te-cli-config for controlling the BPA gate globally via `bpa.onDeploy` / `bpa.onSave` config keys. + +## Refresh patterns + +Refresh in pipelines is typically a follow-up step after deployment. Use `--non-interactive` and pick a deterministic `--type`: + +```bash +# Full refresh of the whole model after deploy +te refresh -s my-ws -d my-model --type full --non-interactive + +# Refresh a single fact table (e.g., daily incremental pipeline) +te refresh -s my-ws -d my-model --table Sales --type full --non-interactive + +# Recalculate only (useful after calculation-group changes) +te refresh -s my-ws -d my-model --type calculate --non-interactive +``` + +For incremental refresh workflows, combine `--apply-refresh-policy`, `--effective-date `, and `--partition ` flags. See @te-cli-commands for details. + +## Artifact patterns + +Emit TMSL or XMLA as an artifact without deploying, so DBAs or a later job can review or apply it: + +```bash +# Produce the XMLA/TMSL script that would deploy - do not deploy +te deploy ./model -s my-ws -d my-model --xmla deploy.tmsl --force + +# Produce the TMSL refresh command - do not execute +te refresh -s my-ws -d my-model --type full --dry-run > refresh.tmsl +``` + +Commit these artifacts to git, upload them to the pipeline's artifact storage, or pass them between jobs. They're plain text and diff cleanly in pull requests. + +## Secret handling + +| Approach | When to use | Notes | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Service principal via env vars (`AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET` / `AZURE_TENANT_ID`, `--auth env`) | General CI/CD | Map pipeline secrets to environment variables at the step or job level. Never pass secrets in command arguments. | +| Service principal via `te auth login` once per job (`echo $SECRET \| te auth login -u $ID -p - -t $TENANT`) | Multi-step jobs | The login is cached, so subsequent `te` commands acquire tokens silently - no need to set `AZURE_CLIENT_*` for every step or re-pass `-u/-p/-t`. Pipe the secret via stdin rather than interpolating it. | +| Managed identity (`--auth managed-identity`) | Azure VMs, Container Apps, Azure Functions | No secrets to manage. Preferred in Azure-hosted environments. | +| Certificate (`--certificate `) | Enterprise scenarios with cert rotation | Mount the certificate as a secure file step; pass `--certificate-password` via env. | + +> [!WARNING] +> Do not echo secrets or the output of `te auth status` to pipeline logs. The CLI writes warnings to stderr when secrets are passed on the command line - respect those warnings in CI. + +## Related pages + +- @te-cli-auth - authentication methods in detail. +- @te-cli-config - configuration and profile overrides. +- @te-cli-automation - general scripting patterns. +- @te-cli-migrate - migrating an existing TE2-based pipeline. diff --git a/localizedContent/zh/content/features/te-cli/te-cli-commands.md b/localizedContent/zh/content/features/te-cli/te-cli-commands.md new file mode 100644 index 000000000..83a196b5f --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-commands.md @@ -0,0 +1,889 @@ +--- +uid: te-cli-commands +title: 命令参考 +author: Peer Grønnerup +updated: 2026-05-12 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# 命令参考 + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +本页为每个命令提供简要说明和一个示例。 每个命令都支持 `--help`,可查看详尽的标志与选项说明: + +```bash +te deploy --help # Help for a single command +te bpa run --help # Help for a command with subcommands +``` + +> [!NOTE] +> 在预览版期间,CLI 的 `--help` 输出是标志和选项的权威参考。 本页内容由人工整理,因此在两次预览版本之间新增的内容,本页更新会比 `--help` 更晚。 + +## 对象路径 + +CLI 中的对象定位在所有命令中都采用同一套语法。 以下参考中会出现两种路径形式: + +- **``** - 解析为**恰好一个**对象或容器。 用于对单个目标执行操作的命令:`te get`、`te set`、`te add`、`te rm`、`te mv`、`te format -p`、`te deps`、`te macro run --on`。 +- **``** - 解析为**零个或多个**对象,并支持通配符。 用于对一组对象执行操作的命令:`te ls`、`te bpa run --path` 以及其他用于检查的命令。 + +两种路径形式共用同一套语法规则;仅有两处不同: + +- 筛选路径允许使用 `*` 通配符;对象路径不允许。 +- 对象路径允许使用 DAX 方括号后缀(例如 `Sales[Amount]`);筛选路径不允许。 + +### 分段和分隔符 + +路径是由斜杠分隔的 **分段** 序列。 每个分段表示一个步骤:一个表、一个子对象,或一个容器关键字。 + +- `Sales` — 一个分段 +- `Sales/Revenue` — 两个分段 +- `Roles/Admin/Members/bob` — 四个分段 + +空输入和 `.` 都表示“模型根”——它既是筛选路径的隐式起点,也是 `te get .` 这类查询显式指向的对象。 + +### 引号 + +大多数分段名称无需加引号即可直接使用。 如果分段名称包含空格、斜杠、方括号,或任何其他会被解析为语法的字符,请将该分段用引号括起来。 CLI 遵循 DAX 的引号规则,因此在 `te` 路径中加引号的写法与在 DAX 表达式中输入的一致: + +| 形式 | 适用场景 | 转义规则 | +| ---------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------- | +| `'Net Sales'` | 表,以及名称中带空格的对象。 | 将引号写两次(`'Bob''s'` → `Bob's`)。 | +| `"Net Sales"` | 同上;当单引号转义不方便时,跨不同 shell 使用会更省事。 | 将引号写两次(`"He said ""hi"""` → `He said "hi"`)。 | +| `[Sales Amount]` | 表引用中的 DAX 方括号后缀(`'Sales'[Sales Amount]`),或不带表前缀、在整个模型范围内解析的单独方括号引用(`[Total Sales]`)。 仅限对象路径。 | 将右方括号写两次(`[foo]]bar]` → `foo]bar`)。 | + +在带引号的分段内,`*` 会被视为字面字符,而不是通配符。 因此,`'Sa*'` 会匹配名称恰好为 `Sa*` 的表。 + +### DAX 风格的引用(仅对象路径) + +凡是允许使用 `` 的位置,都接受两种 DAX 形式: + +- **`'Table'[Member]`**:等同于 `Table/Member`。 方括号后缀会在存在歧义时优先匹配列和度量值,而不是层次结构/分区。 +- **`[Member]`**:一个_独立_的度量值或列,前面不带表名。 在整个模型中搜索具有该名称的度量值或列。 两者都存在时,优先选择度量值。 + +```bash +te get "'Sales'[Amount]" # Same as te get Sales/Amount +te get "'Net Sales'[Sales Amount]" # Spaced names via DAX form +te get "[Total Sales]" # Model-wide measure-or-column lookup +``` + +### 容器和关键字 + +有一些名称可用作容器关键字。 关键字既可以单独使用(列出整个容器),也可以出现在路径中(跳转到当前父级下的该子集合)。 + +| 关键字 | 范围 | 含义 | +| --------------------------------------------------------------------------------------------------------------------- | ---- | ------------ | +| `Tables`, `度量值`, `Columns`, `Hierarchies`, `分区` | 模型 | 模型中该类型的所有对象。 | +| `关系`, `角色`, `Perspectives`, `Cultures`, `DataSources`, `Expressions`, `CalculationGroups`, `Functions`, `Annotations` | 模型 | 模型级容器。 | +| `度量值`, `Columns`, `Hierarchies`, `分区`, `Calendars`, `CalculationItems` | 表 | 表下的子容器。 | +| `Levels` | 层次结构 | 层次结构的级别。 | +| `Members`, `TablePermissions`(别名 `Permissions`) | 角色 | 角色的子级对象。 | + +以下示例展示普通路径与限定容器范围的路径之间的区别: + +```bash +te get Sales/Revenue # Measure or column on Sales +te get Sales/Measures/Revenue # Same, container-scoped - disambiguates if other kinds share the name +te get Sales/Geography/Levels/Year # Specific level of a hierarchy +te get Roles/Admin/Members/bob@example.com # Role member +te get Sales/refreshPolicy # Refresh-policy sub-object on a table +te get "Measures/Revenue/KPI" # KPI sub-object of a measure +``` + +当实际对象名称恰好与关键字同名时,可为该分段加上引号,以强制进行字面名称匹配。 字面名称为 `Tables` 的表需要写作 `'Tables'`,可通过 `te get "'Tables'"` 访问。 + +### 筛选路径中的通配符 + +筛选路径引入了一个通配符字符 `*`,用于匹配单个分段内任意长度的字符序列(贪婪匹配,且仅限单个分段)。 通配符是 `te ls` 和类似命令用来缩小结果范围的方式。 + +```bash +te ls 'Sa*' # Tables whose name starts with Sa +te ls 'Sales/*Amount' # Children of Sales whose name ends with Amount +te ls '*/Amount' # An Amount column/measure across every table +te ls 'Roles/Re*/Members' # Members of every role matching Re* +``` + +包含 **N 个分段** 的筛选路径会返回 **N 层深度** 的结果——通配符不会自动多展开一层,结果深度不会超过你输入的层级。 单分段快捷写法 `te ls Sales` 是个例外:未限定且不含通配符的表名会展开为该表的直接子项,以符合“让我看看 Sales 里有什么”的意图。 相比之下,`te ls Sa*` 只返回匹配的表,不会展开。 + +筛选路径中不支持 DAX 的方括号后缀;如需按字面匹配包含 `[` 和 `]` 的名称,请给名称加引号。 + +### 错误和提示 + +分段拼写错误时会给出一条与上下文相关的错误;如果 CLI 能猜到你的意图,还会附带“你是不是想输入……”的提示。 缺少父级的路径会在检查叶节点之前失败,因此信息会指向真正出错的分段。 空容器(例如,在没有层次结构的模型上运行 `te ls Hierarchies`)会给出简单的“这里没有内容”提示,而不是错误。 + +## 全局选项 + +这些标志适用于每个命令,可在子命令名称之前或之后使用。 + +| 选项 | 说明 | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-m, --model ` | 语义模型的路径(TMDL 文件夹、`.bim` 文件或 TE 文件夹)。 | +| `-s, --server ` | Workspace 名称或终结点(例如 `MyWorkspace`、`powerbi://...`、`asazure://...`、`localhost`)。 | +| `-d, --database ` | Workspace 上的语义模型名称。 | +| `--local` | 连接到本地运行的 Power BI Desktop 实例(仅限 Windows)。 | +| `--auth ` | 身份验证方法:`auto`、`interactive`、`spn`、`env`、`managed-identity`(默认值:`auto`)。 | +| `--output-format ` | 标准输出格式:`text` (默认)、`json`、`csv`、`tmsl` (别名 `bim`)、`tmdl`。 `csv` 会被输出表格数据的命令采用;`tmsl`/`tmdl` 仅在 `te get` 和 `te ls` 中用于整个对象的序列化。 命令会拒绝其不支持的格式。 | +| `--error-format ` | 用于错误、警告和提示的 stderr 格式:`text`(默认)或 `json`。 其他值将回退为 `text`。 它独立于 `--output-format`,因此你可以将 JSON 格式的 stdout 与纯文本错误配合使用(反之亦然)。 | +| `--recent [N]` | 使用最近使用过的模型。 未提供值 = 进入交互式选择器;`N` = 最近使用列表中的第 N 个(1 = 最近一次使用)。 | +| `--non-interactive` | 禁用所有交互式提示。 如果缺少必需输入,将给出可操作的错误提示并失败退出。 | +| `--debug` | 启用调试日志并输出到 stderr(连接字符串、身份验证流程、耗时)。 | + +对于读取模型的命令,解析顺序如下: + +位置参数 `` → 全局选项 `--model` → `--server`/`--database`(远程)→ `te connect` 的当前活动连接 → `--recent`。 + +## 模型 I/O + +### load + +加载语义模型,并显示模型摘要——名称、兼容级别以及主要对象数量(表、度量值、列)。 + +```bash +te load ./model # TMDL folder +te load model.bim # BIM file +te load -s MyWorkspace -d MyModel # Remote workspace +``` + +### save + +将模型保存到磁盘。 可用于将远程 Workspace 中的模型写入本地文件、转换格式,或将编辑内容保存回源位置。 + +`te save` 接受: + +- `-o, --output-path ` - 目标文件或文件夹。 **可选** - 若省略,`te save` 会写回源位置,保留原始格式。 +- `--serialization ` - `tmdl`, `bim`, `te-folder`, `pbip`, `database.json`。 默认会从已加载的模型中推断(BIM 源 → BIM;TMDL `SemanticModel/` → `definition/` 下的 TMDL)。 +- `--force` - 跳过验证并覆盖现有输出。 某些拒绝情况(例如容器不明确、项目根目录中存在多个 `SemanticModel`)即使使用 `--force` 也会触发。 +- `--skip-bpa` - 完全绕过 BPA 检查。 +- `--fix-bpa` - 当规则定义了修复表达式时,自动修复 BPA 违规项。 +- `--bpa-rules ` - 可重复指定;仅对本次保存覆盖 CLI 配置中的 `bpa.rules`。 除非 `bpa.builtInRules` 为 `false`,否则内置规则仍会生效。 +- `--skip-validation` - 跳过 DAX 语义分析和验证,以实现快速直通下载。 +- `--supporting-files` - 生成 Fabric 支持文件(`.platform`、`definition.pbism`)。 + +```bash +te save # Save back to source (no -o needed) +te save ./model.bim -o ./tmdl-out # Convert BIM to TMDL +te save -o ./project --serialization pbip # Save as a PBIP project +te save -o ./out -s my-workspace -d my-model --skip-validation # Fast download +``` + +> [!TIP] +> 你可以用 `te save -o -s -d ` 把远程模型下载到磁盘。 如果你只需要原始字节数据(不做 DAX 语义分析),配合 `--skip-validation` 可实现最快的直通下载。 + +### open + +在 Tabular Editor 3 桌面版中打开模型。 **仅限 Windows**(需要先安装 TE3)。 + +```bash +te open ./my-model +``` + +### init + +在指定路径创建一个新的空语义模型。 + +```bash +te init ./new-model +``` + +## 模型编辑 + +### set + +设置模型对象的属性。 接受 `` 参数。 + +`te set` 接受以下参数: + +- `-q ` - 属性名称(例如 `expression`、`formatString`、`description`、`isHidden`)。 +- `-i ` - 值(使用 `-` 可从 stdin 读取)。 +- `--save` / `--save-to ` - 保存更改。 + +```bash +te set Sales/Amount -q expression -i "SUM(Sales[Amt])" --save +te set "'Net Sales'[Sales Amount]" -q formatString -i "#,0" --save # DAX form with spaced names +te set Sales -q isHidden -i true --save +``` + +### 添加 + +向模型添加对象。 为新对象传入 ``(父级必须已存在;最后一个分段就是新名称),并通过 `-t` / `--type` 指定类型。 关系仍使用其简写语法(`Sales[Key]->Dim[Key]`)。 + +`te add` 支持以下选项: + +- `-t, --type ` - 指定对象类型。 常用值:`Table`、`Measure`、`Column`、`CalculatedColumn`、`Hierarchy`、`Role`、`Perspective`、`Culture`、`CalculationGroup`、`CalculationItem`。 支持 Tab 自动补全;可通过运行 `te add --help` 获取完整列表。 +- `--if-not-exists` - 如果对象已存在,则直接以 `0` 退出且不报错。 可用于幂等的 CI/CD 管道。 + +```bash +te add Sales/Revenue -t Measure -i "SUM(Sales[Amount])" --save +te add Sales -t Table --save +te add "Sales[ProdKey]->Product[ProdKey]" --save # Relationship shorthand +te add Sales/MarketingFlag -t CalculatedColumn -i "Sales[Amount] > 1000" --if-not-exists --save +te add Perspectives/Default/Sales --save # Include Sales in the Default perspective +te add Roles/Reader -t Role --save # New role at the model level +``` + +对于数据绑定表,`te add` 还支持从 SQL、Lakehouse 或 Warehouse 源推断架构。 有关 `--source`、`--endpoint`、`--source-table`、`--columns` 等参数,可查看 `te add --help`。 + +### rm + +删除对象。 默认会检查依赖对象,以避免破坏现有引用。 + +`te rm` 接受: + +- `` — 位置参数:要删除的对象。 +- `--force` — 跳过依赖对象检查。 +- `--if-exists` — 如果对象不存在,则直接以 `0` 退出且不报错。 可用于幂等的 CI/CD 管道。 +- `--dry-run` — 预览删除操作而不实际执行。 +- `--save` — 将更改保存到已加载的模型。 + +```bash +te rm Sales/Revenue --save +te rm "'Sales'[Revenue]" --save # DAX form +te rm Sales/Revenue --dry-run # Preview only +te rm Sales/OldMeasure --if-exists --save # Idempotent +``` + +### mv + +移动或重命名模型对象。 源和目标都是 `` 参数。 + +```bash +te mv Sales/Revenue Finance/Revenue --save # Move measure to another table +te mv Sales/Revenue Sales/TotalRevenue --save # Rename measure +``` + +### replace + +在各个模型对象中查找并替换文本。 默认仅进行干运行;添加 `--save` 才会实际应用更改。 + +`te replace` 接受: + +- `--in ` - 作用域:`names`、`expressions`、`descriptions`、`displayFolders`、`formatStrings`、`annotations`、`all`(默认值:`all`)。 +- `--regex` - 将查找模式视为正则表达式。 +- `--case-sensitive` - 启用大小写敏感匹配。 +- `--dry-run` - 仅预览更改,不会实际应用。 默认行为。 +- `--save` - 将变更保存回源位置。 与 `--revert` 和 `--stage` 互斥。 +- `--save-to ` - 保存到不同的路径(意味着 `--save`)。 +- `--serialization ` - 模型序列化格式:`tmdl`、`bim`、`te-folder`。 +- `--force` - 即使替换引入 DAX 验证错误,也会保存。 + +`--in expressions` 会遍历所有包含表达式的属性: + +- **度量值**:`Expression`、`DetailRowsExpression` +- **KPI**:`TargetExpression`、`StatusExpression`、`TrendExpression` +- **分区**:源 M、轮询 M +- **表格权限**:`FilterExpression` +- **计算组**:选择表达式 +- **计算列**:DAX 表达式 + +在模型中新增具有表达式形态的属性后,工具会自动将其纳入遍历范围。 + +```bash +te replace "OldTable" "NewTable" --in expressions --save +te replace "SUM" "SUMX" --regex --in expressions --save +``` + +## 检查 + +### ls + +以类似文件系统的导航方式列出对象。 接受一个支持通配符的 `` 参数。 同时支持模型级容器(`Tables`, `Measures`, `Columns`, `Hierarchies`, `Relationships`, `Roles`, `Perspectives`, `Cultures`)以及表范围容器(`Sales/Measures`, `Sales/Columns`, …) 均受支持。 + +`te ls` 支持: + +- `--type ` - 限定为一种对象类型(`table`, `measure`, `column`, `hierarchy`, `partition`, `relationship`, `role`, `perspective`, `culture`)。 如果不提供 ``,这等同于输入匹配的容器关键字。 +- `--paths-only` - 每行输出一个对象路径,适合通过管道传给 `xargs`、`te get` 或 `te set`。 +- `--no-multiline` - 将多行单元格(通常是 DAX 或 M 表达式)折叠为单行并截断,让宽表中的各行仍便于浏览。 仅影响文本输出;JSON/CSV/TMSL 输出不受影响。 +- `--output-format tmsl`(别名 `bim`)- 将匹配的对象输出为 TMSL/BIM 脚本。 例如可用于 `te ls Tables --output-format bim > tables.json`。 `ls` 不支持 `--output-format tmdl`(TMDL 仅支持单对象输出——请使用 `te get`)。 + +```bash +te ls # All tables in the model +te ls Sales # All children of Sales (columns + measures + hierarchies + partitions) +te ls Sales/Measures # Just Sales's measures +te ls 'Sales/*Amount' # Children of Sales whose name ends with Amount +te ls 'Sa*' # Tables whose name starts with Sa (no auto-expansion) +te ls '*/Amount' # An Amount column/measure across every table +te ls 'Roles/Re*/Members' # Members of every role matching Re* +te ls Sales/Geography/Levels # All levels of the Geography hierarchy +te ls "'Net Sales'/'Sales Amount'" # Quote names containing spaces +te ls Measures --paths-only # One Table/Measure per line for piping +te ls --type measure # Same as `te ls Measures` +te ls Measures --no-multiline # Wide table with column dividers, single-line DAX +te ls Tables --output-format bim > tables.json # All tables emitted as TMSL/BIM +``` + +### get + +获取模型对象的属性。 接受一个 ``。 + +`te get` 支持: + +- `-q, --query ` - 获取单个属性(例如 `expression`、`formatString`)。 +- `-t, --type ` - 当路径匹配到表下的多个子对象时,用于消除歧义(例如同名的列和层次结构)。 可选值:`Measure`、`Column`、`CalculatedColumn`、`Hierarchy`、`Calendar`、`Partition`、`CalculationItem`。 +- `--output-format tmsl`(别名 `bim`)- 将解析后的对象输出为 TMSL/BIM JSON。 +- `--output-format tmdl` - 将解析后的对象输出为 TMDL(仅限命名对象)。 + +`te get` 和 `te ls` 共用同一个描述符目录,因此无论输出为哪种格式,属性的呈现方式都一致:文本表格、JSON 和 CSV 显示的都是同一组属性;给模型新增属性后,也会在所有格式中自动可见。 + +```bash +te get Sales/Amount -q expression # Print DAX +te get "'Sales'[Amount]" # DAX form: same as Sales/Amount +te get "[Total Sales]" # Lone-bracket: model-wide measure-or-column +te get "'Net Sales'[Sales Amount]" -q expression # DAX form with spaced names +te get "Sales/Revenue/KPI" # KPI sub-object of a measure +te get Sales --output-format tmdl # Emit the table as TMDL +te get Sales --output-format bim # Emit the table as TMSL/BIM +te get Model -q description +``` + +### find + +在模型对象中搜索文本。 + +`te find` 支持: + +- `--in ` - 与 `te replace` 相同(默认值为 `all`)。 +- `--regex`、`--case-sensitive`、`--paths-only`。 +- `--no-multiline` - 将多行匹配上下文折叠为单行。 仅适用于文本输出。 + +`--in expressions` 涵盖模型中的每个 `IExpressionObject`——包括 KPI 的 `TargetExpression` / `StatusExpression` / `TrendExpression`、度量值的 `DetailRowsExpression`、分区源/轮询的 M 表达式、表权限的 `FilterExpression`,以及计算组的 `MultipleOrEmptySelection` / `NoSelection` 表达式——因此,设置在 KPI 目标上的字面量(例如 `123`)也会像度量值正文一样被找到。 + +```bash +te find "CALCULATE" --in expressions +te find "Revenue" --in names +te find "CALCULATE" --in expressions --paths-only | xargs -I{} te get {} -q expression +``` + +### diff + +比较两个模型的结构差异。 返回以下退出码:`0` 表示相同,`1` 表示发现差异,`2` 表示错误。 + +```bash +te diff ./model-v1 ./model-v2 +te diff old.bim new.bim +``` + +### deps + +分析对象的上游和下游依赖关系,或找出整个模型中未使用的对象。 单对象形式接受一个 ``。 + +`te deps` 接受以下选项: + +- `--unused` - 列出未被任何 DAX 引用,且未用于任何关系、层次结构级别、排序依据、变体、AlternateOf 基对象或日历时间角色的度量值、计算列以及**所有数据列**。 每条结果在文本模式下会显示 `(hidden)`,在 JSON 中则包含 `isHidden` 字段。 +- `--hidden` - 将 `--unused` 限制为仅包含隐藏对象。 隐藏且未使用的对象是最安全的清理候选项,因为没有任何用户可见内容依赖它们。 + +```bash +te deps Sales/Revenue # Upstream + downstream for one object +te deps "'Sales'[Revenue]" # DAX form is accepted everywhere a is +te deps --unused # All unused measures and columns +te deps --unused --hidden # Only hidden, unused objects +``` + +## 分析和质量 + +### validate + +验证模型表达式、架构完整性和 TOM 错误。 + +`te validate` 接受以下选项: + +- `--ci ` - 将 CI 注释输出到 stderr:`vsts` 或 `github`。 +- `--trx ` - 将结果写入 VSTEST `.trx` 文件。 + +```bash +te validate ./model +te validate --ci github --trx results.trx +``` + +### bpa run + +针对模型运行 Best Practice Analyzer 规则。 + +`te bpa run` 接受以下选项: + +- `` - 位置参数:模型路径(可替代全局标志 `--model`)。 +- `-r, --rules ` - JSON 格式的 BPA 规则文件(s)的路径(s)或 URL(s)。 可重复指定。 替换本次调用的用户规则层:请参阅下文的 [规则源和解析](#rule-sources-and-resolution)。 +- `--no-model-rules` - 排除嵌入在模型注释中的 BPA 规则。 +- `--no-defaults` - 排除内置的默认 BPA 规则。 +- `--vpax ` - 从 `.vpax` 文件加载 VertiPaq分析器统计信息,以启用可感知 VPA 的规则。 +- `--vpa-rules` - 包含内置的 VPA 感知规则(需要 `--vpax` 或预先标注的模型)。 +- `--allow-external-rules` - 允许从嵌入在模型注释中的 URL 获取 BPA 规则文件。 +- `--rule ` - 仅按 ID 运行指定规则(s)。 可重复指定。 +- `--path ` - 将分析限制为包含匹配对象的表。 支持字面名称、容器关键字和通配符(例如 `'Sales'`、`'Sa*'`、`'Sales/度量值'`、`'*/Amount'`)。 +- `--fix` - 应用修复表达式,在可能的情况下自动修复违规项。 +- `--save` - 应用修复后,将模型保存回原始位置。 +- `--save-to ` - 应用修复后,将模型保存到其他路径。 +- `--serialization ` - 模型序列化格式:`tmdl`、`bim`、`te-folder`。 +- `--fail-on ` - 失败阈值:`error`(默认)或 `warning`。 当违规项达到该阈值时,将以退出代码 `1` 退出。 +- `--ci ` - 向 stderr 输出 CI 日志命令:`vsts`(Azure DevOps)、`github`(GitHub Actions)。 +- `--trx ` - 将结果作为 VSTEST `.trx` 文件写入指定路径。 +- `--no-multiline` - 将违规表中的多行单元格内容折叠为单行。 仅适用于文本输出。 + +```bash +te bpa run --fail-on error --ci github +te bpa run --fix --save +te bpa run --rule PERF_UNUSED_HIDDEN_COLUMN +te bpa run --path Sales # Tables touched by the Sales filter only +te bpa run --path 'Sa*' # Wildcard - every table starting with Sa +te bpa run --path Sales/Measures # Path filter applied to the matched tables +``` + +#### 规则来源与解析 + +每次调用 `te bpa run` 时,都会从三个彼此独立的层级整合规则: + +1. **用户规则** - 按优先级顺序,只有一个来源会生效: + - `-r, --rules ` 标志,接受文件路径或 URL (优先级最高) + - `TE_BPA_RULES` 环境变量 + - 来自 CLI 配置 (`~/.config/te/config.json`) 的 `bpa.rules` 数组 +2. **内置默认规则** - 除非传入 `--no-defaults`,或配置中的 [`bpa.builtInRules`](xref:te-cli-config#built-in-bpa-rules) 为 `false`,否则会加载。 `bpa.disabledBuiltInRuleIds` 中列出的单个内置规则会被跳过。 +3. **模型嵌入规则** - 模型 `BestPracticeAnalyzer_Rules` 注释中的规则;除非传入 `--no-model-rules`,否则会加载。 除非同时传入 `--allow-external-rules` 参数,否则会跳过外部 URL 注释。 + +重复的规则 ID 会被去重(用户规则优先于内置规则)。 然后会移除模型 `BestPracticeAnalyzer_IgnoreRules` 注释中的规则 ID。 + +输出中的 `Rules loaded:` 行会列出每个提供规则的层级,例如: + +``` +Rules loaded: 41 from 1 file(s) from bpa.rules config + built-in defaults + model annotations +``` + +### bpa 规则 + +管理 BPA 规则集——在本地规则文件或模型注释中列出、检查、初始化,以及启用或禁用规则。 内置规则是只读的。要跳过其中某一条而保留其余规则,请使用 `te bpa rules disable`(不要直接编辑内置规则集)。 + +子命令: + +| 子命令 | 用途 | +| ------------------------------- | ---------------------------- | +| `add [model]` | 添加新的 BPA 规则。 | +| [`disable`](#bpa-rules-disable) | 为当前用户禁用一条内置 BPA 规则。 | +| [`enable`](#bpa-rules-enable) | 重新启用先前已禁用的内置 BPA 规则。 | +| `ignore [model]` | 将规则添加到模型的忽略列表。 | +| [`init`](#bpa-rules-init) | 在解析后的 PATH 下创建一个空的 BPA 规则文件。 | +| [`list`](#bpa-rules-list) | 列出来自所有来源的 BPA 规则及其状态。 | +| `rm [model]` | 删除一条 BPA 规则。 | +| `set [model]` | 更新 BPA 规则的属性。 | +| `unignore [model]` | 从模型的忽略列表中移除一条规则。 | + +`te bpa rules` 的所有子命令都接受以下选项: + +- `--rules-file ` - 指定 BPA 规则 JSON 文件的 PATH。 默认使用你的 CLI 配置(`~/.config/te/config.json`)中 `bpa.rules` 的首个已存在条目,或使用 `TE_BPA_RULES` 环境变量。 +- `--model-rules` - 操作嵌入在模型注释中的规则,而非文件中的规则。 + +> [!IMPORTANT] +> `te bpa rules set` 和 `te bpa rules rm` 会拒绝修改内置规则 ID。 如果尝试这样做,命令将以退出码 `1` 退出,并提示改用 `te bpa rules disable`。 要自定义内置规则的行为,先禁用该内置规则,再添加一个使用不同 ID 的自定义副本: +> +> ```bash +> te bpa rules disable TE3_BUILT_IN_DATE_TABLE_EXISTS +> te bpa rules add MY_DATE_TABLE_EXISTS +> ``` + +#### bpa rules list + +列出来自所有来源的规则(内置、用户、模型)。 + +`te bpa rules list` 接受以下选项: + +- (默认)仅显示生效的规则。 +- `--all` - 包含已禁用和已忽略的规则。 +- `--disabled` - 仅显示你通过 `te bpa rules disable` 禁用的内置规则 ID。 +- `--ignored` - 仅显示其 ID 出现在模型的 `BestPracticeAnalyzer_IgnoreRules` 中的规则。 +- `--no-defaults` - 从输出中排除内置规则。 + +```bash +te bpa rules list # Active rules +te bpa rules list --all # Include disabled and ignored rules +te bpa rules list --ignored +``` + +已禁用的内置规则会在规则 ID 旁标记 `[disabled]`。 + +#### bpa rules init + +在配置的 PATH 处创建一个空的 BPA 规则文件(`[]`)。 在对尚不存在的路径执行 `te bpa rules set` / `te bpa rules rm` 之前,请先执行一次此命令。 + +`te bpa rules init` 接受以下选项: + +- `--force` - 用 `[]` 覆盖现有文件。 如果目标文件已存在,则必须提供此选项。 +- `--rules-file ` - 目标文件路径。 可出现在 `init` 子命令之前或之后。 + +路径解析(先匹配到的优先):`--rules-file` → `TE_BPA_RULES` 环境变量 → CLI 配置中 `bpa.rules[]` 的第一项 → `./BPARules.json` (当前工作目录)。 + +```bash +te bpa rules init +te bpa rules init --rules-file ./MyRules.json +te bpa rules init --force +``` + +#### bpa rules disable + +禁用单个内置 BPA 规则。 该规则 ID 会添加到 CLI 配置中的 `bpa.disabledBuiltInRuleIds`。 后续的门禁执行(deploy、save、mutation)以及 `te bpa run` 都会跳过已禁用的规则。 + +该命令是幂等的——对已禁用的规则再次运行 `disable` 会成功,但不会修改配置。 如果 `` 不是内置规则,命令会以退出代码 `1` 结束;可使用 `te bpa rules list` 查看有效的内置 ID。 + +```bash +te bpa rules disable TE3_BUILT_IN_DATE_TABLE_EXISTS +``` + +#### bpa rules enable + +通过从 `bpa.disabledBuiltInRuleIds` 中移除规则 ID,重新启用此前已禁用的内置 BPA 规则。 如果该规则当前并未被禁用,则以退出代码 `1` 结束。 + +```bash +te bpa rules enable TE3_BUILT_IN_DATE_TABLE_EXISTS +``` + +### vertipaq + +分析 VertiPaq 存储统计信息。 + +`te vertipaq` 支持: + +- `--columns`, `--relationships`, `--partitions`, `--all`。 +- `--export ` - 将 VertiPaq 统计信息导出为 `.vpax` 文件,以便离线分析。 +- `--import ` - 加载之前导出的 `.vpax` 文件并进行离线分析。 +- `--obfuscate` - 对导出的 VPAX 中的名称和表达式进行混淆处理。 +- `--top `、`--stats`、`--annotate`、`--save`。 + +```bash +te vertipaq # Columns by size (default) +te vertipaq --all # Tables, columns, relationships, partitions +te vertipaq --export stats.vpax +te vertipaq --import stats.vpax # Analyze offline +``` + +### format + +格式化 DAX 或 M/Power Query 表达式。 + +`te format` 支持: + +- `-e, --expression ` - 格式化单个内联表达式。 +- `-p, --path ` - 格式化指定的度量值或列。 +- `--lang ` - 默认值为 `dax`。 +- `--save` / `--save-to` - 持久化保存格式化后的表达式。 + +```bash +te format --save # Format all DAX +te format -p Sales/Amount --save # Single measure +te format -e "SUM ( Sales[Amount] )" # Inline +te format --lang m --save # Format M +``` + +## 执行 + +### 查询 + +针对已部署的模型执行 DAX 查询。 + +`te query` 支持以下选项: + +- `-q, --query ` - 内联查询。 +- `--file ` - 从文件读取查询。 +- `--limit ` - 默认为 100。 +- `-o, --output-file ` - 将结果写入文件(`.csv`、`.tsv`、`.json`、`.dax`)。 +- `--trace`, `--cold`, `--plan`, `--runs ` - 用于性能跟踪和基准测试。 +- `--no-validate` - 跳过执行前的 DAX 语义验证。 + +```bash +te query -q "EVALUATE TOPN(5, 'Sales')" -s my-ws -d my-model +te query --file query.dax --output-format json +``` + +### 脚本 + +针对语义模型执行一个或多个 C# Script。 CLI 使用与 Tabular Editor 3 Desktop 相同的脚本宿主,因此能在 TE3 中运行的脚本在这里也可原样运行。 + +`te script` 支持以下选项: + +- `-S, --script ` - `.cs` / `.csx` 文件(可重复指定)。 +- `-e, --expression ` - 内联 C#(使用 `-` 表示从 stdin 读取)。 +- `--save` / `--save-to` / `--serialization`。 +- `--dry-run`, `--timeout `。 + +```bash +te script --script fix.cs --save +te script -e "Info(Model.Tables.Count)" +echo "Info(Model.Name);" | te script -e - +``` + +> [!IMPORTANT] +> 如果你要迁移旧脚本,需要了解以下两个行为差异: +> +> - **CLI 脚本中不支持交互式选择。** 从 `te script` 调用 TE3 Desktop 辅助方法 `SelectMeasure()`, `SelectTable()`, `SelectColumn()`, `SelectObject()`, 和 `SelectObjects()` 时,会抛出 `NotSupportedException`,因为 CLI 没有可弹出的 UI。 在脚本外预先解析对象(s) 并将其传入;如果脚本需要与 TE3 共享,请将该调用包裹在 `try/catch` 中。 +> - **默认的 `using` 指令与 TE3 Desktop 一致。** 使用 `DataTable`、`File`、`StringBuilder` 或 `Regex` 的脚本,必须显式包含对应的 `using System.Data;` / `using System.IO;` / `using System.Text;` / `using System.Text.RegularExpressions;` 指令。 + +> [!NOTE] +> **跨宿主脚本的预处理器符号。** 由 `te script` 编译的脚本会定义符号 `TECLI`。 TE3 Desktop 脚本会改为定义 `TE3`,并且还会定义带版本范围限定的符号,例如 `TE3_3_10_OR_GREATER` …… 当前 TE3 次版本对应的是 `TE3_3_X_OR_GREATER`。 TE2 不定义这两个符号。 使用这些符号可编写可移植脚本: +> +> ```csharp +> #if TECLI +> // CLI-only code - no UI calls +> Info($"Running under the CLI on {Environment.OSVersion.Platform}"); +> #elif TE3 +> // TE3 Desktop-only code - UI APIs available +> ShowMessage("Hello from TE3"); +> #else +> // TE2 (legacy) - neither TECLI nor TE3 is defined +> Info("Hello from TE2"); +> #endif +> +> #if TE3_3_15_OR_GREATER +> // Gated on a specific TE3 minor version +> #endif +> ``` +> +> 更全面的跨版本脚本说明,见 @csharp-scripts。 + +### 宏 + +通过宏 JSON 文件(通常为 `MacroActions.json`)管理和运行宏。 宏文件的 PATH 按以下顺序解析:`--macros ` → 环境变量 `TE_MACROS_PATH` → CLI 配置中的 `macros` → `./MacroActions.json`。 + +子命令: + +| 子命令 | 用途 | +| ---------------------------------- | ------------------- | +| `list` | 列出宏。 | +| 宏:[`run `](#macro-run) | 运行宏。 | +| `add ` | 添加宏。 | +| `set ` | 更新宏属性。 | +| `rm ` | 删除宏。 | +| `sort` | 排序并重新分配 ID。 | +| 宏:[`init`](#macro-init) | 在解析得到的路径处创建一个空的宏文件。 | + +#### 宏 init + +在配置的路径下创建一个空的宏文件(`{\"Actions\":[]}`)。 当解析后的宏文件尚不存在时,只需运行一次该命令。 + +`te macro init` 接受: + +- `--force` - 覆盖现有文件。 如果目标已存在,则必须指定此参数。 +- `--macros ` - 目标文件路径。 可放在 `init` 子命令之前或之后。 + +```bash +te macro init +te macro init --macros ./project-macros.json +te macro init --force +``` + +#### 宏 run + +运行宏。 通过 `dataTable.Output()` 输出表格的宏会在终端中显示格式化输出,因此 DAX 风格的查询宏在 `te macro run` 中的行为与在 TE3 中相同。 + +`te macro run` 接受: + +- `--on ` - 将宏的选择上下文设置为单个已命名对象(如表、度量值、列等…)。 这相当于在 TE3 中右键单击该对象,并从上下文菜单调用宏。 +- `--save` / `--save-to` - 将宏所做的所有更改持久化保存。 + +```bash +te macro run "Hide all measures" +te macro run "Format DAX" --on Sales/Revenue --save +te macro run "Format DAX" --on "'Net Sales'[Sales Amount]" --save # DAX form works in --on too +``` + +## 部署和刷新 + +### deploy + +将语义模型部署到 Power BI、Fabric 或 Azure Analysis Services。 + +`te deploy` 支持以下参数: + +- `-s, --server` / `-d, --database` - 目标 Workspace 和模型。 +- `--deploy-full` - 覆盖现有内容,并同时部署连接、分区、共享表达式、角色及角色成员。 +- `--deploy-connections` +- `--deploy-partitions` +- `--skip-refresh-policy` +- `--deploy-roles` +- `--deploy-role-members` +- `--deploy-shared-expressions` +- `--create-only` +- `--xmla ` - 生成 XMLA/TMSL 脚本,而不是部署(`-` 表示输出到标准输出)。 +- `--skip-bpa` - 完全跳过 BPA 门控检查。 +- `--fix-bpa` - 如果规则定义了修复表达式,则自动修复 BPA 违规项。 +- `--bpa-rules ` - 可重复指定;仅针对本次部署覆盖 CLI 配置中的 `bpa.rules`。 除非 `bpa.builtInRules` 为 `false`,否则内置规则仍会生效。 +- `--force` - 跳过交互式确认(CI 必需)。 +- `--ci ` - `vsts` 或 `github`。 +- `--profile ` - 一次性使用已保存的 @te-cli-auth 配置文件。 + +```bash +te deploy ./model -s my-workspace -d my-model --force --ci github +te deploy ./model --xmla script.tmsl # Generate TMSL only +te deploy ./model --profile staging --force +``` + +> [!IMPORTANT] +> `te deploy` 会在执行前运行 Best Practice Analyzer 作为门控检查。 在交互模式下,会显示摘要和确认提示,且 **默认安全选项为 `n`**。 在 CI 中,传入 `--force` 可跳过该提示。 BPA 门控配置请参见 @te-cli-config。 + +### 刷新 + +在已部署的模型上触发数据刷新。 + +`te refresh` 支持: + +- `--type ` - `full`、`dataonly`、`automatic`、`calculate`、`clearvalues`、`defragment`、`add`(默认值:`automatic`)。 +- `--table ` - 刷新特定表(可为多个);可重复指定。 +- `--partition ` - 刷新特定分区(可为多个)。 +- `--apply-refresh-policy` - 应用增量刷新的刷新策略,以确定要刷新的分区。 +- `--effective-date ` - 设置刷新策略使用的生效日期。 +- `--max-parallelism ` - 设置可并行刷新的最大分区数。 +- `--dry-run` - 输出 TMSL 脚本而不执行。 +- `--no-progress`, `--trace [path]`。 + +```bash +te refresh --type full # Full refresh +te refresh --table Sales --type full # Single table +te refresh --type full --dry-run > refresh.tmsl # Emit TMSL only +``` + +### incremental-refresh + +管理表的增量刷新策略。 + +```bash +te incremental-refresh show
+``` + +其他子命令(`set`、`remove`、`apply`)可通过 `te incremental-refresh --help` 查看说明。 + +## 测试 + +### test run + +针对已部署的模型运行一组 DAX 断言测试。 + +`te test run` 支持以下选项: + +- `--suite ` - 测试套件目录(默认:`.te-tests/`)。 +- `--tag ` - 仅运行带有此标签的测试。 +- `--fail-on ` - `error`(默认)或 `warning`。 +- `--ci `, `--trx ` - CI 标注和 TRX 输出。 + +```bash +te test run --ci github --trx results.trx +te test run --tag revenue +``` + +### test init / spec / use / list / snapshot / compare + +其他子命令可用于搭建测试脚手架、打印断言规范格式、切换当前活动套件、列出套件、捕获快照以及比较模型。 查看 `te test --help` 了解详情。 + +```bash +te test init --example # Scaffold an example suite +te test spec # Print the full assertion format reference +te test init --from-model --model ./my-model # Generate stubs from your measures +``` + +## 连接和身份验证 + +### connect + +设置(或显示)当前终端会话的活动连接。 查看 @te-cli-auth。 + +```bash +te connect # Show current active connection +te connect my-workspace my-model # Remote +te connect ./model # Local +te connect --local # Power BI Desktop (Windows) +te connect --profile prod # Activate a saved profile +te connect --clear # Clear the active connection (and any workspace mirror) +``` + +#### 工作区模式(`-w` / `--workspace`) + +将主源与次要目标配对,使后续每次执行 `--save` 都会在两者之间同步镜像模型。 适合保留远程 Workspace 的本地工作副本,或在保存时将本地修改推送到 Workspace。 + +- `te connect -w ./src` - 主源为远程;`./src` 会接收初始 TMDL 导出,并在每次保存时保持镜像同步。 +- `te connect ./src -w ` - 主源为本地;首次部署会将模型推送到 Workspace,后续保存会自动重新部署。 +- `--workspace-format ` - 在镜像到文件夹/文件时选择磁盘上的格式(例如,`-w ./model.bim` 会推断为 BIM)。 +- `--force` - 当目标已存在(例如文件夹非空或数据库已存在)时必须使用。 如果不使用它,`te connect` 会显示交互式 `y/n` 提示,并以 `n` 作为安全的默认选项。 + +启用后,`te set --save`、`te rm --save`、`te script --save` 等都会透明地同时保存到本地和远程。 保存顺序始终是 **先本地,后远程**,因此即使推送到服务器失败,磁盘上的副本也会反映最新的用户更改。 使用 `te connect --clear` 清除镜像。 + +```bash +te connect Finance "Revenue Model" -w ./revenue-model # Mirror remote → local TMDL +te connect ./revenue-model -w Finance "Revenue Model" # Mirror local → remote +``` + +### auth login / status / logout + +管理缓存的身份验证信息。 参见 @te-cli-auth。 + +### profile list / show / set / remove + +管理命名连接配置文件。 参见 @te-cli-auth。 + +## 配置 + +### config show / paths / init / set + +查看和管理 CLI 配置以及 TE3 PATH 覆盖设置。 参见 @te-cli-config。 + +```bash +te config show # Display all settings +te config paths # Resolved TE3 file paths +te config init # Create default config +te config set autoFormat true +``` + +### license + +`te license` 保留用于正式发布 GA 版,在此预览版本中不可用。 这个命令仍会被解析器识别——所以调用它的现有脚本不会在解析阶段报错——但所有子命令都会以状态 `1` 退出,并显示“此预览版本中不可用”的信息。 关于更全面的许可说明,请参见概述页面上的[预览说明](xref:te-cli#preview-notice)。 + +### migrate + +说明旧版 Tabular Editor 2 CLI 参数如何映射到新 CLI 的参考指南。 在迁移基于 TE2 的管道时,可作为实时速查参考。 完整迁移指南参见 @te-cli-migrate。 + +```bash +te migrate # Full flag mapping table +te migrate -A # Look up a single TE2 flag +te migrate --output-format json # Machine-readable mapping +``` + +## Shell + +### 交互式 + +使用具备模型感知能力的提示词启动引导式 REPL 会话。 参见 @te-cli-interactive。 + +```bash +te interactive # Connect later +te interactive ./model # Start with a local model +te interactive -s MyWorkspace -d MyModel # Start with a remote model +``` + +引号和 DAX 风格的引用在会话内外的用法一致——有关 REPL 中支持括号感知的 argv 拆分的详细信息,请参见上文的[对象路径](#object-paths)一节以及 @te-cli-interactive。 + +### 补全 + +生成 shell 补全脚本。 参见 @te-cli-install。 + +```bash +te completion bash +te completion zsh +te completion pwsh +``` + +## 退出代码 + +| 退出代码 | 含义 | +| ---- | ------------------------------------------------------- | +| `0` | 成功。 | +| `1` | 通用失败(参数无效、命令执行失败、校验错误、身份验证失败、BPA 门禁在严重级别 ≥ error 时未通过)。 | +| `2` | 差异非零(`te diff`)——模型不一致。 | + +如需在 CI 管道中进行更细致的控制,可将退出代码与 `--ci ` 注释以及 `--trx` 结果文件结合使用——参见 @te-cli-cicd。 + +## 相关页面 + +- @te-cli - 概览和背景说明。 +- @te-cli-install - 安装并设置 CLI。 +- @te-cli-auth - 进行身份验证并管理连接。 +- @te-cli-config - 配置文件、BPA 门禁和变更后行为。 +- @te-cli-migrate - TE2 → TE3 标志映射。 diff --git a/localizedContent/zh/content/features/te-cli/te-cli-config.md b/localizedContent/zh/content/features/te-cli/te-cli-config.md new file mode 100644 index 000000000..f9e51922b --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-config.md @@ -0,0 +1,258 @@ +--- +uid: te-cli-config +title: 自定义配置 +author: Peer Grønnerup +updated: 2026-04-20 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# 自定义配置 + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +Tabular Editor CLI 可从 JSON 文件读取可选配置。 配置控制三类内容: + +- **文件路径** — CLI 在何处读取宏、BPA 规则和 (可选) TE3 Desktop 可执行文件,以及在何处写入查询日志。 +- **行为默认值** — BPA 门控、自动格式化、验证。 +- **已保存的连接配置文件** — 可在不同命名配置文件之间切换的列表。 + +CLI 是自包含的 - 它不会从任何 Tabular Editor 3 桌面版安装路径读取或写入任何内容。 BPA 规则和宏文件必须通过此配置显式设置(或按需使用 `te bpa rules init` / `te macro init` 进行初始化)。 + +大多数用户无需直接编辑配置文件;`te config show`、`te config set ` 和 `te profile set` 已涵盖常见操作。 + +## 配置文件位置 + +将按以下顺序检查这些位置: + +1. `$TE_CONFIG` 环境变量(如果已设置且文件存在)。 +2. `~/.config/te/config.json`(在 Windows 上为 `%USERPROFILE%\.config\te\config.json`)。 +3. 如果没有配置文件,CLI 将使用内置默认值。 + +`TE_CONFIG` 在所有配置文件相关操作中都会被一致地遵循;`te config show`、`te config set`、`te config init` 和 `te config paths` 都会在解析后的 PATH 上进行读写。 这主要用于测试、脚本化安装以及按环境进行配置。 + +要创建默认配置: + +```bash +te config init # Create config at TE_CONFIG (or ~/.config/te/config.json) +te config init --force # Overwrite existing config +``` + +## 查看配置 + +```bash +te config show # Display all settings +te config show --output-format json # Machine-readable +te config paths # Show resolved macros and BPA rule paths +``` + +使用 `te config paths` 查看 CLI 实际会为宏和 BPA 规则使用哪些文件。 这在调试缺失的数据文件时很有用。 输出会显示两行:`macros` (解析后的宏文件路径或 `[not set]`) 和 `bpa.rules` (由路径解析器解析出的第一个存在的 BPA 规则文件,或 `[not set]`)。 + +> [!NOTE] +> 在 `--output-format json` 模式下,`te config paths` 会显式输出值为 `null` 的字段 (例如 `{"macros": null, "bpa": {"rules": null}}`)。 报告解析结果本来就是此命令的全部用途,因此 `null` 表示“尝试过,但未解析到任何内容”,这是一个有意义的结果。 `te config show --output-format json` 默认会剔除值为 `null` 的字段,因此使用方应以容错方式解析。 + +## 设置值 + +```bash +te config set autoFormat true +te config set bpa.onDeploy false +te config set hidePreviewNotice true +te config set macros null # Clear a path override +``` + +如果键未知,命令将以退出码 `1` 失败,并返回一条列出有效键的错误信息。 + +如果配置文件不存在,`te config set` 会先在解析后的路径自动创建一个配置文件 (若设置了则为 `$TE_CONFIG`,否则为 `~/.config/te/config.json`),然后再应用更改。 + +> [!NOTE] +> 架构中的每个键都可以通过 `te config set` 设置,包括通过点分路径设置嵌套键 (`bpa.onDeploy`、`formatOptions.useSqlBiDaxFormatter` 等)。 唯一的例外是 `formatVersion`,它由 CLI 自动管理。 如果你更愿意直接编辑 JSON,可运行 `te config paths` 来找到配置文件。 + +## 完整 Schema + +完整的 JSON 配置 Schema,包含所有键及其默认值。 直接编辑配置文件时可将其作为参考,或在为 `te config set` 调用查找点分路径时使用。 + +```json +{ + "formatVersion": 1, + "macros": null, + "autoFormat": false, + "validateOnMutation": true, + "vertipaqOnRefresh": false, + + "bpa": { + "rules": null, + "onDeploy": true, + "onSave": true, + "onMutation": false, + "builtInRules": true, + "disabledBuiltInRuleIds": null + }, + + "interactiveEditMode": "stage", + + "formatOptions": { + "useSemicolons": false, + "shortFormat": false, + "skipSpaceAfterFunction": false, + "useSqlBiDaxFormatter": false + }, + + "hidePreviewNotice": false, + "spinner": true, + "debug": false, + "disableTelemetry": false, + + "queryLog": null, + "te3ExePath": null, + + "profiles": {} +} +``` + +### 文件路径 + +在配置中设置这些路径,以避免每次执行命令都传入相同的路径。 每个命令的标志和环境变量都会覆盖配置值;请参阅下方的[路径解析优先级](#path-resolution-priority)。 + +| 键 | 含义 | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `macros` | 宏 JSON 文件的显式路径 (通常为 `MacroActions.json`)。 每个 `te macro` 命令都会解析它。 可将其指向共享文件(网络共享、仓库内文件,甚至 TE3 Desktop 的文件),以便在不同计算机之间以及在 CLI 与 TE3 Desktop 之间复用同一组宏。 | +| `bpa.rules` | 指向 BPA 规则文件的路径或 URL 的有序列表。 `te bpa run` 和 deploy/save gate 会加载**所有**现有条目;`te bpa rules list` 和 `te config paths` 使用第一个现有条目。 在 `te config set bpa.rules ...` 中使用逗号分隔的值时,会将其拆分为数组。 | +| `te3ExePath` | Tabular Editor 3 Desktop 可执行文件 (`TabularEditor.exe`) 的显式路径。 **仅** `te open` 在启动桌面应用时才会用到;在 Linux/macOS 上,或不使用 `te open` 时,可安全留空。 如果未设置,`te open` 会回退到在 `PATH` 中查找。 | +| `queryLog` | 日志文件路径,每次调用 `te query` 时都会将其查询文本和执行元数据追加到该文件中。 可用于审计追踪,或分析随时间变化的查询模式。 支持使用 `~` 表示主目录(例如 `~/.config/te/queries.log`)。 | + +### 路径解析优先级 + +对于每个用户提供的文件 (宏、BPA 规则),CLI 会按以下顺序解析路径: + +1. **命令行标志** - 宏命令使用 `--macros `;部署/保存 gate 使用 `--bpa-rules `;`te bpa rules` 子命令使用 `--rules-file `。 +2. **环境变量**:宏使用 `TE_MACROS_PATH`,BPA 规则使用 `TE_BPA_RULES`。 +3. **CLI 配置**:宏使用 `macros`,BPA 规则使用 `bpa.rules[]` 中第一个现有条目。 + +CLI 不会自动检测 TE3 的任何安装位置——请显式配置这些项。 若要从当前工作目录中的默认文件开始,可运行 `te macro init`(创建 `./MacroActions.json`)或 `te bpa rules init`(创建 `./BPARules.json`)。 + +运行 `te config paths` 可查看 CLI 实际解析到的是哪个文件。 + +### 行为默认值 + +所有与 BPA 相关的设置都位于 `bpa` 对象下,并可在 `te config set` 中使用点号分隔的键进行设置。 + +| 键名 | 默认值 | 说明 | +| ---------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `autoFormat` | `false` | 在执行 `te add` / `te set` / `te mv` / `te macro run` 之后,对修改过的表达式运行 DAX Formatter。 默认使用内置格式化程序;可通过 `formatOptions.useSqlBiDaxFormatter` 改用 SQL BI Web 服务。 | +| `validateOnMutation` | `true` | 在执行更改命令(`add`、`set`、`mv`、`replace --save`、`macro run`)后,检查模型中的每个 `Table[Column]` 引用是否仍可解析。 可在部署前捕获因重命名或删除而引入的悬空引用。 | +| `bpa.onMutation` | `false` | 在每次更改命令(`set`、`add`、`mv`、`rm`、`macro run`)后,运行一次限定范围的 BPA 分析。 只检查受影响表中的对象,而不是整个模型——这对于迭代编辑时获得快速反馈很有用。 | +| `bpa.onDeploy` | `true` | 在执行 `te deploy` 之前运行 BPA 关卡检查。 如果有任一规则触发且严重级别 ≥ error,则中止部署。 可通过 `--skip-bpa` 在单次调用中跳过,或通过 `--fix-bpa` 自动修复。 | +| `bpa.onSave` | `true` | 在 `te save -o` 写入磁盘之前运行 BPA 关卡检查。 可通过 `--skip-bpa` 或 `--force` 在单次调用中跳过。 | +| `bpa.builtInRules` | `true` | 每次运行关卡检查时,都包含精选的内置 BPA 规则集。 设为 `false` 可完全忽略内置规则;此时关卡检查只运行通过 `bpa.rules` 配置的规则以及嵌入模型中的规则。 | +| `bpa.disabledBuiltInRuleIds` | `null` | 要从门禁中排除的各个内置规则的 ID。 可通过 `te bpa rules disable ` / `te bpa rules enable ` 修改——优先使用这些命令,而不是直接编辑该数组。 | +| `vertipaqOnRefresh` | `false` | 成功刷新后(`full`、`dataonly`、`automatic` 或 `add`),自动运行 VertiPaq 分析,以显示已刷新表的存储统计信息。 有助于立即发现意外的基数变化或内存回归。 | +| `interactiveEditMode` | `stage` | 在 `te interactive` 中对内存中变更的默认处理方式。 `stage` 会将变更保留在内存中,直到调用 `save`(最安全);`save` 会在每次产生变更的命令后写回源(对远程源请谨慎使用——每次 `set` 都会触发一次 XMLA 写入);`revert` 会在每条命令后丢弃变更,除非传入了 `--save` 或 `--stage`。 每个命令上的 `--save` / `--revert` / `--stage` 标志始终会覆盖此设置。 | +| `disableTelemetry` | `false` | 选择不参与匿名使用遥测数据收集。 CLI 会收集粗粒度的命令使用数据(命令名称、退出代码、持续时间),用于确定功能优先级。 CLI 绝不会收集模型内容、PATH 或查询文本。 | + +```bash +te config set bpa.rules "/etc/te/team.json,/etc/te/strict.json" +te config set bpa.onDeploy true +te config set bpa.builtInRules false +te config set bpa.disabledBuiltInRuleIds "TE3_BUILT_IN_DATE_TABLE_EXISTS,TE3_BUILT_IN_HIDE_FOREIGN_KEYS" +``` + +### 格式选项 + +每当 CLI 调用 DAX 格式化程序时都会应用(用于 `te format`,以及在启用 `autoFormat` 时对变更进行格式化)。 CLI 附带一个可完全离线工作的自研格式化器;如果你需要那种风格,或希望在启用 "Use daxformatter.com..." 时与 TE2 或 TE3 的行为一致,可通过 `formatOptions.useSqlBiDaxFormatter` 选择使用 SQL BI 的 [daxformatter.com](https://www.daxformatter.com) Web 服务。 + +| 键 | 默认值 | 说明 | +| -------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `formatOptions.useSemicolons` | `false` | 使用 `;` 作为列表分隔符(欧洲/欧盟区域设置惯例)。 默认的 `,` 与 en-US 区域设置一致。 | +| `formatOptions.shortFormat` | `false` | 尽可能优先使用简短的单行格式,而不是默认的多行布局。 | +| `formatOptions.skipSpaceAfterFunction` | `false` | 省略函数名称与左括号之间的空格(例如使用 `SUM(x)`,而不是 `SUM (x)`)。 | +| `formatOptions.useSqlBiDaxFormatter` | `false` | 通过 [SQL BI daxformatter.com](https://www.daxformatter.com) Web 服务格式化 DAX,而不是使用内部格式化程序。 需要联网。 内置格式化器(默认)可离线使用,其效果与 Tabular Editor 3 Desktop 的默认格式化一致。 | + +### 显示 + +控制 CLI 终端输出和诊断详细程度的设置。 + +| 键 | 默认值 | 说明 | +| ------------------- | ------- | ---------------------------------- | +| `hidePreviewNotice` | `false` | 隐藏黄色预览横幅。 **距离到期不足 14 天时,将忽略此设置。** | +| `spinner` | `true` | 在终端中显示动画进度指示器。 在 CI 环境中禁用。 | +| `debug` | `false` | 始终启用调试日志(等同于传入 `--debug`)。 | + +### 配置文件 + +已保存的连接配置文件存放在 `profiles` 键下。 不要手动编辑——请使用 `te profile set / remove / list`。 配置文件管理见 @te-cli-auth。 + +配置文件可以包含 **覆盖项**,在配置文件处于启用状态时,用来覆盖上述默认行为。 这样一来,开发配置文件可以放宽验证和 BPA,而生产配置文件则保持严格: + +```bash +te profile set dev --validate-on-mutation false --bpa-on-deploy false +te profile set prod --auto-format true +``` + +## BPA 闸门 + +BPA 闸门是一道安全防线,用于防止存在规则违规的模型被保存或部署。 执行以下命令时,它会自动运行: + +- `te deploy` 会触发闸门检查,除非传入 `--skip-bpa` 或 `bpa.onDeploy` 为 `false`。 +- `te save` 会触发闸门检查,除非传入 `--skip-bpa`(或 `--force`)或 `bpa.onSave` 为 `false`。 +- `te add`、`te set`、`te mv`、`te macro run` 仅在 `bpa.onMutation` 为 `true` 时才会运行闸门。 + +闸门检查会从 `bpa.rules` 加载 BPA 规则,并且默认还会加载内置规则集(由 `bpa.builtInRules` 控制)。 可通过 `bpa.disabledBuiltInRuleIds` 单独排除内置规则——可使用 `te bpa rules disable ` / `te bpa rules enable ` 管理。 + +当闸门检查触发并发现严重性 ≥ `error` 的违规项时,命令会失败,退出代码为 `1`,并输出违规摘要。 处理选项: + +- `--fix-bpa` - 在内存中将规则的 `fixExpression` 应用于部署/保存产物;不会修改源文件。 +- `--skip-bpa` - 仅对本次命令禁用闸门检查。 +- `--bpa-rules ` - 可重复指定;仅在本次调用 `te deploy` 或 `te save` 时覆盖 `bpa.rules`。 除非 `bpa.builtInRules` 为 `false`,否则内置规则仍会生效。 + +可单独运行 `te bpa run`,在不部署的情况下预览闸门检查的行为: + +```bash +te bpa run ./model --fail-on error +te bpa run ./model --fix --save # Apply fixes to the source +``` + +### 内置 BPA 规则 + +CLI 随附一套权威的内置 BPA 规则集,并以 JSON 资源的形式嵌入其中。 内置规则是只读的:`te bpa rules set` 和 `te bpa rules rm` 拒绝修改内置 ID,并引导用户改用 `te bpa rules disable`。 如果想自定义内置规则的行为,可以把它复制到本地规则文件中,作为一个使用不同 ID 的新规则,然后再禁用内置规则。 + +`bpa.builtInRules` 和 `bpa.disabledBuiltInRuleIds` 会一致地应用于部署/保存/变更的门控检查 **以及** 手动执行的 `te bpa run` 命令——通过 `te bpa rules disable` 禁用一次后,该规则将在所有场景中被排除。 + +## 变更后行为 + +运行会产生变更的命令(`te add`、`te set`、`te mv`、`te replace --save`、`te macro run`)时,CLI 会自动执行以下检查: + +1. **TOM 错误**始终会被提示。 度量值、列、分区或计算项中的无效 DAX 或 M 始终会导致命令失败。 +2. **架构验证** (`validateOnMutation`,默认值为 `true`) 会验证 DAX 中的 `Table[Column]` 引用是否仍可解析,并交叉检查元数据一致性。 +3. **DAX 自动格式化** (`autoFormat`,默认值为 `false`) 在启用时会通过内置的 DAX Formatter 格式化此次变更涉及的所有表达式。 +4. **变更时运行 BPA** (`bpa.onMutation`,默认值为 `false`) 在启用时会在变更后运行 BPA,并根据 `--fail-on` 发出警告或使命令失败。 + +可使用 `te config set false` 禁用某项检查,或通过配置文件将放宽范围限定到特定环境。 + +## 环境变量 + +使用以下 CLI 专用环境变量来设置路径、行为和诊断。 有关 Azure 身份验证变量(`AZURE_CLIENT_ID`、`AZURE_TENANT_ID`、`AZURE_CLIENT_CERTIFICATE_PATH` 等),见 @te-cli-auth。 + +| 变量 | 用途 | +| ---------------- | ---------------------------------------------------------------------------------------------------------- | +| `TE_CONFIG` | 替代配置文件的路径。 所有 `te config` 操作(`show`、`set`、`init`、`paths`)都会遵循该变量的设置。 | +| `TE_MACROS_PATH` | 覆盖宏文件路径(在解析顺序中排第二,见上文)。 由 `te macro` 命令读取。 | +| `TE_BPA_RULES` | 覆盖 `te bpa run` 和 `te bpa rules` 子命令使用的 BPA 规则文件/URL 列表。 | +| `TE_BPA_CONFIG` | 覆盖 deploy/save 门禁读取的 BPA 门禁配置 (`.te-bpa.json`) 的路径。 | +| `TE3_EXE_PATH` | Tabular Editor 3 桌面版二进制文件的路径。 此项 **仅** 用于 `te open`;在 Linux/macOS 上或不使用 `te open` 时,可安全留空。 会回退到 `PATH` 查找。 | +| `TE_DEBUG` | 设为 `1` 可全局启用调试日志(等同于 `--debug` 或配置中的 `debug: true`)。 | +| `NO_SPINNER` | 设为 `1` 或 `true` 可禁用动画进度指示器(可替代配置中的 `spinner: false`)。 | +| `CI` | 自动检测。 当设为 `1` 或 `true` 时,CLI 会禁用动画进度指示器,并切换为纯文本输出。 大多数 CI 运行器都会自动设置此项。 | +| `TE_SESSION` | 覆盖用于活动连接状态的按终端划分的会话 ID。 适用于在同一个 shell 中运行多个相互隔离的 CLI 会话,例如并行的 CI 矩阵作业。 | +| `TE_COMPAT` | 设为 `te2` 可强制启用 TE2 兼容模式;参见 @te-cli-migrate。 | + +## 相关页面 + +- @te-cli-auth - 配置文件、身份验证和凭据存储。 +- @te-cli-commands - `te config` 子命令。 +- @te-cli-cicd - 为管道配置 BPA 门禁。 diff --git a/localizedContent/zh/content/features/te-cli/te-cli-install.md b/localizedContent/zh/content/features/te-cli/te-cli-install.md new file mode 100644 index 000000000..dfb89c1a7 --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-install.md @@ -0,0 +1,201 @@ +--- +uid: te-cli-install +title: Installation and Setup +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Installation and Setup + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +The Tabular Editor CLI ships as a single self-contained executable named `te` (`te.exe` on Windows). It has no external runtime dependencies. + +## 下载 + +1. Sign in at [tabulareditor.com](https://tabulareditor.com/download-tabular-editor-cli) with a Tabular Editor account. +2. Download the archive for your platform and architecture: + + | Platform | 64-bit (Intel/AMD) | ARM64 | Archive | + | -------- | ---------------------------------------------- | -------------------------------------------------------- | --------- | + | Windows | `te-win-x64.zip` | `te-win-arm64.zip` | `.zip` | + | macOS | `te-osx-x64.tar.gz` (Intel) | `te-osx-arm64.tar.gz` (Apple Silicon) | `.tar.gz` | + | Linux | `te-linux-x64.tar.gz` | `te-linux-arm64.tar.gz` | `.tar.gz` | + + Pick the ARM64 build on Apple Silicon Macs (M1 and newer), Windows on ARM devices, and ARM-based Linux servers (including AWS Graviton, Azure Ampere, and Raspberry Pi 64-bit). Pick the `x64` build on everything else. + +## Install + +Unzip the archive into a folder of your choice and add that folder to `PATH` so you can invoke `te` from any working directory. + +### Windows (PowerShell) + +#### x64 + +```powershell +Expand-Archive te-win-x64.zip -DestinationPath "$env:LOCALAPPDATA\Programs\te" +[Environment]::SetEnvironmentVariable( + "PATH", + [Environment]::GetEnvironmentVariable("PATH", "User") + ";$env:LOCALAPPDATA\Programs\te", + "User") +``` + +#### ARM64 + +```powershell +Expand-Archive te-win-arm64.zip -DestinationPath "$env:LOCALAPPDATA\Programs\te" +[Environment]::SetEnvironmentVariable( + "PATH", + [Environment]::GetEnvironmentVariable("PATH", "User") + ";$env:LOCALAPPDATA\Programs\te", + "User") +``` + +### macOS + +#### Apple Silicon (ARM64) + +```bash +mkdir -p ~/.local/bin +tar -xzf te-osx-arm64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc +``` + +#### Intel (x64) + +```bash +mkdir -p ~/.local/bin +tar -xzf te-osx-x64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc +``` + +On macOS, the binary is signed with our Apple Developer ID and notarized by Apple, so the first run completes without a "cannot verify developer" Gatekeeper warning. Network access on first run is recommended so Gatekeeper can fetch the notarization ticket; offline first-runs may briefly prompt before being unblocked once network returns. + +### Linux + +#### x64 + +```bash +mkdir -p ~/.local/bin +tar -xzf te-linux-x64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc +``` + +#### ARM64 + +```bash +mkdir -p ~/.local/bin +tar -xzf te-linux-arm64.tar.gz -C ~/.local/bin +chmod +x ~/.local/bin/te +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc +``` + +> [!NOTE] +> The PATH change takes effect in **new** shell sessions. To run `te` in the shell where you ran the install, open a new terminal, or reload your profile: `source ~/.bashrc` / `source ~/.zshrc` on macOS/Linux, or close and reopen PowerShell on Windows. + +## Verify + +Check the installed version and list available commands: + +```bash +te --version +te --help +``` + +`te --help` prints a colorized help index grouping commands by family. Every subcommand accepts `--help` for detailed usage: + +```bash +te deploy --help +te bpa run --help +``` + +## Hide the preview banner + +The CLI prints a yellow preview banner on stderr by default. To suppress it run: + +```bash +te config set hidePreviewNotice true +``` + +> [!WARNING] +> The banner reappears on every command within **14 days of the preview end date** (2026-09-30), regardless of `hidePreviewNotice`. This ensures you have visible warning before the CLI stops functioning. + +## Shell completion + +The CLI provides tab-completion scripts for **Bash**, **Zsh**, and **PowerShell**. Pick the block that matches your shell — each one installs the completion persistently for new shell sessions. + +### Bash (macOS/Linux) + +```bash +mkdir -p ~/.local/share/bash-completion/completions +te completion bash > ~/.local/share/bash-completion/completions/te +``` + +### Zsh (macOS/Linux) + +```zsh +mkdir -p ~/.zfunc +te completion zsh > ~/.zfunc/_te +echo 'fpath=(~/.zfunc $fpath); autoload -U compinit; compinit' >> ~/.zshrc +``` + +### PowerShell (Windows/macOS/Linux) + +```powershell +Add-Content $PROFILE 'te completion pwsh | Out-String | Invoke-Expression' +``` + +Open a new shell session for completion to take effect. + +Completion covers subcommands, global flags, and model paths (where tab-completion against the filesystem is meaningful). + +## Cross-platform feature matrix + +Most features are identical across platforms. A handful depend on Windows-only transports: + +| Feature | Windows | macOS / Linux | +| ---------------------------------------------------------------------------------------------- | ------- | ------------- | +| Load/save BIM and TMDL | Yes | Yes | +| Deploy to Power BI / Fabric / Azure Analysis Services | Yes | Yes | +| Best Practice Analyzer and VertiPaq Analyzer | Yes | Yes | +| C# scripting | Yes | Yes | +| DAX queries against cloud models | Yes | Yes | +| Authentication: browser, device-code, service principal, env, managed identity | Yes | Yes | +| Connect to local SSAS instance (TCP transport) | Yes | **No** | +| Connect to Power BI Desktop (named-pipe transport) | Yes | **No** | + +> [!IMPORTANT] +> Local SSAS and Power BI Desktop connections rely on Windows-only transport protocols. All cloud-based workflows (Power BI Service, Fabric, Azure Analysis Services) work on every platform. + +## Updating + +To update to a newer preview build, download the latest archive and overwrite the previous installation. Configuration and cached credentials are stored outside the install folder (see and ) and are preserved across updates. + +## Uninstalling + +1. Delete the install folder. +2. Remove the PATH entry. +3. (Optional) Clear cached credentials and config: + - Run `te auth logout` first - it removes all cached tokens and SPN records from the active backend (OS keystore or file fallback). + - Delete `~/.config/te/` (config and saved profiles). + - Delete `~/.te-cli/` (residual cache files; only present when the file fallback was in use, or as legacy from older CLI builds). + - To also purge the OS-native keystore entries - usually unnecessary, since `te auth logout` already clears them - see: + - **Windows:** Credential Manager → Windows Credentials → entries named `com.tabulareditor.cli...` or `te-cli`. + - **Linux:** `secret-tool search Component te-cli` and `secret-tool clear ...`, or use seahorse. + - **macOS:** Keychain Access → search for `com.tabulareditor.cli`. + +## Next steps + +- @te-cli-auth - authenticate to Power BI, Fabric, or Azure Analysis Services. +- @te-cli-commands - full command reference. +- @te-cli-interactive - guided REPL mode. diff --git a/localizedContent/zh/content/features/te-cli/te-cli-interactive.md b/localizedContent/zh/content/features/te-cli/te-cli-interactive.md new file mode 100644 index 000000000..c264d93f0 --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-interactive.md @@ -0,0 +1,98 @@ +--- +uid: te-cli-interactive +title: Interactive Mode +author: Peer Grønnerup +updated: 2026-05-12 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Interactive Mode + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +Interactive mode is a guided read-eval-print loop (REPL) for exploring a model from the terminal. It's the gentlest on-ramp for users who are new to command lines, and a convenient workspace for ad-hoc sessions against a single model. + +## Starting a session + +To Start a session run any of these commands: + +```bash +te interactive # Start and connect to a model later +te interactive ./model # Start with a local model +te interactive -s MyWorkspace -d MyModel # Start with a remote model +``` + +The session prints a welcome banner, shows the active model, and opens you at a model-aware prompt: + +![Tabular Editor CLI interactive mode session](~/content/assets/images/features/cli/cli-interactive-mode.png) + +If no model is set, the prompt is just `te>` - simply use `connect` for connection picker, `connect ` or `connect ` to connect to one. + +## Commands inside the session + +Once a REPL has started, every `te` subcommand is available **without the `te` prefix**: + +``` +ls tables +get "Sales/Revenue" -q expression +query -q "EVALUATE TOPN(5, 'Sales')" +bpa run --fail-on error +``` + +Each command accepts `--help` the same way it does outside the session: + +``` +deploy --help +``` + +## Quoting and DAX-style paths + +The REPL line splitter recognises the same quoting forms as [object paths](xref:te-cli-commands#object-paths) so DAX-shaped references are interpreted as a single argument: + +- `'...'` and `"..."` - single- and double-quoted segments. The quote characters are stripped, doubled quotes escape a literal occurrence. +- `[...]` - bracketed segment. **Brackets are preserved** in the resulting argument so a path like `'Internet Sales'[Sales Amount]` reaches the command as one token that the path parser can re-interpret as a DAX reference. Doubled closing brackets (`]]`) stay verbatim for the same reason. + +``` +get 'Internet Sales'[Sales Amount] # One argument, DAX form +get [Total Sales] # Lone-bracket model-wide lookup +ls 'Net Sales'/'Sales Amount' # Quoted segments with a slash separator +``` + +Unterminated groups absorb to end of line, so a stray opening quote or bracket fails with an explicit error rather than splitting silently. + +## Built-in REPL commands + +These are handled by the REPL itself, not the regular command tree: + +| Command | Purpose | +| ---------------------- | ------------------------------------------------- | +| `help` or `?` | List available commands. | +| `status` or `pwd` | Show the active model/connection. | +| `clear` or `cls` | Clear the screen. | +| `exit`, `quit`, or `q` | Exit interactive mode. | + +## Guided prompts + +When interactive mode is active, commands that need missing input prompt for it instead of failing. Running `auth` without a subcommand opens a picker for Login / Status / Logout; running `deploy` without `--force` shows a summary and asks for confirmation (`n` is the safe default). + +To disable prompts for a single command inside the session, pass `--non-interactive`. + +## When to use interactive vs. non-interactive + +- **Interactive mode** is best for exploration, learning the CLI, one-off bulk edits against a single model, and demos. +- **Non-interactive mode** (the default outside `te interactive`) is what you reach for when scripting, automating, or running in CI. See @te-cli-automation and @te-cli-cicd. + +The two share the same command tree - anything you run inside `te interactive` can be pasted into a shell script by prefixing it with `te`. + +## Related pages + +- @te-cli-commands - full command reference. +- @te-cli-auth - connect to workspaces and manage profiles. +- @te-cli-automation - when to leave interactive mode. diff --git a/localizedContent/zh/content/features/te-cli/te-cli-limitations.md b/localizedContent/zh/content/features/te-cli/te-cli-limitations.md new file mode 100644 index 000000000..aa038bf5f --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-limitations.md @@ -0,0 +1,90 @@ +--- +uid: te-cli-limitations +title: 已知限制 +author: Peer Grønnerup +updated: 2026-05-20 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# 已知限制 + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +本页列出了 Tabular Editor CLI(`te`)的已知限制,帮助你提前规划并避开常见陷阱。 本页会随每次发布而更新;如果你发现此处未列出的问题,请在公开的 [TabularEditor/CLI](https://github.com/TabularEditor/CLI) repository 中提交 issue。 + +> [!NOTE] +> 这些限制按领域分类。 每个条目都会说明具体限制,并在适用时提供变通方法或推荐的 CLI 友好替代方案。 + +## 脚本 + +CLI 会针对你在 Tabular Editor 2 和 3 中使用的同一个 `Model` 对象运行 C# Script(`te script`),但它是无界面的控制台宿主程序。 任何依赖 Windows Forms UI、TOM Explorer 的选择内容,或实时的 UI 端服务(宏注册表、在线 DAX Formatter、实时 VertiPaq分析器)的功能,其行为都会不同——通常表现为空、无操作,或直接报错。 + +| 限制 | 说明 / 变通方法 | +| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **未加载 `System.Windows.Forms`** | CLI 使用的是跨平台 `TOMWrapper` 版本,其中剥离了所有与 WinForms 耦合的代码;WinForms 程序集不会被加载到 AppDomain 中。 引用 `System.Windows.Forms` 类型(`MessageBox`、`Form`、文件选择器、自定义对话框等)的脚本 将无法编译。 将所有 UI 交互重构为脚本参数、环境变量或标准输入 stdin。 | +| **`Selected.` 返回空的可枚举对象** | 在 CLI 中,`Selected.Tables`、`Selected.Measures`、`Selected.Columns`、`Selected.Hierarchies` 等的枚举结果都为空——不会出现编译或运行时错误,只是不会返回任何项。 改为显式查找:`Model.AllMeasures.Where(...)`、`Model.Tables["Sales"].Measures`,或通过 `te script --args` 传递对象路径。 | +| **`Selected.` 会在运行时抛出错误** | `Selected.Table`、`Selected.Measure`、`Selected.Column`、`Selected.Hierarchy` 等都会报错,因为它们要求恰好选中一个该类型的对象,而 CLI 中的选择始终为空。 直接引用该对象,例如 `Model.Tables["Sales"]`。 | +| **`Selected.ActivePerspectives` 和 `Selected.ActiveCulture`**:分别为活动透视和活动区域设置 | 它们分别始终返回空集合和 `null`。 如果需要,就在脚本中显式设置透视或区域设置。 | +| **`Select` 对话框会抛出 `NotSupportedException`** | `SelectTable`、`SelectColumn`、`SelectMeasure`、`SelectObject`、`SelectObjects`(以及所有重载)都会返回以下错误:_"对象选择对话框… 在 CLI 脚本中不可用。 在编写脚本前,先按名称或路径预先选定对象。"_ 通过脚本参数、配置或查询模型来提前解析目标。 | +| **`Info` / `Warning` / `Error` / `Output` 会写入控制台** | 这些仍然可用,但会输出到 stdout/stderr,而不是打开对话框。 它们不会阻塞,也不会提供“忽略后续弹窗”的提示。 可安全用于 CI。 | +| **`ShowPrompt(...)` 始终返回 `Cancel`** | 无法进行交互式确认。 通过脚本参数或配置预先确定答案。 | +| **`SuspendWaitForm` / `WaitFormVisible` 都是空操作** | “请稍候”加载指示器是 TE3 的一个 UI 元素。 `WaitFormVisible` 是一个可设置的标志位,但没有任何 Visual 效果;`SuspendWaitForm` 会被静默忽略——现有脚本仍可继续编译。 | +| **`host.Macro(...)` / `CustomAction(...)` 会抛出错误** | CLI 不会加载 `%APPDATA%/TabularEditor3/MacroActions.json`,因此在脚本内部调用宏会报错。 把宏逻辑直接写进脚本里,或直接调用该宏底层的脚本文件。 | +| **`table.GetCardinality()` / `column.GetTotalSize()` 返回 0** | CLI 主机中没有实时 VPA,因此脚本内的 VertiPaq 基数辅助函数无法使用。 如果要查看 VPA 统计信息,显式加载 VPAX 并使用 `host.Vpa.*`,或运行 [`te vertipaq`](xref:te-cli-commands#vertipaq)。 | + +## Best Practice Analyzer + +| 限制 | 说明 / 变通方法 | +| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **BPA 规则源必须是 HTTPS URL 或本地文件路径** | 只接受 `https://` URL 和不带协议的本地文件路径。 系统能识别 `http://`,但会在加载时故意拒绝,并给出清晰的错误信息——BPA 规则是可执行的规则表达式,通过未经过身份验证的通道获取会有被篡改的风险。 其他 URL 方案(`file://`、`ftp://`、…) 不受支持。 这同时适用于 `te bpa run --rules`,以及通过 [`te config set`](xref:te-cli-commands#config-show--paths--init--set) 配置的规则列表。 | +| **规则 URL 的验证在运行阶段进行,而不是在 `te config set` 时** | 像 `http://` 这样的拼写错误会被 `te config set` 接受,只有在 BPA 实际运行时才会暴露出来。 编辑已配置的规则源后,运行一次 `te bpa run`(或 `te validate`),以验证每个 URL 都能成功加载。 | +| **`--rules` 不会禁用内置规则** | 传入 `te bpa run --rules ` 时,提供的规则会在本次调用中替换 [`bpa.rules`](xref:te-cli-commands#config-show--paths--init--set) 和 `TE_BPA_RULES` 中的条目,但内置默认规则仍会一并加载。 若只想运行显式指定的规则文件,还需传入 `--no-defaults`。 | +| **没有可在单次调用中跳过 `bpa.rules` 配置的标志** | 配置了 `bpa.rules` 后,每次执行 `te bpa run` 都会在加载内置规则的同时加载这些规则。 目前没有可在单次运行中跳过已配置规则文件的标志。 变通方法:显式传入 `--rules `——该标志会在本次调用中完全替换 `bpa.rules` 和 `TE_BPA_RULES`。 | + +## 验证 + +| 限制 | 说明 / 变通方法 | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| **`te validate` 无法自动修复 Code Action 违规项** | `te validate` 会生成 Report 来指出 Code Action 违规项,但不提供用于应用建议修复的 CLI 参数。 在 Tabular Editor 3 中应用修复;或者对与 BPA 规则重叠的那部分 Code Action,使用 `te bpa run --fix`。 | + +## 模型 I/O + +| 限制 | 说明 / 变通方法 | +| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **`--serialization` 不能将序列化格式与 PBIP 容器组合使用** | [`te save`](xref:te-cli-commands#save) 的 `--serialization` 选项将 `bim`、`tmdl`、`te-folder` 和 `pbip` 视为互斥选项,因此目前无法为采用 TMSL 序列化 (`.bim`) 的模型生成 PBIP 容器。 将 TMDL 保存到 PBIP 中,或将 `.bim` 保存在 PBIP 容器之外。 | + +## 身份验证 + +| 限制 | 说明 / 变通方法 | +| -------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| **每种身份验证方法只能缓存一个身份** | CLI 同时只会缓存一个 UPN(交互式)身份和一个 SPN(服务主体)身份。 在同一种身份验证方法下切换到其他用户或租户时,需要先执行 `te auth logout`,再重新执行 `te auth login`,这会使之前的缓存失效。 | + +## 命令行输入 + +| 限制 | 说明 / 变通方法 | +| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **包含空格的 DAX 对象路径必须用 shell 引号括起来** | 当表名或列名包含空格时,必须在终端中用 shell 引号将整个 DAX 对象引用括起来:`te get "'My Table'[My Column]"`。 如果没有外层引号,shell 会将该路径拆分为多个参数,导致解析失败。 在 [`te interactive`](xref:te-cli-interactive) 中不需要 shell 引号,因为 REPL 会在 shell 将输入拆分为参数之前接收原始输入。 | + +## TE2 功能对等性 + +| 限制 | 说明 / 变通方法 | +| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| **`te schemacheck` 目前尚未实现** | TE2 的 `-SC` / `-SCHEMACHECK` 标志目前在 `te` 中还没有对应项;针对源数据源的架构漂移检测计划在未来版本中推出。 有关完整的 TE2 到 `te` 的标志映射表,请参见 @te-cli-migrate。 | + +## Report 缺失的限制 + +如果某个行为让你感到意外,而且这里没有列出,请到 [TabularEditor/CLI](https://github.com/TabularEditor/CLI/issues) 提交一个 Issue,并附上你运行的命令、实际看到的输出,以及你期望的输出。 经确认的限制会在下一个版本中补充到此页面。 + +## 相关页面 + +- @csharp-scripts - 完整的 C# Script 参考(UI 和 CLI)。 +- @script-helper-methods - `ScriptHost` 辅助方法列表,以及这些方法在 CLI 中的行为。 +- @te-cli-commands - 完整的 CLI 命令参考。 +- @te-cli-automation - 在脚本和流水线中使用 CLI 的模式与最佳实践。 diff --git a/localizedContent/zh/content/features/te-cli/te-cli-migrate.md b/localizedContent/zh/content/features/te-cli/te-cli-migrate.md new file mode 100644 index 000000000..6ae97fa4f --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli-migrate.md @@ -0,0 +1,111 @@ +--- +uid: te-cli-migrate +title: Migrating from the TE2 Command Line +author: Peer Grønnerup +updated: 2026-05-06 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Migrating from the TE2 Command Line + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +Teams with existing build pipelines that invoke `TabularEditor.exe` with TE2-style flags (`-S`, `-A`, `-D`, `-O`, `-C`, etc.) can adopt the new CLI incrementally. The Tabular Editor CLI accepts both command shapes: the new subcommand-based form (`te deploy`, `te bpa run`, …) and the legacy TE2 flag syntax, via a built-in compatibility layer. + +For the legacy TE2 Windows command-line reference, see @command-line-options. + +## How TE2 compatibility works + +TE2 compatibility mode is activated in any of three ways: + +1. **Binary name.** Rename `te` to `te2` (or symlink it) and the CLI runs in TE2-exact mode. This is the drop-in replacement path: swap `TabularEditor.exe` for `te2` in your existing pipeline and the same arguments work. +2. **Environment variable.** Set `TE_COMPAT=te2` before invoking `te` to force TE2 mode. +3. **Auto-detection.** If the first argument isn't a `te` subcommand (`load`, `deploy`, …) and at least one recognized TE2 flag appears somewhere in the argument list, the CLI auto-routes to TE2 mode. This means most existing TE2 invocations work without any changes. + +```bash +# All three are equivalent - each runs in TE2 mode +./te2 Model.bim -S fix.csx -D "localhost\tabular" MyDB -O +TE_COMPAT=te2 te Model.bim -S fix.csx -D "localhost\tabular" MyDB -O +te Model.bim -S fix.csx -D "localhost\tabular" MyDB -O +``` + +> [!NOTE] +> TE2 mode runs the same `Load → Scripts → Schema Check → Save → BPA → Deploy → TRX` pipeline as `TabularEditor.exe`, including context-sensitive flag behavior (e.g., `-S` after `-D` means `-SHARED`, not `-SCRIPT`). + +## The migrate command + +Use `te migrate` as a live reference for how TE2 flags map to the new CLI. It prints a colorized table of every known TE2 flag, its status (supported, renamed, planned), and the equivalent `te` command. + +```bash +te migrate # Full flag mapping table +te migrate -A # Look up a single flag +te migrate --output-format json # Machine-readable mapping +``` + +Refer to the output of the `te migrate` command for the current mapping that reflects the CLI version you have installed. + +## Flag mapping (curated subset) + +A non-exhaustive summary of the most commonly used flags. Run `te migrate` for the full list. + +| TE2 flag | New CLI equivalent | Notes | +| ------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `file` (positional) | `te ` or global `--model` | First positional arg on most commands. | +| `server`, `database` | `te connect ` or `te deploy ` | Server is no longer a global positional. | +| `-L` / `-LOCAL` | `te connect --local` | Windows only. | +| `-S` / `-SCRIPT` | `te script -s ` or `-e "code"` | Supports multiple scripts, inline code, and stdin. | +| `-A` / `-ANALYZE` | `te bpa run --rules ` | Supports `--fail-on`, `--fix`, multiple rule files. | +| `-AX` / `-ANALYZEX` | `te bpa run --rules ` (without `--model-rules`) | Excluding model-embedded rules is the new default. | +| `-B` / `-BIM` | `te save -o --serialization bim` | | +| `-F` / `-FOLDER` | `te save -o --serialization te-folder` | After `-D`, TE2's `-F` means `-FULL` - see `--deploy-full`. | +| `-TMDL` | `te save -o --serialization tmdl` | TMDL is the default save format. | +| `-D` / `-DEPLOY` | `te deploy ` | Separate command with named options. | +| `-O` / `-OVERWRITE` | (default) or `--create-only` to opt out | Overwrite is the default in the new CLI. | +| `-C` / `-CONNECTIONS` | `te deploy --deploy-connections` | | +| `-P` / `-PARTITIONS` | `te deploy --deploy-partitions` | | +| `-Y` / `-SKIPPOLICY` | `te deploy --deploy-partitions --skip-refresh-policy` | Requires `--deploy-partitions`. | +| `-SHARED` | `te deploy --deploy-shared-expressions` | After `-D`, TE2's `-S` means `-SHARED`. | +| `-R` / `-ROLES` | `te deploy --deploy-roles` | | +| `-M` / `-MEMBERS` | `te deploy --deploy-role-members` | | +| `-FULL` (after `-D`) | `te deploy --deploy-full` | Equivalent to overwrite + connections + partitions + shared + roles + role-members. | +| `-X` / `-XMLA ` | `te deploy ... --xmla ` | Use `-` for stdout. | +| `-V` / `-VSTS` | `--ci vsts` on `validate`, `bpa run`, `deploy` | Emits `##vso[...]` annotations to stderr. | +| `-G` / `-GITHUB` | `--ci github` | Emits `::error::` / `::warning::` annotations. | +| `-T` / `-TRX ` | `--trx ` on `validate`, `bpa run`, `test run` | VSTEST `.trx` file for Azure DevOps test publishing. | +| `-W` / `-WARN` | (default) | Warnings always reported in deploy results. | +| `-E` / `-ERR` | (default) | Deploy returns non-zero exit on DAX errors. | +| `-SC` / `-SCHEMACHECK` | _Not yet implemented._ | TE2 schema check connects to actual data sources. Different from `te validate` (DAX semantic validation, no data source connection). | +| `-L` / `-LOGIN ` (after `-D`) | `te auth login -u -p -t ` | Use service principal or env-based credentials. The login is cached, so subsequent commands acquire tokens silently - see @te-cli-auth. | + +## Migration playbook + +The recommended path from a TE2-based pipeline to the new CLI: + +1. **Drop-in replacement.** Replace `TabularEditor.exe` with `te` (or `te2`) in your existing pipeline. Verify the pipeline still runs - TE2 compatibility handles most invocations unchanged. +2. **Replace flags incrementally.** Convert one flag group at a time: + - Start with `-A` / `-AX` → `te bpa run` to pick up richer BPA output (`--fail-on`, `--fix`, `--trx`). + - Then `-D` → `te deploy` for fine-grained deploy control. + - Finally `-V` / `-G` → `--ci vsts` / `--ci github`. +3. **Switch to non-interactive CI flags.** Add `--non-interactive --ci ` to every `te` command and remove any `start /wait` wrappers - the new CLI is a regular console binary and doesn't need them. +4. **Adopt service principal auth.** Replace `-D -L ` with `te auth login -u ... -p ... -t ...` or an environment-credential pipeline step. See @te-cli-auth. + +## Important differences + +- **BPA gate on deploy.** `te deploy` now runs BPA as a pre-flight gate by default. Use `--skip-bpa` to preserve the old behavior, or `--fix-bpa` to auto-fix violations before deploy. See @te-cli-config. +- **Interactive confirmation on deploy.** `te deploy` prompts for confirmation by default (with `n` as the safe default answer). CI pipelines must pass `--force`. +- **Structured output.** Every command supports `--output-format json` for machine-readable output - see @te-cli-automation. +- **No `start /wait` needed.** The new CLI is a regular console binary; invoke it directly in shell scripts, PowerShell, and CI tasks. +- **Cross-platform.** The CLI runs on Windows, macOS, and Linux. Local SSAS and Power BI Desktop connections remain Windows-only. + +## Related pages + +- @command-line-options - the legacy TE2 command-line reference. +- @te-cli-commands - the new CLI's full command reference. +- @te-cli-cicd - pipeline examples for GitHub Actions and Azure DevOps. diff --git a/localizedContent/zh/content/features/te-cli/te-cli.md b/localizedContent/zh/content/features/te-cli/te-cli.md new file mode 100644 index 000000000..c3c43e33c --- /dev/null +++ b/localizedContent/zh/content/features/te-cli/te-cli.md @@ -0,0 +1,112 @@ +--- +uid: te-cli +title: Tabular Editor CLI (Limited Public Preview) +author: Peer Grønnerup +updated: 2026-05-12 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + none: true + - product: Tabular Editor CLI + full: true +--- + +# Tabular Editor CLI (Limited Public Preview) + +The Tabular Editor CLI (`te`) is a cross-platform command-line interface for Power BI and Analysis Services semantic models. It runs on Windows, macOS, and Linux as a single self-contained executable and is based on the same foundation that powers Tabular Editor 3. + +With the Tabular Editor CLI you can inspect, edit, validate, deploy, refresh, and test semantic models from a terminal - against local TMDL or BIM files, Power BI Desktop, or semantic models in Fabric and Power BI Service workspaces. + +Unlike the Windows-only `TabularEditor.exe` command-line options (TE2) - which was designed primarily to automate C# scripts and macros from a desktop binary - `te` is a purpose-built, cross-platform CLI with structured output, predictable exit codes, and an interactive shell. This unlocks scenarios that our existing [TE2 CLI](xref:command-line-options) can't cover well: terminal-driven model work on macOS and Linux, AI agents driving model changes directly, and clean drop-in for any modern CI runner. + +[!INCLUDE [te-cli-preview-notice](includes/te-cli-preview-notice.md)] + +## Built for three audiences + +Three design pillars run through every command: + +- **Structured output** — JSON, CSV, TMDL, TMSL alongside default human-readable text. +- **Non-interactive mode** — a global `--non-interactive` flag that disables prompts and fails fast. +- **Clear errors** — written to stderr with predictable exit codes. + +Together they make the same binary work well for three very different audiences: + +- **Humans** - scripting bulk edits, exploring a model from the terminal, composing commands in shell pipelines. +- **AI agents** - token-lean JSON, machine-parseable error shapes, exit codes that signal success or failure without parsing stdout. +- **CI/CD pipelines** - non-interactive execution, GitHub Actions and Azure DevOps annotations, VSTEST-compatible test results. + +## What the CLI can do + +The CLI organizes more than 50 commands into 10 families. Each family maps to a concrete stage of the semantic-model lifecycle. + +See @te-cli-commands for a full command reference with syntax, options, and examples for each command. Click any example command in the table to jump straight to its reference entry. + +| Family | What it does | Example commands | +| ------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Model I/O](xref:te-cli-commands#model-io) | Load, save, convert, initialize models | [`te load`](xref:te-cli-commands#load), [`te save`](xref:te-cli-commands#save), [`te init`](xref:te-cli-commands#init) | +| [Model Editing](xref:te-cli-commands#model-editing) | Get/set properties, add/remove/move objects | [`te set`](xref:te-cli-commands#set), [`te add`](xref:te-cli-commands#add), [`te rm`](xref:te-cli-commands#rm), [`te mv`](xref:te-cli-commands#mv) | +| [Inspection](xref:te-cli-commands#inspection) | List objects, search, diff, dependency analysis | [`te ls`](xref:te-cli-commands#ls), [`te find`](xref:te-cli-commands#find), [`te diff`](xref:te-cli-commands#diff), [`te deps`](xref:te-cli-commands#deps) | +| [Analysis & Quality](xref:te-cli-commands#analysis-and-quality) | Validate, run BPA, format DAX, analyze storage | [`te validate`](xref:te-cli-commands#validate), [`te bpa run`](xref:te-cli-commands#bpa-run), [`te format`](xref:te-cli-commands#format), [`te vertipaq`](xref:te-cli-commands#vertipaq) | +| [Execution](xref:te-cli-commands#execution) | Run DAX queries, C# scripts, macros | [`te query`](xref:te-cli-commands#query), [`te script`](xref:te-cli-commands#script), [`te macro`](xref:te-cli-commands#macro) | +| [Deployment & Refresh](xref:te-cli-commands#deployment-and-refresh) | Deploy to workspace, trigger refresh, incremental refresh | [`te deploy`](xref:te-cli-commands#deploy), [`te refresh`](xref:te-cli-commands#refresh), [`te incremental-refresh`](xref:te-cli-commands#incremental-refresh) | +| [Testing](xref:te-cli-commands#testing) | Assertion tests, snapshots, A/B comparison | [`te test run`](xref:te-cli-commands#test-run) | +| [Connection & Authentication](xref:te-cli-commands#connection-and-auth) | Connect to workspaces, manage authentication and profiles | [`te connect`](xref:te-cli-commands#connect), [`te auth`](xref:te-cli-commands#auth-login--status--logout), [`te profile`](xref:te-cli-commands#profile-list--show--set--remove) | +| [Configuration](xref:te-cli-commands#configuration) | Settings and licensing | [`te config`](xref:te-cli-commands#config-show--paths--init--set) | +| [Shell](xref:te-cli-commands#shell) | Interactive mode, shell completions | [`te interactive`](xref:te-cli-commands#interactive), [`te completion`](xref:te-cli-commands#completion) | + +## Getting started + +1. **Sign up or sign in** at [tabulareditor.com](https://tabulareditor.com/download-tabular-editor-cli) with a Tabular Editor account. +2. **Download and install** - see @te-cli-install for Windows, macOS, and Linux instructions. +3. **Authenticate** - run `te auth login` to connect to Power BI or Fabric. See @te-cli-auth. +4. **Run your first command** - `te --help` lists every command; `te --help` shows detailed options. + +A first look at a live model takes two commands: + +```bash +te auth login +te ls -s MyWorkspace -d MyModel +``` + +![Tabular Editor CLI te ls example output](~/content/assets/images/features/cli/cli-command-ls.png) + +## Preview notice + +Every command prints a yellow preview banner on stderr by default: + +![Tabular Editor CLI preview notice banner](~/content/assets/images/features/cli/cli-preview-notice.png) + +To hide the preview notice, simply run: + +```bash +te config set hidePreviewNotice true +``` + +> [!WARNING] +> The banner reappears on every command within **14 days of the preview end date** (2026-09-30), regardless of `hidePreviewNotice`. This ensures you have visible warning before the CLI stops functioning. + +## License outlook + +During Limited Public Preview, the CLI does not require a license; you only need a Tabular Editor account to download it. At General Availability (GA) the CLI will require a license; pricing is still being finalized and will be announced ahead of GA. + +## Feedback and community + +During the preview, bug reports, feature requests, and general discussion happen in the public [TabularEditor/CLI](https://github.com/TabularEditor/CLI) repository on GitHub: + +- **Issues** - report bugs, request features, and track known problems. +- **Discussions** - ask questions, share feedback, and swap usage tips with other early adopters. + +The repository does not host the CLI source code; it exists to give the community a public place to reach us during the preview. + +## Next steps + +- @te-cli-install - download, install, verify. +- @te-cli-auth - authenticate to Power BI, Fabric, and Azure Analysis Services. +- @te-cli-commands - full command reference. +- @te-cli-config - configuration file and path overrides. +- @te-cli-interactive - guided REPL mode for new users. +- @te-cli-automation - structured output, scripting patterns for Python, PowerShell, and Bash. +- @te-cli-cicd - GitHub Actions and Azure DevOps pipeline examples. +- @te-cli-migrate - migrating from the Tabular Editor 2 command line. diff --git a/localizedContent/zh/content/getting-started/editions.md b/localizedContent/zh/content/getting-started/editions.md index 89ccbaeb1..baf5bff80 100644 --- a/localizedContent/zh/content/getting-started/editions.md +++ b/localizedContent/zh/content/getting-started/editions.md @@ -16,11 +16,11 @@ applies_to: 本文档概述并对比 Tabular Editor 3 的不同版本。 > [!NOTE] -> Tabular Editor 3 的许可证为**按开发者授权**。 换句话说,只有实际使用 Tabular Editor 3 产品的人才需要许可证。 +> Tabular Editor 3 许可证为**按开发者**授权。 换句话说,只有实际使用 Tabular Editor 3 产品的人才需要许可证。 ## 支持的 Data model 建模场景 -Tabular Editor 3 各版本的主要区别在于它们支持哪些类型的表格 Data model 建模场景。 要理解这一差异,可以把 Analysis Services(Tabular)看作有多种不同的“形态”: +Tabular Editor 3 各版本之间的主要区别在于它们支持哪些类型的表格数据建模场景。 要理解这一差异,可以把 Analysis Services(Tabular)看作有多种不同的“形态”: - Power BI Desktop(请确保您了解[限制](xref:desktop-limitations)) - 通过 XMLA 终结点使用的 Power BI Premium(Premium Per User、**Premium 容量 [A、EM 或 P SKUs]**、**Fabric 容量 [F SKUs]**) @@ -30,7 +30,7 @@ Tabular Editor 3 各版本的主要区别在于它们支持哪些类型的表格 我们将 Analysis Services 中**突出显示**的这些形态视为企业级,因此只能在 Tabular Editor 3 企业版中使用。 > [!IMPORTANT] -> Tabular Editor 只允许编辑兼容级别为 1200 或更高的 Data model。 自 SQL Server 2016 起,Analysis Services 的所有实例默认都是如此。 出于同样的原因,Tabular Editor 不支持 Excel PowerPivot,因为它使用更早的兼容级别。 +> Tabular Editor 仅允许编辑兼容级别为 1200 或更高的数据模型。 自 SQL Server 2016 起,Analysis Services 的所有实例默认都是如此。 出于同样的原因,Tabular Editor 不支持 Excel PowerPivot,因为它使用更早的兼容级别。 支持的场景完整概览见下方矩阵: @@ -53,11 +53,11 @@ Tabular Editor 3 各版本的主要区别在于它们支持哪些类型的表格 | [高级刷新对话框](xref:advanced-refresh) | | | | | [免费 DAX优化器许可证](xref:dax-optimizer-integration) | | | | -\*\*\*注意:\*\*如果 Analysis Services Data model 包含透视,或者某个表包含多个分区,则需要企业版(不适用于 Power BI Desktop 或 Power BI Premium Per User 模型)。 +\***注:** 如果 Analysis Services Data model 包含透视或包含多个分区的表,则需要企业版(不适用于 Power BI Desktop 或 Power BI Premium Per User 模型)。 \*\***注意:** 支持的文件格式包括:**.pbip**(Power BI Project)、**.pbit**(Power BI 模板)、**.bim**(Analysis Services 模型元数据)、**.vpax**(VertiPaq分析器)以及**Database.json**(Tabular Editor 文件夹结构)、**TMDL**(Tabular Model Definition Language,表格模型定义语言)。 -\*\*\*\*\*注意:\*\*工作区模式允许 Tabular Editor 3 同时将模型元数据保存到磁盘,并让数据库与所购买的 Tabular Editor 3 版本支持的任意 Analysis Services 或 Power BI 版本保持同步。 +\*\*\***注:** 工作区模式允许 Tabular Editor 3 同时将模型元数据保存到磁盘,并同步所购买的 Tabular Editor 3 版本支持的任意 Analysis Services 或 Power BI 版本上的数据库。 ## 建模限制 @@ -78,7 +78,7 @@ Tabular Editor 3 各版本的主要区别在于它们支持哪些类型的表格 | Power BI | DirectQuery | | | | Power BI | Direct Lake | | | -\***注意:** SQL Server 2019 之前的标准版 Analysis Services 不支持 DirectQuery。 Azure AS 基本层也同样不支持 DirectQuery。 [了解更多](https://learn.microsoft.com/en-us/analysis-services/analysis-services-features-by-edition?view=asallproducts-allversions#tabular-models)。 +\***注:** SQL Server 标准版 2019 之前的 Analysis Services 不支持 DirectQuery。 Azure AS 基本层也同样不支持 DirectQuery。 [了解更多](https://learn.microsoft.com/en-us/analysis-services/analysis-services-features-by-edition?view=asallproducts-allversions#tabular-models)。 \*\***注意:** 在商业版中,Power BI 模型支持透视和多个分区,但模型的 `CompatibilityMode` 必须设置为 `PowerBI`。 有关操作说明,请参阅 [更改兼容模式](xref:change-compatibility-mode)。 @@ -89,10 +89,10 @@ Tabular Editor 3 各版本的主要区别在于它们支持哪些类型的表格 除了上面列出的内容之外,Tabular Editor 3 各版本之间没有其他功能差异。 > [!NOTE] -> 请注意,Power BI Desktop [目前并不支持所有 Data model 建模操作](xref:desktop-limitations)。 因此,Tabular Editor 3 默认会阻止 Power BI Desktop 不支持的操作。 不过,你可以在“工具 > 偏好 > Power BI”中解除该限制。 +> 请注意,Power BI Desktop [目前不支持所有 Data model 建模操作](xref:desktop-limitations)。 因此,Tabular Editor 3 默认会阻止 Power BI Desktop 不支持的操作。 不过,你可以在“工具 > 偏好 > Power BI”中解除该限制。 > [!IMPORTANT] -> 仅当 Power BI Report(.pbix、.pbip 或 .pbit)文件包含 Data model(导入、DirectQuery 或复合模式)时,Tabular Editor 才能作为 Power BI Desktop 的外部工具使用。 **不支持使用 Live connection 的 Report**,因为这些 Report 不包含 Data model。 [更多信息](xref:desktop-limitations)。 +> 只有当 Power BI Report(.pbix、.pbip 或 .pbit)文件包含 Data model(Import、DirectQuery 或 Composite)时,Tabular Editor 才能在 Power BI Desktop 中作为外部工具使用。 **不支持使用 Live connection 的 Report**,因为这些 Report 不包含 Data model。 [更多信息](xref:desktop-limitations)。 ## 个人许可证与可转让许可证 @@ -111,7 +111,7 @@ Tabular Editor 3 各版本的主要区别在于它们支持哪些类型的表格 > [!NOTE] > 在多位用户之间共享同一个许可证违反我们的[许可条款](https://tabulareditor.com/license-terms)。 -你可以随时在工具中停用现有安装:在“帮助 > 关于 Tabular Editor”中选择“更改许可证密钥...”选项。 你也可以通过我们的[自助门户](https://tabulareditor.com/sign-in)停用安装:进入“Licenses”选项卡。 +你可以随时在工具内停用现有安装:在“帮助 > 关于 Tabular Editor”下选择“更改许可证密钥...”选项。 你也可以通过我们的[自助门户](https://tabulareditor.com/sign-in)停用安装:进入“Licenses”选项卡。 如果您需要的 Tabular Editor 3 并发安装数量超过上述范围,请联系 [licensing@tabulareditor.com](mailto:licensing@tabulareditor.com)。 diff --git a/localizedContent/zh/content/how-tos/scripting-check-object-types.md b/localizedContent/zh/content/how-tos/scripting-check-object-types.md index 5f9349f48..3bb738e26 100644 --- a/localizedContent/zh/content/how-tos/scripting-check-object-types.md +++ b/localizedContent/zh/content/how-tos/scripting-check-object-types.md @@ -99,7 +99,7 @@ foreach (var col in Model.AllColumns) > > - `Column` 是抽象类型,但你无需进行类型转换,也可以访问基类型上定义的所有属性(`Name`、`DataType`、`FormatString`、`IsHidden`、`Description`、`DisplayFolder`)。 只有在你需要子类型特有的属性(例如 `CalculatedColumn` 上的 `Expression`)时,才将其转换为该子类型。 > - `OfType()` 会同时进行筛选和类型转换。 `Where(x => x is T)` 只会筛选,结果仍然是基类型。 当你需要访问子类型属性时,优先使用 `OfType()`。 -> - 计算表格的列会自动维护。 要添加或更改列,就编辑计算表格的 `Expression`。 你不能直接添加这些列。 +> - 计算表格的列会自动管理。 要添加或更改列,就编辑计算表格的 `Expression`。 你不能直接添加这些列。 ## 另见 diff --git a/localizedContent/zh/content/how-tos/scripting-dynamic-linq-vs-csharp.md b/localizedContent/zh/content/how-tos/scripting-dynamic-linq-vs-csharp.md index 104982047..851a1475b 100644 --- a/localizedContent/zh/content/how-tos/scripting-dynamic-linq-vs-csharp.md +++ b/localizedContent/zh/content/how-tos/scripting-dynamic-linq-vs-csharp.md @@ -33,7 +33,7 @@ C# Script 使用标准的 C# LINQ,并使用 Lambda 表达式。 Best Practice | 概念 | C# LINQ(脚本) | Dynamic LINQ(BPA / 筛选器) | | -------------- | ------------------------------------------ | ---------------------------------------- | | 逻辑与 | `&&` | `and` | -| 逻辑或 | `\\|\\|` | `or` | +| 逻辑或 | `\|\|` | `or` | | 逻辑非 | `!` | `not` | | 等于 | `==` | `=` | | 不等于 | `!=` | `!=` 或 `<>` | diff --git a/localizedContent/zh/content/how-tos/scripting-perspectives-translations.md b/localizedContent/zh/content/how-tos/scripting-perspectives-translations.md index 9b8f45bb2..a5f6564d9 100644 --- a/localizedContent/zh/content/how-tos/scripting-perspectives-translations.md +++ b/localizedContent/zh/content/how-tos/scripting-perspectives-translations.md @@ -13,7 +13,7 @@ applies_to: # 如何使用透视和翻译 -透视用于控制哪些对象会显示在特定的客户端视图中。 翻译(区域设置)提供本地化的名称、描述和显示文件夹。 两者都使用 TOM 对象上的索引器属性。 有关访问 TOM 对象及其索引器的详细信息,请参阅 @how-to-navigate-tom-hierarchy。 +透视用于控制哪些对象会显示在特定的客户端视图中。 翻译(区域设置)提供本地化的名称、描述和显示文件夹。 两者都使用 TOM 对象上的索引器属性。 有关如何访问 TOM 对象及其索引器的详细信息,请参阅 @how-to-navigate-tom-hierarchy。 ## 快速参考 diff --git a/localizedContent/zh/content/how-tos/scripting-ui-helpers.md b/localizedContent/zh/content/how-tos/scripting-ui-helpers.md index 4b4195643..c4fad3b7a 100644 --- a/localizedContent/zh/content/how-tos/scripting-ui-helpers.md +++ b/localizedContent/zh/content/how-tos/scripting-ui-helpers.md @@ -68,7 +68,7 @@ Info("Updated " + Selected.Measures.Count() + " measures."); | 字符串或基本类型 | 简单的信息对话框 | > [!NOTE] -> 字符串输出使用 Windows 行结束符。 使用 `\r\n` 或 `Environment.NewLine` 来插入换行符。 单独的 `\\n` 会渲染为一行。 这常让使用 M 表达式的用户出错:M 表达式使用 `\n`,但在 `Output()` 中会作为单行输出。 +> 字符串输出使用 Windows 行结束符。 使用 `\r\n` 或 `Environment.NewLine` 来插入换行符。 单独的 `\\n` 会渲染为一行。 这会让使用 M 表达式的用户很容易踩坑:它们使用 `\\n`,但在 `Output()` 中会被打印成一行。 ### 用于结构化输出的 DataTable diff --git a/localizedContent/zh/content/how-tos/scripting-work-with-expressions.md b/localizedContent/zh/content/how-tos/scripting-work-with-expressions.md index 47eaf3cd9..0b62006f8 100644 --- a/localizedContent/zh/content/how-tos/scripting-work-with-expressions.md +++ b/localizedContent/zh/content/how-tos/scripting-work-with-expressions.md @@ -72,7 +72,7 @@ m.FormatString = "#,##0.00"; | `DaxTableName` | `'Sales'` | `'Sales'` | `'Sales'` | > [!NOTE] -> 对于度量值,`DaxObjectFullName` 返回与 `DaxObjectName`(不带限定符)相同的值。 在 DAX 中,度量值不需要表名限定。 对于列,`DaxObjectFullName` 包含表前缀。 +> 对于度量值,`DaxObjectFullName` 返回的值与 `DaxObjectName`(不带限定符)相同。 在 DAX 中,度量值不需要表名限定。 对于列,`DaxObjectFullName` 包含表前缀。 生成 DAX 时,请使用以下属性以避免引号错误: diff --git a/localizedContent/zh/content/how-tos/update-compatibility-level.md b/localizedContent/zh/content/how-tos/update-compatibility-level.md index 451fe15c2..c37d96dd2 100644 --- a/localizedContent/zh/content/how-tos/update-compatibility-level.md +++ b/localizedContent/zh/content/how-tos/update-compatibility-level.md @@ -22,7 +22,7 @@ applies_to: 模型的 **兼容级别** 决定你可以使用哪些 Tabular Object Model (TOM) 功能。 当 Microsoft 引入自定义日历或 DAX 用户定义函数等新功能时,这些功能通常需要在较新的兼容级别下才会开放。 你需要先升级,这些功能才会出现在 Tabular Editor 中。 > [!WARNING] -> 兼容级别升级是不可逆的。 你可以升级,但无法可靠地降级。 将其视为一次架构升级,并先验证你的部署目标。 +> 兼容性升级是不可逆的。 你可以升级,但无法可靠地降级。 将其视为一次架构升级,并先验证你的部署目标。 ## 兼容级别与兼容模式 diff --git a/localizedContent/zh/content/references/downloads.md b/localizedContent/zh/content/references/downloads.md index d8dde3792..8ad847ace 100644 --- a/localizedContent/zh/content/references/downloads.md +++ b/localizedContent/zh/content/references/downloads.md @@ -23,7 +23,7 @@ Tabular Editor 3.26.1 **.NET 8** 下载: ## 安装说明 1. 下载 .exe 安装程序文件。 -2. 运行此 .exe 安装程序。 安装向导将引导你完成安装。 +2. 运行.exe 安装程序。 安装向导将引导你完成安装。 3. 有关如何激活产品或更换许可证密钥的说明,请参阅我们的[入门指南](xref:getting-started)。 升级到更新版本的 Tabular Editor 3 时,无需卸载之前安装的版本。 diff --git a/localizedContent/zh/content/security/terms.md b/localizedContent/zh/content/security/terms.md new file mode 100644 index 000000000..6e2982460 --- /dev/null +++ b/localizedContent/zh/content/security/terms.md @@ -0,0 +1,22 @@ +--- +uid: terms +title: 条款与条件 +author: Søren Toft Joensen +updated: 2026-05-29 +applies_to: + products: + - product: Tabular Editor 2 + none: true + - product: Tabular Editor 3 + full: true + - product: TE CLI + full: true +--- + +# 条款与条件 + +请参阅以下最新版本的条款与条件: + +- [商业条款与条件](https://tabulareditor.com/commercial-terms) +- [Tabular Editor 3 最终用户许可协议 EULA](https://tabulareditor.com/eula-te3) +- [Tabular Editor CLI 最终用户许可协议 EULA](https://tabulareditor.com/eula-cli) diff --git a/localizedContent/zh/content/security/third-party-notices.md b/localizedContent/zh/content/security/third-party-notices.md index be7371086..420c3d068 100644 --- a/localizedContent/zh/content/security/third-party-notices.md +++ b/localizedContent/zh/content/security/third-party-notices.md @@ -260,11 +260,9 @@ Microsoft 公共许可证 (Ms-PL) ## Snowflake.Data 许可证 - ``` - Apache 许可证 - 版本 2.0,2004 年一月 - http://www.apache.org/licenses/ - ``` + Apache 许可证 + 版本 2.0,2004 年一月 + http://www.apache.org/licenses/ 使用、复制和分发的条款与条件 @@ -352,14 +350,14 @@ Microsoft 公共许可证 (Ms-PL) 附录:如何将 Apache 许可证应用于你的作品。 - 要将 Apache 许可证应用于你的作品,请附上以下 - 样板声明,并将花括号“{}”中的字段 - 替换为你自己的识别信息。(不要包含 - 花括号!)文本应使用与该文件格式相适配的 - 注释语法括起来。我们还建议在与版权声明相同的 - “打印页面”上同时包含 - 文件或类名以及用途说明,以便在第三方归档中 - 更容易识别。 + 要将 Apache 许可证应用于你的作品,请附上以下 + 样板声明,并将花括号“{}”中的字段 + 替换为你自己的识别信息。(不要包含 + 花括号!)文本应使用与该文件格式相适配的 + 注释语法括起来。我们还建议在与版权声明相同的 + “打印页面”上同时包含 + 文件或类名以及用途说明,以便在第三方归档中 + 更容易识别。 版权所有 (c) 2017 Snowflake Computing Inc. 保留所有权利。 @@ -367,9 +365,7 @@ Microsoft 公共许可证 (Ms-PL) 除非遵守本许可证,否则你不得使用此文件。 你可以在以下位置获取许可证副本 - ``` - http://www.apache.org/licenses/LICENSE-2.0 - ``` + http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或经书面同意,否则 根据本许可证分发的软件按“原样”提供, @@ -381,11 +377,9 @@ Microsoft 公共许可证 (Ms-PL) ## Dynamic-LINQ.net 的许可证 - ``` - Apache 许可证 - 2.0 版,2004 年一月 - http://www.apache.org/licenses/ - ``` + Apache 许可证 + 2.0 版,2004 年一月 + http://www.apache.org/licenses/ 使用、复制和分发的条款和条件 @@ -494,12 +488,12 @@ Microsoft 公共许可证 (Ms-PL) 附录:如何将 Apache 许可证应用于你的作品。 - 要将 Apache 许可证应用于你的作品,请附上以下 - 样板声明,并将方括号“[]”内的字段替换为你自己的 - 身份标识信息。(不要包含方括号!)文本应置于与该文件 - 格式相应的注释语法中。我们还建议在与版权声明 - 相同的“打印页面”上包含文件或类名称以及用途说明, - 以便在第三方归档中更容易识别。 + 要将 Apache 许可证应用于你的作品,请附上以下 + 样板声明,并将方括号“[]”内的字段替换为你自己的 + 身份标识信息。(不要包含方括号!)文本应置于与该文件 + 格式相应的注释语法中。我们还建议在与版权声明 + 相同的“打印页面”上包含文件或类名称以及用途说明, + 以便在第三方归档中更容易识别。 Copyright [2016] [Stef Heyenrath] @@ -507,9 +501,7 @@ Copyright [2016] [Stef Heyenrath] 除非遵守该许可证,否则你不得使用此文件。 你可以在以下位置获取许可证副本 - ``` - http://www.apache.org/licenses/LICENSE-2.0 - ``` + http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或经书面同意,否则按本许可证分发的软件 按“原样”提供, diff --git a/localizedContent/zh/content/troubleshooting/databricks-column-comments-length.md b/localizedContent/zh/content/troubleshooting/databricks-column-comments-length.md index ec03e7107..8e192d460 100644 --- a/localizedContent/zh/content/troubleshooting/databricks-column-comments-length.md +++ b/localizedContent/zh/content/troubleshooting/databricks-column-comments-length.md @@ -22,7 +22,7 @@ applies_to: > [!TIP] > Databricks 已发布新的 ODBC 驱动程序,用于替代旧版 Simba Spark ODBC Driver。 新版 [Databricks ODBC Driver](https://www.databricks.com/spark/odbc-drivers-download) 可能没有下文所述的 `MaxCommentLen` 限制。 如果你遇到此问题,建议切换到新驱动程序,Tabular Editor 3.26.0 及更高版本已支持该驱动程序。 -使用“导入表向导”从 Databricks 导入表时,如果列注释(描述)超过 512 个字符,可能会出现连接错误。 这一限制来自 Simba Spark ODBC Driver,尽管 Databricks Unity Catalog 允许更长的列注释。 +使用“导入表向导”从 Databricks 导入表时,如果列注释(说明)超过 512 个字符,可能会遇到连接错误。 这一限制来自 Simba Spark ODBC Driver,尽管 Databricks Unity Catalog 允许更长的列注释。 典型的错误信息如下: @@ -34,7 +34,7 @@ applies_to: ## 了解问题 -Tabular Editor 使用 Simba Spark ODBC Driver 连接到 Databricks,而该驱动对列注释的默认长度限制是 512 个字符。 无论 Databricks Unity Catalog 允许的长度是多少,这个限制都会被强制执行。 +Tabular Editor 通过 Simba Spark ODBC Driver 连接到 Databricks,该驱动对列注释的默认长度限制为 512 个字符。 无论 Databricks Unity Catalog 允许的长度是多少,这个限制都会被强制执行。 ### 为什么会这样 @@ -204,13 +204,13 @@ Tabular Editor 使用 Simba Spark ODBC Driver 连接到 Databricks,而该驱 如果以上步骤未能解决你的问题: -1. **验证 ODBC 驱动程序版本**:确保已安装最新版本的 Simba Spark ODBC Driver。 你可以从 [Microsoft Azure Databricks ODBC 下载页面](https://learn.microsoft.com/azure/databricks/integrations/odbc/download) 下载。 +1. **检查 ODBC 驱动程序版本**:确保已安装最新版本的 Simba Spark ODBC Driver。 你可以从 [Microsoft Azure Databricks ODBC 下载页面](https://learn.microsoft.com/azure/databricks/integrations/odbc/download) 下载该驱动程序。 2. **检查 ODBC 数据源配置**:打开 Windows 的 ODBC 数据源管理器 (odbcad32.exe),确认你的 Databricks 连接已正确配置。 3. **用更简单的表测试**:尝试导入一张你确定列注释很短(或没有注释)的 Databricks 表,先确认连接本身是否正常。 -4. **查看 ODBC 驱动程序日志**:Simba Spark ODBC Driver 可以生成详细日志。 参考驱动程序文档,按说明启用日志记录;日志可能会提供更多诊断信息。 +4. **查看 ODBC 驱动程序日志**:Simba Spark ODBC Driver 可以生成详细的日志。 参考驱动程序文档,按说明启用日志记录;日志可能会提供更多诊断信息。 5. **联系支持**:联系 Tabular Editor 支持团队,并提供: - 完整的错误信息文本 diff --git a/localizedContent/zh/content/tutorials/connecting-to-azure-databricks.md b/localizedContent/zh/content/tutorials/connecting-to-azure-databricks.md index f2c787dfd..2bf82561e 100644 --- a/localizedContent/zh/content/tutorials/connecting-to-azure-databricks.md +++ b/localizedContent/zh/content/tutorials/connecting-to-azure-databricks.md @@ -51,9 +51,9 @@ Tabular Editor 使用 Power Query `Databricks.Catalogs()` 函数连接到 Databr 连接到 Azure Databricks 时,您可以使用以下几种身份验证方法: -### 1。 Microsoft Entra ID(原 Azure AD)身份验证 +### 1。 Microsoft Entra ID(前身为 Azure AD)身份验证 -如果你的组织使用 Microsoft Entra ID,建议采用这种方式连接到 Azure Databricks。 这种方法可提供无缝的单点登录,并通过托管身份提升安全性。 +如果你的组织使用 Microsoft Entra ID,这是连接到 Azure Databricks 的推荐方法。 这种方法可提供无缝的单点登录,并通过托管身份提升安全性。 #### 关于 Tabular Editor 企业应用 @@ -62,18 +62,18 @@ Tabular Editor 使用 Power Query `Databricks.Catalogs()` 函数连接到 Databr 此企业应用需要以下 API 权限: - **Microsoft Graph** (`00000003-0000-0000-c000-000000000000`) - - `offline_access`(委托)- 此权限允许 Tabular Editor 即使在你未主动使用该应用时,也能持续访问你已授权其访问的数据。 这是维持与 Databricks 持续连接所必需的。 + - `offline_access`(委托)- 此权限允许 Tabular Editor 在你未主动使用应用程序时,仍能持续访问你已授权给它的数据。 这是维持与 Databricks 持续连接所必需的。 - `openid`(委托)- 允许用户使用其工作或学校账户登录该应用,并允许该应用查看基本的用户个人资料信息。 - `profile`(委托)- 允许该应用查看基本个人资料信息,例如姓名、电子邮件地址、照片和用户名。 - `User.Read`(委托)- 允许该应用读取您的个人资料,并在访问 Databricks API 时识别您的身份。 - **Azure Databricks API** (`2ff814a6-3304-4ab8-85cb-cd0e6f879c1d`) - - `user_impersonation`(委托)- 代表已登录用户访问 Azure Databricks。 这样,Tabular Editor 就能使用你的凭据连接到 Databricks Workspace。 + - `user_impersonation`(委托)- 代表已登录用户访问 Azure Databricks。 这使 Tabular Editor 能够使用你的凭据连接到你的 Databricks Workspace。 有关 Microsoft Entra ID 权限的更多信息,请参阅 [Microsoft 关于权限类型的文档](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent) 和 [应用同意体验](https://learn.microsoft.com/en-us/azure/active-directory/develop/application-consent-experience)。 > [!IMPORTANT] -> Tabular Editor 需要这些权限,才能通过您的 Microsoft Entra ID 凭据安全访问您的 Azure Databricks 数据。 如果没有这些权限,Tabular Editor 将无法在你的 Azure Databricks Workspace 中正确完成身份验证。 +> Tabular Editor 需要这些权限,才能通过您的 Microsoft Entra ID 凭据安全访问您的 Azure Databricks 数据。 如果没有这些权限,Tabular Editor 将无法对你的 Azure Databricks Workspace 正确进行身份验证。 #### Microsoft Entra ID 身份验证的同意流程 @@ -88,7 +88,7 @@ Tabular Editor 使用 Power Query `Databricks.Catalogs()` 函数连接到 Databr 3. 点击 **Accept** 以授予同意 > [!NOTE] -> 是否需要管理员同意取决于你所在组织的 Microsoft Entra ID 策略,而不一定取决于所请求的具体 API 权限。 许多组织允许用户自行同意委托权限,而另一些组织则要求所有第三方应用程序无论权限级别如何都必须由管理员批准。 +> 是否需要管理员同意取决于你所在组织的 Microsoft Entra ID 策略,不一定取决于所请求的具体 API 权限。 许多组织允许用户自行同意委托权限,而另一些组织则要求所有第三方应用程序无论权限级别如何都必须由管理员批准。 ##### 需要管理员同意 @@ -180,7 +180,7 @@ https://login.microsoftonline.com/organizations/v2.0/adminconsent?client_id=ea0f ## 查找你的 HTTP Path -HTTP Path 参数对于连接到 Databricks SQL Warehouse 至关重要。 查找该值的方法: +HTTP Path 参数对于连接到你的 Databricks SQL Warehouse 至关重要。 查找该值的方法: 1. 前往你的 Databricks Workspace 2. 依次选择 **SQL** > **SQL Warehouse** @@ -241,7 +241,7 @@ HTTP Path 参数对于连接到 Databricks SQL Warehouse 至关重要。 查找 2. 请他们将 Tabular Editor 企业应用程序(ID:`ea0fc0fe-ed02-40d7-a29a-cc0a59d8b42c`)添加到你组织的允许应用程序列表中 > [!TIP] -> 在某些组织中,IT 部门在批准新的企业应用程序之前,可能需要提交正式申请或进行安全审查。 你需要准备好说明:此应用由 Tabular Editor 3 使用,借助组织现有的 Microsoft Entra ID 身份验证基础架构,安全连接到 Azure Databricks 资源。 +> 在某些组织中,IT 部门在批准新的企业应用程序之前,可能需要提交正式申请或进行安全审查。 请准备好解释:此应用程序由 Tabular Editor 3 使用,借助你所在组织现有的 Microsoft Entra ID 身份验证基础设施,安全连接到 Azure Databricks 资源。 ## 在 Databricks 中使用“更新表架构” diff --git a/localizedContent/zh/content/tutorials/udfs.md b/localizedContent/zh/content/tutorials/udfs.md index 5d1d854a3..b9b98162d 100644 --- a/localizedContent/zh/content/tutorials/udfs.md +++ b/localizedContent/zh/content/tutorials/udfs.md @@ -317,11 +317,12 @@ Tabular Editor 3 会自动识别所有注释,并在自动完成建议和工具 ## 局限性 -- UDF 目前为预览功能,在某些部署场景中可能会有局限 - 并非所有 Power BI 环境都支持 UDF(需要特定构建版本) - UDF 不能递归(调用自身) -- UDF 不支持可选参数、带默认值的参数或参数重载 + +> [!NOTE] +> 截至 2026 年六月,UDF 已 [正式可用](https://community.fabric.microsoft.com/t5/Power-BI-Updates-Blog/DAX-User-Defined-Functions-Generally-Available/ba-p/5185738)。 作为其中的一部分,UDF 现已支持默认表达式和可选参数。 但是,在使用默认表达式语法时,Tabular Editor 3 目前会误报一条错误信息。 此问题将在 Tabular Editor 3 的下一次更新中修复。 --- -Tabular Editor 3 中的 UDF 提供了一种强大方式,可用于创建可复用、易维护的 DAX 代码。 遵循这些指南和最佳实践,你可以构建一个函数库,从而提升模型一致性并缩短开发时间。 \ No newline at end of file +Tabular Editor 3 中的 UDF 提供了一种强大方式,可用于创建可复用、易维护的 DAX 代码。 遵循这些指南和最佳实践,你可以构建一个函数库,从而提升模型一致性并缩短开发时间。