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.
Files changed (1144) hide show
  1. 6b29784d6b1cafc66758__mypyc.cp315-win_amd64.pyd +0 -0
  2. sqlspec/__init__.py +381 -0
  3. sqlspec/__main__.py +14 -0
  4. sqlspec/__metadata__.py +14 -0
  5. sqlspec/_typing.py +775 -0
  6. sqlspec/adapters/__init__.py +3 -0
  7. sqlspec/adapters/adbc/__init__.py +16 -0
  8. sqlspec/adapters/adbc/_typing.py +221 -0
  9. sqlspec/adapters/adbc/adk/__init__.py +11 -0
  10. sqlspec/adapters/adbc/adk/store.py +4101 -0
  11. sqlspec/adapters/adbc/config.py +843 -0
  12. sqlspec/adapters/adbc/core.cp315-win_amd64.pyd +0 -0
  13. sqlspec/adapters/adbc/core.py +3209 -0
  14. sqlspec/adapters/adbc/data_dictionary.py +1448 -0
  15. sqlspec/adapters/adbc/driver.cp315-win_amd64.pyd +0 -0
  16. sqlspec/adapters/adbc/driver.py +1400 -0
  17. sqlspec/adapters/adbc/events/__init__.py +5 -0
  18. sqlspec/adapters/adbc/events/store.py +384 -0
  19. sqlspec/adapters/adbc/litestar/__init__.py +5 -0
  20. sqlspec/adapters/adbc/litestar/store.py +962 -0
  21. sqlspec/adapters/adbc/pool.cp315-win_amd64.pyd +0 -0
  22. sqlspec/adapters/adbc/pool.py +242 -0
  23. sqlspec/adapters/adbc/type_converter.cp315-win_amd64.pyd +0 -0
  24. sqlspec/adapters/adbc/type_converter.py +117 -0
  25. sqlspec/adapters/aiomysql/__init__.py +25 -0
  26. sqlspec/adapters/aiomysql/_typing.py +134 -0
  27. sqlspec/adapters/aiomysql/adk/__init__.py +5 -0
  28. sqlspec/adapters/aiomysql/adk/store.py +1542 -0
  29. sqlspec/adapters/aiomysql/config.py +634 -0
  30. sqlspec/adapters/aiomysql/core.cp315-win_amd64.pyd +0 -0
  31. sqlspec/adapters/aiomysql/core.py +922 -0
  32. sqlspec/adapters/aiomysql/data_dictionary.py +16 -0
  33. sqlspec/adapters/aiomysql/driver.cp315-win_amd64.pyd +0 -0
  34. sqlspec/adapters/aiomysql/driver.py +494 -0
  35. sqlspec/adapters/aiomysql/events/__init__.py +5 -0
  36. sqlspec/adapters/aiomysql/events/store.py +72 -0
  37. sqlspec/adapters/aiomysql/litestar/__init__.py +5 -0
  38. sqlspec/adapters/aiomysql/litestar/store.py +345 -0
  39. sqlspec/adapters/aiosqlite/__init__.py +43 -0
  40. sqlspec/adapters/aiosqlite/_typing.py +75 -0
  41. sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
  42. sqlspec/adapters/aiosqlite/adk/store.py +1546 -0
  43. sqlspec/adapters/aiosqlite/config.py +607 -0
  44. sqlspec/adapters/aiosqlite/core.cp315-win_amd64.pyd +0 -0
  45. sqlspec/adapters/aiosqlite/core.py +1155 -0
  46. sqlspec/adapters/aiosqlite/data_dictionary.py +343 -0
  47. sqlspec/adapters/aiosqlite/driver.cp315-win_amd64.pyd +0 -0
  48. sqlspec/adapters/aiosqlite/driver.py +559 -0
  49. sqlspec/adapters/aiosqlite/events/__init__.py +5 -0
  50. sqlspec/adapters/aiosqlite/events/store.py +54 -0
  51. sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
  52. sqlspec/adapters/aiosqlite/litestar/store.py +315 -0
  53. sqlspec/adapters/aiosqlite/pool.cp315-win_amd64.pyd +0 -0
  54. sqlspec/adapters/aiosqlite/pool.py +1323 -0
  55. sqlspec/adapters/aiosqlite/type_converter.cp315-win_amd64.pyd +0 -0
  56. sqlspec/adapters/aiosqlite/type_converter.py +114 -0
  57. sqlspec/adapters/arrow_odbc/__init__.py +32 -0
  58. sqlspec/adapters/arrow_odbc/_typing.py +131 -0
  59. sqlspec/adapters/arrow_odbc/adk/__init__.py +5 -0
  60. sqlspec/adapters/arrow_odbc/adk/store.py +1671 -0
  61. sqlspec/adapters/arrow_odbc/config.py +446 -0
  62. sqlspec/adapters/arrow_odbc/core.cp315-win_amd64.pyd +0 -0
  63. sqlspec/adapters/arrow_odbc/core.py +795 -0
  64. sqlspec/adapters/arrow_odbc/data_dictionary.py +345 -0
  65. sqlspec/adapters/arrow_odbc/driver.cp315-win_amd64.pyd +0 -0
  66. sqlspec/adapters/arrow_odbc/driver.py +885 -0
  67. sqlspec/adapters/arrow_odbc/events/__init__.py +5 -0
  68. sqlspec/adapters/arrow_odbc/events/store.py +114 -0
  69. sqlspec/adapters/arrow_odbc/litestar/__init__.py +5 -0
  70. sqlspec/adapters/arrow_odbc/litestar/store.py +682 -0
  71. sqlspec/adapters/arrow_odbc/type_converter.cp315-win_amd64.pyd +0 -0
  72. sqlspec/adapters/arrow_odbc/type_converter.py +95 -0
  73. sqlspec/adapters/asyncmy/__init__.py +27 -0
  74. sqlspec/adapters/asyncmy/_typing.py +215 -0
  75. sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
  76. sqlspec/adapters/asyncmy/adk/store.py +1544 -0
  77. sqlspec/adapters/asyncmy/config.py +707 -0
  78. sqlspec/adapters/asyncmy/core.cp315-win_amd64.pyd +0 -0
  79. sqlspec/adapters/asyncmy/core.py +917 -0
  80. sqlspec/adapters/asyncmy/data_dictionary.py +16 -0
  81. sqlspec/adapters/asyncmy/driver.cp315-win_amd64.pyd +0 -0
  82. sqlspec/adapters/asyncmy/driver.py +529 -0
  83. sqlspec/adapters/asyncmy/events/__init__.py +5 -0
  84. sqlspec/adapters/asyncmy/events/store.py +72 -0
  85. sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
  86. sqlspec/adapters/asyncmy/litestar/store.py +348 -0
  87. sqlspec/adapters/asyncpg/__init__.py +28 -0
  88. sqlspec/adapters/asyncpg/_typing.py +113 -0
  89. sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
  90. sqlspec/adapters/asyncpg/adk/store.py +1145 -0
  91. sqlspec/adapters/asyncpg/config.py +903 -0
  92. sqlspec/adapters/asyncpg/core.cp315-win_amd64.pyd +0 -0
  93. sqlspec/adapters/asyncpg/core.py +797 -0
  94. sqlspec/adapters/asyncpg/data_dictionary.py +417 -0
  95. sqlspec/adapters/asyncpg/driver.cp315-win_amd64.pyd +0 -0
  96. sqlspec/adapters/asyncpg/driver.py +927 -0
  97. sqlspec/adapters/asyncpg/events/__init__.py +6 -0
  98. sqlspec/adapters/asyncpg/events/_hub.cp315-win_amd64.pyd +0 -0
  99. sqlspec/adapters/asyncpg/events/_hub.py +279 -0
  100. sqlspec/adapters/asyncpg/events/backend.py +410 -0
  101. sqlspec/adapters/asyncpg/events/store.py +57 -0
  102. sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
  103. sqlspec/adapters/asyncpg/litestar/store.py +278 -0
  104. sqlspec/adapters/asyncpg/tenant.cp315-win_amd64.pyd +0 -0
  105. sqlspec/adapters/asyncpg/tenant.py +140 -0
  106. sqlspec/adapters/bigquery/__init__.py +23 -0
  107. sqlspec/adapters/bigquery/_typing.py +184 -0
  108. sqlspec/adapters/bigquery/adk/__init__.py +5 -0
  109. sqlspec/adapters/bigquery/adk/store.py +920 -0
  110. sqlspec/adapters/bigquery/config.py +631 -0
  111. sqlspec/adapters/bigquery/core.cp315-win_amd64.pyd +0 -0
  112. sqlspec/adapters/bigquery/core.py +1433 -0
  113. sqlspec/adapters/bigquery/data_dictionary.py +502 -0
  114. sqlspec/adapters/bigquery/driver.cp315-win_amd64.pyd +0 -0
  115. sqlspec/adapters/bigquery/driver.py +1266 -0
  116. sqlspec/adapters/bigquery/events/__init__.py +5 -0
  117. sqlspec/adapters/bigquery/events/store.py +158 -0
  118. sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
  119. sqlspec/adapters/bigquery/litestar/store.py +359 -0
  120. sqlspec/adapters/cockroach_asyncpg/__init__.py +32 -0
  121. sqlspec/adapters/cockroach_asyncpg/_typing.py +54 -0
  122. sqlspec/adapters/cockroach_asyncpg/adk/__init__.py +9 -0
  123. sqlspec/adapters/cockroach_asyncpg/adk/store.py +1096 -0
  124. sqlspec/adapters/cockroach_asyncpg/config.py +653 -0
  125. sqlspec/adapters/cockroach_asyncpg/core.cp315-win_amd64.pyd +0 -0
  126. sqlspec/adapters/cockroach_asyncpg/core.py +835 -0
  127. sqlspec/adapters/cockroach_asyncpg/data_dictionary.py +371 -0
  128. sqlspec/adapters/cockroach_asyncpg/driver.cp315-win_amd64.pyd +0 -0
  129. sqlspec/adapters/cockroach_asyncpg/driver.py +438 -0
  130. sqlspec/adapters/cockroach_asyncpg/events/__init__.py +5 -0
  131. sqlspec/adapters/cockroach_asyncpg/events/store.py +20 -0
  132. sqlspec/adapters/cockroach_asyncpg/litestar/__init__.py +5 -0
  133. sqlspec/adapters/cockroach_asyncpg/litestar/store.py +203 -0
  134. sqlspec/adapters/cockroach_asyncpg/tenant.cp315-win_amd64.pyd +0 -0
  135. sqlspec/adapters/cockroach_asyncpg/tenant.py +143 -0
  136. sqlspec/adapters/cockroach_psycopg/__init__.py +46 -0
  137. sqlspec/adapters/cockroach_psycopg/_typing.py +271 -0
  138. sqlspec/adapters/cockroach_psycopg/adk/__init__.py +17 -0
  139. sqlspec/adapters/cockroach_psycopg/adk/store.py +2274 -0
  140. sqlspec/adapters/cockroach_psycopg/config.py +1285 -0
  141. sqlspec/adapters/cockroach_psycopg/core.cp315-win_amd64.pyd +0 -0
  142. sqlspec/adapters/cockroach_psycopg/core.py +667 -0
  143. sqlspec/adapters/cockroach_psycopg/data_dictionary.py +622 -0
  144. sqlspec/adapters/cockroach_psycopg/driver.cp315-win_amd64.pyd +0 -0
  145. sqlspec/adapters/cockroach_psycopg/driver.py +864 -0
  146. sqlspec/adapters/cockroach_psycopg/events/__init__.py +8 -0
  147. sqlspec/adapters/cockroach_psycopg/events/store.py +34 -0
  148. sqlspec/adapters/cockroach_psycopg/litestar/__init__.py +9 -0
  149. sqlspec/adapters/cockroach_psycopg/litestar/store.py +413 -0
  150. sqlspec/adapters/cockroach_psycopg/tenant.cp315-win_amd64.pyd +0 -0
  151. sqlspec/adapters/cockroach_psycopg/tenant.py +222 -0
  152. sqlspec/adapters/db2/__init__.py +34 -0
  153. sqlspec/adapters/db2/_typing.py +357 -0
  154. sqlspec/adapters/db2/adk/__init__.py +10 -0
  155. sqlspec/adapters/db2/adk/store.py +1950 -0
  156. sqlspec/adapters/db2/config.py +550 -0
  157. sqlspec/adapters/db2/core.cp315-win_amd64.pyd +0 -0
  158. sqlspec/adapters/db2/core.py +1021 -0
  159. sqlspec/adapters/db2/data_dictionary.py +493 -0
  160. sqlspec/adapters/db2/driver.cp315-win_amd64.pyd +0 -0
  161. sqlspec/adapters/db2/driver.py +898 -0
  162. sqlspec/adapters/db2/events/__init__.py +5 -0
  163. sqlspec/adapters/db2/events/store.py +77 -0
  164. sqlspec/adapters/db2/litestar/__init__.py +5 -0
  165. sqlspec/adapters/db2/litestar/store.py +519 -0
  166. sqlspec/adapters/db2/migrations.py +221 -0
  167. sqlspec/adapters/db2/pool.cp315-win_amd64.pyd +0 -0
  168. sqlspec/adapters/db2/pool.py +876 -0
  169. sqlspec/adapters/db2/tenant.cp315-win_amd64.pyd +0 -0
  170. sqlspec/adapters/db2/tenant.py +292 -0
  171. sqlspec/adapters/duckdb/__init__.py +30 -0
  172. sqlspec/adapters/duckdb/_typing.py +182 -0
  173. sqlspec/adapters/duckdb/adk/__init__.py +10 -0
  174. sqlspec/adapters/duckdb/adk/store.py +1672 -0
  175. sqlspec/adapters/duckdb/config.py +506 -0
  176. sqlspec/adapters/duckdb/core.cp315-win_amd64.pyd +0 -0
  177. sqlspec/adapters/duckdb/core.py +1299 -0
  178. sqlspec/adapters/duckdb/data_dictionary.py +553 -0
  179. sqlspec/adapters/duckdb/driver.cp315-win_amd64.pyd +0 -0
  180. sqlspec/adapters/duckdb/driver.py +1214 -0
  181. sqlspec/adapters/duckdb/events/__init__.py +5 -0
  182. sqlspec/adapters/duckdb/events/store.py +38 -0
  183. sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
  184. sqlspec/adapters/duckdb/litestar/store.py +313 -0
  185. sqlspec/adapters/duckdb/pool.cp315-win_amd64.pyd +0 -0
  186. sqlspec/adapters/duckdb/pool.py +1121 -0
  187. sqlspec/adapters/mssql_python/__init__.py +42 -0
  188. sqlspec/adapters/mssql_python/_typing.py +135 -0
  189. sqlspec/adapters/mssql_python/adk/__init__.py +5 -0
  190. sqlspec/adapters/mssql_python/adk/store.py +1278 -0
  191. sqlspec/adapters/mssql_python/config.py +455 -0
  192. sqlspec/adapters/mssql_python/core.cp315-win_amd64.pyd +0 -0
  193. sqlspec/adapters/mssql_python/core.py +862 -0
  194. sqlspec/adapters/mssql_python/data_dictionary.py +417 -0
  195. sqlspec/adapters/mssql_python/driver.cp315-win_amd64.pyd +0 -0
  196. sqlspec/adapters/mssql_python/driver.py +772 -0
  197. sqlspec/adapters/mssql_python/events/__init__.py +5 -0
  198. sqlspec/adapters/mssql_python/events/store.py +46 -0
  199. sqlspec/adapters/mssql_python/litestar/__init__.py +5 -0
  200. sqlspec/adapters/mssql_python/litestar/store.py +355 -0
  201. sqlspec/adapters/mssql_python/migrations.py +162 -0
  202. sqlspec/adapters/mssql_python/pool.cp315-win_amd64.pyd +0 -0
  203. sqlspec/adapters/mssql_python/pool.py +165 -0
  204. sqlspec/adapters/mssql_python/tenant.cp315-win_amd64.pyd +0 -0
  205. sqlspec/adapters/mssql_python/tenant.py +74 -0
  206. sqlspec/adapters/mssql_python/type_converter.cp315-win_amd64.pyd +0 -0
  207. sqlspec/adapters/mssql_python/type_converter.py +98 -0
  208. sqlspec/adapters/mysqlconnector/__init__.py +47 -0
  209. sqlspec/adapters/mysqlconnector/_typing.py +205 -0
  210. sqlspec/adapters/mysqlconnector/adk/__init__.py +17 -0
  211. sqlspec/adapters/mysqlconnector/adk/store.py +2503 -0
  212. sqlspec/adapters/mysqlconnector/config.py +925 -0
  213. sqlspec/adapters/mysqlconnector/core.cp315-win_amd64.pyd +0 -0
  214. sqlspec/adapters/mysqlconnector/core.py +1075 -0
  215. sqlspec/adapters/mysqlconnector/data_dictionary.py +23 -0
  216. sqlspec/adapters/mysqlconnector/driver.cp315-win_amd64.pyd +0 -0
  217. sqlspec/adapters/mysqlconnector/driver.py +702 -0
  218. sqlspec/adapters/mysqlconnector/events/__init__.py +8 -0
  219. sqlspec/adapters/mysqlconnector/events/store.py +89 -0
  220. sqlspec/adapters/mysqlconnector/litestar/__init__.py +9 -0
  221. sqlspec/adapters/mysqlconnector/litestar/store.py +524 -0
  222. sqlspec/adapters/oracledb/__init__.py +159 -0
  223. sqlspec/adapters/oracledb/_json_handlers.cp315-win_amd64.pyd +0 -0
  224. sqlspec/adapters/oracledb/_json_handlers.py +208 -0
  225. sqlspec/adapters/oracledb/_param_types.cp315-win_amd64.pyd +0 -0
  226. sqlspec/adapters/oracledb/_param_types.py +65 -0
  227. sqlspec/adapters/oracledb/_plugins.py +137 -0
  228. sqlspec/adapters/oracledb/_storage.cp315-win_amd64.pyd +0 -0
  229. sqlspec/adapters/oracledb/_storage.py +138 -0
  230. sqlspec/adapters/oracledb/_typing.py +468 -0
  231. sqlspec/adapters/oracledb/_uuid_handlers.cp315-win_amd64.pyd +0 -0
  232. sqlspec/adapters/oracledb/_uuid_handlers.py +143 -0
  233. sqlspec/adapters/oracledb/_vector_handlers.cp315-win_amd64.pyd +0 -0
  234. sqlspec/adapters/oracledb/_vector_handlers.py +252 -0
  235. sqlspec/adapters/oracledb/adk/__init__.py +27 -0
  236. sqlspec/adapters/oracledb/adk/store.py +4031 -0
  237. sqlspec/adapters/oracledb/config.py +1785 -0
  238. sqlspec/adapters/oracledb/core.cp315-win_amd64.pyd +0 -0
  239. sqlspec/adapters/oracledb/core.py +5416 -0
  240. sqlspec/adapters/oracledb/data_dictionary.py +1264 -0
  241. sqlspec/adapters/oracledb/driver.cp315-win_amd64.pyd +0 -0
  242. sqlspec/adapters/oracledb/driver.py +3273 -0
  243. sqlspec/adapters/oracledb/events/__init__.py +29 -0
  244. sqlspec/adapters/oracledb/events/_hub.cp315-win_amd64.pyd +0 -0
  245. sqlspec/adapters/oracledb/events/_hub.py +394 -0
  246. sqlspec/adapters/oracledb/events/backend.py +311 -0
  247. sqlspec/adapters/oracledb/events/store.py +842 -0
  248. sqlspec/adapters/oracledb/litestar/__init__.py +17 -0
  249. sqlspec/adapters/oracledb/litestar/store.py +862 -0
  250. sqlspec/adapters/oracledb/migrations.py +650 -0
  251. sqlspec/adapters/oracledb/tenant.cp315-win_amd64.pyd +0 -0
  252. sqlspec/adapters/oracledb/tenant.py +990 -0
  253. sqlspec/adapters/oracledb/type_converter.cp315-win_amd64.pyd +0 -0
  254. sqlspec/adapters/oracledb/type_converter.py +93 -0
  255. sqlspec/adapters/psqlpy/__init__.py +21 -0
  256. sqlspec/adapters/psqlpy/_typing.py +180 -0
  257. sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
  258. sqlspec/adapters/psqlpy/adk/store.py +1514 -0
  259. sqlspec/adapters/psqlpy/config.py +828 -0
  260. sqlspec/adapters/psqlpy/core.cp315-win_amd64.pyd +0 -0
  261. sqlspec/adapters/psqlpy/core.py +1040 -0
  262. sqlspec/adapters/psqlpy/data_dictionary.py +399 -0
  263. sqlspec/adapters/psqlpy/driver.cp315-win_amd64.pyd +0 -0
  264. sqlspec/adapters/psqlpy/driver.py +631 -0
  265. sqlspec/adapters/psqlpy/events/__init__.py +12 -0
  266. sqlspec/adapters/psqlpy/events/_hub.cp315-win_amd64.pyd +0 -0
  267. sqlspec/adapters/psqlpy/events/_hub.py +367 -0
  268. sqlspec/adapters/psqlpy/events/backend.py +415 -0
  269. sqlspec/adapters/psqlpy/events/store.py +46 -0
  270. sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
  271. sqlspec/adapters/psqlpy/litestar/store.py +270 -0
  272. sqlspec/adapters/psqlpy/tenant.cp315-win_amd64.pyd +0 -0
  273. sqlspec/adapters/psqlpy/tenant.py +137 -0
  274. sqlspec/adapters/psqlpy/type_converter.cp315-win_amd64.pyd +0 -0
  275. sqlspec/adapters/psqlpy/type_converter.py +21 -0
  276. sqlspec/adapters/psycopg/__init__.py +44 -0
  277. sqlspec/adapters/psycopg/_typing.py +408 -0
  278. sqlspec/adapters/psycopg/adk/__init__.py +17 -0
  279. sqlspec/adapters/psycopg/adk/store.py +2761 -0
  280. sqlspec/adapters/psycopg/config.py +1522 -0
  281. sqlspec/adapters/psycopg/core.cp315-win_amd64.pyd +0 -0
  282. sqlspec/adapters/psycopg/core.py +1001 -0
  283. sqlspec/adapters/psycopg/data_dictionary.py +701 -0
  284. sqlspec/adapters/psycopg/driver.cp315-win_amd64.pyd +0 -0
  285. sqlspec/adapters/psycopg/driver.py +1629 -0
  286. sqlspec/adapters/psycopg/events/__init__.py +25 -0
  287. sqlspec/adapters/psycopg/events/_hub.cp315-win_amd64.pyd +0 -0
  288. sqlspec/adapters/psycopg/events/_hub.py +646 -0
  289. sqlspec/adapters/psycopg/events/backend.py +739 -0
  290. sqlspec/adapters/psycopg/events/store.py +82 -0
  291. sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
  292. sqlspec/adapters/psycopg/litestar/store.py +595 -0
  293. sqlspec/adapters/psycopg/tenant.cp315-win_amd64.pyd +0 -0
  294. sqlspec/adapters/psycopg/tenant.py +226 -0
  295. sqlspec/adapters/psycopg/type_converter.cp315-win_amd64.pyd +0 -0
  296. sqlspec/adapters/psycopg/type_converter.py +94 -0
  297. sqlspec/adapters/pymssql/__init__.py +29 -0
  298. sqlspec/adapters/pymssql/_typing.py +156 -0
  299. sqlspec/adapters/pymssql/adk/__init__.py +5 -0
  300. sqlspec/adapters/pymssql/adk/store.py +1270 -0
  301. sqlspec/adapters/pymssql/config.py +299 -0
  302. sqlspec/adapters/pymssql/core.cp315-win_amd64.pyd +0 -0
  303. sqlspec/adapters/pymssql/core.py +527 -0
  304. sqlspec/adapters/pymssql/data_dictionary.py +417 -0
  305. sqlspec/adapters/pymssql/driver.cp315-win_amd64.pyd +0 -0
  306. sqlspec/adapters/pymssql/driver.py +527 -0
  307. sqlspec/adapters/pymssql/events/__init__.py +5 -0
  308. sqlspec/adapters/pymssql/events/store.py +46 -0
  309. sqlspec/adapters/pymssql/litestar/__init__.py +5 -0
  310. sqlspec/adapters/pymssql/litestar/store.py +350 -0
  311. sqlspec/adapters/pymssql/migrations.py +162 -0
  312. sqlspec/adapters/pymssql/pool.cp315-win_amd64.pyd +0 -0
  313. sqlspec/adapters/pymssql/pool.py +417 -0
  314. sqlspec/adapters/pymssql/tenant.cp315-win_amd64.pyd +0 -0
  315. sqlspec/adapters/pymssql/tenant.py +73 -0
  316. sqlspec/adapters/pymysql/__init__.py +27 -0
  317. sqlspec/adapters/pymysql/_typing.py +105 -0
  318. sqlspec/adapters/pymysql/adk/__init__.py +5 -0
  319. sqlspec/adapters/pymysql/adk/store.py +1646 -0
  320. sqlspec/adapters/pymysql/config.py +545 -0
  321. sqlspec/adapters/pymysql/core.cp315-win_amd64.pyd +0 -0
  322. sqlspec/adapters/pymysql/core.py +909 -0
  323. sqlspec/adapters/pymysql/data_dictionary.py +16 -0
  324. sqlspec/adapters/pymysql/driver.cp315-win_amd64.pyd +0 -0
  325. sqlspec/adapters/pymysql/driver.py +370 -0
  326. sqlspec/adapters/pymysql/events/__init__.py +5 -0
  327. sqlspec/adapters/pymysql/events/store.py +42 -0
  328. sqlspec/adapters/pymysql/litestar/__init__.py +5 -0
  329. sqlspec/adapters/pymysql/litestar/store.py +299 -0
  330. sqlspec/adapters/pymysql/pool.cp315-win_amd64.pyd +0 -0
  331. sqlspec/adapters/pymysql/pool.py +480 -0
  332. sqlspec/adapters/snowflake/__init__.py +36 -0
  333. sqlspec/adapters/snowflake/_typing.py +62 -0
  334. sqlspec/adapters/snowflake/adk/__init__.py +5 -0
  335. sqlspec/adapters/snowflake/adk/store.py +778 -0
  336. sqlspec/adapters/snowflake/config.py +333 -0
  337. sqlspec/adapters/snowflake/core.cp315-win_amd64.pyd +0 -0
  338. sqlspec/adapters/snowflake/core.py +683 -0
  339. sqlspec/adapters/snowflake/data_dictionary.py +355 -0
  340. sqlspec/adapters/snowflake/driver.cp315-win_amd64.pyd +0 -0
  341. sqlspec/adapters/snowflake/driver.py +872 -0
  342. sqlspec/adapters/snowflake/events/__init__.py +5 -0
  343. sqlspec/adapters/snowflake/events/store.py +28 -0
  344. sqlspec/adapters/snowflake/litestar/__init__.py +5 -0
  345. sqlspec/adapters/snowflake/litestar/store.py +162 -0
  346. sqlspec/adapters/snowflake/migrations.cp315-win_amd64.pyd +0 -0
  347. sqlspec/adapters/snowflake/migrations.py +76 -0
  348. sqlspec/adapters/snowflake/pool.cp315-win_amd64.pyd +0 -0
  349. sqlspec/adapters/snowflake/pool.py +385 -0
  350. sqlspec/adapters/snowflake/tenant.cp315-win_amd64.pyd +0 -0
  351. sqlspec/adapters/snowflake/tenant.py +200 -0
  352. sqlspec/adapters/snowflake/type_converter.cp315-win_amd64.pyd +0 -0
  353. sqlspec/adapters/snowflake/type_converter.py +33 -0
  354. sqlspec/adapters/spanner/__init__.py +57 -0
  355. sqlspec/adapters/spanner/_typing.py +300 -0
  356. sqlspec/adapters/spanner/adk/__init__.py +22 -0
  357. sqlspec/adapters/spanner/adk/artifact_store.py +693 -0
  358. sqlspec/adapters/spanner/adk/store.py +3053 -0
  359. sqlspec/adapters/spanner/config.py +1578 -0
  360. sqlspec/adapters/spanner/core.cp315-win_amd64.pyd +0 -0
  361. sqlspec/adapters/spanner/core.py +1244 -0
  362. sqlspec/adapters/spanner/data_dictionary.py +706 -0
  363. sqlspec/adapters/spanner/driver.cp315-win_amd64.pyd +0 -0
  364. sqlspec/adapters/spanner/driver.py +1673 -0
  365. sqlspec/adapters/spanner/events/__init__.py +5 -0
  366. sqlspec/adapters/spanner/events/store.py +357 -0
  367. sqlspec/adapters/spanner/litestar/__init__.py +5 -0
  368. sqlspec/adapters/spanner/litestar/store.py +570 -0
  369. sqlspec/adapters/spanner/type_converter.cp315-win_amd64.pyd +0 -0
  370. sqlspec/adapters/spanner/type_converter.py +466 -0
  371. sqlspec/adapters/sqlanywhere/__init__.py +40 -0
  372. sqlspec/adapters/sqlanywhere/_typing.py +139 -0
  373. sqlspec/adapters/sqlanywhere/adk/__init__.py +5 -0
  374. sqlspec/adapters/sqlanywhere/adk/store.py +1136 -0
  375. sqlspec/adapters/sqlanywhere/config.py +359 -0
  376. sqlspec/adapters/sqlanywhere/core.cp315-win_amd64.pyd +0 -0
  377. sqlspec/adapters/sqlanywhere/core.py +583 -0
  378. sqlspec/adapters/sqlanywhere/data_dictionary.py +282 -0
  379. sqlspec/adapters/sqlanywhere/driver.cp315-win_amd64.pyd +0 -0
  380. sqlspec/adapters/sqlanywhere/driver.py +480 -0
  381. sqlspec/adapters/sqlanywhere/events/__init__.py +5 -0
  382. sqlspec/adapters/sqlanywhere/events/store.py +28 -0
  383. sqlspec/adapters/sqlanywhere/litestar/__init__.py +5 -0
  384. sqlspec/adapters/sqlanywhere/litestar/store.py +237 -0
  385. sqlspec/adapters/sqlanywhere/migrations.py +178 -0
  386. sqlspec/adapters/sqlanywhere/pool.cp315-win_amd64.pyd +0 -0
  387. sqlspec/adapters/sqlanywhere/pool.py +397 -0
  388. sqlspec/adapters/sqlite/__init__.py +32 -0
  389. sqlspec/adapters/sqlite/_typing.py +91 -0
  390. sqlspec/adapters/sqlite/adk/__init__.py +5 -0
  391. sqlspec/adapters/sqlite/adk/store.py +1628 -0
  392. sqlspec/adapters/sqlite/config.py +520 -0
  393. sqlspec/adapters/sqlite/core.cp315-win_amd64.pyd +0 -0
  394. sqlspec/adapters/sqlite/core.py +1035 -0
  395. sqlspec/adapters/sqlite/data_dictionary.py +327 -0
  396. sqlspec/adapters/sqlite/driver.cp315-win_amd64.pyd +0 -0
  397. sqlspec/adapters/sqlite/driver.py +432 -0
  398. sqlspec/adapters/sqlite/events/__init__.py +5 -0
  399. sqlspec/adapters/sqlite/events/store.py +54 -0
  400. sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
  401. sqlspec/adapters/sqlite/litestar/store.py +367 -0
  402. sqlspec/adapters/sqlite/pool.cp315-win_amd64.pyd +0 -0
  403. sqlspec/adapters/sqlite/pool.py +935 -0
  404. sqlspec/adapters/sqlite/type_converter.cp315-win_amd64.pyd +0 -0
  405. sqlspec/adapters/sqlite/type_converter.py +114 -0
  406. sqlspec/adapters/sybase/__init__.py +37 -0
  407. sqlspec/adapters/sybase/_typing.py +150 -0
  408. sqlspec/adapters/sybase/adk/__init__.py +5 -0
  409. sqlspec/adapters/sybase/adk/store.py +1370 -0
  410. sqlspec/adapters/sybase/config.py +276 -0
  411. sqlspec/adapters/sybase/core.cp315-win_amd64.pyd +0 -0
  412. sqlspec/adapters/sybase/core.py +578 -0
  413. sqlspec/adapters/sybase/data_dictionary.py +358 -0
  414. sqlspec/adapters/sybase/driver.cp315-win_amd64.pyd +0 -0
  415. sqlspec/adapters/sybase/driver.py +497 -0
  416. sqlspec/adapters/sybase/events/__init__.py +5 -0
  417. sqlspec/adapters/sybase/events/store.py +88 -0
  418. sqlspec/adapters/sybase/litestar/__init__.py +5 -0
  419. sqlspec/adapters/sybase/litestar/store.py +328 -0
  420. sqlspec/adapters/sybase/migrations.py +178 -0
  421. sqlspec/adapters/sybase/pool.cp315-win_amd64.pyd +0 -0
  422. sqlspec/adapters/sybase/pool.py +435 -0
  423. sqlspec/adapters/teradata/__init__.py +59 -0
  424. sqlspec/adapters/teradata/_typing.py +145 -0
  425. sqlspec/adapters/teradata/adk/__init__.py +5 -0
  426. sqlspec/adapters/teradata/adk/store.py +1300 -0
  427. sqlspec/adapters/teradata/config.py +324 -0
  428. sqlspec/adapters/teradata/core.cp315-win_amd64.pyd +0 -0
  429. sqlspec/adapters/teradata/core.py +437 -0
  430. sqlspec/adapters/teradata/data_dictionary.py +316 -0
  431. sqlspec/adapters/teradata/driver.cp315-win_amd64.pyd +0 -0
  432. sqlspec/adapters/teradata/driver.py +721 -0
  433. sqlspec/adapters/teradata/events/__init__.py +5 -0
  434. sqlspec/adapters/teradata/events/store.py +64 -0
  435. sqlspec/adapters/teradata/litestar/__init__.py +5 -0
  436. sqlspec/adapters/teradata/litestar/store.py +264 -0
  437. sqlspec/adapters/teradata/migrations.cp315-win_amd64.pyd +0 -0
  438. sqlspec/adapters/teradata/migrations.py +80 -0
  439. sqlspec/adapters/teradata/pool.cp315-win_amd64.pyd +0 -0
  440. sqlspec/adapters/teradata/pool.py +377 -0
  441. sqlspec/adapters/teradata/type_converter.cp315-win_amd64.pyd +0 -0
  442. sqlspec/adapters/teradata/type_converter.py +95 -0
  443. sqlspec/base.cp315-win_amd64.pyd +0 -0
  444. sqlspec/base.py +1275 -0
  445. sqlspec/builder/__init__.py +330 -0
  446. sqlspec/builder/_base.cp315-win_amd64.pyd +0 -0
  447. sqlspec/builder/_base.py +1752 -0
  448. sqlspec/builder/_column.cp315-win_amd64.pyd +0 -0
  449. sqlspec/builder/_column.py +508 -0
  450. sqlspec/builder/_ddl.cp315-win_amd64.pyd +0 -0
  451. sqlspec/builder/_ddl.py +4503 -0
  452. sqlspec/builder/_delete.cp315-win_amd64.pyd +0 -0
  453. sqlspec/builder/_delete.py +75 -0
  454. sqlspec/builder/_dml.cp315-win_amd64.pyd +0 -0
  455. sqlspec/builder/_dml.py +639 -0
  456. sqlspec/builder/_explain.cp315-win_amd64.pyd +0 -0
  457. sqlspec/builder/_explain.py +650 -0
  458. sqlspec/builder/_expression_wrappers.cp315-win_amd64.pyd +0 -0
  459. sqlspec/builder/_expression_wrappers.py +77 -0
  460. sqlspec/builder/_factory.cp315-win_amd64.pyd +0 -0
  461. sqlspec/builder/_factory.py +1834 -0
  462. sqlspec/builder/_generation.cp315-win_amd64.pyd +0 -0
  463. sqlspec/builder/_generation.py +55 -0
  464. sqlspec/builder/_insert.cp315-win_amd64.pyd +0 -0
  465. sqlspec/builder/_insert.py +308 -0
  466. sqlspec/builder/_join.cp315-win_amd64.pyd +0 -0
  467. sqlspec/builder/_join.py +501 -0
  468. sqlspec/builder/_locking.cp315-win_amd64.pyd +0 -0
  469. sqlspec/builder/_locking.py +77 -0
  470. sqlspec/builder/_merge.cp315-win_amd64.pyd +0 -0
  471. sqlspec/builder/_merge.py +1047 -0
  472. sqlspec/builder/_parsing_utils.cp315-win_amd64.pyd +0 -0
  473. sqlspec/builder/_parsing_utils.py +1197 -0
  474. sqlspec/builder/_select.cp315-win_amd64.pyd +0 -0
  475. sqlspec/builder/_select.py +1514 -0
  476. sqlspec/builder/_temporal.cp315-win_amd64.pyd +0 -0
  477. sqlspec/builder/_temporal.py +183 -0
  478. sqlspec/builder/_update.cp315-win_amd64.pyd +0 -0
  479. sqlspec/builder/_update.py +139 -0
  480. sqlspec/builder/_values.cp315-win_amd64.pyd +0 -0
  481. sqlspec/builder/_values.py +271 -0
  482. sqlspec/builder/_vector_distance.cp315-win_amd64.pyd +0 -0
  483. sqlspec/builder/_vector_distance.py +763 -0
  484. sqlspec/cli.py +1656 -0
  485. sqlspec/config.py +3402 -0
  486. sqlspec/core/__init__.py +542 -0
  487. sqlspec/core/_cursor.cp315-win_amd64.pyd +0 -0
  488. sqlspec/core/_cursor.py +564 -0
  489. sqlspec/core/_operators.cp315-win_amd64.pyd +0 -0
  490. sqlspec/core/_operators.py +167 -0
  491. sqlspec/core/_ordering.cp315-win_amd64.pyd +0 -0
  492. sqlspec/core/_ordering.py +151 -0
  493. sqlspec/core/_pagination.py +66 -0
  494. sqlspec/core/_pipeline.cp315-win_amd64.pyd +0 -0
  495. sqlspec/core/_pipeline.py +343 -0
  496. sqlspec/core/_pool.cp315-win_amd64.pyd +0 -0
  497. sqlspec/core/_pool.py +72 -0
  498. sqlspec/core/cache.cp315-win_amd64.pyd +0 -0
  499. sqlspec/core/cache.py +1503 -0
  500. sqlspec/core/capabilities.cp315-win_amd64.pyd +0 -0
  501. sqlspec/core/capabilities.py +67 -0
  502. sqlspec/core/compiler.cp315-win_amd64.pyd +0 -0
  503. sqlspec/core/compiler.py +1667 -0
  504. sqlspec/core/config_runtime.cp315-win_amd64.pyd +0 -0
  505. sqlspec/core/config_runtime.py +219 -0
  506. sqlspec/core/correlation.cp315-win_amd64.pyd +0 -0
  507. sqlspec/core/correlation.py +135 -0
  508. sqlspec/core/explain.cp315-win_amd64.pyd +0 -0
  509. sqlspec/core/explain.py +284 -0
  510. sqlspec/core/filters.cp315-win_amd64.pyd +0 -0
  511. sqlspec/core/filters.py +1442 -0
  512. sqlspec/core/hashing.cp315-win_amd64.pyd +0 -0
  513. sqlspec/core/hashing.py +394 -0
  514. sqlspec/core/metrics.cp315-win_amd64.pyd +0 -0
  515. sqlspec/core/metrics.py +86 -0
  516. sqlspec/core/parameters/__init__.py +174 -0
  517. sqlspec/core/parameters/_alignment.cp315-win_amd64.pyd +0 -0
  518. sqlspec/core/parameters/_alignment.py +321 -0
  519. sqlspec/core/parameters/_converter.cp315-win_amd64.pyd +0 -0
  520. sqlspec/core/parameters/_converter.py +956 -0
  521. sqlspec/core/parameters/_declared.cp315-win_amd64.pyd +0 -0
  522. sqlspec/core/parameters/_declared.py +154 -0
  523. sqlspec/core/parameters/_processor.cp315-win_amd64.pyd +0 -0
  524. sqlspec/core/parameters/_processor.py +1646 -0
  525. sqlspec/core/parameters/_registry.cp315-win_amd64.pyd +0 -0
  526. sqlspec/core/parameters/_registry.py +207 -0
  527. sqlspec/core/parameters/_transformers.cp315-win_amd64.pyd +0 -0
  528. sqlspec/core/parameters/_transformers.py +318 -0
  529. sqlspec/core/parameters/_types.cp315-win_amd64.pyd +0 -0
  530. sqlspec/core/parameters/_types.py +658 -0
  531. sqlspec/core/parameters/_validator.cp315-win_amd64.pyd +0 -0
  532. sqlspec/core/parameters/_validator.py +699 -0
  533. sqlspec/core/query_modifiers.cp315-win_amd64.pyd +0 -0
  534. sqlspec/core/query_modifiers.py +559 -0
  535. sqlspec/core/result/__init__.py +67 -0
  536. sqlspec/core/result/_base.cp315-win_amd64.pyd +0 -0
  537. sqlspec/core/result/_base.py +1772 -0
  538. sqlspec/core/routing.cp315-win_amd64.pyd +0 -0
  539. sqlspec/core/routing.py +270 -0
  540. sqlspec/core/splitter.cp315-win_amd64.pyd +0 -0
  541. sqlspec/core/splitter.py +1126 -0
  542. sqlspec/core/sqlcommenter.cp315-win_amd64.pyd +0 -0
  543. sqlspec/core/sqlcommenter.py +509 -0
  544. sqlspec/core/stack.cp315-win_amd64.pyd +0 -0
  545. sqlspec/core/stack.py +167 -0
  546. sqlspec/core/statement.cp315-win_amd64.pyd +0 -0
  547. sqlspec/core/statement.py +2253 -0
  548. sqlspec/core/tenant/__init__.py +64 -0
  549. sqlspec/core/tenant/base.cp315-win_amd64.pyd +0 -0
  550. sqlspec/core/tenant/base.py +123 -0
  551. sqlspec/core/type_converter.cp315-win_amd64.pyd +0 -0
  552. sqlspec/core/type_converter.py +147 -0
  553. sqlspec/data_dictionary/__init__.py +237 -0
  554. sqlspec/data_dictionary/_capabilities.cp315-win_amd64.pyd +0 -0
  555. sqlspec/data_dictionary/_capabilities.py +142 -0
  556. sqlspec/data_dictionary/_dependencies.cp315-win_amd64.pyd +0 -0
  557. sqlspec/data_dictionary/_dependencies.py +602 -0
  558. sqlspec/data_dictionary/_index_ddl.cp315-win_amd64.pyd +0 -0
  559. sqlspec/data_dictionary/_index_ddl.py +562 -0
  560. sqlspec/data_dictionary/_loader.cp315-win_amd64.pyd +0 -0
  561. sqlspec/data_dictionary/_loader.py +344 -0
  562. sqlspec/data_dictionary/_registry.cp315-win_amd64.pyd +0 -0
  563. sqlspec/data_dictionary/_registry.py +152 -0
  564. sqlspec/data_dictionary/_types.cp315-win_amd64.pyd +0 -0
  565. sqlspec/data_dictionary/_types.py +1852 -0
  566. sqlspec/data_dictionary/dialects/__init__.py +34 -0
  567. sqlspec/data_dictionary/dialects/bigquery/__init__.py +15 -0
  568. sqlspec/data_dictionary/dialects/bigquery/config.cp315-win_amd64.pyd +0 -0
  569. sqlspec/data_dictionary/dialects/bigquery/config.py +128 -0
  570. sqlspec/data_dictionary/dialects/bigquery/sql/columns.sql +63 -0
  571. sqlspec/data_dictionary/dialects/bigquery/sql/constraints.sql +37 -0
  572. sqlspec/data_dictionary/dialects/bigquery/sql/datasets.sql +14 -0
  573. sqlspec/data_dictionary/dialects/bigquery/sql/ddl.sql +51 -0
  574. sqlspec/data_dictionary/dialects/bigquery/sql/dependencies.sql +22 -0
  575. sqlspec/data_dictionary/dialects/bigquery/sql/foreign_keys.sql +34 -0
  576. sqlspec/data_dictionary/dialects/bigquery/sql/indexes.sql +59 -0
  577. sqlspec/data_dictionary/dialects/bigquery/sql/objects.sql +13 -0
  578. sqlspec/data_dictionary/dialects/bigquery/sql/privileges.sql +13 -0
  579. sqlspec/data_dictionary/dialects/bigquery/sql/routines.sql +50 -0
  580. sqlspec/data_dictionary/dialects/bigquery/sql/system.sql +59 -0
  581. sqlspec/data_dictionary/dialects/bigquery/sql/tables.sql +111 -0
  582. sqlspec/data_dictionary/dialects/bigquery/sql/version.sql +3 -0
  583. sqlspec/data_dictionary/dialects/bigquery/sql/views.sql +31 -0
  584. sqlspec/data_dictionary/dialects/cockroachdb/__init__.py +17 -0
  585. sqlspec/data_dictionary/dialects/cockroachdb/config.cp315-win_amd64.pyd +0 -0
  586. sqlspec/data_dictionary/dialects/cockroachdb/config.py +95 -0
  587. sqlspec/data_dictionary/dialects/cockroachdb/sql/columns.sql +163 -0
  588. sqlspec/data_dictionary/dialects/cockroachdb/sql/comments.sql +10 -0
  589. sqlspec/data_dictionary/dialects/cockroachdb/sql/constraints.sql +67 -0
  590. sqlspec/data_dictionary/dialects/cockroachdb/sql/crdb_internal.sql +11 -0
  591. sqlspec/data_dictionary/dialects/cockroachdb/sql/ddl.sql +10 -0
  592. sqlspec/data_dictionary/dialects/cockroachdb/sql/dependencies.sql +20 -0
  593. sqlspec/data_dictionary/dialects/cockroachdb/sql/foreign_keys.sql +62 -0
  594. sqlspec/data_dictionary/dialects/cockroachdb/sql/indexes.sql +32 -0
  595. sqlspec/data_dictionary/dialects/cockroachdb/sql/objects.sql +15 -0
  596. sqlspec/data_dictionary/dialects/cockroachdb/sql/privileges.sql +13 -0
  597. sqlspec/data_dictionary/dialects/cockroachdb/sql/schemas.sql +10 -0
  598. sqlspec/data_dictionary/dialects/cockroachdb/sql/sequences.sql +14 -0
  599. sqlspec/data_dictionary/dialects/cockroachdb/sql/tables.sql +15 -0
  600. sqlspec/data_dictionary/dialects/cockroachdb/sql/version.sql +3 -0
  601. sqlspec/data_dictionary/dialects/cockroachdb/sql/views.sql +11 -0
  602. sqlspec/data_dictionary/dialects/db2/__init__.py +31 -0
  603. sqlspec/data_dictionary/dialects/db2/config.cp315-win_amd64.pyd +0 -0
  604. sqlspec/data_dictionary/dialects/db2/config.py +172 -0
  605. sqlspec/data_dictionary/dialects/db2/sql/columns.sql +98 -0
  606. sqlspec/data_dictionary/dialects/db2/sql/constraints.sql +49 -0
  607. sqlspec/data_dictionary/dialects/db2/sql/foreign_keys.sql +43 -0
  608. sqlspec/data_dictionary/dialects/db2/sql/indexes.sql +39 -0
  609. sqlspec/data_dictionary/dialects/db2/sql/objects.sql +53 -0
  610. sqlspec/data_dictionary/dialects/db2/sql/schemas.sql +13 -0
  611. sqlspec/data_dictionary/dialects/db2/sql/tables.sql +77 -0
  612. sqlspec/data_dictionary/dialects/db2/sql/version.sql +8 -0
  613. sqlspec/data_dictionary/dialects/db2/sql/views.sql +15 -0
  614. sqlspec/data_dictionary/dialects/duckdb/__init__.py +5 -0
  615. sqlspec/data_dictionary/dialects/duckdb/config.cp315-win_amd64.pyd +0 -0
  616. sqlspec/data_dictionary/dialects/duckdb/config.py +66 -0
  617. sqlspec/data_dictionary/dialects/duckdb/sql/columns.sql +150 -0
  618. sqlspec/data_dictionary/dialects/duckdb/sql/constraints.sql +34 -0
  619. sqlspec/data_dictionary/dialects/duckdb/sql/databases.sql +11 -0
  620. sqlspec/data_dictionary/dialects/duckdb/sql/ddl.sql +221 -0
  621. sqlspec/data_dictionary/dialects/duckdb/sql/dependencies.sql +50 -0
  622. sqlspec/data_dictionary/dialects/duckdb/sql/extensions.sql +14 -0
  623. sqlspec/data_dictionary/dialects/duckdb/sql/foreign_keys.sql +46 -0
  624. sqlspec/data_dictionary/dialects/duckdb/sql/functions.sql +18 -0
  625. sqlspec/data_dictionary/dialects/duckdb/sql/indexes.sql +34 -0
  626. sqlspec/data_dictionary/dialects/duckdb/sql/objects.sql +30 -0
  627. sqlspec/data_dictionary/dialects/duckdb/sql/schemas.sql +10 -0
  628. sqlspec/data_dictionary/dialects/duckdb/sql/sequences.sql +19 -0
  629. sqlspec/data_dictionary/dialects/duckdb/sql/system.sql +21 -0
  630. sqlspec/data_dictionary/dialects/duckdb/sql/tables.sql +59 -0
  631. sqlspec/data_dictionary/dialects/duckdb/sql/types.sql +12 -0
  632. sqlspec/data_dictionary/dialects/duckdb/sql/version.sql +3 -0
  633. sqlspec/data_dictionary/dialects/duckdb/sql/views.sql +15 -0
  634. sqlspec/data_dictionary/dialects/mariadb/__init__.py +5 -0
  635. sqlspec/data_dictionary/dialects/mariadb/sql/columns.sql +45 -0
  636. sqlspec/data_dictionary/dialects/mariadb/sql/constraints.sql +30 -0
  637. sqlspec/data_dictionary/dialects/mariadb/sql/ddl.sql +27 -0
  638. sqlspec/data_dictionary/dialects/mariadb/sql/events.sql +29 -0
  639. sqlspec/data_dictionary/dialects/mariadb/sql/foreign_keys.sql +42 -0
  640. sqlspec/data_dictionary/dialects/mariadb/sql/indexes.sql +33 -0
  641. sqlspec/data_dictionary/dialects/mariadb/sql/objects.sql +50 -0
  642. sqlspec/data_dictionary/dialects/mariadb/sql/partitions.sql +27 -0
  643. sqlspec/data_dictionary/dialects/mariadb/sql/plugins.sql +16 -0
  644. sqlspec/data_dictionary/dialects/mariadb/sql/privileges.sql +24 -0
  645. sqlspec/data_dictionary/dialects/mariadb/sql/routines.sql +21 -0
  646. sqlspec/data_dictionary/dialects/mariadb/sql/schemas.sql +10 -0
  647. sqlspec/data_dictionary/dialects/mariadb/sql/system.sql +12 -0
  648. sqlspec/data_dictionary/dialects/mariadb/sql/tables.sql +64 -0
  649. sqlspec/data_dictionary/dialects/mariadb/sql/triggers.sql +21 -0
  650. sqlspec/data_dictionary/dialects/mariadb/sql/version.sql +7 -0
  651. sqlspec/data_dictionary/dialects/mariadb/sql/views.sql +15 -0
  652. sqlspec/data_dictionary/dialects/mssql/__init__.py +51 -0
  653. sqlspec/data_dictionary/dialects/mssql/config.cp315-win_amd64.pyd +0 -0
  654. sqlspec/data_dictionary/dialects/mssql/config.py +558 -0
  655. sqlspec/data_dictionary/dialects/mssql/sql/columns.sql +120 -0
  656. sqlspec/data_dictionary/dialects/mssql/sql/constraints.sql +106 -0
  657. sqlspec/data_dictionary/dialects/mssql/sql/ddl.sql +89 -0
  658. sqlspec/data_dictionary/dialects/mssql/sql/dependencies.sql +17 -0
  659. sqlspec/data_dictionary/dialects/mssql/sql/extended_properties.sql +16 -0
  660. sqlspec/data_dictionary/dialects/mssql/sql/foreign_keys.sql +40 -0
  661. sqlspec/data_dictionary/dialects/mssql/sql/indexes.sql +86 -0
  662. sqlspec/data_dictionary/dialects/mssql/sql/modules.sql +19 -0
  663. sqlspec/data_dictionary/dialects/mssql/sql/objects.sql +16 -0
  664. sqlspec/data_dictionary/dialects/mssql/sql/permissions.sql +31 -0
  665. sqlspec/data_dictionary/dialects/mssql/sql/routines.sql +39 -0
  666. sqlspec/data_dictionary/dialects/mssql/sql/schemas.sql +13 -0
  667. sqlspec/data_dictionary/dialects/mssql/sql/sequences.sql +18 -0
  668. sqlspec/data_dictionary/dialects/mssql/sql/storage.sql +22 -0
  669. sqlspec/data_dictionary/dialects/mssql/sql/system.sql +38 -0
  670. sqlspec/data_dictionary/dialects/mssql/sql/tables.sql +97 -0
  671. sqlspec/data_dictionary/dialects/mssql/sql/triggers.sql +21 -0
  672. sqlspec/data_dictionary/dialects/mssql/sql/version.sql +7 -0
  673. sqlspec/data_dictionary/dialects/mssql/sql/views.sql +18 -0
  674. sqlspec/data_dictionary/dialects/mysql/__init__.py +34 -0
  675. sqlspec/data_dictionary/dialects/mysql/config.cp315-win_amd64.pyd +0 -0
  676. sqlspec/data_dictionary/dialects/mysql/config.py +363 -0
  677. sqlspec/data_dictionary/dialects/mysql/dictionary.py +650 -0
  678. sqlspec/data_dictionary/dialects/mysql/sql/columns.sql +45 -0
  679. sqlspec/data_dictionary/dialects/mysql/sql/components.sql +8 -0
  680. sqlspec/data_dictionary/dialects/mysql/sql/constraints.sql +30 -0
  681. sqlspec/data_dictionary/dialects/mysql/sql/ddl.sql +23 -0
  682. sqlspec/data_dictionary/dialects/mysql/sql/events.sql +29 -0
  683. sqlspec/data_dictionary/dialects/mysql/sql/foreign_keys.sql +42 -0
  684. sqlspec/data_dictionary/dialects/mysql/sql/indexes.sql +33 -0
  685. sqlspec/data_dictionary/dialects/mysql/sql/objects.sql +38 -0
  686. sqlspec/data_dictionary/dialects/mysql/sql/partitions.sql +27 -0
  687. sqlspec/data_dictionary/dialects/mysql/sql/plugins.sql +16 -0
  688. sqlspec/data_dictionary/dialects/mysql/sql/privileges.sql +26 -0
  689. sqlspec/data_dictionary/dialects/mysql/sql/routines.sql +21 -0
  690. sqlspec/data_dictionary/dialects/mysql/sql/schemas.sql +10 -0
  691. sqlspec/data_dictionary/dialects/mysql/sql/system.sql +25 -0
  692. sqlspec/data_dictionary/dialects/mysql/sql/tables.sql +64 -0
  693. sqlspec/data_dictionary/dialects/mysql/sql/triggers.sql +21 -0
  694. sqlspec/data_dictionary/dialects/mysql/sql/version.sql +3 -0
  695. sqlspec/data_dictionary/dialects/mysql/sql/views.sql +15 -0
  696. sqlspec/data_dictionary/dialects/oracle/__init__.py +39 -0
  697. sqlspec/data_dictionary/dialects/oracle/config.cp315-win_amd64.pyd +0 -0
  698. sqlspec/data_dictionary/dialects/oracle/config.py +266 -0
  699. sqlspec/data_dictionary/dialects/oracle/sql/arguments.sql +29 -0
  700. sqlspec/data_dictionary/dialects/oracle/sql/columns.sql +103 -0
  701. sqlspec/data_dictionary/dialects/oracle/sql/comments.sql +22 -0
  702. sqlspec/data_dictionary/dialects/oracle/sql/constraints.sql +49 -0
  703. sqlspec/data_dictionary/dialects/oracle/sql/ddl.sql +4 -0
  704. sqlspec/data_dictionary/dialects/oracle/sql/dependencies.sql +16 -0
  705. sqlspec/data_dictionary/dialects/oracle/sql/foreign_keys.sql +48 -0
  706. sqlspec/data_dictionary/dialects/oracle/sql/grants.sql +34 -0
  707. sqlspec/data_dictionary/dialects/oracle/sql/indexes.sql +87 -0
  708. sqlspec/data_dictionary/dialects/oracle/sql/lob_storage.sql +28 -0
  709. sqlspec/data_dictionary/dialects/oracle/sql/materialized_views.sql +27 -0
  710. sqlspec/data_dictionary/dialects/oracle/sql/objects.sql +26 -0
  711. sqlspec/data_dictionary/dialects/oracle/sql/partitions.sql +44 -0
  712. sqlspec/data_dictionary/dialects/oracle/sql/routines.sql +21 -0
  713. sqlspec/data_dictionary/dialects/oracle/sql/schemas.sql +13 -0
  714. sqlspec/data_dictionary/dialects/oracle/sql/sequences.sql +21 -0
  715. sqlspec/data_dictionary/dialects/oracle/sql/source.sql +13 -0
  716. sqlspec/data_dictionary/dialects/oracle/sql/system.sql +37 -0
  717. sqlspec/data_dictionary/dialects/oracle/sql/tables.sql +48 -0
  718. sqlspec/data_dictionary/dialects/oracle/sql/triggers.sql +29 -0
  719. sqlspec/data_dictionary/dialects/oracle/sql/version.sql +25 -0
  720. sqlspec/data_dictionary/dialects/oracle/sql/views.sql +49 -0
  721. sqlspec/data_dictionary/dialects/postgres/__init__.py +19 -0
  722. sqlspec/data_dictionary/dialects/postgres/config.cp315-win_amd64.pyd +0 -0
  723. sqlspec/data_dictionary/dialects/postgres/config.py +119 -0
  724. sqlspec/data_dictionary/dialects/postgres/sql/columns.sql +130 -0
  725. sqlspec/data_dictionary/dialects/postgres/sql/comments.sql +27 -0
  726. sqlspec/data_dictionary/dialects/postgres/sql/constraints.sql +53 -0
  727. sqlspec/data_dictionary/dialects/postgres/sql/ddl.sql +55 -0
  728. sqlspec/data_dictionary/dialects/postgres/sql/dependencies.sql +42 -0
  729. sqlspec/data_dictionary/dialects/postgres/sql/extensions.sql +11 -0
  730. sqlspec/data_dictionary/dialects/postgres/sql/foreign_keys.sql +72 -0
  731. sqlspec/data_dictionary/dialects/postgres/sql/indexes.sql +84 -0
  732. sqlspec/data_dictionary/dialects/postgres/sql/materialized_views.sql +17 -0
  733. sqlspec/data_dictionary/dialects/postgres/sql/objects.sql +25 -0
  734. sqlspec/data_dictionary/dialects/postgres/sql/partitions.sql +19 -0
  735. sqlspec/data_dictionary/dialects/postgres/sql/privileges.sql +29 -0
  736. sqlspec/data_dictionary/dialects/postgres/sql/routines.sql +25 -0
  737. sqlspec/data_dictionary/dialects/postgres/sql/schemas.sql +13 -0
  738. sqlspec/data_dictionary/dialects/postgres/sql/sequences.sql +32 -0
  739. sqlspec/data_dictionary/dialects/postgres/sql/system.sql +53 -0
  740. sqlspec/data_dictionary/dialects/postgres/sql/tables.sql +67 -0
  741. sqlspec/data_dictionary/dialects/postgres/sql/triggers.sql +20 -0
  742. sqlspec/data_dictionary/dialects/postgres/sql/types.sql +21 -0
  743. sqlspec/data_dictionary/dialects/postgres/sql/version.sql +3 -0
  744. sqlspec/data_dictionary/dialects/postgres/sql/views.sql +17 -0
  745. sqlspec/data_dictionary/dialects/snowflake/__init__.py +31 -0
  746. sqlspec/data_dictionary/dialects/snowflake/config.cp315-win_amd64.pyd +0 -0
  747. sqlspec/data_dictionary/dialects/snowflake/config.py +321 -0
  748. sqlspec/data_dictionary/dialects/snowflake/sql/columns.sql +48 -0
  749. sqlspec/data_dictionary/dialects/snowflake/sql/constraints.sql +64 -0
  750. sqlspec/data_dictionary/dialects/snowflake/sql/ddl.sql +3 -0
  751. sqlspec/data_dictionary/dialects/snowflake/sql/foreign_keys.sql +7 -0
  752. sqlspec/data_dictionary/dialects/snowflake/sql/objects.sql +34 -0
  753. sqlspec/data_dictionary/dialects/snowflake/sql/routines.sql +79 -0
  754. sqlspec/data_dictionary/dialects/snowflake/sql/schemas.sql +19 -0
  755. sqlspec/data_dictionary/dialects/snowflake/sql/sequences.sql +45 -0
  756. sqlspec/data_dictionary/dialects/snowflake/sql/tables.sql +29 -0
  757. sqlspec/data_dictionary/dialects/snowflake/sql/version.sql +3 -0
  758. sqlspec/data_dictionary/dialects/snowflake/sql/views.sql +37 -0
  759. sqlspec/data_dictionary/dialects/spanner/__init__.py +5 -0
  760. sqlspec/data_dictionary/dialects/spanner/config.cp315-win_amd64.pyd +0 -0
  761. sqlspec/data_dictionary/dialects/spanner/config.py +67 -0
  762. sqlspec/data_dictionary/dialects/spanner/sql/columns.sql +58 -0
  763. sqlspec/data_dictionary/dialects/spanner/sql/foreign_keys.sql +91 -0
  764. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/change_streams.sql +28 -0
  765. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/columns.sql +46 -0
  766. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/constraints.sql +63 -0
  767. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/database.sql +9 -0
  768. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/foreign_keys.sql +91 -0
  769. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/indexes.sql +66 -0
  770. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/objects.sql +10 -0
  771. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/placements.sql +8 -0
  772. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/privileges.sql +13 -0
  773. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/property_graphs.sql +11 -0
  774. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/routines.sql +33 -0
  775. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/sequences.sql +14 -0
  776. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/system.sql +28 -0
  777. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/tables.sql +30 -0
  778. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/views.sql +13 -0
  779. sqlspec/data_dictionary/dialects/spanner/sql/indexes.sql +30 -0
  780. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/change_streams.sql +28 -0
  781. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/columns.sql +34 -0
  782. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/constraints.sql +63 -0
  783. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/foreign_keys.sql +91 -0
  784. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/indexes.sql +52 -0
  785. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/objects.sql +10 -0
  786. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/sequences.sql +14 -0
  787. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/system.sql +28 -0
  788. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/tables.sql +22 -0
  789. sqlspec/data_dictionary/dialects/spanner/sql/tables.sql +9 -0
  790. sqlspec/data_dictionary/dialects/spanner/sql/version.sql +3 -0
  791. sqlspec/data_dictionary/dialects/sqlanywhere/__init__.py +31 -0
  792. sqlspec/data_dictionary/dialects/sqlanywhere/config.cp315-win_amd64.pyd +0 -0
  793. sqlspec/data_dictionary/dialects/sqlanywhere/config.py +191 -0
  794. sqlspec/data_dictionary/dialects/sqlanywhere/sql/columns.sql +97 -0
  795. sqlspec/data_dictionary/dialects/sqlanywhere/sql/constraints.sql +43 -0
  796. sqlspec/data_dictionary/dialects/sqlanywhere/sql/foreign_keys.sql +45 -0
  797. sqlspec/data_dictionary/dialects/sqlanywhere/sql/indexes.sql +39 -0
  798. sqlspec/data_dictionary/dialects/sqlanywhere/sql/objects.sql +18 -0
  799. sqlspec/data_dictionary/dialects/sqlanywhere/sql/schemas.sql +15 -0
  800. sqlspec/data_dictionary/dialects/sqlanywhere/sql/tables.sql +86 -0
  801. sqlspec/data_dictionary/dialects/sqlanywhere/sql/version.sql +3 -0
  802. sqlspec/data_dictionary/dialects/sqlanywhere/sql/views.sql +15 -0
  803. sqlspec/data_dictionary/dialects/sqlite/__init__.py +19 -0
  804. sqlspec/data_dictionary/dialects/sqlite/config.cp315-win_amd64.pyd +0 -0
  805. sqlspec/data_dictionary/dialects/sqlite/config.py +412 -0
  806. sqlspec/data_dictionary/dialects/sqlite/sql/columns.sql +59 -0
  807. sqlspec/data_dictionary/dialects/sqlite/sql/compile_options.sql +3 -0
  808. sqlspec/data_dictionary/dialects/sqlite/sql/constraints.sql +67 -0
  809. sqlspec/data_dictionary/dialects/sqlite/sql/ddl.sql +37 -0
  810. sqlspec/data_dictionary/dialects/sqlite/sql/foreign_keys.sql +45 -0
  811. sqlspec/data_dictionary/dialects/sqlite/sql/functions.sql +3 -0
  812. sqlspec/data_dictionary/dialects/sqlite/sql/indexes.sql +76 -0
  813. sqlspec/data_dictionary/dialects/sqlite/sql/modules.sql +3 -0
  814. sqlspec/data_dictionary/dialects/sqlite/sql/objects.sql +13 -0
  815. sqlspec/data_dictionary/dialects/sqlite/sql/schemas.sql +3 -0
  816. sqlspec/data_dictionary/dialects/sqlite/sql/system.sql +7 -0
  817. sqlspec/data_dictionary/dialects/sqlite/sql/tables.sql +64 -0
  818. sqlspec/data_dictionary/dialects/sqlite/sql/triggers.sql +10 -0
  819. sqlspec/data_dictionary/dialects/sqlite/sql/version.sql +3 -0
  820. sqlspec/data_dictionary/dialects/sqlite/sql/views.sql +10 -0
  821. sqlspec/data_dictionary/dialects/sybase/__init__.py +31 -0
  822. sqlspec/data_dictionary/dialects/sybase/config.cp315-win_amd64.pyd +0 -0
  823. sqlspec/data_dictionary/dialects/sybase/config.py +187 -0
  824. sqlspec/data_dictionary/dialects/sybase/sql/columns.sql +137 -0
  825. sqlspec/data_dictionary/dialects/sybase/sql/constraints.sql +85 -0
  826. sqlspec/data_dictionary/dialects/sybase/sql/foreign_keys.sql +81 -0
  827. sqlspec/data_dictionary/dialects/sybase/sql/indexes.sql +51 -0
  828. sqlspec/data_dictionary/dialects/sybase/sql/objects.sql +21 -0
  829. sqlspec/data_dictionary/dialects/sybase/sql/schemas.sql +16 -0
  830. sqlspec/data_dictionary/dialects/sybase/sql/tables.sql +46 -0
  831. sqlspec/data_dictionary/dialects/sybase/sql/version.sql +3 -0
  832. sqlspec/data_dictionary/dialects/sybase/sql/views.sql +19 -0
  833. sqlspec/data_dictionary/dialects/teradata/__init__.py +33 -0
  834. sqlspec/data_dictionary/dialects/teradata/config.cp315-win_amd64.pyd +0 -0
  835. sqlspec/data_dictionary/dialects/teradata/config.py +228 -0
  836. sqlspec/data_dictionary/dialects/teradata/sql/columns.sql +22 -0
  837. sqlspec/data_dictionary/dialects/teradata/sql/constraints.sql +19 -0
  838. sqlspec/data_dictionary/dialects/teradata/sql/foreign_keys.sql +9 -0
  839. sqlspec/data_dictionary/dialects/teradata/sql/indexes.sql +9 -0
  840. sqlspec/data_dictionary/dialects/teradata/sql/objects.sql +4 -0
  841. sqlspec/data_dictionary/dialects/teradata/sql/schemas.sql +9 -0
  842. sqlspec/data_dictionary/dialects/teradata/sql/tables.sql +22 -0
  843. sqlspec/data_dictionary/dialects/teradata/sql/version.sql +4 -0
  844. sqlspec/data_dictionary/dialects/teradata/sql/views.sql +4 -0
  845. sqlspec/dialects/__init__.py +44 -0
  846. sqlspec/dialects/db2/__init__.py +111 -0
  847. sqlspec/dialects/db2/_generators.cp315-win_amd64.pyd +0 -0
  848. sqlspec/dialects/db2/_generators.py +376 -0
  849. sqlspec/dialects/db2/_parsers.cp315-win_amd64.pyd +0 -0
  850. sqlspec/dialects/db2/_parsers.py +657 -0
  851. sqlspec/dialects/db2/_transforms.cp315-win_amd64.pyd +0 -0
  852. sqlspec/dialects/db2/_transforms.py +175 -0
  853. sqlspec/dialects/postgres/__init__.py +10 -0
  854. sqlspec/dialects/postgres/_generators.cp315-win_amd64.pyd +0 -0
  855. sqlspec/dialects/postgres/_generators.py +81 -0
  856. sqlspec/dialects/postgres/_operators.cp315-win_amd64.pyd +0 -0
  857. sqlspec/dialects/postgres/_operators.py +95 -0
  858. sqlspec/dialects/postgres/_paradedb.py +44 -0
  859. sqlspec/dialects/postgres/_pg_textsearch.py +38 -0
  860. sqlspec/dialects/postgres/_pgvector.py +36 -0
  861. sqlspec/dialects/spanner/__init__.py +69 -0
  862. sqlspec/dialects/spanner/_expressions.py +247 -0
  863. sqlspec/dialects/spanner/_generators.cp315-win_amd64.pyd +0 -0
  864. sqlspec/dialects/spanner/_generators.py +961 -0
  865. sqlspec/dialects/spanner/_parsers.cp315-win_amd64.pyd +0 -0
  866. sqlspec/dialects/spanner/_parsers.py +871 -0
  867. sqlspec/dialects/spanner/_spangres.py +43 -0
  868. sqlspec/dialects/spanner/_spanner.py +57 -0
  869. sqlspec/dialects/sybase/__init__.py +115 -0
  870. sqlspec/dialects/sybase/_generators.cp315-win_amd64.pyd +0 -0
  871. sqlspec/dialects/sybase/_generators.py +379 -0
  872. sqlspec/dialects/sybase/_parsers.cp315-win_amd64.pyd +0 -0
  873. sqlspec/dialects/sybase/_parsers.py +225 -0
  874. sqlspec/dialects/sybase/_transforms.cp315-win_amd64.pyd +0 -0
  875. sqlspec/dialects/sybase/_transforms.py +68 -0
  876. sqlspec/dialects/teradata/__init__.py +42 -0
  877. sqlspec/dialects/teradata/_generators.cp315-win_amd64.pyd +0 -0
  878. sqlspec/dialects/teradata/_generators.py +203 -0
  879. sqlspec/driver/__init__.py +151 -0
  880. sqlspec/driver/_async.cp315-win_amd64.pyd +0 -0
  881. sqlspec/driver/_async.py +3244 -0
  882. sqlspec/driver/_common.cp315-win_amd64.pyd +0 -0
  883. sqlspec/driver/_common.py +4765 -0
  884. sqlspec/driver/_deferred.cp315-win_amd64.pyd +0 -0
  885. sqlspec/driver/_deferred.py +232 -0
  886. sqlspec/driver/_exception_handler.cp315-win_amd64.pyd +0 -0
  887. sqlspec/driver/_exception_handler.py +224 -0
  888. sqlspec/driver/_routing.cp315-win_amd64.pyd +0 -0
  889. sqlspec/driver/_routing.py +2891 -0
  890. sqlspec/driver/_session.cp315-win_amd64.pyd +0 -0
  891. sqlspec/driver/_session.py +180 -0
  892. sqlspec/driver/_sql_helpers.cp315-win_amd64.pyd +0 -0
  893. sqlspec/driver/_sql_helpers.py +140 -0
  894. sqlspec/driver/_stream.cp315-win_amd64.pyd +0 -0
  895. sqlspec/driver/_stream.py +392 -0
  896. sqlspec/driver/_sync.cp315-win_amd64.pyd +0 -0
  897. sqlspec/driver/_sync.py +3107 -0
  898. sqlspec/driver/_tenant.cp315-win_amd64.pyd +0 -0
  899. sqlspec/driver/_tenant.py +326 -0
  900. sqlspec/exceptions.cp315-win_amd64.pyd +0 -0
  901. sqlspec/exceptions.py +568 -0
  902. sqlspec/extensions/__init__.py +3 -0
  903. sqlspec/extensions/adk/__init__.py +136 -0
  904. sqlspec/extensions/adk/_config_utils.py +306 -0
  905. sqlspec/extensions/adk/_table_utils.cp315-win_amd64.pyd +0 -0
  906. sqlspec/extensions/adk/_table_utils.py +126 -0
  907. sqlspec/extensions/adk/_types.cp315-win_amd64.pyd +0 -0
  908. sqlspec/extensions/adk/_types.py +59 -0
  909. sqlspec/extensions/adk/artifact/__init__.py +18 -0
  910. sqlspec/extensions/adk/artifact/_types.cp315-win_amd64.pyd +0 -0
  911. sqlspec/extensions/adk/artifact/_types.py +41 -0
  912. sqlspec/extensions/adk/artifact/service.py +657 -0
  913. sqlspec/extensions/adk/artifact/store.py +444 -0
  914. sqlspec/extensions/adk/converters.py +230 -0
  915. sqlspec/extensions/adk/maintenance.py +262 -0
  916. sqlspec/extensions/adk/memory/__init__.py +36 -0
  917. sqlspec/extensions/adk/memory/_types.cp315-win_amd64.pyd +0 -0
  918. sqlspec/extensions/adk/memory/_types.py +48 -0
  919. sqlspec/extensions/adk/memory/converters.py +271 -0
  920. sqlspec/extensions/adk/memory/service.py +474 -0
  921. sqlspec/extensions/adk/memory/store.py +586 -0
  922. sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +181 -0
  923. sqlspec/extensions/adk/migrations/0002_create_mssql_python_memory.py +51 -0
  924. sqlspec/extensions/adk/migrations/__init__.py +3 -0
  925. sqlspec/extensions/adk/migrations/reconcile.py +282 -0
  926. sqlspec/extensions/adk/service.py +463 -0
  927. sqlspec/extensions/adk/store.py +1239 -0
  928. sqlspec/extensions/events/__init__.py +132 -0
  929. sqlspec/extensions/events/_buffer.cp315-win_amd64.pyd +0 -0
  930. sqlspec/extensions/events/_buffer.py +38 -0
  931. sqlspec/extensions/events/_channel.cp315-win_amd64.pyd +0 -0
  932. sqlspec/extensions/events/_channel.py +1144 -0
  933. sqlspec/extensions/events/_hints.cp315-win_amd64.pyd +0 -0
  934. sqlspec/extensions/events/_hints.py +38 -0
  935. sqlspec/extensions/events/_models.cp315-win_amd64.pyd +0 -0
  936. sqlspec/extensions/events/_models.py +22 -0
  937. sqlspec/extensions/events/_names.cp315-win_amd64.pyd +0 -0
  938. sqlspec/extensions/events/_names.py +27 -0
  939. sqlspec/extensions/events/_payload.cp315-win_amd64.pyd +0 -0
  940. sqlspec/extensions/events/_payload.py +139 -0
  941. sqlspec/extensions/events/_protocols.py +154 -0
  942. sqlspec/extensions/events/_queue.cp315-win_amd64.pyd +0 -0
  943. sqlspec/extensions/events/_queue.py +1147 -0
  944. sqlspec/extensions/events/_store.py +318 -0
  945. sqlspec/extensions/events/migrations/0001_create_event_queue.py +106 -0
  946. sqlspec/extensions/events/migrations/__init__.py +3 -0
  947. sqlspec/extensions/events/migrations/reconcile.py +145 -0
  948. sqlspec/extensions/events/primitives.cp315-win_amd64.pyd +0 -0
  949. sqlspec/extensions/events/primitives.py +91 -0
  950. sqlspec/extensions/fastapi/__init__.py +26 -0
  951. sqlspec/extensions/fastapi/extension.py +360 -0
  952. sqlspec/extensions/fastapi/providers.cp315-win_amd64.pyd +0 -0
  953. sqlspec/extensions/fastapi/providers.py +1091 -0
  954. sqlspec/extensions/flask/__init__.py +20 -0
  955. sqlspec/extensions/flask/_portal.cp315-win_amd64.pyd +0 -0
  956. sqlspec/extensions/flask/_portal.py +212 -0
  957. sqlspec/extensions/flask/_state.cp315-win_amd64.pyd +0 -0
  958. sqlspec/extensions/flask/_state.py +135 -0
  959. sqlspec/extensions/flask/_utils.cp315-win_amd64.pyd +0 -0
  960. sqlspec/extensions/flask/_utils.py +171 -0
  961. sqlspec/extensions/flask/extension.py +1234 -0
  962. sqlspec/extensions/litestar/__init__.py +52 -0
  963. sqlspec/extensions/litestar/_tenant_resolution.cp315-win_amd64.pyd +0 -0
  964. sqlspec/extensions/litestar/_tenant_resolution.py +314 -0
  965. sqlspec/extensions/litestar/_utils.cp315-win_amd64.pyd +0 -0
  966. sqlspec/extensions/litestar/_utils.py +222 -0
  967. sqlspec/extensions/litestar/channels.py +249 -0
  968. sqlspec/extensions/litestar/cli.py +100 -0
  969. sqlspec/extensions/litestar/config.py +5 -0
  970. sqlspec/extensions/litestar/handlers.py +796 -0
  971. sqlspec/extensions/litestar/migrations/0001_create_session_table.py +138 -0
  972. sqlspec/extensions/litestar/migrations/__init__.py +3 -0
  973. sqlspec/extensions/litestar/migrations/reconcile.py +132 -0
  974. sqlspec/extensions/litestar/plugin.py +2172 -0
  975. sqlspec/extensions/litestar/providers.cp315-win_amd64.pyd +0 -0
  976. sqlspec/extensions/litestar/providers.py +1239 -0
  977. sqlspec/extensions/litestar/store.py +613 -0
  978. sqlspec/extensions/litestar/tenant.py +292 -0
  979. sqlspec/extensions/otel/__init__.py +58 -0
  980. sqlspec/extensions/prometheus/__init__.py +5 -0
  981. sqlspec/extensions/prometheus/_observer.cp315-win_amd64.pyd +0 -0
  982. sqlspec/extensions/prometheus/_observer.py +152 -0
  983. sqlspec/extensions/sanic/__init__.py +28 -0
  984. sqlspec/extensions/sanic/_state.cp315-win_amd64.pyd +0 -0
  985. sqlspec/extensions/sanic/_state.py +102 -0
  986. sqlspec/extensions/sanic/_utils.cp315-win_amd64.pyd +0 -0
  987. sqlspec/extensions/sanic/_utils.py +234 -0
  988. sqlspec/extensions/sanic/extension.py +1467 -0
  989. sqlspec/extensions/starlette/__init__.py +31 -0
  990. sqlspec/extensions/starlette/_state.cp315-win_amd64.pyd +0 -0
  991. sqlspec/extensions/starlette/_state.py +103 -0
  992. sqlspec/extensions/starlette/_utils.cp315-win_amd64.pyd +0 -0
  993. sqlspec/extensions/starlette/_utils.py +267 -0
  994. sqlspec/extensions/starlette/extension.py +691 -0
  995. sqlspec/extensions/starlette/middleware.py +845 -0
  996. sqlspec/loader.cp315-win_amd64.pyd +0 -0
  997. sqlspec/loader.py +1733 -0
  998. sqlspec/migrations/__init__.py +104 -0
  999. sqlspec/migrations/_backup.cp315-win_amd64.pyd +0 -0
  1000. sqlspec/migrations/_backup.py +36 -0
  1001. sqlspec/migrations/base.cp315-win_amd64.pyd +0 -0
  1002. sqlspec/migrations/base.py +1688 -0
  1003. sqlspec/migrations/commands.py +4002 -0
  1004. sqlspec/migrations/context.cp315-win_amd64.pyd +0 -0
  1005. sqlspec/migrations/context.py +158 -0
  1006. sqlspec/migrations/fix.cp315-win_amd64.pyd +0 -0
  1007. sqlspec/migrations/fix.py +193 -0
  1008. sqlspec/migrations/loaders.cp315-win_amd64.pyd +0 -0
  1009. sqlspec/migrations/loaders.py +835 -0
  1010. sqlspec/migrations/runner.cp315-win_amd64.pyd +0 -0
  1011. sqlspec/migrations/runner.py +2144 -0
  1012. sqlspec/migrations/schema.cp315-win_amd64.pyd +0 -0
  1013. sqlspec/migrations/schema.py +1266 -0
  1014. sqlspec/migrations/squash.cp315-win_amd64.pyd +0 -0
  1015. sqlspec/migrations/squash.py +2452 -0
  1016. sqlspec/migrations/templates.cp315-win_amd64.pyd +0 -0
  1017. sqlspec/migrations/templates.py +310 -0
  1018. sqlspec/migrations/tracker.cp315-win_amd64.pyd +0 -0
  1019. sqlspec/migrations/tracker.py +1529 -0
  1020. sqlspec/migrations/utils.cp315-win_amd64.pyd +0 -0
  1021. sqlspec/migrations/utils.py +534 -0
  1022. sqlspec/migrations/validation.cp315-win_amd64.pyd +0 -0
  1023. sqlspec/migrations/validation.py +355 -0
  1024. sqlspec/migrations/version.cp315-win_amd64.pyd +0 -0
  1025. sqlspec/migrations/version.py +455 -0
  1026. sqlspec/observability/__init__.py +122 -0
  1027. sqlspec/observability/_common.cp315-win_amd64.pyd +0 -0
  1028. sqlspec/observability/_common.py +307 -0
  1029. sqlspec/observability/_config.cp315-win_amd64.pyd +0 -0
  1030. sqlspec/observability/_config.py +362 -0
  1031. sqlspec/observability/_diagnostics.cp315-win_amd64.pyd +0 -0
  1032. sqlspec/observability/_diagnostics.py +75 -0
  1033. sqlspec/observability/_dispatcher.cp315-win_amd64.pyd +0 -0
  1034. sqlspec/observability/_dispatcher.py +320 -0
  1035. sqlspec/observability/_formatters/__init__.py +13 -0
  1036. sqlspec/observability/_formatters/_aws.cp315-win_amd64.pyd +0 -0
  1037. sqlspec/observability/_formatters/_aws.py +90 -0
  1038. sqlspec/observability/_formatters/_azure.cp315-win_amd64.pyd +0 -0
  1039. sqlspec/observability/_formatters/_azure.py +84 -0
  1040. sqlspec/observability/_formatters/_base.cp315-win_amd64.pyd +0 -0
  1041. sqlspec/observability/_formatters/_base.py +40 -0
  1042. sqlspec/observability/_formatters/_gcp.cp315-win_amd64.pyd +0 -0
  1043. sqlspec/observability/_formatters/_gcp.py +119 -0
  1044. sqlspec/observability/_formatting.cp315-win_amd64.pyd +0 -0
  1045. sqlspec/observability/_formatting.py +76 -0
  1046. sqlspec/observability/_observer.cp315-win_amd64.pyd +0 -0
  1047. sqlspec/observability/_observer.py +445 -0
  1048. sqlspec/observability/_runtime.cp315-win_amd64.pyd +0 -0
  1049. sqlspec/observability/_runtime.py +740 -0
  1050. sqlspec/observability/_sampling.cp315-win_amd64.pyd +0 -0
  1051. sqlspec/observability/_sampling.py +169 -0
  1052. sqlspec/observability/_spans.cp315-win_amd64.pyd +0 -0
  1053. sqlspec/observability/_spans.py +212 -0
  1054. sqlspec/protocols.py +1235 -0
  1055. sqlspec/py.typed +0 -0
  1056. sqlspec/service/__init__.py +5 -0
  1057. sqlspec/service/_base.py +1051 -0
  1058. sqlspec/service/_core.cp315-win_amd64.pyd +0 -0
  1059. sqlspec/service/_core.py +625 -0
  1060. sqlspec/storage/__init__.py +111 -0
  1061. sqlspec/storage/_arrow_payload.py +802 -0
  1062. sqlspec/storage/_arrow_stream.cp315-win_amd64.pyd +0 -0
  1063. sqlspec/storage/_arrow_stream.py +134 -0
  1064. sqlspec/storage/_ingest.cp315-win_amd64.pyd +0 -0
  1065. sqlspec/storage/_ingest.py +810 -0
  1066. sqlspec/storage/_paths.cp315-win_amd64.pyd +0 -0
  1067. sqlspec/storage/_paths.py +313 -0
  1068. sqlspec/storage/_staging_sql.cp315-win_amd64.pyd +0 -0
  1069. sqlspec/storage/_staging_sql.py +695 -0
  1070. sqlspec/storage/_utils.cp315-win_amd64.pyd +0 -0
  1071. sqlspec/storage/_utils.py +174 -0
  1072. sqlspec/storage/backends/__init__.py +43 -0
  1073. sqlspec/storage/backends/base.cp315-win_amd64.pyd +0 -0
  1074. sqlspec/storage/backends/base.py +399 -0
  1075. sqlspec/storage/backends/fsspec.cp315-win_amd64.pyd +0 -0
  1076. sqlspec/storage/backends/fsspec.py +1390 -0
  1077. sqlspec/storage/backends/local.cp315-win_amd64.pyd +0 -0
  1078. sqlspec/storage/backends/local.py +968 -0
  1079. sqlspec/storage/backends/obstore.cp315-win_amd64.pyd +0 -0
  1080. sqlspec/storage/backends/obstore.py +1974 -0
  1081. sqlspec/storage/errors.cp315-win_amd64.pyd +0 -0
  1082. sqlspec/storage/errors.py +127 -0
  1083. sqlspec/storage/pipeline.cp315-win_amd64.pyd +0 -0
  1084. sqlspec/storage/pipeline.py +1270 -0
  1085. sqlspec/storage/registry.cp315-win_amd64.pyd +0 -0
  1086. sqlspec/storage/registry.py +318 -0
  1087. sqlspec/typing.py +261 -0
  1088. sqlspec/utils/__init__.py +9 -0
  1089. sqlspec/utils/adapters.cp315-win_amd64.pyd +0 -0
  1090. sqlspec/utils/adapters.py +186 -0
  1091. sqlspec/utils/arrow_helpers.py +2157 -0
  1092. sqlspec/utils/config_tools.cp315-win_amd64.pyd +0 -0
  1093. sqlspec/utils/config_tools.py +712 -0
  1094. sqlspec/utils/correlation.cp315-win_amd64.pyd +0 -0
  1095. sqlspec/utils/correlation.py +137 -0
  1096. sqlspec/utils/deprecation.cp315-win_amd64.pyd +0 -0
  1097. sqlspec/utils/deprecation.py +222 -0
  1098. sqlspec/utils/dispatch.cp315-win_amd64.pyd +0 -0
  1099. sqlspec/utils/dispatch.py +104 -0
  1100. sqlspec/utils/env.cp315-win_amd64.pyd +0 -0
  1101. sqlspec/utils/env.py +437 -0
  1102. sqlspec/utils/fixtures.cp315-win_amd64.pyd +0 -0
  1103. sqlspec/utils/fixtures.py +2470 -0
  1104. sqlspec/utils/logging.cp315-win_amd64.pyd +0 -0
  1105. sqlspec/utils/logging.py +267 -0
  1106. sqlspec/utils/module_loader.cp315-win_amd64.pyd +0 -0
  1107. sqlspec/utils/module_loader.py +399 -0
  1108. sqlspec/utils/portal.cp315-win_amd64.pyd +0 -0
  1109. sqlspec/utils/portal.py +411 -0
  1110. sqlspec/utils/routing.cp315-win_amd64.pyd +0 -0
  1111. sqlspec/utils/routing.py +645 -0
  1112. sqlspec/utils/schema.cp315-win_amd64.pyd +0 -0
  1113. sqlspec/utils/schema.py +1050 -0
  1114. sqlspec/utils/serializers/__init__.py +69 -0
  1115. sqlspec/utils/serializers/_json.cp315-win_amd64.pyd +0 -0
  1116. sqlspec/utils/serializers/_json.py +525 -0
  1117. sqlspec/utils/serializers/_numpy.cp315-win_amd64.pyd +0 -0
  1118. sqlspec/utils/serializers/_numpy.py +65 -0
  1119. sqlspec/utils/serializers/_schema.cp315-win_amd64.pyd +0 -0
  1120. sqlspec/utils/serializers/_schema.py +340 -0
  1121. sqlspec/utils/sync_tools.cp315-win_amd64.pyd +0 -0
  1122. sqlspec/utils/sync_tools.py +502 -0
  1123. sqlspec/utils/tenant/__init__.py +71 -0
  1124. sqlspec/utils/tenant/_context.cp315-win_amd64.pyd +0 -0
  1125. sqlspec/utils/tenant/_context.py +550 -0
  1126. sqlspec/utils/tenant/_cursor.cp315-win_amd64.pyd +0 -0
  1127. sqlspec/utils/tenant/_cursor.py +43 -0
  1128. sqlspec/utils/tenant/_mssql.cp315-win_amd64.pyd +0 -0
  1129. sqlspec/utils/tenant/_mssql.py +189 -0
  1130. sqlspec/utils/tenant/_postgres.cp315-win_amd64.pyd +0 -0
  1131. sqlspec/utils/tenant/_postgres.py +142 -0
  1132. sqlspec/utils/text.cp315-win_amd64.pyd +0 -0
  1133. sqlspec/utils/text.py +317 -0
  1134. sqlspec/utils/type_converters.cp315-win_amd64.pyd +0 -0
  1135. sqlspec/utils/type_converters.py +220 -0
  1136. sqlspec/utils/type_guards.cp315-win_amd64.pyd +0 -0
  1137. sqlspec/utils/type_guards.py +1505 -0
  1138. sqlspec/utils/uuids.cp315-win_amd64.pyd +0 -0
  1139. sqlspec/utils/uuids.py +263 -0
  1140. sqlspec-0.72.0.dist-info/METADATA +228 -0
  1141. sqlspec-0.72.0.dist-info/RECORD +1144 -0
  1142. sqlspec-0.72.0.dist-info/WHEEL +4 -0
  1143. sqlspec-0.72.0.dist-info/entry_points.txt +13 -0
  1144. sqlspec-0.72.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2452 @@
1
+ """Migration squash engine for combining multiple migrations into a single file.
2
+
3
+ This module provides utilities to consolidate multiple sequential migrations
4
+ into a single "release" migration file, following the Django-style squash workflow.
5
+
6
+ Three strategies are available:
7
+
8
+ - ``concat`` (default) keeps every original statement verbatim, in order, and
9
+ concatenates the original down migrations in reverse order.
10
+ - ``ddl`` folds the chronological DDL into net ``CREATE`` statements. It refuses
11
+ with :class:`~sqlspec.exceptions.SquashValidationError` whenever the folded
12
+ output could not be faithful to sequential application.
13
+ - ``schema`` emits DDL reflected from the live database data dictionary.
14
+ """
15
+
16
+ import re
17
+ from collections import Counter
18
+ from collections.abc import Iterable, Sequence
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING
22
+
23
+ from sqlglot import exp
24
+ from sqlglot.dialects.dialect import Dialect
25
+ from sqlglot.errors import ErrorLevel, ParseError, TokenError, UnsupportedError
26
+ from sqlglot.tokenizer_core import Token, TokenType
27
+
28
+ from sqlspec.data_dictionary._types import DDLResult
29
+ from sqlspec.driver._sync import SyncDriverAdapterBase
30
+ from sqlspec.exceptions import SquashValidationError, with_cause
31
+ from sqlspec.migrations._backup import create_backup, remove_backup, restore_backup
32
+ from sqlspec.migrations.base import _ensure_schema_extraction_safe_sync
33
+ from sqlspec.migrations.loaders import _load_migration_sql
34
+ from sqlspec.migrations.templates import escape_python_docstring, sanitize_header_field
35
+ from sqlspec.migrations.validation import (
36
+ validate_extension_consistency,
37
+ validate_squash_idempotency,
38
+ validate_squash_range,
39
+ )
40
+ from sqlspec.migrations.version import _format_sequential_version, parse_extension_stem, parse_version
41
+ from sqlspec.utils.logging import get_logger
42
+ from sqlspec.utils.text import slugify, split_qualified_identifier
43
+
44
+ if TYPE_CHECKING:
45
+ from sqlspec.migrations.runner import SyncMigrationRunner
46
+ from sqlspec.migrations.templates import MigrationTemplateSettings
47
+
48
+ __all__ = (
49
+ "DDLStateFolder",
50
+ "MigrationSquasher",
51
+ "SquashPlan",
52
+ "fold_migration_ddl",
53
+ "group_migrations_by_type",
54
+ "parse_version_range",
55
+ "schema_ddl_statements",
56
+ )
57
+
58
+ logger = get_logger("sqlspec.migrations.squash")
59
+
60
+ _TRANSACTIONAL_DIRECTIVE_RE = re.compile(r"^--\s*transactional:\s*(true|false)\s*$", re.MULTILINE | re.IGNORECASE)
61
+ _SCHEMA_DIRECTIVE_RE = re.compile(r"^--\s*schema:\s*(\S+)\s*$", re.MULTILINE | re.IGNORECASE)
62
+ _RENAME_TABLE_COMMAND_RE = re.compile(r"^\s*TABLE\s+([^\s;,]+)\s+TO\s+([^\s;,]+)\s*$", re.IGNORECASE)
63
+ _SQUASH_STRATEGIES = frozenset({"concat", "ddl", "schema"})
64
+ _CONCAT_HINT = "Use --strategy concat to keep the original statements verbatim."
65
+ _SNIPPET_LENGTH = 160
66
+ _TEXT_TOKEN_TYPES = frozenset({
67
+ TokenType.VAR,
68
+ TokenType.IDENTIFIER,
69
+ TokenType.NUMBER,
70
+ TokenType.STRING,
71
+ TokenType.NATIONAL_STRING,
72
+ TokenType.HEREDOC_STRING,
73
+ TokenType.RAW_STRING,
74
+ TokenType.BIT_STRING,
75
+ TokenType.HEX_STRING,
76
+ TokenType.BYTE_STRING,
77
+ TokenType.UNICODE_STRING,
78
+ })
79
+ _CASE_SENSITIVE_TOKEN_TYPES = frozenset({
80
+ TokenType.IDENTIFIER,
81
+ TokenType.STRING,
82
+ TokenType.NATIONAL_STRING,
83
+ TokenType.HEREDOC_STRING,
84
+ TokenType.RAW_STRING,
85
+ TokenType.UNICODE_STRING,
86
+ })
87
+ _EQUIVALENT_TOKEN_TYPES: dict[TokenType, TokenType] = {
88
+ TokenType.KEY: TokenType.INDEX,
89
+ TokenType.CHARACTER_SET: TokenType.SET,
90
+ }
91
+ _DML_TYPES = (exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.TruncateTable)
92
+ _TABLE_CONSTRAINT_TYPES = (exp.Constraint, exp.PrimaryKey, exp.ForeignKey, exp.UniqueColumnConstraint)
93
+ _GENERATED_COLUMN_TYPES = (exp.ComputedColumnConstraint, exp.GeneratedAsIdentityColumnConstraint)
94
+ _SUPPORTED_ALTER_COLUMN_ARGS = frozenset({"this", "dtype", "using", "default", "drop", "allow_null"})
95
+ _MAX_TYPE_TOKENS = 12
96
+ _TYPE_PLACEHOLDER = "__sqlspec_column_type__"
97
+ _ALTER_TYPE_KEYWORDS = frozenset({"SET", "DATA", "TYPE"})
98
+ _MYSQL_FAMILY = frozenset({"mysql", "mariadb", "singlestore", "doris", "starrocks", "tidb"})
99
+ _SEQUENCE_FUNCTIONS = frozenset({"NEXTVAL", "CURRVAL", "SETVAL", "LASTVAL"})
100
+
101
+
102
+ class DDLStateFolder:
103
+ """Fold a chronological sequence of SQL DDL statements into net schema DDL.
104
+
105
+ The folder keeps a catalog of every object created within the squash range and
106
+ applies later ``ALTER``/``DROP``/``RENAME``/``COMMENT`` statements to it. Objects
107
+ that are never rewritten are emitted with their original statement text; only
108
+ rewritten objects are re-rendered through SQLGlot.
109
+
110
+ The folder refuses (raises :class:`~sqlspec.exceptions.SquashValidationError`)
111
+ whenever the folded output could differ from applying the statements in order:
112
+ statements against objects created before the range, DML that a later structural
113
+ change would invalidate, unsupported statement kinds or ``ALTER`` actions,
114
+ procedural or unparsable statements, and rewrites of statements SQLGlot cannot
115
+ reproduce faithfully. The synthesized down statements drop exactly the objects the
116
+ folded up statements create, which restores the pre-range schema because nothing
117
+ outside the range may be touched.
118
+ """
119
+
120
+ __slots__ = (
121
+ "_comments",
122
+ "_ctas_sources",
123
+ "_current_faithful",
124
+ "_current_origin",
125
+ "_current_text",
126
+ "_dialect",
127
+ "_dialect_impl",
128
+ "_dml",
129
+ "_dml_touched",
130
+ "_dml_written",
131
+ "_indexes",
132
+ "_order",
133
+ "_schemas",
134
+ "_sequences",
135
+ "_tables",
136
+ "_views",
137
+ )
138
+
139
+ def __init__(self, dialect: str | None = None) -> None:
140
+ normalized_dialect = "mysql" if dialect == "mariadb" else dialect
141
+ self._dialect = normalized_dialect
142
+ self._dialect_impl: Dialect = Dialect.get_or_raise(normalized_dialect)
143
+ self._schemas: dict[str, _FoldedStatement] = {}
144
+ self._sequences: dict[str, _FoldedStatement] = {}
145
+ self._tables: dict[str, _FoldedStatement] = {}
146
+ self._views: dict[str, _FoldedStatement] = {}
147
+ self._indexes: dict[str, _FoldedStatement] = {}
148
+ self._comments: dict[tuple[str, str], _FoldedStatement] = {}
149
+ self._dml: list[_FoldedStatement] = []
150
+ self._dml_touched: dict[str, _FoldedStatement] = {}
151
+ self._dml_written: dict[str, _FoldedStatement] = {}
152
+ self._ctas_sources: dict[str, set[str]] = {}
153
+ self._order = 0
154
+ self._current_text = ""
155
+ self._current_origin: str | None = None
156
+ self._current_faithful = True
157
+
158
+ def feed(self, statement: str, *, origin: str | None = None) -> None:
159
+ """Parse and fold SQL text into the accumulated schema catalog.
160
+
161
+ Args:
162
+ statement: Raw SQL text that may contain one or more semicolon-delimited statements.
163
+ origin: Optional label (usually the migration version) used in refusal messages.
164
+
165
+ Raises:
166
+ SquashValidationError: If any statement cannot be folded faithfully.
167
+ """
168
+ self._current_origin = origin
169
+ for text, expr, tokens in self._split_statements(statement):
170
+ self._current_text = text
171
+ spans = self._column_type_spans(expr, tokens, statement)
172
+ self._current_faithful = self._is_faithful(expr, tokens, spans)
173
+ for node, arg_key, first, last in spans:
174
+ original_type = statement[tokens[first].start : tokens[last].end + 1]
175
+ node.set(arg_key, exp.DataType(this=exp.DataType.Type.USERDEFINED, kind=original_type))
176
+ self._apply_expression(expr)
177
+
178
+ def to_statements(self) -> tuple[list[str], list[str]]:
179
+ """Render the folded UP statements and the DOWN statements that reverse them.
180
+
181
+ Returns:
182
+ Tuple of ``(up_statements, down_statements)``.
183
+
184
+ Raises:
185
+ SquashValidationError: If the folded objects cannot be ordered or rendered faithfully.
186
+ """
187
+ relation_keys = self._ordered_relation_keys()
188
+ up_statements: list[str] = [self._render(entry) for entry in self._schemas.values()]
189
+ up_statements.extend(self._render(entry) for entry in self._sequences.values())
190
+ up_statements.extend(self._render(self._relation(key)) for key in relation_keys)
191
+ up_statements.extend(self._render(entry) for entry in self._indexes.values())
192
+ up_statements.extend(self._render(entry) for entry in self._comments.values())
193
+ up_statements.extend(self._render(entry) for entry in self._dml)
194
+
195
+ down_statements: list[str] = []
196
+ for key in reversed(relation_keys):
197
+ entry = self._relation(key)
198
+ if key in self._views:
199
+ down_statements.append(self._render_drop(entry, "VIEW", materialized=self._is_materialized(entry)))
200
+ else:
201
+ down_statements.append(self._render_drop(entry, "TABLE"))
202
+ down_statements.extend(self._render_drop(entry, "SEQUENCE") for entry in reversed(self._sequences.values()))
203
+ down_statements.extend(self._render_drop(entry, "SCHEMA") for entry in reversed(self._schemas.values()))
204
+ return up_statements, down_statements
205
+
206
+ def _split_statements(self, sql: str) -> list[tuple[str, exp.Expr, list[Token]]]:
207
+ self._current_text = sql.strip()
208
+ try:
209
+ tokens = self._dialect_impl.tokenize(sql)
210
+ except TokenError as error:
211
+ msg = f"it could not be tokenized ({error})"
212
+ raise with_cause(self._refusal(msg), error) from error
213
+
214
+ chunks: list[list[Token]] = [[]]
215
+ for token in tokens:
216
+ if token.token_type == TokenType.SEMICOLON:
217
+ chunks.append([])
218
+ else:
219
+ chunks[-1].append(token)
220
+
221
+ statements: list[tuple[str, exp.Expr, list[Token]]] = []
222
+ for chunk in chunks:
223
+ if not chunk:
224
+ continue
225
+ text = sql[chunk[0].start : chunk[-1].end + 1]
226
+ self._current_text = text
227
+ try:
228
+ parsed = self._dialect_impl.parser().parse(chunk, sql)
229
+ except ParseError as error:
230
+ msg = "SQLGlot cannot parse it"
231
+ raise with_cause(self._refusal(msg), error) from error
232
+ statements.extend((text, expr, chunk) for expr in parsed if expr is not None)
233
+ return statements
234
+
235
+ def _column_type_spans(self, expr: exp.Expr, tokens: list[Token], sql: str) -> list[tuple[exp.Expr, str, int, int]]:
236
+ """Locate the original token span of each declared column data type.
237
+
238
+ SQLGlot canonicalizes type synonyms (for example SQLite renders ``VARCHAR(20)`` as
239
+ ``TEXT(20)``). The span is the longest run of tokens after the column name (or after
240
+ ``ALTER COLUMN ... [SET DATA] TYPE``) whose parsed type renders identically to the
241
+ parsed column type. The spans let the fidelity check compare column types semantically
242
+ while keeping expression casts strict, and let rewritten tables keep the declared type text.
243
+
244
+ Args:
245
+ expr: Parsed statement.
246
+ tokens: Tokens of the statement, with offsets into ``sql``.
247
+ sql: Full SQL text the tokens were produced from.
248
+
249
+ Returns:
250
+ Tuples of ``(node, arg_key, first_token_index, last_token_index)``.
251
+ """
252
+ token_positions = {token.start: position for position, token in enumerate(tokens)}
253
+ spans: list[tuple[exp.Expr, str, int, int]] = []
254
+ for column in expr.find_all(exp.ColumnDef):
255
+ kind = column.args.get("kind")
256
+ ident = column.this
257
+ if not isinstance(kind, exp.DataType) or not isinstance(ident, exp.Identifier):
258
+ continue
259
+ start = ident.meta.get("start")
260
+ position = token_positions.get(start) if isinstance(start, int) else None
261
+ if position is None:
262
+ continue
263
+ last = self._type_span_end(kind, tokens, position + 1, sql)
264
+ if last is not None:
265
+ spans.append((column, "kind", position + 1, last))
266
+ for alter_col in expr.find_all(exp.AlterColumn):
267
+ dtype = alter_col.args.get("dtype")
268
+ ident = alter_col.this.this if isinstance(alter_col.this, exp.Column) else alter_col.this
269
+ if not isinstance(dtype, exp.DataType) or not isinstance(ident, exp.Identifier):
270
+ continue
271
+ start = ident.meta.get("start")
272
+ position = token_positions.get(start) if isinstance(start, int) else None
273
+ if position is None:
274
+ continue
275
+ first = position + 1
276
+ while first < len(tokens) and tokens[first].text.upper() in _ALTER_TYPE_KEYWORDS:
277
+ first += 1
278
+ last = self._type_span_end(dtype, tokens, first, sql)
279
+ if last is not None:
280
+ spans.append((alter_col, "dtype", first, last))
281
+ return spans
282
+
283
+ def _type_span_end(self, kind: exp.DataType, tokens: list[Token], first: int, sql: str) -> int | None:
284
+ expected = kind.sql(dialect=self._dialect)
285
+ matched: int | None = None
286
+ for last in range(first, min(first + _MAX_TYPE_TOKENS, len(tokens))):
287
+ try:
288
+ parsed = self._dialect_impl.parser(error_level=ErrorLevel.IMMEDIATE).parse_into(
289
+ exp.DataType, tokens[first : last + 1], sql
290
+ )
291
+ except ParseError:
292
+ continue
293
+ if len(parsed) == 1 and parsed[0] is not None and parsed[0].sql(dialect=self._dialect) == expected:
294
+ matched = last
295
+ return matched
296
+
297
+ def _apply_expression(self, expr: exp.Expr) -> None:
298
+ if isinstance(expr, exp.Command):
299
+ self._apply_command(expr)
300
+ elif expr.find(exp.Command) is not None:
301
+ msg = "it contains syntax SQLGlot can only read as an opaque command"
302
+ raise self._refusal(msg)
303
+ elif isinstance(expr, exp.Create):
304
+ self._apply_create(expr)
305
+ elif isinstance(expr, exp.Alter):
306
+ self._apply_alter(expr)
307
+ elif isinstance(expr, exp.Drop):
308
+ self._apply_drop(expr)
309
+ elif isinstance(expr, exp.Comment):
310
+ self._apply_comment(expr)
311
+ elif isinstance(expr, _DML_TYPES):
312
+ self._apply_dml(expr)
313
+ else:
314
+ msg = f"{type(expr).__name__} statements are not supported"
315
+ raise self._refusal(msg)
316
+
317
+ def _apply_command(self, expr: exp.Command) -> None:
318
+ keyword = str(expr.this).upper()
319
+ literal = expr.expression.name if isinstance(expr.expression, exp.Expr) else str(expr.expression or "")
320
+ match = _RENAME_TABLE_COMMAND_RE.match(literal) if keyword == "RENAME" else None
321
+ if match is None:
322
+ msg = "SQLGlot can only read it as an opaque command, so its effect on the schema is unknown"
323
+ raise self._refusal(msg)
324
+ old_table = exp.to_table(match.group(1), dialect=self._dialect)
325
+ new_table = exp.to_table(match.group(2), dialect=self._dialect)
326
+ old_key = self._object_key(old_table)
327
+ self._require_table(old_key, "RENAME TABLE")
328
+ self._assert_restructurable(old_key, "RENAME TABLE")
329
+ self._rename_table(old_key, new_table)
330
+
331
+ def _apply_create(self, expr: exp.Create) -> None:
332
+ kind = str(expr.args.get("kind") or "").upper()
333
+ if expr.find(exp.TemporaryProperty) is not None:
334
+ msg = "temporary objects are not part of the persistent schema"
335
+ raise self._refusal(msg)
336
+ if kind == "TABLE":
337
+ self._create_table(expr)
338
+ elif kind == "VIEW":
339
+ self._create_view(expr)
340
+ elif kind == "INDEX":
341
+ self._create_index(expr)
342
+ elif kind == "SCHEMA":
343
+ self._create_simple(expr, self._schemas, kind)
344
+ elif kind == "SEQUENCE":
345
+ self._create_simple(expr, self._sequences, kind)
346
+ else:
347
+ msg = f"CREATE {kind or 'statements of this kind'} cannot be folded"
348
+ raise self._refusal(msg)
349
+
350
+ def _create_simple(self, expr: exp.Create, catalog: "dict[str, _FoldedStatement]", kind: str) -> None:
351
+ key = self._object_key(expr.this)
352
+ if self._create_is_noop(expr, key, key in catalog, kind):
353
+ return
354
+ catalog[key] = self._new_entry(expr)
355
+
356
+ def _create_table(self, expr: exp.Create) -> None:
357
+ key = self._object_key(expr.this)
358
+ if key in self._views:
359
+ msg = f"{key} is already a view created earlier in the squash range"
360
+ raise self._refusal(msg)
361
+ if self._create_is_noop(expr, key, key in self._tables, "TABLE"):
362
+ return
363
+ query = expr.expression
364
+ if isinstance(query, exp.Query):
365
+ sources = self._expand_dependencies(self._query_sources(query))
366
+ for source in sources:
367
+ writer = self._dml_written.get(source)
368
+ if writer is not None:
369
+ msg = (
370
+ f"CREATE TABLE AS SELECT reads {source}, which DML in migration "
371
+ f"{writer.origin or '<unknown>'} modifies first; the folded migration would run it before that DML"
372
+ )
373
+ raise self._refusal(msg)
374
+ for source in sources:
375
+ self._ctas_sources.setdefault(source, set()).add(key)
376
+ elif not isinstance(expr.this, exp.Schema):
377
+ msg = "CREATE TABLE without a column list cannot be folded"
378
+ raise self._refusal(msg)
379
+ self._tables[key] = self._new_entry(expr)
380
+
381
+ def _create_view(self, expr: exp.Create) -> None:
382
+ key = self._object_key(expr.this)
383
+ if key in self._tables:
384
+ msg = f"{key} is already a table created earlier in the squash range"
385
+ raise self._refusal(msg)
386
+ if key in self._views and expr.args.get("replace"):
387
+ self._assert_restructurable(key, "CREATE OR REPLACE VIEW")
388
+ self._views[key] = self._new_entry(expr)
389
+ return
390
+ if self._create_is_noop(expr, key, key in self._views, "VIEW"):
391
+ return
392
+ self._views[key] = self._new_entry(expr)
393
+
394
+ def _create_index(self, expr: exp.Create) -> None:
395
+ index = expr.this
396
+ table = index.args.get("table") if isinstance(index, exp.Index) else None
397
+ if not isinstance(index, exp.Index) or not isinstance(table, exp.Table):
398
+ msg = "the index definition could not be read"
399
+ raise self._refusal(msg)
400
+ table_key = self._object_key(table)
401
+ view_entry = self._views.get(table_key)
402
+ if table_key not in self._tables and (view_entry is None or not self._is_materialized(view_entry)):
403
+ msg = f"CREATE INDEX targets {table_key}, which is not created within the squash range"
404
+ raise self._refusal(msg)
405
+ name = index.this
406
+ base_name = self._name_key(name) if isinstance(name, exp.Expr) else ""
407
+ key = self._index_catalog_key(base_name, table_key) if base_name else f"<unnamed index {self._order}>"
408
+ if key in self._indexes:
409
+ if expr.args.get("exists"):
410
+ return
411
+ msg = f"index {base_name or key} is already created earlier in the squash range"
412
+ raise self._refusal(msg)
413
+ self._indexes[key] = self._new_entry(expr, owner=table_key)
414
+
415
+ def _create_is_noop(self, expr: exp.Create, key: str, exists_in_range: bool, kind: str) -> bool:
416
+ if exists_in_range:
417
+ if expr.args.get("exists"):
418
+ return True
419
+ msg = f"{kind} {key} is already created earlier in the squash range"
420
+ raise self._refusal(msg)
421
+ if expr.args.get("exists"):
422
+ msg = (
423
+ f"CREATE {kind} IF NOT EXISTS cannot tell whether {key} existed before the squash range, "
424
+ "so the folded down migration could drop a pre-existing object"
425
+ )
426
+ raise self._refusal(msg)
427
+ if expr.args.get("replace"):
428
+ msg = f"CREATE OR REPLACE {kind} may replace {key}, which could exist before the squash range"
429
+ raise self._refusal(msg)
430
+ return False
431
+
432
+ def _apply_alter(self, expr: exp.Alter) -> None:
433
+ kind = str(expr.args.get("kind") or "TABLE").upper()
434
+ target = expr.this
435
+ if not isinstance(target, exp.Table):
436
+ msg = "the ALTER target could not be read"
437
+ raise self._refusal(msg)
438
+ if not self._current_faithful:
439
+ msg = "SQLGlot does not reproduce it faithfully, so it cannot be merged into a folded definition"
440
+ raise self._refusal(msg)
441
+ if expr.args.get("not_valid"):
442
+ msg = "NOT VALID constraints cannot be folded into CREATE TABLE"
443
+ raise self._refusal(msg)
444
+ actions = [action for action in expr.args.get("actions") or [] if isinstance(action, exp.Expr)]
445
+ if kind == "INDEX":
446
+ self._alter_index(target, actions)
447
+ return
448
+ if kind != "TABLE":
449
+ msg = f"ALTER {kind} cannot be folded"
450
+ raise self._refusal(msg)
451
+ table_key = self._object_key(target)
452
+ entry = self._require_table(table_key, "ALTER TABLE")
453
+ if isinstance(entry.expr.expression, exp.Query):
454
+ msg = f"{table_key} is created with CREATE TABLE AS SELECT, which cannot absorb ALTER TABLE"
455
+ raise self._refusal(msg)
456
+ for action in actions:
457
+ table_key = self._apply_alter_action(table_key, target, action)
458
+
459
+ def _apply_alter_action(self, table_key: str, target: exp.Table, action: exp.Expr) -> str:
460
+ label = f"ALTER TABLE {type(action).__name__}"
461
+ self._assert_restructurable(table_key, label)
462
+ entry = self._tables[table_key]
463
+ if isinstance(action, exp.AlterRename):
464
+ new_table = action.this
465
+ if not isinstance(new_table, exp.Table):
466
+ msg = "the RENAME target could not be read"
467
+ raise self._refusal(msg)
468
+ target_db = target.args.get("db")
469
+ if isinstance(target_db, exp.Identifier) and not new_table.db:
470
+ new_table = new_table.copy()
471
+ new_table.set("db", target_db.copy())
472
+ return self._rename_table(table_key, new_table)
473
+ schema = self._table_schema(entry)
474
+ if isinstance(action, exp.ColumnDef):
475
+ self._add_column(table_key, entry, schema, action)
476
+ elif isinstance(action, exp.ModifyColumn):
477
+ self._modify_column(table_key, entry, schema, action)
478
+ elif isinstance(action, exp.Drop):
479
+ self._drop_from_table(table_key, entry, schema, action)
480
+ elif isinstance(action, exp.DropPrimaryKey):
481
+ self._drop_primary_key(table_key, entry, schema)
482
+ elif isinstance(action, exp.RenameColumn):
483
+ self._rename_column(table_key, entry, schema, action)
484
+ elif isinstance(action, exp.AlterColumn):
485
+ self._alter_column(table_key, entry, schema, action)
486
+ elif isinstance(action, exp.AddConstraint):
487
+ constraints = [item for item in action.expressions if isinstance(item, exp.Expr)]
488
+ self._add_constraints(entry, schema, constraints)
489
+ elif isinstance(action, _TABLE_CONSTRAINT_TYPES):
490
+ self._add_constraints(entry, schema, [action])
491
+ else:
492
+ msg = f"ALTER TABLE action {type(action).__name__} cannot be folded"
493
+ raise self._refusal(msg)
494
+ return table_key
495
+
496
+ def _alter_index(self, target: exp.Table, actions: list[exp.Expr]) -> None:
497
+ if len(actions) != 1 or not isinstance(actions[0], exp.AlterRename):
498
+ msg = "only ALTER INDEX ... RENAME TO can be folded"
499
+ raise self._refusal(msg)
500
+ raw_old_key = self._object_key(target)
501
+ old_key = self._resolve_index_key(raw_old_key)
502
+ entry = self._indexes.get(old_key)
503
+ if entry is None or not isinstance(entry.expr.this, exp.Index):
504
+ msg = f"ALTER INDEX targets {raw_old_key}, which is not created within the squash range"
505
+ raise self._refusal(msg)
506
+ new_node = actions[0].this
507
+ new_ident = new_node.this if isinstance(new_node, exp.Table) else None
508
+ if not isinstance(new_ident, exp.Identifier):
509
+ msg = "the RENAME target could not be read"
510
+ raise self._refusal(msg)
511
+ new_base = self._ident_key(new_ident)
512
+ new_key = self._index_catalog_key(new_base, entry.owner)
513
+ if new_key in self._indexes:
514
+ msg = f"index {new_base} is already created earlier in the squash range"
515
+ raise self._refusal(msg)
516
+ self._mark_modified(entry)
517
+ entry.expr.this.set("this", new_ident.copy())
518
+ self._indexes = {(new_key if key == old_key else key): value for key, value in self._indexes.items()}
519
+ comment = self._comments.pop(("INDEX", old_key), None)
520
+ if comment is not None:
521
+ self._mark_modified(comment)
522
+ comment_target = comment.expr.this
523
+ if isinstance(comment_target, exp.Table):
524
+ comment_target.set("this", new_ident.copy())
525
+ self._comments["INDEX", new_key] = comment
526
+
527
+ def _add_column(self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, action: exp.ColumnDef) -> None:
528
+ column_key = self._name_key(action)
529
+ if self._find_column(schema, column_key) is not None:
530
+ if action.args.get("exists"):
531
+ return
532
+ msg = f"column {column_key} already exists on {table_key}"
533
+ raise self._refusal(msg)
534
+ if action.args.get("position") is not None:
535
+ msg = "column positioning (FIRST/AFTER) cannot be folded"
536
+ raise self._refusal(msg)
537
+ self._assert_views_allow(table_key, set(), "ADD COLUMN")
538
+ self._mark_modified(entry)
539
+ column = action.copy()
540
+ column.set("exists", None)
541
+ columns = [item for item in schema.expressions if isinstance(item, exp.ColumnDef)]
542
+ constraints = [item for item in schema.expressions if not isinstance(item, exp.ColumnDef)]
543
+ schema.set("expressions", [*columns, column, *constraints])
544
+
545
+ def _modify_column(
546
+ self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, action: exp.ModifyColumn
547
+ ) -> None:
548
+ new_definition = action.this
549
+ if not isinstance(new_definition, exp.ColumnDef):
550
+ msg = "the MODIFY COLUMN definition could not be read"
551
+ raise self._refusal(msg)
552
+ if new_definition.args.get("position") is not None:
553
+ msg = "column positioning (FIRST/AFTER) cannot be folded"
554
+ raise self._refusal(msg)
555
+ rename_from = action.args.get("rename_from")
556
+ new_key = self._name_key(new_definition)
557
+ old_key = self._name_key(rename_from) if isinstance(rename_from, exp.Expr) else new_key
558
+ existing = self._find_column(schema, old_key)
559
+ if existing is None:
560
+ msg = f"column {old_key} does not exist on {table_key}"
561
+ raise self._refusal(msg)
562
+ if old_key != new_key:
563
+ if self._find_column(schema, new_key) is not None:
564
+ msg = f"column {new_key} already exists on {table_key}"
565
+ raise self._refusal(msg)
566
+ self._assert_views_allow(table_key, None, "CHANGE COLUMN")
567
+ self._mark_modified(entry)
568
+ new_ident = new_definition.this
569
+ if isinstance(new_ident, exp.Identifier):
570
+ self._rename_column_references(table_key, old_key, new_ident)
571
+ else:
572
+ self._assert_views_allow(table_key, {old_key}, "MODIFY COLUMN")
573
+ self._mark_modified(entry)
574
+ replacement = new_definition.copy()
575
+ replacement_constraints = list(replacement.args.get("constraints") or [])
576
+ existing_key_kinds = {
577
+ type(c.args.get("kind"))
578
+ for c in replacement_constraints
579
+ if isinstance(c.args.get("kind"), (exp.PrimaryKeyColumnConstraint, exp.UniqueColumnConstraint))
580
+ }
581
+ for constraint in existing.args.get("constraints") or []:
582
+ kind = constraint.args.get("kind")
583
+ if isinstance(kind, (exp.PrimaryKeyColumnConstraint, exp.UniqueColumnConstraint)) and (
584
+ type(kind) not in existing_key_kinds
585
+ ):
586
+ replacement_constraints.append(constraint.copy())
587
+ existing_key_kinds.add(type(kind))
588
+ if replacement_constraints:
589
+ replacement.set("constraints", replacement_constraints)
590
+ schema.set(
591
+ "expressions",
592
+ [
593
+ replacement if isinstance(item, exp.ColumnDef) and self._name_key(item) == new_key else item
594
+ for item in schema.expressions
595
+ ],
596
+ )
597
+
598
+ def _drop_from_table(self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, action: exp.Drop) -> None:
599
+ drop_kind = str(action.args.get("kind") or "").upper()
600
+ if_exists = bool(action.args.get("exists"))
601
+ names = [self._name_key(node) for node in self._drop_targets(action)]
602
+ for name in names:
603
+ if drop_kind == "COLUMN":
604
+ self._drop_column(table_key, entry, schema, name, if_exists=if_exists)
605
+ elif drop_kind == "FOREIGN KEY":
606
+ msg = (
607
+ "ALTER TABLE DROP FOREIGN KEY leaves behind the index MySQL created for the foreign key, "
608
+ "which the folded CREATE TABLE cannot reproduce exactly"
609
+ )
610
+ raise self._refusal(msg)
611
+ elif drop_kind == "CONSTRAINT":
612
+ self._drop_constraint(table_key, entry, schema, name, if_exists=if_exists)
613
+ elif drop_kind == "INDEX":
614
+ self._drop_table_index(table_key, entry, schema, name)
615
+ else:
616
+ msg = f"ALTER TABLE DROP {drop_kind or 'action'} cannot be folded"
617
+ raise self._refusal(msg)
618
+
619
+ def _drop_column(
620
+ self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, column_key: str, *, if_exists: bool
621
+ ) -> None:
622
+ if self._find_column(schema, column_key) is None:
623
+ if if_exists:
624
+ return
625
+ msg = f"column {column_key} does not exist on {table_key}"
626
+ raise self._refusal(msg)
627
+ pk_columns = self._primary_key_columns(table_key)
628
+ if column_key in pk_columns and (len(pk_columns) > 1 or (self._dialect or "") in {"sqlite", "duckdb"}):
629
+ msg = (
630
+ f"dropping primary key column {column_key} on {table_key} leaves dialect-specific primary key and "
631
+ "NOT NULL state, which the folded CREATE TABLE cannot reproduce"
632
+ )
633
+ raise self._refusal(msg)
634
+ if (self._dialect or "") in _MYSQL_FAMILY and self._has_multi_column_index_or_unique(
635
+ table_key, schema, column_key
636
+ ):
637
+ msg = (
638
+ f"dropping column {column_key} on {table_key} narrows a multi-column index or unique constraint "
639
+ "in MySQL, which the folded CREATE TABLE cannot reproduce"
640
+ )
641
+ raise self._refusal(msg)
642
+ self._assert_views_allow(table_key, {column_key}, "DROP COLUMN")
643
+ for other_key, other in self._tables.items():
644
+ if other_key != table_key and column_key in self._referenced_columns(other.expr, table_key):
645
+ msg = f"column {column_key} on {table_key} is referenced by a foreign key on {other_key}"
646
+ raise self._refusal(msg)
647
+ self._mark_modified(entry)
648
+ kept: list[exp.Expr] = []
649
+ for item in schema.expressions:
650
+ if isinstance(item, exp.ColumnDef):
651
+ if self._name_key(item) == column_key:
652
+ continue
653
+ self._strip_column_constraints(item, column_key, table_key)
654
+ elif column_key in self._local_column_keys(item, table_key):
655
+ continue
656
+ kept.append(item)
657
+ schema.set("expressions", kept)
658
+ stale_indexes = [
659
+ index_key
660
+ for index_key, index_entry in self._indexes.items()
661
+ if index_entry.owner == table_key and column_key in self._index_column_keys(index_entry)
662
+ ]
663
+ for index_key in stale_indexes:
664
+ self._indexes.pop(index_key)
665
+ self._comments.pop(("INDEX", index_key), None)
666
+ self._comments.pop(("COLUMN", f"{table_key}.{column_key}"), None)
667
+
668
+ def _strip_column_constraints(self, column: exp.ColumnDef, column_key: str, table_key: str) -> None:
669
+ kept: list[exp.Expr] = []
670
+ for constraint in column.args.get("constraints") or []:
671
+ if column_key in self._local_column_keys(constraint, table_key):
672
+ if isinstance(constraint.args.get("kind"), _GENERATED_COLUMN_TYPES):
673
+ msg = f"generated column {self._name_key(column)} depends on dropped column {column_key}"
674
+ raise self._refusal(msg)
675
+ continue
676
+ kept.append(constraint)
677
+ column.set("constraints", kept)
678
+
679
+ def _drop_constraint(
680
+ self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, name: str, *, if_exists: bool
681
+ ) -> None:
682
+ found = any(
683
+ isinstance(item, exp.Constraint) and self._name_key(item) == name for item in schema.expressions
684
+ ) or any(
685
+ isinstance(constraint.this, exp.Identifier) and self._ident_key(constraint.this) == name
686
+ for column in schema.expressions
687
+ if isinstance(column, exp.ColumnDef)
688
+ for constraint in column.args.get("constraints") or []
689
+ )
690
+ if not found:
691
+ if if_exists:
692
+ return
693
+ msg = f"constraint {name} is not defined by name on {table_key} within the squash range"
694
+ raise self._refusal(msg)
695
+ named = [
696
+ node
697
+ for item in schema.expressions
698
+ for node in ([item] if isinstance(item, exp.Constraint) else item.args.get("constraints") or [])
699
+ if isinstance(node, (exp.Constraint, exp.ColumnConstraint))
700
+ and isinstance(node.this, exp.Identifier)
701
+ and self._ident_key(node.this) == name
702
+ ]
703
+ if any(node.find(exp.PrimaryKey, exp.PrimaryKeyColumnConstraint) is not None for node in named):
704
+ msg = (
705
+ f"dropping primary key constraint {name} leaves dialect-specific NOT NULL state on its columns, "
706
+ "which the folded CREATE TABLE cannot reproduce exactly"
707
+ )
708
+ raise self._refusal(msg)
709
+ if (self._dialect or "") in _MYSQL_FAMILY and any(node.find(exp.Reference) is not None for node in named):
710
+ msg = (
711
+ f"dropping foreign key constraint {name} leaves behind the index MySQL created for it, "
712
+ "which the folded CREATE TABLE cannot reproduce exactly"
713
+ )
714
+ raise self._refusal(msg)
715
+ self._mark_modified(entry)
716
+ kept: list[exp.Expr] = []
717
+ for item in schema.expressions:
718
+ if isinstance(item, exp.Constraint) and self._name_key(item) == name:
719
+ continue
720
+ if isinstance(item, exp.ColumnDef):
721
+ item.set(
722
+ "constraints",
723
+ [
724
+ constraint
725
+ for constraint in item.args.get("constraints") or []
726
+ if not (
727
+ isinstance(constraint.this, exp.Identifier) and self._ident_key(constraint.this) == name
728
+ )
729
+ ],
730
+ )
731
+ kept.append(item)
732
+ schema.set("expressions", kept)
733
+
734
+ def _drop_table_index(self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, name: str) -> None:
735
+ resolved_key = self._resolve_index_key(name, owner=table_key)
736
+ index_entry = self._indexes.get(resolved_key)
737
+ if index_entry is not None and index_entry.owner == table_key:
738
+ self._indexes.pop(resolved_key)
739
+ self._comments.pop(("INDEX", resolved_key), None)
740
+ return
741
+ inline = [
742
+ item
743
+ for item in schema.expressions
744
+ if isinstance(item, exp.IndexColumnConstraint)
745
+ and isinstance(item.this, exp.Identifier)
746
+ and self._ident_key(item.this) == name
747
+ ]
748
+ if not inline:
749
+ msg = f"index {name} is not defined on {table_key} within the squash range"
750
+ raise self._refusal(msg)
751
+ self._mark_modified(entry)
752
+ schema.set("expressions", [item for item in schema.expressions if item not in inline])
753
+
754
+ def _drop_primary_key(self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema) -> None:
755
+ """Drop the primary key while keeping its columns NOT NULL, as MySQL does."""
756
+ primary_key_columns = self._primary_key_columns(table_key)
757
+ kept: list[exp.Expr] = []
758
+ found = False
759
+ for item in schema.expressions:
760
+ if isinstance(item, exp.PrimaryKey) or (
761
+ isinstance(item, exp.Constraint) and any(isinstance(sub, exp.PrimaryKey) for sub in item.expressions)
762
+ ):
763
+ found = True
764
+ continue
765
+ if isinstance(item, exp.ColumnDef):
766
+ constraints = list(item.args.get("constraints") or [])
767
+ filtered = [
768
+ c for c in constraints if not isinstance(c.args.get("kind"), exp.PrimaryKeyColumnConstraint)
769
+ ]
770
+ if len(filtered) != len(constraints):
771
+ found = True
772
+ item.set("constraints", filtered)
773
+ kept.append(item)
774
+ if not found:
775
+ msg = f"{table_key} has no primary key defined within the squash range"
776
+ raise self._refusal(msg)
777
+ self._mark_modified(entry)
778
+ for item in kept:
779
+ if not isinstance(item, exp.ColumnDef) or self._name_key(item) not in primary_key_columns:
780
+ continue
781
+ constraints = list(item.args.get("constraints") or [])
782
+ if not any(
783
+ isinstance(c.args.get("kind"), exp.NotNullColumnConstraint)
784
+ and not c.args["kind"].args.get("allow_null")
785
+ for c in constraints
786
+ ):
787
+ constraints.append(exp.ColumnConstraint(kind=exp.NotNullColumnConstraint()))
788
+ item.set("constraints", constraints)
789
+ schema.set("expressions", kept)
790
+
791
+ def _rename_column(
792
+ self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, action: exp.RenameColumn
793
+ ) -> None:
794
+ old_key = self._name_key(action.this)
795
+ new_node = action.args.get("to")
796
+ new_ident = new_node.this if isinstance(new_node, exp.Column) else new_node
797
+ if not isinstance(new_ident, exp.Identifier):
798
+ msg = "the RENAME COLUMN target could not be read"
799
+ raise self._refusal(msg)
800
+ if self._find_column(schema, old_key) is None:
801
+ if action.args.get("exists"):
802
+ return
803
+ msg = f"column {old_key} does not exist on {table_key}"
804
+ raise self._refusal(msg)
805
+ if self._find_column(schema, self._ident_key(new_ident)) is not None:
806
+ msg = f"column {self._ident_key(new_ident)} already exists on {table_key}"
807
+ raise self._refusal(msg)
808
+ self._assert_views_allow(table_key, None, "RENAME COLUMN")
809
+ self._mark_modified(entry)
810
+ self._rename_column_references(table_key, old_key, new_ident)
811
+
812
+ def _rename_column_references(self, table_key: str, old_key: str, new_ident: exp.Identifier) -> None:
813
+ schema = self._table_schema(self._tables[table_key])
814
+ for item in schema.expressions:
815
+ if isinstance(item, exp.ColumnDef) and self._name_key(item) == old_key:
816
+ item.set("this", new_ident.copy())
817
+ for ident in self._local_column_refs(item, table_key):
818
+ if self._ident_key(ident) == old_key:
819
+ ident.replace(new_ident.copy())
820
+ for index_entry in self._indexes.values():
821
+ if index_entry.owner != table_key:
822
+ continue
823
+ index_refs = [ident for ident in self._index_column_refs(index_entry) if self._ident_key(ident) == old_key]
824
+ if index_refs:
825
+ self._mark_modified(index_entry)
826
+ for ident in index_refs:
827
+ ident.replace(new_ident.copy())
828
+ for other_key, other in self._tables.items():
829
+ if other_key == table_key:
830
+ continue
831
+ foreign_refs = [
832
+ ident
833
+ for ident in self._foreign_reference_idents(other.expr, table_key)
834
+ if self._ident_key(ident) == old_key
835
+ ]
836
+ if foreign_refs:
837
+ self._mark_modified(other)
838
+ for ident in foreign_refs:
839
+ ident.replace(new_ident.copy())
840
+ new_key = self._ident_key(new_ident)
841
+ comment = self._comments.get(("COLUMN", f"{table_key}.{old_key}"))
842
+ if comment is not None:
843
+ self._mark_modified(comment)
844
+ if isinstance(comment.expr.this, exp.Column):
845
+ comment.expr.this.set("this", new_ident.copy())
846
+ self._comments = {
847
+ (("COLUMN", f"{table_key}.{new_key}") if key == ("COLUMN", f"{table_key}.{old_key}") else key): value
848
+ for key, value in self._comments.items()
849
+ }
850
+
851
+ def _alter_column(
852
+ self, table_key: str, entry: "_FoldedStatement", schema: exp.Schema, action: exp.AlterColumn
853
+ ) -> None:
854
+ unsupported = sorted(
855
+ arg for arg, value in action.args.items() if value and arg not in _SUPPORTED_ALTER_COLUMN_ARGS
856
+ )
857
+ if unsupported:
858
+ msg = f"ALTER COLUMN with {', '.join(unsupported)} cannot be folded"
859
+ raise self._refusal(msg)
860
+ column_key = self._name_key(action)
861
+ column = self._find_column(schema, column_key)
862
+ if column is None:
863
+ msg = f"column {column_key} does not exist on {table_key}"
864
+ raise self._refusal(msg)
865
+ dtype = action.args.get("dtype")
866
+ if isinstance(dtype, exp.DataType):
867
+ self._assert_views_allow(table_key, {column_key}, "ALTER COLUMN TYPE")
868
+ self._mark_modified(entry)
869
+ if isinstance(dtype, exp.DataType):
870
+ column.set("kind", dtype.copy())
871
+ constraints: list[exp.ColumnConstraint] = list(column.args.get("constraints") or [])
872
+ default_expr = action.args.get("default")
873
+ allow_null = action.args.get("allow_null")
874
+ if isinstance(default_expr, exp.Expr):
875
+ constraints = [c for c in constraints if not isinstance(c.kind, exp.DefaultColumnConstraint)]
876
+ constraints.append(exp.ColumnConstraint(kind=exp.DefaultColumnConstraint(this=default_expr.copy())))
877
+ elif action.args.get("drop") and allow_null is None:
878
+ constraints = [c for c in constraints if not isinstance(c.kind, exp.DefaultColumnConstraint)]
879
+ if allow_null is False:
880
+ constraints = [c for c in constraints if not isinstance(c.kind, exp.NotNullColumnConstraint)]
881
+ constraints.append(exp.ColumnConstraint(kind=exp.NotNullColumnConstraint()))
882
+ elif allow_null is True:
883
+ constraints = [
884
+ c
885
+ for c in constraints
886
+ if not (isinstance(c.kind, exp.NotNullColumnConstraint) and not c.kind.args.get("allow_null"))
887
+ ]
888
+ column.set("constraints", constraints)
889
+
890
+ def _add_constraints(self, entry: "_FoldedStatement", schema: exp.Schema, constraints: list[exp.Expr]) -> None:
891
+ if not constraints:
892
+ msg = "the added constraint could not be read"
893
+ raise self._refusal(msg)
894
+ self._mark_modified(entry)
895
+ schema.set("expressions", [*schema.expressions, *(constraint.copy() for constraint in constraints)])
896
+
897
+ def _rename_table(self, old_key: str, new_table: exp.Table) -> str:
898
+ new_key = self._object_key(new_table)
899
+ if new_key == old_key:
900
+ return old_key
901
+ if new_key in self._tables or new_key in self._views:
902
+ msg = f"{new_key} already exists within the squash range"
903
+ raise self._refusal(msg)
904
+ self._assert_views_allow(old_key, None, "RENAME TABLE")
905
+ entry = self._tables[old_key]
906
+ referencing: list[tuple[_FoldedStatement, exp.Table]] = []
907
+ for other in self._tables.values():
908
+ for reference in other.expr.find_all(exp.Reference):
909
+ ref_table = self._reference_table(reference)
910
+ if ref_table is not None and self._resolve_reference_key(ref_table) == old_key:
911
+ referencing.append((other, ref_table))
912
+ self._mark_modified(entry)
913
+ self._set_create_table_node(entry.expr, new_table.copy())
914
+ self._tables = {(new_key if key == old_key else key): value for key, value in self._tables.items()}
915
+ for other, ref_table in referencing:
916
+ self._mark_modified(other)
917
+ ref_table.replace(new_table.copy())
918
+ rebuilt_indexes: dict[str, _FoldedStatement] = {}
919
+ renamed_index_keys: dict[str, str] = {}
920
+ for index_key, index_entry in self._indexes.items():
921
+ if index_entry.owner == old_key and isinstance(index_entry.expr.this, exp.Index):
922
+ self._mark_modified(index_entry)
923
+ index_entry.expr.this.set("table", new_table.copy())
924
+ index_entry.owner = new_key
925
+ base_name = index_key.rsplit(".", 1)[-1]
926
+ new_index_key = (
927
+ self._index_catalog_key(base_name, new_key) if not base_name.startswith("<unnamed ") else base_name
928
+ )
929
+ rebuilt_indexes[new_index_key] = index_entry
930
+ renamed_index_keys[index_key] = new_index_key
931
+ else:
932
+ rebuilt_indexes[index_key] = index_entry
933
+ self._indexes = rebuilt_indexes
934
+ rebuilt_comments: dict[tuple[str, str], _FoldedStatement] = {}
935
+ for (comment_kind, comment_key), comment in self._comments.items():
936
+ if comment_kind == "TABLE" and comment_key == old_key:
937
+ self._mark_modified(comment)
938
+ comment.expr.set("this", new_table.copy())
939
+ rebuilt_comments[comment_kind, new_key] = comment
940
+ elif comment_kind == "COLUMN" and comment_key.startswith(f"{old_key}."):
941
+ self._mark_modified(comment)
942
+ column = comment.expr.this
943
+ if isinstance(column, exp.Column):
944
+ column.set("table", new_table.this.copy() if isinstance(new_table.this, exp.Expr) else None)
945
+ new_db = new_table.args.get("db")
946
+ column.set("db", new_db.copy() if isinstance(new_db, exp.Expr) else None)
947
+ rebuilt_comments[comment_kind, f"{new_key}.{comment_key[len(old_key) + 1 :]}"] = comment
948
+ elif comment_kind == "INDEX" and comment_key in renamed_index_keys:
949
+ rebuilt_comments[comment_kind, renamed_index_keys[comment_key]] = comment
950
+ else:
951
+ rebuilt_comments[comment_kind, comment_key] = comment
952
+ self._comments = rebuilt_comments
953
+ return new_key
954
+
955
+ def _apply_drop(self, expr: exp.Drop) -> None:
956
+ kind = str(expr.args.get("kind") or "").upper()
957
+ cascade = bool(expr.args.get("cascade"))
958
+ for target in self._drop_targets(expr):
959
+ if kind == "TABLE":
960
+ self._drop_table(self._object_key(target), cascade=cascade)
961
+ elif kind == "VIEW":
962
+ self._drop_view(self._object_key(target), cascade=cascade)
963
+ elif kind == "INDEX":
964
+ self._drop_index(self._object_key(target))
965
+ elif kind == "SEQUENCE":
966
+ self._drop_sequence(self._object_key(target))
967
+ elif kind == "SCHEMA":
968
+ self._drop_schema(self._object_key(target))
969
+ else:
970
+ msg = f"DROP {kind or 'statements of this kind'} cannot be folded"
971
+ raise self._refusal(msg)
972
+
973
+ def _drop_table(self, key: str, *, cascade: bool) -> None:
974
+ self._require_table(key, "DROP TABLE")
975
+ self._assert_restructurable(key, "DROP TABLE")
976
+ dependent_views = self._dependent_views(key)
977
+ referencing = [
978
+ other_key
979
+ for other_key, other in self._tables.items()
980
+ if other_key != key and self._references_table(other.expr, key)
981
+ ]
982
+ if (dependent_views or referencing) and not cascade:
983
+ msg = f"DROP TABLE {key} without CASCADE while {', '.join([*dependent_views, *referencing])} depend on it"
984
+ raise self._refusal(msg)
985
+ for view_key in dependent_views:
986
+ if view_key in self._views:
987
+ self._drop_view(view_key, cascade=True)
988
+ for other_key in referencing:
989
+ self._strip_foreign_keys(other_key, key)
990
+ self._tables.pop(key)
991
+ self._forget_object(key)
992
+ for sources in self._ctas_sources.values():
993
+ sources.discard(key)
994
+
995
+ def _drop_view(self, key: str, *, cascade: bool) -> None:
996
+ if key not in self._views:
997
+ msg = f"DROP VIEW targets {key}, which is not created within the squash range"
998
+ raise self._refusal(msg)
999
+ self._assert_restructurable(key, "DROP VIEW")
1000
+ dependent_views = self._dependent_views(key)
1001
+ if dependent_views and not cascade:
1002
+ msg = f"DROP VIEW {key} without CASCADE while {', '.join(dependent_views)} depend on it"
1003
+ raise self._refusal(msg)
1004
+ for view_key in dependent_views:
1005
+ if view_key in self._views:
1006
+ self._drop_view(view_key, cascade=True)
1007
+ self._views.pop(key)
1008
+ self._forget_object(key)
1009
+
1010
+ def _drop_index(self, key: str) -> None:
1011
+ resolved_key = self._resolve_index_key(key)
1012
+ if resolved_key not in self._indexes:
1013
+ msg = f"DROP INDEX targets {key}, which is not created within the squash range"
1014
+ raise self._refusal(msg)
1015
+ self._indexes.pop(resolved_key)
1016
+ self._comments.pop(("INDEX", resolved_key), None)
1017
+
1018
+ def _drop_sequence(self, key: str) -> None:
1019
+ if key not in self._sequences:
1020
+ msg = f"DROP SEQUENCE targets {key}, which is not created within the squash range"
1021
+ raise self._refusal(msg)
1022
+ users = self._sequence_users(key)
1023
+ if users:
1024
+ msg = (
1025
+ f"DROP SEQUENCE {key} while {', '.join(users)} still reference it; the folded definitions "
1026
+ "would keep the reference to a dropped sequence"
1027
+ )
1028
+ raise self._refusal(msg)
1029
+ self._sequences.pop(key)
1030
+ self._comments.pop(("SEQUENCE", key), None)
1031
+
1032
+ def _sequence_users(self, key: str) -> list[str]:
1033
+ """Return in-range tables and views whose definitions reference sequence ``key``.
1034
+
1035
+ Covers ``nextval('seq')``-style calls (including ``'seq'::regclass`` casts),
1036
+ ``NEXT VALUE FOR seq``, and Oracle ``seq.NEXTVAL`` references.
1037
+
1038
+ Args:
1039
+ key: Catalog key of the sequence.
1040
+
1041
+ Returns:
1042
+ Keys of the tables and views that reference the sequence.
1043
+ """
1044
+ users: list[str] = []
1045
+ for relation_key, entry in [*self._tables.items(), *self._views.items()]:
1046
+ if any(self._references_sequence(node, key) for node in entry.expr.walk()):
1047
+ users.append(relation_key)
1048
+ return users
1049
+
1050
+ def _references_sequence(self, node: exp.Expr, key: str) -> bool:
1051
+ if isinstance(node, exp.NextValueFor):
1052
+ return self._sequence_name_matches(node.this, key)
1053
+ if isinstance(node, exp.Column) and node.name.upper() in _SEQUENCE_FUNCTIONS:
1054
+ owner = node.args.get("table")
1055
+ return isinstance(owner, exp.Identifier) and self._sequence_name_matches(
1056
+ exp.Table(this=owner.copy(), db=node.args.get("db")), key
1057
+ )
1058
+ if isinstance(node, exp.Literal) and node.is_string and node.find_ancestor(exp.Func) is not None:
1059
+ try:
1060
+ table = exp.to_table(node.this, dialect=self._dialect)
1061
+ except (ParseError, TokenError):
1062
+ return False
1063
+ return self._sequence_name_matches(table, key)
1064
+ return False
1065
+
1066
+ def _sequence_name_matches(self, node: exp.Expr | None, key: str) -> bool:
1067
+ if node is None:
1068
+ return False
1069
+ candidate = self._object_key(node)
1070
+ if not candidate:
1071
+ return False
1072
+ if "." in candidate and "." in key:
1073
+ return candidate == key
1074
+ return candidate.rsplit(".", 1)[-1] == key.rsplit(".", 1)[-1]
1075
+
1076
+ def _drop_schema(self, key: str) -> None:
1077
+ if key not in self._schemas:
1078
+ msg = f"DROP SCHEMA targets {key}, which is not created within the squash range"
1079
+ raise self._refusal(msg)
1080
+ prefix = f"{key}."
1081
+ contained = [
1082
+ object_key
1083
+ for object_key in [*self._tables, *self._views, *self._sequences]
1084
+ if object_key.startswith(prefix)
1085
+ ]
1086
+ if contained:
1087
+ msg = f"DROP SCHEMA {key} while {', '.join(contained)} still exist in it"
1088
+ raise self._refusal(msg)
1089
+ self._schemas.pop(key)
1090
+ self._comments.pop(("SCHEMA", key), None)
1091
+
1092
+ def _strip_foreign_keys(self, table_key: str, target_key: str) -> None:
1093
+ entry = self._tables[table_key]
1094
+ schema = self._table_schema(entry)
1095
+ self._mark_modified(entry)
1096
+ kept: list[exp.Expr] = []
1097
+ for item in schema.expressions:
1098
+ if isinstance(item, exp.ColumnDef):
1099
+ item.set(
1100
+ "constraints",
1101
+ [
1102
+ constraint
1103
+ for constraint in item.args.get("constraints") or []
1104
+ if not self._references_table(constraint, target_key)
1105
+ ],
1106
+ )
1107
+ elif self._references_table(item, target_key):
1108
+ continue
1109
+ kept.append(item)
1110
+ schema.set("expressions", kept)
1111
+
1112
+ def _forget_object(self, key: str) -> None:
1113
+ for index_key in [index_key for index_key, entry in self._indexes.items() if entry.owner == key]:
1114
+ self._indexes.pop(index_key)
1115
+ self._comments.pop(("INDEX", index_key), None)
1116
+ prefix = f"{key}."
1117
+ stale_comments = [
1118
+ comment_key
1119
+ for comment_key in self._comments
1120
+ if (comment_key[0] != "COLUMN" and comment_key[1] == key)
1121
+ or (comment_key[0] == "COLUMN" and comment_key[1].startswith(prefix))
1122
+ ]
1123
+ for comment_key in stale_comments:
1124
+ self._comments.pop(comment_key)
1125
+
1126
+ def _apply_comment(self, expr: exp.Comment) -> None:
1127
+ kind = str(expr.args.get("kind") or "").upper()
1128
+ target = expr.this
1129
+ if not isinstance(target, exp.Expr):
1130
+ msg = "the COMMENT target could not be read"
1131
+ raise self._refusal(msg)
1132
+ if kind == "COLUMN" and isinstance(target, exp.Column):
1133
+ table_key = self._object_key(
1134
+ exp.Table(this=target.args.get("table"), db=target.args.get("db"), catalog=target.args.get("catalog"))
1135
+ )
1136
+ column_key = self._name_key(target)
1137
+ table_entry = self._require_table(table_key, "COMMENT ON COLUMN")
1138
+ if self._find_column(self._table_schema(table_entry), column_key) is None:
1139
+ msg = f"column {column_key} does not exist on {table_key}"
1140
+ raise self._refusal(msg)
1141
+ key = f"{table_key}.{column_key}"
1142
+ elif kind == "INDEX":
1143
+ raw_key = self._object_key(target)
1144
+ key = self._resolve_index_key(raw_key)
1145
+ if key not in self._indexes:
1146
+ msg = f"COMMENT ON INDEX targets {raw_key}, which is not created within the squash range"
1147
+ raise self._refusal(msg)
1148
+ else:
1149
+ key = self._object_key(target)
1150
+ catalogs = {
1151
+ "TABLE": self._tables,
1152
+ "VIEW": self._views,
1153
+ "MATERIALIZED VIEW": self._views,
1154
+ "SEQUENCE": self._sequences,
1155
+ "SCHEMA": self._schemas,
1156
+ }
1157
+ catalog = catalogs.get(kind)
1158
+ if catalog is None:
1159
+ msg = f"COMMENT ON {kind or 'objects of this kind'} cannot be folded"
1160
+ raise self._refusal(msg)
1161
+ if key not in catalog:
1162
+ msg = f"COMMENT ON {kind} targets {key}, which is not created within the squash range"
1163
+ raise self._refusal(msg)
1164
+ self._comments[kind, key] = self._new_entry(expr)
1165
+
1166
+ def _apply_dml(self, expr: exp.Expr) -> None:
1167
+ targets = self._dml_targets(expr)
1168
+ if not targets:
1169
+ msg = "the DML target table could not be read"
1170
+ raise self._refusal(msg)
1171
+ target_keys: list[str] = []
1172
+ for target in targets:
1173
+ key = self._object_key(target)
1174
+ if key not in self._tables:
1175
+ msg = f"DML targets {key}, which is not a table created within the squash range"
1176
+ raise self._refusal(msg)
1177
+ target_keys.append(key)
1178
+ target_ids = {id(target) for target in targets}
1179
+ cte_names = self._cte_names(expr)
1180
+ sources = [
1181
+ self._object_key(table)
1182
+ for table in expr.find_all(exp.Table)
1183
+ if id(table) not in target_ids and self._is_relation_reference(table, cte_names)
1184
+ ]
1185
+ entry = self._new_entry(expr)
1186
+ for key in self._expand_dependencies([*target_keys, *sources]):
1187
+ if key in self._tables or key in self._views:
1188
+ self._dml_touched.setdefault(key, entry)
1189
+ for key in target_keys:
1190
+ self._dml_written.setdefault(key, entry)
1191
+ self._dml.append(entry)
1192
+
1193
+ def _assert_restructurable(self, key: str, label: str) -> None:
1194
+ touched = self._dml_touched.get(key)
1195
+ if touched is not None:
1196
+ msg = (
1197
+ f"{label} changes {key} after DML in migration {touched.origin or '<unknown>'} "
1198
+ f"('{self._snippet(touched.text)}') uses it; the folded migration would replay that DML "
1199
+ "against the final shape"
1200
+ )
1201
+ raise self._refusal(msg)
1202
+ readers = self._ctas_sources.get(key)
1203
+ if readers:
1204
+ msg = f"{label} changes {key} after CREATE TABLE AS SELECT for {', '.join(sorted(readers))} reads it"
1205
+ raise self._refusal(msg)
1206
+
1207
+ def _assert_views_allow(self, table_key: str, columns: set[str] | None, label: str) -> None:
1208
+ for view_key in self._dependent_views(table_key):
1209
+ query = self._views[view_key].expr.expression
1210
+ if columns is None:
1211
+ msg = f"{label} on {table_key} would have to rewrite view {view_key}, which depends on it"
1212
+ raise self._refusal(msg)
1213
+ if not isinstance(query, exp.Expr):
1214
+ continue
1215
+ uses_star = any(not isinstance(star.parent, exp.Count) for star in query.find_all(exp.Star))
1216
+ if uses_star or self._column_names(query) & columns:
1217
+ msg = f"{label} on {table_key} changes columns that view {view_key} selects"
1218
+ raise self._refusal(msg)
1219
+
1220
+ def _require_table(self, key: str, label: str) -> "_FoldedStatement":
1221
+ entry = self._tables.get(key)
1222
+ if entry is None:
1223
+ msg = f"{label} targets {key}, which is not a table created within the squash range"
1224
+ raise self._refusal(msg)
1225
+ return entry
1226
+
1227
+ def _new_entry(self, expr: exp.Expr, owner: str = "") -> "_FoldedStatement":
1228
+ self._order += 1
1229
+ return _FoldedStatement(
1230
+ expr.copy(), self._current_text, self._current_origin, self._order, self._current_faithful, owner
1231
+ )
1232
+
1233
+ def _mark_modified(self, entry: "_FoldedStatement") -> None:
1234
+ if not entry.faithful:
1235
+ msg = (
1236
+ f"it rewrites the statement from migration {entry.origin or '<unknown>'} "
1237
+ f"('{self._snippet(entry.text)}'), which SQLGlot does not reproduce faithfully"
1238
+ )
1239
+ raise self._refusal(msg)
1240
+ entry.modified = True
1241
+
1242
+ def _ordered_relation_keys(self) -> list[str]:
1243
+ entries: dict[str, _FoldedStatement] = {**self._tables, **self._views}
1244
+ keys = sorted(entries, key=lambda key: entries[key].order)
1245
+ dependencies = {key: self._relation_dependencies(key, entries) for key in keys}
1246
+ ordered: list[str] = []
1247
+ state: dict[str, int] = {}
1248
+ for root in keys:
1249
+ if root in state:
1250
+ continue
1251
+ state[root] = 1
1252
+ stack: list[tuple[str, int]] = [(root, 0)]
1253
+ while stack:
1254
+ node, position = stack[-1]
1255
+ node_dependencies = dependencies[node]
1256
+ if position < len(node_dependencies):
1257
+ stack[-1] = (node, position + 1)
1258
+ dependency = node_dependencies[position]
1259
+ dependency_state = state.get(dependency, 0)
1260
+ if dependency_state == 1:
1261
+ msg = (
1262
+ f"{node} and {dependency} depend on each other, which CREATE statements cannot express "
1263
+ "without separate ALTER statements"
1264
+ )
1265
+ raise self._refusal(msg, entries[node])
1266
+ if dependency_state == 0:
1267
+ state[dependency] = 1
1268
+ stack.append((dependency, 0))
1269
+ else:
1270
+ stack.pop()
1271
+ state[node] = 2
1272
+ ordered.append(node)
1273
+ return ordered
1274
+
1275
+ def _relation_dependencies(self, key: str, entries: "dict[str, _FoldedStatement]") -> list[str]:
1276
+ entry = entries[key]
1277
+ found: list[str] = []
1278
+ query = entry.expr.expression
1279
+ if isinstance(query, exp.Query):
1280
+ found.extend(self._query_sources(query))
1281
+ if key in self._tables:
1282
+ for reference in entry.expr.find_all(exp.Reference):
1283
+ ref_table = self._reference_table(reference)
1284
+ if ref_table is not None:
1285
+ found.append(self._resolve_reference_key(ref_table))
1286
+ unique = {dependency for dependency in found if dependency != key and dependency in entries}
1287
+ return sorted(unique, key=lambda dependency: entries[dependency].order)
1288
+
1289
+ def _dependent_views(self, key: str) -> list[str]:
1290
+ return [
1291
+ view_key
1292
+ for view_key, view in self._views.items()
1293
+ if view_key != key
1294
+ and isinstance(view.expr.expression, exp.Query)
1295
+ and key in self._query_sources(view.expr.expression)
1296
+ ]
1297
+
1298
+ def _expand_dependencies(self, keys: Iterable[str]) -> list[str]:
1299
+ expanded: list[str] = []
1300
+ pending = list(keys)
1301
+ while pending:
1302
+ key = pending.pop()
1303
+ if key in expanded:
1304
+ continue
1305
+ expanded.append(key)
1306
+ view = self._views.get(key)
1307
+ if view is not None and isinstance(view.expr.expression, exp.Query):
1308
+ pending.extend(self._query_sources(view.expr.expression))
1309
+ return expanded
1310
+
1311
+ def _query_sources(self, query: exp.Expr) -> list[str]:
1312
+ cte_names = self._cte_names(query)
1313
+ sources: list[str] = []
1314
+ for table in query.find_all(exp.Table):
1315
+ if self._is_relation_reference(table, cte_names):
1316
+ key = self._object_key(table)
1317
+ if key not in sources:
1318
+ sources.append(key)
1319
+ return sources
1320
+
1321
+ def _cte_names(self, node: exp.Expr) -> set[str]:
1322
+ names: set[str] = set()
1323
+ for cte in node.find_all(exp.CTE):
1324
+ alias = cte.args.get("alias")
1325
+ if isinstance(alias, exp.TableAlias) and isinstance(alias.this, exp.Identifier):
1326
+ names.add(self._ident_key(alias.this))
1327
+ return names
1328
+
1329
+ def _is_relation_reference(self, table: exp.Table, cte_names: set[str]) -> bool:
1330
+ if not isinstance(table.this, exp.Identifier):
1331
+ return False
1332
+ return bool(table.args.get("db")) or self._ident_key(table.this) not in cte_names
1333
+
1334
+ def _references_table(self, node: exp.Expr, target_key: str) -> bool:
1335
+ for reference in node.find_all(exp.Reference):
1336
+ ref_table = self._reference_table(reference)
1337
+ if ref_table is not None and self._resolve_reference_key(ref_table) == target_key:
1338
+ return True
1339
+ return False
1340
+
1341
+ def _referenced_columns(self, expr: exp.Expr, target_key: str) -> set[str]:
1342
+ columns: set[str] = set()
1343
+ for reference in expr.find_all(exp.Reference):
1344
+ ref_table = self._reference_table(reference)
1345
+ if ref_table is None or self._resolve_reference_key(ref_table) != target_key:
1346
+ continue
1347
+ ref_schema = reference.this
1348
+ if isinstance(ref_schema, exp.Schema) and ref_schema.expressions:
1349
+ columns.update(self._name_key(ident) for ident in ref_schema.expressions)
1350
+ else:
1351
+ columns.update(self._primary_key_columns(target_key))
1352
+ return columns
1353
+
1354
+ def _foreign_reference_idents(self, expr: exp.Expr, target_key: str) -> list[exp.Identifier]:
1355
+ idents: list[exp.Identifier] = []
1356
+ for reference in expr.find_all(exp.Reference):
1357
+ ref_table = self._reference_table(reference)
1358
+ ref_schema = reference.this
1359
+ if (
1360
+ ref_table is not None
1361
+ and isinstance(ref_schema, exp.Schema)
1362
+ and self._resolve_reference_key(ref_table) == target_key
1363
+ ):
1364
+ idents.extend(ident for ident in ref_schema.expressions if isinstance(ident, exp.Identifier))
1365
+ return idents
1366
+
1367
+ def _primary_key_columns(self, table_key: str) -> set[str]:
1368
+ entry = self._tables.get(table_key)
1369
+ if entry is None:
1370
+ return set()
1371
+ columns: set[str] = set()
1372
+ for item in self._table_schema(entry).expressions:
1373
+ if isinstance(item, exp.ColumnDef):
1374
+ if any(
1375
+ isinstance(c.args.get("kind"), exp.PrimaryKeyColumnConstraint)
1376
+ for c in item.args.get("constraints") or []
1377
+ ):
1378
+ columns.add(self._name_key(item))
1379
+ elif isinstance(item, exp.PrimaryKey) or (
1380
+ isinstance(item, exp.Constraint) and any(isinstance(sub, exp.PrimaryKey) for sub in item.expressions)
1381
+ ):
1382
+ columns.update(self._local_column_keys(item, table_key))
1383
+ return columns
1384
+
1385
+ def _has_multi_column_index_or_unique(self, table_key: str, schema: exp.Schema, column_key: str) -> bool:
1386
+ for index_entry in self._indexes.values():
1387
+ if index_entry.owner == table_key:
1388
+ index_cols = self._index_column_keys(index_entry)
1389
+ if column_key in index_cols and len(index_cols) > 1:
1390
+ return True
1391
+ for item in schema.expressions:
1392
+ if isinstance(item, exp.ColumnDef):
1393
+ continue
1394
+ if item.find(exp.UniqueColumnConstraint, exp.IndexColumnConstraint) is not None:
1395
+ local_cols = self._local_column_keys(item, table_key)
1396
+ if column_key in local_cols and len(local_cols) > 1:
1397
+ return True
1398
+ return False
1399
+
1400
+ def _local_column_keys(self, node: exp.Expr, owner_key: str) -> set[str]:
1401
+ return {self._ident_key(ident) for ident in self._local_column_refs(node, owner_key)}
1402
+
1403
+ def _local_column_refs(self, node: exp.Expr, owner_key: str) -> list[exp.Identifier]:
1404
+ """Return identifiers inside a table item that name columns of the owning table.
1405
+
1406
+ Args:
1407
+ node: A column definition, column constraint, or table-level constraint.
1408
+ owner_key: Catalog key of the table that owns ``node``.
1409
+
1410
+ Returns:
1411
+ Identifier nodes that refer to columns of ``owner_key``, including self-referencing
1412
+ foreign key targets but excluding columns of other referenced tables.
1413
+ """
1414
+ refs: list[exp.Identifier] = []
1415
+ for ident in node.find_all(exp.Identifier):
1416
+ parent = ident.parent
1417
+ if isinstance(parent, exp.Column):
1418
+ if parent.this is ident and parent.find_ancestor(exp.Reference) is None:
1419
+ refs.append(ident)
1420
+ elif isinstance(parent, exp.Schema):
1421
+ if (
1422
+ parent.this is None
1423
+ or (
1424
+ isinstance(parent.parent, (exp.UniqueColumnConstraint, exp.IndexColumnConstraint))
1425
+ and ident.arg_key == "expressions"
1426
+ )
1427
+ or (
1428
+ isinstance(parent.parent, exp.Reference)
1429
+ and isinstance(parent.this, exp.Table)
1430
+ and self._resolve_reference_key(parent.this) == owner_key
1431
+ )
1432
+ ):
1433
+ refs.append(ident)
1434
+ elif isinstance(parent, (exp.ForeignKey, exp.PrimaryKey)) and ident.arg_key == "expressions":
1435
+ refs.append(ident)
1436
+ return refs
1437
+
1438
+ def _index_column_refs(self, entry: "_FoldedStatement") -> list[exp.Identifier]:
1439
+ index = entry.expr.this
1440
+ params = index.args.get("params") if isinstance(index, exp.Index) else None
1441
+ if not isinstance(params, exp.Expr):
1442
+ return []
1443
+ return [column.this for column in params.find_all(exp.Column) if isinstance(column.this, exp.Identifier)]
1444
+
1445
+ def _index_column_keys(self, entry: "_FoldedStatement") -> set[str]:
1446
+ return {self._ident_key(ident) for ident in self._index_column_refs(entry)}
1447
+
1448
+ def _column_names(self, node: exp.Expr) -> set[str]:
1449
+ return {self._name_key(column) for column in node.find_all(exp.Column) if column.name}
1450
+
1451
+ def _find_column(self, schema: exp.Schema, column_key: str) -> exp.ColumnDef | None:
1452
+ for item in schema.expressions:
1453
+ if isinstance(item, exp.ColumnDef) and self._name_key(item) == column_key:
1454
+ return item
1455
+ return None
1456
+
1457
+ def _resolve_reference_key(self, table: exp.Table) -> str:
1458
+ key = self._object_key(table)
1459
+ if key in self._tables or table.args.get("db"):
1460
+ return key
1461
+ candidates = [candidate for candidate in self._tables if candidate.rsplit(".", 1)[-1] == key]
1462
+ return candidates[0] if len(candidates) == 1 else key
1463
+
1464
+ def _relation(self, key: str) -> "_FoldedStatement":
1465
+ entry = self._tables.get(key)
1466
+ return entry if entry is not None else self._views[key]
1467
+
1468
+ def _render(self, entry: "_FoldedStatement") -> str:
1469
+ if not entry.modified:
1470
+ return _ensure_semicolon(entry.text)
1471
+ return self._render_expr(entry.expr, entry)
1472
+
1473
+ def _render_drop(self, entry: "_FoldedStatement", kind: str, *, materialized: bool = False) -> str:
1474
+ target = entry.expr.this.this if isinstance(entry.expr.this, exp.Schema) else entry.expr.this
1475
+ if not isinstance(target, exp.Expr):
1476
+ msg = "the dropped object name could not be read"
1477
+ raise self._refusal(msg, entry)
1478
+ drop = exp.Drop(tables=[target.copy()], kind=kind, exists=True, materialized=materialized)
1479
+ return self._render_expr(drop, entry)
1480
+
1481
+ def _render_expr(self, expr: exp.Expr, entry: "_FoldedStatement") -> str:
1482
+ try:
1483
+ sql = expr.sql(dialect=self._dialect, unsupported_level=ErrorLevel.RAISE)
1484
+ except UnsupportedError as error:
1485
+ msg = f"SQLGlot cannot render it for this dialect ({error})"
1486
+ raise with_cause(self._refusal(msg, entry), error) from error
1487
+ return _ensure_semicolon(sql)
1488
+
1489
+ def _is_faithful(self, expr: exp.Expr, tokens: list[Token], spans: list[tuple[exp.Expr, str, int, int]]) -> bool:
1490
+ """Return whether rendering ``expr`` reproduces the original statement faithfully.
1491
+
1492
+ Declared column data types are compared as parsed type nodes rendered for the dialect,
1493
+ so column type synonyms (``VARCHAR`` versus SQLite ``TEXT``) are faithful while rewrites
1494
+ that change a column definition (Postgres ``SERIAL`` becoming an identity column) are not.
1495
+ Column type spans are then masked on both sides, while non-column types (such as ``CAST``
1496
+ targets inside ``DEFAULT`` or ``CHECK`` expressions) remain unmasked so dialect rewrites
1497
+ that alter runtime evaluation are rejected. Every other keyword token type of the original
1498
+ must appear in the rendering (allowing a small set of synonyms) and every identifier,
1499
+ literal, and non-function word must survive. Function names may be canonicalized because
1500
+ SQLGlot maps them to equivalent spellings.
1501
+
1502
+ Args:
1503
+ expr: Parsed statement, unchanged on return.
1504
+ tokens: Original tokens of the statement.
1505
+ spans: Declared column type spans from :meth:`_column_type_spans`.
1506
+
1507
+ Returns:
1508
+ True when the rendering is faithful to the original text.
1509
+ """
1510
+ try:
1511
+ rendered = expr.sql(dialect=self._dialect, unsupported_level=ErrorLevel.IGNORE)
1512
+ reparsed = [node for node in self._dialect_impl.parse(rendered) if node is not None]
1513
+ except (ParseError, TokenError):
1514
+ return False
1515
+ if self._type_signature([expr]) != self._type_signature(reparsed):
1516
+ return False
1517
+ original_kinds = [(node, arg_key, node.args.get(arg_key)) for node, arg_key, _, _ in spans]
1518
+ for node, arg_key, _ in original_kinds:
1519
+ node.set(arg_key, exp.DataType(this=exp.DataType.Type.USERDEFINED, kind=_TYPE_PLACEHOLDER))
1520
+ try:
1521
+ masked = expr.sql(dialect=self._dialect, unsupported_level=ErrorLevel.IGNORE)
1522
+ finally:
1523
+ for node, arg_key, kind in original_kinds:
1524
+ node.set(arg_key, kind)
1525
+ try:
1526
+ masked_tokens = self._dialect_impl.tokenize(masked)
1527
+ except TokenError:
1528
+ return False
1529
+ skipped = {position for _, _, first, last in spans for position in range(first, last + 1)}
1530
+ original_types, original_words = self._token_signature([
1531
+ token for position, token in enumerate(tokens) if position not in skipped
1532
+ ])
1533
+ original_words[_TYPE_PLACEHOLDER] += len(spans)
1534
+ rendered_types, rendered_words = self._token_signature(masked_tokens)
1535
+ for token_type in original_types - rendered_types:
1536
+ equivalent = _EQUIVALENT_TOKEN_TYPES.get(token_type)
1537
+ if equivalent is None or equivalent not in rendered_types:
1538
+ return False
1539
+ return not original_words - rendered_words
1540
+
1541
+ def _type_signature(self, expressions: list[exp.Expr]) -> "Counter[str]":
1542
+ return Counter(
1543
+ data_type.sql(dialect=self._dialect) for node in expressions for data_type in node.find_all(exp.DataType)
1544
+ )
1545
+
1546
+ def _refusal(self, reason: str, entry: "_FoldedStatement | None" = None) -> SquashValidationError:
1547
+ text = entry.text if entry is not None else self._current_text
1548
+ origin = entry.origin if entry is not None else self._current_origin
1549
+ location = f"migration {origin} statement" if origin else "statement"
1550
+ return SquashValidationError(
1551
+ f"Cannot fold {location} '{self._snippet(text)}' with the ddl squash strategy: {reason}. {_CONCAT_HINT}"
1552
+ )
1553
+
1554
+ def _object_key(self, node: exp.Expr | None) -> str:
1555
+ target = node.this if isinstance(node, exp.Schema) else node
1556
+ if target is None:
1557
+ return ""
1558
+ if isinstance(target, exp.Table):
1559
+ parts = [target.args.get("catalog"), target.args.get("db"), target.this]
1560
+ keys = [self._part_key(part) for part in parts if isinstance(part, exp.Expr)]
1561
+ return ".".join(key for key in keys if key)
1562
+ return self._part_key(target)
1563
+
1564
+ def _part_key(self, part: exp.Expr) -> str:
1565
+ if isinstance(part, exp.Identifier):
1566
+ return self._ident_key(part)
1567
+ return part.name.lower()
1568
+
1569
+ def _name_key(self, node: exp.Expr | None) -> str:
1570
+ if node is None:
1571
+ return ""
1572
+ if isinstance(node, exp.Identifier):
1573
+ return self._ident_key(node)
1574
+ if isinstance(node.this, exp.Identifier):
1575
+ return self._ident_key(node.this)
1576
+ return node.name.lower()
1577
+
1578
+ def _ident_key(self, ident: exp.Identifier) -> str:
1579
+ return self._dialect_impl.normalize_identifier(ident.copy()).name
1580
+
1581
+ def _index_catalog_key(self, base_name: str, table_key: str) -> str:
1582
+ if (self._dialect or "") in _MYSQL_FAMILY | {"tsql", "mssql"}:
1583
+ return f"{table_key}.{base_name}"
1584
+ if "." in table_key:
1585
+ schema_prefix = table_key.rsplit(".", 1)[0]
1586
+ return f"{schema_prefix}.{base_name}"
1587
+ return base_name
1588
+
1589
+ def _resolve_index_key(self, target_key: str, *, owner: str | None = None) -> str:
1590
+ if owner is not None:
1591
+ scoped_key = self._index_catalog_key(target_key.rsplit(".", 1)[-1], owner)
1592
+ if scoped_key in self._indexes:
1593
+ return scoped_key
1594
+ if target_key in self._indexes:
1595
+ return target_key
1596
+ if "." not in target_key:
1597
+ matches = [
1598
+ key
1599
+ for key, entry in self._indexes.items()
1600
+ if key.rsplit(".", 1)[-1] == target_key and (owner is None or entry.owner == owner)
1601
+ ]
1602
+ if len(matches) == 1:
1603
+ return matches[0]
1604
+ if len(matches) > 1:
1605
+ msg = f"index reference {target_key} is ambiguous across {', '.join(matches)}"
1606
+ raise self._refusal(msg)
1607
+ return target_key
1608
+
1609
+ @staticmethod
1610
+ def _token_signature(tokens: list[Token]) -> tuple[set[TokenType], "Counter[str]"]:
1611
+ """Return keyword token types and words for non-masked statement tokens."""
1612
+ types: set[TokenType] = set()
1613
+ words: Counter[str] = Counter()
1614
+ for position, token in enumerate(tokens):
1615
+ token_type = token.token_type
1616
+ if token_type == TokenType.SEMICOLON:
1617
+ continue
1618
+ if token_type not in _TEXT_TOKEN_TYPES:
1619
+ types.add(token_type)
1620
+ continue
1621
+ next_type = tokens[position + 1].token_type if position + 1 < len(tokens) else None
1622
+ if token_type == TokenType.VAR and next_type == TokenType.L_PAREN:
1623
+ continue
1624
+ words[token.text if token_type in _CASE_SENSITIVE_TOKEN_TYPES else token.text.lower()] += 1
1625
+ return types, words
1626
+
1627
+ @staticmethod
1628
+ def _snippet(text: str) -> str:
1629
+ collapsed = " ".join(text.split())
1630
+ if len(collapsed) > _SNIPPET_LENGTH:
1631
+ return f"{collapsed[: _SNIPPET_LENGTH - 3]}..."
1632
+ return collapsed
1633
+
1634
+ @staticmethod
1635
+ def _table_schema(entry: "_FoldedStatement") -> exp.Schema:
1636
+ schema = entry.expr.this
1637
+ if not isinstance(schema, exp.Schema):
1638
+ schema = exp.Schema(this=entry.expr.this, expressions=[])
1639
+ entry.expr.set("this", schema)
1640
+ return schema
1641
+
1642
+ @staticmethod
1643
+ def _set_create_table_node(create_expr: exp.Expr, new_table: exp.Table) -> None:
1644
+ if isinstance(create_expr.this, exp.Schema):
1645
+ create_expr.this.set("this", new_table)
1646
+ else:
1647
+ create_expr.set("this", new_table)
1648
+
1649
+ @staticmethod
1650
+ def _reference_table(reference: exp.Reference) -> exp.Table | None:
1651
+ target = reference.this.this if isinstance(reference.this, exp.Schema) else reference.this
1652
+ return target if isinstance(target, exp.Table) else None
1653
+
1654
+ @staticmethod
1655
+ def _is_materialized(entry: "_FoldedStatement") -> bool:
1656
+ return entry.expr.find(exp.MaterializedProperty) is not None
1657
+
1658
+ @staticmethod
1659
+ def _drop_targets(expr: exp.Drop) -> list[exp.Expr]:
1660
+ targets: list[exp.Expr] = [target for target in expr.args.get("tables") or [] if isinstance(target, exp.Expr)]
1661
+ if isinstance(expr.this, exp.Expr) and all(target is not expr.this for target in targets):
1662
+ targets.append(expr.this)
1663
+ return targets
1664
+
1665
+ @staticmethod
1666
+ def _dml_targets(expr: exp.Expr) -> list[exp.Table]:
1667
+ if isinstance(expr, exp.TruncateTable):
1668
+ return [table for table in expr.expressions if isinstance(table, exp.Table)]
1669
+ target = expr.this.this if isinstance(expr.this, exp.Schema) else expr.this
1670
+ return [target] if isinstance(target, exp.Table) else []
1671
+
1672
+
1673
+ @dataclass(slots=True)
1674
+ class SquashPlan:
1675
+ """Represents a planned squash operation."""
1676
+
1677
+ source_migrations: list[tuple[str, Path]]
1678
+ """List of (version, path) tuples for migrations being squashed."""
1679
+ target_version: str
1680
+ """The version string for the squashed migration."""
1681
+ target_path: Path
1682
+ """Output file path for the squashed migration."""
1683
+ description: str
1684
+ """Combined description for the squashed migration."""
1685
+ source_versions: list[str]
1686
+ """List of version strings being replaced (for tracking table updates)."""
1687
+ transactional: bool | None = None
1688
+ """Optional transactional directive preserved from source SQL migrations."""
1689
+ schema: str | None = None
1690
+ """Optional schema directive preserved from source SQL migrations."""
1691
+ strategy: str = "concat"
1692
+ """Squash strategy ("concat", "ddl", or "schema")."""
1693
+ schema_ddl_up: list[str] | None = None
1694
+ """Optional pre-extracted schema CREATE DDL statements."""
1695
+ schema_ddl_down: list[str] | None = None
1696
+ """Optional pre-extracted schema DROP DDL statements."""
1697
+ missing_down_versions: list[str] | None = None
1698
+ """Optional list of source versions that lacked a down block."""
1699
+
1700
+
1701
+ class MigrationSquasher:
1702
+ """Core squash engine for combining migrations.
1703
+
1704
+ Provides functionality to plan, validate, and execute migration squash operations.
1705
+ Combines multiple sequential or timestamped migrations into a single file.
1706
+ """
1707
+
1708
+ __slots__ = ("backup_path", "migrations_path", "runner", "strategy", "template_settings", "version_table")
1709
+
1710
+ def __init__(
1711
+ self,
1712
+ migrations_path: Path,
1713
+ runner: "SyncMigrationRunner",
1714
+ template_settings: "MigrationTemplateSettings | None" = None,
1715
+ *,
1716
+ strategy: str = "concat",
1717
+ version_table: str = "ddl_migrations",
1718
+ ) -> None:
1719
+ """Initialize the migration squasher.
1720
+
1721
+ Args:
1722
+ migrations_path: Path to the migrations directory.
1723
+ runner: SyncMigrationRunner instance for loading migrations.
1724
+ template_settings: Optional template settings for generating squashed file.
1725
+ strategy: Default squash strategy ("concat", "ddl", or "schema").
1726
+ version_table: Migration tracking table excluded from live "schema" extraction.
1727
+ """
1728
+ self.migrations_path = migrations_path
1729
+ self.runner = runner
1730
+ self.template_settings = template_settings
1731
+ self.backup_path: Path | None = None
1732
+ self.strategy = self._resolve_strategy(strategy)
1733
+ self.version_table = version_table
1734
+
1735
+ def plan_squash(
1736
+ self,
1737
+ start_version: str,
1738
+ end_version: str,
1739
+ description: str,
1740
+ *,
1741
+ allow_gaps: bool = False,
1742
+ output_format: str = "sql",
1743
+ strategy: str | None = None,
1744
+ single_file: bool | None = None,
1745
+ schema_ddl: tuple[list[str], list[str]] | None = None,
1746
+ ) -> list[SquashPlan]:
1747
+ """Plan a squash operation for a range of migrations.
1748
+
1749
+ Args:
1750
+ start_version: First version in the range to squash (inclusive).
1751
+ end_version: Last version in the range to squash (inclusive).
1752
+ description: Description for the squashed migration file.
1753
+ allow_gaps: If True, allow gaps in version sequence.
1754
+ output_format: Output file format ("sql" or "py").
1755
+ strategy: Squash strategy override ("concat", "ddl", or "schema").
1756
+ single_file: When True, require a single SquashPlan (raising if directives or
1757
+ file types conflict); when False or None, split when directives or file types change.
1758
+ schema_ddl: Optional pre-fetched (up_ddl, down_ddl) tuple for "schema" strategy.
1759
+
1760
+ Returns:
1761
+ List of SquashPlan objects with details of planned operations.
1762
+ """
1763
+ resolved_strategy = self._resolve_strategy(strategy or self.strategy)
1764
+ all_migrations = self.runner.get_migration_files()
1765
+ source_migrations = validate_squash_range(all_migrations, start_version, end_version, allow_gaps=allow_gaps)
1766
+ parsed_start = parse_version(start_version)
1767
+
1768
+ if resolved_strategy == "schema":
1769
+ stream_migrations = _stream_migrations(all_migrations, parsed_start.extension)
1770
+ if (
1771
+ not stream_migrations
1772
+ or source_migrations[0][0] != stream_migrations[0][0]
1773
+ or source_migrations[-1][0] != stream_migrations[-1][0]
1774
+ or len(source_migrations) != len(stream_migrations)
1775
+ ):
1776
+ first_ver = stream_migrations[0][0] if stream_migrations else start_version
1777
+ last_ver = stream_migrations[-1][0] if stream_migrations else end_version
1778
+ msg = (
1779
+ "The schema squash strategy reflects the full current database schema and must squash from the "
1780
+ f"first migration ({first_ver}) through head ({last_ver})."
1781
+ )
1782
+ raise SquashValidationError(msg)
1783
+
1784
+ safe_description = slugify(description, separator="_")[:50] or "migration"
1785
+
1786
+ if output_format == "py":
1787
+ tx_dir, schema_dir = _coalesce_sql_directives(source_migrations)
1788
+ if tx_dir is not None or schema_dir is not None:
1789
+ msg = (
1790
+ "Cannot squash SQL migrations with '-- transactional:' or '-- schema:' directives into a Python "
1791
+ "migration because Python migrations do not support SQL header directives."
1792
+ )
1793
+ raise SquashValidationError(msg)
1794
+ if single_file is False:
1795
+ directive_groups: list[tuple[str, bool | None, str | None, list[tuple[str, Path]]]] = [
1796
+ ("py", None, None, grp) for _, _, _, grp in _group_migrations_with_directives(source_migrations)
1797
+ ]
1798
+ else:
1799
+ directive_groups = [("py", None, None, source_migrations)]
1800
+ elif single_file is True:
1801
+ file_type = "py" if all(p.suffix == ".py" for _, p in source_migrations) else "sql"
1802
+ tx_dir, schema_dir = _coalesce_sql_directives(source_migrations) if file_type == "sql" else (None, None)
1803
+ directive_groups = [(file_type, tx_dir, schema_dir, source_migrations)]
1804
+ else:
1805
+ directive_groups = _group_migrations_with_directives(source_migrations)
1806
+
1807
+ if resolved_strategy == "schema" and len(directive_groups) > 1:
1808
+ msg = (
1809
+ "The schema squash strategy emits a single full-schema migration and cannot split across multiple "
1810
+ "files with differing file types or directives."
1811
+ )
1812
+ raise SquashValidationError(msg)
1813
+
1814
+ if parsed_start.sequence is not None:
1815
+ version_counter = parsed_start.sequence
1816
+ else:
1817
+ prior_sequences: list[int] = []
1818
+ for ver_str, _ in all_migrations:
1819
+ try:
1820
+ parsed_ver = parse_version(ver_str)
1821
+ except ValueError:
1822
+ continue
1823
+ if (
1824
+ parsed_ver.extension == parsed_start.extension
1825
+ and parsed_ver < parsed_start
1826
+ and parsed_ver.sequence is not None
1827
+ ):
1828
+ prior_sequences.append(parsed_ver.sequence)
1829
+ version_counter = (max(prior_sequences) + 1) if prior_sequences else 1
1830
+
1831
+ ext_prefix = f"ext_{parsed_start.extension}_" if parsed_start.extension else ""
1832
+
1833
+ plans: list[SquashPlan] = []
1834
+
1835
+ for file_type, transactional, schema, group_migrations in directive_groups:
1836
+ group_versions = [v for v, _ in group_migrations]
1837
+ target_version = f"{ext_prefix}{_format_sequential_version(version_counter)}"
1838
+ extension = ".py" if file_type == "py" else ".sql"
1839
+ target_path = self.migrations_path / f"{target_version}_{safe_description}{extension}"
1840
+
1841
+ plans.append(
1842
+ SquashPlan(
1843
+ source_migrations=group_migrations,
1844
+ target_version=target_version,
1845
+ target_path=target_path,
1846
+ description=description,
1847
+ source_versions=group_versions,
1848
+ transactional=transactional,
1849
+ schema=schema,
1850
+ strategy=resolved_strategy,
1851
+ schema_ddl_up=list(schema_ddl[0]) if schema_ddl is not None else None,
1852
+ schema_ddl_down=list(schema_ddl[1]) if schema_ddl is not None else None,
1853
+ )
1854
+ )
1855
+ version_counter += 1
1856
+
1857
+ return plans
1858
+
1859
+ def extract_sql(
1860
+ self,
1861
+ migrations: list[tuple[str, Path]],
1862
+ *,
1863
+ strategy: str | None = None,
1864
+ dialect: str | None = None,
1865
+ schema_ddl: tuple[list[str], list[str]] | None = None,
1866
+ ) -> tuple[list[str], list[str]]:
1867
+ """Extract UP and DOWN SQL statements from migrations.
1868
+
1869
+ Args:
1870
+ migrations: List of (version, path) tuples to extract SQL from.
1871
+ strategy: Optional strategy ("concat", "ddl", or "schema"). When None,
1872
+ returns the raw UP statements and the reversed raw DOWN statements.
1873
+ dialect: Optional SQLGlot dialect name for DDL folding.
1874
+ schema_ddl: Optional pre-fetched (up_ddl, down_ddl) tuple for "schema" strategy.
1875
+
1876
+ Returns:
1877
+ Tuple of (up_statements, down_statements) lists.
1878
+ """
1879
+ if strategy is None:
1880
+ up_entries, down_statements, _ = self._extract_raw_sql(migrations)
1881
+ return [sql for _, sql in up_entries], down_statements
1882
+ up_statements, down_statements, _ = self._extract_with_strategy(
1883
+ migrations, self._resolve_strategy(strategy), dialect=dialect, schema_ddl=schema_ddl
1884
+ )
1885
+ return up_statements, down_statements
1886
+
1887
+ def extract_plan_sql(self, plan: SquashPlan) -> tuple[list[str], list[str]]:
1888
+ """Extract the UP and DOWN SQL for a squash plan using the plan's strategy.
1889
+
1890
+ Records versions lacking a down block on ``plan.missing_down_versions`` when the
1891
+ squashed migration is irreversible.
1892
+
1893
+ Args:
1894
+ plan: The SquashPlan to extract SQL for.
1895
+
1896
+ Returns:
1897
+ Tuple of (up_statements, down_statements) lists.
1898
+ """
1899
+ plan_schema_ddl = (plan.schema_ddl_up, plan.schema_ddl_down or []) if plan.schema_ddl_up is not None else None
1900
+ up_statements, down_statements, missing_downs = self._extract_with_strategy(
1901
+ plan.source_migrations,
1902
+ self._resolve_strategy(plan.strategy or self.strategy),
1903
+ dialect=None,
1904
+ schema_ddl=plan_schema_ddl,
1905
+ )
1906
+ if missing_downs:
1907
+ plan.missing_down_versions = missing_downs
1908
+ return up_statements, down_statements
1909
+
1910
+ def generate_squashed_content(self, plan: SquashPlan, up_sql: list[str], down_sql: list[str]) -> str:
1911
+ """Generate the content for a squashed migration file.
1912
+
1913
+ Args:
1914
+ plan: The SquashPlan describing the squash operation.
1915
+ up_sql: List of UP SQL statements (in execution order).
1916
+ down_sql: List of DOWN SQL statements (in rollback order).
1917
+
1918
+ Returns:
1919
+ Complete SQL file content as a string.
1920
+ """
1921
+ lines: list[str] = []
1922
+
1923
+ title = "SQLSpec Migration"
1924
+ if self.template_settings and self.template_settings.profile:
1925
+ title = self.template_settings.profile.title
1926
+
1927
+ safe_title = sanitize_header_field(title)
1928
+ safe_version = sanitize_header_field(plan.target_version)
1929
+ safe_description = sanitize_header_field(plan.description)
1930
+ safe_sources = ", ".join(sanitize_header_field(version) for version in plan.source_versions)
1931
+
1932
+ lines.extend((
1933
+ f"-- {safe_title}",
1934
+ f"-- Version: {safe_version}",
1935
+ f"-- Description: {safe_description}",
1936
+ f"-- Squashed from: {safe_sources}",
1937
+ ))
1938
+ if plan.transactional is not None:
1939
+ lines.append(f"-- transactional: {'true' if plan.transactional else 'false'}")
1940
+ if plan.schema is not None:
1941
+ lines.append(f"-- schema: {sanitize_header_field(plan.schema)}")
1942
+ lines.extend(("", f"-- name: migrate-{safe_version}-up"))
1943
+ lines.extend(statement.rstrip() for statement in up_sql)
1944
+ lines.append("")
1945
+
1946
+ if down_sql:
1947
+ lines.append(f"-- name: migrate-{safe_version}-down")
1948
+ lines.extend(statement.rstrip() for statement in down_sql)
1949
+ lines.append("")
1950
+ elif plan.missing_down_versions:
1951
+ safe_missing = ", ".join(sanitize_header_field(version) for version in plan.missing_down_versions)
1952
+ lines.append(f"-- Note: Irreversible squash (missing down in {safe_missing})")
1953
+ lines.append("")
1954
+
1955
+ return "\n".join(lines)
1956
+
1957
+ def generate_python_squash(self, plan: SquashPlan, up_sql: list[str], down_sql: list[str]) -> str:
1958
+ """Generate Python migration file content instead of SQL.
1959
+
1960
+ Creates a Python migration file with up() and down() functions
1961
+ that return the SQL statements as lists.
1962
+
1963
+ Args:
1964
+ plan: The SquashPlan describing the squash operation.
1965
+ up_sql: List of UP SQL statements (in execution order).
1966
+ down_sql: List of DOWN SQL statements (in rollback order).
1967
+
1968
+ Returns:
1969
+ Complete Python file content as a string.
1970
+ """
1971
+ lines: list[str] = []
1972
+
1973
+ title = "SQLSpec Migration"
1974
+ if self.template_settings and self.template_settings.profile:
1975
+ title = self.template_settings.profile.title
1976
+
1977
+ safe_title = sanitize_header_field(title)
1978
+ safe_version = sanitize_header_field(plan.target_version)
1979
+ safe_description = sanitize_header_field(plan.description)
1980
+ safe_sources = ", ".join(sanitize_header_field(version) for version in plan.source_versions)
1981
+ docstring_body = escape_python_docstring(
1982
+ "\n".join((
1983
+ f"{safe_title}.",
1984
+ "",
1985
+ f"Version: {safe_version}",
1986
+ f"Description: {safe_description}",
1987
+ f"Squashed from: {safe_sources}",
1988
+ ))
1989
+ )
1990
+
1991
+ lines.extend([f'"""{docstring_body}', '"""', ""])
1992
+
1993
+ if plan.source_versions:
1994
+ lines.extend([f"__replaces__ = {list(plan.source_versions)!r}", ""])
1995
+
1996
+ lines.extend(["def up() -> list[str]:", ' """Return UP migration SQL statements."""', " return ["])
1997
+ lines.extend(f" {statement!r}," for statement in up_sql)
1998
+ lines.extend([" ]", ""])
1999
+
2000
+ lines.extend(["def down() -> list[str] | None:", ' """Return DOWN migration SQL statements."""'])
2001
+ if down_sql:
2002
+ lines.append(" return [")
2003
+ lines.extend(f" {statement!r}," for statement in down_sql)
2004
+ lines.extend([" ]", ""])
2005
+ else:
2006
+ lines.extend([" return None", ""])
2007
+
2008
+ return "\n".join(lines)
2009
+
2010
+ def apply_squash(self, plans: list[SquashPlan], *, dry_run: bool = False, cleanup_backup: bool = True) -> None:
2011
+ """Apply the squash operation for one or more plans.
2012
+
2013
+ Renders every squashed file before touching the filesystem, so a refusal from the
2014
+ ``ddl`` strategy leaves the migrations directory unchanged. Then creates a backup,
2015
+ writes squashed files, deletes source migrations, and cleans up the backup on
2016
+ success. Rolls back on error.
2017
+
2018
+ Args:
2019
+ plans: List of SquashPlan objects to execute.
2020
+ dry_run: If True, no files are modified (preview only).
2021
+ cleanup_backup: If True (default), remove the backup directory before returning.
2022
+ Set False when callers need to keep the backup until database tracking is updated.
2023
+ """
2024
+ if dry_run:
2025
+ logger.debug("Dry run mode - no changes will be made")
2026
+ return
2027
+
2028
+ all_source_files = {path for plan in plans for _, path in plan.source_migrations}
2029
+ all_target_files = {plan.target_path for plan in plans}
2030
+ ready_plans: list[SquashPlan] = []
2031
+ for plan in plans:
2032
+ validate_extension_consistency(plan.source_migrations)
2033
+ source_files = [path for _, path in plan.source_migrations]
2034
+ status = validate_squash_idempotency(
2035
+ source_files, plan.target_path, all_source_files=all_source_files, all_target_files=all_target_files
2036
+ )
2037
+ if status == "already_squashed":
2038
+ logger.debug("Squash target already applied: %s", plan.target_path)
2039
+ continue
2040
+ if status == "partial":
2041
+ msg = f"Squash plan for {plan.target_path.name} is partially applied"
2042
+ raise SquashValidationError(msg)
2043
+ ready_plans.append(plan)
2044
+
2045
+ if ready_plans and len(ready_plans) != len(plans) and (all_source_files & all_target_files):
2046
+ msg = "Multi-plan squash batch with overlapping target filenames is partially applied"
2047
+ raise SquashValidationError(msg)
2048
+
2049
+ if not ready_plans:
2050
+ return
2051
+
2052
+ planned_contents: list[tuple[SquashPlan, str]] = []
2053
+ for plan in ready_plans:
2054
+ up_sql, down_sql = self.extract_plan_sql(plan)
2055
+ if plan.target_path.suffix == ".py":
2056
+ content = self.generate_python_squash(plan, up_sql, down_sql)
2057
+ else:
2058
+ content = self.generate_squashed_content(plan, up_sql, down_sql)
2059
+ planned_contents.append((plan, content))
2060
+
2061
+ self._create_backup()
2062
+
2063
+ try:
2064
+ for plan, content in planned_contents:
2065
+ plan.target_path.write_text(content, encoding="utf-8")
2066
+ logger.debug("Wrote squashed migration to %s", plan.target_path)
2067
+
2068
+ target_paths = {plan.target_path for plan in ready_plans}
2069
+ all_source_paths = {
2070
+ source_path
2071
+ for plan in ready_plans
2072
+ for _, source_path in plan.source_migrations
2073
+ if source_path not in target_paths
2074
+ }
2075
+
2076
+ for source_path in all_source_paths:
2077
+ if source_path.exists():
2078
+ source_path.unlink()
2079
+ logger.debug("Deleted source migration %s", source_path)
2080
+
2081
+ if cleanup_backup:
2082
+ self.cleanup_backup()
2083
+
2084
+ except Exception:
2085
+ self.rollback_backup()
2086
+ raise
2087
+
2088
+ def cleanup_backup(self) -> None:
2089
+ """Remove the backup directory after a successful operation."""
2090
+ if not self.backup_path or not self.backup_path.exists():
2091
+ return
2092
+
2093
+ remove_backup(self.backup_path)
2094
+ logger.debug("Cleaned up backup at %s", self.backup_path)
2095
+ self.backup_path = None
2096
+
2097
+ def rollback_backup(self) -> None:
2098
+ """Restore migration files from the backup directory after an error."""
2099
+ if not self.backup_path or not self.backup_path.exists():
2100
+ return
2101
+
2102
+ backup_dir = self.backup_path
2103
+ restore_backup(self.migrations_path, backup_dir, delete_backup=True)
2104
+ self.backup_path = None
2105
+
2106
+ logger.debug("Rolled back from backup at %s", backup_dir)
2107
+
2108
+ def _extract_with_strategy(
2109
+ self,
2110
+ migrations: list[tuple[str, Path]],
2111
+ strategy: str,
2112
+ *,
2113
+ dialect: str | None,
2114
+ schema_ddl: tuple[list[str], list[str]] | None,
2115
+ ) -> tuple[list[str], list[str], list[str]]:
2116
+ if strategy == "schema":
2117
+ if schema_ddl is not None:
2118
+ return list(schema_ddl[0]), list(schema_ddl[1]), []
2119
+ schema_up, schema_down = self._extract_schema_ddl_from_context()
2120
+ return schema_up, schema_down, []
2121
+
2122
+ up_entries, down_statements, missing_downs = self._extract_raw_sql(migrations)
2123
+ if strategy == "concat":
2124
+ return [sql for _, sql in up_entries], ([] if missing_downs else down_statements), missing_downs
2125
+
2126
+ folded_up, folded_down = fold_migration_ddl(
2127
+ [sql for _, sql in up_entries],
2128
+ dialect=dialect if dialect is not None else self._resolve_dialect(),
2129
+ origins=[version for version, _ in up_entries],
2130
+ )
2131
+ return folded_up, folded_down, []
2132
+
2133
+ def _extract_raw_sql(
2134
+ self, migrations: list[tuple[str, Path]]
2135
+ ) -> tuple[list[tuple[str, str]], list[str], list[str]]:
2136
+ up_entries: list[tuple[str, str]] = []
2137
+ down_statements: list[str] = []
2138
+ missing_down_versions: list[str] = []
2139
+ migration_down_sql: list[list[str]] = []
2140
+
2141
+ for version, path in migrations:
2142
+ migration_data = self.runner.load_migration(path, version)
2143
+ loader = migration_data["loader"]
2144
+
2145
+ up_sql = _load_migration_sql(loader, path, "up")
2146
+ if up_sql:
2147
+ up_entries.extend((version, statement) for statement in up_sql)
2148
+
2149
+ cleaned_down = [stmt for stmt in _load_migration_sql(loader, path, "down") or [] if stmt.strip()]
2150
+ if not cleaned_down:
2151
+ missing_down_versions.append(version)
2152
+ migration_down_sql.append(cleaned_down)
2153
+
2154
+ for down_sql_group in migration_down_sql[::-1]:
2155
+ down_statements.extend(down_sql_group)
2156
+
2157
+ return up_entries, down_statements, missing_down_versions
2158
+
2159
+ def _resolve_dialect(self) -> str | None:
2160
+ context = self.runner.context
2161
+ dialect = context.dialect if context is not None else None
2162
+ if dialect and dialect not in {"generic", "unknown"}:
2163
+ return dialect
2164
+ return None
2165
+
2166
+ def _extract_schema_ddl_from_context(self) -> tuple[list[str], list[str]]:
2167
+ context = self.runner.context
2168
+ driver = context.driver if context is not None else None
2169
+ if not isinstance(driver, SyncDriverAdapterBase):
2170
+ msg = (
2171
+ "Schema squash strategy requires an active synchronous database driver; "
2172
+ "pass schema_ddl when reflecting through an async driver"
2173
+ )
2174
+ raise SquashValidationError(msg)
2175
+ version_parts = split_qualified_identifier(self.version_table, quote_chars='"`', allow_bracket_quotes=True)
2176
+ version_table = version_parts[-1] if version_parts else self.version_table.strip('"`[]')
2177
+ excluded = (version_table, f"{version_table}_lock")
2178
+ _ensure_schema_extraction_safe_sync(driver, exclude_tables=excluded, use_squash_error=True)
2179
+ data_dictionary = driver.data_dictionary
2180
+ create_res = data_dictionary.get_schema_ddl(driver, exclude_tables=excluded, direction="create")
2181
+ drop_res = data_dictionary.get_schema_ddl(driver, exclude_tables=excluded, direction="drop")
2182
+ return schema_ddl_statements(create_res, drop_res)
2183
+
2184
+ def _create_backup(self) -> Path:
2185
+ """Create timestamped backup directory with all migration files.
2186
+
2187
+ Returns:
2188
+ Path to created backup directory.
2189
+ """
2190
+ self.backup_path = create_backup(self.migrations_path)
2191
+ logger.debug("Created backup at %s", self.backup_path)
2192
+ return self.backup_path
2193
+
2194
+ @staticmethod
2195
+ def _resolve_strategy(strategy: str) -> str:
2196
+ resolved = strategy.lower()
2197
+ if resolved not in _SQUASH_STRATEGIES:
2198
+ msg = f"Unsupported squash strategy: '{strategy}'. Expected 'concat', 'ddl', or 'schema'."
2199
+ raise SquashValidationError(msg)
2200
+ return resolved
2201
+
2202
+
2203
+ def fold_migration_ddl(
2204
+ statements: Sequence[str], *, dialect: str | None = None, origins: Sequence[str] | None = None
2205
+ ) -> tuple[list[str], list[str]]:
2206
+ """Fold a chronological sequence of migration SQL statements into net canonical DDL.
2207
+
2208
+ Args:
2209
+ statements: Chronological sequence of SQL text from ``up`` migrations.
2210
+ dialect: Optional SQLGlot dialect name used to parse and render DDL.
2211
+ origins: Optional labels (usually migration versions) parallel to ``statements``,
2212
+ used to name the offending migration in refusal messages.
2213
+
2214
+ Returns:
2215
+ Tuple of ``(up_statements, down_statements)`` representing net schema DDL
2216
+ and reverse-dependency ``DROP`` statements.
2217
+
2218
+ Raises:
2219
+ SquashValidationError: If the statements cannot be folded faithfully.
2220
+ """
2221
+ folder = DDLStateFolder(dialect=dialect)
2222
+ for position, statement in enumerate(statements):
2223
+ folder.feed(statement, origin=origins[position] if origins is not None else None)
2224
+ return folder.to_statements()
2225
+
2226
+
2227
+ def parse_version_range(range_str: str) -> tuple[str, str]:
2228
+ """Parse a version range string into (start, end) tuple.
2229
+
2230
+ Accepts multiple formats: ``START:END``, ``START..END``, or ``START-END``.
2231
+
2232
+ Args:
2233
+ range_str: Version range string.
2234
+
2235
+ Returns:
2236
+ Tuple of (start_version, end_version) zero-padded to 4 digits.
2237
+
2238
+ Raises:
2239
+ ValueError: If the format is not recognised or an endpoint is empty.
2240
+ """
2241
+ for sep in (":", "..", "-"):
2242
+ if sep in range_str:
2243
+ raw_start, raw_end = (part.strip() for part in range_str.split(sep, 1))
2244
+ if not raw_start or not raw_end:
2245
+ msg = f"Invalid VERSION_RANGE '{range_str}': both START and END are required"
2246
+ raise ValueError(msg)
2247
+ return _normalize_range_endpoint(raw_start), _normalize_range_endpoint(raw_end)
2248
+ msg = f"Invalid VERSION_RANGE format: '{range_str}'. Use START:END, START..END, or START-END"
2249
+ raise ValueError(msg)
2250
+
2251
+
2252
+ def group_migrations_by_type(migrations: list[tuple[str, Path]]) -> list[tuple[str, list[tuple[str, Path]]]]:
2253
+ """Group consecutive migrations by file type (sql or py).
2254
+
2255
+ Partitions a list of migrations into groups where each group contains
2256
+ consecutive migrations of the same type. This enables squashing mixed
2257
+ SQL and Python migrations into separate output files.
2258
+
2259
+ Args:
2260
+ migrations: List of (version, path) tuples to group.
2261
+
2262
+ Returns:
2263
+ List of (type, migrations) tuples where type is "sql" or "py"
2264
+ and migrations is the list of (version, path) for that group.
2265
+ """
2266
+ if not migrations:
2267
+ return []
2268
+
2269
+ groups: list[tuple[str, list[tuple[str, Path]]]] = []
2270
+ current_type: str | None = None
2271
+ current_group: list[tuple[str, Path]] = []
2272
+
2273
+ for version, path in migrations:
2274
+ file_type = "py" if path.suffix == ".py" else "sql"
2275
+
2276
+ if file_type != current_type:
2277
+ if current_group and current_type is not None:
2278
+ groups.append((current_type, current_group))
2279
+ current_type = file_type
2280
+ current_group = [(version, path)]
2281
+ else:
2282
+ current_group.append((version, path))
2283
+
2284
+ if current_group and current_type is not None:
2285
+ groups.append((current_type, current_group))
2286
+
2287
+ return groups
2288
+
2289
+
2290
+ def schema_ddl_statements(create_res: Iterable[object], drop_res: Iterable[object]) -> tuple[list[str], list[str]]:
2291
+ """Convert ``get_schema_ddl`` create/drop results into semicolon-terminated UP and DOWN SQL lists.
2292
+
2293
+ Args:
2294
+ create_res: Result of ``get_schema_ddl(direction="create")``.
2295
+ drop_res: Result of ``get_schema_ddl(direction="drop")``.
2296
+
2297
+ Returns:
2298
+ Tuple of ``(up_ddl, down_ddl)`` statement lists.
2299
+
2300
+ Raises:
2301
+ SquashValidationError: If any reflected object has no DDL text, since omitting it
2302
+ would silently produce an incomplete schema.
2303
+ """
2304
+ return _ddl_texts(create_res, "create"), _ddl_texts(drop_res, "drop")
2305
+
2306
+
2307
+ def _ddl_texts(results: Iterable[object], direction: str) -> list[str]:
2308
+ """Read the DDL text of each schema DDL result, refusing results without DDL."""
2309
+ statements: list[str] = []
2310
+ for item in results:
2311
+ if not isinstance(item, DDLResult):
2312
+ msg = f"Unexpected schema DDL result {item!r} in {direction} direction"
2313
+ raise SquashValidationError(msg)
2314
+ if not item.ddl:
2315
+ identity = item.identity
2316
+ qualified = f"{identity.schema}.{identity.name}" if identity.schema else identity.name
2317
+ msg = (
2318
+ f"The data dictionary returned no {direction} DDL for {identity.object_type} {qualified} "
2319
+ f"(status {item.status}); the schema strategy cannot represent it"
2320
+ )
2321
+ raise SquashValidationError(msg)
2322
+ statements.append(_ensure_semicolon(item.ddl))
2323
+ return statements
2324
+
2325
+
2326
+ def _ensure_semicolon(sql_text: str) -> str:
2327
+ """Return ``sql_text`` stripped and terminated by exactly one semicolon."""
2328
+ stripped = sql_text.strip()
2329
+ return stripped if stripped.endswith(";") else f"{stripped};"
2330
+
2331
+
2332
+ class _FoldedStatement:
2333
+ """Mutable catalog entry for one statement tracked by :class:`DDLStateFolder`.
2334
+
2335
+ Attributes:
2336
+ expr: Parsed statement, mutated in place as later statements are folded into it.
2337
+ text: Original statement text, emitted verbatim while the entry is unmodified.
2338
+ origin: Label of the migration that produced the statement.
2339
+ order: Monotonic creation order used for deterministic output.
2340
+ faithful: Whether SQLGlot reproduces ``text`` faithfully, required before rewriting.
2341
+ owner: Catalog key of the owning table for indexes.
2342
+ modified: Whether ``expr`` diverged from ``text`` and must be re-rendered.
2343
+ """
2344
+
2345
+ __slots__ = ("expr", "faithful", "modified", "order", "origin", "owner", "text")
2346
+
2347
+ def __init__(
2348
+ self, expr: exp.Expr, text: str, origin: str | None, order: int, faithful: bool, owner: str = ""
2349
+ ) -> None:
2350
+ self.expr = expr
2351
+ self.text = text
2352
+ self.origin = origin
2353
+ self.order = order
2354
+ self.faithful = faithful
2355
+ self.owner = owner
2356
+ self.modified = False
2357
+
2358
+
2359
+ def _normalize_range_endpoint(endpoint: str) -> str:
2360
+ """Normalize a squash range endpoint, preserving extension prefixes and timestamps."""
2361
+ min_timestamp_len = 8
2362
+ if endpoint.startswith("ext_"):
2363
+ parsed = parse_extension_stem(endpoint)
2364
+ if parsed is not None:
2365
+ ext_name, ext_version = parsed
2366
+ if ext_version.isdigit() and len(ext_version) >= min_timestamp_len:
2367
+ return f"ext_{ext_name}_{ext_version}"
2368
+ return f"ext_{ext_name}_{_format_sequential_version(ext_version)}"
2369
+ if endpoint.isdigit() and len(endpoint) >= min_timestamp_len:
2370
+ return endpoint
2371
+ return _format_sequential_version(endpoint)
2372
+
2373
+
2374
+ def _stream_migrations(all_migrations: list[tuple[str, Path]], extension: str | None) -> list[tuple[str, Path]]:
2375
+ """Filter ``all_migrations`` to the core or extension stream matching ``extension``."""
2376
+ stream: list[tuple[str, Path]] = []
2377
+ for ver_str, path in all_migrations:
2378
+ try:
2379
+ parsed = parse_version(ver_str)
2380
+ except ValueError:
2381
+ if extension is None:
2382
+ stream.append((ver_str, path))
2383
+ continue
2384
+ if parsed.extension == extension:
2385
+ stream.append((ver_str, path))
2386
+ return stream
2387
+
2388
+
2389
+ def _extract_sql_directives(path: Path) -> tuple[bool | None, str | None]:
2390
+ """Extract transactional and schema directives from a SQL migration file if it exists."""
2391
+ if path.suffix != ".sql" or not path.exists():
2392
+ return None, None
2393
+ try:
2394
+ content = path.read_text(encoding="utf-8")
2395
+ except OSError:
2396
+ return None, None
2397
+ tx_match = _TRANSACTIONAL_DIRECTIVE_RE.search(content)
2398
+ transactional = tx_match.group(1).lower() == "true" if tx_match else None
2399
+ schema_match = _SCHEMA_DIRECTIVE_RE.search(content)
2400
+ schema = schema_match.group(1) if schema_match else None
2401
+ return transactional, schema
2402
+
2403
+
2404
+ def _coalesce_sql_directives(migrations: list[tuple[str, Path]]) -> tuple[bool | None, str | None]:
2405
+ """Coalesce uniform transactional and schema directives across SQL migrations.
2406
+
2407
+ Raises:
2408
+ SquashValidationError: If SQL migrations in ``migrations`` have conflicting
2409
+ ``-- transactional:`` or ``-- schema:`` directives.
2410
+ """
2411
+ sql_paths = [path for _, path in migrations if path.suffix == ".sql"]
2412
+ if not sql_paths:
2413
+ return None, None
2414
+ extracted = [_extract_sql_directives(path) for path in sql_paths]
2415
+ tx_values = {tx for tx, _ in extracted}
2416
+ schema_values = {sc for _, sc in extracted}
2417
+ if len(tx_values) > 1 or len(schema_values) > 1:
2418
+ msg = (
2419
+ "Cannot squash into a single file (--single-file) when SQL migrations have conflicting "
2420
+ "'-- transactional:' or '-- schema:' directives; use --split or omit --single-file."
2421
+ )
2422
+ raise SquashValidationError(msg)
2423
+ return next(iter(tx_values)), next(iter(schema_values))
2424
+
2425
+
2426
+ def _group_migrations_with_directives(
2427
+ migrations: list[tuple[str, Path]],
2428
+ ) -> list[tuple[str, bool | None, str | None, list[tuple[str, Path]]]]:
2429
+ """Group consecutive migrations by file type and SQL execution directives."""
2430
+ if not migrations:
2431
+ return []
2432
+
2433
+ groups: list[tuple[str, bool | None, str | None, list[tuple[str, Path]]]] = []
2434
+ current_key: tuple[str, bool | None, str | None] | None = None
2435
+ current_group: list[tuple[str, Path]] = []
2436
+
2437
+ for version, path in migrations:
2438
+ file_type = "py" if path.suffix == ".py" else "sql"
2439
+ transactional, schema = _extract_sql_directives(path) if file_type == "sql" else (None, None)
2440
+ key = (file_type, transactional, schema)
2441
+ if key != current_key:
2442
+ if current_group and current_key is not None:
2443
+ groups.append((current_key[0], current_key[1], current_key[2], current_group))
2444
+ current_key = key
2445
+ current_group = [(version, path)]
2446
+ else:
2447
+ current_group.append((version, path))
2448
+
2449
+ if current_group and current_key is not None:
2450
+ groups.append((current_key[0], current_key[1], current_key[2], current_group))
2451
+
2452
+ return groups