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,4765 @@
|
|
|
1
|
+
"""Common driver attributes and utilities.
|
|
2
|
+
|
|
3
|
+
``SyncExceptionHandler`` and ``AsyncExceptionHandler`` record mapped exceptions on
|
|
4
|
+
``pending_exception`` rather than raising inside ``__exit__`` or ``__aexit__`` so
|
|
5
|
+
compiled mypyc callers re-raise outside the context-manager ABI boundary.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import contextlib
|
|
9
|
+
import hashlib
|
|
10
|
+
import inspect
|
|
11
|
+
import logging
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from datetime import date, datetime
|
|
15
|
+
from decimal import Decimal
|
|
16
|
+
from itertools import count as _itertools_count
|
|
17
|
+
from time import perf_counter
|
|
18
|
+
from types import BuiltinFunctionType, FunctionType
|
|
19
|
+
from typing import (
|
|
20
|
+
TYPE_CHECKING,
|
|
21
|
+
Any,
|
|
22
|
+
ClassVar,
|
|
23
|
+
Final,
|
|
24
|
+
Literal,
|
|
25
|
+
NamedTuple,
|
|
26
|
+
NoReturn,
|
|
27
|
+
Protocol,
|
|
28
|
+
Self,
|
|
29
|
+
TypeVar,
|
|
30
|
+
cast,
|
|
31
|
+
overload,
|
|
32
|
+
)
|
|
33
|
+
from uuid import UUID
|
|
34
|
+
|
|
35
|
+
import sqlglot
|
|
36
|
+
from mypy_extensions import mypyc_attr, trait
|
|
37
|
+
from sqlglot import exp
|
|
38
|
+
from sqlglot.errors import ParseError, SqlglotError
|
|
39
|
+
from sqlglot.tokenizer_core import TokenType
|
|
40
|
+
|
|
41
|
+
from sqlspec.builder._base import QueryBuilder
|
|
42
|
+
from sqlspec.builder._ddl import compile_table_ddl_results
|
|
43
|
+
from sqlspec.builder._parsing_utils import _normalize_dialect
|
|
44
|
+
from sqlspec.core._pool import ObjectPool, get_processed_state_pool, get_sql_pool
|
|
45
|
+
from sqlspec.core.cache import (
|
|
46
|
+
_POSITIONAL_NUMBERED_STYLES,
|
|
47
|
+
CachedQuery,
|
|
48
|
+
CachedStatement,
|
|
49
|
+
QueryCache,
|
|
50
|
+
StatementCacheHolder,
|
|
51
|
+
get_cache,
|
|
52
|
+
get_cache_config,
|
|
53
|
+
resolve_statement_cache_size,
|
|
54
|
+
)
|
|
55
|
+
from sqlspec.core.compiler import (
|
|
56
|
+
OperationProfile,
|
|
57
|
+
_split_leading_keyword, # pyright: ignore[reportPrivateUsage]
|
|
58
|
+
)
|
|
59
|
+
from sqlspec.core.filters import find_filter as _find_filter_impl
|
|
60
|
+
from sqlspec.core.metrics import StackExecutionMetrics
|
|
61
|
+
from sqlspec.core.parameters._converter import ambiguous_index_message
|
|
62
|
+
from sqlspec.core.parameters._declared import ParameterDeclaration, matches_param_type
|
|
63
|
+
from sqlspec.core.parameters._processor import (
|
|
64
|
+
ParameterProcessor,
|
|
65
|
+
apply_type_coercion,
|
|
66
|
+
structural_fingerprint,
|
|
67
|
+
type_coercion_dispatcher,
|
|
68
|
+
type_coercion_fallbacks,
|
|
69
|
+
value_fingerprint,
|
|
70
|
+
)
|
|
71
|
+
from sqlspec.core.parameters._types import ParameterStyle, TypedParameter
|
|
72
|
+
from sqlspec.core.result._base import RowFormat, SQLResult
|
|
73
|
+
from sqlspec.core.splitter import split_sql_script
|
|
74
|
+
from sqlspec.core.sqlcommenter import format_wire_sqlcomment, strip_sqlcomment
|
|
75
|
+
from sqlspec.core.statement import SQL, ProcessedState, Statement, StatementConfig, _is_uncacheable_callable
|
|
76
|
+
from sqlspec.data_dictionary._dependencies import (
|
|
77
|
+
DependencyEdge,
|
|
78
|
+
DependencyEdgeKind,
|
|
79
|
+
DependencyStrength,
|
|
80
|
+
dependency_edges_from_foreign_keys,
|
|
81
|
+
sort_ddl_results,
|
|
82
|
+
sort_dependencies,
|
|
83
|
+
)
|
|
84
|
+
from sqlspec.data_dictionary._loader import get_data_dictionary_loader
|
|
85
|
+
from sqlspec.data_dictionary._registry import get_dialect_config
|
|
86
|
+
from sqlspec.data_dictionary._types import (
|
|
87
|
+
DDL_PARENT_TABLE_CONTEXT_KEY,
|
|
88
|
+
ColumnProfileMetadata,
|
|
89
|
+
DDLResult,
|
|
90
|
+
ForeignKeyMetadata,
|
|
91
|
+
MetadataCapability,
|
|
92
|
+
MetadataFidelity,
|
|
93
|
+
MetadataResult,
|
|
94
|
+
MetadataSource,
|
|
95
|
+
MetadataSupport,
|
|
96
|
+
ObjectIdentity,
|
|
97
|
+
VersionCacheResult,
|
|
98
|
+
VersionInfo,
|
|
99
|
+
)
|
|
100
|
+
from sqlspec.driver._stream import _CLOSED_CONNECTION_MESSAGE, SyncRowStream
|
|
101
|
+
from sqlspec.exceptions import (
|
|
102
|
+
ImproperConfigurationError,
|
|
103
|
+
NotFoundError,
|
|
104
|
+
SQLFileNotFoundError,
|
|
105
|
+
SQLSpecError,
|
|
106
|
+
StorageCapabilityError,
|
|
107
|
+
TransactionError,
|
|
108
|
+
)
|
|
109
|
+
from sqlspec.observability._common import get_trace_context, redact_sql_literals, resolve_db_system
|
|
110
|
+
from sqlspec.observability._runtime import ObservabilityRuntime
|
|
111
|
+
from sqlspec.protocols import StatementProtocol
|
|
112
|
+
from sqlspec.storage._ingest import (
|
|
113
|
+
execute_load_from_storage_async,
|
|
114
|
+
execute_load_from_storage_sync,
|
|
115
|
+
execute_staged_load_async,
|
|
116
|
+
execute_staged_load_sync,
|
|
117
|
+
)
|
|
118
|
+
from sqlspec.storage.pipeline import (
|
|
119
|
+
CAPABILITY_HINTS,
|
|
120
|
+
attach_partition_telemetry,
|
|
121
|
+
create_storage_job,
|
|
122
|
+
ingest_telemetry_from_batches,
|
|
123
|
+
)
|
|
124
|
+
from sqlspec.utils.arrow_helpers import (
|
|
125
|
+
arrow_batch_to_rows,
|
|
126
|
+
arrow_table_needs_parameter_preparation,
|
|
127
|
+
arrow_table_to_rows,
|
|
128
|
+
build_ingest_telemetry,
|
|
129
|
+
coerce_arrow_batches,
|
|
130
|
+
coerce_arrow_table,
|
|
131
|
+
encode_arrow_batch_pg_binary,
|
|
132
|
+
iter_pgcopy_binary_chunks,
|
|
133
|
+
iter_pgcopy_binary_chunks_async,
|
|
134
|
+
records_to_arrow_table,
|
|
135
|
+
)
|
|
136
|
+
from sqlspec.utils.logging import get_logger, log_with_context
|
|
137
|
+
from sqlspec.utils.schema import to_schema as _to_schema_impl
|
|
138
|
+
from sqlspec.utils.serializers._json import from_json
|
|
139
|
+
from sqlspec.utils.text import normalize_identifier, quote_identifier, split_qualified_identifier
|
|
140
|
+
from sqlspec.utils.type_guards import (
|
|
141
|
+
has_asdict_method,
|
|
142
|
+
has_cursor_metadata,
|
|
143
|
+
has_statement_type,
|
|
144
|
+
is_dict_row,
|
|
145
|
+
is_mapping_like,
|
|
146
|
+
is_statement_filter,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if TYPE_CHECKING:
|
|
150
|
+
from collections import OrderedDict, abc
|
|
151
|
+
from collections.abc import Awaitable
|
|
152
|
+
from types import TracebackType
|
|
153
|
+
|
|
154
|
+
from sqlspec.core.compiler import OperationType
|
|
155
|
+
from sqlspec.core.filters import FilterTypeT, StatementFilter
|
|
156
|
+
from sqlspec.core.parameters._types import ConvertedParameters
|
|
157
|
+
from sqlspec.core.result._base import ArrowResult
|
|
158
|
+
from sqlspec.core.stack import StatementStack
|
|
159
|
+
from sqlspec.data_dictionary._types import DialectConfig
|
|
160
|
+
from sqlspec.storage.pipeline import (
|
|
161
|
+
AsyncStoragePipeline,
|
|
162
|
+
StorageBridgeJob,
|
|
163
|
+
StorageCapabilities,
|
|
164
|
+
StorageTelemetry,
|
|
165
|
+
SyncStoragePipeline,
|
|
166
|
+
)
|
|
167
|
+
from sqlspec.typing import ArrowRecordBatch, ArrowTable, SchemaT, StatementParameters
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
__all__ = (
|
|
171
|
+
"VERSION_GROUPS_MIN_FOR_MINOR",
|
|
172
|
+
"VERSION_GROUPS_MIN_FOR_PATCH",
|
|
173
|
+
"AsyncExceptionHandler",
|
|
174
|
+
"CachedQuery",
|
|
175
|
+
"CommonDriverAttributesMixin",
|
|
176
|
+
"DataDictionaryDialectMixin",
|
|
177
|
+
"DataDictionaryMixin",
|
|
178
|
+
"ExecutionResult",
|
|
179
|
+
"StackExecutionObserver",
|
|
180
|
+
"SyncExceptionHandler",
|
|
181
|
+
"cache_hit_hooks_unchanged",
|
|
182
|
+
"describe_stack_statement",
|
|
183
|
+
"handle_single_row_error",
|
|
184
|
+
"hash_stack_operations",
|
|
185
|
+
"operation_requires_transaction",
|
|
186
|
+
"parameter_value_needs_processing",
|
|
187
|
+
"parameter_values_need_processing",
|
|
188
|
+
"type_coercion_fallbacks",
|
|
189
|
+
"validate_load_from_storage_kwargs",
|
|
190
|
+
"validate_savepoint_name",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
logger = get_logger("sqlspec.driver")
|
|
195
|
+
|
|
196
|
+
_SAVEPOINT_NAME_PATTERN: Final["re.Pattern[str]"] = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
197
|
+
|
|
198
|
+
VERSION_GROUPS_MIN_FOR_MINOR = 1
|
|
199
|
+
VERSION_GROUPS_MIN_FOR_PATCH = 2
|
|
200
|
+
_MIN_QUOTED_IDENTIFIER_LEN: Final[int] = 2
|
|
201
|
+
_INT64_MIN: Final[int] = -9223372036854775808
|
|
202
|
+
_INT64_MAX: Final[int] = 9223372036854775807
|
|
203
|
+
_MAX_NUMERIC_PRECISION: Final[int] = 38
|
|
204
|
+
|
|
205
|
+
StreamT = TypeVar("StreamT")
|
|
206
|
+
_SCRIPT_BIND_KEYWORDS: Final[frozenset[str]] = frozenset({
|
|
207
|
+
"SELECT",
|
|
208
|
+
"INSERT",
|
|
209
|
+
"UPDATE",
|
|
210
|
+
"DELETE",
|
|
211
|
+
"MERGE",
|
|
212
|
+
"WITH",
|
|
213
|
+
"VALUES",
|
|
214
|
+
"CALL",
|
|
215
|
+
"EXEC",
|
|
216
|
+
"EXECUTE",
|
|
217
|
+
})
|
|
218
|
+
_ORACLE_SCRIPT_BIND_KEYWORDS: Final[frozenset[str]] = frozenset({"BEGIN", "DECLARE"})
|
|
219
|
+
_SCRIPT_NAMED_STYLES: Final[frozenset[ParameterStyle]] = frozenset({
|
|
220
|
+
ParameterStyle.NAMED_COLON,
|
|
221
|
+
ParameterStyle.NAMED_AT,
|
|
222
|
+
ParameterStyle.NAMED_DOLLAR,
|
|
223
|
+
ParameterStyle.NAMED_PYFORMAT,
|
|
224
|
+
})
|
|
225
|
+
_SCRIPT_INDEX_STYLES: Final[frozenset[ParameterStyle]] = frozenset({
|
|
226
|
+
ParameterStyle.NUMERIC,
|
|
227
|
+
ParameterStyle.POSITIONAL_COLON,
|
|
228
|
+
})
|
|
229
|
+
_DEFAULT_DML_METADATA: Final = {"status_message": "OK"}
|
|
230
|
+
_EMPTY_DML_DATA: Final[tuple[()]] = ()
|
|
231
|
+
_READ_ONLY_OPERATION_TYPES: Final[frozenset[str]] = frozenset({"SELECT", "PRAGMA", "COPY_TO"})
|
|
232
|
+
|
|
233
|
+
_CACHED_NAMED_STYLES: Final[frozenset[str]] = frozenset((
|
|
234
|
+
ParameterStyle.NAMED_COLON.value,
|
|
235
|
+
ParameterStyle.NAMED_AT.value,
|
|
236
|
+
ParameterStyle.NAMED_DOLLAR.value,
|
|
237
|
+
ParameterStyle.NAMED_PYFORMAT.value,
|
|
238
|
+
))
|
|
239
|
+
_POSITIONAL_DRIVER_STYLES: Final[frozenset[ParameterStyle]] = frozenset((
|
|
240
|
+
ParameterStyle.NUMERIC,
|
|
241
|
+
ParameterStyle.QMARK,
|
|
242
|
+
ParameterStyle.POSITIONAL_COLON,
|
|
243
|
+
ParameterStyle.POSITIONAL_PYFORMAT,
|
|
244
|
+
))
|
|
245
|
+
_TOP_LIMIT_DIALECTS: Final[frozenset[str]] = frozenset({"tsql", "mssql"})
|
|
246
|
+
_DYNAMIC_CALLABLE_COUNTER: Final = _itertools_count(1)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class SyncExceptionHandler(Protocol):
|
|
250
|
+
"""Protocol for synchronous context managers that map driver errors to SQLSpec exceptions.
|
|
251
|
+
|
|
252
|
+
Implementations suppress recognized driver exceptions in ``__exit__`` and expose the
|
|
253
|
+
mapped SQLSpec exception on ``pending_exception`` for the caller to raise.
|
|
254
|
+
"""
|
|
255
|
+
|
|
256
|
+
def __enter__(self) -> Self: ...
|
|
257
|
+
def __exit__(
|
|
258
|
+
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: "TracebackType | None"
|
|
259
|
+
) -> bool: ...
|
|
260
|
+
@property
|
|
261
|
+
def pending_exception(self) -> Exception | None: ...
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class AsyncExceptionHandler(Protocol):
|
|
265
|
+
"""Protocol for asynchronous context managers that map driver errors to SQLSpec exceptions.
|
|
266
|
+
|
|
267
|
+
Implementations suppress recognized driver exceptions in ``__aexit__`` and expose the
|
|
268
|
+
mapped SQLSpec exception on ``pending_exception`` for the caller to raise.
|
|
269
|
+
"""
|
|
270
|
+
|
|
271
|
+
async def __aenter__(self) -> Self: ...
|
|
272
|
+
async def __aexit__(
|
|
273
|
+
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: "TracebackType | None"
|
|
274
|
+
) -> bool: ...
|
|
275
|
+
@property
|
|
276
|
+
def pending_exception(self) -> Exception | None: ...
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class ExecutionResult(NamedTuple):
|
|
280
|
+
"""Execution result containing all data needed for SQLResult building."""
|
|
281
|
+
|
|
282
|
+
cursor_result: Any
|
|
283
|
+
rowcount_override: int | None
|
|
284
|
+
special_data: Any
|
|
285
|
+
selected_data: list[Any] | None
|
|
286
|
+
column_names: list[str] | None
|
|
287
|
+
data_row_count: int | None
|
|
288
|
+
statement_count: int | None
|
|
289
|
+
successful_statements: int | None
|
|
290
|
+
is_script_result: bool
|
|
291
|
+
is_select_result: bool
|
|
292
|
+
is_many_result: bool
|
|
293
|
+
row_format: RowFormat = "dict"
|
|
294
|
+
last_inserted_id: int | str | None = None
|
|
295
|
+
column_types: dict[str, str] | None = None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def describe_stack_statement(statement: "StatementProtocol | str") -> str:
|
|
299
|
+
"""Return a readable representation of a stack statement for diagnostics."""
|
|
300
|
+
if isinstance(statement, str):
|
|
301
|
+
return statement
|
|
302
|
+
if isinstance(statement, StatementProtocol):
|
|
303
|
+
return statement.raw_sql or repr(statement)
|
|
304
|
+
return repr(statement)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def validate_savepoint_name(name: str) -> str:
|
|
308
|
+
"""Return the savepoint name when it is a safe SQL identifier."""
|
|
309
|
+
if not _SAVEPOINT_NAME_PATTERN.fullmatch(name):
|
|
310
|
+
msg = f"Invalid savepoint name: {name!r}"
|
|
311
|
+
raise TransactionError(msg)
|
|
312
|
+
return name
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def handle_single_row_error(error: ValueError) -> "NoReturn":
|
|
316
|
+
"""Normalize single-row selection errors to SQLSpec exceptions."""
|
|
317
|
+
message = str(error)
|
|
318
|
+
if message.startswith("No result found"):
|
|
319
|
+
msg = "No rows found"
|
|
320
|
+
not_found = NotFoundError(msg)
|
|
321
|
+
not_found.__cause__ = error
|
|
322
|
+
raise not_found from error
|
|
323
|
+
raise error
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def hash_stack_operations(stack: "StatementStack") -> "tuple[str, ...]":
|
|
327
|
+
"""Return SHA256 fingerprints for statements contained in the stack."""
|
|
328
|
+
hashes: list[str] = []
|
|
329
|
+
for operation in stack.operations:
|
|
330
|
+
summary = describe_stack_statement(operation.statement)
|
|
331
|
+
if not isinstance(summary, str):
|
|
332
|
+
summary = str(summary)
|
|
333
|
+
digest = hashlib.sha256(summary.encode("utf-8")).hexdigest()
|
|
334
|
+
hashes.append(digest[:16])
|
|
335
|
+
return tuple(hashes)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
@mypyc_attr(allow_interpreted_subclasses=False)
|
|
339
|
+
class StackExecutionObserver:
|
|
340
|
+
"""Context manager that aggregates telemetry for stack execution."""
|
|
341
|
+
|
|
342
|
+
__slots__ = (
|
|
343
|
+
"continue_on_error",
|
|
344
|
+
"driver",
|
|
345
|
+
"hashed_operations",
|
|
346
|
+
"metrics",
|
|
347
|
+
"native_pipeline",
|
|
348
|
+
"runtime",
|
|
349
|
+
"span",
|
|
350
|
+
"stack",
|
|
351
|
+
"started",
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
def __init__(
|
|
355
|
+
self,
|
|
356
|
+
driver: "CommonDriverAttributesMixin",
|
|
357
|
+
stack: "StatementStack",
|
|
358
|
+
continue_on_error: bool,
|
|
359
|
+
native_pipeline: bool,
|
|
360
|
+
) -> None:
|
|
361
|
+
self.driver = driver
|
|
362
|
+
self.stack = stack
|
|
363
|
+
self.continue_on_error = continue_on_error
|
|
364
|
+
self.native_pipeline = native_pipeline
|
|
365
|
+
self.runtime = driver.observability
|
|
366
|
+
self.metrics = StackExecutionMetrics(
|
|
367
|
+
adapter=type(driver).__name__,
|
|
368
|
+
statement_count=len(stack.operations),
|
|
369
|
+
continue_on_error=continue_on_error,
|
|
370
|
+
native_pipeline=native_pipeline,
|
|
371
|
+
forced_disable=driver.stack_native_disabled,
|
|
372
|
+
)
|
|
373
|
+
self.hashed_operations = hash_stack_operations(stack)
|
|
374
|
+
self.span: Any | None = None
|
|
375
|
+
self.started = 0.0
|
|
376
|
+
|
|
377
|
+
def __enter__(self) -> Self:
|
|
378
|
+
self.started = perf_counter()
|
|
379
|
+
trace_id, span_id = get_trace_context()
|
|
380
|
+
attributes = {
|
|
381
|
+
"sqlspec.stack.statement_count": len(self.stack.operations),
|
|
382
|
+
"sqlspec.stack.continue_on_error": self.continue_on_error,
|
|
383
|
+
"sqlspec.stack.native_pipeline": self.native_pipeline,
|
|
384
|
+
"sqlspec.stack.forced_disable": self.driver.stack_native_disabled,
|
|
385
|
+
}
|
|
386
|
+
self.span = self.runtime.start_span("sqlspec.stack.execute", attributes=attributes)
|
|
387
|
+
log_with_context(
|
|
388
|
+
logger,
|
|
389
|
+
logging.DEBUG,
|
|
390
|
+
"stack.execute.start",
|
|
391
|
+
driver=type(self.driver).__name__,
|
|
392
|
+
db_system=resolve_db_system(type(self.driver).__name__),
|
|
393
|
+
stack_size=len(self.stack.operations),
|
|
394
|
+
continue_on_error=self.continue_on_error,
|
|
395
|
+
native_pipeline=self.native_pipeline,
|
|
396
|
+
forced_disable=self.driver.stack_native_disabled,
|
|
397
|
+
hashed_operations=self.hashed_operations,
|
|
398
|
+
trace_id=trace_id,
|
|
399
|
+
span_id=span_id,
|
|
400
|
+
)
|
|
401
|
+
return self
|
|
402
|
+
|
|
403
|
+
def __exit__(
|
|
404
|
+
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: "TracebackType | None"
|
|
405
|
+
) -> Literal[False]:
|
|
406
|
+
duration = perf_counter() - self.started
|
|
407
|
+
self.metrics.record_duration(duration)
|
|
408
|
+
if isinstance(exc_val, Exception):
|
|
409
|
+
self.metrics.record_error(exc_val)
|
|
410
|
+
self.runtime.span_manager.end_span(self.span, error=exc_val if exc_val is not None else None)
|
|
411
|
+
self.metrics.emit(self.runtime)
|
|
412
|
+
level = logging.ERROR if exc_val is not None else logging.DEBUG
|
|
413
|
+
trace_id, span_id = get_trace_context()
|
|
414
|
+
log_with_context(
|
|
415
|
+
logger,
|
|
416
|
+
level,
|
|
417
|
+
"stack.execute.failed" if exc_val is not None else "stack.execute.complete",
|
|
418
|
+
driver=type(self.driver).__name__,
|
|
419
|
+
db_system=resolve_db_system(type(self.driver).__name__),
|
|
420
|
+
stack_size=len(self.stack.operations),
|
|
421
|
+
continue_on_error=self.continue_on_error,
|
|
422
|
+
native_pipeline=self.native_pipeline,
|
|
423
|
+
forced_disable=self.driver.stack_native_disabled,
|
|
424
|
+
hashed_operations=self.hashed_operations,
|
|
425
|
+
duration_ms=duration * 1000,
|
|
426
|
+
error_type=type(exc_val).__name__ if exc_val is not None else None,
|
|
427
|
+
trace_id=trace_id,
|
|
428
|
+
span_id=span_id,
|
|
429
|
+
)
|
|
430
|
+
return False
|
|
431
|
+
|
|
432
|
+
def record_operation_error(self, error: Exception) -> None:
|
|
433
|
+
"""Record an operation error when continue-on-error is enabled."""
|
|
434
|
+
self.metrics.record_operation_error(error)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
438
|
+
@trait
|
|
439
|
+
class DataDictionaryDialectMixin:
|
|
440
|
+
"""Mixin providing dialect SQL helpers for data dictionaries."""
|
|
441
|
+
|
|
442
|
+
__slots__ = ()
|
|
443
|
+
|
|
444
|
+
dialect: "ClassVar[str]"
|
|
445
|
+
|
|
446
|
+
def get_dialect_config(self) -> "DialectConfig":
|
|
447
|
+
"""Return the dialect configuration for this data dictionary."""
|
|
448
|
+
return get_dialect_config(type(self).dialect)
|
|
449
|
+
|
|
450
|
+
def get_query(self, domain: str, operation: str, *, mode: str | None = None) -> "SQL":
|
|
451
|
+
"""Return an exact domain query for this dialect."""
|
|
452
|
+
loader = get_data_dictionary_loader()
|
|
453
|
+
query = loader.get_domain_query(type(self).dialect, domain, operation, mode=mode)
|
|
454
|
+
if query.sql is None:
|
|
455
|
+
msg = f"No data-dictionary query found for {type(self).dialect}/{domain}/{operation}"
|
|
456
|
+
raise SQLFileNotFoundError(msg)
|
|
457
|
+
return query.sql
|
|
458
|
+
|
|
459
|
+
def get_query_text(self, domain: str, operation: str, *, mode: str | None = None) -> str:
|
|
460
|
+
"""Return raw SQL text for an exact domain query."""
|
|
461
|
+
return self.get_query(domain, operation, mode=mode).raw_sql
|
|
462
|
+
|
|
463
|
+
def get_query_text_or_none(self, domain: str, operation: str, *, mode: str | None = None) -> "str | None":
|
|
464
|
+
"""Return raw SQL text for a named query or None if missing."""
|
|
465
|
+
try:
|
|
466
|
+
return self.get_query_text(domain, operation, mode=mode)
|
|
467
|
+
except SQLFileNotFoundError:
|
|
468
|
+
return None
|
|
469
|
+
|
|
470
|
+
def resolve_schema(self, schema: "str | None") -> "str | None":
|
|
471
|
+
"""Return a schema name using dialect defaults when missing."""
|
|
472
|
+
config = self.get_dialect_config()
|
|
473
|
+
if schema is not None:
|
|
474
|
+
return normalize_identifier(schema, config.name)
|
|
475
|
+
if config.default_schema is None:
|
|
476
|
+
return None
|
|
477
|
+
return normalize_identifier(config.default_schema, config.name)
|
|
478
|
+
|
|
479
|
+
def resolve_identifier(self, identifier: str) -> str:
|
|
480
|
+
"""Return a dialect-normalized identifier value."""
|
|
481
|
+
return normalize_identifier(identifier, self.get_dialect_config().name)
|
|
482
|
+
|
|
483
|
+
def resolve_ddl_object_name(self, driver: Any, object_name: str, schema: "str | None") -> "tuple[str, str | None]":
|
|
484
|
+
"""Normalize a caller-supplied object name and schema into exact catalog names.
|
|
485
|
+
|
|
486
|
+
Unquoted names follow the dialect's identifier folding; quoted names are kept verbatim.
|
|
487
|
+
Multi-dialect data dictionaries override this to resolve against the dialect detected
|
|
488
|
+
from ``driver``.
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
driver: Database driver instance.
|
|
492
|
+
object_name: Caller-supplied object name.
|
|
493
|
+
schema: Caller-supplied schema name, or None for the dialect default.
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
Exact catalog object name and schema name.
|
|
497
|
+
"""
|
|
498
|
+
_ = driver
|
|
499
|
+
return (self.resolve_identifier(object_name), self.resolve_schema(schema))
|
|
500
|
+
|
|
501
|
+
def exact_catalog_identifier(self, driver: Any, name: str) -> str:
|
|
502
|
+
"""Return ``name`` in the form metadata getters resolve back to the exact catalog name.
|
|
503
|
+
|
|
504
|
+
Metadata getters such as ``get_columns`` normalize their ``table``/``schema`` arguments
|
|
505
|
+
as caller input (for example PostgreSQL folds unquoted names to lower case). Names read
|
|
506
|
+
from the catalog are already exact, so any name that normalization would change is
|
|
507
|
+
passed quoted.
|
|
508
|
+
|
|
509
|
+
Args:
|
|
510
|
+
driver: Database driver instance.
|
|
511
|
+
name: Exact catalog identifier.
|
|
512
|
+
|
|
513
|
+
Returns:
|
|
514
|
+
Identifier text that round-trips through the dictionary's normalization unchanged.
|
|
515
|
+
"""
|
|
516
|
+
_ = driver
|
|
517
|
+
if self.resolve_identifier(name) == name:
|
|
518
|
+
return name
|
|
519
|
+
return quote_identifier(name)
|
|
520
|
+
|
|
521
|
+
def resolve_feature_flag(self, feature: str, version: "VersionInfo | None") -> bool:
|
|
522
|
+
"""Resolve a feature flag using dialect config and version info."""
|
|
523
|
+
config = self.get_dialect_config()
|
|
524
|
+
flag = config.get_feature_flag(feature)
|
|
525
|
+
if flag is not None:
|
|
526
|
+
return flag
|
|
527
|
+
required_version = config.get_feature_version(feature)
|
|
528
|
+
if required_version is None or version is None:
|
|
529
|
+
return False
|
|
530
|
+
return bool(version >= required_version)
|
|
531
|
+
|
|
532
|
+
def get_default_features(self) -> "list[str]":
|
|
533
|
+
"""Get default feature flags for this dialect."""
|
|
534
|
+
return []
|
|
535
|
+
|
|
536
|
+
def list_available_features(self) -> "list[str]":
|
|
537
|
+
"""List all features that can be checked via get_feature_flag.
|
|
538
|
+
|
|
539
|
+
Returns:
|
|
540
|
+
List of feature names this data dictionary supports
|
|
541
|
+
"""
|
|
542
|
+
config = self.get_dialect_config()
|
|
543
|
+
features = set(self.get_default_features())
|
|
544
|
+
features.update(config.feature_flags.keys())
|
|
545
|
+
features.update(config.feature_versions.keys())
|
|
546
|
+
return sorted(features)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
550
|
+
@trait
|
|
551
|
+
class DataDictionaryMixin:
|
|
552
|
+
"""Mixin providing common data dictionary functionality.
|
|
553
|
+
|
|
554
|
+
Includes version caching to avoid repeated database queries when checking
|
|
555
|
+
feature flags or optimal types.
|
|
556
|
+
"""
|
|
557
|
+
|
|
558
|
+
__slots__ = ()
|
|
559
|
+
|
|
560
|
+
dialect: "ClassVar[str]"
|
|
561
|
+
|
|
562
|
+
_version_cache: "dict[int, VersionInfo | None]"
|
|
563
|
+
_version_fetch_attempted: "set[int]"
|
|
564
|
+
|
|
565
|
+
def get_cached_version(self, driver_id: int) -> "VersionCacheResult":
|
|
566
|
+
"""Get cached version info for a driver.
|
|
567
|
+
|
|
568
|
+
Args:
|
|
569
|
+
driver_id: The id() of the driver instance.
|
|
570
|
+
|
|
571
|
+
Returns:
|
|
572
|
+
Tuple of (was_cached, version_info). If was_cached is False,
|
|
573
|
+
the caller should fetch the version and call cache_version().
|
|
574
|
+
"""
|
|
575
|
+
if driver_id in self._version_fetch_attempted:
|
|
576
|
+
return True, self._version_cache.get(driver_id)
|
|
577
|
+
return False, None
|
|
578
|
+
|
|
579
|
+
def cache_version(self, driver_id: int, version: "VersionInfo | None") -> None:
|
|
580
|
+
"""Cache version info for a driver.
|
|
581
|
+
|
|
582
|
+
Args:
|
|
583
|
+
driver_id: The id() of the driver instance.
|
|
584
|
+
version: The version info to cache (can be None if detection failed).
|
|
585
|
+
"""
|
|
586
|
+
self._version_fetch_attempted.add(driver_id)
|
|
587
|
+
if version is not None:
|
|
588
|
+
self._version_cache[driver_id] = version
|
|
589
|
+
|
|
590
|
+
def parse_version_with_pattern(self, pattern: "re.Pattern[str]", version_str: str) -> "VersionInfo | None":
|
|
591
|
+
"""Parse version string using a specific regex pattern.
|
|
592
|
+
|
|
593
|
+
Args:
|
|
594
|
+
pattern: Compiled regex pattern for the version format
|
|
595
|
+
version_str: Raw version string from database
|
|
596
|
+
|
|
597
|
+
Returns:
|
|
598
|
+
VersionInfo instance or None if parsing fails
|
|
599
|
+
"""
|
|
600
|
+
match = pattern.search(version_str)
|
|
601
|
+
if not match:
|
|
602
|
+
return None
|
|
603
|
+
|
|
604
|
+
groups = match.groups()
|
|
605
|
+
if not groups:
|
|
606
|
+
return None
|
|
607
|
+
|
|
608
|
+
major = int(groups[0])
|
|
609
|
+
minor = int(groups[1]) if len(groups) > VERSION_GROUPS_MIN_FOR_MINOR and groups[1] else 0
|
|
610
|
+
patch = int(groups[2]) if len(groups) > VERSION_GROUPS_MIN_FOR_PATCH and groups[2] else 0
|
|
611
|
+
return VersionInfo(major, minor, patch)
|
|
612
|
+
|
|
613
|
+
def get_default_type_mapping(self) -> "dict[str, str]":
|
|
614
|
+
"""Get default type mappings for common categories.
|
|
615
|
+
|
|
616
|
+
Returns:
|
|
617
|
+
Dictionary mapping type categories to generic SQL types
|
|
618
|
+
"""
|
|
619
|
+
return {
|
|
620
|
+
"json": "TEXT",
|
|
621
|
+
"uuid": "VARCHAR(36)",
|
|
622
|
+
"boolean": "INTEGER",
|
|
623
|
+
"timestamp": "TIMESTAMP",
|
|
624
|
+
"text": "TEXT",
|
|
625
|
+
"blob": "BLOB",
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
def sort_tables_topologically(self, tables: "list[str]", foreign_keys: "list[ForeignKeyMetadata]") -> "list[str]":
|
|
629
|
+
"""Sort tables topologically based on typed foreign key dependency edges.
|
|
630
|
+
|
|
631
|
+
Args:
|
|
632
|
+
tables: List of table names.
|
|
633
|
+
foreign_keys: List of foreign key metadata.
|
|
634
|
+
|
|
635
|
+
Returns:
|
|
636
|
+
List of table names in topological order (dependencies first).
|
|
637
|
+
"""
|
|
638
|
+
table_schemas: dict[str, str | None] = {}
|
|
639
|
+
for fk in foreign_keys:
|
|
640
|
+
table_schemas.setdefault(fk.table_name, fk.schema)
|
|
641
|
+
table_schemas.setdefault(fk.referenced_table, fk.referenced_schema or fk.schema)
|
|
642
|
+
table_objects = tuple(ObjectIdentity(table, "table", schema=table_schemas.get(table)) for table in tables)
|
|
643
|
+
result = sort_dependencies(table_objects, dependency_edges_from_foreign_keys(foreign_keys, source="unknown"))
|
|
644
|
+
result.raise_for_cycles()
|
|
645
|
+
return [identity.name for identity in result.ordered]
|
|
646
|
+
|
|
647
|
+
def build_synthesized_table_ddl(
|
|
648
|
+
self,
|
|
649
|
+
table_name: str,
|
|
650
|
+
columns: "abc.Sequence[Any]",
|
|
651
|
+
*,
|
|
652
|
+
schema: str | None = None,
|
|
653
|
+
constraints: "abc.Sequence[Any] | None" = None,
|
|
654
|
+
foreign_keys: "abc.Sequence[Any] | None" = None,
|
|
655
|
+
indexes: "abc.Sequence[Any] | None" = None,
|
|
656
|
+
target_dialect: str | None = None,
|
|
657
|
+
source_dialect: str | None = None,
|
|
658
|
+
warnings: tuple[str, ...] = (),
|
|
659
|
+
) -> "DDLResult":
|
|
660
|
+
"""Synthesize a table DDLResult from catalog metadata rows via sqlspec.builder.
|
|
661
|
+
|
|
662
|
+
Args:
|
|
663
|
+
table_name: Exact catalog table name.
|
|
664
|
+
columns: Column metadata rows.
|
|
665
|
+
schema: Exact catalog schema name.
|
|
666
|
+
constraints: Constraint metadata rows.
|
|
667
|
+
foreign_keys: Foreign key metadata rows.
|
|
668
|
+
indexes: Index metadata rows.
|
|
669
|
+
target_dialect: Dialect to render; defaults to the source dialect.
|
|
670
|
+
source_dialect: Dialect the catalog types, defaults, and expressions are written in;
|
|
671
|
+
defaults to this dictionary's dialect.
|
|
672
|
+
warnings: Warnings to attach to the result.
|
|
673
|
+
|
|
674
|
+
Returns:
|
|
675
|
+
Generated table DDL result.
|
|
676
|
+
"""
|
|
677
|
+
resolved_source = _ddl_dialect_or_none(source_dialect or type(self).dialect)
|
|
678
|
+
return compile_table_ddl_results(
|
|
679
|
+
table_name,
|
|
680
|
+
columns,
|
|
681
|
+
schema=schema,
|
|
682
|
+
constraints=constraints,
|
|
683
|
+
foreign_keys=foreign_keys,
|
|
684
|
+
indexes=indexes,
|
|
685
|
+
dialect=_ddl_dialect_or_none(target_dialect) or resolved_source,
|
|
686
|
+
source_dialect=resolved_source,
|
|
687
|
+
warnings=warnings,
|
|
688
|
+
)
|
|
689
|
+
|
|
690
|
+
def resolve_ddl_dialect(self, driver: Any) -> "str | None":
|
|
691
|
+
"""Return the SQLGlot dialect used to parse and render DDL for ``driver``.
|
|
692
|
+
|
|
693
|
+
Multi-dialect data dictionaries override this to report the dialect detected from the driver.
|
|
694
|
+
|
|
695
|
+
Args:
|
|
696
|
+
driver: Database driver instance.
|
|
697
|
+
|
|
698
|
+
Returns:
|
|
699
|
+
SQLGlot dialect name, or None for generic SQL.
|
|
700
|
+
"""
|
|
701
|
+
engine_family = getattr(driver, "engine_family", None)
|
|
702
|
+
if not isinstance(engine_family, str) or not engine_family.strip():
|
|
703
|
+
engine_cache = getattr(self, "_engine_version_cache", None)
|
|
704
|
+
if isinstance(engine_cache, Mapping) and id(driver) in engine_cache:
|
|
705
|
+
engine_family = getattr(engine_cache[id(driver)], "engine_family", None)
|
|
706
|
+
else:
|
|
707
|
+
get_engine_version = getattr(self, "_get_engine_version", None)
|
|
708
|
+
if (
|
|
709
|
+
callable(get_engine_version)
|
|
710
|
+
and not getattr(driver, "is_async", False)
|
|
711
|
+
and not inspect.iscoroutinefunction(get_engine_version)
|
|
712
|
+
):
|
|
713
|
+
with contextlib.suppress(Exception):
|
|
714
|
+
engine_family = getattr(get_engine_version(driver), "engine_family", None)
|
|
715
|
+
if isinstance(engine_family, str) and engine_family.strip():
|
|
716
|
+
return _ddl_dialect_or_none(engine_family.strip().lower())
|
|
717
|
+
return _ddl_dialect_or_none(type(self).dialect)
|
|
718
|
+
|
|
719
|
+
def _transpile_ddl_result(self, result: "DDLResult", target_dialect: str | None = None) -> "DDLResult":
|
|
720
|
+
"""Transpile a supported DDLResult into ``target_dialect``.
|
|
721
|
+
|
|
722
|
+
Returns an explicit unsupported result carrying the parser error when SQLGlot cannot
|
|
723
|
+
transpile the statement, instead of returning untranslated SQL labelled as the target.
|
|
724
|
+
"""
|
|
725
|
+
if not target_dialect or not result.ddl or result.status != MetadataSupport.SUPPORTED:
|
|
726
|
+
return result
|
|
727
|
+
source_dialect = _ddl_dialect_or_none(result.identity.dialect or type(self).dialect)
|
|
728
|
+
if source_dialect == target_dialect:
|
|
729
|
+
return result
|
|
730
|
+
identity = self._copy_identity(result.identity, dialect=target_dialect)
|
|
731
|
+
try:
|
|
732
|
+
transpiled = sqlglot.transpile(
|
|
733
|
+
result.ddl, read=_sqlglot_dialect(source_dialect), write=_sqlglot_dialect(target_dialect)
|
|
734
|
+
)
|
|
735
|
+
except SqlglotError as exc:
|
|
736
|
+
return DDLResult.unsupported(
|
|
737
|
+
identity,
|
|
738
|
+
source=result.source,
|
|
739
|
+
warnings=(
|
|
740
|
+
*result.warnings,
|
|
741
|
+
(
|
|
742
|
+
f"Could not transpile {result.identity.object_type} {result.identity.name} DDL "
|
|
743
|
+
f"from {source_dialect or 'generic'} to {target_dialect}: {exc}"
|
|
744
|
+
),
|
|
745
|
+
),
|
|
746
|
+
)
|
|
747
|
+
statements = [stmt.rstrip(";").strip() for stmt in transpiled if stmt.strip()]
|
|
748
|
+
if not statements:
|
|
749
|
+
return DDLResult.unsupported(
|
|
750
|
+
identity,
|
|
751
|
+
source=result.source,
|
|
752
|
+
warnings=(*result.warnings, f"Transpiling {result.identity.name} DDL produced no statements"),
|
|
753
|
+
)
|
|
754
|
+
return DDLResult(
|
|
755
|
+
identity=identity,
|
|
756
|
+
status=result.status,
|
|
757
|
+
fidelity=result.fidelity,
|
|
758
|
+
source=result.source,
|
|
759
|
+
ddl=";\n\n".join(statements) + ";",
|
|
760
|
+
dependencies=result.dependencies,
|
|
761
|
+
redactions=result.redactions,
|
|
762
|
+
context=result.context,
|
|
763
|
+
warnings=result.warnings,
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
def _build_drop_ddl_result(self, result: "DDLResult", target_dialect: str | None = None) -> "DDLResult":
|
|
767
|
+
"""Build a ``DROP <kind> IF EXISTS`` DDLResult for a schema object.
|
|
768
|
+
|
|
769
|
+
Identifiers are always quoted so the statement targets the exact catalog name.
|
|
770
|
+
Object kinds without a portable DROP form return an explicit unsupported result.
|
|
771
|
+
"""
|
|
772
|
+
identity = result.identity
|
|
773
|
+
dialect = _ddl_dialect_or_none(target_dialect or identity.dialect or type(self).dialect)
|
|
774
|
+
drop_identity = self._copy_identity(identity, dialect=dialect or identity.dialect)
|
|
775
|
+
drop_kind = _DROP_OBJECT_KINDS.get(identity.object_type.lower())
|
|
776
|
+
if drop_kind is None:
|
|
777
|
+
return DDLResult.unsupported(
|
|
778
|
+
drop_identity,
|
|
779
|
+
source=result.source,
|
|
780
|
+
warnings=(f"No DROP statement form is defined for {identity.object_type} {identity.name}",),
|
|
781
|
+
)
|
|
782
|
+
kind, materialized = drop_kind
|
|
783
|
+
drop_expr = exp.Drop(
|
|
784
|
+
tables=[self._quoted_table(identity.name, identity.schema, identity.catalog)],
|
|
785
|
+
kind=kind,
|
|
786
|
+
exists=True,
|
|
787
|
+
materialized=materialized,
|
|
788
|
+
)
|
|
789
|
+
return DDLResult(
|
|
790
|
+
identity=drop_identity,
|
|
791
|
+
status=MetadataSupport.SUPPORTED,
|
|
792
|
+
fidelity=result.fidelity,
|
|
793
|
+
source=result.source,
|
|
794
|
+
ddl=f"{drop_expr.sql(dialect=_sqlglot_dialect(dialect), copy=False)};",
|
|
795
|
+
dependencies=result.dependencies,
|
|
796
|
+
redactions=result.redactions,
|
|
797
|
+
context=result.context,
|
|
798
|
+
warnings=result.warnings,
|
|
799
|
+
)
|
|
800
|
+
|
|
801
|
+
def _extract_table_name_and_schema(
|
|
802
|
+
self, item: Any, default_schema: str | None = None
|
|
803
|
+
) -> tuple[str | None, str | None]:
|
|
804
|
+
"""Extract table name and schema from a table metadata row or object."""
|
|
805
|
+
resolved_name: str | None = None
|
|
806
|
+
resolved_schema: str | None = default_schema
|
|
807
|
+
if isinstance(item, Mapping):
|
|
808
|
+
name = item.get("table_name") or item.get("name") or item.get("object_name")
|
|
809
|
+
tbl_schema = item.get("schema_name") or item.get("table_schema") or default_schema
|
|
810
|
+
resolved_name = str(name) if name else None
|
|
811
|
+
resolved_schema = str(tbl_schema) if tbl_schema else default_schema
|
|
812
|
+
else:
|
|
813
|
+
ident = getattr(item, "identity", None)
|
|
814
|
+
if isinstance(ident, ObjectIdentity):
|
|
815
|
+
resolved_name = ident.name
|
|
816
|
+
resolved_schema = ident.schema or default_schema
|
|
817
|
+
else:
|
|
818
|
+
name = getattr(item, "table_name", None) or getattr(item, "name", None)
|
|
819
|
+
tbl_schema = getattr(item, "schema_name", None) or default_schema
|
|
820
|
+
resolved_name = str(name) if name else None
|
|
821
|
+
resolved_schema = str(tbl_schema) if tbl_schema else default_schema
|
|
822
|
+
if (
|
|
823
|
+
resolved_schema
|
|
824
|
+
and resolved_schema.lower() == "main"
|
|
825
|
+
and default_schema is None
|
|
826
|
+
and _sqlglot_dialect(type(self).dialect) in {"sqlite", "duckdb"}
|
|
827
|
+
):
|
|
828
|
+
resolved_schema = None
|
|
829
|
+
return (resolved_name, resolved_schema)
|
|
830
|
+
|
|
831
|
+
def _resolve_schema_ddl_input(self, driver: Any, schema: str | None) -> tuple[str | None, str | None]:
|
|
832
|
+
"""Resolve caller-supplied ``schema`` into ``(exact_catalog_schema, getter_schema_arg)``."""
|
|
833
|
+
if schema is None:
|
|
834
|
+
return (None, None)
|
|
835
|
+
if _ddl_dialect_or_none(type(self).dialect) is not None and isinstance(self, DataDictionaryDialectMixin):
|
|
836
|
+
with contextlib.suppress(ValueError):
|
|
837
|
+
_, exact_schema = type(self).resolve_ddl_object_name(self, driver, "_", schema)
|
|
838
|
+
getter_schema = (
|
|
839
|
+
type(self).exact_catalog_identifier(self, driver, exact_schema)
|
|
840
|
+
if exact_schema is not None
|
|
841
|
+
else None
|
|
842
|
+
)
|
|
843
|
+
return (exact_schema, getter_schema)
|
|
844
|
+
stripped = schema.strip()
|
|
845
|
+
if len(stripped) >= _MIN_QUOTED_IDENTIFIER_LEN and (
|
|
846
|
+
(stripped[0] == stripped[-1] and stripped[0] in {'"', "`"}) or (stripped[0] == "[" and stripped[-1] == "]")
|
|
847
|
+
):
|
|
848
|
+
return (stripped[1:-1], schema)
|
|
849
|
+
return (stripped, schema)
|
|
850
|
+
|
|
851
|
+
def _build_view_ddl_from_row(
|
|
852
|
+
self, row: Any, *, default_schema: str | None = None, dialect: str | None = None
|
|
853
|
+
) -> "DDLResult | None":
|
|
854
|
+
"""Build a view DDLResult from a view metadata row when a definition is present.
|
|
855
|
+
|
|
856
|
+
Full ``CREATE`` statements from the catalog are kept verbatim. Body-only definitions are
|
|
857
|
+
wrapped in ``CREATE VIEW`` with a quoted view name. The result identity carries the
|
|
858
|
+
source ``dialect`` so a later transpile step can convert it to a target dialect.
|
|
859
|
+
"""
|
|
860
|
+
attrs: Mapping[str, Any]
|
|
861
|
+
ident = getattr(row, "identity", None)
|
|
862
|
+
raw_attrs = getattr(row, "attributes", None)
|
|
863
|
+
if isinstance(row, Mapping):
|
|
864
|
+
attrs = row
|
|
865
|
+
view_name_raw = (
|
|
866
|
+
attrs.get("view_name") or attrs.get("table_name") or attrs.get("object_name") or attrs.get("name")
|
|
867
|
+
)
|
|
868
|
+
view_schema_raw = attrs.get("schema_name") or attrs.get("table_schema") or default_schema
|
|
869
|
+
elif isinstance(ident, ObjectIdentity) and isinstance(raw_attrs, Mapping):
|
|
870
|
+
attrs = raw_attrs
|
|
871
|
+
view_name_raw = ident.name
|
|
872
|
+
view_schema_raw = ident.schema or default_schema
|
|
873
|
+
else:
|
|
874
|
+
return None
|
|
875
|
+
|
|
876
|
+
if not view_name_raw:
|
|
877
|
+
return None
|
|
878
|
+
view_name = str(view_name_raw)
|
|
879
|
+
view_schema = str(view_schema_raw) if view_schema_raw else default_schema
|
|
880
|
+
definition_raw = (
|
|
881
|
+
attrs.get("ddl")
|
|
882
|
+
or attrs.get("view_definition")
|
|
883
|
+
or attrs.get("definition")
|
|
884
|
+
or attrs.get("text")
|
|
885
|
+
or attrs.get("native_sql")
|
|
886
|
+
)
|
|
887
|
+
if not definition_raw or not str(definition_raw).strip():
|
|
888
|
+
return None
|
|
889
|
+
|
|
890
|
+
definition_text = str(definition_raw).strip().rstrip(";").strip()
|
|
891
|
+
is_native_statement = definition_text.upper().startswith("CREATE")
|
|
892
|
+
if is_native_statement:
|
|
893
|
+
ddl_text = f"{definition_text};"
|
|
894
|
+
else:
|
|
895
|
+
quoted_view = self._quoted_table(view_name, view_schema).sql(dialect=_sqlglot_dialect(dialect), copy=False)
|
|
896
|
+
ddl_text = f"CREATE VIEW {quoted_view} AS {definition_text};"
|
|
897
|
+
source = MetadataSource.CATALOG if is_native_statement else MetadataSource.GENERATED
|
|
898
|
+
return DDLResult(
|
|
899
|
+
identity=ObjectIdentity(
|
|
900
|
+
name=view_name, object_type="view", schema=view_schema, dialect=dialect, source=source
|
|
901
|
+
),
|
|
902
|
+
status=MetadataSupport.SUPPORTED,
|
|
903
|
+
fidelity=MetadataFidelity.NATIVE if is_native_statement else MetadataFidelity.GENERATED,
|
|
904
|
+
source=source,
|
|
905
|
+
ddl=ddl_text,
|
|
906
|
+
)
|
|
907
|
+
|
|
908
|
+
def _build_sequence_ddl_from_row(
|
|
909
|
+
self, row: Any, *, default_schema: str | None = None, dialect: str | None = None
|
|
910
|
+
) -> "DDLResult | None":
|
|
911
|
+
"""Build a ``CREATE SEQUENCE`` DDLResult from a sequence metadata row.
|
|
912
|
+
|
|
913
|
+
The sequence name is quoted and options are rendered through SQLGlot for ``dialect``.
|
|
914
|
+
Sequences owned by identity columns or extensions are skipped because their owner
|
|
915
|
+
recreates them. Dialects whose sequence options cannot be rebuilt from catalog rows
|
|
916
|
+
return an explicit unsupported result.
|
|
917
|
+
"""
|
|
918
|
+
attrs: Mapping[str, Any]
|
|
919
|
+
ident = getattr(row, "identity", None)
|
|
920
|
+
raw_attrs = getattr(row, "attributes", None)
|
|
921
|
+
if isinstance(row, Mapping):
|
|
922
|
+
attrs = row
|
|
923
|
+
name_raw = attrs.get("sequence_name") or attrs.get("object_name") or attrs.get("name")
|
|
924
|
+
schema_raw = attrs.get("schema_name") or attrs.get("sequence_schema") or default_schema
|
|
925
|
+
elif isinstance(ident, ObjectIdentity) and isinstance(raw_attrs, Mapping):
|
|
926
|
+
attrs = raw_attrs
|
|
927
|
+
name_raw = ident.name
|
|
928
|
+
schema_raw = ident.schema or default_schema
|
|
929
|
+
else:
|
|
930
|
+
return None
|
|
931
|
+
if not name_raw or attrs.get("is_identity_owned") or attrs.get("is_extension_owned"):
|
|
932
|
+
return None
|
|
933
|
+
identity = ObjectIdentity(
|
|
934
|
+
name=str(name_raw),
|
|
935
|
+
object_type="sequence",
|
|
936
|
+
schema=str(schema_raw) if schema_raw else None,
|
|
937
|
+
dialect=dialect,
|
|
938
|
+
source=MetadataSource.GENERATED,
|
|
939
|
+
)
|
|
940
|
+
if dialect in _SEQUENCE_SYNTHESIS_UNSUPPORTED_DIALECTS:
|
|
941
|
+
return DDLResult.unsupported(
|
|
942
|
+
identity,
|
|
943
|
+
source=MetadataSource.GENERATED,
|
|
944
|
+
warnings=(f"{dialect} sequence options cannot be rebuilt from catalog rows",),
|
|
945
|
+
)
|
|
946
|
+
properties: dict[str, Any] = {}
|
|
947
|
+
for prop_name, keys in _SEQUENCE_NUMERIC_PROPERTIES:
|
|
948
|
+
value = next((attrs.get(key) for key in keys if attrs.get(key) is not None), None)
|
|
949
|
+
if value is not None:
|
|
950
|
+
properties[prop_name] = exp.Literal.number(str(value))
|
|
951
|
+
cycle_raw = next(
|
|
952
|
+
(attrs.get(key) for key in ("cycle", "cycles", "cycle_option") if attrs.get(key) is not None), None
|
|
953
|
+
)
|
|
954
|
+
cycles = str(cycle_raw).strip().upper() in {"TRUE", "YES", "1", "Y"} if cycle_raw is not None else False
|
|
955
|
+
properties["options"] = [exp.var("CYCLE" if cycles else "NO CYCLE")]
|
|
956
|
+
create_expr = exp.Create(
|
|
957
|
+
this=self._quoted_table(identity.name, identity.schema),
|
|
958
|
+
kind="SEQUENCE",
|
|
959
|
+
properties=exp.Properties(expressions=[exp.SequenceProperties(**properties)]),
|
|
960
|
+
)
|
|
961
|
+
return DDLResult(
|
|
962
|
+
identity=identity,
|
|
963
|
+
status=MetadataSupport.SUPPORTED,
|
|
964
|
+
fidelity=MetadataFidelity.GENERATED,
|
|
965
|
+
source=MetadataSource.GENERATED,
|
|
966
|
+
ddl=f"{create_expr.sql(dialect=_sqlglot_dialect(dialect), copy=False)};",
|
|
967
|
+
)
|
|
968
|
+
|
|
969
|
+
def _build_type_ddl_from_row(
|
|
970
|
+
self, row: Any, *, default_schema: str | None = None, dialect: str | None = None
|
|
971
|
+
) -> "DDLResult | None":
|
|
972
|
+
"""Build a ``CREATE TYPE ... AS ENUM`` DDLResult from a user-defined type row.
|
|
973
|
+
|
|
974
|
+
Only enum types can be rebuilt from catalog rows; other kinds return an explicit
|
|
975
|
+
unsupported result with a warning.
|
|
976
|
+
"""
|
|
977
|
+
if not isinstance(row, Mapping):
|
|
978
|
+
return None
|
|
979
|
+
name_raw = row.get("type_name") or row.get("name")
|
|
980
|
+
if not name_raw:
|
|
981
|
+
return None
|
|
982
|
+
schema_raw = row.get("schema_name") or default_schema
|
|
983
|
+
identity = ObjectIdentity(
|
|
984
|
+
name=str(name_raw),
|
|
985
|
+
object_type="type",
|
|
986
|
+
schema=str(schema_raw) if schema_raw else None,
|
|
987
|
+
dialect=dialect,
|
|
988
|
+
source=MetadataSource.GENERATED,
|
|
989
|
+
)
|
|
990
|
+
logical_type = str(row.get("logical_type") or "").strip().upper()
|
|
991
|
+
labels = row.get("labels")
|
|
992
|
+
if logical_type != "ENUM" or labels is None:
|
|
993
|
+
return DDLResult.unsupported(
|
|
994
|
+
identity,
|
|
995
|
+
source=MetadataSource.GENERATED,
|
|
996
|
+
warnings=(f"{logical_type or 'unknown'} type {identity.name} cannot be rebuilt from catalog rows",),
|
|
997
|
+
)
|
|
998
|
+
render_dialect = _sqlglot_dialect(dialect)
|
|
999
|
+
quoted_type = self._quoted_table(identity.name, identity.schema).sql(dialect=render_dialect, copy=False)
|
|
1000
|
+
rendered_labels = ", ".join(
|
|
1001
|
+
exp.Literal.string(str(label)).sql(dialect=render_dialect, copy=False) for label in labels
|
|
1002
|
+
)
|
|
1003
|
+
return DDLResult(
|
|
1004
|
+
identity=identity,
|
|
1005
|
+
status=MetadataSupport.SUPPORTED,
|
|
1006
|
+
fidelity=MetadataFidelity.GENERATED,
|
|
1007
|
+
source=MetadataSource.GENERATED,
|
|
1008
|
+
ddl=f"CREATE TYPE {quoted_type} AS ENUM ({rendered_labels});",
|
|
1009
|
+
)
|
|
1010
|
+
|
|
1011
|
+
def _synthesize_table_from_catalog(
|
|
1012
|
+
self,
|
|
1013
|
+
table_name: str,
|
|
1014
|
+
schema: str | None,
|
|
1015
|
+
catalog: "Mapping[str, Mapping[str, abc.Sequence[Any]]]",
|
|
1016
|
+
*,
|
|
1017
|
+
source_dialect: str | None,
|
|
1018
|
+
target_dialect: str | None,
|
|
1019
|
+
warnings: tuple[str, ...] = (),
|
|
1020
|
+
) -> "DDLResult":
|
|
1021
|
+
"""Synthesize one table's DDL from schema-wide catalog rows grouped by table."""
|
|
1022
|
+
columns = catalog.get("columns", {}).get(table_name, ())
|
|
1023
|
+
if not columns:
|
|
1024
|
+
return DDLResult.unsupported(
|
|
1025
|
+
ObjectIdentity(table_name, "table", schema=schema, dialect=type(self).dialect),
|
|
1026
|
+
warnings=(*warnings, f"No catalog columns found for table {table_name}"),
|
|
1027
|
+
)
|
|
1028
|
+
return self.build_synthesized_table_ddl(
|
|
1029
|
+
table_name,
|
|
1030
|
+
columns,
|
|
1031
|
+
schema=schema,
|
|
1032
|
+
constraints=catalog.get("constraints", {}).get(table_name, ()),
|
|
1033
|
+
foreign_keys=catalog.get("foreign_keys", {}).get(table_name, ()),
|
|
1034
|
+
indexes=catalog.get("indexes", {}).get(table_name, ()),
|
|
1035
|
+
target_dialect=target_dialect,
|
|
1036
|
+
source_dialect=source_dialect,
|
|
1037
|
+
warnings=warnings,
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
def _group_rows_by_table(
|
|
1041
|
+
self, rows: "abc.Iterable[Any]", table_names: "abc.Sequence[str]"
|
|
1042
|
+
) -> "dict[str, list[Any]] | None":
|
|
1043
|
+
"""Group schema-wide catalog rows by exact table name.
|
|
1044
|
+
|
|
1045
|
+
Returns None when a row does not name its table, so callers fall back to per-table queries.
|
|
1046
|
+
"""
|
|
1047
|
+
grouped: dict[str, list[Any]] = {name: [] for name in table_names}
|
|
1048
|
+
for row in rows:
|
|
1049
|
+
table_name = row.get("table_name") if isinstance(row, Mapping) else getattr(row, "table_name", None)
|
|
1050
|
+
if not table_name:
|
|
1051
|
+
return None
|
|
1052
|
+
bucket = grouped.get(str(table_name))
|
|
1053
|
+
if bucket is not None:
|
|
1054
|
+
bucket.append(row)
|
|
1055
|
+
return grouped
|
|
1056
|
+
|
|
1057
|
+
def _catalog_object_identity_result(
|
|
1058
|
+
self, name: str, object_type: str, schema: str | None, dialect: str | None
|
|
1059
|
+
) -> "DDLResult":
|
|
1060
|
+
"""Return an identity-only DDLResult used when only the object's existence matters (drop DDL)."""
|
|
1061
|
+
return DDLResult(
|
|
1062
|
+
identity=ObjectIdentity(
|
|
1063
|
+
name, object_type, schema=schema, dialect=dialect or type(self).dialect, source=MetadataSource.CATALOG
|
|
1064
|
+
),
|
|
1065
|
+
status=MetadataSupport.SUPPORTED,
|
|
1066
|
+
fidelity=MetadataFidelity.GENERATED,
|
|
1067
|
+
source=MetadataSource.CATALOG,
|
|
1068
|
+
)
|
|
1069
|
+
|
|
1070
|
+
def _column_reference_text(self, grouped_columns: "Mapping[str, abc.Sequence[Any]]") -> "dict[str, str]":
|
|
1071
|
+
"""Join each table's column types and defaults into text searched for type and sequence references."""
|
|
1072
|
+
texts: dict[str, str] = {}
|
|
1073
|
+
for table_name, columns in grouped_columns.items():
|
|
1074
|
+
parts: list[str] = []
|
|
1075
|
+
for column in columns:
|
|
1076
|
+
if isinstance(column, Mapping):
|
|
1077
|
+
parts.extend(str(column.get(key) or "") for key in ("data_type", "column_default"))
|
|
1078
|
+
texts[table_name] = " ".join(parts)
|
|
1079
|
+
return texts
|
|
1080
|
+
|
|
1081
|
+
def _link_schema_references(
|
|
1082
|
+
self, items: "list[DDLResult]", reference_text: "Mapping[str, str]"
|
|
1083
|
+
) -> "list[DDLResult]":
|
|
1084
|
+
"""Add dependency edges from tables to the types and sequences they reference and from views to relations.
|
|
1085
|
+
|
|
1086
|
+
References are found by whole-identifier search in the table DDL plus ``reference_text``
|
|
1087
|
+
(column types and defaults) and in the view DDL.
|
|
1088
|
+
"""
|
|
1089
|
+
referenced = [item.identity for item in items if item.identity.object_type.lower() in {"sequence", "type"}]
|
|
1090
|
+
relations = [
|
|
1091
|
+
item.identity
|
|
1092
|
+
for item in items
|
|
1093
|
+
if self._is_table_object_type(item.identity.object_type) or "view" in item.identity.object_type.lower()
|
|
1094
|
+
]
|
|
1095
|
+
linked: list[DDLResult] = []
|
|
1096
|
+
for item in items:
|
|
1097
|
+
object_type = item.identity.object_type.lower()
|
|
1098
|
+
if self._is_table_object_type(object_type):
|
|
1099
|
+
text = f"{item.ddl or ''} {reference_text.get(item.identity.name, '')}"
|
|
1100
|
+
candidates = referenced
|
|
1101
|
+
elif "view" in object_type:
|
|
1102
|
+
text = item.ddl or ""
|
|
1103
|
+
candidates = relations
|
|
1104
|
+
else:
|
|
1105
|
+
linked.append(item)
|
|
1106
|
+
continue
|
|
1107
|
+
edges = tuple(
|
|
1108
|
+
DependencyEdge(
|
|
1109
|
+
item.identity,
|
|
1110
|
+
target,
|
|
1111
|
+
_REFERENCE_EDGE_KINDS.get(target.object_type.lower(), DependencyEdgeKind.VIEW_REFERENCE),
|
|
1112
|
+
source=item.identity.source,
|
|
1113
|
+
)
|
|
1114
|
+
for target in candidates
|
|
1115
|
+
if target != item.identity and self._references_identifier(text, target.name)
|
|
1116
|
+
)
|
|
1117
|
+
linked.append(self._with_dependencies(item, (*item.dependencies, *edges)) if edges else item)
|
|
1118
|
+
return linked
|
|
1119
|
+
|
|
1120
|
+
def _resolve_schema_object_identity(
|
|
1121
|
+
self,
|
|
1122
|
+
lookup: "Mapping[tuple[str, str, str], ObjectIdentity]",
|
|
1123
|
+
object_type: str | None,
|
|
1124
|
+
schema: str | None,
|
|
1125
|
+
name: str | None,
|
|
1126
|
+
) -> "ObjectIdentity | None":
|
|
1127
|
+
"""Resolve an object reference to its canonical ObjectIdentity in the schema DDL graph."""
|
|
1128
|
+
if not name:
|
|
1129
|
+
return None
|
|
1130
|
+
t_key = (object_type or "").strip().lower()
|
|
1131
|
+
s_key = (schema or "").strip().lower()
|
|
1132
|
+
n_key = name.strip().lower()
|
|
1133
|
+
for candidate in ((t_key, s_key, n_key), (t_key, "", n_key), ("", s_key, n_key), ("", "", n_key)):
|
|
1134
|
+
found = lookup.get(candidate)
|
|
1135
|
+
if found is not None:
|
|
1136
|
+
return found
|
|
1137
|
+
return None
|
|
1138
|
+
|
|
1139
|
+
def _extract_fk_endpoints(self, fk: Any) -> tuple[str | None, str | None, str | None, str | None]:
|
|
1140
|
+
"""Extract (table_name, schema, referenced_table, referenced_schema) from a foreign key item."""
|
|
1141
|
+
if isinstance(fk, ForeignKeyMetadata):
|
|
1142
|
+
return (fk.table_name, fk.schema, fk.referenced_table, fk.referenced_schema or fk.schema)
|
|
1143
|
+
if isinstance(fk, Mapping):
|
|
1144
|
+
t_name = fk.get("table_name")
|
|
1145
|
+
s_name = fk.get("schema") or fk.get("schema_name") or fk.get("table_schema")
|
|
1146
|
+
r_table = fk.get("referenced_table") or fk.get("references_table") or fk.get("referenced_table_name")
|
|
1147
|
+
r_schema = fk.get("referenced_schema") or fk.get("references_schema") or s_name
|
|
1148
|
+
return (
|
|
1149
|
+
str(t_name) if t_name else None,
|
|
1150
|
+
str(s_name) if s_name else None,
|
|
1151
|
+
str(r_table) if r_table else None,
|
|
1152
|
+
str(r_schema) if r_schema else None,
|
|
1153
|
+
)
|
|
1154
|
+
return (None, None, None, None)
|
|
1155
|
+
|
|
1156
|
+
def _extract_dependency_endpoints(
|
|
1157
|
+
self, dep: Any
|
|
1158
|
+
) -> tuple[str | None, str | None, str | None, str | None, str | None, str | None]:
|
|
1159
|
+
"""Extract (from_type, from_schema, from_name, to_type, to_schema, to_name) from a dependency item."""
|
|
1160
|
+
ident = getattr(dep, "identity", None)
|
|
1161
|
+
raw_attrs = getattr(dep, "attributes", None)
|
|
1162
|
+
attrs: Mapping[str, Any]
|
|
1163
|
+
if isinstance(dep, Mapping):
|
|
1164
|
+
attrs = dep
|
|
1165
|
+
from_name = (
|
|
1166
|
+
attrs.get("object_name")
|
|
1167
|
+
or attrs.get("dependent_name")
|
|
1168
|
+
or attrs.get("referencing_entity_name")
|
|
1169
|
+
or attrs.get("name")
|
|
1170
|
+
)
|
|
1171
|
+
from_schema = (
|
|
1172
|
+
attrs.get("schema_name") or attrs.get("dependent_schema") or attrs.get("referencing_schema_name")
|
|
1173
|
+
)
|
|
1174
|
+
from_type = attrs.get("object_type") or attrs.get("dependent_type")
|
|
1175
|
+
elif isinstance(ident, ObjectIdentity) and isinstance(raw_attrs, Mapping):
|
|
1176
|
+
attrs = raw_attrs
|
|
1177
|
+
from_name = ident.name
|
|
1178
|
+
from_schema = ident.schema
|
|
1179
|
+
from_type = ident.object_type
|
|
1180
|
+
else:
|
|
1181
|
+
return (None, None, None, None, None, None)
|
|
1182
|
+
|
|
1183
|
+
to_name = (
|
|
1184
|
+
attrs.get("referenced_name")
|
|
1185
|
+
or attrs.get("referenced_object")
|
|
1186
|
+
or attrs.get("referenced_object_name")
|
|
1187
|
+
or attrs.get("referenced_entity_name")
|
|
1188
|
+
or attrs.get("parent_name")
|
|
1189
|
+
)
|
|
1190
|
+
to_schema = (
|
|
1191
|
+
attrs.get("referenced_schema")
|
|
1192
|
+
or attrs.get("referenced_schema_name")
|
|
1193
|
+
or attrs.get("parent_schema")
|
|
1194
|
+
or from_schema
|
|
1195
|
+
)
|
|
1196
|
+
to_type = attrs.get("referenced_type") or attrs.get("referenced_object_type") or attrs.get("parent_type")
|
|
1197
|
+
return (
|
|
1198
|
+
str(from_type) if from_type else None,
|
|
1199
|
+
str(from_schema) if from_schema else None,
|
|
1200
|
+
str(from_name) if from_name else None,
|
|
1201
|
+
str(to_type) if to_type else None,
|
|
1202
|
+
str(to_schema) if to_schema else None,
|
|
1203
|
+
str(to_name) if to_name else None,
|
|
1204
|
+
)
|
|
1205
|
+
|
|
1206
|
+
def _schema_ddl_collect_domains(
|
|
1207
|
+
self, include_domains: "abc.Sequence[str] | None", exclude_domains: "abc.Sequence[str] | None"
|
|
1208
|
+
) -> "set[str]":
|
|
1209
|
+
"""Return the synthesizable schema DDL domains selected by include/exclude filters."""
|
|
1210
|
+
allowed = {"sequences", "tables", "types", "views"}
|
|
1211
|
+
if include_domains is not None:
|
|
1212
|
+
allowed &= self._normalize_schema_ddl_domains(include_domains)
|
|
1213
|
+
if exclude_domains is not None:
|
|
1214
|
+
allowed -= self._normalize_schema_ddl_domains(exclude_domains)
|
|
1215
|
+
return allowed
|
|
1216
|
+
|
|
1217
|
+
def _replace_synthesized_table_dependents(
|
|
1218
|
+
self, items: "abc.Sequence[DDLResult]", replaced_tables: "set[tuple[str, str]]"
|
|
1219
|
+
) -> "list[DDLResult]":
|
|
1220
|
+
"""Drop native index items whose parent table was replaced by synthesized DDL.
|
|
1221
|
+
|
|
1222
|
+
Synthesized table DDL already includes the table's indexes, so the native index
|
|
1223
|
+
statements for that table would be duplicates.
|
|
1224
|
+
"""
|
|
1225
|
+
kept: list[DDLResult] = []
|
|
1226
|
+
for item in items:
|
|
1227
|
+
parent = item.context.get(DDL_PARENT_TABLE_CONTEXT_KEY)
|
|
1228
|
+
if (
|
|
1229
|
+
item.identity.object_type.lower() == "index"
|
|
1230
|
+
and parent is not None
|
|
1231
|
+
and ((item.identity.schema or "").lower(), str(parent).lower()) in replaced_tables
|
|
1232
|
+
):
|
|
1233
|
+
continue
|
|
1234
|
+
kept.append(item)
|
|
1235
|
+
return kept
|
|
1236
|
+
|
|
1237
|
+
def _finalize_schema_ddl_results(
|
|
1238
|
+
self,
|
|
1239
|
+
ddl_results: "abc.Sequence[DDLResult]",
|
|
1240
|
+
*,
|
|
1241
|
+
foreign_keys: "abc.Sequence[Any] | None" = None,
|
|
1242
|
+
dependency_items: "abc.Sequence[Any] | None" = None,
|
|
1243
|
+
include_domains: "abc.Sequence[str] | None" = None,
|
|
1244
|
+
exclude_domains: "abc.Sequence[str] | None" = None,
|
|
1245
|
+
exclude_tables: "abc.Sequence[str] | None" = (),
|
|
1246
|
+
direction: "Literal['create', 'drop']" = "create",
|
|
1247
|
+
target_dialect: str | None = None,
|
|
1248
|
+
warnings: tuple[str, ...] = (),
|
|
1249
|
+
) -> "MetadataResult":
|
|
1250
|
+
"""Filter, attach dependency edges, topologically sort, and wrap schema DDL results.
|
|
1251
|
+
|
|
1252
|
+
``exclude_tables`` entries are compared as bare, unquoted, case-insensitive names with any
|
|
1253
|
+
schema qualification stripped; indexes and triggers of excluded tables are excluded too.
|
|
1254
|
+
Objects without usable CREATE DDL are reported in the result warnings instead of being
|
|
1255
|
+
dropped silently; drop direction needs only object identities, so every collected object is
|
|
1256
|
+
kept. For ``direction="drop"`` each object is converted into ``DROP ... IF EXISTS``
|
|
1257
|
+
in reverse dependency order; indexes and triggers are omitted because dropping their
|
|
1258
|
+
table removes them. Table-to-table ordering comes from ``foreign_keys``; catalog dependency
|
|
1259
|
+
rows whose dependent is a table are ignored because engines such as DuckDB record foreign
|
|
1260
|
+
keys there in the opposite direction.
|
|
1261
|
+
"""
|
|
1262
|
+
excluded_names = self._normalize_excluded_table_names(exclude_tables)
|
|
1263
|
+
included = self._normalize_schema_ddl_domains(include_domains) if include_domains is not None else None
|
|
1264
|
+
excluded_domains = self._normalize_schema_ddl_domains(exclude_domains) if exclude_domains is not None else set()
|
|
1265
|
+
result_warnings: list[str] = list(warnings)
|
|
1266
|
+
filtered: list[DDLResult] = []
|
|
1267
|
+
for item in ddl_results:
|
|
1268
|
+
object_type = item.identity.object_type.lower()
|
|
1269
|
+
domain = _SCHEMA_DDL_OBJECT_DOMAINS.get(object_type, f"{object_type}s")
|
|
1270
|
+
if (included is not None and domain not in included) or domain in excluded_domains:
|
|
1271
|
+
continue
|
|
1272
|
+
if self._is_excluded_schema_object(item, excluded_names):
|
|
1273
|
+
continue
|
|
1274
|
+
candidate = item
|
|
1275
|
+
if direction == "create":
|
|
1276
|
+
if candidate.status == MetadataSupport.SUPPORTED and candidate.ddl:
|
|
1277
|
+
candidate = self._transpile_ddl_result(candidate, target_dialect=target_dialect)
|
|
1278
|
+
if candidate.status != MetadataSupport.SUPPORTED or not candidate.ddl:
|
|
1279
|
+
result_warnings.append(self._skipped_schema_object_warning(candidate))
|
|
1280
|
+
continue
|
|
1281
|
+
filtered.append(candidate)
|
|
1282
|
+
|
|
1283
|
+
identity_lookup: dict[tuple[str, str, str], ObjectIdentity] = {}
|
|
1284
|
+
for item in filtered:
|
|
1285
|
+
ident = item.identity
|
|
1286
|
+
t_key = ident.object_type.lower()
|
|
1287
|
+
s_key = (ident.schema or "").lower()
|
|
1288
|
+
n_key = ident.name.lower()
|
|
1289
|
+
identity_lookup[t_key, s_key, n_key] = ident
|
|
1290
|
+
identity_lookup.setdefault((t_key, "", n_key), ident)
|
|
1291
|
+
identity_lookup.setdefault(("", s_key, n_key), ident)
|
|
1292
|
+
identity_lookup.setdefault(("", "", n_key), ident)
|
|
1293
|
+
|
|
1294
|
+
edges_by_source: dict[ObjectIdentity, list[DependencyEdge]] = {}
|
|
1295
|
+
for item in filtered:
|
|
1296
|
+
edges_by_source.setdefault(item.identity, [])
|
|
1297
|
+
for edge in item.dependencies:
|
|
1298
|
+
target_ident = self._resolve_schema_object_identity(
|
|
1299
|
+
identity_lookup, edge.to_object.object_type, edge.to_object.schema, edge.to_object.name
|
|
1300
|
+
)
|
|
1301
|
+
if target_ident is not None and target_ident != item.identity:
|
|
1302
|
+
edges_by_source[item.identity].append(
|
|
1303
|
+
DependencyEdge(
|
|
1304
|
+
item.identity,
|
|
1305
|
+
target_ident,
|
|
1306
|
+
edge.kind,
|
|
1307
|
+
strength=edge.strength,
|
|
1308
|
+
confidence=edge.confidence,
|
|
1309
|
+
source=item.identity.source,
|
|
1310
|
+
)
|
|
1311
|
+
)
|
|
1312
|
+
|
|
1313
|
+
for fk in foreign_keys or ():
|
|
1314
|
+
fk_table, fk_schema, ref_table, ref_schema = self._extract_fk_endpoints(fk)
|
|
1315
|
+
if not fk_table or not ref_table:
|
|
1316
|
+
continue
|
|
1317
|
+
from_ident = self._resolve_schema_object_identity(identity_lookup, "table", fk_schema, fk_table)
|
|
1318
|
+
to_ident = self._resolve_schema_object_identity(
|
|
1319
|
+
identity_lookup, "table", ref_schema or fk_schema, ref_table
|
|
1320
|
+
)
|
|
1321
|
+
if from_ident is not None and to_ident is not None and from_ident != to_ident:
|
|
1322
|
+
edges_by_source.setdefault(from_ident, []).append(
|
|
1323
|
+
DependencyEdge(
|
|
1324
|
+
from_ident,
|
|
1325
|
+
to_ident,
|
|
1326
|
+
DependencyEdgeKind.FOREIGN_KEY,
|
|
1327
|
+
strength=DependencyStrength.HARD,
|
|
1328
|
+
source=from_ident.source,
|
|
1329
|
+
)
|
|
1330
|
+
)
|
|
1331
|
+
|
|
1332
|
+
for dep in dependency_items or ():
|
|
1333
|
+
from_type, from_schema, from_name, to_type, to_schema, to_name = self._extract_dependency_endpoints(dep)
|
|
1334
|
+
if not from_name or not to_name:
|
|
1335
|
+
continue
|
|
1336
|
+
from_ident = self._resolve_schema_object_identity(identity_lookup, from_type, from_schema, from_name)
|
|
1337
|
+
to_ident = self._resolve_schema_object_identity(identity_lookup, to_type, to_schema or from_schema, to_name)
|
|
1338
|
+
if (
|
|
1339
|
+
from_ident is not None
|
|
1340
|
+
and to_ident is not None
|
|
1341
|
+
and from_ident != to_ident
|
|
1342
|
+
and not self._is_table_object_type(from_ident.object_type)
|
|
1343
|
+
):
|
|
1344
|
+
edge_kind = (
|
|
1345
|
+
DependencyEdgeKind.MATERIALIZED_VIEW
|
|
1346
|
+
if from_ident.object_type.lower() == "materialized_view"
|
|
1347
|
+
else DependencyEdgeKind.VIEW_REFERENCE
|
|
1348
|
+
if "view" in from_ident.object_type.lower()
|
|
1349
|
+
else DependencyEdgeKind.ROUTINE_REFERENCE
|
|
1350
|
+
)
|
|
1351
|
+
edges_by_source.setdefault(from_ident, []).append(
|
|
1352
|
+
DependencyEdge(
|
|
1353
|
+
from_ident, to_ident, edge_kind, strength=DependencyStrength.HARD, source=from_ident.source
|
|
1354
|
+
)
|
|
1355
|
+
)
|
|
1356
|
+
|
|
1357
|
+
enriched: list[DDLResult] = [
|
|
1358
|
+
DDLResult(
|
|
1359
|
+
identity=item.identity,
|
|
1360
|
+
status=item.status,
|
|
1361
|
+
fidelity=item.fidelity,
|
|
1362
|
+
source=item.source,
|
|
1363
|
+
ddl=item.ddl,
|
|
1364
|
+
dependencies=tuple(edges_by_source.get(item.identity, ())),
|
|
1365
|
+
redactions=item.redactions,
|
|
1366
|
+
context=item.context,
|
|
1367
|
+
warnings=item.warnings,
|
|
1368
|
+
)
|
|
1369
|
+
for item in filtered
|
|
1370
|
+
]
|
|
1371
|
+
|
|
1372
|
+
sort_input = list(reversed(enriched)) if direction == "drop" else enriched
|
|
1373
|
+
sorted_results: tuple[DDLResult, ...] = sort_ddl_results(sort_input, order=direction, raise_on_cycles=False)
|
|
1374
|
+
if direction == "drop":
|
|
1375
|
+
drop_results: list[DDLResult] = []
|
|
1376
|
+
for item in sorted_results:
|
|
1377
|
+
if item.identity.object_type.lower() in _TABLE_DEPENDENT_OBJECT_TYPES:
|
|
1378
|
+
continue
|
|
1379
|
+
drop_result = self._build_drop_ddl_result(item, target_dialect=target_dialect)
|
|
1380
|
+
if drop_result.status != MetadataSupport.SUPPORTED:
|
|
1381
|
+
result_warnings.append(self._skipped_schema_object_warning(drop_result))
|
|
1382
|
+
continue
|
|
1383
|
+
drop_results.append(drop_result)
|
|
1384
|
+
sorted_results = tuple(drop_results)
|
|
1385
|
+
|
|
1386
|
+
for item in sorted_results:
|
|
1387
|
+
result_warnings.extend(item.warnings)
|
|
1388
|
+
unique_warnings = tuple(dict.fromkeys(result_warnings))
|
|
1389
|
+
fidelities = {item.fidelity for item in sorted_results}
|
|
1390
|
+
sources = {item.source for item in sorted_results}
|
|
1391
|
+
capability = MetadataCapability(
|
|
1392
|
+
domain="ddl",
|
|
1393
|
+
support=MetadataSupport.SUPPORTED,
|
|
1394
|
+
fidelity=MetadataFidelity.NATIVE if fidelities == {MetadataFidelity.NATIVE} else MetadataFidelity.GENERATED,
|
|
1395
|
+
source=next(iter(sources)) if len(sources) == 1 else MetadataSource.GENERATED,
|
|
1396
|
+
warnings=unique_warnings,
|
|
1397
|
+
)
|
|
1398
|
+
return MetadataResult("ddl", capability=capability, items=sorted_results, warnings=unique_warnings)
|
|
1399
|
+
|
|
1400
|
+
def _is_table_object_type(self, object_type: str) -> bool:
|
|
1401
|
+
"""Return True when ``object_type`` names a table."""
|
|
1402
|
+
return object_type.lower() in _TABLE_OBJECT_TYPES
|
|
1403
|
+
|
|
1404
|
+
def _uncollected_domain_warning(self, domain: str, dialect: str | None) -> str:
|
|
1405
|
+
"""Describe a schema DDL domain the data dictionary cannot collect."""
|
|
1406
|
+
return f"{dialect or 'generic'} data dictionary does not expose {domain}; {domain} were omitted from schema DDL"
|
|
1407
|
+
|
|
1408
|
+
def _with_dependencies(self, result: "DDLResult", dependencies: "tuple[DependencyEdge, ...]") -> "DDLResult":
|
|
1409
|
+
"""Return ``result`` with ``dependencies`` re-anchored on its own identity."""
|
|
1410
|
+
if not dependencies:
|
|
1411
|
+
return result
|
|
1412
|
+
return DDLResult(
|
|
1413
|
+
identity=result.identity,
|
|
1414
|
+
status=result.status,
|
|
1415
|
+
fidelity=result.fidelity,
|
|
1416
|
+
source=result.source,
|
|
1417
|
+
ddl=result.ddl,
|
|
1418
|
+
dependencies=tuple(
|
|
1419
|
+
DependencyEdge(
|
|
1420
|
+
result.identity,
|
|
1421
|
+
edge.to_object,
|
|
1422
|
+
edge.kind,
|
|
1423
|
+
strength=edge.strength,
|
|
1424
|
+
confidence=edge.confidence,
|
|
1425
|
+
source=edge.source,
|
|
1426
|
+
)
|
|
1427
|
+
for edge in dependencies
|
|
1428
|
+
),
|
|
1429
|
+
redactions=result.redactions,
|
|
1430
|
+
context=result.context,
|
|
1431
|
+
warnings=result.warnings,
|
|
1432
|
+
)
|
|
1433
|
+
|
|
1434
|
+
def _is_excluded_schema_object(self, item: "DDLResult", excluded_names: "set[str]") -> bool:
|
|
1435
|
+
"""Return True when the object or its parent table matches an excluded table name."""
|
|
1436
|
+
if not excluded_names:
|
|
1437
|
+
return False
|
|
1438
|
+
if item.identity.object_type.lower() in _TABLE_OBJECT_TYPES and item.identity.name.lower() in excluded_names:
|
|
1439
|
+
return True
|
|
1440
|
+
parent = item.context.get(DDL_PARENT_TABLE_CONTEXT_KEY)
|
|
1441
|
+
return parent is not None and str(parent).lower() in excluded_names
|
|
1442
|
+
|
|
1443
|
+
def _skipped_schema_object_warning(self, item: "DDLResult") -> str:
|
|
1444
|
+
"""Describe a schema object omitted from schema DDL output."""
|
|
1445
|
+
qualified = f"{item.identity.schema}.{item.identity.name}" if item.identity.schema else item.identity.name
|
|
1446
|
+
reason = "; ".join(item.warnings) if item.warnings else "no DDL is available"
|
|
1447
|
+
return f"Omitted {item.identity.object_type} {qualified} from schema DDL: {reason}"
|
|
1448
|
+
|
|
1449
|
+
def _build_table_profile_sql(self, table: str, columns: "abc.Sequence[Any]", schema: str | None = None) -> SQL:
|
|
1450
|
+
"""Build a single-pass aggregate query for column profile statistics.
|
|
1451
|
+
|
|
1452
|
+
Table, schema, and column identifiers are exact catalog names and are always quoted.
|
|
1453
|
+
"""
|
|
1454
|
+
effective_dialect = _ddl_dialect_or_none(type(self).dialect)
|
|
1455
|
+
sqlglot_dialect = _sqlglot_dialect(effective_dialect)
|
|
1456
|
+
cast_target = _profile_text_cast_type(sqlglot_dialect)
|
|
1457
|
+
projections: list[exp.Expr] = [
|
|
1458
|
+
exp.Alias(this=exp.Count(this=exp.Star()), alias=exp.to_identifier("__row_count"))
|
|
1459
|
+
]
|
|
1460
|
+
for idx, col_item in enumerate(columns):
|
|
1461
|
+
col_name = (
|
|
1462
|
+
str(col_item.get("column_name") or col_item.get("name") or "")
|
|
1463
|
+
if isinstance(col_item, Mapping)
|
|
1464
|
+
else str(getattr(col_item, "column_name", None) or getattr(col_item, "name", None) or "")
|
|
1465
|
+
)
|
|
1466
|
+
if not col_name:
|
|
1467
|
+
continue
|
|
1468
|
+
col_type = (
|
|
1469
|
+
str(col_item.get("data_type") or col_item.get("type") or "")
|
|
1470
|
+
if isinstance(col_item, Mapping)
|
|
1471
|
+
else str(getattr(col_item, "data_type", None) or getattr(col_item, "type", None) or "")
|
|
1472
|
+
)
|
|
1473
|
+
col_expr = exp.column(col_name, quoted=True)
|
|
1474
|
+
if _is_non_comparable_profile_type(col_type, sqlglot_dialect):
|
|
1475
|
+
projections.extend((
|
|
1476
|
+
exp.Alias(this=exp.Count(this=col_expr.copy()), alias=exp.to_identifier(f"__non_null_{idx}")),
|
|
1477
|
+
exp.Alias(
|
|
1478
|
+
this=exp.Cast(this=exp.Null(), to=exp.DataType.build("BIGINT")),
|
|
1479
|
+
alias=exp.to_identifier(f"__distinct_{idx}"),
|
|
1480
|
+
),
|
|
1481
|
+
exp.Alias(
|
|
1482
|
+
this=exp.Cast(this=exp.Null(), to=exp.DataType.build("BIGINT")),
|
|
1483
|
+
alias=exp.to_identifier(f"__max_len_{idx}"),
|
|
1484
|
+
),
|
|
1485
|
+
))
|
|
1486
|
+
else:
|
|
1487
|
+
projections.extend((
|
|
1488
|
+
exp.Alias(this=exp.Count(this=col_expr.copy()), alias=exp.to_identifier(f"__non_null_{idx}")),
|
|
1489
|
+
exp.Alias(
|
|
1490
|
+
this=exp.Count(this=exp.Distinct(expressions=[col_expr.copy()])),
|
|
1491
|
+
alias=exp.to_identifier(f"__distinct_{idx}"),
|
|
1492
|
+
),
|
|
1493
|
+
exp.Alias(
|
|
1494
|
+
this=exp.Max(
|
|
1495
|
+
this=exp.Length(
|
|
1496
|
+
this=exp.Cast(
|
|
1497
|
+
this=col_expr.copy(), to=exp.DataType.build(cast_target, dialect=sqlglot_dialect)
|
|
1498
|
+
)
|
|
1499
|
+
)
|
|
1500
|
+
),
|
|
1501
|
+
alias=exp.to_identifier(f"__max_len_{idx}"),
|
|
1502
|
+
),
|
|
1503
|
+
))
|
|
1504
|
+
|
|
1505
|
+
select_expr = exp.select(*projections, copy=False).from_(self._quoted_table(table, schema), copy=False)
|
|
1506
|
+
return SQL(select_expr.sql(dialect=sqlglot_dialect, copy=False))
|
|
1507
|
+
|
|
1508
|
+
def _build_table_sample_sql(self, table: str, schema: str | None = None, sample_size: int = 1000) -> SQL:
|
|
1509
|
+
"""Build a query sampling rows from a table, quoting the exact catalog identifiers."""
|
|
1510
|
+
effective_dialect = _ddl_dialect_or_none(type(self).dialect)
|
|
1511
|
+
select_expr = (
|
|
1512
|
+
exp
|
|
1513
|
+
.select(exp.Star(), copy=False)
|
|
1514
|
+
.from_(self._quoted_table(table, schema), copy=False)
|
|
1515
|
+
.limit(max(1, sample_size), copy=False)
|
|
1516
|
+
)
|
|
1517
|
+
return SQL(select_expr.sql(dialect=_sqlglot_dialect(effective_dialect), copy=False))
|
|
1518
|
+
|
|
1519
|
+
def _infer_column_type_from_sample(
|
|
1520
|
+
self, declared_type: str, values: "abc.Sequence[Any]", *, target_dialect: str | None = None
|
|
1521
|
+
) -> str:
|
|
1522
|
+
"""Infer a refined SQL column type from declared catalog type and sampled non-null values."""
|
|
1523
|
+
effective_dialect = target_dialect or type(self).dialect
|
|
1524
|
+
config = None
|
|
1525
|
+
if _ddl_dialect_or_none(effective_dialect) is not None:
|
|
1526
|
+
with contextlib.suppress(ValueError):
|
|
1527
|
+
config = get_dialect_config(effective_dialect)
|
|
1528
|
+
|
|
1529
|
+
clean_declared = declared_type.strip()
|
|
1530
|
+
base_declared = clean_declared.split("(", 1)[0].strip().upper()
|
|
1531
|
+
if base_declared not in _LOOSE_PROFILE_TYPES:
|
|
1532
|
+
if target_dialect and target_dialect != type(self).dialect:
|
|
1533
|
+
src_dialect = _ddl_dialect_or_none(type(self).dialect)
|
|
1534
|
+
with contextlib.suppress(SqlglotError):
|
|
1535
|
+
return exp.DataType.build(clean_declared, dialect=_sqlglot_dialect(src_dialect), copy=False).sql(
|
|
1536
|
+
dialect=_sqlglot_dialect(target_dialect), copy=False
|
|
1537
|
+
)
|
|
1538
|
+
return clean_declared or "TEXT"
|
|
1539
|
+
|
|
1540
|
+
non_empty = [val for val in values if val is not None and (not isinstance(val, str) or val.strip() != "")]
|
|
1541
|
+
if not non_empty:
|
|
1542
|
+
if clean_declared and (target_dialect is None or target_dialect == type(self).dialect):
|
|
1543
|
+
return clean_declared
|
|
1544
|
+
if config is not None:
|
|
1545
|
+
return config.get_optimal_type("text")
|
|
1546
|
+
return clean_declared or "TEXT"
|
|
1547
|
+
|
|
1548
|
+
if all(
|
|
1549
|
+
isinstance(val, bool) or (isinstance(val, str) and val.strip().lower() in {"true", "false"})
|
|
1550
|
+
for val in non_empty
|
|
1551
|
+
):
|
|
1552
|
+
return config.get_optimal_type("boolean") if config is not None else "BOOLEAN"
|
|
1553
|
+
|
|
1554
|
+
if all(
|
|
1555
|
+
(isinstance(val, int) and not isinstance(val, bool))
|
|
1556
|
+
or (isinstance(val, str) and bool(_PROFILE_INT_RE.match(val.strip())))
|
|
1557
|
+
for val in non_empty
|
|
1558
|
+
):
|
|
1559
|
+
int_vals = [int(val.strip()) if isinstance(val, str) else int(val) for val in non_empty]
|
|
1560
|
+
if all(_INT64_MIN <= item <= _INT64_MAX for item in int_vals):
|
|
1561
|
+
return config.get_optimal_type("bigint") if config is not None else "BIGINT"
|
|
1562
|
+
max_digits = max(len(str(abs(item))) for item in int_vals)
|
|
1563
|
+
if max_digits <= _MAX_NUMERIC_PRECISION:
|
|
1564
|
+
return f"NUMERIC({max(10, max_digits)}, 0)"
|
|
1565
|
+
if config is not None and target_dialect is not None and target_dialect != type(self).dialect:
|
|
1566
|
+
return config.get_optimal_type("text")
|
|
1567
|
+
return clean_declared or (config.get_optimal_type("text") if config is not None else "TEXT")
|
|
1568
|
+
|
|
1569
|
+
if all(_is_valid_profile_decimal(val) for val in non_empty):
|
|
1570
|
+
max_int_digits = 1
|
|
1571
|
+
max_frac_digits = 2
|
|
1572
|
+
for val in non_empty:
|
|
1573
|
+
int_digits, frac_digits = _decimal_digit_counts(val)
|
|
1574
|
+
max_int_digits = max(max_int_digits, int_digits)
|
|
1575
|
+
max_frac_digits = max(max_frac_digits, frac_digits)
|
|
1576
|
+
if max_int_digits + max_frac_digits <= _MAX_NUMERIC_PRECISION:
|
|
1577
|
+
precision = max(10, min(_MAX_NUMERIC_PRECISION, max_int_digits + max_frac_digits + 2))
|
|
1578
|
+
scale = min(precision - max_int_digits, max(2, max_frac_digits))
|
|
1579
|
+
return f"NUMERIC({precision}, {scale})"
|
|
1580
|
+
|
|
1581
|
+
if all(
|
|
1582
|
+
isinstance(val, UUID) or (isinstance(val, str) and bool(_PROFILE_UUID_RE.match(val.strip())))
|
|
1583
|
+
for val in non_empty
|
|
1584
|
+
):
|
|
1585
|
+
return config.get_optimal_type("uuid") if config is not None else "UUID"
|
|
1586
|
+
|
|
1587
|
+
if all(_is_valid_profile_date(val) for val in non_empty):
|
|
1588
|
+
return "DATE"
|
|
1589
|
+
|
|
1590
|
+
if all(_is_valid_profile_datetime(val) for val in non_empty):
|
|
1591
|
+
return config.get_optimal_type("timestamp") if config is not None else "TIMESTAMP WITH TIME ZONE"
|
|
1592
|
+
|
|
1593
|
+
if all(_is_valid_profile_json(val) for val in non_empty):
|
|
1594
|
+
return config.get_optimal_type("json") if config is not None else "JSON"
|
|
1595
|
+
|
|
1596
|
+
if config is not None and target_dialect is not None and target_dialect != type(self).dialect:
|
|
1597
|
+
return config.get_optimal_type("text")
|
|
1598
|
+
return clean_declared or (config.get_optimal_type("text") if config is not None else "TEXT")
|
|
1599
|
+
|
|
1600
|
+
def _compile_column_profiles(
|
|
1601
|
+
self,
|
|
1602
|
+
columns: "abc.Sequence[Any]",
|
|
1603
|
+
stats_row: "Mapping[str, Any] | None",
|
|
1604
|
+
sample_rows: "abc.Sequence[Mapping[str, Any]]",
|
|
1605
|
+
*,
|
|
1606
|
+
target_dialect: str | None = None,
|
|
1607
|
+
) -> "list[ColumnProfileMetadata]":
|
|
1608
|
+
"""Compile ColumnProfileMetadata items from catalog columns, aggregate stats, and sampled rows."""
|
|
1609
|
+
normalized_stats: dict[str, Any] = {}
|
|
1610
|
+
if stats_row is not None:
|
|
1611
|
+
for k, v in stats_row.items():
|
|
1612
|
+
normalized_stats[str(k).lower()] = v
|
|
1613
|
+
|
|
1614
|
+
row_count_raw = normalized_stats.get("__row_count")
|
|
1615
|
+
row_count = int(row_count_raw) if row_count_raw is not None else len(sample_rows)
|
|
1616
|
+
|
|
1617
|
+
profiles: list[ColumnProfileMetadata] = []
|
|
1618
|
+
for idx, col_item in enumerate(columns):
|
|
1619
|
+
if isinstance(col_item, Mapping):
|
|
1620
|
+
col_name = str(col_item.get("column_name") or col_item.get("name") or "")
|
|
1621
|
+
declared_type = str(col_item.get("data_type") or col_item.get("type") or "TEXT")
|
|
1622
|
+
is_null_raw = col_item.get("is_nullable")
|
|
1623
|
+
else:
|
|
1624
|
+
col_name = str(getattr(col_item, "column_name", None) or getattr(col_item, "name", None) or "")
|
|
1625
|
+
declared_type = str(getattr(col_item, "data_type", None) or getattr(col_item, "type", None) or "TEXT")
|
|
1626
|
+
is_null_raw = getattr(col_item, "is_nullable", None)
|
|
1627
|
+
if not col_name:
|
|
1628
|
+
continue
|
|
1629
|
+
|
|
1630
|
+
declared_nullable = (
|
|
1631
|
+
str(is_null_raw).strip().upper() not in {"NO", "FALSE", "0", "N"} if is_null_raw is not None else True
|
|
1632
|
+
)
|
|
1633
|
+
|
|
1634
|
+
col_samples: list[Any] = []
|
|
1635
|
+
col_lower = col_name.lower()
|
|
1636
|
+
for s_row in sample_rows:
|
|
1637
|
+
if col_name in s_row:
|
|
1638
|
+
col_samples.append(s_row[col_name])
|
|
1639
|
+
else:
|
|
1640
|
+
for k, v in s_row.items():
|
|
1641
|
+
if str(k).lower() == col_lower:
|
|
1642
|
+
col_samples.append(v)
|
|
1643
|
+
break
|
|
1644
|
+
|
|
1645
|
+
non_null_raw = normalized_stats.get(f"__non_null_{idx}")
|
|
1646
|
+
if non_null_raw is not None:
|
|
1647
|
+
non_null_count = int(non_null_raw)
|
|
1648
|
+
else:
|
|
1649
|
+
non_null_count = sum(1 for v in col_samples if v is not None)
|
|
1650
|
+
|
|
1651
|
+
null_count = max(0, row_count - non_null_count)
|
|
1652
|
+
distinct_raw = normalized_stats.get(f"__distinct_{idx}")
|
|
1653
|
+
if distinct_raw is not None:
|
|
1654
|
+
distinct_count = int(distinct_raw)
|
|
1655
|
+
else:
|
|
1656
|
+
distinct_count = len({repr(v) for v in col_samples if v is not None})
|
|
1657
|
+
|
|
1658
|
+
max_len_raw = normalized_stats.get(f"__max_len_{idx}")
|
|
1659
|
+
if max_len_raw is not None:
|
|
1660
|
+
max_char_length: int | None = int(max_len_raw)
|
|
1661
|
+
else:
|
|
1662
|
+
str_lengths = [len(str(v)) for v in col_samples if v is not None]
|
|
1663
|
+
max_char_length = max(str_lengths) if str_lengths else None
|
|
1664
|
+
|
|
1665
|
+
nullable = (null_count > 0) if row_count > 0 else declared_nullable
|
|
1666
|
+
is_unique_candidate = row_count > 0 and null_count == 0 and distinct_count == row_count
|
|
1667
|
+
inferred_type = self._infer_column_type_from_sample(
|
|
1668
|
+
declared_type, col_samples, target_dialect=target_dialect
|
|
1669
|
+
)
|
|
1670
|
+
|
|
1671
|
+
profiles.append(
|
|
1672
|
+
ColumnProfileMetadata(
|
|
1673
|
+
column_name=col_name,
|
|
1674
|
+
declared_type=declared_type,
|
|
1675
|
+
inferred_type=inferred_type,
|
|
1676
|
+
row_count=row_count,
|
|
1677
|
+
null_count=null_count,
|
|
1678
|
+
distinct_count=distinct_count,
|
|
1679
|
+
nullable=nullable,
|
|
1680
|
+
max_char_length=max_char_length,
|
|
1681
|
+
is_unique_candidate=is_unique_candidate,
|
|
1682
|
+
)
|
|
1683
|
+
)
|
|
1684
|
+
|
|
1685
|
+
return profiles
|
|
1686
|
+
|
|
1687
|
+
def _compile_profiled_table_ddl(
|
|
1688
|
+
self,
|
|
1689
|
+
table_name: str,
|
|
1690
|
+
profiles: "abc.Sequence[ColumnProfileMetadata]",
|
|
1691
|
+
*,
|
|
1692
|
+
schema: str | None = None,
|
|
1693
|
+
target_table: str | None = None,
|
|
1694
|
+
target_dialect: str | None = None,
|
|
1695
|
+
primary_key: "str | abc.Sequence[str] | None" = None,
|
|
1696
|
+
) -> "DDLResult":
|
|
1697
|
+
"""Compile a DDLResult from ColumnProfileMetadata items."""
|
|
1698
|
+
pk_cols = (
|
|
1699
|
+
{primary_key.lower()}
|
|
1700
|
+
if isinstance(primary_key, str)
|
|
1701
|
+
else {str(c).lower() for c in (primary_key or ()) if c}
|
|
1702
|
+
)
|
|
1703
|
+
synthesized_columns: list[dict[str, Any]] = []
|
|
1704
|
+
for idx, prof in enumerate(profiles, start=1):
|
|
1705
|
+
is_pk = prof.column_name.lower() in pk_cols
|
|
1706
|
+
synthesized_columns.append({
|
|
1707
|
+
"column_name": prof.column_name,
|
|
1708
|
+
"data_type": prof.inferred_type,
|
|
1709
|
+
"is_nullable": "NO" if (is_pk or not prof.nullable) else "YES",
|
|
1710
|
+
"ordinal_position": idx,
|
|
1711
|
+
"is_primary": is_pk,
|
|
1712
|
+
})
|
|
1713
|
+
|
|
1714
|
+
return compile_table_ddl_results(
|
|
1715
|
+
target_table or table_name,
|
|
1716
|
+
synthesized_columns,
|
|
1717
|
+
schema=schema,
|
|
1718
|
+
dialect=_ddl_dialect_or_none(target_dialect or type(self).dialect),
|
|
1719
|
+
)
|
|
1720
|
+
|
|
1721
|
+
@staticmethod
|
|
1722
|
+
def _references_identifier(sql_text: str, name: str) -> bool:
|
|
1723
|
+
"""Return True when ``name`` appears in ``sql_text`` as a whole identifier."""
|
|
1724
|
+
return re.search(rf"(?<![\w$]){re.escape(name)}(?![\w$])", sql_text, re.IGNORECASE) is not None
|
|
1725
|
+
|
|
1726
|
+
@staticmethod
|
|
1727
|
+
def _normalize_schema_ddl_domains(domains: "abc.Sequence[str]") -> "set[str]":
|
|
1728
|
+
"""Normalize schema DDL domain names, accepting singular object types or plural domains."""
|
|
1729
|
+
normalized: set[str] = set()
|
|
1730
|
+
for domain in domains:
|
|
1731
|
+
key = domain.strip().lower().replace(" ", "_")
|
|
1732
|
+
if key:
|
|
1733
|
+
normalized.add(_SCHEMA_DDL_OBJECT_DOMAINS.get(key, key))
|
|
1734
|
+
return normalized
|
|
1735
|
+
|
|
1736
|
+
@staticmethod
|
|
1737
|
+
def _normalize_excluded_table_names(exclude_tables: "abc.Sequence[str] | None") -> "set[str]":
|
|
1738
|
+
"""Normalize excluded table names to bare, unquoted, lower-case names without schema qualification."""
|
|
1739
|
+
normalized: set[str] = set()
|
|
1740
|
+
for name in exclude_tables or ():
|
|
1741
|
+
parts = split_qualified_identifier(name) if name else ()
|
|
1742
|
+
if parts and parts[-1]:
|
|
1743
|
+
normalized.add(parts[-1].lower())
|
|
1744
|
+
return normalized
|
|
1745
|
+
|
|
1746
|
+
@staticmethod
|
|
1747
|
+
def _quoted_table(name: str, schema: str | None = None, catalog: str | None = None) -> "exp.Table":
|
|
1748
|
+
"""Build a table expression whose parts are quoted to preserve exact catalog names."""
|
|
1749
|
+
return exp.Table(
|
|
1750
|
+
this=exp.to_identifier(name, quoted=True),
|
|
1751
|
+
db=exp.to_identifier(schema, quoted=True) if schema else None,
|
|
1752
|
+
catalog=exp.to_identifier(catalog, quoted=True) if catalog else None,
|
|
1753
|
+
)
|
|
1754
|
+
|
|
1755
|
+
@staticmethod
|
|
1756
|
+
def _copy_identity(identity: "ObjectIdentity", *, dialect: str | None) -> "ObjectIdentity":
|
|
1757
|
+
"""Copy an ObjectIdentity with a different dialect."""
|
|
1758
|
+
return ObjectIdentity(
|
|
1759
|
+
name=identity.name,
|
|
1760
|
+
object_type=identity.object_type,
|
|
1761
|
+
catalog=identity.catalog,
|
|
1762
|
+
schema=identity.schema,
|
|
1763
|
+
dialect=dialect,
|
|
1764
|
+
quoted_name=identity.quoted_name,
|
|
1765
|
+
source=identity.source,
|
|
1766
|
+
)
|
|
1767
|
+
|
|
1768
|
+
def _log_version_detected(self, adapter: str, version: VersionInfo) -> None:
|
|
1769
|
+
"""Log detected database version with db.system context."""
|
|
1770
|
+
logger.debug(
|
|
1771
|
+
"Detected database version", extra={"db.system": resolve_db_system(adapter), "db.version": str(version)}
|
|
1772
|
+
)
|
|
1773
|
+
|
|
1774
|
+
def _log_version_unavailable(self, adapter: str, reason: str) -> None:
|
|
1775
|
+
"""Log that database version could not be determined."""
|
|
1776
|
+
logger.debug("Database version unavailable", extra={"db.system": resolve_db_system(adapter), "reason": reason})
|
|
1777
|
+
|
|
1778
|
+
def _log_schema_introspect(
|
|
1779
|
+
self, driver: Any, *, schema_name: "str | None", table_name: "str | None", operation: str
|
|
1780
|
+
) -> None:
|
|
1781
|
+
"""Log schema-level introspection activity."""
|
|
1782
|
+
log_with_context(
|
|
1783
|
+
logger,
|
|
1784
|
+
logging.DEBUG,
|
|
1785
|
+
"schema.introspect",
|
|
1786
|
+
db_system=resolve_db_system(type(driver).__name__),
|
|
1787
|
+
schema_name=schema_name,
|
|
1788
|
+
table_name=table_name,
|
|
1789
|
+
operation=operation,
|
|
1790
|
+
)
|
|
1791
|
+
|
|
1792
|
+
def _log_table_describe(self, driver: Any, *, schema_name: "str | None", table_name: str, operation: str) -> None:
|
|
1793
|
+
"""Log table-level introspection activity."""
|
|
1794
|
+
log_with_context(
|
|
1795
|
+
logger,
|
|
1796
|
+
logging.DEBUG,
|
|
1797
|
+
"table.describe",
|
|
1798
|
+
db_system=resolve_db_system(type(driver).__name__),
|
|
1799
|
+
schema_name=schema_name,
|
|
1800
|
+
table_name=table_name,
|
|
1801
|
+
operation=operation,
|
|
1802
|
+
)
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
@mypyc_attr(allow_interpreted_subclasses=False)
|
|
1806
|
+
class _ClosedConnection:
|
|
1807
|
+
"""Sentinel assigned to driver.connection after session exit."""
|
|
1808
|
+
|
|
1809
|
+
__slots__ = ()
|
|
1810
|
+
|
|
1811
|
+
def __bool__(self) -> bool:
|
|
1812
|
+
return False
|
|
1813
|
+
|
|
1814
|
+
def __repr__(self) -> str:
|
|
1815
|
+
return "<ClosedConnection>"
|
|
1816
|
+
|
|
1817
|
+
def __getattr__(self, name: str) -> Any:
|
|
1818
|
+
if name.startswith("__") and name.endswith("__"):
|
|
1819
|
+
raise AttributeError(name)
|
|
1820
|
+
raise ImproperConfigurationError(_CLOSED_CONNECTION_MESSAGE)
|
|
1821
|
+
|
|
1822
|
+
|
|
1823
|
+
_CLOSED_CONNECTION: Final[Any] = _ClosedConnection()
|
|
1824
|
+
|
|
1825
|
+
|
|
1826
|
+
def operation_requires_transaction(operation_type: "OperationType", modifies_rows: bool) -> bool:
|
|
1827
|
+
"""Return whether a statement must run inside a transaction under lazy write begin."""
|
|
1828
|
+
return modifies_rows or operation_type not in _READ_ONLY_OPERATION_TYPES
|
|
1829
|
+
|
|
1830
|
+
|
|
1831
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
1832
|
+
class CommonDriverAttributesMixin:
|
|
1833
|
+
"""Common attributes and methods for driver adapters."""
|
|
1834
|
+
|
|
1835
|
+
__slots__ = (
|
|
1836
|
+
"_auto_begin_on_write",
|
|
1837
|
+
"_cache_hit_executor",
|
|
1838
|
+
"_cache_hit_state",
|
|
1839
|
+
"_cache_holder",
|
|
1840
|
+
"_has_active_observability",
|
|
1841
|
+
"_observability",
|
|
1842
|
+
"_observability_generation",
|
|
1843
|
+
"_open_streams",
|
|
1844
|
+
"_pending_statement_profile",
|
|
1845
|
+
"_processed_state_pool",
|
|
1846
|
+
"_statement_cache",
|
|
1847
|
+
"_statement_pool",
|
|
1848
|
+
"_stmt_cache",
|
|
1849
|
+
"_stmt_cache_enabled",
|
|
1850
|
+
"_stmt_cache_max_size",
|
|
1851
|
+
"_stmt_cache_rebind_processor",
|
|
1852
|
+
"_transaction_depth",
|
|
1853
|
+
"connection",
|
|
1854
|
+
"driver_features",
|
|
1855
|
+
"statement_config",
|
|
1856
|
+
)
|
|
1857
|
+
connection: "Any"
|
|
1858
|
+
statement_config: "StatementConfig"
|
|
1859
|
+
driver_features: "dict[str, Any]"
|
|
1860
|
+
|
|
1861
|
+
storage_pipeline_factory: "ClassVar[type[SyncStoragePipeline | AsyncStoragePipeline] | None]" = None
|
|
1862
|
+
|
|
1863
|
+
def __init__(
|
|
1864
|
+
self,
|
|
1865
|
+
connection: "Any",
|
|
1866
|
+
statement_config: "StatementConfig",
|
|
1867
|
+
driver_features: "dict[str, Any] | None" = None,
|
|
1868
|
+
observability: "ObservabilityRuntime | None" = None,
|
|
1869
|
+
) -> None:
|
|
1870
|
+
"""Initialize driver adapter with connection and configuration.
|
|
1871
|
+
|
|
1872
|
+
Args:
|
|
1873
|
+
connection: Database connection instance
|
|
1874
|
+
statement_config: Statement configuration for the driver
|
|
1875
|
+
driver_features: Driver-specific features like extensions, secrets, and connection callbacks
|
|
1876
|
+
observability: Optional runtime handling lifecycle hooks, observers, and spans
|
|
1877
|
+
"""
|
|
1878
|
+
self.connection = connection
|
|
1879
|
+
statement_config.freeze()
|
|
1880
|
+
self.statement_config = statement_config
|
|
1881
|
+
self.driver_features = driver_features or {}
|
|
1882
|
+
self._observability = observability
|
|
1883
|
+
self._pending_statement_profile: dict[str, Any] | None = None
|
|
1884
|
+
self._auto_begin_on_write = False
|
|
1885
|
+
self._transaction_depth = 0
|
|
1886
|
+
self._open_streams: list[Any] = []
|
|
1887
|
+
self._stmt_cache_max_size = self._statement_cache_size()
|
|
1888
|
+
shared_holder = self.driver_features.get("_statement_cache_holder")
|
|
1889
|
+
if (
|
|
1890
|
+
isinstance(shared_holder, StatementCacheHolder)
|
|
1891
|
+
and shared_holder.statement_config is self.statement_config
|
|
1892
|
+
and shared_holder.max_size == self._stmt_cache_max_size
|
|
1893
|
+
):
|
|
1894
|
+
self._cache_holder = shared_holder
|
|
1895
|
+
else:
|
|
1896
|
+
self._cache_holder = StatementCacheHolder(self.statement_config, self._stmt_cache_max_size)
|
|
1897
|
+
self._statement_cache: OrderedDict[str, SQL] = self._cache_holder._statement_cache
|
|
1898
|
+
self._stmt_cache: QueryCache = self._cache_holder.query_cache
|
|
1899
|
+
self._stmt_cache_rebind_processor: ParameterProcessor = self._cache_holder.rebind_processor
|
|
1900
|
+
self._stmt_cache_enabled = False
|
|
1901
|
+
self._cache_hit_executor: (
|
|
1902
|
+
abc.Callable[
|
|
1903
|
+
[Any, str, Any, CachedQuery, StatementConfig, Any], SQLResult | Awaitable[SQLResult | None] | None
|
|
1904
|
+
]
|
|
1905
|
+
| None
|
|
1906
|
+
) = None
|
|
1907
|
+
self._cache_hit_state: Any = None
|
|
1908
|
+
self._has_active_observability = False
|
|
1909
|
+
self._observability_generation = -1
|
|
1910
|
+
self._statement_pool: ObjectPool[SQL] | None = None
|
|
1911
|
+
self._processed_state_pool: ObjectPool[ProcessedState] | None = None
|
|
1912
|
+
self._refresh_statement_cache_state()
|
|
1913
|
+
|
|
1914
|
+
@property
|
|
1915
|
+
def observability(self) -> "ObservabilityRuntime":
|
|
1916
|
+
"""Return the observability runtime, creating a disabled instance when absent."""
|
|
1917
|
+
if self._observability is None:
|
|
1918
|
+
self._observability = ObservabilityRuntime(config_name=type(self).__name__)
|
|
1919
|
+
return self._observability
|
|
1920
|
+
|
|
1921
|
+
@property
|
|
1922
|
+
def observability_db_system(self) -> str | None:
|
|
1923
|
+
"""Return a backend identity override for multi-backend adapters."""
|
|
1924
|
+
return None
|
|
1925
|
+
|
|
1926
|
+
@property
|
|
1927
|
+
def is_async(self) -> bool:
|
|
1928
|
+
"""Return whether the driver executes asynchronously.
|
|
1929
|
+
|
|
1930
|
+
Returns:
|
|
1931
|
+
False for sync drivers.
|
|
1932
|
+
"""
|
|
1933
|
+
return False
|
|
1934
|
+
|
|
1935
|
+
@property
|
|
1936
|
+
def stack_native_disabled(self) -> bool:
|
|
1937
|
+
"""Return True when native stack execution is disabled for this driver."""
|
|
1938
|
+
return bool(self.driver_features.get("stack_native_disabled", False))
|
|
1939
|
+
|
|
1940
|
+
def attach_observability(self, runtime: "ObservabilityRuntime") -> None:
|
|
1941
|
+
"""Attach or replace the observability runtime."""
|
|
1942
|
+
self._observability = runtime
|
|
1943
|
+
self._refresh_statement_cache_state()
|
|
1944
|
+
|
|
1945
|
+
def storage_capabilities(self) -> "StorageCapabilities":
|
|
1946
|
+
"""Return cached storage capabilities for the active driver.
|
|
1947
|
+
|
|
1948
|
+
Returns:
|
|
1949
|
+
StorageCapabilities dict with capability flags.
|
|
1950
|
+
|
|
1951
|
+
Raises:
|
|
1952
|
+
StorageCapabilityError: If storage capabilities are not configured.
|
|
1953
|
+
"""
|
|
1954
|
+
capabilities = self.driver_features.get("storage_capabilities")
|
|
1955
|
+
if capabilities is None:
|
|
1956
|
+
msg = "Storage capabilities are not configured for this driver."
|
|
1957
|
+
raise StorageCapabilityError(msg, capability="storage_capabilities")
|
|
1958
|
+
return cast("StorageCapabilities", dict(capabilities))
|
|
1959
|
+
|
|
1960
|
+
def stmt_cache_rebind(
|
|
1961
|
+
self, params: "tuple[Any, ...] | list[Any] | dict[str, Any]", cached: "CachedQuery"
|
|
1962
|
+
) -> "ConvertedParameters":
|
|
1963
|
+
"""Rebind parameters for a cached query."""
|
|
1964
|
+
config = self.statement_config.parameter_config
|
|
1965
|
+
if (
|
|
1966
|
+
not cached.input_named_parameters
|
|
1967
|
+
and not cached.applied_wrap_types
|
|
1968
|
+
and not config.type_coercion_map
|
|
1969
|
+
and not cached.needs_style_remap
|
|
1970
|
+
and not _is_mapping_parameters(params)
|
|
1971
|
+
):
|
|
1972
|
+
return params
|
|
1973
|
+
profile = cached.parameter_profile
|
|
1974
|
+
rebound_input = (
|
|
1975
|
+
_normalize_cached_parameters(
|
|
1976
|
+
params, profile, input_named_parameters=cached.input_named_parameters, is_many=False
|
|
1977
|
+
)
|
|
1978
|
+
if profile is not None and profile.is_positional_only
|
|
1979
|
+
else params
|
|
1980
|
+
)
|
|
1981
|
+
return self._stmt_cache_rebind_processor.transform_cached_parameters(
|
|
1982
|
+
rebound_input,
|
|
1983
|
+
profile,
|
|
1984
|
+
config,
|
|
1985
|
+
input_named_parameters=cached.input_named_parameters,
|
|
1986
|
+
is_many=False,
|
|
1987
|
+
apply_wrap_types=cached.applied_wrap_types,
|
|
1988
|
+
)
|
|
1989
|
+
|
|
1990
|
+
@overload
|
|
1991
|
+
@staticmethod
|
|
1992
|
+
def to_schema(data: "list[dict[str, Any]]", *, schema_type: "type[SchemaT]") -> "list[SchemaT]": ...
|
|
1993
|
+
@overload
|
|
1994
|
+
@staticmethod
|
|
1995
|
+
def to_schema(data: "list[dict[str, Any]]", *, schema_type: None = None) -> "list[dict[str, Any]]": ...
|
|
1996
|
+
@overload
|
|
1997
|
+
@staticmethod
|
|
1998
|
+
def to_schema(data: "dict[str, Any]", *, schema_type: "type[SchemaT]") -> "SchemaT": ...
|
|
1999
|
+
@overload
|
|
2000
|
+
@staticmethod
|
|
2001
|
+
def to_schema(data: "dict[str, Any]", *, schema_type: None = None) -> "dict[str, Any]": ...
|
|
2002
|
+
@overload
|
|
2003
|
+
@staticmethod
|
|
2004
|
+
def to_schema(data: Any, *, schema_type: "type[SchemaT]") -> Any: ...
|
|
2005
|
+
@overload
|
|
2006
|
+
@staticmethod
|
|
2007
|
+
def to_schema(data: Any, *, schema_type: None = None) -> Any: ...
|
|
2008
|
+
@staticmethod
|
|
2009
|
+
def to_schema(data: Any, *, schema_type: "type[Any] | None" = None) -> Any:
|
|
2010
|
+
"""Convert data to a specified schema type.
|
|
2011
|
+
|
|
2012
|
+
Supports transformation to various schema types including:
|
|
2013
|
+
- TypedDict
|
|
2014
|
+
- dataclasses
|
|
2015
|
+
- msgspec Structs
|
|
2016
|
+
- Pydantic models
|
|
2017
|
+
- attrs classes
|
|
2018
|
+
|
|
2019
|
+
Args:
|
|
2020
|
+
data: Input data to convert (dict, list of dicts, or other).
|
|
2021
|
+
schema_type: Target schema type for conversion. If None, returns data unchanged.
|
|
2022
|
+
|
|
2023
|
+
Returns:
|
|
2024
|
+
Converted data in the specified schema type, or original data if schema_type is None.
|
|
2025
|
+
"""
|
|
2026
|
+
return _to_schema_impl(data, schema_type=schema_type)
|
|
2027
|
+
|
|
2028
|
+
def create_execution_result(
|
|
2029
|
+
self,
|
|
2030
|
+
cursor_result: Any,
|
|
2031
|
+
*,
|
|
2032
|
+
rowcount_override: int | None = None,
|
|
2033
|
+
special_data: Any = None,
|
|
2034
|
+
selected_data: "list[Any] | None" = None,
|
|
2035
|
+
column_names: "list[str] | None" = None,
|
|
2036
|
+
data_row_count: int | None = None,
|
|
2037
|
+
statement_count: int | None = None,
|
|
2038
|
+
successful_statements: int | None = None,
|
|
2039
|
+
is_script_result: bool = False,
|
|
2040
|
+
is_select_result: bool = False,
|
|
2041
|
+
is_many_result: bool = False,
|
|
2042
|
+
row_format: "RowFormat" = "dict",
|
|
2043
|
+
last_inserted_id: int | str | None = None,
|
|
2044
|
+
column_types: "dict[str, str] | None" = None,
|
|
2045
|
+
) -> ExecutionResult:
|
|
2046
|
+
"""Create ExecutionResult with all necessary data for any operation type.
|
|
2047
|
+
|
|
2048
|
+
Args:
|
|
2049
|
+
cursor_result: The raw result returned by the database cursor/driver
|
|
2050
|
+
rowcount_override: Optional override for the number of affected rows
|
|
2051
|
+
special_data: Any special metadata or additional information
|
|
2052
|
+
selected_data: For SELECT operations, the extracted row data (raw driver-native format)
|
|
2053
|
+
column_names: For SELECT operations, the column names
|
|
2054
|
+
data_row_count: For SELECT operations, the number of rows returned
|
|
2055
|
+
statement_count: For script operations, total number of statements
|
|
2056
|
+
successful_statements: For script operations, number of successful statements
|
|
2057
|
+
is_script_result: Whether this result is from script execution
|
|
2058
|
+
is_select_result: Whether this result is from a SELECT operation
|
|
2059
|
+
is_many_result: Whether this result is from an execute_many operation
|
|
2060
|
+
row_format: Format of raw rows - "tuple", "dict", or "record"
|
|
2061
|
+
last_inserted_id: The ID of the last inserted row (if applicable)
|
|
2062
|
+
column_types: For SELECT operations, a column name to neutral type-token map
|
|
2063
|
+
describing declared column types, used to type all-NULL Arrow columns
|
|
2064
|
+
|
|
2065
|
+
Returns:
|
|
2066
|
+
ExecutionResult configured for the specified operation type
|
|
2067
|
+
"""
|
|
2068
|
+
return ExecutionResult(
|
|
2069
|
+
cursor_result,
|
|
2070
|
+
rowcount_override,
|
|
2071
|
+
special_data,
|
|
2072
|
+
selected_data,
|
|
2073
|
+
column_names,
|
|
2074
|
+
data_row_count,
|
|
2075
|
+
statement_count,
|
|
2076
|
+
successful_statements,
|
|
2077
|
+
is_script_result,
|
|
2078
|
+
is_select_result,
|
|
2079
|
+
is_many_result,
|
|
2080
|
+
row_format,
|
|
2081
|
+
last_inserted_id,
|
|
2082
|
+
column_types,
|
|
2083
|
+
)
|
|
2084
|
+
|
|
2085
|
+
def build_statement_result(self, statement: "SQL", execution_result: ExecutionResult) -> "SQLResult":
|
|
2086
|
+
"""Build and return the SQLResult from ExecutionResult data.
|
|
2087
|
+
|
|
2088
|
+
Args:
|
|
2089
|
+
statement: SQL statement that was executed
|
|
2090
|
+
execution_result: ExecutionResult containing all necessary data
|
|
2091
|
+
|
|
2092
|
+
Returns:
|
|
2093
|
+
SQLResult with complete execution data
|
|
2094
|
+
"""
|
|
2095
|
+
statement._pooled = False
|
|
2096
|
+
if execution_result.is_script_result:
|
|
2097
|
+
return SQLResult(
|
|
2098
|
+
statement=statement,
|
|
2099
|
+
data=[],
|
|
2100
|
+
rows_affected=execution_result.rowcount_override or 0,
|
|
2101
|
+
operation_type="SCRIPT",
|
|
2102
|
+
total_statements=execution_result.statement_count or 0,
|
|
2103
|
+
successful_statements=execution_result.successful_statements or 0,
|
|
2104
|
+
metadata=execution_result.special_data or _DEFAULT_DML_METADATA,
|
|
2105
|
+
)
|
|
2106
|
+
|
|
2107
|
+
if execution_result.is_select_result:
|
|
2108
|
+
select_metadata = execution_result.special_data or {}
|
|
2109
|
+
if execution_result.column_types:
|
|
2110
|
+
select_metadata = {**select_metadata, "column_types": execution_result.column_types}
|
|
2111
|
+
return SQLResult(
|
|
2112
|
+
statement=statement,
|
|
2113
|
+
data=execution_result.selected_data or [],
|
|
2114
|
+
column_names=execution_result.column_names or [],
|
|
2115
|
+
rows_affected=execution_result.data_row_count or 0,
|
|
2116
|
+
operation_type="SELECT",
|
|
2117
|
+
metadata=select_metadata,
|
|
2118
|
+
row_format=execution_result.row_format,
|
|
2119
|
+
last_inserted_id=execution_result.last_inserted_id,
|
|
2120
|
+
)
|
|
2121
|
+
|
|
2122
|
+
return SQLResult(
|
|
2123
|
+
statement=statement,
|
|
2124
|
+
data=_EMPTY_DML_DATA,
|
|
2125
|
+
rows_affected=execution_result.rowcount_override or 0,
|
|
2126
|
+
operation_type=statement.operation_type,
|
|
2127
|
+
last_inserted_id=execution_result.last_inserted_id,
|
|
2128
|
+
metadata=execution_result.special_data or _DEFAULT_DML_METADATA,
|
|
2129
|
+
)
|
|
2130
|
+
|
|
2131
|
+
def prepare_statement(
|
|
2132
|
+
self,
|
|
2133
|
+
statement: "Statement | QueryBuilder",
|
|
2134
|
+
parameters: "tuple[StatementParameters | StatementFilter, ...]" = (),
|
|
2135
|
+
*,
|
|
2136
|
+
statement_config: "StatementConfig | None" = None,
|
|
2137
|
+
kwargs: "dict[str, Any] | None" = None,
|
|
2138
|
+
) -> "SQL":
|
|
2139
|
+
"""Build SQL statement from various input types.
|
|
2140
|
+
|
|
2141
|
+
Ensures dialect is set and preserves existing state when rebuilding SQL objects.
|
|
2142
|
+
|
|
2143
|
+
Args:
|
|
2144
|
+
statement: SQL statement or QueryBuilder to prepare
|
|
2145
|
+
parameters: Parameters for the SQL statement
|
|
2146
|
+
statement_config: Optional statement configuration override.
|
|
2147
|
+
kwargs: Additional keyword arguments
|
|
2148
|
+
|
|
2149
|
+
Returns:
|
|
2150
|
+
Prepared SQL statement
|
|
2151
|
+
"""
|
|
2152
|
+
if statement_config is None:
|
|
2153
|
+
statement_config = self.statement_config
|
|
2154
|
+
use_default_cache = statement_config is self.statement_config
|
|
2155
|
+
|
|
2156
|
+
if use_default_cache and isinstance(statement, str):
|
|
2157
|
+
cached_sql = self._cache_holder.get_statement(statement)
|
|
2158
|
+
if cached_sql is not None and not kwargs:
|
|
2159
|
+
has_filters = any(is_statement_filter(p) for p in parameters)
|
|
2160
|
+
if not has_filters:
|
|
2161
|
+
return cached_sql.copy(parameters=parameters)
|
|
2162
|
+
|
|
2163
|
+
kwargs = kwargs or {}
|
|
2164
|
+
filters, data_parameters = self._split_parameters(parameters)
|
|
2165
|
+
|
|
2166
|
+
if isinstance(statement, QueryBuilder):
|
|
2167
|
+
sql_statement = self._prepare_from_builder(statement, data_parameters, statement_config, kwargs)
|
|
2168
|
+
elif isinstance(statement, SQL):
|
|
2169
|
+
pending_filters = statement.filters
|
|
2170
|
+
sql_statement = self._prepare_from_sql(statement, data_parameters, statement_config, kwargs)
|
|
2171
|
+
sql_statement, _ = sql_statement._take_pending_filters()
|
|
2172
|
+
filters = [*pending_filters, *filters]
|
|
2173
|
+
else:
|
|
2174
|
+
sql_statement = self._prepare_from_string(statement, data_parameters, statement_config, kwargs)
|
|
2175
|
+
if (
|
|
2176
|
+
use_default_cache
|
|
2177
|
+
and not filters
|
|
2178
|
+
and not kwargs
|
|
2179
|
+
and isinstance(statement, str)
|
|
2180
|
+
and self._stmt_cache_max_size > 0
|
|
2181
|
+
):
|
|
2182
|
+
self._cache_holder.set_statement(statement, sql_statement, max_size=self._stmt_cache_max_size)
|
|
2183
|
+
|
|
2184
|
+
_check_declared_parameters(sql_statement)
|
|
2185
|
+
return self._apply_filters(sql_statement, filters)
|
|
2186
|
+
|
|
2187
|
+
def split_script_statements(
|
|
2188
|
+
self, script: str, statement_config: "StatementConfig", strip_trailing_semicolon: bool = False
|
|
2189
|
+
) -> "list[str]":
|
|
2190
|
+
"""Split a SQL script into individual statements.
|
|
2191
|
+
|
|
2192
|
+
Uses a lexer-driven state machine to handle multi-statement scripts,
|
|
2193
|
+
including complex constructs like PL/SQL blocks, T-SQL batches, and nested blocks.
|
|
2194
|
+
|
|
2195
|
+
Args:
|
|
2196
|
+
script: The SQL script to split
|
|
2197
|
+
statement_config: Statement configuration containing dialect information
|
|
2198
|
+
strip_trailing_semicolon: If True, remove trailing semicolons from statements
|
|
2199
|
+
|
|
2200
|
+
Returns:
|
|
2201
|
+
A list of individual SQL statements
|
|
2202
|
+
"""
|
|
2203
|
+
return [
|
|
2204
|
+
sql_script.strip()
|
|
2205
|
+
for sql_script in split_sql_script(
|
|
2206
|
+
script, dialect=str(statement_config.dialect), strip_trailing_terminator=strip_trailing_semicolon
|
|
2207
|
+
)
|
|
2208
|
+
if sql_script.strip()
|
|
2209
|
+
]
|
|
2210
|
+
|
|
2211
|
+
def prepare_driver_parameters(
|
|
2212
|
+
self,
|
|
2213
|
+
parameters: "StatementParameters | list[StatementParameters] | tuple[StatementParameters, ...]",
|
|
2214
|
+
statement_config: "StatementConfig",
|
|
2215
|
+
is_many: bool = False,
|
|
2216
|
+
prepared_statement: Any | None = None,
|
|
2217
|
+
) -> "ConvertedParameters":
|
|
2218
|
+
"""Prepare parameters for database driver consumption.
|
|
2219
|
+
|
|
2220
|
+
Normalizes parameter structure and unwraps TypedParameter objects
|
|
2221
|
+
to their underlying values, which database drivers expect.
|
|
2222
|
+
|
|
2223
|
+
Args:
|
|
2224
|
+
parameters: Parameters in any format (dict, list, tuple, scalar, TypedParameter)
|
|
2225
|
+
statement_config: Statement configuration for parameter style detection
|
|
2226
|
+
is_many: If True, handle as executemany parameter sequence
|
|
2227
|
+
prepared_statement: Optional prepared statement containing metadata for parameter processing
|
|
2228
|
+
|
|
2229
|
+
Returns:
|
|
2230
|
+
Parameters with TypedParameter objects unwrapped to primitive values
|
|
2231
|
+
"""
|
|
2232
|
+
if parameters is None and statement_config.parameter_config.needs_static_script_compilation:
|
|
2233
|
+
return None
|
|
2234
|
+
|
|
2235
|
+
if not parameters:
|
|
2236
|
+
return []
|
|
2237
|
+
|
|
2238
|
+
if is_many:
|
|
2239
|
+
if isinstance(parameters, list):
|
|
2240
|
+
type_coercion_map = statement_config.parameter_config.type_coercion_map
|
|
2241
|
+
fallback_items = type_coercion_fallbacks(type_coercion_map)
|
|
2242
|
+
needs_transform = False
|
|
2243
|
+
for param_set in parameters:
|
|
2244
|
+
if isinstance(param_set, dict):
|
|
2245
|
+
for value in param_set.values():
|
|
2246
|
+
if parameter_value_needs_processing(value, type_coercion_map, fallback_items):
|
|
2247
|
+
needs_transform = True
|
|
2248
|
+
break
|
|
2249
|
+
elif isinstance(param_set, (list, tuple)):
|
|
2250
|
+
for value in param_set:
|
|
2251
|
+
if parameter_value_needs_processing(value, type_coercion_map, fallback_items):
|
|
2252
|
+
needs_transform = True
|
|
2253
|
+
break
|
|
2254
|
+
elif parameter_value_needs_processing(param_set, type_coercion_map, fallback_items):
|
|
2255
|
+
needs_transform = True
|
|
2256
|
+
if needs_transform:
|
|
2257
|
+
break
|
|
2258
|
+
|
|
2259
|
+
if not needs_transform:
|
|
2260
|
+
return parameters
|
|
2261
|
+
|
|
2262
|
+
formatted_many: list[Any] | None = None
|
|
2263
|
+
for idx, param_set in enumerate(parameters):
|
|
2264
|
+
formatted = self._batch_parameters(param_set, statement_config)
|
|
2265
|
+
if formatted_many is None:
|
|
2266
|
+
if formatted is param_set:
|
|
2267
|
+
continue
|
|
2268
|
+
formatted_many = list(parameters[:idx])
|
|
2269
|
+
formatted_many.append(formatted)
|
|
2270
|
+
if formatted_many is None:
|
|
2271
|
+
return parameters
|
|
2272
|
+
return formatted_many
|
|
2273
|
+
return [self._batch_parameters(parameters, statement_config)]
|
|
2274
|
+
return self._driver_parameters(parameters, statement_config, prepared_statement=prepared_statement)
|
|
2275
|
+
|
|
2276
|
+
@staticmethod
|
|
2277
|
+
def find_filter(
|
|
2278
|
+
filter_type: "type[FilterTypeT]",
|
|
2279
|
+
filters: "abc.Sequence[StatementFilter | StatementParameters] | abc.Sequence[StatementFilter]",
|
|
2280
|
+
) -> "FilterTypeT | None":
|
|
2281
|
+
"""Get the filter specified by filter type from the filters.
|
|
2282
|
+
|
|
2283
|
+
Args:
|
|
2284
|
+
filter_type: The type of filter to find.
|
|
2285
|
+
filters: filter types to apply to the query
|
|
2286
|
+
|
|
2287
|
+
Returns:
|
|
2288
|
+
The match filter instance or None
|
|
2289
|
+
"""
|
|
2290
|
+
return _find_filter_impl(filter_type, filters)
|
|
2291
|
+
|
|
2292
|
+
def build_cached_select_result(
|
|
2293
|
+
self,
|
|
2294
|
+
sql: str,
|
|
2295
|
+
params: "tuple[Any, ...] | list[Any] | dict[str, Any]",
|
|
2296
|
+
cached: "CachedQuery",
|
|
2297
|
+
*,
|
|
2298
|
+
selected_data: "list[Any]",
|
|
2299
|
+
column_names: "list[str]",
|
|
2300
|
+
data_row_count: int,
|
|
2301
|
+
row_format: "RowFormat" = "dict",
|
|
2302
|
+
last_inserted_id: int | str | None = None,
|
|
2303
|
+
compiled_sql: str | None = None,
|
|
2304
|
+
) -> "SQLResult":
|
|
2305
|
+
"""Build a fast-path SELECT result with deferred statement materialization."""
|
|
2306
|
+
return SQLResult.create_cached_select(
|
|
2307
|
+
sql=sql,
|
|
2308
|
+
config=self.statement_config,
|
|
2309
|
+
cached_state=cached.processed_state,
|
|
2310
|
+
compiled_sql=cached.compiled_sql if compiled_sql is None else compiled_sql,
|
|
2311
|
+
params=params,
|
|
2312
|
+
data=selected_data,
|
|
2313
|
+
column_names=column_names,
|
|
2314
|
+
rows_affected=data_row_count,
|
|
2315
|
+
row_format=row_format,
|
|
2316
|
+
last_inserted_id=last_inserted_id,
|
|
2317
|
+
)
|
|
2318
|
+
|
|
2319
|
+
def _register_open_stream(self, stream: StreamT) -> StreamT:
|
|
2320
|
+
"""Track a returned row stream so session teardown can close it.
|
|
2321
|
+
|
|
2322
|
+
Args:
|
|
2323
|
+
stream: Row stream returned to the caller.
|
|
2324
|
+
|
|
2325
|
+
Returns:
|
|
2326
|
+
The same stream, unchanged.
|
|
2327
|
+
"""
|
|
2328
|
+
open_streams = self._open_streams
|
|
2329
|
+
open_streams[:] = [open_stream for open_stream in open_streams if not open_stream._closed]
|
|
2330
|
+
open_streams.append(stream)
|
|
2331
|
+
return stream
|
|
2332
|
+
|
|
2333
|
+
def _mark_closed(self) -> None:
|
|
2334
|
+
"""Replace driver.connection with the closed sentinel, then invalidate open streams.
|
|
2335
|
+
|
|
2336
|
+
The sentinel is installed first so a stream closing here sees that the session no longer owns its
|
|
2337
|
+
connection and leaves the released connection untouched.
|
|
2338
|
+
"""
|
|
2339
|
+
self.connection = _CLOSED_CONNECTION
|
|
2340
|
+
open_streams = self._open_streams
|
|
2341
|
+
self._open_streams = []
|
|
2342
|
+
for open_stream in open_streams:
|
|
2343
|
+
if isinstance(open_stream, SyncRowStream):
|
|
2344
|
+
open_stream._close_for_session_exit(error=True)
|
|
2345
|
+
else:
|
|
2346
|
+
open_stream._mark_session_closed()
|
|
2347
|
+
self._auto_begin_on_write = False
|
|
2348
|
+
self._stmt_cache_enabled = False
|
|
2349
|
+
self._transaction_depth = 0
|
|
2350
|
+
|
|
2351
|
+
def _consume_statement_profile(self) -> "dict[str, Any] | None":
|
|
2352
|
+
"""Take the profile produced by an execution callback and clear pending ownership."""
|
|
2353
|
+
profile = self._pending_statement_profile
|
|
2354
|
+
self._pending_statement_profile = None
|
|
2355
|
+
return profile
|
|
2356
|
+
|
|
2357
|
+
def _format_wire_sql(self, sql: str) -> str:
|
|
2358
|
+
"""Apply wire-level sqlcommenter formatting when enabled on statement_config."""
|
|
2359
|
+
if not self.statement_config.enable_sqlcommenter:
|
|
2360
|
+
return sql
|
|
2361
|
+
return format_wire_sqlcomment(sql, self.statement_config)
|
|
2362
|
+
|
|
2363
|
+
def _statement_cache_size(self) -> int:
|
|
2364
|
+
"""Return the configured statement-cache capacity."""
|
|
2365
|
+
return resolve_statement_cache_size(self.driver_features)
|
|
2366
|
+
|
|
2367
|
+
def _refresh_statement_cache_state(self) -> None:
|
|
2368
|
+
runtime = self._observability
|
|
2369
|
+
self._has_active_observability = runtime is not None and not runtime.is_idle
|
|
2370
|
+
self._observability_generation = runtime.hook_generation if runtime is not None else -1
|
|
2371
|
+
self._stmt_cache_enabled = bool(
|
|
2372
|
+
self.connection is not _CLOSED_CONNECTION
|
|
2373
|
+
and self._stmt_cache_max_size > 0
|
|
2374
|
+
and not self.statement_config._has_transformers
|
|
2375
|
+
and not self.statement_config._has_uncacheable_transformers
|
|
2376
|
+
)
|
|
2377
|
+
|
|
2378
|
+
def _require_capability(self, capability_flag: str) -> None:
|
|
2379
|
+
"""Check that a storage capability is enabled.
|
|
2380
|
+
|
|
2381
|
+
Args:
|
|
2382
|
+
capability_flag: The capability flag to check.
|
|
2383
|
+
|
|
2384
|
+
Raises:
|
|
2385
|
+
StorageCapabilityError: If the capability is not available.
|
|
2386
|
+
"""
|
|
2387
|
+
capabilities = self.storage_capabilities()
|
|
2388
|
+
if capabilities.get(capability_flag, False):
|
|
2389
|
+
return
|
|
2390
|
+
human_label = CAPABILITY_HINTS.get(capability_flag, capability_flag)
|
|
2391
|
+
remediation = "Check adapter supports this capability or stage artifacts via storage pipeline."
|
|
2392
|
+
msg = f"{human_label} is not available for this adapter"
|
|
2393
|
+
raise StorageCapabilityError(msg, capability=capability_flag, remediation=remediation)
|
|
2394
|
+
|
|
2395
|
+
def _raise_storage_not_implemented(self, capability: str) -> NoReturn:
|
|
2396
|
+
"""Raise NotImplementedError for storage operations.
|
|
2397
|
+
|
|
2398
|
+
Args:
|
|
2399
|
+
capability: The capability that is not implemented.
|
|
2400
|
+
|
|
2401
|
+
Raises:
|
|
2402
|
+
StorageCapabilityError: Always raised.
|
|
2403
|
+
"""
|
|
2404
|
+
msg = f"{capability} is not implemented for this driver"
|
|
2405
|
+
remediation = "Override storage methods on the adapter to enable this capability."
|
|
2406
|
+
raise StorageCapabilityError(msg, capability=capability, remediation=remediation)
|
|
2407
|
+
|
|
2408
|
+
def _get_statement_pool(self) -> "ObjectPool[SQL]":
|
|
2409
|
+
pool = self._statement_pool
|
|
2410
|
+
if pool is None:
|
|
2411
|
+
pool = get_sql_pool()
|
|
2412
|
+
self._statement_pool = pool
|
|
2413
|
+
return pool
|
|
2414
|
+
|
|
2415
|
+
def _get_processed_state_pool(self) -> "ObjectPool[ProcessedState]":
|
|
2416
|
+
pool = self._processed_state_pool
|
|
2417
|
+
if pool is None:
|
|
2418
|
+
pool = get_processed_state_pool()
|
|
2419
|
+
self._processed_state_pool = pool
|
|
2420
|
+
return pool
|
|
2421
|
+
|
|
2422
|
+
def _release_pooled_statement(self, statement: "SQL") -> None:
|
|
2423
|
+
if statement._pooled:
|
|
2424
|
+
self._get_statement_pool().release(statement)
|
|
2425
|
+
|
|
2426
|
+
def _cached_statement(
|
|
2427
|
+
self,
|
|
2428
|
+
sql: str,
|
|
2429
|
+
_params: "tuple[Any, ...] | list[Any] | dict[str, Any]",
|
|
2430
|
+
cached: "CachedQuery",
|
|
2431
|
+
execution_parameters: "ConvertedParameters",
|
|
2432
|
+
*,
|
|
2433
|
+
params_are_simple: bool = False,
|
|
2434
|
+
compiled_sql: str | None = None,
|
|
2435
|
+
) -> "SQL":
|
|
2436
|
+
if params_are_simple:
|
|
2437
|
+
prepared_parameters = execution_parameters
|
|
2438
|
+
else:
|
|
2439
|
+
prepared_parameters = self.prepare_driver_parameters(
|
|
2440
|
+
execution_parameters, self.statement_config, is_many=False
|
|
2441
|
+
)
|
|
2442
|
+
effective_compiled_sql = cached.compiled_sql if compiled_sql is None else compiled_sql
|
|
2443
|
+
cached_state = cached.processed_state
|
|
2444
|
+
direct_state = ProcessedState(
|
|
2445
|
+
compiled_sql=effective_compiled_sql,
|
|
2446
|
+
execution_parameters=prepared_parameters,
|
|
2447
|
+
parsed_expression=cached_state.parsed_expression,
|
|
2448
|
+
operation_type=cached_state.operation_type,
|
|
2449
|
+
input_named_parameters=cached_state.input_named_parameters,
|
|
2450
|
+
applied_wrap_types=cached_state.applied_wrap_types,
|
|
2451
|
+
filter_hash=cached_state.filter_hash,
|
|
2452
|
+
parameter_fingerprint=cached_state.parameter_fingerprint,
|
|
2453
|
+
parameter_casts=cached_state.parameter_casts,
|
|
2454
|
+
validation_errors=cached_state.validation_errors,
|
|
2455
|
+
parameter_profile=cached_state.parameter_profile,
|
|
2456
|
+
operation_profile=cached_state.operation_profile,
|
|
2457
|
+
is_many=False,
|
|
2458
|
+
expression_is_shared=True,
|
|
2459
|
+
)
|
|
2460
|
+
return SQL._create_cached_direct(sql, self.statement_config, direct_state, pooled=False)
|
|
2461
|
+
|
|
2462
|
+
def _bound_script_statements(self, statement: "SQL") -> "list[SQL] | None":
|
|
2463
|
+
"""Split a parameterized script into per-statement ``SQL`` objects.
|
|
2464
|
+
|
|
2465
|
+
Statements whose leading keyword is DML or DQL bind the parameters they use through the
|
|
2466
|
+
normal execute path. Every other statement compiles in script mode and receives escaped
|
|
2467
|
+
literals. Each returned statement is already compiled.
|
|
2468
|
+
|
|
2469
|
+
Args:
|
|
2470
|
+
statement: Script statement carrying the caller's parameters.
|
|
2471
|
+
|
|
2472
|
+
Returns:
|
|
2473
|
+
One compiled ``SQL`` per script statement, or ``None`` when the script has no parameters.
|
|
2474
|
+
|
|
2475
|
+
Raises:
|
|
2476
|
+
SQLSpecError: When a statement uses a parameter that was not supplied, mixes index and
|
|
2477
|
+
sequential placeholders, or the script receives positional values it never uses.
|
|
2478
|
+
"""
|
|
2479
|
+
positional = list(statement.positional_parameters)
|
|
2480
|
+
named = statement.named_parameters
|
|
2481
|
+
if not positional and not named:
|
|
2482
|
+
return None
|
|
2483
|
+
config = self.statement_config
|
|
2484
|
+
dialect = str(config.dialect) if config.dialect else None
|
|
2485
|
+
bind_keywords = (
|
|
2486
|
+
_SCRIPT_BIND_KEYWORDS | _ORACLE_SCRIPT_BIND_KEYWORDS if dialect == "oracle" else _SCRIPT_BIND_KEYWORDS
|
|
2487
|
+
)
|
|
2488
|
+
validator = config.parameter_validator
|
|
2489
|
+
pieces = self.split_script_statements(statement.raw_sql, config, strip_trailing_semicolon=True)
|
|
2490
|
+
script_config = config._with_script_mode() # pyright: ignore[reportPrivateUsage]
|
|
2491
|
+
statements: list[SQL] = []
|
|
2492
|
+
used_positional: set[int] = set()
|
|
2493
|
+
sequential_cursor = 0
|
|
2494
|
+
for index, piece in enumerate(pieces):
|
|
2495
|
+
infos = validator.extract_parameters(piece, dialect=dialect)
|
|
2496
|
+
if not infos:
|
|
2497
|
+
piece_statement = SQL(piece, statement_config=config)
|
|
2498
|
+
piece_statement.compile()
|
|
2499
|
+
statements.append(piece_statement)
|
|
2500
|
+
continue
|
|
2501
|
+
has_index = any(info.style in _SCRIPT_INDEX_STYLES for info in infos)
|
|
2502
|
+
if has_index and any(
|
|
2503
|
+
info.style not in _SCRIPT_INDEX_STYLES and info.style not in _SCRIPT_NAMED_STYLES for info in infos
|
|
2504
|
+
):
|
|
2505
|
+
first_index = next(info for info in infos if info.style in _SCRIPT_INDEX_STYLES)
|
|
2506
|
+
raise SQLSpecError(ambiguous_index_message(first_index))
|
|
2507
|
+
piece_named: dict[str, Any] = {}
|
|
2508
|
+
piece_positional: list[Any] = []
|
|
2509
|
+
index_slots: dict[int, int] = {}
|
|
2510
|
+
rewrites: list[tuple[int, int, str]] = []
|
|
2511
|
+
for info in infos:
|
|
2512
|
+
if info.style in _SCRIPT_NAMED_STYLES:
|
|
2513
|
+
name = cast("str", info.name)
|
|
2514
|
+
if name not in named:
|
|
2515
|
+
msg = f"Script statement {index + 1} uses parameter {name!r}, which was not supplied"
|
|
2516
|
+
raise SQLSpecError(msg)
|
|
2517
|
+
piece_named[name] = named[name]
|
|
2518
|
+
elif info.style in _SCRIPT_INDEX_STYLES:
|
|
2519
|
+
source_index = int(cast("str", info.name)) - 1
|
|
2520
|
+
if source_index < 0 or source_index >= len(positional):
|
|
2521
|
+
msg = (
|
|
2522
|
+
f"Script statement {index + 1} uses parameter {info.placeholder_text!r}, "
|
|
2523
|
+
"which was not supplied"
|
|
2524
|
+
)
|
|
2525
|
+
raise SQLSpecError(msg)
|
|
2526
|
+
used_positional.add(source_index)
|
|
2527
|
+
slot = index_slots.get(source_index)
|
|
2528
|
+
if slot is None:
|
|
2529
|
+
slot = len(index_slots) + 1
|
|
2530
|
+
index_slots[source_index] = slot
|
|
2531
|
+
piece_positional.append(positional[source_index])
|
|
2532
|
+
prefix = "$" if info.style is ParameterStyle.NUMERIC else ":"
|
|
2533
|
+
rewrites.append((info.position, len(info.placeholder_text), f"{prefix}{slot}"))
|
|
2534
|
+
else:
|
|
2535
|
+
if sequential_cursor >= len(positional):
|
|
2536
|
+
msg = f"Script statement {index + 1} uses more positional parameters than were supplied"
|
|
2537
|
+
raise SQLSpecError(msg)
|
|
2538
|
+
used_positional.add(sequential_cursor)
|
|
2539
|
+
piece_positional.append(positional[sequential_cursor])
|
|
2540
|
+
sequential_cursor += 1
|
|
2541
|
+
for position, length, replacement in reversed(rewrites):
|
|
2542
|
+
piece = piece[:position] + replacement + piece[position + length :]
|
|
2543
|
+
parsed_keyword = _split_leading_keyword(_skip_leading_line_comments(piece, dialect))
|
|
2544
|
+
binds = parsed_keyword is not None and parsed_keyword[0] in bind_keywords
|
|
2545
|
+
piece_statement = SQL(
|
|
2546
|
+
piece, *piece_positional, statement_config=config if binds else script_config, **piece_named
|
|
2547
|
+
)
|
|
2548
|
+
piece_statement.compile()
|
|
2549
|
+
statements.append(piece_statement)
|
|
2550
|
+
if len(used_positional) < len(positional):
|
|
2551
|
+
msg = "Script received more parameters than its statements use"
|
|
2552
|
+
raise SQLSpecError(msg)
|
|
2553
|
+
return statements
|
|
2554
|
+
|
|
2555
|
+
def _sub_statement(self, sql: str, execution_parameters: "ConvertedParameters") -> "SQL":
|
|
2556
|
+
direct_state = self._get_processed_state_pool().acquire()
|
|
2557
|
+
ProcessedState.__init__(direct_state, compiled_sql=sql, execution_parameters=execution_parameters)
|
|
2558
|
+
return SQL._create_cached_direct(sql, self.statement_config, direct_state)
|
|
2559
|
+
|
|
2560
|
+
def _emit_script_statement_event(
|
|
2561
|
+
self,
|
|
2562
|
+
*,
|
|
2563
|
+
sql: str,
|
|
2564
|
+
parameters: Any,
|
|
2565
|
+
operation: "OperationType",
|
|
2566
|
+
rows_affected: int | None,
|
|
2567
|
+
duration_s: float,
|
|
2568
|
+
started_at: float | None,
|
|
2569
|
+
profile: "dict[str, Any] | None",
|
|
2570
|
+
script_ordinal: int,
|
|
2571
|
+
script_statement_count: int,
|
|
2572
|
+
) -> None:
|
|
2573
|
+
"""Emit a per-statement StatementEvent during multi-statement script execution."""
|
|
2574
|
+
runtime = self._observability
|
|
2575
|
+
if runtime is None or not runtime.has_statement_observers:
|
|
2576
|
+
return
|
|
2577
|
+
observed_sql = (
|
|
2578
|
+
redact_sql_literals(sql, dialect=self.observability_db_system)
|
|
2579
|
+
if runtime._redaction is not None and runtime._redaction.mask_parameters
|
|
2580
|
+
else sql
|
|
2581
|
+
)
|
|
2582
|
+
runtime.emit_statement_event(
|
|
2583
|
+
sql=observed_sql,
|
|
2584
|
+
parameters=parameters,
|
|
2585
|
+
driver=type(self).__name__,
|
|
2586
|
+
operation=operation,
|
|
2587
|
+
execution_mode=self.statement_config.execution_mode,
|
|
2588
|
+
is_many=False,
|
|
2589
|
+
is_script=True,
|
|
2590
|
+
rows_affected=rows_affected,
|
|
2591
|
+
duration_s=duration_s,
|
|
2592
|
+
storage_backend=None,
|
|
2593
|
+
started_at=started_at,
|
|
2594
|
+
profile=profile,
|
|
2595
|
+
script_ordinal=script_ordinal,
|
|
2596
|
+
script_statement_index=script_ordinal,
|
|
2597
|
+
script_statement_count=script_statement_count,
|
|
2598
|
+
db_system=self.observability_db_system,
|
|
2599
|
+
)
|
|
2600
|
+
|
|
2601
|
+
def _execute_cached_statement(self, statement: "SQL") -> "SQLResult | Awaitable[SQLResult]":
|
|
2602
|
+
raise NotImplementedError
|
|
2603
|
+
|
|
2604
|
+
def _execute_cached_statement_observed(
|
|
2605
|
+
self, statement: "SQL", compiled_sql: str, execution_parameters: Any, operation: "OperationType"
|
|
2606
|
+
) -> "SQLResult | Awaitable[SQLResult]":
|
|
2607
|
+
return self._execute_cached_statement(statement)
|
|
2608
|
+
|
|
2609
|
+
def _execute_cache_hit(
|
|
2610
|
+
self, sql: str, params: "tuple[Any, ...] | list[Any] | dict[str, Any]", cached: "CachedQuery"
|
|
2611
|
+
) -> "SQLResult | Awaitable[SQLResult]":
|
|
2612
|
+
"""Execute pre-compiled query via ultra-fast path (no rebind needed).
|
|
2613
|
+
|
|
2614
|
+
Default implementation falls back to building a direct SQL object and
|
|
2615
|
+
routing through _execute_cached_statement. Subclasses may override with adapter-specific
|
|
2616
|
+
implementations that bypass SQL object construction entirely.
|
|
2617
|
+
"""
|
|
2618
|
+
prepared = self._cached_statement(
|
|
2619
|
+
sql, params, cached, params, params_are_simple=True, compiled_sql=self._format_wire_sql(cached.compiled_sql)
|
|
2620
|
+
)
|
|
2621
|
+
return self._execute_cached_statement(prepared)
|
|
2622
|
+
|
|
2623
|
+
def _execute_cache_hit_observed(
|
|
2624
|
+
self, sql: str, params: "tuple[Any, ...] | list[Any] | dict[str, Any]", cached: "CachedQuery"
|
|
2625
|
+
) -> "SQLResult | Awaitable[SQLResult]":
|
|
2626
|
+
return self._execute_cache_hit(sql, params, cached)
|
|
2627
|
+
|
|
2628
|
+
def _cache_statement(self, statement: "SQL") -> None:
|
|
2629
|
+
"""Store statement in cache if eligible.
|
|
2630
|
+
|
|
2631
|
+
All eligibility validation happens here (executed once per unique query).
|
|
2632
|
+
This keeps the hot lookup path (qc_prepare) minimal - just a flag check
|
|
2633
|
+
and cache lookup.
|
|
2634
|
+
|
|
2635
|
+
Ineligible queries:
|
|
2636
|
+
- QC disabled or config mismatch
|
|
2637
|
+
- Scripts or execute-many (multiple statements/param sets)
|
|
2638
|
+
- Raw expressions (dynamic SQL)
|
|
2639
|
+
- Static script compilation (parameters embedded in SQL)
|
|
2640
|
+
- Filtered statements (dynamic WHERE clauses)
|
|
2641
|
+
- Unprocessed statements (no compiled metadata)
|
|
2642
|
+
"""
|
|
2643
|
+
if not self._stmt_cache_enabled:
|
|
2644
|
+
return
|
|
2645
|
+
if statement.statement_config is not self.statement_config:
|
|
2646
|
+
return
|
|
2647
|
+
if statement.is_script or statement.is_many:
|
|
2648
|
+
return
|
|
2649
|
+
if statement.raw_expression is not None:
|
|
2650
|
+
return
|
|
2651
|
+
if not statement.raw_sql:
|
|
2652
|
+
return
|
|
2653
|
+
if statement.statement_config.parameter_config.needs_static_script_compilation:
|
|
2654
|
+
return
|
|
2655
|
+
if len(statement.get_filters_view()) > 0:
|
|
2656
|
+
return
|
|
2657
|
+
if not statement.is_processed:
|
|
2658
|
+
return
|
|
2659
|
+
if statement.statement_config.parameter_config.ast_transformer is not None:
|
|
2660
|
+
return
|
|
2661
|
+
if self._stmt_cache.get(statement.raw_sql) is not None:
|
|
2662
|
+
return
|
|
2663
|
+
|
|
2664
|
+
processed = cast("ProcessedState", statement.get_processed_state())
|
|
2665
|
+
if processed.parsed_expression is None or processed.operation_type in {"COMMAND", "UNKNOWN"}:
|
|
2666
|
+
return
|
|
2667
|
+
param_profile = processed.parameter_profile
|
|
2668
|
+
operation_profile = processed.operation_profile
|
|
2669
|
+
if not operation_profile.returns_rows and statement.returns_rows():
|
|
2670
|
+
operation_profile = OperationProfile(
|
|
2671
|
+
returns_rows=True,
|
|
2672
|
+
modifies_rows=operation_profile.modifies_rows,
|
|
2673
|
+
is_read_only=operation_profile.is_read_only,
|
|
2674
|
+
)
|
|
2675
|
+
clean_sql = (
|
|
2676
|
+
strip_sqlcomment(processed.compiled_sql)
|
|
2677
|
+
if self.statement_config.enable_sqlcommenter
|
|
2678
|
+
else processed.compiled_sql
|
|
2679
|
+
)
|
|
2680
|
+
cached_state = _clone_processed_state(processed, operation_profile, compiled_sql=clean_sql)
|
|
2681
|
+
needs_style_remap = bool(_CACHED_NAMED_STYLES.intersection(param_profile.styles))
|
|
2682
|
+
stmt_config = self.statement_config
|
|
2683
|
+
positional_passthrough = (not processed.applied_wrap_types and not needs_style_remap) and (
|
|
2684
|
+
not processed.input_named_parameters
|
|
2685
|
+
or (
|
|
2686
|
+
bool(param_profile.styles)
|
|
2687
|
+
and _POSITIONAL_NUMBERED_STYLES.issuperset(param_profile.styles)
|
|
2688
|
+
and len(processed.input_named_parameters) == param_profile.total_count
|
|
2689
|
+
and processed.input_named_parameters == tuple(str(i) for i in range(1, param_profile.total_count + 1))
|
|
2690
|
+
)
|
|
2691
|
+
)
|
|
2692
|
+
simple_wire_fast_path = (
|
|
2693
|
+
positional_passthrough
|
|
2694
|
+
and not stmt_config._has_output_transformer
|
|
2695
|
+
and not stmt_config.enable_sqlcommenter
|
|
2696
|
+
and stmt_config.parameter_config.ast_transformer is None
|
|
2697
|
+
)
|
|
2698
|
+
cached = CachedQuery(
|
|
2699
|
+
compiled_sql=clean_sql,
|
|
2700
|
+
parameter_profile=param_profile,
|
|
2701
|
+
input_named_parameters=processed.input_named_parameters,
|
|
2702
|
+
applied_wrap_types=processed.applied_wrap_types,
|
|
2703
|
+
parameter_casts=cached_state.parameter_casts,
|
|
2704
|
+
operation_type=processed.operation_type,
|
|
2705
|
+
operation_profile=operation_profile,
|
|
2706
|
+
param_count=param_profile.total_count,
|
|
2707
|
+
processed_state=cached_state,
|
|
2708
|
+
needs_style_remap=needs_style_remap,
|
|
2709
|
+
positional_passthrough=positional_passthrough,
|
|
2710
|
+
simple_wire_fast_path=simple_wire_fast_path,
|
|
2711
|
+
)
|
|
2712
|
+
self._stmt_cache.set(statement.raw_sql, cached)
|
|
2713
|
+
|
|
2714
|
+
def _should_force_select(self, statement: "SQL", cursor: object) -> bool:
|
|
2715
|
+
"""Determine if a statement with unknown type should be treated as SELECT.
|
|
2716
|
+
|
|
2717
|
+
Uses driver metadata (statement_type, description/schema) as a safety net when
|
|
2718
|
+
the compiler cannot classify the operation. This remains conservative by only
|
|
2719
|
+
triggering when the operation type is "COMMAND" (generic fallback).
|
|
2720
|
+
|
|
2721
|
+
Args:
|
|
2722
|
+
statement: SQL statement being executed.
|
|
2723
|
+
cursor: Database cursor/job object that may expose metadata.
|
|
2724
|
+
|
|
2725
|
+
Returns:
|
|
2726
|
+
True when cursor metadata indicates a row-returning operation despite a
|
|
2727
|
+
generic command operation type; otherwise False.
|
|
2728
|
+
"""
|
|
2729
|
+
if statement.operation_type != "COMMAND":
|
|
2730
|
+
return False
|
|
2731
|
+
|
|
2732
|
+
if has_statement_type(cursor) and isinstance(cursor.statement_type, str):
|
|
2733
|
+
statement_type = cursor.statement_type
|
|
2734
|
+
else:
|
|
2735
|
+
statement_type = None
|
|
2736
|
+
if isinstance(statement_type, str) and statement_type.upper() == "SELECT":
|
|
2737
|
+
return True
|
|
2738
|
+
|
|
2739
|
+
if has_cursor_metadata(cursor):
|
|
2740
|
+
return bool(cursor.description)
|
|
2741
|
+
return False
|
|
2742
|
+
|
|
2743
|
+
def _split_parameters(
|
|
2744
|
+
self, parameters: "tuple[StatementParameters | StatementFilter, ...]"
|
|
2745
|
+
) -> "tuple[list[StatementFilter], list[StatementParameters]]":
|
|
2746
|
+
filters: list[StatementFilter] = []
|
|
2747
|
+
data_parameters: list[StatementParameters] = []
|
|
2748
|
+
for param in parameters:
|
|
2749
|
+
if is_statement_filter(param):
|
|
2750
|
+
filters.append(param)
|
|
2751
|
+
else:
|
|
2752
|
+
data_parameters.append(param)
|
|
2753
|
+
return filters, data_parameters
|
|
2754
|
+
|
|
2755
|
+
def _prepare_from_builder(
|
|
2756
|
+
self,
|
|
2757
|
+
builder: "QueryBuilder",
|
|
2758
|
+
data_parameters: "list[StatementParameters]",
|
|
2759
|
+
statement_config: "StatementConfig",
|
|
2760
|
+
kwargs: "dict[str, Any]",
|
|
2761
|
+
) -> "SQL":
|
|
2762
|
+
sql_statement = builder.to_statement(statement_config)
|
|
2763
|
+
if data_parameters or kwargs:
|
|
2764
|
+
merged_parameters = (
|
|
2765
|
+
(*sql_statement.positional_parameters, *tuple(data_parameters))
|
|
2766
|
+
if data_parameters
|
|
2767
|
+
else sql_statement.positional_parameters
|
|
2768
|
+
)
|
|
2769
|
+
statement_seed = sql_statement.raw_expression or sql_statement.raw_sql
|
|
2770
|
+
return SQL(statement_seed, *merged_parameters, statement_config=statement_config, **kwargs)
|
|
2771
|
+
return sql_statement
|
|
2772
|
+
|
|
2773
|
+
def _prepare_from_sql(
|
|
2774
|
+
self,
|
|
2775
|
+
sql_statement: "SQL",
|
|
2776
|
+
data_parameters: "list[StatementParameters]",
|
|
2777
|
+
statement_config: "StatementConfig",
|
|
2778
|
+
kwargs: "dict[str, Any]",
|
|
2779
|
+
) -> "SQL":
|
|
2780
|
+
declared = sql_statement.declared_parameters
|
|
2781
|
+
if data_parameters or kwargs:
|
|
2782
|
+
bound_named = sql_statement.named_parameters
|
|
2783
|
+
extra_mapping = data_parameters[0] if len(data_parameters) == 1 else None
|
|
2784
|
+
if (
|
|
2785
|
+
bound_named
|
|
2786
|
+
and not sql_statement.positional_parameters
|
|
2787
|
+
and (not data_parameters or isinstance(extra_mapping, Mapping))
|
|
2788
|
+
):
|
|
2789
|
+
merged_named = dict(bound_named)
|
|
2790
|
+
if isinstance(extra_mapping, Mapping):
|
|
2791
|
+
merged_named.update(extra_mapping)
|
|
2792
|
+
return SQL(
|
|
2793
|
+
sql_statement.raw_expression or sql_statement.raw_sql,
|
|
2794
|
+
merged_named,
|
|
2795
|
+
statement_config=statement_config,
|
|
2796
|
+
declared_parameters=declared,
|
|
2797
|
+
**kwargs,
|
|
2798
|
+
)
|
|
2799
|
+
merged_parameters = (
|
|
2800
|
+
(*sql_statement.positional_parameters, *tuple(data_parameters))
|
|
2801
|
+
if data_parameters
|
|
2802
|
+
else sql_statement.positional_parameters
|
|
2803
|
+
)
|
|
2804
|
+
statement_seed = sql_statement.raw_expression or sql_statement.raw_sql
|
|
2805
|
+
merged = SQL(
|
|
2806
|
+
statement_seed,
|
|
2807
|
+
*merged_parameters,
|
|
2808
|
+
statement_config=statement_config,
|
|
2809
|
+
declared_parameters=declared,
|
|
2810
|
+
**kwargs,
|
|
2811
|
+
)
|
|
2812
|
+
merged._named_parameters.update({
|
|
2813
|
+
key: value for key, value in bound_named.items() if key not in merged._named_parameters
|
|
2814
|
+
})
|
|
2815
|
+
return merged
|
|
2816
|
+
|
|
2817
|
+
needs_rebuild = False
|
|
2818
|
+
if statement_config.dialect and (
|
|
2819
|
+
not sql_statement.statement_config.dialect
|
|
2820
|
+
or sql_statement.statement_config.dialect != statement_config.dialect
|
|
2821
|
+
):
|
|
2822
|
+
needs_rebuild = True
|
|
2823
|
+
|
|
2824
|
+
if (
|
|
2825
|
+
sql_statement.statement_config.parameter_config.default_execution_parameter_style
|
|
2826
|
+
!= statement_config.parameter_config.default_execution_parameter_style
|
|
2827
|
+
):
|
|
2828
|
+
needs_rebuild = True
|
|
2829
|
+
|
|
2830
|
+
if needs_rebuild:
|
|
2831
|
+
statement_seed = sql_statement.raw_expression or sql_statement.raw_sql
|
|
2832
|
+
if sql_statement.is_many and sql_statement.parameters:
|
|
2833
|
+
return SQL(
|
|
2834
|
+
statement_seed,
|
|
2835
|
+
sql_statement.parameters,
|
|
2836
|
+
statement_config=statement_config,
|
|
2837
|
+
is_many=True,
|
|
2838
|
+
declared_parameters=declared,
|
|
2839
|
+
)
|
|
2840
|
+
rebuilt = SQL(
|
|
2841
|
+
statement_seed,
|
|
2842
|
+
*sql_statement.positional_parameters,
|
|
2843
|
+
statement_config=statement_config,
|
|
2844
|
+
declared_parameters=declared,
|
|
2845
|
+
)
|
|
2846
|
+
rebuilt._named_parameters.update(sql_statement.named_parameters)
|
|
2847
|
+
return rebuilt
|
|
2848
|
+
if declared:
|
|
2849
|
+
return sql_statement.copy()
|
|
2850
|
+
return sql_statement
|
|
2851
|
+
|
|
2852
|
+
def _prepare_from_string(
|
|
2853
|
+
self,
|
|
2854
|
+
statement: "Statement",
|
|
2855
|
+
data_parameters: "list[StatementParameters]",
|
|
2856
|
+
statement_config: "StatementConfig",
|
|
2857
|
+
kwargs: "dict[str, Any]",
|
|
2858
|
+
) -> "SQL":
|
|
2859
|
+
return SQL(statement, *tuple(data_parameters), statement_config=statement_config, **kwargs)
|
|
2860
|
+
|
|
2861
|
+
def _apply_filters(self, sql_statement: "SQL", filters: "list[StatementFilter]") -> "SQL":
|
|
2862
|
+
for filter_obj in filters:
|
|
2863
|
+
sql_statement = filter_obj.append_to_statement(sql_statement)
|
|
2864
|
+
return sql_statement
|
|
2865
|
+
|
|
2866
|
+
def _batch_parameters(
|
|
2867
|
+
self, parameters: "StatementParameters", statement_config: "StatementConfig"
|
|
2868
|
+
) -> "ConvertedParameters":
|
|
2869
|
+
"""Prepare a single parameter set for execute_many operations.
|
|
2870
|
+
|
|
2871
|
+
Handles parameter sets without converting the structure to array format,
|
|
2872
|
+
applying type coercion to individual values while preserving structure.
|
|
2873
|
+
|
|
2874
|
+
Args:
|
|
2875
|
+
parameters: Single parameter set (tuple, list, or dict)
|
|
2876
|
+
statement_config: Statement configuration for parameter style detection
|
|
2877
|
+
|
|
2878
|
+
Returns:
|
|
2879
|
+
Processed parameter set with individual values coerced but structure preserved
|
|
2880
|
+
"""
|
|
2881
|
+
if not parameters:
|
|
2882
|
+
return []
|
|
2883
|
+
|
|
2884
|
+
type_coercion_map = statement_config.parameter_config.type_coercion_map
|
|
2885
|
+
fallback_items = type_coercion_fallbacks(type_coercion_map)
|
|
2886
|
+
|
|
2887
|
+
if not isinstance(parameters, (dict, list, tuple)):
|
|
2888
|
+
return [apply_type_coercion(parameters, type_coercion_map, fallback_items)]
|
|
2889
|
+
|
|
2890
|
+
if isinstance(parameters, dict):
|
|
2891
|
+
result_mapping: dict[str, Any] | None = None
|
|
2892
|
+
for key, value in parameters.items():
|
|
2893
|
+
coerced_value = apply_type_coercion(value, type_coercion_map, fallback_items)
|
|
2894
|
+
if result_mapping is None:
|
|
2895
|
+
if coerced_value is value:
|
|
2896
|
+
continue
|
|
2897
|
+
result_mapping = dict(parameters)
|
|
2898
|
+
result_mapping[key] = coerced_value
|
|
2899
|
+
if result_mapping is None:
|
|
2900
|
+
return parameters
|
|
2901
|
+
return result_mapping
|
|
2902
|
+
|
|
2903
|
+
updated_params: list[Any] | None = None
|
|
2904
|
+
for idx, value in enumerate(parameters):
|
|
2905
|
+
coerced_value = apply_type_coercion(value, type_coercion_map, fallback_items)
|
|
2906
|
+
if updated_params is None:
|
|
2907
|
+
if coerced_value is value:
|
|
2908
|
+
continue
|
|
2909
|
+
updated_params = list(parameters[:idx])
|
|
2910
|
+
updated_params.append(coerced_value)
|
|
2911
|
+
|
|
2912
|
+
if updated_params is None:
|
|
2913
|
+
return parameters
|
|
2914
|
+
return tuple(updated_params) if isinstance(parameters, tuple) else updated_params
|
|
2915
|
+
|
|
2916
|
+
def _driver_parameters(
|
|
2917
|
+
self,
|
|
2918
|
+
parameters: "StatementParameters",
|
|
2919
|
+
statement_config: "StatementConfig",
|
|
2920
|
+
*,
|
|
2921
|
+
prepared_statement: Any | None = None,
|
|
2922
|
+
) -> "ConvertedParameters":
|
|
2923
|
+
"""Prepare a single parameter set for database driver consumption.
|
|
2924
|
+
|
|
2925
|
+
Args:
|
|
2926
|
+
parameters: Single parameter set in any format
|
|
2927
|
+
statement_config: Statement configuration for parameter style detection
|
|
2928
|
+
prepared_statement: Optional prepared statement containing parameter metadata
|
|
2929
|
+
|
|
2930
|
+
Returns:
|
|
2931
|
+
Processed parameter set with TypedParameter objects unwrapped and type coercion applied
|
|
2932
|
+
"""
|
|
2933
|
+
if not parameters:
|
|
2934
|
+
return []
|
|
2935
|
+
|
|
2936
|
+
type_coercion_map = statement_config.parameter_config.type_coercion_map
|
|
2937
|
+
fallback_items = type_coercion_fallbacks(type_coercion_map)
|
|
2938
|
+
coerce_value = apply_type_coercion
|
|
2939
|
+
|
|
2940
|
+
if not isinstance(parameters, (dict, list, tuple)):
|
|
2941
|
+
return [coerce_value(parameters, type_coercion_map, fallback_items)]
|
|
2942
|
+
|
|
2943
|
+
if isinstance(parameters, dict):
|
|
2944
|
+
processed_state = (
|
|
2945
|
+
prepared_statement._processed_state
|
|
2946
|
+
if isinstance(prepared_statement, SQL)
|
|
2947
|
+
and isinstance(prepared_statement._processed_state, ProcessedState)
|
|
2948
|
+
else None
|
|
2949
|
+
)
|
|
2950
|
+
if (
|
|
2951
|
+
processed_state is not None
|
|
2952
|
+
and processed_state.parameter_profile is not None
|
|
2953
|
+
and processed_state.parameter_profile.is_positional_only
|
|
2954
|
+
):
|
|
2955
|
+
aligned_values = _align_positional_mapping(parameters, processed_state.parameter_profile)
|
|
2956
|
+
return [coerce_value(value, type_coercion_map, fallback_items) for value in aligned_values]
|
|
2957
|
+
|
|
2958
|
+
param_config = statement_config.parameter_config
|
|
2959
|
+
if param_config._supports_named_execution and not (
|
|
2960
|
+
param_config._positional_default_execution and _has_only_positional_keys(parameters)
|
|
2961
|
+
):
|
|
2962
|
+
return _lazy_copy_coerce_dict(parameters, coerce_value, type_coercion_map, fallback_items)
|
|
2963
|
+
if (
|
|
2964
|
+
param_config.default_parameter_style in _POSITIONAL_DRIVER_STYLES
|
|
2965
|
+
or param_config._positional_default_execution
|
|
2966
|
+
):
|
|
2967
|
+
sorted_items = sorted(parameters.items(), key=_parameter_sort_key)
|
|
2968
|
+
return [coerce_value(value, type_coercion_map, fallback_items) for _, value in sorted_items]
|
|
2969
|
+
|
|
2970
|
+
return _lazy_copy_coerce_dict(parameters, coerce_value, type_coercion_map, fallback_items)
|
|
2971
|
+
|
|
2972
|
+
updated_params: list[Any] | None = None
|
|
2973
|
+
for idx, value in enumerate(parameters):
|
|
2974
|
+
coerced_value = coerce_value(value, type_coercion_map, fallback_items)
|
|
2975
|
+
if updated_params is None:
|
|
2976
|
+
if coerced_value is value:
|
|
2977
|
+
continue
|
|
2978
|
+
updated_params = list(parameters[:idx])
|
|
2979
|
+
updated_params.append(coerced_value)
|
|
2980
|
+
|
|
2981
|
+
if updated_params is None:
|
|
2982
|
+
if isinstance(parameters, tuple) and statement_config.parameter_config.preserve_parameter_format:
|
|
2983
|
+
return parameters
|
|
2984
|
+
return list(parameters) if isinstance(parameters, tuple) else parameters
|
|
2985
|
+
|
|
2986
|
+
if statement_config.parameter_config.preserve_parameter_format and isinstance(parameters, tuple):
|
|
2987
|
+
return tuple(updated_params)
|
|
2988
|
+
return updated_params
|
|
2989
|
+
|
|
2990
|
+
def _compiled_sql(
|
|
2991
|
+
self, statement: "SQL", statement_config: "StatementConfig", flatten_single_parameters: bool = False
|
|
2992
|
+
) -> "tuple[str, object]":
|
|
2993
|
+
"""Get compiled SQL with parameter style conversion and caching.
|
|
2994
|
+
|
|
2995
|
+
Compiles the SQL statement and applies parameter style conversion.
|
|
2996
|
+
Results are cached when caching is enabled.
|
|
2997
|
+
|
|
2998
|
+
Args:
|
|
2999
|
+
statement: SQL statement to compile
|
|
3000
|
+
statement_config: Statement configuration including parameter config and dialect
|
|
3001
|
+
flatten_single_parameters: If True, flatten single-element lists for scalar parameters
|
|
3002
|
+
|
|
3003
|
+
Returns:
|
|
3004
|
+
Tuple of (compiled_sql, parameters)
|
|
3005
|
+
"""
|
|
3006
|
+
compiled_statement, prepared_parameters = self._compiled_statement(
|
|
3007
|
+
statement, statement_config, flatten_single_parameters=flatten_single_parameters
|
|
3008
|
+
)
|
|
3009
|
+
return compiled_statement.compiled_sql, prepared_parameters
|
|
3010
|
+
|
|
3011
|
+
def _compiled_statement(
|
|
3012
|
+
self, statement: "SQL", statement_config: "StatementConfig", flatten_single_parameters: bool = False
|
|
3013
|
+
) -> "tuple[CachedStatement, object]":
|
|
3014
|
+
"""Compile SQL and return cached statement metadata plus prepared parameters.
|
|
3015
|
+
|
|
3016
|
+
FAST PATH: If the statement is already processed (compiled), we reuse
|
|
3017
|
+
its ProcessedState directly. This eliminates redundant compilation when
|
|
3018
|
+
dispatch_statement_execution() has already triggered compile().
|
|
3019
|
+
"""
|
|
3020
|
+
if statement.is_processed:
|
|
3021
|
+
if statement._compiled_from_cache:
|
|
3022
|
+
compiled_sql, execution_parameters = statement.compile()
|
|
3023
|
+
processed = statement.get_processed_state()
|
|
3024
|
+
if (
|
|
3025
|
+
statement.is_many
|
|
3026
|
+
and isinstance(execution_parameters, list)
|
|
3027
|
+
and type(self).prepare_driver_parameters is CommonDriverAttributesMixin.prepare_driver_parameters
|
|
3028
|
+
and _many_parameters_already_prepared(
|
|
3029
|
+
execution_parameters, statement_config, processed.applied_wrap_types
|
|
3030
|
+
)
|
|
3031
|
+
):
|
|
3032
|
+
prepared_parameters: Any = execution_parameters
|
|
3033
|
+
else:
|
|
3034
|
+
prepared_parameters = self.prepare_driver_parameters(
|
|
3035
|
+
execution_parameters, statement_config, is_many=statement.is_many, prepared_statement=statement
|
|
3036
|
+
)
|
|
3037
|
+
cached_statement = CachedStatement(
|
|
3038
|
+
compiled_sql=compiled_sql,
|
|
3039
|
+
parameters=cast("tuple[Any, ...] | list[Any] | dict[str, Any] | None", prepared_parameters),
|
|
3040
|
+
expression=statement._get_shared_expression(),
|
|
3041
|
+
input_named_parameters=processed.input_named_parameters,
|
|
3042
|
+
parameter_profile=processed.parameter_profile,
|
|
3043
|
+
applied_wrap_types=processed.applied_wrap_types,
|
|
3044
|
+
)
|
|
3045
|
+
self._cache_statement(statement)
|
|
3046
|
+
return cached_statement, prepared_parameters
|
|
3047
|
+
|
|
3048
|
+
processed = statement.get_processed_state()
|
|
3049
|
+
if statement._is_cache_direct:
|
|
3050
|
+
prepared_parameters = processed.execution_parameters
|
|
3051
|
+
cached_statement = CachedStatement(
|
|
3052
|
+
compiled_sql=processed.compiled_sql,
|
|
3053
|
+
parameters=prepared_parameters,
|
|
3054
|
+
expression=processed.parsed_expression,
|
|
3055
|
+
input_named_parameters=processed.input_named_parameters,
|
|
3056
|
+
parameter_profile=processed.parameter_profile,
|
|
3057
|
+
applied_wrap_types=processed.applied_wrap_types,
|
|
3058
|
+
)
|
|
3059
|
+
return cached_statement, prepared_parameters
|
|
3060
|
+
|
|
3061
|
+
if (
|
|
3062
|
+
statement.is_many
|
|
3063
|
+
and isinstance(processed.execution_parameters, list)
|
|
3064
|
+
and type(self).prepare_driver_parameters is CommonDriverAttributesMixin.prepare_driver_parameters
|
|
3065
|
+
and _many_parameters_already_prepared(
|
|
3066
|
+
processed.execution_parameters, statement_config, processed.applied_wrap_types
|
|
3067
|
+
)
|
|
3068
|
+
):
|
|
3069
|
+
prepared_parameters = processed.execution_parameters
|
|
3070
|
+
else:
|
|
3071
|
+
prepared_parameters = self.prepare_driver_parameters(
|
|
3072
|
+
processed.execution_parameters,
|
|
3073
|
+
statement_config,
|
|
3074
|
+
is_many=statement.is_many,
|
|
3075
|
+
prepared_statement=statement,
|
|
3076
|
+
)
|
|
3077
|
+
cached_statement = CachedStatement(
|
|
3078
|
+
compiled_sql=processed.compiled_sql,
|
|
3079
|
+
parameters=cast("tuple[Any, ...] | list[Any] | dict[str, Any] | None", prepared_parameters),
|
|
3080
|
+
expression=processed.parsed_expression,
|
|
3081
|
+
input_named_parameters=processed.input_named_parameters,
|
|
3082
|
+
parameter_profile=processed.parameter_profile,
|
|
3083
|
+
applied_wrap_types=processed.applied_wrap_types,
|
|
3084
|
+
)
|
|
3085
|
+
self._cache_statement(statement)
|
|
3086
|
+
return cached_statement, prepared_parameters
|
|
3087
|
+
|
|
3088
|
+
params = statement.parameters
|
|
3089
|
+
if params is not None and not isinstance(params, (list, tuple, dict)):
|
|
3090
|
+
try:
|
|
3091
|
+
materialized = list(params)
|
|
3092
|
+
statement = statement.copy(parameters=materialized)
|
|
3093
|
+
except TypeError:
|
|
3094
|
+
pass
|
|
3095
|
+
|
|
3096
|
+
cache_config = get_cache_config()
|
|
3097
|
+
dialect_key = str(statement.dialect) if statement.dialect else None
|
|
3098
|
+
cache_key = None
|
|
3099
|
+
cache = None
|
|
3100
|
+
if (
|
|
3101
|
+
cache_config.compiled_cache_enabled
|
|
3102
|
+
and statement_config.enable_caching
|
|
3103
|
+
and not statement_config._has_uncacheable_transformers
|
|
3104
|
+
):
|
|
3105
|
+
cache_key = self._compile_cache_key(statement, statement_config, flatten_single_parameters)
|
|
3106
|
+
cache = get_cache()
|
|
3107
|
+
cached_result = cache.get_statement(cache_key, dialect_key)
|
|
3108
|
+
if cached_result is not None:
|
|
3109
|
+
if __debug__:
|
|
3110
|
+
assert isinstance(cached_result, CachedStatement), (
|
|
3111
|
+
f"Statement cache corruption: expected CachedStatement, got {type(cached_result)!r}"
|
|
3112
|
+
)
|
|
3113
|
+
if not isinstance(cached_result, CachedStatement):
|
|
3114
|
+
cached_result = None
|
|
3115
|
+
if cached_result is not None:
|
|
3116
|
+
expected_guard = (
|
|
3117
|
+
statement.raw_sql,
|
|
3118
|
+
statement.is_many,
|
|
3119
|
+
statement.is_script,
|
|
3120
|
+
flatten_single_parameters,
|
|
3121
|
+
statement_config,
|
|
3122
|
+
)
|
|
3123
|
+
if cached_result._source_guard is not None and cached_result._source_guard != expected_guard:
|
|
3124
|
+
cached_result = None
|
|
3125
|
+
if cached_result is not None:
|
|
3126
|
+
parameter_profile = cached_result.parameter_profile
|
|
3127
|
+
if parameter_profile is not None:
|
|
3128
|
+
rebound_input = (
|
|
3129
|
+
_normalize_cached_parameters(
|
|
3130
|
+
statement.parameters,
|
|
3131
|
+
parameter_profile,
|
|
3132
|
+
input_named_parameters=cached_result.input_named_parameters,
|
|
3133
|
+
is_many=statement.is_many,
|
|
3134
|
+
)
|
|
3135
|
+
if parameter_profile.is_positional_only
|
|
3136
|
+
else statement.parameters
|
|
3137
|
+
)
|
|
3138
|
+
prepared_parameters = self._stmt_cache_rebind_processor.transform_cached_parameters(
|
|
3139
|
+
rebound_input,
|
|
3140
|
+
parameter_profile,
|
|
3141
|
+
statement_config.parameter_config,
|
|
3142
|
+
input_named_parameters=cached_result.input_named_parameters,
|
|
3143
|
+
is_many=statement.is_many,
|
|
3144
|
+
apply_wrap_types=cached_result.applied_wrap_types,
|
|
3145
|
+
)
|
|
3146
|
+
else:
|
|
3147
|
+
prepared_parameters = self.prepare_driver_parameters(
|
|
3148
|
+
statement.parameters, statement_config, is_many=statement.is_many, prepared_statement=statement
|
|
3149
|
+
)
|
|
3150
|
+
wire_sql = (
|
|
3151
|
+
format_wire_sqlcomment(cached_result.compiled_sql, statement_config)
|
|
3152
|
+
if statement_config.enable_sqlcommenter
|
|
3153
|
+
else cached_result.compiled_sql
|
|
3154
|
+
)
|
|
3155
|
+
updated_cached = CachedStatement(
|
|
3156
|
+
compiled_sql=wire_sql,
|
|
3157
|
+
parameters=cast("tuple[Any, ...] | list[Any] | dict[str, Any] | None", prepared_parameters),
|
|
3158
|
+
expression=cached_result.expression,
|
|
3159
|
+
input_named_parameters=cached_result.input_named_parameters,
|
|
3160
|
+
parameter_profile=parameter_profile,
|
|
3161
|
+
applied_wrap_types=cached_result.applied_wrap_types,
|
|
3162
|
+
)
|
|
3163
|
+
return updated_cached, prepared_parameters
|
|
3164
|
+
|
|
3165
|
+
compiled_sql, execution_parameters = statement.compile()
|
|
3166
|
+
processed = statement.get_processed_state()
|
|
3167
|
+
|
|
3168
|
+
if (
|
|
3169
|
+
statement.is_many
|
|
3170
|
+
and isinstance(execution_parameters, list)
|
|
3171
|
+
and type(self).prepare_driver_parameters is CommonDriverAttributesMixin.prepare_driver_parameters
|
|
3172
|
+
and _many_parameters_already_prepared(execution_parameters, statement_config, processed.applied_wrap_types)
|
|
3173
|
+
):
|
|
3174
|
+
prepared_parameters = execution_parameters
|
|
3175
|
+
else:
|
|
3176
|
+
prepared_parameters = self.prepare_driver_parameters(
|
|
3177
|
+
execution_parameters, statement_config, is_many=statement.is_many, prepared_statement=statement
|
|
3178
|
+
)
|
|
3179
|
+
|
|
3180
|
+
cached_parameters = tuple(prepared_parameters) if isinstance(prepared_parameters, list) else prepared_parameters
|
|
3181
|
+
stored_sql = strip_sqlcomment(compiled_sql) if statement_config.enable_sqlcommenter else compiled_sql
|
|
3182
|
+
cached_statement = CachedStatement(
|
|
3183
|
+
compiled_sql=compiled_sql,
|
|
3184
|
+
parameters=cast("tuple[Any, ...] | list[Any] | dict[str, Any] | None", cached_parameters),
|
|
3185
|
+
expression=statement._get_shared_expression(),
|
|
3186
|
+
input_named_parameters=processed.input_named_parameters,
|
|
3187
|
+
parameter_profile=processed.parameter_profile,
|
|
3188
|
+
applied_wrap_types=processed.applied_wrap_types,
|
|
3189
|
+
)
|
|
3190
|
+
|
|
3191
|
+
if cache_key is not None and cache is not None:
|
|
3192
|
+
source_guard = (
|
|
3193
|
+
statement.raw_sql,
|
|
3194
|
+
statement.is_many,
|
|
3195
|
+
statement.is_script,
|
|
3196
|
+
flatten_single_parameters,
|
|
3197
|
+
statement_config,
|
|
3198
|
+
)
|
|
3199
|
+
stored_statement = CachedStatement(
|
|
3200
|
+
compiled_sql=stored_sql,
|
|
3201
|
+
parameters=cached_statement.parameters,
|
|
3202
|
+
expression=cached_statement.expression,
|
|
3203
|
+
input_named_parameters=cached_statement.input_named_parameters,
|
|
3204
|
+
parameter_profile=cached_statement.parameter_profile,
|
|
3205
|
+
applied_wrap_types=cached_statement.applied_wrap_types,
|
|
3206
|
+
_source_guard=source_guard,
|
|
3207
|
+
)
|
|
3208
|
+
cache.put_statement(cache_key, stored_statement, dialect_key)
|
|
3209
|
+
|
|
3210
|
+
self._cache_statement(statement)
|
|
3211
|
+
return cached_statement, prepared_parameters
|
|
3212
|
+
|
|
3213
|
+
def _compile_cache_key(self, statement: "SQL", config: "StatementConfig", flatten_single_parameters: bool) -> str:
|
|
3214
|
+
"""Generate cache key that includes all compilation context.
|
|
3215
|
+
|
|
3216
|
+
Creates a deterministic cache key that includes all factors that affect SQL compilation,
|
|
3217
|
+
preventing cache contamination between different compilation contexts.
|
|
3218
|
+
"""
|
|
3219
|
+
statement_transformers = (
|
|
3220
|
+
tuple(_callable_cache_key(transformer) for transformer in config.statement_transformers)
|
|
3221
|
+
if config.statement_transformers
|
|
3222
|
+
else ()
|
|
3223
|
+
)
|
|
3224
|
+
context_hash = hash((
|
|
3225
|
+
hash(config.parameter_config),
|
|
3226
|
+
config.dialect,
|
|
3227
|
+
statement.is_script,
|
|
3228
|
+
statement.is_many,
|
|
3229
|
+
flatten_single_parameters,
|
|
3230
|
+
_callable_cache_key(config.output_transformer),
|
|
3231
|
+
statement_transformers,
|
|
3232
|
+
_callable_cache_key(config.parameter_config.output_transformer),
|
|
3233
|
+
_callable_cache_key(config.parameter_config.ast_transformer),
|
|
3234
|
+
bool(config.parameter_config.needs_static_script_compilation),
|
|
3235
|
+
))
|
|
3236
|
+
|
|
3237
|
+
params = statement.parameters
|
|
3238
|
+
|
|
3239
|
+
if params is None or (isinstance(params, (list, tuple, dict)) and not params):
|
|
3240
|
+
return f"compiled:{hash(statement.raw_sql)}:{context_hash}"
|
|
3241
|
+
|
|
3242
|
+
if isinstance(params, tuple) and all(isinstance(p, (int, str, bytes, bool, type(None))) for p in params):
|
|
3243
|
+
try:
|
|
3244
|
+
return (
|
|
3245
|
+
f"compiled:{hash((statement.raw_sql, params, statement.is_many, statement.is_script))}:"
|
|
3246
|
+
f"{context_hash}"
|
|
3247
|
+
)
|
|
3248
|
+
except TypeError:
|
|
3249
|
+
pass
|
|
3250
|
+
|
|
3251
|
+
if config.parameter_config.needs_static_script_compilation:
|
|
3252
|
+
params_fingerprint = value_fingerprint(params)
|
|
3253
|
+
else:
|
|
3254
|
+
params_fingerprint = structural_fingerprint(params)
|
|
3255
|
+
base_hash = hash((statement.raw_sql, params_fingerprint, statement.is_many, statement.is_script))
|
|
3256
|
+
return f"compiled:{base_hash}:{context_hash}"
|
|
3257
|
+
|
|
3258
|
+
def _count_query(self, original_sql: "SQL") -> "SQL":
|
|
3259
|
+
"""Create a COUNT query from the original SQL statement.
|
|
3260
|
+
|
|
3261
|
+
Transforms the original SELECT statement to count total rows while preserving
|
|
3262
|
+
WHERE, HAVING, and GROUP BY clauses but removing ORDER BY, LIMIT, OFFSET, and FETCH.
|
|
3263
|
+
Copies any existing ``WITH`` clause (sqlglot stores it under ``with_``).
|
|
3264
|
+
When GROUP BY, HAVING, JOINs, DISTINCT, QUALIFY, LATERALs, window/aggregate
|
|
3265
|
+
projections, or a WITH clause exist, wraps the payload in a subquery before counting.
|
|
3266
|
+
"""
|
|
3267
|
+
if not original_sql.expression:
|
|
3268
|
+
original_sql.compile()
|
|
3269
|
+
|
|
3270
|
+
if not original_sql.expression:
|
|
3271
|
+
msg = "Cannot create COUNT query from empty SQL expression"
|
|
3272
|
+
raise ImproperConfigurationError(msg)
|
|
3273
|
+
|
|
3274
|
+
expr = original_sql.expression
|
|
3275
|
+
cte: exp.Expr | None = None
|
|
3276
|
+
if isinstance(expr, exp.Expression):
|
|
3277
|
+
cte = expr.args.get("with_")
|
|
3278
|
+
if cte is not None:
|
|
3279
|
+
expr = expr.copy()
|
|
3280
|
+
expr.set("with_", None)
|
|
3281
|
+
|
|
3282
|
+
positional_only = not _has_named_input_parameters(original_sql)
|
|
3283
|
+
cte_placeholders = (
|
|
3284
|
+
_count_anonymous_placeholders(cte, count_named_as_positional=positional_only) if cte is not None else 0
|
|
3285
|
+
)
|
|
3286
|
+
|
|
3287
|
+
if isinstance(expr, exp.Select):
|
|
3288
|
+
from_clause = expr.args.get("from_")
|
|
3289
|
+
if from_clause is None:
|
|
3290
|
+
msg = (
|
|
3291
|
+
"Cannot create COUNT query: SELECT statement missing FROM clause. "
|
|
3292
|
+
"COUNT queries require a FROM clause to determine which table to count rows from."
|
|
3293
|
+
)
|
|
3294
|
+
raise ImproperConfigurationError(msg)
|
|
3295
|
+
|
|
3296
|
+
has_group = bool(expr.args.get("group"))
|
|
3297
|
+
has_joins = bool(expr.args.get("joins"))
|
|
3298
|
+
has_distinct = bool(expr.args.get("distinct"))
|
|
3299
|
+
has_qualify = bool(expr.args.get("qualify"))
|
|
3300
|
+
has_laterals = bool(expr.args.get("laterals"))
|
|
3301
|
+
has_having = bool(expr.args.get("having"))
|
|
3302
|
+
has_agg_or_window = any(
|
|
3303
|
+
isinstance(node, (exp.AggFunc, exp.Window))
|
|
3304
|
+
for select_expr in expr.expressions
|
|
3305
|
+
for node in select_expr.walk()
|
|
3306
|
+
)
|
|
3307
|
+
needs_subquery = (
|
|
3308
|
+
has_group
|
|
3309
|
+
or has_joins
|
|
3310
|
+
or cte is not None
|
|
3311
|
+
or has_distinct
|
|
3312
|
+
or has_qualify
|
|
3313
|
+
or has_laterals
|
|
3314
|
+
or has_having
|
|
3315
|
+
or has_agg_or_window
|
|
3316
|
+
)
|
|
3317
|
+
limit_clause = expr.args.get("limit")
|
|
3318
|
+
has_leading_top = _has_leading_top_limit(expr, original_sql)
|
|
3319
|
+
top_placeholders = (
|
|
3320
|
+
_count_anonymous_placeholders(limit_clause, count_named_as_positional=positional_only)
|
|
3321
|
+
if has_leading_top
|
|
3322
|
+
else 0
|
|
3323
|
+
)
|
|
3324
|
+
select_stripped = (
|
|
3325
|
+
0
|
|
3326
|
+
if needs_subquery
|
|
3327
|
+
else sum(
|
|
3328
|
+
_count_anonymous_placeholders(select_expr, count_named_as_positional=positional_only)
|
|
3329
|
+
for select_expr in expr.expressions
|
|
3330
|
+
)
|
|
3331
|
+
)
|
|
3332
|
+
leading_stripped = top_placeholders + select_stripped
|
|
3333
|
+
trailing_clauses = (
|
|
3334
|
+
("order", "offset", "fetch") if has_leading_top else ("order", "limit", "offset", "fetch")
|
|
3335
|
+
)
|
|
3336
|
+
trailing_stripped = sum(
|
|
3337
|
+
_count_anonymous_placeholders(expr.args.get(clause), count_named_as_positional=positional_only)
|
|
3338
|
+
for clause in trailing_clauses
|
|
3339
|
+
)
|
|
3340
|
+
pagination_params = _pagination_names(original_sql, include_select_expressions=not needs_subquery)
|
|
3341
|
+
if needs_subquery:
|
|
3342
|
+
subquery_expr = expr.copy()
|
|
3343
|
+
subquery_expr.set("order", None)
|
|
3344
|
+
subquery_expr.set("limit", None)
|
|
3345
|
+
subquery_expr.set("offset", None)
|
|
3346
|
+
subquery_expr.set("fetch", None)
|
|
3347
|
+
subquery = subquery_expr.subquery(alias="grouped_data", copy=False)
|
|
3348
|
+
count_expr = exp.select(exp.Count(this=exp.Star()), copy=False).from_(subquery, copy=False)
|
|
3349
|
+
else:
|
|
3350
|
+
count_expr = exp.select(exp.Count(this=exp.Star()), copy=False)
|
|
3351
|
+
count_expr.set("from_", from_clause.copy())
|
|
3352
|
+
if expr.args.get("where"):
|
|
3353
|
+
count_expr = count_expr.where(cast("exp.Expression", expr.args.get("where")).copy(), copy=False)
|
|
3354
|
+
|
|
3355
|
+
if cte is not None:
|
|
3356
|
+
count_expr.set("with_", cte.copy())
|
|
3357
|
+
return _build_rewritten_sql(
|
|
3358
|
+
count_expr,
|
|
3359
|
+
original_sql,
|
|
3360
|
+
pagination_params=pagination_params,
|
|
3361
|
+
leading_stripped=leading_stripped,
|
|
3362
|
+
trailing_stripped=trailing_stripped,
|
|
3363
|
+
leading_offset=cte_placeholders if cte_placeholders and leading_stripped else 0,
|
|
3364
|
+
)
|
|
3365
|
+
|
|
3366
|
+
leading_stripped = 0
|
|
3367
|
+
trailing_stripped = sum(
|
|
3368
|
+
_count_anonymous_placeholders(expr.args.get(clause), count_named_as_positional=positional_only)
|
|
3369
|
+
for clause in ("order", "limit", "offset", "fetch")
|
|
3370
|
+
)
|
|
3371
|
+
pagination_params = _pagination_names(original_sql, include_select_expressions=False)
|
|
3372
|
+
count_source = cast("exp.Query", expr.copy())
|
|
3373
|
+
count_source.set("order", None)
|
|
3374
|
+
count_source.set("limit", None)
|
|
3375
|
+
count_source.set("offset", None)
|
|
3376
|
+
count_source.set("fetch", None)
|
|
3377
|
+
subquery = count_source.subquery(alias="total_query", copy=False)
|
|
3378
|
+
count_expr = exp.select(exp.Count(this=exp.Star()), copy=False).from_(subquery, copy=False)
|
|
3379
|
+
if cte is not None:
|
|
3380
|
+
count_expr.set("with_", cte.copy())
|
|
3381
|
+
return _build_rewritten_sql(
|
|
3382
|
+
count_expr,
|
|
3383
|
+
original_sql,
|
|
3384
|
+
pagination_params=pagination_params,
|
|
3385
|
+
leading_stripped=leading_stripped,
|
|
3386
|
+
trailing_stripped=trailing_stripped,
|
|
3387
|
+
)
|
|
3388
|
+
|
|
3389
|
+
def _with_total_count(self, original_sql: "SQL", alias: str = "_total_count") -> "SQL":
|
|
3390
|
+
"""Add a COUNT(*) OVER() column to the SELECT statement for inline total counts.
|
|
3391
|
+
|
|
3392
|
+
This method modifies the SELECT to include a window function that returns
|
|
3393
|
+
the total count of rows matching the WHERE clause, before LIMIT/OFFSET is applied.
|
|
3394
|
+
Useful for pagination where both data and total count are needed in a single query.
|
|
3395
|
+
|
|
3396
|
+
Args:
|
|
3397
|
+
original_sql: The original SQL statement (must be a SELECT).
|
|
3398
|
+
alias: Column alias for the count (default "_total_count").
|
|
3399
|
+
|
|
3400
|
+
Returns:
|
|
3401
|
+
New SQL object with the COUNT(*) OVER() column added.
|
|
3402
|
+
|
|
3403
|
+
Raises:
|
|
3404
|
+
ImproperConfigurationError: If the SQL is not a SELECT statement.
|
|
3405
|
+
"""
|
|
3406
|
+
if not original_sql.expression:
|
|
3407
|
+
original_sql.compile()
|
|
3408
|
+
|
|
3409
|
+
if not original_sql.expression:
|
|
3410
|
+
msg = "Cannot add COUNT OVER to empty SQL expression"
|
|
3411
|
+
raise ImproperConfigurationError(msg)
|
|
3412
|
+
|
|
3413
|
+
expr = original_sql.expression
|
|
3414
|
+
if isinstance(expr, exp.SetOperation):
|
|
3415
|
+
cte = expr.args.get("with_")
|
|
3416
|
+
expr_copy = expr.copy()
|
|
3417
|
+
if cte:
|
|
3418
|
+
expr_copy.set("with_", None)
|
|
3419
|
+
subquery = expr_copy.subquery(alias="__set_op_subq", copy=False)
|
|
3420
|
+
modified_expr = exp.select(exp.Column(this=exp.Star()), copy=False).from_(subquery, copy=False)
|
|
3421
|
+
count_window = exp.Window(this=exp.Count(this=exp.Star()))
|
|
3422
|
+
aliased_count = exp.alias_(count_window, alias, copy=False)
|
|
3423
|
+
modified_expr = modified_expr.select(aliased_count, copy=False)
|
|
3424
|
+
if cte:
|
|
3425
|
+
modified_expr.set("with_", cte.copy())
|
|
3426
|
+
elif isinstance(expr, exp.Select):
|
|
3427
|
+
modified_expr = expr.copy()
|
|
3428
|
+
count_window = exp.Window(this=exp.Count(this=exp.Star()))
|
|
3429
|
+
aliased_count = exp.alias_(count_window, alias, copy=False)
|
|
3430
|
+
modified_expr = modified_expr.select(aliased_count, copy=False)
|
|
3431
|
+
else:
|
|
3432
|
+
msg = "COUNT(*) OVER() can only be added to SELECT or set operation statements"
|
|
3433
|
+
raise ImproperConfigurationError(msg)
|
|
3434
|
+
|
|
3435
|
+
return _build_rewritten_sql(
|
|
3436
|
+
modified_expr, original_sql, pagination_params=set(), leading_stripped=0, trailing_stripped=0
|
|
3437
|
+
)
|
|
3438
|
+
|
|
3439
|
+
def _extract_total_from_rows(self, rows: "list[Any]") -> "tuple[list[dict[str, Any]], int]":
|
|
3440
|
+
"""Extract window-count totals and remove the synthetic total column from rows."""
|
|
3441
|
+
if not rows:
|
|
3442
|
+
return ([], 0)
|
|
3443
|
+
|
|
3444
|
+
clean_rows: list[dict[str, Any]] = []
|
|
3445
|
+
total = 0
|
|
3446
|
+
total_found = False
|
|
3447
|
+
for row in rows:
|
|
3448
|
+
if is_dict_row(row):
|
|
3449
|
+
row_dict: dict[str, Any] = row
|
|
3450
|
+
elif is_mapping_like(row):
|
|
3451
|
+
row_dict = dict(row)
|
|
3452
|
+
elif has_asdict_method(row):
|
|
3453
|
+
row_dict = row._asdict()
|
|
3454
|
+
else:
|
|
3455
|
+
clean_rows.append({})
|
|
3456
|
+
continue
|
|
3457
|
+
if not total_found:
|
|
3458
|
+
total_val = row_dict.get("_total_count")
|
|
3459
|
+
if total_val is None:
|
|
3460
|
+
total_val = row_dict.get("_TOTAL_COUNT")
|
|
3461
|
+
if total_val is not None:
|
|
3462
|
+
total = int(total_val)
|
|
3463
|
+
total_found = True
|
|
3464
|
+
clean_rows.append({k: v for k, v in row_dict.items() if k not in {"_total_count", "_TOTAL_COUNT"}})
|
|
3465
|
+
return (clean_rows, total)
|
|
3466
|
+
|
|
3467
|
+
def _coerce_arrow_table(self, source: "ArrowResult | Any") -> "ArrowTable":
|
|
3468
|
+
"""Coerce various sources to a PyArrow Table."""
|
|
3469
|
+
return coerce_arrow_table(source)
|
|
3470
|
+
|
|
3471
|
+
@staticmethod
|
|
3472
|
+
def _coerce_arrow_batches(
|
|
3473
|
+
source: "ArrowResult | Any", *, batch_size: int = 65_536
|
|
3474
|
+
) -> "tuple[list[str], abc.Iterator[ArrowRecordBatch]]":
|
|
3475
|
+
"""Coerce an Arrow source into column names and a lazy RecordBatch iterator."""
|
|
3476
|
+
return coerce_arrow_batches(source, batch_size=batch_size)
|
|
3477
|
+
|
|
3478
|
+
@staticmethod
|
|
3479
|
+
def _arrow_batch_to_rows(batch: "ArrowRecordBatch", columns: "list[str] | None" = None) -> "list[tuple[Any, ...]]":
|
|
3480
|
+
"""Convert a single Arrow RecordBatch into row tuples."""
|
|
3481
|
+
return arrow_batch_to_rows(batch, columns)
|
|
3482
|
+
|
|
3483
|
+
@staticmethod
|
|
3484
|
+
def _encode_arrow_batch_pg_binary(
|
|
3485
|
+
batch: "ArrowRecordBatch",
|
|
3486
|
+
*,
|
|
3487
|
+
columns: "abc.Sequence[str] | None" = None,
|
|
3488
|
+
vector_columns: frozenset[str] = frozenset(),
|
|
3489
|
+
jsonb_columns: frozenset[str] = frozenset(),
|
|
3490
|
+
include_header: bool = False,
|
|
3491
|
+
include_trailer: bool = False,
|
|
3492
|
+
) -> bytes:
|
|
3493
|
+
"""Encode an Arrow RecordBatch into PostgreSQL COPY BINARY format."""
|
|
3494
|
+
return encode_arrow_batch_pg_binary(
|
|
3495
|
+
batch,
|
|
3496
|
+
columns=columns,
|
|
3497
|
+
vector_columns=vector_columns,
|
|
3498
|
+
jsonb_columns=jsonb_columns,
|
|
3499
|
+
include_header=include_header,
|
|
3500
|
+
include_trailer=include_trailer,
|
|
3501
|
+
)
|
|
3502
|
+
|
|
3503
|
+
@staticmethod
|
|
3504
|
+
def _iter_pgcopy_binary_chunks(
|
|
3505
|
+
source: "ArrowResult | Any",
|
|
3506
|
+
*,
|
|
3507
|
+
columns: "abc.Sequence[str] | None" = None,
|
|
3508
|
+
batch_size: int = 65_536,
|
|
3509
|
+
chunk_bytes: int = 8_388_608,
|
|
3510
|
+
vector_columns: frozenset[str] = frozenset(),
|
|
3511
|
+
jsonb_columns: frozenset[str] = frozenset(),
|
|
3512
|
+
metrics: "dict[str, int] | None" = None,
|
|
3513
|
+
) -> "abc.Iterator[bytes]":
|
|
3514
|
+
"""Yield PostgreSQL COPY BINARY chunks from an Arrow source in bounded memory."""
|
|
3515
|
+
return iter_pgcopy_binary_chunks(
|
|
3516
|
+
source,
|
|
3517
|
+
columns=columns,
|
|
3518
|
+
batch_size=batch_size,
|
|
3519
|
+
chunk_bytes=chunk_bytes,
|
|
3520
|
+
vector_columns=vector_columns,
|
|
3521
|
+
jsonb_columns=jsonb_columns,
|
|
3522
|
+
metrics=metrics,
|
|
3523
|
+
)
|
|
3524
|
+
|
|
3525
|
+
@staticmethod
|
|
3526
|
+
def _iter_pgcopy_binary_chunks_async(
|
|
3527
|
+
source: "ArrowResult | Any",
|
|
3528
|
+
*,
|
|
3529
|
+
columns: "abc.Sequence[str] | None" = None,
|
|
3530
|
+
batch_size: int = 65_536,
|
|
3531
|
+
chunk_bytes: int = 8_388_608,
|
|
3532
|
+
vector_columns: frozenset[str] = frozenset(),
|
|
3533
|
+
jsonb_columns: frozenset[str] = frozenset(),
|
|
3534
|
+
metrics: "dict[str, int] | None" = None,
|
|
3535
|
+
) -> Any:
|
|
3536
|
+
"""Return an async iterator of PostgreSQL COPY BINARY chunks from an Arrow source."""
|
|
3537
|
+
return iter_pgcopy_binary_chunks_async(
|
|
3538
|
+
source,
|
|
3539
|
+
columns=columns,
|
|
3540
|
+
batch_size=batch_size,
|
|
3541
|
+
chunk_bytes=chunk_bytes,
|
|
3542
|
+
vector_columns=vector_columns,
|
|
3543
|
+
jsonb_columns=jsonb_columns,
|
|
3544
|
+
metrics=metrics,
|
|
3545
|
+
)
|
|
3546
|
+
|
|
3547
|
+
@staticmethod
|
|
3548
|
+
def _arrow_table_to_rows(
|
|
3549
|
+
table: "ArrowTable", columns: "list[str] | None" = None
|
|
3550
|
+
) -> "tuple[list[str], list[tuple[Any, ...]]]":
|
|
3551
|
+
"""Convert Arrow table to column names and row tuples."""
|
|
3552
|
+
return arrow_table_to_rows(table, columns)
|
|
3553
|
+
|
|
3554
|
+
@staticmethod
|
|
3555
|
+
def _arrow_rows_need_preparation(table: "ArrowTable | ArrowRecordBatch") -> bool:
|
|
3556
|
+
"""Return whether Arrow rows may contain nested values needing preparation."""
|
|
3557
|
+
return arrow_table_needs_parameter_preparation(table)
|
|
3558
|
+
|
|
3559
|
+
def _prepare_records_for_arrow(
|
|
3560
|
+
self, records: "abc.Sequence[abc.Mapping[str, Any]] | abc.Sequence[abc.Sequence[Any]]"
|
|
3561
|
+
) -> "abc.Sequence[abc.Mapping[str, Any]] | abc.Sequence[abc.Sequence[Any]]":
|
|
3562
|
+
"""Prepare records before Arrow schema inference."""
|
|
3563
|
+
return records
|
|
3564
|
+
|
|
3565
|
+
@staticmethod
|
|
3566
|
+
def _ingest_telemetry(table: "ArrowTable", *, format_label: str = "arrow") -> "StorageTelemetry":
|
|
3567
|
+
"""Build telemetry dict from Arrow table statistics."""
|
|
3568
|
+
return build_ingest_telemetry(table, format_label=format_label)
|
|
3569
|
+
|
|
3570
|
+
@staticmethod
|
|
3571
|
+
def _ingest_telemetry_from_batches(
|
|
3572
|
+
rows_processed: int,
|
|
3573
|
+
bytes_processed: int,
|
|
3574
|
+
*,
|
|
3575
|
+
duration_s: float | None = None,
|
|
3576
|
+
format_label: str = "arrow",
|
|
3577
|
+
read_duration_s: float | None = None,
|
|
3578
|
+
encode_duration_s: float | None = None,
|
|
3579
|
+
write_duration_s: float | None = None,
|
|
3580
|
+
commit_duration_s: float | None = None,
|
|
3581
|
+
shards_processed: int | None = None,
|
|
3582
|
+
shards_skipped: int | None = None,
|
|
3583
|
+
wal_bytes: int | None = None,
|
|
3584
|
+
) -> "StorageTelemetry":
|
|
3585
|
+
"""Build telemetry dict from accumulated batch metrics."""
|
|
3586
|
+
return ingest_telemetry_from_batches(
|
|
3587
|
+
rows_processed,
|
|
3588
|
+
bytes_processed,
|
|
3589
|
+
duration_s=duration_s,
|
|
3590
|
+
format_label=format_label,
|
|
3591
|
+
read_duration_s=read_duration_s,
|
|
3592
|
+
encode_duration_s=encode_duration_s,
|
|
3593
|
+
write_duration_s=write_duration_s,
|
|
3594
|
+
commit_duration_s=commit_duration_s,
|
|
3595
|
+
shards_processed=shards_processed,
|
|
3596
|
+
shards_skipped=shards_skipped,
|
|
3597
|
+
wal_bytes=wal_bytes,
|
|
3598
|
+
)
|
|
3599
|
+
|
|
3600
|
+
@staticmethod
|
|
3601
|
+
def _records_to_arrow_table(
|
|
3602
|
+
records: "abc.Sequence[abc.Mapping[str, Any]] | abc.Sequence[abc.Sequence[Any]]", columns: "list[str] | None"
|
|
3603
|
+
) -> "ArrowTable":
|
|
3604
|
+
"""Normalize dict or positional records into a PyArrow table for ingest."""
|
|
3605
|
+
return records_to_arrow_table(records, columns)
|
|
3606
|
+
|
|
3607
|
+
def _attach_partition_telemetry(
|
|
3608
|
+
self, telemetry: "StorageTelemetry", partitioner: "dict[str, object] | None"
|
|
3609
|
+
) -> None:
|
|
3610
|
+
"""Attach partitioner info to telemetry dict."""
|
|
3611
|
+
attach_partition_telemetry(telemetry, partitioner)
|
|
3612
|
+
|
|
3613
|
+
def _storage_job(
|
|
3614
|
+
self, produced: "StorageTelemetry", provided: "StorageTelemetry | None" = None, *, status: str = "completed"
|
|
3615
|
+
) -> "StorageBridgeJob":
|
|
3616
|
+
"""Create a StorageBridgeJob from telemetry data."""
|
|
3617
|
+
return create_storage_job(produced, provided, status=status)
|
|
3618
|
+
|
|
3619
|
+
def _execute_staged_load_sync(
|
|
3620
|
+
self,
|
|
3621
|
+
table: str,
|
|
3622
|
+
source: "ArrowResult | Any",
|
|
3623
|
+
*,
|
|
3624
|
+
raw_loader: "abc.Callable[..., StorageBridgeJob]",
|
|
3625
|
+
partitioner: "dict[str, object] | None" = None,
|
|
3626
|
+
overwrite: bool = False,
|
|
3627
|
+
telemetry: "StorageTelemetry | None" = None,
|
|
3628
|
+
stage_table: "bool | str | None" = None,
|
|
3629
|
+
conflict_keys: "abc.Sequence[str] | None" = None,
|
|
3630
|
+
on_conflict: Literal["update", "nothing"] = "update",
|
|
3631
|
+
exclude_update_columns: "abc.Sequence[str] | None" = None,
|
|
3632
|
+
drop_stage_table: bool = True,
|
|
3633
|
+
drop_indexes: bool = False,
|
|
3634
|
+
concurrent_indexes: bool = False,
|
|
3635
|
+
type_casts: "abc.Mapping[str, str] | None" = None,
|
|
3636
|
+
) -> "StorageBridgeJob":
|
|
3637
|
+
"""Execute a staged or index-free bulk load synchronously."""
|
|
3638
|
+
return execute_staged_load_sync(
|
|
3639
|
+
self,
|
|
3640
|
+
table,
|
|
3641
|
+
source,
|
|
3642
|
+
raw_loader=raw_loader,
|
|
3643
|
+
partitioner=partitioner,
|
|
3644
|
+
overwrite=overwrite,
|
|
3645
|
+
telemetry=telemetry,
|
|
3646
|
+
stage_table=stage_table,
|
|
3647
|
+
conflict_keys=conflict_keys,
|
|
3648
|
+
on_conflict=on_conflict,
|
|
3649
|
+
exclude_update_columns=exclude_update_columns,
|
|
3650
|
+
drop_stage_table=drop_stage_table,
|
|
3651
|
+
drop_indexes=drop_indexes,
|
|
3652
|
+
concurrent_indexes=concurrent_indexes,
|
|
3653
|
+
type_casts=type_casts,
|
|
3654
|
+
)
|
|
3655
|
+
|
|
3656
|
+
async def _execute_staged_load_async(
|
|
3657
|
+
self,
|
|
3658
|
+
table: str,
|
|
3659
|
+
source: "ArrowResult | Any",
|
|
3660
|
+
*,
|
|
3661
|
+
raw_loader: "abc.Callable[..., Any]",
|
|
3662
|
+
partitioner: "dict[str, object] | None" = None,
|
|
3663
|
+
overwrite: bool = False,
|
|
3664
|
+
telemetry: "StorageTelemetry | None" = None,
|
|
3665
|
+
stage_table: "bool | str | None" = None,
|
|
3666
|
+
conflict_keys: "abc.Sequence[str] | None" = None,
|
|
3667
|
+
on_conflict: Literal["update", "nothing"] = "update",
|
|
3668
|
+
exclude_update_columns: "abc.Sequence[str] | None" = None,
|
|
3669
|
+
drop_stage_table: bool = True,
|
|
3670
|
+
drop_indexes: bool = False,
|
|
3671
|
+
concurrent_indexes: bool = False,
|
|
3672
|
+
type_casts: "abc.Mapping[str, str] | None" = None,
|
|
3673
|
+
) -> "StorageBridgeJob":
|
|
3674
|
+
"""Execute a staged or index-free bulk load asynchronously."""
|
|
3675
|
+
return await execute_staged_load_async(
|
|
3676
|
+
self,
|
|
3677
|
+
table,
|
|
3678
|
+
source,
|
|
3679
|
+
raw_loader=raw_loader,
|
|
3680
|
+
partitioner=partitioner,
|
|
3681
|
+
overwrite=overwrite,
|
|
3682
|
+
telemetry=telemetry,
|
|
3683
|
+
stage_table=stage_table,
|
|
3684
|
+
conflict_keys=conflict_keys,
|
|
3685
|
+
on_conflict=on_conflict,
|
|
3686
|
+
exclude_update_columns=exclude_update_columns,
|
|
3687
|
+
drop_stage_table=drop_stage_table,
|
|
3688
|
+
drop_indexes=drop_indexes,
|
|
3689
|
+
concurrent_indexes=concurrent_indexes,
|
|
3690
|
+
type_casts=type_casts,
|
|
3691
|
+
)
|
|
3692
|
+
|
|
3693
|
+
_execute_load_from_storage_sync = staticmethod(execute_load_from_storage_sync)
|
|
3694
|
+
_execute_load_from_storage_async = staticmethod(execute_load_from_storage_async)
|
|
3695
|
+
|
|
3696
|
+
|
|
3697
|
+
_PASSTHROUGH_TYPES_MAX_SIZE: Final[int] = 256
|
|
3698
|
+
_PASSTHROUGH_TYPES_CACHE: "dict[int, tuple[dict[type, Any], int, set[type]]]" = {}
|
|
3699
|
+
|
|
3700
|
+
|
|
3701
|
+
_CACHE_HIT_HOOKS: Final[tuple[str, ...]] = (
|
|
3702
|
+
"_execute_cache_hit",
|
|
3703
|
+
"_execute_cache_hit_with_cursor",
|
|
3704
|
+
"build_cached_select_result",
|
|
3705
|
+
"collect_rows",
|
|
3706
|
+
"handle_database_exceptions",
|
|
3707
|
+
"resolve_rowcount",
|
|
3708
|
+
"with_cursor",
|
|
3709
|
+
)
|
|
3710
|
+
|
|
3711
|
+
|
|
3712
|
+
def cache_hit_hooks_unchanged(driver_type: type, owner: type) -> bool:
|
|
3713
|
+
"""Report whether ``driver_type`` runs cached statements exactly as ``owner`` does.
|
|
3714
|
+
|
|
3715
|
+
A cache-hit executor replaces the driver methods a cached statement passes through, so a
|
|
3716
|
+
subclass that overrides any of them keeps its overrides only on the method path.
|
|
3717
|
+
|
|
3718
|
+
Args:
|
|
3719
|
+
driver_type: Concrete driver class being constructed.
|
|
3720
|
+
owner: Adapter driver class the executor was written for.
|
|
3721
|
+
|
|
3722
|
+
Returns:
|
|
3723
|
+
True when ``driver_type`` is ``owner`` or inherits every cache-hit method from it unchanged.
|
|
3724
|
+
"""
|
|
3725
|
+
if driver_type is owner:
|
|
3726
|
+
return True
|
|
3727
|
+
return all(getattr(driver_type, name, None) is getattr(owner, name, None) for name in _CACHE_HIT_HOOKS)
|
|
3728
|
+
|
|
3729
|
+
|
|
3730
|
+
def _has_active_observability(driver: "CommonDriverAttributesMixin") -> bool:
|
|
3731
|
+
"""Return whether the driver's runtime has hooks, observers, or spans to notify.
|
|
3732
|
+
|
|
3733
|
+
The driver caches the answer and recomputes it when a lifecycle hook is registered on the runtime.
|
|
3734
|
+
"""
|
|
3735
|
+
runtime = driver._observability
|
|
3736
|
+
if runtime is None:
|
|
3737
|
+
return False
|
|
3738
|
+
if runtime.hook_generation != driver._observability_generation:
|
|
3739
|
+
driver._refresh_statement_cache_state()
|
|
3740
|
+
return driver._has_active_observability
|
|
3741
|
+
|
|
3742
|
+
|
|
3743
|
+
def run_cached_execution(
|
|
3744
|
+
driver: "CommonDriverAttributesMixin", statement: str, params: "tuple[Any, ...] | list[Any] | dict[str, Any]"
|
|
3745
|
+
) -> "SQLResult | Awaitable[SQLResult | None] | None":
|
|
3746
|
+
"""Execute a raw SQL string through the driver's compiled-statement cache.
|
|
3747
|
+
|
|
3748
|
+
A driver that registers a cache-hit executor has it called with the connection, the raw SQL,
|
|
3749
|
+
the parameters, the cached query, the statement configuration, and the driver's executor state.
|
|
3750
|
+
An executor that returns ``None`` declines the call, which then runs through the driver's
|
|
3751
|
+
``_execute_cache_hit`` method.
|
|
3752
|
+
|
|
3753
|
+
Args:
|
|
3754
|
+
driver: Driver owning the statement cache and connection.
|
|
3755
|
+
statement: Raw SQL string.
|
|
3756
|
+
params: Query parameters.
|
|
3757
|
+
|
|
3758
|
+
Returns:
|
|
3759
|
+
SQLResult (sync) or Awaitable[SQLResult] (async) if cache hit, None if cache miss.
|
|
3760
|
+
"""
|
|
3761
|
+
if not driver._stmt_cache_enabled:
|
|
3762
|
+
return None
|
|
3763
|
+
cached = driver._stmt_cache.get(statement)
|
|
3764
|
+
if cached is None or cached.param_count != len(params):
|
|
3765
|
+
return None
|
|
3766
|
+
|
|
3767
|
+
config = driver.statement_config
|
|
3768
|
+
param_config = config.parameter_config
|
|
3769
|
+
if cached.simple_wire_fast_path:
|
|
3770
|
+
is_mapping = _is_mapping_parameters(params)
|
|
3771
|
+
if not is_mapping:
|
|
3772
|
+
needs_rebind = False
|
|
3773
|
+
if params:
|
|
3774
|
+
holder = getattr(driver, "_cache_holder", None)
|
|
3775
|
+
passthrough = holder.passthrough_types if holder is not None else None
|
|
3776
|
+
param_values = _cache_param_values(params)
|
|
3777
|
+
needs_rebind = parameter_values_need_processing(
|
|
3778
|
+
param_values, param_config.type_coercion_map, passthrough_types=passthrough
|
|
3779
|
+
)
|
|
3780
|
+
if not needs_rebind:
|
|
3781
|
+
if _has_active_observability(driver):
|
|
3782
|
+
return driver._execute_cache_hit_observed(statement, params, cached)
|
|
3783
|
+
executor = driver._cache_hit_executor
|
|
3784
|
+
if executor is None:
|
|
3785
|
+
return driver._execute_cache_hit(statement, params, cached)
|
|
3786
|
+
outcome = executor(driver.connection, statement, params, cached, config, driver._cache_hit_state)
|
|
3787
|
+
if outcome is None:
|
|
3788
|
+
return driver._execute_cache_hit(statement, params, cached)
|
|
3789
|
+
return outcome
|
|
3790
|
+
elif param_config.ast_transformer is not None:
|
|
3791
|
+
return None
|
|
3792
|
+
|
|
3793
|
+
needs_rebind = (not cached.positional_passthrough) or _is_mapping_parameters(params)
|
|
3794
|
+
if not needs_rebind and params:
|
|
3795
|
+
holder = getattr(driver, "_cache_holder", None)
|
|
3796
|
+
passthrough = holder.passthrough_types if holder is not None else None
|
|
3797
|
+
param_values = _cache_param_values(params)
|
|
3798
|
+
needs_rebind = parameter_values_need_processing(
|
|
3799
|
+
param_values, param_config.type_coercion_map, passthrough_types=passthrough
|
|
3800
|
+
)
|
|
3801
|
+
|
|
3802
|
+
if not needs_rebind and not config._has_output_transformer:
|
|
3803
|
+
effective_cached = cached
|
|
3804
|
+
if config.enable_sqlcommenter:
|
|
3805
|
+
wire_sql = driver._format_wire_sql(cached.compiled_sql)
|
|
3806
|
+
if wire_sql != cached.compiled_sql:
|
|
3807
|
+
effective_cached = CachedQuery(
|
|
3808
|
+
compiled_sql=wire_sql,
|
|
3809
|
+
parameter_profile=cached.parameter_profile,
|
|
3810
|
+
input_named_parameters=cached.input_named_parameters,
|
|
3811
|
+
applied_wrap_types=cached.applied_wrap_types,
|
|
3812
|
+
parameter_casts=cached.parameter_casts,
|
|
3813
|
+
operation_type=cached.operation_type,
|
|
3814
|
+
operation_profile=cached.operation_profile,
|
|
3815
|
+
param_count=cached.param_count,
|
|
3816
|
+
processed_state=cached.processed_state,
|
|
3817
|
+
needs_style_remap=cached.needs_style_remap,
|
|
3818
|
+
positional_passthrough=cached.positional_passthrough,
|
|
3819
|
+
simple_wire_fast_path=False,
|
|
3820
|
+
)
|
|
3821
|
+
if _has_active_observability(driver):
|
|
3822
|
+
return driver._execute_cache_hit_observed(statement, params, effective_cached)
|
|
3823
|
+
executor = driver._cache_hit_executor
|
|
3824
|
+
if executor is None:
|
|
3825
|
+
return driver._execute_cache_hit(statement, params, effective_cached)
|
|
3826
|
+
outcome = executor(driver.connection, statement, params, effective_cached, config, driver._cache_hit_state)
|
|
3827
|
+
if outcome is None:
|
|
3828
|
+
return driver._execute_cache_hit(statement, params, effective_cached)
|
|
3829
|
+
return outcome
|
|
3830
|
+
|
|
3831
|
+
if needs_rebind:
|
|
3832
|
+
rebound_params = driver.stmt_cache_rebind(params, cached)
|
|
3833
|
+
params_are_simple = False
|
|
3834
|
+
else:
|
|
3835
|
+
rebound_params = params
|
|
3836
|
+
params_are_simple = True
|
|
3837
|
+
|
|
3838
|
+
compiled_sql = driver._format_wire_sql(cached.compiled_sql)
|
|
3839
|
+
output_transformer = config.output_transformer
|
|
3840
|
+
if output_transformer is not None:
|
|
3841
|
+
compiled_sql, rebound_params = output_transformer(compiled_sql, rebound_params)
|
|
3842
|
+
params_are_simple = False
|
|
3843
|
+
|
|
3844
|
+
prepared = driver._cached_statement(
|
|
3845
|
+
statement, params, cached, rebound_params, params_are_simple=params_are_simple, compiled_sql=compiled_sql
|
|
3846
|
+
)
|
|
3847
|
+
if _has_active_observability(driver):
|
|
3848
|
+
return driver._execute_cached_statement_observed(prepared, compiled_sql, rebound_params, cached.operation_type)
|
|
3849
|
+
return driver._execute_cached_statement(prepared)
|
|
3850
|
+
|
|
3851
|
+
|
|
3852
|
+
def parameter_values_need_processing(
|
|
3853
|
+
values: "tuple[Any, ...] | list[Any]",
|
|
3854
|
+
type_coercion_map: "dict[type, Any] | None",
|
|
3855
|
+
fallback_items: "tuple[tuple[type, Any], ...] | None" = None,
|
|
3856
|
+
passthrough_types: "set[type] | None" = None,
|
|
3857
|
+
) -> bool:
|
|
3858
|
+
if not values:
|
|
3859
|
+
return False
|
|
3860
|
+
if not type_coercion_map:
|
|
3861
|
+
if len(values) == 1:
|
|
3862
|
+
return type(values[0]) is TypedParameter
|
|
3863
|
+
return any(type(value) is TypedParameter for value in values)
|
|
3864
|
+
if fallback_items is not None:
|
|
3865
|
+
dispatcher = type_coercion_dispatcher(fallback_items)
|
|
3866
|
+
for value in values:
|
|
3867
|
+
value_type = type(value)
|
|
3868
|
+
if value_type is TypedParameter or value_type in type_coercion_map:
|
|
3869
|
+
return True
|
|
3870
|
+
if dispatcher.resolve_type(value_type) is not None:
|
|
3871
|
+
return True
|
|
3872
|
+
return False
|
|
3873
|
+
active_passthrough = passthrough_types if passthrough_types is not None else _passthrough_types(type_coercion_map)
|
|
3874
|
+
for value in values:
|
|
3875
|
+
value_type = type(value)
|
|
3876
|
+
if value_type in active_passthrough:
|
|
3877
|
+
continue
|
|
3878
|
+
if value_type is TypedParameter or value_type in type_coercion_map:
|
|
3879
|
+
return True
|
|
3880
|
+
if type_coercion_dispatcher(type_coercion_fallbacks(type_coercion_map)).resolve_type(value_type) is not None:
|
|
3881
|
+
return True
|
|
3882
|
+
if len(active_passthrough) < _PASSTHROUGH_TYPES_MAX_SIZE:
|
|
3883
|
+
active_passthrough.add(value_type)
|
|
3884
|
+
return False
|
|
3885
|
+
|
|
3886
|
+
|
|
3887
|
+
def _passthrough_types(type_coercion_map: "dict[type, Any]") -> "set[type]":
|
|
3888
|
+
"""Return the value types already proven to need no coercion under ``type_coercion_map``.
|
|
3889
|
+
|
|
3890
|
+
The set is remembered per map object and discarded when the map's size changes.
|
|
3891
|
+
"""
|
|
3892
|
+
map_id = id(type_coercion_map)
|
|
3893
|
+
map_len = len(type_coercion_map)
|
|
3894
|
+
cached = _PASSTHROUGH_TYPES_CACHE.get(map_id)
|
|
3895
|
+
if cached is not None and cached[0] is type_coercion_map and cached[1] == map_len:
|
|
3896
|
+
return cached[2]
|
|
3897
|
+
if len(_PASSTHROUGH_TYPES_CACHE) >= _PASSTHROUGH_TYPES_MAX_SIZE:
|
|
3898
|
+
_PASSTHROUGH_TYPES_CACHE.clear()
|
|
3899
|
+
passthrough_types: set[type] = set()
|
|
3900
|
+
_PASSTHROUGH_TYPES_CACHE[map_id] = (type_coercion_map, map_len, passthrough_types)
|
|
3901
|
+
return passthrough_types
|
|
3902
|
+
|
|
3903
|
+
|
|
3904
|
+
def parameter_value_needs_processing(
|
|
3905
|
+
value: object,
|
|
3906
|
+
type_coercion_map: "dict[type, Any] | None",
|
|
3907
|
+
fallback_items: "tuple[tuple[type, Any], ...] | None" = None,
|
|
3908
|
+
) -> bool:
|
|
3909
|
+
if type(value) is TypedParameter:
|
|
3910
|
+
return True
|
|
3911
|
+
if not type_coercion_map:
|
|
3912
|
+
return False
|
|
3913
|
+
|
|
3914
|
+
value_type = type(value)
|
|
3915
|
+
if value_type in type_coercion_map:
|
|
3916
|
+
return True
|
|
3917
|
+
if fallback_items is None:
|
|
3918
|
+
fallback_items = type_coercion_fallbacks(type_coercion_map)
|
|
3919
|
+
return type_coercion_dispatcher(fallback_items).resolve_type(value_type) is not None
|
|
3920
|
+
|
|
3921
|
+
|
|
3922
|
+
def _resolve_fast_params(
|
|
3923
|
+
parameters: "tuple[Any, ...]", kwargs: "dict[str, Any]"
|
|
3924
|
+
) -> "tuple[Any, ...] | list[Any] | dict[str, Any] | None":
|
|
3925
|
+
"""Normalize execute(*parameters, **kwargs) arguments for fast-path cache lookup."""
|
|
3926
|
+
if kwargs:
|
|
3927
|
+
if not parameters:
|
|
3928
|
+
return kwargs
|
|
3929
|
+
return None
|
|
3930
|
+
param_len = len(parameters)
|
|
3931
|
+
if param_len == 0:
|
|
3932
|
+
return ()
|
|
3933
|
+
if param_len == 1:
|
|
3934
|
+
first = parameters[0]
|
|
3935
|
+
if isinstance(first, (tuple, list, dict)):
|
|
3936
|
+
return first
|
|
3937
|
+
if is_statement_filter(first):
|
|
3938
|
+
return None
|
|
3939
|
+
return parameters
|
|
3940
|
+
for item in parameters:
|
|
3941
|
+
if is_statement_filter(item) or isinstance(item, (tuple, list, dict)):
|
|
3942
|
+
return None
|
|
3943
|
+
return parameters
|
|
3944
|
+
|
|
3945
|
+
|
|
3946
|
+
def _raise_database_exception(
|
|
3947
|
+
exc_handler: "AsyncExceptionHandler | SyncExceptionHandler", exc: Exception | None
|
|
3948
|
+
) -> None:
|
|
3949
|
+
"""Raise any mapped database exception captured by a deferred exception handler."""
|
|
3950
|
+
pending_exception = exc_handler.pending_exception
|
|
3951
|
+
if pending_exception is not None:
|
|
3952
|
+
if exc is not None:
|
|
3953
|
+
pending_exception.__cause__ = exc
|
|
3954
|
+
raise pending_exception from exc
|
|
3955
|
+
if pending_exception.__cause__ is not None:
|
|
3956
|
+
raise pending_exception
|
|
3957
|
+
raise pending_exception from None
|
|
3958
|
+
if exc is not None:
|
|
3959
|
+
raise exc
|
|
3960
|
+
|
|
3961
|
+
|
|
3962
|
+
def _parameter_sort_key(item: "tuple[str, object]") -> float:
|
|
3963
|
+
key = item[0]
|
|
3964
|
+
if key.isdigit():
|
|
3965
|
+
return float(int(key))
|
|
3966
|
+
if len(key) > 1 and key[0] in {"$", ":", "?"} and key[1:].isdigit():
|
|
3967
|
+
return float(int(key[1:]))
|
|
3968
|
+
if key.startswith("param_"):
|
|
3969
|
+
suffix = key[6:]
|
|
3970
|
+
if suffix.isdigit():
|
|
3971
|
+
return float(int(suffix))
|
|
3972
|
+
return float("inf")
|
|
3973
|
+
|
|
3974
|
+
|
|
3975
|
+
def _is_mapping_parameters(params: Any) -> bool:
|
|
3976
|
+
return type(params) is dict or (type(params) not in (tuple, list) and isinstance(params, Mapping))
|
|
3977
|
+
|
|
3978
|
+
|
|
3979
|
+
def _is_positional_parameter_key(key: str) -> bool:
|
|
3980
|
+
if key.isdigit():
|
|
3981
|
+
return True
|
|
3982
|
+
if len(key) > 1 and key[0] in {"$", ":", "?"} and key[1:].isdigit():
|
|
3983
|
+
return True
|
|
3984
|
+
return key.startswith("param_") and key[6:].isdigit()
|
|
3985
|
+
|
|
3986
|
+
|
|
3987
|
+
def _has_only_positional_keys(parameters: "dict[str, Any]") -> bool:
|
|
3988
|
+
for key in parameters: # noqa: SIM110
|
|
3989
|
+
if not _is_positional_parameter_key(key):
|
|
3990
|
+
return False
|
|
3991
|
+
return True
|
|
3992
|
+
|
|
3993
|
+
|
|
3994
|
+
def _take_mapping_value(
|
|
3995
|
+
param: Any, mapping: "Mapping[str, Any]", positional_keys: "list[str]", consumed: "set[str]"
|
|
3996
|
+
) -> "tuple[Any, bool]":
|
|
3997
|
+
for candidate in (param.name, param.placeholder_text, f"param_{param.ordinal}", str(param.ordinal + 1)):
|
|
3998
|
+
if candidate and candidate in mapping:
|
|
3999
|
+
consumed.add(candidate)
|
|
4000
|
+
return mapping[candidate], True
|
|
4001
|
+
for key in positional_keys:
|
|
4002
|
+
if key not in consumed:
|
|
4003
|
+
consumed.add(key)
|
|
4004
|
+
return mapping[key], True
|
|
4005
|
+
return None, False
|
|
4006
|
+
|
|
4007
|
+
|
|
4008
|
+
def _align_positional_mapping(mapping: "Mapping[str, Any]", parameter_profile: Any) -> "tuple[Any, ...]":
|
|
4009
|
+
positional_keys = list(mapping.keys())
|
|
4010
|
+
consumed: set[str] = set()
|
|
4011
|
+
values: list[Any] = []
|
|
4012
|
+
for param in parameter_profile.parameters:
|
|
4013
|
+
value, found = _take_mapping_value(param, mapping, positional_keys, consumed)
|
|
4014
|
+
if not found:
|
|
4015
|
+
return tuple(mapping.values())
|
|
4016
|
+
values.append(value)
|
|
4017
|
+
return tuple(values)
|
|
4018
|
+
|
|
4019
|
+
|
|
4020
|
+
def _mapping_row_to_profile_names(mapping: "Mapping[str, Any]", parameter_profile: Any) -> "dict[str, Any]":
|
|
4021
|
+
positional_keys = list(mapping.keys())
|
|
4022
|
+
consumed: set[str] = set()
|
|
4023
|
+
remapped: dict[str, Any] = {}
|
|
4024
|
+
for param in parameter_profile.parameters:
|
|
4025
|
+
target_key = param.name or f"param_{param.ordinal}"
|
|
4026
|
+
if target_key in remapped:
|
|
4027
|
+
continue
|
|
4028
|
+
value, found = _take_mapping_value(param, mapping, positional_keys, consumed)
|
|
4029
|
+
if found:
|
|
4030
|
+
remapped[target_key] = value
|
|
4031
|
+
return remapped
|
|
4032
|
+
|
|
4033
|
+
|
|
4034
|
+
def _normalize_cached_mapping_row(
|
|
4035
|
+
mapping: "Mapping[str, Any]", parameter_profile: Any, input_named_parameters: "tuple[str, ...]"
|
|
4036
|
+
) -> Any:
|
|
4037
|
+
if input_named_parameters:
|
|
4038
|
+
for name in input_named_parameters:
|
|
4039
|
+
if name not in mapping:
|
|
4040
|
+
return _mapping_row_to_profile_names(mapping, parameter_profile)
|
|
4041
|
+
return mapping
|
|
4042
|
+
return _align_positional_mapping(mapping, parameter_profile)
|
|
4043
|
+
|
|
4044
|
+
|
|
4045
|
+
def _normalize_cached_parameters(
|
|
4046
|
+
params: Any, parameter_profile: Any, *, input_named_parameters: "tuple[str, ...]", is_many: bool
|
|
4047
|
+
) -> Any:
|
|
4048
|
+
if params is None or parameter_profile is None or not parameter_profile.is_positional_only:
|
|
4049
|
+
return params
|
|
4050
|
+
if not is_many:
|
|
4051
|
+
if _is_mapping_parameters(params):
|
|
4052
|
+
return _normalize_cached_mapping_row(params, parameter_profile, input_named_parameters)
|
|
4053
|
+
return params
|
|
4054
|
+
if isinstance(params, (list, tuple)) and params:
|
|
4055
|
+
has_mapping = False
|
|
4056
|
+
for row in params:
|
|
4057
|
+
if _is_mapping_parameters(row):
|
|
4058
|
+
has_mapping = True
|
|
4059
|
+
break
|
|
4060
|
+
if not has_mapping:
|
|
4061
|
+
return params
|
|
4062
|
+
updated_rows = [
|
|
4063
|
+
_normalize_cached_mapping_row(row, parameter_profile, input_named_parameters)
|
|
4064
|
+
if _is_mapping_parameters(row)
|
|
4065
|
+
else row
|
|
4066
|
+
for row in params
|
|
4067
|
+
]
|
|
4068
|
+
return tuple(updated_rows) if isinstance(params, tuple) else updated_rows
|
|
4069
|
+
return params
|
|
4070
|
+
|
|
4071
|
+
|
|
4072
|
+
def _has_leading_top_limit(expr: "exp.Select", original_sql: "SQL") -> bool:
|
|
4073
|
+
limit_clause = expr.args.get("limit")
|
|
4074
|
+
if not isinstance(limit_clause, exp.Limit):
|
|
4075
|
+
return False
|
|
4076
|
+
dialect = str(original_sql.statement_config.dialect) if original_sql.statement_config.dialect else None
|
|
4077
|
+
normalized_dialect = dialect.lower() if dialect else ""
|
|
4078
|
+
sql_text = original_sql.raw_sql or expr.sql(dialect=dialect)
|
|
4079
|
+
if not sql_text:
|
|
4080
|
+
return normalized_dialect in _TOP_LIMIT_DIALECTS
|
|
4081
|
+
try:
|
|
4082
|
+
tokens = sqlglot.tokenize(sql_text, read=dialect)
|
|
4083
|
+
except SqlglotError:
|
|
4084
|
+
return normalized_dialect in _TOP_LIMIT_DIALECTS
|
|
4085
|
+
depth = 0
|
|
4086
|
+
saw_top = False
|
|
4087
|
+
saw_limit = False
|
|
4088
|
+
for token in tokens:
|
|
4089
|
+
if token.token_type is TokenType.L_PAREN:
|
|
4090
|
+
depth += 1
|
|
4091
|
+
elif token.token_type is TokenType.R_PAREN:
|
|
4092
|
+
if depth > 0:
|
|
4093
|
+
depth -= 1
|
|
4094
|
+
elif depth == 0:
|
|
4095
|
+
if token.token_type is TokenType.TOP:
|
|
4096
|
+
saw_top = True
|
|
4097
|
+
elif token.token_type is TokenType.LIMIT:
|
|
4098
|
+
saw_limit = True
|
|
4099
|
+
if saw_top and not saw_limit:
|
|
4100
|
+
return True
|
|
4101
|
+
if saw_limit:
|
|
4102
|
+
return False
|
|
4103
|
+
return normalized_dialect in _TOP_LIMIT_DIALECTS
|
|
4104
|
+
|
|
4105
|
+
|
|
4106
|
+
def _lazy_copy_coerce_dict(
|
|
4107
|
+
parameters: "dict[str, Any]",
|
|
4108
|
+
coerce_value: Any,
|
|
4109
|
+
type_coercion_map: Any,
|
|
4110
|
+
fallback_items: "tuple[tuple[type, Any], ...]",
|
|
4111
|
+
) -> "dict[str, Any]":
|
|
4112
|
+
result: dict[str, Any] | None = None
|
|
4113
|
+
for key, value in parameters.items():
|
|
4114
|
+
coerced_value = coerce_value(value, type_coercion_map, fallback_items)
|
|
4115
|
+
if result is None:
|
|
4116
|
+
if coerced_value is value:
|
|
4117
|
+
continue
|
|
4118
|
+
result = dict(parameters)
|
|
4119
|
+
result[key] = coerced_value
|
|
4120
|
+
if result is None:
|
|
4121
|
+
return parameters
|
|
4122
|
+
return result
|
|
4123
|
+
|
|
4124
|
+
|
|
4125
|
+
def _cache_param_values(params: "tuple[Any, ...] | list[Any] | dict[str, Any]") -> "tuple[Any, ...] | list[Any]":
|
|
4126
|
+
if isinstance(params, dict):
|
|
4127
|
+
return tuple(params.values())
|
|
4128
|
+
return params
|
|
4129
|
+
|
|
4130
|
+
|
|
4131
|
+
def _clone_processed_state(
|
|
4132
|
+
processed: "ProcessedState", operation_profile: "OperationProfile | None" = None, compiled_sql: str | None = None
|
|
4133
|
+
) -> "ProcessedState":
|
|
4134
|
+
return ProcessedState(
|
|
4135
|
+
compiled_sql=processed.compiled_sql if compiled_sql is None else compiled_sql,
|
|
4136
|
+
execution_parameters=processed.execution_parameters,
|
|
4137
|
+
parsed_expression=processed.parsed_expression,
|
|
4138
|
+
operation_type=processed.operation_type,
|
|
4139
|
+
input_named_parameters=processed.input_named_parameters,
|
|
4140
|
+
applied_wrap_types=processed.applied_wrap_types,
|
|
4141
|
+
filter_hash=processed.filter_hash,
|
|
4142
|
+
parameter_fingerprint=processed.parameter_fingerprint,
|
|
4143
|
+
parameter_casts=dict(processed.parameter_casts),
|
|
4144
|
+
validation_errors=processed.validation_errors.copy(),
|
|
4145
|
+
parameter_profile=processed.parameter_profile,
|
|
4146
|
+
operation_profile=operation_profile if operation_profile is not None else processed.operation_profile,
|
|
4147
|
+
is_many=False,
|
|
4148
|
+
)
|
|
4149
|
+
|
|
4150
|
+
|
|
4151
|
+
def _named_placeholder_name(node: "exp.Expr") -> "str | None":
|
|
4152
|
+
if isinstance(node, exp.Placeholder):
|
|
4153
|
+
return str(node.this) if node.this is not None else None
|
|
4154
|
+
if isinstance(node, exp.Parameter):
|
|
4155
|
+
inner = node.this
|
|
4156
|
+
if isinstance(inner, (exp.Var, exp.Identifier)) and inner.name and not inner.name.isdigit():
|
|
4157
|
+
return inner.name
|
|
4158
|
+
return None
|
|
4159
|
+
|
|
4160
|
+
|
|
4161
|
+
def _numeric_parameter_ordinal(node: "exp.Expr") -> "int | None":
|
|
4162
|
+
if isinstance(node, exp.Placeholder):
|
|
4163
|
+
name = node.this
|
|
4164
|
+
if isinstance(name, str) and name.isdigit():
|
|
4165
|
+
return int(name)
|
|
4166
|
+
return None
|
|
4167
|
+
if isinstance(node, exp.Parameter):
|
|
4168
|
+
inner = node.this
|
|
4169
|
+
if isinstance(inner, exp.Literal) and inner.name.isdigit():
|
|
4170
|
+
return int(inner.name)
|
|
4171
|
+
return None
|
|
4172
|
+
|
|
4173
|
+
|
|
4174
|
+
def _is_positional_placeholder(node: "exp.Expr", *, count_named_as_positional: bool = False) -> bool:
|
|
4175
|
+
if isinstance(node, exp.Placeholder):
|
|
4176
|
+
return count_named_as_positional or node.this is None
|
|
4177
|
+
return _numeric_parameter_ordinal(node) is not None
|
|
4178
|
+
|
|
4179
|
+
|
|
4180
|
+
def _count_anonymous_placeholders(node: "exp.Expr | None", *, count_named_as_positional: bool = False) -> int:
|
|
4181
|
+
"""Count anonymous positional placeholders within a SQLGlot expression subtree."""
|
|
4182
|
+
if node is None:
|
|
4183
|
+
return 0
|
|
4184
|
+
count = 0
|
|
4185
|
+
for child in node.walk():
|
|
4186
|
+
if _is_positional_placeholder(child, count_named_as_positional=count_named_as_positional):
|
|
4187
|
+
count += 1
|
|
4188
|
+
return count
|
|
4189
|
+
|
|
4190
|
+
|
|
4191
|
+
def _pagination_names_in_expression(expression: "exp.Expr", *, include_select_expressions: bool = False) -> "set[str]":
|
|
4192
|
+
"""Extract named placeholder names from stripped clauses of an expression that do not appear in retained clauses.
|
|
4193
|
+
|
|
4194
|
+
Args:
|
|
4195
|
+
expression: A SQLGlot expression to scan.
|
|
4196
|
+
include_select_expressions: Whether top-level SELECT expressions are also stripped.
|
|
4197
|
+
|
|
4198
|
+
Returns:
|
|
4199
|
+
Set of placeholder names that only appear in stripped clauses.
|
|
4200
|
+
"""
|
|
4201
|
+
stripped_placeholders: set[str] = set()
|
|
4202
|
+
stripped_nodes: list[exp.Expr] = []
|
|
4203
|
+
|
|
4204
|
+
if include_select_expressions and isinstance(expression, exp.Select):
|
|
4205
|
+
stripped_nodes.extend(expression.expressions)
|
|
4206
|
+
|
|
4207
|
+
for clause_name in ("order", "limit", "offset", "fetch"):
|
|
4208
|
+
clause = expression.args.get(clause_name)
|
|
4209
|
+
if isinstance(clause, exp.Expr):
|
|
4210
|
+
stripped_nodes.append(clause)
|
|
4211
|
+
|
|
4212
|
+
for clause_node in stripped_nodes:
|
|
4213
|
+
for node in clause_node.walk():
|
|
4214
|
+
name = _named_placeholder_name(node)
|
|
4215
|
+
if name is not None:
|
|
4216
|
+
stripped_placeholders.add(name)
|
|
4217
|
+
|
|
4218
|
+
if not stripped_placeholders:
|
|
4219
|
+
return set()
|
|
4220
|
+
|
|
4221
|
+
retained_expr = expression.copy()
|
|
4222
|
+
if include_select_expressions and isinstance(retained_expr, exp.Select):
|
|
4223
|
+
retained_expr.set("expressions", [])
|
|
4224
|
+
for clause_name in ("order", "limit", "offset", "fetch"):
|
|
4225
|
+
retained_expr.set(clause_name, None)
|
|
4226
|
+
|
|
4227
|
+
retained_placeholders: set[str] = set()
|
|
4228
|
+
for node in retained_expr.walk():
|
|
4229
|
+
name = _named_placeholder_name(node)
|
|
4230
|
+
if name is not None:
|
|
4231
|
+
retained_placeholders.add(name)
|
|
4232
|
+
return stripped_placeholders - retained_placeholders
|
|
4233
|
+
|
|
4234
|
+
|
|
4235
|
+
def _has_stripped_placeholder(stmt_expr: "exp.Expr", *, include_select_expressions: bool) -> bool:
|
|
4236
|
+
for clause_name in ("order", "limit", "offset", "fetch"):
|
|
4237
|
+
clause = stmt_expr.args.get(clause_name)
|
|
4238
|
+
if isinstance(clause, exp.Expr):
|
|
4239
|
+
for node in clause.walk():
|
|
4240
|
+
if isinstance(node, (exp.Placeholder, exp.Parameter)):
|
|
4241
|
+
return True
|
|
4242
|
+
if include_select_expressions and isinstance(stmt_expr, exp.Select):
|
|
4243
|
+
for select_expr in stmt_expr.expressions:
|
|
4244
|
+
for node in select_expr.walk():
|
|
4245
|
+
if isinstance(node, (exp.Placeholder, exp.Parameter)):
|
|
4246
|
+
return True
|
|
4247
|
+
return False
|
|
4248
|
+
|
|
4249
|
+
|
|
4250
|
+
def _has_named_placeholder(stmt_expr: "exp.Expr") -> bool:
|
|
4251
|
+
return any(_named_placeholder_name(node) is not None for node in stmt_expr.walk())
|
|
4252
|
+
|
|
4253
|
+
|
|
4254
|
+
def _has_named_input_parameters(original_sql: "SQL") -> bool:
|
|
4255
|
+
if original_sql.named_parameters:
|
|
4256
|
+
return True
|
|
4257
|
+
processed_state = original_sql._processed_state # pyright: ignore[reportPrivateUsage]
|
|
4258
|
+
if not isinstance(processed_state, ProcessedState) or not processed_state.input_named_parameters:
|
|
4259
|
+
return False
|
|
4260
|
+
return any(not name.isdigit() for name in processed_state.input_named_parameters)
|
|
4261
|
+
|
|
4262
|
+
|
|
4263
|
+
def _realign_numeric_parameters(
|
|
4264
|
+
rewritten_expr: "exp.Expr", positional: "list[Any] | tuple[Any, ...]"
|
|
4265
|
+
) -> "tuple[Any, ...] | None":
|
|
4266
|
+
numeric_nodes: list[tuple[exp.Parameter | exp.Placeholder, int]] = []
|
|
4267
|
+
ordinals: set[int] = set()
|
|
4268
|
+
for node in rewritten_expr.walk():
|
|
4269
|
+
ordinal = _numeric_parameter_ordinal(node)
|
|
4270
|
+
if ordinal is not None:
|
|
4271
|
+
if ordinal < 1 or ordinal > len(positional):
|
|
4272
|
+
return None
|
|
4273
|
+
numeric_nodes.append((cast("exp.Parameter | exp.Placeholder", node), ordinal))
|
|
4274
|
+
ordinals.add(ordinal)
|
|
4275
|
+
if not numeric_nodes:
|
|
4276
|
+
return None
|
|
4277
|
+
ordered = sorted(ordinals)
|
|
4278
|
+
mapping = {old_index: new_index for new_index, old_index in enumerate(ordered, start=1)}
|
|
4279
|
+
for node, old_index in numeric_nodes:
|
|
4280
|
+
new_index = mapping[old_index]
|
|
4281
|
+
if new_index != old_index:
|
|
4282
|
+
node.set("this", str(new_index) if isinstance(node, exp.Placeholder) else exp.Literal.number(new_index))
|
|
4283
|
+
return tuple(positional[old_index - 1] for old_index in ordered)
|
|
4284
|
+
|
|
4285
|
+
|
|
4286
|
+
def _pagination_names(original_sql: "SQL", *, include_select_expressions: bool = False) -> "set[str]":
|
|
4287
|
+
"""Extract placeholder names from stripped pagination/projection clauses.
|
|
4288
|
+
|
|
4289
|
+
Args:
|
|
4290
|
+
original_sql: The SQL object to extract pagination placeholders from.
|
|
4291
|
+
include_select_expressions: Whether top-level SELECT expressions are also stripped.
|
|
4292
|
+
|
|
4293
|
+
Returns:
|
|
4294
|
+
Set of placeholder names found exclusively in stripped clauses.
|
|
4295
|
+
"""
|
|
4296
|
+
has_input_named = _has_named_input_parameters(original_sql)
|
|
4297
|
+
stmt_expr = original_sql.statement_expression
|
|
4298
|
+
if stmt_expr is not None:
|
|
4299
|
+
placeholders = _pagination_names_in_expression(stmt_expr, include_select_expressions=include_select_expressions)
|
|
4300
|
+
if placeholders:
|
|
4301
|
+
return placeholders
|
|
4302
|
+
if _has_named_placeholder(stmt_expr) or not has_input_named:
|
|
4303
|
+
return set()
|
|
4304
|
+
if not _has_stripped_placeholder(stmt_expr, include_select_expressions=include_select_expressions):
|
|
4305
|
+
return set()
|
|
4306
|
+
|
|
4307
|
+
raw_sql = original_sql.raw_sql
|
|
4308
|
+
if not raw_sql:
|
|
4309
|
+
return set()
|
|
4310
|
+
|
|
4311
|
+
try:
|
|
4312
|
+
dialect = str(original_sql.statement_config.dialect) if original_sql.statement_config.dialect else None
|
|
4313
|
+
try:
|
|
4314
|
+
parsed = sqlglot.parse_one(raw_sql, read=dialect)
|
|
4315
|
+
except ParseError:
|
|
4316
|
+
parsed = sqlglot.parse_one(raw_sql)
|
|
4317
|
+
return _pagination_names_in_expression(parsed, include_select_expressions=include_select_expressions)
|
|
4318
|
+
except Exception:
|
|
4319
|
+
return set()
|
|
4320
|
+
|
|
4321
|
+
|
|
4322
|
+
def _parameters_for_repeated_names(original_sql: "SQL", excluded_names: "set[str]") -> "tuple[Any, ...] | None":
|
|
4323
|
+
"""Return occurrence-ordered parameters when a rewritten expression uses repeated named parameters."""
|
|
4324
|
+
processed_state = original_sql._processed_state # pyright: ignore[reportPrivateUsage]
|
|
4325
|
+
if not isinstance(processed_state, ProcessedState):
|
|
4326
|
+
return None
|
|
4327
|
+
|
|
4328
|
+
input_names = processed_state.input_named_parameters
|
|
4329
|
+
if not input_names:
|
|
4330
|
+
return None
|
|
4331
|
+
|
|
4332
|
+
retained_names = tuple(name for name in input_names if name not in excluded_names)
|
|
4333
|
+
if len(retained_names) == len(set(retained_names)):
|
|
4334
|
+
return None
|
|
4335
|
+
|
|
4336
|
+
execution_parameters = processed_state.execution_parameters
|
|
4337
|
+
if not isinstance(execution_parameters, (list, tuple)) or len(execution_parameters) != len(input_names):
|
|
4338
|
+
return None
|
|
4339
|
+
|
|
4340
|
+
return tuple(
|
|
4341
|
+
value for name, value in zip(input_names, execution_parameters, strict=False) if name not in excluded_names
|
|
4342
|
+
)
|
|
4343
|
+
|
|
4344
|
+
|
|
4345
|
+
_LINE_COMMENT_MARKERS: Final[dict[str, str]] = {"snowflake": "//", "mysql": "#", "mariadb": "#"}
|
|
4346
|
+
|
|
4347
|
+
|
|
4348
|
+
def _skip_leading_line_comments(sql: str, dialect: "str | None") -> str:
|
|
4349
|
+
"""Drop leading dialect-specific line comments that the keyword scanner does not recognize."""
|
|
4350
|
+
marker = _LINE_COMMENT_MARKERS.get(dialect or "")
|
|
4351
|
+
if marker is None:
|
|
4352
|
+
return sql
|
|
4353
|
+
text = sql.lstrip()
|
|
4354
|
+
while text.startswith(marker):
|
|
4355
|
+
newline = text.find("\n")
|
|
4356
|
+
if newline < 0:
|
|
4357
|
+
return ""
|
|
4358
|
+
text = text[newline + 1 :].lstrip()
|
|
4359
|
+
return text
|
|
4360
|
+
|
|
4361
|
+
|
|
4362
|
+
def _build_rewritten_sql(
|
|
4363
|
+
rewritten_expr: "exp.Expr",
|
|
4364
|
+
original_sql: "SQL",
|
|
4365
|
+
*,
|
|
4366
|
+
pagination_params: "set[str]",
|
|
4367
|
+
leading_stripped: int,
|
|
4368
|
+
trailing_stripped: int,
|
|
4369
|
+
leading_offset: int = 0,
|
|
4370
|
+
) -> "SQL":
|
|
4371
|
+
"""Construct a rewritten SQL object with stripped positional or named parameters."""
|
|
4372
|
+
positional = original_sql.positional_parameters
|
|
4373
|
+
processed_state = original_sql._processed_state # pyright: ignore[reportPrivateUsage]
|
|
4374
|
+
exec_params = processed_state.execution_parameters if isinstance(processed_state, ProcessedState) else None
|
|
4375
|
+
numeric_source = positional or (exec_params if isinstance(exec_params, (list, tuple)) else None)
|
|
4376
|
+
if numeric_source:
|
|
4377
|
+
realigned = _realign_numeric_parameters(rewritten_expr, numeric_source)
|
|
4378
|
+
if realigned is not None:
|
|
4379
|
+
return SQL(rewritten_expr, *realigned, statement_config=original_sql.statement_config)
|
|
4380
|
+
|
|
4381
|
+
retained_positional: Any = positional
|
|
4382
|
+
if positional and (leading_stripped or trailing_stripped):
|
|
4383
|
+
end_idx = len(positional) - trailing_stripped if trailing_stripped else len(positional)
|
|
4384
|
+
if leading_offset:
|
|
4385
|
+
retained_positional = (
|
|
4386
|
+
*positional[:leading_offset],
|
|
4387
|
+
*positional[leading_offset + leading_stripped : end_idx],
|
|
4388
|
+
)
|
|
4389
|
+
else:
|
|
4390
|
+
retained_positional = positional[leading_stripped:end_idx]
|
|
4391
|
+
|
|
4392
|
+
if original_sql.named_parameters:
|
|
4393
|
+
materialized_parameters = _parameters_for_repeated_names(original_sql, pagination_params)
|
|
4394
|
+
if materialized_parameters is not None:
|
|
4395
|
+
return SQL(rewritten_expr, *materialized_parameters, statement_config=original_sql.statement_config)
|
|
4396
|
+
input_names = processed_state.input_named_parameters if isinstance(processed_state, ProcessedState) else ()
|
|
4397
|
+
filtered_named_params: dict[str, Any] = {}
|
|
4398
|
+
for name in input_names:
|
|
4399
|
+
if (
|
|
4400
|
+
name not in pagination_params
|
|
4401
|
+
and name in original_sql.named_parameters
|
|
4402
|
+
and name not in filtered_named_params
|
|
4403
|
+
):
|
|
4404
|
+
filtered_named_params[name] = original_sql.named_parameters[name]
|
|
4405
|
+
for key, value in original_sql.named_parameters.items():
|
|
4406
|
+
if key not in pagination_params and key not in filtered_named_params:
|
|
4407
|
+
filtered_named_params[key] = value
|
|
4408
|
+
return SQL(
|
|
4409
|
+
rewritten_expr,
|
|
4410
|
+
*retained_positional,
|
|
4411
|
+
statement_config=original_sql.statement_config,
|
|
4412
|
+
**filtered_named_params,
|
|
4413
|
+
)
|
|
4414
|
+
|
|
4415
|
+
return SQL(rewritten_expr, *retained_positional, statement_config=original_sql.statement_config)
|
|
4416
|
+
|
|
4417
|
+
|
|
4418
|
+
def _callable_cache_key(func: Any) -> Any:
|
|
4419
|
+
"""Return a stable cache key component for callables.
|
|
4420
|
+
|
|
4421
|
+
Args:
|
|
4422
|
+
func: Callable or None.
|
|
4423
|
+
|
|
4424
|
+
Returns:
|
|
4425
|
+
Tuple identifying the callable, or None for missing callables.
|
|
4426
|
+
"""
|
|
4427
|
+
if func is None:
|
|
4428
|
+
return None
|
|
4429
|
+
module = getattr(func, "__module__", None)
|
|
4430
|
+
qualname = getattr(func, "__qualname__", type(func).__name__)
|
|
4431
|
+
if _is_uncacheable_callable(func):
|
|
4432
|
+
return (module, qualname, "dynamic", next(_DYNAMIC_CALLABLE_COUNTER))
|
|
4433
|
+
if isinstance(func, (FunctionType, BuiltinFunctionType)):
|
|
4434
|
+
return (module, qualname, id(func))
|
|
4435
|
+
return (module, qualname, hash(func))
|
|
4436
|
+
|
|
4437
|
+
|
|
4438
|
+
def _apply_declared_optional_defaults(declared: "tuple[ParameterDeclaration, ...]", supplied: "dict[str, Any]") -> None:
|
|
4439
|
+
"""Bind missing optional named params as SQL NULL."""
|
|
4440
|
+
for declaration in declared:
|
|
4441
|
+
if not declaration.required and declaration.name not in supplied:
|
|
4442
|
+
supplied[declaration.name] = None
|
|
4443
|
+
|
|
4444
|
+
|
|
4445
|
+
def _check_declared_named_row(declared: "tuple[ParameterDeclaration, ...]", supplied: "dict[str, Any]") -> None:
|
|
4446
|
+
"""Validate a single named-parameter mapping against declared params.
|
|
4447
|
+
|
|
4448
|
+
Required params must be present. Missing optional params are bound as
|
|
4449
|
+
``None`` so SQL receives ``NULL``. A present non-``None`` value whose
|
|
4450
|
+
declared type resolves via the registry must satisfy that matcher.
|
|
4451
|
+
Unresolved types are documentation-only. Extra keys are ignored.
|
|
4452
|
+
"""
|
|
4453
|
+
_apply_declared_optional_defaults(declared, supplied)
|
|
4454
|
+
for declaration in declared:
|
|
4455
|
+
name = declaration.name
|
|
4456
|
+
if name not in supplied:
|
|
4457
|
+
msg = f"Missing required parameter '{name}' for declared SQL statement."
|
|
4458
|
+
raise SQLSpecError(msg)
|
|
4459
|
+
value = supplied[name]
|
|
4460
|
+
if value is None:
|
|
4461
|
+
continue
|
|
4462
|
+
if not matches_param_type(declaration.type_str, value):
|
|
4463
|
+
msg = f"Parameter '{name}' expected type '{declaration.type_str}' but got {type(value).__name__}."
|
|
4464
|
+
raise SQLSpecError(msg)
|
|
4465
|
+
|
|
4466
|
+
|
|
4467
|
+
def _many_parameters_already_prepared(
|
|
4468
|
+
parameters: "list[Any]", statement_config: "StatementConfig", applied_wrap_types: bool
|
|
4469
|
+
) -> bool:
|
|
4470
|
+
"""Return True when execute_many parameters were already coerced during compile()."""
|
|
4471
|
+
if statement_config.parameter_config.type_coercion_map:
|
|
4472
|
+
return True
|
|
4473
|
+
if applied_wrap_types:
|
|
4474
|
+
return False
|
|
4475
|
+
if not parameters:
|
|
4476
|
+
return True
|
|
4477
|
+
first = parameters[0]
|
|
4478
|
+
if isinstance(first, (tuple, list)):
|
|
4479
|
+
return not any(type(v) is TypedParameter for v in first)
|
|
4480
|
+
if isinstance(first, dict):
|
|
4481
|
+
return not any(type(v) is TypedParameter for v in first.values())
|
|
4482
|
+
return type(first) is not TypedParameter
|
|
4483
|
+
|
|
4484
|
+
|
|
4485
|
+
def _row_needs_declared_default(declared: "tuple[ParameterDeclaration, ...]", supplied: "dict[str, Any]") -> bool:
|
|
4486
|
+
"""Return True when any optional declared parameter is missing from supplied."""
|
|
4487
|
+
return any(not declaration.required and declaration.name not in supplied for declaration in declared)
|
|
4488
|
+
|
|
4489
|
+
|
|
4490
|
+
def _check_declared_parameters(sql_statement: "SQL") -> None:
|
|
4491
|
+
"""Enforce declared-parameter contracts on a copy of the user params.
|
|
4492
|
+
|
|
4493
|
+
No-op unless the statement carries declarations and is not a script. Runs before
|
|
4494
|
+
driver style conversion, so declared names and raw values are intact. Named binding
|
|
4495
|
+
is validated for presence and type across all rows without mutating caller dicts;
|
|
4496
|
+
positional binding is skipped (arity is validated at load time).
|
|
4497
|
+
"""
|
|
4498
|
+
declared = sql_statement.declared_parameters
|
|
4499
|
+
if not declared or sql_statement.is_script:
|
|
4500
|
+
return
|
|
4501
|
+
if sql_statement.is_many:
|
|
4502
|
+
rows = sql_statement.positional_parameters
|
|
4503
|
+
if rows and isinstance(rows[0], dict):
|
|
4504
|
+
copied_rows: list[Any] | None = None
|
|
4505
|
+
for idx, row in enumerate(rows):
|
|
4506
|
+
if isinstance(row, dict):
|
|
4507
|
+
if _row_needs_declared_default(declared, row):
|
|
4508
|
+
row_copy = dict(row)
|
|
4509
|
+
_check_declared_named_row(declared, row_copy)
|
|
4510
|
+
if copied_rows is None:
|
|
4511
|
+
copied_rows = list(rows[:idx])
|
|
4512
|
+
copied_rows.append(row_copy)
|
|
4513
|
+
continue
|
|
4514
|
+
_check_declared_named_row(declared, row)
|
|
4515
|
+
if copied_rows is not None:
|
|
4516
|
+
copied_rows.append(row)
|
|
4517
|
+
if copied_rows is not None:
|
|
4518
|
+
sql_statement._positional_parameters = copied_rows
|
|
4519
|
+
return
|
|
4520
|
+
if sql_statement.positional_parameters:
|
|
4521
|
+
return
|
|
4522
|
+
named_params = sql_statement.named_parameters
|
|
4523
|
+
if _row_needs_declared_default(declared, named_params):
|
|
4524
|
+
named_copy = dict(named_params)
|
|
4525
|
+
_check_declared_named_row(declared, named_copy)
|
|
4526
|
+
sql_statement._named_parameters = named_copy
|
|
4527
|
+
else:
|
|
4528
|
+
_check_declared_named_row(declared, named_params)
|
|
4529
|
+
|
|
4530
|
+
|
|
4531
|
+
_GENERIC_DDL_DIALECTS: Final = frozenset({"", "generic", "unknown"})
|
|
4532
|
+
_TABLE_OBJECT_TYPES: Final = frozenset({"table", "temporary_table", "base table"})
|
|
4533
|
+
_TABLE_DEPENDENT_OBJECT_TYPES: Final = frozenset({"index", "trigger"})
|
|
4534
|
+
_SCHEMA_DDL_OBJECT_DOMAINS: Final[dict[str, str]] = {
|
|
4535
|
+
"table": "tables",
|
|
4536
|
+
"temporary_table": "tables",
|
|
4537
|
+
"base table": "tables",
|
|
4538
|
+
"index": "tables",
|
|
4539
|
+
"trigger": "tables",
|
|
4540
|
+
"view": "views",
|
|
4541
|
+
"materialized_view": "views",
|
|
4542
|
+
"materialized view": "views",
|
|
4543
|
+
"sequence": "sequences",
|
|
4544
|
+
"type": "types",
|
|
4545
|
+
"routine": "routines",
|
|
4546
|
+
"function": "routines",
|
|
4547
|
+
"procedure": "routines",
|
|
4548
|
+
"table function": "routines",
|
|
4549
|
+
}
|
|
4550
|
+
_DROP_OBJECT_KINDS: Final[dict[str, tuple[str, bool]]] = {
|
|
4551
|
+
"table": ("TABLE", False),
|
|
4552
|
+
"temporary_table": ("TABLE", False),
|
|
4553
|
+
"base table": ("TABLE", False),
|
|
4554
|
+
"view": ("VIEW", False),
|
|
4555
|
+
"materialized_view": ("VIEW", True),
|
|
4556
|
+
"materialized view": ("VIEW", True),
|
|
4557
|
+
"sequence": ("SEQUENCE", False),
|
|
4558
|
+
"type": ("TYPE", False),
|
|
4559
|
+
"index": ("INDEX", False),
|
|
4560
|
+
"function": ("FUNCTION", False),
|
|
4561
|
+
"procedure": ("PROCEDURE", False),
|
|
4562
|
+
"table function": ("TABLE FUNCTION", False),
|
|
4563
|
+
}
|
|
4564
|
+
_SEQUENCE_SYNTHESIS_UNSUPPORTED_DIALECTS: Final = frozenset({"spanner"})
|
|
4565
|
+
_REFERENCE_EDGE_KINDS: Final[dict[str, DependencyEdgeKind]] = {
|
|
4566
|
+
"sequence": DependencyEdgeKind.SEQUENCE_USE,
|
|
4567
|
+
"type": DependencyEdgeKind.DEFAULT_EXPRESSION,
|
|
4568
|
+
}
|
|
4569
|
+
_SEQUENCE_NUMERIC_PROPERTIES: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (
|
|
4570
|
+
("start", ("start_value", "start_with", "start")),
|
|
4571
|
+
("increment", ("increment_by", "increment_value", "increment")),
|
|
4572
|
+
("minvalue", ("min_value", "minimum_value")),
|
|
4573
|
+
("maxvalue", ("max_value", "maximum_value")),
|
|
4574
|
+
)
|
|
4575
|
+
|
|
4576
|
+
|
|
4577
|
+
def _ddl_dialect_or_none(dialect: str | None) -> str | None:
|
|
4578
|
+
"""Return ``dialect`` or None when it names generic SQL."""
|
|
4579
|
+
if dialect is None or dialect in _GENERIC_DDL_DIALECTS:
|
|
4580
|
+
return None
|
|
4581
|
+
return dialect
|
|
4582
|
+
|
|
4583
|
+
|
|
4584
|
+
def _sqlglot_dialect(dialect: str | None) -> str | None:
|
|
4585
|
+
"""Map a data dictionary dialect name to the SQLGlot dialect used to parse and render it."""
|
|
4586
|
+
return _normalize_dialect(_ddl_dialect_or_none(dialect))
|
|
4587
|
+
|
|
4588
|
+
|
|
4589
|
+
_LOOSE_PROFILE_TYPES: Final = frozenset({
|
|
4590
|
+
"",
|
|
4591
|
+
"TEXT",
|
|
4592
|
+
"VARCHAR",
|
|
4593
|
+
"CHARACTER VARYING",
|
|
4594
|
+
"NVARCHAR",
|
|
4595
|
+
"CHAR",
|
|
4596
|
+
"NCHAR",
|
|
4597
|
+
"CHARACTER",
|
|
4598
|
+
"STRING",
|
|
4599
|
+
"CLOB",
|
|
4600
|
+
"NCLOB",
|
|
4601
|
+
"LONGTEXT",
|
|
4602
|
+
"MEDIUMTEXT",
|
|
4603
|
+
"TINYTEXT",
|
|
4604
|
+
"BPCHAR",
|
|
4605
|
+
"ANY",
|
|
4606
|
+
"VARIANT",
|
|
4607
|
+
"OBJECT",
|
|
4608
|
+
})
|
|
4609
|
+
_NON_COMPARABLE_PROFILE_TYPES: Final = frozenset({
|
|
4610
|
+
"JSON",
|
|
4611
|
+
"JSONB",
|
|
4612
|
+
"XML",
|
|
4613
|
+
"BLOB",
|
|
4614
|
+
"CLOB",
|
|
4615
|
+
"NCLOB",
|
|
4616
|
+
"BFILE",
|
|
4617
|
+
"LONG",
|
|
4618
|
+
"RAW",
|
|
4619
|
+
"LONG RAW",
|
|
4620
|
+
"BYTEA",
|
|
4621
|
+
"VARBINARY",
|
|
4622
|
+
"BINARY",
|
|
4623
|
+
"IMAGE",
|
|
4624
|
+
"STRUCT",
|
|
4625
|
+
"ARRAY",
|
|
4626
|
+
"MAP",
|
|
4627
|
+
"GEOMETRY",
|
|
4628
|
+
"GEOGRAPHY",
|
|
4629
|
+
"SUPER",
|
|
4630
|
+
"VARIANT",
|
|
4631
|
+
})
|
|
4632
|
+
_PROFILE_INT_RE: Final = re.compile(r"^[+-]?(?:0|[1-9]\d*)$")
|
|
4633
|
+
_PROFILE_NUM_RE: Final = re.compile(r"^[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$")
|
|
4634
|
+
_PROFILE_UUID_RE: Final = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
|
4635
|
+
_PROFILE_DATE_RE: Final = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
4636
|
+
_PROFILE_DATETIME_RE: Final = re.compile(r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}")
|
|
4637
|
+
|
|
4638
|
+
|
|
4639
|
+
def _profile_text_cast_type(sqlglot_dialect: str | None) -> str:
|
|
4640
|
+
"""Return a dialect-valid text cast target for ``LENGTH(CAST(col AS ...))``."""
|
|
4641
|
+
if sqlglot_dialect == "oracle":
|
|
4642
|
+
return "VARCHAR2(4000)"
|
|
4643
|
+
if sqlglot_dialect == "db2":
|
|
4644
|
+
return "VARCHAR(32672)"
|
|
4645
|
+
if sqlglot_dialect == "tsql":
|
|
4646
|
+
return "NVARCHAR(MAX)"
|
|
4647
|
+
if sqlglot_dialect in {"bigquery", "spanner"}:
|
|
4648
|
+
return "STRING"
|
|
4649
|
+
if sqlglot_dialect == "mysql":
|
|
4650
|
+
return "CHAR"
|
|
4651
|
+
return "VARCHAR"
|
|
4652
|
+
|
|
4653
|
+
|
|
4654
|
+
def _is_non_comparable_profile_type(data_type: str, sqlglot_dialect: str | None) -> bool:
|
|
4655
|
+
"""Return True when a column type cannot participate in ``COUNT(DISTINCT)`` or ``CAST(... AS VARCHAR)``."""
|
|
4656
|
+
base_type = re.sub(r"\s+", " ", data_type.split("(", 1)[0].split("<", 1)[0].strip().upper())
|
|
4657
|
+
if not base_type:
|
|
4658
|
+
return False
|
|
4659
|
+
if base_type in _NON_COMPARABLE_PROFILE_TYPES or base_type.endswith("[]"):
|
|
4660
|
+
return True
|
|
4661
|
+
return sqlglot_dialect == "tsql" and base_type in {"TEXT", "NTEXT"}
|
|
4662
|
+
|
|
4663
|
+
|
|
4664
|
+
def _is_valid_profile_decimal(value: Any) -> bool:
|
|
4665
|
+
"""Return True when ``value`` is a finite numeric value or decimal string."""
|
|
4666
|
+
if isinstance(value, bool):
|
|
4667
|
+
return False
|
|
4668
|
+
if isinstance(value, int):
|
|
4669
|
+
return True
|
|
4670
|
+
if isinstance(value, (float, Decimal)):
|
|
4671
|
+
try:
|
|
4672
|
+
return Decimal(str(value)).is_finite()
|
|
4673
|
+
except Exception:
|
|
4674
|
+
return False
|
|
4675
|
+
if isinstance(value, str) and bool(_PROFILE_NUM_RE.match(value.strip())):
|
|
4676
|
+
try:
|
|
4677
|
+
return Decimal(value.strip()).is_finite()
|
|
4678
|
+
except Exception:
|
|
4679
|
+
return False
|
|
4680
|
+
return False
|
|
4681
|
+
|
|
4682
|
+
|
|
4683
|
+
def _decimal_digit_counts(value: Any) -> tuple[int, int]:
|
|
4684
|
+
"""Return ``(integer_digits, fractional_digits)`` for a finite numeric sample value."""
|
|
4685
|
+
dec = Decimal(str(value).strip())
|
|
4686
|
+
_, digits, exponent = dec.as_tuple()
|
|
4687
|
+
exp_int = int(exponent) if isinstance(exponent, int) else 0
|
|
4688
|
+
total_sig = len(digits)
|
|
4689
|
+
if exp_int >= 0:
|
|
4690
|
+
return (max(1, total_sig + exp_int), 0)
|
|
4691
|
+
frac_digits = -exp_int
|
|
4692
|
+
int_digits = max(1, total_sig - frac_digits)
|
|
4693
|
+
return (int_digits, frac_digits)
|
|
4694
|
+
|
|
4695
|
+
|
|
4696
|
+
def _is_valid_profile_date(value: Any) -> bool:
|
|
4697
|
+
if isinstance(value, date) and not isinstance(value, datetime):
|
|
4698
|
+
return True
|
|
4699
|
+
if not isinstance(value, str) or not _PROFILE_DATE_RE.match(value.strip()):
|
|
4700
|
+
return False
|
|
4701
|
+
try:
|
|
4702
|
+
date.fromisoformat(value.strip())
|
|
4703
|
+
except ValueError:
|
|
4704
|
+
return False
|
|
4705
|
+
return True
|
|
4706
|
+
|
|
4707
|
+
|
|
4708
|
+
def _is_valid_profile_datetime(value: Any) -> bool:
|
|
4709
|
+
if isinstance(value, datetime):
|
|
4710
|
+
return True
|
|
4711
|
+
if not isinstance(value, str) or not _PROFILE_DATETIME_RE.match(value.strip()):
|
|
4712
|
+
return False
|
|
4713
|
+
normalized = value.strip()
|
|
4714
|
+
if normalized.endswith(("Z", "z")):
|
|
4715
|
+
normalized = f"{normalized[:-1]}+00:00"
|
|
4716
|
+
try:
|
|
4717
|
+
datetime.fromisoformat(normalized)
|
|
4718
|
+
except ValueError:
|
|
4719
|
+
return False
|
|
4720
|
+
return True
|
|
4721
|
+
|
|
4722
|
+
|
|
4723
|
+
_LOAD_FROM_STORAGE_KWARGS: Final[frozenset[str]] = frozenset({
|
|
4724
|
+
"arrow_schema",
|
|
4725
|
+
"checkpoint_phase",
|
|
4726
|
+
"checkpoint_table",
|
|
4727
|
+
"concurrent_indexes",
|
|
4728
|
+
"conflict_keys",
|
|
4729
|
+
"drop_indexes",
|
|
4730
|
+
"drop_stage_table",
|
|
4731
|
+
"exclude_update_columns",
|
|
4732
|
+
"executor",
|
|
4733
|
+
"max_workers",
|
|
4734
|
+
"on_conflict",
|
|
4735
|
+
"stage_table",
|
|
4736
|
+
"storage_options",
|
|
4737
|
+
"type_casts",
|
|
4738
|
+
})
|
|
4739
|
+
|
|
4740
|
+
|
|
4741
|
+
def validate_load_from_storage_kwargs(kwargs: "dict[str, Any]") -> None:
|
|
4742
|
+
"""Validate optional keyword arguments forwarded to ``load_from_storage``."""
|
|
4743
|
+
if not kwargs:
|
|
4744
|
+
return
|
|
4745
|
+
unknown = sorted(set(kwargs) - _LOAD_FROM_STORAGE_KWARGS)
|
|
4746
|
+
if unknown:
|
|
4747
|
+
msg = f"load_from_storage() got unexpected keyword argument '{unknown[0]}'"
|
|
4748
|
+
raise TypeError(msg)
|
|
4749
|
+
|
|
4750
|
+
|
|
4751
|
+
def _is_valid_profile_json(value: Any) -> bool:
|
|
4752
|
+
if isinstance(value, (Mapping, list)):
|
|
4753
|
+
return True
|
|
4754
|
+
if not isinstance(value, str):
|
|
4755
|
+
return False
|
|
4756
|
+
stripped = value.strip()
|
|
4757
|
+
if not (
|
|
4758
|
+
(stripped.startswith("{") and stripped.endswith("}")) or (stripped.startswith("[") and stripped.endswith("]"))
|
|
4759
|
+
):
|
|
4760
|
+
return False
|
|
4761
|
+
try:
|
|
4762
|
+
parsed = from_json(stripped)
|
|
4763
|
+
except ValueError:
|
|
4764
|
+
return False
|
|
4765
|
+
return isinstance(parsed, (Mapping, list))
|