Skip to content

feat(cli): support 4-part Lakehouse Catalog targets in dataform run - #2445

Draft
Pawbag123 wants to merge 31 commits into
mainfrom
fix-cli-lakehouse-4part-targets
Draft

Pawbag123 wants to merge 31 commits into
mainfrom
fix-cli-lakehouse-4part-targets

Conversation

@Pawbag123

@Pawbag123 Pawbag123 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds @dataform/cli execution support (dataform run / dfapi.build / dfapi.run) for 4-part BigQuery Lakehouse Catalog (BigLake Iceberg REST Catalog) table identifiers (project.catalog.namespace.table), building on the @dataform/core compilation and target normalization introduced in #2384.

Problem

In #2384, @dataform/core normalizes 4-part Lakehouse targets into dataform.Target by packing catalog and namespace into target.schema ("${catalog}.${namespace}"), which interpolates as `project.catalog.namespace.table` in GoogleSQL. However, executing these targets in @dataform/cli failed across several stages:

  1. Lazy dataset creation (Runner):
    • Runner.findMissingSchemas() listed standard BigQuery datasets via datasets.list and treated catalog.namespace as a missing dataset, wrapping tasks in CREATE SCHEMA IF NOT EXISTS \project.catalog.namespace`. Lakehouse namespaces are managed externally via BigLake REST APIs and reject CREATE SCHEMA` DDL.
    • Conversely, in a project containing only Lakehouse targets, defaultDataset might not exist yet when an incremental Lakehouse table needs it for onSchemaChange schema inspection, while emitting unconditional CREATE SCHEMA IF NOT EXISTS on every run fails for least-privilege identities without bigquery.datasets.create when defaultDataset already exists.
  2. Incompatible-type DROP VIEW, incremental creation, and onSchemaChange (ExecutionSql):
    • publishTasks() could emit DROP VIEW IF EXISTS on type mismatch, whereas views are unsupported in Lakehouse namespaces.
    • Initial creation of incremental tables emitted CREATE OR REPLACE TABLE unconditionally instead of plain CREATE TABLE when not full-refreshing.
    • For incremental tables with onSchemaChange (FAIL, EXTEND, SYNCHRONIZE), buildIncrementalSchemaChangeTasks() attempted to create a stored procedure (df_osc_<id>) inside catalog.namespace and query 5-part project.catalog.namespace.INFORMATION_SCHEMA.COLUMNS, neither of which BigQuery supports for Lakehouse namespaces.
  3. Warehouse state, descriptions, table deletion, and lineage (BigQueryDbAdapter, Runner, & LineagePayloadBuilder):
    • Unified Iceberg / Lakehouse tables.get responses may omit lastModifiedTime, causing Long.fromString(metadata.lastModifiedTime) in BigQueryDbAdapter.table() to throw during state() resolution, and federated 404 responses may report code: 404 without a legacy errors array.
    • Post-execution BigQueryDbAdapter.setMetadata() (tables.patch) is rejected by BigQuery on 4-part Lakehouse Iceberg tables ("Connection is required for BigQuery tables for Apache Iceberg").
    • BigQueryDbAdapter.deleteTable() used the REST tables.delete endpoint, which BigQuery rejects on Lakehouse targets (HTTP 400: "Biglake resources cannot be modified in BigQuery."), instead of 4-part DROP TABLE IF EXISTS SQL.
    • LineagePayloadBuilder formatted all targets as 3-part BigQuery dataset names, causing Data Lineage to misparse 4-part project.catalog.namespace.table targets.
  4. CLI documentation: --actions, --output-actions, and cli/README.md did not document 4-part Lakehouse target behavior and requirements.

Changes

  • core/targets.ts & core/session.ts: Export shared isCatalogSchema() and isLakehouseTarget() helpers from @dataform/core and reuse isCatalogSchema() in Session.finalizeSchema().
  • cli/api/commands/run.ts:
    • Exclude catalog.namespace targets from CREATE SCHEMA in Runner, while registering defaultDataset in defaultProject (with databaseSuffix/schemaSuffix, via shared ExecutionSql.lakehouseScratchDataset()) for incremental Lakehouse actions so missing scratch datasets are created once via CREATE SCHEMA IF NOT EXISTS and existing ones do not require bigquery.datasets.create.
    • Forward IBigQueryExecutionOptions (location, jobPrefix, labels, actionRetryLimit, reservation) to dbadapter.setMetadata().
  • cli/api/dbadapters/execution_sql.ts:
    • Skip incompatible-type dropIfExists (DROP VIEW IF EXISTS) on 4-part targets in publishTasks().
    • Emit plain CREATE TABLE (without OR REPLACE) for incremental Lakehouse tables unless runConfig.fullRefresh && !table.protected.
    • Reject missing tableMetadata.fields across all incremental onSchemaChange modes (including IGNORE) with an explicit error instead of generating malformed DML.
    • Add buildLakehouseIncrementalSchemaChangeTasks(), lakehouseScratchDataset(), and resolveScratchTarget() for incremental Lakehouse tables with onSchemaChange (FAIL, EXTEND, SYNCHRONIZE): execute a BEGIN ... EXCEPTION WHEN ERROR ... END script block without stored procedures, populate dataform_columns from tableMetadata.fields, inspect the incoming query schema via a short-lived empty LIMIT 0 table (with a 1-day expiration_timestamp) in defaultProject.defaultDataset (with databaseSuffix/schemaSuffix, throwing if either defaultProject or defaultDataset is unset), and drop the scratch table in both normal and error paths.
  • cli/api/dbadapters/index.ts, cli/api/dbadapters/bigquery.ts, & cli/api/commands/jit/rpc.ts:
    • Define IBigQueryExecutionOptions in cli/api/dbadapters/index.ts (re-exported from bigquery.ts) and reuse it across IDbClient and IDbAdapter.
    • Default lastUpdatedMillis to Long.ZERO when metadata.lastModifiedTime is absent, guard metadata.schema?.fields, and treat e?.code === 404 as not-found in getMetadata().
    • Apply table and top-level column (path.length === 1) descriptions on 4-part Lakehouse tables via ALTER TABLE SQL statements in setMetadata() (skipping tables.patch and nested STRUCT field descriptions), forwarding execution options.
    • Execute 4-part DROP TABLE IF EXISTS via this.execute() in deleteTable() for Lakehouse targets, requiring target.database and forwarding execution options from the JiT DeleteTable RPC.
  • cli/api/lineage/payload_builder.ts & docs/lineage.md: Omit 4-part Lakehouse targets from OpenLineage inputs, and omit inputs/outputs when the action's own target is a Lakehouse target.
  • cli/common_options.ts, cli/commands/compile_options.ts, & cli/README.md: Document 4-part database.catalog.namespace.name targets in --actions and --output-actions and document Lakehouse execution requirements under dataform run.

Testing

  • cli/api/dbadapters/bigquery_test.ts, cli/api/commands/jit/rpc_test.ts, & cli/tests/jit/jit_run_test.ts: Unit tests for table() (dotted datasetId, missing lastModifiedTime, 404 handling), setMetadata() applying table/top-level column descriptions via ALTER TABLE SQL with location, and deleteTable() executing 4-part DROP TABLE IF EXISTS with forwarded execution options (and rejecting missing target.database).
  • cli/api/execution_sql_test.ts & cli/api/goldens/lakehouse_on_schema_change_extend.sql: Unit and golden SQL tests for 4-part table DDL (skipping DROP VIEW), incremental plain CREATE TABLE vs CREATE OR REPLACE TABLE (fullRefresh / protected), INSERT / MERGE / INSERT_OVERWRITE DML, missing tableMetadata.fields across all onSchemaChange modes (IGNORE, FAIL, EXTEND, SYNCHRONIZE), cross-project scratch dataset resolution, incrementalPreOps/incrementalPostOps ordering, and operations.
  • cli/api/commands/run_test.ts & cli/api/commands/prune_test.ts: Unit tests verifying Runner skips CREATE SCHEMA on catalog.namespace, creates missing defaultDataset (with suffixes and defaultLocation) for incremental Lakehouse actions while skipping CREATE SCHEMA when defaultDataset already exists, forwards exact IBigQueryExecutionOptions to setMetadata(), resolves warehouse state via build(), and supports 4-part targets in --actions pruning.
  • cli/api/lineage/payload_builder_test.ts: Unit tests verifying OpenLineage omits Lakehouse targets from inputs and outputs.
  • Verified ./scripts/lint and ./scripts/run_tests pass, and verified end-to-end against a live BigLake Iceberg lakehouse catalog in BigQuery (details posted in PR comments).

@google-cla

google-cla Bot commented Nov 13, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@Ford544 Ford544 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could really use a e2e integration test for this (e.g. in cli/index_run_e2e_test.ts or a new adjacent file) in addition to the unit tests, to make sure everything behaves as expected against real BigQuery.

Comment thread cli/api/dbadapters/execution_sql.ts Outdated
"When defining an incremental Lakehouse table, 'defaultDataset' must be defined in workflow_settings.yaml.",
);
}
const scratchSchema = this.project?.schemaSuffix

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This schema may not exist (for example if a new project only has Lakehouse targets). Consider registering the default schema for creation if there is an incremental Lakehouse target with onSchemaChange != IGNORE; or preceding the emitted CREATE OR REPLACE TABLE with CREATE SCHEMA IF NOT EXISTS

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. Additionally, this dataset has to be in the same location as the Lakehouse catalog, otherwise the CREATE TABLE ... AS SELECT reading from the catalog won't run. If it's going to be created automatically, it's worth using defaultLocation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in fbb8d2d — prepended CREATE SCHEMA IF NOT EXISTS (with OPTIONS(location=...) when defaultLocation is configured) before the BEGIN ... END block.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding this. One problem with running it on every run: BigQuery checks the bigquery.datasets.create permission before it checks whether the dataset exists. You can see it with any dataset that exists but that you can't create (a dry run is enough):

CREATE SCHEMA IF NOT EXISTS `bigquery-public-data.samples`;
-- Access Denied: Project bigquery-public-data: User does not have
-- bigquery.datasets.create permission in project bigquery-public-data.

So an identity that may create tables in defaultDataset, but may not create datasets in the project, fails on every incremental run with onSchemaChange, although the dataset exists. That is a common setup (roles/bigquery.dataEditor granted on the dataset only). The README note says the permission is needed only "if missing".

Runner already avoids this for regular targets: findMissingSchemas() lists the datasets once, only a missing dataset gets the wrapWithCreateSchemaIfNotExists() wrapper, and executeTaskCreatingMissingSchema() lets one job at a time create it. The new statement bypasses all of that and runs in every such action, in parallel.

Two ways to fix it:

  1. Preferred: @Ford544's first option. Let Runner treat the scratch dataset as a dataset to create for incremental Lakehouse actions (action.tableType and the target are enough to find them). Then nothing runs when the dataset exists, and a least-privilege identity doesn't produce a denied call on every run.

  2. Smaller: keep the statement, but in its own block that tolerates a failure:

    BEGIN
      CREATE SCHEMA IF NOT EXISTS `project.dataset` OPTIONS(location = '...');
    EXCEPTION WHEN ERROR THEN
      -- The dataset may exist although the caller can't create datasets.
    END;

    If the dataset is really missing, the next statement fails with "Not found: Dataset ...", which is clear enough.

Either way, please add a test for the case "the dataset exists".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 569fe0e (plus 742172d and 77b3a98) — went with option 1: removed CREATE SCHEMA IF NOT EXISTS from ExecutionSql.buildLakehouseIncrementalSchemaChangeTasks() and registered defaultDataset (with databaseSuffix/schemaSuffix, via shared ExecutionSql.lakehouseScratchDataset()) in Runner.actionDatasetToCreate() for incremental Lakehouse actions. Added unit tests in run_test.ts covering both when defaultDataset is missing and when it already exists, and clarified the behavior in cli/README.md.


public async setMetadata(action: dataform.IExecutionAction): Promise<void> {
const { target, actionDescriptor } = action;
if (isLakehouseTarget(target)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to set metadata for Lakehouse tables by running SQL directly instead of skipping it outright (like with delete)?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 to setting descriptions via SQL inside setMetadata() in this PR so table and top-level column descriptions work consistently in dataform run (after task success, skipped on --dry-run).

Note that BigQuery does not allow mixing SET OPTIONS and ALTER COLUMN in a single ALTER TABLE statement, so it needs up to two statements (with properly escaped string literals, e.g. via CompilationSql.sqlString, and forwarding the run's execution location if set):

ALTER TABLE `project.catalog.namespace.table` SET OPTIONS(description = '...');
ALTER TABLE `project.catalog.namespace.table`
  ALTER COLUMN IF EXISTS `col_a` SET OPTIONS(description = '...'),
  ALTER COLUMN IF EXISTS `col_b` SET OPTIONS(description = '...');

(ALTER COLUMN only supports top-level columns, i.e. path.length === 1.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 0c41020 — BigQueryDbAdapter.setMetadata() now applies table and top-level column (path.length === 1) descriptions via separate ALTER TABLE ... SET OPTIONS and ALTER TABLE ... ALTER COLUMN IF EXISTS ... SET OPTIONS SQL statements (forwarding execution options / location), and the duplicate !isLakehouseTarget check in Runner.executeAction() has been removed.

@Ford544

Ford544 commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

On a somewhat-related note, if the defaultDatabase is not defined in either the target or workflow_settings.yaml, it will result in a three-part identifier (catalog.namespace.table) that BigQuery will interpret as project.schema.table.

This should probably be caught at compile step ( in /core) so it's not directly relevant for this PR, but might be a good idea for a follow-up.

Comment thread cli/api/dbadapters/execution_sql.ts Resolved
Comment thread cli/api/dbadapters/execution_sql.ts Resolved
Comment thread cli/api/commands/run.ts Resolved
Comment thread cli/api/dbadapters/bigquery.ts Resolved
Comment thread cli/api/commands/run.ts Resolved
Comment thread cli/api/utils/lakehouse.ts Resolved
Comment thread cli/api/dbadapters/execution_sql.ts Outdated
"When defining an incremental Lakehouse table, 'defaultDataset' must be defined in workflow_settings.yaml.",
);
}
const scratchSchema = this.project?.schemaSuffix

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. Additionally, this dataset has to be in the same location as the Lakehouse catalog, otherwise the CREATE TABLE ... AS SELECT reading from the catalog won't run. If it's going to be created automatically, it's worth using defaultLocation.

@SergikL SergikL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for putting this together! Overall direction looks solid. +1 to the existing comments on the scratch dataset (project, existence, location) and verifying against a live Lakehouse catalog.

A couple of additional items that aren't in the current diff yet and would be good to address directly in this PR:

  1. Lineage (cli/api/lineage/payload_builder.ts): When --emit-lineage (or lineage.enabled in workflow_settings.yaml) is enabled, LineagePayloadBuilder currently formats every target as a 3-part BigQuery dataset name (<project>.<schema>.<name>). For a 4-part Lakehouse target (project.catalog.namespace.table), Data Lineage parses that as table namespace.table in project project.catalog. Could we skip Lakehouse targets in inputs, and omit inputs/outputs when the action's output target itself is a Lakehouse target (plus a unit test in payload_builder_test.ts and a brief note in docs/lineage.md)?
  2. CLI documentation (cli/README.md): Could we add a short note/section covering Lakehouse targets in dataform run — specifically that the catalog/namespace must already exist, that incremental tables with onSchemaChange require both defaultProject and defaultDataset in the same location as the catalog (with table create/drop permissions on defaultDataset), and how table/column descriptions are applied?


const baseTableType = this.baseTableType(table.enumType);
if (tableMetadata && tableMetadata.type !== baseTableType) {
if (!isLakehouseTarget(table.target) && tableMetadata && tableMetadata.type !== baseTableType) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right below at lines 148–150: for a Lakehouse incremental table, whenever tables.get reports no existing metadata (tableMetadata is null), !shouldWriteIncrementally(...) falls through to createOrReplace(table) — even when protected: true. If tables.get ever returns 404 for a Lakehouse table that actually exists in the catalog, CREATE OR REPLACE TABLE would silently overwrite the table and its history.

Could we emit plain CREATE TABLE (without OR REPLACE) for Lakehouse incremental tables unless runConfig.fullRefresh && !table.protected? That way, if the table already exists, BigQuery fails safely with Already Exists instead of replacing it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in c5badcd — incremental Lakehouse tables now emit plain CREATE TABLE unless runConfig.fullRefresh && !table.protected.

Comment thread cli/api/dbadapters/execution_sql.ts Outdated
) {
const uniqueId = this.uniqueIdGenerator();
const tempTableName = `${table.target.name}_df_temp_${uniqueId}_empty`;
const emptyTempTableTarget = this.resolveScratchTarget(table.target, tempTableName);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a CLI run is cancelled or times out between CREATE OR REPLACE TABLE of the empty scratch table and DROP TABLE IF EXISTS, <table>_df_temp_<id>_empty will remain in defaultDataset indefinitely. Could we add a 1-day expiration option on the Lakehouse scratch table so orphaned scratch tables clean themselves up automatically?

OPTIONS(expiration_timestamp = TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 1 DAY))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 1e2c0d4 — added OPTIONS(expiration_timestamp = TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)) to the Lakehouse scratch table DDL.

Comment thread cli/api/commands/run.ts Outdated
!!action.target &&
!!action.target.schema &&
// Lakehouse catalog.namespace targets are managed externally via BigLake REST APIs
// and cannot be listed via datasets.list or created via CREATE SCHEMA.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit on the comment: datasets.list actually can return Lakehouse namespaces (with id: "catalog.namespace" and type BIGLAKE_ICEBERG), though skipping here is still right because CREATE SCHEMA cannot create a Lakehouse namespace. Maybe: // Lakehouse catalog.namespace targets cannot be created via CREATE SCHEMA; they must exist before the run.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 5d4c6e4 — updated the comment as suggested.

…form/core

Move isCatalogSchema() and isLakehouseTarget() from cli/api/utils/lakehouse.ts to core/targets.ts and reuse isCatalogSchema() in Session.finalizeSchema().
Addresses #2445 (comment)
…e incremental tables

Avoid overwriting an existing Lakehouse table if tables.get ever reports no metadata; only emit OR REPLACE when fullRefresh is set and the table is not protected.
Addresses #2445 (comment)
… on schema change

Check !tableMetadata?.fields?.length (accounting for protobufjs empty repeated field initialization) instead of defaulting to [], and document that existingColumns is a build-time snapshot.

Addresses:
- #2445 (comment)
- #2445 (comment)
…re defaultDatabase

Always create the temporary schema-inspection table in defaultDatabase (with databaseSuffix) instead of the catalog's project, and throw when defaultProject is unset.
Addresses:
- #2445 (comment)
- #2445 (comment)
…house onSchemaChange

Prepend CREATE SCHEMA IF NOT EXISTS (using project defaultLocation when configured) before the Lakehouse schema-change block so projects with only Lakehouse targets have the scratch dataset created in the catalog's region.
Addresses:
- #2445 (comment)
- #2445 (comment)
…scratch tables

Ensure orphaned scratch tables in defaultDataset are automatically cleaned up if a run times out or is cancelled before DROP TABLE IF EXISTS executes.
Addresses #2445 (comment)
…r Lakehouse targets

Throw explicitly when target.database is missing instead of falling back to credentials.projectId, avoiding dropping a table in the wrong project when defaultProject differs from credentials.
Addresses #2445 (comment)
…BLE SQL

- Execute separate ALTER TABLE SET OPTIONS and ALTER COLUMN IF EXISTS statements in BigQueryDbAdapter.setMetadata() for 4-part Lakehouse targets, forwarding execution location.
- Keep Lakehouse metadata handling solely in BigQueryDbAdapter instead of duplicating the check in Runner.executeAction().

Addresses:
- #2445 (comment)
- #2445 (comment)
- #2445 (comment)
- #2445 (comment)
…unner

- Remove redundant isLakehouseTarget() guard in missingSchemaToCreate() since findMissingSchemas() already excludes catalog schemas.
- Clarify that datasets.list can list BIGLAKE_ICEBERG namespaces, while CREATE SCHEMA cannot create them.
Addresses:
- #2445 (comment)
- #2445 (comment)
… and outputs

Data Lineage parses bigquery namespace dataset names as 3-part <project>.<dataset>.<table> identifiers. Filter out 4-part Lakehouse targets from inputs and omit inputs/outputs when the action target itself is a Lakehouse target.
Addresses #2445 (review)
…E.md

Document catalog/namespace pre-existence, defaultProject/defaultDataset location and permission requirements for onSchemaChange, and SQL description updates.

Addresses #2445 (review)
@Pawbag123

Copy link
Copy Markdown
Contributor Author

Thank you for the review @SergikL! Addressed both additional items as well:

  1. Lineage (cli/api/lineage/payload_builder.ts, payload_builder_test.ts, docs/lineage.md): Done in cc8dbce — Lakehouse targets are filtered out from inputs, and inputs/outputs are omitted when the action's own target is a Lakehouse target.
  2. CLI documentation (cli/README.md): Done in b171e5a — added a note under dataform run covering catalog/namespace pre-existence, defaultProject + defaultDataset location/permission requirements for onSchemaChange, and SQL-based table/column descriptions.

Comment thread cli/api/dbadapters/execution_sql.ts Outdated
const baseDefaultSchema = this.project?.defaultSchema;
if (!baseDefaultSchema) {
throw new Error(
"When defining an incremental Lakehouse table, 'defaultDataset' must be defined in workflow_settings.yaml.",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: unlike the error message above, this one does not clarify that this affects onSchemaChange.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in f329dca — updated the missing defaultDataset error message in resolveScratchTarget() to specify with onSchemaChange.

Comment thread cli/api/dbadapters/index.ts Outdated
setMetadata(
action: dataform.IExecutionAction,
options?: {
bigquery?: {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I think we can reuse the IBigQueryExecutionOptions interface here instead of typing out all the properties.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 960eb00 — moved IBigQueryExecutionOptions to cli/api/dbadapters/index.ts (re-exported from bigquery.ts) and reused it across IDbClient and IDbAdapter.

@mbiernacik mbiernacik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing all the comments, the fixes look good!

One thing still open is @Ford544's request for an e2e test against real BigQuery. Given how much more SQL is now generated for Lakehouse targets, it would be even more valuable now.

@SergikL SergikL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround. I went through the new commits: the earlier comments are addressed, and the generated SQL for regular 3-part targets is unchanged (no golden file changed). Three notes are inline (including a dataset-permission blocker in the scratch-dataset thread). Three more points:

  1. A run against a real catalog is still missing. The unit tests compare the generated text, and nothing executes these scripts. Before merge, could you run the branch once against a Lakehouse catalog and post the commands and results here? Suggested cases:

    • a table, run twice
    • an incremental table: first run, second run without uniqueKey, second run with uniqueKey
    • onSchemaChange: EXTEND with a new column, and SYNCHRONIZE with a removed column (until #2320 lands, expect the behaviour described there: the new column stays empty in that run, and the first run after a removal fails)
    • table, column and nested-field descriptions
    • a catalog in a single region, with and without defaultLocation
    • defaultDataset missing; and defaultDataset existing, with an identity that can't create datasets
    • a namespace that doesn't exist

    @Ford544 @mbiernacik, would that be enough for this PR, with the automated e2e test as a follow-up once the test project has a catalog and a namespace?

  2. Overlap with #2320. That PR rewrites the same code: the DML moves into the schema-change body, the fall-through in publishTasks() goes away, and the incremental pre- and post-operations are passed into the body instead of being added in publishTasks(). The Lakehouse path here relies on the fall-through. Whichever PR lands second has to adapt the Lakehouse branch, and because the new parameters in #2320 have default values, a call that forgets the pre- and post-operations still compiles. Could you add a Lakehouse test with onSchemaChange plus incremental pre- and post-operations (ideally a golden file, like the 3-part ones) that checks the order and that there is exactly one DML statement? @apilaskowski, which of the two should land first?

  3. The PR description is out of date. It still says that descriptions are skipped and that deleteTable() falls back to the credentials' project, and it names cli/api/utils/lakehouse.ts. It becomes the squash commit message, so please refresh it before marking the PR ready.

// Fall through to run the static DML after the procedure alters the schema
case dataform.OnSchemaChange.IGNORE:
const columns = tableMetadata?.fields.map((f) => f.name) || [];
const columns = tableMetadata?.fields?.map((f) => f.name) || [];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new "missing schema fields" check covers FAIL, EXTEND and SYNCHRONIZE, but not IGNORE, which is the default. With an empty fields list this line builds an invalid statement (insert into ... () select from ..., or a merge with an empty update set and insert () values ()), and BigQuery answers with a syntax error instead of the clear message.

Could the check move above the switch for Lakehouse targets, so that all four modes fail the same way? Plus one unit test for IGNORE.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in b67d865 — moved the !tableMetadata?.fields?.length check above switch (onSchemaChange) in publishTasks() and expanded the unit test in execution_sql_test.ts to cover all four OnSchemaChange modes including IGNORE.

Comment on lines +399 to +401
await this.execute(
`drop table if exists \`${target.database}.${target.schema}.${target.name}\``,
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This DROP TABLE runs without the run's execution options, so the job doesn't get defaultLocation (or the labels and the reservation). It then uses the location from the credentials file, if one is set there. For a catalog in a single region and location: "US" in the credentials, the job fails with "Not found: Dataset ... was not found in location US".

setMetadata() now takes the options for the same reason. Could deleteTable() take the same optional options and pass them to execute()? handleDbRequest() in cli/api/commands/jit/rpc.ts already receives them and passes only dryRun to handleDeleteTable().

Low priority: only JiT code that calls deleteTable gets here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in ac496e7 — added optional options?: { bigquery?: IBigQueryExecutionOptions } to deleteTable(), forwarded full options from handleDbRequest() to handleDeleteTable() in cli/api/commands/jit/rpc.ts, and updated unit tests in bigquery_test.ts, rpc_test.ts, and jit_run_test.ts.

@apilaskowski

Copy link
Copy Markdown
Collaborator
  1. Overlap with Execute dynamic DML inside onSchemaChange procedure (#2307) #2320. That PR rewrites the same code: the DML moves into the schema-change body, the fall-through in publishTasks() goes away, and the incremental pre- and post-operations are passed into the body instead of being added in publishTasks(). The Lakehouse path here relies on the fall-through. Whichever PR lands second has to adapt the Lakehouse branch, and because the new parameters in Execute dynamic DML inside onSchemaChange procedure (#2307) #2320 have default values, a call that forgets the pre- and post-operations still compiles. Could you add a Lakehouse test with onSchemaChange plus incremental pre- and post-operations (ideally a golden file, like the 3-part ones) that checks the order and that there is exactly one DML statement? @apilaskowski, which of the two should land first?

I think we should land Execute dynamic DML inside onSchemaChange procedure (#2307) #2320 first, as it is waiting on review already, while this one is still missing some parts + is in draft.

@Ford544

Ford544 commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

@Ford544 @mbiernacik, would that be enough for this PR, with the automated e2e test as a follow-up once the test project has a catalog and a namespace?

In general I would prefer to include all relevant tests with the feature, so we can be sure all works correctly. In this case I think it would be acceptable to move them to the next PR as it shouldn't break anything that's functional today, but if we are going to wait for #2320 to land anyway then we are not in a hurry to merge this anyway.

);
});

test("delegates setMetadata() with execution options on 4-part Lakehouse tables with descriptions", async () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test title says execution options are forwarded but the check uses anything(), so it passes even if they are dropped. Can we assert the exact options object?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in a93f228 — configured explicit defaultLocation, defaultReservation, jobLabels, and runner BigQuery execution options (jobPrefix, labels, actionRetryLimit) in the test and asserted the exact captured options object with deep.equals.

`Cannot delete Lakehouse table "${target.schema}.${target.name}" without a target database (project).`,
);
}
await this.execute(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we know that REST tables.delete fails for Lakehouse tables? table() still uses REST with the same dataset ID. If it works we can drop this branch, which also removes the missing location and labels (mentioned by @SergikL ).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified this against a live BigLake Iceberg lakehouse catalog: while read-only tables.get succeeds with datasetId = "${catalog}.${namespace}", calling DELETE /bigquery/v2/projects/<project>/datasets/<catalog>.<namespace>/tables/<table> (tables.delete) fails (both when the table exists and when it doesn't) with:
HTTP 400: "Biglake resources cannot be modified in BigQuery."

I'll add the comment regarding it in a separate commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added comment in 508286a

…onSql

Register defaultDataset (with suffixes) in Runner.findMissingSchemas() for incremental Lakehouse actions instead of emitting CREATE SCHEMA IF NOT EXISTS on every run, so least-privilege callers without bigquery.datasets.create succeed when defaultDataset already exists.
Addresses #2445 (comment)
…es in IGNORE mode

Move the !tableMetadata?.fields?.length guard above the onSchemaChange switch in publishTasks() so IGNORE fails with the same clear error instead of generating invalid DML.
Addresses #2445 (comment)
…ouse targets

Pass execution options (location, labels, jobPrefix, reservation) from JiT DeleteTable RPC through to BigQueryDbAdapter.deleteTable() so single-region Lakehouse DROP TABLE jobs run in the configured location.
Addresses #2445 (comment)
…tal pre/post ops

Verify statement ordering (incrementalPreOps, schema-change block, single DML statement, incrementalPostOps) to guard the Lakehouse path across the #2320 rebase.
Addresses #2445 (review)
…ner and ExecutionSql

Extract ExecutionSql.lakehouseScratchDataset() and reuse it in Runner.actionDatasetToCreate() so both places resolve defaultProject/defaultDataset with suffixes identically.
…ouse tables

The Runner cannot see onSchemaChange on execution actions, so it checks defaultDataset for every incremental Lakehouse table and creates it only if it is missing.
Follow-up to #2445 (comment)
@Pawbag123

Copy link
Copy Markdown
Contributor Author

Thank you for the review @SergikL. Addressed all three points from #2445 (review):

  1. Live Lakehouse verification & E2E tests: Added the automated CLI E2E test suite in stacked PR test(cli): add end-to-end tests for 4-part BigQuery Lakehouse targets #2479 (cli/index_lakehouse_e2e_test.ts). Verified against a live single-region (us-central1) BigLake Iceberg lakehouse catalog — all 9/9 cases pass (//cli:index_lakehouse_e2e_test PASSED), covering all 7 requested scenarios plus operations (hasOutput: true) and a 3-part view reading a Lakehouse table via ref().
  2. Overlap with Execute dynamic DML inside onSchemaChange procedure (#2307) #2320: Added the golden SQL test with onSchemaChange: EXTEND and incrementalPreOps/incrementalPostOps in 63ad1022. Will rebase feat(cli): support 4-part Lakehouse Catalog targets in dataform run #2445 and test(cli): add end-to-end tests for 4-part BigQuery Lakehouse targets #2479 once Execute dynamic DML inside onSchemaChange procedure (#2307) #2320 lands.
  3. PR description: Updated to match the current implementation.

Comment thread cli/api/commands/run.ts
if (isCatalogSchema(action.target.schema)) {
return action.tableType === "incremental"
? this.executionSql.lakehouseScratchDataset()
: null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For an incremental Lakehouse table with the default onSchemaChange, the run still creates defaultDataset when it is missing, although nothing uses it. Is that acceptable, or can we limit it to tables that set onSchemaChange?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. The Runner cannot tell IGNORE apart today: ExecutionAction (protos/execution.proto) has no on_schema_change, it only exists on Table (core.proto). One option: set a flag at build time (e.g. requires_scratch_dataset, or copy on_schema_change) on the ExecutionAction when onSchemaChange != IGNORE, and gate this branch on it. That also avoids needing bigquery.datasets.create when defaultDataset is missing but unused.

@Ford544

Ford544 commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

Note that #2320 has been merged which will likely require changes to this PR.

@Pawbag123 Pawbag123 changed the title CLI: support 4-part Lakehouse Catalog targets in dataform run feat(cli): support 4-part Lakehouse Catalog targets in dataform run Nov 24, 2026
}
const alterColumns = (actionDescriptor?.columns || [])
.filter((col) => col.path?.length === 1 && col.description != null && col.description !== "")
.map(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filtering out empty/null descriptions means removing a description from the config never clears it on Lakehouse tables, unlike the tables.patch path for regular tables. Should we emit SET OPTIONS(description = NULL) for the table/columns in that case?

Comment thread cli/api/commands/run.ts
if (isCatalogSchema(action.target.schema)) {
return action.tableType === "incremental"
? this.executionSql.lakehouseScratchDataset()
: null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. The Runner cannot tell IGNORE apart today: ExecutionAction (protos/execution.proto) has no on_schema_change, it only exists on Table (core.proto). One option: set a flag at build time (e.g. requires_scratch_dataset, or copy on_schema_change) on the ExecutionAction when onSchemaChange != IGNORE, and gate this branch on it. That also avoids needing bigquery.datasets.create when defaultDataset is missing but unused.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants