sqlspec 0.72.0__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 6b29784d6b1cafc66758__mypyc.cp315-win_amd64.pyd +0 -0
- sqlspec/__init__.py +381 -0
- sqlspec/__main__.py +14 -0
- sqlspec/__metadata__.py +14 -0
- sqlspec/_typing.py +775 -0
- sqlspec/adapters/__init__.py +3 -0
- sqlspec/adapters/adbc/__init__.py +16 -0
- sqlspec/adapters/adbc/_typing.py +221 -0
- sqlspec/adapters/adbc/adk/__init__.py +11 -0
- sqlspec/adapters/adbc/adk/store.py +4101 -0
- sqlspec/adapters/adbc/config.py +843 -0
- sqlspec/adapters/adbc/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/adbc/core.py +3209 -0
- sqlspec/adapters/adbc/data_dictionary.py +1448 -0
- sqlspec/adapters/adbc/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/adbc/driver.py +1400 -0
- sqlspec/adapters/adbc/events/__init__.py +5 -0
- sqlspec/adapters/adbc/events/store.py +384 -0
- sqlspec/adapters/adbc/litestar/__init__.py +5 -0
- sqlspec/adapters/adbc/litestar/store.py +962 -0
- sqlspec/adapters/adbc/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/adbc/pool.py +242 -0
- sqlspec/adapters/adbc/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/adbc/type_converter.py +117 -0
- sqlspec/adapters/aiomysql/__init__.py +25 -0
- sqlspec/adapters/aiomysql/_typing.py +134 -0
- sqlspec/adapters/aiomysql/adk/__init__.py +5 -0
- sqlspec/adapters/aiomysql/adk/store.py +1542 -0
- sqlspec/adapters/aiomysql/config.py +634 -0
- sqlspec/adapters/aiomysql/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/aiomysql/core.py +922 -0
- sqlspec/adapters/aiomysql/data_dictionary.py +16 -0
- sqlspec/adapters/aiomysql/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/aiomysql/driver.py +494 -0
- sqlspec/adapters/aiomysql/events/__init__.py +5 -0
- sqlspec/adapters/aiomysql/events/store.py +72 -0
- sqlspec/adapters/aiomysql/litestar/__init__.py +5 -0
- sqlspec/adapters/aiomysql/litestar/store.py +345 -0
- sqlspec/adapters/aiosqlite/__init__.py +43 -0
- sqlspec/adapters/aiosqlite/_typing.py +75 -0
- sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
- sqlspec/adapters/aiosqlite/adk/store.py +1546 -0
- sqlspec/adapters/aiosqlite/config.py +607 -0
- sqlspec/adapters/aiosqlite/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/aiosqlite/core.py +1155 -0
- sqlspec/adapters/aiosqlite/data_dictionary.py +343 -0
- sqlspec/adapters/aiosqlite/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/aiosqlite/driver.py +559 -0
- sqlspec/adapters/aiosqlite/events/__init__.py +5 -0
- sqlspec/adapters/aiosqlite/events/store.py +54 -0
- sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
- sqlspec/adapters/aiosqlite/litestar/store.py +315 -0
- sqlspec/adapters/aiosqlite/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/aiosqlite/pool.py +1323 -0
- sqlspec/adapters/aiosqlite/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/aiosqlite/type_converter.py +114 -0
- sqlspec/adapters/arrow_odbc/__init__.py +32 -0
- sqlspec/adapters/arrow_odbc/_typing.py +131 -0
- sqlspec/adapters/arrow_odbc/adk/__init__.py +5 -0
- sqlspec/adapters/arrow_odbc/adk/store.py +1671 -0
- sqlspec/adapters/arrow_odbc/config.py +446 -0
- sqlspec/adapters/arrow_odbc/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/arrow_odbc/core.py +795 -0
- sqlspec/adapters/arrow_odbc/data_dictionary.py +345 -0
- sqlspec/adapters/arrow_odbc/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/arrow_odbc/driver.py +885 -0
- sqlspec/adapters/arrow_odbc/events/__init__.py +5 -0
- sqlspec/adapters/arrow_odbc/events/store.py +114 -0
- sqlspec/adapters/arrow_odbc/litestar/__init__.py +5 -0
- sqlspec/adapters/arrow_odbc/litestar/store.py +682 -0
- sqlspec/adapters/arrow_odbc/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/arrow_odbc/type_converter.py +95 -0
- sqlspec/adapters/asyncmy/__init__.py +27 -0
- sqlspec/adapters/asyncmy/_typing.py +215 -0
- sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
- sqlspec/adapters/asyncmy/adk/store.py +1544 -0
- sqlspec/adapters/asyncmy/config.py +707 -0
- sqlspec/adapters/asyncmy/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/asyncmy/core.py +917 -0
- sqlspec/adapters/asyncmy/data_dictionary.py +16 -0
- sqlspec/adapters/asyncmy/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/asyncmy/driver.py +529 -0
- sqlspec/adapters/asyncmy/events/__init__.py +5 -0
- sqlspec/adapters/asyncmy/events/store.py +72 -0
- sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
- sqlspec/adapters/asyncmy/litestar/store.py +348 -0
- sqlspec/adapters/asyncpg/__init__.py +28 -0
- sqlspec/adapters/asyncpg/_typing.py +113 -0
- sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
- sqlspec/adapters/asyncpg/adk/store.py +1145 -0
- sqlspec/adapters/asyncpg/config.py +903 -0
- sqlspec/adapters/asyncpg/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/asyncpg/core.py +797 -0
- sqlspec/adapters/asyncpg/data_dictionary.py +417 -0
- sqlspec/adapters/asyncpg/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/asyncpg/driver.py +927 -0
- sqlspec/adapters/asyncpg/events/__init__.py +6 -0
- sqlspec/adapters/asyncpg/events/_hub.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/asyncpg/events/_hub.py +279 -0
- sqlspec/adapters/asyncpg/events/backend.py +410 -0
- sqlspec/adapters/asyncpg/events/store.py +57 -0
- sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
- sqlspec/adapters/asyncpg/litestar/store.py +278 -0
- sqlspec/adapters/asyncpg/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/asyncpg/tenant.py +140 -0
- sqlspec/adapters/bigquery/__init__.py +23 -0
- sqlspec/adapters/bigquery/_typing.py +184 -0
- sqlspec/adapters/bigquery/adk/__init__.py +5 -0
- sqlspec/adapters/bigquery/adk/store.py +920 -0
- sqlspec/adapters/bigquery/config.py +631 -0
- sqlspec/adapters/bigquery/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/bigquery/core.py +1433 -0
- sqlspec/adapters/bigquery/data_dictionary.py +502 -0
- sqlspec/adapters/bigquery/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/bigquery/driver.py +1266 -0
- sqlspec/adapters/bigquery/events/__init__.py +5 -0
- sqlspec/adapters/bigquery/events/store.py +158 -0
- sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
- sqlspec/adapters/bigquery/litestar/store.py +359 -0
- sqlspec/adapters/cockroach_asyncpg/__init__.py +32 -0
- sqlspec/adapters/cockroach_asyncpg/_typing.py +54 -0
- sqlspec/adapters/cockroach_asyncpg/adk/__init__.py +9 -0
- sqlspec/adapters/cockroach_asyncpg/adk/store.py +1096 -0
- sqlspec/adapters/cockroach_asyncpg/config.py +653 -0
- sqlspec/adapters/cockroach_asyncpg/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/cockroach_asyncpg/core.py +835 -0
- sqlspec/adapters/cockroach_asyncpg/data_dictionary.py +371 -0
- sqlspec/adapters/cockroach_asyncpg/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/cockroach_asyncpg/driver.py +438 -0
- sqlspec/adapters/cockroach_asyncpg/events/__init__.py +5 -0
- sqlspec/adapters/cockroach_asyncpg/events/store.py +20 -0
- sqlspec/adapters/cockroach_asyncpg/litestar/__init__.py +5 -0
- sqlspec/adapters/cockroach_asyncpg/litestar/store.py +203 -0
- sqlspec/adapters/cockroach_asyncpg/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/cockroach_asyncpg/tenant.py +143 -0
- sqlspec/adapters/cockroach_psycopg/__init__.py +46 -0
- sqlspec/adapters/cockroach_psycopg/_typing.py +271 -0
- sqlspec/adapters/cockroach_psycopg/adk/__init__.py +17 -0
- sqlspec/adapters/cockroach_psycopg/adk/store.py +2274 -0
- sqlspec/adapters/cockroach_psycopg/config.py +1285 -0
- sqlspec/adapters/cockroach_psycopg/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/cockroach_psycopg/core.py +667 -0
- sqlspec/adapters/cockroach_psycopg/data_dictionary.py +622 -0
- sqlspec/adapters/cockroach_psycopg/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/cockroach_psycopg/driver.py +864 -0
- sqlspec/adapters/cockroach_psycopg/events/__init__.py +8 -0
- sqlspec/adapters/cockroach_psycopg/events/store.py +34 -0
- sqlspec/adapters/cockroach_psycopg/litestar/__init__.py +9 -0
- sqlspec/adapters/cockroach_psycopg/litestar/store.py +413 -0
- sqlspec/adapters/cockroach_psycopg/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/cockroach_psycopg/tenant.py +222 -0
- sqlspec/adapters/db2/__init__.py +34 -0
- sqlspec/adapters/db2/_typing.py +357 -0
- sqlspec/adapters/db2/adk/__init__.py +10 -0
- sqlspec/adapters/db2/adk/store.py +1950 -0
- sqlspec/adapters/db2/config.py +550 -0
- sqlspec/adapters/db2/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/db2/core.py +1021 -0
- sqlspec/adapters/db2/data_dictionary.py +493 -0
- sqlspec/adapters/db2/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/db2/driver.py +898 -0
- sqlspec/adapters/db2/events/__init__.py +5 -0
- sqlspec/adapters/db2/events/store.py +77 -0
- sqlspec/adapters/db2/litestar/__init__.py +5 -0
- sqlspec/adapters/db2/litestar/store.py +519 -0
- sqlspec/adapters/db2/migrations.py +221 -0
- sqlspec/adapters/db2/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/db2/pool.py +876 -0
- sqlspec/adapters/db2/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/db2/tenant.py +292 -0
- sqlspec/adapters/duckdb/__init__.py +30 -0
- sqlspec/adapters/duckdb/_typing.py +182 -0
- sqlspec/adapters/duckdb/adk/__init__.py +10 -0
- sqlspec/adapters/duckdb/adk/store.py +1672 -0
- sqlspec/adapters/duckdb/config.py +506 -0
- sqlspec/adapters/duckdb/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/duckdb/core.py +1299 -0
- sqlspec/adapters/duckdb/data_dictionary.py +553 -0
- sqlspec/adapters/duckdb/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/duckdb/driver.py +1214 -0
- sqlspec/adapters/duckdb/events/__init__.py +5 -0
- sqlspec/adapters/duckdb/events/store.py +38 -0
- sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
- sqlspec/adapters/duckdb/litestar/store.py +313 -0
- sqlspec/adapters/duckdb/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/duckdb/pool.py +1121 -0
- sqlspec/adapters/mssql_python/__init__.py +42 -0
- sqlspec/adapters/mssql_python/_typing.py +135 -0
- sqlspec/adapters/mssql_python/adk/__init__.py +5 -0
- sqlspec/adapters/mssql_python/adk/store.py +1278 -0
- sqlspec/adapters/mssql_python/config.py +455 -0
- sqlspec/adapters/mssql_python/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mssql_python/core.py +862 -0
- sqlspec/adapters/mssql_python/data_dictionary.py +417 -0
- sqlspec/adapters/mssql_python/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mssql_python/driver.py +772 -0
- sqlspec/adapters/mssql_python/events/__init__.py +5 -0
- sqlspec/adapters/mssql_python/events/store.py +46 -0
- sqlspec/adapters/mssql_python/litestar/__init__.py +5 -0
- sqlspec/adapters/mssql_python/litestar/store.py +355 -0
- sqlspec/adapters/mssql_python/migrations.py +162 -0
- sqlspec/adapters/mssql_python/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mssql_python/pool.py +165 -0
- sqlspec/adapters/mssql_python/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mssql_python/tenant.py +74 -0
- sqlspec/adapters/mssql_python/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mssql_python/type_converter.py +98 -0
- sqlspec/adapters/mysqlconnector/__init__.py +47 -0
- sqlspec/adapters/mysqlconnector/_typing.py +205 -0
- sqlspec/adapters/mysqlconnector/adk/__init__.py +17 -0
- sqlspec/adapters/mysqlconnector/adk/store.py +2503 -0
- sqlspec/adapters/mysqlconnector/config.py +925 -0
- sqlspec/adapters/mysqlconnector/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mysqlconnector/core.py +1075 -0
- sqlspec/adapters/mysqlconnector/data_dictionary.py +23 -0
- sqlspec/adapters/mysqlconnector/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/mysqlconnector/driver.py +702 -0
- sqlspec/adapters/mysqlconnector/events/__init__.py +8 -0
- sqlspec/adapters/mysqlconnector/events/store.py +89 -0
- sqlspec/adapters/mysqlconnector/litestar/__init__.py +9 -0
- sqlspec/adapters/mysqlconnector/litestar/store.py +524 -0
- sqlspec/adapters/oracledb/__init__.py +159 -0
- sqlspec/adapters/oracledb/_json_handlers.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/_json_handlers.py +208 -0
- sqlspec/adapters/oracledb/_param_types.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/_param_types.py +65 -0
- sqlspec/adapters/oracledb/_plugins.py +137 -0
- sqlspec/adapters/oracledb/_storage.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/_storage.py +138 -0
- sqlspec/adapters/oracledb/_typing.py +468 -0
- sqlspec/adapters/oracledb/_uuid_handlers.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/_uuid_handlers.py +143 -0
- sqlspec/adapters/oracledb/_vector_handlers.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/_vector_handlers.py +252 -0
- sqlspec/adapters/oracledb/adk/__init__.py +27 -0
- sqlspec/adapters/oracledb/adk/store.py +4031 -0
- sqlspec/adapters/oracledb/config.py +1785 -0
- sqlspec/adapters/oracledb/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/core.py +5416 -0
- sqlspec/adapters/oracledb/data_dictionary.py +1264 -0
- sqlspec/adapters/oracledb/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/driver.py +3273 -0
- sqlspec/adapters/oracledb/events/__init__.py +29 -0
- sqlspec/adapters/oracledb/events/_hub.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/events/_hub.py +394 -0
- sqlspec/adapters/oracledb/events/backend.py +311 -0
- sqlspec/adapters/oracledb/events/store.py +842 -0
- sqlspec/adapters/oracledb/litestar/__init__.py +17 -0
- sqlspec/adapters/oracledb/litestar/store.py +862 -0
- sqlspec/adapters/oracledb/migrations.py +650 -0
- sqlspec/adapters/oracledb/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/tenant.py +990 -0
- sqlspec/adapters/oracledb/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/oracledb/type_converter.py +93 -0
- sqlspec/adapters/psqlpy/__init__.py +21 -0
- sqlspec/adapters/psqlpy/_typing.py +180 -0
- sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
- sqlspec/adapters/psqlpy/adk/store.py +1514 -0
- sqlspec/adapters/psqlpy/config.py +828 -0
- sqlspec/adapters/psqlpy/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psqlpy/core.py +1040 -0
- sqlspec/adapters/psqlpy/data_dictionary.py +399 -0
- sqlspec/adapters/psqlpy/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psqlpy/driver.py +631 -0
- sqlspec/adapters/psqlpy/events/__init__.py +12 -0
- sqlspec/adapters/psqlpy/events/_hub.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psqlpy/events/_hub.py +367 -0
- sqlspec/adapters/psqlpy/events/backend.py +415 -0
- sqlspec/adapters/psqlpy/events/store.py +46 -0
- sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
- sqlspec/adapters/psqlpy/litestar/store.py +270 -0
- sqlspec/adapters/psqlpy/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psqlpy/tenant.py +137 -0
- sqlspec/adapters/psqlpy/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psqlpy/type_converter.py +21 -0
- sqlspec/adapters/psycopg/__init__.py +44 -0
- sqlspec/adapters/psycopg/_typing.py +408 -0
- sqlspec/adapters/psycopg/adk/__init__.py +17 -0
- sqlspec/adapters/psycopg/adk/store.py +2761 -0
- sqlspec/adapters/psycopg/config.py +1522 -0
- sqlspec/adapters/psycopg/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psycopg/core.py +1001 -0
- sqlspec/adapters/psycopg/data_dictionary.py +701 -0
- sqlspec/adapters/psycopg/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psycopg/driver.py +1629 -0
- sqlspec/adapters/psycopg/events/__init__.py +25 -0
- sqlspec/adapters/psycopg/events/_hub.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psycopg/events/_hub.py +646 -0
- sqlspec/adapters/psycopg/events/backend.py +739 -0
- sqlspec/adapters/psycopg/events/store.py +82 -0
- sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
- sqlspec/adapters/psycopg/litestar/store.py +595 -0
- sqlspec/adapters/psycopg/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psycopg/tenant.py +226 -0
- sqlspec/adapters/psycopg/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/psycopg/type_converter.py +94 -0
- sqlspec/adapters/pymssql/__init__.py +29 -0
- sqlspec/adapters/pymssql/_typing.py +156 -0
- sqlspec/adapters/pymssql/adk/__init__.py +5 -0
- sqlspec/adapters/pymssql/adk/store.py +1270 -0
- sqlspec/adapters/pymssql/config.py +299 -0
- sqlspec/adapters/pymssql/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymssql/core.py +527 -0
- sqlspec/adapters/pymssql/data_dictionary.py +417 -0
- sqlspec/adapters/pymssql/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymssql/driver.py +527 -0
- sqlspec/adapters/pymssql/events/__init__.py +5 -0
- sqlspec/adapters/pymssql/events/store.py +46 -0
- sqlspec/adapters/pymssql/litestar/__init__.py +5 -0
- sqlspec/adapters/pymssql/litestar/store.py +350 -0
- sqlspec/adapters/pymssql/migrations.py +162 -0
- sqlspec/adapters/pymssql/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymssql/pool.py +417 -0
- sqlspec/adapters/pymssql/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymssql/tenant.py +73 -0
- sqlspec/adapters/pymysql/__init__.py +27 -0
- sqlspec/adapters/pymysql/_typing.py +105 -0
- sqlspec/adapters/pymysql/adk/__init__.py +5 -0
- sqlspec/adapters/pymysql/adk/store.py +1646 -0
- sqlspec/adapters/pymysql/config.py +545 -0
- sqlspec/adapters/pymysql/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymysql/core.py +909 -0
- sqlspec/adapters/pymysql/data_dictionary.py +16 -0
- sqlspec/adapters/pymysql/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymysql/driver.py +370 -0
- sqlspec/adapters/pymysql/events/__init__.py +5 -0
- sqlspec/adapters/pymysql/events/store.py +42 -0
- sqlspec/adapters/pymysql/litestar/__init__.py +5 -0
- sqlspec/adapters/pymysql/litestar/store.py +299 -0
- sqlspec/adapters/pymysql/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/pymysql/pool.py +480 -0
- sqlspec/adapters/snowflake/__init__.py +36 -0
- sqlspec/adapters/snowflake/_typing.py +62 -0
- sqlspec/adapters/snowflake/adk/__init__.py +5 -0
- sqlspec/adapters/snowflake/adk/store.py +778 -0
- sqlspec/adapters/snowflake/config.py +333 -0
- sqlspec/adapters/snowflake/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/snowflake/core.py +683 -0
- sqlspec/adapters/snowflake/data_dictionary.py +355 -0
- sqlspec/adapters/snowflake/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/snowflake/driver.py +872 -0
- sqlspec/adapters/snowflake/events/__init__.py +5 -0
- sqlspec/adapters/snowflake/events/store.py +28 -0
- sqlspec/adapters/snowflake/litestar/__init__.py +5 -0
- sqlspec/adapters/snowflake/litestar/store.py +162 -0
- sqlspec/adapters/snowflake/migrations.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/snowflake/migrations.py +76 -0
- sqlspec/adapters/snowflake/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/snowflake/pool.py +385 -0
- sqlspec/adapters/snowflake/tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/snowflake/tenant.py +200 -0
- sqlspec/adapters/snowflake/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/snowflake/type_converter.py +33 -0
- sqlspec/adapters/spanner/__init__.py +57 -0
- sqlspec/adapters/spanner/_typing.py +300 -0
- sqlspec/adapters/spanner/adk/__init__.py +22 -0
- sqlspec/adapters/spanner/adk/artifact_store.py +693 -0
- sqlspec/adapters/spanner/adk/store.py +3053 -0
- sqlspec/adapters/spanner/config.py +1578 -0
- sqlspec/adapters/spanner/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/spanner/core.py +1244 -0
- sqlspec/adapters/spanner/data_dictionary.py +706 -0
- sqlspec/adapters/spanner/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/spanner/driver.py +1673 -0
- sqlspec/adapters/spanner/events/__init__.py +5 -0
- sqlspec/adapters/spanner/events/store.py +357 -0
- sqlspec/adapters/spanner/litestar/__init__.py +5 -0
- sqlspec/adapters/spanner/litestar/store.py +570 -0
- sqlspec/adapters/spanner/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/spanner/type_converter.py +466 -0
- sqlspec/adapters/sqlanywhere/__init__.py +40 -0
- sqlspec/adapters/sqlanywhere/_typing.py +139 -0
- sqlspec/adapters/sqlanywhere/adk/__init__.py +5 -0
- sqlspec/adapters/sqlanywhere/adk/store.py +1136 -0
- sqlspec/adapters/sqlanywhere/config.py +359 -0
- sqlspec/adapters/sqlanywhere/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlanywhere/core.py +583 -0
- sqlspec/adapters/sqlanywhere/data_dictionary.py +282 -0
- sqlspec/adapters/sqlanywhere/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlanywhere/driver.py +480 -0
- sqlspec/adapters/sqlanywhere/events/__init__.py +5 -0
- sqlspec/adapters/sqlanywhere/events/store.py +28 -0
- sqlspec/adapters/sqlanywhere/litestar/__init__.py +5 -0
- sqlspec/adapters/sqlanywhere/litestar/store.py +237 -0
- sqlspec/adapters/sqlanywhere/migrations.py +178 -0
- sqlspec/adapters/sqlanywhere/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlanywhere/pool.py +397 -0
- sqlspec/adapters/sqlite/__init__.py +32 -0
- sqlspec/adapters/sqlite/_typing.py +91 -0
- sqlspec/adapters/sqlite/adk/__init__.py +5 -0
- sqlspec/adapters/sqlite/adk/store.py +1628 -0
- sqlspec/adapters/sqlite/config.py +520 -0
- sqlspec/adapters/sqlite/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlite/core.py +1035 -0
- sqlspec/adapters/sqlite/data_dictionary.py +327 -0
- sqlspec/adapters/sqlite/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlite/driver.py +432 -0
- sqlspec/adapters/sqlite/events/__init__.py +5 -0
- sqlspec/adapters/sqlite/events/store.py +54 -0
- sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
- sqlspec/adapters/sqlite/litestar/store.py +367 -0
- sqlspec/adapters/sqlite/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlite/pool.py +935 -0
- sqlspec/adapters/sqlite/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sqlite/type_converter.py +114 -0
- sqlspec/adapters/sybase/__init__.py +37 -0
- sqlspec/adapters/sybase/_typing.py +150 -0
- sqlspec/adapters/sybase/adk/__init__.py +5 -0
- sqlspec/adapters/sybase/adk/store.py +1370 -0
- sqlspec/adapters/sybase/config.py +276 -0
- sqlspec/adapters/sybase/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sybase/core.py +578 -0
- sqlspec/adapters/sybase/data_dictionary.py +358 -0
- sqlspec/adapters/sybase/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sybase/driver.py +497 -0
- sqlspec/adapters/sybase/events/__init__.py +5 -0
- sqlspec/adapters/sybase/events/store.py +88 -0
- sqlspec/adapters/sybase/litestar/__init__.py +5 -0
- sqlspec/adapters/sybase/litestar/store.py +328 -0
- sqlspec/adapters/sybase/migrations.py +178 -0
- sqlspec/adapters/sybase/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/sybase/pool.py +435 -0
- sqlspec/adapters/teradata/__init__.py +59 -0
- sqlspec/adapters/teradata/_typing.py +145 -0
- sqlspec/adapters/teradata/adk/__init__.py +5 -0
- sqlspec/adapters/teradata/adk/store.py +1300 -0
- sqlspec/adapters/teradata/config.py +324 -0
- sqlspec/adapters/teradata/core.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/teradata/core.py +437 -0
- sqlspec/adapters/teradata/data_dictionary.py +316 -0
- sqlspec/adapters/teradata/driver.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/teradata/driver.py +721 -0
- sqlspec/adapters/teradata/events/__init__.py +5 -0
- sqlspec/adapters/teradata/events/store.py +64 -0
- sqlspec/adapters/teradata/litestar/__init__.py +5 -0
- sqlspec/adapters/teradata/litestar/store.py +264 -0
- sqlspec/adapters/teradata/migrations.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/teradata/migrations.py +80 -0
- sqlspec/adapters/teradata/pool.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/teradata/pool.py +377 -0
- sqlspec/adapters/teradata/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/adapters/teradata/type_converter.py +95 -0
- sqlspec/base.cp315-win_amd64.pyd +0 -0
- sqlspec/base.py +1275 -0
- sqlspec/builder/__init__.py +330 -0
- sqlspec/builder/_base.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_base.py +1752 -0
- sqlspec/builder/_column.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_column.py +508 -0
- sqlspec/builder/_ddl.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_ddl.py +4503 -0
- sqlspec/builder/_delete.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_delete.py +75 -0
- sqlspec/builder/_dml.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_dml.py +639 -0
- sqlspec/builder/_explain.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_explain.py +650 -0
- sqlspec/builder/_expression_wrappers.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_expression_wrappers.py +77 -0
- sqlspec/builder/_factory.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_factory.py +1834 -0
- sqlspec/builder/_generation.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_generation.py +55 -0
- sqlspec/builder/_insert.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_insert.py +308 -0
- sqlspec/builder/_join.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_join.py +501 -0
- sqlspec/builder/_locking.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_locking.py +77 -0
- sqlspec/builder/_merge.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_merge.py +1047 -0
- sqlspec/builder/_parsing_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_parsing_utils.py +1197 -0
- sqlspec/builder/_select.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_select.py +1514 -0
- sqlspec/builder/_temporal.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_temporal.py +183 -0
- sqlspec/builder/_update.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_update.py +139 -0
- sqlspec/builder/_values.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_values.py +271 -0
- sqlspec/builder/_vector_distance.cp315-win_amd64.pyd +0 -0
- sqlspec/builder/_vector_distance.py +763 -0
- sqlspec/cli.py +1656 -0
- sqlspec/config.py +3402 -0
- sqlspec/core/__init__.py +542 -0
- sqlspec/core/_cursor.cp315-win_amd64.pyd +0 -0
- sqlspec/core/_cursor.py +564 -0
- sqlspec/core/_operators.cp315-win_amd64.pyd +0 -0
- sqlspec/core/_operators.py +167 -0
- sqlspec/core/_ordering.cp315-win_amd64.pyd +0 -0
- sqlspec/core/_ordering.py +151 -0
- sqlspec/core/_pagination.py +66 -0
- sqlspec/core/_pipeline.cp315-win_amd64.pyd +0 -0
- sqlspec/core/_pipeline.py +343 -0
- sqlspec/core/_pool.cp315-win_amd64.pyd +0 -0
- sqlspec/core/_pool.py +72 -0
- sqlspec/core/cache.cp315-win_amd64.pyd +0 -0
- sqlspec/core/cache.py +1503 -0
- sqlspec/core/capabilities.cp315-win_amd64.pyd +0 -0
- sqlspec/core/capabilities.py +67 -0
- sqlspec/core/compiler.cp315-win_amd64.pyd +0 -0
- sqlspec/core/compiler.py +1667 -0
- sqlspec/core/config_runtime.cp315-win_amd64.pyd +0 -0
- sqlspec/core/config_runtime.py +219 -0
- sqlspec/core/correlation.cp315-win_amd64.pyd +0 -0
- sqlspec/core/correlation.py +135 -0
- sqlspec/core/explain.cp315-win_amd64.pyd +0 -0
- sqlspec/core/explain.py +284 -0
- sqlspec/core/filters.cp315-win_amd64.pyd +0 -0
- sqlspec/core/filters.py +1442 -0
- sqlspec/core/hashing.cp315-win_amd64.pyd +0 -0
- sqlspec/core/hashing.py +394 -0
- sqlspec/core/metrics.cp315-win_amd64.pyd +0 -0
- sqlspec/core/metrics.py +86 -0
- sqlspec/core/parameters/__init__.py +174 -0
- sqlspec/core/parameters/_alignment.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_alignment.py +321 -0
- sqlspec/core/parameters/_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_converter.py +956 -0
- sqlspec/core/parameters/_declared.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_declared.py +154 -0
- sqlspec/core/parameters/_processor.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_processor.py +1646 -0
- sqlspec/core/parameters/_registry.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_registry.py +207 -0
- sqlspec/core/parameters/_transformers.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_transformers.py +318 -0
- sqlspec/core/parameters/_types.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_types.py +658 -0
- sqlspec/core/parameters/_validator.cp315-win_amd64.pyd +0 -0
- sqlspec/core/parameters/_validator.py +699 -0
- sqlspec/core/query_modifiers.cp315-win_amd64.pyd +0 -0
- sqlspec/core/query_modifiers.py +559 -0
- sqlspec/core/result/__init__.py +67 -0
- sqlspec/core/result/_base.cp315-win_amd64.pyd +0 -0
- sqlspec/core/result/_base.py +1772 -0
- sqlspec/core/routing.cp315-win_amd64.pyd +0 -0
- sqlspec/core/routing.py +270 -0
- sqlspec/core/splitter.cp315-win_amd64.pyd +0 -0
- sqlspec/core/splitter.py +1126 -0
- sqlspec/core/sqlcommenter.cp315-win_amd64.pyd +0 -0
- sqlspec/core/sqlcommenter.py +509 -0
- sqlspec/core/stack.cp315-win_amd64.pyd +0 -0
- sqlspec/core/stack.py +167 -0
- sqlspec/core/statement.cp315-win_amd64.pyd +0 -0
- sqlspec/core/statement.py +2253 -0
- sqlspec/core/tenant/__init__.py +64 -0
- sqlspec/core/tenant/base.cp315-win_amd64.pyd +0 -0
- sqlspec/core/tenant/base.py +123 -0
- sqlspec/core/type_converter.cp315-win_amd64.pyd +0 -0
- sqlspec/core/type_converter.py +147 -0
- sqlspec/data_dictionary/__init__.py +237 -0
- sqlspec/data_dictionary/_capabilities.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/_capabilities.py +142 -0
- sqlspec/data_dictionary/_dependencies.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/_dependencies.py +602 -0
- sqlspec/data_dictionary/_index_ddl.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/_index_ddl.py +562 -0
- sqlspec/data_dictionary/_loader.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/_loader.py +344 -0
- sqlspec/data_dictionary/_registry.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/_registry.py +152 -0
- sqlspec/data_dictionary/_types.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/_types.py +1852 -0
- sqlspec/data_dictionary/dialects/__init__.py +34 -0
- sqlspec/data_dictionary/dialects/bigquery/__init__.py +15 -0
- sqlspec/data_dictionary/dialects/bigquery/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/bigquery/config.py +128 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/columns.sql +63 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/constraints.sql +37 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/datasets.sql +14 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/ddl.sql +51 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/dependencies.sql +22 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/foreign_keys.sql +34 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/indexes.sql +59 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/objects.sql +13 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/privileges.sql +13 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/routines.sql +50 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/system.sql +59 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/tables.sql +111 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/bigquery/sql/views.sql +31 -0
- sqlspec/data_dictionary/dialects/cockroachdb/__init__.py +17 -0
- sqlspec/data_dictionary/dialects/cockroachdb/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/cockroachdb/config.py +95 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/columns.sql +163 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/comments.sql +10 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/constraints.sql +67 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/crdb_internal.sql +11 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/ddl.sql +10 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/dependencies.sql +20 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/foreign_keys.sql +62 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/indexes.sql +32 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/objects.sql +15 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/privileges.sql +13 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/schemas.sql +10 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/sequences.sql +14 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/tables.sql +15 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/cockroachdb/sql/views.sql +11 -0
- sqlspec/data_dictionary/dialects/db2/__init__.py +31 -0
- sqlspec/data_dictionary/dialects/db2/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/db2/config.py +172 -0
- sqlspec/data_dictionary/dialects/db2/sql/columns.sql +98 -0
- sqlspec/data_dictionary/dialects/db2/sql/constraints.sql +49 -0
- sqlspec/data_dictionary/dialects/db2/sql/foreign_keys.sql +43 -0
- sqlspec/data_dictionary/dialects/db2/sql/indexes.sql +39 -0
- sqlspec/data_dictionary/dialects/db2/sql/objects.sql +53 -0
- sqlspec/data_dictionary/dialects/db2/sql/schemas.sql +13 -0
- sqlspec/data_dictionary/dialects/db2/sql/tables.sql +77 -0
- sqlspec/data_dictionary/dialects/db2/sql/version.sql +8 -0
- sqlspec/data_dictionary/dialects/db2/sql/views.sql +15 -0
- sqlspec/data_dictionary/dialects/duckdb/__init__.py +5 -0
- sqlspec/data_dictionary/dialects/duckdb/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/duckdb/config.py +66 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/columns.sql +150 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/constraints.sql +34 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/databases.sql +11 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/ddl.sql +221 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/dependencies.sql +50 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/extensions.sql +14 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/foreign_keys.sql +46 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/functions.sql +18 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/indexes.sql +34 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/objects.sql +30 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/schemas.sql +10 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/sequences.sql +19 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/system.sql +21 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/tables.sql +59 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/types.sql +12 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/duckdb/sql/views.sql +15 -0
- sqlspec/data_dictionary/dialects/mariadb/__init__.py +5 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/columns.sql +45 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/constraints.sql +30 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/ddl.sql +27 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/events.sql +29 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/foreign_keys.sql +42 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/indexes.sql +33 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/objects.sql +50 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/partitions.sql +27 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/plugins.sql +16 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/privileges.sql +24 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/routines.sql +21 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/schemas.sql +10 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/system.sql +12 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/tables.sql +64 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/triggers.sql +21 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/version.sql +7 -0
- sqlspec/data_dictionary/dialects/mariadb/sql/views.sql +15 -0
- sqlspec/data_dictionary/dialects/mssql/__init__.py +51 -0
- sqlspec/data_dictionary/dialects/mssql/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/mssql/config.py +558 -0
- sqlspec/data_dictionary/dialects/mssql/sql/columns.sql +120 -0
- sqlspec/data_dictionary/dialects/mssql/sql/constraints.sql +106 -0
- sqlspec/data_dictionary/dialects/mssql/sql/ddl.sql +89 -0
- sqlspec/data_dictionary/dialects/mssql/sql/dependencies.sql +17 -0
- sqlspec/data_dictionary/dialects/mssql/sql/extended_properties.sql +16 -0
- sqlspec/data_dictionary/dialects/mssql/sql/foreign_keys.sql +40 -0
- sqlspec/data_dictionary/dialects/mssql/sql/indexes.sql +86 -0
- sqlspec/data_dictionary/dialects/mssql/sql/modules.sql +19 -0
- sqlspec/data_dictionary/dialects/mssql/sql/objects.sql +16 -0
- sqlspec/data_dictionary/dialects/mssql/sql/permissions.sql +31 -0
- sqlspec/data_dictionary/dialects/mssql/sql/routines.sql +39 -0
- sqlspec/data_dictionary/dialects/mssql/sql/schemas.sql +13 -0
- sqlspec/data_dictionary/dialects/mssql/sql/sequences.sql +18 -0
- sqlspec/data_dictionary/dialects/mssql/sql/storage.sql +22 -0
- sqlspec/data_dictionary/dialects/mssql/sql/system.sql +38 -0
- sqlspec/data_dictionary/dialects/mssql/sql/tables.sql +97 -0
- sqlspec/data_dictionary/dialects/mssql/sql/triggers.sql +21 -0
- sqlspec/data_dictionary/dialects/mssql/sql/version.sql +7 -0
- sqlspec/data_dictionary/dialects/mssql/sql/views.sql +18 -0
- sqlspec/data_dictionary/dialects/mysql/__init__.py +34 -0
- sqlspec/data_dictionary/dialects/mysql/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/mysql/config.py +363 -0
- sqlspec/data_dictionary/dialects/mysql/dictionary.py +650 -0
- sqlspec/data_dictionary/dialects/mysql/sql/columns.sql +45 -0
- sqlspec/data_dictionary/dialects/mysql/sql/components.sql +8 -0
- sqlspec/data_dictionary/dialects/mysql/sql/constraints.sql +30 -0
- sqlspec/data_dictionary/dialects/mysql/sql/ddl.sql +23 -0
- sqlspec/data_dictionary/dialects/mysql/sql/events.sql +29 -0
- sqlspec/data_dictionary/dialects/mysql/sql/foreign_keys.sql +42 -0
- sqlspec/data_dictionary/dialects/mysql/sql/indexes.sql +33 -0
- sqlspec/data_dictionary/dialects/mysql/sql/objects.sql +38 -0
- sqlspec/data_dictionary/dialects/mysql/sql/partitions.sql +27 -0
- sqlspec/data_dictionary/dialects/mysql/sql/plugins.sql +16 -0
- sqlspec/data_dictionary/dialects/mysql/sql/privileges.sql +26 -0
- sqlspec/data_dictionary/dialects/mysql/sql/routines.sql +21 -0
- sqlspec/data_dictionary/dialects/mysql/sql/schemas.sql +10 -0
- sqlspec/data_dictionary/dialects/mysql/sql/system.sql +25 -0
- sqlspec/data_dictionary/dialects/mysql/sql/tables.sql +64 -0
- sqlspec/data_dictionary/dialects/mysql/sql/triggers.sql +21 -0
- sqlspec/data_dictionary/dialects/mysql/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/mysql/sql/views.sql +15 -0
- sqlspec/data_dictionary/dialects/oracle/__init__.py +39 -0
- sqlspec/data_dictionary/dialects/oracle/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/oracle/config.py +266 -0
- sqlspec/data_dictionary/dialects/oracle/sql/arguments.sql +29 -0
- sqlspec/data_dictionary/dialects/oracle/sql/columns.sql +103 -0
- sqlspec/data_dictionary/dialects/oracle/sql/comments.sql +22 -0
- sqlspec/data_dictionary/dialects/oracle/sql/constraints.sql +49 -0
- sqlspec/data_dictionary/dialects/oracle/sql/ddl.sql +4 -0
- sqlspec/data_dictionary/dialects/oracle/sql/dependencies.sql +16 -0
- sqlspec/data_dictionary/dialects/oracle/sql/foreign_keys.sql +48 -0
- sqlspec/data_dictionary/dialects/oracle/sql/grants.sql +34 -0
- sqlspec/data_dictionary/dialects/oracle/sql/indexes.sql +87 -0
- sqlspec/data_dictionary/dialects/oracle/sql/lob_storage.sql +28 -0
- sqlspec/data_dictionary/dialects/oracle/sql/materialized_views.sql +27 -0
- sqlspec/data_dictionary/dialects/oracle/sql/objects.sql +26 -0
- sqlspec/data_dictionary/dialects/oracle/sql/partitions.sql +44 -0
- sqlspec/data_dictionary/dialects/oracle/sql/routines.sql +21 -0
- sqlspec/data_dictionary/dialects/oracle/sql/schemas.sql +13 -0
- sqlspec/data_dictionary/dialects/oracle/sql/sequences.sql +21 -0
- sqlspec/data_dictionary/dialects/oracle/sql/source.sql +13 -0
- sqlspec/data_dictionary/dialects/oracle/sql/system.sql +37 -0
- sqlspec/data_dictionary/dialects/oracle/sql/tables.sql +48 -0
- sqlspec/data_dictionary/dialects/oracle/sql/triggers.sql +29 -0
- sqlspec/data_dictionary/dialects/oracle/sql/version.sql +25 -0
- sqlspec/data_dictionary/dialects/oracle/sql/views.sql +49 -0
- sqlspec/data_dictionary/dialects/postgres/__init__.py +19 -0
- sqlspec/data_dictionary/dialects/postgres/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/postgres/config.py +119 -0
- sqlspec/data_dictionary/dialects/postgres/sql/columns.sql +130 -0
- sqlspec/data_dictionary/dialects/postgres/sql/comments.sql +27 -0
- sqlspec/data_dictionary/dialects/postgres/sql/constraints.sql +53 -0
- sqlspec/data_dictionary/dialects/postgres/sql/ddl.sql +55 -0
- sqlspec/data_dictionary/dialects/postgres/sql/dependencies.sql +42 -0
- sqlspec/data_dictionary/dialects/postgres/sql/extensions.sql +11 -0
- sqlspec/data_dictionary/dialects/postgres/sql/foreign_keys.sql +72 -0
- sqlspec/data_dictionary/dialects/postgres/sql/indexes.sql +84 -0
- sqlspec/data_dictionary/dialects/postgres/sql/materialized_views.sql +17 -0
- sqlspec/data_dictionary/dialects/postgres/sql/objects.sql +25 -0
- sqlspec/data_dictionary/dialects/postgres/sql/partitions.sql +19 -0
- sqlspec/data_dictionary/dialects/postgres/sql/privileges.sql +29 -0
- sqlspec/data_dictionary/dialects/postgres/sql/routines.sql +25 -0
- sqlspec/data_dictionary/dialects/postgres/sql/schemas.sql +13 -0
- sqlspec/data_dictionary/dialects/postgres/sql/sequences.sql +32 -0
- sqlspec/data_dictionary/dialects/postgres/sql/system.sql +53 -0
- sqlspec/data_dictionary/dialects/postgres/sql/tables.sql +67 -0
- sqlspec/data_dictionary/dialects/postgres/sql/triggers.sql +20 -0
- sqlspec/data_dictionary/dialects/postgres/sql/types.sql +21 -0
- sqlspec/data_dictionary/dialects/postgres/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/postgres/sql/views.sql +17 -0
- sqlspec/data_dictionary/dialects/snowflake/__init__.py +31 -0
- sqlspec/data_dictionary/dialects/snowflake/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/snowflake/config.py +321 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/columns.sql +48 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/constraints.sql +64 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/ddl.sql +3 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/foreign_keys.sql +7 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/objects.sql +34 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/routines.sql +79 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/schemas.sql +19 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/sequences.sql +45 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/tables.sql +29 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/snowflake/sql/views.sql +37 -0
- sqlspec/data_dictionary/dialects/spanner/__init__.py +5 -0
- sqlspec/data_dictionary/dialects/spanner/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/spanner/config.py +67 -0
- sqlspec/data_dictionary/dialects/spanner/sql/columns.sql +58 -0
- sqlspec/data_dictionary/dialects/spanner/sql/foreign_keys.sql +91 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/change_streams.sql +28 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/columns.sql +46 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/constraints.sql +63 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/database.sql +9 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/foreign_keys.sql +91 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/indexes.sql +66 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/objects.sql +10 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/placements.sql +8 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/privileges.sql +13 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/property_graphs.sql +11 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/routines.sql +33 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/sequences.sql +14 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/system.sql +28 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/tables.sql +30 -0
- sqlspec/data_dictionary/dialects/spanner/sql/googlesql/views.sql +13 -0
- sqlspec/data_dictionary/dialects/spanner/sql/indexes.sql +30 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/change_streams.sql +28 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/columns.sql +34 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/constraints.sql +63 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/foreign_keys.sql +91 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/indexes.sql +52 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/objects.sql +10 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/sequences.sql +14 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/system.sql +28 -0
- sqlspec/data_dictionary/dialects/spanner/sql/postgresql/tables.sql +22 -0
- sqlspec/data_dictionary/dialects/spanner/sql/tables.sql +9 -0
- sqlspec/data_dictionary/dialects/spanner/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/__init__.py +31 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/config.py +191 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/columns.sql +97 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/constraints.sql +43 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/foreign_keys.sql +45 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/indexes.sql +39 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/objects.sql +18 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/schemas.sql +15 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/tables.sql +86 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlanywhere/sql/views.sql +15 -0
- sqlspec/data_dictionary/dialects/sqlite/__init__.py +19 -0
- sqlspec/data_dictionary/dialects/sqlite/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/sqlite/config.py +412 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/columns.sql +59 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/compile_options.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/constraints.sql +67 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/ddl.sql +37 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/foreign_keys.sql +45 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/functions.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/indexes.sql +76 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/modules.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/objects.sql +13 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/schemas.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/system.sql +7 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/tables.sql +64 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/triggers.sql +10 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/sqlite/sql/views.sql +10 -0
- sqlspec/data_dictionary/dialects/sybase/__init__.py +31 -0
- sqlspec/data_dictionary/dialects/sybase/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/sybase/config.py +187 -0
- sqlspec/data_dictionary/dialects/sybase/sql/columns.sql +137 -0
- sqlspec/data_dictionary/dialects/sybase/sql/constraints.sql +85 -0
- sqlspec/data_dictionary/dialects/sybase/sql/foreign_keys.sql +81 -0
- sqlspec/data_dictionary/dialects/sybase/sql/indexes.sql +51 -0
- sqlspec/data_dictionary/dialects/sybase/sql/objects.sql +21 -0
- sqlspec/data_dictionary/dialects/sybase/sql/schemas.sql +16 -0
- sqlspec/data_dictionary/dialects/sybase/sql/tables.sql +46 -0
- sqlspec/data_dictionary/dialects/sybase/sql/version.sql +3 -0
- sqlspec/data_dictionary/dialects/sybase/sql/views.sql +19 -0
- sqlspec/data_dictionary/dialects/teradata/__init__.py +33 -0
- sqlspec/data_dictionary/dialects/teradata/config.cp315-win_amd64.pyd +0 -0
- sqlspec/data_dictionary/dialects/teradata/config.py +228 -0
- sqlspec/data_dictionary/dialects/teradata/sql/columns.sql +22 -0
- sqlspec/data_dictionary/dialects/teradata/sql/constraints.sql +19 -0
- sqlspec/data_dictionary/dialects/teradata/sql/foreign_keys.sql +9 -0
- sqlspec/data_dictionary/dialects/teradata/sql/indexes.sql +9 -0
- sqlspec/data_dictionary/dialects/teradata/sql/objects.sql +4 -0
- sqlspec/data_dictionary/dialects/teradata/sql/schemas.sql +9 -0
- sqlspec/data_dictionary/dialects/teradata/sql/tables.sql +22 -0
- sqlspec/data_dictionary/dialects/teradata/sql/version.sql +4 -0
- sqlspec/data_dictionary/dialects/teradata/sql/views.sql +4 -0
- sqlspec/dialects/__init__.py +44 -0
- sqlspec/dialects/db2/__init__.py +111 -0
- sqlspec/dialects/db2/_generators.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/db2/_generators.py +376 -0
- sqlspec/dialects/db2/_parsers.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/db2/_parsers.py +657 -0
- sqlspec/dialects/db2/_transforms.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/db2/_transforms.py +175 -0
- sqlspec/dialects/postgres/__init__.py +10 -0
- sqlspec/dialects/postgres/_generators.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/postgres/_generators.py +81 -0
- sqlspec/dialects/postgres/_operators.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/postgres/_operators.py +95 -0
- sqlspec/dialects/postgres/_paradedb.py +44 -0
- sqlspec/dialects/postgres/_pg_textsearch.py +38 -0
- sqlspec/dialects/postgres/_pgvector.py +36 -0
- sqlspec/dialects/spanner/__init__.py +69 -0
- sqlspec/dialects/spanner/_expressions.py +247 -0
- sqlspec/dialects/spanner/_generators.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/spanner/_generators.py +961 -0
- sqlspec/dialects/spanner/_parsers.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/spanner/_parsers.py +871 -0
- sqlspec/dialects/spanner/_spangres.py +43 -0
- sqlspec/dialects/spanner/_spanner.py +57 -0
- sqlspec/dialects/sybase/__init__.py +115 -0
- sqlspec/dialects/sybase/_generators.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/sybase/_generators.py +379 -0
- sqlspec/dialects/sybase/_parsers.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/sybase/_parsers.py +225 -0
- sqlspec/dialects/sybase/_transforms.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/sybase/_transforms.py +68 -0
- sqlspec/dialects/teradata/__init__.py +42 -0
- sqlspec/dialects/teradata/_generators.cp315-win_amd64.pyd +0 -0
- sqlspec/dialects/teradata/_generators.py +203 -0
- sqlspec/driver/__init__.py +151 -0
- sqlspec/driver/_async.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_async.py +3244 -0
- sqlspec/driver/_common.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_common.py +4765 -0
- sqlspec/driver/_deferred.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_deferred.py +232 -0
- sqlspec/driver/_exception_handler.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_exception_handler.py +224 -0
- sqlspec/driver/_routing.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_routing.py +2891 -0
- sqlspec/driver/_session.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_session.py +180 -0
- sqlspec/driver/_sql_helpers.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_sql_helpers.py +140 -0
- sqlspec/driver/_stream.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_stream.py +392 -0
- sqlspec/driver/_sync.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_sync.py +3107 -0
- sqlspec/driver/_tenant.cp315-win_amd64.pyd +0 -0
- sqlspec/driver/_tenant.py +326 -0
- sqlspec/exceptions.cp315-win_amd64.pyd +0 -0
- sqlspec/exceptions.py +568 -0
- sqlspec/extensions/__init__.py +3 -0
- sqlspec/extensions/adk/__init__.py +136 -0
- sqlspec/extensions/adk/_config_utils.py +306 -0
- sqlspec/extensions/adk/_table_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/adk/_table_utils.py +126 -0
- sqlspec/extensions/adk/_types.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/adk/_types.py +59 -0
- sqlspec/extensions/adk/artifact/__init__.py +18 -0
- sqlspec/extensions/adk/artifact/_types.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/adk/artifact/_types.py +41 -0
- sqlspec/extensions/adk/artifact/service.py +657 -0
- sqlspec/extensions/adk/artifact/store.py +444 -0
- sqlspec/extensions/adk/converters.py +230 -0
- sqlspec/extensions/adk/maintenance.py +262 -0
- sqlspec/extensions/adk/memory/__init__.py +36 -0
- sqlspec/extensions/adk/memory/_types.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/adk/memory/_types.py +48 -0
- sqlspec/extensions/adk/memory/converters.py +271 -0
- sqlspec/extensions/adk/memory/service.py +474 -0
- sqlspec/extensions/adk/memory/store.py +586 -0
- sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +181 -0
- sqlspec/extensions/adk/migrations/0002_create_mssql_python_memory.py +51 -0
- sqlspec/extensions/adk/migrations/__init__.py +3 -0
- sqlspec/extensions/adk/migrations/reconcile.py +282 -0
- sqlspec/extensions/adk/service.py +463 -0
- sqlspec/extensions/adk/store.py +1239 -0
- sqlspec/extensions/events/__init__.py +132 -0
- sqlspec/extensions/events/_buffer.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_buffer.py +38 -0
- sqlspec/extensions/events/_channel.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_channel.py +1144 -0
- sqlspec/extensions/events/_hints.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_hints.py +38 -0
- sqlspec/extensions/events/_models.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_models.py +22 -0
- sqlspec/extensions/events/_names.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_names.py +27 -0
- sqlspec/extensions/events/_payload.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_payload.py +139 -0
- sqlspec/extensions/events/_protocols.py +154 -0
- sqlspec/extensions/events/_queue.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/_queue.py +1147 -0
- sqlspec/extensions/events/_store.py +318 -0
- sqlspec/extensions/events/migrations/0001_create_event_queue.py +106 -0
- sqlspec/extensions/events/migrations/__init__.py +3 -0
- sqlspec/extensions/events/migrations/reconcile.py +145 -0
- sqlspec/extensions/events/primitives.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/events/primitives.py +91 -0
- sqlspec/extensions/fastapi/__init__.py +26 -0
- sqlspec/extensions/fastapi/extension.py +360 -0
- sqlspec/extensions/fastapi/providers.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/fastapi/providers.py +1091 -0
- sqlspec/extensions/flask/__init__.py +20 -0
- sqlspec/extensions/flask/_portal.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/flask/_portal.py +212 -0
- sqlspec/extensions/flask/_state.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/flask/_state.py +135 -0
- sqlspec/extensions/flask/_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/flask/_utils.py +171 -0
- sqlspec/extensions/flask/extension.py +1234 -0
- sqlspec/extensions/litestar/__init__.py +52 -0
- sqlspec/extensions/litestar/_tenant_resolution.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/litestar/_tenant_resolution.py +314 -0
- sqlspec/extensions/litestar/_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/litestar/_utils.py +222 -0
- sqlspec/extensions/litestar/channels.py +249 -0
- sqlspec/extensions/litestar/cli.py +100 -0
- sqlspec/extensions/litestar/config.py +5 -0
- sqlspec/extensions/litestar/handlers.py +796 -0
- sqlspec/extensions/litestar/migrations/0001_create_session_table.py +138 -0
- sqlspec/extensions/litestar/migrations/__init__.py +3 -0
- sqlspec/extensions/litestar/migrations/reconcile.py +132 -0
- sqlspec/extensions/litestar/plugin.py +2172 -0
- sqlspec/extensions/litestar/providers.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/litestar/providers.py +1239 -0
- sqlspec/extensions/litestar/store.py +613 -0
- sqlspec/extensions/litestar/tenant.py +292 -0
- sqlspec/extensions/otel/__init__.py +58 -0
- sqlspec/extensions/prometheus/__init__.py +5 -0
- sqlspec/extensions/prometheus/_observer.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/prometheus/_observer.py +152 -0
- sqlspec/extensions/sanic/__init__.py +28 -0
- sqlspec/extensions/sanic/_state.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/sanic/_state.py +102 -0
- sqlspec/extensions/sanic/_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/sanic/_utils.py +234 -0
- sqlspec/extensions/sanic/extension.py +1467 -0
- sqlspec/extensions/starlette/__init__.py +31 -0
- sqlspec/extensions/starlette/_state.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/starlette/_state.py +103 -0
- sqlspec/extensions/starlette/_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/extensions/starlette/_utils.py +267 -0
- sqlspec/extensions/starlette/extension.py +691 -0
- sqlspec/extensions/starlette/middleware.py +845 -0
- sqlspec/loader.cp315-win_amd64.pyd +0 -0
- sqlspec/loader.py +1733 -0
- sqlspec/migrations/__init__.py +104 -0
- sqlspec/migrations/_backup.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/_backup.py +36 -0
- sqlspec/migrations/base.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/base.py +1688 -0
- sqlspec/migrations/commands.py +4002 -0
- sqlspec/migrations/context.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/context.py +158 -0
- sqlspec/migrations/fix.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/fix.py +193 -0
- sqlspec/migrations/loaders.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/loaders.py +835 -0
- sqlspec/migrations/runner.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/runner.py +2144 -0
- sqlspec/migrations/schema.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/schema.py +1266 -0
- sqlspec/migrations/squash.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/squash.py +2452 -0
- sqlspec/migrations/templates.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/templates.py +310 -0
- sqlspec/migrations/tracker.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/tracker.py +1529 -0
- sqlspec/migrations/utils.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/utils.py +534 -0
- sqlspec/migrations/validation.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/validation.py +355 -0
- sqlspec/migrations/version.cp315-win_amd64.pyd +0 -0
- sqlspec/migrations/version.py +455 -0
- sqlspec/observability/__init__.py +122 -0
- sqlspec/observability/_common.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_common.py +307 -0
- sqlspec/observability/_config.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_config.py +362 -0
- sqlspec/observability/_diagnostics.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_diagnostics.py +75 -0
- sqlspec/observability/_dispatcher.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_dispatcher.py +320 -0
- sqlspec/observability/_formatters/__init__.py +13 -0
- sqlspec/observability/_formatters/_aws.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_formatters/_aws.py +90 -0
- sqlspec/observability/_formatters/_azure.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_formatters/_azure.py +84 -0
- sqlspec/observability/_formatters/_base.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_formatters/_base.py +40 -0
- sqlspec/observability/_formatters/_gcp.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_formatters/_gcp.py +119 -0
- sqlspec/observability/_formatting.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_formatting.py +76 -0
- sqlspec/observability/_observer.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_observer.py +445 -0
- sqlspec/observability/_runtime.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_runtime.py +740 -0
- sqlspec/observability/_sampling.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_sampling.py +169 -0
- sqlspec/observability/_spans.cp315-win_amd64.pyd +0 -0
- sqlspec/observability/_spans.py +212 -0
- sqlspec/protocols.py +1235 -0
- sqlspec/py.typed +0 -0
- sqlspec/service/__init__.py +5 -0
- sqlspec/service/_base.py +1051 -0
- sqlspec/service/_core.cp315-win_amd64.pyd +0 -0
- sqlspec/service/_core.py +625 -0
- sqlspec/storage/__init__.py +111 -0
- sqlspec/storage/_arrow_payload.py +802 -0
- sqlspec/storage/_arrow_stream.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/_arrow_stream.py +134 -0
- sqlspec/storage/_ingest.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/_ingest.py +810 -0
- sqlspec/storage/_paths.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/_paths.py +313 -0
- sqlspec/storage/_staging_sql.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/_staging_sql.py +695 -0
- sqlspec/storage/_utils.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/_utils.py +174 -0
- sqlspec/storage/backends/__init__.py +43 -0
- sqlspec/storage/backends/base.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/backends/base.py +399 -0
- sqlspec/storage/backends/fsspec.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/backends/fsspec.py +1390 -0
- sqlspec/storage/backends/local.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/backends/local.py +968 -0
- sqlspec/storage/backends/obstore.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/backends/obstore.py +1974 -0
- sqlspec/storage/errors.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/errors.py +127 -0
- sqlspec/storage/pipeline.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/pipeline.py +1270 -0
- sqlspec/storage/registry.cp315-win_amd64.pyd +0 -0
- sqlspec/storage/registry.py +318 -0
- sqlspec/typing.py +261 -0
- sqlspec/utils/__init__.py +9 -0
- sqlspec/utils/adapters.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/adapters.py +186 -0
- sqlspec/utils/arrow_helpers.py +2157 -0
- sqlspec/utils/config_tools.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/config_tools.py +712 -0
- sqlspec/utils/correlation.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/correlation.py +137 -0
- sqlspec/utils/deprecation.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/deprecation.py +222 -0
- sqlspec/utils/dispatch.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/dispatch.py +104 -0
- sqlspec/utils/env.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/env.py +437 -0
- sqlspec/utils/fixtures.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/fixtures.py +2470 -0
- sqlspec/utils/logging.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/logging.py +267 -0
- sqlspec/utils/module_loader.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/module_loader.py +399 -0
- sqlspec/utils/portal.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/portal.py +411 -0
- sqlspec/utils/routing.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/routing.py +645 -0
- sqlspec/utils/schema.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/schema.py +1050 -0
- sqlspec/utils/serializers/__init__.py +69 -0
- sqlspec/utils/serializers/_json.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/serializers/_json.py +525 -0
- sqlspec/utils/serializers/_numpy.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/serializers/_numpy.py +65 -0
- sqlspec/utils/serializers/_schema.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/serializers/_schema.py +340 -0
- sqlspec/utils/sync_tools.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/sync_tools.py +502 -0
- sqlspec/utils/tenant/__init__.py +71 -0
- sqlspec/utils/tenant/_context.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/tenant/_context.py +550 -0
- sqlspec/utils/tenant/_cursor.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/tenant/_cursor.py +43 -0
- sqlspec/utils/tenant/_mssql.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/tenant/_mssql.py +189 -0
- sqlspec/utils/tenant/_postgres.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/tenant/_postgres.py +142 -0
- sqlspec/utils/text.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/text.py +317 -0
- sqlspec/utils/type_converters.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/type_converters.py +220 -0
- sqlspec/utils/type_guards.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/type_guards.py +1505 -0
- sqlspec/utils/uuids.cp315-win_amd64.pyd +0 -0
- sqlspec/utils/uuids.py +263 -0
- sqlspec-0.72.0.dist-info/METADATA +228 -0
- sqlspec-0.72.0.dist-info/RECORD +1144 -0
- sqlspec-0.72.0.dist-info/WHEEL +4 -0
- sqlspec-0.72.0.dist-info/entry_points.txt +13 -0
- sqlspec-0.72.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,3209 @@
|
|
|
1
|
+
"""ADBC adapter compiled helpers."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import datetime as dt
|
|
5
|
+
import decimal
|
|
6
|
+
import importlib
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import tempfile
|
|
11
|
+
from collections.abc import Mapping, Sized
|
|
12
|
+
from functools import partial
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Final, cast
|
|
15
|
+
from urllib.parse import quote, urlsplit, urlunsplit
|
|
16
|
+
from uuid import UUID
|
|
17
|
+
|
|
18
|
+
import sqlglot
|
|
19
|
+
from mypy_extensions import mypyc_attr
|
|
20
|
+
from sqlglot import exp
|
|
21
|
+
from sqlglot.errors import ParseError
|
|
22
|
+
|
|
23
|
+
from sqlspec.adapters.adbc._typing import AdbcNativeError, AdbcStatusCode
|
|
24
|
+
from sqlspec.adapters.adbc.type_converter import ADBCOutputConverter, get_adbc_type_converter
|
|
25
|
+
from sqlspec.core.parameters._processor import type_coercion_dispatcher
|
|
26
|
+
from sqlspec.core.parameters._registry import build_statement_config_from_profile
|
|
27
|
+
from sqlspec.core.parameters._transformers import build_null_pruning_transform
|
|
28
|
+
from sqlspec.core.parameters._types import DriverParameterProfile, ParameterStyle
|
|
29
|
+
from sqlspec.core.result._base import DMLResult, SQLResult
|
|
30
|
+
from sqlspec.core.statement import StatementConfig
|
|
31
|
+
from sqlspec.data_dictionary._registry import normalize_dialect_name
|
|
32
|
+
from sqlspec.exceptions import (
|
|
33
|
+
CheckViolationError,
|
|
34
|
+
DatabaseConnectionError,
|
|
35
|
+
DataError,
|
|
36
|
+
DeadlockError,
|
|
37
|
+
ForeignKeyViolationError,
|
|
38
|
+
ImproperConfigurationError,
|
|
39
|
+
IntegrityError,
|
|
40
|
+
MissingDependencyError,
|
|
41
|
+
NotFoundError,
|
|
42
|
+
NotNullViolationError,
|
|
43
|
+
OperationalError,
|
|
44
|
+
OperationCancelledError,
|
|
45
|
+
PermissionDeniedError,
|
|
46
|
+
QueryTimeoutError,
|
|
47
|
+
ReadOnlyTransactionError,
|
|
48
|
+
SerializationConflictError,
|
|
49
|
+
SQLParsingError,
|
|
50
|
+
SQLSpecError,
|
|
51
|
+
UniqueViolationError,
|
|
52
|
+
_classify_timeout_or_cancellation,
|
|
53
|
+
map_sqlstate_to_exception,
|
|
54
|
+
with_cause,
|
|
55
|
+
)
|
|
56
|
+
from sqlspec.typing import PGVECTOR_INSTALLED, Empty, import_optional_attr
|
|
57
|
+
from sqlspec.utils.correlation import CorrelationContext
|
|
58
|
+
from sqlspec.utils.module_loader import import_optional, import_string
|
|
59
|
+
from sqlspec.utils.serializers._json import from_json, to_json
|
|
60
|
+
from sqlspec.utils.text import normalize_identifier, split_qualified_identifier
|
|
61
|
+
from sqlspec.utils.type_converters import build_uuid_coercions
|
|
62
|
+
from sqlspec.utils.type_guards import has_rowcount, has_sqlstate, resolve_row_format
|
|
63
|
+
from sqlspec.utils.uuids import uuid_from_string
|
|
64
|
+
|
|
65
|
+
if TYPE_CHECKING:
|
|
66
|
+
from collections.abc import Callable
|
|
67
|
+
|
|
68
|
+
from sqlspec.core.cache import CachedQuery
|
|
69
|
+
from sqlspec.core.statement import SQL
|
|
70
|
+
from sqlspec.utils.dispatch import TypeDispatcher
|
|
71
|
+
|
|
72
|
+
__all__ = (
|
|
73
|
+
"RECONCILE_ADBC_DIALECTS",
|
|
74
|
+
"apply_driver_features",
|
|
75
|
+
"build_connection_config",
|
|
76
|
+
"build_profile",
|
|
77
|
+
"cleanup_duckdb_profile_path",
|
|
78
|
+
"collect_rows",
|
|
79
|
+
"configure_adbc_duckdb_profiling",
|
|
80
|
+
"create_duckdb_profile_path",
|
|
81
|
+
"create_mapped_exception",
|
|
82
|
+
"create_teradata_mapped_exception",
|
|
83
|
+
"detect_dialect",
|
|
84
|
+
"detect_postgres_extensions",
|
|
85
|
+
"driver_from_uri",
|
|
86
|
+
"driver_kind_from_driver_name",
|
|
87
|
+
"driver_kind_from_uri",
|
|
88
|
+
"driver_profile",
|
|
89
|
+
"enforce_strict_type_coercion",
|
|
90
|
+
"execute_cache_hit",
|
|
91
|
+
"get_statement_config",
|
|
92
|
+
"handle_postgres_rollback",
|
|
93
|
+
"is_postgres_dialect",
|
|
94
|
+
"is_shared_object_driver",
|
|
95
|
+
"is_sqlite_reconcile_target",
|
|
96
|
+
"normalize_column_names",
|
|
97
|
+
"normalize_connection_aliases",
|
|
98
|
+
"normalize_driver_path",
|
|
99
|
+
"normalize_postgres_empty_parameters",
|
|
100
|
+
"normalize_script_rowcount",
|
|
101
|
+
"prepare_batch_with_casts",
|
|
102
|
+
"prepare_parameters_with_casts",
|
|
103
|
+
"prepare_postgres_parameters",
|
|
104
|
+
"prepare_postgres_uuid_bindings",
|
|
105
|
+
"read_duckdb_profile_json",
|
|
106
|
+
"resolve_column_names",
|
|
107
|
+
"resolve_dialect_from_config",
|
|
108
|
+
"resolve_dialect_from_driver_path",
|
|
109
|
+
"resolve_dialect_name",
|
|
110
|
+
"resolve_driver_connect_func",
|
|
111
|
+
"resolve_driver_name",
|
|
112
|
+
"resolve_driver_name_from_config",
|
|
113
|
+
"resolve_many_rowcount",
|
|
114
|
+
"resolve_parameter_casts",
|
|
115
|
+
"resolve_reconcile_adbc_dialect",
|
|
116
|
+
"resolve_rowcount",
|
|
117
|
+
"split_db2_table_name",
|
|
118
|
+
"split_teradata_table_name",
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
_MAX_TCP_PORT: Final = 65535
|
|
122
|
+
_MIN_BRACED_VALUE_LEN: Final = 2
|
|
123
|
+
_FLIGHTSQL_HEADER_KEY_PATTERN: Final[re.Pattern[str]] = re.compile(r"\A[A-Za-z0-9_-]+\Z")
|
|
124
|
+
_URI_HOST_FORBIDDEN_CHARS: Final[frozenset[str]] = frozenset({"/", "?", "#", "@", " ", "\t", "\r", "\n", "\x00"})
|
|
125
|
+
COLUMN_CACHE_MAX_SIZE: int = 256
|
|
126
|
+
RECONCILE_ADBC_DIALECTS: Final = frozenset({
|
|
127
|
+
"bigquery",
|
|
128
|
+
"db2",
|
|
129
|
+
"duckdb",
|
|
130
|
+
"mssql",
|
|
131
|
+
"oracle",
|
|
132
|
+
"postgres",
|
|
133
|
+
"snowflake",
|
|
134
|
+
"teradata",
|
|
135
|
+
"sqlite",
|
|
136
|
+
})
|
|
137
|
+
_IMPLICIT_UPPER_COLUMN_PATTERN: Final[re.Pattern[str]] = re.compile(r"\A(?!\d)(?:[A-Z0-9_]+)\Z")
|
|
138
|
+
_UUID_TYPES: Final[tuple[type[Any], ...]] = tuple(build_uuid_coercions())
|
|
139
|
+
NoneType: Final = type(None)
|
|
140
|
+
_STRICT_COERCION_ALLOWED_TYPES: Final[tuple[type[Any], ...]] = (
|
|
141
|
+
NoneType,
|
|
142
|
+
bool,
|
|
143
|
+
int,
|
|
144
|
+
float,
|
|
145
|
+
str,
|
|
146
|
+
bytes,
|
|
147
|
+
bytearray,
|
|
148
|
+
memoryview,
|
|
149
|
+
decimal.Decimal,
|
|
150
|
+
dt.date,
|
|
151
|
+
dt.time,
|
|
152
|
+
dt.datetime,
|
|
153
|
+
dt.timedelta,
|
|
154
|
+
UUID,
|
|
155
|
+
list,
|
|
156
|
+
tuple,
|
|
157
|
+
dict,
|
|
158
|
+
*_UUID_TYPES,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
DIALECT_PATTERNS: "dict[str, tuple[str, ...]]" = {
|
|
162
|
+
"postgres": ("postgres", "postgresql"),
|
|
163
|
+
"bigquery": ("bigquery",),
|
|
164
|
+
"teradata": ("teradata", "vantage"),
|
|
165
|
+
"sqlite": ("sqlite", "flight", "flightsql"),
|
|
166
|
+
"duckdb": ("duckdb", "gizmosql", "gizmo", "quack"),
|
|
167
|
+
"mysql": ("mysql",),
|
|
168
|
+
"snowflake": ("snowflake",),
|
|
169
|
+
"oracle": ("oracle",),
|
|
170
|
+
"db2": ("db2", "ibm db2"),
|
|
171
|
+
"mssql": ("mssql", "sql server", "sqlserver", "microsoft sql"),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
DIALECT_PARAMETER_STYLES: "dict[str, tuple[ParameterStyle, list[ParameterStyle]]]" = {
|
|
176
|
+
"postgres": (ParameterStyle.NUMERIC, [ParameterStyle.NUMERIC]),
|
|
177
|
+
"postgresql": (ParameterStyle.NUMERIC, [ParameterStyle.NUMERIC]),
|
|
178
|
+
"bigquery": (ParameterStyle.NAMED_AT, [ParameterStyle.NAMED_AT]),
|
|
179
|
+
"sqlite": (ParameterStyle.QMARK, [ParameterStyle.QMARK]),
|
|
180
|
+
"duckdb": (
|
|
181
|
+
ParameterStyle.QMARK,
|
|
182
|
+
[ParameterStyle.QMARK, ParameterStyle.NUMERIC, ParameterStyle.NAMED_DOLLAR, ParameterStyle.NAMED_COLON],
|
|
183
|
+
),
|
|
184
|
+
"mysql": (ParameterStyle.POSITIONAL_PYFORMAT, [ParameterStyle.POSITIONAL_PYFORMAT, ParameterStyle.NAMED_PYFORMAT]),
|
|
185
|
+
"snowflake": (
|
|
186
|
+
ParameterStyle.QMARK,
|
|
187
|
+
[ParameterStyle.QMARK, ParameterStyle.NAMED_COLON, ParameterStyle.POSITIONAL_COLON],
|
|
188
|
+
),
|
|
189
|
+
"oracle": (
|
|
190
|
+
ParameterStyle.POSITIONAL_COLON,
|
|
191
|
+
[ParameterStyle.POSITIONAL_COLON, ParameterStyle.NAMED_COLON, ParameterStyle.QMARK],
|
|
192
|
+
),
|
|
193
|
+
"db2": (ParameterStyle.QMARK, [ParameterStyle.QMARK, ParameterStyle.NAMED_COLON]),
|
|
194
|
+
"mssql": (ParameterStyle.QMARK, [ParameterStyle.QMARK, ParameterStyle.NAMED_COLON, ParameterStyle.NAMED_AT]),
|
|
195
|
+
"tsql": (ParameterStyle.QMARK, [ParameterStyle.QMARK, ParameterStyle.NAMED_COLON, ParameterStyle.NAMED_AT]),
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
_DRIVER_ALIASES: "dict[str, str]" = {
|
|
199
|
+
"sqlite": "adbc_driver_sqlite.dbapi.connect",
|
|
200
|
+
"sqlite3": "adbc_driver_sqlite.dbapi.connect",
|
|
201
|
+
"duckdb": "adbc_driver_duckdb.dbapi.connect",
|
|
202
|
+
"postgres": "adbc_driver_postgresql.dbapi.connect",
|
|
203
|
+
"postgresql": "adbc_driver_postgresql.dbapi.connect",
|
|
204
|
+
"pg": "adbc_driver_postgresql.dbapi.connect",
|
|
205
|
+
"snowflake": "adbc_driver_snowflake.dbapi.connect",
|
|
206
|
+
"sf": "adbc_driver_snowflake.dbapi.connect",
|
|
207
|
+
"teradata": "adbc_driver_teradata.dbapi.connect",
|
|
208
|
+
"vantage": "adbc_driver_teradata.dbapi.connect",
|
|
209
|
+
"adbc-driver-flightsql": "adbc_driver_flightsql.dbapi.connect",
|
|
210
|
+
"bigquery": "adbc_driver_bigquery.dbapi.connect",
|
|
211
|
+
"bq": "adbc_driver_bigquery.dbapi.connect",
|
|
212
|
+
"flightsql": "adbc_driver_flightsql.dbapi.connect",
|
|
213
|
+
"grpc": "adbc_driver_flightsql.dbapi.connect",
|
|
214
|
+
"gizmosql": "adbc_driver_flightsql.dbapi.connect",
|
|
215
|
+
"gizmo": "adbc_driver_flightsql.dbapi.connect",
|
|
216
|
+
"oracle": "adbc_driver_oracle.dbapi.connect",
|
|
217
|
+
"oracledb": "adbc_driver_oracle.dbapi.connect",
|
|
218
|
+
"db2": "adbc_driver_db2.dbapi.connect",
|
|
219
|
+
"ibmdb2": "adbc_driver_db2.dbapi.connect",
|
|
220
|
+
"ibm_db": "adbc_driver_db2.dbapi.connect",
|
|
221
|
+
"quack": "adbc_driver_quack.dbapi.connect",
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
_URI_PREFIX_DRIVER: "tuple[tuple[str, str], ...]" = (
|
|
225
|
+
("postgresql://", "adbc_driver_postgresql.dbapi.connect"),
|
|
226
|
+
("postgres://", "adbc_driver_postgresql.dbapi.connect"),
|
|
227
|
+
("sqlite://", "adbc_driver_sqlite.dbapi.connect"),
|
|
228
|
+
("duckdb://", "adbc_driver_duckdb.dbapi.connect"),
|
|
229
|
+
("grpc://", "adbc_driver_flightsql.dbapi.connect"),
|
|
230
|
+
("grpc+tls://", "adbc_driver_flightsql.dbapi.connect"),
|
|
231
|
+
("gizmosql://", "adbc_driver_flightsql.dbapi.connect"),
|
|
232
|
+
("gizmo://", "adbc_driver_flightsql.dbapi.connect"),
|
|
233
|
+
("teradata://", "adbc_driver_teradata.dbapi.connect"),
|
|
234
|
+
("snowflake://", "adbc_driver_snowflake.dbapi.connect"),
|
|
235
|
+
("bigquery://", "adbc_driver_bigquery.dbapi.connect"),
|
|
236
|
+
("oracle://", "adbc_driver_oracle.dbapi.connect"),
|
|
237
|
+
("db2://", "adbc_driver_db2.dbapi.connect"),
|
|
238
|
+
("quack://", "adbc_driver_quack.dbapi.connect"),
|
|
239
|
+
("quack+tls://", "adbc_driver_quack.dbapi.connect"),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
_DRIVER_PATH_KEYWORDS_TO_DIALECT: "tuple[tuple[str, str], ...]" = (
|
|
243
|
+
("postgresql", "postgres"),
|
|
244
|
+
("sqlite", "sqlite"),
|
|
245
|
+
("duckdb", "duckdb"),
|
|
246
|
+
("bigquery", "bigquery"),
|
|
247
|
+
("teradata", "teradata"),
|
|
248
|
+
("vantage", "teradata"),
|
|
249
|
+
("snowflake", "snowflake"),
|
|
250
|
+
("gizmosql", "duckdb"),
|
|
251
|
+
("quack", "duckdb"),
|
|
252
|
+
("oracle", "oracle"),
|
|
253
|
+
("db2", "db2"),
|
|
254
|
+
("mssql", "mssql"),
|
|
255
|
+
("sqlserver", "mssql"),
|
|
256
|
+
("flightsql", "sqlite"),
|
|
257
|
+
("grpc", "sqlite"),
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
_BIGQUERY_DB_KWARGS_OPTIONS: "tuple[tuple[str, str], ...]" = (
|
|
261
|
+
("project_id", "adbc.bigquery.sql.project_id"),
|
|
262
|
+
("dataset_id", "adbc.bigquery.sql.dataset_id"),
|
|
263
|
+
("token", "adbc.bigquery.sql.auth.refresh_token"),
|
|
264
|
+
)
|
|
265
|
+
_SHARED_OBJECT_SUFFIXES: "tuple[str, ...]" = (".so", ".dylib", ".dll")
|
|
266
|
+
_DRIVER_MANAGER_CONNECT: Final[str] = "adbc_driver_manager.dbapi.connect"
|
|
267
|
+
_GIZMOSQL_NATIVE_CONNECT: Final[str] = "adbc_driver_gizmosql.dbapi.connect"
|
|
268
|
+
_FLIGHTSQL_CONNECT: Final[str] = "adbc_driver_flightsql.dbapi.connect"
|
|
269
|
+
_MSSQL_NATIVE_CONNECT: Final[str] = "adbc_driver_mssql.dbapi.connect"
|
|
270
|
+
_QUACK_AUTH_KEY: Final[str] = "adbc.quack.token"
|
|
271
|
+
_GIZMOSQL_AUTH_TYPE_KEY: Final[str] = "adbc.gizmosql.auth_type"
|
|
272
|
+
_FLIGHTSQL_DB_KWARGS_FIELDS: "tuple[str, ...]" = ("username", "password")
|
|
273
|
+
_FLIGHTSQL_TLS_SKIP_VERIFY_KEY: Final[str] = "adbc.flight.sql.client_option.tls_skip_verify"
|
|
274
|
+
_FLIGHTSQL_AUTHORIZATION_HEADER_KEY: Final[str] = "adbc.flight.sql.authorization_header"
|
|
275
|
+
_FLIGHTSQL_WITH_MAX_MSG_SIZE_KEY: Final[str] = "adbc.flight.sql.client_option.with_max_msg_size"
|
|
276
|
+
_FLIGHTSQL_TIMEOUT_QUERY_KEY: Final[str] = "adbc.flight.sql.rpc.timeout_seconds.query"
|
|
277
|
+
_FLIGHTSQL_TIMEOUT_FETCH_KEY: Final[str] = "adbc.flight.sql.rpc.timeout_seconds.fetch"
|
|
278
|
+
_FLIGHTSQL_TLS_ROOT_CERTS_KEY: Final[str] = "adbc.flight.sql.client_option.tls_root_certs"
|
|
279
|
+
_FLIGHTSQL_MTLS_CERT_CHAIN_KEY: Final[str] = "adbc.flight.sql.client_option.mtls_cert_chain"
|
|
280
|
+
_FLIGHTSQL_MTLS_PRIVATE_KEY_KEY: Final[str] = "adbc.flight.sql.client_option.mtls_private_key"
|
|
281
|
+
_FLIGHTSQL_WITH_COOKIE_MIDDLEWARE_KEY: Final[str] = "adbc.flight.sql.rpc.with_cookie_middleware"
|
|
282
|
+
_FLIGHTSQL_RPC_CALL_HEADER_PREFIX: Final[str] = "adbc.flight.sql.rpc.call_header."
|
|
283
|
+
_SQLSTATE_CLASS_CODE_LEN = 2
|
|
284
|
+
_SQLSTATE_DESCRIPTIONS: dict[str, str] = {
|
|
285
|
+
"23": "integrity constraint violation",
|
|
286
|
+
"40": "transaction error",
|
|
287
|
+
"42": "SQL syntax error",
|
|
288
|
+
"08": "connection error",
|
|
289
|
+
"22": "data error",
|
|
290
|
+
"28": "authorization error",
|
|
291
|
+
"57": "operational error",
|
|
292
|
+
"02": "no data",
|
|
293
|
+
}
|
|
294
|
+
_ORA_CODE_PATTERN: Final[re.Pattern[str]] = re.compile(r"\bORA-(\d{5})\b", re.IGNORECASE)
|
|
295
|
+
_ORA_INTEGRITY_START: Final[int] = 2290
|
|
296
|
+
_ORA_INTEGRITY_END: Final[int] = 2300
|
|
297
|
+
_ORA_PARSING_START: Final[int] = 900
|
|
298
|
+
_ORA_PARSING_END: Final[int] = 1000
|
|
299
|
+
_ORA_ERROR_CODE_MAP: Final[dict[int, tuple[type[SQLSpecError], str]]] = {
|
|
300
|
+
1: (UniqueViolationError, "unique constraint violation"),
|
|
301
|
+
60: (DeadlockError, "deadlock detected"),
|
|
302
|
+
900: (SQLParsingError, "invalid SQL statement"),
|
|
303
|
+
904: (SQLParsingError, "invalid identifier"),
|
|
304
|
+
907: (SQLParsingError, "missing right parenthesis"),
|
|
305
|
+
923: (SQLParsingError, "FROM keyword not found where expected"),
|
|
306
|
+
933: (SQLParsingError, "SQL command not properly ended"),
|
|
307
|
+
936: (SQLParsingError, "missing expression"),
|
|
308
|
+
942: (SQLParsingError, "table or view does not exist"),
|
|
309
|
+
1013: (QueryTimeoutError, "user requested cancel of current operation"),
|
|
310
|
+
1017: (PermissionDeniedError, "invalid username/password"),
|
|
311
|
+
1031: (PermissionDeniedError, "insufficient privileges"),
|
|
312
|
+
1400: (NotNullViolationError, "not-null constraint violation"),
|
|
313
|
+
1407: (NotNullViolationError, "not-null constraint violation"),
|
|
314
|
+
1438: (DataError, "numeric precision overflow"),
|
|
315
|
+
1722: (DataError, "invalid number"),
|
|
316
|
+
1843: (DataError, "not a valid month"),
|
|
317
|
+
1858: (DataError, "invalid character"),
|
|
318
|
+
1861: (DataError, "literal does not match format string"),
|
|
319
|
+
2290: (CheckViolationError, "check constraint violation"),
|
|
320
|
+
2291: (ForeignKeyViolationError, "foreign key constraint violation"),
|
|
321
|
+
2292: (ForeignKeyViolationError, "foreign key constraint violation"),
|
|
322
|
+
3113: (DatabaseConnectionError, "end-of-file on communication channel"),
|
|
323
|
+
3114: (DatabaseConnectionError, "not connected to ORACLE"),
|
|
324
|
+
3135: (DatabaseConnectionError, "connection lost contact"),
|
|
325
|
+
8177: (SerializationConflictError, "cannot serialize access"),
|
|
326
|
+
12154: (DatabaseConnectionError, "TNS resolution failed"),
|
|
327
|
+
12170: (QueryTimeoutError, "connect timeout"),
|
|
328
|
+
12505: (DatabaseConnectionError, "listener rejected"),
|
|
329
|
+
12514: (DatabaseConnectionError, "service not known"),
|
|
330
|
+
12541: (DatabaseConnectionError, "no listener"),
|
|
331
|
+
12899: (DataError, "value too large for column"),
|
|
332
|
+
}
|
|
333
|
+
_DB2_SQLSTATE_PATTERN: Final[re.Pattern[str]] = re.compile(
|
|
334
|
+
r"(?:SQLSTATE[=:\s]+|state[:=\s]+)([0-9A-Z]{5})\b", re.IGNORECASE
|
|
335
|
+
)
|
|
336
|
+
_DB2_SQLCODE_PATTERN: Final[re.Pattern[str]] = re.compile(r"\bSQL(?:CODE[=:\s]*)?(-?\d{3,5})[NCW]?\b", re.IGNORECASE)
|
|
337
|
+
_DB2_REASON_CODE_PATTERN: Final[re.Pattern[str]] = re.compile(r'Reason code\s*"?(\d+)"?', re.IGNORECASE)
|
|
338
|
+
_DB2_LOCK_TIMEOUT_REASON_CODE: Final[int] = 68
|
|
339
|
+
_DB2_UNDEFINED_OBJECT_CODE: Final[int] = 204
|
|
340
|
+
_DB2_ROLLBACK_SQLSTATES: Final[frozenset[str]] = frozenset({"40001", "57033"})
|
|
341
|
+
_DB2_ROLLBACK_SQLCODES: Final[frozenset[int]] = frozenset({911, 913})
|
|
342
|
+
_DB2_SQLCODE_MAP: Final[dict[int, tuple[type[SQLSpecError], str]]] = {
|
|
343
|
+
104: (SQLParsingError, "sql syntax error"),
|
|
344
|
+
204: (SQLParsingError, "undefined object"),
|
|
345
|
+
302: (DataError, "numeric or string value out of range"),
|
|
346
|
+
407: (NotNullViolationError, "not-null constraint violation"),
|
|
347
|
+
433: (DataError, "value is too long"),
|
|
348
|
+
530: (ForeignKeyViolationError, "foreign key constraint violation"),
|
|
349
|
+
532: (ForeignKeyViolationError, "foreign key constraint violation"),
|
|
350
|
+
545: (CheckViolationError, "check constraint violation"),
|
|
351
|
+
551: (PermissionDeniedError, "permission denied"),
|
|
352
|
+
552: (PermissionDeniedError, "authorization error"),
|
|
353
|
+
803: (UniqueViolationError, "unique constraint violation"),
|
|
354
|
+
900: (DatabaseConnectionError, "connection does not exist or was severed"),
|
|
355
|
+
952: (QueryTimeoutError, "statement execution interrupted or timed out"),
|
|
356
|
+
1042: (DatabaseConnectionError, "unexpected system error occurred"),
|
|
357
|
+
30081: (DatabaseConnectionError, "communication failure"),
|
|
358
|
+
}
|
|
359
|
+
_MSSQL_MSG_NUMBER_PATTERN: Final[re.Pattern[str]] = re.compile(r"\b(?:Msg|error|number)\s+(\d{3,5})\b", re.IGNORECASE)
|
|
360
|
+
_MSSQL_CONSTRAINT_ERROR_CODE: Final[int] = 547
|
|
361
|
+
_MSSQL_ERROR_CODE_MAP: Final[dict[int, tuple[type[SQLSpecError], str]]] = {
|
|
362
|
+
53: (DatabaseConnectionError, "could not open connection to SQL Server"),
|
|
363
|
+
102: (SQLParsingError, "incorrect syntax"),
|
|
364
|
+
105: (SQLParsingError, "unclosed quotation mark"),
|
|
365
|
+
156: (SQLParsingError, "incorrect syntax near keyword"),
|
|
366
|
+
207: (SQLParsingError, "invalid column name"),
|
|
367
|
+
208: (SQLParsingError, "invalid object name"),
|
|
368
|
+
229: (PermissionDeniedError, "permission denied on object"),
|
|
369
|
+
230: (PermissionDeniedError, "permission denied on column"),
|
|
370
|
+
241: (DataError, "conversion failed when converting date/time"),
|
|
371
|
+
242: (DataError, "datetime data type conversion out-of-range"),
|
|
372
|
+
245: (DataError, "conversion failed when converting varchar to int"),
|
|
373
|
+
262: (PermissionDeniedError, "permission denied in database"),
|
|
374
|
+
515: (NotNullViolationError, "cannot insert the value NULL into column"),
|
|
375
|
+
1205: (DeadlockError, "transaction was deadlocked on lock resources"),
|
|
376
|
+
1222: (QueryTimeoutError, "lock request time out period exceeded"),
|
|
377
|
+
2601: (UniqueViolationError, "cannot insert duplicate key row"),
|
|
378
|
+
2627: (UniqueViolationError, "violation of unique or primary key constraint"),
|
|
379
|
+
2628: (DataError, "string or binary data would be truncated"),
|
|
380
|
+
3960: (SerializationConflictError, "snapshot isolation transaction aborted due to update conflict"),
|
|
381
|
+
4060: (DatabaseConnectionError, "cannot open database requested by the login"),
|
|
382
|
+
8114: (DataError, "error converting data type"),
|
|
383
|
+
8115: (DataError, "arithmetic overflow error"),
|
|
384
|
+
8152: (DataError, "string or binary data would be truncated"),
|
|
385
|
+
18456: (PermissionDeniedError, "login failed for user"),
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def detect_dialect(connection: Any, logger: Any | None = None, *, fallback_dialect: "str | None" = None) -> str:
|
|
390
|
+
"""Detect database dialect from ADBC driver information.
|
|
391
|
+
|
|
392
|
+
Args:
|
|
393
|
+
connection: ADBC connection with driver metadata.
|
|
394
|
+
logger: Optional logger for diagnostics.
|
|
395
|
+
fallback_dialect: Pre-resolved dialect from config. Used when introspection
|
|
396
|
+
yields no match, before defaulting to ``postgres``.
|
|
397
|
+
|
|
398
|
+
Returns:
|
|
399
|
+
Detected dialect name, defaulting to ``postgres``.
|
|
400
|
+
"""
|
|
401
|
+
try:
|
|
402
|
+
driver_info = _get_adbc_driver_info(connection)
|
|
403
|
+
vendor_name = driver_info.get("vendor_name", "").lower()
|
|
404
|
+
vendor_version = driver_info.get("vendor_version", "").lower()
|
|
405
|
+
driver_name = driver_info.get("driver_name", "").lower()
|
|
406
|
+
|
|
407
|
+
if "gizmosql" in vendor_name or "gizmosql" in vendor_version:
|
|
408
|
+
if "sqlite" in vendor_version:
|
|
409
|
+
return "sqlite"
|
|
410
|
+
if "duckdb" in vendor_version:
|
|
411
|
+
return "duckdb"
|
|
412
|
+
return "duckdb"
|
|
413
|
+
|
|
414
|
+
for dialect, patterns in DIALECT_PATTERNS.items():
|
|
415
|
+
for pattern in patterns:
|
|
416
|
+
if pattern in vendor_name or pattern in driver_name:
|
|
417
|
+
if logger is not None:
|
|
418
|
+
logger.debug("Dialect detected: %s (from %s/%s)", dialect, vendor_name, driver_name)
|
|
419
|
+
return dialect
|
|
420
|
+
except Exception as exc:
|
|
421
|
+
if logger is not None:
|
|
422
|
+
logger.debug("Dialect detection failed: %s", exc)
|
|
423
|
+
|
|
424
|
+
if fallback_dialect:
|
|
425
|
+
if logger is not None:
|
|
426
|
+
logger.debug("Dialect from connection_config: %s (introspection yielded no match)", fallback_dialect)
|
|
427
|
+
return fallback_dialect
|
|
428
|
+
|
|
429
|
+
if logger is not None:
|
|
430
|
+
logger.warning("Could not determine dialect from driver info. Defaulting to 'postgres'.")
|
|
431
|
+
return "postgres"
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def detect_postgres_extensions(
|
|
435
|
+
connection: Any, *, enable_pgvector: bool = False, enable_paradedb: bool = False, enable_pg_textsearch: bool = False
|
|
436
|
+
) -> "tuple[bool, bool, bool]":
|
|
437
|
+
"""Detect pgvector, paradedb, and pg_textsearch extensions on a postgres connection.
|
|
438
|
+
|
|
439
|
+
Queries ``pg_extension`` for the ``vector``, ``pg_search``, and ``pg_textsearch`` extensions.
|
|
440
|
+
Returns cached-friendly booleans suitable for storing on the config instance.
|
|
441
|
+
|
|
442
|
+
Args:
|
|
443
|
+
connection: ADBC connection to a PostgreSQL database.
|
|
444
|
+
enable_pgvector: Whether to check for the pgvector extension.
|
|
445
|
+
enable_paradedb: Whether to check for the pg_search extension.
|
|
446
|
+
enable_pg_textsearch: Whether to check for the pg_textsearch extension.
|
|
447
|
+
|
|
448
|
+
Returns:
|
|
449
|
+
Tuple of ``(pgvector_available, paradedb_available, pg_textsearch_available)``.
|
|
450
|
+
"""
|
|
451
|
+
extensions: list[str] = []
|
|
452
|
+
if enable_pgvector:
|
|
453
|
+
extensions.append("vector")
|
|
454
|
+
if enable_paradedb:
|
|
455
|
+
extensions.append("pg_search")
|
|
456
|
+
if enable_pg_textsearch:
|
|
457
|
+
extensions.append("pg_textsearch")
|
|
458
|
+
|
|
459
|
+
if not extensions:
|
|
460
|
+
return False, False, False
|
|
461
|
+
|
|
462
|
+
try:
|
|
463
|
+
cursor = connection.cursor()
|
|
464
|
+
try:
|
|
465
|
+
cursor.execute("SELECT extname FROM pg_extension WHERE extname = ANY($1::text[])", [extensions])
|
|
466
|
+
rows = cursor.fetchall()
|
|
467
|
+
detected: set[str] = {row[0] for row in rows} if rows else set()
|
|
468
|
+
return ("vector" in detected, "pg_search" in detected, "pg_textsearch" in detected)
|
|
469
|
+
finally:
|
|
470
|
+
cursor.close()
|
|
471
|
+
except Exception:
|
|
472
|
+
return False, False, False
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def is_shared_object_driver(driver_name: str) -> bool:
|
|
476
|
+
"""Return whether a driver name points at a shared library rather than a module.
|
|
477
|
+
|
|
478
|
+
Args:
|
|
479
|
+
driver_name: Raw driver name or path from configuration.
|
|
480
|
+
|
|
481
|
+
Returns:
|
|
482
|
+
True when the value is a filesystem path to a driver shared object.
|
|
483
|
+
"""
|
|
484
|
+
stripped = driver_name.strip()
|
|
485
|
+
if not stripped:
|
|
486
|
+
return False
|
|
487
|
+
lowered = stripped.lower()
|
|
488
|
+
return lowered.endswith(_SHARED_OBJECT_SUFFIXES) or "/" in stripped or "\\" in stripped
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def normalize_driver_path(driver_name: str) -> str:
|
|
492
|
+
"""Normalize a driver name to an importable connect function path."""
|
|
493
|
+
stripped = driver_name.strip()
|
|
494
|
+
if is_shared_object_driver(stripped):
|
|
495
|
+
return _DRIVER_MANAGER_CONNECT
|
|
496
|
+
if stripped.endswith(".dbapi.connect"):
|
|
497
|
+
return stripped
|
|
498
|
+
if stripped.endswith(".dbapi"):
|
|
499
|
+
return f"{stripped}.connect"
|
|
500
|
+
if "." in stripped:
|
|
501
|
+
return stripped
|
|
502
|
+
return f"{stripped}.dbapi.connect"
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def driver_from_uri(uri: str) -> "str | None":
|
|
506
|
+
"""Resolve a default driver connect path from a URI."""
|
|
507
|
+
lowered = uri.lower()
|
|
508
|
+
if lowered.startswith("teradata://"):
|
|
509
|
+
return _resolve_teradata_driver_connect()
|
|
510
|
+
if lowered.startswith(("gizmosql://", "gizmo://")):
|
|
511
|
+
return _resolve_gizmosql_driver_connect()
|
|
512
|
+
if lowered.startswith(("mssql://", "sqlserver://")):
|
|
513
|
+
return _resolve_mssql_driver_connect()
|
|
514
|
+
for prefix, driver_path in _URI_PREFIX_DRIVER:
|
|
515
|
+
if lowered.startswith(prefix):
|
|
516
|
+
return driver_path
|
|
517
|
+
if _parse_db2_cli_dsn(uri) is not None:
|
|
518
|
+
return "adbc_driver_db2.dbapi.connect"
|
|
519
|
+
return None
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def driver_kind_from_driver_name(driver_name: str) -> "str | None":
|
|
523
|
+
"""Return a canonical driver kind based on driver name content."""
|
|
524
|
+
lowered_name = driver_name.lower()
|
|
525
|
+
if is_shared_object_driver(driver_name):
|
|
526
|
+
lowered_name = lowered_name.replace("\\", "/").rsplit("/", 1)[-1]
|
|
527
|
+
if "teradata" in lowered_name or "vantage" in lowered_name:
|
|
528
|
+
return "teradata"
|
|
529
|
+
if lowered_name in {"gizmosql", "gizmo"} or "gizmosql" in lowered_name:
|
|
530
|
+
return "gizmosql"
|
|
531
|
+
if lowered_name in {"mssql", "sqlserver", "tsql"} or "mssql" in lowered_name or "sqlserver" in lowered_name:
|
|
532
|
+
return "mssql"
|
|
533
|
+
if lowered_name in {"oracle", "oracledb"} or "oracle" in lowered_name:
|
|
534
|
+
return "oracle"
|
|
535
|
+
if lowered_name in {"db2", "ibmdb2", "ibm_db"} or "db2" in lowered_name:
|
|
536
|
+
return "db2"
|
|
537
|
+
if lowered_name == "quack" or "quack" in lowered_name:
|
|
538
|
+
return "quack"
|
|
539
|
+
resolved = _DRIVER_ALIASES.get(lowered_name, lowered_name)
|
|
540
|
+
lowered = resolved.lower()
|
|
541
|
+
for keyword, _dialect in _DRIVER_PATH_KEYWORDS_TO_DIALECT:
|
|
542
|
+
if keyword in lowered:
|
|
543
|
+
return keyword
|
|
544
|
+
return None
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def driver_kind_from_uri(uri: str) -> "str | None":
|
|
548
|
+
"""Return a canonical driver kind based on URI scheme."""
|
|
549
|
+
lowered = uri.lower()
|
|
550
|
+
if lowered.startswith("teradata://"):
|
|
551
|
+
return "teradata"
|
|
552
|
+
if lowered.startswith(("gizmosql://", "gizmo://")):
|
|
553
|
+
return "gizmosql"
|
|
554
|
+
if lowered.startswith(("mssql://", "sqlserver://")):
|
|
555
|
+
return "mssql"
|
|
556
|
+
if lowered.startswith(("quack://", "quack+tls://")):
|
|
557
|
+
return "quack"
|
|
558
|
+
if lowered.startswith("oracle://"):
|
|
559
|
+
return "oracle"
|
|
560
|
+
if lowered.startswith("db2://") or _parse_db2_cli_dsn(uri) is not None:
|
|
561
|
+
return "db2"
|
|
562
|
+
for prefix, driver_path in _URI_PREFIX_DRIVER:
|
|
563
|
+
if lowered.startswith(prefix):
|
|
564
|
+
return driver_kind_from_driver_name(driver_path)
|
|
565
|
+
return None
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def resolve_driver_name(driver_name: str | None, uri: str | None) -> str:
|
|
569
|
+
"""Resolve and normalize the driver name."""
|
|
570
|
+
if isinstance(driver_name, str):
|
|
571
|
+
if is_shared_object_driver(driver_name):
|
|
572
|
+
return _DRIVER_MANAGER_CONNECT
|
|
573
|
+
lowered_driver = driver_name.lower()
|
|
574
|
+
if lowered_driver in {"teradata", "vantage"}:
|
|
575
|
+
return _resolve_teradata_driver_connect()
|
|
576
|
+
if lowered_driver in {"gizmosql", "gizmo"}:
|
|
577
|
+
return _resolve_gizmosql_driver_connect()
|
|
578
|
+
if lowered_driver in {"mssql", "sqlserver", "tsql"}:
|
|
579
|
+
return _resolve_mssql_driver_connect()
|
|
580
|
+
alias = _DRIVER_ALIASES.get(lowered_driver)
|
|
581
|
+
if alias is not None:
|
|
582
|
+
return alias
|
|
583
|
+
return normalize_driver_path(driver_name)
|
|
584
|
+
|
|
585
|
+
if isinstance(uri, str):
|
|
586
|
+
resolved = driver_from_uri(uri)
|
|
587
|
+
if resolved is not None:
|
|
588
|
+
return resolved
|
|
589
|
+
|
|
590
|
+
return "adbc_driver_sqlite.dbapi.connect"
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def resolve_driver_name_from_config(connection_config: "Mapping[str, Any]") -> str:
|
|
594
|
+
"""Resolve and normalize the driver name from a connection config mapping."""
|
|
595
|
+
db_kwargs = connection_config.get("db_kwargs")
|
|
596
|
+
nested_uri = db_kwargs.get("uri") if isinstance(db_kwargs, dict) else None
|
|
597
|
+
uri = (
|
|
598
|
+
connection_config.get("uri")
|
|
599
|
+
or connection_config.get("url")
|
|
600
|
+
or connection_config.get("dsn")
|
|
601
|
+
or connection_config.get("connection_string")
|
|
602
|
+
or nested_uri
|
|
603
|
+
)
|
|
604
|
+
driver_name = connection_config.get("driver_name") or connection_config.get("driver")
|
|
605
|
+
return resolve_driver_name(driver_name, uri)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def resolve_driver_connect_func(driver_name: str | None, uri: str | None) -> "Callable[..., Any]":
|
|
609
|
+
"""Resolve the driver connect function.
|
|
610
|
+
|
|
611
|
+
Raises:
|
|
612
|
+
ImproperConfigurationError: If driver cannot be loaded.
|
|
613
|
+
"""
|
|
614
|
+
driver_path = resolve_driver_name(driver_name, uri)
|
|
615
|
+
try:
|
|
616
|
+
connect_func = import_string(driver_path)
|
|
617
|
+
except ImportError as exc:
|
|
618
|
+
msg = f"Failed to import connect function from '{driver_path}'. Is the driver installed? Error: {exc}"
|
|
619
|
+
raise with_cause(ImproperConfigurationError(msg), exc) from exc
|
|
620
|
+
|
|
621
|
+
if not callable(connect_func):
|
|
622
|
+
msg = f"The path '{driver_path}' did not resolve to a callable function."
|
|
623
|
+
raise ImproperConfigurationError(msg)
|
|
624
|
+
|
|
625
|
+
return cast("Callable[..., Any]", connect_func)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def resolve_dialect_from_driver_path(driver_path: str) -> str:
|
|
629
|
+
"""Get the SQL dialect type based on the driver path.
|
|
630
|
+
|
|
631
|
+
Only the final path segment is considered, because a directory on the way to
|
|
632
|
+
the driver can carry the name of an unrelated database.
|
|
633
|
+
"""
|
|
634
|
+
candidate = driver_path.replace("\\", "/").rsplit("/", 1)[-1] or driver_path
|
|
635
|
+
for keyword, dialect in _DRIVER_PATH_KEYWORDS_TO_DIALECT:
|
|
636
|
+
if keyword in candidate:
|
|
637
|
+
return dialect
|
|
638
|
+
return "sqlite"
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def resolve_dialect_from_config(connection_config: "Mapping[str, Any]") -> str:
|
|
642
|
+
"""Resolve dialect using ADBC connection configuration.
|
|
643
|
+
|
|
644
|
+
GizmoSQL connections default to DuckDB unless the backend is explicitly overridden.
|
|
645
|
+
"""
|
|
646
|
+
override = connection_config.get("adbc_dialect")
|
|
647
|
+
if isinstance(override, str) and override.strip():
|
|
648
|
+
return normalize_dialect_name(override.strip())
|
|
649
|
+
backend = connection_config.get("gizmosql_backend")
|
|
650
|
+
if isinstance(backend, str):
|
|
651
|
+
lowered_backend = backend.lower()
|
|
652
|
+
if lowered_backend in {"duckdb", "sqlite"}:
|
|
653
|
+
return lowered_backend
|
|
654
|
+
|
|
655
|
+
driver_name = connection_config.get("driver_name") or connection_config.get("driver")
|
|
656
|
+
if isinstance(driver_name, str):
|
|
657
|
+
lowered_driver_name = driver_name.lower()
|
|
658
|
+
if lowered_driver_name in {"teradata", "vantage"}:
|
|
659
|
+
return "teradata"
|
|
660
|
+
if lowered_driver_name in {"gizmosql", "gizmo"}:
|
|
661
|
+
return "duckdb"
|
|
662
|
+
if lowered_driver_name in {"mssql", "sqlserver", "tsql"}:
|
|
663
|
+
return "mssql"
|
|
664
|
+
if lowered_driver_name in {"oracle", "oracledb"}:
|
|
665
|
+
return "oracle"
|
|
666
|
+
if lowered_driver_name in {"db2", "ibmdb2", "ibm_db"}:
|
|
667
|
+
return "db2"
|
|
668
|
+
if lowered_driver_name == "quack":
|
|
669
|
+
return "duckdb"
|
|
670
|
+
if is_shared_object_driver(driver_name):
|
|
671
|
+
return resolve_dialect_from_driver_path(lowered_driver_name)
|
|
672
|
+
|
|
673
|
+
db_kwargs = connection_config.get("db_kwargs")
|
|
674
|
+
nested_uri = db_kwargs.get("uri") if isinstance(db_kwargs, dict) else None
|
|
675
|
+
uri = (
|
|
676
|
+
connection_config.get("uri")
|
|
677
|
+
or connection_config.get("url")
|
|
678
|
+
or connection_config.get("dsn")
|
|
679
|
+
or connection_config.get("connection_string")
|
|
680
|
+
or nested_uri
|
|
681
|
+
)
|
|
682
|
+
if isinstance(uri, str):
|
|
683
|
+
lowered_uri = uri.lower()
|
|
684
|
+
if lowered_uri.startswith("teradata://"):
|
|
685
|
+
return "teradata"
|
|
686
|
+
if lowered_uri.startswith(("gizmosql://", "gizmo://", "quack://", "quack+tls://")):
|
|
687
|
+
return "duckdb"
|
|
688
|
+
if lowered_uri.startswith(("mssql://", "sqlserver://")):
|
|
689
|
+
return "mssql"
|
|
690
|
+
if lowered_uri.startswith("oracle://"):
|
|
691
|
+
return "oracle"
|
|
692
|
+
if lowered_uri.startswith("db2://") or _parse_db2_cli_dsn(uri) is not None:
|
|
693
|
+
return "db2"
|
|
694
|
+
if driver_name is None and lowered_uri.startswith("grpc+tls://"):
|
|
695
|
+
return "duckdb"
|
|
696
|
+
|
|
697
|
+
return resolve_dialect_from_driver_path(resolve_driver_name_from_config(connection_config))
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def is_sqlite_reconcile_target(connection_config: "Mapping[str, Any]") -> bool:
|
|
701
|
+
"""Return whether an ADBC connection configuration targets local SQLite.
|
|
702
|
+
|
|
703
|
+
Args:
|
|
704
|
+
connection_config: Raw ADBC connection configuration mapping.
|
|
705
|
+
|
|
706
|
+
Returns:
|
|
707
|
+
True when the configuration unambiguously resolves to a local SQLite ADBC target.
|
|
708
|
+
"""
|
|
709
|
+
override = connection_config.get("adbc_dialect")
|
|
710
|
+
if isinstance(override, str) and override.strip().lower() not in {"", "sqlite"}:
|
|
711
|
+
return False
|
|
712
|
+
backend = connection_config.get("gizmosql_backend")
|
|
713
|
+
if isinstance(backend, str) and backend.strip().lower() not in {"", "sqlite"}:
|
|
714
|
+
return False
|
|
715
|
+
|
|
716
|
+
raw_driver_name = connection_config.get("driver_name") or connection_config.get("driver")
|
|
717
|
+
has_driver_name = isinstance(raw_driver_name, str) and bool(raw_driver_name.strip())
|
|
718
|
+
if has_driver_name:
|
|
719
|
+
assert isinstance(raw_driver_name, str)
|
|
720
|
+
if is_shared_object_driver(raw_driver_name):
|
|
721
|
+
basename = raw_driver_name.replace("\\", "/").rsplit("/", 1)[-1].lower()
|
|
722
|
+
if "sqlite" not in basename:
|
|
723
|
+
return False
|
|
724
|
+
elif driver_kind_from_driver_name(raw_driver_name) != "sqlite":
|
|
725
|
+
return False
|
|
726
|
+
|
|
727
|
+
db_kwargs = connection_config.get("db_kwargs")
|
|
728
|
+
nested_uri = db_kwargs.get("uri") if isinstance(db_kwargs, Mapping) else None
|
|
729
|
+
raw_uri = (
|
|
730
|
+
connection_config.get("uri")
|
|
731
|
+
or connection_config.get("url")
|
|
732
|
+
or connection_config.get("dsn")
|
|
733
|
+
or connection_config.get("connection_string")
|
|
734
|
+
or nested_uri
|
|
735
|
+
)
|
|
736
|
+
has_uri = isinstance(raw_uri, str) and bool(raw_uri.strip())
|
|
737
|
+
if has_uri:
|
|
738
|
+
assert isinstance(raw_uri, str)
|
|
739
|
+
if driver_kind_from_uri(raw_uri) not in {"sqlite", None}:
|
|
740
|
+
return False
|
|
741
|
+
if not has_driver_name:
|
|
742
|
+
return driver_kind_from_driver_name(resolve_driver_name_from_config(connection_config)) == "sqlite"
|
|
743
|
+
return True
|
|
744
|
+
|
|
745
|
+
if has_driver_name:
|
|
746
|
+
return True
|
|
747
|
+
return driver_kind_from_driver_name(resolve_driver_name_from_config(connection_config)) == "sqlite"
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def resolve_reconcile_adbc_dialect(connection_config: "Mapping[str, Any]", statement_dialect: str | None) -> str | None:
|
|
751
|
+
"""Return the reconcile dialect for an ADBC config, or None when it cannot be determined.
|
|
752
|
+
|
|
753
|
+
Args:
|
|
754
|
+
connection_config: Raw or normalized ADBC connection configuration mapping.
|
|
755
|
+
statement_dialect: Caller-supplied statement dialect, or ``None`` when filled automatically.
|
|
756
|
+
|
|
757
|
+
Returns:
|
|
758
|
+
Canonical dialect name from ``RECONCILE_ADBC_DIALECTS``, or ``None`` when undetermined.
|
|
759
|
+
"""
|
|
760
|
+
hint = connection_config.get("adbc_dialect")
|
|
761
|
+
if isinstance(hint, str) and hint.strip():
|
|
762
|
+
normalized_hint = normalize_dialect_name(hint.strip())
|
|
763
|
+
return normalized_hint if normalized_hint in RECONCILE_ADBC_DIALECTS else None
|
|
764
|
+
|
|
765
|
+
backend = connection_config.get("gizmosql_backend")
|
|
766
|
+
if isinstance(backend, str) and backend.strip():
|
|
767
|
+
normalized_backend = normalize_dialect_name(backend.strip())
|
|
768
|
+
if normalized_backend in {"duckdb", "sqlite"}:
|
|
769
|
+
return normalized_backend
|
|
770
|
+
return None
|
|
771
|
+
|
|
772
|
+
if is_sqlite_reconcile_target(connection_config):
|
|
773
|
+
return "sqlite"
|
|
774
|
+
|
|
775
|
+
raw_driver = connection_config.get("driver_name") or connection_config.get("driver")
|
|
776
|
+
db_kwargs = connection_config.get("db_kwargs")
|
|
777
|
+
nested_uri = db_kwargs.get("uri") if isinstance(db_kwargs, Mapping) else None
|
|
778
|
+
raw_uri = (
|
|
779
|
+
connection_config.get("uri")
|
|
780
|
+
or connection_config.get("url")
|
|
781
|
+
or connection_config.get("dsn")
|
|
782
|
+
or connection_config.get("connection_string")
|
|
783
|
+
or nested_uri
|
|
784
|
+
)
|
|
785
|
+
|
|
786
|
+
driver_kind: str | None = None
|
|
787
|
+
if isinstance(raw_driver, str) and raw_driver.strip():
|
|
788
|
+
driver_candidate = (
|
|
789
|
+
raw_driver.replace("\\", "/").rsplit("/", 1)[-1] if is_shared_object_driver(raw_driver) else raw_driver
|
|
790
|
+
)
|
|
791
|
+
driver_kind = driver_kind_from_driver_name(driver_candidate)
|
|
792
|
+
elif isinstance(raw_uri, str) and raw_uri.strip():
|
|
793
|
+
driver_kind = driver_kind_from_uri(raw_uri)
|
|
794
|
+
|
|
795
|
+
if driver_kind is None:
|
|
796
|
+
return None
|
|
797
|
+
|
|
798
|
+
if driver_kind not in {"flightsql", "grpc"}:
|
|
799
|
+
resolved = normalize_dialect_name(resolve_dialect_from_config(connection_config))
|
|
800
|
+
if resolved in RECONCILE_ADBC_DIALECTS and resolved != "sqlite":
|
|
801
|
+
return resolved
|
|
802
|
+
return None
|
|
803
|
+
|
|
804
|
+
if isinstance(statement_dialect, str) and statement_dialect.strip():
|
|
805
|
+
normalized_statement = normalize_dialect_name(statement_dialect.strip())
|
|
806
|
+
if normalized_statement in RECONCILE_ADBC_DIALECTS and normalized_statement != "sqlite":
|
|
807
|
+
return normalized_statement
|
|
808
|
+
|
|
809
|
+
return None
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def normalize_connection_aliases(connection_config: "Mapping[str, Any]") -> "dict[str, Any]":
|
|
813
|
+
"""Normalize URI and file-path aliases in an ADBC connection config mapping.
|
|
814
|
+
|
|
815
|
+
Args:
|
|
816
|
+
connection_config: Raw connection configuration mapping.
|
|
817
|
+
|
|
818
|
+
Returns:
|
|
819
|
+
Dictionary with normalized ``uri`` / ``path`` keys.
|
|
820
|
+
"""
|
|
821
|
+
config = dict(connection_config)
|
|
822
|
+
|
|
823
|
+
if "uri" not in config:
|
|
824
|
+
uri_alias = config.pop("url", None) or config.pop("dsn", None) or config.pop("connection_string", None)
|
|
825
|
+
if uri_alias is not None:
|
|
826
|
+
config["uri"] = uri_alias
|
|
827
|
+
else:
|
|
828
|
+
config.pop("url", None)
|
|
829
|
+
config.pop("dsn", None)
|
|
830
|
+
config.pop("connection_string", None)
|
|
831
|
+
|
|
832
|
+
driver_name = config.get("driver_name") or config.get("driver")
|
|
833
|
+
uri = config.get("uri")
|
|
834
|
+
driver_kind: str | None = None
|
|
835
|
+
if isinstance(driver_name, str):
|
|
836
|
+
driver_kind = driver_kind_from_driver_name(driver_name)
|
|
837
|
+
if driver_kind is None and isinstance(uri, str):
|
|
838
|
+
driver_kind = driver_kind_from_uri(uri)
|
|
839
|
+
|
|
840
|
+
hint = config.get("adbc_dialect")
|
|
841
|
+
non_sqlite_hint = isinstance(hint, str) and hint.strip().lower() not in {"", "sqlite"}
|
|
842
|
+
if (
|
|
843
|
+
not non_sqlite_hint
|
|
844
|
+
and (driver_kind == "sqlite" or driver_kind is None)
|
|
845
|
+
and "uri" not in config
|
|
846
|
+
and "db_kwargs" not in config
|
|
847
|
+
):
|
|
848
|
+
db_path = (
|
|
849
|
+
config.pop("database", None)
|
|
850
|
+
or config.pop("db", None)
|
|
851
|
+
or config.pop("path", None)
|
|
852
|
+
or config.pop("file", None)
|
|
853
|
+
)
|
|
854
|
+
if db_path is not None:
|
|
855
|
+
config["uri"] = db_path
|
|
856
|
+
elif driver_kind == "duckdb" and "path" not in config:
|
|
857
|
+
duck_path = (
|
|
858
|
+
config.pop("database", None)
|
|
859
|
+
or config.pop("db", None)
|
|
860
|
+
or config.pop("file", None)
|
|
861
|
+
or config.pop("path", None)
|
|
862
|
+
)
|
|
863
|
+
if duck_path is not None:
|
|
864
|
+
config["path"] = duck_path
|
|
865
|
+
|
|
866
|
+
return config
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def build_connection_config(connection_config: "Mapping[str, Any]") -> "dict[str, Any]":
|
|
870
|
+
"""Build a normalized connection configuration dictionary.
|
|
871
|
+
|
|
872
|
+
Args:
|
|
873
|
+
connection_config: Raw connection configuration mapping.
|
|
874
|
+
|
|
875
|
+
Returns:
|
|
876
|
+
Normalized connection configuration dictionary.
|
|
877
|
+
"""
|
|
878
|
+
config = normalize_connection_aliases(connection_config)
|
|
879
|
+
config.pop("adbc_dialect", None)
|
|
880
|
+
|
|
881
|
+
driver_name = config.get("driver_name") or config.get("driver")
|
|
882
|
+
db_kwargs_existing = config.get("db_kwargs")
|
|
883
|
+
nested_uri = db_kwargs_existing.get("uri") if isinstance(db_kwargs_existing, dict) else None
|
|
884
|
+
uri = config.get("uri") or nested_uri
|
|
885
|
+
driver_kind: str | None = None
|
|
886
|
+
if isinstance(driver_name, str):
|
|
887
|
+
driver_kind = driver_kind_from_driver_name(driver_name)
|
|
888
|
+
if driver_kind is None and isinstance(uri, str):
|
|
889
|
+
driver_kind = driver_kind_from_uri(uri)
|
|
890
|
+
if driver_kind is None and "uri" in config:
|
|
891
|
+
driver_kind = "sqlite"
|
|
892
|
+
|
|
893
|
+
if isinstance(uri, str) and driver_kind == "sqlite" and uri.lower().startswith("sqlite://"):
|
|
894
|
+
config["uri"] = uri[9:]
|
|
895
|
+
if driver_kind == "duckdb" or str(config.get("entrypoint", "")).strip().lower() == "duckdb_adbc_init":
|
|
896
|
+
_normalize_and_validate_duckdb_config(config, uri)
|
|
897
|
+
if isinstance(uri, str) and driver_kind == "db2" and not uri.lower().startswith("db2://"):
|
|
898
|
+
_normalize_db2_cli_dsn(config, uri)
|
|
899
|
+
|
|
900
|
+
legacy_entrypoint = config.pop("adbc_driver_manager_entrypoint", None)
|
|
901
|
+
if legacy_entrypoint is not None:
|
|
902
|
+
config.setdefault("entrypoint", legacy_entrypoint)
|
|
903
|
+
|
|
904
|
+
resolved_connect_path = resolve_driver_name(
|
|
905
|
+
driver_name if isinstance(driver_name, str) else None, uri if isinstance(uri, str) else None
|
|
906
|
+
)
|
|
907
|
+
uses_driver_manager = resolved_connect_path == _DRIVER_MANAGER_CONNECT
|
|
908
|
+
if not uses_driver_manager:
|
|
909
|
+
config.pop("entrypoint", None)
|
|
910
|
+
|
|
911
|
+
if driver_kind == "snowflake" and "user" in config:
|
|
912
|
+
user = config.pop("user")
|
|
913
|
+
config.setdefault("username", user)
|
|
914
|
+
|
|
915
|
+
auth_token_provider = config.pop("auth_token_provider", None)
|
|
916
|
+
if callable(auth_token_provider):
|
|
917
|
+
fresh_token = str(auth_token_provider())
|
|
918
|
+
if driver_kind == "snowflake":
|
|
919
|
+
_apply_snowflake_auth_token_provider(config, fresh_token)
|
|
920
|
+
elif driver_kind == "quack" and "username" not in config and "user" not in config:
|
|
921
|
+
config["token"] = fresh_token
|
|
922
|
+
elif driver_kind in {"gizmosql", "flightsql"} and "username" not in config and "user" not in config:
|
|
923
|
+
config["authorization_header"] = (
|
|
924
|
+
fresh_token if fresh_token.lower().startswith("bearer ") else f"Bearer {fresh_token}"
|
|
925
|
+
)
|
|
926
|
+
else:
|
|
927
|
+
config["password"] = fresh_token
|
|
928
|
+
|
|
929
|
+
if driver_kind == "teradata":
|
|
930
|
+
_build_or_augment_teradata_uri(config)
|
|
931
|
+
if not uses_driver_manager and driver_kind in {"mssql", "teradata"}:
|
|
932
|
+
config.pop("driver", None)
|
|
933
|
+
_lift_driver_specific_db_kwargs(config, driver_kind, resolved_connect_path)
|
|
934
|
+
|
|
935
|
+
config.pop("driver_name", None)
|
|
936
|
+
if uses_driver_manager:
|
|
937
|
+
_apply_driver_manager_config(config, driver_kind, driver_name)
|
|
938
|
+
else:
|
|
939
|
+
config.pop("driver", None)
|
|
940
|
+
|
|
941
|
+
return config
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def resolve_dialect_name(dialect: Any) -> str:
|
|
945
|
+
"""Return the normalized dialect name string, reporting the ``vantage`` dialect as ``teradata``."""
|
|
946
|
+
if dialect is None:
|
|
947
|
+
return ""
|
|
948
|
+
if isinstance(dialect, str):
|
|
949
|
+
name = dialect.lower()
|
|
950
|
+
elif isinstance(dialect, type) and issubclass(dialect, sqlglot.Dialect):
|
|
951
|
+
name = dialect.__name__.lower()
|
|
952
|
+
elif isinstance(dialect, sqlglot.Dialect):
|
|
953
|
+
name = type(dialect).__name__.lower()
|
|
954
|
+
else:
|
|
955
|
+
return str(dialect)
|
|
956
|
+
return "teradata" if name == "vantage" else name
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def is_postgres_dialect(dialect_name: str) -> bool:
|
|
960
|
+
"""Return True when the dialect indicates PostgreSQL.
|
|
961
|
+
|
|
962
|
+
Includes pgvector, paradedb, and pg_textsearch extension dialects.
|
|
963
|
+
"""
|
|
964
|
+
return dialect_name in {"postgres", "postgresql", "pgvector", "paradedb", "pg_textsearch", "pgtextsearch"}
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def handle_postgres_rollback(dialect: str, cursor: Any, logger: Any | None = None) -> None:
|
|
968
|
+
"""Clear an aborted PostgreSQL transaction after a statement failure.
|
|
969
|
+
|
|
970
|
+
The connection-level rollback is preferred because the driver refuses to
|
|
971
|
+
start a transaction on an errored connection, which a cursor needs in order
|
|
972
|
+
to issue a ``ROLLBACK`` statement.
|
|
973
|
+
|
|
974
|
+
Args:
|
|
975
|
+
dialect: Active dialect identifier.
|
|
976
|
+
cursor: Database cursor whose connection should be rolled back.
|
|
977
|
+
logger: Optional logger for diagnostics.
|
|
978
|
+
"""
|
|
979
|
+
if not is_postgres_dialect(dialect):
|
|
980
|
+
return
|
|
981
|
+
|
|
982
|
+
connection = getattr(cursor, "connection", None)
|
|
983
|
+
if connection is not None and _try_rollback(connection.rollback):
|
|
984
|
+
_log_rollback(logger)
|
|
985
|
+
return
|
|
986
|
+
|
|
987
|
+
if _try_rollback(partial(cursor.execute, "ROLLBACK")):
|
|
988
|
+
_log_rollback(logger)
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def normalize_postgres_empty_parameters(dialect: str, parameters: Any) -> Any:
|
|
992
|
+
"""Normalize empty parameter payloads for PostgreSQL drivers.
|
|
993
|
+
|
|
994
|
+
Args:
|
|
995
|
+
dialect: Active dialect identifier.
|
|
996
|
+
parameters: Parameter payload in any supported shape.
|
|
997
|
+
|
|
998
|
+
Returns:
|
|
999
|
+
Normalized parameter payload.
|
|
1000
|
+
"""
|
|
1001
|
+
if is_postgres_dialect(dialect) and isinstance(parameters, dict) and not parameters:
|
|
1002
|
+
return None
|
|
1003
|
+
return parameters
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
def prepare_postgres_parameters(
|
|
1007
|
+
parameters: Any,
|
|
1008
|
+
parameter_casts: "dict[int, str]",
|
|
1009
|
+
statement_config: "StatementConfig",
|
|
1010
|
+
*,
|
|
1011
|
+
dialect: str,
|
|
1012
|
+
json_serializer: "Callable[[Any], str]",
|
|
1013
|
+
) -> Any:
|
|
1014
|
+
"""Prepare Postgres parameters with cast-aware coercion."""
|
|
1015
|
+
postgres_compatible = normalize_postgres_empty_parameters(dialect, parameters)
|
|
1016
|
+
converter = get_adbc_type_converter(dialect, json_serializer=json_serializer)
|
|
1017
|
+
if isinstance(postgres_compatible, (list, tuple)) and hasattr(converter, "convert_sequence"):
|
|
1018
|
+
seq = [
|
|
1019
|
+
converter.convert_sequence(item, json_serializer=json_serializer)
|
|
1020
|
+
if isinstance(item, (list, tuple))
|
|
1021
|
+
else item
|
|
1022
|
+
for item in postgres_compatible
|
|
1023
|
+
]
|
|
1024
|
+
postgres_compatible = tuple(seq) if isinstance(postgres_compatible, tuple) else seq
|
|
1025
|
+
if not parameter_casts:
|
|
1026
|
+
return postgres_compatible
|
|
1027
|
+
return prepare_parameters_with_casts(
|
|
1028
|
+
postgres_compatible, parameter_casts, statement_config, dialect=dialect, json_serializer=json_serializer
|
|
1029
|
+
)
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
_ADBC_STATUS_CODE_MAP: Final[dict[str, tuple[type[SQLSpecError], str]]] = {
|
|
1033
|
+
"TIMEOUT": (QueryTimeoutError, "query timeout"),
|
|
1034
|
+
"CANCELLED": (OperationCancelledError, "operation cancelled"),
|
|
1035
|
+
"UNAUTHENTICATED": (PermissionDeniedError, "unauthenticated"),
|
|
1036
|
+
"UNAUTHORIZED": (PermissionDeniedError, "unauthorized"),
|
|
1037
|
+
"NOT_FOUND": (NotFoundError, "not found"),
|
|
1038
|
+
"ALREADY_EXISTS": (IntegrityError, "already exists"),
|
|
1039
|
+
"INVALID_ARGUMENT": (DataError, "invalid argument"),
|
|
1040
|
+
"INVALID_DATA": (DataError, "invalid data"),
|
|
1041
|
+
"INTEGRITY": (IntegrityError, "integrity violation"),
|
|
1042
|
+
"IO": (DatabaseConnectionError, "I/O error"),
|
|
1043
|
+
"INVALID_STATE": (OperationalError, "invalid state"),
|
|
1044
|
+
"INTERNAL": (OperationalError, "internal error"),
|
|
1045
|
+
"NOT_IMPLEMENTED": (SQLSpecError, "not implemented"),
|
|
1046
|
+
}
|
|
1047
|
+
_MIN_QUALIFIED_PARTS: Final = 2
|
|
1048
|
+
_MAX_TERADATA_QUALIFIED_PARTS: Final[int] = 2
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def create_mapped_exception(error: Any, *, logger: Any | None = None) -> SQLSpecError:
|
|
1052
|
+
"""Map ADBC errors to SQLSpec exceptions.
|
|
1053
|
+
|
|
1054
|
+
Teradata ``[Error NNNN]`` diagnostics are mapped only when the message identifies Teradata;
|
|
1055
|
+
use ``create_teradata_mapped_exception`` for connections known to reach Teradata.
|
|
1056
|
+
|
|
1057
|
+
This is a factory function that returns an exception instance rather than
|
|
1058
|
+
raising. This pattern is more robust for use in __exit__ handlers and
|
|
1059
|
+
avoids issues with exception control flow in different Python versions.
|
|
1060
|
+
|
|
1061
|
+
Mapping priority:
|
|
1062
|
+
1. Cancellation and timeout status codes
|
|
1063
|
+
2. SQLSTATE codes and vendor-specific diagnostics
|
|
1064
|
+
3. Error message patterns
|
|
1065
|
+
4. Generic ADBC status codes or SQLSpecError fallback
|
|
1066
|
+
|
|
1067
|
+
Args:
|
|
1068
|
+
error: The ADBC exception to map
|
|
1069
|
+
logger: Optional logger accepted for adapter signature parity.
|
|
1070
|
+
|
|
1071
|
+
Returns:
|
|
1072
|
+
A SQLSpec exception that wraps the original error
|
|
1073
|
+
"""
|
|
1074
|
+
_ = logger
|
|
1075
|
+
return _create_mapped_exception(error, assume_teradata=False)
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
def create_teradata_mapped_exception(error: Any) -> SQLSpecError:
|
|
1079
|
+
"""Map an error from a connection known to reach Teradata, including Flight SQL routes.
|
|
1080
|
+
|
|
1081
|
+
Teradata ``[Error NNNN]`` diagnostics are mapped even when the message carries no Teradata
|
|
1082
|
+
marker, then the generic ADBC mapping applies.
|
|
1083
|
+
|
|
1084
|
+
Args:
|
|
1085
|
+
error: The ADBC exception to map.
|
|
1086
|
+
|
|
1087
|
+
Returns:
|
|
1088
|
+
A SQLSpec exception that wraps the original error.
|
|
1089
|
+
"""
|
|
1090
|
+
return _create_mapped_exception(error, assume_teradata=True)
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
def build_profile() -> "DriverParameterProfile":
|
|
1094
|
+
"""Create the ADBC driver parameter profile."""
|
|
1095
|
+
|
|
1096
|
+
return DriverParameterProfile(
|
|
1097
|
+
name="ADBC",
|
|
1098
|
+
default_style=ParameterStyle.QMARK,
|
|
1099
|
+
supported_styles={ParameterStyle.QMARK},
|
|
1100
|
+
default_execution_style=ParameterStyle.QMARK,
|
|
1101
|
+
supported_execution_styles={ParameterStyle.QMARK},
|
|
1102
|
+
has_native_list_expansion=True,
|
|
1103
|
+
preserve_parameter_format=True,
|
|
1104
|
+
needs_static_script_compilation=False,
|
|
1105
|
+
allow_mixed_parameter_styles=False,
|
|
1106
|
+
preserve_original_params_for_many=False,
|
|
1107
|
+
json_serializer_strategy="helper",
|
|
1108
|
+
custom_type_coercions={
|
|
1109
|
+
dt.datetime: _identity,
|
|
1110
|
+
dt.date: _identity,
|
|
1111
|
+
dt.time: _identity,
|
|
1112
|
+
decimal.Decimal: _identity,
|
|
1113
|
+
bool: _identity,
|
|
1114
|
+
int: _identity,
|
|
1115
|
+
float: _identity,
|
|
1116
|
+
bytes: _identity,
|
|
1117
|
+
tuple: _convert_array_for_postgres_adbc,
|
|
1118
|
+
list: _convert_array_for_postgres_adbc,
|
|
1119
|
+
dict: _identity,
|
|
1120
|
+
**build_uuid_coercions(native=True),
|
|
1121
|
+
},
|
|
1122
|
+
extras={
|
|
1123
|
+
"type_coercion_overrides": {list: _convert_array_for_postgres_adbc, tuple: _convert_array_for_postgres_adbc}
|
|
1124
|
+
},
|
|
1125
|
+
)
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def get_statement_config(detected_dialect: str) -> StatementConfig:
|
|
1129
|
+
"""Create statement configuration for the specified dialect."""
|
|
1130
|
+
detected_dialect = "teradata" if detected_dialect == "vantage" else detected_dialect
|
|
1131
|
+
default_style, supported_styles = DIALECT_PARAMETER_STYLES.get(
|
|
1132
|
+
"postgres" if is_postgres_dialect(detected_dialect) else detected_dialect,
|
|
1133
|
+
(ParameterStyle.QMARK, [ParameterStyle.QMARK]),
|
|
1134
|
+
)
|
|
1135
|
+
|
|
1136
|
+
if detected_dialect == "postgresql":
|
|
1137
|
+
sqlglot_dialect = "postgres"
|
|
1138
|
+
elif detected_dialect == "mssql":
|
|
1139
|
+
sqlglot_dialect = "tsql"
|
|
1140
|
+
elif detected_dialect == "teradata":
|
|
1141
|
+
importlib.import_module("sqlspec.dialects.teradata")
|
|
1142
|
+
sqlglot_dialect = "vantage"
|
|
1143
|
+
else:
|
|
1144
|
+
sqlglot_dialect = detected_dialect
|
|
1145
|
+
profile = driver_profile
|
|
1146
|
+
|
|
1147
|
+
parameter_overrides: dict[str, Any] = {
|
|
1148
|
+
"default_parameter_style": default_style,
|
|
1149
|
+
"supported_parameter_styles": set(supported_styles),
|
|
1150
|
+
"default_execution_parameter_style": default_style,
|
|
1151
|
+
"supported_execution_parameter_styles": set(supported_styles),
|
|
1152
|
+
"type_coercion_map": _BASE_TYPE_COERCION_MAP,
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
statement_overrides: dict[str, Any] = {"dialect": sqlglot_dialect}
|
|
1156
|
+
if detected_dialect == "duckdb":
|
|
1157
|
+
parameter_overrides["preserve_parameter_format"] = False
|
|
1158
|
+
parameter_overrides["supported_execution_parameter_styles"] = {ParameterStyle.QMARK, ParameterStyle.NUMERIC}
|
|
1159
|
+
statement_overrides["statement_transformers"] = (_transform_duckdb_copy_parameters,)
|
|
1160
|
+
elif detected_dialect == "oracle":
|
|
1161
|
+
parameter_overrides["preserve_parameter_format"] = False
|
|
1162
|
+
parameter_overrides["supported_execution_parameter_styles"] = {ParameterStyle.POSITIONAL_COLON}
|
|
1163
|
+
elif detected_dialect in {"db2", "mssql", "tsql", "snowflake", "teradata"}:
|
|
1164
|
+
parameter_overrides["preserve_parameter_format"] = False
|
|
1165
|
+
parameter_overrides["supported_execution_parameter_styles"] = {ParameterStyle.QMARK}
|
|
1166
|
+
|
|
1167
|
+
if is_postgres_dialect(detected_dialect) or detected_dialect == "snowflake":
|
|
1168
|
+
parameter_overrides["ast_transformer"] = build_null_pruning_transform(dialect=sqlglot_dialect)
|
|
1169
|
+
|
|
1170
|
+
return build_statement_config_from_profile(
|
|
1171
|
+
profile, parameter_overrides=parameter_overrides, statement_overrides=statement_overrides
|
|
1172
|
+
)
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
def apply_driver_features(
|
|
1176
|
+
statement_config: "StatementConfig", driver_features: "Mapping[str, Any] | None"
|
|
1177
|
+
) -> "tuple[StatementConfig, dict[str, Any]]":
|
|
1178
|
+
"""Apply ADBC driver feature defaults to the statement config.
|
|
1179
|
+
|
|
1180
|
+
Args:
|
|
1181
|
+
statement_config: Base statement configuration.
|
|
1182
|
+
driver_features: Optional driver feature overrides.
|
|
1183
|
+
|
|
1184
|
+
Returns:
|
|
1185
|
+
Updated statement configuration and normalized driver features.
|
|
1186
|
+
"""
|
|
1187
|
+
processed_features: dict[str, Any] = dict(driver_features) if driver_features else {}
|
|
1188
|
+
resolved_dialect = resolve_dialect_name(statement_config.dialect).lower()
|
|
1189
|
+
|
|
1190
|
+
json_serializer = cast("Callable[[Any], str] | None", processed_features.setdefault("json_serializer", to_json))
|
|
1191
|
+
processed_features.setdefault("enable_cast_detection", True)
|
|
1192
|
+
processed_features.setdefault("enable_strict_type_coercion", False)
|
|
1193
|
+
processed_features.setdefault("enable_arrow_extension_types", True)
|
|
1194
|
+
processed_features.setdefault("enable_pgvector", PGVECTOR_INSTALLED)
|
|
1195
|
+
processed_features.setdefault("enable_paradedb", True)
|
|
1196
|
+
processed_features.setdefault("enable_pg_textsearch", True)
|
|
1197
|
+
processed_features.setdefault(
|
|
1198
|
+
"enable_lowercase_column_names", resolved_dialect in {"oracle", "db2", "snowflake", "teradata", "vantage"}
|
|
1199
|
+
)
|
|
1200
|
+
processed_features.setdefault("enable_statement_profiling", False)
|
|
1201
|
+
|
|
1202
|
+
if json_serializer is not None:
|
|
1203
|
+
statement_config = _apply_adbc_json_serializer(statement_config, json_serializer)
|
|
1204
|
+
|
|
1205
|
+
return statement_config, processed_features
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def create_duckdb_profile_path() -> Path:
|
|
1209
|
+
"""Create a 0600 temporary file path for DuckDB JSON statement profiling."""
|
|
1210
|
+
fd, raw_path = tempfile.mkstemp(prefix="sqlspec_duckdb_profile_", suffix=".json", dir=tempfile.gettempdir())
|
|
1211
|
+
path = Path(raw_path)
|
|
1212
|
+
try:
|
|
1213
|
+
os.close(fd)
|
|
1214
|
+
path.chmod(0o600)
|
|
1215
|
+
except BaseException:
|
|
1216
|
+
with contextlib.suppress(OSError):
|
|
1217
|
+
path.unlink(missing_ok=True)
|
|
1218
|
+
raise
|
|
1219
|
+
return path
|
|
1220
|
+
|
|
1221
|
+
|
|
1222
|
+
def cleanup_duckdb_profile_path(profile_path: Path | str | None) -> None:
|
|
1223
|
+
"""Remove a temporary DuckDB JSON statement profile file if it exists."""
|
|
1224
|
+
if not profile_path:
|
|
1225
|
+
return
|
|
1226
|
+
with contextlib.suppress(OSError):
|
|
1227
|
+
Path(profile_path).unlink(missing_ok=True)
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
def read_duckdb_profile_json(profile_path: Path | str | None, executed_sql: str | None = None) -> dict[str, Any] | None:
|
|
1231
|
+
"""Read and validate the DuckDB JSON profile file written for executed_sql."""
|
|
1232
|
+
if not profile_path:
|
|
1233
|
+
return None
|
|
1234
|
+
path_obj = Path(profile_path)
|
|
1235
|
+
if not path_obj.exists():
|
|
1236
|
+
return None
|
|
1237
|
+
try:
|
|
1238
|
+
raw_bytes = path_obj.read_bytes()
|
|
1239
|
+
except OSError:
|
|
1240
|
+
return None
|
|
1241
|
+
if not raw_bytes:
|
|
1242
|
+
return None
|
|
1243
|
+
try:
|
|
1244
|
+
parsed: Any = from_json(raw_bytes)
|
|
1245
|
+
except Exception:
|
|
1246
|
+
return None
|
|
1247
|
+
if not isinstance(parsed, dict):
|
|
1248
|
+
return None
|
|
1249
|
+
query_name = parsed.get("query_name")
|
|
1250
|
+
if query_name is None and isinstance(parsed.get("query"), dict):
|
|
1251
|
+
query_name = parsed["query"].get("sql")
|
|
1252
|
+
if isinstance(query_name, str) and executed_sql:
|
|
1253
|
+
normalized_query = query_name.strip().rstrip(";").strip()
|
|
1254
|
+
normalized_sql = executed_sql.strip().rstrip(";").strip()
|
|
1255
|
+
if normalized_sql and normalized_query != normalized_sql:
|
|
1256
|
+
return None
|
|
1257
|
+
if "cpu_time" not in parsed and isinstance(parsed.get("query"), dict) and "cpu_time" in parsed["query"]:
|
|
1258
|
+
parsed["cpu_time"] = parsed["query"]["cpu_time"]
|
|
1259
|
+
if "children" not in parsed and isinstance(parsed.get("operator"), list) and parsed["operator"]:
|
|
1260
|
+
root_op = parsed["operator"][0]
|
|
1261
|
+
if isinstance(root_op, dict) and "children" in root_op:
|
|
1262
|
+
parsed["children"] = root_op["children"]
|
|
1263
|
+
return cast("dict[str, Any]", parsed)
|
|
1264
|
+
|
|
1265
|
+
|
|
1266
|
+
def configure_adbc_duckdb_profiling(connection: Any, profile_path: Path) -> None:
|
|
1267
|
+
"""Enable DuckDB JSON statement profiling on an ADBC DuckDB connection.
|
|
1268
|
+
|
|
1269
|
+
Args:
|
|
1270
|
+
connection: Active ADBC DuckDB connection.
|
|
1271
|
+
profile_path: Temporary file path where DuckDB writes statement profiles.
|
|
1272
|
+
"""
|
|
1273
|
+
escaped_path = str(profile_path).replace("'", "''")
|
|
1274
|
+
cursor = connection.cursor()
|
|
1275
|
+
try:
|
|
1276
|
+
cursor.execute("PRAGMA enable_profiling='json'")
|
|
1277
|
+
with contextlib.suppress(Exception):
|
|
1278
|
+
cursor.execute("SET profiling_coverage='ALL'")
|
|
1279
|
+
cursor.execute(f"SET profiling_output='{escaped_path}'")
|
|
1280
|
+
finally:
|
|
1281
|
+
with contextlib.suppress(Exception):
|
|
1282
|
+
cursor.close()
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
def normalize_column_names(
|
|
1286
|
+
column_names: "list[str]", driver_features: "Mapping[str, Any] | None" = None
|
|
1287
|
+
) -> "list[str]":
|
|
1288
|
+
"""Lowercase implicit-uppercase column names when enabled in driver_features."""
|
|
1289
|
+
if not driver_features or not driver_features.get("enable_lowercase_column_names", False):
|
|
1290
|
+
return column_names
|
|
1291
|
+
return [name.lower() if name and _IMPLICIT_UPPER_COLUMN_PATTERN.fullmatch(name) else name for name in column_names]
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
def enforce_strict_type_coercion(parameters: Any, *, is_many: bool = False) -> None:
|
|
1295
|
+
"""Validate parameter values when ``strict_type_coercion`` is enabled.
|
|
1296
|
+
|
|
1297
|
+
Args:
|
|
1298
|
+
parameters: Parameter payload to validate.
|
|
1299
|
+
is_many: Whether the payload represents an execute-many batch.
|
|
1300
|
+
|
|
1301
|
+
Raises:
|
|
1302
|
+
SQLSpecError: If any parameter value is not a supported SQL/Arrow scalar or container type.
|
|
1303
|
+
"""
|
|
1304
|
+
if parameters is None:
|
|
1305
|
+
return
|
|
1306
|
+
if is_many and isinstance(parameters, (list, tuple)):
|
|
1307
|
+
for row in parameters:
|
|
1308
|
+
_validate_strict_parameter_payload(row)
|
|
1309
|
+
return
|
|
1310
|
+
_validate_strict_parameter_payload(parameters)
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
def resolve_column_names(
|
|
1314
|
+
description: "list[Any] | None",
|
|
1315
|
+
cache: "dict[int, tuple[Any, list[str]]]",
|
|
1316
|
+
driver_features: "Mapping[str, Any] | None" = None,
|
|
1317
|
+
) -> list[str]:
|
|
1318
|
+
"""Resolve and cache ADBC cursor description column names."""
|
|
1319
|
+
if not description:
|
|
1320
|
+
return []
|
|
1321
|
+
|
|
1322
|
+
cache_key = id(description)
|
|
1323
|
+
cached = cache.get(cache_key)
|
|
1324
|
+
if cached is not None and cached[0] is description:
|
|
1325
|
+
return cached[1]
|
|
1326
|
+
|
|
1327
|
+
column_names = normalize_column_names([col[0] for col in description], driver_features)
|
|
1328
|
+
if len(cache) >= COLUMN_CACHE_MAX_SIZE:
|
|
1329
|
+
cache.pop(next(iter(cache)))
|
|
1330
|
+
cache[cache_key] = (description, column_names)
|
|
1331
|
+
return column_names
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def collect_rows(
|
|
1335
|
+
fetched_data: "list[Any] | None",
|
|
1336
|
+
description: "list[Any] | None",
|
|
1337
|
+
*,
|
|
1338
|
+
column_names: "list[str] | None" = None,
|
|
1339
|
+
driver_features: "Mapping[str, Any] | None" = None,
|
|
1340
|
+
) -> "tuple[list[Any], list[str]]":
|
|
1341
|
+
"""Collect ADBC rows and column names.
|
|
1342
|
+
|
|
1343
|
+
Returns raw data without dict conversion. The row format is detected
|
|
1344
|
+
by the driver and passed to ``create_execution_result`` so that
|
|
1345
|
+
``SQLResult`` can handle lazy dict materialisation.
|
|
1346
|
+
|
|
1347
|
+
Args:
|
|
1348
|
+
fetched_data: Rows returned from cursor.fetchall().
|
|
1349
|
+
description: Cursor description metadata.
|
|
1350
|
+
column_names: Optional precomputed column names.
|
|
1351
|
+
driver_features: Optional driver feature configuration.
|
|
1352
|
+
|
|
1353
|
+
Returns:
|
|
1354
|
+
Tuple of (rows, column_names).
|
|
1355
|
+
"""
|
|
1356
|
+
if not description:
|
|
1357
|
+
return [], []
|
|
1358
|
+
resolved_column_names = (
|
|
1359
|
+
normalize_column_names([col[0] for col in description], driver_features)
|
|
1360
|
+
if column_names is None
|
|
1361
|
+
else normalize_column_names(column_names, driver_features)
|
|
1362
|
+
)
|
|
1363
|
+
if not fetched_data:
|
|
1364
|
+
return [], resolved_column_names
|
|
1365
|
+
return fetched_data, resolved_column_names
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def resolve_rowcount(cursor: Any) -> int:
|
|
1369
|
+
"""Resolve rowcount from an ADBC cursor.
|
|
1370
|
+
|
|
1371
|
+
Args:
|
|
1372
|
+
cursor: ADBC cursor with optional rowcount metadata.
|
|
1373
|
+
|
|
1374
|
+
Returns:
|
|
1375
|
+
Rowcount value or -1 when unavailable.
|
|
1376
|
+
"""
|
|
1377
|
+
if not has_rowcount(cursor):
|
|
1378
|
+
return -1
|
|
1379
|
+
rowcount = cursor.rowcount
|
|
1380
|
+
if isinstance(rowcount, int):
|
|
1381
|
+
return rowcount
|
|
1382
|
+
return -1
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
def execute_cache_hit(
|
|
1386
|
+
connection: Any,
|
|
1387
|
+
sql: str,
|
|
1388
|
+
params: Any,
|
|
1389
|
+
cached: "CachedQuery",
|
|
1390
|
+
statement_config: "StatementConfig",
|
|
1391
|
+
state: "tuple[str | None, dict[str, Any], dict[int, tuple[Any, list[str]]]]",
|
|
1392
|
+
) -> "SQLResult | None":
|
|
1393
|
+
"""Execute a cached statement on an ADBC connection and build its result.
|
|
1394
|
+
|
|
1395
|
+
Args:
|
|
1396
|
+
connection: ADBC connection to execute on.
|
|
1397
|
+
sql: Raw SQL text the caller passed.
|
|
1398
|
+
params: Parameters the caller passed, already valid for the compiled SQL.
|
|
1399
|
+
cached: Cached compilation of ``sql``.
|
|
1400
|
+
statement_config: Statement configuration the result uses to rebuild its statement.
|
|
1401
|
+
state: The session's dialect name, driver features, and column-name cache.
|
|
1402
|
+
|
|
1403
|
+
Returns:
|
|
1404
|
+
The statement result, or ``None`` for parameterized Db2 statements that return no
|
|
1405
|
+
rows and for cursors without the DB-API execution surface.
|
|
1406
|
+
|
|
1407
|
+
Raises:
|
|
1408
|
+
SQLSpecError: Mapped from any ADBC error the statement raises.
|
|
1409
|
+
DataError: If Arrow cannot convert a parameter or result value.
|
|
1410
|
+
"""
|
|
1411
|
+
dialect_name = state[0]
|
|
1412
|
+
returns_rows = cached.operation_profile.returns_rows
|
|
1413
|
+
if dialect_name == "db2" and not returns_rows and params:
|
|
1414
|
+
return None
|
|
1415
|
+
try:
|
|
1416
|
+
cursor = (
|
|
1417
|
+
_open_snowflake_cache_hit_cursor(connection, state[1])
|
|
1418
|
+
if dialect_name == "snowflake"
|
|
1419
|
+
else connection.cursor()
|
|
1420
|
+
)
|
|
1421
|
+
try:
|
|
1422
|
+
execute = getattr(cursor, "execute", None)
|
|
1423
|
+
if execute is None:
|
|
1424
|
+
return None
|
|
1425
|
+
if not returns_rows:
|
|
1426
|
+
if not hasattr(cursor, "rowcount"):
|
|
1427
|
+
return None
|
|
1428
|
+
if params:
|
|
1429
|
+
execute(cached.compiled_sql, params)
|
|
1430
|
+
else:
|
|
1431
|
+
execute(cached.compiled_sql)
|
|
1432
|
+
return DMLResult(cached.operation_type, resolve_rowcount(cursor))
|
|
1433
|
+
fetchall = getattr(cursor, "fetchall", None)
|
|
1434
|
+
if fetchall is None:
|
|
1435
|
+
return None
|
|
1436
|
+
if params:
|
|
1437
|
+
execute(cached.compiled_sql, params)
|
|
1438
|
+
else:
|
|
1439
|
+
execute(cached.compiled_sql)
|
|
1440
|
+
fetched_data = fetchall()
|
|
1441
|
+
driver_features = state[1]
|
|
1442
|
+
description = cursor.description
|
|
1443
|
+
data, column_names = collect_rows(
|
|
1444
|
+
fetched_data,
|
|
1445
|
+
description,
|
|
1446
|
+
column_names=resolve_column_names(description, state[2], driver_features),
|
|
1447
|
+
driver_features=driver_features,
|
|
1448
|
+
)
|
|
1449
|
+
return SQLResult.create_cached_select(
|
|
1450
|
+
sql,
|
|
1451
|
+
statement_config,
|
|
1452
|
+
cached.processed_state,
|
|
1453
|
+
cached.compiled_sql,
|
|
1454
|
+
params,
|
|
1455
|
+
data,
|
|
1456
|
+
column_names,
|
|
1457
|
+
len(data),
|
|
1458
|
+
resolve_row_format(data),
|
|
1459
|
+
None,
|
|
1460
|
+
)
|
|
1461
|
+
finally:
|
|
1462
|
+
_close_cache_hit_cursor(cursor)
|
|
1463
|
+
except AdbcNativeError as exc:
|
|
1464
|
+
if dialect_name == "teradata":
|
|
1465
|
+
mapped_error = create_teradata_mapped_exception(exc)
|
|
1466
|
+
mapped_error.__cause__ = exc
|
|
1467
|
+
raise mapped_error from exc
|
|
1468
|
+
mapped_error = create_mapped_exception(exc)
|
|
1469
|
+
mapped_error.__cause__ = exc
|
|
1470
|
+
raise mapped_error from exc
|
|
1471
|
+
except Exception as exc:
|
|
1472
|
+
if _is_arrow_conversion_error(exc):
|
|
1473
|
+
msg = f"ADBC could not convert a parameter or result value: {exc}"
|
|
1474
|
+
mapped_error = DataError(msg)
|
|
1475
|
+
mapped_error.__cause__ = exc
|
|
1476
|
+
raise mapped_error from exc
|
|
1477
|
+
raise
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def _open_snowflake_cache_hit_cursor(connection: Any, driver_features: "dict[str, Any]") -> Any:
|
|
1481
|
+
"""Open a Snowflake cursor tagged with the configured query tag and active correlation id."""
|
|
1482
|
+
raw_tag = driver_features.get("query_tag")
|
|
1483
|
+
tag = raw_tag.strip() if isinstance(raw_tag, str) else ""
|
|
1484
|
+
correlation = CorrelationContext.get()
|
|
1485
|
+
if correlation and correlation != tag:
|
|
1486
|
+
tag = f"{tag}:{correlation}" if tag else correlation
|
|
1487
|
+
if tag:
|
|
1488
|
+
return connection.cursor(adbc_stmt_kwargs={"adbc.snowflake.statement.query_tag": tag})
|
|
1489
|
+
return connection.cursor()
|
|
1490
|
+
|
|
1491
|
+
|
|
1492
|
+
def _close_cache_hit_cursor(cursor: Any) -> None:
|
|
1493
|
+
"""Close a cursor, ignoring one that can no longer be closed."""
|
|
1494
|
+
try:
|
|
1495
|
+
cursor.close()
|
|
1496
|
+
except Exception:
|
|
1497
|
+
return
|
|
1498
|
+
|
|
1499
|
+
|
|
1500
|
+
def _is_arrow_conversion_error(error: BaseException) -> bool:
|
|
1501
|
+
"""Return whether an error is a PyArrow value or type conversion failure."""
|
|
1502
|
+
invalid_error = import_optional_attr("pyarrow", "ArrowInvalid")
|
|
1503
|
+
if isinstance(invalid_error, type) and isinstance(error, invalid_error):
|
|
1504
|
+
return True
|
|
1505
|
+
type_error = import_optional_attr("pyarrow", "ArrowTypeError")
|
|
1506
|
+
return isinstance(type_error, type) and isinstance(error, type_error)
|
|
1507
|
+
|
|
1508
|
+
|
|
1509
|
+
def resolve_many_rowcount(cursor: Any, parameter_sets: Any, *, fallback_count: "int | None" = None) -> int:
|
|
1510
|
+
"""Resolve execute_many rowcount with a parameter-count fallback.
|
|
1511
|
+
|
|
1512
|
+
Args:
|
|
1513
|
+
cursor: ADBC cursor with optional rowcount metadata.
|
|
1514
|
+
parameter_sets: Execute-many payload.
|
|
1515
|
+
fallback_count: Optional precomputed execute-many payload size.
|
|
1516
|
+
|
|
1517
|
+
Returns:
|
|
1518
|
+
Driver rowcount when available, otherwise parameter count when sized.
|
|
1519
|
+
"""
|
|
1520
|
+
rowcount = resolve_rowcount(cursor)
|
|
1521
|
+
if rowcount != -1:
|
|
1522
|
+
return rowcount
|
|
1523
|
+
if fallback_count is not None:
|
|
1524
|
+
return fallback_count
|
|
1525
|
+
if isinstance(parameter_sets, Sized):
|
|
1526
|
+
return len(parameter_sets)
|
|
1527
|
+
return -1
|
|
1528
|
+
|
|
1529
|
+
|
|
1530
|
+
def normalize_script_rowcount(previous: int, cursor: Any) -> int:
|
|
1531
|
+
"""Normalize script rowcount using the latest cursor value when present.
|
|
1532
|
+
|
|
1533
|
+
Args:
|
|
1534
|
+
previous: Previously recorded rowcount.
|
|
1535
|
+
cursor: ADBC cursor with optional rowcount metadata.
|
|
1536
|
+
|
|
1537
|
+
Returns:
|
|
1538
|
+
Updated rowcount value.
|
|
1539
|
+
"""
|
|
1540
|
+
rowcount = resolve_rowcount(cursor)
|
|
1541
|
+
return rowcount if rowcount != -1 else previous
|
|
1542
|
+
|
|
1543
|
+
|
|
1544
|
+
def resolve_parameter_casts(statement: "SQL") -> "dict[int, str]":
|
|
1545
|
+
"""Return parameter cast mapping from a compiled SQL statement."""
|
|
1546
|
+
processed_state = statement.get_processed_state()
|
|
1547
|
+
if processed_state is not Empty:
|
|
1548
|
+
return processed_state.parameter_casts or {}
|
|
1549
|
+
return {}
|
|
1550
|
+
|
|
1551
|
+
|
|
1552
|
+
def prepare_parameters_with_casts(
|
|
1553
|
+
parameters: Any,
|
|
1554
|
+
parameter_casts: "dict[int, str]",
|
|
1555
|
+
statement_config: "StatementConfig",
|
|
1556
|
+
*,
|
|
1557
|
+
dialect: str,
|
|
1558
|
+
json_serializer: "Callable[[Any], str]",
|
|
1559
|
+
) -> Any:
|
|
1560
|
+
"""Prepare parameters with cast-aware type coercion for ADBC."""
|
|
1561
|
+
json_encoder = statement_config.parameter_config.json_serializer or json_serializer
|
|
1562
|
+
|
|
1563
|
+
if isinstance(parameters, (list, tuple)):
|
|
1564
|
+
converter = get_adbc_type_converter(dialect)
|
|
1565
|
+
type_map = statement_config.parameter_config.type_coercion_map
|
|
1566
|
+
dispatcher = type_coercion_dispatcher(tuple(type_map.items())) if type_map else None
|
|
1567
|
+
return _prepare_parameter_sequence_with_casts(
|
|
1568
|
+
parameters, parameter_casts, type_map, dispatcher, converter, json_encoder
|
|
1569
|
+
)
|
|
1570
|
+
return parameters
|
|
1571
|
+
|
|
1572
|
+
|
|
1573
|
+
def prepare_batch_with_casts(
|
|
1574
|
+
parameter_sets: Any,
|
|
1575
|
+
parameter_casts: "dict[int, str]",
|
|
1576
|
+
statement_config: "StatementConfig",
|
|
1577
|
+
*,
|
|
1578
|
+
dialect: str,
|
|
1579
|
+
json_serializer: "Callable[[Any], str]",
|
|
1580
|
+
) -> Any:
|
|
1581
|
+
"""Prepare an execute-many batch while sharing converter setup across rows."""
|
|
1582
|
+
if not isinstance(parameter_sets, (list, tuple)):
|
|
1583
|
+
return normalize_postgres_empty_parameters(dialect, parameter_sets)
|
|
1584
|
+
|
|
1585
|
+
postgres_compatible = [normalize_postgres_empty_parameters(dialect, row) for row in parameter_sets]
|
|
1586
|
+
if not parameter_casts:
|
|
1587
|
+
return postgres_compatible
|
|
1588
|
+
|
|
1589
|
+
json_encoder = statement_config.parameter_config.json_serializer or json_serializer
|
|
1590
|
+
converter = get_adbc_type_converter(dialect)
|
|
1591
|
+
type_map = statement_config.parameter_config.type_coercion_map
|
|
1592
|
+
dispatcher = type_coercion_dispatcher(tuple(type_map.items())) if type_map else None
|
|
1593
|
+
return [
|
|
1594
|
+
_prepare_parameter_sequence_with_casts(row, parameter_casts, type_map, dispatcher, converter, json_encoder)
|
|
1595
|
+
if isinstance(row, (list, tuple))
|
|
1596
|
+
else row
|
|
1597
|
+
for row in postgres_compatible
|
|
1598
|
+
]
|
|
1599
|
+
|
|
1600
|
+
|
|
1601
|
+
def prepare_postgres_uuid_bindings(
|
|
1602
|
+
compiled_sql: str, prepared_parameters: Any, *, is_many: bool, dialect: str
|
|
1603
|
+
) -> "tuple[str, object]":
|
|
1604
|
+
"""Bind top-level UUID values through PostgreSQL-family ADBC drivers.
|
|
1605
|
+
|
|
1606
|
+
Args:
|
|
1607
|
+
compiled_sql: SQL after normal statement compilation and cache rebinding.
|
|
1608
|
+
prepared_parameters: Current execution's driver parameters.
|
|
1609
|
+
is_many: Whether parameters contain an execute-many batch.
|
|
1610
|
+
dialect: Resolved ADBC dialect name.
|
|
1611
|
+
|
|
1612
|
+
Returns:
|
|
1613
|
+
Rewritten SQL and current-call parameters with UUID values normalized,
|
|
1614
|
+
or the inputs unchanged when no placeholder needs a new UUID cast.
|
|
1615
|
+
"""
|
|
1616
|
+
if not is_postgres_dialect(dialect):
|
|
1617
|
+
return compiled_sql, prepared_parameters
|
|
1618
|
+
if is_many:
|
|
1619
|
+
scalar_ordinals, array_ordinals = _detect_batch_uuid_ordinals(prepared_parameters)
|
|
1620
|
+
elif isinstance(prepared_parameters, (list, tuple)):
|
|
1621
|
+
scalar_ordinals, array_ordinals = _detect_uuid_ordinals(prepared_parameters)
|
|
1622
|
+
else:
|
|
1623
|
+
scalar_ordinals, array_ordinals = (), ()
|
|
1624
|
+
if not scalar_ordinals and not array_ordinals:
|
|
1625
|
+
return compiled_sql, prepared_parameters
|
|
1626
|
+
sqlglot_dialect = "postgres" if dialect == "postgresql" else dialect
|
|
1627
|
+
rewritten_sql, effective_scalars, effective_arrays = _rewrite_postgres_uuid_placeholders(
|
|
1628
|
+
compiled_sql, tuple(sorted(scalar_ordinals)), tuple(sorted(array_ordinals)), sqlglot_dialect
|
|
1629
|
+
)
|
|
1630
|
+
if not effective_scalars and not effective_arrays:
|
|
1631
|
+
return compiled_sql, prepared_parameters
|
|
1632
|
+
if is_many:
|
|
1633
|
+
converted_rows = [
|
|
1634
|
+
_convert_uuid_row(row, effective_scalars, effective_arrays, row_number)
|
|
1635
|
+
for row_number, row in enumerate(prepared_parameters, 1)
|
|
1636
|
+
]
|
|
1637
|
+
converted_parameters = tuple(converted_rows) if isinstance(prepared_parameters, tuple) else converted_rows
|
|
1638
|
+
else:
|
|
1639
|
+
converted_parameters = _convert_uuid_row(prepared_parameters, effective_scalars, effective_arrays, 1)
|
|
1640
|
+
return rewritten_sql, converted_parameters
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
def split_db2_table_name(table_name: str) -> "tuple[str | None, str]":
|
|
1644
|
+
"""Split qualified DB2 table name into schema and table components."""
|
|
1645
|
+
parts = [part.strip() for part in split_qualified_identifier(table_name, quote_chars='"') if part.strip()]
|
|
1646
|
+
if len(parts) >= _MIN_QUALIFIED_PARTS:
|
|
1647
|
+
return normalize_identifier(parts[-2], "db2"), normalize_identifier(parts[-1], "db2")
|
|
1648
|
+
return None, normalize_identifier(parts[0] if parts else table_name, "db2")
|
|
1649
|
+
|
|
1650
|
+
|
|
1651
|
+
def split_teradata_table_name(table_name: str) -> tuple[str | None, str]:
|
|
1652
|
+
"""Split a qualified Teradata table name into optional database and table identifiers.
|
|
1653
|
+
|
|
1654
|
+
Args:
|
|
1655
|
+
table_name: Bare or database-qualified Teradata table name.
|
|
1656
|
+
|
|
1657
|
+
Returns:
|
|
1658
|
+
Tuple of ``(database_or_none, table)`` with unquoted segments uppercased
|
|
1659
|
+
and double-quoted segments preserved with ``""`` unescaped.
|
|
1660
|
+
|
|
1661
|
+
Raises:
|
|
1662
|
+
ImproperConfigurationError: If the table name is empty, malformed, or has more than two parts.
|
|
1663
|
+
"""
|
|
1664
|
+
cleaned = table_name.strip()
|
|
1665
|
+
if not cleaned or cleaned.startswith(".") or cleaned.endswith("."):
|
|
1666
|
+
msg = f"Invalid Teradata table name: {table_name!r}"
|
|
1667
|
+
raise ImproperConfigurationError(msg)
|
|
1668
|
+
parts = _split_raw_teradata_segments(cleaned)
|
|
1669
|
+
if not parts or len(parts) > _MAX_TERADATA_QUALIFIED_PARTS or any(not part.strip() for part in parts):
|
|
1670
|
+
msg = f"Invalid Teradata table name {table_name!r}: expected '[database.]table'"
|
|
1671
|
+
raise ImproperConfigurationError(msg)
|
|
1672
|
+
if len(parts) == _MAX_TERADATA_QUALIFIED_PARTS:
|
|
1673
|
+
return (
|
|
1674
|
+
_normalize_teradata_identifier_segment(parts[0], table_name),
|
|
1675
|
+
_normalize_teradata_identifier_segment(parts[1], table_name),
|
|
1676
|
+
)
|
|
1677
|
+
return None, _normalize_teradata_identifier_segment(parts[0], table_name)
|
|
1678
|
+
|
|
1679
|
+
|
|
1680
|
+
def _map_adbc_status_exception(error: Any) -> "SQLSpecError | None":
|
|
1681
|
+
status_code = getattr(error, "status_code", None)
|
|
1682
|
+
if status_code is None:
|
|
1683
|
+
return None
|
|
1684
|
+
status_name: str | None = getattr(status_code, "name", None)
|
|
1685
|
+
if status_name is None and isinstance(status_code, int) and AdbcStatusCode is not None:
|
|
1686
|
+
with contextlib.suppress(ValueError):
|
|
1687
|
+
status_name = AdbcStatusCode(status_code).name
|
|
1688
|
+
if status_name is None:
|
|
1689
|
+
status_name = str(status_code).upper()
|
|
1690
|
+
if status_name in _ADBC_STATUS_CODE_MAP:
|
|
1691
|
+
exc_cls, desc = _ADBC_STATUS_CODE_MAP[status_name]
|
|
1692
|
+
return _create_adbc_error(error, exc_cls, desc)
|
|
1693
|
+
return None
|
|
1694
|
+
|
|
1695
|
+
|
|
1696
|
+
def _create_mapped_exception(error: Any, *, assume_teradata: bool) -> SQLSpecError:
|
|
1697
|
+
status_mapped = _map_adbc_status_exception(error)
|
|
1698
|
+
if isinstance(status_mapped, (QueryTimeoutError, OperationCancelledError)):
|
|
1699
|
+
return status_mapped
|
|
1700
|
+
|
|
1701
|
+
raw_message = str(error)
|
|
1702
|
+
error_msg = raw_message.lower()
|
|
1703
|
+
sqlstate_attr = error.sqlstate if has_sqlstate(error) else None
|
|
1704
|
+
sqlstate = sqlstate_attr.strip().upper() if isinstance(sqlstate_attr, str) and sqlstate_attr.strip() else None
|
|
1705
|
+
|
|
1706
|
+
if enterprise_mapped := _map_enterprise_exception(
|
|
1707
|
+
error, raw_message, error_msg, sqlstate, assume_teradata=assume_teradata
|
|
1708
|
+
):
|
|
1709
|
+
return enterprise_mapped
|
|
1710
|
+
|
|
1711
|
+
if sqlstate:
|
|
1712
|
+
return _map_sqlstate_exception(error, sqlstate)
|
|
1713
|
+
|
|
1714
|
+
if "unique" in error_msg or "duplicate" in error_msg:
|
|
1715
|
+
return _create_adbc_error(error, UniqueViolationError, "unique constraint violation")
|
|
1716
|
+
if "foreign key" in error_msg:
|
|
1717
|
+
return _create_adbc_error(error, ForeignKeyViolationError, "foreign key constraint violation")
|
|
1718
|
+
if "not null" in error_msg or "null value" in error_msg:
|
|
1719
|
+
return _create_adbc_error(error, NotNullViolationError, "not-null constraint violation")
|
|
1720
|
+
if "check constraint" in error_msg:
|
|
1721
|
+
return _create_adbc_error(error, CheckViolationError, "check constraint violation")
|
|
1722
|
+
if "constraint" in error_msg:
|
|
1723
|
+
return _create_adbc_error(error, IntegrityError, "integrity constraint violation")
|
|
1724
|
+
|
|
1725
|
+
if "deadlock" in error_msg:
|
|
1726
|
+
return _create_adbc_error(error, DeadlockError, "deadlock detected")
|
|
1727
|
+
if "serialization" in error_msg or "concurrent update" in error_msg:
|
|
1728
|
+
return _create_adbc_error(error, SerializationConflictError, "serialization failure")
|
|
1729
|
+
|
|
1730
|
+
if message_class := _classify_timeout_or_cancellation(error_msg):
|
|
1731
|
+
return _create_adbc_error(error, message_class, "query terminated")
|
|
1732
|
+
|
|
1733
|
+
if "permission" in error_msg or "denied" in error_msg or "unauthorized" in error_msg:
|
|
1734
|
+
return _create_adbc_error(error, PermissionDeniedError, "permission denied")
|
|
1735
|
+
|
|
1736
|
+
if "syntax" in error_msg:
|
|
1737
|
+
return _create_adbc_error(error, SQLParsingError, "SQL parsing error")
|
|
1738
|
+
|
|
1739
|
+
if "connection" in error_msg or "connect" in error_msg:
|
|
1740
|
+
return _create_adbc_error(error, DatabaseConnectionError, "connection error")
|
|
1741
|
+
|
|
1742
|
+
if status_mapped is not None:
|
|
1743
|
+
return status_mapped
|
|
1744
|
+
|
|
1745
|
+
return _create_adbc_error(error, SQLSpecError, "database error")
|
|
1746
|
+
|
|
1747
|
+
|
|
1748
|
+
def _try_rollback(rollback: "Callable[[], Any]") -> bool:
|
|
1749
|
+
"""Run a rollback callable and report whether it succeeded.
|
|
1750
|
+
|
|
1751
|
+
Args:
|
|
1752
|
+
rollback: Zero-argument callable performing the rollback.
|
|
1753
|
+
|
|
1754
|
+
Returns:
|
|
1755
|
+
True if the rollback completed without raising.
|
|
1756
|
+
"""
|
|
1757
|
+
try:
|
|
1758
|
+
rollback()
|
|
1759
|
+
except Exception:
|
|
1760
|
+
return False
|
|
1761
|
+
return True
|
|
1762
|
+
|
|
1763
|
+
|
|
1764
|
+
def _log_rollback(logger: "Any | None") -> None:
|
|
1765
|
+
"""Record that a PostgreSQL rollback completed.
|
|
1766
|
+
|
|
1767
|
+
Args:
|
|
1768
|
+
logger: Optional logger for diagnostics.
|
|
1769
|
+
"""
|
|
1770
|
+
if logger is not None:
|
|
1771
|
+
logger.debug("PostgreSQL rollback executed after transaction failure")
|
|
1772
|
+
|
|
1773
|
+
|
|
1774
|
+
def _identity(value: Any) -> Any:
|
|
1775
|
+
return value
|
|
1776
|
+
|
|
1777
|
+
|
|
1778
|
+
def _convert_array_for_postgres_adbc(value: Any) -> Any:
|
|
1779
|
+
"""Convert array values for PostgreSQL compatibility."""
|
|
1780
|
+
|
|
1781
|
+
if isinstance(value, tuple):
|
|
1782
|
+
return list(value)
|
|
1783
|
+
return value
|
|
1784
|
+
|
|
1785
|
+
|
|
1786
|
+
_BASE_TYPE_COERCION_MAP: Final[dict[type, Any]] = {
|
|
1787
|
+
dt.datetime: _identity,
|
|
1788
|
+
dt.date: _identity,
|
|
1789
|
+
dt.time: _identity,
|
|
1790
|
+
decimal.Decimal: _identity,
|
|
1791
|
+
bool: _identity,
|
|
1792
|
+
int: _identity,
|
|
1793
|
+
float: _identity,
|
|
1794
|
+
bytes: _identity,
|
|
1795
|
+
bytearray: bytes,
|
|
1796
|
+
memoryview: bytes,
|
|
1797
|
+
tuple: _convert_array_for_postgres_adbc,
|
|
1798
|
+
list: _convert_array_for_postgres_adbc,
|
|
1799
|
+
dict: _identity,
|
|
1800
|
+
UUID: _identity,
|
|
1801
|
+
**build_uuid_coercions(native=True),
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def _parameter_ordinal(parameter: exp.Parameter) -> "int | None":
|
|
1806
|
+
value = parameter.this
|
|
1807
|
+
if not isinstance(value, exp.Literal) or value.is_string:
|
|
1808
|
+
return None
|
|
1809
|
+
try:
|
|
1810
|
+
return int(value.this)
|
|
1811
|
+
except (TypeError, ValueError):
|
|
1812
|
+
return None
|
|
1813
|
+
|
|
1814
|
+
|
|
1815
|
+
def _direct_parameter_cast(parameter: exp.Parameter) -> "exp.Cast | None":
|
|
1816
|
+
current: exp.Expression = parameter
|
|
1817
|
+
parent = current.parent
|
|
1818
|
+
while isinstance(parent, exp.Paren):
|
|
1819
|
+
current = parent
|
|
1820
|
+
parent = current.parent
|
|
1821
|
+
if isinstance(parent, exp.Cast) and parent.this is current:
|
|
1822
|
+
return parent
|
|
1823
|
+
return None
|
|
1824
|
+
|
|
1825
|
+
|
|
1826
|
+
def _is_uuid_data_type(target: Any) -> bool:
|
|
1827
|
+
"""Report whether a cast target names the scalar ``UUID`` type."""
|
|
1828
|
+
if not isinstance(target, exp.DataType):
|
|
1829
|
+
return False
|
|
1830
|
+
if target.this == exp.DataType.Type.UUID:
|
|
1831
|
+
return True
|
|
1832
|
+
target_kind = target.args.get("kind")
|
|
1833
|
+
if isinstance(target_kind, exp.Dot):
|
|
1834
|
+
target_kind = target_kind.expression
|
|
1835
|
+
return (
|
|
1836
|
+
target.this == exp.DataType.Type.USERDEFINED
|
|
1837
|
+
and isinstance(target_kind, exp.Identifier)
|
|
1838
|
+
and target_kind.name.lower() == "uuid"
|
|
1839
|
+
)
|
|
1840
|
+
|
|
1841
|
+
|
|
1842
|
+
def _is_uuid_array_data_type(target: Any) -> bool:
|
|
1843
|
+
"""Report whether a cast target names a one-dimensional ``UUID[]`` type."""
|
|
1844
|
+
if not isinstance(target, exp.DataType) or target.this != exp.DataType.Type.ARRAY:
|
|
1845
|
+
return False
|
|
1846
|
+
element_types = target.expressions
|
|
1847
|
+
return len(element_types) == 1 and _is_uuid_data_type(element_types[0])
|
|
1848
|
+
|
|
1849
|
+
|
|
1850
|
+
@mypyc_attr(allow_interpreted_subclasses=False)
|
|
1851
|
+
class _RewriteCacheState:
|
|
1852
|
+
__slots__ = ("cache", "hits", "maxsize", "misses")
|
|
1853
|
+
|
|
1854
|
+
def __init__(self, maxsize: int = 256) -> None:
|
|
1855
|
+
self.maxsize = maxsize
|
|
1856
|
+
self.hits = 0
|
|
1857
|
+
self.misses = 0
|
|
1858
|
+
self.cache: dict[
|
|
1859
|
+
tuple[str, tuple[int, ...], tuple[int, ...], str], tuple[str, tuple[int, ...], tuple[int, ...]]
|
|
1860
|
+
] = {}
|
|
1861
|
+
|
|
1862
|
+
def clear(self) -> None:
|
|
1863
|
+
self.hits = 0
|
|
1864
|
+
self.misses = 0
|
|
1865
|
+
self.cache.clear()
|
|
1866
|
+
|
|
1867
|
+
|
|
1868
|
+
_REWRITE_CACHE_STATE: Final[_RewriteCacheState] = _RewriteCacheState(256)
|
|
1869
|
+
_REWRITE_UUID_CACHE: Final[
|
|
1870
|
+
dict[tuple[str, tuple[int, ...], tuple[int, ...], str], tuple[str, tuple[int, ...], tuple[int, ...]]]
|
|
1871
|
+
] = _REWRITE_CACHE_STATE.cache
|
|
1872
|
+
|
|
1873
|
+
|
|
1874
|
+
def _rewrite_postgres_uuid_placeholders(
|
|
1875
|
+
sql: str, scalar_ordinals: "tuple[int, ...]", array_ordinals: "tuple[int, ...]", dialect: str
|
|
1876
|
+
) -> "tuple[str, tuple[int, ...], tuple[int, ...]]":
|
|
1877
|
+
"""Wrap requested UUID parameter placeholders in explicit UUID or UUID[] casts.
|
|
1878
|
+
|
|
1879
|
+
Placeholders already carrying the cast their ordinal requires keep that cast
|
|
1880
|
+
and stay effective. Placeholders carrying any other explicit cast stay
|
|
1881
|
+
authoritative and are excluded from the returned effective ordinals. Results
|
|
1882
|
+
are memoized per ``(sql, scalar_ordinals, array_ordinals, dialect)`` so
|
|
1883
|
+
repeated executions of the same statement shape reuse the rewrite without
|
|
1884
|
+
parsing again.
|
|
1885
|
+
"""
|
|
1886
|
+
cache_key = (sql, scalar_ordinals, array_ordinals, dialect)
|
|
1887
|
+
cached = _REWRITE_CACHE_STATE.cache.get(cache_key)
|
|
1888
|
+
if cached is not None:
|
|
1889
|
+
_REWRITE_CACHE_STATE.hits += 1
|
|
1890
|
+
return cached
|
|
1891
|
+
|
|
1892
|
+
_REWRITE_CACHE_STATE.misses += 1
|
|
1893
|
+
try:
|
|
1894
|
+
expressions = cast(
|
|
1895
|
+
"list[exp.Expression]",
|
|
1896
|
+
[expression for expression in sqlglot.parse(sql, read=dialect) if expression is not None],
|
|
1897
|
+
)
|
|
1898
|
+
except ParseError as exc:
|
|
1899
|
+
msg = f"Failed to parse PostgreSQL ADBC SQL for UUID parameter binding: {exc}"
|
|
1900
|
+
raise with_cause(SQLSpecError(msg), exc) from exc
|
|
1901
|
+
if not expressions:
|
|
1902
|
+
msg = "Failed to parse PostgreSQL ADBC SQL for UUID parameter binding: SQLGlot returned no statements."
|
|
1903
|
+
raise SQLSpecError(msg)
|
|
1904
|
+
|
|
1905
|
+
array_requested = set(array_ordinals)
|
|
1906
|
+
requested = set(scalar_ordinals) | array_requested
|
|
1907
|
+
authoritative: set[int] = set()
|
|
1908
|
+
for expression in expressions:
|
|
1909
|
+
for parameter in expression.find_all(exp.Parameter):
|
|
1910
|
+
ordinal = _parameter_ordinal(parameter)
|
|
1911
|
+
if ordinal is None or ordinal not in requested:
|
|
1912
|
+
continue
|
|
1913
|
+
cast_expression = _direct_parameter_cast(parameter)
|
|
1914
|
+
if cast_expression is None:
|
|
1915
|
+
continue
|
|
1916
|
+
target = cast_expression.args.get("to")
|
|
1917
|
+
matches_required_cast = (
|
|
1918
|
+
_is_uuid_array_data_type(target) if ordinal in array_requested else _is_uuid_data_type(target)
|
|
1919
|
+
)
|
|
1920
|
+
if not matches_required_cast:
|
|
1921
|
+
authoritative.add(ordinal)
|
|
1922
|
+
effective_scalars = tuple(ordinal for ordinal in scalar_ordinals if ordinal not in authoritative)
|
|
1923
|
+
effective_arrays = tuple(ordinal for ordinal in array_ordinals if ordinal not in authoritative)
|
|
1924
|
+
effective_array_set = set(effective_arrays)
|
|
1925
|
+
effective_set = set(effective_scalars) | effective_array_set
|
|
1926
|
+
|
|
1927
|
+
for expression in expressions:
|
|
1928
|
+
for node in list(expression.find_all(exp.Parameter)):
|
|
1929
|
+
ordinal = _parameter_ordinal(node)
|
|
1930
|
+
if ordinal is None or ordinal not in effective_set:
|
|
1931
|
+
continue
|
|
1932
|
+
if _direct_parameter_cast(node) is not None:
|
|
1933
|
+
continue
|
|
1934
|
+
target_type = "UUID[]" if ordinal in effective_array_set else "UUID"
|
|
1935
|
+
node.replace(exp.Cast(this=node.copy(), to=exp.DataType.build(target_type, dialect=dialect)))
|
|
1936
|
+
|
|
1937
|
+
rewritten = "; ".join(expression.sql(dialect=dialect, copy=False) for expression in expressions)
|
|
1938
|
+
result = (rewritten, effective_scalars, effective_arrays)
|
|
1939
|
+
if len(_REWRITE_CACHE_STATE.cache) >= _REWRITE_CACHE_STATE.maxsize:
|
|
1940
|
+
_REWRITE_CACHE_STATE.cache.pop(next(iter(_REWRITE_CACHE_STATE.cache)))
|
|
1941
|
+
_REWRITE_CACHE_STATE.cache[cache_key] = result
|
|
1942
|
+
return result
|
|
1943
|
+
|
|
1944
|
+
|
|
1945
|
+
def _sequence_holds_uuid(values: "list[Any] | tuple[Any, ...]") -> bool:
|
|
1946
|
+
"""Report whether a sequence's first non-null element is a UUID."""
|
|
1947
|
+
for value in values:
|
|
1948
|
+
if value is not None:
|
|
1949
|
+
return isinstance(value, _UUID_TYPES)
|
|
1950
|
+
return False
|
|
1951
|
+
|
|
1952
|
+
|
|
1953
|
+
def _detect_uuid_ordinals(parameters: "list[Any] | tuple[Any, ...]") -> "tuple[tuple[int, ...], tuple[int, ...]]":
|
|
1954
|
+
"""Split a parameter sequence into scalar-UUID and UUID-array ordinals."""
|
|
1955
|
+
scalar_ordinals: list[int] = []
|
|
1956
|
+
array_ordinals: list[int] = []
|
|
1957
|
+
for ordinal, value in enumerate(parameters, 1):
|
|
1958
|
+
if isinstance(value, _UUID_TYPES):
|
|
1959
|
+
scalar_ordinals.append(ordinal)
|
|
1960
|
+
elif isinstance(value, (list, tuple)) and _sequence_holds_uuid(value):
|
|
1961
|
+
array_ordinals.append(ordinal)
|
|
1962
|
+
return tuple(scalar_ordinals), tuple(array_ordinals)
|
|
1963
|
+
|
|
1964
|
+
|
|
1965
|
+
def _detect_batch_uuid_ordinals(parameters: Any) -> "tuple[tuple[int, ...], tuple[int, ...]]":
|
|
1966
|
+
if not isinstance(parameters, (list, tuple)) or not parameters:
|
|
1967
|
+
return (), ()
|
|
1968
|
+
first_row = parameters[0]
|
|
1969
|
+
if not isinstance(first_row, (list, tuple)):
|
|
1970
|
+
return (), ()
|
|
1971
|
+
expected_size = len(first_row)
|
|
1972
|
+
for row in parameters:
|
|
1973
|
+
if not isinstance(row, (list, tuple)) or len(row) != expected_size:
|
|
1974
|
+
return (), ()
|
|
1975
|
+
scalar_ordinals: list[int] = []
|
|
1976
|
+
array_ordinals: list[int] = []
|
|
1977
|
+
for ordinal in range(1, expected_size + 1):
|
|
1978
|
+
values = [row[ordinal - 1] for row in parameters]
|
|
1979
|
+
if any(isinstance(value, _UUID_TYPES) for value in values):
|
|
1980
|
+
scalar_ordinals.append(ordinal)
|
|
1981
|
+
elif any(isinstance(value, (list, tuple)) and _sequence_holds_uuid(value) for value in values):
|
|
1982
|
+
array_ordinals.append(ordinal)
|
|
1983
|
+
return tuple(scalar_ordinals), tuple(array_ordinals)
|
|
1984
|
+
|
|
1985
|
+
|
|
1986
|
+
def _uuid_binding_error(ordinal: int, value: Any, row_number: int, element_index: "int | None" = None) -> str:
|
|
1987
|
+
"""Build the incompatible-value message for a UUID parameter ordinal."""
|
|
1988
|
+
location = "" if element_index is None else f" at element {element_index}"
|
|
1989
|
+
return (
|
|
1990
|
+
f"ADBC PostgreSQL UUID parameter ordinal {ordinal} has incompatible "
|
|
1991
|
+
f"{type(value).__name__} value{location} in batch row {row_number}; expected a UUID object, "
|
|
1992
|
+
"parseable UUID string, or None."
|
|
1993
|
+
)
|
|
1994
|
+
|
|
1995
|
+
|
|
1996
|
+
def _convert_uuid_value(value: Any, ordinal: int, row_number: int, element_index: "int | None" = None) -> Any:
|
|
1997
|
+
"""Normalize one UUID-bound value to its canonical string form."""
|
|
1998
|
+
if value is None:
|
|
1999
|
+
return None
|
|
2000
|
+
if isinstance(value, _UUID_TYPES):
|
|
2001
|
+
return str(value)
|
|
2002
|
+
if not isinstance(value, str):
|
|
2003
|
+
raise SQLSpecError(_uuid_binding_error(ordinal, value, row_number, element_index))
|
|
2004
|
+
try:
|
|
2005
|
+
return str(uuid_from_string(value))
|
|
2006
|
+
except (TypeError, ValueError) as exc:
|
|
2007
|
+
raise with_cause(SQLSpecError(_uuid_binding_error(ordinal, value, row_number, element_index)), exc) from exc
|
|
2008
|
+
|
|
2009
|
+
|
|
2010
|
+
def _null_array_element_error(ordinal: int, row_number: int, element_index: int) -> str:
|
|
2011
|
+
"""Build the null-array-element message for a UUID array parameter ordinal."""
|
|
2012
|
+
return (
|
|
2013
|
+
f"ADBC PostgreSQL UUID parameter ordinal {ordinal} has a null value at element {element_index} "
|
|
2014
|
+
f"in batch row {row_number}; the PostgreSQL ADBC driver encodes null array elements as empty "
|
|
2015
|
+
"strings, which PostgreSQL rejects for UUID[]. Remove the null element or bind the array as text."
|
|
2016
|
+
)
|
|
2017
|
+
|
|
2018
|
+
|
|
2019
|
+
def _convert_uuid_sequence(values: Any, ordinal: int, row_number: int) -> "list[Any]":
|
|
2020
|
+
"""Normalize every element of a UUID array parameter."""
|
|
2021
|
+
converted: list[Any] = []
|
|
2022
|
+
for element_index, value in enumerate(values, 1):
|
|
2023
|
+
if value is None:
|
|
2024
|
+
raise SQLSpecError(_null_array_element_error(ordinal, row_number, element_index))
|
|
2025
|
+
converted.append(_convert_uuid_value(value, ordinal, row_number, element_index))
|
|
2026
|
+
return converted
|
|
2027
|
+
|
|
2028
|
+
|
|
2029
|
+
def _convert_uuid_row(
|
|
2030
|
+
row: Any, scalar_ordinals: "tuple[int, ...]", array_ordinals: "tuple[int, ...]", row_number: int
|
|
2031
|
+
) -> Any:
|
|
2032
|
+
converted = list(row)
|
|
2033
|
+
for ordinal in scalar_ordinals:
|
|
2034
|
+
converted[ordinal - 1] = _convert_uuid_value(converted[ordinal - 1], ordinal, row_number)
|
|
2035
|
+
for ordinal in array_ordinals:
|
|
2036
|
+
value = converted[ordinal - 1]
|
|
2037
|
+
if value is None:
|
|
2038
|
+
continue
|
|
2039
|
+
if not isinstance(value, (list, tuple)):
|
|
2040
|
+
raise SQLSpecError(_uuid_binding_error(ordinal, value, row_number))
|
|
2041
|
+
converted[ordinal - 1] = _convert_uuid_sequence(value, ordinal, row_number)
|
|
2042
|
+
return tuple(converted) if isinstance(row, tuple) else converted
|
|
2043
|
+
|
|
2044
|
+
|
|
2045
|
+
def _create_adbc_error(error: Any, error_class: type[SQLSpecError], description: str) -> SQLSpecError:
|
|
2046
|
+
"""Create an ADBC error instance without raising it."""
|
|
2047
|
+
msg = f"ADBC {description}: {error}"
|
|
2048
|
+
exc = error_class(msg)
|
|
2049
|
+
exc.__cause__ = error
|
|
2050
|
+
return exc
|
|
2051
|
+
|
|
2052
|
+
|
|
2053
|
+
def _get_sqlstate_description(sqlstate: str) -> str:
|
|
2054
|
+
"""Get a human-readable description for a SQLSTATE code class."""
|
|
2055
|
+
class_code = sqlstate[:_SQLSTATE_CLASS_CODE_LEN] if len(sqlstate) >= _SQLSTATE_CLASS_CODE_LEN else sqlstate
|
|
2056
|
+
return _SQLSTATE_DESCRIPTIONS.get(class_code, "database error")
|
|
2057
|
+
|
|
2058
|
+
|
|
2059
|
+
def _map_oracle_exception(error: Any, raw_message: str) -> "SQLSpecError | None":
|
|
2060
|
+
match = _ORA_CODE_PATTERN.search(raw_message)
|
|
2061
|
+
if match is None:
|
|
2062
|
+
return None
|
|
2063
|
+
code = int(match.group(1))
|
|
2064
|
+
if code in _ORA_ERROR_CODE_MAP:
|
|
2065
|
+
exc_cls, desc = _ORA_ERROR_CODE_MAP[code]
|
|
2066
|
+
return _create_adbc_error(error, exc_cls, desc)
|
|
2067
|
+
if _ORA_INTEGRITY_START <= code < _ORA_INTEGRITY_END:
|
|
2068
|
+
return _create_adbc_error(error, IntegrityError, "integrity constraint violation")
|
|
2069
|
+
if _ORA_PARSING_START <= code < _ORA_PARSING_END:
|
|
2070
|
+
return _create_adbc_error(error, SQLParsingError, "SQL parsing error")
|
|
2071
|
+
return None
|
|
2072
|
+
|
|
2073
|
+
|
|
2074
|
+
def _extract_db2_sqlcode(error: Any, raw_message: str, has_db2_marker: bool) -> "int | None":
|
|
2075
|
+
match = _DB2_SQLCODE_PATTERN.search(raw_message)
|
|
2076
|
+
if match is not None:
|
|
2077
|
+
return abs(int(match.group(1)))
|
|
2078
|
+
vendor_code = getattr(error, "vendor_code", None)
|
|
2079
|
+
if isinstance(vendor_code, int) and (vendor_code < 0 or has_db2_marker):
|
|
2080
|
+
return abs(vendor_code)
|
|
2081
|
+
return None
|
|
2082
|
+
|
|
2083
|
+
|
|
2084
|
+
def _map_db2_exception(
|
|
2085
|
+
error: Any, raw_message: str, lowered_message: str, explicit_sqlstate: "str | None"
|
|
2086
|
+
) -> "SQLSpecError | None":
|
|
2087
|
+
sqlstate = explicit_sqlstate
|
|
2088
|
+
if sqlstate is None:
|
|
2089
|
+
state_matches = _DB2_SQLSTATE_PATTERN.findall(raw_message)
|
|
2090
|
+
if state_matches:
|
|
2091
|
+
sqlstate = str(state_matches[-1]).upper()
|
|
2092
|
+
|
|
2093
|
+
has_db2_marker = (
|
|
2094
|
+
"db2" in lowered_message
|
|
2095
|
+
or "sqlstate=" in lowered_message
|
|
2096
|
+
or "reason code" in lowered_message
|
|
2097
|
+
or _DB2_SQLCODE_PATTERN.search(raw_message) is not None
|
|
2098
|
+
)
|
|
2099
|
+
sqlcode = _extract_db2_sqlcode(error, raw_message, has_db2_marker)
|
|
2100
|
+
if not has_db2_marker and sqlcode is None and sqlstate not in {"57033", "42704"}:
|
|
2101
|
+
return None
|
|
2102
|
+
|
|
2103
|
+
if sqlstate in _DB2_ROLLBACK_SQLSTATES or (sqlcode is not None and sqlcode in _DB2_ROLLBACK_SQLCODES):
|
|
2104
|
+
reason_match = _DB2_REASON_CODE_PATTERN.search(raw_message)
|
|
2105
|
+
if reason_match is not None and int(reason_match.group(1)) == _DB2_LOCK_TIMEOUT_REASON_CODE:
|
|
2106
|
+
return _create_adbc_error(error, QueryTimeoutError, "lock timeout")
|
|
2107
|
+
if sqlstate == "57033" or (sqlcode is not None and sqlcode in _DB2_ROLLBACK_SQLCODES) or has_db2_marker:
|
|
2108
|
+
return _create_adbc_error(error, DeadlockError, "deadlock detected")
|
|
2109
|
+
|
|
2110
|
+
if sqlstate == "42704" or sqlcode == _DB2_UNDEFINED_OBJECT_CODE:
|
|
2111
|
+
return _create_adbc_error(error, SQLParsingError, "undefined object")
|
|
2112
|
+
if sqlstate == "42501" or (sqlcode is not None and sqlcode in {551, 552}):
|
|
2113
|
+
return _create_adbc_error(error, PermissionDeniedError, "permission denied")
|
|
2114
|
+
|
|
2115
|
+
if sqlcode is not None and sqlcode in _DB2_SQLCODE_MAP:
|
|
2116
|
+
exc_cls, desc = _DB2_SQLCODE_MAP[sqlcode]
|
|
2117
|
+
return _create_adbc_error(error, exc_cls, desc)
|
|
2118
|
+
return None
|
|
2119
|
+
|
|
2120
|
+
|
|
2121
|
+
def _map_mssql_exception(error: Any, raw_message: str, lowered_message: str) -> "SQLSpecError | None":
|
|
2122
|
+
has_mssql_marker = any(marker in lowered_message for marker in ("mssql", "sql server", "sqlserver", "tds:", "msg "))
|
|
2123
|
+
code: int | None = None
|
|
2124
|
+
vendor_code = getattr(error, "vendor_code", None)
|
|
2125
|
+
if isinstance(vendor_code, int) and vendor_code > 0 and has_mssql_marker:
|
|
2126
|
+
code = vendor_code
|
|
2127
|
+
else:
|
|
2128
|
+
msg_match = _MSSQL_MSG_NUMBER_PATTERN.search(raw_message)
|
|
2129
|
+
if msg_match is not None and has_mssql_marker:
|
|
2130
|
+
code = int(msg_match.group(1))
|
|
2131
|
+
|
|
2132
|
+
if code is None:
|
|
2133
|
+
return None
|
|
2134
|
+
if code == _MSSQL_CONSTRAINT_ERROR_CODE:
|
|
2135
|
+
if "check constraint" in lowered_message:
|
|
2136
|
+
return _create_adbc_error(error, CheckViolationError, "check constraint violation")
|
|
2137
|
+
return _create_adbc_error(error, ForeignKeyViolationError, "foreign key constraint violation")
|
|
2138
|
+
if code in _MSSQL_ERROR_CODE_MAP:
|
|
2139
|
+
exc_cls, desc = _MSSQL_ERROR_CODE_MAP[code]
|
|
2140
|
+
return _create_adbc_error(error, exc_cls, desc)
|
|
2141
|
+
return None
|
|
2142
|
+
|
|
2143
|
+
|
|
2144
|
+
def _map_enterprise_exception(
|
|
2145
|
+
error: Any, raw_message: str, lowered_message: str, sqlstate: "str | None", *, assume_teradata: bool = False
|
|
2146
|
+
) -> "SQLSpecError | None":
|
|
2147
|
+
if oracle_mapped := _map_oracle_exception(error, raw_message):
|
|
2148
|
+
return oracle_mapped
|
|
2149
|
+
if db2_mapped := _map_db2_exception(error, raw_message, lowered_message, sqlstate):
|
|
2150
|
+
return db2_mapped
|
|
2151
|
+
if snowflake_mapped := _map_snowflake_exception(error, raw_message):
|
|
2152
|
+
return snowflake_mapped
|
|
2153
|
+
if teradata_mapped := _map_teradata_exception(
|
|
2154
|
+
error, raw_message, lowered_message, sqlstate, assume_teradata=assume_teradata
|
|
2155
|
+
):
|
|
2156
|
+
return teradata_mapped
|
|
2157
|
+
return _map_mssql_exception(error, raw_message, lowered_message)
|
|
2158
|
+
|
|
2159
|
+
|
|
2160
|
+
def _map_sqlstate_exception(error: Any, sqlstate: str) -> SQLSpecError:
|
|
2161
|
+
if sqlstate == "25006":
|
|
2162
|
+
return _create_adbc_error(error, ReadOnlyTransactionError, "read-only transaction")
|
|
2163
|
+
if sqlstate == "23505":
|
|
2164
|
+
return _create_adbc_error(error, UniqueViolationError, "unique constraint violation")
|
|
2165
|
+
if sqlstate == "23503":
|
|
2166
|
+
return _create_adbc_error(error, ForeignKeyViolationError, "foreign key constraint violation")
|
|
2167
|
+
if sqlstate == "23502":
|
|
2168
|
+
return _create_adbc_error(error, NotNullViolationError, "not-null constraint violation")
|
|
2169
|
+
if sqlstate == "23514":
|
|
2170
|
+
return _create_adbc_error(error, CheckViolationError, "check constraint violation")
|
|
2171
|
+
|
|
2172
|
+
if sqlstate == "40P01":
|
|
2173
|
+
return _create_adbc_error(error, DeadlockError, "deadlock detected")
|
|
2174
|
+
if sqlstate == "40001":
|
|
2175
|
+
return _create_adbc_error(error, SerializationConflictError, "serialization failure")
|
|
2176
|
+
|
|
2177
|
+
if sqlstate == "57014":
|
|
2178
|
+
termination_class = _classify_timeout_or_cancellation(str(error)) or OperationalError
|
|
2179
|
+
return _create_adbc_error(error, termination_class, "query terminated")
|
|
2180
|
+
|
|
2181
|
+
if sqlstate == "42501":
|
|
2182
|
+
return _create_adbc_error(error, PermissionDeniedError, "insufficient privilege")
|
|
2183
|
+
if sqlstate == "28000":
|
|
2184
|
+
return _create_adbc_error(error, PermissionDeniedError, "invalid authorization")
|
|
2185
|
+
|
|
2186
|
+
exc_class = map_sqlstate_to_exception(sqlstate)
|
|
2187
|
+
if exc_class is not None and exc_class is not SQLSpecError:
|
|
2188
|
+
description = _get_sqlstate_description(sqlstate)
|
|
2189
|
+
return _create_adbc_error(error, exc_class, description)
|
|
2190
|
+
|
|
2191
|
+
return _create_adbc_error(error, SQLSpecError, "database error")
|
|
2192
|
+
|
|
2193
|
+
|
|
2194
|
+
def _validate_strict_parameter_value(value: Any) -> None:
|
|
2195
|
+
if isinstance(value, (list, tuple)):
|
|
2196
|
+
for item in value:
|
|
2197
|
+
_validate_strict_parameter_value(item)
|
|
2198
|
+
return
|
|
2199
|
+
if isinstance(value, dict):
|
|
2200
|
+
for item in value.values():
|
|
2201
|
+
_validate_strict_parameter_value(item)
|
|
2202
|
+
return
|
|
2203
|
+
if not isinstance(value, _STRICT_COERCION_ALLOWED_TYPES):
|
|
2204
|
+
msg = f"Unsupported parameter type for strict_type_coercion: {type(value).__name__}"
|
|
2205
|
+
raise SQLSpecError(msg)
|
|
2206
|
+
|
|
2207
|
+
|
|
2208
|
+
def _validate_strict_parameter_payload(parameters: Any) -> None:
|
|
2209
|
+
if isinstance(parameters, (list, tuple)):
|
|
2210
|
+
for item in parameters:
|
|
2211
|
+
_validate_strict_parameter_value(item)
|
|
2212
|
+
elif isinstance(parameters, dict):
|
|
2213
|
+
for item in parameters.values():
|
|
2214
|
+
_validate_strict_parameter_value(item)
|
|
2215
|
+
else:
|
|
2216
|
+
_validate_strict_parameter_value(parameters)
|
|
2217
|
+
|
|
2218
|
+
|
|
2219
|
+
def _transform_duckdb_copy_parameters(
|
|
2220
|
+
expression: Any, parameters: Any, _parameter_profile: Any = None, is_many: bool = False
|
|
2221
|
+
) -> "tuple[Any, Any]":
|
|
2222
|
+
"""Inline bound file-target placeholders in DuckDB ``COPY ... TO/FROM`` statements."""
|
|
2223
|
+
if is_many or not isinstance(expression, exp.Copy) or not isinstance(parameters, (list, tuple)) or not parameters:
|
|
2224
|
+
return expression, parameters
|
|
2225
|
+
|
|
2226
|
+
files = expression.args.get("files")
|
|
2227
|
+
if not isinstance(files, list) or not files:
|
|
2228
|
+
return expression, parameters
|
|
2229
|
+
|
|
2230
|
+
this_node = expression.this
|
|
2231
|
+
prefix_count = (
|
|
2232
|
+
len(list(this_node.find_all(exp.Placeholder, exp.Parameter))) if isinstance(this_node, exp.Expression) else 0
|
|
2233
|
+
)
|
|
2234
|
+
|
|
2235
|
+
inlined_indices: set[int] = set()
|
|
2236
|
+
new_files: list[Any] = list(files)
|
|
2237
|
+
file_qmark_offset = 0
|
|
2238
|
+
for idx, file_expr in enumerate(new_files):
|
|
2239
|
+
placeholder_node: exp.Expression | None = None
|
|
2240
|
+
if isinstance(file_expr, (exp.Placeholder, exp.Parameter)):
|
|
2241
|
+
placeholder_node = file_expr
|
|
2242
|
+
elif isinstance(file_expr, exp.Table) and isinstance(file_expr.this, (exp.Placeholder, exp.Parameter)):
|
|
2243
|
+
placeholder_node = file_expr.this
|
|
2244
|
+
|
|
2245
|
+
if placeholder_node is None:
|
|
2246
|
+
continue
|
|
2247
|
+
|
|
2248
|
+
param_idx: int | None = None
|
|
2249
|
+
if isinstance(placeholder_node, exp.Parameter):
|
|
2250
|
+
ordinal = _parameter_ordinal(placeholder_node)
|
|
2251
|
+
if ordinal is not None:
|
|
2252
|
+
param_idx = ordinal - 1
|
|
2253
|
+
elif isinstance(placeholder_node, exp.Placeholder):
|
|
2254
|
+
raw_val = placeholder_node.this
|
|
2255
|
+
if raw_val is not None and str(raw_val).lstrip("$").isdigit():
|
|
2256
|
+
param_idx = int(str(raw_val).lstrip("$")) - 1
|
|
2257
|
+
|
|
2258
|
+
if param_idx is None:
|
|
2259
|
+
param_idx = prefix_count + file_qmark_offset
|
|
2260
|
+
file_qmark_offset += 1
|
|
2261
|
+
|
|
2262
|
+
if 0 <= param_idx < len(parameters):
|
|
2263
|
+
new_files[idx] = exp.Literal.string(str(parameters[param_idx]))
|
|
2264
|
+
inlined_indices.add(param_idx)
|
|
2265
|
+
|
|
2266
|
+
if not inlined_indices:
|
|
2267
|
+
return expression, parameters
|
|
2268
|
+
|
|
2269
|
+
transformed_copy = expression.copy()
|
|
2270
|
+
transformed_copy.set("files", new_files)
|
|
2271
|
+
remaining = [val for idx, val in enumerate(parameters) if idx not in inlined_indices]
|
|
2272
|
+
if not remaining:
|
|
2273
|
+
return transformed_copy, []
|
|
2274
|
+
return transformed_copy, tuple(remaining) if isinstance(parameters, tuple) else remaining
|
|
2275
|
+
|
|
2276
|
+
|
|
2277
|
+
def _apply_adbc_json_serializer(
|
|
2278
|
+
statement_config: "StatementConfig", json_serializer: "Callable[[Any], str]"
|
|
2279
|
+
) -> "StatementConfig":
|
|
2280
|
+
"""Apply a JSON serializer to statement config while preserving list/tuple converters.
|
|
2281
|
+
|
|
2282
|
+
Args:
|
|
2283
|
+
statement_config: Base statement configuration to update.
|
|
2284
|
+
json_serializer: JSON serializer function.
|
|
2285
|
+
|
|
2286
|
+
Returns:
|
|
2287
|
+
Updated statement configuration.
|
|
2288
|
+
"""
|
|
2289
|
+
parameter_config = statement_config.parameter_config
|
|
2290
|
+
previous_list_converter = parameter_config.type_coercion_map.get(list)
|
|
2291
|
+
previous_tuple_converter = parameter_config.type_coercion_map.get(tuple)
|
|
2292
|
+
|
|
2293
|
+
updated_parameter_config = parameter_config.with_json_serializers(json_serializer)
|
|
2294
|
+
updated_map = dict(updated_parameter_config.type_coercion_map)
|
|
2295
|
+
|
|
2296
|
+
if previous_list_converter is not None:
|
|
2297
|
+
updated_map[list] = previous_list_converter
|
|
2298
|
+
if previous_tuple_converter is not None:
|
|
2299
|
+
updated_map[tuple] = previous_tuple_converter
|
|
2300
|
+
|
|
2301
|
+
return statement_config.replace(parameter_config=updated_parameter_config.replace(type_coercion_map=updated_map))
|
|
2302
|
+
|
|
2303
|
+
|
|
2304
|
+
def _prepare_parameter_sequence_with_casts(
|
|
2305
|
+
parameters: "list[Any] | tuple[Any, ...]",
|
|
2306
|
+
parameter_casts: "dict[int, str]",
|
|
2307
|
+
type_map: "dict[type, Callable[[Any], Any]]",
|
|
2308
|
+
dispatcher: "TypeDispatcher[Callable[[Any], Any]] | None",
|
|
2309
|
+
converter: Any,
|
|
2310
|
+
json_encoder: "Callable[[Any], str]",
|
|
2311
|
+
) -> "list[Any] | tuple[Any, ...]":
|
|
2312
|
+
result: list[Any] = []
|
|
2313
|
+
for idx, param in enumerate(parameters, start=1):
|
|
2314
|
+
cast_type = parameter_casts.get(idx, "").upper()
|
|
2315
|
+
if cast_type in {"JSON", "JSONB", "TYPE.JSON", "TYPE.JSONB"}:
|
|
2316
|
+
if isinstance(param, dict):
|
|
2317
|
+
result.append(json_encoder(param))
|
|
2318
|
+
else:
|
|
2319
|
+
result.append(param)
|
|
2320
|
+
elif isinstance(param, dict):
|
|
2321
|
+
if isinstance(converter, ADBCOutputConverter):
|
|
2322
|
+
result.append(converter.convert_dict(param, json_serializer=json_encoder))
|
|
2323
|
+
else:
|
|
2324
|
+
result.append(converter.convert_dict(param))
|
|
2325
|
+
elif isinstance(param, (list, tuple)):
|
|
2326
|
+
if type_map and dispatcher is not None:
|
|
2327
|
+
exact_converter = type_map.get(type(param))
|
|
2328
|
+
if exact_converter is not None:
|
|
2329
|
+
param = exact_converter(param)
|
|
2330
|
+
else:
|
|
2331
|
+
converter_func = dispatcher.get(param)
|
|
2332
|
+
if converter_func is not None:
|
|
2333
|
+
param = converter_func(param)
|
|
2334
|
+
elif hasattr(converter, "convert_sequence"):
|
|
2335
|
+
if isinstance(converter, ADBCOutputConverter):
|
|
2336
|
+
param = converter.convert_sequence(param, json_serializer=json_encoder)
|
|
2337
|
+
else:
|
|
2338
|
+
param = converter.convert_sequence(param)
|
|
2339
|
+
elif hasattr(converter, "convert_sequence"):
|
|
2340
|
+
if isinstance(converter, ADBCOutputConverter):
|
|
2341
|
+
param = converter.convert_sequence(param, json_serializer=json_encoder)
|
|
2342
|
+
else:
|
|
2343
|
+
param = converter.convert_sequence(param)
|
|
2344
|
+
result.append(param)
|
|
2345
|
+
else:
|
|
2346
|
+
if type_map and dispatcher is not None:
|
|
2347
|
+
exact_converter = type_map.get(type(param))
|
|
2348
|
+
if exact_converter is not None and type(param) is not dict:
|
|
2349
|
+
param = exact_converter(param)
|
|
2350
|
+
else:
|
|
2351
|
+
converter_func = dispatcher.get(param)
|
|
2352
|
+
if converter_func is not None and type(param) is not dict:
|
|
2353
|
+
param = converter_func(param)
|
|
2354
|
+
result.append(param)
|
|
2355
|
+
return tuple(result) if isinstance(parameters, tuple) else result
|
|
2356
|
+
|
|
2357
|
+
|
|
2358
|
+
def _resolve_gizmosql_driver_connect() -> str:
|
|
2359
|
+
"""Return the preferred GizmoSQL connect path based on installed packages."""
|
|
2360
|
+
if import_optional("adbc_driver_gizmosql") is not None:
|
|
2361
|
+
return _GIZMOSQL_NATIVE_CONNECT
|
|
2362
|
+
return _FLIGHTSQL_CONNECT
|
|
2363
|
+
|
|
2364
|
+
|
|
2365
|
+
def _resolve_mssql_driver_connect() -> str:
|
|
2366
|
+
"""Return the preferred SQL Server connect path based on installed packages."""
|
|
2367
|
+
if import_optional("adbc_driver_mssql") is not None:
|
|
2368
|
+
return _MSSQL_NATIVE_CONNECT
|
|
2369
|
+
return _DRIVER_MANAGER_CONNECT
|
|
2370
|
+
|
|
2371
|
+
|
|
2372
|
+
def _resolve_flightsql_db_kwargs_keys() -> "tuple[str, str]":
|
|
2373
|
+
database_options = import_optional_attr("adbc_driver_flightsql", "DatabaseOptions")
|
|
2374
|
+
if database_options is None:
|
|
2375
|
+
return _FLIGHTSQL_TLS_SKIP_VERIFY_KEY, _FLIGHTSQL_AUTHORIZATION_HEADER_KEY
|
|
2376
|
+
return (database_options.TLS_SKIP_VERIFY.value, database_options.AUTHORIZATION_HEADER.value)
|
|
2377
|
+
|
|
2378
|
+
|
|
2379
|
+
def _lift_flightsql_common_options(
|
|
2380
|
+
config: "dict[str, Any]", db_kwargs_dict: "dict[str, Any]", authorization_header_key: str
|
|
2381
|
+
) -> None:
|
|
2382
|
+
if "authorization_header" in config:
|
|
2383
|
+
auth_header = config.pop("authorization_header")
|
|
2384
|
+
if auth_header is not None:
|
|
2385
|
+
auth_header_text = str(auth_header)
|
|
2386
|
+
if "\x00" in auth_header_text or "\r" in auth_header_text or "\n" in auth_header_text:
|
|
2387
|
+
msg = "FlightSQL authorization_header contains disallowed control characters."
|
|
2388
|
+
raise ImproperConfigurationError(msg)
|
|
2389
|
+
db_kwargs_dict.setdefault(authorization_header_key, auth_header_text)
|
|
2390
|
+
|
|
2391
|
+
if "grpc_max_message_size" in config:
|
|
2392
|
+
db_kwargs_dict.setdefault(_FLIGHTSQL_WITH_MAX_MSG_SIZE_KEY, str(config.pop("grpc_max_message_size")))
|
|
2393
|
+
|
|
2394
|
+
if "query_timeout" in config:
|
|
2395
|
+
db_kwargs_dict.setdefault(_FLIGHTSQL_TIMEOUT_QUERY_KEY, str(config.pop("query_timeout")))
|
|
2396
|
+
|
|
2397
|
+
if "fetch_timeout" in config:
|
|
2398
|
+
db_kwargs_dict.setdefault(_FLIGHTSQL_TIMEOUT_FETCH_KEY, str(config.pop("fetch_timeout")))
|
|
2399
|
+
|
|
2400
|
+
if "tls_root_certs" in config:
|
|
2401
|
+
db_kwargs_dict.setdefault(_FLIGHTSQL_TLS_ROOT_CERTS_KEY, str(config.pop("tls_root_certs")))
|
|
2402
|
+
|
|
2403
|
+
if "mtls_cert_chain" in config:
|
|
2404
|
+
db_kwargs_dict.setdefault(_FLIGHTSQL_MTLS_CERT_CHAIN_KEY, str(config.pop("mtls_cert_chain")))
|
|
2405
|
+
|
|
2406
|
+
if "mtls_private_key" in config:
|
|
2407
|
+
db_kwargs_dict.setdefault(_FLIGHTSQL_MTLS_PRIVATE_KEY_KEY, str(config.pop("mtls_private_key")))
|
|
2408
|
+
|
|
2409
|
+
if "with_cookie_middleware" in config:
|
|
2410
|
+
val = config.pop("with_cookie_middleware")
|
|
2411
|
+
db_kwargs_dict.setdefault(
|
|
2412
|
+
_FLIGHTSQL_WITH_COOKIE_MIDDLEWARE_KEY, str(val).lower() if isinstance(val, bool) else str(val)
|
|
2413
|
+
)
|
|
2414
|
+
|
|
2415
|
+
if "headers" in config:
|
|
2416
|
+
headers = config.pop("headers")
|
|
2417
|
+
if headers is not None:
|
|
2418
|
+
if not isinstance(headers, Mapping):
|
|
2419
|
+
msg = "FlightSQL headers must be a mapping."
|
|
2420
|
+
raise ImproperConfigurationError(msg)
|
|
2421
|
+
for hdr_key, hdr_val in headers.items():
|
|
2422
|
+
if (
|
|
2423
|
+
not isinstance(hdr_key, str)
|
|
2424
|
+
or "\x00" in hdr_key
|
|
2425
|
+
or "\r" in hdr_key
|
|
2426
|
+
or "\n" in hdr_key
|
|
2427
|
+
or _FLIGHTSQL_HEADER_KEY_PATTERN.fullmatch(hdr_key) is None
|
|
2428
|
+
):
|
|
2429
|
+
msg = f"Invalid FlightSQL header key: {hdr_key!r}."
|
|
2430
|
+
raise ImproperConfigurationError(msg)
|
|
2431
|
+
hdr_val_text = str(hdr_val)
|
|
2432
|
+
if "\x00" in hdr_val_text or "\r" in hdr_val_text or "\n" in hdr_val_text:
|
|
2433
|
+
msg = f"FlightSQL header {hdr_key!r} contains disallowed control characters."
|
|
2434
|
+
raise ImproperConfigurationError(msg)
|
|
2435
|
+
db_kwargs_dict.setdefault(f"{_FLIGHTSQL_RPC_CALL_HEADER_PREFIX}{hdr_key}", hdr_val_text)
|
|
2436
|
+
|
|
2437
|
+
|
|
2438
|
+
def _get_adbc_driver_info(connection: Any) -> "dict[Any, Any]":
|
|
2439
|
+
"""Return per-connection ADBC driver metadata without class-level cache bleed."""
|
|
2440
|
+
conn_type: Any = type(connection)
|
|
2441
|
+
if "_get_info_cache" in conn_type.__dict__:
|
|
2442
|
+
conn_dict = getattr(connection, "__dict__", None)
|
|
2443
|
+
if isinstance(conn_dict, dict):
|
|
2444
|
+
cached = conn_dict.get("_get_info_cache")
|
|
2445
|
+
if isinstance(cached, dict):
|
|
2446
|
+
return cached
|
|
2447
|
+
for base_cls in conn_type.__mro__[1:]:
|
|
2448
|
+
base_method = base_cls.__dict__.get("adbc_get_info")
|
|
2449
|
+
if callable(base_method):
|
|
2450
|
+
info = cast("dict[Any, Any]", base_method(connection))
|
|
2451
|
+
conn_dict["_get_info_cache"] = info
|
|
2452
|
+
return info
|
|
2453
|
+
return cast("dict[Any, Any]", connection.adbc_get_info())
|
|
2454
|
+
|
|
2455
|
+
|
|
2456
|
+
def _lift_native_gizmosql_db_kwargs(config: "dict[str, Any]") -> None:
|
|
2457
|
+
db_kwargs = config.pop("db_kwargs", None)
|
|
2458
|
+
db_kwargs_dict: dict[str, Any] = dict(db_kwargs) if isinstance(db_kwargs, dict) else {}
|
|
2459
|
+
_tls_skip_verify_key, authorization_header_key = _resolve_flightsql_db_kwargs_keys()
|
|
2460
|
+
_lift_flightsql_common_options(config, db_kwargs_dict, authorization_header_key)
|
|
2461
|
+
config.pop("gizmosql_backend", None)
|
|
2462
|
+
config.setdefault("autocommit", False)
|
|
2463
|
+
if db_kwargs_dict:
|
|
2464
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2465
|
+
|
|
2466
|
+
|
|
2467
|
+
def _lift_flightsql_db_kwargs(config: "dict[str, Any]") -> None:
|
|
2468
|
+
db_kwargs = config.pop("db_kwargs", None)
|
|
2469
|
+
db_kwargs_dict: dict[str, Any] = dict(db_kwargs) if isinstance(db_kwargs, dict) else {}
|
|
2470
|
+
tls_skip_verify_key, authorization_header_key = _resolve_flightsql_db_kwargs_keys()
|
|
2471
|
+
|
|
2472
|
+
for field in _FLIGHTSQL_DB_KWARGS_FIELDS:
|
|
2473
|
+
if field in config:
|
|
2474
|
+
db_kwargs_dict.setdefault(field, config.pop(field))
|
|
2475
|
+
|
|
2476
|
+
if "auth_type" in config:
|
|
2477
|
+
db_kwargs_dict.setdefault(_GIZMOSQL_AUTH_TYPE_KEY, config.pop("auth_type"))
|
|
2478
|
+
|
|
2479
|
+
if "tls_skip_verify" in config:
|
|
2480
|
+
tls_skip_verify = config.pop("tls_skip_verify")
|
|
2481
|
+
if isinstance(tls_skip_verify, bool):
|
|
2482
|
+
tls_skip_verify = str(tls_skip_verify).lower()
|
|
2483
|
+
db_kwargs_dict.setdefault(tls_skip_verify_key, tls_skip_verify)
|
|
2484
|
+
|
|
2485
|
+
_lift_flightsql_common_options(config, db_kwargs_dict, authorization_header_key)
|
|
2486
|
+
|
|
2487
|
+
config.pop("gizmosql_backend", None)
|
|
2488
|
+
if db_kwargs_dict:
|
|
2489
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2490
|
+
|
|
2491
|
+
|
|
2492
|
+
_SNOWFLAKE_AUTH_TYPES: Final[dict[str, str]] = {
|
|
2493
|
+
"snowflake": "auth_snowflake",
|
|
2494
|
+
"jwt": "auth_jwt",
|
|
2495
|
+
"keypair": "auth_jwt",
|
|
2496
|
+
"key_pair": "auth_jwt",
|
|
2497
|
+
"pat": "auth_pat",
|
|
2498
|
+
"programmatic_access_token": "auth_pat",
|
|
2499
|
+
"oauth": "auth_oauth",
|
|
2500
|
+
"workload_identity": "auth_wif",
|
|
2501
|
+
"wif": "auth_wif",
|
|
2502
|
+
"externalbrowser": "auth_ext_browser",
|
|
2503
|
+
"ext_browser": "auth_ext_browser",
|
|
2504
|
+
"okta": "auth_okta",
|
|
2505
|
+
"mfa": "auth_mfa",
|
|
2506
|
+
}
|
|
2507
|
+
_SNOWFLAKE_OPTIONS: Final[dict[str, str]] = {
|
|
2508
|
+
"account": "adbc.snowflake.sql.account",
|
|
2509
|
+
"warehouse": "adbc.snowflake.sql.warehouse",
|
|
2510
|
+
"database": "adbc.snowflake.sql.db",
|
|
2511
|
+
"schema": "adbc.snowflake.sql.schema",
|
|
2512
|
+
"role": "adbc.snowflake.sql.role",
|
|
2513
|
+
"region": "adbc.snowflake.sql.region",
|
|
2514
|
+
"host": "adbc.snowflake.sql.uri.host",
|
|
2515
|
+
"port": "adbc.snowflake.sql.uri.port",
|
|
2516
|
+
"protocol": "adbc.snowflake.sql.uri.protocol",
|
|
2517
|
+
"application": "adbc.snowflake.sql.client_option.app_name",
|
|
2518
|
+
"username": "username",
|
|
2519
|
+
"password": "password",
|
|
2520
|
+
"token": "adbc.snowflake.sql.client_option.auth_token",
|
|
2521
|
+
"okta_url": "adbc.snowflake.sql.client_option.okta_url",
|
|
2522
|
+
"identity_provider": "adbc.snowflake.sql.client_option.identity_provider",
|
|
2523
|
+
"workload_identity_provider": "adbc.snowflake.sql.client_option.identity_provider",
|
|
2524
|
+
"jwt_private_key": "adbc.snowflake.sql.client_option.jwt_private_key",
|
|
2525
|
+
"jwt_private_key_pkcs8_value": "adbc.snowflake.sql.client_option.jwt_private_key_pkcs8_value",
|
|
2526
|
+
"jwt_private_key_pkcs8_password": "adbc.snowflake.sql.client_option.jwt_private_key_pkcs8_password",
|
|
2527
|
+
}
|
|
2528
|
+
_SNOWFLAKE_BOOLEAN_OPTIONS: Final[tuple[str, ...]] = (
|
|
2529
|
+
"keep_session_alive",
|
|
2530
|
+
"ocsp_fail_open_mode",
|
|
2531
|
+
"tls_skip_verify",
|
|
2532
|
+
"use_high_precision",
|
|
2533
|
+
)
|
|
2534
|
+
_SNOWFLAKE_DURATION_OPTIONS: Final[tuple[tuple[str, str], ...]] = (
|
|
2535
|
+
("login_timeout", "login_timeout"),
|
|
2536
|
+
("connection_timeout", "login_timeout"),
|
|
2537
|
+
("request_timeout", "request_timeout"),
|
|
2538
|
+
("query_timeout", "request_timeout"),
|
|
2539
|
+
("client_timeout", "client_timeout"),
|
|
2540
|
+
("jwt_expire_timeout", "jwt_expire_timeout"),
|
|
2541
|
+
)
|
|
2542
|
+
_GO_DURATION_PATTERN: Final[re.Pattern[str]] = re.compile(r"\A(?:\d+(?:\.\d+)?(?:ns|us|\u00b5s|ms|s|m|h))+\Z")
|
|
2543
|
+
_SNOWFLAKE_ERROR_MARKER: Final = "[snowflake]"
|
|
2544
|
+
_SNOWFLAKE_ERROR_PATTERN: Final[re.Pattern[str]] = re.compile(r"\b(\d{6})(?:\s*\([0-9A-Z]{5}\))?\s*:")
|
|
2545
|
+
_SNOWFLAKE_ERROR_CODES: Final[dict[str, tuple[type[SQLSpecError], str]]] = {
|
|
2546
|
+
"002003": (NotFoundError, "object does not exist"),
|
|
2547
|
+
"000604": (QueryTimeoutError, "query timeout or canceled"),
|
|
2548
|
+
"000606": (OperationalError, "no active warehouse selected"),
|
|
2549
|
+
"250001": (DatabaseConnectionError, "authentication or connection failure"),
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
|
|
2553
|
+
def _normalize_snowflake_auth_type(value: Any) -> str:
|
|
2554
|
+
"""Resolve a Snowflake authentication shorthand or canonical option value."""
|
|
2555
|
+
if isinstance(value, str):
|
|
2556
|
+
lowered = value.strip().lower()
|
|
2557
|
+
if lowered in _SNOWFLAKE_AUTH_TYPES:
|
|
2558
|
+
return _SNOWFLAKE_AUTH_TYPES[lowered]
|
|
2559
|
+
if lowered in _SNOWFLAKE_AUTH_TYPES.values():
|
|
2560
|
+
return lowered
|
|
2561
|
+
msg = "Unsupported Snowflake authentication type."
|
|
2562
|
+
raise ImproperConfigurationError(msg)
|
|
2563
|
+
|
|
2564
|
+
|
|
2565
|
+
def _snowflake_option_text(value: Any) -> str:
|
|
2566
|
+
"""Render a database option without Python boolean spellings."""
|
|
2567
|
+
return ("true" if value else "false") if isinstance(value, bool) else str(value)
|
|
2568
|
+
|
|
2569
|
+
|
|
2570
|
+
def _format_go_duration(value: Any, *, field_name: str) -> str:
|
|
2571
|
+
"""Format a nonnegative seconds value as a Go duration."""
|
|
2572
|
+
if isinstance(value, str):
|
|
2573
|
+
text_value = value.strip()
|
|
2574
|
+
if _GO_DURATION_PATTERN.fullmatch(text_value):
|
|
2575
|
+
return text_value
|
|
2576
|
+
if re.fullmatch(r"\d+(?:\.\d+)?", text_value):
|
|
2577
|
+
value = float(text_value)
|
|
2578
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value >= 0:
|
|
2579
|
+
seconds = float(value)
|
|
2580
|
+
if seconds.is_integer():
|
|
2581
|
+
return f"{int(seconds)}s"
|
|
2582
|
+
milliseconds = seconds * 1000
|
|
2583
|
+
if math.isclose(milliseconds, round(milliseconds), rel_tol=0, abs_tol=1e-6):
|
|
2584
|
+
return f"{round(milliseconds)}ms"
|
|
2585
|
+
return f"{round(seconds * 1_000_000_000)}ns"
|
|
2586
|
+
msg = f"Snowflake {field_name} must be a finite nonnegative duration."
|
|
2587
|
+
raise ImproperConfigurationError(msg)
|
|
2588
|
+
|
|
2589
|
+
|
|
2590
|
+
def _normalize_snowflake_private_key(value: Any, passphrase: Any, options: dict[str, Any]) -> None:
|
|
2591
|
+
"""Normalize file, PEM, DER, and private key objects for Snowflake JWT authentication."""
|
|
2592
|
+
if passphrase is not None and not isinstance(passphrase, (str, bytes)):
|
|
2593
|
+
msg = "Snowflake private_key_passphrase must be str or bytes."
|
|
2594
|
+
raise ImproperConfigurationError(msg)
|
|
2595
|
+
password = passphrase.encode() if isinstance(passphrase, str) else passphrase
|
|
2596
|
+
password_text = passphrase.decode() if isinstance(passphrase, bytes) else passphrase
|
|
2597
|
+
prefix = "adbc.snowflake.sql.client_option."
|
|
2598
|
+
if isinstance(value, (str, Path)) and not (isinstance(value, str) and value.lstrip().startswith("-----BEGIN")):
|
|
2599
|
+
if password is None:
|
|
2600
|
+
options.setdefault(prefix + "jwt_private_key", str(value))
|
|
2601
|
+
return
|
|
2602
|
+
try:
|
|
2603
|
+
value = Path(value).read_bytes()
|
|
2604
|
+
except OSError as read_err:
|
|
2605
|
+
msg = "Cannot read Snowflake private key file."
|
|
2606
|
+
file_config_err = ImproperConfigurationError(msg)
|
|
2607
|
+
file_config_err.__cause__ = read_err
|
|
2608
|
+
raise file_config_err from read_err
|
|
2609
|
+
if isinstance(value, (bytearray, memoryview)):
|
|
2610
|
+
value = bytes(value)
|
|
2611
|
+
if isinstance(value, bytes) and value.lstrip().startswith(b"-----BEGIN"):
|
|
2612
|
+
value = value.decode()
|
|
2613
|
+
if isinstance(value, str):
|
|
2614
|
+
options.setdefault(prefix + "jwt_private_key_pkcs8_value", value)
|
|
2615
|
+
else:
|
|
2616
|
+
serialization = import_optional("cryptography.hazmat.primitives.serialization")
|
|
2617
|
+
if serialization is None:
|
|
2618
|
+
msg_0 = "cryptography"
|
|
2619
|
+
raise MissingDependencyError(msg_0)
|
|
2620
|
+
try:
|
|
2621
|
+
key = serialization.load_der_private_key(value, password=password) if isinstance(value, bytes) else value
|
|
2622
|
+
if not callable(getattr(key, "private_bytes", None)):
|
|
2623
|
+
msg = "Snowflake private_key must be a key object, PEM text, DER bytes, or file path."
|
|
2624
|
+
raise ImproperConfigurationError(msg)
|
|
2625
|
+
encryption = serialization.BestAvailableEncryption(password) if password else serialization.NoEncryption()
|
|
2626
|
+
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, encryption)
|
|
2627
|
+
except (TypeError, ValueError) as decode_err:
|
|
2628
|
+
msg = "Cannot decode Snowflake private key."
|
|
2629
|
+
decode_config_err = ImproperConfigurationError(msg)
|
|
2630
|
+
decode_config_err.__cause__ = decode_err
|
|
2631
|
+
raise decode_config_err from decode_err
|
|
2632
|
+
options.setdefault(prefix + "jwt_private_key_pkcs8_value", pem.decode())
|
|
2633
|
+
if password_text is not None:
|
|
2634
|
+
options.setdefault(prefix + "jwt_private_key_pkcs8_password", password_text)
|
|
2635
|
+
|
|
2636
|
+
|
|
2637
|
+
def _apply_snowflake_auth_token_provider(config: dict[str, Any], token: str) -> None:
|
|
2638
|
+
"""Refresh a password or bearer token according to the effective auth mode."""
|
|
2639
|
+
nested = config.get("db_kwargs")
|
|
2640
|
+
options = dict(nested) if isinstance(nested, Mapping) else {}
|
|
2641
|
+
raw_auth = options.get("adbc.snowflake.sql.auth_type", config.get("auth_type"))
|
|
2642
|
+
auth = _normalize_snowflake_auth_type(raw_auth) if raw_auth is not None else None
|
|
2643
|
+
token_mode = auth in {"auth_oauth", "auth_pat", "auth_wif"} or (
|
|
2644
|
+
auth is None
|
|
2645
|
+
and (
|
|
2646
|
+
"token" in config
|
|
2647
|
+
or "adbc.snowflake.sql.client_option.auth_token" in options
|
|
2648
|
+
or (
|
|
2649
|
+
not config.get("username")
|
|
2650
|
+
and not options.get("username")
|
|
2651
|
+
and not config.get("password")
|
|
2652
|
+
and not options.get("password")
|
|
2653
|
+
)
|
|
2654
|
+
)
|
|
2655
|
+
)
|
|
2656
|
+
if token_mode:
|
|
2657
|
+
options["adbc.snowflake.sql.client_option.auth_token"] = token
|
|
2658
|
+
options.setdefault("adbc.snowflake.sql.auth_type", auth or "auth_oauth")
|
|
2659
|
+
config.pop("token", None)
|
|
2660
|
+
else:
|
|
2661
|
+
options["password"] = token
|
|
2662
|
+
config.pop("password", None)
|
|
2663
|
+
config["db_kwargs"] = options
|
|
2664
|
+
|
|
2665
|
+
|
|
2666
|
+
def _lift_snowflake_db_kwargs(config: dict[str, Any]) -> None:
|
|
2667
|
+
"""Lift Snowflake connection fields into independent, string-valued database options."""
|
|
2668
|
+
nested = config.get("db_kwargs")
|
|
2669
|
+
options: dict[str, Any] = dict(nested) if isinstance(nested, Mapping) else {}
|
|
2670
|
+
extra = config.pop("extra", None)
|
|
2671
|
+
if isinstance(extra, Mapping):
|
|
2672
|
+
for key, value in extra.items():
|
|
2673
|
+
options.setdefault(str(key), value)
|
|
2674
|
+
session_parameters = config.pop("session_parameters", None)
|
|
2675
|
+
if isinstance(session_parameters, Mapping):
|
|
2676
|
+
for key, value in session_parameters.items():
|
|
2677
|
+
options.setdefault(str(key), value)
|
|
2678
|
+
query_tag = config.pop("query_tag", None)
|
|
2679
|
+
if query_tag is not None:
|
|
2680
|
+
options.setdefault("QUERY_TAG", query_tag)
|
|
2681
|
+
for field, option in _SNOWFLAKE_OPTIONS.items():
|
|
2682
|
+
if field in config:
|
|
2683
|
+
options.setdefault(option, config.pop(field))
|
|
2684
|
+
for field in _SNOWFLAKE_BOOLEAN_OPTIONS:
|
|
2685
|
+
if field in config:
|
|
2686
|
+
value = config.pop(field)
|
|
2687
|
+
if not isinstance(value, bool) and not (isinstance(value, str) and value.lower() in {"true", "false"}):
|
|
2688
|
+
msg = f"Snowflake {field} must be a boolean."
|
|
2689
|
+
raise ImproperConfigurationError(msg)
|
|
2690
|
+
options.setdefault("adbc.snowflake.sql.client_option." + field, _snowflake_option_text(value).lower())
|
|
2691
|
+
for field, option in _SNOWFLAKE_DURATION_OPTIONS:
|
|
2692
|
+
if field in config:
|
|
2693
|
+
value = config.pop(field)
|
|
2694
|
+
options.setdefault(
|
|
2695
|
+
"adbc.snowflake.sql.client_option." + option, _format_go_duration(value, field_name=field)
|
|
2696
|
+
)
|
|
2697
|
+
auth = config.pop("auth_type", None)
|
|
2698
|
+
if auth is not None:
|
|
2699
|
+
options.setdefault("adbc.snowflake.sql.auth_type", _normalize_snowflake_auth_type(auth))
|
|
2700
|
+
if "adbc.snowflake.sql.auth_type" in options:
|
|
2701
|
+
options["adbc.snowflake.sql.auth_type"] = _normalize_snowflake_auth_type(
|
|
2702
|
+
options["adbc.snowflake.sql.auth_type"]
|
|
2703
|
+
)
|
|
2704
|
+
private_key = config.pop("private_key", None)
|
|
2705
|
+
passphrase = config.pop("private_key_passphrase", None)
|
|
2706
|
+
if private_key is not None:
|
|
2707
|
+
_normalize_snowflake_private_key(private_key, passphrase, options)
|
|
2708
|
+
if private_key is not None or any("jwt_private_key" in key for key in options):
|
|
2709
|
+
options.setdefault("adbc.snowflake.sql.auth_type", "auth_jwt")
|
|
2710
|
+
if "uri" in config:
|
|
2711
|
+
options.setdefault("uri", config.pop("uri"))
|
|
2712
|
+
uri = options.get("uri")
|
|
2713
|
+
if isinstance(uri, str) and uri.lower().startswith("snowflake://"):
|
|
2714
|
+
options["uri"] = uri[len("snowflake://") :]
|
|
2715
|
+
config["db_kwargs"] = {key: _snowflake_option_text(value) for key, value in options.items()}
|
|
2716
|
+
|
|
2717
|
+
|
|
2718
|
+
def _map_snowflake_exception(error: Any, message: str) -> SQLSpecError | None:
|
|
2719
|
+
"""Map diagnostics carrying the Snowflake driver marker before generic SQLSTATE fallbacks."""
|
|
2720
|
+
if _SNOWFLAKE_ERROR_MARKER not in message.lower():
|
|
2721
|
+
return None
|
|
2722
|
+
match = _SNOWFLAKE_ERROR_PATTERN.search(message)
|
|
2723
|
+
code = match.group(1) if match else None
|
|
2724
|
+
vendor_code = getattr(error, "vendor_code", None)
|
|
2725
|
+
if code is None and isinstance(vendor_code, int) and not isinstance(vendor_code, bool) and vendor_code > 0:
|
|
2726
|
+
code = f"{vendor_code:06d}"
|
|
2727
|
+
if code is not None and code in _SNOWFLAKE_ERROR_CODES:
|
|
2728
|
+
exc_type, description = _SNOWFLAKE_ERROR_CODES[code]
|
|
2729
|
+
return _create_adbc_error(error, exc_type, description)
|
|
2730
|
+
return None
|
|
2731
|
+
|
|
2732
|
+
|
|
2733
|
+
def _lift_driver_specific_db_kwargs(
|
|
2734
|
+
config: "dict[str, Any]", driver_kind: "str | None", resolved_connect_path: str
|
|
2735
|
+
) -> None:
|
|
2736
|
+
if driver_kind == "snowflake":
|
|
2737
|
+
_lift_snowflake_db_kwargs(config)
|
|
2738
|
+
return
|
|
2739
|
+
if driver_kind == "gizmosql" and resolved_connect_path == _GIZMOSQL_NATIVE_CONNECT:
|
|
2740
|
+
_lift_native_gizmosql_db_kwargs(config)
|
|
2741
|
+
return
|
|
2742
|
+
if driver_kind in {"gizmosql", "flightsql"}:
|
|
2743
|
+
_lift_flightsql_db_kwargs(config)
|
|
2744
|
+
return
|
|
2745
|
+
if driver_kind == "bigquery":
|
|
2746
|
+
db_kwargs = config.get("db_kwargs")
|
|
2747
|
+
db_kwargs_dict: dict[str, Any] = dict(db_kwargs) if isinstance(db_kwargs, dict) else {}
|
|
2748
|
+
for param, option in _BIGQUERY_DB_KWARGS_OPTIONS:
|
|
2749
|
+
if param in config:
|
|
2750
|
+
db_kwargs_dict[option] = config.pop(param)
|
|
2751
|
+
if db_kwargs_dict:
|
|
2752
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2753
|
+
return
|
|
2754
|
+
if driver_kind == "quack" and "token" in config:
|
|
2755
|
+
db_kwargs = config.get("db_kwargs")
|
|
2756
|
+
db_kwargs_dict = dict(db_kwargs) if isinstance(db_kwargs, dict) else {}
|
|
2757
|
+
db_kwargs_dict.setdefault(_QUACK_AUTH_KEY, config.pop("token"))
|
|
2758
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2759
|
+
return
|
|
2760
|
+
if driver_kind == "oracle":
|
|
2761
|
+
db_kwargs = config.get("db_kwargs")
|
|
2762
|
+
db_kwargs_dict = dict(db_kwargs) if isinstance(db_kwargs, dict) else {}
|
|
2763
|
+
for field in ("username", "password"):
|
|
2764
|
+
if field in config:
|
|
2765
|
+
db_kwargs_dict.setdefault(field, config.pop(field))
|
|
2766
|
+
if db_kwargs_dict:
|
|
2767
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2768
|
+
|
|
2769
|
+
|
|
2770
|
+
def _validate_uri_host(host: str, *, backend: str) -> str:
|
|
2771
|
+
"""Validate a discrete URI host token, supporting IPv4, hostname, and IPv6 literals."""
|
|
2772
|
+
if not host or any(ch in _URI_HOST_FORBIDDEN_CHARS for ch in host):
|
|
2773
|
+
msg = f"Invalid {backend} host: {host!r}."
|
|
2774
|
+
raise ImproperConfigurationError(msg)
|
|
2775
|
+
if host.startswith("[") or host.endswith("]"):
|
|
2776
|
+
if (
|
|
2777
|
+
len(host) <= _MIN_BRACED_VALUE_LEN
|
|
2778
|
+
or not (host.startswith("[") and host.endswith("]"))
|
|
2779
|
+
or "[" in host[1:-1]
|
|
2780
|
+
or "]" in host[1:-1]
|
|
2781
|
+
):
|
|
2782
|
+
msg = f"Invalid {backend} host: {host!r}."
|
|
2783
|
+
raise ImproperConfigurationError(msg)
|
|
2784
|
+
return host
|
|
2785
|
+
if ":" in host:
|
|
2786
|
+
if "[" in host or "]" in host:
|
|
2787
|
+
msg = f"Invalid {backend} host: {host!r}."
|
|
2788
|
+
raise ImproperConfigurationError(msg)
|
|
2789
|
+
return f"[{host}]"
|
|
2790
|
+
return host
|
|
2791
|
+
|
|
2792
|
+
|
|
2793
|
+
def _parse_db2_cli_dsn(uri: str) -> "dict[str, str] | None":
|
|
2794
|
+
"""Parse semicolon-delimited Db2 CLI keyword=value pairs with MS-ODBCSTR brace awareness."""
|
|
2795
|
+
if "://" in uri or ";" not in uri:
|
|
2796
|
+
return None
|
|
2797
|
+
if "\x00" in uri or "\r" in uri or "\n" in uri:
|
|
2798
|
+
msg = "Db2 CLI DSN contains disallowed control characters."
|
|
2799
|
+
raise ImproperConfigurationError(msg)
|
|
2800
|
+
segments: list[str] = []
|
|
2801
|
+
buf: list[str] = []
|
|
2802
|
+
in_braces = False
|
|
2803
|
+
idx = 0
|
|
2804
|
+
length = len(uri)
|
|
2805
|
+
while idx < length:
|
|
2806
|
+
ch = uri[idx]
|
|
2807
|
+
if in_braces:
|
|
2808
|
+
if ch == "}":
|
|
2809
|
+
if idx + 1 < length and uri[idx + 1] == "}":
|
|
2810
|
+
buf.append("}}")
|
|
2811
|
+
idx += 2
|
|
2812
|
+
continue
|
|
2813
|
+
in_braces = False
|
|
2814
|
+
buf.append(ch)
|
|
2815
|
+
idx += 1
|
|
2816
|
+
continue
|
|
2817
|
+
if ch == "{":
|
|
2818
|
+
in_braces = True
|
|
2819
|
+
buf.append(ch)
|
|
2820
|
+
idx += 1
|
|
2821
|
+
continue
|
|
2822
|
+
if ch == "}":
|
|
2823
|
+
msg = "Db2 CLI DSN contains an unmatched closing brace."
|
|
2824
|
+
raise ImproperConfigurationError(msg)
|
|
2825
|
+
if ch == ";":
|
|
2826
|
+
segments.append("".join(buf))
|
|
2827
|
+
buf.clear()
|
|
2828
|
+
idx += 1
|
|
2829
|
+
continue
|
|
2830
|
+
buf.append(ch)
|
|
2831
|
+
idx += 1
|
|
2832
|
+
if in_braces:
|
|
2833
|
+
msg = "Db2 CLI DSN contains an unclosed opening brace."
|
|
2834
|
+
raise ImproperConfigurationError(msg)
|
|
2835
|
+
segments.append("".join(buf))
|
|
2836
|
+
|
|
2837
|
+
parsed: dict[str, str] = {}
|
|
2838
|
+
for raw_segment in segments:
|
|
2839
|
+
segment = raw_segment.strip()
|
|
2840
|
+
if not segment or "=" not in segment:
|
|
2841
|
+
continue
|
|
2842
|
+
key, raw_value = segment.split("=", 1)
|
|
2843
|
+
normalized_key = key.strip().lower()
|
|
2844
|
+
if "{" in normalized_key or "}" in normalized_key:
|
|
2845
|
+
msg = f"Invalid Db2 CLI DSN keyword: {key.strip()!r}."
|
|
2846
|
+
raise ImproperConfigurationError(msg)
|
|
2847
|
+
trimmed_val = raw_value.strip()
|
|
2848
|
+
if trimmed_val.startswith("{"):
|
|
2849
|
+
if len(trimmed_val) < _MIN_BRACED_VALUE_LEN or not trimmed_val.endswith("}"):
|
|
2850
|
+
msg = f"Malformed braced value for Db2 CLI keyword {key.strip()!r}."
|
|
2851
|
+
raise ImproperConfigurationError(msg)
|
|
2852
|
+
inner = trimmed_val[1:-1]
|
|
2853
|
+
if "}" in inner.replace("}}", ""):
|
|
2854
|
+
msg = f"Unescaped closing brace in Db2 CLI keyword {key.strip()!r}."
|
|
2855
|
+
raise ImproperConfigurationError(msg)
|
|
2856
|
+
normalized_val = inner.replace("}}", "}")
|
|
2857
|
+
elif "{" in trimmed_val or "}" in trimmed_val:
|
|
2858
|
+
msg = f"Malformed brace in Db2 CLI keyword {key.strip()!r}."
|
|
2859
|
+
raise ImproperConfigurationError(msg)
|
|
2860
|
+
else:
|
|
2861
|
+
normalized_val = trimmed_val
|
|
2862
|
+
if normalized_key and normalized_val:
|
|
2863
|
+
parsed[normalized_key] = normalized_val
|
|
2864
|
+
if "driver" in parsed:
|
|
2865
|
+
return None
|
|
2866
|
+
database = parsed.get("database") or parsed.get("dbalias")
|
|
2867
|
+
host = parsed.get("hostname") or parsed.get("host")
|
|
2868
|
+
if not database or not host:
|
|
2869
|
+
return None
|
|
2870
|
+
return parsed
|
|
2871
|
+
|
|
2872
|
+
|
|
2873
|
+
def _normalize_db2_cli_dsn(config: "dict[str, Any]", uri: str) -> None:
|
|
2874
|
+
"""Convert an IBM Db2 CLI keyword DSN into a db2:// URI, credentials, and db_kwargs."""
|
|
2875
|
+
parsed = _parse_db2_cli_dsn(uri)
|
|
2876
|
+
if parsed is None:
|
|
2877
|
+
return
|
|
2878
|
+
database = parsed.get("database") or parsed.get("dbalias") or ""
|
|
2879
|
+
host = parsed.get("hostname") or parsed.get("host") or ""
|
|
2880
|
+
port_raw = parsed.get("port", "")
|
|
2881
|
+
formatted_host = _validate_uri_host(host, backend="Db2")
|
|
2882
|
+
encoded_database = quote(database, safe="")
|
|
2883
|
+
if port_raw:
|
|
2884
|
+
try:
|
|
2885
|
+
port_num = int(port_raw)
|
|
2886
|
+
except ValueError as exc:
|
|
2887
|
+
msg = f"Db2 port must be an integer between 1 and 65535, got {port_raw!r}."
|
|
2888
|
+
raise with_cause(ImproperConfigurationError(msg), exc) from exc
|
|
2889
|
+
if not 1 <= port_num <= _MAX_TCP_PORT:
|
|
2890
|
+
msg = f"Db2 port must be an integer between 1 and 65535, got {port_num}."
|
|
2891
|
+
raise ImproperConfigurationError(msg)
|
|
2892
|
+
config["uri"] = f"db2://{formatted_host}:{port_num}/{encoded_database}"
|
|
2893
|
+
else:
|
|
2894
|
+
config["uri"] = f"db2://{formatted_host}/{encoded_database}"
|
|
2895
|
+
|
|
2896
|
+
uid = parsed.get("uid") or parsed.get("user")
|
|
2897
|
+
if uid is not None:
|
|
2898
|
+
config.setdefault("username", uid)
|
|
2899
|
+
pwd = parsed.get("pwd") or parsed.get("password")
|
|
2900
|
+
if pwd is not None:
|
|
2901
|
+
config.setdefault("password", pwd)
|
|
2902
|
+
|
|
2903
|
+
existing_db_kwargs = config.get("db_kwargs")
|
|
2904
|
+
db_kwargs_dict: dict[str, Any] = dict(existing_db_kwargs) if isinstance(existing_db_kwargs, dict) else {}
|
|
2905
|
+
if "uri" in db_kwargs_dict and db_kwargs_dict.get("uri") == uri:
|
|
2906
|
+
db_kwargs_dict.pop("uri", None)
|
|
2907
|
+
|
|
2908
|
+
security = parsed.get("security", "").lower()
|
|
2909
|
+
if security in {"ssl", "tls"}:
|
|
2910
|
+
db_kwargs_dict.setdefault("adbc.db2.tls", "true")
|
|
2911
|
+
ssl_cert = parsed.get("sslservercertificate")
|
|
2912
|
+
if ssl_cert is not None:
|
|
2913
|
+
db_kwargs_dict.setdefault("adbc.db2.tls.ca_cert", ssl_cert)
|
|
2914
|
+
current_schema = parsed.get("currentschema")
|
|
2915
|
+
if current_schema is not None:
|
|
2916
|
+
db_kwargs_dict.setdefault("adbc.db2.current_schema", current_schema)
|
|
2917
|
+
connect_timeout = parsed.get("connecttimeout")
|
|
2918
|
+
if connect_timeout is not None:
|
|
2919
|
+
db_kwargs_dict.setdefault("adbc.db2.connect_timeout", connect_timeout)
|
|
2920
|
+
|
|
2921
|
+
if db_kwargs_dict:
|
|
2922
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2923
|
+
elif isinstance(existing_db_kwargs, dict) and "uri" in existing_db_kwargs:
|
|
2924
|
+
config.pop("db_kwargs", None)
|
|
2925
|
+
|
|
2926
|
+
|
|
2927
|
+
def _apply_driver_manager_config(config: "dict[str, Any]", driver_kind: "str | None", driver_name: Any) -> None:
|
|
2928
|
+
if driver_kind in {"mssql", "teradata"} and not (
|
|
2929
|
+
isinstance(driver_name, str) and is_shared_object_driver(driver_name)
|
|
2930
|
+
):
|
|
2931
|
+
config["driver"] = driver_kind
|
|
2932
|
+
elif isinstance(driver_name, str) and "driver" not in config:
|
|
2933
|
+
config["driver"] = driver_name.strip()
|
|
2934
|
+
if any(field in config for field in ("uri", "username", "password")):
|
|
2935
|
+
db_kwargs = config.get("db_kwargs")
|
|
2936
|
+
db_kwargs_dict = dict(db_kwargs) if isinstance(db_kwargs, dict) else {}
|
|
2937
|
+
for field in ("uri", "username", "password"):
|
|
2938
|
+
if field in config:
|
|
2939
|
+
db_kwargs_dict.setdefault(field, config.pop(field))
|
|
2940
|
+
if db_kwargs_dict:
|
|
2941
|
+
config["db_kwargs"] = db_kwargs_dict
|
|
2942
|
+
|
|
2943
|
+
|
|
2944
|
+
def _normalize_duckdb_memory_path(value: str) -> str:
|
|
2945
|
+
stripped = value.strip()
|
|
2946
|
+
if stripped in {":memory:", "/:memory:"}:
|
|
2947
|
+
return ":memory:"
|
|
2948
|
+
if stripped.startswith((":memory:", "/:memory:")):
|
|
2949
|
+
msg = "DuckDB ADBC does not support named ':memory:<name>' identifiers; use ':memory:' instead."
|
|
2950
|
+
raise ImproperConfigurationError(msg)
|
|
2951
|
+
return value
|
|
2952
|
+
|
|
2953
|
+
|
|
2954
|
+
def _normalize_and_validate_duckdb_config(config: "dict[str, Any]", uri: Any) -> None:
|
|
2955
|
+
if isinstance(config.get("uri"), str):
|
|
2956
|
+
raw_uri = config.pop("uri")
|
|
2957
|
+
raw_path = raw_uri[9:] if raw_uri.lower().startswith("duckdb://") else raw_uri
|
|
2958
|
+
if raw_path.startswith("/:memory:"):
|
|
2959
|
+
raw_path = raw_path[1:]
|
|
2960
|
+
if "path" not in config:
|
|
2961
|
+
config["path"] = raw_path
|
|
2962
|
+
elif "uri" in config:
|
|
2963
|
+
config.pop("uri", None)
|
|
2964
|
+
|
|
2965
|
+
path_value = config.get("path")
|
|
2966
|
+
if isinstance(path_value, str):
|
|
2967
|
+
config["path"] = _normalize_duckdb_memory_path(path_value)
|
|
2968
|
+
|
|
2969
|
+
db_kwargs = config.get("db_kwargs")
|
|
2970
|
+
if isinstance(db_kwargs, dict):
|
|
2971
|
+
updated_kwargs = dict(db_kwargs)
|
|
2972
|
+
changed = False
|
|
2973
|
+
for key in ("path", "uri"):
|
|
2974
|
+
nested_val = updated_kwargs.get(key)
|
|
2975
|
+
if isinstance(nested_val, str):
|
|
2976
|
+
candidate = (
|
|
2977
|
+
nested_val[9:] if key == "uri" and nested_val.lower().startswith("duckdb://") else nested_val
|
|
2978
|
+
)
|
|
2979
|
+
if candidate.startswith("/:memory:"):
|
|
2980
|
+
candidate = candidate[1:]
|
|
2981
|
+
normalized = _normalize_duckdb_memory_path(candidate)
|
|
2982
|
+
if normalized != nested_val:
|
|
2983
|
+
updated_kwargs[key] = normalized
|
|
2984
|
+
changed = True
|
|
2985
|
+
if changed:
|
|
2986
|
+
config["db_kwargs"] = updated_kwargs
|
|
2987
|
+
elif isinstance(uri, str) and uri.lower().startswith("duckdb://") and "path" not in config:
|
|
2988
|
+
raw_path = uri[9:]
|
|
2989
|
+
if raw_path.startswith("/:memory:"):
|
|
2990
|
+
raw_path = raw_path[1:]
|
|
2991
|
+
config["path"] = _normalize_duckdb_memory_path(raw_path)
|
|
2992
|
+
|
|
2993
|
+
|
|
2994
|
+
driver_profile: Final[DriverParameterProfile] = build_profile()
|
|
2995
|
+
|
|
2996
|
+
_DB2_TABLE_EXISTS_SQL: Final = (
|
|
2997
|
+
"SELECT 1 FROM SYSCAT.TABLES WHERE TABSCHEMA = COALESCE(CAST(? AS VARCHAR(128)), CURRENT SCHEMA) AND TABNAME = ?"
|
|
2998
|
+
)
|
|
2999
|
+
_DB2_INDEX_EXISTS_SQL: Final = (
|
|
3000
|
+
"SELECT 1 FROM SYSCAT.INDEXES WHERE INDSCHEMA = COALESCE(CAST(? AS VARCHAR(128)), CURRENT SCHEMA) AND INDNAME = ?"
|
|
3001
|
+
)
|
|
3002
|
+
|
|
3003
|
+
|
|
3004
|
+
_TERADATA_ERROR_CODE_PATTERN: Final[re.Pattern[str]] = re.compile(r"\[\s*Error\s+(\d+)\s*\]", re.IGNORECASE)
|
|
3005
|
+
_TERADATA_ERROR_CODE_MAP: Final[dict[int, tuple[type[SQLSpecError], str]]] = {
|
|
3006
|
+
2616: (DataError, "numeric overflow"),
|
|
3007
|
+
2620: (DataError, "format or data contains a bad character"),
|
|
3008
|
+
2621: (DataError, "bad character in number"),
|
|
3009
|
+
2631: (DeadlockError, "transaction ABORTed due to deadlock"),
|
|
3010
|
+
2644: (OperationalError, "no more room in database"),
|
|
3011
|
+
2646: (OperationalError, "no more spool space"),
|
|
3012
|
+
2665: (DataError, "invalid date"),
|
|
3013
|
+
2700: (ForeignKeyViolationError, "referential constraint violation"),
|
|
3014
|
+
2701: (ForeignKeyViolationError, "referential constraint violation"),
|
|
3015
|
+
2801: (UniqueViolationError, "duplicate unique prime key"),
|
|
3016
|
+
2802: (UniqueViolationError, "duplicate row error"),
|
|
3017
|
+
2803: (UniqueViolationError, "secondary index uniqueness violation"),
|
|
3018
|
+
2843: (OperationalError, "no more temporary table space"),
|
|
3019
|
+
3110: (QueryTimeoutError, "transaction aborted due to timeout"),
|
|
3020
|
+
3156: (QueryTimeoutError, "request aborted by TDWM"),
|
|
3021
|
+
3523: (PermissionDeniedError, "insufficient access privilege"),
|
|
3022
|
+
3524: (PermissionDeniedError, "insufficient privilege for database object"),
|
|
3023
|
+
3604: (NotNullViolationError, "cannot place a null value in a not-null field"),
|
|
3024
|
+
3706: (SQLParsingError, "syntax error"),
|
|
3025
|
+
3707: (SQLParsingError, "syntax error"),
|
|
3026
|
+
3802: (NotFoundError, "database does not exist"),
|
|
3027
|
+
3807: (NotFoundError, "object does not exist"),
|
|
3028
|
+
3811: (NotNullViolationError, "column is NOT NULL"),
|
|
3029
|
+
3932: (OperationalError, "only an ET or null statement is legal after a DDL statement"),
|
|
3030
|
+
5312: (ForeignKeyViolationError, "referential integrity violation"),
|
|
3031
|
+
5313: (ForeignKeyViolationError, "referential integrity violation"),
|
|
3032
|
+
5317: (CheckViolationError, "check constraint violation"),
|
|
3033
|
+
5628: (NotFoundError, "column not found"),
|
|
3034
|
+
6706: (DataError, "untranslatable character"),
|
|
3035
|
+
6758: (DataError, "invalid time"),
|
|
3036
|
+
6760: (DataError, "invalid timestamp"),
|
|
3037
|
+
8017: (PermissionDeniedError, "invalid username or password"),
|
|
3038
|
+
}
|
|
3039
|
+
|
|
3040
|
+
|
|
3041
|
+
def _map_teradata_exception(
|
|
3042
|
+
error: Any, raw_message: str, lowered_message: str, sqlstate: str | None, *, assume_teradata: bool = False
|
|
3043
|
+
) -> SQLSpecError | None:
|
|
3044
|
+
"""Map Teradata DBS [Error NNNN] diagnostics and ODBC SQLSTATE codes to SQLSpecError.
|
|
3045
|
+
|
|
3046
|
+
Diagnostics are mapped only for messages that name Teradata, or when the caller knows the
|
|
3047
|
+
connection reaches Teradata.
|
|
3048
|
+
"""
|
|
3049
|
+
has_teradata_marker = assume_teradata or any(
|
|
3050
|
+
marker in lowered_message for marker in ("teradata", "[teradata", "teradatasql", "tdwm")
|
|
3051
|
+
)
|
|
3052
|
+
if not has_teradata_marker:
|
|
3053
|
+
return None
|
|
3054
|
+
match = _TERADATA_ERROR_CODE_PATTERN.search(raw_message)
|
|
3055
|
+
code: int | None = None
|
|
3056
|
+
if match is not None:
|
|
3057
|
+
code = int(match.group(1))
|
|
3058
|
+
elif has_teradata_marker:
|
|
3059
|
+
vendor_code = getattr(error, "vendor_code", None)
|
|
3060
|
+
if isinstance(vendor_code, int) and not isinstance(vendor_code, bool) and vendor_code != 0:
|
|
3061
|
+
code = abs(vendor_code)
|
|
3062
|
+
|
|
3063
|
+
if code is not None and code in _TERADATA_ERROR_CODE_MAP:
|
|
3064
|
+
exc_cls, desc = _TERADATA_ERROR_CODE_MAP[code]
|
|
3065
|
+
return _create_adbc_error(error, exc_cls, desc)
|
|
3066
|
+
|
|
3067
|
+
if has_teradata_marker and sqlstate is not None:
|
|
3068
|
+
if sqlstate in {"HYT00", "HYT01"}:
|
|
3069
|
+
return _create_adbc_error(error, QueryTimeoutError, "query timeout")
|
|
3070
|
+
if sqlstate == "HY008":
|
|
3071
|
+
return _create_adbc_error(error, OperationCancelledError, "operation cancelled")
|
|
3072
|
+
if sqlstate == "42S02":
|
|
3073
|
+
return _create_adbc_error(error, NotFoundError, "object does not exist")
|
|
3074
|
+
|
|
3075
|
+
return None
|
|
3076
|
+
|
|
3077
|
+
|
|
3078
|
+
def _resolve_teradata_driver_connect() -> str:
|
|
3079
|
+
"""Resolve the optional native module or dbc-managed Teradata manifest."""
|
|
3080
|
+
if import_optional("adbc_driver_teradata") is not None:
|
|
3081
|
+
return "adbc_driver_teradata.dbapi.connect"
|
|
3082
|
+
return _DRIVER_MANAGER_CONNECT
|
|
3083
|
+
|
|
3084
|
+
|
|
3085
|
+
def _build_or_augment_teradata_uri(config: dict[str, Any]) -> None:
|
|
3086
|
+
"""Encode discrete Teradata fields while preserving pre-encoded URI components.
|
|
3087
|
+
|
|
3088
|
+
Raises:
|
|
3089
|
+
ImproperConfigurationError: If a discrete port is invalid.
|
|
3090
|
+
"""
|
|
3091
|
+
nested = config.get("db_kwargs")
|
|
3092
|
+
uri = config.get("uri") or (nested.get("uri") if isinstance(nested, dict) else None)
|
|
3093
|
+
host = config.pop("host", None)
|
|
3094
|
+
port = config.pop("port", None)
|
|
3095
|
+
database = config.pop("database", None)
|
|
3096
|
+
user = config.pop("user", None)
|
|
3097
|
+
username = config.pop("username", None)
|
|
3098
|
+
username = username if username is not None else user
|
|
3099
|
+
password = config.pop("password", None)
|
|
3100
|
+
if port is not None and (isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= _MAX_TCP_PORT):
|
|
3101
|
+
msg = "Teradata port must be an integer between 1 and 65535"
|
|
3102
|
+
raise ImproperConfigurationError(msg)
|
|
3103
|
+
if uri is None and host is None:
|
|
3104
|
+
if username is not None:
|
|
3105
|
+
config["username"] = username
|
|
3106
|
+
if password is not None:
|
|
3107
|
+
config["password"] = password
|
|
3108
|
+
return
|
|
3109
|
+
if isinstance(uri, str) and all(value is None for value in (host, port, database, username, password)):
|
|
3110
|
+
return
|
|
3111
|
+
parsed = urlsplit(uri) if isinstance(uri, str) else None
|
|
3112
|
+
if host is not None:
|
|
3113
|
+
host_text = _validate_uri_host(str(host), backend="Teradata")
|
|
3114
|
+
elif parsed is not None and parsed.hostname:
|
|
3115
|
+
host_text = _validate_uri_host(parsed.hostname, backend="Teradata")
|
|
3116
|
+
else:
|
|
3117
|
+
host_text = ""
|
|
3118
|
+
resolved_port = port if port is not None else (parsed.port if parsed is not None else 1025)
|
|
3119
|
+
raw_auth = parsed.netloc.rsplit("@", 1)[0] if parsed is not None and "@" in parsed.netloc else ""
|
|
3120
|
+
raw_user, separator, raw_password = raw_auth.partition(":")
|
|
3121
|
+
if username is not None:
|
|
3122
|
+
raw_user = quote(str(username), safe="")
|
|
3123
|
+
if password is not None:
|
|
3124
|
+
raw_password = quote(str(password), safe="")
|
|
3125
|
+
separator = ":"
|
|
3126
|
+
auth = (raw_user + separator + raw_password + "@") if raw_user or separator else ""
|
|
3127
|
+
path = parsed.path if parsed is not None else ""
|
|
3128
|
+
if database is not None:
|
|
3129
|
+
path = "/" + quote(str(database).strip().lstrip("/"), safe="")
|
|
3130
|
+
netloc = auth + host_text + (":" + str(resolved_port) if resolved_port is not None else "")
|
|
3131
|
+
config["uri"] = urlunsplit((
|
|
3132
|
+
"teradata",
|
|
3133
|
+
netloc,
|
|
3134
|
+
path,
|
|
3135
|
+
parsed.query if parsed else "",
|
|
3136
|
+
parsed.fragment if parsed else "",
|
|
3137
|
+
))
|
|
3138
|
+
if isinstance(nested, dict) and nested.get("uri") == uri:
|
|
3139
|
+
nested_copy = dict(nested)
|
|
3140
|
+
nested_copy.pop("uri", None)
|
|
3141
|
+
config["db_kwargs"] = nested_copy
|
|
3142
|
+
|
|
3143
|
+
|
|
3144
|
+
_TERADATA_TABLE_EXISTS_SQL: Final[str] = (
|
|
3145
|
+
"LOCKING ROW FOR ACCESS SELECT 1 FROM DBC.TablesV "
|
|
3146
|
+
"WHERE UPPER(TRIM(DatabaseName)) = UPPER(TRIM(COALESCE(CAST(? AS VARCHAR(128)), DATABASE))) "
|
|
3147
|
+
"AND UPPER(TRIM(TableName)) = UPPER(TRIM(CAST(? AS VARCHAR(128)))) "
|
|
3148
|
+
"AND TableKind IN ('T', 'O')"
|
|
3149
|
+
)
|
|
3150
|
+
_TERADATA_INDEX_EXISTS_SQL: Final[str] = (
|
|
3151
|
+
"LOCKING ROW FOR ACCESS SELECT 1 FROM DBC.IndicesV "
|
|
3152
|
+
"WHERE UPPER(TRIM(DatabaseName)) = UPPER(TRIM(COALESCE(CAST(? AS VARCHAR(128)), DATABASE))) "
|
|
3153
|
+
"AND UPPER(TRIM(TableName)) = UPPER(TRIM(CAST(? AS VARCHAR(128)))) "
|
|
3154
|
+
"AND UPPER(TRIM(IndexName)) = UPPER(TRIM(CAST(? AS VARCHAR(128))))"
|
|
3155
|
+
)
|
|
3156
|
+
|
|
3157
|
+
|
|
3158
|
+
def _normalize_teradata_identifier_segment(segment: str, raw_table_name: str) -> str:
|
|
3159
|
+
"""Normalize one Teradata identifier segment, preserving double-quoted case and unescaping quotes."""
|
|
3160
|
+
stripped = segment.strip()
|
|
3161
|
+
if not stripped:
|
|
3162
|
+
msg = f"Invalid Teradata table name: {raw_table_name!r}"
|
|
3163
|
+
raise ImproperConfigurationError(msg)
|
|
3164
|
+
if stripped.startswith('"') or stripped.endswith('"'):
|
|
3165
|
+
if len(stripped) < _MIN_QUALIFIED_PARTS or not (stripped.startswith('"') and stripped.endswith('"')):
|
|
3166
|
+
msg = f"Invalid Teradata table name: {raw_table_name!r}"
|
|
3167
|
+
raise ImproperConfigurationError(msg)
|
|
3168
|
+
inner = stripped[1:-1]
|
|
3169
|
+
if '"' in inner.replace('""', ""):
|
|
3170
|
+
msg = f"Invalid Teradata table name: {raw_table_name!r}"
|
|
3171
|
+
raise ImproperConfigurationError(msg)
|
|
3172
|
+
unquoted = inner.replace('""', '"')
|
|
3173
|
+
if not unquoted:
|
|
3174
|
+
msg = f"Invalid Teradata table name: {raw_table_name!r}"
|
|
3175
|
+
raise ImproperConfigurationError(msg)
|
|
3176
|
+
return unquoted
|
|
3177
|
+
if '"' in stripped:
|
|
3178
|
+
msg = f"Invalid Teradata table name: {raw_table_name!r}"
|
|
3179
|
+
raise ImproperConfigurationError(msg)
|
|
3180
|
+
return stripped.upper()
|
|
3181
|
+
|
|
3182
|
+
|
|
3183
|
+
def _split_raw_teradata_segments(table_name: str) -> list[str]:
|
|
3184
|
+
"""Split a Teradata table reference on unquoted dots while preserving raw segment quotes."""
|
|
3185
|
+
segments: list[str] = []
|
|
3186
|
+
buf: list[str] = []
|
|
3187
|
+
in_quotes = False
|
|
3188
|
+
idx = 0
|
|
3189
|
+
length = len(table_name)
|
|
3190
|
+
while idx < length:
|
|
3191
|
+
ch = table_name[idx]
|
|
3192
|
+
if ch == '"':
|
|
3193
|
+
buf.append(ch)
|
|
3194
|
+
if in_quotes and idx + 1 < length and table_name[idx + 1] == '"':
|
|
3195
|
+
buf.append('"')
|
|
3196
|
+
idx += 2
|
|
3197
|
+
continue
|
|
3198
|
+
in_quotes = not in_quotes
|
|
3199
|
+
elif ch == "." and not in_quotes:
|
|
3200
|
+
segments.append("".join(buf))
|
|
3201
|
+
buf.clear()
|
|
3202
|
+
else:
|
|
3203
|
+
buf.append(ch)
|
|
3204
|
+
idx += 1
|
|
3205
|
+
if in_quotes:
|
|
3206
|
+
msg = f"Invalid Teradata table name: {table_name!r}"
|
|
3207
|
+
raise ImproperConfigurationError(msg)
|
|
3208
|
+
segments.append("".join(buf))
|
|
3209
|
+
return segments
|