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,4002 @@
1
+ """Migration command implementations for SQLSpec.
2
+
3
+ This module provides the main command interface for database migrations.
4
+ """
5
+
6
+ import asyncio
7
+ import functools
8
+ import gzip
9
+ import importlib
10
+ import inspect
11
+ import logging
12
+ import os
13
+ import time
14
+ from collections.abc import Awaitable, Callable, Sequence
15
+ from contextlib import asynccontextmanager, contextmanager
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any, Final, Generic, Literal, NamedTuple, NoReturn, ParamSpec, TypeVar, cast, overload
18
+
19
+ import sqlglot
20
+ from rich.console import Console
21
+ from rich.prompt import Confirm, Prompt
22
+ from rich.table import Table
23
+ from sqlglot import exp
24
+ from sqlglot.errors import SqlglotError
25
+
26
+ from sqlspec.builder import CreateTable, sql
27
+ from sqlspec.exceptions import MigrationError, SQLBuilderError, SQLSpecError, SquashValidationError
28
+ from sqlspec.migrations.base import (
29
+ BaseMigrationCommands,
30
+ BaseMigrationTracker,
31
+ _ensure_schema_extraction_safe_async,
32
+ _ensure_schema_extraction_safe_sync,
33
+ )
34
+ from sqlspec.migrations.context import MigrationContext
35
+ from sqlspec.migrations.fix import MigrationFixer
36
+ from sqlspec.migrations.runner import (
37
+ AsyncMigrationRunner,
38
+ BaseMigrationRunner,
39
+ SyncMigrationRunner,
40
+ _driver_in_transaction_async,
41
+ )
42
+ from sqlspec.migrations.squash import MigrationSquasher, schema_ddl_statements
43
+ from sqlspec.migrations.tracker import AsyncMigrationTracker, SyncMigrationTracker
44
+ from sqlspec.migrations.utils import create_migration_file
45
+ from sqlspec.migrations.validation import validate_migration_order, validate_squash_range
46
+ from sqlspec.migrations.version import generate_conversion_map, generate_timestamp_version, parse_version
47
+ from sqlspec.observability import resolve_db_system
48
+ from sqlspec.utils.logging import get_logger, log_with_context
49
+ from sqlspec.utils.module_loader import ensure_pyarrow
50
+ from sqlspec.utils.serializers import from_json
51
+
52
+ if TYPE_CHECKING:
53
+ from collections.abc import AsyncGenerator, Generator
54
+ from collections.abc import Set as AbstractSet
55
+
56
+ from sqlspec.config import AsyncConfigT, DatabaseConfigProtocol, SyncConfigT
57
+ from sqlspec.data_dictionary import TableMetadata
58
+ from sqlspec.migrations.base import AppliedMigrationRecord, LoadedMigrationMetadata
59
+ from sqlspec.migrations.squash import SquashPlan
60
+
61
+ __all__ = (
62
+ "SUPPORTED_DATA_FILE_SUFFIXES",
63
+ "AsyncMigrationCommands",
64
+ "MigrationCommandsCore",
65
+ "SquashReconciliation",
66
+ "SyncMigrationCommands",
67
+ "VersionReconciliationPlan",
68
+ "VersionRename",
69
+ "create_migration_commands",
70
+ )
71
+
72
+ logger = get_logger("sqlspec.migrations.commands")
73
+ console = Console()
74
+ P = ParamSpec("P")
75
+ R = TypeVar("R")
76
+ CommandConfigT = TypeVar("CommandConfigT", bound="DatabaseConfigProtocol[Any, Any, Any]")
77
+ CommandRunnerT = TypeVar("CommandRunnerT", bound="BaseMigrationRunner")
78
+
79
+ SUPPORTED_DATA_FILE_SUFFIXES: Final[tuple[str, ...]] = (
80
+ ".json",
81
+ ".json.gz",
82
+ ".jsonl",
83
+ ".jsonl.gz",
84
+ ".ndjson",
85
+ ".ndjson.gz",
86
+ ".parquet",
87
+ ".arrow",
88
+ ".ipc",
89
+ ".feather",
90
+ )
91
+ _ARROW_FILE_SUFFIXES: Final[frozenset[str]] = frozenset({".arrow", ".ipc", ".feather"})
92
+ _LINE_DELIMITED_SUFFIXES: Final[frozenset[str]] = frozenset({".jsonl", ".jsonl.gz", ".ndjson", ".ndjson.gz"})
93
+ _MAX_DATA_FILE_BYTES: Final[int] = 256 * 1024 * 1024
94
+ _OTHER_DATA_FILE_SUFFIXES: Final[tuple[str, ...]] = (
95
+ ".csv",
96
+ ".tsv",
97
+ ".txt",
98
+ ".xlsx",
99
+ ".xls",
100
+ ".xml",
101
+ ".yaml",
102
+ ".yml",
103
+ ".avro",
104
+ ".orc",
105
+ ".sql",
106
+ ".zip",
107
+ ".gz",
108
+ ".bz2",
109
+ ".xz",
110
+ ".zst",
111
+ ".tar",
112
+ )
113
+ _GENERIC_DIALECTS: Final[frozenset[str]] = frozenset({"", "generic", "unknown"})
114
+ _AUTO_DUMP_ERRORS: Final[tuple[type[Exception], ...]] = (OSError, SQLSpecError, SqlglotError, ValueError)
115
+
116
+
117
+ MetadataBuilder = Callable[[dict[str, Any]], tuple[str | None, dict[str, Any]]]
118
+
119
+
120
+ def _with_command_span(
121
+ event: str, metadata_fn: "MetadataBuilder | None" = None, *, dry_run_param: str | None = "dry_run"
122
+ ) -> Callable[[Callable[P, R]], Callable[P, R]]:
123
+ """Attach span lifecycle and command metric management to command methods."""
124
+
125
+ metric_prefix = f"migrations.command.{event}"
126
+
127
+ def decorator(func: Callable[P, R]) -> Callable[P, R]:
128
+ signature = inspect.signature(func)
129
+
130
+ def _prepare(self: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> tuple[Any, bool, Any]:
131
+ runtime = self._runtime
132
+ metadata_args = _bind_arguments(signature, args, kwargs)
133
+ dry_run = False
134
+ if dry_run_param is not None:
135
+ dry_run = bool(metadata_args.get(dry_run_param, False))
136
+ metadata: dict[str, Any] | None = None
137
+ version: str | None = None
138
+ span = None
139
+ if runtime is not None:
140
+ runtime.increment_metric(f"{metric_prefix}.invocations")
141
+ if dry_run_param is not None and dry_run:
142
+ runtime.increment_metric(f"{metric_prefix}.dry_run")
143
+ if metadata_fn is not None:
144
+ version, metadata = metadata_fn(metadata_args)
145
+ span = runtime.start_migration_span(f"command.{event}", version=version, metadata=metadata)
146
+ return runtime, dry_run, span
147
+
148
+ def _finalize(
149
+ self: Any,
150
+ runtime: Any,
151
+ span: Any,
152
+ start: float,
153
+ error: "Exception | None",
154
+ recorded_error: bool,
155
+ dry_run: bool,
156
+ ) -> None:
157
+ command_error = self._last_command_error
158
+ self._last_command_error = None
159
+ command_metrics = self._last_command_metrics
160
+ self._last_command_metrics = None
161
+ if runtime is None:
162
+ return
163
+ if command_error is not None and not recorded_error:
164
+ runtime.increment_metric(f"{metric_prefix}.errors")
165
+ if not dry_run and command_metrics:
166
+ for metric, value in command_metrics.items():
167
+ runtime.increment_metric(f"{metric_prefix}.{metric}", value)
168
+ duration_ms = int((time.perf_counter() - start) * 1000)
169
+ runtime.end_migration_span(span, duration_ms=duration_ms, error=error or command_error)
170
+
171
+ if inspect.iscoroutinefunction(func):
172
+
173
+ @functools.wraps(func)
174
+ async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
175
+ self = args[0]
176
+ runtime, dry_run, span = _prepare(self, args, kwargs)
177
+ start = time.perf_counter()
178
+ error: Exception | None = None
179
+ error_recorded = False
180
+ try:
181
+ async_func = cast("Callable[P, Awaitable[R]]", func)
182
+ return await async_func(*args, **kwargs)
183
+ except Exception as exc: # pragma: no cover
184
+ error = exc
185
+ if runtime is not None:
186
+ runtime.increment_metric(f"{metric_prefix}.errors")
187
+ error_recorded = True
188
+ raise
189
+ finally:
190
+ _finalize(self, runtime, span, start, error, error_recorded, dry_run)
191
+
192
+ return cast("Callable[P, R]", async_wrapper)
193
+
194
+ @functools.wraps(func)
195
+ def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
196
+ self = args[0]
197
+ runtime, dry_run, span = _prepare(self, args, kwargs)
198
+ start = time.perf_counter()
199
+ error: Exception | None = None
200
+ error_recorded = False
201
+ try:
202
+ return func(*args, **kwargs)
203
+ except Exception as exc: # pragma: no cover
204
+ error = exc
205
+ if runtime is not None:
206
+ runtime.increment_metric(f"{metric_prefix}.errors")
207
+ error_recorded = True
208
+ raise
209
+ finally:
210
+ _finalize(self, runtime, span, start, error, error_recorded, dry_run)
211
+
212
+ return cast("Callable[P, R]", sync_wrapper)
213
+
214
+ return decorator
215
+
216
+
217
+ def _command_metadata(args: dict[str, Any]) -> tuple[str | None, dict[str, Any]]:
218
+ """Build span metadata (revision, dry_run) shared by upgrade and downgrade commands."""
219
+ revision = cast("str | None", args.get("revision"))
220
+ metadata = {"dry_run": str(args.get("dry_run", False)).lower()}
221
+ return revision, metadata
222
+
223
+
224
+ class SquashReconciliation(NamedTuple):
225
+ """Tracking-table change that collapses applied replaced versions into one squashed migration record."""
226
+
227
+ target_version: str
228
+ replaced_versions: tuple[str, ...]
229
+ description: str
230
+ checksum: str
231
+
232
+
233
+ class VersionRename(NamedTuple):
234
+ """Tracking-table change that renames an applied version to the version of its migration file on disk.
235
+
236
+ ``claimed_versions`` is the set of versions already accounted for when the rename was planned; the tracker uses
237
+ it to recognise a rename that another process already performed.
238
+ """
239
+
240
+ old_version: str
241
+ new_version: str
242
+ claimed_versions: frozenset[str]
243
+
244
+
245
+ class VersionReconciliationPlan(NamedTuple):
246
+ """Tracking-table changes needed to match the applied records to the migration files on disk.
247
+
248
+ ``applied_versions`` lists the applied versions as they will look once the changes are written, which lets a
249
+ dry run compute pending migrations without touching the database.
250
+ """
251
+
252
+ squashes: tuple[SquashReconciliation, ...]
253
+ renames: tuple[VersionRename, ...]
254
+ checksum_mismatches: tuple[tuple[str, str], ...]
255
+ applied_versions: tuple[str, ...]
256
+
257
+ @property
258
+ def change_count(self) -> int:
259
+ """Return the number of tracking-table changes in the plan."""
260
+ return len(self.squashes) + len(self.renames)
261
+
262
+
263
+ class MigrationCommandsCore(BaseMigrationCommands[CommandConfigT, Any], Generic[CommandConfigT, CommandRunnerT]):
264
+ """Database-independent planning, rendering, and reporting shared by sync and async migration commands.
265
+
266
+ Subclasses perform every database, tracker, and migration-loader call and pass the results to these methods, so
267
+ the sync and async command classes stay thin I/O shells around one implementation.
268
+ """
269
+
270
+ tracker: Any
271
+ runner: CommandRunnerT
272
+
273
+ def ensure_reconcilers_allow(self, operation: Literal["upgrade", "downgrade"], revision: str) -> None:
274
+ """Validate reconciler compatibility with the requested operation and revision.
275
+
276
+ Args:
277
+ operation: Migration command operation (``"upgrade"`` or ``"downgrade"``).
278
+ revision: Requested target revision string.
279
+ """
280
+ del operation, revision
281
+
282
+ def report_reconciler_preview(
283
+ self, *, use_logger: bool = False, echo: bool = True, summary_only: bool = False
284
+ ) -> None:
285
+ """Emit read-only dry-run preview lines for configured extension reconcilers."""
286
+ if not self.extension_reconcilers:
287
+ return
288
+ total = len(self.extension_reconcilers)
289
+ for index, descriptor in enumerate(self.extension_reconcilers, start=1):
290
+ _output_info(
291
+ use_logger,
292
+ echo,
293
+ summary_only,
294
+ "Would invoke reconciler %d/%d: %s (%s)",
295
+ index,
296
+ total,
297
+ descriptor.name,
298
+ descriptor.module_path,
299
+ rich_message=(
300
+ f"[cyan]Would invoke reconciler {index}/{total}:[/] {descriptor.name} "
301
+ f"[dim]({descriptor.module_path})[/]"
302
+ ),
303
+ )
304
+ _output_info(
305
+ use_logger,
306
+ echo,
307
+ summary_only,
308
+ "Reconciler DDL is determined by live catalog inspection during upgrade and is not evaluated during dry run.",
309
+ rich_message="[dim]Note: Reconciler DDL requires live catalog inspection and is not evaluated during dry run.[/]",
310
+ )
311
+
312
+ def report_reconciler_downgrade_preview(
313
+ self, *, use_logger: bool = False, echo: bool = True, summary_only: bool = False
314
+ ) -> None:
315
+ """Emit read-only dry-run preview lines for base-reaching reconciler downgrades."""
316
+ if not self.extension_reconcilers:
317
+ return
318
+ reversed_reconcilers = list(reversed(self.extension_reconcilers))
319
+ total = len(reversed_reconcilers)
320
+ for index, descriptor in enumerate(reversed_reconcilers, start=1):
321
+ _output_info(
322
+ use_logger,
323
+ echo,
324
+ summary_only,
325
+ "Would downgrade reconciler %d/%d: %s (%s)",
326
+ index,
327
+ total,
328
+ descriptor.name,
329
+ descriptor.module_path,
330
+ rich_message=(
331
+ f"[cyan]Would downgrade reconciler {index}/{total}:[/] {descriptor.name} "
332
+ f"[dim]({descriptor.module_path})[/]"
333
+ ),
334
+ )
335
+
336
+ def _print_configured_reconcilers(self) -> None:
337
+ """Render a Rich table of configured extension reconcilers for verbose current output."""
338
+ if not self.extension_reconcilers:
339
+ return
340
+ table = Table(title="Configured reconcilers (run on upgrade; drop at base downgrade)")
341
+ table.add_column("Order", style="cyan", justify="right")
342
+ table.add_column("Extension", style="green")
343
+ table.add_column("Module Path")
344
+ for index, descriptor in enumerate(self.extension_reconcilers, start=1):
345
+ table.add_row(str(index), descriptor.name, str(descriptor.module_path))
346
+ console.print(table)
347
+
348
+ def _version_table_exclusion(self, include_migrations_table: bool = False) -> tuple[str, ...]:
349
+ """Return the ``exclude_tables`` value for schema DDL introspection.
350
+
351
+ The tracker exposes the bare, unquoted version table name with any schema qualifier removed, which is the
352
+ form the data dictionary matches against.
353
+
354
+ Args:
355
+ include_migrations_table: Keep the tracking table in the introspected DDL.
356
+
357
+ Returns:
358
+ Table names to exclude.
359
+ """
360
+ if include_migrations_table:
361
+ return ()
362
+ version_table_name = str(self.tracker.version_table_name)
363
+ return (version_table_name, f"{version_table_name}_lock")
364
+
365
+ def _tracking_table_exists(self, tables: "Sequence[TableMetadata]") -> bool:
366
+ """Return whether the migration tracking table appears in introspected table metadata.
367
+
368
+ Names compare case-insensitively. When the tracker is schema-qualified, a table reported in another schema
369
+ does not match.
370
+
371
+ Args:
372
+ tables: Table metadata returned by ``data_dictionary.get_tables``.
373
+
374
+ Returns:
375
+ True when the tracking table exists.
376
+ """
377
+ target_name = str(self.tracker.version_table_name).lower()
378
+ target_schema = self.tracker.version_table_schema
379
+ for table in tables:
380
+ if str(table.get("table_name") or "").lower() != target_name:
381
+ continue
382
+ reported_schema = table.get("schema_name") or table.get("table_schema")
383
+ if target_schema is None or reported_schema is None:
384
+ return True
385
+ if str(reported_schema).lower() == str(target_schema).lower():
386
+ return True
387
+ return False
388
+
389
+ def _resolve_data_source(self, from_data: "str | Path") -> "Path | str":
390
+ """Classify a ``from_data`` value as a data file path or a database table name.
391
+
392
+ Classification is syntactic so the same argument never changes meaning based on what happens to exist in
393
+ the working directory:
394
+
395
+ - A ``Path`` instance, a value containing a path separator, or a value ending with a known data file
396
+ suffix is a file path. It must be an existing regular file with a supported suffix
397
+ (``SUPPORTED_DATA_FILE_SUFFIXES``); directories, missing files, and unsupported suffixes such as
398
+ ``.csv`` raise ``MigrationError``.
399
+ - Anything else is a table name, optionally schema-qualified (``public.users``). Without an explicit
400
+ ``schema`` argument, a qualified name splits on its last dot.
401
+
402
+ Args:
403
+ from_data: Value passed as ``from_data`` / ``--from-data``.
404
+
405
+ Returns:
406
+ The validated file ``Path``, or the table name string.
407
+
408
+ Raises:
409
+ MigrationError: When a file path is a directory, missing, or has an unsupported suffix.
410
+ """
411
+ text = str(from_data)
412
+ if not isinstance(from_data, Path) and not self._looks_like_data_path(text):
413
+ return text
414
+ path = Path(from_data)
415
+ supported = ", ".join(SUPPORTED_DATA_FILE_SUFFIXES)
416
+ if path.is_dir():
417
+ msg = f"Data source '{text}' is a directory; pass a data file ({supported}) or a table name"
418
+ raise MigrationError(msg)
419
+ if self._data_file_suffix(path) is None:
420
+ msg = f"Unsupported data file '{text}'; supported suffixes: {supported}"
421
+ raise MigrationError(msg)
422
+ if not path.is_file():
423
+ msg = f"Data file not found: {text}"
424
+ raise MigrationError(msg)
425
+ return path
426
+
427
+ def _prepare_revision_source(self, *, from_schema: bool, from_data: "str | Path | None") -> "Path | str | None":
428
+ """Validate revision source flags and classify ``from_data`` as a file ``Path`` or table name."""
429
+ if from_schema and from_data is not None:
430
+ msg = "Cannot specify both from_schema and from_data"
431
+ raise MigrationError(msg)
432
+ if from_data is None:
433
+ return None
434
+ return self._resolve_data_source(from_data)
435
+
436
+ def _data_file_revision_sql(
437
+ self, data_path: Path, *, schema: str | None, target_table: str | None
438
+ ) -> "tuple[list[str], list[str]]":
439
+ """Infer CREATE TABLE and matching DROP TABLE statements from a validated data file.
440
+
441
+ ``target_table`` and ``schema`` are literal names; they are quoted as needed rather than parsed as SQL.
442
+
443
+ Args:
444
+ data_path: Data file returned by ``_resolve_data_source``.
445
+ schema: Optional schema for the created table.
446
+ target_table: Optional table name. Defaults to the file name without its data suffix.
447
+
448
+ Returns:
449
+ Tuple of UP and DOWN statement lists.
450
+
451
+ Raises:
452
+ MigrationError: When the file cannot be read or no DDL can be inferred from it.
453
+ """
454
+ suffix = cast("str", self._data_file_suffix(data_path))
455
+ table_name = target_table or data_path.name[: -len(suffix)]
456
+ dialect = self._context_dialect()
457
+ table_sql = exp.Table(this=exp.to_identifier(table_name), db=exp.to_identifier(schema) if schema else None).sql(
458
+ dialect=dialect, copy=False
459
+ )
460
+ try:
461
+ if suffix == ".parquet":
462
+ ensure_pyarrow()
463
+ arrow_schema = importlib.import_module("pyarrow.parquet").read_schema(data_path)
464
+ builder = CreateTable.from_arrow_schema(table_sql, arrow_schema, dialect=dialect)
465
+ elif suffix in _ARROW_FILE_SUFFIXES:
466
+ ensure_pyarrow()
467
+ with importlib.import_module("pyarrow.ipc").open_file(data_path) as reader:
468
+ arrow_schema = reader.schema
469
+ builder = CreateTable.from_arrow_schema(table_sql, arrow_schema, dialect=dialect)
470
+ else:
471
+ builder = CreateTable.from_records(
472
+ table_sql, self._read_data_file_records(data_path, suffix), dialect=dialect
473
+ )
474
+ up_statement = self._terminate_statement(builder.build(dialect=dialect).sql)
475
+ except (OSError, ValueError, SQLBuilderError, SqlglotError) as exc:
476
+ msg = f"Could not infer DDL from data file '{data_path}': {exc}"
477
+ raise MigrationError(msg) from exc
478
+ return [up_statement], [self._drop_statement_for(up_statement, dialect)]
479
+
480
+ def _staging_table_revision_sql(
481
+ self, ddl: "str | None", source_table: str, dialect: str | None
482
+ ) -> "tuple[list[str], list[str]]":
483
+ """Build UP and DOWN statements from DDL inferred by profiling a staging table.
484
+
485
+ The DOWN statement drops exactly the table the UP statement creates, with the same identifier quoting.
486
+
487
+ Args:
488
+ ddl: CREATE TABLE statement returned by ``infer_table_ddl_from_data``.
489
+ source_table: Staging table that was profiled.
490
+ dialect: Dialect of the inferred DDL.
491
+
492
+ Returns:
493
+ Tuple of UP and DOWN statement lists.
494
+
495
+ Raises:
496
+ MigrationError: When no DDL was inferred.
497
+ """
498
+ if not ddl:
499
+ msg = f"Could not infer DDL from table '{source_table}'"
500
+ raise MigrationError(msg)
501
+ up_statement = self._terminate_statement(ddl)
502
+ return [up_statement], [self._drop_statement_for(up_statement, dialect)]
503
+
504
+ def _write_revision(
505
+ self,
506
+ message: str,
507
+ file_type: str | None,
508
+ up_sql: "Sequence[str] | None" = None,
509
+ down_sql: "Sequence[str] | None" = None,
510
+ ) -> Path:
511
+ """Create a timestamp-versioned migration file and report it.
512
+
513
+ Args:
514
+ message: Description for the migration.
515
+ file_type: Migration file format ('sql' or 'py'); defaults to the template profile.
516
+ up_sql: Optional statements for the UP section.
517
+ down_sql: Optional statements for the DOWN section.
518
+
519
+ Returns:
520
+ Path to the created migration file.
521
+ """
522
+ version = generate_timestamp_version()
523
+ selected_format = file_type or self._template_settings.default_format
524
+ file_path = create_migration_file(
525
+ self.migrations_path,
526
+ version,
527
+ message,
528
+ selected_format,
529
+ config=self.config,
530
+ template_settings=self._template_settings,
531
+ up_sql=up_sql,
532
+ down_sql=down_sql,
533
+ )
534
+ log_with_context(
535
+ logger,
536
+ logging.DEBUG,
537
+ "migration.create",
538
+ db_system=resolve_db_system(type(self.config).__name__),
539
+ version=version,
540
+ file_path=str(file_path),
541
+ file_type=selected_format,
542
+ description=message,
543
+ )
544
+ console.print(f"[green]Created migration:[/] {file_path}")
545
+ return file_path
546
+
547
+ def _render_schema_dump(
548
+ self, create_res: Any, *, dialect_label: str, schema: str | None, output_path: "str | Path | None", echo: bool
549
+ ) -> str:
550
+ """Render schema DDL to SQL text and write it to the requested or configured dump path.
551
+
552
+ Args:
553
+ create_res: ``get_schema_ddl(direction="create")`` result.
554
+ dialect_label: Dialect name for the dump header.
555
+ schema: Inspected schema, recorded in the header when set.
556
+ output_path: Explicit output file. Falls back to ``migration_config["schema_dump_path"]``.
557
+ echo: Report the written file on the console.
558
+
559
+ Returns:
560
+ The rendered schema SQL.
561
+ """
562
+ up_ddl, _ = schema_ddl_statements(create_res, ())
563
+ lines: list[str] = ["-- SQLSpec Schema Dump", f"-- Dialect: {dialect_label}"]
564
+ if schema:
565
+ lines.append(f"-- Schema: {schema}")
566
+ lines.append("")
567
+ if up_ddl:
568
+ lines.append("\n\n".join(stmt.rstrip() for stmt in up_ddl))
569
+ rendered = "\n".join(lines).rstrip() + "\n"
570
+
571
+ resolved_output: Path | None = None
572
+ if output_path is not None:
573
+ resolved_output = Path(output_path)
574
+ else:
575
+ configured_path = self._get_migration_config().get("schema_dump_path")
576
+ if isinstance(configured_path, (str, Path)):
577
+ resolved_output = Path(configured_path)
578
+
579
+ if resolved_output is not None:
580
+ resolved_output.parent.mkdir(parents=True, exist_ok=True)
581
+ resolved_output.write_text(rendered, encoding="utf-8")
582
+ if echo:
583
+ console.print(f"[green]✓ Schema dumped to {resolved_output}[/]")
584
+ return rendered
585
+
586
+ def _auto_dump_path(self) -> "Path | None":
587
+ """Return the schema dump path written after ``upgrade`` when ``auto_dump_schema`` is enabled."""
588
+ migration_config = self._get_migration_config()
589
+ auto_dump = migration_config.get("auto_dump_schema")
590
+ if not auto_dump:
591
+ return None
592
+ if isinstance(auto_dump, (str, Path)):
593
+ return Path(auto_dump)
594
+ configured_path = migration_config.get("schema_dump_path")
595
+ if isinstance(configured_path, (str, Path)):
596
+ return Path(configured_path)
597
+ return self.migrations_path / "schema.sql"
598
+
599
+ def _report_auto_dump_failure(self, path: Path, error: Exception, *, use_logger: bool, echo: bool) -> None:
600
+ """Report a failed post-upgrade schema dump without failing the already committed upgrade.
601
+
602
+ Args:
603
+ path: Dump path that could not be written.
604
+ error: Failure raised while dumping the schema.
605
+ use_logger: Whether logger output is enabled.
606
+ echo: Whether console output is enabled.
607
+ """
608
+ logger.warning(
609
+ "Migrations were applied, but the automatic schema dump to %s failed: %s", path, error, exc_info=error
610
+ )
611
+ if echo and not use_logger:
612
+ console.print(
613
+ f"[yellow]Warning: migrations were applied, but the automatic schema dump to {path} failed: {error}[/]"
614
+ )
615
+
616
+ def _verification_report(
617
+ self,
618
+ applied_migrations: "list[AppliedMigrationRecord]",
619
+ loaded_files: "dict[str, LoadedMigrationMetadata]",
620
+ *,
621
+ strict: bool,
622
+ fail_on_pending: bool,
623
+ use_logger: bool,
624
+ echo: bool,
625
+ summary_only: bool,
626
+ ) -> "dict[str, Any]":
627
+ """Compare applied records against migration files, report the result, and enforce failure modes.
628
+
629
+ Args:
630
+ applied_migrations: Records from the tracking table (empty when it does not exist).
631
+ loaded_files: Loaded migration metadata keyed by version.
632
+ strict: Raise on checksum drift, orphaned records, partially applied squashes, or unrecorded
633
+ squash replacements.
634
+ fail_on_pending: Raise when migrations are pending.
635
+ use_logger: Whether logger output is enabled.
636
+ echo: Whether console output is enabled.
637
+ summary_only: Whether summary-only logging is enabled.
638
+
639
+ Returns:
640
+ Verification report with ``valid``, ``checksum_mismatches``, ``orphaned_records``,
641
+ ``pending_versions``, ``partial_squash_errors``, and ``unrecorded_replaces``.
642
+
643
+ Raises:
644
+ MigrationError: When ``strict`` and the report is invalid, or ``fail_on_pending`` and migrations are
645
+ pending.
646
+ """
647
+ retained_versions = self._retained_reconcile_versions(applied_migrations)
648
+ report = self._evaluate_verification(applied_migrations, loaded_files, retained_versions=retained_versions)
649
+ problems: list[str] = []
650
+ if report["checksum_mismatches"]:
651
+ mismatched = ", ".join(item["version"] for item in report["checksum_mismatches"])
652
+ problems.append(f"checksum mismatch in [{mismatched}]")
653
+ if report["orphaned_records"]:
654
+ problems.append(f"orphaned applied records [{', '.join(report['orphaned_records'])}]")
655
+ if report["partial_squash_errors"]:
656
+ partials = ", ".join(item["version"] for item in report["partial_squash_errors"])
657
+ problems.append(f"partially applied squash in [{partials}]")
658
+ if report["unrecorded_replaces"]:
659
+ unrecorded = ", ".join(item["version"] for item in report["unrecorded_replaces"])
660
+ problems.append(f"unrecorded squash replacements in [{unrecorded}]")
661
+ pending_failure = fail_on_pending and bool(report["pending_versions"])
662
+ if pending_failure:
663
+ problems.append(f"pending migrations [{', '.join(report['pending_versions'])}]")
664
+
665
+ if not problems:
666
+ pending_count = len(report["pending_versions"])
667
+ _output_info(
668
+ use_logger,
669
+ echo,
670
+ summary_only,
671
+ "Migration verification passed (%d pending)",
672
+ pending_count,
673
+ rich_message=f"[green]✓ Migration verification passed ({pending_count} pending)[/]",
674
+ )
675
+ return report
676
+
677
+ summary_text = "; ".join(problems)
678
+ _output_error(
679
+ use_logger,
680
+ echo,
681
+ summary_only,
682
+ "Verification failed: %s",
683
+ summary_text,
684
+ rich_message=f"[red]✗ Verification failed: {summary_text}[/]",
685
+ )
686
+ if (strict and not report["valid"]) or pending_failure:
687
+ msg = f"Verification failed: {summary_text}"
688
+ raise MigrationError(msg)
689
+ return report
690
+
691
+ def _plan_version_reconciliation(
692
+ self,
693
+ all_migrations: "list[tuple[str, Path]]",
694
+ applied_migrations: "list[AppliedMigrationRecord]",
695
+ loaded_files: "dict[str, LoadedMigrationMetadata]",
696
+ ) -> VersionReconciliationPlan:
697
+ """Plan the tracking-table changes that align applied records with migration files on disk.
698
+
699
+ Squashed files whose replaced versions are all applied collapse into one record. Timestamp versions renamed
700
+ by ``fix`` are renamed when checksums match, as are applied versions whose file was renamed to another
701
+ unclaimed version with the same checksum.
702
+
703
+ Args:
704
+ all_migrations: Migration files on disk as ``(version, path)`` pairs.
705
+ applied_migrations: Records from the tracking table.
706
+ loaded_files: Loaded metadata for every migration file that could be loaded.
707
+
708
+ Returns:
709
+ The reconciliation plan. Nothing is written.
710
+
711
+ Raises:
712
+ SquashValidationError: When a squashed migration's replaced versions are only partially applied.
713
+ """
714
+ retained_versions = self._retained_reconcile_versions(applied_migrations)
715
+ applied_map: dict[str, AppliedMigrationRecord] = {
716
+ m["version_num"]: m for m in applied_migrations if m["version_num"] not in retained_versions
717
+ }
718
+ applied_versions: list[str] = [m["version_num"] for m in applied_migrations]
719
+ files_by_version = dict(all_migrations)
720
+ claimed_versions = set(applied_map)
721
+ reconciled_old_versions: set[str] = set()
722
+ squashes: list[SquashReconciliation] = []
723
+ renames: list[VersionRename] = []
724
+ checksum_mismatches: list[tuple[str, str]] = []
725
+
726
+ for target_version, _ in all_migrations:
727
+ migration = loaded_files.get(target_version)
728
+ if migration is None:
729
+ continue
730
+ state, applied_replaces, missing_replaces = self._classify_squash_state(
731
+ target_version, migration, applied_map
732
+ )
733
+ if state == "already_reconciled":
734
+ reconciled_old_versions.update(applied_replaces)
735
+ continue
736
+ if state == "partial":
737
+ self._raise_partial_squash(target_version, applied_replaces, missing_replaces)
738
+ if state != "replace":
739
+ continue
740
+ squashes.append(
741
+ SquashReconciliation(
742
+ target_version=target_version,
743
+ replaced_versions=tuple(applied_replaces),
744
+ description=migration["description"],
745
+ checksum=migration["checksum"],
746
+ )
747
+ )
748
+ for old_version in applied_replaces:
749
+ applied_map.pop(old_version, None)
750
+ claimed_versions.discard(old_version)
751
+ reconciled_old_versions.add(old_version)
752
+ applied_versions = [v for v in applied_versions if v not in applied_replaces]
753
+ applied_versions.append(target_version)
754
+ applied_map[target_version] = cast(
755
+ "AppliedMigrationRecord",
756
+ {
757
+ "version_num": target_version,
758
+ "description": migration["description"],
759
+ "checksum": migration["checksum"],
760
+ "replaces": ",".join(applied_replaces),
761
+ },
762
+ )
763
+ claimed_versions.add(target_version)
764
+
765
+ core_migrations = [(v, p) for v, p in all_migrations if not v.startswith("ext_")]
766
+ for old_version, new_version in generate_conversion_map(core_migrations).items():
767
+ if old_version not in applied_map or new_version in claimed_versions:
768
+ continue
769
+ renamed_migration = loaded_files.get(new_version)
770
+ if renamed_migration is None:
771
+ continue
772
+ reconciled_old_versions.add(old_version)
773
+ if not BaseMigrationRunner.verify_migration_checksum(
774
+ renamed_migration["content"], str(applied_map[old_version].get("checksum") or "")
775
+ ):
776
+ checksum_mismatches.append((old_version, new_version))
777
+ continue
778
+ renames.append(VersionRename(old_version, new_version, frozenset(claimed_versions)))
779
+ claimed_versions.discard(old_version)
780
+ claimed_versions.add(new_version)
781
+ applied_versions = [new_version if v == old_version else v for v in applied_versions]
782
+
783
+ for applied_version, applied_record in list(applied_map.items()):
784
+ if (
785
+ applied_version.startswith("ext_")
786
+ or applied_version in files_by_version
787
+ or applied_version in reconciled_old_versions
788
+ ):
789
+ continue
790
+ for file_version, _ in core_migrations:
791
+ file_migration = loaded_files.get(file_version)
792
+ if file_migration is None or file_version in claimed_versions:
793
+ continue
794
+ if BaseMigrationRunner.verify_migration_checksum(
795
+ file_migration["content"], str(applied_record.get("checksum") or "")
796
+ ):
797
+ renames.append(VersionRename(applied_version, file_version, frozenset(claimed_versions)))
798
+ claimed_versions.discard(applied_version)
799
+ claimed_versions.add(file_version)
800
+ applied_versions = [file_version if v == applied_version else v for v in applied_versions]
801
+ break
802
+
803
+ return VersionReconciliationPlan(
804
+ squashes=tuple(squashes),
805
+ renames=tuple(renames),
806
+ checksum_mismatches=tuple(checksum_mismatches),
807
+ applied_versions=tuple(applied_versions),
808
+ )
809
+
810
+ def _report_version_reconciliation(
811
+ self, plan: VersionReconciliationPlan, *, dry_run: bool, use_logger: bool, echo: bool, summary_only: bool
812
+ ) -> None:
813
+ """Report planned (dry run) or applied tracking-table reconciliation.
814
+
815
+ Args:
816
+ plan: Reconciliation plan.
817
+ dry_run: Whether the changes were only planned.
818
+ use_logger: Whether logger output is enabled.
819
+ echo: Whether console output is enabled.
820
+ summary_only: Whether summary-only logging is enabled.
821
+ """
822
+ verb = "Would reconcile" if dry_run else "Reconciled"
823
+ for squash in plan.squashes:
824
+ replaced = ", ".join(squash.replaced_versions)
825
+ _output_info(
826
+ use_logger,
827
+ echo,
828
+ summary_only,
829
+ "%s squashed migration: %s -> %s",
830
+ verb,
831
+ replaced,
832
+ squash.target_version,
833
+ rich_message=f" [dim]{verb} squashed migration:[/] {replaced} → {squash.target_version}",
834
+ )
835
+ for rename in plan.renames:
836
+ _output_info(
837
+ use_logger,
838
+ echo,
839
+ summary_only,
840
+ "%s version: %s -> %s",
841
+ verb,
842
+ rename.old_version,
843
+ rename.new_version,
844
+ rich_message=f" [dim]{verb} version:[/] {rename.old_version} → {rename.new_version}",
845
+ )
846
+ for old_version, new_version in plan.checksum_mismatches:
847
+ if use_logger:
848
+ logger.warning("Checksum mismatch for %s -> %s, skipping auto-sync", old_version, new_version)
849
+ elif echo:
850
+ console.print(
851
+ f" [yellow]Warning: Checksum mismatch for {old_version} → {new_version}, skipping auto-sync[/]"
852
+ )
853
+ if plan.change_count:
854
+ _output_info(
855
+ use_logger,
856
+ echo,
857
+ summary_only,
858
+ "%s %d version record(s)",
859
+ verb,
860
+ plan.change_count,
861
+ rich_message=f"[cyan]{verb} {plan.change_count} version record(s)[/]",
862
+ )
863
+
864
+ def _create_squasher(self, runner: SyncMigrationRunner, strategy: str) -> MigrationSquasher:
865
+ """Create a squasher bound to a synchronous migration runner and the configured version table."""
866
+ return MigrationSquasher(
867
+ self.migrations_path,
868
+ runner,
869
+ self._template_settings,
870
+ strategy=strategy,
871
+ version_table=str(self.tracker.version_table_name),
872
+ )
873
+
874
+ def _resolve_squash_range(
875
+ self, all_migrations: "list[tuple[str, Path]]", start_version: str | None, end_version: str | None
876
+ ) -> "tuple[str, str] | None":
877
+ """Resolve an open squash range to the first and last core migrations.
878
+
879
+ Args:
880
+ all_migrations: Migration files on disk as ``(version, path)`` pairs.
881
+ start_version: Requested first version, or None for the first core migration.
882
+ end_version: Requested last version, or None for the last core migration.
883
+
884
+ Returns:
885
+ The resolved ``(start, end)`` range, or None when there are no core migrations to squash.
886
+ """
887
+ if start_version is not None and end_version is not None:
888
+ return start_version, end_version
889
+ core_versions = [version for version, _ in all_migrations if not version.startswith("ext_")]
890
+ if not core_versions:
891
+ console.print("[yellow]No sequential migrations found to squash[/]")
892
+ return None
893
+ resolved_start = start_version if start_version is not None else core_versions[0]
894
+ resolved_end = end_version if end_version is not None else core_versions[-1]
895
+ console.print(f"[cyan]Squashing range: {resolved_start} to {resolved_end}[/]")
896
+ return resolved_start, resolved_end
897
+
898
+ def _print_squash_plan(self, plans: "list[SquashPlan]") -> None:
899
+ """Print the source-to-target table for a squash plan."""
900
+ table = Table(title="Squash Plan")
901
+ table.add_column("Version", style="cyan")
902
+ table.add_column("File")
903
+ table.add_column("Target", style="green")
904
+ total_migrations = 0
905
+ for plan in plans:
906
+ for version, file_path in plan.source_migrations:
907
+ table.add_row(version, file_path.name, plan.target_path.name)
908
+ total_migrations += 1
909
+ console.print(table)
910
+ target_files = ", ".join(plan.target_path.name for plan in plans)
911
+ console.print(
912
+ f"\n[yellow]{total_migrations} migrations will be squashed into {len(plans)} file(s): {target_files}[/]"
913
+ )
914
+
915
+ def _print_squash_dry_run(self, squasher: MigrationSquasher, plans: "list[SquashPlan]") -> None:
916
+ """Extract and print the planned UP and DOWN SQL for each squash plan in dry-run mode."""
917
+ for plan in plans:
918
+ up_sql, down_sql = squasher.extract_plan_sql(plan)
919
+ console.print(f"\n[cyan]-- {plan.target_path.name} (up)[/]")
920
+ for statement in up_sql:
921
+ console.print(statement.rstrip())
922
+ if down_sql:
923
+ console.print(f"\n[cyan]-- {plan.target_path.name} (down)[/]")
924
+ for statement in down_sql:
925
+ console.print(statement.rstrip())
926
+ console.print("[yellow][Preview Mode - No changes made][/]")
927
+
928
+ def _validate_schema_squash_applied(
929
+ self,
930
+ runner: SyncMigrationRunner,
931
+ all_migrations: "list[tuple[str, Path]]",
932
+ start_version: str,
933
+ end_version: str,
934
+ *,
935
+ allow_gaps: bool,
936
+ applied_migrations: "list[AppliedMigrationRecord]",
937
+ ) -> None:
938
+ """Ensure every migration in a ``schema`` squash range is already applied in the database."""
939
+ source_migrations = validate_squash_range(all_migrations, start_version, end_version, allow_gaps=allow_gaps)
940
+ covered_versions: set[str] = set()
941
+ for record in applied_migrations:
942
+ covered_versions.add(record["version_num"])
943
+ raw_replaces = record.get("replaces")
944
+ if isinstance(raw_replaces, str) and raw_replaces:
945
+ covered_versions.update(part.strip() for part in raw_replaces.split(",") if part.strip())
946
+ unapplied: list[str] = []
947
+ for version, file_path in source_migrations:
948
+ if version in covered_versions:
949
+ continue
950
+ migration = runner.load_migration(file_path, version)
951
+ replaces = list(migration.get("replaces") or [])
952
+ if replaces and all(rep in covered_versions for rep in replaces):
953
+ continue
954
+ unapplied.append(version)
955
+ if unapplied:
956
+ msg = (
957
+ "Cannot squash with the schema strategy because the database has unapplied migrations "
958
+ f"({', '.join(unapplied)}). Run 'upgrade' so all migrations through {end_version} are applied."
959
+ )
960
+ raise SquashValidationError(msg)
961
+
962
+ def _apply_squash_files(self, squasher: MigrationSquasher, plans: "list[SquashPlan]") -> None:
963
+ """Write squashed migration files, keeping the backup until the caller commits or rolls back."""
964
+ squasher.apply_squash(plans, cleanup_backup=False)
965
+ for plan in plans:
966
+ console.print(f"[green]✓ Created squashed migration: {plan.target_path.name}[/]")
967
+
968
+ def _squash_record_checksum(self, plan: "SquashPlan") -> str:
969
+ """Return the checksum recorded for a squashed migration in the tracking table."""
970
+ return self.runner.calculate_checksum(plan.target_path.read_text(encoding="utf-8"))
971
+
972
+ def _finish_squash(self, squasher: MigrationSquasher) -> None:
973
+ """Remove the squash backup, drop stale migration caches, and report completion."""
974
+ squasher.cleanup_backup()
975
+ self.runner.clear_caches()
976
+ console.print("[green]✓ Squash complete![/]")
977
+
978
+ def _context_dialect(self) -> str | None:
979
+ """Return the configured migration dialect, or None for generic SQL."""
980
+ dialect = MigrationContext.from_config(self.config).dialect
981
+ return None if dialect in _GENERIC_DIALECTS else dialect
982
+
983
+ def _log_reconciliation_load_failure(self, version: str, file_path: Path, error: Exception) -> None:
984
+ """Log a migration file that could not be loaded for tracking-table reconciliation."""
985
+ log_with_context(
986
+ logger,
987
+ logging.DEBUG,
988
+ "migration.list",
989
+ db_system=resolve_db_system(type(self.config).__name__),
990
+ version=version,
991
+ file_path=str(file_path),
992
+ error_type=type(error).__name__,
993
+ status="failed",
994
+ operation="load_for_reconciliation",
995
+ )
996
+
997
+ @staticmethod
998
+ def _evaluate_verification(
999
+ applied_migrations: "list[AppliedMigrationRecord]",
1000
+ loaded_files: "dict[str, LoadedMigrationMetadata]",
1001
+ *,
1002
+ retained_versions: "AbstractSet[str]" = frozenset(),
1003
+ ) -> "dict[str, Any]":
1004
+ """Compare applied tracking records against loaded migration files."""
1005
+ applied_map = {m["version_num"]: m for m in applied_migrations}
1006
+ checksum_mismatches: list[dict[str, str]] = []
1007
+ orphaned_records: list[str] = []
1008
+ pending_versions: list[str] = []
1009
+ partial_squash_errors: list[dict[str, Any]] = []
1010
+ unrecorded_replaces: list[dict[str, Any]] = []
1011
+ covered_applied_versions: set[str] = set()
1012
+
1013
+ for version, migration in loaded_files.items():
1014
+ state, applied_replaces, missing_replaces = MigrationCommandsCore._classify_squash_state(
1015
+ version, migration, applied_map
1016
+ )
1017
+ if state in {"replace", "partial"}:
1018
+ covered_applied_versions.update(applied_replaces)
1019
+ if state == "partial":
1020
+ partial_squash_errors.append({
1021
+ "version": version,
1022
+ "applied_replaces": applied_replaces,
1023
+ "missing_replaces": missing_replaces,
1024
+ })
1025
+ else:
1026
+ unrecorded_replaces.append({"version": version, "replaces": applied_replaces})
1027
+ continue
1028
+ if state == "already_reconciled":
1029
+ covered_applied_versions.update(applied_replaces)
1030
+ elif version not in applied_map:
1031
+ pending_versions.append(version)
1032
+ continue
1033
+ covered_applied_versions.add(version)
1034
+ if version in retained_versions:
1035
+ continue
1036
+ applied_checksum = str(applied_map[version].get("checksum") or "")
1037
+ file_checksum = str(migration.get("checksum") or "")
1038
+ if not BaseMigrationRunner.verify_migration_checksum(migration["content"], applied_checksum):
1039
+ checksum_mismatches.append({"version": version, "expected": applied_checksum, "actual": file_checksum})
1040
+
1041
+ orphaned_records.extend(
1042
+ record["version_num"]
1043
+ for record in applied_migrations
1044
+ if record["version_num"] not in covered_applied_versions and record["version_num"] not in retained_versions
1045
+ )
1046
+ return {
1047
+ "valid": not (checksum_mismatches or orphaned_records or partial_squash_errors or unrecorded_replaces),
1048
+ "checksum_mismatches": checksum_mismatches,
1049
+ "orphaned_records": orphaned_records,
1050
+ "pending_versions": pending_versions,
1051
+ "partial_squash_errors": partial_squash_errors,
1052
+ "unrecorded_replaces": unrecorded_replaces,
1053
+ }
1054
+
1055
+ def _ensure_applied_checksums(self, mismatched: "list[str]") -> None:
1056
+ """Raise when applied migration files changed and checksum verification is enabled.
1057
+
1058
+ Args:
1059
+ mismatched: Versions whose file no longer matches the recorded checksum.
1060
+
1061
+ Raises:
1062
+ MigrationError: When ``mismatched`` is non-empty and ``verify_checksums`` is enabled.
1063
+ """
1064
+ if mismatched and self._get_migration_config().get("verify_checksums", True):
1065
+ msg = (
1066
+ f"Applied migration files changed after they were applied: {', '.join(mismatched)}. "
1067
+ "Restore the files, or review the change and set migration_config['verify_checksums'] = False."
1068
+ )
1069
+ raise MigrationError(msg)
1070
+
1071
+ @staticmethod
1072
+ def _classify_squash_state(
1073
+ target_version: str, migration: "LoadedMigrationMetadata", applied_map: "dict[str, AppliedMigrationRecord]"
1074
+ ) -> "tuple[str, list[str], list[str]]":
1075
+ """Classify a migration file against applied records for squash reconciliation.
1076
+
1077
+ Args:
1078
+ target_version: Version of the migration file.
1079
+ migration: Loaded migration metadata.
1080
+ applied_map: Applied records keyed by ``version_num``.
1081
+
1082
+ Returns:
1083
+ Tuple of ``(state, applied_replaces, missing_replaces)`` where ``state`` is one of ``"none"``,
1084
+ ``"already_reconciled"``, ``"fresh"``, ``"replace"``, or ``"partial"``.
1085
+ """
1086
+ replaces = list(migration.get("replaces") or [])
1087
+ if not replaces:
1088
+ return "none", [], []
1089
+
1090
+ target_record = applied_map.get(target_version)
1091
+ other_replaced_applied = [v for v in replaces if v != target_version and v in applied_map]
1092
+ if (
1093
+ target_record is not None
1094
+ and not other_replaced_applied
1095
+ and (
1096
+ target_version not in replaces
1097
+ or bool(target_record.get("replaces"))
1098
+ or BaseMigrationRunner.verify_migration_checksum(
1099
+ migration["content"], str(target_record.get("checksum") or "")
1100
+ )
1101
+ )
1102
+ ):
1103
+ return "already_reconciled", replaces, []
1104
+
1105
+ applied_replaces = [v for v in replaces if v in applied_map]
1106
+ missing_replaces = [v for v in replaces if v not in applied_map]
1107
+ if not applied_replaces:
1108
+ return "fresh", [], missing_replaces
1109
+ if not missing_replaces:
1110
+ return "replace", applied_replaces, []
1111
+ return "partial", applied_replaces, missing_replaces
1112
+
1113
+ @staticmethod
1114
+ def _raise_partial_squash(
1115
+ target_version: str, applied_replaces: "list[str]", missing_replaces: "list[str]"
1116
+ ) -> NoReturn:
1117
+ """Raise the error for a squashed migration whose replaced versions are only partially applied."""
1118
+ msg = (
1119
+ f"Cannot reconcile squashed migration {target_version}: "
1120
+ f"applied replaced versions {applied_replaces}, missing {missing_replaces}. "
1121
+ "Apply the missing versions with the pre-squash migration files, or restore the database, before "
1122
+ "upgrading with the squashed migration."
1123
+ )
1124
+ raise SquashValidationError(msg)
1125
+
1126
+ @staticmethod
1127
+ def _driver_dialect(driver: Any) -> str | None:
1128
+ """Return the SQL dialect of a driver, or None for generic SQL."""
1129
+ dialect = getattr(driver.data_dictionary, "dialect", None) or getattr(driver, "dialect", None)
1130
+ if dialect is None or str(dialect) in _GENERIC_DIALECTS:
1131
+ return None
1132
+ return str(dialect)
1133
+
1134
+ @staticmethod
1135
+ def _dump_dialect_label(driver: Any, target_dialect: str | None) -> str:
1136
+ """Return the dialect name written into a schema dump header."""
1137
+ return str(
1138
+ target_dialect
1139
+ or getattr(driver.data_dictionary, "dialect", None)
1140
+ or getattr(driver, "dialect", None)
1141
+ or "sql"
1142
+ )
1143
+
1144
+ @staticmethod
1145
+ def _looks_like_data_path(text: str) -> bool:
1146
+ """Return whether a ``from_data`` string is written as a file path rather than a table name."""
1147
+ separators = {"/", os.sep} | ({os.altsep} if os.altsep else set())
1148
+ if any(separator in text for separator in separators):
1149
+ return True
1150
+ lowered = text.lower()
1151
+ return lowered.endswith(SUPPORTED_DATA_FILE_SUFFIXES + _OTHER_DATA_FILE_SUFFIXES)
1152
+
1153
+ @staticmethod
1154
+ def _split_qualified_table(source: str, schema: str | None) -> "tuple[str, str | None]":
1155
+ """Split a ``schema.table`` staging table reference on its last dot unless a schema was given."""
1156
+ if schema is not None or "." not in source:
1157
+ return source, schema
1158
+ source_schema, _, table_name = source.rpartition(".")
1159
+ return table_name, source_schema
1160
+
1161
+ @staticmethod
1162
+ def _data_file_suffix(path: Path) -> str | None:
1163
+ """Return the longest supported data suffix of a file name, or None when it is unsupported."""
1164
+ lowered = path.name.lower()
1165
+ matches = [suffix for suffix in SUPPORTED_DATA_FILE_SUFFIXES if lowered.endswith(suffix)]
1166
+ if not matches or len(lowered) == len(max(matches, key=len)):
1167
+ return None
1168
+ return max(matches, key=len)
1169
+
1170
+ @staticmethod
1171
+ def _read_data_file_records(data_path: Path, suffix: str) -> "list[dict[str, Any]]":
1172
+ """Read JSON or line-delimited JSON records from a (optionally gzipped) data file.
1173
+
1174
+ Raises:
1175
+ MigrationError: When the file exceeds the size cap or does not contain a list of JSON objects.
1176
+ """
1177
+ if suffix.endswith(".gz"):
1178
+ with gzip.open(data_path, mode="rb") as handle:
1179
+ raw = handle.read(_MAX_DATA_FILE_BYTES + 1)
1180
+ if len(raw) > _MAX_DATA_FILE_BYTES:
1181
+ msg = f"Compressed data file '{data_path}' exceeds maximum allowed size ({_MAX_DATA_FILE_BYTES} bytes)"
1182
+ raise MigrationError(msg)
1183
+ content = raw.decode("utf-8")
1184
+ else:
1185
+ if data_path.stat().st_size > _MAX_DATA_FILE_BYTES:
1186
+ msg = f"Data file '{data_path}' exceeds maximum allowed size ({_MAX_DATA_FILE_BYTES} bytes)"
1187
+ raise MigrationError(msg)
1188
+ content = data_path.read_text(encoding="utf-8")
1189
+ decoded: Any
1190
+ if suffix in _LINE_DELIMITED_SUFFIXES:
1191
+ decoded = [from_json(line) for line in content.splitlines() if line.strip()]
1192
+ else:
1193
+ decoded = from_json(content)
1194
+ if not isinstance(decoded, list) or not all(isinstance(row, dict) for row in decoded):
1195
+ msg = f"Data file '{data_path}' must contain a list of JSON objects"
1196
+ raise MigrationError(msg)
1197
+ return cast("list[dict[str, Any]]", decoded)
1198
+
1199
+ @staticmethod
1200
+ def _terminate_statement(statement: str) -> str:
1201
+ """Return a statement with exactly one trailing semicolon."""
1202
+ return statement.strip().rstrip(";").rstrip() + ";"
1203
+
1204
+ @staticmethod
1205
+ def _drop_statement_for(create_statement: str, dialect: str | None) -> str:
1206
+ """Build ``DROP TABLE IF EXISTS`` for the exact table a CREATE TABLE statement creates.
1207
+
1208
+ Raises:
1209
+ MigrationError: When the statement cannot be parsed as CREATE TABLE.
1210
+ """
1211
+ try:
1212
+ parsed = sqlglot.parse_one(create_statement, read=dialect)
1213
+ except SqlglotError as exc:
1214
+ msg = f"Could not parse inferred DDL to build its DROP statement: {exc}"
1215
+ raise MigrationError(msg) from exc
1216
+ target = parsed.this if isinstance(parsed, exp.Create) else None
1217
+ if isinstance(target, exp.Schema):
1218
+ target = target.this
1219
+ if not isinstance(target, exp.Table):
1220
+ msg = f"Inferred DDL is not a CREATE TABLE statement: {create_statement}"
1221
+ raise MigrationError(msg)
1222
+ drop = exp.Drop(kind="TABLE", tables=[target], exists=True)
1223
+ return MigrationCommandsCore._terminate_statement(drop.sql(dialect=dialect, copy=False))
1224
+
1225
+ @staticmethod
1226
+ def _ensure_schema_extraction_safe_sync(
1227
+ driver: Any, *, schema: str | None = None, exclude_tables: "Sequence[str] | None" = None
1228
+ ) -> None:
1229
+ """Refuse row-security objects and warn about objects schema extraction drops."""
1230
+ _ensure_schema_extraction_safe_sync(driver, schema=schema, exclude_tables=exclude_tables)
1231
+
1232
+ @staticmethod
1233
+ async def _ensure_schema_extraction_safe_async(
1234
+ driver: Any, *, schema: str | None = None, exclude_tables: "Sequence[str] | None" = None
1235
+ ) -> None:
1236
+ """Refuse row-security objects and warn about objects schema extraction drops asynchronously."""
1237
+ await _ensure_schema_extraction_safe_async(driver, schema=schema, exclude_tables=exclude_tables)
1238
+
1239
+
1240
+ class SyncMigrationCommands(MigrationCommandsCore["SyncConfigT", SyncMigrationRunner]):
1241
+ """Synchronous migration commands."""
1242
+
1243
+ def __init__(self, config: "SyncConfigT") -> None:
1244
+ """Initialize migration commands.
1245
+
1246
+ Args:
1247
+ config: The SQLSpec configuration.
1248
+ """
1249
+ super().__init__(config)
1250
+ self.tracker = self._create_tracker()
1251
+ context = MigrationContext.from_config(self.config)
1252
+ context.extension_config = self.extension_configs
1253
+
1254
+ self.runner = SyncMigrationRunner(
1255
+ self.migrations_path,
1256
+ self._discover_extension_migrations(),
1257
+ context,
1258
+ self.extension_configs,
1259
+ runtime=self._runtime,
1260
+ description_hints=self._template_settings.description_hints,
1261
+ )
1262
+ self.runner.project_root = self.project_root
1263
+
1264
+ def init(self, directory: str, package: bool = True) -> None:
1265
+ """Initialize migration directory structure.
1266
+
1267
+ Args:
1268
+ directory: Directory to initialize migrations in.
1269
+ package: Whether to create __init__.py file.
1270
+ """
1271
+ self.init_directory(directory, package)
1272
+
1273
+ def current(self, verbose: bool = False) -> "str | None":
1274
+ """Show current migration version.
1275
+
1276
+ Args:
1277
+ verbose: Whether to show detailed migration history.
1278
+
1279
+ Returns:
1280
+ The current migration version or None if no migrations applied.
1281
+ """
1282
+ with self.config.provide_session() as driver:
1283
+ tables = driver.data_dictionary.get_tables(driver, schema=self.tracker.catalog_schema_name())
1284
+ tracking_exists = self._tracking_table_exists(tables)
1285
+
1286
+ applied: list[AppliedMigrationRecord] = []
1287
+ if not tracking_exists:
1288
+ current = None
1289
+ else:
1290
+ self.tracker.ensure_tracking_table(driver)
1291
+ if verbose:
1292
+ applied = self.tracker.get_applied_migrations(driver)
1293
+ current = applied[-1]["version_num"] if applied else None
1294
+ else:
1295
+ current = self.tracker.get_current_version(driver)
1296
+ if not current:
1297
+ log_with_context(
1298
+ logger,
1299
+ logging.DEBUG,
1300
+ "migration.list",
1301
+ db_system=resolve_db_system(type(driver).__name__),
1302
+ current_version=None,
1303
+ applied_count=0,
1304
+ verbose=verbose,
1305
+ status="empty",
1306
+ )
1307
+ if verbose:
1308
+ self._print_configured_reconcilers()
1309
+ console.print("[yellow]No migrations applied yet[/]")
1310
+ return None
1311
+
1312
+ console.print(f"[green]Current version:[/] {current}")
1313
+
1314
+ if verbose:
1315
+ table = Table(title="Applied Migrations")
1316
+ table.add_column("Version", style="cyan")
1317
+ table.add_column("Description")
1318
+ table.add_column("Applied At")
1319
+ table.add_column("Time (ms)", justify="right")
1320
+ table.add_column("Applied By")
1321
+
1322
+ for migration in applied:
1323
+ table.add_row(
1324
+ migration["version_num"],
1325
+ migration.get("description", ""),
1326
+ str(migration.get("applied_at", "")),
1327
+ str(migration.get("execution_time_ms", "")),
1328
+ migration.get("applied_by", ""),
1329
+ )
1330
+
1331
+ console.print(table)
1332
+ self._print_configured_reconcilers()
1333
+
1334
+ applied_count = len(applied) if verbose else None
1335
+ log_with_context(
1336
+ logger,
1337
+ logging.DEBUG,
1338
+ "migration.list",
1339
+ db_system=resolve_db_system(type(driver).__name__),
1340
+ current_version=current,
1341
+ applied_count=applied_count,
1342
+ verbose=verbose,
1343
+ status="complete",
1344
+ )
1345
+ return cast("str | None", current)
1346
+
1347
+ @_with_command_span("upgrade", metadata_fn=_command_metadata)
1348
+ def upgrade(
1349
+ self,
1350
+ revision: str = "head",
1351
+ allow_missing: bool = False,
1352
+ auto_sync: bool = True,
1353
+ dry_run: bool = False,
1354
+ *,
1355
+ use_logger: bool = False,
1356
+ echo: bool | None = None,
1357
+ summary_only: bool | None = None,
1358
+ ) -> None:
1359
+ """Upgrade to a target revision.
1360
+
1361
+ Validates migration order and warns if out-of-order migrations are detected.
1362
+ Out-of-order migrations can occur when branches merge in different orders
1363
+ across environments.
1364
+
1365
+ Args:
1366
+ revision: Target revision or "head" for latest.
1367
+ allow_missing: If True, allow out-of-order migrations even in strict mode.
1368
+ Defaults to False.
1369
+ auto_sync: If True, automatically reconcile renamed and squashed migrations in the tracking table.
1370
+ Defaults to True. Can be disabled via --no-auto-sync flag. A partially applied squash raises
1371
+ ``SquashValidationError`` either way.
1372
+ dry_run: If True, report the reconciliation and migrations that would run without creating the
1373
+ tracking table or writing any tracking rows.
1374
+ use_logger: If True, output to logger instead of Rich console.
1375
+ Defaults to False. Can be set via MigrationConfig for persistent default.
1376
+ echo: Echo output to the console. Defaults to True when unset.
1377
+ summary_only: Emit a single summary log entry when logger output is enabled.
1378
+ """
1379
+ runtime = self._runtime
1380
+ applied_count = 0
1381
+ pending_count = 0
1382
+ reconcilers_invoked: list[str] = []
1383
+ has_reconcilers = False
1384
+ db_system: str | None = None
1385
+ error: Exception | None = None
1386
+ ul, echo_value, summary_value = self._resolve_output_policy(use_logger, echo, summary_only)
1387
+ self.runner.set_use_logger(ul)
1388
+ self.runner.set_summary_only(summary_value)
1389
+ self.tracker.set_output_policy(use_logger=ul, echo=echo_value, summary_only=summary_value)
1390
+ output_info = functools.partial(_output_info, ul, echo_value, summary_value)
1391
+ start_time = time.perf_counter()
1392
+
1393
+ try:
1394
+ self.ensure_reconcilers_allow("upgrade", revision)
1395
+ has_reconcilers = bool(self.extension_reconcilers)
1396
+ if dry_run:
1397
+ output_info(
1398
+ "DRY RUN MODE: No database changes will be applied",
1399
+ rich_message="[bold yellow]DRY RUN MODE:[/] No database changes will be applied\n",
1400
+ )
1401
+
1402
+ with self.config.provide_session() as driver, self._hold_migration_lock(driver, dry_run=dry_run):
1403
+ db_system = resolve_db_system(type(driver).__name__)
1404
+ self.runner.set_driver(driver)
1405
+ applied_versions = self._synchronized_applied_versions(
1406
+ driver,
1407
+ auto_sync=auto_sync and bool(self._get_migration_config().get("auto_sync", True)),
1408
+ dry_run=dry_run,
1409
+ use_logger=ul,
1410
+ echo=echo_value,
1411
+ summary_only=summary_value,
1412
+ )
1413
+ self._enforce_applied_checksums(
1414
+ driver, dry_run=dry_run, use_logger=ul, echo=echo_value, summary_only=summary_value
1415
+ )
1416
+ applied_set = set(applied_versions)
1417
+
1418
+ all_migrations = self.runner.get_migration_files()
1419
+ if runtime is not None:
1420
+ runtime.increment_metric("migrations.command.upgrade.available", float(len(all_migrations)))
1421
+
1422
+ pending = self._collect_pending_migrations(all_migrations, applied_set, revision)
1423
+ pending_count = len(pending)
1424
+
1425
+ if runtime is not None:
1426
+ runtime.increment_metric("migrations.command.upgrade.pending", float(len(pending)))
1427
+
1428
+ if pending:
1429
+ migration_config = cast("dict[str, Any]", self.config.migration_config) or {}
1430
+ strict_ordering = migration_config.get("strict_ordering", False) and not allow_missing
1431
+ validate_migration_order(
1432
+ [v for v, _ in pending],
1433
+ applied_versions,
1434
+ strict_ordering,
1435
+ use_logger=ul,
1436
+ echo=echo_value,
1437
+ summary_only=summary_value,
1438
+ )
1439
+
1440
+ if dry_run:
1441
+ self.report_reconciler_preview(use_logger=ul, echo=echo_value, summary_only=summary_value)
1442
+ elif has_reconcilers:
1443
+ self._run_reconcilers(
1444
+ driver, reconcilers_invoked, use_logger=ul, echo=echo_value, summary_only=summary_value
1445
+ )
1446
+
1447
+ if not pending:
1448
+ _report_no_pending_migrations(
1449
+ ul, echo_value, summary_value, bool(all_migrations or has_reconcilers)
1450
+ )
1451
+ return
1452
+
1453
+ output_info(
1454
+ "Found %d pending migrations",
1455
+ len(pending),
1456
+ rich_message=f"[yellow]Found {len(pending)} pending migrations[/]",
1457
+ )
1458
+
1459
+ for version, file_path in pending:
1460
+ migration = self.runner.load_migration(file_path, version)
1461
+ action_verb = "Would apply" if dry_run else "Applying"
1462
+ output_info(
1463
+ "%s %s: %s",
1464
+ action_verb,
1465
+ version,
1466
+ migration["description"],
1467
+ rich_message=f"\n[cyan]{action_verb} {version}:[/] {migration['description']}",
1468
+ )
1469
+
1470
+ if dry_run:
1471
+ output_info(
1472
+ "Migration file: %s", file_path, rich_message=f"[dim]Migration file: {file_path}[/]"
1473
+ )
1474
+ continue
1475
+
1476
+ result = self._apply_single_migration(driver, migration, version, ul, echo_value, summary_value)
1477
+ if result is None:
1478
+ break
1479
+ applied_count += 1
1480
+
1481
+ except Exception as exc: # pragma: no cover
1482
+ error = exc
1483
+ raise
1484
+ finally:
1485
+ effective_error = error or self._last_command_error
1486
+ if not dry_run and applied_count:
1487
+ self._record_command_metric("applied", float(applied_count))
1488
+ duration_ms = int((time.perf_counter() - start_time) * 1000)
1489
+ _log_command_summary(
1490
+ use_logger=ul,
1491
+ summary_only=summary_value,
1492
+ command="upgrade",
1493
+ status="failed" if effective_error else "complete",
1494
+ revision=revision,
1495
+ dry_run=dry_run,
1496
+ pending_count=pending_count,
1497
+ applied_count=applied_count,
1498
+ reverted_count=None,
1499
+ duration_ms=duration_ms,
1500
+ db_system=db_system,
1501
+ bind_key=getattr(self.config, "bind_key", None),
1502
+ config_name=type(self.config).__name__,
1503
+ error=effective_error,
1504
+ allow_missing=allow_missing,
1505
+ auto_sync=auto_sync,
1506
+ reconcilers_invoked=len(reconcilers_invoked) if has_reconcilers else None,
1507
+ )
1508
+
1509
+ recorded_error = self._last_command_error
1510
+ if recorded_error is not None:
1511
+ _raise_as_migration_error(recorded_error)
1512
+
1513
+ if dry_run:
1514
+ output_info(
1515
+ "Dry run complete. No changes were made to the database.",
1516
+ rich_message="\n[bold yellow]Dry run complete.[/] No changes were made to the database.",
1517
+ )
1518
+ elif applied_count > 0 and self._last_command_error is None:
1519
+ auto_dump_path = self._auto_dump_path()
1520
+ if auto_dump_path is not None:
1521
+ try:
1522
+ self.dump_schema(output_path=auto_dump_path, echo=echo_value)
1523
+ except _AUTO_DUMP_ERRORS as exc:
1524
+ self._report_auto_dump_failure(auto_dump_path, exc, use_logger=ul, echo=echo_value)
1525
+
1526
+ @_with_command_span("downgrade", metadata_fn=_command_metadata)
1527
+ def downgrade(
1528
+ self,
1529
+ revision: str = "-1",
1530
+ *,
1531
+ dry_run: bool = False,
1532
+ use_logger: bool = False,
1533
+ echo: bool | None = None,
1534
+ summary_only: bool | None = None,
1535
+ ) -> None:
1536
+ """Downgrade to a target revision.
1537
+
1538
+ Args:
1539
+ revision: Target revision or "-1" for one step back.
1540
+ dry_run: If True, show what would be done without making changes.
1541
+ use_logger: If True, output to logger instead of Rich console.
1542
+ Defaults to False. Can be set via MigrationConfig for persistent default.
1543
+ echo: Echo output to the console. Defaults to True when unset.
1544
+ summary_only: Emit a single summary log entry when logger output is enabled.
1545
+ """
1546
+ runtime = self._runtime
1547
+ reverted_count = 0
1548
+ pending_count = 0
1549
+ reconcilers_invoked: list[str] = []
1550
+ has_reconcilers = False
1551
+ reaches_base = False
1552
+ db_system: str | None = None
1553
+ error: Exception | None = None
1554
+ ul, echo_value, summary_value = self._resolve_output_policy(use_logger, echo, summary_only)
1555
+ self.runner.set_use_logger(ul)
1556
+ self.runner.set_summary_only(summary_value)
1557
+ self.tracker.set_output_policy(use_logger=ul, echo=echo_value, summary_only=summary_value)
1558
+ output_info = functools.partial(_output_info, ul, echo_value, summary_value)
1559
+ output_error = functools.partial(_output_error, ul, echo_value, summary_value)
1560
+ start_time = time.perf_counter()
1561
+
1562
+ try:
1563
+ self.ensure_reconcilers_allow("downgrade", revision)
1564
+ has_reconcilers = bool(self.extension_reconcilers)
1565
+ if dry_run:
1566
+ output_info(
1567
+ "DRY RUN MODE: No database changes will be applied",
1568
+ rich_message="[bold yellow]DRY RUN MODE:[/] No database changes will be applied\n",
1569
+ )
1570
+
1571
+ with self.config.provide_session() as driver, self._hold_migration_lock(driver, dry_run=dry_run):
1572
+ db_system = resolve_db_system(type(driver).__name__)
1573
+ self.runner.set_driver(driver)
1574
+ self.tracker.ensure_tracking_table(driver)
1575
+ applied: list[AppliedMigrationRecord] = self.tracker.get_applied_migrations(driver)
1576
+ retained_reconcile = self._retained_reconcile_versions(applied)
1577
+ active_applied = [m for m in applied if m["version_num"] not in retained_reconcile]
1578
+ if runtime is not None:
1579
+ runtime.increment_metric("migrations.command.downgrade.available", float(len(active_applied)))
1580
+ if not active_applied and not (revision == "base" and has_reconcilers):
1581
+ output_info("No migrations to downgrade", rich_message="[yellow]No migrations to downgrade[/]")
1582
+ return
1583
+
1584
+ to_revert = self._collect_revert_migrations(active_applied, revision) if active_applied else []
1585
+ reaches_base = revision == "base"
1586
+ pending_count = len(to_revert)
1587
+
1588
+ if runtime is not None:
1589
+ runtime.increment_metric("migrations.command.downgrade.pending", float(len(to_revert)))
1590
+
1591
+ if not to_revert and not (reaches_base and has_reconcilers):
1592
+ output_info("Nothing to downgrade", rich_message="[yellow]Nothing to downgrade[/]")
1593
+ return
1594
+
1595
+ if to_revert:
1596
+ self._enforce_applied_checksums(
1597
+ driver,
1598
+ dry_run=dry_run,
1599
+ use_logger=ul,
1600
+ echo=echo_value,
1601
+ summary_only=summary_value,
1602
+ records=active_applied,
1603
+ versions={record["version_num"] for record in to_revert},
1604
+ )
1605
+ output_info(
1606
+ "Reverting %d migrations",
1607
+ len(to_revert),
1608
+ rich_message=f"[yellow]Reverting {len(to_revert)} migrations[/]",
1609
+ )
1610
+ all_files = dict(self.runner.get_migration_files())
1611
+
1612
+ for migration_record in to_revert:
1613
+ version = migration_record["version_num"]
1614
+ if version not in all_files:
1615
+ output_error(
1616
+ "Migration file not found for %s",
1617
+ version,
1618
+ rich_message=f"[red]Migration file not found for {version}[/]",
1619
+ )
1620
+ if runtime is not None:
1621
+ runtime.increment_metric("migrations.command.downgrade.missing_files")
1622
+ self._last_command_error = MigrationError(f"Migration file not found for {version}")
1623
+ break
1624
+
1625
+ migration = self.runner.load_migration(all_files[version], version)
1626
+ action_verb = "Would revert" if dry_run else "Reverting"
1627
+ output_info(
1628
+ "%s %s: %s",
1629
+ action_verb,
1630
+ version,
1631
+ migration["description"],
1632
+ rich_message=f"\n[cyan]{action_verb} {version}:[/] {migration['description']}",
1633
+ )
1634
+
1635
+ if dry_run:
1636
+ output_info(
1637
+ "Migration file: %s",
1638
+ all_files[version],
1639
+ rich_message=f"[dim]Migration file: {all_files[version]}[/]",
1640
+ )
1641
+ continue
1642
+
1643
+ result = self._revert_single_migration(
1644
+ driver, migration, version, ul, echo_value, summary_value
1645
+ )
1646
+ if result is None:
1647
+ break
1648
+ reverted_count += 1
1649
+
1650
+ if reaches_base and has_reconcilers and self._last_command_error is None:
1651
+ if dry_run:
1652
+ self.report_reconciler_downgrade_preview(
1653
+ use_logger=ul, echo=echo_value, summary_only=summary_value
1654
+ )
1655
+ else:
1656
+ self._run_reconciler_downgrades(
1657
+ driver,
1658
+ retained_reconcile,
1659
+ reconcilers_invoked,
1660
+ use_logger=ul,
1661
+ echo=echo_value,
1662
+ summary_only=summary_value,
1663
+ )
1664
+
1665
+ except Exception as exc: # pragma: no cover
1666
+ error = exc
1667
+ raise
1668
+ finally:
1669
+ effective_error = error or self._last_command_error
1670
+ if not dry_run and reverted_count:
1671
+ self._record_command_metric("reverted", float(reverted_count))
1672
+ duration_ms = int((time.perf_counter() - start_time) * 1000)
1673
+ _log_command_summary(
1674
+ use_logger=ul,
1675
+ summary_only=summary_value,
1676
+ command="downgrade",
1677
+ status="failed" if effective_error else "complete",
1678
+ revision=revision,
1679
+ dry_run=dry_run,
1680
+ pending_count=pending_count,
1681
+ applied_count=None,
1682
+ reverted_count=reverted_count,
1683
+ duration_ms=duration_ms,
1684
+ db_system=db_system,
1685
+ bind_key=getattr(self.config, "bind_key", None),
1686
+ config_name=type(self.config).__name__,
1687
+ error=effective_error,
1688
+ reconcilers_invoked=len(reconcilers_invoked) if (reaches_base and has_reconcilers) else None,
1689
+ )
1690
+
1691
+ recorded_error = self._last_command_error
1692
+ if recorded_error is not None:
1693
+ _raise_as_migration_error(recorded_error)
1694
+
1695
+ if dry_run:
1696
+ output_info(
1697
+ "Dry run complete. No changes were made to the database.",
1698
+ rich_message="\n[bold yellow]Dry run complete.[/] No changes were made to the database.",
1699
+ )
1700
+
1701
+ def stamp(self, revision: str) -> None:
1702
+ """Mark database as being at a specific revision without running migrations.
1703
+
1704
+ Args:
1705
+ revision: The revision to stamp.
1706
+ """
1707
+ with self.config.provide_session() as driver, self._hold_migration_lock(driver):
1708
+ self.tracker.ensure_tracking_table(driver)
1709
+ applied = self.tracker.get_applied_migrations(driver) if self.extension_reconcilers else []
1710
+ retained = self._retained_reconcile_versions(applied)
1711
+ if revision == "base":
1712
+ clear_sql = (
1713
+ sql.delete().from_(self.tracker.version_table).where_not_in("version_num", sorted(retained))
1714
+ if retained
1715
+ else sql.delete().from_(self.tracker.version_table)
1716
+ )
1717
+ driver.execute(clear_sql)
1718
+ if isinstance(self.tracker, SyncMigrationTracker):
1719
+ self.tracker._safe_commit(driver)
1720
+ console.print("[green]Database stamped at revision base[/]")
1721
+ return
1722
+
1723
+ all_migrations_list = self.runner.get_migration_files()
1724
+ target_version: str | None = None
1725
+ try:
1726
+ parsed_target = parse_version(revision)
1727
+ except ValueError:
1728
+ parsed_target = None
1729
+
1730
+ for v, _ in all_migrations_list:
1731
+ if v == revision:
1732
+ target_version = v
1733
+ break
1734
+ if parsed_target is not None:
1735
+ try:
1736
+ if parse_version(v) == parsed_target:
1737
+ target_version = v
1738
+ break
1739
+ except ValueError:
1740
+ continue
1741
+
1742
+ if target_version is None:
1743
+ msg = f"Unknown revision: {revision}"
1744
+ raise MigrationError(msg)
1745
+
1746
+ target_parsed = parse_version(target_version) if parsed_target is not None else None
1747
+ clear_sql = (
1748
+ sql.delete().from_(self.tracker.version_table).where_not_in("version_num", sorted(retained))
1749
+ if retained
1750
+ else sql.delete().from_(self.tracker.version_table)
1751
+ )
1752
+ driver.execute(clear_sql)
1753
+ for v, path in all_migrations_list:
1754
+ should_record = False
1755
+ if target_parsed is not None:
1756
+ try:
1757
+ v_parsed = parse_version(v)
1758
+ if v_parsed.extension == target_parsed.extension and v_parsed <= target_parsed:
1759
+ should_record = True
1760
+ except ValueError:
1761
+ should_record = v == target_version
1762
+ elif v == target_version:
1763
+ should_record = True
1764
+ if should_record:
1765
+ if path.exists():
1766
+ migration = self.runner.load_migration(path, v)
1767
+ description = migration["description"] or f"Stamped to {v}"
1768
+ checksum = migration["checksum"]
1769
+ else:
1770
+ description = f"Stamped to {v}"
1771
+ checksum = "manual-stamp"
1772
+ self.tracker.record_migration(driver, v, description, 0, checksum)
1773
+ console.print(f"[green]Database stamped at revision {target_version}[/]")
1774
+
1775
+ def revision(
1776
+ self,
1777
+ message: str,
1778
+ file_type: str | None = None,
1779
+ *,
1780
+ from_schema: bool = False,
1781
+ from_data: "str | Path | None" = None,
1782
+ schema: str | None = None,
1783
+ target_table: str | None = None,
1784
+ ) -> "Path":
1785
+ """Create a new migration file with timestamp-based versioning.
1786
+
1787
+ Generates a unique timestamp version (YYYYMMDDHHmmss format) to avoid
1788
+ conflicts when multiple developers create migrations concurrently.
1789
+
1790
+ Args:
1791
+ message: Description for the migration.
1792
+ file_type: Type of migration file to create ('sql' or 'py').
1793
+ from_schema: When True, populate the migration with the current database schema DDL.
1794
+ from_data: Data file path or staging table name to infer DDL from. See
1795
+ ``MigrationCommandsCore._resolve_data_source`` for the detection rules.
1796
+ schema: Optional database schema name.
1797
+ target_table: Optional target table name when bootstrapping from data.
1798
+
1799
+ Returns:
1800
+ Path to the created migration file.
1801
+
1802
+ Raises:
1803
+ MigrationError: When both sources are given or DDL cannot be inferred.
1804
+ """
1805
+ source = self._prepare_revision_source(from_schema=from_schema, from_data=from_data)
1806
+ up_sql: Sequence[str] | None = None
1807
+ down_sql: Sequence[str] | None = None
1808
+ if from_schema:
1809
+ excluded = self._version_table_exclusion()
1810
+ with self.config.provide_session() as driver:
1811
+ self._ensure_schema_extraction_safe_sync(driver, schema=schema, exclude_tables=excluded)
1812
+ up_sql, down_sql = schema_ddl_statements(
1813
+ driver.data_dictionary.get_schema_ddl(
1814
+ driver, schema=schema, exclude_tables=excluded, direction="create"
1815
+ ),
1816
+ driver.data_dictionary.get_schema_ddl(
1817
+ driver, schema=schema, exclude_tables=excluded, direction="drop"
1818
+ ),
1819
+ )
1820
+ elif isinstance(source, Path):
1821
+ up_sql, down_sql = self._data_file_revision_sql(source, schema=schema, target_table=target_table)
1822
+ elif isinstance(source, str):
1823
+ source_table, source_schema = self._split_qualified_table(source, schema)
1824
+ with self.config.provide_session() as driver:
1825
+ try:
1826
+ ddl_res = driver.data_dictionary.infer_table_ddl_from_data(
1827
+ driver, source_table, schema=source_schema, target_table=target_table
1828
+ )
1829
+ except (SqlglotError, SQLBuilderError) as exc:
1830
+ msg = f"Could not infer DDL from table '{source}': {exc}"
1831
+ raise MigrationError(msg) from exc
1832
+ up_sql, down_sql = self._staging_table_revision_sql(ddl_res.ddl, source, self._driver_dialect(driver))
1833
+
1834
+ return self._write_revision(message, file_type, up_sql, down_sql)
1835
+
1836
+ def dump_schema(
1837
+ self,
1838
+ output_path: "str | Path | None" = None,
1839
+ *,
1840
+ schema: str | None = None,
1841
+ include_migrations_table: bool = False,
1842
+ prefer_native: bool = True,
1843
+ target_dialect: str | None = None,
1844
+ echo: bool | None = None,
1845
+ ) -> str:
1846
+ """Dump the full current database schema DDL to a string and optional file path.
1847
+
1848
+ Args:
1849
+ output_path: Optional file path to write the rendered schema SQL.
1850
+ schema: Optional database schema name to inspect.
1851
+ include_migrations_table: Whether to include the migration tracking table.
1852
+ prefer_native: Prefer engine-native catalog DDL when available.
1853
+ target_dialect: Optional target SQLGlot dialect for cross-dialect transpilation.
1854
+ echo: Echo output to the console.
1855
+
1856
+ Returns:
1857
+ Rendered schema DDL string.
1858
+ """
1859
+ _, echo_value, _ = self._resolve_output_policy(False, echo, False)
1860
+ excluded = self._version_table_exclusion(include_migrations_table)
1861
+ with self.config.provide_session() as driver:
1862
+ self._ensure_schema_extraction_safe_sync(driver, schema=schema, exclude_tables=excluded)
1863
+ create_res = driver.data_dictionary.get_schema_ddl(
1864
+ driver,
1865
+ schema=schema,
1866
+ exclude_tables=excluded,
1867
+ direction="create",
1868
+ prefer_native=prefer_native,
1869
+ target_dialect=target_dialect,
1870
+ )
1871
+ dialect_label = self._dump_dialect_label(driver, target_dialect)
1872
+ return self._render_schema_dump(
1873
+ create_res, dialect_label=dialect_label, schema=schema, output_path=output_path, echo=echo_value
1874
+ )
1875
+
1876
+ def verify(
1877
+ self, *, strict: bool = False, fail_on_pending: bool = False, use_logger: bool = False, echo: bool | None = None
1878
+ ) -> "dict[str, Any]":
1879
+ """Verify database migration tracking records against migration files on disk.
1880
+
1881
+ Verification is read-only: a missing tracking table is reported as every migration pending and is never
1882
+ created.
1883
+
1884
+ Args:
1885
+ strict: Raise ``MigrationError`` when checksum drift, orphaned records, or partial squashes exist.
1886
+ fail_on_pending: Raise ``MigrationError`` when migrations are pending.
1887
+ use_logger: Output verification messages to logger instead of Rich console.
1888
+ echo: Echo output to the console.
1889
+
1890
+ Returns:
1891
+ Verification report dictionary with ``valid``, ``checksum_mismatches``, ``orphaned_records``,
1892
+ ``pending_versions``, and ``partial_squash_errors``.
1893
+ """
1894
+ ul, echo_value, summary_value = self._resolve_output_policy(use_logger, echo, None)
1895
+ with self.config.provide_session() as driver:
1896
+ applied_migrations = self._read_applied_migrations(driver)
1897
+
1898
+ self.runner.clear_caches()
1899
+ migration_files = self.runner.get_migration_files()
1900
+ loaded_files: dict[str, LoadedMigrationMetadata] = {
1901
+ version: self.runner.load_migration(file_path, version) for version, file_path in migration_files
1902
+ }
1903
+ report = self._verification_report(
1904
+ applied_migrations,
1905
+ loaded_files,
1906
+ strict=strict,
1907
+ fail_on_pending=fail_on_pending,
1908
+ use_logger=ul,
1909
+ echo=echo_value,
1910
+ summary_only=summary_value,
1911
+ )
1912
+ if not report["checksum_mismatches"]:
1913
+ _, rerecord = self._applied_checksum_audit(applied_migrations, migration_files)
1914
+ if rerecord:
1915
+ with self.config.provide_session() as driver, self._hold_migration_lock(driver):
1916
+ self._rerecord_legacy_checksums(
1917
+ driver, rerecord, dry_run=False, use_logger=ul, echo=echo_value, summary_only=summary_value
1918
+ )
1919
+ return report
1920
+
1921
+ def squash(
1922
+ self,
1923
+ start_version: str | None = None,
1924
+ end_version: str | None = None,
1925
+ description: str | None = None,
1926
+ *,
1927
+ dry_run: bool = False,
1928
+ update_database: bool = True,
1929
+ yes: bool = False,
1930
+ allow_gaps: bool = False,
1931
+ output_format: str = "sql",
1932
+ strategy: str = "concat",
1933
+ single_file: bool | None = None,
1934
+ ) -> None:
1935
+ """Squash a range of migrations into a single file.
1936
+
1937
+ Combines multiple sequential or timestamped migrations into a single release migration.
1938
+
1939
+ Args:
1940
+ start_version: First version in the range to squash (inclusive).
1941
+ When None, defaults to the first core migration found.
1942
+ end_version: Last version in the range to squash (inclusive).
1943
+ When None, defaults to the last core migration found.
1944
+ description: Description for the squashed migration file.
1945
+ When None, defaults to 'initial_schema' if yes=True or prompts interactively.
1946
+ dry_run: Preview changes without applying.
1947
+ update_database: Update migration records in database.
1948
+ yes: Skip confirmation prompt.
1949
+ allow_gaps: Allow gaps in version sequence.
1950
+ output_format: Output format ("sql" or "py").
1951
+ strategy: Squash strategy: "concat" (default) keeps every statement in order, "ddl" folds DDL and
1952
+ refuses ranges it cannot fold faithfully, "schema" reflects the live database schema.
1953
+ single_file: Force a single squashed file when True, split by file type/directives when False or None.
1954
+ """
1955
+ resolved_strategy = strategy.lower()
1956
+ all_migrations = self.runner.get_migration_files()
1957
+ squasher = self._create_squasher(self.runner, resolved_strategy)
1958
+ version_range = self._resolve_squash_range(all_migrations, start_version, end_version)
1959
+ if version_range is None:
1960
+ return
1961
+ if description is None:
1962
+ description = (
1963
+ "initial_schema" if yes else Prompt.ask("Migration description", default="squashed_migrations")
1964
+ )
1965
+
1966
+ schema_ddl: tuple[list[str], list[str]] | None = None
1967
+ if resolved_strategy == "schema":
1968
+ squasher.plan_squash(
1969
+ version_range[0],
1970
+ version_range[1],
1971
+ description,
1972
+ allow_gaps=allow_gaps,
1973
+ output_format=output_format,
1974
+ strategy=resolved_strategy,
1975
+ single_file=single_file,
1976
+ )
1977
+ excluded = self._version_table_exclusion()
1978
+ with self.config.provide_session() as driver:
1979
+ self._validate_schema_squash_applied(
1980
+ self.runner,
1981
+ all_migrations,
1982
+ version_range[0],
1983
+ version_range[1],
1984
+ allow_gaps=allow_gaps,
1985
+ applied_migrations=self._read_applied_migrations(driver),
1986
+ )
1987
+ self._ensure_schema_extraction_safe_sync(driver, exclude_tables=excluded)
1988
+ schema_ddl = schema_ddl_statements(
1989
+ driver.data_dictionary.get_schema_ddl(driver, exclude_tables=excluded, direction="create"),
1990
+ driver.data_dictionary.get_schema_ddl(driver, exclude_tables=excluded, direction="drop"),
1991
+ )
1992
+
1993
+ plans = squasher.plan_squash(
1994
+ version_range[0],
1995
+ version_range[1],
1996
+ description,
1997
+ allow_gaps=allow_gaps,
1998
+ output_format=output_format,
1999
+ strategy=resolved_strategy,
2000
+ single_file=single_file,
2001
+ schema_ddl=schema_ddl,
2002
+ )
2003
+ self._print_squash_plan(plans)
2004
+ if dry_run:
2005
+ self._print_squash_dry_run(squasher, plans)
2006
+ return
2007
+ if not yes and not Confirm.ask("Proceed with squash?", default=False):
2008
+ console.print("[yellow]Squash cancelled[/]")
2009
+ return
2010
+
2011
+ try:
2012
+ if update_database:
2013
+ with self.config.provide_session() as driver, self._hold_migration_lock(driver):
2014
+ self.tracker.ensure_tracking_table(driver)
2015
+ applied_plans = [
2016
+ plan
2017
+ for plan in plans
2018
+ if self.tracker.is_squash_already_applied(driver, plan.target_version, plan.source_versions)
2019
+ ]
2020
+ self._apply_squash_files(squasher, plans)
2021
+ for plan in applied_plans:
2022
+ self.tracker.replace_with_squash(
2023
+ driver,
2024
+ plan.target_version,
2025
+ plan.source_versions,
2026
+ description,
2027
+ self._squash_record_checksum(plan),
2028
+ )
2029
+ console.print("[green]✓ Updated migration tracking table[/]")
2030
+ else:
2031
+ self._apply_squash_files(squasher, plans)
2032
+ except BaseException:
2033
+ squasher.rollback_backup()
2034
+ raise
2035
+ self._finish_squash(squasher)
2036
+
2037
+ def fix(self, dry_run: bool = False, update_database: bool = True, yes: bool = False) -> None:
2038
+ """Convert timestamp migrations to sequential format.
2039
+
2040
+ Implements hybrid versioning workflow where development uses timestamps
2041
+ and production uses sequential numbers. Creates backup before changes
2042
+ and provides rollback on errors.
2043
+
2044
+ Args:
2045
+ dry_run: Preview changes without applying.
2046
+ update_database: Update migration records in database.
2047
+ yes: Skip confirmation prompt.
2048
+ """
2049
+ all_migrations = self.runner.get_migration_files()
2050
+
2051
+ conversion_map = generate_conversion_map(all_migrations)
2052
+
2053
+ if not conversion_map:
2054
+ console.print("[yellow]No timestamp migrations found - nothing to convert[/]")
2055
+ return
2056
+
2057
+ fixer = MigrationFixer(self.migrations_path)
2058
+ try:
2059
+ renames = fixer.plan_renames(conversion_map)
2060
+ except ValueError as exc:
2061
+ raise MigrationError(str(exc)) from exc
2062
+
2063
+ table = Table(title="Migration Conversions")
2064
+ table.add_column("Current Version", style="cyan")
2065
+ table.add_column("New Version", style="green")
2066
+ table.add_column("File")
2067
+
2068
+ for rename in renames:
2069
+ table.add_row(rename.old_version, rename.new_version, rename.old_path.name)
2070
+
2071
+ console.print(table)
2072
+ console.print(f"\n[yellow]{len(renames)} migrations will be converted[/]")
2073
+
2074
+ if dry_run:
2075
+ console.print("[yellow][Preview Mode - No changes made][/]")
2076
+ return
2077
+
2078
+ if not yes and not Confirm.ask("Proceed with conversion?", default=False):
2079
+ console.print("[yellow]Conversion cancelled[/]")
2080
+ return
2081
+
2082
+ try:
2083
+ backup_path = fixer.create_backup()
2084
+ console.print(f"[green]✓ Created backup in {backup_path.name}[/]")
2085
+
2086
+ fixer.apply_renames(renames)
2087
+ for rename in renames:
2088
+ console.print(f"[green]✓ Renamed {rename.old_path.name} → {rename.new_path.name}[/]")
2089
+
2090
+ if update_database:
2091
+ with self.config.provide_session() as driver, self._hold_migration_lock(driver):
2092
+ self.tracker.ensure_tracking_table(driver)
2093
+ applied_migrations: list[AppliedMigrationRecord] = self.tracker.get_applied_migrations(driver)
2094
+ applied_versions = {m["version_num"] for m in applied_migrations}
2095
+
2096
+ updated_count = 0
2097
+ for old_version, new_version in conversion_map.items():
2098
+ if old_version in applied_versions:
2099
+ self.tracker.update_version_record(
2100
+ driver, old_version, new_version, applied_versions=applied_versions
2101
+ )
2102
+ updated_count += 1
2103
+
2104
+ if updated_count > 0:
2105
+ console.print(
2106
+ f"[green]✓ Updated {updated_count} version records in migration tracking table[/]"
2107
+ )
2108
+ else:
2109
+ console.print("[green]✓ No applied migrations to update in tracking table[/]")
2110
+
2111
+ fixer.cleanup()
2112
+ self.runner.clear_caches()
2113
+ console.print("[green]✓ Conversion complete![/]")
2114
+
2115
+ except Exception as e:
2116
+ console.print(f"[red]✗ Error: {e}[/]")
2117
+ fixer.rollback()
2118
+ console.print("[yellow]Restored files from backup[/]")
2119
+ raise
2120
+ except BaseException:
2121
+ fixer.rollback()
2122
+ raise
2123
+
2124
+ def _run_reconcilers(
2125
+ self, driver: Any, invoked: list[str], *, use_logger: bool, echo: bool, summary_only: bool
2126
+ ) -> None:
2127
+ """Execute enabled extension reconcilers in configured order."""
2128
+ for descriptor in self.extension_reconcilers:
2129
+ self.tracker.renew_lock(driver)
2130
+ try:
2131
+ execution_time = self.runner.execute_reconciliation(driver, descriptor)
2132
+ except Exception as exc:
2133
+ _output_error(
2134
+ use_logger,
2135
+ echo,
2136
+ summary_only,
2137
+ "Reconciler %s (mode=%s) %s",
2138
+ descriptor.name,
2139
+ "reconcile",
2140
+ "failed",
2141
+ rich_message=f"[red]✗ Reconciler {descriptor.name} (mode=reconcile) failed: {exc}[/]",
2142
+ )
2143
+ raise
2144
+ invoked.append(descriptor.name)
2145
+ _output_info(
2146
+ use_logger,
2147
+ echo,
2148
+ summary_only,
2149
+ "Reconciler %s (mode=%s) %s in %dms",
2150
+ descriptor.name,
2151
+ "reconcile",
2152
+ "complete",
2153
+ execution_time,
2154
+ rich_message=f"[green]✓ Reconciler {descriptor.name} (mode=reconcile) complete in {execution_time}ms[/]",
2155
+ )
2156
+
2157
+ def _run_reconciler_downgrades(
2158
+ self,
2159
+ driver: Any,
2160
+ retained_reconcile: "AbstractSet[str]",
2161
+ invoked: list[str],
2162
+ *,
2163
+ use_logger: bool,
2164
+ echo: bool,
2165
+ summary_only: bool,
2166
+ ) -> None:
2167
+ """Execute extension reconciler downgrades in reverse configured order at base."""
2168
+ for descriptor in reversed(self.extension_reconcilers):
2169
+ self.tracker.renew_lock(driver)
2170
+ try:
2171
+ execution_time = self.runner.execute_reconciliation_downgrade(driver, descriptor)
2172
+ except Exception as exc:
2173
+ _output_error(
2174
+ use_logger,
2175
+ echo,
2176
+ summary_only,
2177
+ "Reconciler %s (mode=%s) %s",
2178
+ descriptor.name,
2179
+ "reconcile",
2180
+ "downgrade failed",
2181
+ rich_message=f"[red]✗ Reconciler {descriptor.name} (mode=reconcile) downgrade failed: {exc}[/]",
2182
+ )
2183
+ raise
2184
+ invoked.append(descriptor.name)
2185
+ _output_info(
2186
+ use_logger,
2187
+ echo,
2188
+ summary_only,
2189
+ "Reconciler %s (mode=%s) %s in %dms",
2190
+ descriptor.name,
2191
+ "reconcile",
2192
+ "downgrade complete",
2193
+ execution_time,
2194
+ rich_message=f"[green]✓ Reconciler {descriptor.name} (mode=reconcile) downgrade complete in {execution_time}ms[/]",
2195
+ )
2196
+ for version_num in sorted(retained_reconcile):
2197
+ self.tracker.remove_migration(driver, version_num)
2198
+
2199
+ @contextmanager
2200
+ def _hold_migration_lock(self, driver: Any, *, dry_run: bool = False) -> "Generator[None, None, None]":
2201
+ """Validate the configured schema, then hold the tracker lock for the command.
2202
+
2203
+ Outer SQLite transactions are preserved across step commits.
2204
+
2205
+ Yields:
2206
+ Control to the caller under the active migration lock context.
2207
+ """
2208
+ self._validate_migration_schema(driver)
2209
+ if dry_run:
2210
+ yield
2211
+ return
2212
+ acquire_lock = getattr(self.tracker, "acquire_lock", None)
2213
+ if not callable(acquire_lock):
2214
+ yield
2215
+ return
2216
+ lock_cm = cast("Any", acquire_lock(driver))
2217
+ with lock_cm:
2218
+ if isinstance(self.tracker, BaseMigrationTracker) and self.tracker.holds_transaction_scoped_lock(driver):
2219
+ with self.runner.use_step_savepoints(driver):
2220
+ step_error: BaseException | None = None
2221
+ try:
2222
+ yield
2223
+ except BaseException as exc:
2224
+ step_error = exc
2225
+ if step_error is not None:
2226
+ if self.runner.pop_savepoint_recovered(driver) and driver._connection_in_transaction(): # pyright: ignore[reportPrivateUsage]
2227
+ try:
2228
+ driver.commit()
2229
+ except Exception as commit_exc:
2230
+ raise commit_exc from step_error
2231
+ raise step_error
2232
+ recorded_error = self._last_command_error
2233
+ if recorded_error is not None:
2234
+ self.runner.pop_savepoint_recovered(driver)
2235
+ if self.runner.pop_unrecovered_step_failure(driver):
2236
+ _raise_as_migration_error(recorded_error)
2237
+ else:
2238
+ yield
2239
+
2240
+ def _validate_migration_schema(self, driver: Any) -> None:
2241
+ """Validate the configured migration schema exists before issuing DDL."""
2242
+ default_schema = self._resolve_default_schema()
2243
+ if default_schema is None:
2244
+ return
2245
+ if not driver.has_schema(default_schema):
2246
+ msg = f"Configured schema '{default_schema}' does not exist"
2247
+ raise MigrationError(msg)
2248
+
2249
+ def _enforce_applied_checksums(
2250
+ self,
2251
+ driver: Any,
2252
+ *,
2253
+ dry_run: bool,
2254
+ use_logger: bool,
2255
+ echo: bool,
2256
+ summary_only: bool,
2257
+ records: "list[AppliedMigrationRecord] | None" = None,
2258
+ versions: "AbstractSet[str] | None" = None,
2259
+ ) -> None:
2260
+ """Refuse changed applied migration files and re-record verified legacy checksums.
2261
+
2262
+ Args:
2263
+ driver: Active database driver.
2264
+ dry_run: Whether database writes are disabled.
2265
+ use_logger: Whether logger output is enabled.
2266
+ echo: Whether console output is enabled.
2267
+ summary_only: Whether summary-only logging is enabled.
2268
+ records: Applied records to audit. Read from the tracking table when None.
2269
+ versions: Optional subset of applied versions to audit.
2270
+ """
2271
+ audited: list[AppliedMigrationRecord] = (
2272
+ records
2273
+ if records is not None
2274
+ else (self._read_applied_migrations(driver) if dry_run else self.tracker.get_applied_migrations(driver))
2275
+ )
2276
+ mismatched, rerecord = self._applied_checksum_audit(
2277
+ audited, self.runner.get_migration_files(), versions=versions
2278
+ )
2279
+ self._ensure_applied_checksums(mismatched)
2280
+ self._rerecord_legacy_checksums(
2281
+ driver, rerecord, dry_run=dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only
2282
+ )
2283
+
2284
+ def _rerecord_legacy_checksums(
2285
+ self,
2286
+ driver: Any,
2287
+ rerecord: "dict[str, str]",
2288
+ *,
2289
+ dry_run: bool,
2290
+ use_logger: bool,
2291
+ echo: bool,
2292
+ summary_only: bool,
2293
+ ) -> None:
2294
+ """Write marker digests for applied rows that verified through the legacy checksum form."""
2295
+ if not rerecord:
2296
+ return
2297
+ versions = ", ".join(sorted(rerecord))
2298
+ verb = "Would re-record" if dry_run else "Re-recorded"
2299
+ if not dry_run:
2300
+ for version in sorted(rerecord):
2301
+ self.tracker.update_checksum(driver, version, rerecord[version])
2302
+ _output_info(
2303
+ use_logger,
2304
+ echo,
2305
+ summary_only,
2306
+ "%s legacy checksums for [%s]",
2307
+ verb,
2308
+ versions,
2309
+ rich_message=f"[cyan]{verb} legacy checksums for [{versions}][/]",
2310
+ )
2311
+
2312
+ def _read_applied_migrations(self, driver: Any) -> "list[AppliedMigrationRecord]":
2313
+ """Read applied migration records without creating the tracking table.
2314
+
2315
+ Returns:
2316
+ Applied records, or an empty list when the tracking table does not exist.
2317
+ """
2318
+ tables = driver.data_dictionary.get_tables(driver, schema=self.tracker.catalog_schema_name())
2319
+ if not self._tracking_table_exists(tables):
2320
+ return []
2321
+ return cast("list[AppliedMigrationRecord]", self.tracker.get_applied_migrations(driver))
2322
+
2323
+ def _load_reconcilable_migrations(
2324
+ self, all_migrations: "list[tuple[str, Path]]"
2325
+ ) -> "dict[str, LoadedMigrationMetadata]":
2326
+ """Load metadata for tracking-table reconciliation, skipping files that cannot be loaded.
2327
+
2328
+ A skipped file is never reconciled; if it is pending, ``upgrade`` loads it again and reports the failure.
2329
+ """
2330
+ loaded: dict[str, LoadedMigrationMetadata] = {}
2331
+ for version, file_path in all_migrations:
2332
+ try:
2333
+ loaded[version] = self.runner.load_migration(file_path, version)
2334
+ except Exception as exc:
2335
+ self._log_reconciliation_load_failure(version, file_path, exc)
2336
+ return loaded
2337
+
2338
+ def _synchronized_applied_versions(
2339
+ self, driver: Any, *, auto_sync: bool, dry_run: bool, use_logger: bool, echo: bool, summary_only: bool
2340
+ ) -> "list[str]":
2341
+ """Return applied versions after optional reconciliation, writing nothing in a dry run.
2342
+
2343
+ A dry run neither creates the tracking table nor reconciles records; it reports the reconciliation it would
2344
+ perform and returns the applied versions as they would look afterwards. A partially applied squash raises
2345
+ even when ``auto_sync`` is disabled.
2346
+
2347
+ Args:
2348
+ driver: Active database driver.
2349
+ auto_sync: Whether to reconcile renamed and squashed migrations.
2350
+ dry_run: Whether database writes are disabled.
2351
+ use_logger: Whether logger output is enabled.
2352
+ echo: Whether console output is enabled.
2353
+ summary_only: Whether summary-only logging is enabled.
2354
+
2355
+ Returns:
2356
+ Applied version numbers.
2357
+ """
2358
+ if dry_run:
2359
+ applied_migrations = self._read_applied_migrations(driver)
2360
+ else:
2361
+ self.tracker.ensure_tracking_table(driver)
2362
+ applied_migrations = self.tracker.get_applied_migrations(driver)
2363
+ all_migrations = self.runner.get_migration_files()
2364
+ plan = self._plan_version_reconciliation(
2365
+ all_migrations, applied_migrations, self._load_reconcilable_migrations(all_migrations)
2366
+ )
2367
+ if not auto_sync or not plan.change_count:
2368
+ return [m["version_num"] for m in applied_migrations]
2369
+ self._report_version_reconciliation(
2370
+ plan, dry_run=dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only
2371
+ )
2372
+ if dry_run:
2373
+ return list(plan.applied_versions)
2374
+ self._apply_version_reconciliation(driver, plan)
2375
+ return [m["version_num"] for m in self.tracker.get_applied_migrations(driver)]
2376
+
2377
+ def _apply_version_reconciliation(self, driver: Any, plan: VersionReconciliationPlan) -> None:
2378
+ """Write a reconciliation plan to the tracking table."""
2379
+ for squash in plan.squashes:
2380
+ self.tracker.replace_with_squash(
2381
+ driver, squash.target_version, list(squash.replaced_versions), squash.description, squash.checksum
2382
+ )
2383
+ for rename in plan.renames:
2384
+ self.tracker.update_version_record(
2385
+ driver, rename.old_version, rename.new_version, applied_versions=set(rename.claimed_versions)
2386
+ )
2387
+
2388
+ def _apply_single_migration(
2389
+ self,
2390
+ driver: Any,
2391
+ migration: "LoadedMigrationMetadata",
2392
+ version: str,
2393
+ use_logger: bool,
2394
+ echo: bool,
2395
+ summary_only: bool,
2396
+ ) -> int | None:
2397
+ """Apply a single migration and record it.
2398
+
2399
+ Args:
2400
+ driver: Database driver instance.
2401
+ migration: Migration dictionary with version, description, checksum.
2402
+ version: Version string.
2403
+ use_logger: Whether to output to logger instead of console.
2404
+ echo: Whether to echo output to the console.
2405
+ summary_only: Whether summary-only logging is enabled.
2406
+
2407
+ Returns:
2408
+ Execution time in ms on success, None on failure.
2409
+ """
2410
+ self.tracker.renew_lock(driver)
2411
+ use_txn = self.runner.should_use_transaction(migration, self.config)
2412
+ try:
2413
+
2414
+ def record_version(
2415
+ exec_time: int,
2416
+ migration: "LoadedMigrationMetadata" = migration,
2417
+ version: str = version,
2418
+ use_txn: bool = use_txn,
2419
+ ) -> None:
2420
+ recorded_version = migration["version"] or version
2421
+ if isinstance(self.tracker, SyncMigrationTracker):
2422
+ self.tracker.record_migration(
2423
+ driver,
2424
+ recorded_version,
2425
+ migration["description"],
2426
+ exec_time,
2427
+ migration["checksum"],
2428
+ commit=not use_txn,
2429
+ replaces=migration.get("replaces"),
2430
+ )
2431
+ else:
2432
+ self.tracker.record_migration(
2433
+ driver, recorded_version, migration["description"], exec_time, migration["checksum"]
2434
+ )
2435
+
2436
+ _, execution_time = self.runner.execute_upgrade(
2437
+ driver, migration, use_transaction=use_txn, on_success=record_version
2438
+ )
2439
+ except Exception as exc:
2440
+ rollback_msg = " (transaction rolled back)" if use_txn else ""
2441
+ _output_error(
2442
+ use_logger,
2443
+ echo,
2444
+ summary_only,
2445
+ "Migration %s failed%s",
2446
+ version,
2447
+ rollback_msg,
2448
+ rich_message=f"[red]✗ Failed{rollback_msg}: {exc}[/]",
2449
+ )
2450
+ self._last_command_error = exc
2451
+ return None
2452
+ else:
2453
+ _output_info(
2454
+ use_logger,
2455
+ echo,
2456
+ summary_only,
2457
+ "Applied migration %s in %dms",
2458
+ version,
2459
+ execution_time,
2460
+ rich_message=f"[green]✓ Applied in {execution_time}ms[/]",
2461
+ )
2462
+ return execution_time
2463
+
2464
+ def _revert_single_migration(
2465
+ self,
2466
+ driver: Any,
2467
+ migration: "LoadedMigrationMetadata",
2468
+ version: str,
2469
+ use_logger: bool,
2470
+ echo: bool,
2471
+ summary_only: bool,
2472
+ ) -> int | None:
2473
+ """Revert a single migration.
2474
+
2475
+ Args:
2476
+ driver: Database driver instance.
2477
+ migration: Migration dictionary.
2478
+ version: Version string.
2479
+ use_logger: Whether to output to logger instead of console.
2480
+ echo: Whether to echo output to the console.
2481
+ summary_only: Whether summary-only logging is enabled.
2482
+
2483
+ Returns:
2484
+ Execution time in ms on success, None on failure.
2485
+ """
2486
+ self.tracker.renew_lock(driver)
2487
+ use_txn = self.runner.should_use_transaction(migration, self.config)
2488
+ reverted = False
2489
+ try:
2490
+
2491
+ def remove_version(exec_time: int, version: str = version, use_txn: bool = use_txn) -> None:
2492
+ nonlocal reverted
2493
+ reverted = True
2494
+ if isinstance(self.tracker, SyncMigrationTracker):
2495
+ self.tracker.remove_migration(driver, version, commit=not use_txn)
2496
+ else:
2497
+ self.tracker.remove_migration(driver, version)
2498
+
2499
+ _, execution_time = self.runner.execute_downgrade(
2500
+ driver, migration, use_transaction=use_txn, on_success=remove_version
2501
+ )
2502
+ except Exception as exc:
2503
+ rollback_msg = " (transaction rolled back)" if use_txn else ""
2504
+ _output_error(
2505
+ use_logger,
2506
+ echo,
2507
+ summary_only,
2508
+ "Migration %s failed%s",
2509
+ version,
2510
+ rollback_msg,
2511
+ rich_message=f"[red]✗ Failed{rollback_msg}: {exc}[/]",
2512
+ )
2513
+ self._last_command_error = exc
2514
+ return None
2515
+ if not reverted:
2516
+ missing_exc = MigrationError(f"Migration {version} does not support downgrade")
2517
+ _output_error(
2518
+ use_logger,
2519
+ echo,
2520
+ summary_only,
2521
+ "Migration %s failed",
2522
+ version,
2523
+ rich_message=f"[red]✗ Failed: {missing_exc}[/]",
2524
+ )
2525
+ self._last_command_error = missing_exc
2526
+ return None
2527
+ _output_info(
2528
+ use_logger,
2529
+ echo,
2530
+ summary_only,
2531
+ "Reverted migration %s in %dms",
2532
+ version,
2533
+ execution_time,
2534
+ rich_message=f"[green]✓ Reverted in {execution_time}ms[/]",
2535
+ )
2536
+ return execution_time
2537
+
2538
+
2539
+ class AsyncMigrationCommands(MigrationCommandsCore["AsyncConfigT", AsyncMigrationRunner]):
2540
+ """Asynchronous migration commands."""
2541
+
2542
+ def __init__(self, config: "AsyncConfigT") -> None:
2543
+ """Initialize migration commands.
2544
+
2545
+ Args:
2546
+ config: The SQLSpec configuration.
2547
+ """
2548
+ super().__init__(config)
2549
+ self.tracker = self._create_tracker()
2550
+ context = MigrationContext.from_config(self.config)
2551
+ context.extension_config = self.extension_configs
2552
+
2553
+ self.runner = AsyncMigrationRunner(
2554
+ self.migrations_path,
2555
+ self._discover_extension_migrations(),
2556
+ context,
2557
+ self.extension_configs,
2558
+ runtime=self._runtime,
2559
+ description_hints=self._template_settings.description_hints,
2560
+ )
2561
+ self.runner.project_root = self.project_root
2562
+
2563
+ async def init(self, directory: str, package: bool = True) -> None:
2564
+ """Initialize migration directory structure.
2565
+
2566
+ Args:
2567
+ directory: Directory path for migrations.
2568
+ package: Whether to create __init__.py in the directory.
2569
+ """
2570
+ self.init_directory(directory, package)
2571
+
2572
+ async def current(self, verbose: bool = False) -> "str | None":
2573
+ """Show current migration version.
2574
+
2575
+ Args:
2576
+ verbose: Whether to show detailed migration history.
2577
+
2578
+ Returns:
2579
+ The current migration version or None if no migrations applied.
2580
+ """
2581
+ async with self.config.provide_session() as driver:
2582
+ tables = await driver.data_dictionary.get_tables(driver, schema=self.tracker.catalog_schema_name())
2583
+ tracking_exists = self._tracking_table_exists(tables)
2584
+
2585
+ applied: list[AppliedMigrationRecord] = []
2586
+ if not tracking_exists:
2587
+ current = None
2588
+ else:
2589
+ await self.tracker.ensure_tracking_table(driver)
2590
+ if verbose:
2591
+ applied = await self.tracker.get_applied_migrations(driver)
2592
+ current = applied[-1]["version_num"] if applied else None
2593
+ else:
2594
+ current = await self.tracker.get_current_version(driver)
2595
+ if not current:
2596
+ log_with_context(
2597
+ logger,
2598
+ logging.DEBUG,
2599
+ "migration.list",
2600
+ db_system=resolve_db_system(type(driver).__name__),
2601
+ current_version=None,
2602
+ applied_count=0,
2603
+ verbose=verbose,
2604
+ status="empty",
2605
+ )
2606
+ if verbose:
2607
+ self._print_configured_reconcilers()
2608
+ console.print("[yellow]No migrations applied yet[/]")
2609
+ return None
2610
+
2611
+ console.print(f"[green]Current version:[/] {current}")
2612
+ if verbose:
2613
+ table = Table(title="Applied Migrations")
2614
+ table.add_column("Version", style="cyan")
2615
+ table.add_column("Description")
2616
+ table.add_column("Applied At")
2617
+ table.add_column("Time (ms)", justify="right")
2618
+ table.add_column("Applied By")
2619
+ for migration in applied:
2620
+ table.add_row(
2621
+ migration["version_num"],
2622
+ migration.get("description", ""),
2623
+ str(migration.get("applied_at", "")),
2624
+ str(migration.get("execution_time_ms", "")),
2625
+ migration.get("applied_by", ""),
2626
+ )
2627
+ console.print(table)
2628
+ self._print_configured_reconcilers()
2629
+
2630
+ applied_count = len(applied) if verbose else None
2631
+ log_with_context(
2632
+ logger,
2633
+ logging.DEBUG,
2634
+ "migration.list",
2635
+ db_system=resolve_db_system(type(driver).__name__),
2636
+ current_version=current,
2637
+ applied_count=applied_count,
2638
+ verbose=verbose,
2639
+ status="complete",
2640
+ )
2641
+ return cast("str | None", current)
2642
+
2643
+ @_with_command_span("upgrade", metadata_fn=_command_metadata)
2644
+ async def upgrade(
2645
+ self,
2646
+ revision: str = "head",
2647
+ allow_missing: bool = False,
2648
+ auto_sync: bool = True,
2649
+ dry_run: bool = False,
2650
+ *,
2651
+ use_logger: bool = False,
2652
+ echo: bool | None = None,
2653
+ summary_only: bool | None = None,
2654
+ ) -> None:
2655
+ """Upgrade to a target revision.
2656
+
2657
+ Validates migration order and warns if out-of-order migrations are detected.
2658
+ Out-of-order migrations can occur when branches merge in different orders
2659
+ across environments.
2660
+
2661
+ Args:
2662
+ revision: Target revision or "head" for latest.
2663
+ allow_missing: If True, allow out-of-order migrations even in strict mode.
2664
+ Defaults to False.
2665
+ auto_sync: If True, automatically reconcile renamed and squashed migrations in the tracking table.
2666
+ Defaults to True. Can be disabled via --no-auto-sync flag. A partially applied squash raises
2667
+ ``SquashValidationError`` either way.
2668
+ dry_run: If True, report the reconciliation and migrations that would run without creating the
2669
+ tracking table or writing any tracking rows.
2670
+ use_logger: If True, output to logger instead of Rich console.
2671
+ Defaults to False. Can be set via MigrationConfig for persistent default.
2672
+ echo: Echo output to the console. Defaults to True when unset.
2673
+ summary_only: Emit a single summary log entry when logger output is enabled.
2674
+ """
2675
+ runtime = self._runtime
2676
+ applied_count = 0
2677
+ pending_count = 0
2678
+ reconcilers_invoked: list[str] = []
2679
+ has_reconcilers = False
2680
+ db_system: str | None = None
2681
+ error: Exception | None = None
2682
+ ul, echo_value, summary_value = self._resolve_output_policy(use_logger, echo, summary_only)
2683
+ self.runner.set_use_logger(ul)
2684
+ self.runner.set_summary_only(summary_value)
2685
+ self.tracker.set_output_policy(use_logger=ul, echo=echo_value, summary_only=summary_value)
2686
+ output_info = functools.partial(_output_info, ul, echo_value, summary_value)
2687
+ start_time = time.perf_counter()
2688
+
2689
+ try:
2690
+ self.ensure_reconcilers_allow("upgrade", revision)
2691
+ has_reconcilers = bool(self.extension_reconcilers)
2692
+ if dry_run:
2693
+ output_info(
2694
+ "DRY RUN MODE: No database changes will be applied",
2695
+ rich_message="[bold yellow]DRY RUN MODE:[/] No database changes will be applied\n",
2696
+ )
2697
+
2698
+ async with self.config.provide_session() as driver, self._hold_migration_lock(driver, dry_run=dry_run):
2699
+ db_system = resolve_db_system(type(driver).__name__)
2700
+ self.runner.set_driver(driver)
2701
+ applied_versions = await self._synchronized_applied_versions(
2702
+ driver,
2703
+ auto_sync=auto_sync and bool(self._get_migration_config().get("auto_sync", True)),
2704
+ dry_run=dry_run,
2705
+ use_logger=ul,
2706
+ echo=echo_value,
2707
+ summary_only=summary_value,
2708
+ )
2709
+ await self._enforce_applied_checksums(
2710
+ driver, dry_run=dry_run, use_logger=ul, echo=echo_value, summary_only=summary_value
2711
+ )
2712
+ applied_set = set(applied_versions)
2713
+
2714
+ all_migrations = await self.runner.get_migration_files()
2715
+ if runtime is not None:
2716
+ runtime.increment_metric("migrations.command.upgrade.available", float(len(all_migrations)))
2717
+
2718
+ pending = self._collect_pending_migrations(all_migrations, applied_set, revision)
2719
+ pending_count = len(pending)
2720
+
2721
+ if runtime is not None:
2722
+ runtime.increment_metric("migrations.command.upgrade.pending", float(len(pending)))
2723
+
2724
+ if pending:
2725
+ migration_config = cast("dict[str, Any]", self.config.migration_config) or {}
2726
+ strict_ordering = migration_config.get("strict_ordering", False) and not allow_missing
2727
+ validate_migration_order(
2728
+ [v for v, _ in pending],
2729
+ applied_versions,
2730
+ strict_ordering,
2731
+ use_logger=ul,
2732
+ echo=echo_value,
2733
+ summary_only=summary_value,
2734
+ )
2735
+
2736
+ if dry_run:
2737
+ self.report_reconciler_preview(use_logger=ul, echo=echo_value, summary_only=summary_value)
2738
+ elif has_reconcilers:
2739
+ await self._run_reconcilers(
2740
+ driver, reconcilers_invoked, use_logger=ul, echo=echo_value, summary_only=summary_value
2741
+ )
2742
+
2743
+ if not pending:
2744
+ _report_no_pending_migrations(
2745
+ ul, echo_value, summary_value, bool(all_migrations or has_reconcilers)
2746
+ )
2747
+ return
2748
+
2749
+ output_info(
2750
+ "Found %d pending migrations",
2751
+ len(pending),
2752
+ rich_message=f"[yellow]Found {len(pending)} pending migrations[/]",
2753
+ )
2754
+
2755
+ for version, file_path in pending:
2756
+ migration = await self.runner.load_migration(file_path, version)
2757
+ action_verb = "Would apply" if dry_run else "Applying"
2758
+ output_info(
2759
+ "%s %s: %s",
2760
+ action_verb,
2761
+ version,
2762
+ migration["description"],
2763
+ rich_message=f"\n[cyan]{action_verb} {version}:[/] {migration['description']}",
2764
+ )
2765
+
2766
+ if dry_run:
2767
+ output_info(
2768
+ "Migration file: %s", file_path, rich_message=f"[dim]Migration file: {file_path}[/]"
2769
+ )
2770
+ continue
2771
+
2772
+ result = await self._apply_single_migration(
2773
+ driver, migration, version, ul, echo_value, summary_value
2774
+ )
2775
+ if result is None:
2776
+ break
2777
+ applied_count += 1
2778
+
2779
+ except Exception as exc: # pragma: no cover
2780
+ error = exc
2781
+ raise
2782
+ finally:
2783
+ effective_error = error or self._last_command_error
2784
+ if not dry_run and applied_count:
2785
+ self._record_command_metric("applied", float(applied_count))
2786
+ duration_ms = int((time.perf_counter() - start_time) * 1000)
2787
+ _log_command_summary(
2788
+ use_logger=ul,
2789
+ summary_only=summary_value,
2790
+ command="upgrade",
2791
+ status="failed" if effective_error else "complete",
2792
+ revision=revision,
2793
+ dry_run=dry_run,
2794
+ pending_count=pending_count,
2795
+ applied_count=applied_count,
2796
+ reverted_count=None,
2797
+ duration_ms=duration_ms,
2798
+ db_system=db_system,
2799
+ bind_key=getattr(self.config, "bind_key", None),
2800
+ config_name=type(self.config).__name__,
2801
+ error=effective_error,
2802
+ allow_missing=allow_missing,
2803
+ auto_sync=auto_sync,
2804
+ reconcilers_invoked=len(reconcilers_invoked) if has_reconcilers else None,
2805
+ )
2806
+
2807
+ recorded_error = self._last_command_error
2808
+ if recorded_error is not None:
2809
+ _raise_as_migration_error(recorded_error)
2810
+
2811
+ if dry_run:
2812
+ output_info(
2813
+ "Dry run complete. No changes were made to the database.",
2814
+ rich_message="\n[bold yellow]Dry run complete.[/] No changes were made to the database.",
2815
+ )
2816
+ elif applied_count > 0 and self._last_command_error is None:
2817
+ auto_dump_path = self._auto_dump_path()
2818
+ if auto_dump_path is not None:
2819
+ try:
2820
+ await self.dump_schema(output_path=auto_dump_path, echo=echo_value)
2821
+ except _AUTO_DUMP_ERRORS as exc:
2822
+ self._report_auto_dump_failure(auto_dump_path, exc, use_logger=ul, echo=echo_value)
2823
+
2824
+ @_with_command_span("downgrade", metadata_fn=_command_metadata)
2825
+ async def downgrade(
2826
+ self,
2827
+ revision: str = "-1",
2828
+ *,
2829
+ dry_run: bool = False,
2830
+ use_logger: bool = False,
2831
+ echo: bool | None = None,
2832
+ summary_only: bool | None = None,
2833
+ ) -> None:
2834
+ """Downgrade to a target revision.
2835
+
2836
+ Args:
2837
+ revision: Target revision or "-1" for one step back.
2838
+ dry_run: If True, show what would be done without making changes.
2839
+ use_logger: If True, output to logger instead of Rich console.
2840
+ Defaults to False. Can be set via MigrationConfig for persistent default.
2841
+ echo: Echo output to the console. Defaults to True when unset.
2842
+ summary_only: Emit a single summary log entry when logger output is enabled.
2843
+ """
2844
+ runtime = self._runtime
2845
+ reverted_count = 0
2846
+ pending_count = 0
2847
+ reconcilers_invoked: list[str] = []
2848
+ has_reconcilers = False
2849
+ reaches_base = False
2850
+ db_system: str | None = None
2851
+ error: Exception | None = None
2852
+ ul, echo_value, summary_value = self._resolve_output_policy(use_logger, echo, summary_only)
2853
+ self.runner.set_use_logger(ul)
2854
+ self.runner.set_summary_only(summary_value)
2855
+ self.tracker.set_output_policy(use_logger=ul, echo=echo_value, summary_only=summary_value)
2856
+ output_info = functools.partial(_output_info, ul, echo_value, summary_value)
2857
+ output_error = functools.partial(_output_error, ul, echo_value, summary_value)
2858
+ start_time = time.perf_counter()
2859
+
2860
+ try:
2861
+ self.ensure_reconcilers_allow("downgrade", revision)
2862
+ has_reconcilers = bool(self.extension_reconcilers)
2863
+ if dry_run:
2864
+ output_info(
2865
+ "DRY RUN MODE: No database changes will be applied",
2866
+ rich_message="[bold yellow]DRY RUN MODE:[/] No database changes will be applied\n",
2867
+ )
2868
+
2869
+ async with self.config.provide_session() as driver, self._hold_migration_lock(driver, dry_run=dry_run):
2870
+ db_system = resolve_db_system(type(driver).__name__)
2871
+ self.runner.set_driver(driver)
2872
+ await self.tracker.ensure_tracking_table(driver)
2873
+
2874
+ applied: list[AppliedMigrationRecord] = await self.tracker.get_applied_migrations(driver)
2875
+ retained_reconcile = self._retained_reconcile_versions(applied)
2876
+ active_applied = [m for m in applied if m["version_num"] not in retained_reconcile]
2877
+ if runtime is not None:
2878
+ runtime.increment_metric("migrations.command.downgrade.available", float(len(active_applied)))
2879
+ if not active_applied and not (revision == "base" and has_reconcilers):
2880
+ output_info("No migrations to downgrade", rich_message="[yellow]No migrations to downgrade[/]")
2881
+ return
2882
+
2883
+ to_revert = self._collect_revert_migrations(active_applied, revision) if active_applied else []
2884
+ reaches_base = revision == "base"
2885
+ pending_count = len(to_revert)
2886
+
2887
+ if runtime is not None:
2888
+ runtime.increment_metric("migrations.command.downgrade.pending", float(len(to_revert)))
2889
+
2890
+ if not to_revert and not (reaches_base and has_reconcilers):
2891
+ output_info("Nothing to downgrade", rich_message="[yellow]Nothing to downgrade[/]")
2892
+ return
2893
+
2894
+ if to_revert:
2895
+ await self._enforce_applied_checksums(
2896
+ driver,
2897
+ dry_run=dry_run,
2898
+ use_logger=ul,
2899
+ echo=echo_value,
2900
+ summary_only=summary_value,
2901
+ records=active_applied,
2902
+ versions={record["version_num"] for record in to_revert},
2903
+ )
2904
+ output_info(
2905
+ "Reverting %d migrations",
2906
+ len(to_revert),
2907
+ rich_message=f"[yellow]Reverting {len(to_revert)} migrations[/]",
2908
+ )
2909
+ all_files = dict(await self.runner.get_migration_files())
2910
+
2911
+ for migration_record in to_revert:
2912
+ version = migration_record["version_num"]
2913
+ if version not in all_files:
2914
+ output_error(
2915
+ "Migration file not found for %s",
2916
+ version,
2917
+ rich_message=f"[red]Migration file not found for {version}[/]",
2918
+ )
2919
+ if runtime is not None:
2920
+ runtime.increment_metric("migrations.command.downgrade.missing_files")
2921
+ self._last_command_error = MigrationError(f"Migration file not found for {version}")
2922
+ break
2923
+
2924
+ migration = await self.runner.load_migration(all_files[version], version)
2925
+ action_verb = "Would revert" if dry_run else "Reverting"
2926
+ output_info(
2927
+ "%s %s: %s",
2928
+ action_verb,
2929
+ version,
2930
+ migration["description"],
2931
+ rich_message=f"\n[cyan]{action_verb} {version}:[/] {migration['description']}",
2932
+ )
2933
+
2934
+ if dry_run:
2935
+ output_info(
2936
+ "Migration file: %s",
2937
+ all_files[version],
2938
+ rich_message=f"[dim]Migration file: {all_files[version]}[/]",
2939
+ )
2940
+ continue
2941
+
2942
+ result = await self._revert_single_migration(
2943
+ driver, migration, version, ul, echo_value, summary_value
2944
+ )
2945
+ if result is None:
2946
+ break
2947
+ reverted_count += 1
2948
+
2949
+ if reaches_base and has_reconcilers and self._last_command_error is None:
2950
+ if dry_run:
2951
+ self.report_reconciler_downgrade_preview(
2952
+ use_logger=ul, echo=echo_value, summary_only=summary_value
2953
+ )
2954
+ else:
2955
+ await self._run_reconciler_downgrades(
2956
+ driver,
2957
+ retained_reconcile,
2958
+ reconcilers_invoked,
2959
+ use_logger=ul,
2960
+ echo=echo_value,
2961
+ summary_only=summary_value,
2962
+ )
2963
+
2964
+ except Exception as exc: # pragma: no cover
2965
+ error = exc
2966
+ raise
2967
+ finally:
2968
+ effective_error = error or self._last_command_error
2969
+ if not dry_run and reverted_count:
2970
+ self._record_command_metric("reverted", float(reverted_count))
2971
+ duration_ms = int((time.perf_counter() - start_time) * 1000)
2972
+ _log_command_summary(
2973
+ use_logger=ul,
2974
+ summary_only=summary_value,
2975
+ command="downgrade",
2976
+ status="failed" if effective_error else "complete",
2977
+ revision=revision,
2978
+ dry_run=dry_run,
2979
+ pending_count=pending_count,
2980
+ applied_count=None,
2981
+ reverted_count=reverted_count,
2982
+ duration_ms=duration_ms,
2983
+ db_system=db_system,
2984
+ bind_key=getattr(self.config, "bind_key", None),
2985
+ config_name=type(self.config).__name__,
2986
+ error=effective_error,
2987
+ reconcilers_invoked=len(reconcilers_invoked) if (reaches_base and has_reconcilers) else None,
2988
+ )
2989
+
2990
+ recorded_error = self._last_command_error
2991
+ if recorded_error is not None:
2992
+ _raise_as_migration_error(recorded_error)
2993
+
2994
+ if dry_run:
2995
+ output_info(
2996
+ "Dry run complete. No changes were made to the database.",
2997
+ rich_message="\n[bold yellow]Dry run complete.[/] No changes were made to the database.",
2998
+ )
2999
+
3000
+ async def stamp(self, revision: str) -> None:
3001
+ """Mark database as being at a specific revision without running migrations.
3002
+
3003
+ Args:
3004
+ revision: The revision to stamp.
3005
+ """
3006
+ async with self.config.provide_session() as driver, self._hold_migration_lock(driver):
3007
+ await self.tracker.ensure_tracking_table(driver)
3008
+ applied = await self.tracker.get_applied_migrations(driver) if self.extension_reconcilers else []
3009
+ retained = self._retained_reconcile_versions(applied)
3010
+
3011
+ if revision == "base":
3012
+ clear_sql = (
3013
+ sql.delete().from_(self.tracker.version_table).where_not_in("version_num", sorted(retained))
3014
+ if retained
3015
+ else sql.delete().from_(self.tracker.version_table)
3016
+ )
3017
+ await driver.execute(clear_sql)
3018
+ if isinstance(self.tracker, AsyncMigrationTracker):
3019
+ await self.tracker._safe_commit(driver)
3020
+ console.print("[green]Database stamped at revision base[/]")
3021
+ return
3022
+
3023
+ all_migrations_list = await self.runner.get_migration_files()
3024
+ target_version: str | None = None
3025
+ try:
3026
+ parsed_target = parse_version(revision)
3027
+ except ValueError:
3028
+ parsed_target = None
3029
+
3030
+ for v, _ in all_migrations_list:
3031
+ if v == revision:
3032
+ target_version = v
3033
+ break
3034
+ if parsed_target is not None:
3035
+ try:
3036
+ if parse_version(v) == parsed_target:
3037
+ target_version = v
3038
+ break
3039
+ except ValueError:
3040
+ continue
3041
+
3042
+ if target_version is None:
3043
+ msg = f"Unknown revision: {revision}"
3044
+ raise MigrationError(msg)
3045
+
3046
+ target_parsed = parse_version(target_version) if parsed_target is not None else None
3047
+ clear_sql = (
3048
+ sql.delete().from_(self.tracker.version_table).where_not_in("version_num", sorted(retained))
3049
+ if retained
3050
+ else sql.delete().from_(self.tracker.version_table)
3051
+ )
3052
+ await driver.execute(clear_sql)
3053
+ for v, path in all_migrations_list:
3054
+ should_record = False
3055
+ if target_parsed is not None:
3056
+ try:
3057
+ v_parsed = parse_version(v)
3058
+ if v_parsed.extension == target_parsed.extension and v_parsed <= target_parsed:
3059
+ should_record = True
3060
+ except ValueError:
3061
+ should_record = v == target_version
3062
+ elif v == target_version:
3063
+ should_record = True
3064
+ if should_record:
3065
+ if path.exists():
3066
+ migration = await self.runner.load_migration(path, v)
3067
+ description = migration["description"] or f"Stamped to {v}"
3068
+ checksum = migration["checksum"]
3069
+ else:
3070
+ description = f"Stamped to {v}"
3071
+ checksum = "manual-stamp"
3072
+ await self.tracker.record_migration(driver, v, description, 0, checksum)
3073
+ console.print(f"[green]Database stamped at revision {target_version}[/]")
3074
+
3075
+ async def revision(
3076
+ self,
3077
+ message: str,
3078
+ file_type: str | None = None,
3079
+ *,
3080
+ from_schema: bool = False,
3081
+ from_data: "str | Path | None" = None,
3082
+ schema: str | None = None,
3083
+ target_table: str | None = None,
3084
+ ) -> "Path":
3085
+ """Create a new migration file with timestamp-based versioning.
3086
+
3087
+ Generates a unique timestamp version (YYYYMMDDHHmmss format) to avoid
3088
+ conflicts when multiple developers create migrations concurrently.
3089
+
3090
+ Args:
3091
+ message: Description for the migration.
3092
+ file_type: Type of migration file to create ('sql' or 'py').
3093
+ from_schema: When True, populate the migration with the current database schema DDL.
3094
+ from_data: Data file path or staging table name to infer DDL from. See
3095
+ ``MigrationCommandsCore._resolve_data_source`` for the detection rules.
3096
+ schema: Optional database schema name.
3097
+ target_table: Optional target table name when bootstrapping from data.
3098
+
3099
+ Returns:
3100
+ Path to the created migration file.
3101
+
3102
+ Raises:
3103
+ MigrationError: When both sources are given or DDL cannot be inferred.
3104
+ """
3105
+ source = self._prepare_revision_source(from_schema=from_schema, from_data=from_data)
3106
+ up_sql: Sequence[str] | None = None
3107
+ down_sql: Sequence[str] | None = None
3108
+ if from_schema:
3109
+ excluded = self._version_table_exclusion()
3110
+ async with self.config.provide_session() as driver:
3111
+ await self._ensure_schema_extraction_safe_async(driver, schema=schema, exclude_tables=excluded)
3112
+ up_sql, down_sql = schema_ddl_statements(
3113
+ await driver.data_dictionary.get_schema_ddl(
3114
+ driver, schema=schema, exclude_tables=excluded, direction="create"
3115
+ ),
3116
+ await driver.data_dictionary.get_schema_ddl(
3117
+ driver, schema=schema, exclude_tables=excluded, direction="drop"
3118
+ ),
3119
+ )
3120
+ elif isinstance(source, Path):
3121
+ up_sql, down_sql = self._data_file_revision_sql(source, schema=schema, target_table=target_table)
3122
+ elif isinstance(source, str):
3123
+ source_table, source_schema = self._split_qualified_table(source, schema)
3124
+ async with self.config.provide_session() as driver:
3125
+ try:
3126
+ ddl_res = await driver.data_dictionary.infer_table_ddl_from_data(
3127
+ driver, source_table, schema=source_schema, target_table=target_table
3128
+ )
3129
+ except (SqlglotError, SQLBuilderError) as exc:
3130
+ msg = f"Could not infer DDL from table '{source}': {exc}"
3131
+ raise MigrationError(msg) from exc
3132
+ up_sql, down_sql = self._staging_table_revision_sql(ddl_res.ddl, source, self._driver_dialect(driver))
3133
+
3134
+ return self._write_revision(message, file_type, up_sql, down_sql)
3135
+
3136
+ async def dump_schema(
3137
+ self,
3138
+ output_path: "str | Path | None" = None,
3139
+ *,
3140
+ schema: str | None = None,
3141
+ include_migrations_table: bool = False,
3142
+ prefer_native: bool = True,
3143
+ target_dialect: str | None = None,
3144
+ echo: bool | None = None,
3145
+ ) -> str:
3146
+ """Dump the full current database schema DDL to a string and optional file path.
3147
+
3148
+ Args:
3149
+ output_path: Optional file path to write the rendered schema SQL.
3150
+ schema: Optional database schema name to inspect.
3151
+ include_migrations_table: Whether to include the migration tracking table.
3152
+ prefer_native: Prefer engine-native catalog DDL when available.
3153
+ target_dialect: Optional target SQLGlot dialect for cross-dialect transpilation.
3154
+ echo: Echo output to the console.
3155
+
3156
+ Returns:
3157
+ Rendered schema DDL string.
3158
+ """
3159
+ _, echo_value, _ = self._resolve_output_policy(False, echo, False)
3160
+ excluded = self._version_table_exclusion(include_migrations_table)
3161
+ async with self.config.provide_session() as driver:
3162
+ await self._ensure_schema_extraction_safe_async(driver, schema=schema, exclude_tables=excluded)
3163
+ create_res = await driver.data_dictionary.get_schema_ddl(
3164
+ driver,
3165
+ schema=schema,
3166
+ exclude_tables=excluded,
3167
+ direction="create",
3168
+ prefer_native=prefer_native,
3169
+ target_dialect=target_dialect,
3170
+ )
3171
+ dialect_label = self._dump_dialect_label(driver, target_dialect)
3172
+ return self._render_schema_dump(
3173
+ create_res, dialect_label=dialect_label, schema=schema, output_path=output_path, echo=echo_value
3174
+ )
3175
+
3176
+ async def verify(
3177
+ self, *, strict: bool = False, fail_on_pending: bool = False, use_logger: bool = False, echo: bool | None = None
3178
+ ) -> "dict[str, Any]":
3179
+ """Verify database migration tracking records against migration files on disk.
3180
+
3181
+ Verification is read-only: a missing tracking table is reported as every migration pending and is never
3182
+ created.
3183
+
3184
+ Args:
3185
+ strict: Raise ``MigrationError`` when checksum drift, orphaned records, or partial squashes exist.
3186
+ fail_on_pending: Raise ``MigrationError`` when migrations are pending.
3187
+ use_logger: Output verification messages to logger instead of Rich console.
3188
+ echo: Echo output to the console.
3189
+
3190
+ Returns:
3191
+ Verification report dictionary with ``valid``, ``checksum_mismatches``, ``orphaned_records``,
3192
+ ``pending_versions``, and ``partial_squash_errors``.
3193
+ """
3194
+ ul, echo_value, summary_value = self._resolve_output_policy(use_logger, echo, None)
3195
+ async with self.config.provide_session() as driver:
3196
+ applied_migrations = await self._read_applied_migrations(driver)
3197
+
3198
+ self.runner.clear_caches()
3199
+ migration_files = await self.runner.get_migration_files()
3200
+ loaded_files: dict[str, LoadedMigrationMetadata] = {
3201
+ version: await self.runner.load_migration(file_path, version) for version, file_path in migration_files
3202
+ }
3203
+ report = self._verification_report(
3204
+ applied_migrations,
3205
+ loaded_files,
3206
+ strict=strict,
3207
+ fail_on_pending=fail_on_pending,
3208
+ use_logger=ul,
3209
+ echo=echo_value,
3210
+ summary_only=summary_value,
3211
+ )
3212
+ if not report["checksum_mismatches"]:
3213
+ _, rerecord = self._applied_checksum_audit(applied_migrations, migration_files)
3214
+ if rerecord:
3215
+ async with self.config.provide_session() as driver, self._hold_migration_lock(driver):
3216
+ await self._rerecord_legacy_checksums(
3217
+ driver, rerecord, dry_run=False, use_logger=ul, echo=echo_value, summary_only=summary_value
3218
+ )
3219
+ return report
3220
+
3221
+ async def squash(
3222
+ self,
3223
+ start_version: str | None = None,
3224
+ end_version: str | None = None,
3225
+ description: str | None = None,
3226
+ *,
3227
+ dry_run: bool = False,
3228
+ update_database: bool = True,
3229
+ yes: bool = False,
3230
+ allow_gaps: bool = False,
3231
+ output_format: str = "sql",
3232
+ strategy: str = "concat",
3233
+ single_file: bool | None = None,
3234
+ ) -> None:
3235
+ """Squash a range of migrations into a single file.
3236
+
3237
+ Combines multiple sequential or timestamped migrations into a single release migration.
3238
+
3239
+ Args:
3240
+ start_version: First version in the range to squash (inclusive).
3241
+ When None, defaults to the first core migration found.
3242
+ end_version: Last version in the range to squash (inclusive).
3243
+ When None, defaults to the last core migration found.
3244
+ description: Description for the squashed migration file.
3245
+ When None, defaults to 'initial_schema' if yes=True or prompts interactively.
3246
+ dry_run: Preview changes without applying.
3247
+ update_database: Update migration records in database.
3248
+ yes: Skip confirmation prompt.
3249
+ allow_gaps: Allow gaps in version sequence.
3250
+ output_format: Output format ("sql" or "py").
3251
+ strategy: Squash strategy: "concat" (default) keeps every statement in order, "ddl" folds DDL and
3252
+ refuses ranges it cannot fold faithfully, "schema" reflects the live database schema.
3253
+ single_file: Force a single squashed file when True, split by file type/directives when False or None.
3254
+ """
3255
+ resolved_strategy = strategy.lower()
3256
+ sync_runner = self._create_squash_runner()
3257
+ all_migrations = sync_runner.get_migration_files()
3258
+ squasher = self._create_squasher(sync_runner, resolved_strategy)
3259
+ version_range = self._resolve_squash_range(all_migrations, start_version, end_version)
3260
+ if version_range is None:
3261
+ return
3262
+ if description is None:
3263
+ description = (
3264
+ "initial_schema"
3265
+ if yes
3266
+ else await asyncio.to_thread(Prompt.ask, "Migration description", default="squashed_migrations")
3267
+ )
3268
+
3269
+ schema_ddl: tuple[list[str], list[str]] | None = None
3270
+ if resolved_strategy == "schema":
3271
+ squasher.plan_squash(
3272
+ version_range[0],
3273
+ version_range[1],
3274
+ description,
3275
+ allow_gaps=allow_gaps,
3276
+ output_format=output_format,
3277
+ strategy=resolved_strategy,
3278
+ single_file=single_file,
3279
+ )
3280
+ excluded = self._version_table_exclusion()
3281
+ async with self.config.provide_session() as driver:
3282
+ self._validate_schema_squash_applied(
3283
+ sync_runner,
3284
+ all_migrations,
3285
+ version_range[0],
3286
+ version_range[1],
3287
+ allow_gaps=allow_gaps,
3288
+ applied_migrations=await self._read_applied_migrations(driver),
3289
+ )
3290
+ await self._ensure_schema_extraction_safe_async(driver, exclude_tables=excluded)
3291
+ schema_ddl = schema_ddl_statements(
3292
+ await driver.data_dictionary.get_schema_ddl(driver, exclude_tables=excluded, direction="create"),
3293
+ await driver.data_dictionary.get_schema_ddl(driver, exclude_tables=excluded, direction="drop"),
3294
+ )
3295
+
3296
+ plans = squasher.plan_squash(
3297
+ version_range[0],
3298
+ version_range[1],
3299
+ description,
3300
+ allow_gaps=allow_gaps,
3301
+ output_format=output_format,
3302
+ strategy=resolved_strategy,
3303
+ single_file=single_file,
3304
+ schema_ddl=schema_ddl,
3305
+ )
3306
+ self._print_squash_plan(plans)
3307
+ if dry_run:
3308
+ self._print_squash_dry_run(squasher, plans)
3309
+ return
3310
+ if not yes and not await asyncio.to_thread(Confirm.ask, "Proceed with squash?", default=False):
3311
+ console.print("[yellow]Squash cancelled[/]")
3312
+ return
3313
+
3314
+ try:
3315
+ if update_database:
3316
+ async with self.config.provide_session() as driver, self._hold_migration_lock(driver):
3317
+ await self.tracker.ensure_tracking_table(driver)
3318
+ applied_plans = [
3319
+ plan
3320
+ for plan in plans
3321
+ if await self.tracker.is_squash_already_applied(
3322
+ driver, plan.target_version, plan.source_versions
3323
+ )
3324
+ ]
3325
+ self._apply_squash_files(squasher, plans)
3326
+ for plan in applied_plans:
3327
+ await self.tracker.replace_with_squash(
3328
+ driver,
3329
+ plan.target_version,
3330
+ plan.source_versions,
3331
+ description,
3332
+ self._squash_record_checksum(plan),
3333
+ )
3334
+ console.print("[green]✓ Updated migration tracking table[/]")
3335
+ else:
3336
+ self._apply_squash_files(squasher, plans)
3337
+ except BaseException:
3338
+ squasher.rollback_backup()
3339
+ raise
3340
+ self._finish_squash(squasher)
3341
+
3342
+ async def fix(self, dry_run: bool = False, update_database: bool = True, yes: bool = False) -> None:
3343
+ """Convert timestamp migrations to sequential format.
3344
+
3345
+ Implements hybrid versioning workflow where development uses timestamps
3346
+ and production uses sequential numbers. Creates backup before changes
3347
+ and provides rollback on errors.
3348
+
3349
+ Args:
3350
+ dry_run: Preview changes without applying.
3351
+ update_database: Update migration records in database.
3352
+ yes: Skip confirmation prompt.
3353
+ """
3354
+ all_migrations = await self.runner.get_migration_files()
3355
+
3356
+ conversion_map = generate_conversion_map(all_migrations)
3357
+
3358
+ if not conversion_map:
3359
+ console.print("[yellow]No timestamp migrations found - nothing to convert[/]")
3360
+ return
3361
+
3362
+ fixer = MigrationFixer(self.migrations_path)
3363
+ try:
3364
+ renames = fixer.plan_renames(conversion_map)
3365
+ except ValueError as exc:
3366
+ raise MigrationError(str(exc)) from exc
3367
+
3368
+ table = Table(title="Migration Conversions")
3369
+ table.add_column("Current Version", style="cyan")
3370
+ table.add_column("New Version", style="green")
3371
+ table.add_column("File")
3372
+
3373
+ for rename in renames:
3374
+ table.add_row(rename.old_version, rename.new_version, rename.old_path.name)
3375
+
3376
+ console.print(table)
3377
+ console.print(f"\n[yellow]{len(renames)} migrations will be converted[/]")
3378
+
3379
+ if dry_run:
3380
+ console.print("[yellow][Preview Mode - No changes made][/]")
3381
+ return
3382
+
3383
+ if not yes and not await asyncio.to_thread(Confirm.ask, "Proceed with conversion?", default=False):
3384
+ console.print("[yellow]Conversion cancelled[/]")
3385
+ return
3386
+
3387
+ try:
3388
+ backup_path = fixer.create_backup()
3389
+ console.print(f"[green]✓ Created backup in {backup_path.name}[/]")
3390
+
3391
+ fixer.apply_renames(renames)
3392
+ for rename in renames:
3393
+ console.print(f"[green]✓ Renamed {rename.old_path.name} → {rename.new_path.name}[/]")
3394
+
3395
+ if update_database:
3396
+ async with self.config.provide_session() as driver, self._hold_migration_lock(driver):
3397
+ await self.tracker.ensure_tracking_table(driver)
3398
+ applied_migrations: list[AppliedMigrationRecord] = await self.tracker.get_applied_migrations(driver)
3399
+ applied_versions = {m["version_num"] for m in applied_migrations}
3400
+
3401
+ updated_count = 0
3402
+ for old_version, new_version in conversion_map.items():
3403
+ if old_version in applied_versions:
3404
+ await self.tracker.update_version_record(
3405
+ driver, old_version, new_version, applied_versions=applied_versions
3406
+ )
3407
+ updated_count += 1
3408
+
3409
+ if updated_count > 0:
3410
+ console.print(
3411
+ f"[green]✓ Updated {updated_count} version records in migration tracking table[/]"
3412
+ )
3413
+ else:
3414
+ console.print("[green]✓ No applied migrations to update in tracking table[/]")
3415
+
3416
+ fixer.cleanup()
3417
+ self.runner.clear_caches()
3418
+ console.print("[green]✓ Conversion complete![/]")
3419
+
3420
+ except Exception as e:
3421
+ console.print(f"[red]✗ Error: {e}[/]")
3422
+ fixer.rollback()
3423
+ console.print("[yellow]Restored files from backup[/]")
3424
+ raise
3425
+ except BaseException:
3426
+ fixer.rollback()
3427
+ raise
3428
+
3429
+ async def _run_reconcilers(
3430
+ self, driver: Any, invoked: list[str], *, use_logger: bool, echo: bool, summary_only: bool
3431
+ ) -> None:
3432
+ """Execute enabled extension reconcilers in configured order."""
3433
+ for descriptor in self.extension_reconcilers:
3434
+ await self.tracker.renew_lock(driver)
3435
+ try:
3436
+ execution_time = await self.runner.execute_reconciliation(driver, descriptor)
3437
+ except Exception as exc:
3438
+ _output_error(
3439
+ use_logger,
3440
+ echo,
3441
+ summary_only,
3442
+ "Reconciler %s (mode=%s) %s",
3443
+ descriptor.name,
3444
+ "reconcile",
3445
+ "failed",
3446
+ rich_message=f"[red]✗ Reconciler {descriptor.name} (mode=reconcile) failed: {exc}[/]",
3447
+ )
3448
+ raise
3449
+ invoked.append(descriptor.name)
3450
+ _output_info(
3451
+ use_logger,
3452
+ echo,
3453
+ summary_only,
3454
+ "Reconciler %s (mode=%s) %s in %dms",
3455
+ descriptor.name,
3456
+ "reconcile",
3457
+ "complete",
3458
+ execution_time,
3459
+ rich_message=f"[green]✓ Reconciler {descriptor.name} (mode=reconcile) complete in {execution_time}ms[/]",
3460
+ )
3461
+
3462
+ async def _run_reconciler_downgrades(
3463
+ self,
3464
+ driver: Any,
3465
+ retained_reconcile: "AbstractSet[str]",
3466
+ invoked: list[str],
3467
+ *,
3468
+ use_logger: bool,
3469
+ echo: bool,
3470
+ summary_only: bool,
3471
+ ) -> None:
3472
+ """Execute extension reconciler downgrades in reverse configured order at base."""
3473
+ for descriptor in reversed(self.extension_reconcilers):
3474
+ await self.tracker.renew_lock(driver)
3475
+ try:
3476
+ execution_time = await self.runner.execute_reconciliation_downgrade(driver, descriptor)
3477
+ except Exception as exc:
3478
+ _output_error(
3479
+ use_logger,
3480
+ echo,
3481
+ summary_only,
3482
+ "Reconciler %s (mode=%s) %s",
3483
+ descriptor.name,
3484
+ "reconcile",
3485
+ "downgrade failed",
3486
+ rich_message=f"[red]✗ Reconciler {descriptor.name} (mode=reconcile) downgrade failed: {exc}[/]",
3487
+ )
3488
+ raise
3489
+ invoked.append(descriptor.name)
3490
+ _output_info(
3491
+ use_logger,
3492
+ echo,
3493
+ summary_only,
3494
+ "Reconciler %s (mode=%s) %s in %dms",
3495
+ descriptor.name,
3496
+ "reconcile",
3497
+ "downgrade complete",
3498
+ execution_time,
3499
+ rich_message=f"[green]✓ Reconciler {descriptor.name} (mode=reconcile) downgrade complete in {execution_time}ms[/]",
3500
+ )
3501
+ for version_num in sorted(retained_reconcile):
3502
+ await self.tracker.remove_migration(driver, version_num)
3503
+
3504
+ @asynccontextmanager
3505
+ async def _hold_migration_lock(self, driver: Any, *, dry_run: bool = False) -> "AsyncGenerator[None, None]":
3506
+ """Validate the configured schema, then hold the async tracker lock for the command.
3507
+
3508
+ Outer SQLite transactions are preserved across step commits.
3509
+
3510
+ Yields:
3511
+ Control to the caller under the active async migration lock context.
3512
+ """
3513
+ await self._validate_migration_schema(driver)
3514
+ if dry_run:
3515
+ yield
3516
+ return
3517
+ acquire_lock = getattr(self.tracker, "acquire_lock", None)
3518
+ if not callable(acquire_lock):
3519
+ yield
3520
+ return
3521
+ lock_cm = cast("Any", acquire_lock(driver))
3522
+ async with lock_cm:
3523
+ if isinstance(self.tracker, BaseMigrationTracker) and self.tracker.holds_transaction_scoped_lock(driver):
3524
+ with self.runner.use_step_savepoints(driver):
3525
+ step_error: BaseException | None = None
3526
+ try:
3527
+ yield
3528
+ except BaseException as exc:
3529
+ step_error = exc
3530
+ if step_error is not None:
3531
+ if self.runner.pop_savepoint_recovered(driver) and await _driver_in_transaction_async(driver):
3532
+ try:
3533
+ await driver.commit()
3534
+ except Exception as commit_exc:
3535
+ raise commit_exc from step_error
3536
+ raise step_error
3537
+ recorded_error = self._last_command_error
3538
+ if recorded_error is not None:
3539
+ self.runner.pop_savepoint_recovered(driver)
3540
+ if self.runner.pop_unrecovered_step_failure(driver):
3541
+ _raise_as_migration_error(recorded_error)
3542
+ else:
3543
+ yield
3544
+
3545
+ async def _validate_migration_schema(self, driver: Any) -> None:
3546
+ """Validate the configured migration schema exists before issuing DDL."""
3547
+ default_schema = self._resolve_default_schema()
3548
+ if default_schema is None:
3549
+ return
3550
+ if not await driver.has_schema(default_schema):
3551
+ msg = f"Configured schema '{default_schema}' does not exist"
3552
+ raise MigrationError(msg)
3553
+
3554
+ async def _enforce_applied_checksums(
3555
+ self,
3556
+ driver: Any,
3557
+ *,
3558
+ dry_run: bool,
3559
+ use_logger: bool,
3560
+ echo: bool,
3561
+ summary_only: bool,
3562
+ records: "list[AppliedMigrationRecord] | None" = None,
3563
+ versions: "AbstractSet[str] | None" = None,
3564
+ ) -> None:
3565
+ """Refuse changed applied migration files and re-record verified legacy checksums.
3566
+
3567
+ Args:
3568
+ driver: Active database driver.
3569
+ dry_run: Whether database writes are disabled.
3570
+ use_logger: Whether logger output is enabled.
3571
+ echo: Whether console output is enabled.
3572
+ summary_only: Whether summary-only logging is enabled.
3573
+ records: Applied records to audit. Read from the tracking table when None.
3574
+ versions: Optional subset of applied versions to audit.
3575
+ """
3576
+ audited: list[AppliedMigrationRecord]
3577
+ if records is not None:
3578
+ audited = records
3579
+ elif dry_run:
3580
+ audited = await self._read_applied_migrations(driver)
3581
+ else:
3582
+ audited = await self.tracker.get_applied_migrations(driver)
3583
+ mismatched, rerecord = self._applied_checksum_audit(
3584
+ audited, await self.runner.get_migration_files(), versions=versions
3585
+ )
3586
+ self._ensure_applied_checksums(mismatched)
3587
+ await self._rerecord_legacy_checksums(
3588
+ driver, rerecord, dry_run=dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only
3589
+ )
3590
+
3591
+ async def _rerecord_legacy_checksums(
3592
+ self,
3593
+ driver: Any,
3594
+ rerecord: "dict[str, str]",
3595
+ *,
3596
+ dry_run: bool,
3597
+ use_logger: bool,
3598
+ echo: bool,
3599
+ summary_only: bool,
3600
+ ) -> None:
3601
+ """Write marker digests for applied rows that verified through the legacy checksum form."""
3602
+ if not rerecord:
3603
+ return
3604
+ versions = ", ".join(sorted(rerecord))
3605
+ verb = "Would re-record" if dry_run else "Re-recorded"
3606
+ if not dry_run:
3607
+ for version in sorted(rerecord):
3608
+ await self.tracker.update_checksum(driver, version, rerecord[version])
3609
+ _output_info(
3610
+ use_logger,
3611
+ echo,
3612
+ summary_only,
3613
+ "%s legacy checksums for [%s]",
3614
+ verb,
3615
+ versions,
3616
+ rich_message=f"[cyan]{verb} legacy checksums for [{versions}][/]",
3617
+ )
3618
+
3619
+ async def _read_applied_migrations(self, driver: Any) -> "list[AppliedMigrationRecord]":
3620
+ """Read applied migration records without creating the tracking table.
3621
+
3622
+ Returns:
3623
+ Applied records, or an empty list when the tracking table does not exist.
3624
+ """
3625
+ tables = await driver.data_dictionary.get_tables(driver, schema=self.tracker.catalog_schema_name())
3626
+ if not self._tracking_table_exists(tables):
3627
+ return []
3628
+ return cast("list[AppliedMigrationRecord]", await self.tracker.get_applied_migrations(driver))
3629
+
3630
+ async def _load_reconcilable_migrations(
3631
+ self, all_migrations: "list[tuple[str, Path]]"
3632
+ ) -> "dict[str, LoadedMigrationMetadata]":
3633
+ """Load metadata for tracking-table reconciliation, skipping files that cannot be loaded.
3634
+
3635
+ A skipped file is never reconciled; if it is pending, ``upgrade`` loads it again and reports the failure.
3636
+ """
3637
+ loaded: dict[str, LoadedMigrationMetadata] = {}
3638
+ for version, file_path in all_migrations:
3639
+ try:
3640
+ loaded[version] = await self.runner.load_migration(file_path, version)
3641
+ except Exception as exc:
3642
+ self._log_reconciliation_load_failure(version, file_path, exc)
3643
+ return loaded
3644
+
3645
+ async def _synchronized_applied_versions(
3646
+ self, driver: Any, *, auto_sync: bool, dry_run: bool, use_logger: bool, echo: bool, summary_only: bool
3647
+ ) -> "list[str]":
3648
+ """Return applied versions after optional reconciliation, writing nothing in a dry run.
3649
+
3650
+ A dry run neither creates the tracking table nor reconciles records; it reports the reconciliation it would
3651
+ perform and returns the applied versions as they would look afterwards. A partially applied squash raises
3652
+ even when ``auto_sync`` is disabled.
3653
+
3654
+ Args:
3655
+ driver: Active database driver.
3656
+ auto_sync: Whether to reconcile renamed and squashed migrations.
3657
+ dry_run: Whether database writes are disabled.
3658
+ use_logger: Whether logger output is enabled.
3659
+ echo: Whether console output is enabled.
3660
+ summary_only: Whether summary-only logging is enabled.
3661
+
3662
+ Returns:
3663
+ Applied version numbers.
3664
+ """
3665
+ if dry_run:
3666
+ applied_migrations = await self._read_applied_migrations(driver)
3667
+ else:
3668
+ await self.tracker.ensure_tracking_table(driver)
3669
+ applied_migrations = await self.tracker.get_applied_migrations(driver)
3670
+ all_migrations = await self.runner.get_migration_files()
3671
+ plan = self._plan_version_reconciliation(
3672
+ all_migrations, applied_migrations, await self._load_reconcilable_migrations(all_migrations)
3673
+ )
3674
+ if not auto_sync or not plan.change_count:
3675
+ return [m["version_num"] for m in applied_migrations]
3676
+ self._report_version_reconciliation(
3677
+ plan, dry_run=dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only
3678
+ )
3679
+ if dry_run:
3680
+ return list(plan.applied_versions)
3681
+ await self._apply_version_reconciliation(driver, plan)
3682
+ return [m["version_num"] for m in await self.tracker.get_applied_migrations(driver)]
3683
+
3684
+ async def _apply_version_reconciliation(self, driver: Any, plan: VersionReconciliationPlan) -> None:
3685
+ """Write a reconciliation plan to the tracking table."""
3686
+ for squash in plan.squashes:
3687
+ await self.tracker.replace_with_squash(
3688
+ driver, squash.target_version, list(squash.replaced_versions), squash.description, squash.checksum
3689
+ )
3690
+ for rename in plan.renames:
3691
+ await self.tracker.update_version_record(
3692
+ driver, rename.old_version, rename.new_version, applied_versions=set(rename.claimed_versions)
3693
+ )
3694
+
3695
+ def _create_squash_runner(self) -> SyncMigrationRunner:
3696
+ """Create the synchronous runner the squasher uses to load migration files.
3697
+
3698
+ Squash planning only reads files, so async commands share the synchronous squasher through a dedicated
3699
+ runner bound to a fresh migration context.
3700
+ """
3701
+ context = MigrationContext.from_config(self.config)
3702
+ context.extension_config = self.extension_configs
3703
+ return SyncMigrationRunner(
3704
+ self.migrations_path,
3705
+ self._discover_extension_migrations(),
3706
+ context,
3707
+ self.extension_configs,
3708
+ runtime=self._runtime,
3709
+ description_hints=self._template_settings.description_hints,
3710
+ )
3711
+
3712
+ async def _apply_single_migration(
3713
+ self,
3714
+ driver: Any,
3715
+ migration: "LoadedMigrationMetadata",
3716
+ version: str,
3717
+ use_logger: bool,
3718
+ echo: bool,
3719
+ summary_only: bool,
3720
+ ) -> int | None:
3721
+ """Apply a single migration and record it.
3722
+
3723
+ Args:
3724
+ driver: Database driver instance.
3725
+ migration: Migration dictionary with version, description, checksum.
3726
+ version: Version string.
3727
+ use_logger: Whether to output to logger instead of console.
3728
+ echo: Whether to echo output to the console.
3729
+ summary_only: Whether summary-only logging is enabled.
3730
+
3731
+ Returns:
3732
+ Execution time in ms on success, None on failure.
3733
+ """
3734
+ await self.tracker.renew_lock(driver)
3735
+ use_txn = self.runner.should_use_transaction(migration, self.config)
3736
+ try:
3737
+
3738
+ async def record_version(
3739
+ exec_time: int,
3740
+ migration: "LoadedMigrationMetadata" = migration,
3741
+ version: str = version,
3742
+ use_txn: bool = use_txn,
3743
+ ) -> None:
3744
+ recorded_version = migration["version"] or version
3745
+ if isinstance(self.tracker, AsyncMigrationTracker):
3746
+ await self.tracker.record_migration(
3747
+ driver,
3748
+ recorded_version,
3749
+ migration["description"],
3750
+ exec_time,
3751
+ migration["checksum"],
3752
+ commit=not use_txn,
3753
+ replaces=migration.get("replaces"),
3754
+ )
3755
+ else:
3756
+ await self.tracker.record_migration(
3757
+ driver, recorded_version, migration["description"], exec_time, migration["checksum"]
3758
+ )
3759
+
3760
+ _, execution_time = await self.runner.execute_upgrade(
3761
+ driver, migration, use_transaction=use_txn, on_success=record_version
3762
+ )
3763
+ except Exception as exc:
3764
+ rollback_msg = " (transaction rolled back)" if use_txn else ""
3765
+ _output_error(
3766
+ use_logger,
3767
+ echo,
3768
+ summary_only,
3769
+ "Migration %s failed%s",
3770
+ version,
3771
+ rollback_msg,
3772
+ rich_message=f"[red]✗ Failed{rollback_msg}: {exc}[/]",
3773
+ )
3774
+ self._last_command_error = exc
3775
+ return None
3776
+ else:
3777
+ _output_info(
3778
+ use_logger,
3779
+ echo,
3780
+ summary_only,
3781
+ "Applied migration %s in %dms",
3782
+ version,
3783
+ execution_time,
3784
+ rich_message=f"[green]✓ Applied in {execution_time}ms[/]",
3785
+ )
3786
+ return execution_time
3787
+
3788
+ async def _revert_single_migration(
3789
+ self,
3790
+ driver: Any,
3791
+ migration: "LoadedMigrationMetadata",
3792
+ version: str,
3793
+ use_logger: bool,
3794
+ echo: bool,
3795
+ summary_only: bool,
3796
+ ) -> int | None:
3797
+ """Revert a single migration.
3798
+
3799
+ Args:
3800
+ driver: Database driver instance.
3801
+ migration: Migration dictionary.
3802
+ version: Version string.
3803
+ use_logger: Whether to output to logger instead of console.
3804
+ echo: Whether to echo output to the console.
3805
+ summary_only: Whether summary-only logging is enabled.
3806
+
3807
+ Returns:
3808
+ Execution time in ms on success, None on failure.
3809
+ """
3810
+ await self.tracker.renew_lock(driver)
3811
+ use_txn = self.runner.should_use_transaction(migration, self.config)
3812
+ reverted = False
3813
+ try:
3814
+
3815
+ async def remove_version(exec_time: int, version: str = version, use_txn: bool = use_txn) -> None:
3816
+ nonlocal reverted
3817
+ reverted = True
3818
+ if isinstance(self.tracker, AsyncMigrationTracker):
3819
+ await self.tracker.remove_migration(driver, version, commit=not use_txn)
3820
+ else:
3821
+ await self.tracker.remove_migration(driver, version)
3822
+
3823
+ _, execution_time = await self.runner.execute_downgrade(
3824
+ driver, migration, use_transaction=use_txn, on_success=remove_version
3825
+ )
3826
+ except Exception as exc:
3827
+ rollback_msg = " (transaction rolled back)" if use_txn else ""
3828
+ _output_error(
3829
+ use_logger,
3830
+ echo,
3831
+ summary_only,
3832
+ "Migration %s failed%s",
3833
+ version,
3834
+ rollback_msg,
3835
+ rich_message=f"[red]✗ Failed{rollback_msg}: {exc}[/]",
3836
+ )
3837
+ self._last_command_error = exc
3838
+ return None
3839
+ if not reverted:
3840
+ missing_exc = MigrationError(f"Migration {version} does not support downgrade")
3841
+ _output_error(
3842
+ use_logger,
3843
+ echo,
3844
+ summary_only,
3845
+ "Migration %s failed",
3846
+ version,
3847
+ rich_message=f"[red]✗ Failed: {missing_exc}[/]",
3848
+ )
3849
+ self._last_command_error = missing_exc
3850
+ return None
3851
+ _output_info(
3852
+ use_logger,
3853
+ echo,
3854
+ summary_only,
3855
+ "Reverted migration %s in %dms",
3856
+ version,
3857
+ execution_time,
3858
+ rich_message=f"[green]✓ Reverted in {execution_time}ms[/]",
3859
+ )
3860
+ return execution_time
3861
+
3862
+
3863
+ @overload
3864
+ def create_migration_commands(config: "SyncConfigT") -> "SyncMigrationCommands[SyncConfigT]": ...
3865
+
3866
+
3867
+ @overload
3868
+ def create_migration_commands(config: "AsyncConfigT") -> "AsyncMigrationCommands[AsyncConfigT]": ...
3869
+
3870
+
3871
+ def create_migration_commands(
3872
+ config: "SyncConfigT | AsyncConfigT",
3873
+ ) -> "SyncMigrationCommands[SyncConfigT] | AsyncMigrationCommands[AsyncConfigT]":
3874
+ """Factory function to create the appropriate migration commands.
3875
+
3876
+ Args:
3877
+ config: The SQLSpec configuration.
3878
+
3879
+ Returns:
3880
+ Appropriate migration commands instance.
3881
+ """
3882
+ if config.is_async:
3883
+ return cast("AsyncMigrationCommands[AsyncConfigT]", AsyncMigrationCommands(cast("AsyncConfigT", config)))
3884
+ return cast("SyncMigrationCommands[SyncConfigT]", SyncMigrationCommands(cast("SyncConfigT", config)))
3885
+
3886
+
3887
+ def _output_info(
3888
+ use_logger: bool, echo: bool, summary_only: bool, message: str, *args: Any, rich_message: str | None = None
3889
+ ) -> None:
3890
+ """Output an info message to logger or console."""
3891
+ if use_logger:
3892
+ if summary_only:
3893
+ return
3894
+ logger.info(message, *args)
3895
+ else:
3896
+ if not echo:
3897
+ return
3898
+ console.print(rich_message or message % args if args else message)
3899
+
3900
+
3901
+ def _output_error(
3902
+ use_logger: bool, echo: bool, summary_only: bool, message: str, *args: Any, rich_message: str | None = None
3903
+ ) -> None:
3904
+ """Output an error message to logger or console."""
3905
+ if use_logger:
3906
+ logger.error(message, *args)
3907
+ else:
3908
+ if not echo:
3909
+ return
3910
+ console.print(rich_message or message % args if args else message)
3911
+
3912
+
3913
+ def _log_command_summary(
3914
+ *,
3915
+ use_logger: bool,
3916
+ summary_only: bool,
3917
+ command: str,
3918
+ status: str,
3919
+ revision: str,
3920
+ dry_run: bool,
3921
+ pending_count: int,
3922
+ applied_count: int | None,
3923
+ reverted_count: int | None,
3924
+ duration_ms: int,
3925
+ db_system: str | None,
3926
+ bind_key: str | None,
3927
+ config_name: str,
3928
+ error: Exception | None = None,
3929
+ allow_missing: bool | None = None,
3930
+ auto_sync: bool | None = None,
3931
+ reconcilers_invoked: int | None = None,
3932
+ ) -> None:
3933
+ """Emit a single summary log entry for migration commands."""
3934
+ if not use_logger or not summary_only:
3935
+ return
3936
+ level = logging.ERROR if status == "failed" else logging.INFO
3937
+ extra_fields: dict[str, Any] = {
3938
+ "command": command,
3939
+ "status": status,
3940
+ "revision": revision,
3941
+ "dry_run": dry_run,
3942
+ "pending_count": pending_count,
3943
+ "duration_ms": duration_ms,
3944
+ "db_system": db_system,
3945
+ "bind_key": bind_key,
3946
+ "config_name": config_name,
3947
+ }
3948
+ if applied_count is not None:
3949
+ extra_fields["applied_count"] = applied_count
3950
+ if reverted_count is not None:
3951
+ extra_fields["reverted_count"] = reverted_count
3952
+ if allow_missing is not None:
3953
+ extra_fields["allow_missing"] = allow_missing
3954
+ if auto_sync is not None:
3955
+ extra_fields["auto_sync"] = auto_sync
3956
+ if reconcilers_invoked is not None:
3957
+ extra_fields["reconcilers_invoked"] = reconcilers_invoked
3958
+ if error is not None:
3959
+ extra_fields["error_type"] = type(error).__name__
3960
+ log_with_context(logger, level, "migration.command.summary", **extra_fields)
3961
+
3962
+
3963
+ def _report_no_pending_migrations(use_logger: bool, echo: bool, summary_only: bool, has_migrations: bool) -> None:
3964
+ """Report that there are no pending migrations.
3965
+
3966
+ Args:
3967
+ use_logger: Whether to output to logger instead of console.
3968
+ echo: Whether to echo output to the console.
3969
+ summary_only: Whether summary-only logging is enabled.
3970
+ has_migrations: Whether any migrations exist at all.
3971
+ """
3972
+ if not has_migrations:
3973
+ _output_info(
3974
+ use_logger,
3975
+ echo,
3976
+ summary_only,
3977
+ "No migrations found. Create your first migration with 'sqlspec create-migration'.",
3978
+ rich_message="[yellow]No migrations found. Create your first migration with 'sqlspec create-migration'.[/]",
3979
+ )
3980
+ else:
3981
+ _output_info(
3982
+ use_logger,
3983
+ echo,
3984
+ summary_only,
3985
+ "Already at latest version",
3986
+ rich_message="[green]Already at latest version[/]",
3987
+ )
3988
+
3989
+
3990
+ def _bind_arguments(signature: inspect.Signature, args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any]:
3991
+ bound = signature.bind_partial(*args, **kwargs)
3992
+ arguments = dict(bound.arguments)
3993
+ arguments.pop("self", None)
3994
+ return arguments
3995
+
3996
+
3997
+ def _raise_as_migration_error(error: Exception) -> NoReturn:
3998
+ """Raise a recorded command error directly when already a ``MigrationError``."""
3999
+ if isinstance(error, MigrationError):
4000
+ raise error
4001
+ msg = f"Migration command failed: {error}"
4002
+ raise MigrationError(msg) from error