Repository navigation
feat(spanner): add native AsyncIO Spanner adapter, extension stores, and sync/async parity - #831
Merged
Merged
Conversation
…er inference and coercion
…ncSelectStreamSource
…, and transaction lifecycle
… _batch_write_mutations
…pannerAsyncConfig
…registries, and docs
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #831 +/- ##
==========================================
- Coverage 82.58% 81.71% -0.87%
==========================================
Files 521 521
Lines 78458 79815 +1357
Branches 11342 11531 +189
==========================================
+ Hits 64792 65224 +432
- Misses 10734 10866 +132
- Partials 2932 3725 +793
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
mypyc 2.4.0 fails with an internal AssertionError when compiling a for loop over reversed(...) whose items involve Any. Iterate a reversed slice instead so compiled wheels build on both mypy 2.3 and 2.4.
JSONBContainsTopKey first appears in sqlglot 30.18, so importing sqlspec.core failed on 30.13 through 30.17. Register the ?? rendering only when SQLGlot defines the expression.
Async ADK base stores now expose the reset-drop hooks as coroutines, matching the other DDL hooks, and the create migration awaits them on rollback. Adapters that need a database lookup to decide which tables to drop can now do so from an async store.
The async Spanner ADK session and memory stores now drop only tables that exist, as the sync stores already did, so rolling back the ADK migration no longer fails on missing tables. The stores now call the async SDK directly, declare slots, share option parsing, and use sync/async helper pairs with matching names.
Group the stores under an Extensions section ahead of Extension Settings, promote native execution controls and parameter types to top-level sections, document the SpannerSync* names, and record the async adapter, renames, and fixes in the changelog.
Run duplicated driver checks and transaction completion tests against both adapters through a mode-parametrized config, and make the async config fixture session-scoped like the other async adapters.
Run the shared ADK and Litestar store contracts against both Spanner stores, add an ADK memory round-trip, and exercise the event queue lifecycle and metadata on both adapters.
… one loop Try the full optimizer rules, then the same rules without pushdown_projections when SQLGlot raises OptimizeError, instead of a nested try that repeats the optimize call.
TypedParameter.original_type stays a Python type. Spanner reads a declared type such as FLOAT32, ARRAY<FLOAT32>, VECTOR, or INTERVAL from semantic_name and binds FLOAT32 and INTERVAL through param_types directly.
…vers - Name sync classes SpannerSync* (exception handler, data dictionary, connection and session contexts, connection alias) and drop the unprefixed and bare Async* aliases; exports follow psycopg. - Share one commit/rollback decision between both connection contexts and drivers; an explicit rollback is no longer followed by a commit, and rollback discards mutations buffered before the transaction began. - Call the async SDK directly instead of probing for awaitables, and move run_in_transaction, script query detection, DDL helpers, and the stream sources (now SpannerSyncStreamSource/SpannerAsyncStreamSource) into core.py. - Reject a session pool class from the other sync/async variant, default both configs to FixedSizePool, report no native Parquet support for either, and map load_from_arrow errors in the sync driver too. - Drop the undeclared database_provider driver feature.
…pannerSyncTransactionType The ADK session and memory stores list tables and apply DDL through the core helpers used by the Litestar and events stores. The sync TransactionType alias is SpannerSyncTransactionType, and the changelog covers the sync rollback fix, semantic_name type declarations, and pool class validation.
TransactionType is a Spanner SDK re-export, so it keeps the Spanner plus SDK class name form used by the other SDK aliases.
Spanner requires an explicit length on STRING and BYTES columns and parentheses around column defaults. Column definitions now render unsized text and binary types as STRING(MAX) and BYTES(MAX), and defaults as DEFAULT (expr); query casts keep the unsized forms.
Script splitting treated a semicolon inside a backtick-quoted identifier as a statement terminator, which broke MySQL, BigQuery and Spanner scripts that quote identifiers with backticks. Spanner and Spangres scripts now use the GoogleSQL and PostgreSQL splitter rules instead of the generic fallback.
Spanner rejects DDL sent through a transaction, so migrations and any schema change failed on both adapters. DDL statements now run through the database update_ddl API, consecutive DDL in a script is applied as one schema change, and a begun write transaction is committed before a schema change. Write sessions also keep working after commit() or rollback(): the next statement runs in a new transaction on the same session, and session release completes the transaction the driver holds. Drivers inside run_in_transaction leave commit and retry to the SDK. The shared migration contracts now run against the Spanner emulator in both modes.
Read sessions rejected DML but let DDL through to the schema API, so a read-only session could change the schema. DDL from a Snapshot session now raises SQLConversionError, as DML does.
SQLGlot could not parse Spanner's THEN RETURN clause, so the statement was treated as plain DML and its returned rows were discarded. The Spanner dialect now parses THEN RETURN [WITH ACTION [AS alias]] into a Returning clause and renders it back, so these statements return rows on both adapters, including repeated cached executions.
The pinned upload-artifact and download-artifact commits are v7.0.1 and v8.0.1, but their comments named the floating v7 and v8 tags, which have since moved. zizmor's online audit flags the mismatch.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds full native AsyncIO support for Google Cloud Spanner (
google.cloud.spanner_v1._asyncintroduced ingoogle-cloud-spanner>=3.64.0) alongside sync/async parity and performance optimizations across the Spanner adapter, data dictionary, and framework extension stores.Key Changes
Native AsyncIO Spanner Adapter Stack (
sqlspec.adapters.spanner)SpannerAsyncConfig(AsyncDatabaseConfig): ManagesAsyncClient,await config.get_database(),AsyncBurstyPool(default) /AsyncFixedSizePool/AsyncPingingPool/AsyncTransactionPingingPoolsession pools,SpannerAsyncConnectionContext,_SpannerAsyncSessionConnectionHandler,provide_session(),provide_read_session(),provide_write_session(), andawait config.run_in_transaction(...).SpannerAsyncDriver(AsyncDriverAdapterBase): ImplementsSpannerAsyncExceptionHandler,_SpannerAsyncSelectStreamSource(AsyncRowStream),dispatch_execute,dispatch_execute_many,dispatch_execute_script,select_stream,select_to_arrow,select_to_storage,load_from_arrow,load_from_storage,_batch_write_mutations,begin,commit,rollback, savepoints, and per-call execution options (request_options,query_options,directed_read_options,retry,timeout,last_statement).SpannerAsyncDataDictionary(AsyncDataDictionaryBase): Shares GoogleSQL and Spangres PostgreSQL dialect metadata routing withSpannerSyncDataDictionary(SpannerDataDictionary).*Sync*/*Async*Exports: ExposesSpannerSyncConnection,SpannerSyncConnectionContext,SpannerSyncCursor,SpannerSyncDataDictionary,SpannerSyncDriver,SpannerSyncExceptionHandler, andSpannerSyncSessionContextalongside theirSpannerAsync*counterparts while retaining unprefixed aliases for backward compatibility.Native AsyncIO Extension Stores
sqlspec.adapters.spanner.adk):SpannerAsyncADKStore(BaseAsyncADKStore[SpannerAsyncConfig])andSpannerAsyncADKMemoryStore(BaseAsyncADKMemoryStore[SpannerAsyncConfig])sharing DDL and query builders with the sync stores via_SpannerADKStoreCommonMixinand_SpannerADKMemoryStoreCommonMixin.sqlspec.adapters.spanner.litestar):SpannerAsyncStore(BaseSQLSpecStore[SpannerAsyncConfig])executing native async snapshot reads andawait database.run_in_transaction(...)writes without worker-thread offloading.sqlspec.adapters.spanner.events):SpannerAsyncEventQueueStore(BaseEventQueueStore[SpannerAsyncConfig])sharing_SpannerEventQueueStoreMixinwithSpannerSyncEventQueueStore.Sync + Async Parity & Performance Optimizations
run_in_transactionAbort Retry Unwrapping: BothSpannerSyncConfig.run_in_transaction/SpannerSyncDriver.run_in_transactionandSpannerAsyncConfig.run_in_transaction/SpannerAsyncDriver.run_in_transactionunwrapDeadlockError.__cause__when caused bygoogle.api_core.exceptions.Abortedso Spanner's native transaction runner backs off and retries on409 Aborted, mapping terminalAbortedexceptions back toDeadlockError.SpannerSyncConfig._create_poolandSpannerAsyncConfig._create_pooldefaultping_interval=1800onPingingPool/TransactionPingingPooland automatically map syncFLOAT32Vectors &INTERVALParameter Inference: SupportsFLOAT32,ARRAY<FLOAT32>/VECTOR(TypedParameter), andINTERVAL(datetime.timedelta) parameter type inference and coercion insqlspec/adapters/spanner/type_converter.py.JsonObjectUnwrapping:_convert_json_row_valueunwrapsJsonObjectcells directly whenjson_deserializer is from_json, avoiding redundantserialize()string round-trips.Tests & Documentation
tests/unit/adapters/test_spanner/(test_async_driver.py,test_config.py,test_adk_store.py,test_litestar_store.py,test_events_store.py,test_data_dictionary_routing.py,test_spanner_type_inference.py,test_core.py,test_init.py) and cross-adapter test registries.spanner_async_config,spanner_async_session,spanner_async_write_session,spanner_async_read_session) and integration suite (tests/integration/adapters/spanner/spanner/test_async_driver.py).docs/reference/adapters/spanner.rst,docs/reference/adapters/index.rst,docs/reference/driver.rst,docs/usage/frameworks/litestar/session_stores.rst,docs/extensions/adk/backends.rst,docs/extensions/adk/adapters.rst).Test Plan
uv run pytest tests/unit/adapters/test_spanner/ tests/unit/adapters/test_extension_config.pyuv run pytest tests/unit(13,275 passed)uv run mypy sqlspec/adapters/spanner tests/unit/adapters/test_spanneruv run pyright sqlspec/adapters/spanner tests/unit/adapters/test_spanneruv run ruff check sqlspec/adapters/spanner tests/unit/adapters/test_spanneruv run python tools/scripts/mypyc_inventory.py --check