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
sqlspec/builder/_ddl.py
ADDED
|
@@ -0,0 +1,4503 @@
|
|
|
1
|
+
"""DDL statement builders.
|
|
2
|
+
|
|
3
|
+
Provides builders for DDL operations including CREATE, DROP, ALTER,
|
|
4
|
+
TRUNCATE, and other schema manipulation statements.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import contextlib
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from datetime import date, datetime, time, timedelta
|
|
11
|
+
from decimal import Decimal
|
|
12
|
+
from typing import TYPE_CHECKING, Any, ClassVar, Final, Self, cast
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
import sqlglot
|
|
16
|
+
from mypy_extensions import mypyc_attr, trait
|
|
17
|
+
from sqlglot import exp
|
|
18
|
+
from sqlglot.dialects.dialect import Dialect, NormalizationStrategy
|
|
19
|
+
from sqlglot.errors import ParseError, TokenError
|
|
20
|
+
from sqlglot.tokenizer_core import TokenType
|
|
21
|
+
|
|
22
|
+
from sqlspec.builder._base import QueryBuilder
|
|
23
|
+
from sqlspec.builder._parsing_utils import (
|
|
24
|
+
_FORBIDDEN_STATEMENT_NODES,
|
|
25
|
+
_is_simple_identifier,
|
|
26
|
+
_mark_explicit_table_quotes,
|
|
27
|
+
_normalize_dialect,
|
|
28
|
+
_parse_table_reference,
|
|
29
|
+
_truthy_metadata_flag,
|
|
30
|
+
parse_order_expression,
|
|
31
|
+
)
|
|
32
|
+
from sqlspec.core.splitter import contains_statement_terminator
|
|
33
|
+
from sqlspec.core.statement import SQL
|
|
34
|
+
from sqlspec.data_dictionary._types import (
|
|
35
|
+
DDLResult,
|
|
36
|
+
ForeignKeyMetadata,
|
|
37
|
+
MetadataFidelity,
|
|
38
|
+
MetadataSource,
|
|
39
|
+
MetadataSupport,
|
|
40
|
+
ObjectIdentity,
|
|
41
|
+
)
|
|
42
|
+
from sqlspec.exceptions import SQLBuilderError, with_cause
|
|
43
|
+
from sqlspec.utils.arrow_helpers import sql_type_for_category, sql_type_from_arrow_type
|
|
44
|
+
from sqlspec.utils.type_guards import has_sqlglot_expression
|
|
45
|
+
|
|
46
|
+
if TYPE_CHECKING:
|
|
47
|
+
from sqlglot.dialects.dialect import DialectType
|
|
48
|
+
|
|
49
|
+
from sqlspec.builder._column import ColumnExpression
|
|
50
|
+
|
|
51
|
+
__all__ = (
|
|
52
|
+
"AlterOperation",
|
|
53
|
+
"AlterTable",
|
|
54
|
+
"ColumnDefinition",
|
|
55
|
+
"CommentOn",
|
|
56
|
+
"ConstraintDefinition",
|
|
57
|
+
"CreateIndex",
|
|
58
|
+
"CreateMaterializedView",
|
|
59
|
+
"CreateSchema",
|
|
60
|
+
"CreateSequence",
|
|
61
|
+
"CreateTable",
|
|
62
|
+
"CreateTableAsSelect",
|
|
63
|
+
"CreateView",
|
|
64
|
+
"DDLBuilder",
|
|
65
|
+
"DropIndex",
|
|
66
|
+
"DropMaterializedView",
|
|
67
|
+
"DropSchema",
|
|
68
|
+
"DropSequence",
|
|
69
|
+
"DropTable",
|
|
70
|
+
"DropView",
|
|
71
|
+
"RenameTable",
|
|
72
|
+
"Truncate",
|
|
73
|
+
"compile_table_ddl_results",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
CONSTRAINT_TYPE_PRIMARY_KEY = "PRIMARY KEY"
|
|
77
|
+
CONSTRAINT_TYPE_FOREIGN_KEY = "FOREIGN KEY"
|
|
78
|
+
CONSTRAINT_TYPE_UNIQUE = "UNIQUE"
|
|
79
|
+
CONSTRAINT_TYPE_CHECK = "CHECK"
|
|
80
|
+
|
|
81
|
+
FOREIGN_KEY_ACTION_CASCADE = "CASCADE"
|
|
82
|
+
FOREIGN_KEY_ACTION_SET_NULL = "SET NULL"
|
|
83
|
+
FOREIGN_KEY_ACTION_SET_DEFAULT = "SET DEFAULT"
|
|
84
|
+
FOREIGN_KEY_ACTION_RESTRICT = "RESTRICT"
|
|
85
|
+
FOREIGN_KEY_ACTION_NO_ACTION = "NO ACTION"
|
|
86
|
+
|
|
87
|
+
VALID_FOREIGN_KEY_ACTIONS = {
|
|
88
|
+
FOREIGN_KEY_ACTION_CASCADE,
|
|
89
|
+
FOREIGN_KEY_ACTION_SET_NULL,
|
|
90
|
+
FOREIGN_KEY_ACTION_SET_DEFAULT,
|
|
91
|
+
FOREIGN_KEY_ACTION_RESTRICT,
|
|
92
|
+
FOREIGN_KEY_ACTION_NO_ACTION,
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
VALID_CONSTRAINT_TYPES = {
|
|
96
|
+
CONSTRAINT_TYPE_PRIMARY_KEY,
|
|
97
|
+
CONSTRAINT_TYPE_FOREIGN_KEY,
|
|
98
|
+
CONSTRAINT_TYPE_UNIQUE,
|
|
99
|
+
CONSTRAINT_TYPE_CHECK,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
CURRENT_TIMESTAMP_KEYWORD = "CURRENT_TIMESTAMP"
|
|
103
|
+
CURRENT_DATE_KEYWORD = "CURRENT_DATE"
|
|
104
|
+
CURRENT_TIME_KEYWORD = "CURRENT_TIME"
|
|
105
|
+
|
|
106
|
+
_IDENTITY_KEYWORDS = frozenset({
|
|
107
|
+
"ALWAYS",
|
|
108
|
+
"BY DEFAULT",
|
|
109
|
+
"ALWAYS AS IDENTITY",
|
|
110
|
+
"BY DEFAULT AS IDENTITY",
|
|
111
|
+
"BY DEFAULT ON NULL",
|
|
112
|
+
"BY DEFAULT ON NULL AS IDENTITY",
|
|
113
|
+
})
|
|
114
|
+
_IDENTITY_SEED_INC_RE = re.compile(r"^IDENTITY\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$", re.IGNORECASE)
|
|
115
|
+
_ORDER_DIRECTION_SUFFIX_RE = re.compile(
|
|
116
|
+
r"\s+(?:ASC|DESC|NULLS\s+(?:FIRST|LAST))(?:\s+NULLS\s+(?:FIRST|LAST))?\s*$", re.IGNORECASE
|
|
117
|
+
)
|
|
118
|
+
_PAREN_COLS_RE = re.compile(r"\(([^)]+)\)")
|
|
119
|
+
_FK_DEF_RE = re.compile(
|
|
120
|
+
r"FOREIGN\s+KEY\s*\((?P<cols>[^)]+)\)\s*REFERENCES\s+(?P<ref_table>[^\s(]+)\s*\((?P<ref_cols>[^)]+)\)",
|
|
121
|
+
re.IGNORECASE,
|
|
122
|
+
)
|
|
123
|
+
_FK_ON_DELETE_RE = re.compile(
|
|
124
|
+
r"\bON\s+DELETE\s+(CASCADE|SET\s+NULL|SET\s+DEFAULT|RESTRICT|NO\s+ACTION)\b", re.IGNORECASE
|
|
125
|
+
)
|
|
126
|
+
_FK_ON_UPDATE_RE = re.compile(
|
|
127
|
+
r"\bON\s+UPDATE\s+(CASCADE|SET\s+NULL|SET\s+DEFAULT|RESTRICT|NO\s+ACTION)\b", re.IGNORECASE
|
|
128
|
+
)
|
|
129
|
+
_UUID_STR_RE = 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}$")
|
|
130
|
+
_ISO_DATETIME_STR_RE = re.compile(
|
|
131
|
+
r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$", re.IGNORECASE
|
|
132
|
+
)
|
|
133
|
+
_ISO_DATE_STR_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
134
|
+
_ISO_OFFSET_SUFFIX_RE = re.compile(r"(?:Z|[+-]\d{2}:?\d{2})$", re.IGNORECASE)
|
|
135
|
+
_DEFAULT_INFERRED_DECIMAL_PRECISION = 38
|
|
136
|
+
_DEFAULT_INFERRED_DECIMAL_SCALE = 9
|
|
137
|
+
_ORACLE_NUMBER_MAX_PRECISION = 38
|
|
138
|
+
_BARE_IDENTIFIER_RE = re.compile(r"\A[A-Za-z_][A-Za-z0-9_]*\Z")
|
|
139
|
+
_TYPE_NAME_PART = r'(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|\[(?:[^\]]|\]\])+\]|[A-Za-z_][A-Za-z0-9_$]*)'
|
|
140
|
+
_QUALIFIED_TYPE_NAME_RE = re.compile(rf"^{_TYPE_NAME_PART}(?:\s*\.\s*{_TYPE_NAME_PART}){{0,2}}$")
|
|
141
|
+
_INLINE_ENUM_TYPE_RE = re.compile(r"^\s*ENUM\s*\(", re.IGNORECASE)
|
|
142
|
+
_INLINE_ENUM_DIALECTS = frozenset({"duckdb", "mysql", "clickhouse"})
|
|
143
|
+
_VERBATIM_TYPE_NAME_RE = re.compile(
|
|
144
|
+
r"^[A-Za-z_]\w*(?:\s+[A-Za-z_]\w*)*(?:\s*\(\s*(?:\d+|MAX)(?:\s*,\s*\d+)?\s*\))?$", re.IGNORECASE
|
|
145
|
+
)
|
|
146
|
+
_QUOTED_IDENTIFIER_RE = re.compile(r'^(?:"(?:[^"]|"")+"|`(?:[^`]|``)+`|\[(?:[^\]]|\]\])+\])$')
|
|
147
|
+
_INDEX_EXPRESSION_CHARS_RE = re.compile(r"[()+\-*/%|<>=!:,']")
|
|
148
|
+
_INDEX_PLACEHOLDER_RE = re.compile(r"^<[^<>]*>$")
|
|
149
|
+
_NATIVE_INDEX_SQL_RE = re.compile(r"^\s*CREATE\s+(?:UNIQUE\s+)?(?:\w+\s+)*INDEX\b", re.IGNORECASE)
|
|
150
|
+
_NUMERIC_LITERAL_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")
|
|
151
|
+
_MYSQL_KEYWORD_DEFAULT_RE = re.compile(
|
|
152
|
+
r"^(?:CURRENT_TIMESTAMP|NOW|LOCALTIME|LOCALTIMESTAMP|CURRENT_DATE|CURRENT_TIME|CURDATE|CURTIME|UTC_TIMESTAMP)"
|
|
153
|
+
r"(?:\(\s*\d*\s*\))?$",
|
|
154
|
+
re.IGNORECASE,
|
|
155
|
+
)
|
|
156
|
+
_MYSQL_BIT_HEX_LITERAL_RE = re.compile(r"^[bBxX]'[0-9a-fA-F]*'$")
|
|
157
|
+
_UNPARSEABLE_DEFAULT: Final[object] = object()
|
|
158
|
+
_RESERVED_IDENTIFIER_WORDS = frozenset({
|
|
159
|
+
"ACCESS",
|
|
160
|
+
"ADD",
|
|
161
|
+
"ALL",
|
|
162
|
+
"ALTER",
|
|
163
|
+
"AND",
|
|
164
|
+
"ANY",
|
|
165
|
+
"AS",
|
|
166
|
+
"ASC",
|
|
167
|
+
"AUDIT",
|
|
168
|
+
"BETWEEN",
|
|
169
|
+
"BY",
|
|
170
|
+
"CHAR",
|
|
171
|
+
"CHECK",
|
|
172
|
+
"CLUSTER",
|
|
173
|
+
"COLUMN",
|
|
174
|
+
"COMMENT",
|
|
175
|
+
"COMPRESS",
|
|
176
|
+
"CONNECT",
|
|
177
|
+
"CREATE",
|
|
178
|
+
"CURRENT",
|
|
179
|
+
"DATE",
|
|
180
|
+
"DECIMAL",
|
|
181
|
+
"DEFAULT",
|
|
182
|
+
"DELETE",
|
|
183
|
+
"DESC",
|
|
184
|
+
"DISTINCT",
|
|
185
|
+
"DROP",
|
|
186
|
+
"ELSE",
|
|
187
|
+
"EXCLUSIVE",
|
|
188
|
+
"EXISTS",
|
|
189
|
+
"FILE",
|
|
190
|
+
"FLOAT",
|
|
191
|
+
"FOR",
|
|
192
|
+
"FROM",
|
|
193
|
+
"GRANT",
|
|
194
|
+
"GROUP",
|
|
195
|
+
"HAVING",
|
|
196
|
+
"IDENTIFIED",
|
|
197
|
+
"IMMEDIATE",
|
|
198
|
+
"IN",
|
|
199
|
+
"INCREMENT",
|
|
200
|
+
"INDEX",
|
|
201
|
+
"INITIAL",
|
|
202
|
+
"INSERT",
|
|
203
|
+
"INTEGER",
|
|
204
|
+
"INTERSECT",
|
|
205
|
+
"INTO",
|
|
206
|
+
"IS",
|
|
207
|
+
"LEVEL",
|
|
208
|
+
"LIKE",
|
|
209
|
+
"LOCK",
|
|
210
|
+
"LONG",
|
|
211
|
+
"MAXEXTENTS",
|
|
212
|
+
"MINUS",
|
|
213
|
+
"MLSLABEL",
|
|
214
|
+
"MODE",
|
|
215
|
+
"MODIFY",
|
|
216
|
+
"NOAUDIT",
|
|
217
|
+
"NOCOMPRESS",
|
|
218
|
+
"NOT",
|
|
219
|
+
"NOWAIT",
|
|
220
|
+
"NULL",
|
|
221
|
+
"NUMBER",
|
|
222
|
+
"OF",
|
|
223
|
+
"OFFLINE",
|
|
224
|
+
"ON",
|
|
225
|
+
"ONLINE",
|
|
226
|
+
"OPTION",
|
|
227
|
+
"OR",
|
|
228
|
+
"ORDER",
|
|
229
|
+
"PCTFREE",
|
|
230
|
+
"PRIOR",
|
|
231
|
+
"PUBLIC",
|
|
232
|
+
"RAW",
|
|
233
|
+
"RENAME",
|
|
234
|
+
"RESOURCE",
|
|
235
|
+
"REVOKE",
|
|
236
|
+
"ROW",
|
|
237
|
+
"ROWID",
|
|
238
|
+
"ROWNUM",
|
|
239
|
+
"ROWS",
|
|
240
|
+
"SELECT",
|
|
241
|
+
"SESSION",
|
|
242
|
+
"SET",
|
|
243
|
+
"SHARE",
|
|
244
|
+
"SIZE",
|
|
245
|
+
"SMALLINT",
|
|
246
|
+
"START",
|
|
247
|
+
"SUCCESSFUL",
|
|
248
|
+
"SYNONYM",
|
|
249
|
+
"SYSDATE",
|
|
250
|
+
"TABLE",
|
|
251
|
+
"THEN",
|
|
252
|
+
"TO",
|
|
253
|
+
"TRIGGER",
|
|
254
|
+
"UID",
|
|
255
|
+
"UNION",
|
|
256
|
+
"UNIQUE",
|
|
257
|
+
"UPDATE",
|
|
258
|
+
"USER",
|
|
259
|
+
"VALIDATE",
|
|
260
|
+
"VALUES",
|
|
261
|
+
"VARCHAR",
|
|
262
|
+
"VARCHAR2",
|
|
263
|
+
"VIEW",
|
|
264
|
+
"WHENEVER",
|
|
265
|
+
"WHERE",
|
|
266
|
+
"WITH",
|
|
267
|
+
})
|
|
268
|
+
_CHAR_LENGTH_TYPES = frozenset({
|
|
269
|
+
"binary",
|
|
270
|
+
"bit",
|
|
271
|
+
"bit varying",
|
|
272
|
+
"bytes",
|
|
273
|
+
"char",
|
|
274
|
+
"char varying",
|
|
275
|
+
"character",
|
|
276
|
+
"character varying",
|
|
277
|
+
"national character",
|
|
278
|
+
"national character varying",
|
|
279
|
+
"nchar",
|
|
280
|
+
"nvarchar",
|
|
281
|
+
"nvarchar2",
|
|
282
|
+
"raw",
|
|
283
|
+
"string",
|
|
284
|
+
"varbinary",
|
|
285
|
+
"varbit",
|
|
286
|
+
"varchar",
|
|
287
|
+
"varchar2",
|
|
288
|
+
})
|
|
289
|
+
_UNICODE_CHAR_TYPES = frozenset({"nchar", "nvarchar", "national character", "national character varying"})
|
|
290
|
+
_DECIMAL_TYPES = frozenset({"dec", "decimal", "number", "numeric"})
|
|
291
|
+
_TEMPORAL_SCALE_TYPES = frozenset({"datetime2", "datetimeoffset", "time"})
|
|
292
|
+
_ORACLE_ON_DELETE_ACTIONS = frozenset({FOREIGN_KEY_ACTION_CASCADE, FOREIGN_KEY_ACTION_SET_NULL})
|
|
293
|
+
_NO_PARTIAL_INDEX_DIALECTS = frozenset({"duckdb"})
|
|
294
|
+
_NO_CASCADE_SEQUENCE_DIALECTS = frozenset({"tsql", "oracle", "spanner", "bigquery", "db2"})
|
|
295
|
+
_COMMENT_ON_DIALECTS = frozenset({"postgres", "oracle", "db2", "duckdb", "snowflake"})
|
|
296
|
+
_INCLUDE_INDEX_DIALECTS = frozenset({"postgres", "tsql", "db2"})
|
|
297
|
+
_STORING_INDEX_DIALECTS = frozenset({"spanner", "spangres"})
|
|
298
|
+
_PARENTHESIZED_DEFAULT_DIALECTS = frozenset({"sqlite", "mysql", "spanner"})
|
|
299
|
+
_SELF_PARENTHESIZED_GENERATED_DIALECTS = frozenset({"postgres", "mysql", "sqlite"})
|
|
300
|
+
_GENERIC_NORMALIZATION_DIALECTS = frozenset({"oracle", "db2", "snowflake"})
|
|
301
|
+
_AUTO_INCREMENT_IDENTITY_DIALECTS = frozenset({"mysql", "sqlite", "duckdb"})
|
|
302
|
+
_VIRTUAL_ONLY_GENERATED_DIALECTS = frozenset({"duckdb", "oracle"})
|
|
303
|
+
_STORED_GENERATED_DEFAULT_DIALECTS = frozenset({"postgres", "spanner"})
|
|
304
|
+
_MSSQL_STORAGE_INDEX_TYPES = frozenset({
|
|
305
|
+
"CLUSTERED",
|
|
306
|
+
"NONCLUSTERED",
|
|
307
|
+
"HEAP",
|
|
308
|
+
"XML",
|
|
309
|
+
"SPATIAL",
|
|
310
|
+
"CLUSTERED COLUMNSTORE",
|
|
311
|
+
"NONCLUSTERED COLUMNSTORE",
|
|
312
|
+
"CLUSTERED_COLUMNSTORE",
|
|
313
|
+
"NONCLUSTERED_COLUMNSTORE",
|
|
314
|
+
})
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def build_column_expression(
|
|
318
|
+
col: "ColumnDefinition", dialect: "DialectType | None" = None, *, include_primary_key: bool = True
|
|
319
|
+
) -> "exp.Expr":
|
|
320
|
+
"""Build SQLGlot expression for a column definition.
|
|
321
|
+
|
|
322
|
+
Raises:
|
|
323
|
+
SQLBuilderError: When the column uses an identity or auto-increment feature the
|
|
324
|
+
target dialect cannot express.
|
|
325
|
+
"""
|
|
326
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
327
|
+
col_def = exp.ColumnDef(
|
|
328
|
+
this=_parse_ddl_identifier(col.name, dialect=dialect), kind=_parse_column_type(col.name, col.dtype, dialect)
|
|
329
|
+
)
|
|
330
|
+
inline_primary_key = col.primary_key and include_primary_key
|
|
331
|
+
|
|
332
|
+
constraints: list[exp.ColumnConstraint] = []
|
|
333
|
+
|
|
334
|
+
if norm_dialect == "oracle" and col.default is not None:
|
|
335
|
+
constraints.append(
|
|
336
|
+
exp.ColumnConstraint(kind=exp.DefaultColumnConstraint(this=_build_default_expression(col.default, dialect)))
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
if col.not_null or (inline_primary_key and norm_dialect == "db2"):
|
|
340
|
+
constraints.append(exp.ColumnConstraint(kind=exp.NotNullColumnConstraint()))
|
|
341
|
+
|
|
342
|
+
if inline_primary_key:
|
|
343
|
+
constraints.append(exp.ColumnConstraint(kind=exp.PrimaryKeyColumnConstraint()))
|
|
344
|
+
|
|
345
|
+
if col.unique:
|
|
346
|
+
constraints.append(exp.ColumnConstraint(kind=exp.UniqueColumnConstraint()))
|
|
347
|
+
|
|
348
|
+
identity_constraint = _build_identity_column_constraint(col, dialect=dialect)
|
|
349
|
+
use_auto_increment = col.auto_increment or (
|
|
350
|
+
identity_constraint is not None and norm_dialect in _AUTO_INCREMENT_IDENTITY_DIALECTS
|
|
351
|
+
)
|
|
352
|
+
if use_auto_increment:
|
|
353
|
+
if norm_dialect == "duckdb":
|
|
354
|
+
msg = (
|
|
355
|
+
f"Column {col.name!r}: DuckDB has no AUTO_INCREMENT or identity columns; "
|
|
356
|
+
"create a sequence with CreateSequence and use DEFAULT nextval('<sequence>') instead"
|
|
357
|
+
)
|
|
358
|
+
raise SQLBuilderError(msg)
|
|
359
|
+
if norm_dialect == "sqlite" and not inline_primary_key:
|
|
360
|
+
msg = f"Column {col.name!r}: SQLite AUTOINCREMENT requires an inline INTEGER PRIMARY KEY column"
|
|
361
|
+
raise SQLBuilderError(msg)
|
|
362
|
+
constraints.append(exp.ColumnConstraint(kind=exp.AutoIncrementColumnConstraint(this=False)))
|
|
363
|
+
elif identity_constraint is not None:
|
|
364
|
+
constraints.append(identity_constraint)
|
|
365
|
+
|
|
366
|
+
if norm_dialect != "oracle" and col.default is not None:
|
|
367
|
+
constraints.append(
|
|
368
|
+
exp.ColumnConstraint(kind=exp.DefaultColumnConstraint(this=_build_default_expression(col.default, dialect)))
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
if col.check:
|
|
372
|
+
check_expr = _parse_ddl_expression(col.check, label="column CHECK expression", dialect=norm_dialect)
|
|
373
|
+
constraints.append(exp.ColumnConstraint(kind=exp.Check(this=check_expr)))
|
|
374
|
+
|
|
375
|
+
if col.comment:
|
|
376
|
+
constraints.append(exp.ColumnConstraint(kind=exp.CommentColumnConstraint(this=exp.convert(col.comment))))
|
|
377
|
+
|
|
378
|
+
computed_constraint = _build_computed_column_constraint(col, dialect=dialect)
|
|
379
|
+
if computed_constraint is not None:
|
|
380
|
+
constraints.append(computed_constraint)
|
|
381
|
+
|
|
382
|
+
if col.collate:
|
|
383
|
+
constraints.append(_build_collate_column_constraint(col.collate, dialect=dialect))
|
|
384
|
+
|
|
385
|
+
if constraints:
|
|
386
|
+
col_def.set("constraints", constraints)
|
|
387
|
+
|
|
388
|
+
return col_def
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def build_constraint_expression(
|
|
392
|
+
constraint: "ConstraintDefinition", dialect: "DialectType | None" = None
|
|
393
|
+
) -> "exp.Expr | None":
|
|
394
|
+
"""Build SQLGlot expression for a table constraint."""
|
|
395
|
+
if constraint.constraint_type == CONSTRAINT_TYPE_PRIMARY_KEY:
|
|
396
|
+
pk_constraint = exp.PrimaryKey(
|
|
397
|
+
expressions=[_parse_ddl_identifier(col, dialect=dialect) for col in constraint.columns]
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
if constraint.name:
|
|
401
|
+
return exp.Constraint(
|
|
402
|
+
this=_parse_ddl_identifier(constraint.name, dialect=dialect), expressions=[pk_constraint]
|
|
403
|
+
)
|
|
404
|
+
return pk_constraint
|
|
405
|
+
|
|
406
|
+
if constraint.constraint_type == CONSTRAINT_TYPE_FOREIGN_KEY:
|
|
407
|
+
fk_options: list[str] = []
|
|
408
|
+
if constraint.deferrable:
|
|
409
|
+
if constraint.initially_deferred:
|
|
410
|
+
fk_options.append("DEFERRABLE INITIALLY DEFERRED")
|
|
411
|
+
else:
|
|
412
|
+
fk_options.append("DEFERRABLE INITIALLY IMMEDIATE")
|
|
413
|
+
|
|
414
|
+
reference_options: list[str] = []
|
|
415
|
+
on_delete, on_update = _dialect_foreign_key_actions(constraint, dialect)
|
|
416
|
+
if on_delete:
|
|
417
|
+
reference_options.append(f"ON DELETE {on_delete}")
|
|
418
|
+
if on_update:
|
|
419
|
+
reference_options.append(f"ON UPDATE {on_update}")
|
|
420
|
+
|
|
421
|
+
fk_constraint = exp.ForeignKey(
|
|
422
|
+
expressions=[_parse_ddl_identifier(col, dialect=dialect) for col in constraint.columns],
|
|
423
|
+
reference=exp.Reference(
|
|
424
|
+
this=_parse_ddl_table(constraint.references_table, dialect=dialect)
|
|
425
|
+
if constraint.references_table
|
|
426
|
+
else None,
|
|
427
|
+
expressions=[_parse_ddl_identifier(col, dialect=dialect) for col in constraint.references_columns],
|
|
428
|
+
options=reference_options or None,
|
|
429
|
+
),
|
|
430
|
+
options=fk_options or None,
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
if constraint.name:
|
|
434
|
+
return exp.Constraint(
|
|
435
|
+
this=_parse_ddl_identifier(constraint.name, dialect=dialect), expressions=[fk_constraint]
|
|
436
|
+
)
|
|
437
|
+
return fk_constraint
|
|
438
|
+
|
|
439
|
+
if constraint.constraint_type == CONSTRAINT_TYPE_UNIQUE:
|
|
440
|
+
unique_constraint = exp.UniqueColumnConstraint(
|
|
441
|
+
this=exp.Tuple(expressions=[_parse_ddl_identifier(col, dialect=dialect) for col in constraint.columns])
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
if constraint.name:
|
|
445
|
+
return exp.Constraint(
|
|
446
|
+
this=_parse_ddl_identifier(constraint.name, dialect=dialect), expressions=[unique_constraint]
|
|
447
|
+
)
|
|
448
|
+
return unique_constraint
|
|
449
|
+
|
|
450
|
+
if constraint.constraint_type == CONSTRAINT_TYPE_CHECK:
|
|
451
|
+
check_condition: exp.Expr | None = None
|
|
452
|
+
if constraint.condition_expr is not None:
|
|
453
|
+
check_condition = _check_ddl_expression_nodes(
|
|
454
|
+
constraint.condition_expr, label="CHECK constraint condition", text=constraint.condition_expr.sql()
|
|
455
|
+
)
|
|
456
|
+
elif constraint.condition:
|
|
457
|
+
check_condition = _parse_ddl_expression(
|
|
458
|
+
constraint.condition, label="CHECK constraint condition", dialect=dialect
|
|
459
|
+
)
|
|
460
|
+
check_expr = exp.Check(this=check_condition)
|
|
461
|
+
|
|
462
|
+
if constraint.name:
|
|
463
|
+
return exp.Constraint(
|
|
464
|
+
this=_parse_ddl_identifier(constraint.name, dialect=dialect), expressions=[check_expr]
|
|
465
|
+
)
|
|
466
|
+
return check_expr
|
|
467
|
+
|
|
468
|
+
return None
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
472
|
+
class DDLBuilder(QueryBuilder):
|
|
473
|
+
"""Base class for DDL builders (CREATE, DROP, ALTER, etc)."""
|
|
474
|
+
|
|
475
|
+
__slots__ = ("_expression_dialect",)
|
|
476
|
+
|
|
477
|
+
def __init__(self, dialect: "DialectType" = None) -> None:
|
|
478
|
+
super().__init__(dialect=dialect)
|
|
479
|
+
self._expression: exp.Expr | None = None
|
|
480
|
+
self._expression_dialect: DialectType | None = None
|
|
481
|
+
|
|
482
|
+
def _prepare_expression_for_build(self, dialect: "DialectType" = None, *, copy: bool = True) -> exp.Expr:
|
|
483
|
+
target_dialect = _normalize_dialect(dialect or self.dialect)
|
|
484
|
+
self._expression_dialect = target_dialect
|
|
485
|
+
self.set_parameters({})
|
|
486
|
+
self._expression = self._create_base_expression()
|
|
487
|
+
return super()._prepare_expression_for_build(dialect=target_dialect, copy=copy)
|
|
488
|
+
|
|
489
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
490
|
+
msg = "Subclasses must implement _create_base_expression."
|
|
491
|
+
raise NotImplementedError(msg)
|
|
492
|
+
|
|
493
|
+
def _require(self, value: object, message: str) -> None:
|
|
494
|
+
if not value:
|
|
495
|
+
self._raise_builder_error(message)
|
|
496
|
+
|
|
497
|
+
def _optimize_expression(
|
|
498
|
+
self, expression: exp.Expr, *, force: bool = False, dialect: "DialectType" = None
|
|
499
|
+
) -> exp.Expr:
|
|
500
|
+
"""Normalize DDL identifiers without disturbing explicitly quoted names.
|
|
501
|
+
|
|
502
|
+
Statements without an embedded query only need identifier normalization. SQLGlot
|
|
503
|
+
folds even quoted identifiers on case-insensitive dialects (T-SQL, SQLite, DuckDB),
|
|
504
|
+
which would rename catalog objects, so identifiers carrying an explicit quote marker
|
|
505
|
+
are left exactly as supplied. Statements embedding a query (CTAS, views) keep the
|
|
506
|
+
full query optimizer.
|
|
507
|
+
"""
|
|
508
|
+
if not force and not self.enable_optimization:
|
|
509
|
+
return expression
|
|
510
|
+
if expression.find(exp.Query) is not None:
|
|
511
|
+
return super()._optimize_expression(expression, force=force, dialect=dialect)
|
|
512
|
+
target_dialect = _normalize_dialect(dialect) if dialect is not None else self.dialect_name
|
|
513
|
+
normalizer = Dialect.get_or_raise(None if target_dialect in _GENERIC_NORMALIZATION_DIALECTS else target_dialect)
|
|
514
|
+
return expression.transform(lambda node: _normalize_ddl_identifier(node, normalizer), copy=True)
|
|
515
|
+
|
|
516
|
+
def _resolve_select_query(self, query: object, context: str, *, require_select_type: bool = True) -> exp.Expr:
|
|
517
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
518
|
+
select_parameters: dict[str, Any] | None = None
|
|
519
|
+
|
|
520
|
+
if isinstance(query, SQL):
|
|
521
|
+
select_expr = (
|
|
522
|
+
query.expression.copy()
|
|
523
|
+
if query.expression is not None
|
|
524
|
+
else exp.maybe_parse(query.sql, dialect=effective_dialect)
|
|
525
|
+
)
|
|
526
|
+
select_parameters = query.parameters
|
|
527
|
+
elif isinstance(query, QueryBuilder):
|
|
528
|
+
select_expr = query._prepare_expression_for_build(dialect=effective_dialect, copy=True)
|
|
529
|
+
select_parameters = query.parameters
|
|
530
|
+
elif isinstance(query, str):
|
|
531
|
+
select_expr = exp.maybe_parse(query, dialect=effective_dialect)
|
|
532
|
+
elif isinstance(query, exp.Expr):
|
|
533
|
+
select_expr = query.copy()
|
|
534
|
+
else:
|
|
535
|
+
self._raise_builder_error(f"Unsupported type for SELECT query in {context}.")
|
|
536
|
+
|
|
537
|
+
if select_expr is None or (require_select_type and not isinstance(select_expr, (exp.Select, exp.SetOperation))):
|
|
538
|
+
self._raise_builder_error("SELECT query must be a valid SELECT expression.")
|
|
539
|
+
|
|
540
|
+
if select_parameters:
|
|
541
|
+
self.load_parameters(select_parameters)
|
|
542
|
+
|
|
543
|
+
return select_expr
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
547
|
+
@trait
|
|
548
|
+
class _IfExistsDDLMixin:
|
|
549
|
+
__slots__ = ()
|
|
550
|
+
|
|
551
|
+
_if_exists: bool
|
|
552
|
+
|
|
553
|
+
def if_exists(self) -> Self:
|
|
554
|
+
cast("Any", self)._if_exists = True
|
|
555
|
+
return self
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
559
|
+
@trait
|
|
560
|
+
class _CascadeRestrictDDLMixin:
|
|
561
|
+
__slots__ = ()
|
|
562
|
+
|
|
563
|
+
_cascade: "bool | None"
|
|
564
|
+
|
|
565
|
+
def cascade(self) -> Self:
|
|
566
|
+
cast("Any", self)._cascade = True
|
|
567
|
+
return self
|
|
568
|
+
|
|
569
|
+
def restrict(self) -> Self:
|
|
570
|
+
cast("Any", self)._cascade = False
|
|
571
|
+
return self
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
@mypyc_attr(allow_interpreted_subclasses=True)
|
|
575
|
+
@trait
|
|
576
|
+
class _IfNotExistsDDLMixin:
|
|
577
|
+
__slots__ = ()
|
|
578
|
+
|
|
579
|
+
_if_not_exists: bool
|
|
580
|
+
|
|
581
|
+
def if_not_exists(self) -> Self:
|
|
582
|
+
cast("Any", self)._if_not_exists = True
|
|
583
|
+
return self
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
class ColumnDefinition:
|
|
587
|
+
"""Column definition for CREATE TABLE."""
|
|
588
|
+
|
|
589
|
+
__slots__ = (
|
|
590
|
+
"auto_increment",
|
|
591
|
+
"check",
|
|
592
|
+
"collate",
|
|
593
|
+
"comment",
|
|
594
|
+
"default",
|
|
595
|
+
"dtype",
|
|
596
|
+
"generated",
|
|
597
|
+
"generated_expression",
|
|
598
|
+
"identity",
|
|
599
|
+
"name",
|
|
600
|
+
"not_null",
|
|
601
|
+
"persisted",
|
|
602
|
+
"primary_key",
|
|
603
|
+
"unique",
|
|
604
|
+
)
|
|
605
|
+
|
|
606
|
+
def __init__(
|
|
607
|
+
self,
|
|
608
|
+
name: str,
|
|
609
|
+
dtype: str,
|
|
610
|
+
default: "Any | None" = None,
|
|
611
|
+
not_null: bool = False,
|
|
612
|
+
primary_key: bool = False,
|
|
613
|
+
unique: bool = False,
|
|
614
|
+
auto_increment: bool = False,
|
|
615
|
+
comment: "str | None" = None,
|
|
616
|
+
check: "str | None" = None,
|
|
617
|
+
generated: "str | bool | None" = None,
|
|
618
|
+
collate: "str | None" = None,
|
|
619
|
+
identity: "str | bool | None" = None,
|
|
620
|
+
generated_expression: "str | exp.Expr | None" = None,
|
|
621
|
+
persisted: "bool | None" = None,
|
|
622
|
+
) -> None:
|
|
623
|
+
self.name = name
|
|
624
|
+
self.dtype = dtype
|
|
625
|
+
self.default = default
|
|
626
|
+
self.not_null = not_null
|
|
627
|
+
self.primary_key = primary_key
|
|
628
|
+
self.unique = unique
|
|
629
|
+
self.auto_increment = auto_increment
|
|
630
|
+
self.comment = comment
|
|
631
|
+
self.check = check
|
|
632
|
+
self.generated = generated
|
|
633
|
+
self.collate = collate
|
|
634
|
+
self.identity = identity
|
|
635
|
+
self.generated_expression = generated_expression
|
|
636
|
+
self.persisted = persisted
|
|
637
|
+
|
|
638
|
+
def to_sqlglot(self, dialect: "DialectType | None" = None, *, include_primary_key: bool = True) -> "exp.Expr":
|
|
639
|
+
"""Build a SQLGlot ColumnDef expression for this column definition."""
|
|
640
|
+
return build_column_expression(self, dialect=dialect, include_primary_key=include_primary_key)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
class ConstraintDefinition:
|
|
644
|
+
"""Constraint definition for CREATE TABLE."""
|
|
645
|
+
|
|
646
|
+
__slots__ = (
|
|
647
|
+
"columns",
|
|
648
|
+
"condition",
|
|
649
|
+
"condition_expr",
|
|
650
|
+
"constraint_type",
|
|
651
|
+
"deferrable",
|
|
652
|
+
"initially_deferred",
|
|
653
|
+
"name",
|
|
654
|
+
"on_delete",
|
|
655
|
+
"on_update",
|
|
656
|
+
"references_columns",
|
|
657
|
+
"references_table",
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
def __init__(
|
|
661
|
+
self,
|
|
662
|
+
constraint_type: str,
|
|
663
|
+
name: "str | None" = None,
|
|
664
|
+
columns: "list[str] | None" = None,
|
|
665
|
+
references_table: "str | None" = None,
|
|
666
|
+
references_columns: "list[str] | None" = None,
|
|
667
|
+
condition: "str | None" = None,
|
|
668
|
+
condition_expr: "exp.Expr | None" = None,
|
|
669
|
+
on_delete: "str | None" = None,
|
|
670
|
+
on_update: "str | None" = None,
|
|
671
|
+
deferrable: bool = False,
|
|
672
|
+
initially_deferred: bool = False,
|
|
673
|
+
) -> None:
|
|
674
|
+
self.constraint_type = constraint_type
|
|
675
|
+
self.name = name
|
|
676
|
+
self.columns = columns or []
|
|
677
|
+
self.references_table = references_table
|
|
678
|
+
self.references_columns = references_columns or []
|
|
679
|
+
self.condition = condition
|
|
680
|
+
self.condition_expr = condition_expr
|
|
681
|
+
self.on_delete = on_delete
|
|
682
|
+
self.on_update = on_update
|
|
683
|
+
self.deferrable = deferrable
|
|
684
|
+
self.initially_deferred = initially_deferred
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
class CreateTable(DDLBuilder, _IfNotExistsDDLMixin):
|
|
688
|
+
"""Builder for CREATE TABLE statements with columns and constraints."""
|
|
689
|
+
|
|
690
|
+
__slots__ = (
|
|
691
|
+
"_columns",
|
|
692
|
+
"_constraints",
|
|
693
|
+
"_if_not_exists",
|
|
694
|
+
"_like_table",
|
|
695
|
+
"_partition_by",
|
|
696
|
+
"_schema",
|
|
697
|
+
"_table_name",
|
|
698
|
+
"_table_options",
|
|
699
|
+
"_tablespace",
|
|
700
|
+
"_temporary",
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
def __init__(self, table_name: str, dialect: "DialectType" = None) -> None:
|
|
704
|
+
super().__init__(dialect=dialect)
|
|
705
|
+
self._table_name = table_name
|
|
706
|
+
self._if_not_exists = False
|
|
707
|
+
self._temporary = False
|
|
708
|
+
self._columns: list[ColumnDefinition] = []
|
|
709
|
+
self._constraints: list[ConstraintDefinition] = []
|
|
710
|
+
self._table_options: dict[str, Any] = {}
|
|
711
|
+
self._schema: str | None = None
|
|
712
|
+
self._tablespace: str | None = None
|
|
713
|
+
self._like_table: str | None = None
|
|
714
|
+
self._partition_by: str | None = None
|
|
715
|
+
|
|
716
|
+
@property
|
|
717
|
+
def columns(self) -> "list[ColumnDefinition]":
|
|
718
|
+
"""Get the list of column definitions for this table.
|
|
719
|
+
|
|
720
|
+
Returns:
|
|
721
|
+
List of ColumnDefinition objects.
|
|
722
|
+
"""
|
|
723
|
+
return self._columns
|
|
724
|
+
|
|
725
|
+
def in_schema(self, schema_name: str) -> "Self":
|
|
726
|
+
"""Set the schema for the table."""
|
|
727
|
+
self._schema = schema_name
|
|
728
|
+
return self
|
|
729
|
+
|
|
730
|
+
def temporary(self) -> "Self":
|
|
731
|
+
"""Create a temporary table."""
|
|
732
|
+
self._temporary = True
|
|
733
|
+
return self
|
|
734
|
+
|
|
735
|
+
def like(self, source_table: str) -> "Self":
|
|
736
|
+
"""Create table LIKE another table."""
|
|
737
|
+
self._like_table = source_table
|
|
738
|
+
return self
|
|
739
|
+
|
|
740
|
+
def tablespace(self, name: str) -> "Self":
|
|
741
|
+
"""Set tablespace for the table."""
|
|
742
|
+
self._tablespace = _validate_clause_identifier(name, label="tablespace")
|
|
743
|
+
return self
|
|
744
|
+
|
|
745
|
+
def partition_by(self, partition_spec: str) -> "Self":
|
|
746
|
+
"""Set partitioning specification."""
|
|
747
|
+
if not isinstance(partition_spec, str) or not partition_spec.strip():
|
|
748
|
+
msg = f"Invalid PARTITION BY specification: {partition_spec!r}"
|
|
749
|
+
raise SQLBuilderError(msg)
|
|
750
|
+
self._partition_by = partition_spec
|
|
751
|
+
return self
|
|
752
|
+
|
|
753
|
+
def column(
|
|
754
|
+
self,
|
|
755
|
+
name: str,
|
|
756
|
+
dtype: str,
|
|
757
|
+
default: "Any | None" = None,
|
|
758
|
+
not_null: bool = False,
|
|
759
|
+
primary_key: bool = False,
|
|
760
|
+
unique: bool = False,
|
|
761
|
+
auto_increment: bool = False,
|
|
762
|
+
comment: "str | None" = None,
|
|
763
|
+
check: "str | None" = None,
|
|
764
|
+
generated: "str | bool | None" = None,
|
|
765
|
+
collate: "str | None" = None,
|
|
766
|
+
identity: "str | bool | None" = None,
|
|
767
|
+
generated_expression: "str | exp.Expr | None" = None,
|
|
768
|
+
persisted: "bool | None" = None,
|
|
769
|
+
) -> "Self":
|
|
770
|
+
"""Add a column definition to the table."""
|
|
771
|
+
if not name:
|
|
772
|
+
self._raise_builder_error("Column name must be a non-empty string")
|
|
773
|
+
|
|
774
|
+
if not dtype:
|
|
775
|
+
self._raise_builder_error("Column type must be a non-empty string")
|
|
776
|
+
|
|
777
|
+
if any(col.name == name for col in self._columns):
|
|
778
|
+
self._raise_builder_error(f"Column '{name}' already defined")
|
|
779
|
+
|
|
780
|
+
if check:
|
|
781
|
+
_parse_ddl_expression(check, label="column CHECK expression", dialect=self.dialect)
|
|
782
|
+
|
|
783
|
+
column_def = ColumnDefinition(
|
|
784
|
+
name=name,
|
|
785
|
+
dtype=dtype,
|
|
786
|
+
default=default,
|
|
787
|
+
not_null=not_null,
|
|
788
|
+
primary_key=primary_key,
|
|
789
|
+
unique=unique,
|
|
790
|
+
auto_increment=auto_increment,
|
|
791
|
+
comment=comment,
|
|
792
|
+
check=check,
|
|
793
|
+
generated=generated,
|
|
794
|
+
collate=collate,
|
|
795
|
+
identity=identity,
|
|
796
|
+
generated_expression=generated_expression,
|
|
797
|
+
persisted=persisted,
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
self._columns.append(column_def)
|
|
801
|
+
|
|
802
|
+
if primary_key:
|
|
803
|
+
self.primary_key_constraint([name])
|
|
804
|
+
|
|
805
|
+
return self
|
|
806
|
+
|
|
807
|
+
def primary_key_constraint(self, columns: "str | list[str]", name: "str | None" = None) -> "Self":
|
|
808
|
+
"""Add a primary key constraint."""
|
|
809
|
+
col_list = [columns] if isinstance(columns, str) else list(columns)
|
|
810
|
+
|
|
811
|
+
if not col_list:
|
|
812
|
+
self._raise_builder_error("Primary key must include at least one column")
|
|
813
|
+
|
|
814
|
+
existing_pk = self._find_primary_key_constraint()
|
|
815
|
+
if existing_pk:
|
|
816
|
+
if name:
|
|
817
|
+
existing_pk.name = name
|
|
818
|
+
for col in col_list:
|
|
819
|
+
if col not in existing_pk.columns:
|
|
820
|
+
existing_pk.columns.append(col)
|
|
821
|
+
else:
|
|
822
|
+
constraint = ConstraintDefinition(constraint_type=CONSTRAINT_TYPE_PRIMARY_KEY, name=name, columns=col_list)
|
|
823
|
+
self._constraints.append(constraint)
|
|
824
|
+
|
|
825
|
+
return self
|
|
826
|
+
|
|
827
|
+
def foreign_key_constraint(
|
|
828
|
+
self,
|
|
829
|
+
columns: "str | list[str]",
|
|
830
|
+
references_table: str,
|
|
831
|
+
references_columns: "str | list[str]",
|
|
832
|
+
name: "str | None" = None,
|
|
833
|
+
on_delete: "str | None" = None,
|
|
834
|
+
on_update: "str | None" = None,
|
|
835
|
+
deferrable: bool = False,
|
|
836
|
+
initially_deferred: bool = False,
|
|
837
|
+
) -> "Self":
|
|
838
|
+
"""Add a foreign key constraint."""
|
|
839
|
+
col_list = [columns] if isinstance(columns, str) else list(columns)
|
|
840
|
+
|
|
841
|
+
ref_col_list = [references_columns] if isinstance(references_columns, str) else list(references_columns)
|
|
842
|
+
|
|
843
|
+
if len(col_list) != len(ref_col_list):
|
|
844
|
+
self._raise_builder_error("Foreign key columns and referenced columns must have same length")
|
|
845
|
+
|
|
846
|
+
self._validate_foreign_key_action(on_delete, "ON DELETE")
|
|
847
|
+
self._validate_foreign_key_action(on_update, "ON UPDATE")
|
|
848
|
+
|
|
849
|
+
constraint = ConstraintDefinition(
|
|
850
|
+
constraint_type=CONSTRAINT_TYPE_FOREIGN_KEY,
|
|
851
|
+
name=name,
|
|
852
|
+
columns=col_list,
|
|
853
|
+
references_table=references_table,
|
|
854
|
+
references_columns=ref_col_list,
|
|
855
|
+
on_delete=on_delete.upper() if on_delete else None,
|
|
856
|
+
on_update=on_update.upper() if on_update else None,
|
|
857
|
+
deferrable=deferrable,
|
|
858
|
+
initially_deferred=initially_deferred,
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
self._constraints.append(constraint)
|
|
862
|
+
return self
|
|
863
|
+
|
|
864
|
+
def unique_constraint(self, columns: "str | list[str]", name: "str | None" = None) -> "Self":
|
|
865
|
+
"""Add a unique constraint."""
|
|
866
|
+
col_list = [columns] if isinstance(columns, str) else list(columns)
|
|
867
|
+
|
|
868
|
+
if not col_list:
|
|
869
|
+
self._raise_builder_error("Unique constraint must include at least one column")
|
|
870
|
+
|
|
871
|
+
constraint = ConstraintDefinition(constraint_type=CONSTRAINT_TYPE_UNIQUE, name=name, columns=col_list)
|
|
872
|
+
|
|
873
|
+
self._constraints.append(constraint)
|
|
874
|
+
return self
|
|
875
|
+
|
|
876
|
+
def check_constraint(self, condition: "str | ColumnExpression", name: "str | None" = None) -> "Self":
|
|
877
|
+
"""Add a check constraint."""
|
|
878
|
+
if condition is None or (isinstance(condition, str) and not condition):
|
|
879
|
+
self._raise_builder_error("Check constraint must have a condition")
|
|
880
|
+
|
|
881
|
+
condition_expr: exp.Expr | None = None
|
|
882
|
+
condition_str: str | None = None
|
|
883
|
+
if has_sqlglot_expression(condition):
|
|
884
|
+
sqlglot_expr = condition.sqlglot_expression
|
|
885
|
+
condition_expr = sqlglot_expr if isinstance(sqlglot_expr, exp.Expr) else None
|
|
886
|
+
if condition_expr is not None:
|
|
887
|
+
_check_ddl_expression_nodes(
|
|
888
|
+
condition_expr, label="CHECK constraint condition", text=condition_expr.sql()
|
|
889
|
+
)
|
|
890
|
+
else:
|
|
891
|
+
condition_str = str(condition)
|
|
892
|
+
_parse_ddl_expression(condition_str, label="CHECK constraint condition", dialect=self.dialect)
|
|
893
|
+
|
|
894
|
+
constraint = ConstraintDefinition(
|
|
895
|
+
constraint_type=CONSTRAINT_TYPE_CHECK, name=name, condition=condition_str, condition_expr=condition_expr
|
|
896
|
+
)
|
|
897
|
+
|
|
898
|
+
self._constraints.append(constraint)
|
|
899
|
+
return self
|
|
900
|
+
|
|
901
|
+
def engine(self, engine_name: str) -> "Self":
|
|
902
|
+
"""Set storage engine (MySQL/MariaDB)."""
|
|
903
|
+
self._table_options["engine"] = _validate_clause_identifier(engine_name, label="table engine")
|
|
904
|
+
return self
|
|
905
|
+
|
|
906
|
+
def charset(self, charset_name: str) -> "Self":
|
|
907
|
+
"""Set character set."""
|
|
908
|
+
self._table_options["charset"] = charset_name
|
|
909
|
+
return self
|
|
910
|
+
|
|
911
|
+
def collate(self, collation: str) -> "Self":
|
|
912
|
+
"""Set table collation."""
|
|
913
|
+
self._table_options["collate"] = collation
|
|
914
|
+
return self
|
|
915
|
+
|
|
916
|
+
def comment(self, comment_text: str) -> "Self":
|
|
917
|
+
"""Set table comment."""
|
|
918
|
+
self._table_options["comment"] = comment_text
|
|
919
|
+
return self
|
|
920
|
+
|
|
921
|
+
def with_option(self, key: str, value: "Any") -> "Self":
|
|
922
|
+
"""Add custom table option."""
|
|
923
|
+
self._table_options[_validate_clause_identifier(key, label="table option key")] = value
|
|
924
|
+
return self
|
|
925
|
+
|
|
926
|
+
@classmethod
|
|
927
|
+
def from_metadata(
|
|
928
|
+
cls,
|
|
929
|
+
table_name: str,
|
|
930
|
+
columns: "Sequence[Mapping[str, Any] | Any]",
|
|
931
|
+
constraints: "Sequence[Mapping[str, Any] | Any] | None" = None,
|
|
932
|
+
foreign_keys: "Sequence[Mapping[str, Any] | Any] | None" = None,
|
|
933
|
+
schema: "str | None" = None,
|
|
934
|
+
if_not_exists: bool = False,
|
|
935
|
+
dialect: "DialectType" = None,
|
|
936
|
+
*,
|
|
937
|
+
source_dialect: "DialectType" = None,
|
|
938
|
+
warnings: "list[str] | None" = None,
|
|
939
|
+
) -> "CreateTable":
|
|
940
|
+
"""Build a CreateTable builder from structured data_dictionary metadata rows.
|
|
941
|
+
|
|
942
|
+
Names are raw catalog identifiers and are quoted whenever the bare spelling would
|
|
943
|
+
not resolve to the exact catalog name in ``dialect``. Catalog SQL fragments
|
|
944
|
+
(defaults, CHECK and generated expressions) are parsed with ``source_dialect``
|
|
945
|
+
(defaults to ``dialect``).
|
|
946
|
+
|
|
947
|
+
Args:
|
|
948
|
+
table_name: Raw catalog table name.
|
|
949
|
+
columns: Column metadata rows.
|
|
950
|
+
constraints: Constraint metadata rows.
|
|
951
|
+
foreign_keys: Foreign key metadata rows.
|
|
952
|
+
schema: Raw catalog schema name.
|
|
953
|
+
if_not_exists: Whether to emit ``IF NOT EXISTS``.
|
|
954
|
+
dialect: Target dialect for the generated DDL.
|
|
955
|
+
source_dialect: Dialect the catalog SQL fragments are written in.
|
|
956
|
+
warnings: Collector for metadata that cannot be reproduced faithfully. When
|
|
957
|
+
omitted, any such loss raises instead of being dropped.
|
|
958
|
+
|
|
959
|
+
Returns:
|
|
960
|
+
Configured CreateTable builder.
|
|
961
|
+
|
|
962
|
+
Raises:
|
|
963
|
+
SQLBuilderError: When metadata cannot be reproduced and no ``warnings`` collector is given.
|
|
964
|
+
"""
|
|
965
|
+
collected: list[str] = []
|
|
966
|
+
fragment_dialect = source_dialect if source_dialect is not None else dialect
|
|
967
|
+
builder = cls(_catalog_name(table_name, dialect, fragment_dialect), dialect=dialect)
|
|
968
|
+
if schema:
|
|
969
|
+
builder.in_schema(_catalog_name(schema, dialect, fragment_dialect))
|
|
970
|
+
if if_not_exists:
|
|
971
|
+
builder.if_not_exists()
|
|
972
|
+
|
|
973
|
+
norm_columns = [
|
|
974
|
+
row for row in (_normalize_metadata_row(col) for col in columns) if not _is_hidden_metadata_column(row)
|
|
975
|
+
]
|
|
976
|
+
if any(row.get("ordinal_position") is not None for row in norm_columns):
|
|
977
|
+
indexed_cols = list(enumerate(norm_columns))
|
|
978
|
+
indexed_cols.sort(key=lambda item: (_safe_int(item[1].get("ordinal_position"), item[0] + 1), item[0]))
|
|
979
|
+
norm_columns = [item[1] for item in indexed_cols]
|
|
980
|
+
|
|
981
|
+
norm_constraints = [_normalize_metadata_row(c) for c in constraints or ()]
|
|
982
|
+
norm_fks = [_normalize_metadata_row(fk) for fk in foreign_keys or ()]
|
|
983
|
+
|
|
984
|
+
default_constraint_map: dict[str, Any] = {}
|
|
985
|
+
for c_row in norm_constraints:
|
|
986
|
+
c_type_raw = str(_first_present(c_row, "constraint_type", "type") or "").strip().upper()
|
|
987
|
+
if c_type_raw in {"DEFAULT", "DEFAULT_CONSTRAINT"}:
|
|
988
|
+
c_col = _first_non_empty_str(c_row, "column_name", "name")
|
|
989
|
+
c_def = _first_present(c_row, "definition", "default", "column_default")
|
|
990
|
+
if c_col and c_def is not None:
|
|
991
|
+
default_constraint_map[c_col] = c_def
|
|
992
|
+
|
|
993
|
+
pk_cols, pk_name = _extract_metadata_primary_key(norm_columns, norm_constraints)
|
|
994
|
+
use_inline_pk = len(pk_cols) == 1 and pk_name is None
|
|
995
|
+
|
|
996
|
+
unique_specs: list[tuple[str | None, list[str]]] = []
|
|
997
|
+
seen_unique_cols: set[tuple[str, ...]] = set()
|
|
998
|
+
for c_row in norm_constraints:
|
|
999
|
+
if _normalize_constraint_type(c_row) != CONSTRAINT_TYPE_UNIQUE:
|
|
1000
|
+
continue
|
|
1001
|
+
uq_name = _first_non_empty_str(c_row, "constraint_name", "name")
|
|
1002
|
+
uq_cols = _extract_constraint_columns(c_row)
|
|
1003
|
+
if not uq_cols:
|
|
1004
|
+
collected.append(f"UNIQUE constraint {uq_name or '<unnamed>'} has no catalog columns and was omitted")
|
|
1005
|
+
continue
|
|
1006
|
+
if tuple(uq_cols) == tuple(pk_cols) or tuple(uq_cols) in seen_unique_cols:
|
|
1007
|
+
continue
|
|
1008
|
+
seen_unique_cols.add(tuple(uq_cols))
|
|
1009
|
+
unique_specs.append((uq_name, uq_cols))
|
|
1010
|
+
|
|
1011
|
+
for row in norm_columns:
|
|
1012
|
+
col_name = _first_non_empty_str(row, "column_name", "name")
|
|
1013
|
+
if not col_name:
|
|
1014
|
+
continue
|
|
1015
|
+
builder._add_metadata_column(
|
|
1016
|
+
row,
|
|
1017
|
+
col_name,
|
|
1018
|
+
dialect=dialect,
|
|
1019
|
+
fragment_dialect=fragment_dialect,
|
|
1020
|
+
primary_key=use_inline_pk and col_name == pk_cols[0],
|
|
1021
|
+
unique=_truthy_metadata_flag(_first_present(row, "is_unique", "unique"))
|
|
1022
|
+
and col_name not in pk_cols
|
|
1023
|
+
and (col_name,) not in seen_unique_cols,
|
|
1024
|
+
fallback_default=default_constraint_map.get(col_name),
|
|
1025
|
+
warnings=collected,
|
|
1026
|
+
)
|
|
1027
|
+
|
|
1028
|
+
if pk_cols and not use_inline_pk:
|
|
1029
|
+
builder.primary_key_constraint(
|
|
1030
|
+
[_catalog_name(col, dialect, fragment_dialect) for col in pk_cols],
|
|
1031
|
+
name=_catalog_name(pk_name, dialect, fragment_dialect) if pk_name else None,
|
|
1032
|
+
)
|
|
1033
|
+
|
|
1034
|
+
for uq_name, uq_cols in unique_specs:
|
|
1035
|
+
builder.unique_constraint(
|
|
1036
|
+
[_catalog_name(col, dialect, fragment_dialect) for col in uq_cols],
|
|
1037
|
+
name=_catalog_name(uq_name, dialect, fragment_dialect) if uq_name else None,
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
seen_checks: set[str] = set()
|
|
1041
|
+
for c_row in norm_constraints:
|
|
1042
|
+
if _normalize_constraint_type(c_row) != CONSTRAINT_TYPE_CHECK:
|
|
1043
|
+
continue
|
|
1044
|
+
chk_name = _first_non_empty_str(c_row, "constraint_name", "name")
|
|
1045
|
+
raw_cond = _first_non_empty_str(c_row, "check_clause", "condition", "definition", "expression")
|
|
1046
|
+
cond = _strip_check_wrapper(raw_cond) if raw_cond else None
|
|
1047
|
+
if not cond:
|
|
1048
|
+
collected.append(
|
|
1049
|
+
f"CHECK constraint {chk_name or '<unnamed>'} has no catalog expression and was omitted"
|
|
1050
|
+
)
|
|
1051
|
+
continue
|
|
1052
|
+
dedup_key = chk_name or cond
|
|
1053
|
+
if dedup_key in seen_checks:
|
|
1054
|
+
continue
|
|
1055
|
+
seen_checks.add(dedup_key)
|
|
1056
|
+
cond_expr = _parse_catalog_fragment(cond, fragment_dialect)
|
|
1057
|
+
if cond_expr is None:
|
|
1058
|
+
collected.append(
|
|
1059
|
+
f"CHECK constraint {chk_name or '<unnamed>'} could not be parsed and was omitted: {cond}"
|
|
1060
|
+
)
|
|
1061
|
+
continue
|
|
1062
|
+
builder._constraints.append(
|
|
1063
|
+
ConstraintDefinition(
|
|
1064
|
+
constraint_type=CONSTRAINT_TYPE_CHECK,
|
|
1065
|
+
name=_catalog_name(chk_name, dialect, fragment_dialect) if chk_name else None,
|
|
1066
|
+
condition_expr=cond_expr,
|
|
1067
|
+
)
|
|
1068
|
+
)
|
|
1069
|
+
|
|
1070
|
+
for fk_spec in _extract_metadata_foreign_keys(
|
|
1071
|
+
norm_constraints,
|
|
1072
|
+
norm_fks,
|
|
1073
|
+
table_schema=schema,
|
|
1074
|
+
dialect=dialect,
|
|
1075
|
+
source_dialect=fragment_dialect,
|
|
1076
|
+
warnings=collected,
|
|
1077
|
+
):
|
|
1078
|
+
on_delete, on_update = _supported_foreign_key_actions(
|
|
1079
|
+
fk_spec["on_delete"], fk_spec["on_update"], dialect, name=fk_spec["name"], warnings=collected
|
|
1080
|
+
)
|
|
1081
|
+
builder.foreign_key_constraint(
|
|
1082
|
+
columns=fk_spec["columns"],
|
|
1083
|
+
references_table=fk_spec["ref_table"],
|
|
1084
|
+
references_columns=fk_spec["ref_columns"],
|
|
1085
|
+
name=fk_spec["name"],
|
|
1086
|
+
on_delete=on_delete,
|
|
1087
|
+
on_update=on_update,
|
|
1088
|
+
deferrable=fk_spec["deferrable"],
|
|
1089
|
+
initially_deferred=fk_spec["initially_deferred"],
|
|
1090
|
+
)
|
|
1091
|
+
|
|
1092
|
+
_deliver_metadata_warnings(collected, warnings, context=f"table {table_name!r}")
|
|
1093
|
+
return builder
|
|
1094
|
+
|
|
1095
|
+
@classmethod
|
|
1096
|
+
def from_arrow_schema(
|
|
1097
|
+
cls,
|
|
1098
|
+
table_name: str,
|
|
1099
|
+
arrow_schema: Any,
|
|
1100
|
+
*,
|
|
1101
|
+
schema: "str | None" = None,
|
|
1102
|
+
primary_key: "str | Sequence[str] | None" = None,
|
|
1103
|
+
if_not_exists: bool = False,
|
|
1104
|
+
dialect: "DialectType" = None,
|
|
1105
|
+
) -> "CreateTable":
|
|
1106
|
+
"""Build a CreateTable builder from a pyarrow.Schema or pyarrow.Table."""
|
|
1107
|
+
resolved_schema = getattr(arrow_schema, "schema", arrow_schema)
|
|
1108
|
+
fields = list(resolved_schema)
|
|
1109
|
+
if not fields:
|
|
1110
|
+
msg = "Cannot infer table schema from empty Arrow schema"
|
|
1111
|
+
raise SQLBuilderError(msg)
|
|
1112
|
+
|
|
1113
|
+
builder = cls(table_name, dialect=dialect)
|
|
1114
|
+
if schema:
|
|
1115
|
+
builder.in_schema(schema)
|
|
1116
|
+
if if_not_exists:
|
|
1117
|
+
builder.if_not_exists()
|
|
1118
|
+
|
|
1119
|
+
pk_cols = [primary_key] if isinstance(primary_key, str) else [str(col) for col in (primary_key or ()) if col]
|
|
1120
|
+
use_inline_pk = len(pk_cols) == 1
|
|
1121
|
+
dialect_str = _normalize_dialect(dialect) if dialect else None
|
|
1122
|
+
text_type = sql_type_for_category("text", dialect_str)
|
|
1123
|
+
|
|
1124
|
+
for field in fields:
|
|
1125
|
+
col_name = str(field.name)
|
|
1126
|
+
dtype = sql_type_from_arrow_type(field.type, dialect=dialect_str)
|
|
1127
|
+
is_pk_member = col_name in pk_cols
|
|
1128
|
+
if is_pk_member and dtype == text_type:
|
|
1129
|
+
dtype = sql_type_for_category("key_text", dialect_str)
|
|
1130
|
+
not_null = is_pk_member or not bool(getattr(field, "nullable", True))
|
|
1131
|
+
builder.column(
|
|
1132
|
+
name=_record_field_name(col_name, dialect_str),
|
|
1133
|
+
dtype=dtype,
|
|
1134
|
+
not_null=not_null,
|
|
1135
|
+
primary_key=use_inline_pk and is_pk_member,
|
|
1136
|
+
)
|
|
1137
|
+
|
|
1138
|
+
if len(pk_cols) > 1:
|
|
1139
|
+
builder.primary_key_constraint([_record_field_name(col, dialect_str) for col in pk_cols])
|
|
1140
|
+
|
|
1141
|
+
return builder
|
|
1142
|
+
|
|
1143
|
+
@classmethod
|
|
1144
|
+
def from_records(
|
|
1145
|
+
cls,
|
|
1146
|
+
table_name: str,
|
|
1147
|
+
records: "Sequence[Mapping[str, Any] | Any]",
|
|
1148
|
+
*,
|
|
1149
|
+
schema: "str | None" = None,
|
|
1150
|
+
primary_key: "str | Sequence[str] | None" = None,
|
|
1151
|
+
if_not_exists: bool = False,
|
|
1152
|
+
dialect: "DialectType" = None,
|
|
1153
|
+
) -> "CreateTable":
|
|
1154
|
+
"""Infer a CreateTable builder from a sequence of mapping or struct records."""
|
|
1155
|
+
if not records:
|
|
1156
|
+
msg = "Cannot infer table schema from empty records"
|
|
1157
|
+
raise SQLBuilderError(msg)
|
|
1158
|
+
|
|
1159
|
+
norm_records = [row if isinstance(row, Mapping) else _normalize_metadata_row(row) for row in records]
|
|
1160
|
+
ordered_columns: list[str] = []
|
|
1161
|
+
seen_columns: set[str] = set()
|
|
1162
|
+
for row in norm_records:
|
|
1163
|
+
for key in row:
|
|
1164
|
+
col_str = str(key)
|
|
1165
|
+
if col_str not in seen_columns:
|
|
1166
|
+
seen_columns.add(col_str)
|
|
1167
|
+
ordered_columns.append(col_str)
|
|
1168
|
+
|
|
1169
|
+
if not ordered_columns:
|
|
1170
|
+
msg = "Cannot infer table schema from empty records"
|
|
1171
|
+
raise SQLBuilderError(msg)
|
|
1172
|
+
|
|
1173
|
+
builder = cls(table_name, dialect=dialect)
|
|
1174
|
+
if schema:
|
|
1175
|
+
builder.in_schema(schema)
|
|
1176
|
+
if if_not_exists:
|
|
1177
|
+
builder.if_not_exists()
|
|
1178
|
+
|
|
1179
|
+
pk_cols = [primary_key] if isinstance(primary_key, str) else [str(col) for col in (primary_key or ()) if col]
|
|
1180
|
+
use_inline_pk = len(pk_cols) == 1
|
|
1181
|
+
dialect_str = _normalize_dialect(dialect) if dialect else None
|
|
1182
|
+
|
|
1183
|
+
for col_name in ordered_columns:
|
|
1184
|
+
has_null = False
|
|
1185
|
+
values: list[Any] = []
|
|
1186
|
+
for row in norm_records:
|
|
1187
|
+
if col_name not in row or row[col_name] is None:
|
|
1188
|
+
has_null = True
|
|
1189
|
+
else:
|
|
1190
|
+
values.append(row[col_name])
|
|
1191
|
+
|
|
1192
|
+
is_pk_member = col_name in pk_cols
|
|
1193
|
+
not_null = is_pk_member or not has_null
|
|
1194
|
+
dtype = _infer_sql_type_from_values(values, dialect=dialect_str, key=is_pk_member)
|
|
1195
|
+
builder.column(
|
|
1196
|
+
name=_record_field_name(col_name, dialect_str),
|
|
1197
|
+
dtype=dtype,
|
|
1198
|
+
not_null=not_null,
|
|
1199
|
+
primary_key=use_inline_pk and is_pk_member,
|
|
1200
|
+
)
|
|
1201
|
+
|
|
1202
|
+
if len(pk_cols) > 1:
|
|
1203
|
+
builder.primary_key_constraint([_record_field_name(col, dialect_str) for col in pk_cols])
|
|
1204
|
+
|
|
1205
|
+
return builder
|
|
1206
|
+
|
|
1207
|
+
def _create_base_expression(self) -> "exp.Expr":
|
|
1208
|
+
"""Create the SQLGlot expression for CREATE TABLE."""
|
|
1209
|
+
self._require(self._columns or self._like_table, "Table must have at least one column or use LIKE clause")
|
|
1210
|
+
|
|
1211
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
1212
|
+
primary_key_after_schema = _normalize_dialect(effective_dialect) == "spanner"
|
|
1213
|
+
has_table_level_pk = primary_key_after_schema or any(
|
|
1214
|
+
c.constraint_type == CONSTRAINT_TYPE_PRIMARY_KEY and not self._is_redundant_single_column_primary_key(c)
|
|
1215
|
+
for c in self._constraints
|
|
1216
|
+
)
|
|
1217
|
+
column_defs: list[exp.Expr] = []
|
|
1218
|
+
for col in self._columns:
|
|
1219
|
+
col_expr = build_column_expression(
|
|
1220
|
+
col, dialect=effective_dialect, include_primary_key=not has_table_level_pk
|
|
1221
|
+
)
|
|
1222
|
+
column_defs.append(col_expr)
|
|
1223
|
+
|
|
1224
|
+
for constraint in self._constraints:
|
|
1225
|
+
if primary_key_after_schema and constraint.constraint_type == CONSTRAINT_TYPE_PRIMARY_KEY:
|
|
1226
|
+
continue
|
|
1227
|
+
if self._is_redundant_single_column_primary_key(constraint):
|
|
1228
|
+
continue
|
|
1229
|
+
|
|
1230
|
+
constraint_expr = build_constraint_expression(constraint, dialect=effective_dialect)
|
|
1231
|
+
if constraint_expr:
|
|
1232
|
+
column_defs.append(constraint_expr)
|
|
1233
|
+
|
|
1234
|
+
props: list[exp.Expr] = []
|
|
1235
|
+
primary_key_constraint = self._find_primary_key_constraint()
|
|
1236
|
+
if primary_key_after_schema and primary_key_constraint is not None:
|
|
1237
|
+
props.append(
|
|
1238
|
+
exp.PrimaryKey(
|
|
1239
|
+
expressions=[
|
|
1240
|
+
exp.Ordered(this=_parse_ddl_identifier(col, dialect=effective_dialect), nulls_first=True)
|
|
1241
|
+
for col in primary_key_constraint.columns
|
|
1242
|
+
]
|
|
1243
|
+
)
|
|
1244
|
+
)
|
|
1245
|
+
if self._table_options.get("engine"):
|
|
1246
|
+
engine_name = _validate_clause_identifier(self._table_options.get("engine"), label="table engine")
|
|
1247
|
+
props.append(exp.Property(this=exp.to_identifier("ENGINE"), value=exp.to_identifier(engine_name)))
|
|
1248
|
+
if self._tablespace:
|
|
1249
|
+
tablespace_name = _validate_clause_identifier(self._tablespace, label="tablespace")
|
|
1250
|
+
props.append(exp.Property(this=exp.to_identifier("TABLESPACE"), value=exp.to_identifier(tablespace_name)))
|
|
1251
|
+
if self._partition_by:
|
|
1252
|
+
props.append(exp.PartitionedByProperty(this=_parse_partition_by(self._partition_by, effective_dialect)))
|
|
1253
|
+
|
|
1254
|
+
for key, value in self._table_options.items():
|
|
1255
|
+
if key != "engine":
|
|
1256
|
+
option_key = _validate_clause_identifier(key, label="table option key")
|
|
1257
|
+
props.append(exp.Property(this=exp.to_identifier(option_key.upper()), value=exp.convert(value)))
|
|
1258
|
+
|
|
1259
|
+
table_identifier = _parse_ddl_table(self._table_name, schema=self._schema, dialect=effective_dialect)
|
|
1260
|
+
|
|
1261
|
+
schema_expr = exp.Schema(this=table_identifier, expressions=column_defs)
|
|
1262
|
+
|
|
1263
|
+
if self._temporary:
|
|
1264
|
+
props.append(exp.TemporaryProperty())
|
|
1265
|
+
if self._like_table:
|
|
1266
|
+
props.append(exp.LikeProperty(this=_parse_ddl_table(self._like_table, dialect=effective_dialect)))
|
|
1267
|
+
properties_node = _wrap_properties(props)
|
|
1268
|
+
|
|
1269
|
+
create_target: exp.Expr = table_identifier if self._like_table and not column_defs else schema_expr
|
|
1270
|
+
return exp.Create(kind="TABLE", this=create_target, exists=self._if_not_exists, properties=properties_node)
|
|
1271
|
+
|
|
1272
|
+
def _has_primary_key_constraint(self) -> bool:
|
|
1273
|
+
"""Check if table already has a primary key constraint."""
|
|
1274
|
+
return any(c.constraint_type == CONSTRAINT_TYPE_PRIMARY_KEY for c in self._constraints)
|
|
1275
|
+
|
|
1276
|
+
def _find_primary_key_constraint(self) -> "ConstraintDefinition | None":
|
|
1277
|
+
"""Find existing primary key constraint."""
|
|
1278
|
+
return next((c for c in self._constraints if c.constraint_type == CONSTRAINT_TYPE_PRIMARY_KEY), None)
|
|
1279
|
+
|
|
1280
|
+
def _validate_foreign_key_action(self, action: "str | None", action_type: str) -> None:
|
|
1281
|
+
"""Validate foreign key action (ON DELETE or ON UPDATE)."""
|
|
1282
|
+
if action and action.upper() not in VALID_FOREIGN_KEY_ACTIONS:
|
|
1283
|
+
self._raise_builder_error(f"Invalid {action_type} action: {action}")
|
|
1284
|
+
|
|
1285
|
+
def _is_redundant_single_column_primary_key(self, constraint: "ConstraintDefinition") -> bool:
|
|
1286
|
+
"""Check if constraint is a redundant single-column primary key."""
|
|
1287
|
+
if (
|
|
1288
|
+
constraint.constraint_type != CONSTRAINT_TYPE_PRIMARY_KEY
|
|
1289
|
+
or len(constraint.columns) != 1
|
|
1290
|
+
or constraint.name is not None
|
|
1291
|
+
):
|
|
1292
|
+
return False
|
|
1293
|
+
|
|
1294
|
+
col_name = constraint.columns[0]
|
|
1295
|
+
return any(c.name == col_name and c.primary_key for c in self._columns)
|
|
1296
|
+
|
|
1297
|
+
def _add_metadata_column(
|
|
1298
|
+
self,
|
|
1299
|
+
row: "Mapping[str, Any]",
|
|
1300
|
+
col_name: str,
|
|
1301
|
+
*,
|
|
1302
|
+
dialect: "DialectType",
|
|
1303
|
+
fragment_dialect: "DialectType",
|
|
1304
|
+
primary_key: bool,
|
|
1305
|
+
unique: bool,
|
|
1306
|
+
fallback_default: Any,
|
|
1307
|
+
warnings: "list[str]",
|
|
1308
|
+
) -> None:
|
|
1309
|
+
"""Add one catalog column, recording any attribute that cannot be reproduced in ``warnings``."""
|
|
1310
|
+
computed_source, persisted, is_generated = _resolve_metadata_computed(row)
|
|
1311
|
+
computed_expr: exp.Expr | None = None
|
|
1312
|
+
if computed_source is not None:
|
|
1313
|
+
computed_expr = (
|
|
1314
|
+
computed_source
|
|
1315
|
+
if isinstance(computed_source, exp.Expr)
|
|
1316
|
+
else _parse_catalog_fragment(computed_source, fragment_dialect)
|
|
1317
|
+
)
|
|
1318
|
+
if computed_expr is None:
|
|
1319
|
+
warnings.append(
|
|
1320
|
+
f"Column {col_name!r} generated expression could not be parsed; emitted as a plain column: "
|
|
1321
|
+
f"{computed_source}"
|
|
1322
|
+
)
|
|
1323
|
+
elif is_generated:
|
|
1324
|
+
warnings.append(
|
|
1325
|
+
f"Column {col_name!r} is a generated column but the catalog did not report its expression; "
|
|
1326
|
+
"emitted as a plain column"
|
|
1327
|
+
)
|
|
1328
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
1329
|
+
if computed_expr is not None and persisted and norm_dialect in _VIRTUAL_ONLY_GENERATED_DIALECTS:
|
|
1330
|
+
warnings.append(
|
|
1331
|
+
f"Column {col_name!r} is a stored generated column; {norm_dialect} supports only virtual generated "
|
|
1332
|
+
"columns, so it is emitted as virtual"
|
|
1333
|
+
)
|
|
1334
|
+
persisted = False
|
|
1335
|
+
is_computed = computed_expr is not None or is_generated
|
|
1336
|
+
identity_val = None if is_computed else _resolve_metadata_identity(row)
|
|
1337
|
+
auto_increment = False if (is_computed or identity_val is not None) else _resolve_metadata_auto_increment(row)
|
|
1338
|
+
if (identity_val is not None or auto_increment) and (
|
|
1339
|
+
norm_dialect in {"duckdb", "bigquery"} or (norm_dialect == "sqlite" and not primary_key)
|
|
1340
|
+
):
|
|
1341
|
+
warnings.append(
|
|
1342
|
+
f"Column {col_name!r} is an identity/auto-increment column; {norm_dialect} cannot express it on this "
|
|
1343
|
+
"column, so it is emitted without automatic value generation"
|
|
1344
|
+
)
|
|
1345
|
+
identity_val = None
|
|
1346
|
+
auto_increment = False
|
|
1347
|
+
raw_default = (
|
|
1348
|
+
None
|
|
1349
|
+
if (is_computed or identity_val is not None or auto_increment)
|
|
1350
|
+
else (_first_present(row, "column_default", "default", "default_value") or fallback_default)
|
|
1351
|
+
)
|
|
1352
|
+
default_val: Any = None
|
|
1353
|
+
if raw_default is not None:
|
|
1354
|
+
default_val = _parse_metadata_default(
|
|
1355
|
+
raw_default, source_dialect=fragment_dialect, extra=str(row.get("extra") or "")
|
|
1356
|
+
)
|
|
1357
|
+
if default_val is _UNPARSEABLE_DEFAULT:
|
|
1358
|
+
warnings.append(f"Column {col_name!r} default could not be parsed and was omitted: {raw_default}")
|
|
1359
|
+
default_val = None
|
|
1360
|
+
dtype = _translate_catalog_type(
|
|
1361
|
+
_resolve_metadata_column_type(row, dialect=fragment_dialect), fragment_dialect, dialect
|
|
1362
|
+
)
|
|
1363
|
+
if _INLINE_ENUM_TYPE_RE.match(dtype) and norm_dialect not in _INLINE_ENUM_DIALECTS:
|
|
1364
|
+
warnings.append(
|
|
1365
|
+
f"Column {col_name!r} uses an inline ENUM type that {norm_dialect or 'the target dialect'} cannot "
|
|
1366
|
+
"declare; emitted as text"
|
|
1367
|
+
)
|
|
1368
|
+
dtype = sql_type_for_category("text", norm_dialect)
|
|
1369
|
+
col_comment = (
|
|
1370
|
+
_first_non_empty_str(row, "comment", "column_comment", "description") if norm_dialect == "mysql" else None
|
|
1371
|
+
)
|
|
1372
|
+
self.column(
|
|
1373
|
+
name=_catalog_name(col_name, dialect, fragment_dialect),
|
|
1374
|
+
dtype=dtype,
|
|
1375
|
+
default=default_val,
|
|
1376
|
+
not_null=_resolve_metadata_not_null(row),
|
|
1377
|
+
primary_key=primary_key,
|
|
1378
|
+
unique=unique,
|
|
1379
|
+
auto_increment=auto_increment,
|
|
1380
|
+
comment=col_comment,
|
|
1381
|
+
check=_first_non_empty_str(row, "check"),
|
|
1382
|
+
collate=_first_non_empty_str(row, "collate", "collation", "collation_name"),
|
|
1383
|
+
identity=identity_val,
|
|
1384
|
+
generated_expression=computed_expr,
|
|
1385
|
+
persisted=persisted,
|
|
1386
|
+
)
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
class _SingleObjectDropBuilder(DDLBuilder, _IfExistsDDLMixin, _CascadeRestrictDDLMixin):
|
|
1390
|
+
"""Template base for DROP builders targeting a single named object.
|
|
1391
|
+
|
|
1392
|
+
Subclasses set ``_drop_kind`` (the SQL object kind) and ``_object_label``
|
|
1393
|
+
(the human-readable noun used in error messages), and may override
|
|
1394
|
+
``_build_drop_this`` or ``_drop_expression_args`` to customize the
|
|
1395
|
+
generated ``exp.Drop`` expression.
|
|
1396
|
+
"""
|
|
1397
|
+
|
|
1398
|
+
__slots__ = ("_cascade", "_if_exists", "_name")
|
|
1399
|
+
|
|
1400
|
+
_drop_kind: "ClassVar[str]" = ""
|
|
1401
|
+
_object_label: "ClassVar[str]" = ""
|
|
1402
|
+
|
|
1403
|
+
def __init__(self, name: str, dialect: "DialectType" = None) -> None:
|
|
1404
|
+
super().__init__(dialect=dialect)
|
|
1405
|
+
self._name = name
|
|
1406
|
+
self._if_exists = False
|
|
1407
|
+
self._cascade: bool | None = None
|
|
1408
|
+
|
|
1409
|
+
def _build_drop_this(self) -> exp.Expr:
|
|
1410
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
1411
|
+
if self._drop_kind == "SCHEMA":
|
|
1412
|
+
return _parse_ddl_identifier(self._name, dialect=effective_dialect)
|
|
1413
|
+
return _parse_ddl_table(self._name, dialect=effective_dialect)
|
|
1414
|
+
|
|
1415
|
+
def _drop_expression_args(self) -> "dict[str, Any]":
|
|
1416
|
+
return {}
|
|
1417
|
+
|
|
1418
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
1419
|
+
self._require(self._name, f"{self._object_label} name must be set for DROP {self._drop_kind}.")
|
|
1420
|
+
return exp.Drop(
|
|
1421
|
+
kind=self._drop_kind,
|
|
1422
|
+
tables=[self._build_drop_this()],
|
|
1423
|
+
exists=self._if_exists,
|
|
1424
|
+
cascade=self._cascade,
|
|
1425
|
+
**self._drop_expression_args(),
|
|
1426
|
+
)
|
|
1427
|
+
|
|
1428
|
+
|
|
1429
|
+
class DropTable(_SingleObjectDropBuilder):
|
|
1430
|
+
"""Builder for DROP TABLE [IF EXISTS] ... [CASCADE|RESTRICT]."""
|
|
1431
|
+
|
|
1432
|
+
__slots__ = ()
|
|
1433
|
+
|
|
1434
|
+
_drop_kind: "ClassVar[str]" = "TABLE"
|
|
1435
|
+
_object_label: "ClassVar[str]" = "Table"
|
|
1436
|
+
|
|
1437
|
+
def __init__(self, table_name: str, dialect: "DialectType" = None) -> None:
|
|
1438
|
+
"""Initialize DROP TABLE with table name.
|
|
1439
|
+
|
|
1440
|
+
Args:
|
|
1441
|
+
table_name: Name of the table to drop
|
|
1442
|
+
dialect: SQL dialect to use
|
|
1443
|
+
"""
|
|
1444
|
+
super().__init__(table_name, dialect=dialect)
|
|
1445
|
+
|
|
1446
|
+
def table(self, name: str) -> Self:
|
|
1447
|
+
self._name = name
|
|
1448
|
+
return self
|
|
1449
|
+
|
|
1450
|
+
|
|
1451
|
+
class DropIndex(_SingleObjectDropBuilder):
|
|
1452
|
+
"""Builder for ``DROP INDEX [IF EXISTS] ... [ON table] [CASCADE|RESTRICT]``."""
|
|
1453
|
+
|
|
1454
|
+
__slots__ = ("_table_name",)
|
|
1455
|
+
|
|
1456
|
+
_drop_kind: "ClassVar[str]" = "INDEX"
|
|
1457
|
+
_object_label: "ClassVar[str]" = "Index"
|
|
1458
|
+
|
|
1459
|
+
def __init__(self, index_name: str, dialect: "DialectType" = None) -> None:
|
|
1460
|
+
"""Initialize DROP INDEX with index name.
|
|
1461
|
+
|
|
1462
|
+
Args:
|
|
1463
|
+
index_name: Name of the index to drop
|
|
1464
|
+
dialect: SQL dialect to use
|
|
1465
|
+
"""
|
|
1466
|
+
super().__init__(index_name, dialect=dialect)
|
|
1467
|
+
self._table_name: str | None = None
|
|
1468
|
+
|
|
1469
|
+
def name(self, index_name: str) -> Self:
|
|
1470
|
+
self._name = index_name
|
|
1471
|
+
return self
|
|
1472
|
+
|
|
1473
|
+
def on_table(self, table_name: str) -> Self:
|
|
1474
|
+
self._table_name = table_name
|
|
1475
|
+
return self
|
|
1476
|
+
|
|
1477
|
+
def _drop_expression_args(self) -> "dict[str, Any]":
|
|
1478
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
1479
|
+
return {
|
|
1480
|
+
"cluster": exp.OnProperty(this=_parse_ddl_table(self._table_name, dialect=effective_dialect))
|
|
1481
|
+
if self._table_name
|
|
1482
|
+
else None
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
|
|
1486
|
+
class DropView(_SingleObjectDropBuilder):
|
|
1487
|
+
"""Builder for DROP VIEW [IF EXISTS] ... [CASCADE|RESTRICT]."""
|
|
1488
|
+
|
|
1489
|
+
__slots__ = ()
|
|
1490
|
+
|
|
1491
|
+
_drop_kind: "ClassVar[str]" = "VIEW"
|
|
1492
|
+
_object_label: "ClassVar[str]" = "View"
|
|
1493
|
+
|
|
1494
|
+
def __init__(self, view_name: str, dialect: "DialectType" = None) -> None:
|
|
1495
|
+
"""Initialize DROP VIEW with view name.
|
|
1496
|
+
|
|
1497
|
+
Args:
|
|
1498
|
+
view_name: Name of the view to drop
|
|
1499
|
+
dialect: SQL dialect to use
|
|
1500
|
+
"""
|
|
1501
|
+
super().__init__(view_name, dialect=dialect)
|
|
1502
|
+
|
|
1503
|
+
def name(self, view_name: str) -> Self:
|
|
1504
|
+
self._name = view_name
|
|
1505
|
+
return self
|
|
1506
|
+
|
|
1507
|
+
|
|
1508
|
+
class DropSchema(_SingleObjectDropBuilder):
|
|
1509
|
+
"""Builder for DROP SCHEMA [IF EXISTS] ... [CASCADE|RESTRICT]."""
|
|
1510
|
+
|
|
1511
|
+
__slots__ = ()
|
|
1512
|
+
|
|
1513
|
+
_drop_kind: "ClassVar[str]" = "SCHEMA"
|
|
1514
|
+
_object_label: "ClassVar[str]" = "Schema"
|
|
1515
|
+
|
|
1516
|
+
def __init__(self, schema_name: str, dialect: "DialectType" = None) -> None:
|
|
1517
|
+
"""Initialize DROP SCHEMA with schema name.
|
|
1518
|
+
|
|
1519
|
+
Args:
|
|
1520
|
+
schema_name: Name of the schema to drop
|
|
1521
|
+
dialect: SQL dialect to use
|
|
1522
|
+
"""
|
|
1523
|
+
super().__init__(schema_name, dialect=dialect)
|
|
1524
|
+
|
|
1525
|
+
def name(self, schema_name: str) -> Self:
|
|
1526
|
+
self._name = schema_name
|
|
1527
|
+
return self
|
|
1528
|
+
|
|
1529
|
+
|
|
1530
|
+
class DropMaterializedView(_SingleObjectDropBuilder):
|
|
1531
|
+
"""Builder for DROP MATERIALIZED VIEW [IF EXISTS] ... [CASCADE|RESTRICT]."""
|
|
1532
|
+
|
|
1533
|
+
__slots__ = ()
|
|
1534
|
+
|
|
1535
|
+
_drop_kind: "ClassVar[str]" = "MATERIALIZED VIEW"
|
|
1536
|
+
_object_label: "ClassVar[str]" = "View"
|
|
1537
|
+
|
|
1538
|
+
def __init__(self, view_name: str, dialect: "DialectType" = None) -> None:
|
|
1539
|
+
"""Initialize DROP MATERIALIZED VIEW with view name.
|
|
1540
|
+
|
|
1541
|
+
Args:
|
|
1542
|
+
view_name: Name of the materialized view to drop
|
|
1543
|
+
dialect: SQL dialect to use
|
|
1544
|
+
"""
|
|
1545
|
+
super().__init__(view_name, dialect=dialect)
|
|
1546
|
+
|
|
1547
|
+
def name(self, view_name: str) -> Self:
|
|
1548
|
+
"""Set the materialized view name."""
|
|
1549
|
+
self._name = view_name
|
|
1550
|
+
return self
|
|
1551
|
+
|
|
1552
|
+
|
|
1553
|
+
class CreateIndex(DDLBuilder, _IfNotExistsDDLMixin):
|
|
1554
|
+
"""Builder for CREATE [UNIQUE] INDEX [IF NOT EXISTS] ... ON ... (...)."""
|
|
1555
|
+
|
|
1556
|
+
__slots__ = (
|
|
1557
|
+
"_clustered",
|
|
1558
|
+
"_columns",
|
|
1559
|
+
"_if_not_exists",
|
|
1560
|
+
"_include_columns",
|
|
1561
|
+
"_index_name",
|
|
1562
|
+
"_schema",
|
|
1563
|
+
"_table_name",
|
|
1564
|
+
"_unique",
|
|
1565
|
+
"_using",
|
|
1566
|
+
"_where",
|
|
1567
|
+
)
|
|
1568
|
+
|
|
1569
|
+
def __init__(
|
|
1570
|
+
self,
|
|
1571
|
+
index_name: str,
|
|
1572
|
+
dialect: "DialectType" = None,
|
|
1573
|
+
include: "Sequence[str | exp.Expr] | None" = None,
|
|
1574
|
+
schema: "str | None" = None,
|
|
1575
|
+
) -> None:
|
|
1576
|
+
"""Initialize CREATE INDEX with index name.
|
|
1577
|
+
|
|
1578
|
+
Args:
|
|
1579
|
+
index_name: Name of the index to create
|
|
1580
|
+
dialect: SQL dialect to use
|
|
1581
|
+
include: Optional sequence of covering columns for INCLUDE (...)
|
|
1582
|
+
schema: Optional schema name for the target table
|
|
1583
|
+
"""
|
|
1584
|
+
super().__init__(dialect=dialect)
|
|
1585
|
+
self._index_name = index_name
|
|
1586
|
+
self._table_name: str | None = None
|
|
1587
|
+
self._schema: str | None = schema
|
|
1588
|
+
self._columns: list[str | exp.Ordered | exp.Expr] = []
|
|
1589
|
+
self._include_columns: list[str | exp.Expr] = list(include) if include is not None else []
|
|
1590
|
+
self._unique = False
|
|
1591
|
+
self._if_not_exists = False
|
|
1592
|
+
self._using: str | None = None
|
|
1593
|
+
self._where: str | exp.Expr | None = None
|
|
1594
|
+
self._clustered: bool | None = None
|
|
1595
|
+
|
|
1596
|
+
def name(self, index_name: str) -> Self:
|
|
1597
|
+
self._index_name = index_name
|
|
1598
|
+
return self
|
|
1599
|
+
|
|
1600
|
+
def in_schema(self, schema_name: str) -> Self:
|
|
1601
|
+
"""Set the schema for the indexed table."""
|
|
1602
|
+
self._schema = schema_name
|
|
1603
|
+
return self
|
|
1604
|
+
|
|
1605
|
+
def on(self, table_name: str, *cols: str | exp.Ordered | exp.Expr) -> Self:
|
|
1606
|
+
"""Set the target table (and optional index columns) for the index."""
|
|
1607
|
+
self._table_name = table_name
|
|
1608
|
+
if cols:
|
|
1609
|
+
self._columns.extend(cols)
|
|
1610
|
+
return self
|
|
1611
|
+
|
|
1612
|
+
def on_table(self, table_name: str) -> Self:
|
|
1613
|
+
self._table_name = table_name
|
|
1614
|
+
return self
|
|
1615
|
+
|
|
1616
|
+
def columns(self, *cols: str | exp.Ordered | exp.Expr) -> Self:
|
|
1617
|
+
self._columns.extend(cols)
|
|
1618
|
+
return self
|
|
1619
|
+
|
|
1620
|
+
def include(self, *columns: str | exp.Expr) -> Self:
|
|
1621
|
+
"""Add covering columns for the INCLUDE (...) clause."""
|
|
1622
|
+
self._include_columns.extend(columns)
|
|
1623
|
+
return self
|
|
1624
|
+
|
|
1625
|
+
def expressions(self, *exprs: str | exp.Expr) -> Self:
|
|
1626
|
+
self._columns.extend(exprs)
|
|
1627
|
+
return self
|
|
1628
|
+
|
|
1629
|
+
def unique(self) -> Self:
|
|
1630
|
+
self._unique = True
|
|
1631
|
+
return self
|
|
1632
|
+
|
|
1633
|
+
def using(self, method: str) -> Self:
|
|
1634
|
+
self._using = _validate_clause_identifier(method, label="index method")
|
|
1635
|
+
return self
|
|
1636
|
+
|
|
1637
|
+
def where(self, condition: str | exp.Expr) -> Self:
|
|
1638
|
+
if isinstance(condition, str):
|
|
1639
|
+
_parse_ddl_expression(condition, label="partial index predicate", dialect=self.dialect)
|
|
1640
|
+
else:
|
|
1641
|
+
_check_ddl_expression_nodes(condition, label="partial index predicate", text=condition.sql())
|
|
1642
|
+
self._where = condition
|
|
1643
|
+
return self
|
|
1644
|
+
|
|
1645
|
+
def clustered(self, value: bool = True) -> Self:
|
|
1646
|
+
"""Mark the index ``CLUSTERED`` (or ``NONCLUSTERED`` when ``value`` is false) on T-SQL.
|
|
1647
|
+
|
|
1648
|
+
Other dialects have no clustered-index DDL and ignore the setting.
|
|
1649
|
+
"""
|
|
1650
|
+
self._clustered = value
|
|
1651
|
+
return self
|
|
1652
|
+
|
|
1653
|
+
@classmethod
|
|
1654
|
+
def from_metadata(
|
|
1655
|
+
cls,
|
|
1656
|
+
index: "Mapping[str, Any] | Any",
|
|
1657
|
+
*,
|
|
1658
|
+
table_name: "str | None" = None,
|
|
1659
|
+
schema: "str | None" = None,
|
|
1660
|
+
dialect: "DialectType" = None,
|
|
1661
|
+
source_dialect: "DialectType" = None,
|
|
1662
|
+
known_columns: "Sequence[str] | None" = None,
|
|
1663
|
+
warnings: "list[str] | None" = None,
|
|
1664
|
+
) -> "CreateIndex | None":
|
|
1665
|
+
"""Build a CreateIndex builder from a structured index metadata row or IndexDetails object.
|
|
1666
|
+
|
|
1667
|
+
Native index SQL reported by the catalog (``native_sql`` or a ``CREATE ... INDEX``
|
|
1668
|
+
``definition``) is parsed for key expressions, sort order, and the partial-index
|
|
1669
|
+
predicate. Otherwise the catalog column list is used; entries that match
|
|
1670
|
+
``known_columns`` or are not expression-like are treated as identifiers.
|
|
1671
|
+
|
|
1672
|
+
Args:
|
|
1673
|
+
index: Index metadata row.
|
|
1674
|
+
table_name: Raw catalog table name (defaults to the row's table name).
|
|
1675
|
+
schema: Raw catalog schema name (defaults to the row's schema).
|
|
1676
|
+
dialect: Target dialect for the generated DDL.
|
|
1677
|
+
source_dialect: Dialect of catalog SQL fragments (defaults to ``dialect``).
|
|
1678
|
+
known_columns: Raw names of the table's columns.
|
|
1679
|
+
warnings: Collector for indexes that cannot be reproduced faithfully. When
|
|
1680
|
+
omitted, such an index raises instead of being dropped.
|
|
1681
|
+
|
|
1682
|
+
Returns:
|
|
1683
|
+
Configured builder, or ``None`` for primary-key, unique-constraint, and
|
|
1684
|
+
internal indexes (and for unreproducible indexes when ``warnings`` is given).
|
|
1685
|
+
|
|
1686
|
+
Raises:
|
|
1687
|
+
SQLBuilderError: When the index cannot be reproduced and no ``warnings`` collector is given.
|
|
1688
|
+
"""
|
|
1689
|
+
collected: list[str] = []
|
|
1690
|
+
builder = cls._from_metadata_row(
|
|
1691
|
+
_normalize_metadata_row(index),
|
|
1692
|
+
table_name=table_name,
|
|
1693
|
+
schema=schema,
|
|
1694
|
+
dialect=dialect,
|
|
1695
|
+
source_dialect=source_dialect,
|
|
1696
|
+
known_columns=known_columns,
|
|
1697
|
+
warnings=collected,
|
|
1698
|
+
)
|
|
1699
|
+
_deliver_metadata_warnings(collected, warnings, context="index")
|
|
1700
|
+
return builder
|
|
1701
|
+
|
|
1702
|
+
@classmethod
|
|
1703
|
+
def _from_metadata_row(
|
|
1704
|
+
cls,
|
|
1705
|
+
row: "Mapping[str, Any]",
|
|
1706
|
+
*,
|
|
1707
|
+
table_name: "str | None",
|
|
1708
|
+
schema: "str | None",
|
|
1709
|
+
dialect: "DialectType",
|
|
1710
|
+
source_dialect: "DialectType",
|
|
1711
|
+
known_columns: "Sequence[str] | None",
|
|
1712
|
+
warnings: "list[str]",
|
|
1713
|
+
) -> "CreateIndex | None":
|
|
1714
|
+
if _truthy_metadata_flag(_first_present(row, "is_primary", "is_primary_key", "primary_key")):
|
|
1715
|
+
return None
|
|
1716
|
+
if _truthy_metadata_flag(row.get("is_unique_constraint")):
|
|
1717
|
+
return None
|
|
1718
|
+
|
|
1719
|
+
index_name = _first_non_empty_str(row, "index_name", "name")
|
|
1720
|
+
if not index_name or index_name.lower().startswith("sqlite_autoindex_"):
|
|
1721
|
+
return None
|
|
1722
|
+
|
|
1723
|
+
resolved_table = table_name or _first_non_empty_str(row, "table_name", "table")
|
|
1724
|
+
resolved_schema = (
|
|
1725
|
+
schema if schema is not None else _first_non_empty_str(row, "schema_name", "schema", "table_schema")
|
|
1726
|
+
)
|
|
1727
|
+
if not resolved_table:
|
|
1728
|
+
return None
|
|
1729
|
+
|
|
1730
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
1731
|
+
if norm_dialect == "bigquery":
|
|
1732
|
+
warnings.append(
|
|
1733
|
+
f"BigQuery does not support secondary CREATE INDEX statements; index '{index_name}' omitted"
|
|
1734
|
+
)
|
|
1735
|
+
return None
|
|
1736
|
+
|
|
1737
|
+
fragment_dialect = source_dialect if source_dialect is not None else dialect
|
|
1738
|
+
storage_type = str(row.get("type_desc") or "").strip().upper().replace("_", " ")
|
|
1739
|
+
if storage_type and storage_type not in {"CLUSTERED", "NONCLUSTERED", "HEAP"}:
|
|
1740
|
+
warnings.append(f"Index {index_name}: {storage_type} indexes are not reproduced; index omitted")
|
|
1741
|
+
return None
|
|
1742
|
+
|
|
1743
|
+
key_exprs: list[exp.Expr] | None = None
|
|
1744
|
+
where_expr: exp.Expr | None = None
|
|
1745
|
+
native_sql = _native_index_sql(row)
|
|
1746
|
+
if native_sql is not None:
|
|
1747
|
+
native_parts = _parse_native_index_sql(native_sql, fragment_dialect)
|
|
1748
|
+
if native_parts is not None:
|
|
1749
|
+
key_exprs, where_expr = native_parts
|
|
1750
|
+
|
|
1751
|
+
if key_exprs is None:
|
|
1752
|
+
key_exprs = _metadata_index_key_expressions(
|
|
1753
|
+
row,
|
|
1754
|
+
index_name,
|
|
1755
|
+
dialect=dialect,
|
|
1756
|
+
fragment_dialect=fragment_dialect,
|
|
1757
|
+
known_columns=known_columns,
|
|
1758
|
+
warnings=warnings,
|
|
1759
|
+
)
|
|
1760
|
+
if key_exprs is None:
|
|
1761
|
+
return None
|
|
1762
|
+
where_text = _first_non_empty_str(row, "where", "filter_definition", "predicate")
|
|
1763
|
+
has_filter_val = row.get("has_filter")
|
|
1764
|
+
is_partial = _truthy_metadata_flag(has_filter_val) or _truthy_metadata_flag(row.get("is_partial"))
|
|
1765
|
+
if where_text and (has_filter_val is None or _truthy_metadata_flag(has_filter_val)):
|
|
1766
|
+
where_expr = _parse_catalog_fragment(where_text, fragment_dialect)
|
|
1767
|
+
if where_expr is None:
|
|
1768
|
+
warnings.append(f"Index {index_name}: predicate could not be parsed ({where_text}); index omitted")
|
|
1769
|
+
return None
|
|
1770
|
+
elif is_partial:
|
|
1771
|
+
warnings.append(f"Index {index_name} is partial but the catalog did not report its predicate; omitted")
|
|
1772
|
+
return None
|
|
1773
|
+
|
|
1774
|
+
if where_expr is not None and norm_dialect in _NO_PARTIAL_INDEX_DIALECTS:
|
|
1775
|
+
warnings.append(f"DuckDB does not support partial indexes; index '{index_name}' omitted")
|
|
1776
|
+
return None
|
|
1777
|
+
|
|
1778
|
+
builder = cls(_catalog_name(index_name, dialect, fragment_dialect), dialect=dialect)
|
|
1779
|
+
if resolved_schema:
|
|
1780
|
+
builder.in_schema(_catalog_name(resolved_schema, dialect, fragment_dialect))
|
|
1781
|
+
builder.on(_catalog_name(resolved_table, dialect, fragment_dialect), *key_exprs)
|
|
1782
|
+
|
|
1783
|
+
if _truthy_metadata_flag(_first_present(row, "is_unique", "unique")):
|
|
1784
|
+
builder.unique()
|
|
1785
|
+
|
|
1786
|
+
inc_cols = _split_metadata_columns(_first_present(row, "included_columns", "include", "include_columns"))
|
|
1787
|
+
if inc_cols:
|
|
1788
|
+
if (
|
|
1789
|
+
norm_dialect is None
|
|
1790
|
+
or norm_dialect in _INCLUDE_INDEX_DIALECTS
|
|
1791
|
+
or norm_dialect in _STORING_INDEX_DIALECTS
|
|
1792
|
+
):
|
|
1793
|
+
builder.include(*(_catalog_name(col, dialect, fragment_dialect) for col in inc_cols))
|
|
1794
|
+
else:
|
|
1795
|
+
warnings.append(
|
|
1796
|
+
f"Index {index_name}: covering INCLUDE columns are not supported on {norm_dialect} and were omitted"
|
|
1797
|
+
)
|
|
1798
|
+
|
|
1799
|
+
if where_expr is not None:
|
|
1800
|
+
builder.where(where_expr)
|
|
1801
|
+
|
|
1802
|
+
if storage_type in {"CLUSTERED", "NONCLUSTERED"}:
|
|
1803
|
+
builder.clustered(storage_type == "CLUSTERED")
|
|
1804
|
+
|
|
1805
|
+
using_method = _first_non_empty_str(row, "using", "index_type", "access_method")
|
|
1806
|
+
if using_method:
|
|
1807
|
+
using_upper = using_method.strip().upper().replace("_", " ")
|
|
1808
|
+
if using_upper not in _MSSQL_STORAGE_INDEX_TYPES and not (
|
|
1809
|
+
using_upper == "BTREE" and norm_dialect in {"tsql", "mssql", "sqlite"}
|
|
1810
|
+
):
|
|
1811
|
+
builder.using(using_method.strip())
|
|
1812
|
+
|
|
1813
|
+
return builder
|
|
1814
|
+
|
|
1815
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
1816
|
+
"""Build the CREATE INDEX expression for this builder.
|
|
1817
|
+
|
|
1818
|
+
String columns become identifiers unless they are expression-like (parentheses,
|
|
1819
|
+
operators, literals) or carry an explicit ASC/DESC suffix; names that are not bare
|
|
1820
|
+
identifiers (for example ``Customer Id``) are quoted rather than parsed. String
|
|
1821
|
+
``where`` clauses are parsed with the target dialect.
|
|
1822
|
+
"""
|
|
1823
|
+
self._require(self._index_name and self._table_name, "Index name and table name must be set for CREATE INDEX.")
|
|
1824
|
+
|
|
1825
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
1826
|
+
norm_dialect = _normalize_dialect(effective_dialect) if effective_dialect else None
|
|
1827
|
+
cols: list[exp.Expr] = [
|
|
1828
|
+
_index_column_expression(col, effective_dialect) if isinstance(col, str) else col.copy()
|
|
1829
|
+
for col in self._columns
|
|
1830
|
+
]
|
|
1831
|
+
|
|
1832
|
+
include_cols: list[exp.Expr] = []
|
|
1833
|
+
for inc_col in self._include_columns:
|
|
1834
|
+
if isinstance(inc_col, str):
|
|
1835
|
+
include_cols.append(_parse_ddl_identifier(inc_col, dialect=effective_dialect))
|
|
1836
|
+
else:
|
|
1837
|
+
include_cols.append(inc_col.copy())
|
|
1838
|
+
|
|
1839
|
+
where_expr: exp.Expr | None = None
|
|
1840
|
+
if self._where is not None:
|
|
1841
|
+
if norm_dialect in _NO_PARTIAL_INDEX_DIALECTS:
|
|
1842
|
+
self._raise_builder_error(
|
|
1843
|
+
"DuckDB does not support partial indexes; a full index would change the index semantics."
|
|
1844
|
+
)
|
|
1845
|
+
where_expr = (
|
|
1846
|
+
_parse_ddl_expression(self._where, label="partial index predicate", dialect=norm_dialect)
|
|
1847
|
+
if isinstance(self._where, str)
|
|
1848
|
+
else _check_ddl_expression_nodes(
|
|
1849
|
+
self._where.copy(), label="partial index predicate", text=self._where.sql()
|
|
1850
|
+
)
|
|
1851
|
+
)
|
|
1852
|
+
|
|
1853
|
+
index_params = exp.IndexParameters(columns=cols) if cols else None
|
|
1854
|
+
|
|
1855
|
+
if include_cols:
|
|
1856
|
+
if index_params is None:
|
|
1857
|
+
index_params = exp.IndexParameters()
|
|
1858
|
+
index_params.set("include", include_cols)
|
|
1859
|
+
|
|
1860
|
+
if self._using:
|
|
1861
|
+
if index_params is None:
|
|
1862
|
+
index_params = exp.IndexParameters()
|
|
1863
|
+
index_params.set("using", exp.Var(this=_validate_clause_identifier(self._using, label="index method")))
|
|
1864
|
+
|
|
1865
|
+
if where_expr is not None:
|
|
1866
|
+
if index_params is None:
|
|
1867
|
+
index_params = exp.IndexParameters()
|
|
1868
|
+
index_params.set("where", exp.Where(this=where_expr))
|
|
1869
|
+
|
|
1870
|
+
index_expr = exp.Index(
|
|
1871
|
+
this=_parse_ddl_identifier(self._index_name, dialect=effective_dialect),
|
|
1872
|
+
table=_parse_ddl_table(cast("str", self._table_name), schema=self._schema, dialect=effective_dialect),
|
|
1873
|
+
params=index_params,
|
|
1874
|
+
)
|
|
1875
|
+
|
|
1876
|
+
kind = "INDEX"
|
|
1877
|
+
if self._clustered is not None and norm_dialect == "tsql":
|
|
1878
|
+
kind = "CLUSTERED INDEX" if self._clustered else "NONCLUSTERED INDEX"
|
|
1879
|
+
return exp.Create(kind=kind, this=index_expr, unique=self._unique, exists=self._if_not_exists)
|
|
1880
|
+
|
|
1881
|
+
def _optimize_expression(
|
|
1882
|
+
self, expression: exp.Expr, *, force: bool = False, dialect: "DialectType" = None
|
|
1883
|
+
) -> exp.Expr:
|
|
1884
|
+
"""Optimize the CREATE INDEX expression while preserving explicit ASC ordering."""
|
|
1885
|
+
explicit_asc_positions: list[int] = []
|
|
1886
|
+
index_params = expression.find(exp.IndexParameters)
|
|
1887
|
+
if index_params is not None:
|
|
1888
|
+
for idx, col_expr in enumerate(index_params.args.get("columns") or []):
|
|
1889
|
+
if isinstance(col_expr, exp.Ordered) and col_expr.args.get("desc") is False:
|
|
1890
|
+
explicit_asc_positions.append(idx)
|
|
1891
|
+
|
|
1892
|
+
optimized = super()._optimize_expression(expression, force=force, dialect=dialect)
|
|
1893
|
+
if explicit_asc_positions:
|
|
1894
|
+
optimized = optimized.copy()
|
|
1895
|
+
opt_params = optimized.find(exp.IndexParameters)
|
|
1896
|
+
if opt_params is not None:
|
|
1897
|
+
opt_columns = opt_params.args.get("columns") or []
|
|
1898
|
+
for idx in explicit_asc_positions:
|
|
1899
|
+
if idx < len(opt_columns) and isinstance(opt_columns[idx], exp.Ordered):
|
|
1900
|
+
opt_columns[idx].set("desc", False)
|
|
1901
|
+
return optimized
|
|
1902
|
+
|
|
1903
|
+
def _has_sql_postprocessing(self) -> bool:
|
|
1904
|
+
return bool(self._include_columns)
|
|
1905
|
+
|
|
1906
|
+
def _postprocess_built_sql(self, sql_string: str, dialect: "DialectType" = None) -> str:
|
|
1907
|
+
target_dialect = _normalize_dialect(dialect) if dialect is not None else self.dialect_name
|
|
1908
|
+
if self._include_columns and target_dialect in _STORING_INDEX_DIALECTS:
|
|
1909
|
+
return sql_string.replace(" INCLUDE (", " STORING (", 1)
|
|
1910
|
+
return sql_string
|
|
1911
|
+
|
|
1912
|
+
|
|
1913
|
+
class Truncate(DDLBuilder, _CascadeRestrictDDLMixin):
|
|
1914
|
+
"""Builder for ``TRUNCATE TABLE ... [CASCADE|RESTRICT] [RESTART IDENTITY|CONTINUE IDENTITY]``."""
|
|
1915
|
+
|
|
1916
|
+
__slots__ = ("_cascade", "_identity", "_table_name")
|
|
1917
|
+
|
|
1918
|
+
def __init__(self, table_name: str, dialect: "DialectType" = None) -> None:
|
|
1919
|
+
"""Initialize TRUNCATE with table name.
|
|
1920
|
+
|
|
1921
|
+
Args:
|
|
1922
|
+
table_name: Name of the table to truncate
|
|
1923
|
+
dialect: SQL dialect to use
|
|
1924
|
+
"""
|
|
1925
|
+
super().__init__(dialect=dialect)
|
|
1926
|
+
self._table_name = table_name
|
|
1927
|
+
self._cascade: bool | None = None
|
|
1928
|
+
self._identity: str | None = None
|
|
1929
|
+
|
|
1930
|
+
def table(self, name: str) -> Self:
|
|
1931
|
+
self._table_name = name
|
|
1932
|
+
return self
|
|
1933
|
+
|
|
1934
|
+
def restart_identity(self) -> Self:
|
|
1935
|
+
self._identity = "RESTART"
|
|
1936
|
+
return self
|
|
1937
|
+
|
|
1938
|
+
def continue_identity(self) -> Self:
|
|
1939
|
+
self._identity = "CONTINUE"
|
|
1940
|
+
return self
|
|
1941
|
+
|
|
1942
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
1943
|
+
self._require(self._table_name, "Table name must be set for TRUNCATE TABLE.")
|
|
1944
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
1945
|
+
identity_expr = exp.Var(this=self._identity) if self._identity else None
|
|
1946
|
+
option_expr = (
|
|
1947
|
+
exp.Var(this="CASCADE")
|
|
1948
|
+
if self._cascade is True
|
|
1949
|
+
else exp.Var(this="RESTRICT")
|
|
1950
|
+
if self._cascade is False
|
|
1951
|
+
else None
|
|
1952
|
+
)
|
|
1953
|
+
return exp.TruncateTable(
|
|
1954
|
+
expressions=[_parse_ddl_table(self._table_name, dialect=effective_dialect)],
|
|
1955
|
+
option=option_expr,
|
|
1956
|
+
identity=identity_expr,
|
|
1957
|
+
)
|
|
1958
|
+
|
|
1959
|
+
|
|
1960
|
+
class AlterOperation:
|
|
1961
|
+
"""Represents a single ALTER TABLE operation."""
|
|
1962
|
+
|
|
1963
|
+
__slots__ = (
|
|
1964
|
+
"after_column",
|
|
1965
|
+
"column_definition",
|
|
1966
|
+
"column_name",
|
|
1967
|
+
"constraint_definition",
|
|
1968
|
+
"constraint_name",
|
|
1969
|
+
"first",
|
|
1970
|
+
"new_name",
|
|
1971
|
+
"new_type",
|
|
1972
|
+
"operation_type",
|
|
1973
|
+
"using_expression",
|
|
1974
|
+
)
|
|
1975
|
+
|
|
1976
|
+
def __init__(
|
|
1977
|
+
self,
|
|
1978
|
+
operation_type: str,
|
|
1979
|
+
column_name: "str | None" = None,
|
|
1980
|
+
column_definition: "ColumnDefinition | None" = None,
|
|
1981
|
+
constraint_name: "str | None" = None,
|
|
1982
|
+
constraint_definition: "ConstraintDefinition | None" = None,
|
|
1983
|
+
new_type: "str | None" = None,
|
|
1984
|
+
new_name: "str | None" = None,
|
|
1985
|
+
after_column: "str | None" = None,
|
|
1986
|
+
first: bool = False,
|
|
1987
|
+
using_expression: "str | None" = None,
|
|
1988
|
+
) -> None:
|
|
1989
|
+
self.operation_type = operation_type
|
|
1990
|
+
self.column_name = column_name
|
|
1991
|
+
self.column_definition = column_definition
|
|
1992
|
+
self.constraint_name = constraint_name
|
|
1993
|
+
self.constraint_definition = constraint_definition
|
|
1994
|
+
self.new_type = new_type
|
|
1995
|
+
self.new_name = new_name
|
|
1996
|
+
self.after_column = after_column
|
|
1997
|
+
self.first = first
|
|
1998
|
+
self.using_expression = using_expression
|
|
1999
|
+
|
|
2000
|
+
|
|
2001
|
+
class CreateSchema(DDLBuilder, _IfNotExistsDDLMixin):
|
|
2002
|
+
"""Builder for CREATE SCHEMA [IF NOT EXISTS] schema_name [AUTHORIZATION user_name]."""
|
|
2003
|
+
|
|
2004
|
+
__slots__ = ("_authorization", "_if_not_exists", "_schema_name")
|
|
2005
|
+
|
|
2006
|
+
def __init__(self, schema_name: str, dialect: "DialectType" = None) -> None:
|
|
2007
|
+
"""Initialize CREATE SCHEMA with schema name.
|
|
2008
|
+
|
|
2009
|
+
Args:
|
|
2010
|
+
schema_name: Name of the schema to create
|
|
2011
|
+
dialect: SQL dialect to use
|
|
2012
|
+
"""
|
|
2013
|
+
super().__init__(dialect=dialect)
|
|
2014
|
+
self._schema_name = schema_name
|
|
2015
|
+
self._if_not_exists = False
|
|
2016
|
+
self._authorization: str | None = None
|
|
2017
|
+
|
|
2018
|
+
def name(self, schema_name: str) -> Self:
|
|
2019
|
+
self._schema_name = schema_name
|
|
2020
|
+
return self
|
|
2021
|
+
|
|
2022
|
+
def authorization(self, user_name: str) -> Self:
|
|
2023
|
+
self._authorization = user_name
|
|
2024
|
+
return self
|
|
2025
|
+
|
|
2026
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2027
|
+
self._require(self._schema_name, "Schema name must be set for CREATE SCHEMA.")
|
|
2028
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2029
|
+
props: list[exp.Property] = []
|
|
2030
|
+
if self._authorization:
|
|
2031
|
+
props.append(
|
|
2032
|
+
exp.Property(
|
|
2033
|
+
this=exp.to_identifier("AUTHORIZATION"),
|
|
2034
|
+
value=_parse_ddl_identifier(self._authorization, dialect=effective_dialect),
|
|
2035
|
+
)
|
|
2036
|
+
)
|
|
2037
|
+
properties_node = _wrap_properties(props)
|
|
2038
|
+
return exp.Create(
|
|
2039
|
+
kind="SCHEMA",
|
|
2040
|
+
this=_parse_ddl_identifier(self._schema_name, dialect=effective_dialect),
|
|
2041
|
+
exists=self._if_not_exists,
|
|
2042
|
+
properties=properties_node,
|
|
2043
|
+
)
|
|
2044
|
+
|
|
2045
|
+
|
|
2046
|
+
class CreateTableAsSelect(DDLBuilder, _IfNotExistsDDLMixin):
|
|
2047
|
+
"""Builder for CREATE TABLE [IF NOT EXISTS] ... AS SELECT ... (CTAS).
|
|
2048
|
+
|
|
2049
|
+
Methods:
|
|
2050
|
+
- name(table_name: str): Set the table name.
|
|
2051
|
+
- if_not_exists(): Add IF NOT EXISTS.
|
|
2052
|
+
- columns(*cols: str): Set explicit column list (optional).
|
|
2053
|
+
- as_select(select_query): Set the SELECT source (SQL, SelectBuilder, or str).
|
|
2054
|
+
"""
|
|
2055
|
+
|
|
2056
|
+
__slots__ = ("_columns", "_if_not_exists", "_select_query", "_table_name")
|
|
2057
|
+
|
|
2058
|
+
def __init__(self, dialect: "DialectType" = None) -> None:
|
|
2059
|
+
super().__init__(dialect=dialect)
|
|
2060
|
+
self._table_name: str | None = None
|
|
2061
|
+
self._if_not_exists = False
|
|
2062
|
+
self._columns: list[str] = []
|
|
2063
|
+
self._select_query: object | None = None
|
|
2064
|
+
|
|
2065
|
+
def name(self, table_name: str) -> Self:
|
|
2066
|
+
self._table_name = table_name
|
|
2067
|
+
return self
|
|
2068
|
+
|
|
2069
|
+
def columns(self, *cols: str) -> Self:
|
|
2070
|
+
self._columns = list(cols)
|
|
2071
|
+
return self
|
|
2072
|
+
|
|
2073
|
+
def as_select(self, select_query: "str | exp.Expr | Any") -> Self:
|
|
2074
|
+
self._select_query = select_query
|
|
2075
|
+
return self
|
|
2076
|
+
|
|
2077
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2078
|
+
self._require(self._table_name, "Table name must be set for CREATE TABLE AS SELECT.")
|
|
2079
|
+
if self._select_query is None:
|
|
2080
|
+
self._raise_builder_error("SELECT query must be set for CREATE TABLE AS SELECT.")
|
|
2081
|
+
|
|
2082
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2083
|
+
select_expr = self._resolve_select_query(self._select_query, "CTAS", require_select_type=False)
|
|
2084
|
+
|
|
2085
|
+
create_target: exp.Expr = _parse_ddl_table(cast("str", self._table_name), dialect=effective_dialect)
|
|
2086
|
+
if self._columns:
|
|
2087
|
+
create_target = exp.Schema(
|
|
2088
|
+
this=create_target,
|
|
2089
|
+
expressions=[_parse_ddl_identifier(c, dialect=effective_dialect) for c in self._columns],
|
|
2090
|
+
)
|
|
2091
|
+
|
|
2092
|
+
return exp.Create(kind="TABLE", this=create_target, exists=self._if_not_exists, expression=select_expr)
|
|
2093
|
+
|
|
2094
|
+
|
|
2095
|
+
class CreateMaterializedView(DDLBuilder, _IfNotExistsDDLMixin):
|
|
2096
|
+
"""Builder for CREATE MATERIALIZED VIEW [IF NOT EXISTS] ... AS SELECT ..."""
|
|
2097
|
+
|
|
2098
|
+
__slots__ = (
|
|
2099
|
+
"_columns",
|
|
2100
|
+
"_hints",
|
|
2101
|
+
"_if_not_exists",
|
|
2102
|
+
"_refresh_mode",
|
|
2103
|
+
"_select_query",
|
|
2104
|
+
"_storage_parameters",
|
|
2105
|
+
"_tablespace",
|
|
2106
|
+
"_using_index",
|
|
2107
|
+
"_view_name",
|
|
2108
|
+
"_with_data",
|
|
2109
|
+
)
|
|
2110
|
+
|
|
2111
|
+
def __init__(self, view_name: str, dialect: "DialectType" = None) -> None:
|
|
2112
|
+
"""Initialize CREATE MATERIALIZED VIEW with view name.
|
|
2113
|
+
|
|
2114
|
+
Args:
|
|
2115
|
+
view_name: Name of the materialized view to create
|
|
2116
|
+
dialect: SQL dialect to use
|
|
2117
|
+
"""
|
|
2118
|
+
super().__init__(dialect=dialect)
|
|
2119
|
+
self._view_name = view_name
|
|
2120
|
+
self._if_not_exists = False
|
|
2121
|
+
self._columns: list[str] = []
|
|
2122
|
+
self._select_query: Any = None
|
|
2123
|
+
self._with_data: bool | None = None
|
|
2124
|
+
self._refresh_mode: str | None = None
|
|
2125
|
+
self._storage_parameters: dict[str, Any] = {}
|
|
2126
|
+
self._tablespace: str | None = None
|
|
2127
|
+
self._using_index: str | None = None
|
|
2128
|
+
self._hints: list[str] = []
|
|
2129
|
+
|
|
2130
|
+
def name(self, view_name: str) -> Self:
|
|
2131
|
+
self._view_name = view_name
|
|
2132
|
+
return self
|
|
2133
|
+
|
|
2134
|
+
def columns(self, *cols: str) -> Self:
|
|
2135
|
+
self._columns = list(cols)
|
|
2136
|
+
return self
|
|
2137
|
+
|
|
2138
|
+
def as_select(self, select_query: "str | exp.Expr | Any") -> Self:
|
|
2139
|
+
self._select_query = select_query
|
|
2140
|
+
return self
|
|
2141
|
+
|
|
2142
|
+
def with_data(self) -> Self:
|
|
2143
|
+
self._with_data = True
|
|
2144
|
+
return self
|
|
2145
|
+
|
|
2146
|
+
def no_data(self) -> Self:
|
|
2147
|
+
self._with_data = False
|
|
2148
|
+
return self
|
|
2149
|
+
|
|
2150
|
+
def refresh_mode(self, mode: str) -> Self:
|
|
2151
|
+
self._refresh_mode = mode
|
|
2152
|
+
return self
|
|
2153
|
+
|
|
2154
|
+
def storage_parameter(self, key: str, value: Any) -> Self:
|
|
2155
|
+
self._storage_parameters[_validate_clause_identifier(key, label="storage parameter key")] = value
|
|
2156
|
+
return self
|
|
2157
|
+
|
|
2158
|
+
def tablespace(self, name: str) -> Self:
|
|
2159
|
+
self._tablespace = _validate_clause_identifier(name, label="tablespace")
|
|
2160
|
+
return self
|
|
2161
|
+
|
|
2162
|
+
def using_index(self, index_name: str) -> Self:
|
|
2163
|
+
self._using_index = _validate_clause_identifier(index_name, label="index name")
|
|
2164
|
+
return self
|
|
2165
|
+
|
|
2166
|
+
def with_hint(self, hint: str) -> Self:
|
|
2167
|
+
self._hints.append(hint)
|
|
2168
|
+
return self
|
|
2169
|
+
|
|
2170
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2171
|
+
self._require(self._view_name, "View name must be set for CREATE MATERIALIZED VIEW.")
|
|
2172
|
+
if self._select_query is None:
|
|
2173
|
+
self._raise_builder_error("SELECT query must be set for CREATE MATERIALIZED VIEW.")
|
|
2174
|
+
|
|
2175
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2176
|
+
select_expr = self._resolve_select_query(self._select_query, "materialized view")
|
|
2177
|
+
|
|
2178
|
+
schema_expr = _build_optional_column_schema(self._columns, dialect=effective_dialect)
|
|
2179
|
+
|
|
2180
|
+
props: list[exp.Property] = []
|
|
2181
|
+
if self._refresh_mode:
|
|
2182
|
+
props.append(exp.Property(this=exp.to_identifier("REFRESH_MODE"), value=exp.convert(self._refresh_mode)))
|
|
2183
|
+
if self._tablespace:
|
|
2184
|
+
tablespace_name = _validate_clause_identifier(self._tablespace, label="tablespace")
|
|
2185
|
+
props.append(exp.Property(this=exp.to_identifier("TABLESPACE"), value=exp.to_identifier(tablespace_name)))
|
|
2186
|
+
if self._using_index:
|
|
2187
|
+
index_name = _validate_clause_identifier(self._using_index, label="index name")
|
|
2188
|
+
props.append(exp.Property(this=exp.to_identifier("USING_INDEX"), value=exp.to_identifier(index_name)))
|
|
2189
|
+
for k, v in self._storage_parameters.items():
|
|
2190
|
+
param_key = _validate_clause_identifier(k, label="storage parameter key")
|
|
2191
|
+
props.append(exp.Property(this=exp.to_identifier(param_key), value=exp.convert(str(v))))
|
|
2192
|
+
if self._with_data is not None:
|
|
2193
|
+
props.append(exp.WithDataProperty(no=not self._with_data))
|
|
2194
|
+
props.extend(exp.Property(this=exp.to_identifier("HINT"), value=exp.convert(hint)) for hint in self._hints)
|
|
2195
|
+
properties_node = _wrap_properties(props)
|
|
2196
|
+
|
|
2197
|
+
create_target: exp.Expr = _parse_ddl_table(self._view_name, dialect=effective_dialect)
|
|
2198
|
+
if schema_expr is not None:
|
|
2199
|
+
create_target = exp.Schema(this=create_target, expressions=schema_expr.expressions)
|
|
2200
|
+
|
|
2201
|
+
return exp.Create(
|
|
2202
|
+
kind="MATERIALIZED_VIEW",
|
|
2203
|
+
this=create_target,
|
|
2204
|
+
exists=self._if_not_exists,
|
|
2205
|
+
expression=select_expr,
|
|
2206
|
+
properties=properties_node,
|
|
2207
|
+
)
|
|
2208
|
+
|
|
2209
|
+
|
|
2210
|
+
class CreateView(DDLBuilder, _IfNotExistsDDLMixin):
|
|
2211
|
+
"""Builder for CREATE VIEW [IF NOT EXISTS] ... AS SELECT ..."""
|
|
2212
|
+
|
|
2213
|
+
__slots__ = ("_columns", "_hints", "_if_not_exists", "_select_query", "_view_name")
|
|
2214
|
+
|
|
2215
|
+
def __init__(self, view_name: str, dialect: "DialectType" = None) -> None:
|
|
2216
|
+
"""Initialize CREATE VIEW with view name.
|
|
2217
|
+
|
|
2218
|
+
Args:
|
|
2219
|
+
view_name: Name of the view to create
|
|
2220
|
+
dialect: SQL dialect to use
|
|
2221
|
+
"""
|
|
2222
|
+
super().__init__(dialect=dialect)
|
|
2223
|
+
self._view_name = view_name
|
|
2224
|
+
self._if_not_exists = False
|
|
2225
|
+
self._columns: list[str] = []
|
|
2226
|
+
self._select_query: Any = None
|
|
2227
|
+
self._hints: list[str] = []
|
|
2228
|
+
|
|
2229
|
+
def name(self, view_name: str) -> Self:
|
|
2230
|
+
self._view_name = view_name
|
|
2231
|
+
return self
|
|
2232
|
+
|
|
2233
|
+
def columns(self, *cols: str) -> Self:
|
|
2234
|
+
self._columns = list(cols)
|
|
2235
|
+
return self
|
|
2236
|
+
|
|
2237
|
+
def as_select(self, select_query: "str | exp.Expr | Any") -> Self:
|
|
2238
|
+
self._select_query = select_query
|
|
2239
|
+
return self
|
|
2240
|
+
|
|
2241
|
+
def with_hint(self, hint: str) -> Self:
|
|
2242
|
+
self._hints.append(hint)
|
|
2243
|
+
return self
|
|
2244
|
+
|
|
2245
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2246
|
+
self._require(self._view_name, "View name must be set for CREATE VIEW.")
|
|
2247
|
+
if self._select_query is None:
|
|
2248
|
+
self._raise_builder_error("SELECT query must be set for CREATE VIEW.")
|
|
2249
|
+
|
|
2250
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2251
|
+
select_expr = self._resolve_select_query(self._select_query, "view")
|
|
2252
|
+
|
|
2253
|
+
schema_expr = _build_optional_column_schema(self._columns, dialect=effective_dialect)
|
|
2254
|
+
|
|
2255
|
+
props: list[exp.Property] = [
|
|
2256
|
+
exp.Property(this=exp.to_identifier("HINT"), value=exp.convert(h)) for h in self._hints
|
|
2257
|
+
]
|
|
2258
|
+
properties_node = _wrap_properties(props)
|
|
2259
|
+
|
|
2260
|
+
create_target: exp.Expr = _parse_ddl_table(self._view_name, dialect=effective_dialect)
|
|
2261
|
+
if schema_expr is not None:
|
|
2262
|
+
create_target = exp.Schema(this=create_target, expressions=schema_expr.expressions)
|
|
2263
|
+
|
|
2264
|
+
return exp.Create(
|
|
2265
|
+
kind="VIEW",
|
|
2266
|
+
this=create_target,
|
|
2267
|
+
exists=self._if_not_exists,
|
|
2268
|
+
expression=select_expr,
|
|
2269
|
+
properties=properties_node,
|
|
2270
|
+
)
|
|
2271
|
+
|
|
2272
|
+
|
|
2273
|
+
class AlterTable(DDLBuilder, _IfExistsDDLMixin):
|
|
2274
|
+
"""Builder for ALTER TABLE operations."""
|
|
2275
|
+
|
|
2276
|
+
__slots__ = ("_if_exists", "_operations", "_schema", "_table_name")
|
|
2277
|
+
|
|
2278
|
+
def __init__(self, table_name: str, dialect: "DialectType" = None) -> None:
|
|
2279
|
+
super().__init__(dialect=dialect)
|
|
2280
|
+
self._table_name = table_name
|
|
2281
|
+
self._operations: list[AlterOperation] = []
|
|
2282
|
+
self._schema: str | None = None
|
|
2283
|
+
self._if_exists = False
|
|
2284
|
+
|
|
2285
|
+
def add_column(
|
|
2286
|
+
self,
|
|
2287
|
+
name: str,
|
|
2288
|
+
dtype: str,
|
|
2289
|
+
default: "Any | None" = None,
|
|
2290
|
+
not_null: bool = False,
|
|
2291
|
+
unique: bool = False,
|
|
2292
|
+
comment: "str | None" = None,
|
|
2293
|
+
after: "str | None" = None,
|
|
2294
|
+
first: bool = False,
|
|
2295
|
+
) -> "Self":
|
|
2296
|
+
"""Add a new column to the table."""
|
|
2297
|
+
if not name:
|
|
2298
|
+
self._raise_builder_error("Column name must be a non-empty string")
|
|
2299
|
+
|
|
2300
|
+
if not dtype:
|
|
2301
|
+
self._raise_builder_error("Column type must be a non-empty string")
|
|
2302
|
+
|
|
2303
|
+
column_def = ColumnDefinition(
|
|
2304
|
+
name=name, dtype=dtype, default=default, not_null=not_null, unique=unique, comment=comment
|
|
2305
|
+
)
|
|
2306
|
+
|
|
2307
|
+
operation = AlterOperation(
|
|
2308
|
+
operation_type="ADD COLUMN", column_definition=column_def, after_column=after, first=first
|
|
2309
|
+
)
|
|
2310
|
+
|
|
2311
|
+
self._operations.append(operation)
|
|
2312
|
+
return self
|
|
2313
|
+
|
|
2314
|
+
def drop_column(self, name: str, cascade: bool = False) -> "Self":
|
|
2315
|
+
"""Drop a column from the table."""
|
|
2316
|
+
if not name:
|
|
2317
|
+
self._raise_builder_error("Column name must be a non-empty string")
|
|
2318
|
+
|
|
2319
|
+
operation = AlterOperation(operation_type="DROP COLUMN CASCADE" if cascade else "DROP COLUMN", column_name=name)
|
|
2320
|
+
|
|
2321
|
+
self._operations.append(operation)
|
|
2322
|
+
return self
|
|
2323
|
+
|
|
2324
|
+
def alter_column_type(self, name: str, new_type: str, using: "str | None" = None) -> "Self":
|
|
2325
|
+
"""Change the type of an existing column."""
|
|
2326
|
+
if not name:
|
|
2327
|
+
self._raise_builder_error("Column name must be a non-empty string")
|
|
2328
|
+
|
|
2329
|
+
if not new_type:
|
|
2330
|
+
self._raise_builder_error("New type must be a non-empty string")
|
|
2331
|
+
|
|
2332
|
+
if using is not None:
|
|
2333
|
+
_parse_ddl_expression(using, label="ALTER COLUMN TYPE USING expression", dialect=self.dialect)
|
|
2334
|
+
|
|
2335
|
+
operation = AlterOperation(
|
|
2336
|
+
operation_type="ALTER COLUMN TYPE", column_name=name, new_type=new_type, using_expression=using
|
|
2337
|
+
)
|
|
2338
|
+
|
|
2339
|
+
self._operations.append(operation)
|
|
2340
|
+
return self
|
|
2341
|
+
|
|
2342
|
+
def rename_column(self, old_name: str, new_name: str) -> "Self":
|
|
2343
|
+
"""Rename a column."""
|
|
2344
|
+
if not old_name:
|
|
2345
|
+
self._raise_builder_error("Old column name must be a non-empty string")
|
|
2346
|
+
|
|
2347
|
+
if not new_name:
|
|
2348
|
+
self._raise_builder_error("New column name must be a non-empty string")
|
|
2349
|
+
|
|
2350
|
+
operation = AlterOperation(operation_type="RENAME COLUMN", column_name=old_name, new_name=new_name)
|
|
2351
|
+
|
|
2352
|
+
self._operations.append(operation)
|
|
2353
|
+
return self
|
|
2354
|
+
|
|
2355
|
+
def add_constraint(
|
|
2356
|
+
self,
|
|
2357
|
+
constraint_type: str,
|
|
2358
|
+
columns: "str | list[str] | None" = None,
|
|
2359
|
+
name: "str | None" = None,
|
|
2360
|
+
references_table: "str | None" = None,
|
|
2361
|
+
references_columns: "str | list[str] | None" = None,
|
|
2362
|
+
condition: "str | ColumnExpression | None" = None,
|
|
2363
|
+
on_delete: "str | None" = None,
|
|
2364
|
+
on_update: "str | None" = None,
|
|
2365
|
+
) -> "Self":
|
|
2366
|
+
"""Add a constraint to the table.
|
|
2367
|
+
|
|
2368
|
+
Args:
|
|
2369
|
+
constraint_type: Type of constraint ('PRIMARY KEY', 'FOREIGN KEY', 'UNIQUE', 'CHECK')
|
|
2370
|
+
columns: Column(s) for the constraint (not needed for CHECK)
|
|
2371
|
+
name: Optional constraint name
|
|
2372
|
+
references_table: Table referenced by foreign key
|
|
2373
|
+
references_columns: Columns referenced by foreign key
|
|
2374
|
+
condition: CHECK constraint condition
|
|
2375
|
+
on_delete: Foreign key ON DELETE action
|
|
2376
|
+
on_update: Foreign key ON UPDATE action
|
|
2377
|
+
"""
|
|
2378
|
+
if constraint_type.upper() not in VALID_CONSTRAINT_TYPES:
|
|
2379
|
+
self._raise_builder_error(f"Invalid constraint type: {constraint_type}")
|
|
2380
|
+
|
|
2381
|
+
col_list = None
|
|
2382
|
+
if columns is not None:
|
|
2383
|
+
col_list = [columns] if isinstance(columns, str) else list(columns)
|
|
2384
|
+
|
|
2385
|
+
ref_col_list = None
|
|
2386
|
+
if references_columns is not None:
|
|
2387
|
+
ref_col_list = [references_columns] if isinstance(references_columns, str) else list(references_columns)
|
|
2388
|
+
|
|
2389
|
+
condition_str: str | None = None
|
|
2390
|
+
if condition is not None:
|
|
2391
|
+
if has_sqlglot_expression(condition):
|
|
2392
|
+
sqlglot_expr = condition.sqlglot_expression
|
|
2393
|
+
condition_str = sqlglot_expr.sql(dialect=self.dialect, copy=False) if sqlglot_expr else str(condition)
|
|
2394
|
+
else:
|
|
2395
|
+
condition_str = str(condition)
|
|
2396
|
+
|
|
2397
|
+
if condition_str is not None and constraint_type.upper() == CONSTRAINT_TYPE_CHECK:
|
|
2398
|
+
_parse_ddl_expression(condition_str, label="CHECK constraint condition", dialect=self.dialect)
|
|
2399
|
+
|
|
2400
|
+
constraint_def = ConstraintDefinition(
|
|
2401
|
+
constraint_type=constraint_type.upper(),
|
|
2402
|
+
name=name,
|
|
2403
|
+
columns=col_list or [],
|
|
2404
|
+
references_table=references_table,
|
|
2405
|
+
references_columns=ref_col_list or [],
|
|
2406
|
+
condition=condition_str,
|
|
2407
|
+
on_delete=on_delete,
|
|
2408
|
+
on_update=on_update,
|
|
2409
|
+
)
|
|
2410
|
+
|
|
2411
|
+
operation = AlterOperation(operation_type="ADD CONSTRAINT", constraint_definition=constraint_def)
|
|
2412
|
+
|
|
2413
|
+
self._operations.append(operation)
|
|
2414
|
+
return self
|
|
2415
|
+
|
|
2416
|
+
def drop_constraint(self, name: str, cascade: bool = False) -> "Self":
|
|
2417
|
+
"""Drop a constraint from the table."""
|
|
2418
|
+
if not name:
|
|
2419
|
+
self._raise_builder_error("Constraint name must be a non-empty string")
|
|
2420
|
+
|
|
2421
|
+
operation = AlterOperation(
|
|
2422
|
+
operation_type="DROP CONSTRAINT CASCADE" if cascade else "DROP CONSTRAINT", constraint_name=name
|
|
2423
|
+
)
|
|
2424
|
+
|
|
2425
|
+
self._operations.append(operation)
|
|
2426
|
+
return self
|
|
2427
|
+
|
|
2428
|
+
def set_not_null(self, column: str) -> "Self":
|
|
2429
|
+
"""Set a column to NOT NULL."""
|
|
2430
|
+
operation = AlterOperation(operation_type="ALTER COLUMN SET NOT NULL", column_name=column)
|
|
2431
|
+
|
|
2432
|
+
self._operations.append(operation)
|
|
2433
|
+
return self
|
|
2434
|
+
|
|
2435
|
+
def drop_not_null(self, column: str) -> "Self":
|
|
2436
|
+
"""Remove NOT NULL constraint from a column."""
|
|
2437
|
+
operation = AlterOperation(operation_type="ALTER COLUMN DROP NOT NULL", column_name=column)
|
|
2438
|
+
|
|
2439
|
+
self._operations.append(operation)
|
|
2440
|
+
return self
|
|
2441
|
+
|
|
2442
|
+
def in_schema(self, schema_name: str) -> "Self":
|
|
2443
|
+
"""Set the schema for the table."""
|
|
2444
|
+
self._schema = schema_name
|
|
2445
|
+
return self
|
|
2446
|
+
|
|
2447
|
+
def set_column_default(self, column: str, value: "Any") -> "Self":
|
|
2448
|
+
"""Set the default value for a column."""
|
|
2449
|
+
if not column:
|
|
2450
|
+
self._raise_builder_error("Column name must be a non-empty string")
|
|
2451
|
+
|
|
2452
|
+
column_def = ColumnDefinition(name=column, dtype="", default=value)
|
|
2453
|
+
operation = AlterOperation(
|
|
2454
|
+
operation_type="ALTER COLUMN SET DEFAULT", column_name=column, column_definition=column_def
|
|
2455
|
+
)
|
|
2456
|
+
self._operations.append(operation)
|
|
2457
|
+
return self
|
|
2458
|
+
|
|
2459
|
+
def drop_column_default(self, column: str) -> "Self":
|
|
2460
|
+
"""Remove the default value from a column."""
|
|
2461
|
+
if not column:
|
|
2462
|
+
self._raise_builder_error("Column name must be a non-empty string")
|
|
2463
|
+
|
|
2464
|
+
operation = AlterOperation(operation_type="ALTER COLUMN DROP DEFAULT", column_name=column)
|
|
2465
|
+
self._operations.append(operation)
|
|
2466
|
+
return self
|
|
2467
|
+
|
|
2468
|
+
def _create_base_expression(self) -> "exp.Expr":
|
|
2469
|
+
"""Create the SQLGlot expression for ALTER TABLE."""
|
|
2470
|
+
self._require(self._operations, "At least one operation must be specified for ALTER TABLE")
|
|
2471
|
+
|
|
2472
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2473
|
+
table = _parse_ddl_table(self._table_name, schema=self._schema, dialect=effective_dialect)
|
|
2474
|
+
|
|
2475
|
+
actions: list[exp.Expr] = [self._build_operation_expression(op) for op in self._operations]
|
|
2476
|
+
|
|
2477
|
+
return exp.Alter(this=table, kind="TABLE", actions=actions, exists=self._if_exists)
|
|
2478
|
+
|
|
2479
|
+
def _build_operation_expression(self, op: "AlterOperation") -> exp.Expr:
|
|
2480
|
+
"""Build a structured SQLGlot expression for a single alter operation."""
|
|
2481
|
+
op_type = op.operation_type.upper()
|
|
2482
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2483
|
+
|
|
2484
|
+
if op_type == "ADD COLUMN":
|
|
2485
|
+
if not op.column_definition:
|
|
2486
|
+
self._raise_builder_error("Column definition required for ADD COLUMN")
|
|
2487
|
+
col_expr = build_column_expression(op.column_definition, dialect=effective_dialect)
|
|
2488
|
+
if isinstance(col_expr, exp.ColumnDef) and (op.after_column or op.first):
|
|
2489
|
+
constraints = list(col_expr.args.get("constraints") or [])
|
|
2490
|
+
if op.after_column:
|
|
2491
|
+
constraints.append(
|
|
2492
|
+
exp.ColumnConstraint(
|
|
2493
|
+
kind=exp.ColumnPosition(
|
|
2494
|
+
this=_parse_ddl_identifier(op.after_column, dialect=effective_dialect), position="AFTER"
|
|
2495
|
+
)
|
|
2496
|
+
)
|
|
2497
|
+
)
|
|
2498
|
+
elif op.first:
|
|
2499
|
+
constraints.append(exp.ColumnConstraint(kind=exp.ColumnPosition(position="FIRST")))
|
|
2500
|
+
col_expr.set("constraints", constraints)
|
|
2501
|
+
return col_expr
|
|
2502
|
+
|
|
2503
|
+
if op_type == "DROP COLUMN":
|
|
2504
|
+
return exp.Drop(
|
|
2505
|
+
tables=[_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect)],
|
|
2506
|
+
kind="COLUMN",
|
|
2507
|
+
exists=True,
|
|
2508
|
+
)
|
|
2509
|
+
|
|
2510
|
+
if op_type == "DROP COLUMN CASCADE":
|
|
2511
|
+
return exp.Drop(
|
|
2512
|
+
tables=[_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect)],
|
|
2513
|
+
kind="COLUMN",
|
|
2514
|
+
cascade=True,
|
|
2515
|
+
exists=True,
|
|
2516
|
+
)
|
|
2517
|
+
|
|
2518
|
+
if op_type == "ALTER COLUMN TYPE":
|
|
2519
|
+
if not op.new_type:
|
|
2520
|
+
self._raise_builder_error("New type required for ALTER COLUMN TYPE")
|
|
2521
|
+
return exp.AlterColumn(
|
|
2522
|
+
this=_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect),
|
|
2523
|
+
dtype=_parse_column_type(op.column_name, op.new_type, effective_dialect),
|
|
2524
|
+
using=_parse_ddl_expression(
|
|
2525
|
+
op.using_expression, label="ALTER COLUMN TYPE USING expression", dialect=effective_dialect
|
|
2526
|
+
)
|
|
2527
|
+
if op.using_expression
|
|
2528
|
+
else None,
|
|
2529
|
+
)
|
|
2530
|
+
|
|
2531
|
+
if op_type == "RENAME COLUMN":
|
|
2532
|
+
return exp.RenameColumn(
|
|
2533
|
+
this=_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect),
|
|
2534
|
+
to=_parse_ddl_identifier(cast("str", op.new_name), dialect=effective_dialect),
|
|
2535
|
+
)
|
|
2536
|
+
|
|
2537
|
+
if op_type == "ADD CONSTRAINT":
|
|
2538
|
+
if not op.constraint_definition:
|
|
2539
|
+
self._raise_builder_error("Constraint definition required for ADD CONSTRAINT")
|
|
2540
|
+
constraint_expr = build_constraint_expression(op.constraint_definition, dialect=effective_dialect)
|
|
2541
|
+
return exp.AddConstraint(expressions=[constraint_expr])
|
|
2542
|
+
|
|
2543
|
+
if op_type == "DROP CONSTRAINT":
|
|
2544
|
+
return exp.Drop(
|
|
2545
|
+
tables=[_parse_ddl_identifier(cast("str", op.constraint_name), dialect=effective_dialect)],
|
|
2546
|
+
kind="CONSTRAINT",
|
|
2547
|
+
exists=True,
|
|
2548
|
+
)
|
|
2549
|
+
|
|
2550
|
+
if op_type == "DROP CONSTRAINT CASCADE":
|
|
2551
|
+
return exp.Drop(
|
|
2552
|
+
tables=[_parse_ddl_identifier(cast("str", op.constraint_name), dialect=effective_dialect)],
|
|
2553
|
+
kind="CONSTRAINT",
|
|
2554
|
+
cascade=True,
|
|
2555
|
+
exists=True,
|
|
2556
|
+
)
|
|
2557
|
+
|
|
2558
|
+
if op_type == "ALTER COLUMN SET NOT NULL":
|
|
2559
|
+
return exp.AlterColumn(
|
|
2560
|
+
this=_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect), allow_null=False
|
|
2561
|
+
)
|
|
2562
|
+
|
|
2563
|
+
if op_type == "ALTER COLUMN DROP NOT NULL":
|
|
2564
|
+
return exp.AlterColumn(
|
|
2565
|
+
this=_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect),
|
|
2566
|
+
drop=True,
|
|
2567
|
+
allow_null=True,
|
|
2568
|
+
)
|
|
2569
|
+
|
|
2570
|
+
if op_type == "ALTER COLUMN SET DEFAULT":
|
|
2571
|
+
if not op.column_definition or op.column_definition.default is None:
|
|
2572
|
+
self._raise_builder_error("Default value required for SET DEFAULT")
|
|
2573
|
+
default_val = op.column_definition.default
|
|
2574
|
+
default_expr: exp.Expr | None
|
|
2575
|
+
if isinstance(default_val, str):
|
|
2576
|
+
if self._is_sql_function_default(default_val):
|
|
2577
|
+
default_expr = exp.maybe_parse(default_val, dialect=effective_dialect)
|
|
2578
|
+
else:
|
|
2579
|
+
default_expr = exp.convert(default_val)
|
|
2580
|
+
elif isinstance(default_val, (int, float)):
|
|
2581
|
+
default_expr = exp.convert(default_val)
|
|
2582
|
+
elif default_val is True:
|
|
2583
|
+
default_expr = exp.true()
|
|
2584
|
+
elif default_val is False:
|
|
2585
|
+
default_expr = exp.false()
|
|
2586
|
+
else:
|
|
2587
|
+
default_expr = exp.convert(str(default_val))
|
|
2588
|
+
return exp.AlterColumn(
|
|
2589
|
+
this=_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect), default=default_expr
|
|
2590
|
+
)
|
|
2591
|
+
|
|
2592
|
+
if op_type == "ALTER COLUMN DROP DEFAULT":
|
|
2593
|
+
return exp.AlterColumn(
|
|
2594
|
+
this=_parse_ddl_identifier(cast("str", op.column_name), dialect=effective_dialect), drop=True
|
|
2595
|
+
)
|
|
2596
|
+
|
|
2597
|
+
self._raise_builder_error(f"Unknown operation type: {op.operation_type}")
|
|
2598
|
+
raise AssertionError
|
|
2599
|
+
|
|
2600
|
+
def _is_sql_function_default(self, default_val: str) -> bool:
|
|
2601
|
+
"""Check if default value is a SQL function or expression."""
|
|
2602
|
+
default_upper = default_val.upper()
|
|
2603
|
+
return (
|
|
2604
|
+
default_upper in {CURRENT_TIMESTAMP_KEYWORD, CURRENT_DATE_KEYWORD, CURRENT_TIME_KEYWORD}
|
|
2605
|
+
or "(" in default_val
|
|
2606
|
+
)
|
|
2607
|
+
|
|
2608
|
+
|
|
2609
|
+
class CommentOn(DDLBuilder):
|
|
2610
|
+
"""Builder for COMMENT ON ... IS ... statements."""
|
|
2611
|
+
|
|
2612
|
+
__slots__ = ("_column", "_comment", "_schema", "_table", "_target_type")
|
|
2613
|
+
|
|
2614
|
+
def __init__(self, dialect: "DialectType" = None) -> None:
|
|
2615
|
+
"""Initialize COMMENT ON builder.
|
|
2616
|
+
|
|
2617
|
+
Args:
|
|
2618
|
+
dialect: SQL dialect to use
|
|
2619
|
+
"""
|
|
2620
|
+
super().__init__(dialect=dialect)
|
|
2621
|
+
self._target_type: str | None = None
|
|
2622
|
+
self._table: str | None = None
|
|
2623
|
+
self._schema: str | None = None
|
|
2624
|
+
self._column: str | None = None
|
|
2625
|
+
self._comment: str | None = None
|
|
2626
|
+
|
|
2627
|
+
def in_schema(self, schema_name: str) -> Self:
|
|
2628
|
+
"""Set the schema for the target table or column."""
|
|
2629
|
+
self._schema = schema_name
|
|
2630
|
+
return self
|
|
2631
|
+
|
|
2632
|
+
def on_table(self, table: str) -> Self:
|
|
2633
|
+
self._target_type = "TABLE"
|
|
2634
|
+
self._table = table
|
|
2635
|
+
self._column = None
|
|
2636
|
+
return self
|
|
2637
|
+
|
|
2638
|
+
def on_column(self, table: str, column: str) -> Self:
|
|
2639
|
+
self._target_type = "COLUMN"
|
|
2640
|
+
self._table = table
|
|
2641
|
+
self._column = column
|
|
2642
|
+
return self
|
|
2643
|
+
|
|
2644
|
+
def is_(self, comment: str) -> Self:
|
|
2645
|
+
self._comment = comment
|
|
2646
|
+
return self
|
|
2647
|
+
|
|
2648
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2649
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2650
|
+
if self._target_type == "TABLE" and self._table and self._comment is not None:
|
|
2651
|
+
return exp.Comment(
|
|
2652
|
+
this=_parse_ddl_table(self._table, schema=self._schema, dialect=effective_dialect),
|
|
2653
|
+
kind="TABLE",
|
|
2654
|
+
expression=exp.convert(self._comment),
|
|
2655
|
+
)
|
|
2656
|
+
if self._target_type == "COLUMN" and self._table and self._column and self._comment is not None:
|
|
2657
|
+
table_expr = _parse_ddl_table(self._table, schema=self._schema, dialect=effective_dialect)
|
|
2658
|
+
col_expr = exp.Column(
|
|
2659
|
+
this=_parse_ddl_identifier(self._column, dialect=effective_dialect),
|
|
2660
|
+
table=table_expr.args.get("this"),
|
|
2661
|
+
db=table_expr.args.get("db"),
|
|
2662
|
+
catalog=table_expr.args.get("catalog"),
|
|
2663
|
+
)
|
|
2664
|
+
return exp.Comment(this=col_expr, kind="COLUMN", expression=exp.convert(self._comment))
|
|
2665
|
+
self._raise_builder_error("Must specify target and comment for COMMENT ON statement.")
|
|
2666
|
+
raise AssertionError
|
|
2667
|
+
|
|
2668
|
+
|
|
2669
|
+
class RenameTable(DDLBuilder):
|
|
2670
|
+
"""Builder for ALTER TABLE ... RENAME TO ... statements."""
|
|
2671
|
+
|
|
2672
|
+
__slots__ = ("_new_name", "_old_name")
|
|
2673
|
+
|
|
2674
|
+
def __init__(self, old_name: str, dialect: "DialectType" = None) -> None:
|
|
2675
|
+
"""Initialize RENAME TABLE with old name.
|
|
2676
|
+
|
|
2677
|
+
Args:
|
|
2678
|
+
old_name: Current name of the table
|
|
2679
|
+
dialect: SQL dialect to use
|
|
2680
|
+
"""
|
|
2681
|
+
super().__init__(dialect=dialect)
|
|
2682
|
+
self._old_name = old_name
|
|
2683
|
+
self._new_name: str | None = None
|
|
2684
|
+
|
|
2685
|
+
def table(self, old_name: str) -> Self:
|
|
2686
|
+
self._old_name = old_name
|
|
2687
|
+
return self
|
|
2688
|
+
|
|
2689
|
+
def to(self, new_name: str) -> Self:
|
|
2690
|
+
self._new_name = new_name
|
|
2691
|
+
return self
|
|
2692
|
+
|
|
2693
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2694
|
+
self._require(self._old_name and self._new_name, "Both old and new table names must be set for RENAME TABLE.")
|
|
2695
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2696
|
+
return exp.Alter(
|
|
2697
|
+
this=_parse_ddl_table(self._old_name, dialect=effective_dialect),
|
|
2698
|
+
kind="TABLE",
|
|
2699
|
+
actions=[exp.AlterRename(this=_parse_ddl_table(cast("str", self._new_name), dialect=effective_dialect))],
|
|
2700
|
+
)
|
|
2701
|
+
|
|
2702
|
+
|
|
2703
|
+
@mypyc_attr(allow_interpreted_subclasses=False)
|
|
2704
|
+
class CreateSequence(DDLBuilder):
|
|
2705
|
+
"""Builder for CREATE SEQUENCE statements."""
|
|
2706
|
+
|
|
2707
|
+
__slots__ = (
|
|
2708
|
+
"_cache",
|
|
2709
|
+
"_cycle",
|
|
2710
|
+
"_if_not_exists",
|
|
2711
|
+
"_increment_by",
|
|
2712
|
+
"_max_value",
|
|
2713
|
+
"_min_value",
|
|
2714
|
+
"_schema",
|
|
2715
|
+
"_sequence_name",
|
|
2716
|
+
"_start_with",
|
|
2717
|
+
)
|
|
2718
|
+
|
|
2719
|
+
def __init__(
|
|
2720
|
+
self,
|
|
2721
|
+
sequence_name: str,
|
|
2722
|
+
schema: "str | None" = None,
|
|
2723
|
+
if_not_exists: bool = False,
|
|
2724
|
+
start_with: "int | None" = None,
|
|
2725
|
+
increment_by: "int | None" = None,
|
|
2726
|
+
min_value: "int | None" = None,
|
|
2727
|
+
max_value: "int | None" = None,
|
|
2728
|
+
cycle: bool = False,
|
|
2729
|
+
cache: "int | None" = None,
|
|
2730
|
+
dialect: "DialectType" = None,
|
|
2731
|
+
) -> None:
|
|
2732
|
+
super().__init__(dialect=dialect)
|
|
2733
|
+
self._sequence_name = sequence_name
|
|
2734
|
+
self._schema = schema
|
|
2735
|
+
self._if_not_exists = if_not_exists
|
|
2736
|
+
self._start_with = _coerce_int_argument(start_with, name="start_with") if start_with is not None else None
|
|
2737
|
+
self._increment_by = (
|
|
2738
|
+
_coerce_int_argument(increment_by, name="increment_by") if increment_by is not None else None
|
|
2739
|
+
)
|
|
2740
|
+
self._min_value = _coerce_int_argument(min_value, name="min_value") if min_value is not None else None
|
|
2741
|
+
self._max_value = _coerce_int_argument(max_value, name="max_value") if max_value is not None else None
|
|
2742
|
+
self._cycle = cycle
|
|
2743
|
+
self._cache = _coerce_int_argument(cache, name="cache") if cache is not None else None
|
|
2744
|
+
|
|
2745
|
+
def name(self, sequence_name: str) -> Self:
|
|
2746
|
+
"""Set the sequence name."""
|
|
2747
|
+
self._sequence_name = sequence_name
|
|
2748
|
+
return self
|
|
2749
|
+
|
|
2750
|
+
def in_schema(self, schema_name: str) -> Self:
|
|
2751
|
+
"""Set the schema for the sequence."""
|
|
2752
|
+
self._schema = schema_name
|
|
2753
|
+
return self
|
|
2754
|
+
|
|
2755
|
+
def if_not_exists(self) -> Self:
|
|
2756
|
+
"""Add IF NOT EXISTS to the CREATE SEQUENCE statement."""
|
|
2757
|
+
self._if_not_exists = True
|
|
2758
|
+
return self
|
|
2759
|
+
|
|
2760
|
+
def start_with(self, value: int) -> Self:
|
|
2761
|
+
"""Set the START WITH value for the sequence."""
|
|
2762
|
+
self._start_with = _coerce_int_argument(value, name="start_with")
|
|
2763
|
+
return self
|
|
2764
|
+
|
|
2765
|
+
def increment_by(self, value: int) -> Self:
|
|
2766
|
+
"""Set the INCREMENT BY value for the sequence."""
|
|
2767
|
+
self._increment_by = _coerce_int_argument(value, name="increment_by")
|
|
2768
|
+
return self
|
|
2769
|
+
|
|
2770
|
+
def min_value(self, value: int) -> Self:
|
|
2771
|
+
"""Set the MINVALUE for the sequence."""
|
|
2772
|
+
self._min_value = _coerce_int_argument(value, name="min_value")
|
|
2773
|
+
return self
|
|
2774
|
+
|
|
2775
|
+
def max_value(self, value: int) -> Self:
|
|
2776
|
+
"""Set the MAXVALUE for the sequence."""
|
|
2777
|
+
self._max_value = _coerce_int_argument(value, name="max_value")
|
|
2778
|
+
return self
|
|
2779
|
+
|
|
2780
|
+
def cycle(self) -> Self:
|
|
2781
|
+
"""Enable CYCLE on the sequence."""
|
|
2782
|
+
self._cycle = True
|
|
2783
|
+
return self
|
|
2784
|
+
|
|
2785
|
+
def no_cycle(self) -> Self:
|
|
2786
|
+
"""Disable CYCLE on the sequence."""
|
|
2787
|
+
self._cycle = False
|
|
2788
|
+
return self
|
|
2789
|
+
|
|
2790
|
+
def cache(self, value: int) -> Self:
|
|
2791
|
+
"""Set the CACHE size for the sequence."""
|
|
2792
|
+
self._cache = _coerce_int_argument(value, name="cache")
|
|
2793
|
+
return self
|
|
2794
|
+
|
|
2795
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2796
|
+
"""Build the SQLGlot Create expression for this sequence.
|
|
2797
|
+
|
|
2798
|
+
Raises:
|
|
2799
|
+
SQLBuilderError: On SQLite (no sequences), or when Spanner is asked for options
|
|
2800
|
+
other than a start counter (Spanner sequences are bit-reversed and accept only
|
|
2801
|
+
``start_with_counter``).
|
|
2802
|
+
"""
|
|
2803
|
+
self._require(self._sequence_name, "Sequence name must be set for CREATE SEQUENCE.")
|
|
2804
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2805
|
+
norm_dialect = _normalize_dialect(effective_dialect) if effective_dialect else None
|
|
2806
|
+
if norm_dialect == "sqlite":
|
|
2807
|
+
self._raise_builder_error("SQLite has no sequences; use an INTEGER PRIMARY KEY column instead.")
|
|
2808
|
+
table_expr = _parse_ddl_table(self._sequence_name, schema=self._schema, dialect=effective_dialect)
|
|
2809
|
+
|
|
2810
|
+
if norm_dialect == "spanner":
|
|
2811
|
+
unsupported = [
|
|
2812
|
+
option
|
|
2813
|
+
for option, value in (
|
|
2814
|
+
("INCREMENT BY", self._increment_by),
|
|
2815
|
+
("MINVALUE", self._min_value),
|
|
2816
|
+
("MAXVALUE", self._max_value),
|
|
2817
|
+
("CACHE", self._cache),
|
|
2818
|
+
)
|
|
2819
|
+
if value is not None
|
|
2820
|
+
]
|
|
2821
|
+
if self._cycle:
|
|
2822
|
+
unsupported.append("CYCLE")
|
|
2823
|
+
if unsupported:
|
|
2824
|
+
self._raise_builder_error(
|
|
2825
|
+
f"Spanner sequences do not support {', '.join(unsupported)}; only start_with is available."
|
|
2826
|
+
)
|
|
2827
|
+
spanner_options: list[exp.Expr] = [
|
|
2828
|
+
exp.Property(this=exp.Var(this="sequence_kind"), value=exp.Literal.string("bit_reversed_positive"))
|
|
2829
|
+
]
|
|
2830
|
+
if self._start_with is not None:
|
|
2831
|
+
spanner_options.append(
|
|
2832
|
+
exp.Property(this=exp.Var(this="start_with_counter"), value=exp.Literal.number(self._start_with))
|
|
2833
|
+
)
|
|
2834
|
+
return exp.Create(
|
|
2835
|
+
this=table_expr,
|
|
2836
|
+
kind="SEQUENCE",
|
|
2837
|
+
exists=self._if_not_exists,
|
|
2838
|
+
properties=exp.Properties(expressions=spanner_options),
|
|
2839
|
+
)
|
|
2840
|
+
|
|
2841
|
+
options: list[exp.Expr] = [exp.Var(this="CYCLE")] if self._cycle else []
|
|
2842
|
+
has_seq_props = any(
|
|
2843
|
+
v is not None for v in (self._start_with, self._increment_by, self._min_value, self._max_value, self._cache)
|
|
2844
|
+
) or bool(options)
|
|
2845
|
+
|
|
2846
|
+
properties_node: exp.Properties | None = None
|
|
2847
|
+
if has_seq_props:
|
|
2848
|
+
seq_props = exp.SequenceProperties(
|
|
2849
|
+
start=exp.Literal.number(self._start_with) if self._start_with is not None else None,
|
|
2850
|
+
increment=exp.Literal.number(self._increment_by) if self._increment_by is not None else None,
|
|
2851
|
+
minvalue=exp.Literal.number(self._min_value) if self._min_value is not None else None,
|
|
2852
|
+
maxvalue=exp.Literal.number(self._max_value) if self._max_value is not None else None,
|
|
2853
|
+
cache=exp.Literal.number(self._cache) if self._cache is not None else None,
|
|
2854
|
+
options=options or None,
|
|
2855
|
+
)
|
|
2856
|
+
properties_node = exp.Properties(expressions=[seq_props])
|
|
2857
|
+
|
|
2858
|
+
return exp.Create(this=table_expr, kind="SEQUENCE", exists=self._if_not_exists, properties=properties_node)
|
|
2859
|
+
|
|
2860
|
+
|
|
2861
|
+
@mypyc_attr(allow_interpreted_subclasses=False)
|
|
2862
|
+
class DropSequence(DDLBuilder):
|
|
2863
|
+
"""Builder for DROP SEQUENCE statements."""
|
|
2864
|
+
|
|
2865
|
+
__slots__ = ("_cascade", "_if_exists", "_schema", "_sequence_name")
|
|
2866
|
+
|
|
2867
|
+
def __init__(
|
|
2868
|
+
self,
|
|
2869
|
+
sequence_name: str,
|
|
2870
|
+
schema: "str | None" = None,
|
|
2871
|
+
if_exists: bool = False,
|
|
2872
|
+
cascade: bool = False,
|
|
2873
|
+
dialect: "DialectType" = None,
|
|
2874
|
+
) -> None:
|
|
2875
|
+
super().__init__(dialect=dialect)
|
|
2876
|
+
self._sequence_name = sequence_name
|
|
2877
|
+
self._schema = schema
|
|
2878
|
+
self._if_exists = if_exists
|
|
2879
|
+
self._cascade = cascade
|
|
2880
|
+
|
|
2881
|
+
def name(self, sequence_name: str) -> Self:
|
|
2882
|
+
"""Set the sequence name."""
|
|
2883
|
+
self._sequence_name = sequence_name
|
|
2884
|
+
return self
|
|
2885
|
+
|
|
2886
|
+
def in_schema(self, schema_name: str) -> Self:
|
|
2887
|
+
"""Set the schema for the sequence."""
|
|
2888
|
+
self._schema = schema_name
|
|
2889
|
+
return self
|
|
2890
|
+
|
|
2891
|
+
def if_exists(self) -> Self:
|
|
2892
|
+
"""Add IF EXISTS to the DROP SEQUENCE statement."""
|
|
2893
|
+
self._if_exists = True
|
|
2894
|
+
return self
|
|
2895
|
+
|
|
2896
|
+
def cascade(self) -> Self:
|
|
2897
|
+
"""Add CASCADE to the DROP SEQUENCE statement."""
|
|
2898
|
+
self._cascade = True
|
|
2899
|
+
return self
|
|
2900
|
+
|
|
2901
|
+
def _create_base_expression(self) -> exp.Expr:
|
|
2902
|
+
"""Build the SQLGlot Drop expression for this sequence.
|
|
2903
|
+
|
|
2904
|
+
Raises:
|
|
2905
|
+
SQLBuilderError: On SQLite (no sequences), or when ``CASCADE`` is requested on a
|
|
2906
|
+
dialect whose ``DROP SEQUENCE`` has no ``CASCADE`` option.
|
|
2907
|
+
"""
|
|
2908
|
+
self._require(self._sequence_name, "Sequence name must be set for DROP SEQUENCE.")
|
|
2909
|
+
effective_dialect = self._expression_dialect or self.dialect_name
|
|
2910
|
+
norm_dialect = _normalize_dialect(effective_dialect) if effective_dialect else None
|
|
2911
|
+
if norm_dialect == "sqlite":
|
|
2912
|
+
self._raise_builder_error("SQLite has no sequences.")
|
|
2913
|
+
if self._cascade and norm_dialect in _NO_CASCADE_SEQUENCE_DIALECTS:
|
|
2914
|
+
self._raise_builder_error(f"DROP SEQUENCE ... CASCADE is not supported by {norm_dialect}.")
|
|
2915
|
+
table_expr = _parse_ddl_table(self._sequence_name, schema=self._schema, dialect=effective_dialect)
|
|
2916
|
+
return exp.Drop(
|
|
2917
|
+
this=table_expr, tables=[table_expr.copy()], kind="SEQUENCE", exists=self._if_exists, cascade=self._cascade
|
|
2918
|
+
)
|
|
2919
|
+
|
|
2920
|
+
|
|
2921
|
+
def compile_table_ddl_results(
|
|
2922
|
+
table_name: str,
|
|
2923
|
+
columns: "Sequence[Mapping[str, Any] | Any]",
|
|
2924
|
+
*,
|
|
2925
|
+
schema: "str | None" = None,
|
|
2926
|
+
constraints: "Sequence[Mapping[str, Any] | Any] | None" = None,
|
|
2927
|
+
foreign_keys: "Sequence[Mapping[str, Any] | Any] | None" = None,
|
|
2928
|
+
indexes: "Sequence[Mapping[str, Any] | Any] | None" = None,
|
|
2929
|
+
table_comment: "str | None" = None,
|
|
2930
|
+
column_comments: "Mapping[str, str] | None" = None,
|
|
2931
|
+
dialect: "DialectType" = None,
|
|
2932
|
+
source_dialect: "DialectType" = None,
|
|
2933
|
+
object_type: str = "table",
|
|
2934
|
+
warnings: tuple[str, ...] = (),
|
|
2935
|
+
) -> DDLResult:
|
|
2936
|
+
"""Compile structured catalog metadata into a generated DDLResult for a table.
|
|
2937
|
+
|
|
2938
|
+
Catalog attributes that cannot be reproduced on ``dialect`` (unreported generated
|
|
2939
|
+
expressions, partial-index predicates, expression index keys, unsupported referential
|
|
2940
|
+
actions, unparsable defaults) are listed in ``DDLResult.warnings`` and the result's
|
|
2941
|
+
fidelity becomes ``LOSSY`` instead of ``GENERATED``.
|
|
2942
|
+
|
|
2943
|
+
Args:
|
|
2944
|
+
table_name: Raw catalog table name.
|
|
2945
|
+
columns: Column metadata rows.
|
|
2946
|
+
schema: Raw catalog schema name.
|
|
2947
|
+
constraints: Constraint metadata rows.
|
|
2948
|
+
foreign_keys: Foreign key metadata rows.
|
|
2949
|
+
indexes: Index metadata rows.
|
|
2950
|
+
table_comment: Optional table comment.
|
|
2951
|
+
column_comments: Optional column comments keyed by raw column name.
|
|
2952
|
+
dialect: Target dialect for the generated DDL.
|
|
2953
|
+
source_dialect: Dialect of catalog SQL fragments (defaults to ``dialect``).
|
|
2954
|
+
object_type: Object type recorded on the result identity.
|
|
2955
|
+
warnings: Caller warnings to carry on the result.
|
|
2956
|
+
|
|
2957
|
+
Returns:
|
|
2958
|
+
Generated DDL result.
|
|
2959
|
+
"""
|
|
2960
|
+
dialect_str = _normalize_dialect(dialect) if dialect else None
|
|
2961
|
+
identity = ObjectIdentity(
|
|
2962
|
+
name=table_name, object_type=object_type, schema=schema, dialect=dialect_str, source=MetadataSource.GENERATED
|
|
2963
|
+
)
|
|
2964
|
+
if not columns:
|
|
2965
|
+
return DDLResult.unsupported(
|
|
2966
|
+
identity,
|
|
2967
|
+
source=MetadataSource.GENERATED,
|
|
2968
|
+
warnings=warnings or (f"No catalog columns found for {schema or '<default>'}.{table_name}",),
|
|
2969
|
+
)
|
|
2970
|
+
|
|
2971
|
+
lossy: list[str] = []
|
|
2972
|
+
normalized_columns = [_normalize_metadata_row(col) for col in columns]
|
|
2973
|
+
fragment_dialect = source_dialect if source_dialect is not None else dialect
|
|
2974
|
+
|
|
2975
|
+
merged_column_comments: dict[str, str] = {}
|
|
2976
|
+
for row in normalized_columns:
|
|
2977
|
+
col_name = _first_non_empty_str(row, "column_name", "name")
|
|
2978
|
+
col_comment = _first_non_empty_str(row, "comment", "column_comment", "description")
|
|
2979
|
+
if col_name and col_comment:
|
|
2980
|
+
merged_column_comments[col_name] = col_comment
|
|
2981
|
+
if column_comments:
|
|
2982
|
+
merged_column_comments.update({
|
|
2983
|
+
col_name: col_comment for col_name, col_comment in column_comments.items() if col_name and col_comment
|
|
2984
|
+
})
|
|
2985
|
+
|
|
2986
|
+
table_builder = CreateTable.from_metadata(
|
|
2987
|
+
table_name,
|
|
2988
|
+
normalized_columns,
|
|
2989
|
+
constraints=constraints,
|
|
2990
|
+
foreign_keys=foreign_keys,
|
|
2991
|
+
schema=schema,
|
|
2992
|
+
dialect=dialect,
|
|
2993
|
+
source_dialect=source_dialect,
|
|
2994
|
+
warnings=lossy,
|
|
2995
|
+
)
|
|
2996
|
+
if dialect_str == "mysql":
|
|
2997
|
+
if table_comment:
|
|
2998
|
+
table_builder.comment(table_comment)
|
|
2999
|
+
if merged_column_comments:
|
|
3000
|
+
by_builder_name = {
|
|
3001
|
+
_catalog_name(col_name, dialect, fragment_dialect): col_comment
|
|
3002
|
+
for col_name, col_comment in merged_column_comments.items()
|
|
3003
|
+
}
|
|
3004
|
+
for col_def in table_builder._columns:
|
|
3005
|
+
col_comment_val = by_builder_name.get(col_def.name) or merged_column_comments.get(col_def.name)
|
|
3006
|
+
if col_comment_val:
|
|
3007
|
+
col_def.comment = col_comment_val
|
|
3008
|
+
statements: list[str] = [table_builder.build(dialect=dialect).sql.rstrip(";").strip()]
|
|
3009
|
+
|
|
3010
|
+
known_columns = [
|
|
3011
|
+
col_name
|
|
3012
|
+
for col_name in (_first_non_empty_str(row, "column_name", "name") for row in normalized_columns)
|
|
3013
|
+
if col_name
|
|
3014
|
+
]
|
|
3015
|
+
constraint_names: set[str] = {
|
|
3016
|
+
c.name
|
|
3017
|
+
for c in table_builder._constraints
|
|
3018
|
+
if c.name and c.constraint_type in {CONSTRAINT_TYPE_PRIMARY_KEY, CONSTRAINT_TYPE_UNIQUE}
|
|
3019
|
+
}
|
|
3020
|
+
constrained_column_tuples: set[tuple[str, ...]] = {
|
|
3021
|
+
tuple(c.columns)
|
|
3022
|
+
for c in table_builder._constraints
|
|
3023
|
+
if c.columns and c.constraint_type in {CONSTRAINT_TYPE_PRIMARY_KEY, CONSTRAINT_TYPE_UNIQUE}
|
|
3024
|
+
}
|
|
3025
|
+
for col_def in table_builder._columns:
|
|
3026
|
+
if col_def.primary_key or col_def.unique:
|
|
3027
|
+
constrained_column_tuples.add((col_def.name,))
|
|
3028
|
+
|
|
3029
|
+
for index_row in _group_metadata_index_rows(indexes or ()):
|
|
3030
|
+
raw_idx_name = _first_non_empty_str(index_row, "index_name", "name")
|
|
3031
|
+
if raw_idx_name and _catalog_name(raw_idx_name, dialect, fragment_dialect) in constraint_names:
|
|
3032
|
+
continue
|
|
3033
|
+
idx_builder = CreateIndex._from_metadata_row(
|
|
3034
|
+
index_row,
|
|
3035
|
+
table_name=table_name,
|
|
3036
|
+
schema=schema or "",
|
|
3037
|
+
dialect=dialect,
|
|
3038
|
+
source_dialect=source_dialect,
|
|
3039
|
+
known_columns=known_columns,
|
|
3040
|
+
warnings=lossy,
|
|
3041
|
+
)
|
|
3042
|
+
if idx_builder is not None:
|
|
3043
|
+
if (
|
|
3044
|
+
idx_builder._unique
|
|
3045
|
+
and not idx_builder._where
|
|
3046
|
+
and not idx_builder._include_columns
|
|
3047
|
+
and all(isinstance(col_expr, exp.Column) for col_expr in idx_builder._columns)
|
|
3048
|
+
):
|
|
3049
|
+
idx_cols = tuple(
|
|
3050
|
+
_catalog_name(col, dialect, fragment_dialect)
|
|
3051
|
+
for col in _split_metadata_columns(
|
|
3052
|
+
_first_present(index_row, "columns", "column_names", "column_name")
|
|
3053
|
+
)
|
|
3054
|
+
)
|
|
3055
|
+
if idx_cols and idx_cols in constrained_column_tuples:
|
|
3056
|
+
continue
|
|
3057
|
+
statements.append(idx_builder.build(dialect=dialect).sql.rstrip(";").strip())
|
|
3058
|
+
|
|
3059
|
+
if dialect_str is None or dialect_str in _COMMENT_ON_DIALECTS:
|
|
3060
|
+
quoted_table = _catalog_name(table_name, dialect, source_dialect)
|
|
3061
|
+
quoted_schema = _catalog_name(schema, dialect, source_dialect) if schema else None
|
|
3062
|
+
if table_comment:
|
|
3063
|
+
tbl_comment = CommentOn(dialect=dialect).on_table(quoted_table).is_(table_comment)
|
|
3064
|
+
if quoted_schema:
|
|
3065
|
+
tbl_comment.in_schema(quoted_schema)
|
|
3066
|
+
statements.append(tbl_comment.build(dialect=dialect).sql.rstrip(";").strip())
|
|
3067
|
+
|
|
3068
|
+
for col_name, col_comment in merged_column_comments.items():
|
|
3069
|
+
col_comment_builder = (
|
|
3070
|
+
CommentOn(dialect=dialect)
|
|
3071
|
+
.on_column(quoted_table, _catalog_name(col_name, dialect, source_dialect))
|
|
3072
|
+
.is_(col_comment)
|
|
3073
|
+
)
|
|
3074
|
+
if quoted_schema:
|
|
3075
|
+
col_comment_builder.in_schema(quoted_schema)
|
|
3076
|
+
statements.append(col_comment_builder.build(dialect=dialect).sql.rstrip(";").strip())
|
|
3077
|
+
elif dialect_str != "mysql":
|
|
3078
|
+
if table_comment:
|
|
3079
|
+
lossy.append(f"Table comment is not supported by {dialect_str}; comment omitted")
|
|
3080
|
+
lossy.extend(
|
|
3081
|
+
f"Column comment on {col_name!r} is not supported by {dialect_str}; comment omitted"
|
|
3082
|
+
for col_name in merged_column_comments
|
|
3083
|
+
)
|
|
3084
|
+
|
|
3085
|
+
ddl_text = ";\n\n".join(stmt for stmt in statements if stmt) + ";"
|
|
3086
|
+
return DDLResult(
|
|
3087
|
+
identity=identity,
|
|
3088
|
+
status=MetadataSupport.SUPPORTED,
|
|
3089
|
+
fidelity=MetadataFidelity.LOSSY if lossy else MetadataFidelity.GENERATED,
|
|
3090
|
+
source=MetadataSource.GENERATED,
|
|
3091
|
+
ddl=ddl_text,
|
|
3092
|
+
warnings=(*warnings, *lossy),
|
|
3093
|
+
)
|
|
3094
|
+
|
|
3095
|
+
|
|
3096
|
+
def _normalize_metadata_row(item: Any) -> dict[str, Any]:
|
|
3097
|
+
"""Normalize a metadata mapping, ObjectMetadata, or ForeignKeyMetadata into a dict."""
|
|
3098
|
+
if type(item) is dict and "attributes" not in item and "identity" not in item and all(type(k) is str for k in item):
|
|
3099
|
+
return item
|
|
3100
|
+
if isinstance(item, Mapping):
|
|
3101
|
+
result: dict[str, Any] = {str(k): v for k, v in item.items()}
|
|
3102
|
+
nested_attrs = result.get("attributes")
|
|
3103
|
+
if isinstance(nested_attrs, Mapping):
|
|
3104
|
+
for k, v in nested_attrs.items():
|
|
3105
|
+
result.setdefault(str(k), v)
|
|
3106
|
+
nested_ident = result.get("identity")
|
|
3107
|
+
if isinstance(nested_ident, Mapping):
|
|
3108
|
+
if nested_ident.get("name") is not None:
|
|
3109
|
+
result.setdefault("name", nested_ident["name"])
|
|
3110
|
+
if nested_ident.get("schema") is not None:
|
|
3111
|
+
result.setdefault("schema_name", nested_ident["schema"])
|
|
3112
|
+
elif isinstance(nested_ident, ObjectIdentity):
|
|
3113
|
+
result.setdefault("name", nested_ident.name)
|
|
3114
|
+
if nested_ident.schema is not None:
|
|
3115
|
+
result.setdefault("schema_name", nested_ident.schema)
|
|
3116
|
+
return result
|
|
3117
|
+
|
|
3118
|
+
if isinstance(item, ForeignKeyMetadata):
|
|
3119
|
+
return {
|
|
3120
|
+
"table_name": item.table_name,
|
|
3121
|
+
"column_name": item.column_name,
|
|
3122
|
+
"referenced_table": item.referenced_table,
|
|
3123
|
+
"referenced_column": item.referenced_column,
|
|
3124
|
+
"constraint_name": item.constraint_name,
|
|
3125
|
+
"schema": item.schema,
|
|
3126
|
+
"referenced_schema": item.referenced_schema,
|
|
3127
|
+
"on_delete": item.on_delete,
|
|
3128
|
+
"on_update": item.on_update,
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
ident = getattr(item, "identity", None)
|
|
3132
|
+
attrs = getattr(item, "attributes", None)
|
|
3133
|
+
if isinstance(ident, ObjectIdentity) and isinstance(attrs, Mapping):
|
|
3134
|
+
result = {str(k): v for k, v in attrs.items()}
|
|
3135
|
+
result.setdefault("name", ident.name)
|
|
3136
|
+
if ident.schema is not None:
|
|
3137
|
+
result.setdefault("schema_name", ident.schema)
|
|
3138
|
+
return result
|
|
3139
|
+
|
|
3140
|
+
asdict_fn = getattr(item, "_asdict", None)
|
|
3141
|
+
if callable(asdict_fn):
|
|
3142
|
+
asdict_res = asdict_fn()
|
|
3143
|
+
if isinstance(asdict_res, Mapping):
|
|
3144
|
+
return {str(k): v for k, v in asdict_res.items()}
|
|
3145
|
+
|
|
3146
|
+
field_names = getattr(type(item), "__struct_fields__", None) or getattr(type(item), "__slots__", None)
|
|
3147
|
+
if isinstance(field_names, (tuple, list)):
|
|
3148
|
+
return {key: getattr(item, key) for key in field_names if isinstance(key, str) and hasattr(item, key)}
|
|
3149
|
+
|
|
3150
|
+
msg = f"Unsupported catalog metadata row type: {type(item).__name__}"
|
|
3151
|
+
raise SQLBuilderError(msg)
|
|
3152
|
+
|
|
3153
|
+
|
|
3154
|
+
def _first_present(row: Mapping[str, Any], *keys: str) -> Any:
|
|
3155
|
+
for key in keys:
|
|
3156
|
+
val = row.get(key)
|
|
3157
|
+
if val is not None:
|
|
3158
|
+
return val
|
|
3159
|
+
return None
|
|
3160
|
+
|
|
3161
|
+
|
|
3162
|
+
def _first_non_empty_str(row: Mapping[str, Any], *keys: str) -> str | None:
|
|
3163
|
+
for key in keys:
|
|
3164
|
+
val = row.get(key)
|
|
3165
|
+
if val is not None:
|
|
3166
|
+
text = str(val).strip()
|
|
3167
|
+
if text:
|
|
3168
|
+
return text
|
|
3169
|
+
return None
|
|
3170
|
+
|
|
3171
|
+
|
|
3172
|
+
def _safe_int(value: Any, default: int = 0) -> int:
|
|
3173
|
+
if value is None:
|
|
3174
|
+
return default
|
|
3175
|
+
try:
|
|
3176
|
+
return int(value)
|
|
3177
|
+
except (TypeError, ValueError):
|
|
3178
|
+
return default
|
|
3179
|
+
|
|
3180
|
+
|
|
3181
|
+
def _split_metadata_columns(value: Any) -> list[str]:
|
|
3182
|
+
if value is None:
|
|
3183
|
+
return []
|
|
3184
|
+
if isinstance(value, str):
|
|
3185
|
+
return [
|
|
3186
|
+
part.strip().strip('"[]`')
|
|
3187
|
+
if _is_simple_identifier(part.strip().strip('"[]`')) and " " not in part.strip()
|
|
3188
|
+
else part.strip()
|
|
3189
|
+
for part in value.split(",")
|
|
3190
|
+
if part.strip()
|
|
3191
|
+
]
|
|
3192
|
+
if isinstance(value, Sequence):
|
|
3193
|
+
return [str(part).strip() for part in value if str(part).strip()]
|
|
3194
|
+
return [str(value).strip()] if str(value).strip() else []
|
|
3195
|
+
|
|
3196
|
+
|
|
3197
|
+
def _resolve_metadata_column_type(row: Mapping[str, Any], dialect: "DialectType | None" = None) -> str:
|
|
3198
|
+
data_type_val = _first_non_empty_str(row, "data_type", "type")
|
|
3199
|
+
column_type_val = _first_non_empty_str(row, "column_type")
|
|
3200
|
+
if column_type_val and "(" in column_type_val and (not data_type_val or "(" not in data_type_val):
|
|
3201
|
+
raw_type = column_type_val
|
|
3202
|
+
else:
|
|
3203
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
3204
|
+
fallback_type = "sql_variant" if norm_dialect in {"tsql", "mssql"} else "TEXT"
|
|
3205
|
+
raw_type = data_type_val or column_type_val or fallback_type
|
|
3206
|
+
|
|
3207
|
+
if "(" in raw_type or "[" in raw_type:
|
|
3208
|
+
return raw_type
|
|
3209
|
+
|
|
3210
|
+
normalized = raw_type.strip().lower()
|
|
3211
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
3212
|
+
char_len = _first_present(row, "character_maximum_length", "char_length")
|
|
3213
|
+
max_length = char_len if char_len is not None else row.get("max_length")
|
|
3214
|
+
precision = _first_present(row, "numeric_precision", "precision")
|
|
3215
|
+
scale = _first_present(row, "numeric_scale", "scale")
|
|
3216
|
+
|
|
3217
|
+
if normalized in _UNICODE_CHAR_TYPES:
|
|
3218
|
+
if max_length in {-1, "-1"} or (isinstance(max_length, str) and max_length.strip().upper() == "MAX"):
|
|
3219
|
+
return f"{raw_type}(MAX)" if norm_dialect in {"tsql", "mssql", None} else "TEXT"
|
|
3220
|
+
if max_length is not None:
|
|
3221
|
+
raw_len = _safe_int(max_length, 0)
|
|
3222
|
+
if raw_len > 0:
|
|
3223
|
+
is_mssql_bytes = _truthy_metadata_flag(row.get("from_mssql_byte_length")) or (
|
|
3224
|
+
char_len is None
|
|
3225
|
+
and (
|
|
3226
|
+
norm_dialect in {"tsql", "mssql"}
|
|
3227
|
+
or "identity_seed" in row
|
|
3228
|
+
or "is_computed" in row
|
|
3229
|
+
or "is_persisted_computed" in row
|
|
3230
|
+
)
|
|
3231
|
+
)
|
|
3232
|
+
effective_len = max(1, raw_len // 2) if is_mssql_bytes else raw_len
|
|
3233
|
+
return f"{raw_type}({effective_len})"
|
|
3234
|
+
|
|
3235
|
+
if normalized in _CHAR_LENGTH_TYPES:
|
|
3236
|
+
if max_length in {-1, "-1"} or (isinstance(max_length, str) and max_length.strip().upper() == "MAX"):
|
|
3237
|
+
if norm_dialect in {"tsql", "mssql"}:
|
|
3238
|
+
return f"{raw_type}(MAX)"
|
|
3239
|
+
return "TEXT" if "char" in normalized else raw_type
|
|
3240
|
+
if max_length is not None:
|
|
3241
|
+
raw_len = _safe_int(max_length, 0)
|
|
3242
|
+
if raw_len > 0:
|
|
3243
|
+
return f"{raw_type}({raw_len})"
|
|
3244
|
+
|
|
3245
|
+
if normalized in _DECIMAL_TYPES:
|
|
3246
|
+
if precision is not None and scale is not None:
|
|
3247
|
+
return f"{raw_type}({_safe_int(precision)},{_safe_int(scale)})"
|
|
3248
|
+
if precision is not None:
|
|
3249
|
+
return f"{raw_type}({_safe_int(precision)})"
|
|
3250
|
+
if normalized == "number" and scale is not None and _safe_int(scale, -1) == 0:
|
|
3251
|
+
return f"{raw_type}({_ORACLE_NUMBER_MAX_PRECISION},0)"
|
|
3252
|
+
|
|
3253
|
+
if normalized in _TEMPORAL_SCALE_TYPES and scale is not None:
|
|
3254
|
+
return f"{raw_type}({_safe_int(scale)})"
|
|
3255
|
+
|
|
3256
|
+
return raw_type
|
|
3257
|
+
|
|
3258
|
+
|
|
3259
|
+
def _translate_catalog_type(
|
|
3260
|
+
dtype: str, source_dialect: "DialectType | None", target_dialect: "DialectType | None"
|
|
3261
|
+
) -> str:
|
|
3262
|
+
"""Render a catalog type written in ``source_dialect`` as type text for ``target_dialect``."""
|
|
3263
|
+
norm_source = _normalize_dialect(source_dialect) if source_dialect else None
|
|
3264
|
+
norm_target = _normalize_dialect(target_dialect) if target_dialect else None
|
|
3265
|
+
if norm_source is None or norm_source == norm_target:
|
|
3266
|
+
return dtype
|
|
3267
|
+
with contextlib.suppress(ParseError):
|
|
3268
|
+
built = exp.DataType.build(dtype, dialect=norm_source)
|
|
3269
|
+
rendered = built.sql(dialect=norm_target, copy=False)
|
|
3270
|
+
if norm_target == "sqlite" and _sqlite_type_affinity(rendered) != _sqlite_type_affinity(dtype):
|
|
3271
|
+
return dtype
|
|
3272
|
+
return rendered
|
|
3273
|
+
return dtype
|
|
3274
|
+
|
|
3275
|
+
|
|
3276
|
+
def _resolve_metadata_not_null(row: Mapping[str, Any]) -> bool:
|
|
3277
|
+
if row.get("not_null") is not None:
|
|
3278
|
+
return _truthy_metadata_flag(row["not_null"])
|
|
3279
|
+
nullable_val = _first_present(row, "is_nullable", "nullable")
|
|
3280
|
+
if nullable_val is None:
|
|
3281
|
+
return False
|
|
3282
|
+
if isinstance(nullable_val, bool):
|
|
3283
|
+
return not nullable_val
|
|
3284
|
+
if isinstance(nullable_val, (int, float)):
|
|
3285
|
+
return nullable_val == 0
|
|
3286
|
+
if isinstance(nullable_val, str):
|
|
3287
|
+
norm = nullable_val.strip().lower()
|
|
3288
|
+
if norm in {"no", "n", "false", "f", "0"}:
|
|
3289
|
+
return True
|
|
3290
|
+
if norm in {"yes", "y", "true", "t", "1"}:
|
|
3291
|
+
return False
|
|
3292
|
+
return not bool(nullable_val)
|
|
3293
|
+
|
|
3294
|
+
|
|
3295
|
+
def _resolve_metadata_computed(row: Mapping[str, Any]) -> tuple[str | exp.Expr | None, bool | None, bool]:
|
|
3296
|
+
"""Return the generated-column expression, storage (``None`` when unknown), and generated flag."""
|
|
3297
|
+
generated_kind = str(row.get("generated_kind") or "").strip().lower()
|
|
3298
|
+
extra = str(row.get("extra") or "").strip().lower()
|
|
3299
|
+
persisted_val = _first_present(row, "is_persisted_computed", "is_stored", "persisted")
|
|
3300
|
+
persisted: bool | None
|
|
3301
|
+
if persisted_val is not None:
|
|
3302
|
+
persisted = _truthy_metadata_flag(persisted_val)
|
|
3303
|
+
elif generated_kind in {"v", "virtual"} or "virtual generated" in extra:
|
|
3304
|
+
persisted = False
|
|
3305
|
+
elif generated_kind in {"s", "stored"} or "stored generated" in extra:
|
|
3306
|
+
persisted = True
|
|
3307
|
+
else:
|
|
3308
|
+
persisted = None
|
|
3309
|
+
|
|
3310
|
+
is_generated = (
|
|
3311
|
+
_truthy_metadata_flag(row.get("is_computed"))
|
|
3312
|
+
or _truthy_metadata_flag(row.get("is_generated"))
|
|
3313
|
+
or _truthy_metadata_flag(row.get("virtual_column"))
|
|
3314
|
+
or generated_kind in {"s", "v", "stored", "virtual"}
|
|
3315
|
+
or extra in {"generated", "virtual generated", "stored generated"}
|
|
3316
|
+
)
|
|
3317
|
+
|
|
3318
|
+
expr_val = _first_present(row, "computed_definition", "generation_expression", "generated_expression")
|
|
3319
|
+
if expr_val is not None and str(expr_val).strip():
|
|
3320
|
+
return (expr_val if isinstance(expr_val, exp.Expr) else str(expr_val).strip(), persisted, True)
|
|
3321
|
+
|
|
3322
|
+
gen_val = row.get("generated")
|
|
3323
|
+
if isinstance(gen_val, str) and gen_val.strip() and gen_val.strip().upper() not in _IDENTITY_KEYWORDS:
|
|
3324
|
+
return (gen_val.strip(), persisted, True)
|
|
3325
|
+
|
|
3326
|
+
if is_generated:
|
|
3327
|
+
fallback_expr = _first_non_empty_str(row, "column_default", "default")
|
|
3328
|
+
if fallback_expr:
|
|
3329
|
+
return (fallback_expr, persisted, True)
|
|
3330
|
+
|
|
3331
|
+
return (None, persisted, is_generated)
|
|
3332
|
+
|
|
3333
|
+
|
|
3334
|
+
def _is_hidden_metadata_column(row: Mapping[str, Any]) -> bool:
|
|
3335
|
+
"""Return whether a catalog column is a system-generated hidden column (Oracle ``SYS_NC*`` columns)."""
|
|
3336
|
+
if not _truthy_metadata_flag(row.get("hidden_column")):
|
|
3337
|
+
return False
|
|
3338
|
+
name = _first_non_empty_str(row, "column_name", "name") or ""
|
|
3339
|
+
return name.upper().startswith("SYS_")
|
|
3340
|
+
|
|
3341
|
+
|
|
3342
|
+
def _resolve_metadata_identity(row: Mapping[str, Any]) -> str | None:
|
|
3343
|
+
raw_identity = _first_present(row, "identity", "identity_generation")
|
|
3344
|
+
if isinstance(raw_identity, bool):
|
|
3345
|
+
if raw_identity:
|
|
3346
|
+
return "ALWAYS"
|
|
3347
|
+
elif isinstance(raw_identity, str):
|
|
3348
|
+
ident_clean = raw_identity.strip().upper()
|
|
3349
|
+
if ident_clean in {"D", "BY DEFAULT", "GENERATED BY DEFAULT", "BY DEFAULT AS IDENTITY"}:
|
|
3350
|
+
return "BY DEFAULT"
|
|
3351
|
+
if ident_clean in {"A", "Y", "YES", "ALWAYS", "GENERATED ALWAYS", "ALWAYS AS IDENTITY", "TRUE", "1"}:
|
|
3352
|
+
return "ALWAYS"
|
|
3353
|
+
if ident_clean not in {"", "N", "NO", "NONE", "FALSE", "0", "NOT_APPLICABLE"}:
|
|
3354
|
+
return ident_clean
|
|
3355
|
+
|
|
3356
|
+
if _truthy_metadata_flag(row.get("is_identity")) or _truthy_metadata_flag(row.get("identity_column")):
|
|
3357
|
+
seed = row.get("identity_seed")
|
|
3358
|
+
inc = row.get("identity_increment")
|
|
3359
|
+
if seed is not None and inc is not None:
|
|
3360
|
+
seed_i = _safe_int(seed, 1)
|
|
3361
|
+
inc_i = _safe_int(inc, 1)
|
|
3362
|
+
if (seed_i, inc_i) != (1, 1):
|
|
3363
|
+
return f"IDENTITY({seed_i},{inc_i})"
|
|
3364
|
+
return "ALWAYS"
|
|
3365
|
+
|
|
3366
|
+
return None
|
|
3367
|
+
|
|
3368
|
+
|
|
3369
|
+
def _resolve_metadata_auto_increment(row: Mapping[str, Any]) -> bool:
|
|
3370
|
+
if _truthy_metadata_flag(row.get("auto_increment")):
|
|
3371
|
+
return True
|
|
3372
|
+
extra = str(row.get("extra") or "").lower()
|
|
3373
|
+
return "auto_increment" in extra or "autoincrement" in extra
|
|
3374
|
+
|
|
3375
|
+
|
|
3376
|
+
def _parse_metadata_default(value: Any, *, source_dialect: "DialectType | None" = None, extra: str = "") -> Any:
|
|
3377
|
+
"""Convert a raw catalog default into a builder default value.
|
|
3378
|
+
|
|
3379
|
+
MySQL ``information_schema`` reports literal defaults unquoted (``hello world``,
|
|
3380
|
+
``2024-01-01``), so on MySQL raw defaults are string literals unless they are numeric,
|
|
3381
|
+
``NULL``, a ``CURRENT_TIMESTAMP``-family keyword, a bit/hex literal, or the column's
|
|
3382
|
+
``EXTRA`` marks an expression default (``DEFAULT_GENERATED``). Other engines report
|
|
3383
|
+
SQL text, which is parsed; non-literal expressions are parenthesized because engines
|
|
3384
|
+
such as SQLite and MySQL require ``DEFAULT (expr)`` (added when the column is rendered).
|
|
3385
|
+
|
|
3386
|
+
Returns:
|
|
3387
|
+
``None`` for no default, a keyword string, an expression, or ``_UNPARSEABLE_DEFAULT``.
|
|
3388
|
+
"""
|
|
3389
|
+
if value is None or isinstance(value, exp.Expr):
|
|
3390
|
+
return value
|
|
3391
|
+
if not isinstance(value, str):
|
|
3392
|
+
return value
|
|
3393
|
+
stripped = value.strip()
|
|
3394
|
+
if not stripped or stripped.upper() == "NULL":
|
|
3395
|
+
return None
|
|
3396
|
+
normalized_kw = re.sub(r"\s+", "_", stripped.upper())
|
|
3397
|
+
if normalized_kw in {CURRENT_TIMESTAMP_KEYWORD, CURRENT_DATE_KEYWORD, CURRENT_TIME_KEYWORD}:
|
|
3398
|
+
return normalized_kw
|
|
3399
|
+
|
|
3400
|
+
raw_source = source_dialect.lower() if isinstance(source_dialect, str) else None
|
|
3401
|
+
norm_source = _normalize_dialect(source_dialect) if source_dialect else None
|
|
3402
|
+
if norm_source == "mysql" and raw_source != "mariadb" and "default_generated" not in extra.lower():
|
|
3403
|
+
if _NUMERIC_LITERAL_RE.fullmatch(stripped):
|
|
3404
|
+
return exp.Literal.number(stripped)
|
|
3405
|
+
if not _MYSQL_KEYWORD_DEFAULT_RE.fullmatch(stripped) and not _MYSQL_BIT_HEX_LITERAL_RE.fullmatch(stripped):
|
|
3406
|
+
return exp.Literal.string(stripped)
|
|
3407
|
+
|
|
3408
|
+
parsed = _parse_catalog_fragment(stripped, source_dialect)
|
|
3409
|
+
if parsed is None:
|
|
3410
|
+
return _UNPARSEABLE_DEFAULT
|
|
3411
|
+
while isinstance(parsed, exp.Paren):
|
|
3412
|
+
parsed = parsed.this
|
|
3413
|
+
if isinstance(parsed, exp.Column) and not parsed.table:
|
|
3414
|
+
return exp.Literal.string(parsed.name)
|
|
3415
|
+
return parsed
|
|
3416
|
+
|
|
3417
|
+
|
|
3418
|
+
def _is_literal_default(expression: "exp.Expr | None") -> bool:
|
|
3419
|
+
"""Return whether a default expression is a literal or keyword that needs no parentheses."""
|
|
3420
|
+
if isinstance(expression, exp.Neg):
|
|
3421
|
+
expression = expression.this
|
|
3422
|
+
return isinstance(
|
|
3423
|
+
expression,
|
|
3424
|
+
(
|
|
3425
|
+
exp.Literal,
|
|
3426
|
+
exp.Null,
|
|
3427
|
+
exp.Boolean,
|
|
3428
|
+
exp.BitString,
|
|
3429
|
+
exp.HexString,
|
|
3430
|
+
exp.CurrentTimestamp,
|
|
3431
|
+
exp.CurrentDate,
|
|
3432
|
+
exp.CurrentTime,
|
|
3433
|
+
),
|
|
3434
|
+
)
|
|
3435
|
+
|
|
3436
|
+
|
|
3437
|
+
def _parse_catalog_fragment(text: str, dialect: "DialectType | None") -> exp.Expr | None:
|
|
3438
|
+
"""Parse a catalog SQL fragment, returning ``None`` when it is not valid SQL for ``dialect``.
|
|
3439
|
+
|
|
3440
|
+
Catalogs wrap stored expressions in redundant parentheses (T-SQL reports
|
|
3441
|
+
``([Total]>=(0))``); those around the whole fragment and around single literals or
|
|
3442
|
+
columns are removed. Identifiers keep the catalog's spelling: quoted identifiers, and
|
|
3443
|
+
unquoted identifiers whose spelling differs from the source dialect's folded form
|
|
3444
|
+
(DuckDB and T-SQL store ``Amount > 0`` for column ``"Amount"``), are marked explicitly
|
|
3445
|
+
quoted so case normalization cannot rename them.
|
|
3446
|
+
"""
|
|
3447
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
3448
|
+
try:
|
|
3449
|
+
parsed = sqlglot.parse_one(text, read=norm_dialect)
|
|
3450
|
+
except (ParseError, TokenError):
|
|
3451
|
+
return None
|
|
3452
|
+
if isinstance(parsed, exp.Paren):
|
|
3453
|
+
parsed = parsed.unnest()
|
|
3454
|
+
return parsed.transform(lambda node: _simplify_catalog_fragment_node(node, norm_dialect), copy=False)
|
|
3455
|
+
|
|
3456
|
+
|
|
3457
|
+
def _simplify_catalog_fragment_node(node: exp.Expr, dialect: str | None) -> exp.Expr:
|
|
3458
|
+
if isinstance(node, exp.Paren) and isinstance(node.this, (exp.Literal, exp.Column, exp.Null, exp.Boolean)):
|
|
3459
|
+
return node.this
|
|
3460
|
+
if isinstance(node, exp.Identifier) and (node.quoted or _fold_identifier(node.name, dialect) != node.name):
|
|
3461
|
+
node.set("quoted", True)
|
|
3462
|
+
node.meta["sqlspec_explicit_table_quote"] = True
|
|
3463
|
+
return node
|
|
3464
|
+
|
|
3465
|
+
|
|
3466
|
+
def _deliver_metadata_warnings(collected: "list[str]", warnings: "list[str] | None", *, context: str) -> None:
|
|
3467
|
+
"""Hand lossy-metadata findings to the caller's collector, or raise when none was supplied."""
|
|
3468
|
+
if not collected:
|
|
3469
|
+
return
|
|
3470
|
+
if warnings is None:
|
|
3471
|
+
msg = f"Cannot reproduce catalog metadata for {context} faithfully: " + "; ".join(collected)
|
|
3472
|
+
raise SQLBuilderError(msg)
|
|
3473
|
+
warnings.extend(collected)
|
|
3474
|
+
|
|
3475
|
+
|
|
3476
|
+
def _normalize_constraint_type(row: Mapping[str, Any]) -> str | None:
|
|
3477
|
+
raw = str(_first_present(row, "constraint_type", "type") or "").strip().upper().replace("_", " ")
|
|
3478
|
+
if raw in {"PRIMARY KEY", "P", "PRIMARY KEY CONSTRAINT"}:
|
|
3479
|
+
return CONSTRAINT_TYPE_PRIMARY_KEY
|
|
3480
|
+
if raw in {"UNIQUE", "U", "UNIQUE CONSTRAINT"}:
|
|
3481
|
+
return CONSTRAINT_TYPE_UNIQUE
|
|
3482
|
+
if raw in {"CHECK", "C", "K", "CHECK CONSTRAINT"}:
|
|
3483
|
+
return CONSTRAINT_TYPE_CHECK
|
|
3484
|
+
if raw in {"FOREIGN KEY", "F", "R", "FOREIGN KEY CONSTRAINT"}:
|
|
3485
|
+
return CONSTRAINT_TYPE_FOREIGN_KEY
|
|
3486
|
+
return None
|
|
3487
|
+
|
|
3488
|
+
|
|
3489
|
+
def _extract_constraint_columns(row: Mapping[str, Any]) -> list[str]:
|
|
3490
|
+
cols = _split_metadata_columns(_first_present(row, "columns", "column_names", "column_name"))
|
|
3491
|
+
if cols:
|
|
3492
|
+
return cols
|
|
3493
|
+
defn = _first_non_empty_str(row, "definition")
|
|
3494
|
+
if defn:
|
|
3495
|
+
match = _PAREN_COLS_RE.search(defn)
|
|
3496
|
+
if match:
|
|
3497
|
+
return _split_metadata_columns(match.group(1))
|
|
3498
|
+
return []
|
|
3499
|
+
|
|
3500
|
+
|
|
3501
|
+
def _extract_metadata_primary_key(
|
|
3502
|
+
columns: Sequence[Mapping[str, Any]], constraints: Sequence[Mapping[str, Any]]
|
|
3503
|
+
) -> tuple[list[str], str | None]:
|
|
3504
|
+
pk_name_from_constraint: str | None = None
|
|
3505
|
+
pk_cols_from_constraint: list[str] = []
|
|
3506
|
+
for c_row in constraints:
|
|
3507
|
+
if _normalize_constraint_type(c_row) == CONSTRAINT_TYPE_PRIMARY_KEY:
|
|
3508
|
+
pk_name_from_constraint = pk_name_from_constraint or _first_non_empty_str(c_row, "constraint_name", "name")
|
|
3509
|
+
c_cols = _extract_constraint_columns(c_row)
|
|
3510
|
+
for col in c_cols:
|
|
3511
|
+
if col not in pk_cols_from_constraint:
|
|
3512
|
+
pk_cols_from_constraint.append(col)
|
|
3513
|
+
|
|
3514
|
+
pk_candidates: list[tuple[int, int, str]] = []
|
|
3515
|
+
pk_name_from_columns: str | None = None
|
|
3516
|
+
for idx, row in enumerate(columns):
|
|
3517
|
+
if not pk_name_from_columns:
|
|
3518
|
+
pk_name_from_columns = _first_non_empty_str(row, "primary_key_name")
|
|
3519
|
+
col_name = _first_non_empty_str(row, "column_name", "name")
|
|
3520
|
+
if not col_name:
|
|
3521
|
+
continue
|
|
3522
|
+
pk_ord = row.get("primary_key_ordinal")
|
|
3523
|
+
if pk_ord is not None and str(pk_ord).strip() not in {"", "0"}:
|
|
3524
|
+
pk_candidates.append((_safe_int(pk_ord, idx + 1), idx, col_name))
|
|
3525
|
+
continue
|
|
3526
|
+
is_pk_val = _first_present(row, "is_primary", "is_primary_key", "primary_key")
|
|
3527
|
+
if isinstance(is_pk_val, int) and not isinstance(is_pk_val, bool) and is_pk_val > 0:
|
|
3528
|
+
pk_candidates.append((is_pk_val, idx, col_name))
|
|
3529
|
+
elif _truthy_metadata_flag(is_pk_val) or str(row.get("column_key") or "").strip().upper() == "PRI":
|
|
3530
|
+
pk_candidates.append((idx + 1, idx, col_name))
|
|
3531
|
+
|
|
3532
|
+
pk_candidates.sort(key=lambda item: (item[0], item[1]))
|
|
3533
|
+
pk_cols_from_columns: list[str] = []
|
|
3534
|
+
for _, _, col_name in pk_candidates:
|
|
3535
|
+
if col_name not in pk_cols_from_columns:
|
|
3536
|
+
pk_cols_from_columns.append(col_name)
|
|
3537
|
+
|
|
3538
|
+
return (pk_cols_from_constraint or pk_cols_from_columns, pk_name_from_constraint or pk_name_from_columns)
|
|
3539
|
+
|
|
3540
|
+
|
|
3541
|
+
def _strip_check_wrapper(definition: str) -> str:
|
|
3542
|
+
stripped = definition.strip()
|
|
3543
|
+
if stripped.upper().startswith("CHECK"):
|
|
3544
|
+
remainder = stripped[5:].strip()
|
|
3545
|
+
if remainder.startswith("(") and remainder.endswith(")"):
|
|
3546
|
+
return remainder[1:-1].strip()
|
|
3547
|
+
return remainder
|
|
3548
|
+
return stripped
|
|
3549
|
+
|
|
3550
|
+
|
|
3551
|
+
def _normalize_fk_action(action: str | None) -> str | None:
|
|
3552
|
+
if not action:
|
|
3553
|
+
return None
|
|
3554
|
+
cleaned = re.sub(r"[\s_]+", " ", action.strip().upper())
|
|
3555
|
+
if cleaned == FOREIGN_KEY_ACTION_NO_ACTION:
|
|
3556
|
+
return None
|
|
3557
|
+
return cleaned if cleaned in VALID_FOREIGN_KEY_ACTIONS else None
|
|
3558
|
+
|
|
3559
|
+
|
|
3560
|
+
def _supported_foreign_key_actions(
|
|
3561
|
+
on_delete: str | None,
|
|
3562
|
+
on_update: str | None,
|
|
3563
|
+
dialect: "DialectType | None",
|
|
3564
|
+
*,
|
|
3565
|
+
name: str | None,
|
|
3566
|
+
warnings: "list[str]",
|
|
3567
|
+
) -> tuple[str | None, str | None]:
|
|
3568
|
+
"""Drop referential actions the target dialect rejects, recording each semantic loss."""
|
|
3569
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
3570
|
+
label = name or "<unnamed>"
|
|
3571
|
+
if norm_dialect == "oracle":
|
|
3572
|
+
resolved_delete = on_delete if on_delete in _ORACLE_ON_DELETE_ACTIONS else None
|
|
3573
|
+
if on_delete and resolved_delete is None and on_delete != FOREIGN_KEY_ACTION_RESTRICT:
|
|
3574
|
+
warnings.append(f"Foreign key {label}: Oracle does not support ON DELETE {on_delete}; action omitted")
|
|
3575
|
+
if on_update and on_update != FOREIGN_KEY_ACTION_RESTRICT:
|
|
3576
|
+
warnings.append(f"Foreign key {label}: Oracle does not support ON UPDATE {on_update}; action omitted")
|
|
3577
|
+
return resolved_delete, None
|
|
3578
|
+
if norm_dialect in {"duckdb", "bigquery"}:
|
|
3579
|
+
label_dialect = "BigQuery" if norm_dialect == "bigquery" else "DuckDB"
|
|
3580
|
+
implicit_actions = {FOREIGN_KEY_ACTION_RESTRICT}
|
|
3581
|
+
if on_delete and on_delete not in implicit_actions:
|
|
3582
|
+
warnings.append(
|
|
3583
|
+
f"Foreign key {label}: {label_dialect} does not support ON DELETE {on_delete}; action omitted"
|
|
3584
|
+
)
|
|
3585
|
+
if on_update and on_update not in implicit_actions:
|
|
3586
|
+
warnings.append(
|
|
3587
|
+
f"Foreign key {label}: {label_dialect} does not support ON UPDATE {on_update}; action omitted"
|
|
3588
|
+
)
|
|
3589
|
+
return None, None
|
|
3590
|
+
if norm_dialect == "tsql":
|
|
3591
|
+
return (
|
|
3592
|
+
None if on_delete == FOREIGN_KEY_ACTION_RESTRICT else on_delete,
|
|
3593
|
+
None if on_update == FOREIGN_KEY_ACTION_RESTRICT else on_update,
|
|
3594
|
+
)
|
|
3595
|
+
return on_delete, on_update
|
|
3596
|
+
|
|
3597
|
+
|
|
3598
|
+
def _metadata_fk_actions(row: Mapping[str, Any], definition: str | None) -> tuple[str | None, str | None]:
|
|
3599
|
+
"""Return the ON DELETE / ON UPDATE actions from FK metadata keys, falling back to its definition text."""
|
|
3600
|
+
on_delete = _normalize_fk_action(_first_non_empty_str(row, "on_delete", "delete_rule"))
|
|
3601
|
+
on_update = _normalize_fk_action(_first_non_empty_str(row, "on_update", "update_rule"))
|
|
3602
|
+
if definition:
|
|
3603
|
+
if on_delete is None:
|
|
3604
|
+
del_match = _FK_ON_DELETE_RE.search(definition)
|
|
3605
|
+
on_delete = _normalize_fk_action(del_match.group(1)) if del_match else None
|
|
3606
|
+
if on_update is None:
|
|
3607
|
+
upd_match = _FK_ON_UPDATE_RE.search(definition)
|
|
3608
|
+
on_update = _normalize_fk_action(upd_match.group(1)) if upd_match else None
|
|
3609
|
+
return on_delete, on_update
|
|
3610
|
+
|
|
3611
|
+
|
|
3612
|
+
def _find_matching_metadata_fk(
|
|
3613
|
+
merged: list[dict[str, Any]],
|
|
3614
|
+
*,
|
|
3615
|
+
quoted_name: str | None,
|
|
3616
|
+
fk_group_id: Any,
|
|
3617
|
+
ref_table: str,
|
|
3618
|
+
quoted_cols: Sequence[str],
|
|
3619
|
+
quoted_ref_cols: Sequence[str],
|
|
3620
|
+
on_delete: str | None = None,
|
|
3621
|
+
on_update: str | None = None,
|
|
3622
|
+
) -> dict[str, Any] | None:
|
|
3623
|
+
"""Find an existing merged FK entry that belongs to the same constraint group."""
|
|
3624
|
+
for existing in merged:
|
|
3625
|
+
if quoted_name and existing["name"] == quoted_name:
|
|
3626
|
+
return existing
|
|
3627
|
+
if (
|
|
3628
|
+
fk_group_id is not None
|
|
3629
|
+
and existing.get("_fk_group_id") == fk_group_id
|
|
3630
|
+
and existing["ref_table"] == ref_table
|
|
3631
|
+
):
|
|
3632
|
+
return existing
|
|
3633
|
+
if (
|
|
3634
|
+
tuple(existing["columns"]) == tuple(quoted_cols)
|
|
3635
|
+
and existing["ref_table"] == ref_table
|
|
3636
|
+
and tuple(existing["ref_columns"]) == tuple(quoted_ref_cols)
|
|
3637
|
+
):
|
|
3638
|
+
return existing
|
|
3639
|
+
if (
|
|
3640
|
+
quoted_name is None
|
|
3641
|
+
and fk_group_id is None
|
|
3642
|
+
and existing["name"] is None
|
|
3643
|
+
and existing.get("_fk_group_id") is None
|
|
3644
|
+
and existing["ref_table"] == ref_table
|
|
3645
|
+
and existing["on_delete"] == on_delete
|
|
3646
|
+
and existing["on_update"] == on_update
|
|
3647
|
+
and len(quoted_cols) == 1
|
|
3648
|
+
and len(quoted_ref_cols) == 1
|
|
3649
|
+
and quoted_cols[0] not in existing["columns"]
|
|
3650
|
+
and quoted_ref_cols[0] not in existing["ref_columns"]
|
|
3651
|
+
):
|
|
3652
|
+
return existing
|
|
3653
|
+
return None
|
|
3654
|
+
|
|
3655
|
+
|
|
3656
|
+
def _extract_metadata_foreign_keys(
|
|
3657
|
+
constraints: Sequence[Mapping[str, Any]],
|
|
3658
|
+
foreign_keys: Sequence[Mapping[str, Any]],
|
|
3659
|
+
*,
|
|
3660
|
+
table_schema: str | None = None,
|
|
3661
|
+
dialect: "DialectType | None" = None,
|
|
3662
|
+
source_dialect: "DialectType | None" = None,
|
|
3663
|
+
warnings: "list[str] | None" = None,
|
|
3664
|
+
) -> list[dict[str, Any]]:
|
|
3665
|
+
"""Merge FK metadata rows into specs whose names are already quoted for ``dialect``."""
|
|
3666
|
+
fk_names = {
|
|
3667
|
+
name for fk_row in foreign_keys if (name := _first_non_empty_str(fk_row, "constraint_name", "name")) is not None
|
|
3668
|
+
}
|
|
3669
|
+
raw_items: list[Mapping[str, Any]] = []
|
|
3670
|
+
for c_row in constraints:
|
|
3671
|
+
if _normalize_constraint_type(c_row) != CONSTRAINT_TYPE_FOREIGN_KEY:
|
|
3672
|
+
continue
|
|
3673
|
+
c_name = _first_non_empty_str(c_row, "constraint_name", "name")
|
|
3674
|
+
has_ref = bool(
|
|
3675
|
+
_first_non_empty_str(
|
|
3676
|
+
c_row, "referenced_table", "references_table", "referenced_table_name", "table", "definition"
|
|
3677
|
+
)
|
|
3678
|
+
)
|
|
3679
|
+
if not has_ref and ((c_name and c_name in fk_names) or bool(foreign_keys)):
|
|
3680
|
+
continue
|
|
3681
|
+
raw_items.append(c_row)
|
|
3682
|
+
raw_items.extend(foreign_keys)
|
|
3683
|
+
|
|
3684
|
+
merged: list[dict[str, Any]] = []
|
|
3685
|
+
for row in raw_items:
|
|
3686
|
+
name = _first_non_empty_str(row, "constraint_name", "name")
|
|
3687
|
+
fk_group_id = row.get("id") if name is None else None
|
|
3688
|
+
cols = _split_metadata_columns(_first_present(row, "columns", "column_names", "column_name", "from"))
|
|
3689
|
+
ref_table = _first_non_empty_str(row, "referenced_table", "references_table", "referenced_table_name", "table")
|
|
3690
|
+
ref_cols = _split_metadata_columns(
|
|
3691
|
+
_first_present(
|
|
3692
|
+
row, "referenced_columns", "references_columns", "referenced_column", "referenced_column_name", "to"
|
|
3693
|
+
)
|
|
3694
|
+
)
|
|
3695
|
+
ref_is_catalog_name = ref_table is not None
|
|
3696
|
+
defn = _first_non_empty_str(row, "definition")
|
|
3697
|
+
if defn and (not cols or not ref_table or not ref_cols):
|
|
3698
|
+
fk_match = _FK_DEF_RE.search(defn)
|
|
3699
|
+
if fk_match:
|
|
3700
|
+
if not cols:
|
|
3701
|
+
cols = _split_metadata_columns(fk_match.group("cols"))
|
|
3702
|
+
if not ref_table:
|
|
3703
|
+
ref_table = fk_match.group("ref_table").strip()
|
|
3704
|
+
if not ref_cols:
|
|
3705
|
+
ref_cols = _split_metadata_columns(fk_match.group("ref_cols"))
|
|
3706
|
+
|
|
3707
|
+
if not cols or not ref_table or not ref_cols:
|
|
3708
|
+
if warnings is not None:
|
|
3709
|
+
warnings.append(f"Foreign key {name or '<unnamed>'} metadata is incomplete and was omitted")
|
|
3710
|
+
continue
|
|
3711
|
+
|
|
3712
|
+
explicit_ref_schema = _first_non_empty_str(
|
|
3713
|
+
row, "referenced_schema", "references_schema", "referenced_table_schema"
|
|
3714
|
+
)
|
|
3715
|
+
norm_target = _normalize_dialect(dialect) if dialect else None
|
|
3716
|
+
if (
|
|
3717
|
+
explicit_ref_schema
|
|
3718
|
+
and table_schema is None
|
|
3719
|
+
and norm_target in {"sqlite", "duckdb"}
|
|
3720
|
+
and explicit_ref_schema.lower() == "main"
|
|
3721
|
+
):
|
|
3722
|
+
explicit_ref_schema = None
|
|
3723
|
+
ref_schema = explicit_ref_schema or table_schema
|
|
3724
|
+
qualify_ref = bool(explicit_ref_schema or (ref_schema and table_schema))
|
|
3725
|
+
if ref_is_catalog_name:
|
|
3726
|
+
ref_table = _catalog_qualified_name(ref_table, ref_schema if qualify_ref else None, dialect, source_dialect)
|
|
3727
|
+
elif qualify_ref and ref_schema and "." not in ref_table:
|
|
3728
|
+
ref_table = f"{_catalog_name(ref_schema, dialect, source_dialect)}.{ref_table}"
|
|
3729
|
+
|
|
3730
|
+
on_delete, on_update = _metadata_fk_actions(row, defn)
|
|
3731
|
+
deferrable = _truthy_metadata_flag(_first_present(row, "deferrable", "is_deferrable"))
|
|
3732
|
+
initially_deferred = _truthy_metadata_flag(row.get("initially_deferred"))
|
|
3733
|
+
quoted_cols = [_catalog_name(col, dialect, source_dialect) for col in cols]
|
|
3734
|
+
quoted_ref_cols = (
|
|
3735
|
+
[_catalog_name(col, dialect, source_dialect) for col in ref_cols] if ref_is_catalog_name else ref_cols
|
|
3736
|
+
)
|
|
3737
|
+
quoted_name = _catalog_name(name, dialect, source_dialect) if name else None
|
|
3738
|
+
|
|
3739
|
+
matched_existing = _find_matching_metadata_fk(
|
|
3740
|
+
merged,
|
|
3741
|
+
quoted_name=quoted_name,
|
|
3742
|
+
fk_group_id=fk_group_id,
|
|
3743
|
+
ref_table=ref_table,
|
|
3744
|
+
quoted_cols=quoted_cols,
|
|
3745
|
+
quoted_ref_cols=quoted_ref_cols,
|
|
3746
|
+
on_delete=on_delete,
|
|
3747
|
+
on_update=on_update,
|
|
3748
|
+
)
|
|
3749
|
+
|
|
3750
|
+
if matched_existing is not None:
|
|
3751
|
+
if (
|
|
3752
|
+
len(quoted_cols) == 1
|
|
3753
|
+
and len(quoted_ref_cols) == 1
|
|
3754
|
+
and quoted_cols[0] not in matched_existing["columns"]
|
|
3755
|
+
):
|
|
3756
|
+
matched_existing["columns"].append(quoted_cols[0])
|
|
3757
|
+
matched_existing["ref_columns"].append(quoted_ref_cols[0])
|
|
3758
|
+
if not matched_existing["name"] and quoted_name:
|
|
3759
|
+
matched_existing["name"] = quoted_name
|
|
3760
|
+
if not matched_existing["on_delete"] and on_delete:
|
|
3761
|
+
matched_existing["on_delete"] = on_delete
|
|
3762
|
+
if not matched_existing["on_update"] and on_update:
|
|
3763
|
+
matched_existing["on_update"] = on_update
|
|
3764
|
+
if deferrable:
|
|
3765
|
+
matched_existing["deferrable"] = True
|
|
3766
|
+
if initially_deferred:
|
|
3767
|
+
matched_existing["initially_deferred"] = True
|
|
3768
|
+
continue
|
|
3769
|
+
|
|
3770
|
+
merged.append({
|
|
3771
|
+
"name": quoted_name,
|
|
3772
|
+
"columns": list(quoted_cols),
|
|
3773
|
+
"ref_table": ref_table,
|
|
3774
|
+
"ref_columns": list(quoted_ref_cols),
|
|
3775
|
+
"on_delete": on_delete,
|
|
3776
|
+
"on_update": on_update,
|
|
3777
|
+
"deferrable": deferrable,
|
|
3778
|
+
"initially_deferred": initially_deferred,
|
|
3779
|
+
"_fk_group_id": fk_group_id,
|
|
3780
|
+
})
|
|
3781
|
+
|
|
3782
|
+
return [item for item in merged if len(item["columns"]) == len(item["ref_columns"])]
|
|
3783
|
+
|
|
3784
|
+
|
|
3785
|
+
def _native_index_sql(row: Mapping[str, Any]) -> str | None:
|
|
3786
|
+
"""Return the catalog's native ``CREATE INDEX`` text when the row carries it."""
|
|
3787
|
+
native = _first_non_empty_str(row, "native_sql", "index_sql")
|
|
3788
|
+
if native is not None:
|
|
3789
|
+
return native
|
|
3790
|
+
definition = _first_non_empty_str(row, "definition", "indexdef")
|
|
3791
|
+
if definition is not None and _NATIVE_INDEX_SQL_RE.match(definition):
|
|
3792
|
+
return definition
|
|
3793
|
+
return None
|
|
3794
|
+
|
|
3795
|
+
|
|
3796
|
+
def _parse_native_index_sql(
|
|
3797
|
+
native_sql: str, dialect: "DialectType | None"
|
|
3798
|
+
) -> tuple[list[exp.Expr], exp.Expr | None] | None:
|
|
3799
|
+
"""Return the key expressions and predicate of a native ``CREATE INDEX`` statement."""
|
|
3800
|
+
parsed = _parse_catalog_fragment(native_sql.strip().rstrip(";"), dialect)
|
|
3801
|
+
if parsed is None and dialect is not None:
|
|
3802
|
+
parsed = _parse_catalog_fragment(native_sql.strip().rstrip(";"), None)
|
|
3803
|
+
if not isinstance(parsed, exp.Create) or not isinstance(parsed.this, exp.Index):
|
|
3804
|
+
return None
|
|
3805
|
+
params = parsed.this.args.get("params")
|
|
3806
|
+
if not isinstance(params, exp.IndexParameters):
|
|
3807
|
+
return None
|
|
3808
|
+
key_exprs = [_strip_default_ordering(col) for col in params.args.get("columns") or []]
|
|
3809
|
+
if not key_exprs:
|
|
3810
|
+
return None
|
|
3811
|
+
where_node = params.args.get("where")
|
|
3812
|
+
where_expr = where_node.this if isinstance(where_node, exp.Where) else None
|
|
3813
|
+
return key_exprs, where_expr
|
|
3814
|
+
|
|
3815
|
+
|
|
3816
|
+
def _strip_default_ordering(column: exp.Expr) -> exp.Expr:
|
|
3817
|
+
"""Drop the implicit ascending wrapper and redundant parentheses around column or function keys, keeping DESC."""
|
|
3818
|
+
inner: exp.Expr = column.this if isinstance(column, exp.Ordered) and not column.args.get("desc") else column
|
|
3819
|
+
if isinstance(inner, exp.Paren) and isinstance(inner.this, (exp.Column, exp.Func)):
|
|
3820
|
+
unwrapped: exp.Expr = inner.this
|
|
3821
|
+
return unwrapped
|
|
3822
|
+
return inner
|
|
3823
|
+
|
|
3824
|
+
|
|
3825
|
+
def _metadata_index_key_expressions(
|
|
3826
|
+
row: Mapping[str, Any],
|
|
3827
|
+
index_name: str,
|
|
3828
|
+
*,
|
|
3829
|
+
dialect: "DialectType | None",
|
|
3830
|
+
fragment_dialect: "DialectType | None",
|
|
3831
|
+
known_columns: "Sequence[str] | None",
|
|
3832
|
+
warnings: "list[str]",
|
|
3833
|
+
) -> list[exp.Expr] | None:
|
|
3834
|
+
"""Build index key expressions from the catalog column list and per-column sort order."""
|
|
3835
|
+
cols = _split_metadata_columns(_first_present(row, "columns", "column_names", "column_name"))
|
|
3836
|
+
if not cols:
|
|
3837
|
+
warnings.append(f"Index {index_name} has no catalog key columns; index omitted")
|
|
3838
|
+
return None
|
|
3839
|
+
known = set(known_columns or ())
|
|
3840
|
+
descending = _metadata_index_descending_flags(row, len(cols))
|
|
3841
|
+
key_exprs: list[exp.Expr] = []
|
|
3842
|
+
for position, col in enumerate(cols):
|
|
3843
|
+
key_expr: exp.Expr
|
|
3844
|
+
if col in known:
|
|
3845
|
+
key_expr = exp.Column(this=_explicit_or_bare_identifier(col, dialect, fragment_dialect))
|
|
3846
|
+
elif _ORDER_DIRECTION_SUFFIX_RE.search(col) and not _INDEX_EXPRESSION_CHARS_RE.search(col):
|
|
3847
|
+
base_name = _ORDER_DIRECTION_SUFFIX_RE.sub("", col).strip()
|
|
3848
|
+
descending[position] = descending[position] or "DESC" in col[len(base_name) :].upper()
|
|
3849
|
+
key_expr = exp.Column(this=_explicit_or_bare_identifier(base_name, dialect, fragment_dialect))
|
|
3850
|
+
elif _INDEX_PLACEHOLDER_RE.fullmatch(col):
|
|
3851
|
+
warnings.append(f"Index {index_name} uses an expression the catalog did not report; index omitted")
|
|
3852
|
+
return None
|
|
3853
|
+
elif _INDEX_EXPRESSION_CHARS_RE.search(col):
|
|
3854
|
+
parsed_key = _parse_catalog_fragment(col, fragment_dialect)
|
|
3855
|
+
if parsed_key is None:
|
|
3856
|
+
warnings.append(f"Index {index_name}: key expression could not be parsed ({col}); index omitted")
|
|
3857
|
+
return None
|
|
3858
|
+
key_expr = parsed_key
|
|
3859
|
+
else:
|
|
3860
|
+
key_expr = exp.Column(this=_explicit_or_bare_identifier(col, dialect, fragment_dialect))
|
|
3861
|
+
key_exprs.append(_descending_key(key_expr, dialect) if descending[position] else key_expr)
|
|
3862
|
+
return key_exprs
|
|
3863
|
+
|
|
3864
|
+
|
|
3865
|
+
def _metadata_index_descending_flags(row: Mapping[str, Any], count: int) -> list[bool]:
|
|
3866
|
+
"""Return per-key descending flags from ``column_orders`` (``A``/``D``) or ``is_descending`` metadata."""
|
|
3867
|
+
raw_orders = _first_present(row, "column_orders", "descending", "is_descending")
|
|
3868
|
+
if raw_orders is None:
|
|
3869
|
+
return [False] * count
|
|
3870
|
+
values: list[Any] = (
|
|
3871
|
+
raw_orders.split(",")
|
|
3872
|
+
if isinstance(raw_orders, str)
|
|
3873
|
+
else list(raw_orders)
|
|
3874
|
+
if isinstance(raw_orders, Sequence)
|
|
3875
|
+
else [raw_orders]
|
|
3876
|
+
)
|
|
3877
|
+
flags = [
|
|
3878
|
+
str(value).strip().upper() in {"D", "DESC"} or (not isinstance(value, str) and _truthy_metadata_flag(value))
|
|
3879
|
+
for value in values
|
|
3880
|
+
]
|
|
3881
|
+
return (flags + [False] * count)[:count]
|
|
3882
|
+
|
|
3883
|
+
|
|
3884
|
+
def _descending_key(expression: exp.Expr, dialect: "DialectType | None") -> exp.Ordered:
|
|
3885
|
+
"""Wrap an index key as DESC using the dialect's default null ordering (no explicit NULLS clause)."""
|
|
3886
|
+
null_ordering = Dialect.get_or_raise(_normalize_dialect(dialect) if dialect else None).NULL_ORDERING
|
|
3887
|
+
return exp.Ordered(
|
|
3888
|
+
this=expression, desc=True, nulls_first=null_ordering not in {"nulls_are_small", "nulls_are_last"}
|
|
3889
|
+
)
|
|
3890
|
+
|
|
3891
|
+
|
|
3892
|
+
def _explicit_or_bare_identifier(
|
|
3893
|
+
name: str, dialect: "DialectType | None", source_dialect: "DialectType | None" = None
|
|
3894
|
+
) -> exp.Identifier:
|
|
3895
|
+
"""Return an identifier for a raw catalog name, explicitly quoted when its spelling requires it."""
|
|
3896
|
+
if not _catalog_name_needs_quotes(name, dialect, source_dialect):
|
|
3897
|
+
return exp.to_identifier(name)
|
|
3898
|
+
norm_dialect = _normalize_dialect(dialect)
|
|
3899
|
+
case_dialect = norm_dialect if source_dialect is None else _normalize_dialect(source_dialect)
|
|
3900
|
+
target_name = name
|
|
3901
|
+
if _BARE_IDENTIFIER_RE.fullmatch(name) and _fold_identifier(name, case_dialect) == name:
|
|
3902
|
+
target_name = _fold_identifier(name, norm_dialect)
|
|
3903
|
+
return _explicit_identifier(target_name)
|
|
3904
|
+
|
|
3905
|
+
|
|
3906
|
+
def _explicit_identifier(name: str) -> exp.Identifier:
|
|
3907
|
+
"""Return a quoted identifier marked so normalization and unquoting passes keep it verbatim."""
|
|
3908
|
+
identifier = exp.Identifier(this=name, quoted=True)
|
|
3909
|
+
identifier.meta["sqlspec_explicit_table_quote"] = True
|
|
3910
|
+
return identifier
|
|
3911
|
+
|
|
3912
|
+
|
|
3913
|
+
def _index_column_expression(text: str, dialect: "DialectType | None") -> exp.Expr:
|
|
3914
|
+
"""Turn a user-supplied index column string into an identifier, ordered key, or expression."""
|
|
3915
|
+
stripped = text.strip()
|
|
3916
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
3917
|
+
base = _ORDER_DIRECTION_SUFFIX_RE.sub("", stripped).strip()
|
|
3918
|
+
has_order_suffix = base != stripped
|
|
3919
|
+
base_is_name = _is_simple_identifier(base) or bool(_QUOTED_IDENTIFIER_RE.fullmatch(base))
|
|
3920
|
+
if has_order_suffix and (base_is_name or _INDEX_EXPRESSION_CHARS_RE.search(base)):
|
|
3921
|
+
ordered: exp.Expr = parse_order_expression(stripped)
|
|
3922
|
+
return ordered
|
|
3923
|
+
if _is_simple_identifier(stripped) or _QUOTED_IDENTIFIER_RE.fullmatch(stripped):
|
|
3924
|
+
return exp.Column(this=_parse_ddl_identifier(stripped, dialect=dialect))
|
|
3925
|
+
if _INDEX_EXPRESSION_CHARS_RE.search(stripped):
|
|
3926
|
+
parsed: exp.Expr | None = exp.maybe_parse(stripped, dialect=norm_dialect)
|
|
3927
|
+
if parsed is not None:
|
|
3928
|
+
return parsed
|
|
3929
|
+
if has_order_suffix:
|
|
3930
|
+
suffix = stripped[len(base) :].upper()
|
|
3931
|
+
column = exp.Column(this=_explicit_identifier(base))
|
|
3932
|
+
return _descending_key(column, dialect) if "DESC" in suffix else column
|
|
3933
|
+
return exp.Column(this=_explicit_identifier(stripped))
|
|
3934
|
+
|
|
3935
|
+
|
|
3936
|
+
def _group_metadata_index_rows(indexes: Sequence[Mapping[str, Any] | Any]) -> list[dict[str, Any]]:
|
|
3937
|
+
grouped: list[dict[str, Any]] = []
|
|
3938
|
+
by_name: dict[str, dict[str, Any]] = {}
|
|
3939
|
+
for item in indexes:
|
|
3940
|
+
row = _normalize_metadata_row(item)
|
|
3941
|
+
idx_name = _first_non_empty_str(row, "index_name", "name")
|
|
3942
|
+
if not idx_name:
|
|
3943
|
+
continue
|
|
3944
|
+
has_col_list = row.get("columns") is not None or row.get("column_names") is not None
|
|
3945
|
+
single_col = _first_non_empty_str(row, "column_name")
|
|
3946
|
+
if not has_col_list and single_col:
|
|
3947
|
+
existing = by_name.get(idx_name)
|
|
3948
|
+
pos = _safe_int(_first_present(row, "column_position", "ordinal_position", "key_ordinal"), 0)
|
|
3949
|
+
if existing is None:
|
|
3950
|
+
entry = dict(row)
|
|
3951
|
+
entry["_col_pairs"] = [(pos, single_col)]
|
|
3952
|
+
by_name[idx_name] = entry
|
|
3953
|
+
grouped.append(entry)
|
|
3954
|
+
else:
|
|
3955
|
+
existing["_col_pairs"].append((pos, single_col))
|
|
3956
|
+
elif idx_name not in by_name:
|
|
3957
|
+
by_name[idx_name] = row
|
|
3958
|
+
grouped.append(row)
|
|
3959
|
+
|
|
3960
|
+
result: list[dict[str, Any]] = []
|
|
3961
|
+
for entry in grouped:
|
|
3962
|
+
pairs = entry.pop("_col_pairs", None)
|
|
3963
|
+
if pairs is not None:
|
|
3964
|
+
pairs.sort(key=lambda pair: pair[0])
|
|
3965
|
+
entry["columns"] = [col for _, col in pairs]
|
|
3966
|
+
result.append(entry)
|
|
3967
|
+
return result
|
|
3968
|
+
|
|
3969
|
+
|
|
3970
|
+
def _build_optional_column_schema(columns: list[str], dialect: "DialectType | None" = None) -> exp.Schema | None:
|
|
3971
|
+
if not columns:
|
|
3972
|
+
return None
|
|
3973
|
+
return exp.Schema(
|
|
3974
|
+
expressions=[exp.Column(this=_parse_ddl_identifier(column, dialect=dialect)) for column in columns]
|
|
3975
|
+
)
|
|
3976
|
+
|
|
3977
|
+
|
|
3978
|
+
def _wrap_properties(properties: "Sequence[exp.Expr]") -> exp.Properties | None:
|
|
3979
|
+
return exp.Properties(expressions=list(properties)) if properties else None
|
|
3980
|
+
|
|
3981
|
+
|
|
3982
|
+
def _parse_column_type(name: str | None, dtype: str, dialect: "DialectType | None") -> exp.DataType:
|
|
3983
|
+
"""Parse a column type for ``dialect``.
|
|
3984
|
+
|
|
3985
|
+
SQLite derives column affinity from the declared type name, so SQLite keeps the type
|
|
3986
|
+
text verbatim (``NUMERIC(12,2)`` must not become ``REAL``). Types SQLGlot cannot parse
|
|
3987
|
+
(for example Oracle ``RAW(16)``) are kept verbatim as user-defined types.
|
|
3988
|
+
"""
|
|
3989
|
+
target_dialect = dialect
|
|
3990
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
3991
|
+
if norm_dialect == "sqlite":
|
|
3992
|
+
declared = dtype.strip()
|
|
3993
|
+
with contextlib.suppress(ParseError):
|
|
3994
|
+
built = exp.DataType.build(declared, dialect=target_dialect)
|
|
3995
|
+
if _sqlite_type_affinity(built.sql(dialect="sqlite", copy=False)) == _sqlite_type_affinity(declared):
|
|
3996
|
+
return built
|
|
3997
|
+
return exp.DataType(this=exp.DataType.Type.USERDEFINED, kind=declared)
|
|
3998
|
+
if norm_dialect in ("tsql", "mssql") and dtype.strip().upper().startswith("TIMESTAMP"):
|
|
3999
|
+
target_dialect = None
|
|
4000
|
+
with contextlib.suppress(ParseError):
|
|
4001
|
+
return exp.DataType.build(dtype, dialect=target_dialect)
|
|
4002
|
+
if _QUALIFIED_TYPE_NAME_RE.fullmatch(dtype.strip()):
|
|
4003
|
+
type_name = _mark_explicit_table_quotes(exp.to_table(dtype.strip(), dialect=norm_dialect), dtype.strip())
|
|
4004
|
+
return exp.DataType(this=exp.DataType.Type.USERDEFINED, kind=type_name.sql(dialect=norm_dialect, copy=False))
|
|
4005
|
+
if target_dialect is not None:
|
|
4006
|
+
with contextlib.suppress(ParseError):
|
|
4007
|
+
return exp.DataType.build(dtype)
|
|
4008
|
+
if _VERBATIM_TYPE_NAME_RE.fullmatch(dtype.strip()):
|
|
4009
|
+
return exp.DataType(this=exp.DataType.Type.USERDEFINED, kind=dtype.strip())
|
|
4010
|
+
msg = f"Column {name!r}: cannot parse type {dtype!r} for dialect {dialect!r}"
|
|
4011
|
+
raise SQLBuilderError(msg)
|
|
4012
|
+
|
|
4013
|
+
|
|
4014
|
+
def _parse_ddl_identifier(name: str, dialect: "DialectType | None" = None) -> exp.Identifier:
|
|
4015
|
+
"""Parse a DDL identifier, preserving explicit SQL quoting without double-wrapping."""
|
|
4016
|
+
stripped = name.strip()
|
|
4017
|
+
if not stripped:
|
|
4018
|
+
return exp.to_identifier(name)
|
|
4019
|
+
parsed = _mark_explicit_table_quotes(exp.to_table(stripped, dialect=dialect), stripped)
|
|
4020
|
+
if isinstance(parsed.this, exp.Identifier) and not parsed.args.get("db"):
|
|
4021
|
+
return parsed.this
|
|
4022
|
+
return exp.to_identifier(name)
|
|
4023
|
+
|
|
4024
|
+
|
|
4025
|
+
def _parse_ddl_table(table_name: str, schema: "str | None" = None, dialect: "DialectType | None" = None) -> exp.Table:
|
|
4026
|
+
"""Parse a DDL table reference, preserving quoted table and schema identifiers."""
|
|
4027
|
+
table = _parse_table_reference(table_name, dialect=dialect)
|
|
4028
|
+
if table.args.get("alias"):
|
|
4029
|
+
msg = f"Invalid table reference {table_name!r}: DDL table names cannot have an alias."
|
|
4030
|
+
raise SQLBuilderError(msg)
|
|
4031
|
+
if schema:
|
|
4032
|
+
table.set("db", _parse_ddl_identifier(schema, dialect=dialect))
|
|
4033
|
+
return table
|
|
4034
|
+
|
|
4035
|
+
|
|
4036
|
+
def _sqlite_type_affinity(type_text: str) -> str:
|
|
4037
|
+
"""Return the SQLite column affinity for a declared type name (SQLite datatype rules 3.1)."""
|
|
4038
|
+
upper = type_text.upper()
|
|
4039
|
+
if "INT" in upper:
|
|
4040
|
+
return "INTEGER"
|
|
4041
|
+
if "CHAR" in upper or "CLOB" in upper or "TEXT" in upper:
|
|
4042
|
+
return "TEXT"
|
|
4043
|
+
if "BLOB" in upper or not upper.strip():
|
|
4044
|
+
return "BLOB"
|
|
4045
|
+
if "REAL" in upper or "FLOA" in upper or "DOUB" in upper:
|
|
4046
|
+
return "REAL"
|
|
4047
|
+
return "NUMERIC"
|
|
4048
|
+
|
|
4049
|
+
|
|
4050
|
+
def _catalog_name(name: str, dialect: "DialectType | None", source_dialect: "DialectType | None" = None) -> str:
|
|
4051
|
+
"""Return SQL text that resolves to exactly the catalog-supplied identifier ``name``.
|
|
4052
|
+
|
|
4053
|
+
Catalog identifiers are stored with their real case. When the bare spelling would be
|
|
4054
|
+
folded by the dialect's normalization strategy, collides with a keyword, or contains
|
|
4055
|
+
characters outside the bare identifier alphabet, the name is returned in the
|
|
4056
|
+
dialect's quoted spelling so the builder marks it as explicitly quoted.
|
|
4057
|
+
"""
|
|
4058
|
+
if not _catalog_name_needs_quotes(name, dialect, source_dialect):
|
|
4059
|
+
return name
|
|
4060
|
+
norm_dialect = _normalize_dialect(dialect)
|
|
4061
|
+
case_dialect = norm_dialect if source_dialect is None else _normalize_dialect(source_dialect)
|
|
4062
|
+
target_name = name
|
|
4063
|
+
if _BARE_IDENTIFIER_RE.fullmatch(name) and _fold_identifier(name, case_dialect) == name:
|
|
4064
|
+
target_name = _fold_identifier(name, norm_dialect)
|
|
4065
|
+
return exp.Identifier(this=target_name, quoted=True).sql(dialect=norm_dialect, copy=False)
|
|
4066
|
+
|
|
4067
|
+
|
|
4068
|
+
def _fold_identifier(name: str, dialect: str | None) -> str:
|
|
4069
|
+
"""Return ``name`` as ``dialect`` folds an unquoted identifier."""
|
|
4070
|
+
strategy = Dialect.get_or_raise(dialect).normalization_strategy
|
|
4071
|
+
if strategy in {NormalizationStrategy.UPPERCASE, NormalizationStrategy.CASE_INSENSITIVE_UPPERCASE}:
|
|
4072
|
+
return name.upper()
|
|
4073
|
+
if strategy is NormalizationStrategy.CASE_SENSITIVE:
|
|
4074
|
+
return name
|
|
4075
|
+
return name.lower()
|
|
4076
|
+
|
|
4077
|
+
|
|
4078
|
+
def _catalog_name_needs_quotes(
|
|
4079
|
+
name: str, dialect: "DialectType | None", source_dialect: "DialectType | None" = None
|
|
4080
|
+
) -> bool:
|
|
4081
|
+
"""Return whether a raw catalog identifier must be quoted to keep its exact spelling.
|
|
4082
|
+
|
|
4083
|
+
Case is judged against the catalog's own (``source_dialect``) folding: a name already in
|
|
4084
|
+
the source's folded form was created unquoted and stays unquoted in the target, so it
|
|
4085
|
+
follows the target's folding. Keywords are judged against the target dialect.
|
|
4086
|
+
"""
|
|
4087
|
+
if not _BARE_IDENTIFIER_RE.fullmatch(name):
|
|
4088
|
+
return True
|
|
4089
|
+
norm_dialect = _normalize_dialect(dialect)
|
|
4090
|
+
sqlglot_dialect = Dialect.get_or_raise(norm_dialect)
|
|
4091
|
+
case_dialect = norm_dialect if source_dialect is None else _normalize_dialect(source_dialect)
|
|
4092
|
+
if _fold_identifier(name, case_dialect) != name:
|
|
4093
|
+
return True
|
|
4094
|
+
if name.lower() in sqlglot_dialect.generator_class.RESERVED_KEYWORDS or name.upper() in _RESERVED_IDENTIFIER_WORDS:
|
|
4095
|
+
return True
|
|
4096
|
+
tokens = sqlglot_dialect.tokenize(name)
|
|
4097
|
+
return len(tokens) != 1 or tokens[0].token_type is not TokenType.VAR
|
|
4098
|
+
|
|
4099
|
+
|
|
4100
|
+
def _record_field_name(name: str, dialect: "DialectType | None") -> str:
|
|
4101
|
+
"""Return SQL text for a record or Arrow field name.
|
|
4102
|
+
|
|
4103
|
+
Single-case bare names (``id``, ``ID``) are left unquoted so they follow the
|
|
4104
|
+
dialect's normal case folding; mixed-case names, keywords, and names with other
|
|
4105
|
+
characters are quoted so ``UserName`` stays ``UserName``.
|
|
4106
|
+
"""
|
|
4107
|
+
if _BARE_IDENTIFIER_RE.fullmatch(name) and (name.islower() or name.isupper()):
|
|
4108
|
+
bare_spelling = name.lower() if name.islower() else name.upper()
|
|
4109
|
+
if not _catalog_name_needs_quotes(bare_spelling, None) and name.upper() not in _RESERVED_IDENTIFIER_WORDS:
|
|
4110
|
+
return name
|
|
4111
|
+
return _catalog_name(name, dialect)
|
|
4112
|
+
|
|
4113
|
+
|
|
4114
|
+
def _catalog_qualified_name(
|
|
4115
|
+
name: str, schema: "str | None", dialect: "DialectType | None", source_dialect: "DialectType | None" = None
|
|
4116
|
+
) -> str:
|
|
4117
|
+
"""Return a schema-qualified SQL reference built from raw catalog identifiers."""
|
|
4118
|
+
quoted_name = _catalog_name(name, dialect, source_dialect)
|
|
4119
|
+
return f"{_catalog_name(schema, dialect, source_dialect)}.{quoted_name}" if schema else quoted_name
|
|
4120
|
+
|
|
4121
|
+
|
|
4122
|
+
def _build_identity_column_constraint(
|
|
4123
|
+
col: "ColumnDefinition", dialect: "DialectType | None" = None
|
|
4124
|
+
) -> exp.ColumnConstraint | None:
|
|
4125
|
+
"""Build an identity ColumnConstraint for a ColumnDefinition when configured.
|
|
4126
|
+
|
|
4127
|
+
Raises:
|
|
4128
|
+
SQLBuilderError: When identity is requested on SQLite, which has no identity columns.
|
|
4129
|
+
"""
|
|
4130
|
+
constraint = _identity_constraint_from_spec(col)
|
|
4131
|
+
if constraint is None:
|
|
4132
|
+
return None
|
|
4133
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
4134
|
+
if norm_dialect == "sqlite" and not col.primary_key:
|
|
4135
|
+
msg = (
|
|
4136
|
+
f"Column {col.name!r}: SQLite has no identity columns; "
|
|
4137
|
+
"use an INTEGER PRIMARY KEY column (optionally AUTOINCREMENT) instead"
|
|
4138
|
+
)
|
|
4139
|
+
raise SQLBuilderError(msg)
|
|
4140
|
+
return constraint
|
|
4141
|
+
|
|
4142
|
+
|
|
4143
|
+
def _identity_constraint_from_spec(col: "ColumnDefinition") -> exp.ColumnConstraint | None:
|
|
4144
|
+
"""Translate the identity / generated identity settings of a column into a constraint node."""
|
|
4145
|
+
if col.identity is not None and col.identity is not False:
|
|
4146
|
+
start_lit: exp.Expr | None = None
|
|
4147
|
+
inc_lit: exp.Expr | None = None
|
|
4148
|
+
if isinstance(col.identity, str):
|
|
4149
|
+
ident_upper = col.identity.strip().upper()
|
|
4150
|
+
ident_match = _IDENTITY_SEED_INC_RE.match(ident_upper)
|
|
4151
|
+
if ident_match is not None:
|
|
4152
|
+
seed_num = int(ident_match.group(1))
|
|
4153
|
+
inc_num = int(ident_match.group(2))
|
|
4154
|
+
is_always = True
|
|
4155
|
+
on_null = False
|
|
4156
|
+
if (seed_num, inc_num) != (1, 1):
|
|
4157
|
+
start_lit = exp.Literal.number(seed_num)
|
|
4158
|
+
inc_lit = exp.Literal.number(inc_num)
|
|
4159
|
+
else:
|
|
4160
|
+
is_always = not ident_upper.startswith("BY DEFAULT")
|
|
4161
|
+
on_null = "ON NULL" in ident_upper
|
|
4162
|
+
else:
|
|
4163
|
+
is_always = True
|
|
4164
|
+
on_null = False
|
|
4165
|
+
return exp.ColumnConstraint(
|
|
4166
|
+
kind=exp.GeneratedAsIdentityColumnConstraint(
|
|
4167
|
+
this=is_always, on_null=on_null or None, start=start_lit, increment=inc_lit
|
|
4168
|
+
)
|
|
4169
|
+
)
|
|
4170
|
+
|
|
4171
|
+
if col.generated is True or (
|
|
4172
|
+
isinstance(col.generated, str) and col.generated.strip().upper() in _IDENTITY_KEYWORDS
|
|
4173
|
+
):
|
|
4174
|
+
if isinstance(col.generated, str):
|
|
4175
|
+
gen_upper = col.generated.strip().upper()
|
|
4176
|
+
is_always = not gen_upper.startswith("BY DEFAULT")
|
|
4177
|
+
on_null = "ON NULL" in gen_upper
|
|
4178
|
+
else:
|
|
4179
|
+
is_always = True
|
|
4180
|
+
on_null = False
|
|
4181
|
+
return exp.ColumnConstraint(
|
|
4182
|
+
kind=exp.GeneratedAsIdentityColumnConstraint(this=is_always, on_null=on_null or None)
|
|
4183
|
+
)
|
|
4184
|
+
|
|
4185
|
+
return None
|
|
4186
|
+
|
|
4187
|
+
|
|
4188
|
+
def _build_computed_column_constraint(
|
|
4189
|
+
col: "ColumnDefinition", dialect: "DialectType | None" = None
|
|
4190
|
+
) -> exp.ColumnConstraint | None:
|
|
4191
|
+
"""Build a generated (computed) column constraint using the dialect's valid syntax.
|
|
4192
|
+
|
|
4193
|
+
PostgreSQL, MySQL, and SQLite render ``GENERATED ALWAYS AS (expr) STORED|VIRTUAL``;
|
|
4194
|
+
DuckDB and Oracle render ``GENERATED ALWAYS AS (expr)`` (virtual only); T-SQL renders
|
|
4195
|
+
``AS (expr) [PERSISTED]``; Spanner renders ``AS (expr) STORED``. ``persisted=None``
|
|
4196
|
+
selects the dialect default storage.
|
|
4197
|
+
|
|
4198
|
+
Raises:
|
|
4199
|
+
SQLBuilderError: When a stored generated column is requested on a dialect that only
|
|
4200
|
+
supports virtual generated columns.
|
|
4201
|
+
"""
|
|
4202
|
+
computed_source: str | exp.Expr | None = col.generated_expression
|
|
4203
|
+
if (
|
|
4204
|
+
computed_source is None
|
|
4205
|
+
and isinstance(col.generated, str)
|
|
4206
|
+
and col.generated.strip().upper() not in _IDENTITY_KEYWORDS
|
|
4207
|
+
):
|
|
4208
|
+
computed_source = col.generated
|
|
4209
|
+
|
|
4210
|
+
if computed_source is None:
|
|
4211
|
+
return None
|
|
4212
|
+
|
|
4213
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
4214
|
+
if isinstance(computed_source, exp.Expr):
|
|
4215
|
+
parsed_computed: exp.Expr = computed_source.copy()
|
|
4216
|
+
else:
|
|
4217
|
+
parsed_computed = sqlglot.parse_one(str(computed_source), read=norm_dialect)
|
|
4218
|
+
parsed_computed = parsed_computed.unnest() if isinstance(parsed_computed, exp.Paren) else parsed_computed
|
|
4219
|
+
persisted = col.persisted if col.persisted is not None else norm_dialect in _STORED_GENERATED_DEFAULT_DIALECTS
|
|
4220
|
+
|
|
4221
|
+
if norm_dialect in _VIRTUAL_ONLY_GENERATED_DIALECTS:
|
|
4222
|
+
if persisted:
|
|
4223
|
+
msg = f"Column {col.name!r}: {norm_dialect} supports only virtual generated columns, not STORED"
|
|
4224
|
+
raise SQLBuilderError(msg)
|
|
4225
|
+
return exp.ColumnConstraint(kind=exp.GeneratedAsIdentityColumnConstraint(this=True, expression=parsed_computed))
|
|
4226
|
+
if norm_dialect == "spanner":
|
|
4227
|
+
persisted = True
|
|
4228
|
+
computed_body = (
|
|
4229
|
+
parsed_computed if norm_dialect in _SELF_PARENTHESIZED_GENERATED_DIALECTS else exp.Paren(this=parsed_computed)
|
|
4230
|
+
)
|
|
4231
|
+
return exp.ColumnConstraint(kind=exp.ComputedColumnConstraint(this=computed_body, persisted=persisted))
|
|
4232
|
+
|
|
4233
|
+
|
|
4234
|
+
def _build_default_expression(default: Any, dialect: "DialectType | None") -> exp.Expr:
|
|
4235
|
+
"""Convert a column default (literal value, keyword string, SQL text, or expression) to an expression.
|
|
4236
|
+
|
|
4237
|
+
Expression defaults are parenthesized on engines that only accept ``DEFAULT (expr)``
|
|
4238
|
+
for non-literal defaults (SQLite, MySQL, Spanner).
|
|
4239
|
+
"""
|
|
4240
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
4241
|
+
if isinstance(default, exp.Expr):
|
|
4242
|
+
default_expr: exp.Expr = default.copy()
|
|
4243
|
+
elif not isinstance(default, str):
|
|
4244
|
+
return exp.convert(default)
|
|
4245
|
+
elif default.upper() == CURRENT_TIMESTAMP_KEYWORD:
|
|
4246
|
+
return exp.CurrentTimestamp()
|
|
4247
|
+
elif default.upper() == CURRENT_DATE_KEYWORD:
|
|
4248
|
+
return exp.CurrentDate()
|
|
4249
|
+
elif default.upper() == CURRENT_TIME_KEYWORD:
|
|
4250
|
+
return exp.CurrentTime()
|
|
4251
|
+
elif "(" in default:
|
|
4252
|
+
default_expr = exp.maybe_parse(default, dialect=norm_dialect)
|
|
4253
|
+
else:
|
|
4254
|
+
return exp.convert(default)
|
|
4255
|
+
if (
|
|
4256
|
+
norm_dialect in _PARENTHESIZED_DEFAULT_DIALECTS
|
|
4257
|
+
and not isinstance(default_expr, exp.Paren)
|
|
4258
|
+
and not _is_literal_default(default_expr)
|
|
4259
|
+
):
|
|
4260
|
+
return exp.Paren(this=default_expr)
|
|
4261
|
+
return default_expr
|
|
4262
|
+
|
|
4263
|
+
|
|
4264
|
+
def _build_collate_column_constraint(collate: str, dialect: "DialectType | None" = None) -> exp.ColumnConstraint:
|
|
4265
|
+
"""Build a COLLATE ColumnConstraint, preserving explicit case on case-folding dialects."""
|
|
4266
|
+
collate_ident = _parse_ddl_identifier(collate, dialect=dialect)
|
|
4267
|
+
if any(ch.isupper() for ch in collate) and (
|
|
4268
|
+
_normalize_dialect(dialect) in {"postgres", "postgresql", "cockroach", "cockroachdb", "duckdb"}
|
|
4269
|
+
):
|
|
4270
|
+
collate_ident.set("quoted", True)
|
|
4271
|
+
collate_ident.meta["_explicit_quoted"] = True
|
|
4272
|
+
collate_ident.meta["sqlspec_explicit_table_quote"] = True
|
|
4273
|
+
return exp.ColumnConstraint(kind=exp.CollateColumnConstraint(this=collate_ident))
|
|
4274
|
+
|
|
4275
|
+
|
|
4276
|
+
def _is_uuid_string(value: Any) -> bool:
|
|
4277
|
+
return isinstance(value, str) and bool(_UUID_STR_RE.match(value.strip()))
|
|
4278
|
+
|
|
4279
|
+
|
|
4280
|
+
def _is_iso_datetime_string(value: Any) -> bool:
|
|
4281
|
+
if not isinstance(value, str) or not _ISO_DATETIME_STR_RE.match(value.strip()):
|
|
4282
|
+
return False
|
|
4283
|
+
normalized = value.strip()
|
|
4284
|
+
if normalized.endswith(("Z", "z")):
|
|
4285
|
+
normalized = f"{normalized[:-1]}+00:00"
|
|
4286
|
+
try:
|
|
4287
|
+
datetime.fromisoformat(normalized)
|
|
4288
|
+
except ValueError:
|
|
4289
|
+
return False
|
|
4290
|
+
return True
|
|
4291
|
+
|
|
4292
|
+
|
|
4293
|
+
def _is_iso_date_string(value: Any) -> bool:
|
|
4294
|
+
if not isinstance(value, str) or not _ISO_DATE_STR_RE.match(value.strip()):
|
|
4295
|
+
return False
|
|
4296
|
+
try:
|
|
4297
|
+
date.fromisoformat(value.strip())
|
|
4298
|
+
except ValueError:
|
|
4299
|
+
return False
|
|
4300
|
+
return True
|
|
4301
|
+
|
|
4302
|
+
|
|
4303
|
+
def _infer_sql_type_from_values(values: "Sequence[Any]", dialect: str | None = None, *, key: bool = False) -> str:
|
|
4304
|
+
"""Infer a dialect-aware SQL column type string from observed non-null Python values.
|
|
4305
|
+
|
|
4306
|
+
Args:
|
|
4307
|
+
values: Observed non-null values for one column.
|
|
4308
|
+
dialect: Optional target dialect name.
|
|
4309
|
+
key: Whether the column participates in a primary key, which bounds text types
|
|
4310
|
+
on engines that cannot index unbounded text.
|
|
4311
|
+
|
|
4312
|
+
Returns:
|
|
4313
|
+
SQL type string resolved through the shared category mapping.
|
|
4314
|
+
"""
|
|
4315
|
+
category = _infer_value_category(values)
|
|
4316
|
+
if key and category == "text":
|
|
4317
|
+
category = "key_text"
|
|
4318
|
+
if category == "decimal":
|
|
4319
|
+
precision, scale = _decimal_values_precision(values)
|
|
4320
|
+
return sql_type_for_category("decimal", dialect, precision=precision, scale=scale)
|
|
4321
|
+
return sql_type_for_category(category, dialect)
|
|
4322
|
+
|
|
4323
|
+
|
|
4324
|
+
def _infer_value_category(values: "Sequence[Any]") -> str:
|
|
4325
|
+
"""Map observed non-null Python values to a neutral SQL type category."""
|
|
4326
|
+
if not values:
|
|
4327
|
+
return "text"
|
|
4328
|
+
if all(isinstance(val, bool) for val in values):
|
|
4329
|
+
return "boolean"
|
|
4330
|
+
if all(isinstance(val, (int, float, Decimal)) and not isinstance(val, bool) for val in values):
|
|
4331
|
+
if any(isinstance(val, Decimal) for val in values):
|
|
4332
|
+
return "decimal"
|
|
4333
|
+
if any(isinstance(val, float) for val in values):
|
|
4334
|
+
return "double"
|
|
4335
|
+
return "bigint"
|
|
4336
|
+
if all(isinstance(val, UUID) or _is_uuid_string(val) for val in values):
|
|
4337
|
+
return "uuid"
|
|
4338
|
+
if all(isinstance(val, datetime) or _is_iso_datetime_string(val) for val in values):
|
|
4339
|
+
return "timestamptz" if any(_is_timezone_aware(val) for val in values) else "timestamp"
|
|
4340
|
+
if all((isinstance(val, date) and not isinstance(val, datetime)) or _is_iso_date_string(val) for val in values):
|
|
4341
|
+
return "date"
|
|
4342
|
+
if all(
|
|
4343
|
+
isinstance(val, (date, datetime)) or _is_iso_date_string(val) or _is_iso_datetime_string(val) for val in values
|
|
4344
|
+
):
|
|
4345
|
+
return "timestamptz" if any(_is_timezone_aware(val) for val in values) else "timestamp"
|
|
4346
|
+
if all(isinstance(val, time) for val in values):
|
|
4347
|
+
return "time"
|
|
4348
|
+
if all(isinstance(val, timedelta) for val in values):
|
|
4349
|
+
return "interval"
|
|
4350
|
+
if all(isinstance(val, (bytes, bytearray, memoryview)) for val in values):
|
|
4351
|
+
return "blob"
|
|
4352
|
+
if all(isinstance(val, (Mapping, list, tuple)) for val in values):
|
|
4353
|
+
return "json"
|
|
4354
|
+
return "text"
|
|
4355
|
+
|
|
4356
|
+
|
|
4357
|
+
def _is_timezone_aware(value: Any) -> bool:
|
|
4358
|
+
"""Return whether a datetime or ISO datetime string carries a UTC offset."""
|
|
4359
|
+
if isinstance(value, datetime):
|
|
4360
|
+
return value.tzinfo is not None and value.utcoffset() is not None
|
|
4361
|
+
if isinstance(value, str) and _is_iso_datetime_string(value):
|
|
4362
|
+
return bool(_ISO_OFFSET_SUFFIX_RE.search(value.strip()))
|
|
4363
|
+
return False
|
|
4364
|
+
|
|
4365
|
+
|
|
4366
|
+
def _decimal_values_precision(values: "Sequence[Any]") -> tuple[int, int]:
|
|
4367
|
+
"""Return a decimal precision and scale wide enough for every observed numeric value."""
|
|
4368
|
+
integer_digits = 1
|
|
4369
|
+
scale = _DEFAULT_INFERRED_DECIMAL_SCALE
|
|
4370
|
+
for val in values:
|
|
4371
|
+
if isinstance(val, Decimal) and val.is_finite():
|
|
4372
|
+
integer_digits = max(integer_digits, val.adjusted() + 1)
|
|
4373
|
+
scale = max(scale, -int(val.as_tuple().exponent))
|
|
4374
|
+
elif isinstance(val, int):
|
|
4375
|
+
integer_digits = max(integer_digits, len(str(abs(val))))
|
|
4376
|
+
return max(_DEFAULT_INFERRED_DECIMAL_PRECISION, integer_digits + scale), scale
|
|
4377
|
+
|
|
4378
|
+
|
|
4379
|
+
def _normalize_ddl_identifier(node: exp.Expr, normalizer: Dialect) -> exp.Expr:
|
|
4380
|
+
"""Case-normalize and quote one DDL identifier unless it carries an explicit quote marker."""
|
|
4381
|
+
if not isinstance(node, exp.Identifier):
|
|
4382
|
+
return node
|
|
4383
|
+
if not node.meta.get("sqlspec_explicit_table_quote"):
|
|
4384
|
+
normalizer.normalize_identifier(node)
|
|
4385
|
+
node.set("quoted", True)
|
|
4386
|
+
return node
|
|
4387
|
+
|
|
4388
|
+
|
|
4389
|
+
def _dialect_foreign_key_actions(
|
|
4390
|
+
constraint: "ConstraintDefinition", dialect: "DialectType | None"
|
|
4391
|
+
) -> tuple[str | None, str | None]:
|
|
4392
|
+
"""Return the referential actions to render, rejecting actions the dialect cannot express.
|
|
4393
|
+
|
|
4394
|
+
Oracle accepts only ``ON DELETE CASCADE`` and ``ON DELETE SET NULL``; DuckDB accepts no
|
|
4395
|
+
referential actions. ``NO ACTION`` and ``RESTRICT`` are the default behaviour there and
|
|
4396
|
+
are omitted.
|
|
4397
|
+
|
|
4398
|
+
Raises:
|
|
4399
|
+
SQLBuilderError: When an action has no equivalent on the target dialect.
|
|
4400
|
+
"""
|
|
4401
|
+
on_delete = constraint.on_delete
|
|
4402
|
+
on_update = constraint.on_update
|
|
4403
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
4404
|
+
implicit_actions = {FOREIGN_KEY_ACTION_NO_ACTION, FOREIGN_KEY_ACTION_RESTRICT}
|
|
4405
|
+
if norm_dialect in {"duckdb", "bigquery"}:
|
|
4406
|
+
label_dialect = "BigQuery" if norm_dialect == "bigquery" else "DuckDB"
|
|
4407
|
+
for action_type, action in (("ON DELETE", on_delete), ("ON UPDATE", on_update)):
|
|
4408
|
+
if action and action not in implicit_actions:
|
|
4409
|
+
msg = f"{label_dialect} does not support {action_type} {action} on foreign keys"
|
|
4410
|
+
raise SQLBuilderError(msg)
|
|
4411
|
+
return None, None
|
|
4412
|
+
if norm_dialect != "oracle":
|
|
4413
|
+
return on_delete, on_update
|
|
4414
|
+
if on_update and on_update not in implicit_actions:
|
|
4415
|
+
msg = f"Oracle does not support ON UPDATE {on_update} on foreign keys"
|
|
4416
|
+
raise SQLBuilderError(msg)
|
|
4417
|
+
if on_delete and on_delete not in implicit_actions and on_delete not in _ORACLE_ON_DELETE_ACTIONS:
|
|
4418
|
+
msg = f"Oracle does not support ON DELETE {on_delete} on foreign keys"
|
|
4419
|
+
raise SQLBuilderError(msg)
|
|
4420
|
+
return (on_delete if on_delete in _ORACLE_ON_DELETE_ACTIONS else None), None
|
|
4421
|
+
|
|
4422
|
+
|
|
4423
|
+
def _validate_clause_identifier(value: Any, *, label: str) -> str:
|
|
4424
|
+
"""Validate that a raw DDL clause identifier matches ``[A-Za-z_][A-Za-z0-9_]*``."""
|
|
4425
|
+
if not isinstance(value, str) or not _BARE_IDENTIFIER_RE.fullmatch(value):
|
|
4426
|
+
msg = f"Invalid {label}: {value!r}"
|
|
4427
|
+
raise SQLBuilderError(msg)
|
|
4428
|
+
return value
|
|
4429
|
+
|
|
4430
|
+
|
|
4431
|
+
_FORBIDDEN_CLAUSE_NODES: Final = (*_FORBIDDEN_STATEMENT_NODES, exp.Select, exp.Subquery, exp.SetOperation)
|
|
4432
|
+
|
|
4433
|
+
|
|
4434
|
+
def _check_ddl_expression_nodes(expression: exp.Expr, *, label: str, text: Any) -> exp.Expr:
|
|
4435
|
+
"""Reject statement, subquery, and set-operation nodes inside a raw DDL expression."""
|
|
4436
|
+
if isinstance(expression, _FORBIDDEN_CLAUSE_NODES) or expression.find(*_FORBIDDEN_CLAUSE_NODES) is not None:
|
|
4437
|
+
msg = f"Invalid {label}: {text!r}"
|
|
4438
|
+
raise SQLBuilderError(msg)
|
|
4439
|
+
return expression
|
|
4440
|
+
|
|
4441
|
+
|
|
4442
|
+
def _parse_ddl_expression(text: str, *, label: str, dialect: "DialectType | None") -> exp.Expr:
|
|
4443
|
+
"""Parse trusted raw DDL expression text and require exactly one plain expression.
|
|
4444
|
+
|
|
4445
|
+
Args:
|
|
4446
|
+
text: Raw expression text supplied to a DDL builder.
|
|
4447
|
+
label: Clause name used in the error message.
|
|
4448
|
+
dialect: Dialect used to parse the text.
|
|
4449
|
+
|
|
4450
|
+
Returns:
|
|
4451
|
+
The parsed expression.
|
|
4452
|
+
|
|
4453
|
+
Raises:
|
|
4454
|
+
SQLBuilderError: When the text is blank, contains a statement terminator, fails to parse,
|
|
4455
|
+
holds more than one statement, or contains a statement, subquery, or set operation.
|
|
4456
|
+
"""
|
|
4457
|
+
norm_dialect = _normalize_dialect(dialect) if dialect else None
|
|
4458
|
+
if (
|
|
4459
|
+
not isinstance(text, str)
|
|
4460
|
+
or not text.strip()
|
|
4461
|
+
or "\x00" in text
|
|
4462
|
+
or contains_statement_terminator(text, dialect=norm_dialect)
|
|
4463
|
+
):
|
|
4464
|
+
msg = f"Invalid {label}: {text!r}"
|
|
4465
|
+
raise SQLBuilderError(msg)
|
|
4466
|
+
try:
|
|
4467
|
+
statements = sqlglot.parse(text, read=norm_dialect)
|
|
4468
|
+
except (ParseError, TokenError) as exc:
|
|
4469
|
+
msg = f"Invalid {label}: {text!r}"
|
|
4470
|
+
raise with_cause(SQLBuilderError(msg), exc) from exc
|
|
4471
|
+
if len(statements) != 1 or statements[0] is None:
|
|
4472
|
+
msg = f"Invalid {label}: {text!r}"
|
|
4473
|
+
raise SQLBuilderError(msg)
|
|
4474
|
+
return _check_ddl_expression_nodes(statements[0], label=label, text=text)
|
|
4475
|
+
|
|
4476
|
+
|
|
4477
|
+
def _parse_partition_by(spec: str, dialect: "DialectType | None") -> exp.Expr:
|
|
4478
|
+
"""Parse and validate a CREATE TABLE PARTITION BY specification."""
|
|
4479
|
+
try:
|
|
4480
|
+
return _parse_ddl_expression(spec, label="PARTITION BY specification", dialect=dialect)
|
|
4481
|
+
except SQLBuilderError:
|
|
4482
|
+
if isinstance(spec, str) and _BARE_IDENTIFIER_RE.fullmatch(spec):
|
|
4483
|
+
return exp.var(spec)
|
|
4484
|
+
raise
|
|
4485
|
+
|
|
4486
|
+
|
|
4487
|
+
def _coerce_int_argument(value: Any, *, name: str) -> int:
|
|
4488
|
+
"""Coerce an integer sequence option, rejecting booleans and non-integer values."""
|
|
4489
|
+
if isinstance(value, bool):
|
|
4490
|
+
msg = f"{name} must be an integer, got bool"
|
|
4491
|
+
raise SQLBuilderError(msg)
|
|
4492
|
+
if isinstance(value, int):
|
|
4493
|
+
return int(value)
|
|
4494
|
+
if isinstance(value, str):
|
|
4495
|
+
stripped = value.strip()
|
|
4496
|
+
if stripped:
|
|
4497
|
+
try:
|
|
4498
|
+
return int(stripped)
|
|
4499
|
+
except ValueError as exc:
|
|
4500
|
+
msg = f"{name} must be an integer, got {value!r}"
|
|
4501
|
+
raise with_cause(SQLBuilderError(msg), exc) from exc
|
|
4502
|
+
msg = f"{name} must be an integer, got {type(value).__name__}"
|
|
4503
|
+
raise SQLBuilderError(msg)
|