# CLI Cortex Framework metadata

`uv run cortex-metadata` extracts, caches, searches, and inspects
Google Cloud Cortex Framework schema metadata across raw source datasets, data
foundations, data products, and external catalogs, and generates column-level
lineage graphs and Entity-Relationship (ER) diagrams.

## Before you begin

- **Local Dataform compiler** : Extracting foundation or data product schemas (`uv run cortex-metadata fetch`) compiles models in an ephemeral workspace and requires Node.js (`npx`) or `@dataform/cli` in your `PATH`. See [Install Dataform CLI](https://docs.cloud.google.com/cortex/docs/prerequisites.md.txt#dataform-cli).
- **BigQuery credentials and roles** : Authenticate Application Default Credentials (`gcloud auth application-default login`). Your principal needs `roles/bigquery.dataViewer` on raw, foundation, and external catalog datasets plus `roles/bigquery.jobUser` on `buildEnvironment.buildProjectId` for zero-cost data product dry runs. For SAP Data Dictionary (DDIC) enrichment, your principal also needs `roles/bigquery.jobUser` on the SAP raw dataset project if it differs from `buildEnvironment.buildProjectId`. Once schemas are cached in `.cortex/cache`, `list`, `search`, and `lineage` read strictly from the local cache without BigQuery API calls, while `show` and `erd` (when `MODULE_ID` is provided) read from cache and auto-fetch missing targets on demand unless `--no-auto-fetch` is set.

## Synopsis

```bash
uv run cortex-metadata [-h] \
    [-c CONFIG_PATH | --config CONFIG_PATH] \
    [-w WORKSPACE_ROOT] \
    [--cache-dir CACHE_DIR] \
    {fetch,list,show,search,lineage,erd,clear} ...
```

Replace the following:

- `CONFIG_PATH`: path to your active `config.yaml` file, for example: `config/config.yaml`.
- `WORKSPACE_ROOT`: root directory of your Cortex Framework workspace, for example: `.`.
- `CACHE_DIR`: directory where cached schema metadata files are stored, for example: `.cortex/cache`.

> [!NOTE]
> **Note:** Common workspace options (`-c` or `--config`, `-w` or `--workspace-root`, and `--cache-dir`) are accepted either before or after the sub-command name.

## Global flags

The following table describes the global options shared across all
`uv run cortex-metadata` sub-commands:

| Flag | Description | Default |
| `-h, --help` | Show the command or sub-command help message and exit. | None |
| `-c, --config CONFIG_PATH` | Path to the active [`config.yaml`](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#config-config-yaml) configuration file. | `config/config.yaml` |
| `-w, --workspace-root WORKSPACE_ROOT` | Workspace root directory used to resolve relative paths and the default metadata cache. | Current working directory |
| `--cache-dir CACHE_DIR` | Custom directory for reading and writing cached YAML metadata artifacts. | `.cortex/cache` |
|---|---|---|

## Schema cache and ephemeral compilation

`uv run cortex-metadata fetch` persists structured YAML schema documents under
`.cortex/cache/` across four architectural categories:

    .cortex/cache/
    ├── raw/                      # Raw physical BigQuery landing and CDC tables
    │   └── <dataSourceId>/
    │       └── <table_name>.yaml
    ├── foundations/              # Conformed data foundation tables and operations
    │   └── <moduleId>/
    │       └── <table_name>.yaml
    ├── products/                 # Source-aligned and consumption data products
    │   └── <moduleId>/
    │       └── <table_name>.yaml
    └── catalogs/                 # External BigLake Delta Sharing and Analytics Hub catalogs
        └── <catalogId>/
            └── <table_name>.yaml

Each cached YAML file stores a validated `TableMetadata` record serialized with
camelCase keys containing:

- **Origin coordinates (`origin`)** : `category`, `moduleId`, `dataSourceId`, or `catalogId`, Google Cloud `projectId`, `datasetId`, `targetDataset`, and `sourceFile`.
- **Table properties (`tableProperties`)** : Materialization `tableType` (`TABLE`, `VIEW`, `INCREMENTAL`, `OPERATION`, `EXTERNAL`, or `DDIC_ONLY` for SAP raw tables read from SAP DDIC that aren't replicated to BigQuery), `primaryKeys`, `uniqueKeys`, partitioning (`partitionColumn` and `partitionType`) and clustering (`clusterColumns`), BigLake and linked dataset metadata (`externalTable` and `linkedDataset` for `lakehouse_delta_share` and `analytics_hub`), `snapshotClone`, direct upstream `dependencies`, and SAP table DDIC metadata (`sap`, including `DD08L` and `DD05S` foreign keys).
- **Compiled SQL (`compiledQuery`)**: Top-level field storing the compiled SQL query for foundation and data product models.
- **Column schema (`columns`)** : Column `name`, BigQuery `dataType` (with `length`, `precision`, and `scale`), `mode` and `nullable`, `isPrimaryKey` and `isUniqueKey` flags, business `description`, `dateGrain`, `labels`, and SAP field DDIC attributes (`sap`, including `dataElement`, `domain`, `domainValues`, `checkTable`, `refTable`, `refField`, and `conversionExit`).

When compiling foundation or product models, `fetch` generates SQLX and
JavaScript files inside an ephemeral directory (`.cortex/.tmp_dist/build_<id>/`),
extracts the compiled Dataform graph, and deletes the temporary
directory automatically on exit unless you pass `--keep-temp`. After modifying
local `.js` definitions, re-run
`uv run cortex-metadata fetch -m MODULE_ID`
to refresh the cached schema and compiled SQL.

## Target resolution and disambiguation

Sub-commands that accept module and table targets (`fetch`, `list`, `show`,
`lineage`, `erd`, and `clear`) evaluate named flags and positional shortcuts in
the following order:

- **Named flags take highest precedence** : Passing `-m MODULE_ID` and `-t TABLE_NAME` binds the module and table explicitly.
- **Two positional arguments (`fetch`, `show`, `lineage`, and `erd` only)** : Passing `MODULE_ID TABLE_NAME` (for example, `uv run cortex-metadata show erp kna1`) binds `MODULE_ID` and `TABLE_NAME` in order. The `list` and `clear` sub-commands accept at most one positional argument; pass `-t` or `--table` to filter by table name alongside a module filter.
- **Single positional argument** :
  - If `-m` is already set, the positional argument resolves as `TABLE_NAME`.
  - Otherwise, if the argument matches a configured or cached `moduleId`, catalog `id`, or `dataSourceId`, it resolves as `MODULE_ID`.
  - If the argument doesn't match a module identifier but matches a cached table name, it resolves automatically as `TABLE_NAME` (for example, `uv run cortex-metadata show accounting_documents_header`).

When you query a table name without `-m` and that table exists in multiple
cached layers (for example, `kna1` in both `raw.sap_raw` and `foundations.erp`),
`show` and `lineage` print a disambiguation prompt listing the exact `-m`
commands to run. Similarly, passing a multi-table module to `show` without `-t`
lists its cached tables and prompts you to specify
`-t TABLE_NAME`.

## Sub-commands

`uv run cortex-metadata` provides sub-commands for managing cached schemas,
tracing SQL lineage, and generating ER diagrams.

### `fetch`

Extracts BigQuery table schemas, compiles Dataform models in
an ephemeral workspace, and writes resolved YAML schemas to `.cortex/cache`. For
SAP raw datasets, `fetch` also enriches columns and foreign keys from SAP Data
Dictionary (DDIC) tables (`DD03L` required plus optional `DD02L`, `DD02T`,
`DD03T`, `DD04T`, `DD01L`, `DD07L`, `DD07T`, `DD08L`, and `DD05S`). If you omit
`MODULE_ID` (or pass `all`), `fetch` caches metadata for every module in
`config.yaml` using parallel worker threads for data products.

```bash
uv run cortex-metadata fetch [MODULE_ID] [TABLE_NAME] \
                             [-m MODULE_ID] [-t TABLE_NAME] \
                             [-cat {raw,foundations,products,catalogs}] \
                             [--discover-only] [--keep-temp] [--strict] [--no-ddic]
```

Replace the following:

- `MODULE_ID`: optional `moduleId`, catalog `id`, or `dataSourceId`, for example: `erp`, `sap_customers`, `sap_bdc_catalog`, or `sap_raw`.
- `TABLE_NAME`: optional table or view name to fetch individually, for example: `kna1`.

The following table describes the flags specific to `fetch`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Target module ID, catalog ID, or raw `dataSourceId`. Takes precedence over positional arguments. | All configured modules |
| `-t, --table, --table-name TABLE_NAME` | Specific table or model name to fetch. When `-m` is omitted, resolves the owning module from `.cortex/cache` if already cached, or falls back to the first configured foundation; pass `-m` explicitly for uncached product or catalog tables. | All tables in target |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Accepted for CLI consistency across sub-commands, but ignored by `fetch`; the metadata layer is always inferred from `config.yaml`. | Inferred from `config.yaml` |
| `--discover-only` | List available tables (or print a single table's columns when `-t` is set) directly from BigQuery without writing YAML files to the local cache. Direct table listing applies only to `raw` dataset targets (not foundation or product modules). In a full workspace fetch, foundation and product compilation is skipped while configured catalogs are still extracted (and targeting a catalog ID directly ignores `--discover-only`). | `false` |
| `--keep-temp` | Preserve the temporary Dataform build directory (`.cortex/.tmp_dist/build_<id>/`) on disk for troubleshooting. | `false` |
| `--strict` | Exit with a non-zero status code if any data product model fails its BigQuery dry run, if no models are found for a targeted product module, or if SAP DDIC metadata is missing for a targeted SAP raw table. | `false` |
| `--no-ddic` | Skip SAP Data Dictionary (DDIC) enrichment when fetching SAP raw tables. | `false` |
|---|---|---|

### `list`

Lists all table and view schemas stored in the workspace cache, grouped by
category (`raw`, `foundations`, `products`, and `catalogs`).

```bash
uv run cortex-metadata list [MODULE_ID] \
                            [-m MODULE_ID] [-t TABLE_NAME] \
                            [-cat {raw,foundations,products,catalogs}]
```

Replace the following:

- `MODULE_ID`: optional module ID, catalog ID, or `dataSourceId` filter, for example: `erp`.
- `TABLE_NAME`: optional table name filter across cached modules, for example: `kna1`.

The following table describes the filter flags for `list`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Filter cached tables by module ID, catalog ID, or `dataSourceId`. | None |
| `-t, --table, --table-name TABLE_NAME` | Filter by table name across all cached categories and modules. | None |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Restrict listing to a single metadata layer. | All categories |
|---|---|---|

### `show`

Displays detailed column names, data types, modes, primary and unique key flags,
partitioning and clustering properties, SAP DDIC attributes, and descriptions
for a cached table. When a requested table is missing from the local cache,
`show` automatically fetches it from the configured source unless you pass
`--no-auto-fetch`.

```bash
uv run cortex-metadata show [MODULE_ID] [TABLE_NAME] \
                            [-m MODULE_ID] [-t TABLE_NAME] \
                            [-cat {raw,foundations,products,catalogs}] \
                            [-f {yaml,summary,markdown,md,json}] \
                            [--no-auto-fetch | --no-fetch]
```

Replace the following:

- `MODULE_ID`: module ID, catalog ID, `dataSourceId`, or single-argument table name, for example: `erp` or `accounting_documents_header`.
- `TABLE_NAME`: table or view name to inspect (optional if the module exposes a single table or if `TABLE_NAME` is unique in `.cortex/cache`), for example: `kna1`.

The following table describes the target, formatting, and cache flags for
`show`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Target module ID, catalog ID, or `dataSourceId` (optional when `TABLE_NAME` is unique in the cache). | Auto-resolved |
| `-t, --table, --table-name TABLE_NAME` | Target table or view name to inspect. | Auto-resolved for single-table modules |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Optional metadata category qualifier when disambiguating identically named tables. | None |
| `-f, --format {yaml,summary,markdown,md,json}` | Output format: `yaml` (structured for coding agents), `summary`, `markdown`, or `md` (Markdown table with SAP DDIC details), or `json`. | `yaml` |
| `--no-auto-fetch, --no-fetch` | Fail immediately instead of fetching metadata from BigQuery when the requested table isn't in the local cache. | `false` |
|---|---|---|

### `search`

Searches cached table names, descriptions, tags, labels, and column metadata for
a case-insensitive substring across all four cache layers.

```bash
uv run cortex-metadata search QUERY \
                              [-m MODULE_ID] [-t TABLE_NAME] \
                              [-cat {raw,foundations,products,catalogs}] \
                              [--columns-only] [--tables-only] \
                              [-f {yaml,summary,markdown,md,json}] [-l LIMIT]
```

Replace the following:

- `QUERY`: required case-insensitive search term, for example: `"local currency"` or `netwr`.
- `MODULE_ID`: optional module ID, catalog ID, or `dataSourceId` filter, for example: `erp`.
- `TABLE_NAME`: optional table name substring filter, for example: `sales`.
- `LIMIT`: maximum number of matching tables to return, for example: `50`.

The following table describes the scope, formatting, and pagination flags for
`search`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Scope search results to a specific module ID, catalog ID, or `dataSourceId`. | All cached modules |
| `-t, --table, --table-name TABLE_NAME` | Scope search results to table names containing the specified substring. | All cached tables |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Scope search results to a single metadata layer. | All categories |
| `--columns-only` | Search within column names and column descriptions only. | `false` |
| `--tables-only` | Search within table names, descriptions, Dataform tags, and BigQuery labels only. | `false` |
| `-f, --format {yaml,summary,markdown,md,json}` | Output display format. | `yaml` |
| `-l, --limit LIMIT` | Maximum number of matching tables returned. | `50` |
|---|---|---|

### `lineage`

Traces upstream table-level DAG dependencies, downstream cached consumers, and
hop-by-hop column-level SQL transformation formulas across cached data products,
foundations, raw tables, and external catalogs.

Using `sqlglot` AST analysis, `lineage` isolates declarative SQL statements
(`MERGE`, `CREATE TABLE AS SELECT`, and `INSERT INTO ... SELECT`) from
procedural BigQuery scripts (`BEGIN ... EXCEPTION ... END`). It
then classifies column expressions into operations such as `Direct Passthrough`,
`Currency Scaling` (SAP `TCURX` and `CURRFIX`), `Hash / Masking`,
`Window Function`, `Aggregation`, `Type Cast`, `Conditional Logic`,
`String Function`, and `Calculation`. Omitting `TABLE_NAME` renders the combined
lineage graph across all cached tables in `MODULE_ID`.

```bash
uv run cortex-metadata lineage [MODULE_ID] [TABLE_NAME] \
                               [-m MODULE_ID] [-t TABLE_NAME] \
                               [-cat {raw,foundations,products,catalogs}] \
                               [-col COLUMN_NAME ...] \
                               [-f {tree,summary,markdown,md,mermaid,yaml,json}]
```

Replace the following:

- `MODULE_ID`: module ID, catalog ID, `dataSourceId`, or single-argument table name, for example: `sap_sales_documents`.
- `TABLE_NAME`: optional table or view name to trace (omit to trace all cached tables in `MODULE_ID`), for example: `sales_document_items`.
- `COLUMN_NAME`: one or more space-separated or comma-separated column names to trace at the field level, for example: `client_mandt`.

The following table describes the target, column, and rendering flags for
`lineage`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Target module ID, catalog ID, or `dataSourceId`. | Auto-resolved when `TABLE_NAME` is unique |
| `-t, --table, --table-name TABLE_NAME` | Target table or view name (omit to generate module-wide lineage). | All tables in module |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Optional metadata category qualifier. | None |
| `-col, --column, --columns COLUMN_NAME ...` | Specific column name or names (space-separated or comma-separated) to trace back to upstream foundation, catalog, or raw fields. Requires single-table resolution; pass `-t` when targeting a multi-table module (otherwise module-wide table lineage is rendered and `--column` is ignored). | None (table-level DAG) |
| `-f, --format {tree,summary,markdown,md,mermaid,yaml,json}` | Output format: visual hierarchy (`tree`, `summary`, `markdown`, or `md`), flowchart diagram (`mermaid`), `yaml`, or `json`. | `tree` |
|---|---|---|

### `erd`

Generates an Entity-Relationship (ER) diagram---including primary keys, join
predicates, inferred cardinalities (`1:1`, `1:N`, `N:1`, `N:M`), table grain,
and fan-out warnings---from cached schemas, SAP DDIC foreign keys (`DD08L` and
`DD05S`), and SQL AST join analysis. When `MODULE_ID` is specified and the
target isn't in `.cortex/cache`, `erd` fetches it automatically unless you pass
`--no-auto-fetch`. Passing only an uncached table name without `MODULE_ID` fails
instead of auto-fetching.

```bash
uv run cortex-metadata erd [MODULE_ID] [TABLE_NAME] \
                           [-m MODULE_ID] [-t TABLE_NAME] \
                           [-cat {raw,foundations,products,catalogs}] \
                           [--tables TABLE_LIST ...] [--all-columns] \
                           [-f {mermaid,markdown,md,json,dot}] [-o OUTPUT_FILE] \
                           [--no-auto-fetch]
```

Replace the following:

- `MODULE_ID`: module ID, catalog ID, `dataSourceId`, or unique cached table name, for example: `sap_sales_documents`.
- `TABLE_NAME`: optional specific table name within the module, for example: `sales_document_items`.
- `TABLE_LIST`: space-separated or comma-separated foundation, raw, or catalog tables to relate using joins observed across cached data products, for example: `vbak vbap`.
- `OUTPUT_FILE`: optional path where the rendered diagram is written, for example: `erd.md`.

The following table describes the flags specific to `erd`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Target module ID, catalog ID, or `dataSourceId`. | Auto-resolved when `TABLE_NAME` is unique |
| `-t, --table, --table-name TABLE_NAME` | Specific table name within the target module. | All cached tables in module |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Optional metadata category qualifier. | None |
| `--tables TABLE_LIST ...` | Relate specific foundation, raw, or catalog tables using join predicates mined from cached data products. Requires `MODULE_ID` (positional or using `-m`). | None |
| `--all-columns` | Include every column in each entity box instead of only primary key and join columns. | `false` |
| `-f, --format {mermaid,markdown,md,json,dot}` | Output format: `mermaid` (`erDiagram`), `markdown` or `md` (diagram plus relationship table), `json`, or `dot` (Graphviz). | `mermaid` |
| `-o, --output OUTPUT_FILE` | Write the rendered diagram to the specified path instead of standard output. | Standard output |
| `--no-auto-fetch` | Don't auto-fetch missing targets from source when absent from `.cortex/cache`. Auto-fetch requires `MODULE_ID`. | `false` |
|---|---|---|

### `clear`

Removes cached metadata files from `.cortex/cache` for the entire workspace or a
targeted module, category, or table.

```bash
uv run cortex-metadata clear [MODULE_ID] \
                             [-m MODULE_ID] [-t TABLE_NAME] \
                             [-cat {raw,foundations,products,catalogs}]
```

Replace the following:

- `MODULE_ID`: optional module ID, catalog ID, or `dataSourceId` to clear selectively, for example: `erp`.
- `TABLE_NAME`: optional table name to clear selectively, for example: `kna1`.

The following table describes the filter flags for `clear`:

| Flag | Description | Default |
| `-m, --module-id, --module MODULE_ID` | Purge cached schemas for a specific module ID, catalog ID, or `dataSourceId`. | All cached modules |
| `-t, --table, --table-name TABLE_NAME` | Purge a single cached table YAML file. | All cached tables in scope |
| `-cat, --category, --type {raw,foundations,products,catalogs}` | Purge cached schemas for an entire layer (`raw`, `foundations`, `products`, or `catalogs`). | All categories |
|---|---|---|

## Examples

Cache all configured workspace schemas with strict dry-run and SAP DDIC checks:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

uv run cortex-metadata fetch --config $CORTEX_CONFIG_FILE --strict
```

Inspect a cached table schema in Markdown format using single-argument table
auto-resolution:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

uv run cortex-metadata show accounting_documents_header \
    --config $CORTEX_CONFIG_FILE \
    -f summary
```

Search column names and descriptions across all cached modules:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

uv run cortex-metadata search "company code" \
    --config $CORTEX_CONFIG_FILE \
    --columns-only \
    -f summary
```

Generate a module-wide lineage diagram or trace multiple columns at the field
level in Mermaid format:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

# Module-wide table lineage flowchart
uv run cortex-metadata lineage \
    --config $CORTEX_CONFIG_FILE \
    -m sap_accounting_documents \
    -f mermaid

# Multi-column transformation lineage
uv run cortex-metadata lineage \
    --config $CORTEX_CONFIG_FILE \
    -m sap_sales_documents \
    -t sales_document_items \
    --column client_mandt net_value_of_the_sales_document_item_in_document_currency_netwr \
    -f mermaid
```

Generate a Markdown ER diagram and join cardinality summary for a data product:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

uv run cortex-metadata erd \
    --config $CORTEX_CONFIG_FILE \
    -m sap_sales_documents \
    -f markdown \
    -o erd.md
```

Purge cached raw schemas before re-fetching updated DDIC metadata:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

uv run cortex-metadata clear \
    --config $CORTEX_CONFIG_FILE \
    -cat raw
```

## What's next

- Use cached metadata in [Build data products with agent skills](https://docs.cloud.google.com/cortex/docs/agentic-skills-for-data-product-building.md.txt).
- Configure SAP Data Dictionary tables in [SAP ERP integration](https://docs.cloud.google.com/cortex/docs/source-system-integration/sap-erp.md.txt#sap-ddic-metadata-tables).
- Inspect offline SQL compilation graphs with [`uv run cortex-compile`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-compile.md.txt).