Skip to content

server: let CREATE OR REPLACE TABLE replace an existing table - #519

Open
ymatrix1 wants to merge 1 commit into
goccy:mainfrom
ymatrix1:fix/create-or-replace-existing-table
Open

ymatrix1 wants to merge 1 commit into
goccy:mainfrom
ymatrix1:fix/create-or-replace-existing-table

Conversation

@ymatrix1

Copy link
Copy Markdown

Related: #105 (closed, "Creating and dropping and recreating tables").

Problem

CREATE OR REPLACE TABLE on a table that already exists fails instead of replacing it:

CREATE OR REPLACE TABLE dataset1.t AS SELECT 1 AS id;
CREATE OR REPLACE TABLE dataset1.t AS SELECT 1 AS id UNION ALL SELECT 2;
-- googleapi: Error 409: table t: table is already created, duplicate

Same for CREATE OR REPLACE TABLE t (a INT64, b STRING) over an existing t. dbt hits this whenever a previous run left a __dbt_tmp table behind: the next run's CREATE OR REPLACE returns 409.

Cause

googlesqlite reports CREATE OR REPLACE of an existing table in ChangedCatalog.Table.Added (it never uses Updated). syncCatalog → addTableMetadata then inserts a second metadata entry, and Dataset.AddTable rejects the duplicate.

Fix

addTableMetadata removes the metadata already recorded for the table before creating the new entry. This adds Dataset.DeleteTable, which, unlike Table.Delete, also drops the entry from the dataset's in-memory table list (and releases d.mu before UpdateDataset, which takes it again through TableIDs).

Tests

server/create_or_replace_test.go: CTAS replaced twice (rows and numRows reflect the new content), a column-list table replaced with a new schema, CREATE TABLE without OR REPLACE still fails on an existing table, and create/drop cycles.

Before:

create_or_replace_test.go:82: replace: googleapi: Error 409: table cor_ctas: table is already created, duplicate
create_or_replace_test.go:101: replace: googleapi: Error 409: table cor_cols: table is already created, duplicate
--- FAIL: TestCreateOrReplaceExistingTable/CTAS
--- FAIL: TestCreateOrReplaceExistingTable/column_list

After: all 4 subtests pass. go test ./... passes with no new failures against main.

googlesqlite reports CREATE OR REPLACE of an existing table as an
added table. addTableMetadata then tried to insert a second metadata
entry and the job failed with '409 ... table is already created', so
OR REPLACE could never replace a table. Remove the existing metadata
first. Adds Dataset.DeleteTable, which, unlike Table.Delete, also
drops the entry from the dataset's in-memory table list.
@ymatrix1
ymatrix1 marked this pull request as ready for review September 22, 2026 23:41
@ymatrix1

ymatrix1 commented Oct 9, 2026

Copy link
Copy Markdown
Author

Status note: this fix is already running in production use of the emulator. While these PRs wait for review we carry them, together with the related fixes, in a fork: https://github.com/Flip-to/bigquery-emulator (branch flipto/main, tag flipto-v1), whose SQL engine is https://github.com/Flip-to/googlesqlite. A dbt project's fixture test suite (28 tests) runs green on it except for tests that need external seed data, and the engine fork replays 6,136 recorded BigQuery query results as a regression test.

Happy to rebase, split or adjust anything here if that helps review.

Zeus26286 pushed a commit to Zeus26286/bigquery-emulator that referenced this pull request Nov 3, 2026
* Pin the Ruby e2e client's json gem below 3

multi_json passes JSON.parse a positional options hash, which json 3
rejects, so every Ruby conformance case failed with "wrong number of
arguments (given 2, expected 1)" once a fresh image build picked up
json 3.1.0 through faraday's unpinned dependency. Pin json 2.10.2 and
remove any json >= 3 after installing, failing the build if one remains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the table catalog in sync with DDL

CREATE OR REPLACE TABLE failed with "duplicate" and left the analyzer
with the old columns, ALTER TABLE was a no-op, and a script that failed
partway committed its statements without syncing metadata, so a later
DROP crashed with a 500 nil-pointer panic (upstream goccy#519, goccy#481, goccy#523).

- Replace the catalog sync with an idempotent one (server/catalog_sync.go)
  that runs in a single transaction, deletes before adds, replaces
  re-added tables, keeps the existing table on IF NOT EXISTS (repairing
  googlesqlite's stored spec), skips temp and unknown tables, and forces
  an analyzer rebuild afterwards.
- Implement ALTER TABLE ADD/DROP/RENAME COLUMN, RENAME TO and IF [NOT]
  EXISTS (server/alter_table.go) by parsing with go-googlesql and
  rewriting into a data-preserving rebuild. Column descriptions, modes,
  partitioning, clustering and creation time are kept; dropping or
  renaming a partitioning/clustering column and unsupported column
  clauses (DEFAULT, COLLATE, generated) are rejected; a failed rebuild
  rolls back; concurrent ALTERs are serialized.
- On a failed script, commit the statements that ran and sync the
  catalog on both jobs.insert and jobs.query, matching BigQuery.
- Add Dataset.DeleteTable and use it from tables.delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Activate json < 3 in the Ruby e2e runner instead of uninstalling json 3

The Dockerfile removed json >= 3 with `gem uninstall --ignore-dependencies`
and checked the result with a `json-[3-9]` grep, which misses json 10+ and
leaves faraday's dependency unsatisfied. Keep json 2.10.2 in gems.txt next
to whatever json faraday pulls in, and activate it at the top of runner.rb
with `gem "json", "< 3"`, before anything requires json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: note that jobs.query now keeps the effects of a failed script

jobs.query used to roll back the whole query when any statement failed.
It now commits the statements that ran before the failing one, like
jobs.insert and BigQuery. Call out the behaviour change in the jobs and
scripting rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Guard ALTER TABLE rebuilds against concurrent changes

Address review comments on the DDL catalog sync:

- Check inside the job transaction, right before the rebuild, that the
  table still has the columns the ALTER TABLE was planned from, and fail
  with a concurrent-modification error (rolled back) otherwise. Without it,
  a CREATE OR REPLACE between planning and the rebuild could silently drop
  the new table's extra columns. alterMu still serializes ALTER TABLE.
- Report an ALTER TABLE rejected while planning through the same path as
  any other failed query on jobs.query.
- Only take the ALTER path for ALTER TABLE (after comments, any
  whitespace between the keywords), not ALTER VIEW / SCHEMA.
- Name the rebuild's temporary table with a short fixed prefix and a random
  suffix, so its length no longer grows with the table name, and skip it
  in the catalog sync.
- Link goccy/googlesqlite#104, goccy#92 and goccy#96 from the code they explain, and
  mark the googlesqlite behaviours with no upstream issue yet as
  TODO(googlesqlite).
- Test that a single failing INSERT / UPDATE / DELETE leaves the table
  unchanged on both endpoints, and that ALTER planning errors are reported
  like invalid queries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Clarify the ALTER TABLE guard's error and what it checks

The guard compares column names only, and also fires when a table's
columns and metadata have already drifted apart, where retrying does not
help. Say both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

1 participant