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
sqlspec/config.py ADDED
@@ -0,0 +1,3402 @@
1
+ """Database configuration surfaces for SQLSpec adapters.
2
+
3
+ This module is intentionally interpreted even though compiled modules consume
4
+ its config classes. The public configuration API is stability-critical for
5
+ compiled callers: keep constructor fields, protocol attributes, migration
6
+ refresh behavior, storage capability hooks, and provider context managers
7
+ runtime-visible and backwards coherent. Move small pure helpers into compiled
8
+ modules only after proving the boundary with installed-wheel smoke coverage.
9
+ """
10
+
11
+ import asyncio
12
+ import datetime as dt
13
+ import sys
14
+ import threading
15
+ import time
16
+ from abc import ABC, abstractmethod
17
+ from collections.abc import Callable, Mapping, Sequence
18
+ from contextlib import (
19
+ AbstractAsyncContextManager,
20
+ AbstractContextManager,
21
+ AsyncExitStack,
22
+ ExitStack,
23
+ asynccontextmanager,
24
+ contextmanager,
25
+ )
26
+ from difflib import get_close_matches
27
+ from inspect import Signature, isawaitable, iscoroutinefunction, signature
28
+ from pathlib import Path
29
+ from types import MappingProxyType
30
+ from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, NotRequired, Self, TypeAlias, TypeVar, cast
31
+
32
+ from typing_extensions import TypedDict
33
+
34
+ from sqlspec.core import StatementCacheHolder, TypeCoercionCapabilities, resolve_statement_cache_size
35
+ from sqlspec.core.config_runtime import (
36
+ build_default_statement_config,
37
+ close_async_pool,
38
+ close_sync_pool,
39
+ create_async_pool,
40
+ create_sync_pool,
41
+ seed_runtime_driver_features,
42
+ )
43
+ from sqlspec.core.routing import ReplicaHealthBreaker, ReplicaSelector, ReplicaSpec, SelectionStrategy, build_selector
44
+ from sqlspec.exceptions import (
45
+ DatabaseConnectionError,
46
+ ImproperConfigurationError,
47
+ MissingDependencyError,
48
+ OperationalError,
49
+ ReplicaUnavailableError,
50
+ RoutingContextError,
51
+ )
52
+ from sqlspec.extensions.events import EventRuntimeHints
53
+ from sqlspec.loader import SQLFileLoader
54
+ from sqlspec.migrations.tracker import AsyncMigrationTracker, SyncMigrationTracker
55
+ from sqlspec.migrations.utils import ExtensionMigrationMode, resolve_extension_migration_mode
56
+ from sqlspec.observability import ObservabilityConfig, ObservabilityRuntime
57
+ from sqlspec.typing import ConnectionT, PoolT
58
+ from sqlspec.utils.logging import get_logger
59
+ from sqlspec.utils.module_loader import ensure_pyarrow
60
+ from sqlspec.utils.routing import RoutingContext, RoutingEntry
61
+ from sqlspec.utils.tenant import TenantContext, TenantContextPayload
62
+
63
+ if TYPE_CHECKING:
64
+ from collections.abc import AsyncGenerator, Awaitable, Generator, MutableMapping
65
+ from uuid import UUID
66
+
67
+ from sqlspec.core import StatementConfig
68
+ from sqlspec.core.tenant import TenantStrategy
69
+ from sqlspec.driver import AsyncDriverAdapterBase, SyncDriverAdapterBase
70
+ from sqlspec.driver._routing import AsyncDriverT, AsyncRoutingSession, SyncDriverT, SyncRoutingSession
71
+ from sqlspec.migrations.commands import AsyncMigrationCommands, SyncMigrationCommands
72
+ from sqlspec.storage import StorageCapabilities
73
+ from sqlspec.utils.tenant import TenantExtractorValue
74
+
75
+
76
+ __all__ = (
77
+ "MIGRATION_CONFIG_KEYS",
78
+ "MIGRATION_TEMPLATES_KEYS",
79
+ "ADKConfig",
80
+ "AsyncConfigT",
81
+ "AsyncDatabaseConfig",
82
+ "ConfigT",
83
+ "ConnectionT",
84
+ "DatabaseConfigProtocol",
85
+ "DriverT",
86
+ "EventsConfig",
87
+ "ExtensionConfigs",
88
+ "ExtensionMigrationMode",
89
+ "FastAPIConfig",
90
+ "FlaskConfig",
91
+ "LifecycleConfig",
92
+ "LitestarConfig",
93
+ "MigrationConfig",
94
+ "MigrationTemplates",
95
+ "NoPoolAsyncConfig",
96
+ "NoPoolSyncConfig",
97
+ "OpenTelemetryConfig",
98
+ "PoolT",
99
+ "PrometheusConfig",
100
+ "PythonTemplateOverride",
101
+ "ReplicaGroup",
102
+ "SQLTemplateOverride",
103
+ "SanicConfig",
104
+ "StarletteConfig",
105
+ "SyncConfigT",
106
+ "SyncDatabaseConfig",
107
+ "TypeCoercionCapabilities",
108
+ "resolve_extension_migration_mode",
109
+ "validate_migration_config_keys",
110
+ )
111
+
112
+ AsyncConfigT = TypeVar("AsyncConfigT", bound="AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]")
113
+ SyncConfigT = TypeVar("SyncConfigT", bound="SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]")
114
+ ConfigT = TypeVar(
115
+ "ConfigT",
116
+ bound="AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]",
117
+ )
118
+
119
+ DriverT = TypeVar("DriverT", bound="SyncDriverAdapterBase | AsyncDriverAdapterBase")
120
+ ReplicaItemInput: TypeAlias = "DatabaseConfigProtocol[Any, Any, Any] | ReplicaSpec | Mapping[str, Any] | str | bool"
121
+ ReplicaGroupInput: TypeAlias = "ReplicaGroup[Any] | Sequence[ReplicaItemInput]"
122
+ ReplicasInput: TypeAlias = "bool | ReplicaItemInput | ReplicaGroupInput | Mapping[str, Any]"
123
+
124
+ logger = get_logger("sqlspec.config")
125
+
126
+ DRIVER_FEATURE_LIFECYCLE_HOOKS: dict[str, str | None] = {
127
+ "on_connection_create": "connection",
128
+ "on_connection_destroy": "connection",
129
+ "on_pool_create": "pool",
130
+ "on_pool_destroying": "pool",
131
+ "on_pool_destroy": "pool",
132
+ "on_session_start": "session",
133
+ "on_session_end": "session",
134
+ }
135
+
136
+
137
+ class LifecycleConfig(TypedDict):
138
+ """Lifecycle callback hooks for database adapters.
139
+
140
+ Each hook accepts a list of callables receiving a single
141
+ :data:`~sqlspec.observability.LifecycleContext` (``dict[str, Any]``)
142
+ mapping containing the ``config`` key (plus ``bind_key`` and
143
+ ``correlation_id`` when set) and event-specific payload keys.
144
+ """
145
+
146
+ on_connection_create: NotRequired[list[Callable[[dict[str, Any]], Any]]]
147
+ """Callbacks invoked after a raw driver connection is created (``connection`` key)."""
148
+ on_connection_destroy: NotRequired[list[Callable[[dict[str, Any]], Any]]]
149
+ """Callbacks invoked before closing or destroying a driver connection (``connection`` key)."""
150
+ on_pool_create: NotRequired[list[Callable[[dict[str, Any]], Any]]]
151
+ """Callbacks invoked after the adapter connection pool is initialized (``pool`` key)."""
152
+ on_pool_destroying: NotRequired[list[Callable[[dict[str, Any]], Any]]]
153
+ """Callbacks invoked immediately before shutting down the connection pool (``pool`` key)."""
154
+ on_pool_destroy: NotRequired[list[Callable[[dict[str, Any]], Any]]]
155
+ """Callbacks invoked after the connection pool has finished closing (``pool`` key)."""
156
+ on_session_start: NotRequired[list[Callable[[dict[str, Any]], Any]]]
157
+ """Callbacks invoked when a driver session context begins (``session`` key)."""
158
+ on_session_end: NotRequired[list[Callable[[dict[str, Any]], Any]]]
159
+ """Callbacks invoked when a driver session context exits (``session`` key)."""
160
+ on_query_start: NotRequired[list[Callable[[dict[str, Any]], Any]]]
161
+ """Callbacks invoked before statement execution with ``LifecycleContext`` keys ``sql``, ``parameters``, ``driver``, ``operation``, ``is_many``, and ``is_script``."""
162
+ on_query_complete: NotRequired[list[Callable[[dict[str, Any]], Any]]]
163
+ """Callbacks invoked on completion with ``LifecycleContext`` keys ``sql``, ``parameters``, ``driver``, ``operation``, ``is_many``, ``is_script``, and ``rows_affected``."""
164
+ on_error: NotRequired[list[Callable[[dict[str, Any]], Any]]]
165
+ """Callbacks invoked on query failure with ``LifecycleContext`` keys ``exception``, ``sql``, ``parameters``, ``driver``, ``operation``, ``is_many``, and ``is_script``."""
166
+
167
+
168
+ class SQLTemplateOverride(TypedDict):
169
+ """Overrides for the SQL migration template."""
170
+
171
+ header: NotRequired[str]
172
+ """First line of the generated file. Supports the migration template placeholders."""
173
+
174
+ metadata: NotRequired["list[str]"]
175
+ """Comment lines rendered beneath the header."""
176
+
177
+ body: NotRequired[str]
178
+ """Migration body containing the up and down named statements."""
179
+
180
+ description_key: NotRequired["str | list[str]"]
181
+ """Metadata label(s) the description is read back from. Defaults to 'Description'."""
182
+
183
+
184
+ class PythonTemplateOverride(TypedDict):
185
+ """Overrides for the Python migration template."""
186
+
187
+ docstring: NotRequired[str]
188
+ """Module docstring contents. Supports the migration template placeholders."""
189
+
190
+ body: NotRequired[str]
191
+ """Module body defining the up and down functions."""
192
+
193
+ imports: NotRequired["list[str]"]
194
+ """Import lines rendered between the docstring and the body."""
195
+
196
+ description_key: NotRequired["str | list[str]"]
197
+ """Docstring label(s) the description is read back from. Defaults to 'Description'."""
198
+
199
+
200
+ class MigrationTemplates(TypedDict):
201
+ """Template overrides applied when generating migration files.
202
+
203
+ Placeholders available to every fragment: ``title``, ``version``, ``message``,
204
+ ``description``, ``created_at``, ``author``, ``adapter``, and ``project_slug``.
205
+ """
206
+
207
+ sql: NotRequired[SQLTemplateOverride]
208
+ """Overrides for generated ``.sql`` migrations."""
209
+
210
+ py: NotRequired[PythonTemplateOverride]
211
+ """Overrides for generated ``.py`` migrations."""
212
+
213
+ title: NotRequired[str]
214
+ """Title used when ``MigrationConfig.title`` is omitted."""
215
+
216
+
217
+ class MigrationConfig(TypedDict):
218
+ """Configuration options for database migrations.
219
+
220
+ All fields are optional with default values.
221
+ """
222
+
223
+ script_location: NotRequired["str | Path"]
224
+ """Path to the migrations directory. Accepts string or Path object. Defaults to 'migrations'."""
225
+
226
+ version_table_name: NotRequired[str]
227
+ """Name of the table used to track applied migrations. Defaults to 'ddl_migrations'."""
228
+
229
+ default_schema: NotRequired[str]
230
+ """Schema applied to migration sessions before user migration SQL runs, when supported by the adapter.
231
+ Can be overridden on individual migration files via the ``-- schema: <name>`` directive.
232
+ """
233
+
234
+ version_table_schema: NotRequired[str]
235
+ """Schema that stores the migration tracking table. Defaults to default_schema when omitted."""
236
+
237
+ project_root: NotRequired[str]
238
+ """Path to the project root directory. Used for relative path resolution."""
239
+
240
+ author: NotRequired[str]
241
+ """Author recorded on generated migration files. Defaults to the detected git user."""
242
+
243
+ enabled: NotRequired[bool]
244
+ """Whether this configuration should be included in CLI operations. Defaults to True."""
245
+
246
+ auto_sync: NotRequired[bool]
247
+ """Enable automatic version reconciliation during upgrade. When enabled (default), SQLSpec automatically updates database tracking when migrations are renamed from timestamp to sequential format. Defaults to True."""
248
+
249
+ verify_checksums: NotRequired[bool]
250
+ """Refuse upgrade and downgrade when an applied migration file no longer matches its recorded checksum. Defaults to True."""
251
+
252
+ lock_lease_seconds: NotRequired[int]
253
+ """Lease length in seconds for migration locks on backends without a native session lock. Renewed before each migration, so it must exceed the longest single migration. Defaults to 900."""
254
+
255
+ strict_ordering: NotRequired[bool]
256
+ """Enforce strict migration ordering. When enabled, prevents out-of-order migrations from being applied. Defaults to False."""
257
+
258
+ include_extensions: NotRequired["list[str]"]
259
+ """List of extension names whose migrations should be included. Extension migrations maintain separate versioning and are prefixed with 'ext_{name}_'.
260
+
261
+ Note: Extensions with migration support (litestar, adk, events) are auto-included when
262
+ their settings are present in ``extension_config``, as is any extension whose settings
263
+ declare ``migrations_path``. Use ``exclude_extensions`` to opt out.
264
+ """
265
+
266
+ exclude_extensions: NotRequired["list[str]"]
267
+ """
268
+ List of extension names to exclude from automatic migration inclusion.
269
+
270
+ When an extension is configured in ``extension_config``, its migrations are automatically
271
+ included. Use this to prevent that for specific extensions:
272
+ """
273
+
274
+ transactional: NotRequired[bool]
275
+ """Wrap migrations in transactions when supported. When enabled (default for adapters that support it), each migration runs in a transaction that is committed on success or rolled back on failure. This prevents partial migrations from leaving the database in an inconsistent state. Requires adapter support for transactional DDL. Defaults to True for PostgreSQL, SQLite, and DuckDB; False for MySQL, Oracle, and BigQuery. Individual migrations can override this with a '-- transactional: false' comment."""
276
+
277
+ use_logger: NotRequired[bool]
278
+ """
279
+ Use Python logger instead of Rich console for migration output.
280
+
281
+ When True, migration progress is logged via structlog/logging instead of being
282
+ printed to the console with Rich formatting. This is useful for programmatic
283
+ usage where console output is not desired.
284
+
285
+ Can be overridden per-call via the ``use_logger`` parameter on ``migrate_up()``
286
+ and ``migrate_down()`` methods.
287
+
288
+ Defaults to False (Rich console output).
289
+ """
290
+
291
+ echo: NotRequired[bool]
292
+ """Echo migration output to the console.
293
+
294
+ When False, console output is suppressed. This is useful for script or CI
295
+ environments that need quiet stdout.
296
+
297
+ Defaults to True.
298
+ """
299
+
300
+ summary_only: NotRequired[bool]
301
+ """Emit a single summary log entry for migration commands.
302
+
303
+ When True and ``use_logger`` is enabled, per-migration output is suppressed
304
+ in favor of a single structured summary log event.
305
+
306
+ Defaults to False.
307
+ """
308
+
309
+ default_format: NotRequired["Literal['sql', 'py']"]
310
+ """File format used by ``create-migration`` when none is requested. Defaults to 'sql'."""
311
+
312
+ title: NotRequired[str]
313
+ """Title rendered into generated migration files. Defaults to 'SQLSpec Migration'."""
314
+
315
+ templates: NotRequired[MigrationTemplates]
316
+ """Template fragment overrides applied when generating migration files."""
317
+
318
+ schema_dump_path: NotRequired["str | Path | None"]
319
+ """Default file path written by ``dump_schema()`` when ``output_path`` is omitted."""
320
+
321
+ auto_dump_schema: NotRequired["bool | str | Path | None"]
322
+ """Automatically dump the current database schema after ``upgrade()`` applies migrations.
323
+
324
+ ``True`` writes to ``schema_dump_path`` (or ``<script_location>/schema.sql``); a path writes there. The dump runs
325
+ after the migrations have committed, so a dump failure is logged as a warning and does not fail the upgrade.
326
+ """
327
+
328
+
329
+ MIGRATION_CONFIG_KEYS: "frozenset[str]" = MigrationConfig.__required_keys__ | MigrationConfig.__optional_keys__
330
+ MIGRATION_TEMPLATES_KEYS: "frozenset[str]" = MigrationTemplates.__required_keys__ | MigrationTemplates.__optional_keys__
331
+ _TEMPLATE_FRAGMENT_KEYS: "dict[str, frozenset[str]]" = {
332
+ "sql": SQLTemplateOverride.__required_keys__ | SQLTemplateOverride.__optional_keys__,
333
+ "py": PythonTemplateOverride.__required_keys__ | PythonTemplateOverride.__optional_keys__,
334
+ }
335
+
336
+
337
+ def validate_migration_config_keys(migration_config: "Mapping[str, Any]") -> None:
338
+ """Reject migration configuration keys that SQLSpec does not read.
339
+
340
+ Args:
341
+ migration_config: Migration configuration mapping to check.
342
+
343
+ Raises:
344
+ ImproperConfigurationError: If the mapping contains an unrecognized key.
345
+ """
346
+ lines = _report_unknown_keys(migration_config, MIGRATION_CONFIG_KEYS, "", "")
347
+ templates = migration_config.get("templates")
348
+ if templates is not None:
349
+ lines.extend(_report_template_keys(templates))
350
+ if lines:
351
+ raise ImproperConfigurationError(" ".join(lines))
352
+
353
+
354
+ class FlaskConfig(TypedDict):
355
+ """Configuration options for Flask SQLSpec extension.
356
+
357
+ All fields are optional with sensible defaults. Use in extension_config["flask"]:
358
+ """
359
+
360
+ tenant_extractor: NotRequired[Callable[..., "TenantExtractorValue"]]
361
+ """Return the authorized tenant payload, string, UUID, or None (no tenant from this source) for the request. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start. Accepts zero arguments or the Flask request."""
362
+
363
+ connection_key: NotRequired[str]
364
+ """Key for storing the connection in Flask g once it is checked out on first access. Default: auto-generated from session_key."""
365
+
366
+ session_key: NotRequired[str]
367
+ """Key for accessing session via plugin.get_session(). Default: 'db_session'."""
368
+
369
+ commit_mode: NotRequired[Literal["manual", "autocommit", "autocommit_include_redirect"]]
370
+ """Transaction commit mode. Default: 'autocommit'.
371
+ - manual: No automatic commit; uncommitted work rolls back on release
372
+ - autocommit: Commits on 2xx status, rollback otherwise
373
+ - autocommit_include_redirect: Commits on 2xx-3xx status, rollback otherwise
374
+ """
375
+
376
+ extra_commit_statuses: NotRequired[set[int]]
377
+ """Additional HTTP status codes that trigger commit. Default: None."""
378
+
379
+ extra_rollback_statuses: NotRequired[set[int]]
380
+ """Additional HTTP status codes that trigger rollback. Default: None."""
381
+
382
+ disable_di: NotRequired[bool]
383
+ """Disable built-in dependency injection. Default: False.
384
+ When True, the Flask extension will not register request hooks for managing
385
+ database connections and sessions. Users are responsible for managing the
386
+ database lifecycle manually via their own DI solution.
387
+ """
388
+
389
+ enable_sqlcommenter_middleware: NotRequired[bool]
390
+ """Control automatic SQLCommenter context population. Default: True.
391
+ When the driver's :class:`~sqlspec.core.statement.StatementConfig` has
392
+ ``enable_sqlcommenter=True``, request attributes are populated automatically.
393
+ Set to ``False`` to explicitly disable this behavior.
394
+ """
395
+
396
+ enable_correlation_middleware: NotRequired[bool]
397
+ """Enable request correlation ID middleware. Default: True"""
398
+
399
+ correlation_header: NotRequired[str]
400
+ """HTTP header to read the request correlation ID from when middleware is enabled. Default: ``X-Request-ID``"""
401
+
402
+ correlation_headers: NotRequired[tuple[str, ...] | list[str]]
403
+ """Additional HTTP headers to read as correlation ID fallbacks."""
404
+
405
+ auto_trace_headers: NotRequired[bool]
406
+ """Read standard trace context headers as correlation ID fallbacks. Default: True."""
407
+
408
+ replica_session_key: NotRequired[str]
409
+ """Request key for a replica session."""
410
+ replica_connection_key: NotRequired[str]
411
+ """Request key for a replica connection."""
412
+ routing_session_key: NotRequired[str]
413
+ """Request key for a routing session."""
414
+ default_routing_mode: NotRequired[Literal["primary", "auto"]]
415
+ """Default request routing mode. Default: ``'auto'``."""
416
+ enable_routing_middleware: NotRequired[bool]
417
+ """Install request-scoped routing middleware. Default: True."""
418
+ routing_header: NotRequired[str | None]
419
+ """Trusted application routing header name when explicitly enabled behind a gateway. Default: None."""
420
+ primary_pin_cookie: NotRequired[str | None]
421
+ """Optional application primary pin cookie name. Default: None."""
422
+ primary_pin_secret: NotRequired[str | bytes | None]
423
+ """Optional HMAC secret verifying signed primary pin cookies. Default: None."""
424
+
425
+
426
+ class LitestarConfig(TypedDict):
427
+ """Configuration options for Litestar SQLSpec plugin.
428
+
429
+ All fields are optional with sensible defaults.
430
+ """
431
+
432
+ tenant_extractor: NotRequired["Callable[[MutableMapping[str, Any]], Any]"]
433
+ """Trusted scope callable returning a tenant identity, payload, None (no tenant from this source), or an awaitable. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start."""
434
+
435
+ tenant_user_attr: NotRequired[str]
436
+ """Verified direct tenant attribute or mapping key. Default: 'tenant_id'."""
437
+
438
+ tenant_memberships_attr: NotRequired[str]
439
+ """Verified membership attribute or mapping key. Default: 'tenant_ids'."""
440
+
441
+ tenant_variables_attr: NotRequired[str]
442
+ """Extra session variables attribute or mapping key. Default: 'tenant_variables'."""
443
+
444
+ tenant_jwt_claim: NotRequired[str]
445
+ """Direct tenant key in verified auth claims or extras. Default: 'tenant_id'."""
446
+
447
+ tenant_path_parameter: NotRequired[str | None]
448
+ """Route parameter checked against verified memberships. Default: 'tenant_id'."""
449
+
450
+ tenant_session_key: NotRequired[str | None]
451
+ """Session selector checked against verified memberships. Default: 'tenant_id'."""
452
+
453
+ tenant_header: NotRequired[str | None]
454
+ """Optional header selector checked against verified memberships. Default: None."""
455
+
456
+ migrations_path: NotRequired[str | Path]
457
+ """Directory containing this extension's migrations, or a ``'<dotted.module>:<subdir>'`` specification.
458
+
459
+ Overrides the default ``sqlspec.extensions.<name>`` lookup. Setting this auto-includes the
460
+ extension in ``migration_config["include_extensions"]``.
461
+ """
462
+
463
+ session_table: NotRequired["bool | str"]
464
+ """Enable session table for server-side session storage.
465
+
466
+ - ``True``: Use default table name ('litestar_session')
467
+ - ``"custom_name"``: Use custom table name
468
+
469
+ When set, litestar extension migrations are auto-included to create the session table.
470
+ If you're only using litestar for DI/connection management (not session storage),
471
+ leave this unset to skip the migrations.
472
+ """
473
+
474
+ connection_key: NotRequired[str]
475
+ """Key for storing connection in ASGI scope. Default: 'db_connection'"""
476
+
477
+ pool_key: NotRequired[str]
478
+ """Key for storing connection pool in application state. Default: 'db_pool'"""
479
+
480
+ session_key: NotRequired[str]
481
+ """Key for storing session in ASGI scope. Default: 'db_session'"""
482
+
483
+ commit_mode: NotRequired[Literal["manual", "autocommit", "autocommit_include_redirect"]]
484
+ """Transaction commit mode. Default: 'autocommit'"""
485
+
486
+ enable_correlation_middleware: NotRequired[bool]
487
+ """Enable request correlation ID middleware. Default: True"""
488
+
489
+ correlation_header: NotRequired[str]
490
+ """HTTP header to read the request correlation ID from when middleware is enabled. Default: ``X-Request-ID``"""
491
+
492
+ correlation_headers: NotRequired[tuple[str, ...] | list[str]]
493
+ """Additional HTTP headers to read as correlation ID fallbacks."""
494
+
495
+ auto_trace_headers: NotRequired[bool]
496
+ """Read standard trace context headers as correlation ID fallbacks. Default: True."""
497
+
498
+ extra_commit_statuses: NotRequired[set[int]]
499
+ """Additional HTTP status codes that trigger commit. Default: set()"""
500
+
501
+ extra_rollback_statuses: NotRequired[set[int]]
502
+ """Additional HTTP status codes that trigger rollback. Default: set()"""
503
+
504
+ disable_di: NotRequired[bool]
505
+ """Disable built-in dependency injection. Default: False.
506
+ When True, the Litestar plugin will not register dependency providers for database
507
+ connections, pools, and sessions, or the per-request handler that commits and closes
508
+ request connections. Pool startup and shutdown follow ``manage_lifespan``, which
509
+ defaults to False when ``disable_di`` is True.
510
+ """
511
+
512
+ manage_lifespan: NotRequired[bool]
513
+ """Register the plugin's pool lifespan handler. Default: the inverse of ``disable_di``.
514
+ When True, the Litestar plugin creates the configuration's pool on application startup,
515
+ stores it in application state under ``pool_key``, and closes it on shutdown, whether or
516
+ not ``disable_di`` is set. Set to True alongside ``disable_di=True`` to keep pool lifecycle
517
+ management while another DI solution provides connections and sessions. When False, the
518
+ application creates and closes the pool itself; with dependency injection enabled, the
519
+ plugin's providers still read the pool from application state under ``pool_key``.
520
+ """
521
+
522
+ enable_sqlcommenter_middleware: NotRequired[bool]
523
+ """Control automatic SQLCommenter middleware registration. Default: True.
524
+ When the driver's :class:`~sqlspec.core.statement.StatementConfig` has
525
+ ``enable_sqlcommenter=True``, the middleware is registered automatically.
526
+ Set to ``False`` to explicitly disable middleware registration even when
527
+ SQLCommenter is enabled on the driver config.
528
+ """
529
+
530
+ manage_schema: NotRequired[bool]
531
+ """Apply additive session-table reconciliation. Default: True."""
532
+
533
+ create_schema: NotRequired[bool]
534
+ """Create a missing session table during managed reconciliation. Default: True."""
535
+
536
+ migration_mode: NotRequired[ExtensionMigrationMode]
537
+ """Extension migration strategy (``'versioned'`` or ``'reconcile'``). Default: ``'reconcile'``."""
538
+
539
+ replica_session_key: NotRequired[str]
540
+ """Request key for a replica session."""
541
+ replica_connection_key: NotRequired[str]
542
+ """Request key for a replica connection."""
543
+ routing_session_key: NotRequired[str]
544
+ """Request key for a routing session."""
545
+ default_routing_mode: NotRequired[Literal["primary", "auto"]]
546
+ """Default request routing mode. Default: ``'auto'``."""
547
+ enable_routing_middleware: NotRequired[bool]
548
+ """Install request-scoped routing middleware. Default: True."""
549
+ routing_header: NotRequired[str | None]
550
+ """Trusted application routing header name when explicitly enabled behind a gateway. Default: None."""
551
+ primary_pin_cookie: NotRequired[str | None]
552
+ """Optional application primary pin cookie name. Default: None."""
553
+ primary_pin_secret: NotRequired[str | bytes | None]
554
+ """Optional HMAC secret verifying signed primary pin cookies. Default: None."""
555
+ replica_pool_key: NotRequired[str]
556
+ """Request key for the selected replica pool."""
557
+ pagination_cursor_secret: NotRequired[str | bytes]
558
+ """Application-wide secret enabling HMAC-SHA256 signed pagination cursors."""
559
+ pagination_cursor_ttl: NotRequired[int | float | dt.timedelta]
560
+ """Default cursor expiration window in seconds or timedelta."""
561
+ pagination_cursor_encrypted: NotRequired[bool]
562
+ """Encrypt cursor payloads at rest when a cursor secret is configured."""
563
+
564
+
565
+ class StarletteConfig(TypedDict):
566
+ """Configuration options for Starlette SQLSpec extension.
567
+
568
+ All fields are optional with sensible defaults. Use in extension_config["starlette"]:
569
+ """
570
+
571
+ tenant_extractor: NotRequired[Callable[[Any], Any]]
572
+ """Trusted scope extractor returning a tenant payload, string, UUID, None (no tenant from this source), or an awaitable. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start."""
573
+
574
+ connection_key: NotRequired[str]
575
+ """Key for storing the connection in request.state once it is checked out on first access. Default: 'db_connection'"""
576
+
577
+ pool_key: NotRequired[str]
578
+ """Key for storing connection pool in app.state. Default: 'db_pool'"""
579
+
580
+ session_key: NotRequired[str]
581
+ """Key for storing session in request.state. Default: 'db_session'"""
582
+
583
+ commit_mode: NotRequired[Literal["manual", "autocommit", "autocommit_include_redirect"]]
584
+ """Transaction commit mode. Default: 'autocommit'
585
+
586
+ - manual: No automatic commit; uncommitted work rolls back on release
587
+ - autocommit: Commit on 2xx, rollback otherwise
588
+ - autocommit_include_redirect: Commit on 2xx-3xx, rollback otherwise
589
+ """
590
+
591
+ extra_commit_statuses: NotRequired[set[int]]
592
+ """Additional HTTP status codes that trigger commit. Default: set()"""
593
+
594
+ extra_rollback_statuses: NotRequired[set[int]]
595
+ """Additional HTTP status codes that trigger rollback. Default: set()"""
596
+
597
+ disable_di: NotRequired[bool]
598
+ """Disable built-in dependency injection. Default: False.
599
+ When True, the Starlette/FastAPI extension will not add middleware for managing
600
+ database connections and sessions. Users are responsible for managing the
601
+ database lifecycle manually via their own DI solution.
602
+ """
603
+
604
+ enable_sqlcommenter_middleware: NotRequired[bool]
605
+ """Control automatic SQLCommenter middleware registration. Default: True.
606
+ When the driver's :class:`~sqlspec.core.statement.StatementConfig` has
607
+ ``enable_sqlcommenter=True``, the middleware is registered automatically.
608
+ Set to ``False`` to explicitly disable middleware registration.
609
+ """
610
+
611
+ sqlcommenter_framework: NotRequired[str]
612
+ """Framework name for SQLCommenter attributes. Default: 'starlette'.
613
+ Set to 'fastapi' when using FastAPI.
614
+ """
615
+
616
+ enable_correlation_middleware: NotRequired[bool]
617
+ """Enable request correlation ID middleware. Default: True"""
618
+
619
+ correlation_header: NotRequired[str]
620
+ """HTTP header to read the request correlation ID from when middleware is enabled. Default: ``X-Request-ID``"""
621
+
622
+ correlation_headers: NotRequired[tuple[str, ...] | list[str]]
623
+ """Additional HTTP headers to read as correlation ID fallbacks."""
624
+
625
+ auto_trace_headers: NotRequired[bool]
626
+ """Read standard trace context headers as correlation ID fallbacks. Default: True."""
627
+
628
+ replica_session_key: NotRequired[str]
629
+ """Request key for a replica session."""
630
+ replica_connection_key: NotRequired[str]
631
+ """Request key for a replica connection."""
632
+ routing_session_key: NotRequired[str]
633
+ """Request key for a routing session."""
634
+ default_routing_mode: NotRequired[Literal["primary", "auto"]]
635
+ """Default request routing mode. Default: ``'auto'``."""
636
+ enable_routing_middleware: NotRequired[bool]
637
+ """Install request-scoped routing middleware. Default: True."""
638
+ routing_header: NotRequired[str | None]
639
+ """Trusted application routing header name when explicitly enabled behind a gateway. Default: None."""
640
+ primary_pin_cookie: NotRequired[str | None]
641
+ """Optional application primary pin cookie name. Default: None."""
642
+ primary_pin_secret: NotRequired[str | bytes | None]
643
+ """Optional HMAC secret verifying signed primary pin cookies. Default: None."""
644
+ replica_pool_key: NotRequired[str]
645
+ """Request key for the selected replica pool."""
646
+ pagination_cursor_secret: NotRequired[str | bytes]
647
+ """Application-wide secret enabling HMAC-SHA256 signed pagination cursors."""
648
+ pagination_cursor_ttl: NotRequired[int | float | dt.timedelta]
649
+ """Default cursor expiration window in seconds or timedelta."""
650
+ pagination_cursor_encrypted: NotRequired[bool]
651
+ """Encrypt cursor payloads at rest when a cursor secret is configured."""
652
+
653
+
654
+ class FastAPIConfig(StarletteConfig):
655
+ """Configuration options for FastAPI SQLSpec extension.
656
+
657
+ All fields are optional with sensible defaults. Use in ``extension_config["fastapi"]``.
658
+ SQLCommenter defaults the framework attribute to ``"fastapi"``.
659
+ """
660
+
661
+
662
+ class SanicConfig(TypedDict):
663
+ """Configuration options for Sanic SQLSpec extension.
664
+
665
+ All fields are optional with sensible defaults. Use in ``extension_config["sanic"]``.
666
+ """
667
+
668
+ tenant_extractor: NotRequired[Callable[[Any], "TenantExtractorValue | Awaitable[TenantExtractorValue]"]]
669
+ """Return the authorized tenant payload, string, UUID, or None (no tenant from this source), optionally as an awaitable. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start."""
670
+
671
+ connection_key: NotRequired[str]
672
+ """Key for storing the connection in request.ctx once it is checked out on first access. Default: 'db_connection'"""
673
+
674
+ pool_key: NotRequired[str]
675
+ """Key for storing connection pool in app.ctx. Default: 'db_pool'"""
676
+
677
+ session_key: NotRequired[str]
678
+ """Key for storing session in request.ctx. Default: 'db_session'"""
679
+
680
+ commit_mode: NotRequired[Literal["manual", "autocommit", "autocommit_include_redirect"]]
681
+ """Transaction commit mode. Default: 'autocommit'
682
+
683
+ - manual: No automatic commit; uncommitted work rolls back on release
684
+ - autocommit: Commit on 2xx, rollback otherwise
685
+ - autocommit_include_redirect: Commit on 2xx-3xx, rollback otherwise
686
+ """
687
+
688
+ extra_commit_statuses: NotRequired[set[int]]
689
+ """Additional HTTP status codes that trigger commit. Default: set()"""
690
+
691
+ extra_rollback_statuses: NotRequired[set[int]]
692
+ """Additional HTTP status codes that trigger rollback. Default: set()"""
693
+
694
+ disable_di: NotRequired[bool]
695
+ """Disable built-in dependency injection. Default: False.
696
+ When True, the Sanic extension will not register request middleware for
697
+ managing database connections and sessions. Users are responsible for
698
+ managing the database lifecycle manually via their own DI solution.
699
+ """
700
+
701
+ enable_correlation_middleware: NotRequired[bool]
702
+ """Enable request correlation ID middleware. Default: True."""
703
+
704
+ correlation_header: NotRequired[str]
705
+ """HTTP header to read the request correlation ID from when middleware is enabled. Default: ``X-Request-ID``."""
706
+
707
+ correlation_headers: NotRequired[tuple[str, ...] | list[str]]
708
+ """Additional HTTP headers to read as correlation ID fallbacks."""
709
+
710
+ auto_trace_headers: NotRequired[bool]
711
+ """Read standard trace context headers as correlation ID fallbacks. Default: True."""
712
+
713
+ enable_sqlcommenter_middleware: NotRequired[bool]
714
+ """Control automatic SQLCommenter middleware registration. Default: True.
715
+ When the driver's :class:`~sqlspec.core.statement.StatementConfig` has
716
+ ``enable_sqlcommenter=True``, the middleware is registered automatically.
717
+ Set to ``False`` to explicitly disable middleware registration.
718
+ """
719
+
720
+ sqlcommenter_framework: NotRequired[str]
721
+ """Framework name for SQLCommenter attributes. Default: 'sanic'."""
722
+
723
+ replica_session_key: NotRequired[str]
724
+ """Request key for a replica session."""
725
+ replica_connection_key: NotRequired[str]
726
+ """Request key for a replica connection."""
727
+ routing_session_key: NotRequired[str]
728
+ """Request key for a routing session."""
729
+ default_routing_mode: NotRequired[Literal["primary", "auto"]]
730
+ """Default request routing mode. Default: ``'auto'``."""
731
+ enable_routing_middleware: NotRequired[bool]
732
+ """Install request-scoped routing middleware. Default: True."""
733
+ routing_header: NotRequired[str | None]
734
+ """Trusted application routing header name when explicitly enabled behind a gateway. Default: None."""
735
+ primary_pin_cookie: NotRequired[str | None]
736
+ """Optional application primary pin cookie name. Default: None."""
737
+ primary_pin_secret: NotRequired[str | bytes | None]
738
+ """Optional HMAC secret verifying signed primary pin cookies. Default: None."""
739
+ replica_pool_key: NotRequired[str]
740
+ """Request key for the selected replica pool."""
741
+
742
+
743
+ class ADKConfig(TypedDict):
744
+ """Configuration options for ADK session and memory store extension.
745
+
746
+ All fields are optional with sensible defaults. Use in extension_config["adk"]:
747
+
748
+ Configuration supports three deployment scenarios:
749
+ 1. SQLSpec manages everything (runtime + migrations)
750
+ 2. SQLSpec runtime only (external migration tools like Alembic/Flyway)
751
+ 3. Selective features (sessions OR memory, not both)
752
+ """
753
+
754
+ migrations_path: NotRequired[str | Path]
755
+ """Directory containing this extension's migrations, or a ``'<dotted.module>:<subdir>'`` specification.
756
+
757
+ Overrides the default ``sqlspec.extensions.<name>`` lookup. Setting this auto-includes the
758
+ extension in ``migration_config["include_extensions"]``.
759
+ """
760
+
761
+ manage_schema: NotRequired[bool]
762
+ """Apply additive target-schema reconciliation. Default: True."""
763
+
764
+ create_schema: NotRequired[bool]
765
+ """Create missing ADK tables during managed reconciliation. Default: True."""
766
+
767
+ enable_sessions: NotRequired[bool]
768
+ """Enable the session store at runtime and in packaged migrations. Default: True.
769
+
770
+ When False the session service is unavailable, session store operations are
771
+ disabled, and packaged ADK migrations emit no session, event, state, or
772
+ metadata DDL.
773
+ """
774
+
775
+ enable_memory: NotRequired[bool]
776
+ """Enable the memory store at runtime and in packaged migrations. Default: True.
777
+
778
+ When False the memory service is unavailable, memory store operations are
779
+ disabled, and packaged ADK migrations emit no memory table DDL or PostgreSQL
780
+ vector extension statement.
781
+ """
782
+
783
+ session_table: NotRequired[str]
784
+ """Name of the sessions table. Default: 'adk_session'"""
785
+
786
+ events_table: NotRequired[str]
787
+ """Name of the events table. Default: 'adk_event'"""
788
+
789
+ app_state_table: NotRequired[str]
790
+ """Name of the app-scoped state table. Default: 'adk_app_state'"""
791
+
792
+ user_state_table: NotRequired[str]
793
+ """Name of the user-scoped state table. Default: 'adk_user_state'"""
794
+
795
+ metadata_table: NotRequired[str]
796
+ """Name of the internal metadata table. Default: 'adk_internal_metadata'"""
797
+
798
+ memory_table: NotRequired[str]
799
+ """Name of the memory entries table. Default: 'adk_memory'"""
800
+
801
+ artifact_table: NotRequired[str]
802
+ """Name of the artifact metadata table. Default: 'adk_artifact'"""
803
+
804
+ artifact_storage_uri: NotRequired[str]
805
+ """
806
+ Base URI for artifact content storage.
807
+
808
+ Points to a ``sqlspec/storage/`` backend where artifact binary content
809
+ is stored. Can be a direct URI (``s3://bucket/path``, ``file:///path``)
810
+ or a registered alias in the storage registry.
811
+ """
812
+
813
+ memory_use_fts: NotRequired[bool]
814
+ """Enable full-text search when supported. Default: False.
815
+
816
+ When True, adapters will use their native FTS capabilities where available:
817
+ - PostgreSQL: to_tsvector/to_tsquery with GIN index
818
+ - SQLite: FTS5 virtual table
819
+ - DuckDB: FTS extension with match_bm25
820
+ - Oracle: CONTAINS() with CTXSYS.CONTEXT index
821
+ - Spanner: TOKENIZE_FULLTEXT with search index
822
+ - MySQL: MATCH...AGAINST with FULLTEXT index
823
+
824
+ When False, adapters use simple LIKE/ILIKE queries (works without indexes).
825
+ """
826
+
827
+ memory_max_results: NotRequired[int]
828
+ """Maximum number of results for memory search queries. Default: 20.
829
+
830
+ Limits the number of memory entries returned by search_memory().
831
+ Can be overridden per-query via the limit parameter.
832
+ """
833
+
834
+ owner_id_column: NotRequired[str]
835
+ """
836
+ Optional owner ID column definition to link sessions/memories to a user, tenant, team, or other entity.
837
+
838
+ Format: "column_name TYPE [NOT NULL] REFERENCES table(column) [options...]"
839
+
840
+ The entire definition is passed through to DDL verbatim. We only parse
841
+ the column name (first word) for use in INSERT/SELECT statements.
842
+
843
+ This column is added to both session and memory tables for consistent
844
+ multi-tenant isolation.
845
+
846
+ Supports:
847
+ - Foreign key constraints: REFERENCES table(column)
848
+ - Nullable or NOT NULL
849
+ - CASCADE options: ON DELETE CASCADE, ON UPDATE CASCADE
850
+ - Dialect-specific options (DEFERRABLE, ENABLE VALIDATE, etc.)
851
+ - Plain columns without FK (just extra column storage)
852
+ """
853
+
854
+ migration_mode: NotRequired[ExtensionMigrationMode]
855
+ """Extension migration strategy (``'versioned'`` or ``'reconcile'``). Default: ``'reconcile'``."""
856
+
857
+ enable_replica_reads: NotRequired[bool]
858
+ """Enable optional read configuration for ADK lookups."""
859
+ default_replica_group: NotRequired[str | None]
860
+ """Named replica group used for ADK reads."""
861
+
862
+
863
+ class EventsConfig(TypedDict):
864
+ """Configuration options for the events extension.
865
+
866
+ Use in ``extension_config["events"]``.
867
+ """
868
+
869
+ migrations_path: NotRequired[str | Path]
870
+ """Directory containing this extension's migrations, or a ``'<dotted.module>:<subdir>'`` specification.
871
+
872
+ Overrides the default ``sqlspec.extensions.<name>`` lookup. Setting this auto-includes the
873
+ extension in ``migration_config["include_extensions"]``.
874
+ """
875
+
876
+ manage_schema: NotRequired[bool]
877
+ """Apply additive target-schema reconciliation. Default: True."""
878
+
879
+ create_schema: NotRequired[bool]
880
+ """Create the queue table during managed reconciliation. Default: True."""
881
+
882
+ backend: NotRequired[Literal["notify", "notify_queue", "poll_queue", "aq", "txeventq"]]
883
+ """Backend implementation. PostgreSQL adapters default to 'notify', others to 'poll_queue'.
884
+
885
+ - notify: Transient PostgreSQL LISTEN/NOTIFY wakeup; not a durable event ledger
886
+ - notify_queue: Durable table queue with PostgreSQL LISTEN/NOTIFY wakeups
887
+ - poll_queue: Durable table queue discovered by polling
888
+ - aq: Oracle Advanced Queuing
889
+ - txeventq: Oracle Transactional Event Queues
890
+ """
891
+
892
+ queue_table: NotRequired[str]
893
+ """Name of the fallback queue table. Defaults to 'sqlspec_event_queue'."""
894
+
895
+ lease_seconds: NotRequired[int]
896
+ """Lease duration for claimed events before they can be retried. Defaults to 30 seconds."""
897
+
898
+ retention_seconds: NotRequired[int]
899
+ """Retention window for acknowledged events before cleanup. Defaults to 86400 (24 hours)."""
900
+
901
+ max_attempts: NotRequired[int]
902
+ """Maximum claims per event before ``nack`` marks it failed. Defaults to 5."""
903
+
904
+ retry_backoff_seconds: NotRequired[float]
905
+ """Base delay for exponential redelivery backoff after ``nack``. Defaults to 1.0."""
906
+
907
+ poll_interval: NotRequired[float]
908
+ """Compatibility alias for event_poll_interval. Defaults to 1.0."""
909
+
910
+ event_poll_interval: NotRequired[float]
911
+ """Durable event reconciliation interval in seconds. Takes precedence over poll_interval."""
912
+
913
+ select_for_update: NotRequired[bool]
914
+ """Use SELECT FOR UPDATE locking when claiming events. Defaults to False."""
915
+
916
+ skip_locked: NotRequired[bool]
917
+ """Use SKIP LOCKED for non-blocking event claims. Defaults to False."""
918
+
919
+ shard_count: NotRequired[int]
920
+ """Number of hash shards for queue table and index prefixing (e.g. Cloud Spanner). Defaults to 1."""
921
+
922
+ migration_mode: NotRequired[ExtensionMigrationMode]
923
+ """Extension migration strategy (``'versioned'`` or ``'reconcile'``). Default: ``'reconcile'``."""
924
+
925
+
926
+ class OpenTelemetryConfig(TypedDict):
927
+ """Configuration options for OpenTelemetry integration.
928
+
929
+ Use in ``extension_config["otel"]``.
930
+ """
931
+
932
+ enabled: NotRequired[bool]
933
+ """Enable the extension. Default: True."""
934
+
935
+ enable_spans: NotRequired[bool]
936
+ """Enable span emission (set False to disable while keeping other settings)."""
937
+
938
+ resource_attributes: NotRequired[dict[str, Any]]
939
+ """Additional resource attributes passed to the tracer provider factory."""
940
+
941
+ tracer_provider: NotRequired[Any]
942
+ """Tracer provider instance to reuse. Mutually exclusive with ``tracer_provider_factory``."""
943
+
944
+ tracer_provider_factory: NotRequired[Callable[[], Any]]
945
+ """Factory returning a tracer provider. Invoked lazily when spans are needed."""
946
+
947
+
948
+ class PrometheusConfig(TypedDict):
949
+ """Configuration options for Prometheus metrics.
950
+
951
+ Use in ``extension_config["prometheus"]``.
952
+ """
953
+
954
+ enabled: NotRequired[bool]
955
+ """Enable the extension. Default: True."""
956
+
957
+ namespace: NotRequired[str]
958
+ """Prometheus metric namespace. Default: ``"sqlspec"``."""
959
+
960
+ subsystem: NotRequired[str]
961
+ """Prometheus metric subsystem. Default: ``"driver"``."""
962
+
963
+ registry: NotRequired[Any]
964
+ """Custom Prometheus registry (defaults to the global registry)."""
965
+
966
+ label_names: NotRequired[tuple[str, ...]]
967
+ """Labels applied to metrics. Default: ("driver", "operation")."""
968
+
969
+ duration_buckets: NotRequired[tuple[float, ...]]
970
+ """Histogram buckets for query duration (seconds)."""
971
+
972
+
973
+ ExtensionConfigs: TypeAlias = dict[
974
+ str,
975
+ dict[str, Any]
976
+ | LitestarConfig
977
+ | FastAPIConfig
978
+ | StarletteConfig
979
+ | SanicConfig
980
+ | FlaskConfig
981
+ | ADKConfig
982
+ | EventsConfig
983
+ | OpenTelemetryConfig
984
+ | PrometheusConfig,
985
+ ]
986
+
987
+
988
+ class DatabaseConfigProtocol(ABC, Generic[ConnectionT, PoolT, DriverT]):
989
+ """Protocol defining the stability-critical config contract.
990
+
991
+ Compiled callers rely on these attributes and methods remaining
992
+ runtime-visible while ``sqlspec.config`` stays interpreted. Changes to
993
+ migration setup, pool/session provider behavior, storage capabilities, or
994
+ observability bootstrap must preserve this contract or move behind a
995
+ separately verified compiled helper boundary.
996
+ """
997
+
998
+ __slots__ = (
999
+ "_is_replica",
1000
+ "_migration_commands",
1001
+ "_migration_config",
1002
+ "_migration_loader",
1003
+ "_migration_lock",
1004
+ "_observability_runtime",
1005
+ "_replica_groups",
1006
+ "_replica_pools_initialized",
1007
+ "_storage_capabilities",
1008
+ "_tenant_key",
1009
+ "bind_key",
1010
+ "connection_config",
1011
+ "connection_instance",
1012
+ "driver_features",
1013
+ "extension_config",
1014
+ "observability_config",
1015
+ "statement_config",
1016
+ )
1017
+
1018
+ _tenant_key: Any
1019
+ _is_replica: bool
1020
+ _replica_groups: "dict[str, ReplicaGroup[Any]]"
1021
+ _replica_pools_initialized: bool
1022
+ _migration_loader: "SQLFileLoader | None"
1023
+ _migration_commands: "SyncMigrationCommands[Any] | AsyncMigrationCommands[Any] | None"
1024
+ _migration_lock: "threading.RLock"
1025
+ _migration_config: "dict[str, Any] | MigrationConfig"
1026
+ driver_type: "ClassVar[type[Any]]"
1027
+ connection_type: "ClassVar[type[Any]]"
1028
+ migration_tracker_type: "ClassVar[type[Any]]"
1029
+ _connection_context_class: "ClassVar[type[Any]]"
1030
+ _session_factory_class: "ClassVar[type[Any]]"
1031
+ _session_context_class: "ClassVar[type[Any]]"
1032
+ _default_statement_config: "ClassVar[StatementConfig]"
1033
+ is_async: "ClassVar[bool]" = False
1034
+ supports_connection_pooling: "ClassVar[bool]" = False
1035
+ supports_transactions: "ClassVar[bool]" = True
1036
+ supports_transactional_ddl: "ClassVar[bool]" = False
1037
+ supports_native_arrow_import: "ClassVar[bool]" = False
1038
+ supports_native_arrow_export: "ClassVar[bool]" = False
1039
+ supports_arrow_streaming: "ClassVar[bool]" = False
1040
+ supports_native_row_streaming: "ClassVar[bool]" = False
1041
+ supports_migration_schemas: "ClassVar[bool]" = False
1042
+ supports_native_parquet_import: "ClassVar[bool]" = False
1043
+ supports_native_parquet_export: "ClassVar[bool]" = False
1044
+ supports_reliable_rowcount: "ClassVar[bool]" = True
1045
+ supports_tenant_strategy: "ClassVar[bool]" = False
1046
+ supports_tenant_session_baseline: "ClassVar[bool]" = False
1047
+ tenant_strategy_shorthands: "ClassVar[frozenset[str]]" = frozenset()
1048
+ tenant_strategy_type: "ClassVar[type[Any] | None]" = None
1049
+ tenant_lease_type: "ClassVar[type[Any] | None]" = None
1050
+ default_storage_profile: "ClassVar[str | None]" = None
1051
+ storage_partition_strategies: "ClassVar[tuple[str, ...]]" = ("fixed",)
1052
+ type_coercion_capabilities: "ClassVar[TypeCoercionCapabilities]" = TypeCoercionCapabilities(
1053
+ datetime_binding="native", timestamp_precision="microsecond", json_columns_decoded=False, uuid_binding="native"
1054
+ )
1055
+ adapter_name: "ClassVar[str | None]" = None
1056
+ events_store_class: "ClassVar[type[Any] | None]" = None
1057
+ adk_store_class: "ClassVar[type[Any] | None]" = None
1058
+ adk_memory_store_class: "ClassVar[type[Any] | None]" = None
1059
+ litestar_store_class: "ClassVar[type[Any] | None]" = None
1060
+ bind_key: "str | None"
1061
+ statement_config: "StatementConfig"
1062
+ connection_config: "dict[str, Any]"
1063
+ connection_instance: "PoolT | None"
1064
+ extension_config: "ExtensionConfigs"
1065
+ driver_features: "dict[str, Any]"
1066
+ _storage_capabilities: "StorageCapabilities | None"
1067
+ observability_config: "ObservabilityConfig | None"
1068
+ _observability_runtime: "ObservabilityRuntime | None"
1069
+
1070
+ @property
1071
+ def is_replica(self) -> bool:
1072
+ """Whether this configuration represents a read replica."""
1073
+ return self._is_replica
1074
+
1075
+ @property
1076
+ def has_replicas(self) -> bool:
1077
+ """Whether this configuration owns any replica groups."""
1078
+ return bool(self._replica_groups)
1079
+
1080
+ @property
1081
+ def supports_read_routing(self) -> bool:
1082
+ """Whether replica pools or an adapter-specific read provider are available."""
1083
+ return self.has_replicas or type(self).provide_replica_session not in {
1084
+ DatabaseConfigProtocol.provide_replica_session,
1085
+ NoPoolSyncConfig.provide_replica_session,
1086
+ NoPoolAsyncConfig.provide_replica_session,
1087
+ SyncDatabaseConfig.provide_replica_session,
1088
+ AsyncDatabaseConfig.provide_replica_session,
1089
+ }
1090
+
1091
+ @property
1092
+ def replica_groups(self) -> "Mapping[str, ReplicaGroup[Any]]":
1093
+ """Return a read-only view of named replica groups."""
1094
+ return MappingProxyType(self._replica_groups)
1095
+
1096
+ @property
1097
+ def migration_config(self) -> "dict[str, Any] | MigrationConfig":
1098
+ """Return the current migration configuration."""
1099
+ return self._migration_config
1100
+
1101
+ @migration_config.setter
1102
+ def migration_config(self, value: "dict[str, Any] | MigrationConfig | None") -> None:
1103
+ """Store migration configuration and refresh derived migration helpers."""
1104
+ resolved = dict(cast("dict[str, Any]", value) or {})
1105
+ validate_migration_config_keys(resolved)
1106
+ Path(resolved.get("script_location", "migrations"))
1107
+ if "project_root" in resolved:
1108
+ Path(resolved["project_root"])
1109
+ if any(key in resolved for key in ("templates", "title", "default_format")):
1110
+ from sqlspec.migrations.templates import build_template_settings
1111
+
1112
+ build_template_settings(resolved)
1113
+ with self._migration_lock:
1114
+ object.__setattr__(self, "_migration_config", resolved)
1115
+ self._migration_loader = None
1116
+ self._migration_commands = None
1117
+ if self._has_initialized_attribute("extension_config"):
1118
+ self._ensure_extension_migrations()
1119
+
1120
+ def derive_pool(
1121
+ self,
1122
+ *,
1123
+ connection_config_overrides: "Mapping[str, Any] | None" = None,
1124
+ driver_features_overrides: "Mapping[str, Any] | None" = None,
1125
+ statement_config: "StatementConfig | None" = None,
1126
+ migration_config: "dict[str, Any] | MigrationConfig | None" = None,
1127
+ extension_config: "ExtensionConfigs | None" = None,
1128
+ observability_config: "ObservabilityConfig | None" = None,
1129
+ bind_key: "str | None" = None,
1130
+ is_replica: bool = False,
1131
+ **overrides: Any,
1132
+ ) -> Self:
1133
+ """Clone this configuration with overridden connection/pool or feature settings and ``connection_instance=None``."""
1134
+ new_conn_cfg: dict[str, Any] = dict(self.connection_config)
1135
+ connection_overrides: dict[str, Any] = dict(connection_config_overrides or {})
1136
+ new_driver_features: dict[str, Any] = {
1137
+ key: value
1138
+ for key, value in self.driver_features.items()
1139
+ if key not in {"_statement_cache_holder", "storage_capabilities"}
1140
+ }
1141
+ pool_session_cb = getattr(self, "_pool_session_callback", None)
1142
+ if pool_session_cb is not None and "session_callback" not in new_conn_cfg:
1143
+ new_conn_cfg["session_callback"] = pool_session_cb
1144
+ user_conn_hook = getattr(self, "_user_connection_hook", None)
1145
+ if user_conn_hook is not None and "on_connection_create" not in new_driver_features:
1146
+ new_driver_features["on_connection_create"] = user_conn_hook
1147
+ if connection_config_overrides:
1148
+ new_conn_cfg.update(connection_config_overrides)
1149
+ if driver_features_overrides:
1150
+ new_driver_features.update(driver_features_overrides)
1151
+ for key, val in overrides.items():
1152
+ if key in self.driver_features or key in DRIVER_FEATURE_LIFECYCLE_HOOKS:
1153
+ new_driver_features[key] = val
1154
+ else:
1155
+ new_conn_cfg[key] = val
1156
+ connection_overrides[key] = val
1157
+ new_conn_cfg = self._prepare_derived_connection_config(new_conn_cfg, connection_overrides)
1158
+ derived = cast("Callable[..., Self]", type(self))(
1159
+ is_replica=is_replica,
1160
+ replicas=None,
1161
+ connection_config=new_conn_cfg,
1162
+ connection_instance=None,
1163
+ migration_config=dict(self.migration_config) if migration_config is None else migration_config,
1164
+ statement_config=self.statement_config if statement_config is None else statement_config,
1165
+ driver_features=new_driver_features,
1166
+ bind_key=self.bind_key if bind_key is None else bind_key,
1167
+ extension_config=cast("ExtensionConfigs", dict(self.extension_config))
1168
+ if extension_config is None
1169
+ else extension_config,
1170
+ observability_config=self.observability_config if observability_config is None else observability_config,
1171
+ )
1172
+
1173
+ if bind_key is None or bind_key == self.bind_key:
1174
+ derived._tenant_key = self._tenant_key
1175
+ return derived
1176
+
1177
+ def provide_routing_session(
1178
+ self,
1179
+ *,
1180
+ replica_group: str | None = None,
1181
+ statement_config: "StatementConfig | None" = None,
1182
+ tenant: "str | UUID | TenantContextPayload | None" = None,
1183
+ bypass_tenant: bool = False,
1184
+ ) -> "SyncRoutingSession[Any] | AsyncRoutingSession[Any]":
1185
+ """Construct a lazy routing facade for this configuration.
1186
+
1187
+ Args:
1188
+ replica_group: Replica group used for eligible reads.
1189
+ statement_config: Statement configuration override.
1190
+ tenant: Tenant identity or payload for physical checkouts.
1191
+ bypass_tenant: Explicitly bypass tenant setup.
1192
+
1193
+ Returns:
1194
+ A facade matching this configuration's execution mode.
1195
+ """
1196
+ from sqlspec.driver._routing import AsyncRoutingSession, SyncRoutingSession
1197
+
1198
+ if self.is_async:
1199
+ async_config = cast("AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]", self)
1200
+ return AsyncRoutingSession(
1201
+ async_config,
1202
+ replica_group=replica_group,
1203
+ statement_config=statement_config,
1204
+ tenant=tenant,
1205
+ bypass_tenant=bypass_tenant,
1206
+ )
1207
+ sync_config = cast("SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]", self)
1208
+ return SyncRoutingSession(
1209
+ sync_config,
1210
+ replica_group=replica_group,
1211
+ statement_config=statement_config,
1212
+ tenant=tenant,
1213
+ bypass_tenant=bypass_tenant,
1214
+ )
1215
+
1216
+ def provide_replica_connection(
1217
+ self, *args: Any, replica_group: str | None = None, **kwargs: Any
1218
+ ) -> "AbstractContextManager[ConnectionT] | AbstractAsyncContextManager[ConnectionT]":
1219
+ """Provide a replica connection, honoring scoped primary pins."""
1220
+ return cast(
1221
+ "AbstractContextManager[ConnectionT] | AbstractAsyncContextManager[ConnectionT]",
1222
+ self._provide_read(False, args, kwargs, replica_group),
1223
+ )
1224
+
1225
+ def provide_replica_session(
1226
+ self,
1227
+ *args: Any,
1228
+ replica_group: str | None = None,
1229
+ statement_config: "StatementConfig | None" = None,
1230
+ tenant: "str | UUID | TenantContextPayload | None" = None,
1231
+ bypass_tenant: bool = False,
1232
+ **kwargs: Any,
1233
+ ) -> "AbstractContextManager[DriverT] | AbstractAsyncContextManager[DriverT]":
1234
+ """Provide a replica session while retaining the selected config's tenant lease."""
1235
+ kwargs.update(statement_config=statement_config, tenant=tenant, bypass_tenant=bypass_tenant)
1236
+ return cast(
1237
+ "AbstractContextManager[DriverT] | AbstractAsyncContextManager[DriverT]",
1238
+ self._provide_read(True, args, kwargs, replica_group),
1239
+ )
1240
+
1241
+ def __hash__(self) -> int:
1242
+ return id(self)
1243
+
1244
+ def __eq__(self, other: object) -> bool:
1245
+ return self is other
1246
+
1247
+ def __repr__(self) -> str:
1248
+ parts = ", ".join([
1249
+ f"connection_instance={self.connection_instance!r}",
1250
+ f"migration_config={self.migration_config!r}",
1251
+ ])
1252
+ return f"{type(self).__name__}({parts})"
1253
+
1254
+ def set_migration_config(self, config: "dict[str, Any] | MigrationConfig") -> None:
1255
+ """Attach migration configuration after initial config creation.
1256
+
1257
+ This is equivalent to setting ``migration_config`` directly but provides
1258
+ a discoverable method for post-construction configuration.
1259
+
1260
+ Args:
1261
+ config: Migration configuration dictionary.
1262
+ """
1263
+ self.migration_config = config
1264
+
1265
+ def storage_capabilities(self) -> "StorageCapabilities":
1266
+ """Return cached storage capabilities for this configuration."""
1267
+
1268
+ if self._storage_capabilities is None:
1269
+ self._storage_capabilities = self._build_storage_capabilities()
1270
+ return cast("StorageCapabilities", dict(self._storage_capabilities))
1271
+
1272
+ def reset_storage_capabilities_cache(self) -> None:
1273
+ """Clear the cached capability snapshot."""
1274
+
1275
+ self._storage_capabilities = None
1276
+
1277
+ def get_event_runtime_hints(self) -> "EventRuntimeHints":
1278
+ """Return default event runtime hints for this configuration."""
1279
+
1280
+ return EventRuntimeHints()
1281
+
1282
+ def attach_observability(self, registry_config: "ObservabilityConfig | None") -> None:
1283
+ """Attach merged observability runtime composed from registry and adapter overrides."""
1284
+ merged = ObservabilityConfig.merge(registry_config, self.observability_config)
1285
+ self._observability_runtime = ObservabilityRuntime(
1286
+ merged, bind_key=self.bind_key, config_name=type(self).__name__
1287
+ )
1288
+ for group in self._replica_groups.values():
1289
+ group.attach_observability(registry_config)
1290
+
1291
+ def get_observability_runtime(self) -> "ObservabilityRuntime":
1292
+ """Return the attached runtime, creating a disabled instance when missing."""
1293
+
1294
+ if self._observability_runtime is None:
1295
+ self.attach_observability(None)
1296
+ if self._observability_runtime is None:
1297
+ msg = "ObservabilityRuntime was not set by attach_observability; this is a bug"
1298
+ raise RuntimeError(msg)
1299
+ return self._observability_runtime
1300
+
1301
+ @abstractmethod
1302
+ def create_connection(self) -> "ConnectionT | Awaitable[ConnectionT]":
1303
+ """Create and return a new database connection."""
1304
+ raise NotImplementedError
1305
+
1306
+ @abstractmethod
1307
+ def provide_connection(
1308
+ self, *args: Any, **kwargs: Any
1309
+ ) -> "AbstractContextManager[ConnectionT] | AbstractAsyncContextManager[ConnectionT]":
1310
+ """Provide a database connection context manager."""
1311
+ raise NotImplementedError
1312
+
1313
+ @abstractmethod
1314
+ def provide_session(
1315
+ self, *args: Any, **kwargs: Any
1316
+ ) -> "AbstractContextManager[DriverT] | AbstractAsyncContextManager[DriverT]":
1317
+ """Provide a database session context manager."""
1318
+ raise NotImplementedError
1319
+
1320
+ @abstractmethod
1321
+ def create_pool(self) -> "PoolT | Awaitable[PoolT]":
1322
+ """Create and return connection pool."""
1323
+ raise NotImplementedError
1324
+
1325
+ @abstractmethod
1326
+ def close_pool(self) -> "Awaitable[None] | None":
1327
+ """Terminate the connection pool."""
1328
+ raise NotImplementedError
1329
+
1330
+ @abstractmethod
1331
+ def provide_pool(
1332
+ self, *args: Any, **kwargs: Any
1333
+ ) -> "PoolT | Awaitable[PoolT] | AbstractContextManager[PoolT] | AbstractAsyncContextManager[PoolT]":
1334
+ """Provide pool instance."""
1335
+ raise NotImplementedError
1336
+
1337
+ def get_signature_namespace(self) -> "dict[str, Any]":
1338
+ """Get the signature namespace for this database configuration.
1339
+
1340
+ Returns a dictionary of type names to objects (classes, functions, or
1341
+ other callables) that should be registered with Litestar's signature
1342
+ namespace to prevent serialization attempts on database-specific
1343
+ structures.
1344
+
1345
+ Returns:
1346
+ Dictionary mapping type names to objects.
1347
+ """
1348
+ return {}
1349
+
1350
+ def get_migration_loader(self) -> "SQLFileLoader":
1351
+ """Get the SQL loader for migration files.
1352
+
1353
+ Provides access to migration SQL files loaded from the configured
1354
+ script_location directory. Files are loaded lazily on first access.
1355
+
1356
+ Returns:
1357
+ SQLFileLoader instance with migration files loaded.
1358
+ """
1359
+ return self._ensure_migration_loader()
1360
+
1361
+ def load_migration_sql_files(self, *paths: "str | Path") -> None:
1362
+ """Load additional migration SQL files from specified paths.
1363
+
1364
+ Args:
1365
+ *paths: One or more file paths or directory paths to load migration SQL files from.
1366
+ """
1367
+
1368
+ loader = self._ensure_migration_loader()
1369
+ for path in paths:
1370
+ path_obj = Path(path)
1371
+ if path_obj.exists():
1372
+ loader.load_sql(path_obj)
1373
+ logger.debug("Loaded migration SQL files from %s", path_obj)
1374
+ else:
1375
+ logger.warning("Migration path does not exist: %s", path_obj)
1376
+
1377
+ def get_migration_commands(self) -> "SyncMigrationCommands[Any] | AsyncMigrationCommands[Any]":
1378
+ """Get migration commands for this configuration.
1379
+
1380
+ The first call constructs the tracker and discovers extension migrations.
1381
+ Call this during application startup to surface their initialization errors
1382
+ eagerly. Subsequent calls reuse the helper until configuration changes.
1383
+
1384
+ Returns:
1385
+ MigrationCommands instance configured for this database.
1386
+ """
1387
+ return self._ensure_migration_commands()
1388
+
1389
+ def add_extension_migrations(
1390
+ self,
1391
+ name: str,
1392
+ migrations_path: "str | Path",
1393
+ settings: "dict[str, Any] | None" = None,
1394
+ *,
1395
+ migration_mode: ExtensionMigrationMode | None = None,
1396
+ ) -> None:
1397
+ """Register migrations shipped by a package outside the ``sqlspec.extensions`` namespace.
1398
+
1399
+ Records the extension under ``extension_config``, opts it into
1400
+ ``migration_config["include_extensions"]``, and invalidates cached migration
1401
+ commands so the extension is discovered on their next access. Migrations
1402
+ are versioned under the ``ext_{name}_`` prefix, so ``name`` must stay stable
1403
+ once migrations are applied.
1404
+
1405
+ Args:
1406
+ name: Extension name, used as the ``ext_{name}_`` version prefix.
1407
+ migrations_path: Directory containing the migrations, or a
1408
+ ``'<dotted.module>:<subdir>'`` specification.
1409
+ settings: Extension settings passed to its migrations. Merged into any
1410
+ settings already registered under ``name``.
1411
+ migration_mode: Optional explicit migration mode (``'versioned'`` or ``'reconcile'``).
1412
+ """
1413
+ with self._migration_lock:
1414
+ extension_config = cast("dict[str, Any]", self.extension_config)
1415
+ existing = extension_config.get(name)
1416
+ merged: dict[str, Any] = dict(existing) if isinstance(existing, Mapping) else {}
1417
+ if settings:
1418
+ merged.update(settings)
1419
+ merged["migrations_path"] = migrations_path
1420
+ resolve_extension_migration_mode(migration_mode, merged, extension_name=name)
1421
+ if migration_mode is not None:
1422
+ merged["migration_mode"] = migration_mode
1423
+ extension_config[name] = merged
1424
+
1425
+ migration_config = cast("dict[str, Any]", self.migration_config)
1426
+ include_extensions = migration_config.get("include_extensions")
1427
+ include_list = list(include_extensions) if include_extensions else []
1428
+ changed = merged != existing or name not in include_list
1429
+ if name not in include_list:
1430
+ include_list.append(name)
1431
+ migration_config["include_extensions"] = include_list
1432
+
1433
+ if changed:
1434
+ self._migration_commands = None
1435
+
1436
+ def remove_extension_migrations(self, name: str) -> bool:
1437
+ """Unregister migrations previously registered for an extension.
1438
+
1439
+ Removes the extension entry from ``extension_config`` and from
1440
+ ``migration_config["include_extensions"]``. If anything
1441
+ was removed, cached migration commands are invalidated so the extension is no
1442
+ longer discovered on their next access.
1443
+
1444
+ Args:
1445
+ name: Extension name to unregister.
1446
+
1447
+ Returns:
1448
+ True if the extension was found and removed, False otherwise.
1449
+ """
1450
+ with self._migration_lock:
1451
+ removed = False
1452
+ extension_config = cast("dict[str, Any]", self.extension_config)
1453
+ if isinstance(extension_config, dict) and name in extension_config:
1454
+ del extension_config[name]
1455
+ removed = True
1456
+
1457
+ migration_config = cast("dict[str, Any]", self.migration_config)
1458
+ include_extensions = migration_config.get("include_extensions")
1459
+ if include_extensions is not None and name in include_extensions:
1460
+ migration_config["include_extensions"] = [ext for ext in include_extensions if ext != name]
1461
+ removed = True
1462
+
1463
+ if removed:
1464
+ self._migration_commands = None
1465
+ return True
1466
+
1467
+ return False
1468
+
1469
+ @abstractmethod
1470
+ def migrate_up(
1471
+ self,
1472
+ revision: str = "head",
1473
+ allow_missing: bool = False,
1474
+ auto_sync: bool = True,
1475
+ dry_run: bool = False,
1476
+ *,
1477
+ use_logger: bool = False,
1478
+ echo: bool | None = None,
1479
+ summary_only: bool | None = None,
1480
+ ) -> "Awaitable[None] | None":
1481
+ """Apply database migrations up to specified revision.
1482
+
1483
+ Args:
1484
+ revision: Target revision or "head" for latest. Defaults to "head".
1485
+ allow_missing: Allow out-of-order migrations. Defaults to False.
1486
+ auto_sync: Auto-reconcile renamed migrations. Defaults to True.
1487
+ dry_run: Show what would be done without applying. Defaults to False.
1488
+ use_logger: Use Python logger instead of Rich console for output.
1489
+ Defaults to False. Can be set via MigrationConfig for persistent default.
1490
+ echo: Echo output to the console. Defaults to True when unset.
1491
+ summary_only: Emit a single summary log entry when logger output is enabled.
1492
+ """
1493
+ raise NotImplementedError
1494
+
1495
+ @abstractmethod
1496
+ def migrate_down(
1497
+ self,
1498
+ revision: str = "-1",
1499
+ *,
1500
+ dry_run: bool = False,
1501
+ use_logger: bool = False,
1502
+ echo: bool | None = None,
1503
+ summary_only: bool | None = None,
1504
+ ) -> "Awaitable[None] | None":
1505
+ """Apply database migrations down to specified revision.
1506
+
1507
+ Args:
1508
+ revision: Target revision, "-1" for one step back, or "base" for all migrations. Defaults to "-1".
1509
+ dry_run: Show what would be done without applying. Defaults to False.
1510
+ use_logger: Use Python logger instead of Rich console for output.
1511
+ Defaults to False. Can be set via MigrationConfig for persistent default.
1512
+ echo: Echo output to the console. Defaults to True when unset.
1513
+ summary_only: Emit a single summary log entry when logger output is enabled.
1514
+ """
1515
+ raise NotImplementedError
1516
+
1517
+ @abstractmethod
1518
+ def get_current_migration(self, verbose: bool = False) -> "Awaitable[str | None] | str | None":
1519
+ """Get the current migration version.
1520
+
1521
+ Args:
1522
+ verbose: Whether to show detailed migration history. Defaults to False.
1523
+
1524
+ Returns:
1525
+ Current migration version or None if no migrations applied.
1526
+ """
1527
+ raise NotImplementedError
1528
+
1529
+ @abstractmethod
1530
+ def create_migration(self, message: str, file_type: str = "sql") -> "Awaitable[None] | None":
1531
+ """Create a new migration file.
1532
+
1533
+ Args:
1534
+ message: Description for the migration.
1535
+ file_type: Type of migration file to create ('sql' or 'py'). Defaults to 'sql'.
1536
+ """
1537
+ raise NotImplementedError
1538
+
1539
+ @abstractmethod
1540
+ def init_migrations(self, directory: "str | None" = None, package: bool = True) -> "Awaitable[None] | None":
1541
+ """Initialize migration directory structure.
1542
+
1543
+ Args:
1544
+ directory: Directory to initialize migrations in. Uses script_location from migration_config if not provided.
1545
+ package: Whether to create __init__.py file. Defaults to True.
1546
+ """
1547
+ raise NotImplementedError
1548
+
1549
+ @abstractmethod
1550
+ def stamp_migration(self, revision: str) -> "Awaitable[None] | None":
1551
+ """Mark database as being at a specific revision without running migrations.
1552
+
1553
+ Args:
1554
+ revision: The revision to stamp.
1555
+ """
1556
+ raise NotImplementedError
1557
+
1558
+ @abstractmethod
1559
+ def fix_migrations(
1560
+ self, dry_run: bool = False, update_database: bool = True, yes: bool = False
1561
+ ) -> "Awaitable[None] | None":
1562
+ """Convert timestamp migrations to sequential format.
1563
+
1564
+ Implements hybrid versioning workflow where development uses timestamps
1565
+ and production uses sequential numbers. Creates backup before changes
1566
+ and provides rollback on errors.
1567
+
1568
+ Args:
1569
+ dry_run: Preview changes without applying. Defaults to False.
1570
+ update_database: Update migration records in database. Defaults to True.
1571
+ yes: Skip confirmation prompt. Defaults to False.
1572
+ """
1573
+ raise NotImplementedError
1574
+
1575
+ def _allow_replica_fallback(self, _error: Exception) -> bool:
1576
+ """Return whether a failed reader checkout may fall back to this primary."""
1577
+ return True
1578
+
1579
+ def _prepare_derived_connection_config(
1580
+ self, config: dict[str, Any], overrides: Mapping[str, Any]
1581
+ ) -> dict[str, Any]:
1582
+ """Normalize merged clone options while preserving explicit overrides."""
1583
+ return config
1584
+
1585
+ def _build_replica_spec_overrides(self, spec_input: str | bool | Mapping[str, Any]) -> dict[str, Any]:
1586
+ if isinstance(spec_input, bool):
1587
+ msg = f"{type(self).__name__} does not support replicas=True shorthand; pass explicit replica endpoints or overrides"
1588
+ raise ImproperConfigurationError(msg)
1589
+ if isinstance(spec_input, str):
1590
+ key = next(
1591
+ (
1592
+ key
1593
+ for key in ("dsn", "conninfo", "uri", "url", "database")
1594
+ if isinstance(self.connection_config.get(key), str)
1595
+ ),
1596
+ "dsn",
1597
+ )
1598
+ return {"connection_config_overrides": {key: spec_input}}
1599
+ return dict(spec_input)
1600
+
1601
+ def _normalize_replica(self, item: ReplicaItemInput) -> ReplicaSpec:
1602
+ spec = item if isinstance(item, ReplicaSpec) else ReplicaSpec(item)
1603
+ config = spec.config
1604
+ if not isinstance(config, DatabaseConfigProtocol):
1605
+ config = self.derive_pool(is_replica=True, **self._build_replica_spec_overrides(config))
1606
+ if config is self or config.has_replicas or config.is_async != self.is_async:
1607
+ msg = "Replica configurations must be distinct, unnested, and use the primary execution mode"
1608
+ raise ImproperConfigurationError(msg)
1609
+ config._is_replica = True
1610
+ if config.bind_key is None or config.bind_key == self.bind_key:
1611
+ config._tenant_key = self._tenant_key
1612
+ return ReplicaSpec(config, weight=spec.weight, name=spec.name, max_staleness_seconds=spec.max_staleness_seconds)
1613
+
1614
+ def _normalize_replicas(self, replicas: "ReplicasInput | None") -> "dict[str, ReplicaGroup[Any]]":
1615
+ if not replicas:
1616
+ return {}
1617
+ if self._is_replica:
1618
+ msg = "A replica configuration cannot declare nested replicas"
1619
+ raise ImproperConfigurationError(msg)
1620
+ groups: Mapping[Any, Any]
1621
+ if isinstance(replicas, Mapping):
1622
+ grouped = all(
1623
+ isinstance(value, ReplicaGroup)
1624
+ or (isinstance(value, Sequence) and not isinstance(value, (str, bytes, Mapping)))
1625
+ for value in replicas.values()
1626
+ )
1627
+ if grouped:
1628
+ groups = replicas
1629
+ elif any(isinstance(value, ReplicaGroup) for value in replicas.values()):
1630
+ msg = "Cannot mix ReplicaGroup entries with scalar connection override keys in replicas mapping"
1631
+ raise ImproperConfigurationError(msg)
1632
+ else:
1633
+ groups = {"default": [replicas]}
1634
+ elif isinstance(replicas, ReplicaGroup) or (
1635
+ isinstance(replicas, Sequence) and not isinstance(replicas, (str, bytes))
1636
+ ):
1637
+ groups = {"default": replicas}
1638
+ else:
1639
+ groups = {"default": [replicas]}
1640
+ result: dict[str, ReplicaGroup[Any]] = {}
1641
+ for name, items in groups.items():
1642
+ if not isinstance(name, str) or not name:
1643
+ msg = "Replica group names must be nonempty strings"
1644
+ raise ImproperConfigurationError(msg)
1645
+ if isinstance(items, ReplicaGroup):
1646
+ for spec in items.specs:
1647
+ self._normalize_replica(spec)
1648
+ result[name] = items
1649
+ else:
1650
+ result[name] = ReplicaGroup([self._normalize_replica(item) for item in items], name=name)
1651
+ return result
1652
+
1653
+ def _resolve_replica_group(
1654
+ self, replica_group: str | None
1655
+ ) -> "tuple[ReplicaGroup[Any] | None, RoutingEntry | None]":
1656
+ entry = RoutingContext.get_entry(self.bind_key)
1657
+ if replica_group is None and entry is not None and (entry.mode == "primary" or entry.pinned_by_write):
1658
+ return None, entry
1659
+ effective_group = (
1660
+ replica_group if replica_group is not None else entry.replica_group if entry is not None else None
1661
+ )
1662
+ if not self._replica_groups and effective_group is None:
1663
+ return None, entry
1664
+ group_key = effective_group if effective_group is not None else "default"
1665
+ if group_key in self._replica_groups:
1666
+ return self._replica_groups[group_key], entry
1667
+ if effective_group is None and (entry is None or entry.mode != "replica"):
1668
+ return None, entry
1669
+ msg = f"Unknown replica group {group_key!r}; available groups: {sorted(self._replica_groups)}"
1670
+ raise RoutingContextError(msg)
1671
+
1672
+ def _provide_read(
1673
+ self, session: bool, args: tuple[Any, ...], kwargs: dict[str, Any], replica_group: str | None
1674
+ ) -> Any:
1675
+ group, entry = self._resolve_replica_group(replica_group)
1676
+ if group is not None:
1677
+ provider = group.provide_session if session else group.provide_connection
1678
+ return provider(
1679
+ *args,
1680
+ primary=None if entry is not None and entry.mode == "replica" else self,
1681
+ causal_token=None if entry is None else entry.causal_token,
1682
+ max_staleness_seconds=None if entry is None else entry.max_staleness_seconds,
1683
+ **kwargs,
1684
+ )
1685
+ if entry is not None and entry.mode == "replica":
1686
+ msg = "No read replica is configured for the requested bind"
1687
+ raise ReplicaUnavailableError(msg)
1688
+ receipt = _ReadSelectionReceipt()
1689
+ reused = _get_reusable_primary_session(self, session=session, kwargs=kwargs)
1690
+ if reused is not None:
1691
+ if self.is_async:
1692
+ return _ReadAsyncContext(_provide_reused_primary_async(reused, self, receipt), receipt)
1693
+ return _ReadSyncContext(_provide_reused_primary_sync(reused, self, receipt), receipt)
1694
+ provider = self.provide_session if session else self.provide_connection
1695
+ context = provider(*args, **kwargs)
1696
+ if self.is_async:
1697
+ return _ReadAsyncContext(
1698
+ self._primary_read_async(cast("AbstractAsyncContextManager[Any]", context), receipt), receipt
1699
+ )
1700
+ return _ReadSyncContext(self._primary_read_sync(cast("AbstractContextManager[Any]", context), receipt), receipt)
1701
+
1702
+ @contextmanager
1703
+ def _primary_read_sync(
1704
+ self, context: "AbstractContextManager[Any]", receipt: "_ReadSelectionReceipt"
1705
+ ) -> "Generator[Any]":
1706
+ with context as value:
1707
+ receipt.config = self
1708
+ yield value
1709
+
1710
+ @asynccontextmanager
1711
+ async def _primary_read_async(
1712
+ self, context: "AbstractAsyncContextManager[Any]", receipt: "_ReadSelectionReceipt"
1713
+ ) -> "AsyncGenerator[Any]":
1714
+ async with context as value:
1715
+ receipt.config = self
1716
+ yield value
1717
+
1718
+ def _create_replica_pools_sync(self) -> None:
1719
+ for group in self._replica_groups.values():
1720
+ group.create_pools()
1721
+ self._replica_pools_initialized = True
1722
+
1723
+ async def _create_replica_pools_async(self) -> None:
1724
+ for group in self._replica_groups.values():
1725
+ await cast("Awaitable[list[Any]]", group.create_pools())
1726
+ self._replica_pools_initialized = True
1727
+
1728
+ def _close_pools_sync(self, close_primary: Callable[[], None] | None = None) -> None:
1729
+ error: BaseException | None = None
1730
+ try:
1731
+ if close_primary is not None:
1732
+ close_primary()
1733
+ self.connection_instance = None
1734
+ except BaseException as exc:
1735
+ error = exc
1736
+ for group in self._replica_groups.values():
1737
+ try:
1738
+ group.close_pools()
1739
+ except BaseException as exc:
1740
+ error = error or exc
1741
+ self._replica_pools_initialized = False
1742
+ if error is not None:
1743
+ raise error
1744
+
1745
+ async def _close_pools_async(self, close_primary: "Callable[[], Awaitable[None]] | None" = None) -> None:
1746
+ error: BaseException | None = None
1747
+ try:
1748
+ if close_primary is not None:
1749
+ await close_primary()
1750
+ self.connection_instance = None
1751
+ except BaseException as exc:
1752
+ error = exc
1753
+ for group in self._replica_groups.values():
1754
+ try:
1755
+ await cast("Awaitable[None]", group.close_pools())
1756
+ except BaseException as exc:
1757
+ error = error or exc
1758
+ self._replica_pools_initialized = False
1759
+ if error is not None:
1760
+ raise error
1761
+
1762
+ def _has_initialized_attribute(self, attribute_name: str) -> bool:
1763
+ """Return whether a slot-backed attribute has been initialized."""
1764
+ try:
1765
+ object.__getattribute__(self, attribute_name)
1766
+ except AttributeError:
1767
+ return False
1768
+ return True
1769
+
1770
+ def _ensure_extension_migrations(self) -> None:
1771
+ """Auto-include extension migrations when extension_config has them configured.
1772
+
1773
+ Extensions with migration support are automatically included in
1774
+ ``migration_config["include_extensions"]`` based on their settings:
1775
+
1776
+ - **litestar**: Only when ``session_table`` is set (for session storage)
1777
+ - **adk**: When any adk settings are present
1778
+ - **events**: When any events settings are present
1779
+
1780
+ Any other extension is auto-included when its settings declare ``migrations_path``,
1781
+ which is how packages outside the ``sqlspec.extensions`` namespace ship migrations.
1782
+
1783
+ Use ``exclude_extensions`` to opt out of auto-inclusion.
1784
+ """
1785
+ extension_settings = cast("dict[str, Any]", self.extension_config)
1786
+ migration_config = cast("dict[str, Any]", self.migration_config)
1787
+
1788
+ for ext_name, ext_settings in extension_settings.items():
1789
+ if isinstance(ext_settings, Mapping):
1790
+ resolve_extension_migration_mode(None, dict(ext_settings), extension_name=ext_name)
1791
+
1792
+ exclude_extensions = migration_config.get("exclude_extensions", [])
1793
+ if isinstance(exclude_extensions, tuple):
1794
+ exclude_extensions = list(exclude_extensions) # pyright: ignore
1795
+
1796
+ extensions_to_add: list[str] = []
1797
+
1798
+ litestar_settings = extension_settings.get("litestar")
1799
+ if (
1800
+ isinstance(litestar_settings, Mapping)
1801
+ and "session_table" in litestar_settings
1802
+ and "litestar" not in exclude_extensions
1803
+ ):
1804
+ extensions_to_add.append("litestar")
1805
+
1806
+ adk_settings = extension_settings.get("adk")
1807
+ if adk_settings is not None and "adk" not in exclude_extensions:
1808
+ from sqlspec.extensions.adk._config_utils import _ensure_adk_store_registration
1809
+
1810
+ _ensure_adk_store_registration(self)
1811
+ extensions_to_add.append("adk")
1812
+
1813
+ events_settings = extension_settings.get("events")
1814
+ if events_settings is not None and "events" not in exclude_extensions:
1815
+ extensions_to_add.append("events")
1816
+
1817
+ for ext_name, ext_settings in extension_settings.items():
1818
+ if ext_name in extensions_to_add or ext_name in exclude_extensions:
1819
+ continue
1820
+ if isinstance(ext_settings, Mapping) and "migrations_path" in ext_settings:
1821
+ extensions_to_add.append(ext_name)
1822
+
1823
+ if not extensions_to_add:
1824
+ return
1825
+
1826
+ include_extensions = migration_config.get("include_extensions")
1827
+ include_list = list(include_extensions) if include_extensions else []
1828
+ for ext in extensions_to_add:
1829
+ if ext not in include_list:
1830
+ include_list.append(ext)
1831
+ migration_config["include_extensions"] = include_list
1832
+
1833
+ def _build_storage_capabilities(self) -> "StorageCapabilities":
1834
+ arrow_dependency_needed = self.supports_native_arrow_export or self.supports_native_arrow_import
1835
+ parquet_dependency_needed = self.supports_native_parquet_export or self.supports_native_parquet_import
1836
+
1837
+ pyarrow_dependency_ready = (
1838
+ self._dependency_available(ensure_pyarrow)
1839
+ if (arrow_dependency_needed or parquet_dependency_needed)
1840
+ else False
1841
+ )
1842
+ arrow_dependency_ready = pyarrow_dependency_ready if arrow_dependency_needed else False
1843
+ parquet_dependency_ready = pyarrow_dependency_ready if parquet_dependency_needed else False
1844
+
1845
+ capabilities: StorageCapabilities = {
1846
+ "arrow_export_enabled": bool(self.supports_native_arrow_export and arrow_dependency_ready),
1847
+ "arrow_import_enabled": bool(self.supports_native_arrow_import and arrow_dependency_ready),
1848
+ "parquet_export_enabled": bool(self.supports_native_parquet_export and parquet_dependency_ready),
1849
+ "parquet_import_enabled": bool(self.supports_native_parquet_import and parquet_dependency_ready),
1850
+ "partition_strategies": list(self.storage_partition_strategies),
1851
+ }
1852
+ if self.default_storage_profile is not None:
1853
+ capabilities["default_storage_profile"] = self.default_storage_profile
1854
+ return capabilities
1855
+
1856
+ def _init_observability(self, observability_config: "ObservabilityConfig | None" = None) -> None:
1857
+ """Initialize observability attributes for the configuration."""
1858
+
1859
+ self.observability_config = observability_config
1860
+ self._observability_runtime = None
1861
+
1862
+ def _configure_observability_extensions(self) -> None:
1863
+ """Apply extension_config hooks (otel/prometheus) to ObservabilityConfig."""
1864
+
1865
+ config_map = cast("dict[str, Any]", self.extension_config)
1866
+ if not config_map:
1867
+ return
1868
+ updated = self.observability_config
1869
+
1870
+ otel_config = cast("OpenTelemetryConfig | None", config_map.get("otel"))
1871
+ if otel_config and otel_config.get("enabled", True):
1872
+ from sqlspec.extensions import otel as otel_extension
1873
+
1874
+ updated = otel_extension.enable_tracing(
1875
+ base_config=updated,
1876
+ resource_attributes=otel_config.get("resource_attributes"),
1877
+ tracer_provider=otel_config.get("tracer_provider"),
1878
+ tracer_provider_factory=otel_config.get("tracer_provider_factory"),
1879
+ enable_spans=otel_config.get("enable_spans", True),
1880
+ )
1881
+
1882
+ prom_config = cast("PrometheusConfig | None", config_map.get("prometheus"))
1883
+ if prom_config and prom_config.get("enabled", True):
1884
+ from sqlspec.extensions import prometheus as prometheus_extension
1885
+
1886
+ label_names = tuple(prom_config.get("label_names", ("driver", "operation")))
1887
+ duration_buckets = prom_config.get("duration_buckets")
1888
+ if duration_buckets is not None:
1889
+ duration_buckets = tuple(duration_buckets)
1890
+
1891
+ updated = prometheus_extension.enable_metrics(
1892
+ base_config=updated,
1893
+ namespace=prom_config.get("namespace", "sqlspec"),
1894
+ subsystem=prom_config.get("subsystem", "driver"),
1895
+ registry=prom_config.get("registry"),
1896
+ label_names=label_names,
1897
+ duration_buckets=duration_buckets,
1898
+ )
1899
+
1900
+ if updated is not self.observability_config:
1901
+ self.observability_config = updated
1902
+
1903
+ def _attach_lifecycle_hooks(self) -> None:
1904
+ lifecycle_hooks: dict[str, list[Callable[[dict[str, Any]], None]]] = {}
1905
+
1906
+ for hook_name, context_key in DRIVER_FEATURE_LIFECYCLE_HOOKS.items():
1907
+ callback = self.driver_features.pop(hook_name, None)
1908
+ if callback is None:
1909
+ continue
1910
+ callbacks = callback if isinstance(callback, (list, tuple)) else (callback,) # pyright: ignore
1911
+ wrapped_callbacks = [self._adapt_lifecycle_hook(cb, context_key) for cb in callbacks] # pyright: ignore
1912
+ lifecycle_hooks.setdefault(hook_name, []).extend(wrapped_callbacks)
1913
+
1914
+ if not lifecycle_hooks:
1915
+ return
1916
+
1917
+ lifecycle_config = cast("LifecycleConfig", lifecycle_hooks)
1918
+ override = ObservabilityConfig(lifecycle=lifecycle_config)
1919
+ if self.observability_config is None:
1920
+ self.observability_config = override
1921
+ else:
1922
+ self.observability_config = ObservabilityConfig.merge(self.observability_config, override)
1923
+
1924
+ @staticmethod
1925
+ def _adapt_lifecycle_hook(
1926
+ callback: Callable[..., Any], context_key: str | None
1927
+ ) -> Callable[[dict[str, Any]], None]:
1928
+ try:
1929
+ hook_signature: Signature = signature(callback)
1930
+ except (TypeError, ValueError): # pragma: no cover
1931
+ hook_signature = Signature()
1932
+
1933
+ positional_params = [
1934
+ param
1935
+ for param in hook_signature.parameters.values()
1936
+ if param.kind in {param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD} and param.default is param.empty
1937
+ ]
1938
+ expects_argument = bool(positional_params)
1939
+
1940
+ return _DriverFeatureHookWrapper(callback, context_key, expects_argument)
1941
+
1942
+ def _prepare_driver(self, driver: DriverT) -> DriverT:
1943
+ """Attach observability runtime to driver instances before returning them."""
1944
+
1945
+ driver.attach_observability(self.get_observability_runtime())
1946
+ if (
1947
+ driver.statement_config is self.statement_config
1948
+ and self.driver_features.get("_statement_cache_holder") is not driver._cache_holder
1949
+ ):
1950
+ self.driver_features["_statement_cache_holder"] = driver._cache_holder
1951
+ return driver
1952
+
1953
+ @staticmethod
1954
+ def _dependency_available(checker: "Callable[[], None]") -> bool:
1955
+ try:
1956
+ checker()
1957
+ except MissingDependencyError:
1958
+ return False
1959
+ return True
1960
+
1961
+ def _ensure_migration_loader(self) -> "SQLFileLoader":
1962
+ """Get the migration SQL loader and auto-load files if needed.
1963
+
1964
+ Returns:
1965
+ SQLFileLoader instance for migration files.
1966
+ """
1967
+ loader = self._migration_loader
1968
+ if loader is not None and loader.list_files():
1969
+ return loader
1970
+ with self._migration_lock:
1971
+ loader = self._migration_loader
1972
+ if loader is None:
1973
+ loader = SQLFileLoader(runtime=self.get_observability_runtime())
1974
+ migration_path = Path(self.migration_config.get("script_location", "migrations"))
1975
+ if migration_path.exists() and not loader.list_files():
1976
+ loader.load_sql(migration_path)
1977
+ logger.debug("Auto-loaded migration SQL files from %s", migration_path)
1978
+ self._migration_loader = loader
1979
+ return loader
1980
+
1981
+ def _ensure_migration_commands(self) -> "SyncMigrationCommands[Any] | AsyncMigrationCommands[Any]":
1982
+ """Get the migration commands instance.
1983
+
1984
+ Returns:
1985
+ MigrationCommands instance for this config.
1986
+ """
1987
+ commands = self._migration_commands
1988
+ if commands is not None:
1989
+ return commands
1990
+ with self._migration_lock:
1991
+ commands = self._migration_commands
1992
+ if commands is None:
1993
+ from sqlspec.migrations.commands import create_migration_commands
1994
+
1995
+ commands = create_migration_commands(self) # pyright: ignore
1996
+ self._migration_commands = commands
1997
+ return commands
1998
+
1999
+ def _reject_unexpected_kwargs(self, kwargs: "dict[str, Any]") -> None:
2000
+ """Raise ``TypeError`` when construction receives unrecognized keyword arguments."""
2001
+ if kwargs:
2002
+ unexpected = ", ".join(sorted(kwargs))
2003
+ msg = f"{type(self).__name__}.__init__() got unexpected keyword arguments: {unexpected}"
2004
+ raise TypeError(msg)
2005
+
2006
+ def _default_tenant_strategy(self) -> "TenantStrategy":
2007
+ """Build the strategy selected by ``True`` or an adapter shorthand."""
2008
+ strategy_type = self.tenant_strategy_type
2009
+ if strategy_type is None:
2010
+ msg = f"{type(self).__name__} does not support tenant_strategy"
2011
+ raise ImproperConfigurationError(msg)
2012
+ return cast("TenantStrategy", strategy_type())
2013
+
2014
+ def _resolve_tenant_strategy(self, strategy: Any) -> "TenantStrategy | None":
2015
+ """Normalize disabled tenancy, adapter shorthands, and structural strategy instances.
2016
+
2017
+ Raises:
2018
+ ImproperConfigurationError: The shorthand or strategy is unsupported.
2019
+ """
2020
+ if strategy is None or strategy is False:
2021
+ return None
2022
+ if self.tenant_strategy_type is not None and (
2023
+ strategy is True or (isinstance(strategy, str) and strategy in self.tenant_strategy_shorthands)
2024
+ ):
2025
+ return self._default_tenant_strategy()
2026
+ if isinstance(strategy, (str, bool)):
2027
+ msg = f"{type(self).__name__} does not support tenant_strategy shorthand {strategy!r}"
2028
+ raise ImproperConfigurationError(msg)
2029
+ if callable(getattr(strategy, "checkout", None)) and callable(getattr(strategy, "checkin", None)):
2030
+ return cast("TenantStrategy", strategy)
2031
+ msg = f"{type(self).__name__} received an invalid tenant_strategy: {strategy!r}"
2032
+ raise ImproperConfigurationError(msg)
2033
+
2034
+ def _create_tenant_lease(self) -> Any:
2035
+ """Build one fail-closed lease for a connection or session acquisition.
2036
+
2037
+ Returns:
2038
+ The adapter lease, or None when no tenant strategy is configured.
2039
+
2040
+ Raises:
2041
+ ImproperConfigurationError: A strategy is configured without a lease implementation.
2042
+ """
2043
+ strategy = self.driver_features.get("tenant_strategy")
2044
+ if strategy is None:
2045
+ return None
2046
+ lease_type = self.tenant_lease_type
2047
+ if lease_type is None:
2048
+ msg = f"{type(self).__name__} has a tenant_strategy but no tenant lease implementation"
2049
+ raise ImproperConfigurationError(msg)
2050
+ lease = lease_type(self, strategy)
2051
+ lease.tenant_key = self._tenant_key
2052
+ return lease
2053
+
2054
+ def _require_leased_tenant_connection(self) -> None:
2055
+ """Reject standalone connections that would bypass tenant leases.
2056
+
2057
+ Raises:
2058
+ ImproperConfigurationError: A tenant strategy is configured.
2059
+ """
2060
+ if self.driver_features.get("tenant_strategy") is not None:
2061
+ msg = (
2062
+ f"{type(self).__name__} tenant configurations require provide_connection() or provide_session() leases"
2063
+ )
2064
+ raise ImproperConfigurationError(msg)
2065
+
2066
+ @contextmanager
2067
+ def _provide_sync_tenant_session(
2068
+ self, tenant: "str | UUID | TenantContextPayload", *args: Any, **kwargs: Any
2069
+ ) -> "Generator[DriverT]":
2070
+ """Keep an explicit tenant bound until the session finishes cleanup.
2071
+
2072
+ Yields:
2073
+ The driver session with the explicit tenant active.
2074
+ """
2075
+ if self.driver_features.get("tenant_strategy") is None:
2076
+ msg = "provide_session(tenant=...) requires a configured tenant_strategy"
2077
+ raise ImproperConfigurationError(msg)
2078
+ with TenantContext.scope(tenant):
2079
+ context = cast("AbstractContextManager[DriverT]", self.provide_session(*args, **kwargs))
2080
+ with context as session:
2081
+ yield session
2082
+
2083
+ @asynccontextmanager
2084
+ async def _provide_async_tenant_session(
2085
+ self, tenant: "str | UUID | TenantContextPayload", *args: Any, **kwargs: Any
2086
+ ) -> "AsyncGenerator[DriverT]":
2087
+ """Keep an explicit tenant bound through asynchronous session cleanup.
2088
+
2089
+ Yields:
2090
+ The driver session with the explicit tenant active.
2091
+ """
2092
+ if self.driver_features.get("tenant_strategy") is None:
2093
+ msg = "provide_session(tenant=...) requires a configured tenant_strategy"
2094
+ raise ImproperConfigurationError(msg)
2095
+ with TenantContext.scope(tenant):
2096
+ context = cast("AbstractAsyncContextManager[DriverT]", self.provide_session(*args, **kwargs))
2097
+ async with context as session:
2098
+ yield session
2099
+
2100
+ def _init_config_state(
2101
+ self,
2102
+ *,
2103
+ connection_config: "dict[str, Any] | None",
2104
+ connection_instance: "Any",
2105
+ migration_config: "dict[str, Any] | MigrationConfig | None",
2106
+ statement_config: "StatementConfig | None",
2107
+ driver_features: "dict[str, Any] | None",
2108
+ bind_key: "str | None",
2109
+ extension_config: "ExtensionConfigs | None",
2110
+ observability_config: "ObservabilityConfig | None",
2111
+ default_dialect: str,
2112
+ replicas: "ReplicasInput | None" = None,
2113
+ is_replica: bool = False,
2114
+ ) -> None:
2115
+ """Populate the configuration state shared by every base config class.
2116
+
2117
+ Assigns identity and connection attributes, initializes observability and
2118
+ migration helper caches, resolves the statement configuration against
2119
+ ``default_dialect``, seeds runtime driver features from storage
2120
+ capabilities, and attaches lifecycle and observability extensions.
2121
+ """
2122
+ self._is_replica = is_replica
2123
+ self._replica_groups = {}
2124
+ self._replica_pools_initialized = False
2125
+ self._migration_lock = threading.RLock()
2126
+ self._migration_loader = None
2127
+ self._migration_commands = None
2128
+ self.bind_key = bind_key
2129
+ self._tenant_key = self
2130
+ self.connection_instance = connection_instance
2131
+ self.connection_config = connection_config or {}
2132
+ self.extension_config = extension_config or {}
2133
+ self.migration_config = migration_config or {}
2134
+ self._init_observability(observability_config)
2135
+ self.statement_config = statement_config or build_default_statement_config(default_dialect)
2136
+ self._storage_capabilities = None
2137
+ strategy = self._resolve_tenant_strategy((driver_features or {}).get("tenant_strategy"))
2138
+ if driver_features is not None and "tenant_strategy" in driver_features:
2139
+ driver_features = {**driver_features, "tenant_strategy": strategy}
2140
+ if strategy is not None:
2141
+ if not self.supports_tenant_strategy:
2142
+ msg = f"{type(self).__name__} does not support tenant_strategy"
2143
+ raise ImproperConfigurationError(msg)
2144
+ if any(
2145
+ iscoroutinefunction(method) is not self.is_async for method in (strategy.checkout, strategy.checkin)
2146
+ ):
2147
+ msg = f"{type(self).__name__} tenant_strategy must match its async execution mode ({self.is_async})"
2148
+ raise ImproperConfigurationError(msg)
2149
+ if "tenant_session_baseline" in (driver_features or {}) and not self.supports_tenant_session_baseline:
2150
+ msg = f"{type(self).__name__} does not support tenant_session_baseline"
2151
+ raise ImproperConfigurationError(msg)
2152
+ self.driver_features = seed_runtime_driver_features(driver_features, self.storage_capabilities())
2153
+ self.driver_features["_statement_cache_holder"] = StatementCacheHolder(
2154
+ self.statement_config, resolve_statement_cache_size(self.driver_features)
2155
+ )
2156
+ self._attach_lifecycle_hooks()
2157
+ self._configure_observability_extensions()
2158
+ self._replica_groups = self._normalize_replicas(replicas)
2159
+
2160
+ def _provide_connection_impl(self, *args: Any, **kwargs: Any) -> Any:
2161
+ """Build the connection context manager shared by pooled configs."""
2162
+ return self._connection_context_class(self)
2163
+
2164
+ def _provide_session_impl(
2165
+ self, *args: Any, statement_config: "StatementConfig | None" = None, **kwargs: Any
2166
+ ) -> Any:
2167
+ """Build the session context manager shared by pooled configs."""
2168
+ handler = self._session_factory_class(self)
2169
+ return self._session_context_class(
2170
+ acquire_connection=handler.acquire_connection,
2171
+ release_connection=handler.release_connection,
2172
+ statement_config=statement_config or self.statement_config or self._default_statement_config,
2173
+ driver_features=self.driver_features,
2174
+ prepare_driver=self._prepare_driver,
2175
+ )
2176
+
2177
+
2178
+ class _SyncMigrationMixin:
2179
+ """Shared sync migration convenience methods."""
2180
+
2181
+ __slots__ = ()
2182
+
2183
+ def migrate_up(
2184
+ self: Any,
2185
+ revision: str = "head",
2186
+ allow_missing: bool = False,
2187
+ auto_sync: bool = True,
2188
+ dry_run: bool = False,
2189
+ *,
2190
+ use_logger: bool = False,
2191
+ echo: bool | None = None,
2192
+ summary_only: bool | None = None,
2193
+ ) -> None:
2194
+ """Apply database migrations up to specified revision."""
2195
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2196
+ commands.upgrade(
2197
+ revision, allow_missing, auto_sync, dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only
2198
+ )
2199
+
2200
+ def migrate_down(
2201
+ self: Any,
2202
+ revision: str = "-1",
2203
+ *,
2204
+ dry_run: bool = False,
2205
+ use_logger: bool = False,
2206
+ echo: bool | None = None,
2207
+ summary_only: bool | None = None,
2208
+ ) -> None:
2209
+ """Apply database migrations down to specified revision."""
2210
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2211
+ commands.downgrade(revision, dry_run=dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only)
2212
+
2213
+ def get_current_migration(self: Any, verbose: bool = False) -> "str | None":
2214
+ """Get the current migration version."""
2215
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2216
+ return commands.current(verbose=verbose)
2217
+
2218
+ def create_migration(self: Any, message: str, file_type: str = "sql") -> None:
2219
+ """Create a new migration file."""
2220
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2221
+ commands.revision(message, file_type)
2222
+
2223
+ def init_migrations(self: Any, directory: "str | None" = None, package: bool = True) -> None:
2224
+ """Initialize migration directory structure."""
2225
+ if directory is None:
2226
+ migration_config = self.migration_config or {}
2227
+ directory = str(migration_config.get("script_location") or "migrations")
2228
+
2229
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2230
+ commands.init(directory, package)
2231
+
2232
+ def stamp_migration(self: Any, revision: str) -> None:
2233
+ """Mark database as being at a specific revision without running migrations."""
2234
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2235
+ commands.stamp(revision)
2236
+
2237
+ def fix_migrations(self: Any, dry_run: bool = False, update_database: bool = True, yes: bool = False) -> None:
2238
+ """Convert timestamp migrations to sequential format."""
2239
+ commands = cast("SyncMigrationCommands[Any]", self._ensure_migration_commands())
2240
+ commands.fix(dry_run, update_database, yes)
2241
+
2242
+
2243
+ class _AsyncMigrationMixin:
2244
+ """Shared async migration convenience methods."""
2245
+
2246
+ __slots__ = ()
2247
+
2248
+ async def migrate_up(
2249
+ self: Any,
2250
+ revision: str = "head",
2251
+ allow_missing: bool = False,
2252
+ auto_sync: bool = True,
2253
+ dry_run: bool = False,
2254
+ *,
2255
+ use_logger: bool = False,
2256
+ echo: bool | None = None,
2257
+ summary_only: bool | None = None,
2258
+ ) -> None:
2259
+ """Apply database migrations up to specified revision."""
2260
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2261
+ await commands.upgrade(
2262
+ revision, allow_missing, auto_sync, dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only
2263
+ )
2264
+
2265
+ async def migrate_down(
2266
+ self: Any,
2267
+ revision: str = "-1",
2268
+ *,
2269
+ dry_run: bool = False,
2270
+ use_logger: bool = False,
2271
+ echo: bool | None = None,
2272
+ summary_only: bool | None = None,
2273
+ ) -> None:
2274
+ """Apply database migrations down to specified revision."""
2275
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2276
+ await commands.downgrade(revision, dry_run=dry_run, use_logger=use_logger, echo=echo, summary_only=summary_only)
2277
+
2278
+ async def get_current_migration(self: Any, verbose: bool = False) -> "str | None":
2279
+ """Get the current migration version."""
2280
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2281
+ return await commands.current(verbose=verbose)
2282
+
2283
+ async def create_migration(self: Any, message: str, file_type: str = "sql") -> None:
2284
+ """Create a new migration file."""
2285
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2286
+ await commands.revision(message, file_type)
2287
+
2288
+ async def init_migrations(self: Any, directory: "str | None" = None, package: bool = True) -> None:
2289
+ """Initialize migration directory structure."""
2290
+ if directory is None:
2291
+ migration_config = self.migration_config or {}
2292
+ directory = str(migration_config.get("script_location") or "migrations")
2293
+
2294
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2295
+ await commands.init(directory, package)
2296
+
2297
+ async def stamp_migration(self: Any, revision: str) -> None:
2298
+ """Mark database as being at a specific revision without running migrations."""
2299
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2300
+ await commands.stamp(revision)
2301
+
2302
+ async def fix_migrations(self: Any, dry_run: bool = False, update_database: bool = True, yes: bool = False) -> None:
2303
+ """Convert timestamp migrations to sequential format."""
2304
+ commands = cast("AsyncMigrationCommands[Any]", self._ensure_migration_commands())
2305
+ await commands.fix(dry_run, update_database, yes)
2306
+
2307
+
2308
+ class NoPoolSyncConfig(_SyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, None, DriverT]):
2309
+ """Base class for sync database configurations that do not implement a pool."""
2310
+
2311
+ __slots__ = ()
2312
+ is_async: "ClassVar[bool]" = False
2313
+ supports_connection_pooling: "ClassVar[bool]" = False
2314
+ migration_tracker_type: "ClassVar[type[Any]]" = SyncMigrationTracker
2315
+
2316
+ def __init__(
2317
+ self,
2318
+ *,
2319
+ connection_config: dict[str, Any] | None = None,
2320
+ connection_instance: "Any" = None,
2321
+ migration_config: "dict[str, Any] | MigrationConfig | None" = None,
2322
+ statement_config: "StatementConfig | None" = None,
2323
+ driver_features: "dict[str, Any] | None" = None,
2324
+ bind_key: "str | None" = None,
2325
+ extension_config: "ExtensionConfigs | None" = None,
2326
+ observability_config: "ObservabilityConfig | None" = None,
2327
+ replicas: "ReplicasInput | None" = None,
2328
+ is_replica: bool = False,
2329
+ **kwargs: Any,
2330
+ ) -> None:
2331
+ self._reject_unexpected_kwargs(kwargs)
2332
+ self._init_config_state(
2333
+ connection_config=connection_config,
2334
+ connection_instance=connection_instance,
2335
+ migration_config=migration_config,
2336
+ statement_config=statement_config,
2337
+ driver_features=driver_features,
2338
+ bind_key=bind_key,
2339
+ extension_config=extension_config,
2340
+ observability_config=observability_config,
2341
+ replicas=replicas,
2342
+ is_replica=is_replica,
2343
+ default_dialect="sqlite",
2344
+ )
2345
+
2346
+ def create_connection(self) -> ConnectionT:
2347
+ """Create a database connection."""
2348
+ raise NotImplementedError
2349
+
2350
+ def provide_connection(self, *args: Any, **kwargs: Any) -> "AbstractContextManager[ConnectionT]":
2351
+ """Provide a database connection context manager."""
2352
+ raise NotImplementedError
2353
+
2354
+ def provide_replica_connection(
2355
+ self, *args: Any, replica_group: str | None = None, **kwargs: Any
2356
+ ) -> "AbstractContextManager[ConnectionT]":
2357
+ """Provide a replica connection with this config's execution mode."""
2358
+ return cast(
2359
+ "AbstractContextManager[ConnectionT]",
2360
+ super().provide_replica_connection(*args, replica_group=replica_group, **kwargs),
2361
+ )
2362
+
2363
+ def provide_replica_session(
2364
+ self,
2365
+ *args: Any,
2366
+ replica_group: str | None = None,
2367
+ statement_config: "StatementConfig | None" = None,
2368
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2369
+ bypass_tenant: bool = False,
2370
+ **kwargs: Any,
2371
+ ) -> "AbstractContextManager[DriverT]":
2372
+ """Provide a replica session with this config's execution mode."""
2373
+ return cast(
2374
+ "AbstractContextManager[DriverT]",
2375
+ super().provide_replica_session(
2376
+ *args,
2377
+ replica_group=replica_group,
2378
+ statement_config=statement_config,
2379
+ tenant=tenant,
2380
+ bypass_tenant=bypass_tenant,
2381
+ **kwargs,
2382
+ ),
2383
+ )
2384
+
2385
+ def provide_routing_session(
2386
+ self: "NoPoolSyncConfig[ConnectionT, SyncDriverT]",
2387
+ *args: Any,
2388
+ replica_group: str | None = None,
2389
+ statement_config: "StatementConfig | None" = None,
2390
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2391
+ bypass_tenant: bool = False,
2392
+ **kwargs: Any,
2393
+ ) -> "SyncRoutingSession[SyncDriverT]":
2394
+ """Construct a lazy session that routes each operation safely."""
2395
+ from sqlspec.driver._routing import SyncRoutingSession
2396
+
2397
+ return SyncRoutingSession(
2398
+ self,
2399
+ *args,
2400
+ replica_group=replica_group,
2401
+ statement_config=statement_config,
2402
+ tenant=tenant,
2403
+ bypass_tenant=bypass_tenant,
2404
+ **kwargs,
2405
+ )
2406
+
2407
+ def provide_session(
2408
+ self,
2409
+ *args: Any,
2410
+ statement_config: "StatementConfig | None" = None,
2411
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2412
+ bypass_tenant: bool = False,
2413
+ **kwargs: Any,
2414
+ ) -> "AbstractContextManager[DriverT]":
2415
+ """Provide a database session context manager."""
2416
+ raise NotImplementedError
2417
+
2418
+ def create_pool(self) -> None:
2419
+ if not self._replica_pools_initialized:
2420
+ self._create_replica_pools_sync()
2421
+
2422
+ def close_pool(self) -> None:
2423
+ self._close_pools_sync()
2424
+
2425
+ def provide_pool(self, *args: Any, **kwargs: Any) -> None:
2426
+ return None
2427
+
2428
+
2429
+ class NoPoolAsyncConfig(_AsyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, None, DriverT]):
2430
+ """Base class for async database configurations that do not implement a pool."""
2431
+
2432
+ __slots__ = ()
2433
+ is_async: "ClassVar[bool]" = True
2434
+ supports_connection_pooling: "ClassVar[bool]" = False
2435
+ migration_tracker_type: "ClassVar[type[Any]]" = AsyncMigrationTracker
2436
+
2437
+ def __init__(
2438
+ self,
2439
+ *,
2440
+ connection_config: "dict[str, Any] | None" = None,
2441
+ connection_instance: "Any" = None,
2442
+ migration_config: "dict[str, Any] | MigrationConfig | None" = None,
2443
+ statement_config: "StatementConfig | None" = None,
2444
+ driver_features: "dict[str, Any] | None" = None,
2445
+ bind_key: "str | None" = None,
2446
+ extension_config: "ExtensionConfigs | None" = None,
2447
+ observability_config: "ObservabilityConfig | None" = None,
2448
+ replicas: "ReplicasInput | None" = None,
2449
+ is_replica: bool = False,
2450
+ **kwargs: Any,
2451
+ ) -> None:
2452
+ self._reject_unexpected_kwargs(kwargs)
2453
+ self._init_config_state(
2454
+ connection_config=connection_config,
2455
+ connection_instance=connection_instance,
2456
+ migration_config=migration_config,
2457
+ statement_config=statement_config,
2458
+ driver_features=driver_features,
2459
+ bind_key=bind_key,
2460
+ extension_config=extension_config,
2461
+ observability_config=observability_config,
2462
+ replicas=replicas,
2463
+ is_replica=is_replica,
2464
+ default_dialect="sqlite",
2465
+ )
2466
+
2467
+ async def create_connection(self) -> ConnectionT:
2468
+ """Create a database connection."""
2469
+ raise NotImplementedError
2470
+
2471
+ def provide_connection(self, *args: Any, **kwargs: Any) -> "AbstractAsyncContextManager[ConnectionT]":
2472
+ """Provide a database connection context manager."""
2473
+ raise NotImplementedError
2474
+
2475
+ def provide_replica_connection(
2476
+ self, *args: Any, replica_group: str | None = None, **kwargs: Any
2477
+ ) -> "AbstractAsyncContextManager[ConnectionT]":
2478
+ """Provide a replica connection with this config's execution mode."""
2479
+ return cast(
2480
+ "AbstractAsyncContextManager[ConnectionT]",
2481
+ super().provide_replica_connection(*args, replica_group=replica_group, **kwargs),
2482
+ )
2483
+
2484
+ def provide_replica_session(
2485
+ self,
2486
+ *args: Any,
2487
+ replica_group: str | None = None,
2488
+ statement_config: "StatementConfig | None" = None,
2489
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2490
+ bypass_tenant: bool = False,
2491
+ **kwargs: Any,
2492
+ ) -> "AbstractAsyncContextManager[DriverT]":
2493
+ """Provide a replica session with this config's execution mode."""
2494
+ return cast(
2495
+ "AbstractAsyncContextManager[DriverT]",
2496
+ super().provide_replica_session(
2497
+ *args,
2498
+ replica_group=replica_group,
2499
+ statement_config=statement_config,
2500
+ tenant=tenant,
2501
+ bypass_tenant=bypass_tenant,
2502
+ **kwargs,
2503
+ ),
2504
+ )
2505
+
2506
+ def provide_routing_session(
2507
+ self: "NoPoolAsyncConfig[ConnectionT, AsyncDriverT]",
2508
+ *args: Any,
2509
+ replica_group: str | None = None,
2510
+ statement_config: "StatementConfig | None" = None,
2511
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2512
+ bypass_tenant: bool = False,
2513
+ **kwargs: Any,
2514
+ ) -> "AsyncRoutingSession[AsyncDriverT]":
2515
+ """Construct a lazy session that routes each operation safely."""
2516
+ from sqlspec.driver._routing import AsyncRoutingSession
2517
+
2518
+ return AsyncRoutingSession(
2519
+ self,
2520
+ *args,
2521
+ replica_group=replica_group,
2522
+ statement_config=statement_config,
2523
+ tenant=tenant,
2524
+ bypass_tenant=bypass_tenant,
2525
+ **kwargs,
2526
+ )
2527
+
2528
+ def provide_session(
2529
+ self,
2530
+ *args: Any,
2531
+ statement_config: "StatementConfig | None" = None,
2532
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2533
+ bypass_tenant: bool = False,
2534
+ **kwargs: Any,
2535
+ ) -> "AbstractAsyncContextManager[DriverT]":
2536
+ """Provide a database session context manager."""
2537
+ raise NotImplementedError
2538
+
2539
+ async def create_pool(self) -> None:
2540
+ if not self._replica_pools_initialized:
2541
+ await self._create_replica_pools_async()
2542
+
2543
+ async def close_pool(self) -> None:
2544
+ await self._close_pools_async()
2545
+
2546
+ def provide_pool(self, *args: Any, **kwargs: Any) -> None:
2547
+ return None
2548
+
2549
+
2550
+ class SyncDatabaseConfig(_SyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, PoolT, DriverT]):
2551
+ """Base class for sync database configurations with connection pooling."""
2552
+
2553
+ __slots__ = ("_pool_lock",)
2554
+ is_async: "ClassVar[bool]" = False
2555
+ supports_connection_pooling: "ClassVar[bool]" = True
2556
+ migration_tracker_type: "ClassVar[type[Any]]" = SyncMigrationTracker
2557
+
2558
+ def __init__(
2559
+ self,
2560
+ *,
2561
+ connection_config: "dict[str, Any] | None" = None,
2562
+ connection_instance: "PoolT | None" = None,
2563
+ migration_config: "dict[str, Any] | MigrationConfig | None" = None,
2564
+ statement_config: "StatementConfig | None" = None,
2565
+ driver_features: "dict[str, Any] | None" = None,
2566
+ bind_key: "str | None" = None,
2567
+ extension_config: "ExtensionConfigs | None" = None,
2568
+ observability_config: "ObservabilityConfig | None" = None,
2569
+ replicas: "ReplicasInput | None" = None,
2570
+ is_replica: bool = False,
2571
+ **kwargs: Any,
2572
+ ) -> None:
2573
+ self._reject_unexpected_kwargs(kwargs)
2574
+ self._init_config_state(
2575
+ connection_config=connection_config,
2576
+ connection_instance=connection_instance,
2577
+ migration_config=migration_config,
2578
+ statement_config=statement_config,
2579
+ driver_features=driver_features,
2580
+ bind_key=bind_key,
2581
+ extension_config=extension_config,
2582
+ observability_config=observability_config,
2583
+ replicas=replicas,
2584
+ is_replica=is_replica,
2585
+ default_dialect="postgres",
2586
+ )
2587
+ self._pool_lock = threading.Lock()
2588
+
2589
+ def create_pool(self) -> PoolT:
2590
+ """Create and return the connection pool.
2591
+
2592
+ Returns:
2593
+ The created pool.
2594
+ """
2595
+ existing_pool = self.connection_instance
2596
+ if existing_pool is not None:
2597
+ if not self._replica_pools_initialized:
2598
+ self._create_replica_pools_sync()
2599
+ return existing_pool
2600
+
2601
+ created_pool = create_sync_pool(
2602
+ None,
2603
+ self._pool_lock,
2604
+ lambda: self.connection_instance,
2605
+ self._create_pool,
2606
+ self.get_observability_runtime().emit_pool_create_sync,
2607
+ )
2608
+ self.connection_instance = created_pool
2609
+ self._create_replica_pools_sync()
2610
+ return cast("PoolT", created_pool)
2611
+
2612
+ def close_pool(self) -> None:
2613
+ """Close the primary and every replica, preserving the first error."""
2614
+ runtime = self.get_observability_runtime()
2615
+ self._close_pools_sync(
2616
+ lambda: close_sync_pool(
2617
+ self.connection_instance,
2618
+ self._close_pool,
2619
+ runtime.emit_pool_destroy_sync,
2620
+ runtime.emit_pool_destroying_sync,
2621
+ )
2622
+ )
2623
+
2624
+ def provide_pool(self, *args: Any, **kwargs: Any) -> PoolT:
2625
+ """Provide pool instance."""
2626
+ return self.create_pool()
2627
+
2628
+ def create_connection(self) -> ConnectionT:
2629
+ """Create a database connection."""
2630
+ raise NotImplementedError
2631
+
2632
+ def provide_connection(self, *args: Any, **kwargs: Any) -> "AbstractContextManager[ConnectionT]":
2633
+ """Provide a database connection context manager."""
2634
+ return cast("AbstractContextManager[ConnectionT]", self._provide_connection_impl(*args, **kwargs))
2635
+
2636
+ def provide_replica_connection(
2637
+ self, *args: Any, replica_group: str | None = None, **kwargs: Any
2638
+ ) -> "AbstractContextManager[ConnectionT]":
2639
+ """Provide a replica connection with this config's execution mode."""
2640
+ return cast(
2641
+ "AbstractContextManager[ConnectionT]",
2642
+ super().provide_replica_connection(*args, replica_group=replica_group, **kwargs),
2643
+ )
2644
+
2645
+ def provide_replica_session(
2646
+ self,
2647
+ *args: Any,
2648
+ replica_group: str | None = None,
2649
+ statement_config: "StatementConfig | None" = None,
2650
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2651
+ bypass_tenant: bool = False,
2652
+ **kwargs: Any,
2653
+ ) -> "AbstractContextManager[DriverT]":
2654
+ """Provide a replica session with this config's execution mode."""
2655
+ return cast(
2656
+ "AbstractContextManager[DriverT]",
2657
+ super().provide_replica_session(
2658
+ *args,
2659
+ replica_group=replica_group,
2660
+ statement_config=statement_config,
2661
+ tenant=tenant,
2662
+ bypass_tenant=bypass_tenant,
2663
+ **kwargs,
2664
+ ),
2665
+ )
2666
+
2667
+ def provide_routing_session(
2668
+ self: "SyncDatabaseConfig[ConnectionT, PoolT, SyncDriverT]",
2669
+ *args: Any,
2670
+ replica_group: str | None = None,
2671
+ statement_config: "StatementConfig | None" = None,
2672
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2673
+ bypass_tenant: bool = False,
2674
+ **kwargs: Any,
2675
+ ) -> "SyncRoutingSession[SyncDriverT]":
2676
+ """Construct a lazy session that routes each operation safely."""
2677
+ from sqlspec.driver._routing import SyncRoutingSession
2678
+
2679
+ return SyncRoutingSession(
2680
+ self,
2681
+ *args,
2682
+ replica_group=replica_group,
2683
+ statement_config=statement_config,
2684
+ tenant=tenant,
2685
+ bypass_tenant=bypass_tenant,
2686
+ **kwargs,
2687
+ )
2688
+
2689
+ def provide_session(
2690
+ self,
2691
+ *args: Any,
2692
+ statement_config: "StatementConfig | None" = None,
2693
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2694
+ bypass_tenant: bool = False,
2695
+ **kwargs: Any,
2696
+ ) -> "AbstractContextManager[DriverT]":
2697
+ """Provide a session, optionally binding or bypassing a tenant until cleanup completes.
2698
+
2699
+ Args:
2700
+ *args: Adapter-specific session arguments.
2701
+ statement_config: Statement configuration override.
2702
+ tenant: Tenant identity or payload; None inherits the current scope.
2703
+ bypass_tenant: Explicitly bypass tenant setup for this session.
2704
+ **kwargs: Adapter-specific session options.
2705
+
2706
+ Returns:
2707
+ A driver session context manager.
2708
+ """
2709
+ if bypass_tenant:
2710
+ if tenant is not None:
2711
+ msg = "provide_session() cannot combine tenant with bypass_tenant=True"
2712
+ raise ImproperConfigurationError(msg)
2713
+ return self._provide_sync_tenant_session(
2714
+ TenantContextPayload.bypass(), *args, statement_config=statement_config, **kwargs
2715
+ )
2716
+ if tenant is not None:
2717
+ return self._provide_sync_tenant_session(tenant, *args, statement_config=statement_config, **kwargs)
2718
+ return cast(
2719
+ "AbstractContextManager[DriverT]",
2720
+ self._provide_session_impl(*args, statement_config=statement_config, **kwargs),
2721
+ )
2722
+
2723
+ @abstractmethod
2724
+ def _create_pool(self) -> PoolT:
2725
+ """Actual pool creation implementation."""
2726
+ raise NotImplementedError
2727
+
2728
+ @abstractmethod
2729
+ def _close_pool(self) -> None:
2730
+ """Actual pool destruction implementation."""
2731
+ raise NotImplementedError
2732
+
2733
+
2734
+ class AsyncDatabaseConfig(_AsyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, PoolT, DriverT]):
2735
+ """Base class for async database configurations with connection pooling."""
2736
+
2737
+ __slots__ = ("_pool_lock",)
2738
+ is_async: "ClassVar[bool]" = True
2739
+ supports_connection_pooling: "ClassVar[bool]" = True
2740
+ migration_tracker_type: "ClassVar[type[Any]]" = AsyncMigrationTracker
2741
+
2742
+ def __init__(
2743
+ self,
2744
+ *,
2745
+ connection_config: "dict[str, Any] | None" = None,
2746
+ connection_instance: "PoolT | None" = None,
2747
+ migration_config: "dict[str, Any] | MigrationConfig | None" = None,
2748
+ statement_config: "StatementConfig | None" = None,
2749
+ driver_features: "dict[str, Any] | None" = None,
2750
+ bind_key: "str | None" = None,
2751
+ extension_config: "ExtensionConfigs | None" = None,
2752
+ observability_config: "ObservabilityConfig | None" = None,
2753
+ replicas: "ReplicasInput | None" = None,
2754
+ is_replica: bool = False,
2755
+ **kwargs: Any,
2756
+ ) -> None:
2757
+ self._reject_unexpected_kwargs(kwargs)
2758
+ self._init_config_state(
2759
+ connection_config=connection_config,
2760
+ connection_instance=connection_instance,
2761
+ migration_config=migration_config,
2762
+ statement_config=statement_config,
2763
+ driver_features=driver_features,
2764
+ bind_key=bind_key,
2765
+ extension_config=extension_config,
2766
+ observability_config=observability_config,
2767
+ replicas=replicas,
2768
+ is_replica=is_replica,
2769
+ default_dialect="postgres",
2770
+ )
2771
+ self._pool_lock = asyncio.Lock()
2772
+
2773
+ async def create_pool(self) -> PoolT:
2774
+ """Create and return the connection pool.
2775
+
2776
+ Returns:
2777
+ The created pool.
2778
+ """
2779
+ existing_pool = self.connection_instance
2780
+ if existing_pool is not None:
2781
+ if not self._replica_pools_initialized:
2782
+ await self._create_replica_pools_async()
2783
+ return existing_pool
2784
+
2785
+ created_pool = await create_async_pool(
2786
+ None,
2787
+ self._pool_lock,
2788
+ lambda: self.connection_instance,
2789
+ self._create_pool,
2790
+ self.get_observability_runtime().emit_pool_create_async,
2791
+ )
2792
+ self.connection_instance = created_pool
2793
+ await self._create_replica_pools_async()
2794
+ return cast("PoolT", created_pool)
2795
+
2796
+ async def close_pool(self) -> None:
2797
+ """Close the primary and every replica, preserving the first error."""
2798
+ runtime = self.get_observability_runtime()
2799
+ await self._close_pools_async(
2800
+ lambda: close_async_pool(
2801
+ self.connection_instance,
2802
+ self._close_pool,
2803
+ runtime.emit_pool_destroy_async,
2804
+ runtime.emit_pool_destroying_async,
2805
+ )
2806
+ )
2807
+
2808
+ async def provide_pool(self, *args: Any, **kwargs: Any) -> PoolT:
2809
+ """Provide pool instance."""
2810
+ return await self.create_pool()
2811
+
2812
+ async def create_connection(self) -> ConnectionT:
2813
+ """Create a database connection."""
2814
+ raise NotImplementedError
2815
+
2816
+ def provide_connection(self, *args: Any, **kwargs: Any) -> "AbstractAsyncContextManager[ConnectionT]":
2817
+ """Provide a database connection context manager."""
2818
+ return cast("AbstractAsyncContextManager[ConnectionT]", self._provide_connection_impl(*args, **kwargs))
2819
+
2820
+ def provide_replica_connection(
2821
+ self, *args: Any, replica_group: str | None = None, **kwargs: Any
2822
+ ) -> "AbstractAsyncContextManager[ConnectionT]":
2823
+ """Provide a replica connection with this config's execution mode."""
2824
+ return cast(
2825
+ "AbstractAsyncContextManager[ConnectionT]",
2826
+ super().provide_replica_connection(*args, replica_group=replica_group, **kwargs),
2827
+ )
2828
+
2829
+ def provide_replica_session(
2830
+ self,
2831
+ *args: Any,
2832
+ replica_group: str | None = None,
2833
+ statement_config: "StatementConfig | None" = None,
2834
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2835
+ bypass_tenant: bool = False,
2836
+ **kwargs: Any,
2837
+ ) -> "AbstractAsyncContextManager[DriverT]":
2838
+ """Provide a replica session with this config's execution mode."""
2839
+ return cast(
2840
+ "AbstractAsyncContextManager[DriverT]",
2841
+ super().provide_replica_session(
2842
+ *args,
2843
+ replica_group=replica_group,
2844
+ statement_config=statement_config,
2845
+ tenant=tenant,
2846
+ bypass_tenant=bypass_tenant,
2847
+ **kwargs,
2848
+ ),
2849
+ )
2850
+
2851
+ def provide_routing_session(
2852
+ self: "AsyncDatabaseConfig[ConnectionT, PoolT, AsyncDriverT]",
2853
+ *args: Any,
2854
+ replica_group: str | None = None,
2855
+ statement_config: "StatementConfig | None" = None,
2856
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2857
+ bypass_tenant: bool = False,
2858
+ **kwargs: Any,
2859
+ ) -> "AsyncRoutingSession[AsyncDriverT]":
2860
+ """Construct a lazy session that routes each operation safely."""
2861
+ from sqlspec.driver._routing import AsyncRoutingSession
2862
+
2863
+ return AsyncRoutingSession(
2864
+ self,
2865
+ *args,
2866
+ replica_group=replica_group,
2867
+ statement_config=statement_config,
2868
+ tenant=tenant,
2869
+ bypass_tenant=bypass_tenant,
2870
+ **kwargs,
2871
+ )
2872
+
2873
+ def provide_session(
2874
+ self,
2875
+ *args: Any,
2876
+ statement_config: "StatementConfig | None" = None,
2877
+ tenant: "str | UUID | TenantContextPayload | None" = None,
2878
+ bypass_tenant: bool = False,
2879
+ **kwargs: Any,
2880
+ ) -> "AbstractAsyncContextManager[DriverT]":
2881
+ """Provide a session, optionally binding or bypassing a tenant until cleanup completes.
2882
+
2883
+ Args:
2884
+ *args: Adapter-specific session arguments.
2885
+ statement_config: Statement configuration override.
2886
+ tenant: Tenant identity or payload; None inherits the current scope.
2887
+ bypass_tenant: Explicitly bypass tenant setup for this session.
2888
+ **kwargs: Adapter-specific session options.
2889
+
2890
+ Returns:
2891
+ A driver session context manager.
2892
+ """
2893
+ if bypass_tenant:
2894
+ if tenant is not None:
2895
+ msg = "provide_session() cannot combine tenant with bypass_tenant=True"
2896
+ raise ImproperConfigurationError(msg)
2897
+ return self._provide_async_tenant_session(
2898
+ TenantContextPayload.bypass(), *args, statement_config=statement_config, **kwargs
2899
+ )
2900
+ if tenant is not None:
2901
+ return self._provide_async_tenant_session(tenant, *args, statement_config=statement_config, **kwargs)
2902
+ return cast(
2903
+ "AbstractAsyncContextManager[DriverT]",
2904
+ self._provide_session_impl(*args, statement_config=statement_config, **kwargs),
2905
+ )
2906
+
2907
+ @abstractmethod
2908
+ async def _create_pool(self) -> PoolT:
2909
+ """Actual async pool creation implementation."""
2910
+ raise NotImplementedError
2911
+
2912
+ @abstractmethod
2913
+ async def _close_pool(self) -> None:
2914
+ """Actual async pool destruction implementation."""
2915
+ raise NotImplementedError
2916
+
2917
+
2918
+ class _ReadSelectionReceipt:
2919
+ __slots__ = ("config",)
2920
+
2921
+ def __init__(self) -> None:
2922
+ self.config: DatabaseConfigProtocol[Any, Any, Any] | None = None
2923
+
2924
+
2925
+ class _ReadSyncContext(Generic[ConfigT]):
2926
+ __slots__ = ("_context", "_selection_receipt")
2927
+
2928
+ def __init__(self, context: "AbstractContextManager[Any]", receipt: _ReadSelectionReceipt) -> None:
2929
+ self._context = context
2930
+ self._selection_receipt = receipt
2931
+
2932
+ def __enter__(self) -> Any:
2933
+ return self._context.__enter__()
2934
+
2935
+ def __exit__(self, *args: Any) -> Any:
2936
+ return self._context.__exit__(*args)
2937
+
2938
+
2939
+ class _ReadAsyncContext(Generic[ConfigT]):
2940
+ __slots__ = ("_context", "_selection_receipt")
2941
+
2942
+ def __init__(self, context: "AbstractAsyncContextManager[Any]", receipt: _ReadSelectionReceipt) -> None:
2943
+ self._context = context
2944
+ self._selection_receipt = receipt
2945
+
2946
+ async def __aenter__(self) -> Any:
2947
+ return await self._context.__aenter__()
2948
+
2949
+ async def __aexit__(self, *args: Any) -> Any:
2950
+ return await self._context.__aexit__(*args)
2951
+
2952
+
2953
+ class ReplicaGroup(Generic[ConfigT]):
2954
+ """Managed homogeneous replica pools with checkout-only failover."""
2955
+
2956
+ __slots__ = (
2957
+ "_breaker",
2958
+ "_causal_validator",
2959
+ "_configs",
2960
+ "_fallback_to_primary",
2961
+ "_is_async",
2962
+ "_name",
2963
+ "_selector",
2964
+ "_specs",
2965
+ )
2966
+
2967
+ def __init__(
2968
+ self,
2969
+ configs: "Sequence[ConfigT | ReplicaSpec]",
2970
+ *,
2971
+ strategy: SelectionStrategy | ReplicaSelector = "round_robin",
2972
+ fallback_to_primary: bool = True,
2973
+ failure_threshold: int = 3,
2974
+ recovery_seconds: float = 10.0,
2975
+ name: str = "default",
2976
+ causal_validator: "Callable[[Any, str], bool | Awaitable[bool]] | None" = None,
2977
+ clock: Callable[[], float] | None = None,
2978
+ ) -> None:
2979
+ """Configure replica selection, recovery, and optional causal validation."""
2980
+ if not configs or not name:
2981
+ msg = "Read replica groups need a name and at least one replica"
2982
+ raise ImproperConfigurationError(msg)
2983
+ self._specs = tuple(item if isinstance(item, ReplicaSpec) else ReplicaSpec(item) for item in configs)
2984
+ if any(not isinstance(spec.config, DatabaseConfigProtocol) for spec in self._specs):
2985
+ msg = "Read replica groups require database configurations"
2986
+ raise ImproperConfigurationError(msg)
2987
+ self._configs = tuple(cast("ConfigT", spec.config) for spec in self._specs)
2988
+ self._is_async = self._configs[0].is_async
2989
+ if any(config.is_async != self._is_async for config in self._configs):
2990
+ msg = "Read replica groups cannot mix sync and async configurations"
2991
+ raise ImproperConfigurationError(msg)
2992
+ self._name = name
2993
+ self._fallback_to_primary = fallback_to_primary
2994
+ self._causal_validator = causal_validator
2995
+ self._selector = build_selector(strategy, self._specs)
2996
+ self._breaker = ReplicaHealthBreaker(
2997
+ len(self._configs),
2998
+ failure_threshold=failure_threshold,
2999
+ recovery_seconds=recovery_seconds,
3000
+ clock=clock or time.monotonic,
3001
+ )
3002
+
3003
+ @property
3004
+ def configs(self) -> tuple[ConfigT, ...]:
3005
+ """Return the group's configuration instances."""
3006
+ return self._configs
3007
+
3008
+ @property
3009
+ def specs(self) -> tuple[ReplicaSpec, ...]:
3010
+ """Return weighted descriptors in their stable index order."""
3011
+ return self._specs
3012
+
3013
+ @property
3014
+ def breaker(self) -> ReplicaHealthBreaker:
3015
+ """Return passive checkout health state."""
3016
+ return self._breaker
3017
+
3018
+ @property
3019
+ def selector(self) -> ReplicaSelector:
3020
+ """Return the configured candidate selector."""
3021
+ return self._selector
3022
+
3023
+ @property
3024
+ def fallback_to_primary(self) -> bool:
3025
+ """Whether exhaustion permits primary checkout."""
3026
+ return self._fallback_to_primary
3027
+
3028
+ @property
3029
+ def name(self) -> str:
3030
+ """Return the group name."""
3031
+ return self._name
3032
+
3033
+ @property
3034
+ def is_async(self) -> bool:
3035
+ """Whether all configurations use asynchronous providers."""
3036
+ return self._is_async
3037
+
3038
+ def create_pools(self) -> "list[Any] | Awaitable[list[Any]]":
3039
+ """Create every replica pool, isolating transient connection failures per replica."""
3040
+ if self._is_async:
3041
+ return self._create_async_pools()
3042
+ pools: list[Any] = []
3043
+ for idx, config in enumerate(self._configs):
3044
+ try:
3045
+ pools.append(config.create_pool())
3046
+ except (DatabaseConnectionError, OperationalError, OSError) as exc:
3047
+ self._breaker.record_failure(idx)
3048
+ logger.warning(
3049
+ "Replica pool initialization failed for %r[%d]; continuing with primary and lazy retry: %s",
3050
+ self._name,
3051
+ idx,
3052
+ exc,
3053
+ )
3054
+ return pools
3055
+
3056
+ def close_pools(self) -> "Awaitable[None] | None":
3057
+ """Close every pool before propagating the first close error."""
3058
+ if self._is_async:
3059
+ return self._close_async_pools()
3060
+ error: BaseException | None = None
3061
+ for config in self._configs:
3062
+ try:
3063
+ config.close_pool()
3064
+ except BaseException as exc:
3065
+ error = error or exc
3066
+ if error is not None:
3067
+ raise error
3068
+ return None
3069
+
3070
+ def attach_observability(self, registry_config: ObservabilityConfig | None) -> None:
3071
+ """Attach the registry settings to each replica's own runtime."""
3072
+ for config in self._configs:
3073
+ config.attach_observability(registry_config)
3074
+
3075
+ def provide_connection(
3076
+ self,
3077
+ *args: Any,
3078
+ primary: "DatabaseConfigProtocol[Any, Any, Any] | None" = None,
3079
+ causal_token: str | None = None,
3080
+ max_staleness_seconds: float | None = None,
3081
+ **kwargs: Any,
3082
+ ) -> Any:
3083
+ """Acquire a connection from one healthy candidate without replaying callers."""
3084
+ return self._provide(False, args, kwargs, primary, causal_token, max_staleness_seconds)
3085
+
3086
+ def provide_session(
3087
+ self,
3088
+ *args: Any,
3089
+ primary: "DatabaseConfigProtocol[Any, Any, Any] | None" = None,
3090
+ statement_config: "StatementConfig | None" = None,
3091
+ tenant: "str | UUID | TenantContextPayload | None" = None,
3092
+ bypass_tenant: bool = False,
3093
+ causal_token: str | None = None,
3094
+ max_staleness_seconds: float | None = None,
3095
+ **kwargs: Any,
3096
+ ) -> Any:
3097
+ """Acquire a tenant-aware session with failover limited to checkout."""
3098
+ kwargs.update(statement_config=statement_config, tenant=tenant, bypass_tenant=bypass_tenant)
3099
+ return self._provide(True, args, kwargs, primary, causal_token, max_staleness_seconds)
3100
+
3101
+ async def _create_async_pools(self) -> list[Any]:
3102
+ pools: list[Any] = []
3103
+ for idx, config in enumerate(self._configs):
3104
+ try:
3105
+ pools.append(await cast("Awaitable[Any]", config.create_pool()))
3106
+ except (DatabaseConnectionError, OperationalError, OSError) as exc:
3107
+ self._breaker.record_failure(idx)
3108
+ logger.warning(
3109
+ "Replica pool initialization failed for %r[%d]; continuing with primary and lazy retry: %s",
3110
+ self._name,
3111
+ idx,
3112
+ exc,
3113
+ )
3114
+ return pools
3115
+
3116
+ async def _close_async_pools(self) -> None:
3117
+ error: BaseException | None = None
3118
+ for config in self._configs:
3119
+ try:
3120
+ await cast("Awaitable[None]", config.close_pool())
3121
+ except BaseException as exc:
3122
+ error = error or exc
3123
+ if error is not None:
3124
+ raise error
3125
+
3126
+ def _provide(
3127
+ self,
3128
+ session: bool,
3129
+ args: tuple[Any, ...],
3130
+ kwargs: dict[str, Any],
3131
+ primary: "DatabaseConfigProtocol[Any, Any, Any] | None",
3132
+ causal_token: str | None,
3133
+ staleness: float | None,
3134
+ ) -> Any:
3135
+ receipt = _ReadSelectionReceipt()
3136
+ if self._is_async:
3137
+ return _ReadAsyncContext(
3138
+ self._provide_async(session, args, kwargs, primary, causal_token, staleness, receipt), receipt
3139
+ )
3140
+ return _ReadSyncContext(
3141
+ self._provide_sync(session, args, kwargs, primary, causal_token, staleness, receipt), receipt
3142
+ )
3143
+
3144
+ def _is_caught_up_sync(self, value: Any, causal_token: str | None) -> bool:
3145
+ """Return whether the replica has caught up to the causal token.
3146
+
3147
+ Raises:
3148
+ ImproperConfigurationError: If the causal validator is asynchronous.
3149
+ """
3150
+ if causal_token is None or self._causal_validator is None:
3151
+ return True
3152
+ result = self._causal_validator(value, causal_token)
3153
+ if isawaitable(result):
3154
+ if callable(getattr(result, "close", None)):
3155
+ cast("Any", result).close()
3156
+ msg = "An async causal validator requires an async replica group"
3157
+ raise ImproperConfigurationError(msg)
3158
+ return result
3159
+
3160
+ async def _is_caught_up_async(self, value: Any, causal_token: str | None) -> bool:
3161
+ if causal_token is None or self._causal_validator is None:
3162
+ return True
3163
+ result = self._causal_validator(value, causal_token)
3164
+ if isawaitable(result):
3165
+ return await result
3166
+ return result
3167
+
3168
+ @contextmanager
3169
+ def _provide_sync(
3170
+ self,
3171
+ session: bool,
3172
+ args: tuple[Any, ...],
3173
+ kwargs: dict[str, Any],
3174
+ primary: "DatabaseConfigProtocol[Any, Any, Any] | None",
3175
+ causal_token: str | None,
3176
+ staleness: float | None,
3177
+ receipt: _ReadSelectionReceipt,
3178
+ ) -> "Generator[Any]":
3179
+ last_error: Exception | None = None
3180
+ for index in self._selector.select_order(self._breaker, max_staleness_seconds=staleness):
3181
+ if not self._breaker.try_acquire_probe(index):
3182
+ continue
3183
+ stack = ExitStack()
3184
+ config = self._configs[index]
3185
+ provider: Callable[..., Any] = config.provide_session if session else config.provide_connection
3186
+ try:
3187
+ value = stack.enter_context(cast("AbstractContextManager[Any]", provider(*args, **kwargs)))
3188
+ except (DatabaseConnectionError, OperationalError, OSError, TimeoutError) as exc:
3189
+ stack.__exit__(*sys.exc_info())
3190
+ self._breaker.record_failure(index)
3191
+ last_error = exc
3192
+ continue
3193
+ except BaseException:
3194
+ self._breaker.release_probe(index)
3195
+ stack.__exit__(*sys.exc_info())
3196
+ raise
3197
+ try:
3198
+ caught_up = self._is_caught_up_sync(value, causal_token)
3199
+ except (DatabaseConnectionError, OperationalError, OSError, TimeoutError) as exc:
3200
+ try:
3201
+ stack.__exit__(*sys.exc_info())
3202
+ finally:
3203
+ self._breaker.record_failure(index)
3204
+ last_error = exc
3205
+ continue
3206
+ except BaseException:
3207
+ self._breaker.release_probe(index)
3208
+ stack.__exit__(*sys.exc_info())
3209
+ raise
3210
+ if not caught_up:
3211
+ self._breaker.release_probe(index)
3212
+ stack.close()
3213
+ continue
3214
+ self._breaker.record_success(index)
3215
+ receipt.config = config
3216
+ with stack:
3217
+ yield value
3218
+ return
3219
+ if self._fallback_to_primary and primary is not None:
3220
+ if last_error is not None and not primary._allow_replica_fallback(last_error):
3221
+ raise last_error
3222
+ reused = _get_reusable_primary_session(primary, session=session, kwargs=kwargs)
3223
+ if reused is not None:
3224
+ receipt.config = primary
3225
+ yield reused
3226
+ return
3227
+ provider = primary.provide_session if session else primary.provide_connection
3228
+ with cast("AbstractContextManager[Any]", provider(*args, **kwargs)) as value:
3229
+ receipt.config = primary
3230
+ yield value
3231
+ return
3232
+ msg = f"No healthy read replica available in group {self._name!r}"
3233
+ raise ReplicaUnavailableError(msg) from last_error
3234
+
3235
+ @asynccontextmanager
3236
+ async def _provide_async(
3237
+ self,
3238
+ session: bool,
3239
+ args: tuple[Any, ...],
3240
+ kwargs: dict[str, Any],
3241
+ primary: "DatabaseConfigProtocol[Any, Any, Any] | None",
3242
+ causal_token: str | None,
3243
+ staleness: float | None,
3244
+ receipt: _ReadSelectionReceipt,
3245
+ ) -> "AsyncGenerator[Any]":
3246
+ last_error: Exception | None = None
3247
+ for index in self._selector.select_order(self._breaker, max_staleness_seconds=staleness):
3248
+ if not self._breaker.try_acquire_probe(index):
3249
+ continue
3250
+ stack = AsyncExitStack()
3251
+ config = self._configs[index]
3252
+ provider: Callable[..., Any] = config.provide_session if session else config.provide_connection
3253
+ try:
3254
+ value = await stack.enter_async_context(
3255
+ cast("AbstractAsyncContextManager[Any]", provider(*args, **kwargs))
3256
+ )
3257
+ except (DatabaseConnectionError, OperationalError, OSError, TimeoutError) as exc:
3258
+ await stack.__aexit__(*sys.exc_info())
3259
+ self._breaker.record_failure(index)
3260
+ last_error = exc
3261
+ continue
3262
+ except BaseException:
3263
+ self._breaker.release_probe(index)
3264
+ await stack.__aexit__(*sys.exc_info())
3265
+ raise
3266
+ try:
3267
+ caught_up = await self._is_caught_up_async(value, causal_token)
3268
+ except (DatabaseConnectionError, OperationalError, OSError, TimeoutError) as exc:
3269
+ try:
3270
+ await stack.__aexit__(*sys.exc_info())
3271
+ finally:
3272
+ self._breaker.record_failure(index)
3273
+ last_error = exc
3274
+ continue
3275
+ except BaseException:
3276
+ self._breaker.release_probe(index)
3277
+ await stack.__aexit__(*sys.exc_info())
3278
+ raise
3279
+ if not caught_up:
3280
+ self._breaker.release_probe(index)
3281
+ await stack.aclose()
3282
+ continue
3283
+ self._breaker.record_success(index)
3284
+ receipt.config = config
3285
+ async with stack:
3286
+ yield value
3287
+ return
3288
+ if self._fallback_to_primary and primary is not None:
3289
+ if last_error is not None and not primary._allow_replica_fallback(last_error):
3290
+ raise last_error
3291
+ reused = _get_reusable_primary_session(primary, session=session, kwargs=kwargs)
3292
+ if reused is not None:
3293
+ receipt.config = primary
3294
+ yield reused
3295
+ return
3296
+ provider = primary.provide_session if session else primary.provide_connection
3297
+ async with cast("AbstractAsyncContextManager[Any]", provider(*args, **kwargs)) as value:
3298
+ receipt.config = primary
3299
+ yield value
3300
+ return
3301
+ msg = f"No healthy read replica available in group {self._name!r}"
3302
+ raise ReplicaUnavailableError(msg) from last_error
3303
+
3304
+
3305
+ class _DriverFeatureHookWrapper:
3306
+ __slots__ = ("_callback", "_context_key", "_expects_argument")
3307
+
3308
+ def __init__(self, callback: "Callable[..., Any]", context_key: "str | None", expects_argument: bool) -> None:
3309
+ self._callback = callback
3310
+ self._context_key = context_key
3311
+ self._expects_argument = expects_argument
3312
+
3313
+ def __call__(self, context: "dict[str, Any]") -> None:
3314
+ if not self._expects_argument:
3315
+ self._callback()
3316
+ return
3317
+ if self._context_key is None:
3318
+ self._callback(context)
3319
+ return
3320
+ self._callback(context.get(self._context_key))
3321
+
3322
+
3323
+ def _report_unknown_keys(
3324
+ mapping: "Mapping[str, Any]", valid_keys: "frozenset[str]", prefix: str, scope: str
3325
+ ) -> "list[str]":
3326
+ """Describe keys a configuration scope does not declare.
3327
+
3328
+ Args:
3329
+ mapping: Mapping to check.
3330
+ valid_keys: Keys the scope accepts.
3331
+ prefix: Dotted path prepended to each reported key.
3332
+ scope: Scope name used in the valid-key summary, empty for the top level.
3333
+
3334
+ Returns:
3335
+ Report lines, empty when every key is recognized.
3336
+ """
3337
+ unknown = sorted(key for key in mapping if key not in valid_keys)
3338
+ if not unknown:
3339
+ return []
3340
+
3341
+ lines = []
3342
+ for key in unknown:
3343
+ suggestions = get_close_matches(key, valid_keys, n=1, cutoff=0.6)
3344
+ hint = f" Did you mean {suggestions[0]!r}?" if suggestions else ""
3345
+ lines.append(f"Unknown migration_config key {f'{prefix}{key}'!r}.{hint}")
3346
+ lines.append(f"Valid {scope}keys: {', '.join(sorted(valid_keys))}.")
3347
+ return lines
3348
+
3349
+
3350
+ def _report_template_keys(templates: Any) -> "list[str]":
3351
+ """Describe unrecognized keys nested under ``templates``.
3352
+
3353
+ Args:
3354
+ templates: Value configured for the ``templates`` key.
3355
+
3356
+ Returns:
3357
+ Report lines, empty when the overrides are recognized.
3358
+ """
3359
+ if not isinstance(templates, Mapping):
3360
+ return [f"migration_config key 'templates' must be a mapping, got {type(templates).__name__}."]
3361
+
3362
+ lines = _report_unknown_keys(templates, MIGRATION_TEMPLATES_KEYS, "templates.", "'templates' ")
3363
+ for section, fragment_keys in _TEMPLATE_FRAGMENT_KEYS.items():
3364
+ overrides = templates.get(section)
3365
+ if overrides is None:
3366
+ continue
3367
+ path = f"templates.{section}"
3368
+ if not isinstance(overrides, Mapping):
3369
+ lines.append(f"migration_config key '{path}' must be a mapping, got {type(overrides).__name__}.")
3370
+ continue
3371
+ lines.extend(_report_unknown_keys(overrides, fragment_keys, f"{path}.", f"'{path}' "))
3372
+ return lines
3373
+
3374
+
3375
+ def _get_reusable_primary_session(
3376
+ primary: "DatabaseConfigProtocol[Any, Any, Any]", *, session: bool, kwargs: Mapping[str, Any]
3377
+ ) -> Any:
3378
+ if (
3379
+ not session
3380
+ or kwargs.get("read_only_session")
3381
+ or kwargs.get("follower_reads")
3382
+ or primary.driver_features.get("read_only_session")
3383
+ or primary.driver_features.get("enable_follower_reads")
3384
+ ):
3385
+ return None
3386
+ return RoutingContext._current_reusable_primary_session(primary)
3387
+
3388
+
3389
+ @contextmanager
3390
+ def _provide_reused_primary_sync(
3391
+ value: Any, config: "DatabaseConfigProtocol[Any, Any, Any]", receipt: _ReadSelectionReceipt
3392
+ ) -> "Generator[Any]":
3393
+ receipt.config = config
3394
+ yield value
3395
+
3396
+
3397
+ @asynccontextmanager
3398
+ async def _provide_reused_primary_async(
3399
+ value: Any, config: "DatabaseConfigProtocol[Any, Any, Any]", receipt: _ReadSelectionReceipt
3400
+ ) -> "AsyncGenerator[Any]":
3401
+ receipt.config = config
3402
+ yield value