Repository navigation
Execute dynamic DML inside onSchemaChange procedure (#2307) - #2320
Conversation
fd91cd7 to
60cbbbe
Compare
kolina
left a comment
There was a problem hiding this comment.
I haven't taken a close look, but it seems you completely replaced the implementation?
This is quite concerning, I'd really prefer to not support two separate implementations for merge that we'll need to constantly keep in sync with each other
|
There is new issue around onSchemaChange - #2372. Would this PR cover it or this is a separate thing? |
|
I will try to go back to this or defer to someone. |
|
@rafal-hawrylak to answer your question: I think so |
@kolina already marked it as duplicate |
60cbbbe to
b99d099
Compare
|
Updated to account for review comments, fix some remaining issues and add regression tests:
Note: |
This wasn't really a duplicate, but will nonetheless be solved with this PR. |
There is now one implementation, with columns passed either statically or dynamically depending on strategy. |
…or handler The outer EXCEPTION handler emitted by safeCallAndDropProcedure dropped the `_temp` staging table by its unqualified name. That table is scoped to the stored procedure, so it is not resolvable from the calling script, and BigQuery resolves table names before evaluating IF EXISTS. The handler therefore raised Invalid value: Table "<table>_df_temp_<id>_temp" must be qualified with a dataset (e.g. dataset.table) which masked the original error and, because DROP PROCEDURE runs after it, leaked the df_osc_* procedure into the user's dataset. This was most visible with onSchemaChange: "FAIL", where the intended "Schema mismatch defined by on_schema_change = 'FAIL'. Added columns: ..." message never reached the user. The staging table is already dropped inside the procedure by cleanupSql, and BigQuery drops procedure-scoped temporary tables on exit, so the statement was redundant as well as harmful. Removing it also restores parity with the managed Dataform service, whose handler drops only the fully qualified `_empty` table. Adds a regression test asserting that every table dropped in the error handler is fully qualified, and fixes the destructuring in the dynamic-DML test so that the "no static DML after the procedure" assertions inspect the whole trailing script rather than only the CALL block.
3482a0f to
ca3f3c2
Compare
…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)
| this.declareSchemaChangeVariablesSql(table), | ||
| this.createEmptyTempTableSql(emptyTempTableName, query), | ||
| this.compareSchemasSql(table.target, emptyTempTableTarget), | ||
| this.applySchemaChangeStrategySql(table, qualifiedTargetTableName), |
There was a problem hiding this comment.
When onSchemaChange is SYNCHRONIZE and table.uniqueKey is empty or unset (append INSERT or INSERT_OVERWRITE), incrementalSchemaChangeBody calls applySchemaChangeStrategySql (lines 406–418), which emits WHERE col IN UNNEST([]). In BigQuery GoogleSQL, untyped [] defaults to ARRAY<INT64> while col is STRING, failing unconditionally with No matching signature for operator IN for argument types STRING and INT64.
Guard both DECLARE invalid_removed_columns in declareSchemaChangeVariablesSql (lines 330–332) and the SET invalid_removed_columns / IF ARRAY_LENGTH(invalid_removed_columns) > 0 block in applySchemaChangeStrategySql (lines 407–418) on uniqueKeys.length > 0, and add unit/E2E coverage for SYNCHRONIZE without uniqueKey.
There was a problem hiding this comment.
I was not able to reproduce this issue. An e2e test with SYNCHRONIZE without uniqueKey passes, and a query like the following:
with cte as (select 'text' as string_col)
SELECT string_col from cte where string_col in unnest([])
runs without error in the BigQuery web interface
| this.applySchemaChangeStrategySql(table, qualifiedTargetTableName), | ||
| this.prepareDynamicColumnsSql(table), | ||
| this.getIncrementalDmlStatement(table), |
There was a problem hiding this comment.
applySchemaChangeStrategySql runs ALTER TABLE ... DROP/ADD COLUMN before getIncrementalDmlStatement materializes staging_table_temp_*. Because BigQuery DDL cannot roll back, a runtime error in the incremental query (e.g. division by zero, cast error, ERROR()) — or a SYNCHRONIZE query reading a soon-to-be-dropped column from ${self()} — permanently drops columns before the run fails.
Consider splitting the schema-policy validation guards (FAIL, EXTEND removal check, SYNCHRONIZE uniqueKey check) from the ALTER TABLE DDL so invalid schema changes still fail fast on the LIMIT 0 probe, then materializing the staging table before running ALTER TABLE. (Fine as a follow-up if you want to keep the current managed-service execution order for now.)
There was a problem hiding this comment.
If the current order matches the managed-service then let's delegate it to a follow-up so we can properly surface the issue and consider whether we should deviate from backend behavior here.
fa8ebe3 to
2ce1b4d
Compare
…n begin ... end, move temp table cleanup earlier
f921dc5 to
bec312f
Compare
Remove the conditional fallback in SYNCHRONIZE and assert the exact current pre-#2320 behavior (syncRun2 fails referencing legacy_col, followed by a successful syncRun3), and explicitly assert status: null on EXTEND rows. Both assertions carry TODO(#2320) comments so rebasing onto #2320 will fail loudly until updated for dynamic DML.
Fixes #2307 (together with #2319, which this is stacked on — review that first).
Problem
ExecutionSql.publishTasksemitted the schema-change stored procedure and then fell through to a staticINSERT/MERGE/INSERT_OVERWRITEbuilt fromtableMetadata.fields.tableMetadatais fetched once, before execution, so the DML always used the pre-alteration column list:EXTEND— newly added columns were omitted from theINSERTlist and silently leftNULL.SYNCHRONIZE— dropped columns were still referenced, failing at runtime withUnrecognized name: <dropped_col>.The correct column list only exists after the schema-change DDL has run, i.e. at BigQuery script runtime. It cannot be computed by the CLI at compile time, so the DML has to move inside the procedure.
Solution
Generate the DML dynamically inside the stored procedure, matching the behaviour of the managed Dataform service:
publishTasksnowbreaks instead of falling through, so no static DML is emitted forFAIL/EXTEND/SYNCHRONIZE.IGNOREis unchanged.dataform_columns_list(plusdataform_columns_mergefor merge-strategy tables) is declared up front andSETfromtemp_table_columnsafter the schema-change DDL._tempstaging table.INSERT/MERGE/INSERT_OVERWRITEruns viaEXECUTE IMMEDIATE, splicing in the runtime column lists._emptyand_tempare cleaned up on completion and on error.Generated SQL for
EXTEND— beforeGenerated SQL for
EXTEND— afterBehaviour change
Projects using
EXTENDorSYNCHRONIZEwill see a different generated script. The incremental query is now materialised into a temporary staging table before the DML instead of being inlined into it, so the query text appears twice in the script (once as theLIMIT 0schema probe, once as the staging table).IGNOREis unaffected.Because the procedure queries
INFORMATION_SCHEMA.COLUMNStwice and creates the_emptyprobe table, an incremental run withonSchemaChangeset bills a small fixed amount (~40 MiB observed) even for a trivial query. This matches the managed service.Test coverage
onSchemaChangeINSERT(nouniqueKey)FAIL,EXTENDEXTEND)MERGE(uniqueKey)SYNCHRONIZEINSERT_OVERWRITEEXTENDFAILtrips)FAILcli/api/execution_sql_test.ts): updated goldens foron_schema_change_{fail,extend,synchronize}.sqlandinsert_overwrite_extend.sql; a test asserting the dynamic DML is emitted inside the procedure and no static DML referencing staletableMetadatacolumns is emitted after it; and a test asserting every table dropped in the outer error handler is fully qualified.cli/index_run_e2e_test.ts): theonSchemaChangesuite is upgraded from--dry-runonly to executingEXTENDandSYNCHRONIZElive against BigQuery, asserting via Dataform assertions that added columns (field2) are populated with non-null data and dropped columns (field1) are removed. These require GCP credentials and are taggedintegration(Mark tests that require valid GCP project credentials as integration tests #2289).Verified manually against the exact repro from #2307 (
type: "incremental",onSchemaChange: "FAIL",SELECT 1 AS a) on BigQuery: run 1 creates the table, run 2 succeeds and appends correctly, and changing the query toSELECT 1 AS a, 2 AS bnow fails with the intended message:Reviewer note: intentional commit split
style(cli): format index_run_e2e_test.ts with prettier— mechanical Prettier formatting of pre-existing code incli/index_run_e2e_test.ts, required byscripts/lint, with no logic changes. Kept separate so it does not pollute the functional diff.fix(cli): execute dynamic DML inside onSchemaChange procedure (#2307)— the functional change, goldens, unit test and E2E tests.fix(cli): do not drop the procedure-scoped staging table from the error handler— follow-up fix found while testing this branch live; see below.Reviewing commits 2 and 3 individually gives the cleanest diff.
On commit 3: the outer
EXCEPTIONhandler dropped the_tempstaging table by its unqualified name. That table is scoped to the stored procedure, so it is not resolvable from the calling script, and BigQuery resolves table names before evaluatingIF EXISTS. The handler therefore raisedTable "..._temp" must be qualified with a dataset, which masked the original error and leaked thedf_osc_*procedure (becauseDROP PROCEDUREruns after it). It was most visible withonSchemaChange: "FAIL", where the intended schema-mismatch message never reached the user. The statement was also redundant —cleanupSqlalready drops the table inside the procedure, and BigQuery drops procedure-scoped temp tables on exit.