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,2470 @@
1
+ """Fixture loading utilities for SQLSpec.
2
+
3
+ Provides functions for writing, loading and parsing JSON fixture files
4
+ used in testing and development, and for loading and exporting per-table
5
+ fixture files against a database driver. Supports both sync and async operations.
6
+ """
7
+
8
+ import array
9
+ import base64
10
+ import gzip
11
+ import importlib
12
+ import os
13
+ import re
14
+ import secrets
15
+ import struct
16
+ import zipfile
17
+ from collections.abc import Callable, Mapping, Sequence
18
+ from datetime import time, timedelta
19
+ from decimal import Decimal
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING, Any, Final, NamedTuple
22
+
23
+ from sqlglot import Dialect, exp
24
+
25
+ from sqlspec import dialects as _dialects
26
+ from sqlspec.core.parameters._types import TypedParameter
27
+ from sqlspec.core.query_modifiers import sanitize_parameter_name
28
+ from sqlspec.core.type_converter import convert_iso_date, convert_iso_datetime, convert_uuid
29
+ from sqlspec.exceptions import with_cause
30
+ from sqlspec.storage.registry import storage_registry
31
+ from sqlspec.utils.logging import get_logger
32
+ from sqlspec.utils.serializers._json import from_json, to_json
33
+ from sqlspec.utils.serializers._schema import schema_dump
34
+ from sqlspec.utils.sync_tools import async_
35
+
36
+ if TYPE_CHECKING:
37
+ from sqlglot.dialects.dialect import DialectType
38
+
39
+ from sqlspec.driver._async import AsyncDriverAdapterBase
40
+ from sqlspec.driver._sync import SyncDriverAdapterBase
41
+ from sqlspec.typing import SupportedSchemaModel
42
+
43
+ _ = _dialects
44
+
45
+ __all__ = (
46
+ "export_table_fixtures_async",
47
+ "export_table_fixtures_sync",
48
+ "load_table_fixtures_async",
49
+ "load_table_fixtures_sync",
50
+ "open_fixture_async",
51
+ "open_fixture_sync",
52
+ "write_fixture_async",
53
+ "write_fixture_sync",
54
+ )
55
+
56
+ _TABLE_FIXTURE_EXTENSIONS: Final["tuple[str, ...]"] = (".jsonl.gz", ".json.gz", ".jsonl", ".json")
57
+ _SHARD_STEM_PATTERN: Final["re.Pattern[str]"] = re.compile(r"^(.+)\.(\d+)$")
58
+ _COLUMN_NAME_PATTERN: Final["re.Pattern[str]"] = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
59
+ _TABLE_NAME_PATTERN: Final["re.Pattern[str]"] = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?")
60
+ _SEQUENCE_IDENTIFIER_PATTERN: Final["re.Pattern[str]"] = re.compile(
61
+ r"[A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)?"
62
+ )
63
+ _NEXTVAL_CALL_PATTERN: Final["re.Pattern[str]"] = re.compile(r"""(?i)\bnextval\(\s*(?:'([^']+)'|([`A-Za-z0-9_.$]+))""")
64
+ _NEXT_VALUE_FOR_PATTERN: Final["re.Pattern[str]"] = re.compile(
65
+ r"""(?i)\b(?:next\s+value|nextval)\s+for\s+([A-Za-z0-9_.$"\[\]`]+)"""
66
+ )
67
+ _ORACLE_NEXTVAL_PATTERN: Final["re.Pattern[str]"] = re.compile(
68
+ r"""(?i)^\s*\(*\s*([A-Za-z0-9_.$"]+)\.\s*"?nextval"?\s*\)*\s*$"""
69
+ )
70
+ _INSERT_VALUES_CLAUSE_PATTERN: Final["re.Pattern[str]"] = re.compile(r"\)\s+VALUES\s+\(")
71
+ _POSTGRES_DIALECTS: Final["frozenset[str]"] = frozenset({"cockroach", "cockroachdb", "postgres", "postgresql"})
72
+ _SEQUENCE_RESYNC_DIALECTS: Final["frozenset[str]"] = frozenset({
73
+ "cockroach",
74
+ "cockroachdb",
75
+ "db2",
76
+ "duckdb",
77
+ "mariadb",
78
+ "mssql",
79
+ "mysql",
80
+ "oracle",
81
+ "postgres",
82
+ "postgresql",
83
+ "sqlanywhere",
84
+ "sqlite",
85
+ "sybase",
86
+ "tsql",
87
+ })
88
+ _MYSQL_DIALECTS: Final["frozenset[str]"] = frozenset({"mariadb", "mysql"})
89
+ _ON_CONFLICT_FAMILIES: Final["frozenset[str]"] = frozenset({"duckdb", "postgres", "sqlite"})
90
+ _JSON_VALUE_FAMILIES: Final["frozenset[str]"] = frozenset({"duckdb", "mysql", "postgres", "sqlite"})
91
+ _JSON_TYPE_NAMES: Final["frozenset[str]"] = frozenset({"json", "jsonb"})
92
+ _BINARY_TYPES: Final["frozenset[str]"] = frozenset({
93
+ "binary",
94
+ "blob",
95
+ "byte",
96
+ "bytea",
97
+ "image",
98
+ "long binary",
99
+ "long raw",
100
+ "longblob",
101
+ "mediumblob",
102
+ "raw",
103
+ "tinyblob",
104
+ "varbinary",
105
+ "varbyte",
106
+ })
107
+ _BINARY_TYPE_PREFIXES: Final["tuple[str, ...]"] = ("binary(", "varbinary(", "byte(", "varbyte(")
108
+ _UNORDERABLE_POSTGRES_TYPES: Final["frozenset[str]"] = frozenset({
109
+ "box",
110
+ "circle",
111
+ "halfvec",
112
+ "json",
113
+ "line",
114
+ "lseg",
115
+ "path",
116
+ "point",
117
+ "polygon",
118
+ "sparsevec",
119
+ "vector",
120
+ "xml",
121
+ })
122
+ _UNORDERABLE_FAMILY_TYPES: Final["Mapping[str, frozenset[str]]"] = {
123
+ "teradata": frozenset({"blob", "clob", "json", "xml", "st_geometry", "mbr", "mbb", "period"}),
124
+ "bigquery": frozenset({"geography", "json"}),
125
+ "snowflake": frozenset({"array", "geography", "geometry", "object", "variant"}),
126
+ "db2": frozenset({"blob", "clob", "dbclob", "long varchar", "long vargraphic", "xml"}),
127
+ "mysql": frozenset({"blob", "geometry", "json", "longblob", "mediumblob", "point", "tinyblob", "vector"}),
128
+ "oracle": frozenset({"bfile", "blob", "clob", "long", "long raw", "nclob", "vector", "xmltype"}),
129
+ "spanner": frozenset({"json", "tokenlist"}),
130
+ "sqlanywhere": frozenset({"long binary", "long nvarchar", "long varchar", "xml"}),
131
+ "sybase": frozenset({"image", "long binary", "long nvarchar", "long varchar", "text", "unitext"}),
132
+ "tsql": frozenset({"geography", "geometry", "image", "ntext", "text", "xml"}),
133
+ }
134
+ _IDENTITY_GENERATION_VALUES: Final["frozenset[str]"] = frozenset({"always", "by default", "by default on null"})
135
+ _ALWAYS_IDENTITY_GENERATION_VALUES: Final["frozenset[str]"] = frozenset({"always"})
136
+ _ISO_DURATION_PATTERN: Final["re.Pattern[str]"] = re.compile(
137
+ r"(-)?P(?:(\d+(?:\.\d+)?)W)?(?:(\d+(?:\.\d+)?)D)?"
138
+ r"(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?"
139
+ )
140
+ _DUCKDB_INTERVAL_PARTS: Final[int] = 3
141
+ _NANOSECONDS_PER_MICROSECOND: Final[int] = 1000
142
+ _TEMPORARY_FILE_MODE: Final[int] = 0o666
143
+ _MAX_ZIP_FIXTURE_BYTES: Final[int] = 256 * 1024 * 1024
144
+ _FLOAT32_BYTES: Final[int] = 4
145
+ _PG_VECTOR_HEADER_BYTES: Final[int] = 4
146
+
147
+ logger = get_logger("sqlspec.utils.fixtures")
148
+
149
+
150
+ def open_fixture_sync(fixtures_path: Any, fixture_name: str) -> Any:
151
+ """Load and parse a JSON fixture file with compression support.
152
+
153
+ Supports reading from:
154
+ - Regular JSON files (.json)
155
+ - Gzipped JSON files (.json.gz)
156
+ - Zipped JSON files (.json.zip)
157
+
158
+ Args:
159
+ fixtures_path: The path to look for fixtures (pathlib.Path)
160
+ fixture_name: The fixture name to load.
161
+
162
+ Returns:
163
+ The parsed JSON data
164
+ """
165
+ fixture_path = _find_fixture_file(fixtures_path, fixture_name)
166
+
167
+ if fixture_path.suffix in {".gz", ".zip"}:
168
+ f_data = _read_compressed_file(fixture_path)
169
+ else:
170
+ with fixture_path.open(mode="r", encoding="utf-8") as f:
171
+ f_data = f.read()
172
+
173
+ return from_json(f_data)
174
+
175
+
176
+ async def open_fixture_async(fixtures_path: Any, fixture_name: str) -> Any:
177
+ """Load and parse a JSON fixture file asynchronously with compression support.
178
+
179
+ Supports reading from:
180
+ - Regular JSON files (.json)
181
+ - Gzipped JSON files (.json.gz)
182
+ - Zipped JSON files (.json.zip)
183
+
184
+ For compressed files, uses sync reading in a thread pool since gzip and zipfile
185
+ don't have native async equivalents.
186
+
187
+ Args:
188
+ fixtures_path: The path to look for fixtures (pathlib.Path)
189
+ fixture_name: The fixture name to load.
190
+
191
+ Returns:
192
+ The parsed JSON data
193
+ """
194
+ fixture_path = _find_fixture_file(fixtures_path, fixture_name)
195
+
196
+ if fixture_path.suffix in {".gz", ".zip"}:
197
+ f_data = await _async_read_compressed(fixture_path)
198
+ else:
199
+ f_data = await _async_read_text(fixture_path)
200
+
201
+ return from_json(f_data)
202
+
203
+
204
+ def write_fixture_sync(
205
+ fixtures_path: str,
206
+ table_name: str,
207
+ data: "list[SupportedSchemaModel] | list[dict[str, Any]] | SupportedSchemaModel",
208
+ storage_backend: str = "local",
209
+ compress: bool = False,
210
+ **storage_kwargs: Any,
211
+ ) -> None:
212
+ """Write fixture data to storage using SQLSpec storage backend.
213
+
214
+ Args:
215
+ fixtures_path: Base path where fixtures should be stored
216
+ table_name: Name of the table/fixture (used as filename)
217
+ data: Data to write - can be list of dicts, models, or single model
218
+ storage_backend: Storage backend to use (default: "local")
219
+ compress: Whether to gzip compress the output
220
+ **storage_kwargs: Additional arguments for the storage backend
221
+
222
+ Raises:
223
+ ValueError: If storage backend is not found or table_name is invalid
224
+ """
225
+ _validated_fixture_name(table_name)
226
+ if storage_backend == "local":
227
+ uri = "file://"
228
+ storage_kwargs["base_path"] = _resolve_path_str(fixtures_path)
229
+ else:
230
+ uri = storage_backend
231
+
232
+ try:
233
+ storage = storage_registry.get(uri, **storage_kwargs)
234
+ except Exception as exc:
235
+ msg = f"Failed to get storage backend for '{storage_backend}': {exc}"
236
+ raise with_cause(ValueError(msg), exc) from exc
237
+
238
+ json_content = _serialize_data(data)
239
+
240
+ if compress:
241
+ file_path = f"{table_name}.json.gz"
242
+ content = gzip.compress(json_content.encode("utf-8"))
243
+ storage.write_bytes_sync(file_path, content)
244
+ else:
245
+ file_path = f"{table_name}.json"
246
+ storage.write_text_sync(file_path, json_content)
247
+
248
+
249
+ async def write_fixture_async(
250
+ fixtures_path: str,
251
+ table_name: str,
252
+ data: "list[SupportedSchemaModel] | list[dict[str, Any]] | SupportedSchemaModel",
253
+ storage_backend: str = "local",
254
+ compress: bool = False,
255
+ **storage_kwargs: Any,
256
+ ) -> None:
257
+ """Write fixture data to storage using SQLSpec storage backend asynchronously.
258
+
259
+ Args:
260
+ fixtures_path: Base path where fixtures should be stored
261
+ table_name: Name of the table/fixture (used as filename)
262
+ data: Data to write - can be list of dicts, models, or single model
263
+ storage_backend: Storage backend to use (default: "local")
264
+ compress: Whether to gzip compress the output
265
+ **storage_kwargs: Additional arguments for the storage backend
266
+
267
+ Raises:
268
+ ValueError: If storage backend is not found or table_name is invalid
269
+ """
270
+ _validated_fixture_name(table_name)
271
+ if storage_backend == "local":
272
+ uri = "file://"
273
+ storage_kwargs["base_path"] = _resolve_path_str(fixtures_path)
274
+ else:
275
+ uri = storage_backend
276
+
277
+ try:
278
+ storage = storage_registry.get(uri, **storage_kwargs)
279
+ except Exception as exc:
280
+ msg = f"Failed to get storage backend for '{storage_backend}': {exc}"
281
+ raise with_cause(ValueError(msg), exc) from exc
282
+
283
+ json_content = await _async_serialize(data)
284
+
285
+ if compress:
286
+ file_path = f"{table_name}.json.gz"
287
+ content = await _async_compress(json_content)
288
+ await storage.write_bytes_async(file_path, content)
289
+ else:
290
+ file_path = f"{table_name}.json"
291
+ await storage.write_text_async(file_path, json_content)
292
+
293
+
294
+ def load_table_fixtures_sync(
295
+ driver: "SyncDriverAdapterBase",
296
+ fixtures_path: "str | Path",
297
+ *,
298
+ tables: "Sequence[str] | None" = None,
299
+ table_order: "Sequence[str] | None" = None,
300
+ conflict_keys: "Mapping[str, Sequence[str] | str] | None" = None,
301
+ batch_size: int = 500,
302
+ resync_sequences: bool = False,
303
+ ignore_unknown_columns: bool = False,
304
+ exclude_update_columns: "Sequence[str] | Mapping[str, Sequence[str] | str] | None" = None,
305
+ ) -> "dict[str, int]":
306
+ """Load per-table fixture files into database tables.
307
+
308
+ Each table reads from one or more files named after it: ``<table>.json`` holding a JSON
309
+ array of row objects, or ``<table>.jsonl`` holding one row object per line, either
310
+ optionally gzipped (``.gz``). Tables split into multiple shards (e.g. ``<table>.001.jsonl.gz``,
311
+ ``<table>.002.jsonl.gz``) are loaded in ascending numeric shard order. Sparse row objects
312
+ are normalized across the ordered union of column keys in the file, defaulting omitted keys
313
+ to ``None``. Table and column names are quoted, so they must match the database spelling
314
+ exactly. Rows are inserted in batches with ``execute_many``; each file is read into memory.
315
+ Transaction control stays with the caller.
316
+
317
+ The target table's columns are read from the driver's data dictionary first, and
318
+ JSON values of these column types are converted: ISO 8601 strings in timestamp,
319
+ datetime, date (datetimes on Oracle, whose DATE carries a time), and (except on
320
+ MySQL) time columns to datetimes, dates, and times; ISO 8601 durations without year
321
+ or month parts and numbers of seconds in interval columns to ``timedelta``, and
322
+ DuckDB ``[months, days, nanoseconds]`` interval lists to interval text; strings and
323
+ numbers in numeric and decimal columns to ``Decimal``; strings in uuid columns to
324
+ ``UUID``; base64 strings in bytea, blob, raw, image, binary, and varbinary columns
325
+ to bytes; and PostgreSQL, MySQL, DuckDB, and SQLite json and jsonb values to JSON
326
+ text. Vector column values are converted according to the driver family and data
327
+ type. Values of generated (computed) columns are ignored, while identity column
328
+ values are loaded. On PostgreSQL, ``GENERATED ALWAYS`` identity columns receive
329
+ the loaded values through ``OVERRIDING SYSTEM VALUE`` and are never updated by upserts;
330
+ on SQL Server, inserts into identity columns run between ``SET IDENTITY_INSERT ... ON``
331
+ and ``OFF``. Other databases receive identity values as given and reject them for
332
+ identity columns that only allow generated values.
333
+
334
+ Args:
335
+ driver: Sync driver that runs the inserts.
336
+ fixtures_path: Directory containing the table fixture files.
337
+ tables: Tables to load. Defaults to every table fixture file in the directory;
338
+ files whose names are not table identifiers are skipped with a debug log, and
339
+ a dot in a file name marks a schema-qualified table.
340
+ table_order: Tables to load first, in this order. Remaining tables load
341
+ afterwards in alphabetical order; names not being loaded are ignored.
342
+ conflict_keys: Mapping of table name to a column name or sequence of key column
343
+ names of a unique constraint; tables not being loaded are ignored. Rows for
344
+ matched tables are upserted, updating every non-key, non-excluded column
345
+ when a row with the same key already exists. Supported on PostgreSQL-family,
346
+ SQLite, and DuckDB drivers (``ON CONFLICT``) and MySQL
347
+ (``ON DUPLICATE KEY UPDATE``, which matches any unique key of the table).
348
+ batch_size: Maximum number of rows per ``execute_many`` call.
349
+ resync_sequences: On supported database drivers (PostgreSQL, CockroachDB,
350
+ DuckDB, Oracle, SQL Server, SQLite, IBM Db2, MySQL, MariaDB), set the
351
+ sequence, identity column, or auto-increment counter behind each loaded
352
+ table to follow the column's maximum value, or back to its initial
353
+ minimum/seed value for an empty table, so subsequent generated values follow
354
+ the loaded rows. On MySQL, MariaDB, and Oracle, sequence and identity
355
+ resynchronization executes ``ALTER TABLE`` or ``ALTER SEQUENCE`` DDL, which
356
+ issues an implicit commit of the active transaction. On dialects where
357
+ monotonic sequence resynchronization does not apply (Cloud Spanner,
358
+ BigQuery), the option is skipped with a debug log.
359
+ ignore_unknown_columns: When ``True`` and table column metadata is available,
360
+ strip fixture columns not present in the target table before inserting.
361
+ exclude_update_columns: Column names (or per-table mapping of column names) to
362
+ omit from the ``SET`` clause of upserts so existing values are preserved on
363
+ conflict.
364
+
365
+ Returns:
366
+ Mapping of table name to the number of rows loaded, in load order.
367
+
368
+ Raises:
369
+ ValueError: If ``batch_size`` is below 1, ``conflict_keys`` is given for an
370
+ unsupported dialect, a table or column name is not a plain SQL identifier,
371
+ a table has both unsharded and sharded fixture files, mixed extensions across
372
+ shards, duplicate shard indices, a row in a fixture file is empty, or a fixture
373
+ file only holds generated columns.
374
+ TypeError: If a fixture file does not hold a list of row objects, or
375
+ ``conflict_keys`` / ``exclude_update_columns`` has an invalid type.
376
+ FileNotFoundError: If a requested table has no fixture file.
377
+ """
378
+ dialect = driver.statement_config.dialect
379
+ dialect_name = _dialect_name(dialect)
380
+ family = _dialect_family(dialect_name)
381
+ _validate_load_arguments(conflict_keys, batch_size, dialect_name, family, exclude_update_columns)
382
+ table_files = _ordered_table_files(fixtures_path, tables, table_order)
383
+ resync = _sequence_resync_enabled(resync_sequences, dialect_name, family)
384
+ counts: dict[str, int] = {}
385
+ for table, file_paths in table_files:
386
+ columns: list[_TableColumn] | None = _table_columns_sync(driver, family, table) if resync else None
387
+ total_loaded = 0
388
+ for file_path in file_paths:
389
+ rows = _table_fixture_rows(file_path, _read_table_fixture_text(file_path))
390
+ if columns is None and rows:
391
+ columns = _table_columns_sync(driver, family, table)
392
+ loaded_count = _insert_table_rows_sync(
393
+ driver,
394
+ dialect,
395
+ family,
396
+ table,
397
+ rows,
398
+ columns or [],
399
+ _conflict_keys_for(conflict_keys, table),
400
+ _excluded_update_columns_for(exclude_update_columns, table),
401
+ batch_size,
402
+ ignore_unknown_columns=ignore_unknown_columns,
403
+ )
404
+ total_loaded += loaded_count
405
+ if resync and columns:
406
+ _resync_table_sequences_sync(driver, family, dialect_name, table, columns)
407
+ counts[table] = total_loaded
408
+ return counts
409
+
410
+
411
+ async def load_table_fixtures_async(
412
+ driver: "AsyncDriverAdapterBase",
413
+ fixtures_path: "str | Path",
414
+ *,
415
+ tables: "Sequence[str] | None" = None,
416
+ table_order: "Sequence[str] | None" = None,
417
+ conflict_keys: "Mapping[str, Sequence[str] | str] | None" = None,
418
+ batch_size: int = 500,
419
+ resync_sequences: bool = False,
420
+ ignore_unknown_columns: bool = False,
421
+ exclude_update_columns: "Sequence[str] | Mapping[str, Sequence[str] | str] | None" = None,
422
+ ) -> "dict[str, int]":
423
+ """Load per-table fixture files into database tables asynchronously.
424
+
425
+ Each table reads from one or more files named after it: ``<table>.json`` holding a JSON
426
+ array of row objects, or ``<table>.jsonl`` holding one row object per line, either
427
+ optionally gzipped (``.gz``). Tables split into multiple shards (e.g. ``<table>.001.jsonl.gz``,
428
+ ``<table>.002.jsonl.gz``) are loaded in ascending numeric shard order. Sparse row objects
429
+ are normalized across the ordered union of column keys in the file, defaulting omitted keys
430
+ to ``None``. Table and column names are quoted, so they must match the database spelling
431
+ exactly. Rows are inserted in batches with ``execute_many``; each file is read into memory in a
432
+ worker thread. Transaction control stays with the caller.
433
+
434
+ The target table's columns are read from the driver's data dictionary first, and
435
+ JSON values of these column types are converted: ISO 8601 strings in timestamp,
436
+ datetime, date (datetimes on Oracle, whose DATE carries a time), and (except on
437
+ MySQL) time columns to datetimes, dates, and times; ISO 8601 durations without year
438
+ or month parts and numbers of seconds in interval columns to ``timedelta``, and
439
+ DuckDB ``[months, days, nanoseconds]`` interval lists to interval text; strings and
440
+ numbers in numeric and decimal columns to ``Decimal``; strings in uuid columns to
441
+ ``UUID``; base64 strings in bytea, blob, raw, image, binary, and varbinary columns
442
+ to bytes; and PostgreSQL, MySQL, DuckDB, and SQLite json and jsonb values to JSON
443
+ text. Vector column values are converted according to the driver family and data
444
+ type. Values of generated (computed) columns are ignored, while identity column
445
+ values are loaded. On PostgreSQL, ``GENERATED ALWAYS`` identity columns receive
446
+ the loaded values through ``OVERRIDING SYSTEM VALUE`` and are never updated by upserts;
447
+ on SQL Server, inserts into identity columns run between ``SET IDENTITY_INSERT ... ON``
448
+ and ``OFF``. Other databases receive identity values as given and reject them for
449
+ identity columns that only allow generated values.
450
+
451
+ Args:
452
+ driver: Async driver that runs the inserts.
453
+ fixtures_path: Directory containing the table fixture files.
454
+ tables: Tables to load. Defaults to every table fixture file in the directory;
455
+ files whose names are not table identifiers are skipped with a debug log, and
456
+ a dot in a file name marks a schema-qualified table.
457
+ table_order: Tables to load first, in this order. Remaining tables load
458
+ afterwards in alphabetical order; names not being loaded are ignored.
459
+ conflict_keys: Mapping of table name to a column name or sequence of key column
460
+ names of a unique constraint; tables not being loaded are ignored. Rows for
461
+ matched tables are upserted, updating every non-key, non-excluded column
462
+ when a row with the same key already exists. Supported on PostgreSQL-family,
463
+ SQLite, and DuckDB drivers (``ON CONFLICT``) and MySQL
464
+ (``ON DUPLICATE KEY UPDATE``, which matches any unique key of the table).
465
+ batch_size: Maximum number of rows per ``execute_many`` call.
466
+ resync_sequences: On supported database drivers (PostgreSQL, CockroachDB,
467
+ DuckDB, Oracle, SQL Server, SQLite, IBM Db2, MySQL, MariaDB), set the
468
+ sequence, identity column, or auto-increment counter behind each loaded
469
+ table to follow the column's maximum value, or back to its initial
470
+ minimum/seed value for an empty table, so subsequent generated values follow
471
+ the loaded rows. On MySQL, MariaDB, and Oracle, sequence and identity
472
+ resynchronization executes ``ALTER TABLE`` or ``ALTER SEQUENCE`` DDL, which
473
+ issues an implicit commit of the active transaction. On dialects where
474
+ monotonic sequence resynchronization does not apply (Cloud Spanner,
475
+ BigQuery), the option is skipped with a debug log.
476
+ ignore_unknown_columns: When ``True`` and table column metadata is available,
477
+ strip fixture columns not present in the target table before inserting.
478
+ exclude_update_columns: Column names (or per-table mapping of column names) to
479
+ omit from the ``SET`` clause of upserts so existing values are preserved on
480
+ conflict.
481
+
482
+ Returns:
483
+ Mapping of table name to the number of rows loaded, in load order.
484
+
485
+ Raises:
486
+ ValueError: If ``batch_size`` is below 1, ``conflict_keys`` is given for an
487
+ unsupported dialect, a table or column name is not a plain SQL identifier,
488
+ a table has both unsharded and sharded fixture files, mixed extensions across
489
+ shards, duplicate shard indices, a row in a fixture file is empty, or a fixture
490
+ file only holds generated columns.
491
+ TypeError: If a fixture file does not hold a list of row objects, or
492
+ ``conflict_keys`` / ``exclude_update_columns`` has an invalid type.
493
+ FileNotFoundError: If a requested table has no fixture file.
494
+ """
495
+ dialect = driver.statement_config.dialect
496
+ dialect_name = _dialect_name(dialect)
497
+ family = _dialect_family(dialect_name)
498
+ _validate_load_arguments(conflict_keys, batch_size, dialect_name, family, exclude_update_columns)
499
+ table_files = await _async_ordered_table_files(fixtures_path, tables, table_order)
500
+ resync = _sequence_resync_enabled(resync_sequences, dialect_name, family)
501
+ counts: dict[str, int] = {}
502
+ for table, file_paths in table_files:
503
+ columns: list[_TableColumn] | None = await _table_columns_async(driver, family, table) if resync else None
504
+ total_loaded = 0
505
+ for file_path in file_paths:
506
+ rows = _table_fixture_rows(file_path, await _async_read_table_fixture_text(file_path))
507
+ if columns is None and rows:
508
+ columns = await _table_columns_async(driver, family, table)
509
+ loaded_count = await _insert_table_rows_async(
510
+ driver,
511
+ dialect,
512
+ family,
513
+ table,
514
+ rows,
515
+ columns or [],
516
+ _conflict_keys_for(conflict_keys, table),
517
+ _excluded_update_columns_for(exclude_update_columns, table),
518
+ batch_size,
519
+ ignore_unknown_columns=ignore_unknown_columns,
520
+ )
521
+ total_loaded += loaded_count
522
+ if resync and columns:
523
+ await _resync_table_sequences_async(driver, family, dialect_name, table, columns)
524
+ counts[table] = total_loaded
525
+ return counts
526
+
527
+
528
+ def export_table_fixtures_sync(
529
+ driver: "SyncDriverAdapterBase",
530
+ fixtures_path: "str | Path",
531
+ tables: "Sequence[str]",
532
+ *,
533
+ compress: bool = True,
534
+ jsonl: bool = False,
535
+ max_shard_bytes: "int | None" = None,
536
+ max_rows_per_shard: "int | None" = None,
537
+ ) -> "dict[str, int]":
538
+ """Export database tables to per-table fixture files.
539
+
540
+ Writes every row of each table to ``<table>.json`` (a JSON array) or, with
541
+ ``jsonl``, ``<table>.jsonl`` (one JSON object per line), gzipped with a ``.gz``
542
+ suffix when ``compress`` is set. When ``max_shard_bytes`` or ``max_rows_per_shard``
543
+ is provided and the table exceeds the threshold, rows are split across numbered
544
+ shards ``<table>.001<ext>``, ``<table>.002<ext>``, etc. Generated columns are left out.
545
+ Rows are ordered by the primary key, or by every orderable column when the table has none,
546
+ and each table is read into memory. Dates, times, and datetimes are written as ISO 8601
547
+ strings, ``Decimal`` and ``UUID`` values as strings, bytes as base64 strings, and vector
548
+ values as lists of numbers, which :func:`load_table_fixtures_sync` converts back for typed
549
+ columns.
550
+
551
+ Each file is written to a temporary file in the directory, created with the
552
+ process umask, and stale table fixture files for the same table in the directory
553
+ are removed before moving the new files into place, so the next load reads the
554
+ exported files.
555
+ The directory is created when missing. Table names are quoted and must match the database
556
+ spelling exactly.
557
+
558
+ Args:
559
+ driver: Sync driver that reads the tables.
560
+ fixtures_path: Directory to write the fixture files to.
561
+ tables: Tables to export.
562
+ compress: Whether to gzip the written files.
563
+ jsonl: Whether to write one JSON object per line instead of a JSON array.
564
+ max_shard_bytes: Maximum uncompressed bytes per shard file before splitting.
565
+ max_rows_per_shard: Maximum rows per shard file before splitting.
566
+
567
+ Returns:
568
+ Mapping of table name to the number of rows written.
569
+
570
+ Raises:
571
+ ValueError: If a table name is not a plain SQL identifier, or shard limits are invalid.
572
+ """
573
+ if max_shard_bytes is not None and max_shard_bytes <= 0:
574
+ msg = f"max_shard_bytes must be greater than 0, got {max_shard_bytes}"
575
+ raise ValueError(msg)
576
+ if max_rows_per_shard is not None and max_rows_per_shard <= 0:
577
+ msg = f"max_rows_per_shard must be greater than 0, got {max_rows_per_shard}"
578
+ raise ValueError(msg)
579
+ table_names = [_validated_table_name(table) for table in tables]
580
+ dialect = driver.statement_config.dialect
581
+ family = _dialect_family(_dialect_name(dialect))
582
+ counts: dict[str, int] = {}
583
+ for table in table_names:
584
+ columns = _table_columns_sync(driver, family, table)
585
+ rows = _without_generated_values(
586
+ driver.select(_table_export_query(dialect, family, table, columns)), columns, family
587
+ )
588
+ _write_table_fixture(
589
+ Path(fixtures_path),
590
+ table,
591
+ rows,
592
+ compress,
593
+ jsonl,
594
+ max_shard_bytes=max_shard_bytes,
595
+ max_rows_per_shard=max_rows_per_shard,
596
+ )
597
+ counts[table] = len(rows)
598
+ return counts
599
+
600
+
601
+ async def export_table_fixtures_async(
602
+ driver: "AsyncDriverAdapterBase",
603
+ fixtures_path: "str | Path",
604
+ tables: "Sequence[str]",
605
+ *,
606
+ compress: bool = True,
607
+ jsonl: bool = False,
608
+ max_shard_bytes: "int | None" = None,
609
+ max_rows_per_shard: "int | None" = None,
610
+ ) -> "dict[str, int]":
611
+ """Export database tables to per-table fixture files asynchronously.
612
+
613
+ Writes every row of each table to ``<table>.json`` (a JSON array) or, with
614
+ ``jsonl``, ``<table>.jsonl`` (one JSON object per line), gzipped with a ``.gz``
615
+ suffix when ``compress`` is set. When ``max_shard_bytes`` or ``max_rows_per_shard``
616
+ is provided and the table exceeds the threshold, rows are split across numbered
617
+ shards ``<table>.001<ext>``, ``<table>.002<ext>``, etc. Generated columns are left out.
618
+ Rows are ordered by the primary key, or by every orderable column when the table has none,
619
+ and each table is read into memory. Dates, times, and datetimes are written as ISO 8601
620
+ strings, ``Decimal`` and ``UUID`` values as strings, bytes as base64 strings, and vector
621
+ values as lists of numbers, which :func:`load_table_fixtures_async` converts back for typed
622
+ columns.
623
+
624
+ Each file is written to a temporary file in the directory, created with the
625
+ process umask, and stale table fixture files for the same table in the directory
626
+ are removed before moving the new files into place, so the next load reads the
627
+ exported files.
628
+ The directory is created when missing, and file writes run in a worker thread.
629
+ Table names are quoted and must match the database spelling exactly.
630
+
631
+ Args:
632
+ driver: Async driver that reads the tables.
633
+ fixtures_path: Directory to write the fixture files to.
634
+ tables: Tables to export.
635
+ compress: Whether to gzip the written files.
636
+ jsonl: Whether to write one JSON object per line instead of a JSON array.
637
+ max_shard_bytes: Maximum uncompressed bytes per shard file before splitting.
638
+ max_rows_per_shard: Maximum rows per shard file before splitting.
639
+
640
+ Returns:
641
+ Mapping of table name to the number of rows written.
642
+
643
+ Raises:
644
+ ValueError: If a table name is not a plain SQL identifier, or shard limits are invalid.
645
+ """
646
+ if max_shard_bytes is not None and max_shard_bytes <= 0:
647
+ msg = f"max_shard_bytes must be greater than 0, got {max_shard_bytes}"
648
+ raise ValueError(msg)
649
+ if max_rows_per_shard is not None and max_rows_per_shard <= 0:
650
+ msg = f"max_rows_per_shard must be greater than 0, got {max_rows_per_shard}"
651
+ raise ValueError(msg)
652
+ table_names = [_validated_table_name(table) for table in tables]
653
+ dialect = driver.statement_config.dialect
654
+ family = _dialect_family(_dialect_name(dialect))
655
+ counts: dict[str, int] = {}
656
+ for table in table_names:
657
+ columns = await _table_columns_async(driver, family, table)
658
+ rows = _without_generated_values(
659
+ await driver.select(_table_export_query(dialect, family, table, columns)), columns, family
660
+ )
661
+ await _async_write_table_fixture(
662
+ Path(fixtures_path), table, rows, compress, jsonl, max_shard_bytes, max_rows_per_shard
663
+ )
664
+ counts[table] = len(rows)
665
+ return counts
666
+
667
+
668
+ def _is_binary_type_info(data_type: str) -> bool:
669
+ """Return whether a normalized column data-type label represents raw binary data."""
670
+ normalized = data_type.strip().lower()
671
+ return normalized in _BINARY_TYPES or normalized.startswith(_BINARY_TYPE_PREFIXES)
672
+
673
+
674
+ class _TableColumn(NamedTuple):
675
+ """Column metadata used to convert, insert, order, and resync table fixture rows.
676
+
677
+ Attributes:
678
+ name: Column name as spelled in the catalog.
679
+ data_type: Lower-case catalog data type name.
680
+ is_primary: Whether the column is part of the primary key.
681
+ is_identity: Whether the column is an identity column.
682
+ identity_always: Whether the catalog reports the identity as ``GENERATED ALWAYS``.
683
+ sequence_name: Sequence owned by or defaulted on the column.
684
+ is_generated: Whether the column is a computed column that never accepts values.
685
+ identity_on_null: Whether the catalog reports the identity as ``GENERATED BY DEFAULT ON NULL``.
686
+ """
687
+
688
+ name: str
689
+ data_type: str
690
+ is_primary: bool
691
+ is_identity: bool
692
+ identity_always: bool
693
+ sequence_name: "str | None"
694
+ is_generated: bool
695
+ identity_on_null: bool = False
696
+
697
+
698
+ class _ResyncStep(NamedTuple):
699
+ """Planned SQL step for resynchronizing a table sequence, identity column, or auto-increment counter.
700
+
701
+ Attributes:
702
+ statement: SQL statement or DDL template containing ``{next_val}`` when ``max_query`` is set.
703
+ parameters: Bind parameters for direct statement execution.
704
+ max_query: Optional ``SELECT`` query returning the next or maximum value to format into ``statement``.
705
+ default_next: Fallback integer value when ``max_query`` returns ``None`` or ``0``.
706
+ skip_when_zero: Whether to skip executing ``statement`` when the resolved integer value is ``<= 0``.
707
+ ignore_missing_sqlite_sequence: Whether to suppress ``no such table: sqlite_sequence`` errors.
708
+ """
709
+
710
+ statement: str
711
+ parameters: "dict[str, Any]"
712
+ max_query: "str | None" = None
713
+ default_next: int = 1
714
+ skip_when_zero: bool = False
715
+ ignore_missing_sqlite_sequence: bool = False
716
+
717
+
718
+ def _sqlglot_dialect(dialect: "DialectType", family: str) -> "DialectType":
719
+ """Return a SQLGlot-compatible dialect string or object for the driver family.
720
+
721
+ SQLGlot does not recognize dialect aliases such as cockroach, cockroachdb,
722
+ postgresql, mariadb, or mssql, so dialect families are mapped to standard
723
+ SQLGlot identifiers.
724
+ """
725
+ if family == "teradata":
726
+ importlib.import_module("sqlspec.dialects.teradata")
727
+ return "vantage"
728
+ if family in {"postgres", "mysql", "tsql"}:
729
+ return family
730
+ if family in {"sybase", "sqlanywhere"} and family not in Dialect.classes:
731
+ importlib.import_module("sqlspec.dialects.sybase")
732
+ return dialect
733
+
734
+
735
+ def _postgres_vector_kind(data_type: str) -> "str | None":
736
+ """Return the vector kind if the PostgreSQL column is a pgvector type."""
737
+ base = data_type.partition("(")[0].strip().lower()
738
+ if base in {"vector", "halfvec", "sparsevec"}:
739
+ return base
740
+ return None
741
+
742
+
743
+ def _mysql_vector_kind(data_type: str) -> "str | None":
744
+ """Return the vector kind if the MySQL column is a vector type."""
745
+ base = data_type.partition("(")[0].strip().lower()
746
+ if base == "vector":
747
+ return "vector"
748
+ return None
749
+
750
+
751
+ def _is_vector_column(data_type: str) -> bool:
752
+ """Return whether a column data type represents a vector."""
753
+ normalized = data_type.lower().strip()
754
+ base = normalized.partition("(")[0].partition("[")[0].strip()
755
+ if base in {"vector", "halfvec", "sparsevec", "f32_blob", "float32_blob"}:
756
+ return True
757
+ if base in {"float", "double"} and "[" in normalized:
758
+ return True
759
+ return normalized.startswith(("array<float32>", "array<float64>"))
760
+
761
+
762
+ def _truthy_metadata_flag(value: Any) -> bool:
763
+ """Interpret a catalog flag value (bool, number, or yes/true/1 text) as a boolean."""
764
+ if isinstance(value, bool):
765
+ return value
766
+ if isinstance(value, (int, float)):
767
+ return value != 0
768
+ if isinstance(value, str):
769
+ return value.strip().lower() in {"1", "true", "t", "yes", "y", "always"}
770
+ return bool(value)
771
+
772
+
773
+ def _read_text_sync(path: "Path") -> str:
774
+ return path.read_text(encoding="utf-8")
775
+
776
+
777
+ def _resolve_path_str(path: str) -> str:
778
+ return str(Path(path).resolve())
779
+
780
+
781
+ def _compress_text(content: str) -> bytes:
782
+ return gzip.compress(content.encode("utf-8"))
783
+
784
+
785
+ def _read_zip_member(zf: zipfile.ZipFile, member_name: str) -> str:
786
+ """Read and decode a single JSON member from a ZIP archive with size bounds checking."""
787
+ info = zf.getinfo(member_name)
788
+ if info.file_size > _MAX_ZIP_FIXTURE_BYTES:
789
+ msg = f"ZIP fixture member {member_name!r} exceeds maximum allowed size ({_MAX_ZIP_FIXTURE_BYTES} bytes)"
790
+ raise ValueError(msg)
791
+ with zf.open(member_name) as member_file:
792
+ data = member_file.read(_MAX_ZIP_FIXTURE_BYTES + 1)
793
+ if len(data) > _MAX_ZIP_FIXTURE_BYTES:
794
+ msg = f"ZIP fixture member {member_name!r} exceeds maximum allowed size ({_MAX_ZIP_FIXTURE_BYTES} bytes)"
795
+ raise ValueError(msg)
796
+ return data.decode("utf-8")
797
+
798
+
799
+ def _read_compressed_file(file_path: Path) -> str:
800
+ """Read and decompress a file based on its extension.
801
+
802
+ Args:
803
+ file_path: Path to the file to read
804
+
805
+ Returns:
806
+ The decompressed file content as a string
807
+
808
+ Raises:
809
+ ValueError: If the file format is not supported
810
+ """
811
+ if file_path.suffix == ".gz":
812
+ with gzip.open(file_path, mode="rb") as f:
813
+ data = f.read(_MAX_ZIP_FIXTURE_BYTES + 1)
814
+ if len(data) > _MAX_ZIP_FIXTURE_BYTES:
815
+ msg = f"Gzip fixture {file_path.name!r} exceeds maximum allowed size ({_MAX_ZIP_FIXTURE_BYTES} bytes)"
816
+ raise ValueError(msg)
817
+ return data.decode("utf-8")
818
+ if file_path.suffix == ".zip":
819
+ with zipfile.ZipFile(file_path, "r") as zf:
820
+ json_name = file_path.stem + ".json"
821
+ if json_name in zf.namelist():
822
+ return _read_zip_member(zf, json_name)
823
+ json_files = [name for name in zf.namelist() if name.endswith(".json")]
824
+ if json_files:
825
+ return _read_zip_member(zf, json_files[0])
826
+ msg = f"No JSON file found in ZIP archive: {file_path}"
827
+ raise ValueError(msg)
828
+ msg = f"Unsupported compression format: {file_path.suffix}"
829
+ raise ValueError(msg)
830
+
831
+
832
+ def _find_fixture_file(fixtures_path: Any, fixture_name: str) -> Path:
833
+ """Find a fixture file with various extensions.
834
+
835
+ Args:
836
+ fixtures_path: The path to look for fixtures
837
+ fixture_name: The fixture name to load
838
+
839
+ Returns:
840
+ Path to the found fixture file
841
+
842
+ Raises:
843
+ FileNotFoundError: If no fixture file is found
844
+ ValueError: If fixture_name contains path traversal segments
845
+ """
846
+ validated_name = _validated_fixture_name(fixture_name)
847
+ base_path = Path(fixtures_path).resolve()
848
+
849
+ for extension in [".json", ".json.gz", ".json.zip"]:
850
+ fixture_path = (base_path / f"{validated_name}{extension}").resolve()
851
+ if not fixture_path.is_relative_to(base_path):
852
+ msg = f"Invalid fixture name: {fixture_name!r}"
853
+ raise ValueError(msg)
854
+ if fixture_path.exists():
855
+ return fixture_path
856
+
857
+ msg = f"Could not find the {fixture_name} fixture"
858
+ raise FileNotFoundError(msg)
859
+
860
+
861
+ def _serialize_data(data: Any) -> str:
862
+ """Serialize data to JSON string, handling different input types.
863
+
864
+ Args:
865
+ data: Data to serialize. Can be dict, list, or SQLSpec model types
866
+
867
+ Returns:
868
+ JSON string representation of the data
869
+ """
870
+ if isinstance(data, (list, tuple)):
871
+ serialized_items: list[Any] = []
872
+
873
+ for item in data:
874
+ if isinstance(item, (str, int, float, bool, type(None))):
875
+ serialized_items.append(item)
876
+ else:
877
+ serialized_items.append(schema_dump(item))
878
+
879
+ return to_json(serialized_items)
880
+ if isinstance(data, (str, int, float, bool, type(None))):
881
+ return to_json(data)
882
+
883
+ return to_json(schema_dump(data))
884
+
885
+
886
+ def _validated_fixture_name(name: str) -> str:
887
+ """Return the fixture name when it is a safe single-segment file stem.
888
+
889
+ Raises:
890
+ ValueError: If the name is empty or contains path separators or traversal segments.
891
+ """
892
+ candidate = Path(name)
893
+ if (
894
+ not name
895
+ or candidate.is_absolute()
896
+ or len(candidate.parts) != 1
897
+ or name in {".", ".."}
898
+ or "/" in name
899
+ or "\\" in name
900
+ ):
901
+ msg = f"Invalid fixture name: {name!r}"
902
+ raise ValueError(msg)
903
+ return name
904
+
905
+
906
+ def _validated_table_name(name: str) -> str:
907
+ """Return the table name when it is a plain or schema-qualified SQL identifier.
908
+
909
+ Raises:
910
+ ValueError: If the name is not a safe identifier.
911
+ """
912
+ if not _TABLE_NAME_PATTERN.fullmatch(name):
913
+ msg = f"Invalid table name for table fixtures: {name!r}"
914
+ raise ValueError(msg)
915
+ return name
916
+
917
+
918
+ def _validated_column_name(name: str) -> str:
919
+ """Return the column name when it is a plain SQL identifier.
920
+
921
+ Raises:
922
+ ValueError: If the name is not a safe identifier.
923
+ """
924
+ if not _COLUMN_NAME_PATTERN.fullmatch(name):
925
+ msg = f"Invalid column name for table fixtures: {name!r}"
926
+ raise ValueError(msg)
927
+ return name
928
+
929
+
930
+ def _dialect_name(dialect: "DialectType") -> str:
931
+ """Return the lower-case name of a dialect, or an empty string when unset."""
932
+ if dialect is None:
933
+ return ""
934
+ if isinstance(dialect, str):
935
+ return dialect.lower()
936
+ if isinstance(dialect, type):
937
+ return dialect.__name__.lower()
938
+ return type(dialect).__name__.lower()
939
+
940
+
941
+ def _dialect_family(dialect_name: str) -> str:
942
+ """Return canonical dialect family for a dialect name."""
943
+ if dialect_name in _POSTGRES_DIALECTS:
944
+ return "postgres"
945
+ if dialect_name in _MYSQL_DIALECTS:
946
+ return "mysql"
947
+ if dialect_name in {"teradata", "vantage"}:
948
+ return "teradata"
949
+ if dialect_name == "ase":
950
+ return "sybase"
951
+ if dialect_name == "sa":
952
+ return "sqlanywhere"
953
+ return dialect_name
954
+
955
+
956
+ def _normalize_column_sequence(columns: "Sequence[str] | str", parameter_name: str) -> "tuple[str, ...]":
957
+ """Normalize a single column name or sequence of column names to a validated non-empty tuple."""
958
+ if isinstance(columns, (bytes, bytearray)):
959
+ msg = f"{parameter_name} must be a column name or sequence of column names, not bytes"
960
+ raise TypeError(msg)
961
+ items = (columns,) if isinstance(columns, str) else tuple(columns)
962
+ if not items:
963
+ msg = f"{parameter_name} must not be empty"
964
+ raise ValueError(msg)
965
+ return tuple(_validated_column_name(item) for item in items)
966
+
967
+
968
+ def _validate_load_arguments(
969
+ conflict_keys: "Mapping[str, Sequence[str] | str] | None",
970
+ batch_size: int,
971
+ dialect_name: str,
972
+ family: str,
973
+ exclude_update_columns: "Sequence[str] | Mapping[str, Sequence[str] | str] | None" = None,
974
+ ) -> None:
975
+ """Validate the batch size, conflict keys, and excluded update columns of a table fixture load.
976
+
977
+ Raises:
978
+ ValueError: If ``batch_size`` is below 1, conflict keys are unsupported for the
979
+ dialect, or a table or column name is unsafe or empty.
980
+ TypeError: If ``conflict_keys`` or ``exclude_update_columns`` has an invalid type.
981
+ """
982
+ if batch_size < 1:
983
+ msg = f"batch_size must be at least 1, got {batch_size}"
984
+ raise ValueError(msg)
985
+ if exclude_update_columns is not None:
986
+ if isinstance(exclude_update_columns, (str, bytes, bytearray)):
987
+ msg = (
988
+ "exclude_update_columns must be a sequence of column names or a mapping of table names to column names"
989
+ )
990
+ raise TypeError(msg)
991
+ if isinstance(exclude_update_columns, Mapping):
992
+ for table, cols in exclude_update_columns.items():
993
+ _validated_table_name(table)
994
+ if cols or isinstance(cols, (str, bytes, bytearray)):
995
+ _normalize_column_sequence(cols, f"exclude_update_columns[{table!r}]")
996
+ else:
997
+ for column in exclude_update_columns:
998
+ if not isinstance(column, str):
999
+ msg = "exclude_update_columns items must be column name strings"
1000
+ raise TypeError(msg)
1001
+ _validated_column_name(column)
1002
+ if not conflict_keys:
1003
+ return
1004
+ if family not in _ON_CONFLICT_FAMILIES and family != "mysql":
1005
+ msg = (
1006
+ f"conflict_keys is not supported for dialect {dialect_name!r}; "
1007
+ "supported dialects are PostgreSQL-family, SQLite, DuckDB, and MySQL"
1008
+ )
1009
+ raise ValueError(msg)
1010
+ for table, keys in conflict_keys.items():
1011
+ _validated_table_name(table)
1012
+ _normalize_column_sequence(keys, f"conflict_keys[{table!r}]")
1013
+
1014
+
1015
+ def _conflict_keys_for(conflict_keys: "Mapping[str, Sequence[str] | str] | None", table: str) -> "tuple[str, ...]":
1016
+ """Return the conflict key columns configured for a table."""
1017
+ if not conflict_keys or table not in conflict_keys:
1018
+ return ()
1019
+ return _normalize_column_sequence(conflict_keys[table], f"conflict_keys[{table!r}]")
1020
+
1021
+
1022
+ def _excluded_update_columns_for(
1023
+ exclude_update_columns: "Sequence[str] | Mapping[str, Sequence[str] | str] | None", table: str
1024
+ ) -> "set[str]":
1025
+ """Return the column names excluded from upsert updates for a table."""
1026
+ if not exclude_update_columns:
1027
+ return set()
1028
+ if isinstance(exclude_update_columns, Mapping):
1029
+ raw = exclude_update_columns.get(table)
1030
+ if not raw:
1031
+ return set()
1032
+ return set(_normalize_column_sequence(raw, f"exclude_update_columns[{table!r}]"))
1033
+ return set(exclude_update_columns)
1034
+
1035
+
1036
+ def _parse_table_fixture_filename(file_name: str) -> "tuple[str, int | None, str] | None":
1037
+ """Parse a table fixture file name into (table, shard_index, extension).
1038
+
1039
+ Returns ``None`` if the file does not have a recognized table fixture extension.
1040
+ For sharded files like ``users.001.jsonl.gz``, returns ``("users", 1, ".jsonl.gz")``.
1041
+ For unsharded files like ``users.jsonl.gz``, returns ``("users", None, ".jsonl.gz")``.
1042
+ """
1043
+ for extension in _TABLE_FIXTURE_EXTENSIONS:
1044
+ if file_name.endswith(extension):
1045
+ stem = file_name[: -len(extension)]
1046
+ match = _SHARD_STEM_PATTERN.fullmatch(stem)
1047
+ if match is not None:
1048
+ table, digits = match.groups()
1049
+ return table, int(digits), extension
1050
+ return stem, None, extension
1051
+ return None
1052
+
1053
+
1054
+ def _resolve_table_fixture_paths(table: str, entries: "list[tuple[int | None, str, Path]]") -> "tuple[Path, ...]":
1055
+ """Validate and return ordered fixture file paths for a table.
1056
+
1057
+ Raises:
1058
+ FileNotFoundError: If no fixture files exist for the table.
1059
+ ValueError: If unsharded and sharded files are mixed, multiple unsharded files exist,
1060
+ extensions differ across shards, or duplicate shard indices are present.
1061
+ """
1062
+ if not entries:
1063
+ msg = f"Could not find the {table} fixture"
1064
+ raise FileNotFoundError(msg)
1065
+ unsharded = [entry for entry in entries if entry[0] is None]
1066
+ sharded = [entry for entry in entries if entry[0] is not None]
1067
+ if unsharded and sharded:
1068
+ names = ", ".join(path.name for _, _, path in entries)
1069
+ msg = f"Table {table!r} has both unsharded and sharded fixture files: {names}"
1070
+ raise ValueError(msg)
1071
+ if unsharded:
1072
+ if len(unsharded) > 1:
1073
+ names = ", ".join(path.name for _, _, path in unsharded)
1074
+ msg = f"Table {table!r} has more than one fixture file: {names}"
1075
+ raise ValueError(msg)
1076
+ return (unsharded[0][2],)
1077
+ extensions = {ext for _, ext, _ in sharded}
1078
+ if len(extensions) > 1:
1079
+ names = ", ".join(path.name for _, _, path in sharded)
1080
+ msg = f"Table {table!r} has mixed fixture extensions across shards: {names}"
1081
+ raise ValueError(msg)
1082
+ seen_indices: set[int] = set()
1083
+ for idx, _, _path in sharded:
1084
+ if idx is not None and idx in seen_indices:
1085
+ names = ", ".join(p.name for _, _, p in sharded)
1086
+ msg = f"Table {table!r} has duplicate shard index {idx}: {names}"
1087
+ raise ValueError(msg)
1088
+ if idx is not None:
1089
+ seen_indices.add(idx)
1090
+ sorted_shards = sorted(sharded, key=lambda item: item[0] or 0)
1091
+ return tuple(path for _, _, path in sorted_shards)
1092
+
1093
+
1094
+ def _discover_table_files(fixtures_path: "str | Path") -> "dict[str, tuple[Path, ...]]":
1095
+ """Map each table with fixture files in the directory to its ordered file paths.
1096
+
1097
+ Raises:
1098
+ ValueError: If a table has both unsharded and sharded fixture files, mixed
1099
+ extensions across shards, or duplicate shard indices.
1100
+ """
1101
+ table_entries: dict[str, list[tuple[int | None, str, Path]]] = {}
1102
+ for entry in sorted(Path(fixtures_path).iterdir()):
1103
+ if not entry.is_file():
1104
+ continue
1105
+ parsed = _parse_table_fixture_filename(entry.name)
1106
+ if parsed is None:
1107
+ continue
1108
+ table, shard_idx, ext = parsed
1109
+ if not _TABLE_NAME_PATTERN.fullmatch(table):
1110
+ logger.debug("Skipping table fixture file %s: %r is not a table identifier", entry.name, table)
1111
+ continue
1112
+ if "." in table:
1113
+ logger.debug("Table fixture file %s names schema-qualified table %r", entry.name, table)
1114
+ table_entries.setdefault(table, []).append((shard_idx, ext, entry))
1115
+ return {table: _resolve_table_fixture_paths(table, entries) for table, entries in table_entries.items()}
1116
+
1117
+
1118
+ def _ordered_table_files(
1119
+ fixtures_path: "str | Path", tables: "Sequence[str] | None", table_order: "Sequence[str] | None"
1120
+ ) -> "list[tuple[str, tuple[Path, ...]]]":
1121
+ """Resolve the tables to load and their fixture files in load order.
1122
+
1123
+ Raises:
1124
+ ValueError: If a table name is not a safe identifier or a table has invalid fixture files.
1125
+ FileNotFoundError: If a requested table has no fixture file.
1126
+ """
1127
+ if tables is None:
1128
+ table_files = _discover_table_files(fixtures_path)
1129
+ else:
1130
+ for table in tables:
1131
+ _validated_table_name(table)
1132
+ all_files = _discover_table_files(fixtures_path)
1133
+ table_files = {}
1134
+ for table in tables:
1135
+ if table not in all_files:
1136
+ msg = f"Could not find the {table} fixture"
1137
+ raise FileNotFoundError(msg)
1138
+ table_files[table] = all_files[table]
1139
+ ordered = [table for table in dict.fromkeys(table_order or ()) if table in table_files]
1140
+ listed = set(ordered)
1141
+ ordered.extend(sorted(table for table in table_files if table not in listed))
1142
+ return [(table, table_files[table]) for table in ordered]
1143
+
1144
+
1145
+ def _read_table_fixture_text(file_path: Path) -> str:
1146
+ """Read a table fixture file, decompressing gzipped files."""
1147
+ if file_path.suffix == ".gz":
1148
+ return _read_compressed_file(file_path)
1149
+ return file_path.read_text(encoding="utf-8")
1150
+
1151
+
1152
+ def _table_fixture_rows(file_path: Path, content: str) -> "list[dict[str, Any]]":
1153
+ """Decode the row objects of a table fixture file and normalize sparse columns.
1154
+
1155
+ Raises:
1156
+ TypeError: If the content is not a list of row objects.
1157
+ ValueError: If any row is empty or has an unsafe column name.
1158
+ """
1159
+ decoded: Any
1160
+ if file_path.name.endswith((".jsonl", ".jsonl.gz")):
1161
+ decoded = [from_json(line) for line in content.splitlines() if line.strip()]
1162
+ else:
1163
+ decoded = from_json(content)
1164
+ if not isinstance(decoded, list):
1165
+ msg = f"Table fixture {file_path} must contain a JSON array of row objects"
1166
+ raise TypeError(msg)
1167
+ raw_rows: list[dict[str, Any]] = []
1168
+ ordered_columns: list[str] = []
1169
+ seen_columns: set[str] = set()
1170
+ for index, row in enumerate(decoded):
1171
+ if not isinstance(row, dict):
1172
+ msg = f"Row {index} in table fixture {file_path} must be an object"
1173
+ raise TypeError(msg)
1174
+ if not row:
1175
+ msg = f"Row {index} in table fixture {file_path} must have at least one column"
1176
+ raise ValueError(msg)
1177
+ for column in row:
1178
+ if column not in seen_columns:
1179
+ _validated_column_name(column)
1180
+ seen_columns.add(column)
1181
+ ordered_columns.append(column)
1182
+ raw_rows.append(row)
1183
+ return [{column: raw_row.get(column) for column in ordered_columns} for raw_row in raw_rows]
1184
+
1185
+
1186
+ def _quoted_identifier(name: str) -> exp.Identifier:
1187
+ """Return a quoted identifier expression for a name."""
1188
+ return exp.to_identifier(name, quoted=True)
1189
+
1190
+
1191
+ def _quoted_identifier_sql(name: str) -> str:
1192
+ """Return the name as double-quoted SQL identifier text."""
1193
+ escaped = name.replace('"', '""')
1194
+ return f'"{escaped}"'
1195
+
1196
+
1197
+ def _quoted_table_name(table: str) -> str:
1198
+ """Return a validated plain or schema-qualified table name with each part double-quoted."""
1199
+ return ".".join(_quoted_identifier_sql(part) for part in table.split("."))
1200
+
1201
+
1202
+ def _quoted_table(table: str) -> exp.Table:
1203
+ """Return a table expression with each part of a plain or schema-qualified name quoted."""
1204
+ schema_name, _, table_name = table.rpartition(".")
1205
+ return exp.Table(this=_quoted_identifier(table_name), db=_quoted_identifier(schema_name) if schema_name else None)
1206
+
1207
+
1208
+ def _validated_sequence_identifier(name: str) -> str:
1209
+ """Return a plain or schema-qualified sequence identifier stripped of dialect quotes.
1210
+
1211
+ Raises:
1212
+ ValueError: If the sequence name is not a safe SQL identifier.
1213
+ """
1214
+ cleaned = ".".join(part.strip('`"[] ') for part in name.strip().split("."))
1215
+ if not _SEQUENCE_IDENTIFIER_PATTERN.fullmatch(cleaned):
1216
+ msg = f"Invalid sequence name for table fixtures: {name!r}"
1217
+ raise ValueError(msg)
1218
+ return cleaned
1219
+
1220
+
1221
+ def _extract_sequence_from_default(column_default: Any) -> "str | None":
1222
+ """Extract a backing sequence name from a column ``DEFAULT`` expression if present.
1223
+
1224
+ Recognizes ``nextval('seq'::regclass)`` / ``nextval('seq')`` / ``nextval(`seq`)``
1225
+ (PostgreSQL, CockroachDB, DuckDB, MariaDB), ``NEXT VALUE FOR seq`` / ``NEXTVAL FOR seq``
1226
+ (SQL Server, IBM Db2, MariaDB), and ``seq.NEXTVAL`` (Oracle).
1227
+ """
1228
+ if not isinstance(column_default, str) or not column_default.strip():
1229
+ return None
1230
+ text = column_default.strip()
1231
+ nextval_match = _NEXTVAL_CALL_PATTERN.search(text)
1232
+ if nextval_match is not None:
1233
+ single_quoted, identifier_expr = nextval_match.groups()
1234
+ if single_quoted is not None:
1235
+ cleaned_single = single_quoted.split("::", 1)[0].strip()
1236
+ cleaned = ".".join(part.strip('`"[] ') for part in cleaned_single.split("."))
1237
+ if _SEQUENCE_IDENTIFIER_PATTERN.fullmatch(cleaned):
1238
+ return cleaned
1239
+ return None
1240
+ if identifier_expr is not None:
1241
+ cleaned = ".".join(part.strip("` ") for part in identifier_expr.split("."))
1242
+ if _SEQUENCE_IDENTIFIER_PATTERN.fullmatch(cleaned):
1243
+ return cleaned
1244
+ next_value_for_match = _NEXT_VALUE_FOR_PATTERN.search(text)
1245
+ if next_value_for_match is not None:
1246
+ raw_seq = next_value_for_match.group(1)
1247
+ cleaned = ".".join(part.strip('`"[] ') for part in raw_seq.split("."))
1248
+ if _SEQUENCE_IDENTIFIER_PATTERN.fullmatch(cleaned):
1249
+ return cleaned
1250
+ oracle_match = _ORACLE_NEXTVAL_PATTERN.match(text)
1251
+ if oracle_match is not None:
1252
+ raw_seq = oracle_match.group(1)
1253
+ cleaned = ".".join(part.strip('" ') for part in raw_seq.split("."))
1254
+ if _SEQUENCE_IDENTIFIER_PATTERN.fullmatch(cleaned):
1255
+ return cleaned
1256
+ return None
1257
+
1258
+
1259
+ def _table_column(row: "Mapping[str, Any]") -> _TableColumn:
1260
+ """Return column metadata from a data dictionary column row.
1261
+
1262
+ Identity columns are recognized from canonical ``is_identity`` (boolean, numeric,
1263
+ or truthy string flag), ``identity_generation`` (such as ``ALWAYS``, ``BY DEFAULT``,
1264
+ or ``BY DEFAULT ON NULL``), or ``auto_increment`` in ``extra`` (MySQL, MariaDB).
1265
+ Standalone sequence defaults are recognized from ``sequence_name`` or parsed from
1266
+ ``column_default``. An identity column is never treated as generated, because Db2
1267
+ also flags identity columns in ``is_generated``.
1268
+ """
1269
+ sequence_name = row.get("sequence_name")
1270
+ if sequence_name is None:
1271
+ sequence_name = _extract_sequence_from_default(row.get("column_default"))
1272
+ identity_generation = str(row.get("identity_generation") or "").strip().lower()
1273
+ extra = str(row.get("extra") or "").lower()
1274
+ is_identity = (
1275
+ identity_generation in _IDENTITY_GENERATION_VALUES
1276
+ or _truthy_metadata_flag(row.get("is_identity"))
1277
+ or "auto_increment" in extra
1278
+ )
1279
+ identity_always = identity_generation in _ALWAYS_IDENTITY_GENERATION_VALUES
1280
+ identity_on_null = identity_generation == "by default on null"
1281
+ return _TableColumn(
1282
+ name=str(row["column_name"]),
1283
+ data_type=str(row.get("data_type") or "").lower(),
1284
+ is_primary=_truthy_metadata_flag(row.get("is_primary")),
1285
+ is_identity=is_identity,
1286
+ identity_always=identity_always,
1287
+ sequence_name=None if sequence_name is None else str(sequence_name),
1288
+ is_generated=not is_identity and _is_generated_column(row),
1289
+ identity_on_null=identity_on_null,
1290
+ )
1291
+
1292
+
1293
+ def _is_generated_column(row: "Mapping[str, Any]") -> bool:
1294
+ """Return whether a data dictionary column row describes a generated (computed) column.
1295
+
1296
+ Recognized from canonical ``is_generated`` or ``generation_expression`` metadata,
1297
+ or dialect-specific ``extra`` flags containing the word ``generated``.
1298
+ """
1299
+ if _truthy_metadata_flag(row.get("is_generated")) or bool(row.get("generation_expression")):
1300
+ return True
1301
+ return "generated" in str(row.get("extra") or "").lower().split()
1302
+
1303
+
1304
+ def _column_lookup_names(family: str, table: str) -> "tuple[str, str | None]":
1305
+ """Return the table and schema names to pass to the data dictionary for an exact-case table."""
1306
+ schema_name, _, table_name = table.rpartition(".")
1307
+ if family == "postgres":
1308
+ return _quoted_identifier_sql(table_name), _quoted_identifier_sql(schema_name) if schema_name else None
1309
+ return table_name, schema_name or None
1310
+
1311
+
1312
+ def _table_columns_sync(driver: "SyncDriverAdapterBase", family: str, table: str) -> "list[_TableColumn]":
1313
+ """Read the column metadata of a table from the driver's data dictionary.
1314
+
1315
+ An unqualified PostgreSQL-family table with no rows is looked up again in
1316
+ ``current_schema()``, because the data dictionary resolves unqualified names
1317
+ through the search path.
1318
+ """
1319
+ table_name, schema_name = _column_lookup_names(family, table)
1320
+ rows = driver.data_dictionary.get_columns(driver, table=table_name, schema=schema_name)
1321
+ if not rows and family == "postgres" and schema_name is None:
1322
+ active_schema = driver.select_value_or_none("SELECT current_schema()")
1323
+ if active_schema:
1324
+ rows = driver.data_dictionary.get_columns(
1325
+ driver, table=table_name, schema=_quoted_identifier_sql(str(active_schema))
1326
+ )
1327
+ return [_table_column(row) for row in rows]
1328
+
1329
+
1330
+ async def _table_columns_async(driver: "AsyncDriverAdapterBase", family: str, table: str) -> "list[_TableColumn]":
1331
+ """Read the column metadata of a table from the driver's data dictionary.
1332
+
1333
+ An unqualified PostgreSQL-family table with no rows is looked up again in
1334
+ ``current_schema()``, because the data dictionary resolves unqualified names
1335
+ through the search path.
1336
+ """
1337
+ table_name, schema_name = _column_lookup_names(family, table)
1338
+ rows = await driver.data_dictionary.get_columns(driver, table=table_name, schema=schema_name)
1339
+ if not rows and family == "postgres" and schema_name is None:
1340
+ active_schema = await driver.select_value_or_none("SELECT current_schema()")
1341
+ if active_schema:
1342
+ rows = await driver.data_dictionary.get_columns(
1343
+ driver, table=table_name, schema=_quoted_identifier_sql(str(active_schema))
1344
+ )
1345
+ return [_table_column(row) for row in rows]
1346
+
1347
+
1348
+ def _generated_column_names(columns: "list[_TableColumn]") -> "set[str]":
1349
+ """Return the names of the generated columns of a table."""
1350
+ return {column.name for column in columns if column.is_generated}
1351
+
1352
+
1353
+ def _drop_generated_values(
1354
+ rows: "list[dict[str, Any]]", columns: "list[_TableColumn]", *, ignore_unknown_columns: bool = False
1355
+ ) -> None:
1356
+ """Remove generated columns and optionally unknown columns from fixture rows in place.
1357
+
1358
+ Raises:
1359
+ ValueError: If only generated columns remain in the rows.
1360
+ """
1361
+ if not rows or not columns:
1362
+ return
1363
+ generated = _generated_column_names(columns)
1364
+ unknown: set[str] = set()
1365
+ if ignore_unknown_columns:
1366
+ known = {column.name for column in columns}
1367
+ unknown = set(rows[0]) - known
1368
+ to_drop = (generated & set(rows[0])) | unknown
1369
+ if not to_drop:
1370
+ return
1371
+ for row in rows:
1372
+ for name in to_drop:
1373
+ row.pop(name, None)
1374
+ if not rows[0]:
1375
+ if unknown:
1376
+ rows.clear()
1377
+ return
1378
+ msg = f"Table fixture rows only contain generated columns: {sorted(generated)}"
1379
+ raise ValueError(msg)
1380
+
1381
+
1382
+ def _decode_exported_json_value(value: Any) -> Any:
1383
+ """Decode a JSON string returned by a driver on a JSON/JSONB column, falling back to the raw string."""
1384
+ if not isinstance(value, str):
1385
+ return value
1386
+ try:
1387
+ return from_json(value)
1388
+ except (ValueError, TypeError):
1389
+ return value
1390
+
1391
+
1392
+ def _vector_items(value: Any) -> "list[float] | None":
1393
+ """Extract a list of floats from a sequence, array, vector object, or bracketed/sparse string."""
1394
+ if isinstance(value, (list, tuple, array.array)):
1395
+ return [float(x) for x in value]
1396
+ if hasattr(value, "tolist"):
1397
+ return [float(x) for x in value.tolist()]
1398
+ if hasattr(value, "to_list"):
1399
+ return [float(x) for x in value.to_list()]
1400
+ if isinstance(value, str):
1401
+ v = value.strip()
1402
+ if v.startswith("[") and v.endswith("]"):
1403
+ inner = v[1:-1].strip()
1404
+ return [float(x.strip()) for x in inner.split(",") if x.strip()] if inner else []
1405
+ if v.startswith("{") and "/" in v:
1406
+ body, _, dim_str = v.rpartition("/")
1407
+ if body.startswith("{") and body.endswith("}") and dim_str.strip().isdigit():
1408
+ dim = int(dim_str.strip())
1409
+ dense = [0.0] * dim
1410
+ inner = body[1:-1].strip()
1411
+ if inner:
1412
+ for entry in inner.split(","):
1413
+ idx_str, sep, val_str = entry.partition(":")
1414
+ if not sep or not idx_str.strip().isdigit():
1415
+ return None
1416
+ idx = int(idx_str.strip()) - 1
1417
+ if 0 <= idx < dim:
1418
+ dense[idx] = float(val_str.strip())
1419
+ return dense
1420
+ return None
1421
+
1422
+
1423
+ def _decode_exported_vector_value(value: Any, data_type: str, family: str = "") -> Any:
1424
+ """Normalize vector representations to a JSON-serializable list of floats."""
1425
+ if value is None:
1426
+ return None
1427
+ items = _vector_items(value)
1428
+ if items is not None:
1429
+ return items
1430
+ if isinstance(value, (bytes, bytearray, memoryview)):
1431
+ b = bytes(value)
1432
+ if family == "mysql" or "f32" in data_type or "float32" in data_type:
1433
+ n = len(b) // _FLOAT32_BYTES
1434
+ return list(struct.unpack(f"<{n}f", b[: n * _FLOAT32_BYTES]))
1435
+ if len(b) >= _PG_VECTOR_HEADER_BYTES:
1436
+ dim, _ = struct.unpack(">HH", b[:_PG_VECTOR_HEADER_BYTES])
1437
+ if _PG_VECTOR_HEADER_BYTES + dim * _FLOAT32_BYTES == len(b):
1438
+ return list(struct.unpack(f">{dim}f", b[_PG_VECTOR_HEADER_BYTES:]))
1439
+ return value
1440
+
1441
+
1442
+ def _without_generated_values(
1443
+ rows: "list[dict[str, Any]]", columns: "list[_TableColumn]", family: str = ""
1444
+ ) -> "list[dict[str, Any]]":
1445
+ """Return exported rows without generated columns and with string JSON/vector cells normalized."""
1446
+ generated = _generated_column_names(columns)
1447
+ json_columns = {
1448
+ column.name
1449
+ for column in columns
1450
+ if column.data_type in _JSON_TYPE_NAMES
1451
+ or (family == "snowflake" and column.data_type in {"variant", "object", "array"})
1452
+ }
1453
+ vector_columns = {column.name: column.data_type for column in columns if _is_vector_column(column.data_type)}
1454
+ if not generated and not json_columns and not vector_columns:
1455
+ return rows
1456
+ result: list[dict[str, Any]] = []
1457
+ for row in rows:
1458
+ row_dict: dict[str, Any] = {}
1459
+ for key, value in row.items():
1460
+ if key in generated:
1461
+ continue
1462
+ if key in json_columns:
1463
+ row_dict[key] = _decode_exported_json_value(value)
1464
+ elif key in vector_columns:
1465
+ row_dict[key] = _decode_exported_vector_value(value, vector_columns[key], family)
1466
+ else:
1467
+ row_dict[key] = value
1468
+ result.append(row_dict)
1469
+ return result
1470
+
1471
+
1472
+ def _decode_bytes(value: Any) -> Any:
1473
+ """Decode a base64 string to bytes."""
1474
+ return base64.b64decode(value, validate=True) if isinstance(value, str) else value
1475
+
1476
+
1477
+ def _decode_datetime(value: Any) -> Any:
1478
+ """Decode an ISO 8601 string to a datetime."""
1479
+ return convert_iso_datetime(value) if isinstance(value, str) else value
1480
+
1481
+
1482
+ def _decode_date(value: Any) -> Any:
1483
+ """Decode an ISO 8601 string to a date."""
1484
+ return convert_iso_date(value) if isinstance(value, str) else value
1485
+
1486
+
1487
+ def _decode_time(value: Any) -> Any:
1488
+ """Decode an ISO 8601 string to a time."""
1489
+ if not isinstance(value, str):
1490
+ return value
1491
+ return time.fromisoformat(f"{value[:-1]}+00:00" if value.endswith("Z") else value)
1492
+
1493
+
1494
+ def _decode_interval(value: Any) -> Any:
1495
+ """Decode an ISO 8601 duration string or a number of seconds to a timedelta."""
1496
+ if isinstance(value, bool):
1497
+ return value
1498
+ if isinstance(value, (int, float)):
1499
+ return timedelta(seconds=value)
1500
+ if not isinstance(value, str):
1501
+ return value
1502
+ match = _ISO_DURATION_PATTERN.fullmatch(value)
1503
+ if match is None:
1504
+ return value
1505
+ sign, weeks, days, hours, minutes, seconds = match.groups()
1506
+ if not (weeks or days or hours or minutes or seconds):
1507
+ return value
1508
+ whole_seconds, _, fraction = (seconds or "0").partition(".")
1509
+ duration = timedelta(
1510
+ weeks=float(weeks or 0),
1511
+ days=float(days or 0),
1512
+ hours=float(hours or 0),
1513
+ minutes=float(minutes or 0),
1514
+ seconds=int(whole_seconds),
1515
+ microseconds=round(float(f"0.{fraction or 0}") * 1_000_000),
1516
+ )
1517
+ return -duration if sign else duration
1518
+
1519
+
1520
+ def _decode_duckdb_interval(value: Any) -> Any:
1521
+ """Decode a ``[months, days, nanoseconds]`` list to DuckDB interval text and other values to a timedelta."""
1522
+ if (
1523
+ isinstance(value, list)
1524
+ and len(value) == _DUCKDB_INTERVAL_PARTS
1525
+ and all(isinstance(part, int) and not isinstance(part, bool) for part in value)
1526
+ ):
1527
+ months, days, nanoseconds = value
1528
+ return f"{months} months {days} days {nanoseconds // _NANOSECONDS_PER_MICROSECOND} microseconds"
1529
+ return _decode_interval(value)
1530
+
1531
+
1532
+ def _decode_decimal(value: Any) -> Any:
1533
+ """Decode a numeric string or JSON number to a Decimal."""
1534
+ if isinstance(value, str):
1535
+ return Decimal(value)
1536
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
1537
+ return Decimal(str(value))
1538
+ return value
1539
+
1540
+
1541
+ def _decode_uuid(value: Any) -> Any:
1542
+ """Decode a UUID string to a UUID."""
1543
+ return convert_uuid(value) if isinstance(value, str) else value
1544
+
1545
+
1546
+ def _format_sparsevec(items: "Sequence[float]", data_type: str = "") -> str:
1547
+ """Format a dense float sequence as a pgvector ``sparsevec`` literal ``{i:v}/dim``."""
1548
+ dim = len(items)
1549
+ if not dim and "(" in data_type and ")" in data_type:
1550
+ dim_text = data_type.partition("(")[2].partition(")")[0].strip()
1551
+ if dim_text.isdigit():
1552
+ dim = int(dim_text)
1553
+ entries = ",".join(f"{index}:{float(val)}" for index, val in enumerate(items, start=1) if float(val) != 0.0)
1554
+ return f"{{{entries}}}/{dim}"
1555
+
1556
+
1557
+ def _decode_pg_vector(value: Any, data_type: str = "vector") -> Any:
1558
+ """Format vector values as a PostgreSQL/pgvector string literal."""
1559
+ if value is None:
1560
+ return None
1561
+ is_sparse = _postgres_vector_kind(data_type) == "sparsevec"
1562
+ if isinstance(value, str):
1563
+ v = value.strip()
1564
+ if is_sparse and v.startswith("[") and v.endswith("]"):
1565
+ items = _vector_items(v)
1566
+ if items is not None:
1567
+ return _format_sparsevec(items, data_type)
1568
+ return value
1569
+ if hasattr(value, "to_text"):
1570
+ text = str(value.to_text())
1571
+ if is_sparse and text.startswith("{"):
1572
+ return text
1573
+ if not is_sparse and text.startswith("["):
1574
+ return text
1575
+ items = _vector_items(value)
1576
+ if items is not None:
1577
+ if is_sparse:
1578
+ return _format_sparsevec(items, data_type)
1579
+ return f"[{','.join(str(x) for x in items)}]"
1580
+ return str(value)
1581
+
1582
+
1583
+ def _pg_vector_decoder(data_type: str) -> "Callable[[Any], Any]":
1584
+ """Return a decoder formatting vector values for a PostgreSQL pgvector column."""
1585
+ if _postgres_vector_kind(data_type) == "sparsevec":
1586
+
1587
+ def _sparse_converter(value: Any) -> Any:
1588
+ return _decode_pg_vector(value, data_type)
1589
+
1590
+ return _sparse_converter
1591
+ return _decode_pg_vector
1592
+
1593
+
1594
+ def _decode_mysql_vector(value: Any) -> Any:
1595
+ """Format vector values as MySQL string literal."""
1596
+ return _decode_pg_vector(value)
1597
+
1598
+
1599
+ def _decode_oracle_vector(data_type: str) -> "Callable[[Any], Any]":
1600
+ """Return decoder converting vector values to array.array for Oracle."""
1601
+ typecode = "f" if "32" in data_type else "d"
1602
+
1603
+ def _oracle_vector_converter(value: Any) -> Any:
1604
+ if value is None or isinstance(value, array.array):
1605
+ return value
1606
+ if hasattr(value, "indices") and hasattr(value, "values"):
1607
+ return value
1608
+ items = _vector_items(value)
1609
+ return array.array(typecode, items) if items is not None else value
1610
+
1611
+ return _oracle_vector_converter
1612
+
1613
+
1614
+ def _decode_spanner_vector(data_type: str) -> "Callable[[Any], Any]":
1615
+ """Return decoder binding Spanner vector arrays with proper type hints."""
1616
+ is_float32 = "32" in data_type or data_type in {"real[]", "float4[]"}
1617
+
1618
+ def _spanner_vector_converter(value: Any) -> Any:
1619
+ if value is None:
1620
+ return None
1621
+ items = _vector_items(value)
1622
+ if items is None:
1623
+ if isinstance(value, str):
1624
+ items = []
1625
+ else:
1626
+ return value
1627
+ if is_float32:
1628
+ return TypedParameter(items, list, semantic_name="ARRAY<FLOAT32>")
1629
+ return items
1630
+
1631
+ return _spanner_vector_converter
1632
+
1633
+
1634
+ def _decode_sqlite_vector(data_type: str) -> "Callable[[Any], Any]":
1635
+ """Return decoder converting vector values for SQLite."""
1636
+ is_blob = "blob" in data_type or "f32" in data_type
1637
+
1638
+ def _sqlite_vector_converter(value: Any) -> Any:
1639
+ if value is None:
1640
+ return None
1641
+ if isinstance(value, (bytes, bytearray, memoryview)):
1642
+ return bytes(value)
1643
+ items = _vector_items(value)
1644
+ if items is None:
1645
+ return value
1646
+ if is_blob:
1647
+ return struct.pack(f"<{len(items)}f", *items)
1648
+ return to_json(items)
1649
+
1650
+ return _sqlite_vector_converter
1651
+
1652
+
1653
+ def _decode_generic_vector(value: Any) -> Any:
1654
+ """Normalize vector values to a list of floats."""
1655
+ if value is None:
1656
+ return None
1657
+ items = _vector_items(value)
1658
+ return items if items is not None else value
1659
+
1660
+
1661
+ def _column_value_decoder(family: str, data_type: str) -> "Callable[[Any], Any] | None":
1662
+ """Return the converter from a JSON value to the driver value for a column type, if any.
1663
+
1664
+ Oracle ``DATE`` columns store a time of day, so their values decode to datetimes.
1665
+ """
1666
+ normalized_type = data_type.lower()
1667
+ if family == "snowflake" and normalized_type in {"variant", "object", "array"}:
1668
+ return to_json
1669
+ if _is_vector_column(normalized_type):
1670
+ if family == "postgres":
1671
+ return _pg_vector_decoder(normalized_type)
1672
+ if family == "mysql":
1673
+ return _decode_mysql_vector
1674
+ if family == "oracle":
1675
+ return _decode_oracle_vector(normalized_type)
1676
+ if family in {"spanner", "spangres"}:
1677
+ return _decode_spanner_vector(normalized_type)
1678
+ if family == "sqlite":
1679
+ return _decode_sqlite_vector(normalized_type)
1680
+ if family == "duckdb":
1681
+ return _decode_pg_vector
1682
+ return _decode_generic_vector
1683
+ if data_type.endswith("]"):
1684
+ return None
1685
+ if _is_binary_type_info(data_type):
1686
+ return _decode_bytes
1687
+ if data_type in _JSON_TYPE_NAMES:
1688
+ return to_json if family in _JSON_VALUE_FAMILIES else None
1689
+ if family == "sqlite":
1690
+ return None
1691
+ if data_type.startswith(("timestamp", "datetime", "bigdatetime", "smalldatetime", "datetimetz")):
1692
+ return _decode_datetime
1693
+ if data_type == "date":
1694
+ return _decode_datetime if family == "oracle" else _decode_date
1695
+ if data_type.startswith(("time", "bigtime")) and family != "mysql":
1696
+ return _decode_time
1697
+ if data_type.startswith("interval"):
1698
+ return _decode_duckdb_interval if family == "duckdb" else _decode_interval
1699
+ if data_type.startswith(("numeric", "decimal", "money", "smallmoney")):
1700
+ return _decode_decimal
1701
+ if data_type in {"uuid", "uniqueidentifier"}:
1702
+ return _decode_uuid
1703
+ return None
1704
+
1705
+
1706
+ def _decode_row_values(rows: "list[dict[str, Any]]", family: str, columns: "list[_TableColumn]") -> None:
1707
+ """Convert the JSON values of typed columns in place."""
1708
+ decoders: list[tuple[str, Callable[[Any], Any]]] = []
1709
+ for column in columns:
1710
+ decoder = _column_value_decoder(family, column.data_type)
1711
+ if decoder is not None:
1712
+ decoders.append((column.name, decoder))
1713
+ if not decoders:
1714
+ return
1715
+ for row in rows:
1716
+ for name, decoder in decoders:
1717
+ value = row.get(name)
1718
+ if value is not None:
1719
+ row[name] = decoder(value)
1720
+
1721
+
1722
+ def _conflict_clause(
1723
+ family: str,
1724
+ columns: "list[str]",
1725
+ conflict_keys: "tuple[str, ...]",
1726
+ always_identity: "set[str]",
1727
+ excluded_updates: "set[str] | None" = None,
1728
+ ) -> exp.OnConflict:
1729
+ """Return the upsert clause that updates non-key, non-identity, non-excluded columns on a key conflict."""
1730
+ excluded = excluded_updates or set()
1731
+ updates = [
1732
+ column
1733
+ for column in columns
1734
+ if column not in conflict_keys and column not in always_identity and column not in excluded
1735
+ ]
1736
+ if family == "mysql":
1737
+ assignments = [
1738
+ exp.EQ(
1739
+ this=exp.column(_quoted_identifier(column), copy=False),
1740
+ expression=exp.Anonymous(
1741
+ this="VALUES", expressions=[exp.column(_quoted_identifier(column), copy=False)]
1742
+ ),
1743
+ )
1744
+ for column in updates or list(conflict_keys)
1745
+ ]
1746
+ return exp.OnConflict(duplicate=True, action=exp.var("UPDATE"), expressions=assignments)
1747
+ keys = [_quoted_identifier(key) for key in conflict_keys]
1748
+ if not updates:
1749
+ return exp.OnConflict(conflict_keys=keys, action=exp.var("DO NOTHING"))
1750
+ assignments = [
1751
+ exp.EQ(
1752
+ this=exp.column(_quoted_identifier(column), copy=False),
1753
+ expression=exp.column(_quoted_identifier(column), table=_quoted_identifier("excluded"), copy=False),
1754
+ )
1755
+ for column in updates
1756
+ ]
1757
+ return exp.OnConflict(conflict_keys=keys, action=exp.var("DO UPDATE"), expressions=assignments)
1758
+
1759
+
1760
+ def _fixture_placeholder_map(columns: "Sequence[str]") -> "dict[str, str]":
1761
+ """Return a collision-free mapping from fixture column names to safe placeholder names."""
1762
+ mapping: dict[str, str] = {}
1763
+ used: set[str] = set()
1764
+ for column in columns:
1765
+ base = sanitize_parameter_name(column)
1766
+ candidate = base
1767
+ suffix = 2
1768
+ while candidate in used:
1769
+ candidate = f"{base}_{suffix}"
1770
+ suffix += 1
1771
+ used.add(candidate)
1772
+ mapping[column] = candidate
1773
+ return mapping
1774
+
1775
+
1776
+ def _table_insert_statement(
1777
+ dialect: "DialectType",
1778
+ family: str,
1779
+ table: str,
1780
+ columns: "list[str]",
1781
+ conflict_keys: "tuple[str, ...]",
1782
+ table_columns: "list[_TableColumn]",
1783
+ excluded_updates: "set[str] | None" = None,
1784
+ placeholder_names: "Mapping[str, str] | None" = None,
1785
+ ) -> str:
1786
+ """Return INSERT SQL text with a named placeholder per quoted column, upserting on conflict keys.
1787
+
1788
+ The statement is rendered directly from the expression in the target dialect so
1789
+ quoted catalog names keep their exact spelling. On PostgreSQL, an insert into
1790
+ ``GENERATED ALWAYS`` identity columns carries ``OVERRIDING SYSTEM VALUE``.
1791
+ """
1792
+ col_map = {col.name: col for col in table_columns}
1793
+ param_map = placeholder_names if placeholder_names is not None else _fixture_placeholder_map(columns)
1794
+ value_expressions: list[exp.Expr] = []
1795
+ for column in columns:
1796
+ col = col_map.get(column)
1797
+ ph = exp.Placeholder(this=param_map[column])
1798
+ if col is not None and family == "snowflake" and col.data_type in {"variant", "object", "array"}:
1799
+ value_expressions.append(exp.Anonymous(this="PARSE_JSON", expressions=[ph]))
1800
+ elif col is not None and family == "postgres" and _postgres_vector_kind(col.data_type):
1801
+ target_type = exp.DataType.build(col.data_type, dialect="postgres", udt=True)
1802
+ cast_text = exp.Cast(this=ph, to=exp.DataType(this=exp.DataType.Type.TEXT))
1803
+ value_expressions.append(exp.Cast(this=cast_text, to=target_type))
1804
+ elif col is not None and family == "postgres" and col.data_type in _JSON_TYPE_NAMES:
1805
+ target_type = exp.DataType.build(col.data_type, dialect="postgres")
1806
+ cast_text = exp.Cast(this=ph, to=exp.DataType(this=exp.DataType.Type.TEXT))
1807
+ value_expressions.append(exp.Cast(this=cast_text, to=target_type))
1808
+ elif col is not None and family == "mysql" and _mysql_vector_kind(col.data_type):
1809
+ dialect_str = _dialect_name(dialect)
1810
+ if dialect_str == "mariadb":
1811
+ value_expressions.append(exp.Anonymous(this="VEC_FromText", expressions=[ph]))
1812
+ else:
1813
+ value_expressions.append(exp.Anonymous(this="STRING_TO_VECTOR", expressions=[ph]))
1814
+ else:
1815
+ value_expressions.append(ph)
1816
+
1817
+ insert_expression = exp.Insert(
1818
+ this=exp.Schema(this=_quoted_table(table), expressions=[_quoted_identifier(column) for column in columns]),
1819
+ expression=exp.Values(expressions=[exp.Tuple(expressions=value_expressions)]),
1820
+ )
1821
+ if family == "snowflake" and any(
1822
+ column.data_type in {"variant", "object", "array"} for column in table_columns if column.name in columns
1823
+ ):
1824
+ insert_expression.set("expression", exp.Select(expressions=value_expressions))
1825
+ always_identity = {column.name for column in table_columns if column.identity_always}
1826
+ if conflict_keys:
1827
+ insert_expression.set(
1828
+ "conflict", _conflict_clause(family, columns, conflict_keys, always_identity, excluded_updates)
1829
+ )
1830
+ rendered_sql = insert_expression.sql(dialect=_sqlglot_dialect(dialect, family), copy=False)
1831
+ if family != "postgres" or always_identity.isdisjoint(columns):
1832
+ return rendered_sql
1833
+ return _INSERT_VALUES_CLAUSE_PATTERN.sub(") OVERRIDING SYSTEM VALUE VALUES (", rendered_sql, count=1)
1834
+
1835
+
1836
+ def _identity_insert_statements(
1837
+ dialect: "DialectType", family: str, table: str, columns: "list[str]", table_columns: "list[_TableColumn]"
1838
+ ) -> "tuple[str, str] | None":
1839
+ """Return the SQL Server and Sybase ASE statements that allow and then disallow explicit identity values.
1840
+
1841
+ SQL Server and Sybase ASE reject values for identity columns unless ``IDENTITY_INSERT`` is on for
1842
+ the table, so inserts that include an identity column run between these statements.
1843
+ Other dialects return ``None``.
1844
+ """
1845
+ inserted = set(columns)
1846
+ if family not in {"tsql", "sybase"} or not any(
1847
+ column.is_identity and column.name in inserted for column in table_columns
1848
+ ):
1849
+ return None
1850
+ table_sql = _quoted_table(table).sql(dialect=_sqlglot_dialect(dialect, family), copy=False)
1851
+ return f"SET IDENTITY_INSERT {table_sql} ON", f"SET IDENTITY_INSERT {table_sql} OFF"
1852
+
1853
+
1854
+ def _insert_table_rows_sync(
1855
+ driver: "SyncDriverAdapterBase",
1856
+ dialect: "DialectType",
1857
+ family: str,
1858
+ table: str,
1859
+ rows: "list[dict[str, Any]]",
1860
+ columns: "list[_TableColumn]",
1861
+ conflict_keys: "tuple[str, ...]",
1862
+ excluded_updates: "set[str]",
1863
+ batch_size: int,
1864
+ *,
1865
+ ignore_unknown_columns: bool = False,
1866
+ ) -> int:
1867
+ """Prepare and insert fixture rows for a single table synchronously, returning the loaded row count."""
1868
+ if not rows:
1869
+ return 0
1870
+ _drop_generated_values(rows, columns, ignore_unknown_columns=ignore_unknown_columns)
1871
+ if not rows:
1872
+ return 0
1873
+ _decode_row_values(rows, family, columns)
1874
+ inserted_columns = list(rows[0])
1875
+ param_map = _fixture_placeholder_map(inserted_columns)
1876
+ statement = _table_insert_statement(
1877
+ dialect, family, table, inserted_columns, conflict_keys, columns, excluded_updates, placeholder_names=param_map
1878
+ )
1879
+ bound_rows = (
1880
+ [{param_map.get(key, key): value for key, value in row.items()} for row in rows]
1881
+ if any(key != value for key, value in param_map.items())
1882
+ else rows
1883
+ )
1884
+ identity_insert = _identity_insert_statements(dialect, family, table, inserted_columns, columns)
1885
+ if identity_insert is not None:
1886
+ driver.execute(identity_insert[0])
1887
+ try:
1888
+ for start in range(0, len(bound_rows), batch_size):
1889
+ driver.execute_many(statement, bound_rows[start : start + batch_size])
1890
+ finally:
1891
+ if identity_insert is not None:
1892
+ driver.execute(identity_insert[1])
1893
+ return len(bound_rows)
1894
+
1895
+
1896
+ async def _insert_table_rows_async(
1897
+ driver: "AsyncDriverAdapterBase",
1898
+ dialect: "DialectType",
1899
+ family: str,
1900
+ table: str,
1901
+ rows: "list[dict[str, Any]]",
1902
+ columns: "list[_TableColumn]",
1903
+ conflict_keys: "tuple[str, ...]",
1904
+ excluded_updates: "set[str]",
1905
+ batch_size: int,
1906
+ *,
1907
+ ignore_unknown_columns: bool = False,
1908
+ ) -> int:
1909
+ """Prepare and insert fixture rows for a single table asynchronously, returning the loaded row count."""
1910
+ if not rows:
1911
+ return 0
1912
+ _drop_generated_values(rows, columns, ignore_unknown_columns=ignore_unknown_columns)
1913
+ if not rows:
1914
+ return 0
1915
+ _decode_row_values(rows, family, columns)
1916
+ inserted_columns = list(rows[0])
1917
+ param_map = _fixture_placeholder_map(inserted_columns)
1918
+ statement = _table_insert_statement(
1919
+ dialect, family, table, inserted_columns, conflict_keys, columns, excluded_updates, placeholder_names=param_map
1920
+ )
1921
+ bound_rows = (
1922
+ [{param_map.get(key, key): value for key, value in row.items()} for row in rows]
1923
+ if any(key != value for key, value in param_map.items())
1924
+ else rows
1925
+ )
1926
+ identity_insert = _identity_insert_statements(dialect, family, table, inserted_columns, columns)
1927
+ if identity_insert is not None:
1928
+ await driver.execute(identity_insert[0])
1929
+ insert_error: BaseException | None = None
1930
+ try:
1931
+ for start in range(0, len(bound_rows), batch_size):
1932
+ await driver.execute_many(statement, bound_rows[start : start + batch_size])
1933
+ except BaseException as exc:
1934
+ insert_error = exc
1935
+ if identity_insert is not None:
1936
+ await driver.execute(identity_insert[1])
1937
+ if insert_error is not None:
1938
+ raise insert_error
1939
+ return len(bound_rows)
1940
+
1941
+
1942
+ def _is_orderable_type(family: str, data_type: str) -> bool:
1943
+ """Return whether a column type, or the element type of an array type, can be used in ORDER BY.
1944
+
1945
+ PostgreSQL types without a default sort order are skipped on every dialect, and
1946
+ large object, XML, and spatial types are skipped on Oracle, Db2, and SQL Server,
1947
+ which reject them in ORDER BY.
1948
+ """
1949
+ base_type = data_type.partition("[")[0].partition("(")[0].strip().lower()
1950
+ if base_type in _UNORDERABLE_POSTGRES_TYPES:
1951
+ return False
1952
+ if base_type.startswith(("array<", "struct<")):
1953
+ return False
1954
+ family_types = _UNORDERABLE_FAMILY_TYPES.get(family)
1955
+ return family_types is None or base_type not in family_types
1956
+
1957
+
1958
+ def _table_export_query(dialect: "DialectType", family: str, table: str, table_columns: "list[_TableColumn]") -> str:
1959
+ """Return SELECT SQL text for every row ordered by the primary key, every orderable column, or position 1.
1960
+
1961
+ The statement is rendered directly from the expression in the target dialect so
1962
+ quoted catalog names keep their exact spelling.
1963
+ """
1964
+ order_columns = [column.name for column in table_columns if column.is_primary] or [
1965
+ column.name for column in table_columns if _is_orderable_type(family, column.data_type)
1966
+ ]
1967
+ order_by: list[exp.Expr] = [exp.Column(this=_quoted_identifier(name)) for name in order_columns]
1968
+ if not order_by and not table_columns:
1969
+ order_by = [exp.Literal.number(1)]
1970
+ projections: list[exp.Expr] = []
1971
+ if family in _JSON_VALUE_FAMILIES and any(column.data_type in _JSON_TYPE_NAMES for column in table_columns):
1972
+ for column in table_columns:
1973
+ expression = exp.Column(this=_quoted_identifier(column.name))
1974
+ if column.data_type in _JSON_TYPE_NAMES:
1975
+ projections.append(
1976
+ exp.Alias(
1977
+ this=exp.Cast(this=expression, to=exp.DataType(this=exp.DataType.Type.TEXT)),
1978
+ alias=_quoted_identifier(column.name),
1979
+ )
1980
+ )
1981
+ else:
1982
+ projections.append(expression)
1983
+ query = exp.Select().select(*(projections or [exp.Star()]), copy=False).from_(_quoted_table(table), copy=False)
1984
+ if order_by:
1985
+ query = query.order_by(*order_by, copy=False)
1986
+ return query.sql(dialect=_sqlglot_dialect(dialect, family), copy=False)
1987
+
1988
+
1989
+ def _sequence_resync_enabled(resync_sequences: bool, dialect_name: str, family: str) -> bool:
1990
+ """Return whether sequence resync applies, logging when it is skipped for the dialect."""
1991
+ if not resync_sequences:
1992
+ return False
1993
+ if dialect_name in _SEQUENCE_RESYNC_DIALECTS or family in _SEQUENCE_RESYNC_DIALECTS:
1994
+ return True
1995
+ logger.debug("Skipping table fixture sequence resync for unsupported dialect %r", dialect_name or None)
1996
+ return False
1997
+
1998
+
1999
+ def _sequence_resync_statements(
2000
+ table: str, table_columns: "list[_TableColumn]", dialect_name: str = "postgres", family: str = "postgres"
2001
+ ) -> "list[tuple[str, dict[str, Any]]]":
2002
+ """Return statements aligning each owned sequence or identity column of a table with its maximum value."""
2003
+ statements: list[tuple[str, dict[str, Any]]] = []
2004
+
2005
+ if family == "postgres" and dialect_name not in {"cockroach", "cockroachdb"}:
2006
+ quoted_table = _quoted_table_name(table)
2007
+ for column in table_columns:
2008
+ quoted_column = _quoted_identifier_sql(column.name)
2009
+ if column.sequence_name is not None:
2010
+ statement = (
2011
+ "WITH seq_info AS ("
2012
+ "SELECT to_regclass(:sequence_name) AS relid, seqmin "
2013
+ "FROM pg_catalog.pg_sequence "
2014
+ "WHERE seqrelid = to_regclass(:sequence_name)"
2015
+ "), table_max AS ("
2016
+ f"SELECT max({quoted_column}) AS max_val FROM {quoted_table}"
2017
+ ") "
2018
+ "SELECT setval("
2019
+ "s.relid, coalesce(m.max_val, s.seqmin), m.max_val IS NOT NULL"
2020
+ ") FROM seq_info s CROSS JOIN table_max m"
2021
+ )
2022
+ statements.append((statement, {"sequence_name": column.sequence_name}))
2023
+ elif column.is_identity:
2024
+ statement = (
2025
+ "WITH seq_info AS ("
2026
+ "SELECT to_regclass(pg_catalog.pg_get_serial_sequence(:table_name, :column_name)) AS relid, s.seqmin "
2027
+ "FROM pg_catalog.pg_sequence s "
2028
+ "WHERE s.seqrelid = to_regclass(pg_catalog.pg_get_serial_sequence(:table_name, :column_name))"
2029
+ "), table_max AS ("
2030
+ f"SELECT max({quoted_column}) AS max_val FROM {quoted_table}"
2031
+ ") "
2032
+ "SELECT setval("
2033
+ "s.relid, coalesce(m.max_val, s.seqmin), m.max_val IS NOT NULL"
2034
+ ") FROM seq_info s CROSS JOIN table_max m"
2035
+ )
2036
+ statements.append((statement, {"table_name": quoted_table, "column_name": column.name}))
2037
+ return statements
2038
+
2039
+ if dialect_name in {"cockroach", "cockroachdb"} or family in {"cockroach", "cockroachdb"}:
2040
+ for column in table_columns:
2041
+ if column.sequence_name is None:
2042
+ continue
2043
+ quoted_column = _quoted_identifier_sql(column.name)
2044
+ statement = (
2045
+ f"SELECT setval(:sequence_name, coalesce(max({quoted_column}), 1), "
2046
+ f"max({quoted_column}) IS NOT NULL) FROM {_quoted_table_name(table)}"
2047
+ )
2048
+ statements.append((statement, {"sequence_name": column.sequence_name}))
2049
+ return statements
2050
+
2051
+ if dialect_name == "duckdb" or family == "duckdb":
2052
+ for column in table_columns:
2053
+ if column.sequence_name is None:
2054
+ continue
2055
+ quoted_column = _quoted_identifier_sql(column.name)
2056
+ sequence_schema, _, sequence_name = column.sequence_name.rpartition(".")
2057
+ if not sequence_schema:
2058
+ table_schema, _, _ = table.rpartition(".")
2059
+ sequence_schema = table_schema or "main"
2060
+ quoted_seq = f"{sequence_schema}.{sequence_name}" if sequence_schema else sequence_name
2061
+ statement = (
2062
+ f"WITH seq_info AS ("
2063
+ f"SELECT coalesce(last_value, start_value - increment_by) AS cur_val, increment_by "
2064
+ f"FROM duckdb_sequences() "
2065
+ f"WHERE schema_name = :sequence_schema AND sequence_name = :sequence_name"
2066
+ f"), "
2067
+ f"table_max AS ("
2068
+ f"SELECT coalesce(max({quoted_column}), 0) AS max_val FROM {_quoted_table_name(table)}"
2069
+ f"), "
2070
+ f"calc AS ("
2071
+ f"SELECT CASE "
2072
+ f"WHEN table_max.max_val > seq_info.cur_val AND seq_info.increment_by > 0 "
2073
+ f"THEN cast(ceil((table_max.max_val - seq_info.cur_val) * 1.0 / seq_info.increment_by) AS bigint) "
2074
+ f"ELSE 0 "
2075
+ f"END AS steps "
2076
+ f"FROM seq_info CROSS JOIN table_max"
2077
+ f") "
2078
+ f"SELECT count(nextval(:quoted_seq)) FROM calc, range(calc.steps)"
2079
+ )
2080
+ statements.append((
2081
+ statement,
2082
+ {"sequence_schema": sequence_schema, "sequence_name": sequence_name, "quoted_seq": quoted_seq},
2083
+ ))
2084
+ return statements
2085
+
2086
+ if family == "oracle":
2087
+ for column in table_columns:
2088
+ if column.is_identity:
2089
+ quoted_column = _quoted_identifier_sql(column.name)
2090
+ if column.identity_always:
2091
+ generation_clause = "GENERATED ALWAYS AS IDENTITY"
2092
+ elif column.identity_on_null:
2093
+ generation_clause = "GENERATED BY DEFAULT ON NULL AS IDENTITY"
2094
+ else:
2095
+ generation_clause = "GENERATED BY DEFAULT AS IDENTITY"
2096
+ statement = (
2097
+ f"ALTER TABLE {_quoted_table_name(table)} MODIFY ("
2098
+ f"{quoted_column} {generation_clause} (START WITH LIMIT VALUE))"
2099
+ )
2100
+ statements.append((statement, {}))
2101
+ return statements
2102
+
2103
+ if family == "tsql":
2104
+ if any(column.is_identity for column in table_columns):
2105
+ table_sql = _quoted_table(table).sql(dialect="tsql", copy=False)
2106
+ statement = f"DBCC CHECKIDENT ('{table_sql}', RESEED)"
2107
+ statements.append((statement, {}))
2108
+ return statements
2109
+
2110
+ if family == "sqlite":
2111
+ primary_columns = [
2112
+ col
2113
+ for col in table_columns
2114
+ if col.is_primary and (col.is_identity or "int" in col.data_type or col.data_type == "")
2115
+ ]
2116
+ if primary_columns:
2117
+ quoted_column = _quoted_identifier_sql(primary_columns[0].name)
2118
+ table_base = table.rsplit(".", maxsplit=1)[-1]
2119
+ statement = (
2120
+ "WITH max_val AS ("
2121
+ f"SELECT coalesce(max({quoted_column}), 0) AS val "
2122
+ f"FROM {_quoted_table_name(table)}"
2123
+ ") "
2124
+ "UPDATE sqlite_sequence SET seq = max_val.val "
2125
+ "FROM max_val WHERE sqlite_sequence.name = :table_name"
2126
+ )
2127
+ statements.append((statement, {"table_name": table_base}))
2128
+ return statements
2129
+
2130
+ return statements
2131
+
2132
+
2133
+ def _plan_sequence_resync_steps(
2134
+ table: str, columns: "list[_TableColumn]", dialect_name: str = "postgres", family: str = "postgres"
2135
+ ) -> "list[_ResyncStep]":
2136
+ """Plan the ordered SQL execution steps to resynchronize sequences or identity columns for a table."""
2137
+ if family == "sybase":
2138
+ escaped_table = table.replace("'", "''")
2139
+ return [
2140
+ _ResyncStep(
2141
+ statement=f"EXEC sp_chgattribute '{escaped_table}', 'identity_burn_max', 0, '{{next_val}}'",
2142
+ parameters={},
2143
+ max_query=f"SELECT coalesce(max({_quoted_identifier_sql(column.name)}), 0) FROM {_quoted_table_name(table)}",
2144
+ default_next=0,
2145
+ skip_when_zero=True,
2146
+ )
2147
+ for column in columns
2148
+ if column.is_identity
2149
+ ]
2150
+
2151
+ if family == "sqlanywhere":
2152
+ schema_part, _, table_part = table.rpartition(".")
2153
+ escaped_table = table_part.replace("'", "''")
2154
+ escaped_schema = schema_part.replace("'", "''")
2155
+ schema_sql = f"'{escaped_schema}'" if schema_part else "NULL"
2156
+ return [
2157
+ _ResyncStep(
2158
+ statement=f"CALL sa_reset_identity('{escaped_table}', {schema_sql}, {{next_val}})",
2159
+ parameters={},
2160
+ max_query=f"SELECT coalesce(max({_quoted_identifier_sql(column.name)}), 0) FROM {_quoted_table_name(table)}",
2161
+ default_next=0,
2162
+ )
2163
+ for column in columns
2164
+ if column.is_identity
2165
+ ]
2166
+
2167
+ if family == "db2":
2168
+ quoted_table = _quoted_table_name(table)
2169
+ steps: list[_ResyncStep] = []
2170
+ for column in columns:
2171
+ quoted_col = _quoted_identifier_sql(column.name)
2172
+ if column.is_identity:
2173
+ steps.append(
2174
+ _ResyncStep(
2175
+ statement=f"ALTER TABLE {quoted_table} ALTER COLUMN {quoted_col} RESTART WITH {{next_val}}",
2176
+ parameters={},
2177
+ max_query=f"SELECT coalesce(max({quoted_col}), 0) + 1 FROM {quoted_table}",
2178
+ )
2179
+ )
2180
+ elif column.sequence_name is not None:
2181
+ quoted_seq = _quoted_table_name(_validated_sequence_identifier(column.sequence_name))
2182
+ steps.append(
2183
+ _ResyncStep(
2184
+ statement=f"ALTER SEQUENCE {quoted_seq} RESTART WITH {{next_val}}",
2185
+ parameters={},
2186
+ max_query=f"SELECT coalesce(max({quoted_col}), 0) + 1 FROM {quoted_table}",
2187
+ )
2188
+ )
2189
+ return steps
2190
+
2191
+ if family == "oracle":
2192
+ steps = [
2193
+ _ResyncStep(statement=stmt, parameters=params)
2194
+ for stmt, params in _sequence_resync_statements(table, columns, dialect_name=dialect_name, family=family)
2195
+ ]
2196
+ quoted_table = _quoted_table_name(table)
2197
+ for column in columns:
2198
+ if not column.is_identity and column.sequence_name is not None:
2199
+ quoted_col = _quoted_identifier_sql(column.name)
2200
+ quoted_seq = _quoted_table_name(_validated_sequence_identifier(column.sequence_name))
2201
+ steps.append(
2202
+ _ResyncStep(
2203
+ statement=f"ALTER SEQUENCE {quoted_seq} RESTART START WITH {{next_val}}",
2204
+ parameters={},
2205
+ max_query=f"SELECT coalesce(max({quoted_col}), 0) + 1 FROM {quoted_table}",
2206
+ )
2207
+ )
2208
+ return steps
2209
+
2210
+ if family == "tsql":
2211
+ steps = [
2212
+ _ResyncStep(statement=stmt, parameters=params)
2213
+ for stmt, params in _sequence_resync_statements(table, columns, dialect_name=dialect_name, family=family)
2214
+ ]
2215
+ quoted_table = _quoted_table(table).sql(dialect="tsql", copy=False)
2216
+ for column in columns:
2217
+ if not column.is_identity and column.sequence_name is not None:
2218
+ quoted_col = exp.column(_quoted_identifier(column.name), copy=False).sql(dialect="tsql", copy=False)
2219
+ quoted_seq = _quoted_table(_validated_sequence_identifier(column.sequence_name)).sql(
2220
+ dialect="tsql", copy=False
2221
+ )
2222
+ steps.append(
2223
+ _ResyncStep(
2224
+ statement=f"ALTER SEQUENCE {quoted_seq} RESTART WITH {{next_val}}",
2225
+ parameters={},
2226
+ max_query=f"SELECT coalesce(max({quoted_col}), 0) + 1 FROM {quoted_table}",
2227
+ )
2228
+ )
2229
+ return steps
2230
+
2231
+ if family == "mysql":
2232
+ quoted_table = _quoted_table(table).sql(dialect="mysql", copy=False)
2233
+ steps = []
2234
+ for column in columns:
2235
+ if not column.is_identity and column.sequence_name is not None:
2236
+ quoted_col = exp.column(_quoted_identifier(column.name), copy=False).sql(dialect="mysql", copy=False)
2237
+ quoted_seq = _quoted_table(_validated_sequence_identifier(column.sequence_name)).sql(
2238
+ dialect="mysql", copy=False
2239
+ )
2240
+ steps.append(
2241
+ _ResyncStep(
2242
+ statement=f"ALTER SEQUENCE {quoted_seq} RESTART WITH {{next_val}}",
2243
+ parameters={},
2244
+ max_query=f"SELECT coalesce(max({quoted_col}), 0) + 1 FROM {quoted_table}",
2245
+ )
2246
+ )
2247
+ auto_columns = [
2248
+ col
2249
+ for col in columns
2250
+ if col.is_identity
2251
+ or (col.is_primary and col.sequence_name is None and ("int" in col.data_type or col.data_type == ""))
2252
+ ]
2253
+ if auto_columns:
2254
+ column = auto_columns[0]
2255
+ quoted_col = exp.column(_quoted_identifier(column.name), copy=False).sql(dialect="mysql", copy=False)
2256
+ steps.append(
2257
+ _ResyncStep(
2258
+ statement=f"ALTER TABLE {quoted_table} AUTO_INCREMENT = {{next_val}}",
2259
+ parameters={},
2260
+ max_query=f"SELECT coalesce(max({quoted_col}), 0) + 1 FROM {quoted_table}",
2261
+ )
2262
+ )
2263
+ return steps
2264
+
2265
+ is_sqlite = family == "sqlite"
2266
+ return [
2267
+ _ResyncStep(statement=stmt, parameters=params, ignore_missing_sqlite_sequence=is_sqlite)
2268
+ for stmt, params in _sequence_resync_statements(table, columns, dialect_name=dialect_name, family=family)
2269
+ ]
2270
+
2271
+
2272
+ def _resync_table_sequences_sync(
2273
+ driver: "SyncDriverAdapterBase", family: str, dialect_name: str, table: str, columns: "list[_TableColumn]"
2274
+ ) -> None:
2275
+ """Resynchronize sequences, identity columns, or auto-increment counters for a table synchronously."""
2276
+ steps = _plan_sequence_resync_steps(table, columns, dialect_name=dialect_name, family=family)
2277
+ if not steps:
2278
+ if family not in {"sybase", "sqlanywhere", "db2", "oracle", "tsql", "mysql", "sqlite"}:
2279
+ logger.debug("Skipping table fixture sequence resync for table %r: no sequence or identity columns", table)
2280
+ return
2281
+ for step in steps:
2282
+ if step.max_query is not None:
2283
+ max_val = driver.select_value(step.max_query)
2284
+ next_val = int(max_val or step.default_next)
2285
+ if step.skip_when_zero and next_val <= 0:
2286
+ continue
2287
+ driver.execute(step.statement.format(next_val=next_val))
2288
+ elif step.ignore_missing_sqlite_sequence:
2289
+ try:
2290
+ driver.execute(step.statement, step.parameters)
2291
+ except Exception as exc:
2292
+ if "no such table: sqlite_sequence" in str(exc).lower():
2293
+ logger.debug("Skipping sqlite_sequence update: sqlite_sequence table does not exist")
2294
+ else:
2295
+ raise
2296
+ else:
2297
+ driver.execute(step.statement, step.parameters)
2298
+
2299
+
2300
+ async def _resync_table_sequences_async(
2301
+ driver: "AsyncDriverAdapterBase", family: str, dialect_name: str, table: str, columns: "list[_TableColumn]"
2302
+ ) -> None:
2303
+ """Resynchronize sequences, identity columns, or auto-increment counters for a table asynchronously."""
2304
+ steps = _plan_sequence_resync_steps(table, columns, dialect_name=dialect_name, family=family)
2305
+ if not steps:
2306
+ if family not in {"sybase", "sqlanywhere", "db2", "oracle", "tsql", "mysql", "sqlite"}:
2307
+ logger.debug("Skipping table fixture sequence resync for table %r: no sequence or identity columns", table)
2308
+ return
2309
+ for step in steps:
2310
+ if step.max_query is not None:
2311
+ max_val = await driver.select_value(step.max_query)
2312
+ next_val = int(max_val or step.default_next)
2313
+ if step.skip_when_zero and next_val <= 0:
2314
+ continue
2315
+ await driver.execute(step.statement.format(next_val=next_val))
2316
+ elif step.ignore_missing_sqlite_sequence:
2317
+ try:
2318
+ await driver.execute(step.statement, step.parameters)
2319
+ except Exception as exc:
2320
+ if "no such table: sqlite_sequence" in str(exc).lower():
2321
+ logger.debug("Skipping sqlite_sequence update: sqlite_sequence table does not exist")
2322
+ else:
2323
+ raise
2324
+ else:
2325
+ await driver.execute(step.statement, step.parameters)
2326
+
2327
+
2328
+ def _exportable_value(value: Any) -> Any:
2329
+ """Return a JSON-ready value, encoding bytes as base64 text and vectors as lists."""
2330
+ if isinstance(value, (bytes, bytearray, memoryview)):
2331
+ return base64.b64encode(value).decode("ascii")
2332
+ if isinstance(value, array.array):
2333
+ return [float(x) for x in value]
2334
+ if hasattr(value, "tolist"):
2335
+ return [float(x) for x in value.tolist()]
2336
+ if hasattr(value, "to_list"):
2337
+ return [float(x) for x in value.to_list()]
2338
+ return value
2339
+
2340
+
2341
+ def _table_fixture_text(rows: "list[dict[str, Any]]", jsonl: bool) -> str:
2342
+ """Serialize table rows as a JSON array or as JSON lines, encoding bytes as base64 text."""
2343
+ exportable = [{key: _exportable_value(value) for key, value in row.items()} for row in rows]
2344
+ if not jsonl:
2345
+ return to_json(exportable)
2346
+ return "".join(f"{to_json(row)}\n" for row in exportable)
2347
+
2348
+
2349
+ def _partition_table_fixture_shards(
2350
+ rows: "list[dict[str, Any]]",
2351
+ jsonl: bool,
2352
+ max_shard_bytes: "int | None" = None,
2353
+ max_rows_per_shard: "int | None" = None,
2354
+ ) -> "list[str]":
2355
+ """Partition table rows into serialized shard text strings."""
2356
+ if not rows:
2357
+ return ["" if jsonl else "[]"]
2358
+ if max_shard_bytes is None and max_rows_per_shard is None:
2359
+ return [_table_fixture_text(rows, jsonl)]
2360
+
2361
+ exportable = [{key: _exportable_value(value) for key, value in row.items()} for row in rows]
2362
+ shards: list[str] = []
2363
+
2364
+ if jsonl:
2365
+ current_lines: list[str] = []
2366
+ current_bytes = 0
2367
+ for row in exportable:
2368
+ line = f"{to_json(row)}\n"
2369
+ line_bytes = len(line.encode("utf-8"))
2370
+ if current_lines and (
2371
+ (max_rows_per_shard is not None and len(current_lines) >= max_rows_per_shard)
2372
+ or (max_shard_bytes is not None and current_bytes + line_bytes > max_shard_bytes)
2373
+ ):
2374
+ shards.append("".join(current_lines))
2375
+ current_lines = [line]
2376
+ current_bytes = line_bytes
2377
+ else:
2378
+ current_lines.append(line)
2379
+ current_bytes += line_bytes
2380
+ if current_lines:
2381
+ shards.append("".join(current_lines))
2382
+ else:
2383
+ current_rows: list[str] = []
2384
+ current_bytes = 2
2385
+ for row in exportable:
2386
+ row_json = to_json(row)
2387
+ row_bytes = len(row_json.encode("utf-8"))
2388
+ row_cost = row_bytes if not current_rows else (1 + row_bytes)
2389
+ if current_rows and (
2390
+ (max_rows_per_shard is not None and len(current_rows) >= max_rows_per_shard)
2391
+ or (max_shard_bytes is not None and current_bytes + row_cost > max_shard_bytes)
2392
+ ):
2393
+ shards.append(f"[{','.join(current_rows)}]")
2394
+ current_rows = [row_json]
2395
+ current_bytes = 2 + row_bytes
2396
+ else:
2397
+ current_rows.append(row_json)
2398
+ current_bytes += row_cost
2399
+ if current_rows:
2400
+ shards.append(f"[{','.join(current_rows)}]")
2401
+
2402
+ return shards
2403
+
2404
+
2405
+ def _write_table_fixture(
2406
+ base_path: Path,
2407
+ table: str,
2408
+ rows: "list[dict[str, Any]]",
2409
+ compress: bool,
2410
+ jsonl: bool,
2411
+ max_shard_bytes: "int | None" = None,
2412
+ max_rows_per_shard: "int | None" = None,
2413
+ ) -> None:
2414
+ """Atomically write table rows to fixture files, removing other fixture files of the table."""
2415
+ base_path.mkdir(parents=True, exist_ok=True)
2416
+ extension = (".jsonl" if jsonl else ".json") + (".gz" if compress else "")
2417
+ shards = _partition_table_fixture_shards(rows, jsonl, max_shard_bytes, max_rows_per_shard)
2418
+
2419
+ temp_paths: list[Path] = []
2420
+ final_paths: list[Path] = []
2421
+ try:
2422
+ target_names = (
2423
+ [f"{table}{extension}"]
2424
+ if len(shards) == 1
2425
+ else [f"{table}.{index:03d}{extension}" for index in range(1, len(shards) + 1)]
2426
+ )
2427
+ for target_name, shard_text in zip(target_names, shards, strict=True):
2428
+ final_paths.append(base_path / target_name)
2429
+ temp_path = base_path / f".{table}.{secrets.token_hex(8)}.tmp"
2430
+ temp_paths.append(temp_path)
2431
+ payload = _compress_text(shard_text) if compress else shard_text.encode("utf-8")
2432
+ descriptor = os.open(temp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, _TEMPORARY_FILE_MODE)
2433
+ with os.fdopen(descriptor, "wb") as handle:
2434
+ handle.write(payload)
2435
+
2436
+ written_paths = set(final_paths)
2437
+ for entry in base_path.iterdir():
2438
+ if not entry.is_file():
2439
+ continue
2440
+ parsed = _parse_table_fixture_filename(entry.name)
2441
+ if (
2442
+ parsed is not None
2443
+ and parsed[0] == table
2444
+ and entry not in written_paths
2445
+ and (parsed[1] is not None or len(shards) > 1)
2446
+ ):
2447
+ entry.unlink(missing_ok=True)
2448
+
2449
+ for temp_path, final_path in zip(temp_paths, final_paths, strict=True):
2450
+ temp_path.replace(final_path)
2451
+ except BaseException:
2452
+ for temp_path in temp_paths:
2453
+ temp_path.unlink(missing_ok=True)
2454
+ raise
2455
+
2456
+ for entry in base_path.iterdir():
2457
+ if not entry.is_file():
2458
+ continue
2459
+ parsed = _parse_table_fixture_filename(entry.name)
2460
+ if parsed is not None and parsed[0] == table and entry not in written_paths:
2461
+ entry.unlink(missing_ok=True)
2462
+
2463
+
2464
+ _async_read_text = async_(_read_text_sync)
2465
+ _async_read_compressed = async_(_read_compressed_file)
2466
+ _async_serialize = async_(_serialize_data)
2467
+ _async_compress = async_(_compress_text)
2468
+ _async_ordered_table_files = async_(_ordered_table_files)
2469
+ _async_read_table_fixture_text = async_(_read_table_fixture_text)
2470
+ _async_write_table_fixture = async_(_write_table_fixture)