sqlspec 0.72.0__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1144) hide show
  1. 6b29784d6b1cafc66758__mypyc.cp315-win_amd64.pyd +0 -0
  2. sqlspec/__init__.py +381 -0
  3. sqlspec/__main__.py +14 -0
  4. sqlspec/__metadata__.py +14 -0
  5. sqlspec/_typing.py +775 -0
  6. sqlspec/adapters/__init__.py +3 -0
  7. sqlspec/adapters/adbc/__init__.py +16 -0
  8. sqlspec/adapters/adbc/_typing.py +221 -0
  9. sqlspec/adapters/adbc/adk/__init__.py +11 -0
  10. sqlspec/adapters/adbc/adk/store.py +4101 -0
  11. sqlspec/adapters/adbc/config.py +843 -0
  12. sqlspec/adapters/adbc/core.cp315-win_amd64.pyd +0 -0
  13. sqlspec/adapters/adbc/core.py +3209 -0
  14. sqlspec/adapters/adbc/data_dictionary.py +1448 -0
  15. sqlspec/adapters/adbc/driver.cp315-win_amd64.pyd +0 -0
  16. sqlspec/adapters/adbc/driver.py +1400 -0
  17. sqlspec/adapters/adbc/events/__init__.py +5 -0
  18. sqlspec/adapters/adbc/events/store.py +384 -0
  19. sqlspec/adapters/adbc/litestar/__init__.py +5 -0
  20. sqlspec/adapters/adbc/litestar/store.py +962 -0
  21. sqlspec/adapters/adbc/pool.cp315-win_amd64.pyd +0 -0
  22. sqlspec/adapters/adbc/pool.py +242 -0
  23. sqlspec/adapters/adbc/type_converter.cp315-win_amd64.pyd +0 -0
  24. sqlspec/adapters/adbc/type_converter.py +117 -0
  25. sqlspec/adapters/aiomysql/__init__.py +25 -0
  26. sqlspec/adapters/aiomysql/_typing.py +134 -0
  27. sqlspec/adapters/aiomysql/adk/__init__.py +5 -0
  28. sqlspec/adapters/aiomysql/adk/store.py +1542 -0
  29. sqlspec/adapters/aiomysql/config.py +634 -0
  30. sqlspec/adapters/aiomysql/core.cp315-win_amd64.pyd +0 -0
  31. sqlspec/adapters/aiomysql/core.py +922 -0
  32. sqlspec/adapters/aiomysql/data_dictionary.py +16 -0
  33. sqlspec/adapters/aiomysql/driver.cp315-win_amd64.pyd +0 -0
  34. sqlspec/adapters/aiomysql/driver.py +494 -0
  35. sqlspec/adapters/aiomysql/events/__init__.py +5 -0
  36. sqlspec/adapters/aiomysql/events/store.py +72 -0
  37. sqlspec/adapters/aiomysql/litestar/__init__.py +5 -0
  38. sqlspec/adapters/aiomysql/litestar/store.py +345 -0
  39. sqlspec/adapters/aiosqlite/__init__.py +43 -0
  40. sqlspec/adapters/aiosqlite/_typing.py +75 -0
  41. sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
  42. sqlspec/adapters/aiosqlite/adk/store.py +1546 -0
  43. sqlspec/adapters/aiosqlite/config.py +607 -0
  44. sqlspec/adapters/aiosqlite/core.cp315-win_amd64.pyd +0 -0
  45. sqlspec/adapters/aiosqlite/core.py +1155 -0
  46. sqlspec/adapters/aiosqlite/data_dictionary.py +343 -0
  47. sqlspec/adapters/aiosqlite/driver.cp315-win_amd64.pyd +0 -0
  48. sqlspec/adapters/aiosqlite/driver.py +559 -0
  49. sqlspec/adapters/aiosqlite/events/__init__.py +5 -0
  50. sqlspec/adapters/aiosqlite/events/store.py +54 -0
  51. sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
  52. sqlspec/adapters/aiosqlite/litestar/store.py +315 -0
  53. sqlspec/adapters/aiosqlite/pool.cp315-win_amd64.pyd +0 -0
  54. sqlspec/adapters/aiosqlite/pool.py +1323 -0
  55. sqlspec/adapters/aiosqlite/type_converter.cp315-win_amd64.pyd +0 -0
  56. sqlspec/adapters/aiosqlite/type_converter.py +114 -0
  57. sqlspec/adapters/arrow_odbc/__init__.py +32 -0
  58. sqlspec/adapters/arrow_odbc/_typing.py +131 -0
  59. sqlspec/adapters/arrow_odbc/adk/__init__.py +5 -0
  60. sqlspec/adapters/arrow_odbc/adk/store.py +1671 -0
  61. sqlspec/adapters/arrow_odbc/config.py +446 -0
  62. sqlspec/adapters/arrow_odbc/core.cp315-win_amd64.pyd +0 -0
  63. sqlspec/adapters/arrow_odbc/core.py +795 -0
  64. sqlspec/adapters/arrow_odbc/data_dictionary.py +345 -0
  65. sqlspec/adapters/arrow_odbc/driver.cp315-win_amd64.pyd +0 -0
  66. sqlspec/adapters/arrow_odbc/driver.py +885 -0
  67. sqlspec/adapters/arrow_odbc/events/__init__.py +5 -0
  68. sqlspec/adapters/arrow_odbc/events/store.py +114 -0
  69. sqlspec/adapters/arrow_odbc/litestar/__init__.py +5 -0
  70. sqlspec/adapters/arrow_odbc/litestar/store.py +682 -0
  71. sqlspec/adapters/arrow_odbc/type_converter.cp315-win_amd64.pyd +0 -0
  72. sqlspec/adapters/arrow_odbc/type_converter.py +95 -0
  73. sqlspec/adapters/asyncmy/__init__.py +27 -0
  74. sqlspec/adapters/asyncmy/_typing.py +215 -0
  75. sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
  76. sqlspec/adapters/asyncmy/adk/store.py +1544 -0
  77. sqlspec/adapters/asyncmy/config.py +707 -0
  78. sqlspec/adapters/asyncmy/core.cp315-win_amd64.pyd +0 -0
  79. sqlspec/adapters/asyncmy/core.py +917 -0
  80. sqlspec/adapters/asyncmy/data_dictionary.py +16 -0
  81. sqlspec/adapters/asyncmy/driver.cp315-win_amd64.pyd +0 -0
  82. sqlspec/adapters/asyncmy/driver.py +529 -0
  83. sqlspec/adapters/asyncmy/events/__init__.py +5 -0
  84. sqlspec/adapters/asyncmy/events/store.py +72 -0
  85. sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
  86. sqlspec/adapters/asyncmy/litestar/store.py +348 -0
  87. sqlspec/adapters/asyncpg/__init__.py +28 -0
  88. sqlspec/adapters/asyncpg/_typing.py +113 -0
  89. sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
  90. sqlspec/adapters/asyncpg/adk/store.py +1145 -0
  91. sqlspec/adapters/asyncpg/config.py +903 -0
  92. sqlspec/adapters/asyncpg/core.cp315-win_amd64.pyd +0 -0
  93. sqlspec/adapters/asyncpg/core.py +797 -0
  94. sqlspec/adapters/asyncpg/data_dictionary.py +417 -0
  95. sqlspec/adapters/asyncpg/driver.cp315-win_amd64.pyd +0 -0
  96. sqlspec/adapters/asyncpg/driver.py +927 -0
  97. sqlspec/adapters/asyncpg/events/__init__.py +6 -0
  98. sqlspec/adapters/asyncpg/events/_hub.cp315-win_amd64.pyd +0 -0
  99. sqlspec/adapters/asyncpg/events/_hub.py +279 -0
  100. sqlspec/adapters/asyncpg/events/backend.py +410 -0
  101. sqlspec/adapters/asyncpg/events/store.py +57 -0
  102. sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
  103. sqlspec/adapters/asyncpg/litestar/store.py +278 -0
  104. sqlspec/adapters/asyncpg/tenant.cp315-win_amd64.pyd +0 -0
  105. sqlspec/adapters/asyncpg/tenant.py +140 -0
  106. sqlspec/adapters/bigquery/__init__.py +23 -0
  107. sqlspec/adapters/bigquery/_typing.py +184 -0
  108. sqlspec/adapters/bigquery/adk/__init__.py +5 -0
  109. sqlspec/adapters/bigquery/adk/store.py +920 -0
  110. sqlspec/adapters/bigquery/config.py +631 -0
  111. sqlspec/adapters/bigquery/core.cp315-win_amd64.pyd +0 -0
  112. sqlspec/adapters/bigquery/core.py +1433 -0
  113. sqlspec/adapters/bigquery/data_dictionary.py +502 -0
  114. sqlspec/adapters/bigquery/driver.cp315-win_amd64.pyd +0 -0
  115. sqlspec/adapters/bigquery/driver.py +1266 -0
  116. sqlspec/adapters/bigquery/events/__init__.py +5 -0
  117. sqlspec/adapters/bigquery/events/store.py +158 -0
  118. sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
  119. sqlspec/adapters/bigquery/litestar/store.py +359 -0
  120. sqlspec/adapters/cockroach_asyncpg/__init__.py +32 -0
  121. sqlspec/adapters/cockroach_asyncpg/_typing.py +54 -0
  122. sqlspec/adapters/cockroach_asyncpg/adk/__init__.py +9 -0
  123. sqlspec/adapters/cockroach_asyncpg/adk/store.py +1096 -0
  124. sqlspec/adapters/cockroach_asyncpg/config.py +653 -0
  125. sqlspec/adapters/cockroach_asyncpg/core.cp315-win_amd64.pyd +0 -0
  126. sqlspec/adapters/cockroach_asyncpg/core.py +835 -0
  127. sqlspec/adapters/cockroach_asyncpg/data_dictionary.py +371 -0
  128. sqlspec/adapters/cockroach_asyncpg/driver.cp315-win_amd64.pyd +0 -0
  129. sqlspec/adapters/cockroach_asyncpg/driver.py +438 -0
  130. sqlspec/adapters/cockroach_asyncpg/events/__init__.py +5 -0
  131. sqlspec/adapters/cockroach_asyncpg/events/store.py +20 -0
  132. sqlspec/adapters/cockroach_asyncpg/litestar/__init__.py +5 -0
  133. sqlspec/adapters/cockroach_asyncpg/litestar/store.py +203 -0
  134. sqlspec/adapters/cockroach_asyncpg/tenant.cp315-win_amd64.pyd +0 -0
  135. sqlspec/adapters/cockroach_asyncpg/tenant.py +143 -0
  136. sqlspec/adapters/cockroach_psycopg/__init__.py +46 -0
  137. sqlspec/adapters/cockroach_psycopg/_typing.py +271 -0
  138. sqlspec/adapters/cockroach_psycopg/adk/__init__.py +17 -0
  139. sqlspec/adapters/cockroach_psycopg/adk/store.py +2274 -0
  140. sqlspec/adapters/cockroach_psycopg/config.py +1285 -0
  141. sqlspec/adapters/cockroach_psycopg/core.cp315-win_amd64.pyd +0 -0
  142. sqlspec/adapters/cockroach_psycopg/core.py +667 -0
  143. sqlspec/adapters/cockroach_psycopg/data_dictionary.py +622 -0
  144. sqlspec/adapters/cockroach_psycopg/driver.cp315-win_amd64.pyd +0 -0
  145. sqlspec/adapters/cockroach_psycopg/driver.py +864 -0
  146. sqlspec/adapters/cockroach_psycopg/events/__init__.py +8 -0
  147. sqlspec/adapters/cockroach_psycopg/events/store.py +34 -0
  148. sqlspec/adapters/cockroach_psycopg/litestar/__init__.py +9 -0
  149. sqlspec/adapters/cockroach_psycopg/litestar/store.py +413 -0
  150. sqlspec/adapters/cockroach_psycopg/tenant.cp315-win_amd64.pyd +0 -0
  151. sqlspec/adapters/cockroach_psycopg/tenant.py +222 -0
  152. sqlspec/adapters/db2/__init__.py +34 -0
  153. sqlspec/adapters/db2/_typing.py +357 -0
  154. sqlspec/adapters/db2/adk/__init__.py +10 -0
  155. sqlspec/adapters/db2/adk/store.py +1950 -0
  156. sqlspec/adapters/db2/config.py +550 -0
  157. sqlspec/adapters/db2/core.cp315-win_amd64.pyd +0 -0
  158. sqlspec/adapters/db2/core.py +1021 -0
  159. sqlspec/adapters/db2/data_dictionary.py +493 -0
  160. sqlspec/adapters/db2/driver.cp315-win_amd64.pyd +0 -0
  161. sqlspec/adapters/db2/driver.py +898 -0
  162. sqlspec/adapters/db2/events/__init__.py +5 -0
  163. sqlspec/adapters/db2/events/store.py +77 -0
  164. sqlspec/adapters/db2/litestar/__init__.py +5 -0
  165. sqlspec/adapters/db2/litestar/store.py +519 -0
  166. sqlspec/adapters/db2/migrations.py +221 -0
  167. sqlspec/adapters/db2/pool.cp315-win_amd64.pyd +0 -0
  168. sqlspec/adapters/db2/pool.py +876 -0
  169. sqlspec/adapters/db2/tenant.cp315-win_amd64.pyd +0 -0
  170. sqlspec/adapters/db2/tenant.py +292 -0
  171. sqlspec/adapters/duckdb/__init__.py +30 -0
  172. sqlspec/adapters/duckdb/_typing.py +182 -0
  173. sqlspec/adapters/duckdb/adk/__init__.py +10 -0
  174. sqlspec/adapters/duckdb/adk/store.py +1672 -0
  175. sqlspec/adapters/duckdb/config.py +506 -0
  176. sqlspec/adapters/duckdb/core.cp315-win_amd64.pyd +0 -0
  177. sqlspec/adapters/duckdb/core.py +1299 -0
  178. sqlspec/adapters/duckdb/data_dictionary.py +553 -0
  179. sqlspec/adapters/duckdb/driver.cp315-win_amd64.pyd +0 -0
  180. sqlspec/adapters/duckdb/driver.py +1214 -0
  181. sqlspec/adapters/duckdb/events/__init__.py +5 -0
  182. sqlspec/adapters/duckdb/events/store.py +38 -0
  183. sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
  184. sqlspec/adapters/duckdb/litestar/store.py +313 -0
  185. sqlspec/adapters/duckdb/pool.cp315-win_amd64.pyd +0 -0
  186. sqlspec/adapters/duckdb/pool.py +1121 -0
  187. sqlspec/adapters/mssql_python/__init__.py +42 -0
  188. sqlspec/adapters/mssql_python/_typing.py +135 -0
  189. sqlspec/adapters/mssql_python/adk/__init__.py +5 -0
  190. sqlspec/adapters/mssql_python/adk/store.py +1278 -0
  191. sqlspec/adapters/mssql_python/config.py +455 -0
  192. sqlspec/adapters/mssql_python/core.cp315-win_amd64.pyd +0 -0
  193. sqlspec/adapters/mssql_python/core.py +862 -0
  194. sqlspec/adapters/mssql_python/data_dictionary.py +417 -0
  195. sqlspec/adapters/mssql_python/driver.cp315-win_amd64.pyd +0 -0
  196. sqlspec/adapters/mssql_python/driver.py +772 -0
  197. sqlspec/adapters/mssql_python/events/__init__.py +5 -0
  198. sqlspec/adapters/mssql_python/events/store.py +46 -0
  199. sqlspec/adapters/mssql_python/litestar/__init__.py +5 -0
  200. sqlspec/adapters/mssql_python/litestar/store.py +355 -0
  201. sqlspec/adapters/mssql_python/migrations.py +162 -0
  202. sqlspec/adapters/mssql_python/pool.cp315-win_amd64.pyd +0 -0
  203. sqlspec/adapters/mssql_python/pool.py +165 -0
  204. sqlspec/adapters/mssql_python/tenant.cp315-win_amd64.pyd +0 -0
  205. sqlspec/adapters/mssql_python/tenant.py +74 -0
  206. sqlspec/adapters/mssql_python/type_converter.cp315-win_amd64.pyd +0 -0
  207. sqlspec/adapters/mssql_python/type_converter.py +98 -0
  208. sqlspec/adapters/mysqlconnector/__init__.py +47 -0
  209. sqlspec/adapters/mysqlconnector/_typing.py +205 -0
  210. sqlspec/adapters/mysqlconnector/adk/__init__.py +17 -0
  211. sqlspec/adapters/mysqlconnector/adk/store.py +2503 -0
  212. sqlspec/adapters/mysqlconnector/config.py +925 -0
  213. sqlspec/adapters/mysqlconnector/core.cp315-win_amd64.pyd +0 -0
  214. sqlspec/adapters/mysqlconnector/core.py +1075 -0
  215. sqlspec/adapters/mysqlconnector/data_dictionary.py +23 -0
  216. sqlspec/adapters/mysqlconnector/driver.cp315-win_amd64.pyd +0 -0
  217. sqlspec/adapters/mysqlconnector/driver.py +702 -0
  218. sqlspec/adapters/mysqlconnector/events/__init__.py +8 -0
  219. sqlspec/adapters/mysqlconnector/events/store.py +89 -0
  220. sqlspec/adapters/mysqlconnector/litestar/__init__.py +9 -0
  221. sqlspec/adapters/mysqlconnector/litestar/store.py +524 -0
  222. sqlspec/adapters/oracledb/__init__.py +159 -0
  223. sqlspec/adapters/oracledb/_json_handlers.cp315-win_amd64.pyd +0 -0
  224. sqlspec/adapters/oracledb/_json_handlers.py +208 -0
  225. sqlspec/adapters/oracledb/_param_types.cp315-win_amd64.pyd +0 -0
  226. sqlspec/adapters/oracledb/_param_types.py +65 -0
  227. sqlspec/adapters/oracledb/_plugins.py +137 -0
  228. sqlspec/adapters/oracledb/_storage.cp315-win_amd64.pyd +0 -0
  229. sqlspec/adapters/oracledb/_storage.py +138 -0
  230. sqlspec/adapters/oracledb/_typing.py +468 -0
  231. sqlspec/adapters/oracledb/_uuid_handlers.cp315-win_amd64.pyd +0 -0
  232. sqlspec/adapters/oracledb/_uuid_handlers.py +143 -0
  233. sqlspec/adapters/oracledb/_vector_handlers.cp315-win_amd64.pyd +0 -0
  234. sqlspec/adapters/oracledb/_vector_handlers.py +252 -0
  235. sqlspec/adapters/oracledb/adk/__init__.py +27 -0
  236. sqlspec/adapters/oracledb/adk/store.py +4031 -0
  237. sqlspec/adapters/oracledb/config.py +1785 -0
  238. sqlspec/adapters/oracledb/core.cp315-win_amd64.pyd +0 -0
  239. sqlspec/adapters/oracledb/core.py +5416 -0
  240. sqlspec/adapters/oracledb/data_dictionary.py +1264 -0
  241. sqlspec/adapters/oracledb/driver.cp315-win_amd64.pyd +0 -0
  242. sqlspec/adapters/oracledb/driver.py +3273 -0
  243. sqlspec/adapters/oracledb/events/__init__.py +29 -0
  244. sqlspec/adapters/oracledb/events/_hub.cp315-win_amd64.pyd +0 -0
  245. sqlspec/adapters/oracledb/events/_hub.py +394 -0
  246. sqlspec/adapters/oracledb/events/backend.py +311 -0
  247. sqlspec/adapters/oracledb/events/store.py +842 -0
  248. sqlspec/adapters/oracledb/litestar/__init__.py +17 -0
  249. sqlspec/adapters/oracledb/litestar/store.py +862 -0
  250. sqlspec/adapters/oracledb/migrations.py +650 -0
  251. sqlspec/adapters/oracledb/tenant.cp315-win_amd64.pyd +0 -0
  252. sqlspec/adapters/oracledb/tenant.py +990 -0
  253. sqlspec/adapters/oracledb/type_converter.cp315-win_amd64.pyd +0 -0
  254. sqlspec/adapters/oracledb/type_converter.py +93 -0
  255. sqlspec/adapters/psqlpy/__init__.py +21 -0
  256. sqlspec/adapters/psqlpy/_typing.py +180 -0
  257. sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
  258. sqlspec/adapters/psqlpy/adk/store.py +1514 -0
  259. sqlspec/adapters/psqlpy/config.py +828 -0
  260. sqlspec/adapters/psqlpy/core.cp315-win_amd64.pyd +0 -0
  261. sqlspec/adapters/psqlpy/core.py +1040 -0
  262. sqlspec/adapters/psqlpy/data_dictionary.py +399 -0
  263. sqlspec/adapters/psqlpy/driver.cp315-win_amd64.pyd +0 -0
  264. sqlspec/adapters/psqlpy/driver.py +631 -0
  265. sqlspec/adapters/psqlpy/events/__init__.py +12 -0
  266. sqlspec/adapters/psqlpy/events/_hub.cp315-win_amd64.pyd +0 -0
  267. sqlspec/adapters/psqlpy/events/_hub.py +367 -0
  268. sqlspec/adapters/psqlpy/events/backend.py +415 -0
  269. sqlspec/adapters/psqlpy/events/store.py +46 -0
  270. sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
  271. sqlspec/adapters/psqlpy/litestar/store.py +270 -0
  272. sqlspec/adapters/psqlpy/tenant.cp315-win_amd64.pyd +0 -0
  273. sqlspec/adapters/psqlpy/tenant.py +137 -0
  274. sqlspec/adapters/psqlpy/type_converter.cp315-win_amd64.pyd +0 -0
  275. sqlspec/adapters/psqlpy/type_converter.py +21 -0
  276. sqlspec/adapters/psycopg/__init__.py +44 -0
  277. sqlspec/adapters/psycopg/_typing.py +408 -0
  278. sqlspec/adapters/psycopg/adk/__init__.py +17 -0
  279. sqlspec/adapters/psycopg/adk/store.py +2761 -0
  280. sqlspec/adapters/psycopg/config.py +1522 -0
  281. sqlspec/adapters/psycopg/core.cp315-win_amd64.pyd +0 -0
  282. sqlspec/adapters/psycopg/core.py +1001 -0
  283. sqlspec/adapters/psycopg/data_dictionary.py +701 -0
  284. sqlspec/adapters/psycopg/driver.cp315-win_amd64.pyd +0 -0
  285. sqlspec/adapters/psycopg/driver.py +1629 -0
  286. sqlspec/adapters/psycopg/events/__init__.py +25 -0
  287. sqlspec/adapters/psycopg/events/_hub.cp315-win_amd64.pyd +0 -0
  288. sqlspec/adapters/psycopg/events/_hub.py +646 -0
  289. sqlspec/adapters/psycopg/events/backend.py +739 -0
  290. sqlspec/adapters/psycopg/events/store.py +82 -0
  291. sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
  292. sqlspec/adapters/psycopg/litestar/store.py +595 -0
  293. sqlspec/adapters/psycopg/tenant.cp315-win_amd64.pyd +0 -0
  294. sqlspec/adapters/psycopg/tenant.py +226 -0
  295. sqlspec/adapters/psycopg/type_converter.cp315-win_amd64.pyd +0 -0
  296. sqlspec/adapters/psycopg/type_converter.py +94 -0
  297. sqlspec/adapters/pymssql/__init__.py +29 -0
  298. sqlspec/adapters/pymssql/_typing.py +156 -0
  299. sqlspec/adapters/pymssql/adk/__init__.py +5 -0
  300. sqlspec/adapters/pymssql/adk/store.py +1270 -0
  301. sqlspec/adapters/pymssql/config.py +299 -0
  302. sqlspec/adapters/pymssql/core.cp315-win_amd64.pyd +0 -0
  303. sqlspec/adapters/pymssql/core.py +527 -0
  304. sqlspec/adapters/pymssql/data_dictionary.py +417 -0
  305. sqlspec/adapters/pymssql/driver.cp315-win_amd64.pyd +0 -0
  306. sqlspec/adapters/pymssql/driver.py +527 -0
  307. sqlspec/adapters/pymssql/events/__init__.py +5 -0
  308. sqlspec/adapters/pymssql/events/store.py +46 -0
  309. sqlspec/adapters/pymssql/litestar/__init__.py +5 -0
  310. sqlspec/adapters/pymssql/litestar/store.py +350 -0
  311. sqlspec/adapters/pymssql/migrations.py +162 -0
  312. sqlspec/adapters/pymssql/pool.cp315-win_amd64.pyd +0 -0
  313. sqlspec/adapters/pymssql/pool.py +417 -0
  314. sqlspec/adapters/pymssql/tenant.cp315-win_amd64.pyd +0 -0
  315. sqlspec/adapters/pymssql/tenant.py +73 -0
  316. sqlspec/adapters/pymysql/__init__.py +27 -0
  317. sqlspec/adapters/pymysql/_typing.py +105 -0
  318. sqlspec/adapters/pymysql/adk/__init__.py +5 -0
  319. sqlspec/adapters/pymysql/adk/store.py +1646 -0
  320. sqlspec/adapters/pymysql/config.py +545 -0
  321. sqlspec/adapters/pymysql/core.cp315-win_amd64.pyd +0 -0
  322. sqlspec/adapters/pymysql/core.py +909 -0
  323. sqlspec/adapters/pymysql/data_dictionary.py +16 -0
  324. sqlspec/adapters/pymysql/driver.cp315-win_amd64.pyd +0 -0
  325. sqlspec/adapters/pymysql/driver.py +370 -0
  326. sqlspec/adapters/pymysql/events/__init__.py +5 -0
  327. sqlspec/adapters/pymysql/events/store.py +42 -0
  328. sqlspec/adapters/pymysql/litestar/__init__.py +5 -0
  329. sqlspec/adapters/pymysql/litestar/store.py +299 -0
  330. sqlspec/adapters/pymysql/pool.cp315-win_amd64.pyd +0 -0
  331. sqlspec/adapters/pymysql/pool.py +480 -0
  332. sqlspec/adapters/snowflake/__init__.py +36 -0
  333. sqlspec/adapters/snowflake/_typing.py +62 -0
  334. sqlspec/adapters/snowflake/adk/__init__.py +5 -0
  335. sqlspec/adapters/snowflake/adk/store.py +778 -0
  336. sqlspec/adapters/snowflake/config.py +333 -0
  337. sqlspec/adapters/snowflake/core.cp315-win_amd64.pyd +0 -0
  338. sqlspec/adapters/snowflake/core.py +683 -0
  339. sqlspec/adapters/snowflake/data_dictionary.py +355 -0
  340. sqlspec/adapters/snowflake/driver.cp315-win_amd64.pyd +0 -0
  341. sqlspec/adapters/snowflake/driver.py +872 -0
  342. sqlspec/adapters/snowflake/events/__init__.py +5 -0
  343. sqlspec/adapters/snowflake/events/store.py +28 -0
  344. sqlspec/adapters/snowflake/litestar/__init__.py +5 -0
  345. sqlspec/adapters/snowflake/litestar/store.py +162 -0
  346. sqlspec/adapters/snowflake/migrations.cp315-win_amd64.pyd +0 -0
  347. sqlspec/adapters/snowflake/migrations.py +76 -0
  348. sqlspec/adapters/snowflake/pool.cp315-win_amd64.pyd +0 -0
  349. sqlspec/adapters/snowflake/pool.py +385 -0
  350. sqlspec/adapters/snowflake/tenant.cp315-win_amd64.pyd +0 -0
  351. sqlspec/adapters/snowflake/tenant.py +200 -0
  352. sqlspec/adapters/snowflake/type_converter.cp315-win_amd64.pyd +0 -0
  353. sqlspec/adapters/snowflake/type_converter.py +33 -0
  354. sqlspec/adapters/spanner/__init__.py +57 -0
  355. sqlspec/adapters/spanner/_typing.py +300 -0
  356. sqlspec/adapters/spanner/adk/__init__.py +22 -0
  357. sqlspec/adapters/spanner/adk/artifact_store.py +693 -0
  358. sqlspec/adapters/spanner/adk/store.py +3053 -0
  359. sqlspec/adapters/spanner/config.py +1578 -0
  360. sqlspec/adapters/spanner/core.cp315-win_amd64.pyd +0 -0
  361. sqlspec/adapters/spanner/core.py +1244 -0
  362. sqlspec/adapters/spanner/data_dictionary.py +706 -0
  363. sqlspec/adapters/spanner/driver.cp315-win_amd64.pyd +0 -0
  364. sqlspec/adapters/spanner/driver.py +1673 -0
  365. sqlspec/adapters/spanner/events/__init__.py +5 -0
  366. sqlspec/adapters/spanner/events/store.py +357 -0
  367. sqlspec/adapters/spanner/litestar/__init__.py +5 -0
  368. sqlspec/adapters/spanner/litestar/store.py +570 -0
  369. sqlspec/adapters/spanner/type_converter.cp315-win_amd64.pyd +0 -0
  370. sqlspec/adapters/spanner/type_converter.py +466 -0
  371. sqlspec/adapters/sqlanywhere/__init__.py +40 -0
  372. sqlspec/adapters/sqlanywhere/_typing.py +139 -0
  373. sqlspec/adapters/sqlanywhere/adk/__init__.py +5 -0
  374. sqlspec/adapters/sqlanywhere/adk/store.py +1136 -0
  375. sqlspec/adapters/sqlanywhere/config.py +359 -0
  376. sqlspec/adapters/sqlanywhere/core.cp315-win_amd64.pyd +0 -0
  377. sqlspec/adapters/sqlanywhere/core.py +583 -0
  378. sqlspec/adapters/sqlanywhere/data_dictionary.py +282 -0
  379. sqlspec/adapters/sqlanywhere/driver.cp315-win_amd64.pyd +0 -0
  380. sqlspec/adapters/sqlanywhere/driver.py +480 -0
  381. sqlspec/adapters/sqlanywhere/events/__init__.py +5 -0
  382. sqlspec/adapters/sqlanywhere/events/store.py +28 -0
  383. sqlspec/adapters/sqlanywhere/litestar/__init__.py +5 -0
  384. sqlspec/adapters/sqlanywhere/litestar/store.py +237 -0
  385. sqlspec/adapters/sqlanywhere/migrations.py +178 -0
  386. sqlspec/adapters/sqlanywhere/pool.cp315-win_amd64.pyd +0 -0
  387. sqlspec/adapters/sqlanywhere/pool.py +397 -0
  388. sqlspec/adapters/sqlite/__init__.py +32 -0
  389. sqlspec/adapters/sqlite/_typing.py +91 -0
  390. sqlspec/adapters/sqlite/adk/__init__.py +5 -0
  391. sqlspec/adapters/sqlite/adk/store.py +1628 -0
  392. sqlspec/adapters/sqlite/config.py +520 -0
  393. sqlspec/adapters/sqlite/core.cp315-win_amd64.pyd +0 -0
  394. sqlspec/adapters/sqlite/core.py +1035 -0
  395. sqlspec/adapters/sqlite/data_dictionary.py +327 -0
  396. sqlspec/adapters/sqlite/driver.cp315-win_amd64.pyd +0 -0
  397. sqlspec/adapters/sqlite/driver.py +432 -0
  398. sqlspec/adapters/sqlite/events/__init__.py +5 -0
  399. sqlspec/adapters/sqlite/events/store.py +54 -0
  400. sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
  401. sqlspec/adapters/sqlite/litestar/store.py +367 -0
  402. sqlspec/adapters/sqlite/pool.cp315-win_amd64.pyd +0 -0
  403. sqlspec/adapters/sqlite/pool.py +935 -0
  404. sqlspec/adapters/sqlite/type_converter.cp315-win_amd64.pyd +0 -0
  405. sqlspec/adapters/sqlite/type_converter.py +114 -0
  406. sqlspec/adapters/sybase/__init__.py +37 -0
  407. sqlspec/adapters/sybase/_typing.py +150 -0
  408. sqlspec/adapters/sybase/adk/__init__.py +5 -0
  409. sqlspec/adapters/sybase/adk/store.py +1370 -0
  410. sqlspec/adapters/sybase/config.py +276 -0
  411. sqlspec/adapters/sybase/core.cp315-win_amd64.pyd +0 -0
  412. sqlspec/adapters/sybase/core.py +578 -0
  413. sqlspec/adapters/sybase/data_dictionary.py +358 -0
  414. sqlspec/adapters/sybase/driver.cp315-win_amd64.pyd +0 -0
  415. sqlspec/adapters/sybase/driver.py +497 -0
  416. sqlspec/adapters/sybase/events/__init__.py +5 -0
  417. sqlspec/adapters/sybase/events/store.py +88 -0
  418. sqlspec/adapters/sybase/litestar/__init__.py +5 -0
  419. sqlspec/adapters/sybase/litestar/store.py +328 -0
  420. sqlspec/adapters/sybase/migrations.py +178 -0
  421. sqlspec/adapters/sybase/pool.cp315-win_amd64.pyd +0 -0
  422. sqlspec/adapters/sybase/pool.py +435 -0
  423. sqlspec/adapters/teradata/__init__.py +59 -0
  424. sqlspec/adapters/teradata/_typing.py +145 -0
  425. sqlspec/adapters/teradata/adk/__init__.py +5 -0
  426. sqlspec/adapters/teradata/adk/store.py +1300 -0
  427. sqlspec/adapters/teradata/config.py +324 -0
  428. sqlspec/adapters/teradata/core.cp315-win_amd64.pyd +0 -0
  429. sqlspec/adapters/teradata/core.py +437 -0
  430. sqlspec/adapters/teradata/data_dictionary.py +316 -0
  431. sqlspec/adapters/teradata/driver.cp315-win_amd64.pyd +0 -0
  432. sqlspec/adapters/teradata/driver.py +721 -0
  433. sqlspec/adapters/teradata/events/__init__.py +5 -0
  434. sqlspec/adapters/teradata/events/store.py +64 -0
  435. sqlspec/adapters/teradata/litestar/__init__.py +5 -0
  436. sqlspec/adapters/teradata/litestar/store.py +264 -0
  437. sqlspec/adapters/teradata/migrations.cp315-win_amd64.pyd +0 -0
  438. sqlspec/adapters/teradata/migrations.py +80 -0
  439. sqlspec/adapters/teradata/pool.cp315-win_amd64.pyd +0 -0
  440. sqlspec/adapters/teradata/pool.py +377 -0
  441. sqlspec/adapters/teradata/type_converter.cp315-win_amd64.pyd +0 -0
  442. sqlspec/adapters/teradata/type_converter.py +95 -0
  443. sqlspec/base.cp315-win_amd64.pyd +0 -0
  444. sqlspec/base.py +1275 -0
  445. sqlspec/builder/__init__.py +330 -0
  446. sqlspec/builder/_base.cp315-win_amd64.pyd +0 -0
  447. sqlspec/builder/_base.py +1752 -0
  448. sqlspec/builder/_column.cp315-win_amd64.pyd +0 -0
  449. sqlspec/builder/_column.py +508 -0
  450. sqlspec/builder/_ddl.cp315-win_amd64.pyd +0 -0
  451. sqlspec/builder/_ddl.py +4503 -0
  452. sqlspec/builder/_delete.cp315-win_amd64.pyd +0 -0
  453. sqlspec/builder/_delete.py +75 -0
  454. sqlspec/builder/_dml.cp315-win_amd64.pyd +0 -0
  455. sqlspec/builder/_dml.py +639 -0
  456. sqlspec/builder/_explain.cp315-win_amd64.pyd +0 -0
  457. sqlspec/builder/_explain.py +650 -0
  458. sqlspec/builder/_expression_wrappers.cp315-win_amd64.pyd +0 -0
  459. sqlspec/builder/_expression_wrappers.py +77 -0
  460. sqlspec/builder/_factory.cp315-win_amd64.pyd +0 -0
  461. sqlspec/builder/_factory.py +1834 -0
  462. sqlspec/builder/_generation.cp315-win_amd64.pyd +0 -0
  463. sqlspec/builder/_generation.py +55 -0
  464. sqlspec/builder/_insert.cp315-win_amd64.pyd +0 -0
  465. sqlspec/builder/_insert.py +308 -0
  466. sqlspec/builder/_join.cp315-win_amd64.pyd +0 -0
  467. sqlspec/builder/_join.py +501 -0
  468. sqlspec/builder/_locking.cp315-win_amd64.pyd +0 -0
  469. sqlspec/builder/_locking.py +77 -0
  470. sqlspec/builder/_merge.cp315-win_amd64.pyd +0 -0
  471. sqlspec/builder/_merge.py +1047 -0
  472. sqlspec/builder/_parsing_utils.cp315-win_amd64.pyd +0 -0
  473. sqlspec/builder/_parsing_utils.py +1197 -0
  474. sqlspec/builder/_select.cp315-win_amd64.pyd +0 -0
  475. sqlspec/builder/_select.py +1514 -0
  476. sqlspec/builder/_temporal.cp315-win_amd64.pyd +0 -0
  477. sqlspec/builder/_temporal.py +183 -0
  478. sqlspec/builder/_update.cp315-win_amd64.pyd +0 -0
  479. sqlspec/builder/_update.py +139 -0
  480. sqlspec/builder/_values.cp315-win_amd64.pyd +0 -0
  481. sqlspec/builder/_values.py +271 -0
  482. sqlspec/builder/_vector_distance.cp315-win_amd64.pyd +0 -0
  483. sqlspec/builder/_vector_distance.py +763 -0
  484. sqlspec/cli.py +1656 -0
  485. sqlspec/config.py +3402 -0
  486. sqlspec/core/__init__.py +542 -0
  487. sqlspec/core/_cursor.cp315-win_amd64.pyd +0 -0
  488. sqlspec/core/_cursor.py +564 -0
  489. sqlspec/core/_operators.cp315-win_amd64.pyd +0 -0
  490. sqlspec/core/_operators.py +167 -0
  491. sqlspec/core/_ordering.cp315-win_amd64.pyd +0 -0
  492. sqlspec/core/_ordering.py +151 -0
  493. sqlspec/core/_pagination.py +66 -0
  494. sqlspec/core/_pipeline.cp315-win_amd64.pyd +0 -0
  495. sqlspec/core/_pipeline.py +343 -0
  496. sqlspec/core/_pool.cp315-win_amd64.pyd +0 -0
  497. sqlspec/core/_pool.py +72 -0
  498. sqlspec/core/cache.cp315-win_amd64.pyd +0 -0
  499. sqlspec/core/cache.py +1503 -0
  500. sqlspec/core/capabilities.cp315-win_amd64.pyd +0 -0
  501. sqlspec/core/capabilities.py +67 -0
  502. sqlspec/core/compiler.cp315-win_amd64.pyd +0 -0
  503. sqlspec/core/compiler.py +1667 -0
  504. sqlspec/core/config_runtime.cp315-win_amd64.pyd +0 -0
  505. sqlspec/core/config_runtime.py +219 -0
  506. sqlspec/core/correlation.cp315-win_amd64.pyd +0 -0
  507. sqlspec/core/correlation.py +135 -0
  508. sqlspec/core/explain.cp315-win_amd64.pyd +0 -0
  509. sqlspec/core/explain.py +284 -0
  510. sqlspec/core/filters.cp315-win_amd64.pyd +0 -0
  511. sqlspec/core/filters.py +1442 -0
  512. sqlspec/core/hashing.cp315-win_amd64.pyd +0 -0
  513. sqlspec/core/hashing.py +394 -0
  514. sqlspec/core/metrics.cp315-win_amd64.pyd +0 -0
  515. sqlspec/core/metrics.py +86 -0
  516. sqlspec/core/parameters/__init__.py +174 -0
  517. sqlspec/core/parameters/_alignment.cp315-win_amd64.pyd +0 -0
  518. sqlspec/core/parameters/_alignment.py +321 -0
  519. sqlspec/core/parameters/_converter.cp315-win_amd64.pyd +0 -0
  520. sqlspec/core/parameters/_converter.py +956 -0
  521. sqlspec/core/parameters/_declared.cp315-win_amd64.pyd +0 -0
  522. sqlspec/core/parameters/_declared.py +154 -0
  523. sqlspec/core/parameters/_processor.cp315-win_amd64.pyd +0 -0
  524. sqlspec/core/parameters/_processor.py +1646 -0
  525. sqlspec/core/parameters/_registry.cp315-win_amd64.pyd +0 -0
  526. sqlspec/core/parameters/_registry.py +207 -0
  527. sqlspec/core/parameters/_transformers.cp315-win_amd64.pyd +0 -0
  528. sqlspec/core/parameters/_transformers.py +318 -0
  529. sqlspec/core/parameters/_types.cp315-win_amd64.pyd +0 -0
  530. sqlspec/core/parameters/_types.py +658 -0
  531. sqlspec/core/parameters/_validator.cp315-win_amd64.pyd +0 -0
  532. sqlspec/core/parameters/_validator.py +699 -0
  533. sqlspec/core/query_modifiers.cp315-win_amd64.pyd +0 -0
  534. sqlspec/core/query_modifiers.py +559 -0
  535. sqlspec/core/result/__init__.py +67 -0
  536. sqlspec/core/result/_base.cp315-win_amd64.pyd +0 -0
  537. sqlspec/core/result/_base.py +1772 -0
  538. sqlspec/core/routing.cp315-win_amd64.pyd +0 -0
  539. sqlspec/core/routing.py +270 -0
  540. sqlspec/core/splitter.cp315-win_amd64.pyd +0 -0
  541. sqlspec/core/splitter.py +1126 -0
  542. sqlspec/core/sqlcommenter.cp315-win_amd64.pyd +0 -0
  543. sqlspec/core/sqlcommenter.py +509 -0
  544. sqlspec/core/stack.cp315-win_amd64.pyd +0 -0
  545. sqlspec/core/stack.py +167 -0
  546. sqlspec/core/statement.cp315-win_amd64.pyd +0 -0
  547. sqlspec/core/statement.py +2253 -0
  548. sqlspec/core/tenant/__init__.py +64 -0
  549. sqlspec/core/tenant/base.cp315-win_amd64.pyd +0 -0
  550. sqlspec/core/tenant/base.py +123 -0
  551. sqlspec/core/type_converter.cp315-win_amd64.pyd +0 -0
  552. sqlspec/core/type_converter.py +147 -0
  553. sqlspec/data_dictionary/__init__.py +237 -0
  554. sqlspec/data_dictionary/_capabilities.cp315-win_amd64.pyd +0 -0
  555. sqlspec/data_dictionary/_capabilities.py +142 -0
  556. sqlspec/data_dictionary/_dependencies.cp315-win_amd64.pyd +0 -0
  557. sqlspec/data_dictionary/_dependencies.py +602 -0
  558. sqlspec/data_dictionary/_index_ddl.cp315-win_amd64.pyd +0 -0
  559. sqlspec/data_dictionary/_index_ddl.py +562 -0
  560. sqlspec/data_dictionary/_loader.cp315-win_amd64.pyd +0 -0
  561. sqlspec/data_dictionary/_loader.py +344 -0
  562. sqlspec/data_dictionary/_registry.cp315-win_amd64.pyd +0 -0
  563. sqlspec/data_dictionary/_registry.py +152 -0
  564. sqlspec/data_dictionary/_types.cp315-win_amd64.pyd +0 -0
  565. sqlspec/data_dictionary/_types.py +1852 -0
  566. sqlspec/data_dictionary/dialects/__init__.py +34 -0
  567. sqlspec/data_dictionary/dialects/bigquery/__init__.py +15 -0
  568. sqlspec/data_dictionary/dialects/bigquery/config.cp315-win_amd64.pyd +0 -0
  569. sqlspec/data_dictionary/dialects/bigquery/config.py +128 -0
  570. sqlspec/data_dictionary/dialects/bigquery/sql/columns.sql +63 -0
  571. sqlspec/data_dictionary/dialects/bigquery/sql/constraints.sql +37 -0
  572. sqlspec/data_dictionary/dialects/bigquery/sql/datasets.sql +14 -0
  573. sqlspec/data_dictionary/dialects/bigquery/sql/ddl.sql +51 -0
  574. sqlspec/data_dictionary/dialects/bigquery/sql/dependencies.sql +22 -0
  575. sqlspec/data_dictionary/dialects/bigquery/sql/foreign_keys.sql +34 -0
  576. sqlspec/data_dictionary/dialects/bigquery/sql/indexes.sql +59 -0
  577. sqlspec/data_dictionary/dialects/bigquery/sql/objects.sql +13 -0
  578. sqlspec/data_dictionary/dialects/bigquery/sql/privileges.sql +13 -0
  579. sqlspec/data_dictionary/dialects/bigquery/sql/routines.sql +50 -0
  580. sqlspec/data_dictionary/dialects/bigquery/sql/system.sql +59 -0
  581. sqlspec/data_dictionary/dialects/bigquery/sql/tables.sql +111 -0
  582. sqlspec/data_dictionary/dialects/bigquery/sql/version.sql +3 -0
  583. sqlspec/data_dictionary/dialects/bigquery/sql/views.sql +31 -0
  584. sqlspec/data_dictionary/dialects/cockroachdb/__init__.py +17 -0
  585. sqlspec/data_dictionary/dialects/cockroachdb/config.cp315-win_amd64.pyd +0 -0
  586. sqlspec/data_dictionary/dialects/cockroachdb/config.py +95 -0
  587. sqlspec/data_dictionary/dialects/cockroachdb/sql/columns.sql +163 -0
  588. sqlspec/data_dictionary/dialects/cockroachdb/sql/comments.sql +10 -0
  589. sqlspec/data_dictionary/dialects/cockroachdb/sql/constraints.sql +67 -0
  590. sqlspec/data_dictionary/dialects/cockroachdb/sql/crdb_internal.sql +11 -0
  591. sqlspec/data_dictionary/dialects/cockroachdb/sql/ddl.sql +10 -0
  592. sqlspec/data_dictionary/dialects/cockroachdb/sql/dependencies.sql +20 -0
  593. sqlspec/data_dictionary/dialects/cockroachdb/sql/foreign_keys.sql +62 -0
  594. sqlspec/data_dictionary/dialects/cockroachdb/sql/indexes.sql +32 -0
  595. sqlspec/data_dictionary/dialects/cockroachdb/sql/objects.sql +15 -0
  596. sqlspec/data_dictionary/dialects/cockroachdb/sql/privileges.sql +13 -0
  597. sqlspec/data_dictionary/dialects/cockroachdb/sql/schemas.sql +10 -0
  598. sqlspec/data_dictionary/dialects/cockroachdb/sql/sequences.sql +14 -0
  599. sqlspec/data_dictionary/dialects/cockroachdb/sql/tables.sql +15 -0
  600. sqlspec/data_dictionary/dialects/cockroachdb/sql/version.sql +3 -0
  601. sqlspec/data_dictionary/dialects/cockroachdb/sql/views.sql +11 -0
  602. sqlspec/data_dictionary/dialects/db2/__init__.py +31 -0
  603. sqlspec/data_dictionary/dialects/db2/config.cp315-win_amd64.pyd +0 -0
  604. sqlspec/data_dictionary/dialects/db2/config.py +172 -0
  605. sqlspec/data_dictionary/dialects/db2/sql/columns.sql +98 -0
  606. sqlspec/data_dictionary/dialects/db2/sql/constraints.sql +49 -0
  607. sqlspec/data_dictionary/dialects/db2/sql/foreign_keys.sql +43 -0
  608. sqlspec/data_dictionary/dialects/db2/sql/indexes.sql +39 -0
  609. sqlspec/data_dictionary/dialects/db2/sql/objects.sql +53 -0
  610. sqlspec/data_dictionary/dialects/db2/sql/schemas.sql +13 -0
  611. sqlspec/data_dictionary/dialects/db2/sql/tables.sql +77 -0
  612. sqlspec/data_dictionary/dialects/db2/sql/version.sql +8 -0
  613. sqlspec/data_dictionary/dialects/db2/sql/views.sql +15 -0
  614. sqlspec/data_dictionary/dialects/duckdb/__init__.py +5 -0
  615. sqlspec/data_dictionary/dialects/duckdb/config.cp315-win_amd64.pyd +0 -0
  616. sqlspec/data_dictionary/dialects/duckdb/config.py +66 -0
  617. sqlspec/data_dictionary/dialects/duckdb/sql/columns.sql +150 -0
  618. sqlspec/data_dictionary/dialects/duckdb/sql/constraints.sql +34 -0
  619. sqlspec/data_dictionary/dialects/duckdb/sql/databases.sql +11 -0
  620. sqlspec/data_dictionary/dialects/duckdb/sql/ddl.sql +221 -0
  621. sqlspec/data_dictionary/dialects/duckdb/sql/dependencies.sql +50 -0
  622. sqlspec/data_dictionary/dialects/duckdb/sql/extensions.sql +14 -0
  623. sqlspec/data_dictionary/dialects/duckdb/sql/foreign_keys.sql +46 -0
  624. sqlspec/data_dictionary/dialects/duckdb/sql/functions.sql +18 -0
  625. sqlspec/data_dictionary/dialects/duckdb/sql/indexes.sql +34 -0
  626. sqlspec/data_dictionary/dialects/duckdb/sql/objects.sql +30 -0
  627. sqlspec/data_dictionary/dialects/duckdb/sql/schemas.sql +10 -0
  628. sqlspec/data_dictionary/dialects/duckdb/sql/sequences.sql +19 -0
  629. sqlspec/data_dictionary/dialects/duckdb/sql/system.sql +21 -0
  630. sqlspec/data_dictionary/dialects/duckdb/sql/tables.sql +59 -0
  631. sqlspec/data_dictionary/dialects/duckdb/sql/types.sql +12 -0
  632. sqlspec/data_dictionary/dialects/duckdb/sql/version.sql +3 -0
  633. sqlspec/data_dictionary/dialects/duckdb/sql/views.sql +15 -0
  634. sqlspec/data_dictionary/dialects/mariadb/__init__.py +5 -0
  635. sqlspec/data_dictionary/dialects/mariadb/sql/columns.sql +45 -0
  636. sqlspec/data_dictionary/dialects/mariadb/sql/constraints.sql +30 -0
  637. sqlspec/data_dictionary/dialects/mariadb/sql/ddl.sql +27 -0
  638. sqlspec/data_dictionary/dialects/mariadb/sql/events.sql +29 -0
  639. sqlspec/data_dictionary/dialects/mariadb/sql/foreign_keys.sql +42 -0
  640. sqlspec/data_dictionary/dialects/mariadb/sql/indexes.sql +33 -0
  641. sqlspec/data_dictionary/dialects/mariadb/sql/objects.sql +50 -0
  642. sqlspec/data_dictionary/dialects/mariadb/sql/partitions.sql +27 -0
  643. sqlspec/data_dictionary/dialects/mariadb/sql/plugins.sql +16 -0
  644. sqlspec/data_dictionary/dialects/mariadb/sql/privileges.sql +24 -0
  645. sqlspec/data_dictionary/dialects/mariadb/sql/routines.sql +21 -0
  646. sqlspec/data_dictionary/dialects/mariadb/sql/schemas.sql +10 -0
  647. sqlspec/data_dictionary/dialects/mariadb/sql/system.sql +12 -0
  648. sqlspec/data_dictionary/dialects/mariadb/sql/tables.sql +64 -0
  649. sqlspec/data_dictionary/dialects/mariadb/sql/triggers.sql +21 -0
  650. sqlspec/data_dictionary/dialects/mariadb/sql/version.sql +7 -0
  651. sqlspec/data_dictionary/dialects/mariadb/sql/views.sql +15 -0
  652. sqlspec/data_dictionary/dialects/mssql/__init__.py +51 -0
  653. sqlspec/data_dictionary/dialects/mssql/config.cp315-win_amd64.pyd +0 -0
  654. sqlspec/data_dictionary/dialects/mssql/config.py +558 -0
  655. sqlspec/data_dictionary/dialects/mssql/sql/columns.sql +120 -0
  656. sqlspec/data_dictionary/dialects/mssql/sql/constraints.sql +106 -0
  657. sqlspec/data_dictionary/dialects/mssql/sql/ddl.sql +89 -0
  658. sqlspec/data_dictionary/dialects/mssql/sql/dependencies.sql +17 -0
  659. sqlspec/data_dictionary/dialects/mssql/sql/extended_properties.sql +16 -0
  660. sqlspec/data_dictionary/dialects/mssql/sql/foreign_keys.sql +40 -0
  661. sqlspec/data_dictionary/dialects/mssql/sql/indexes.sql +86 -0
  662. sqlspec/data_dictionary/dialects/mssql/sql/modules.sql +19 -0
  663. sqlspec/data_dictionary/dialects/mssql/sql/objects.sql +16 -0
  664. sqlspec/data_dictionary/dialects/mssql/sql/permissions.sql +31 -0
  665. sqlspec/data_dictionary/dialects/mssql/sql/routines.sql +39 -0
  666. sqlspec/data_dictionary/dialects/mssql/sql/schemas.sql +13 -0
  667. sqlspec/data_dictionary/dialects/mssql/sql/sequences.sql +18 -0
  668. sqlspec/data_dictionary/dialects/mssql/sql/storage.sql +22 -0
  669. sqlspec/data_dictionary/dialects/mssql/sql/system.sql +38 -0
  670. sqlspec/data_dictionary/dialects/mssql/sql/tables.sql +97 -0
  671. sqlspec/data_dictionary/dialects/mssql/sql/triggers.sql +21 -0
  672. sqlspec/data_dictionary/dialects/mssql/sql/version.sql +7 -0
  673. sqlspec/data_dictionary/dialects/mssql/sql/views.sql +18 -0
  674. sqlspec/data_dictionary/dialects/mysql/__init__.py +34 -0
  675. sqlspec/data_dictionary/dialects/mysql/config.cp315-win_amd64.pyd +0 -0
  676. sqlspec/data_dictionary/dialects/mysql/config.py +363 -0
  677. sqlspec/data_dictionary/dialects/mysql/dictionary.py +650 -0
  678. sqlspec/data_dictionary/dialects/mysql/sql/columns.sql +45 -0
  679. sqlspec/data_dictionary/dialects/mysql/sql/components.sql +8 -0
  680. sqlspec/data_dictionary/dialects/mysql/sql/constraints.sql +30 -0
  681. sqlspec/data_dictionary/dialects/mysql/sql/ddl.sql +23 -0
  682. sqlspec/data_dictionary/dialects/mysql/sql/events.sql +29 -0
  683. sqlspec/data_dictionary/dialects/mysql/sql/foreign_keys.sql +42 -0
  684. sqlspec/data_dictionary/dialects/mysql/sql/indexes.sql +33 -0
  685. sqlspec/data_dictionary/dialects/mysql/sql/objects.sql +38 -0
  686. sqlspec/data_dictionary/dialects/mysql/sql/partitions.sql +27 -0
  687. sqlspec/data_dictionary/dialects/mysql/sql/plugins.sql +16 -0
  688. sqlspec/data_dictionary/dialects/mysql/sql/privileges.sql +26 -0
  689. sqlspec/data_dictionary/dialects/mysql/sql/routines.sql +21 -0
  690. sqlspec/data_dictionary/dialects/mysql/sql/schemas.sql +10 -0
  691. sqlspec/data_dictionary/dialects/mysql/sql/system.sql +25 -0
  692. sqlspec/data_dictionary/dialects/mysql/sql/tables.sql +64 -0
  693. sqlspec/data_dictionary/dialects/mysql/sql/triggers.sql +21 -0
  694. sqlspec/data_dictionary/dialects/mysql/sql/version.sql +3 -0
  695. sqlspec/data_dictionary/dialects/mysql/sql/views.sql +15 -0
  696. sqlspec/data_dictionary/dialects/oracle/__init__.py +39 -0
  697. sqlspec/data_dictionary/dialects/oracle/config.cp315-win_amd64.pyd +0 -0
  698. sqlspec/data_dictionary/dialects/oracle/config.py +266 -0
  699. sqlspec/data_dictionary/dialects/oracle/sql/arguments.sql +29 -0
  700. sqlspec/data_dictionary/dialects/oracle/sql/columns.sql +103 -0
  701. sqlspec/data_dictionary/dialects/oracle/sql/comments.sql +22 -0
  702. sqlspec/data_dictionary/dialects/oracle/sql/constraints.sql +49 -0
  703. sqlspec/data_dictionary/dialects/oracle/sql/ddl.sql +4 -0
  704. sqlspec/data_dictionary/dialects/oracle/sql/dependencies.sql +16 -0
  705. sqlspec/data_dictionary/dialects/oracle/sql/foreign_keys.sql +48 -0
  706. sqlspec/data_dictionary/dialects/oracle/sql/grants.sql +34 -0
  707. sqlspec/data_dictionary/dialects/oracle/sql/indexes.sql +87 -0
  708. sqlspec/data_dictionary/dialects/oracle/sql/lob_storage.sql +28 -0
  709. sqlspec/data_dictionary/dialects/oracle/sql/materialized_views.sql +27 -0
  710. sqlspec/data_dictionary/dialects/oracle/sql/objects.sql +26 -0
  711. sqlspec/data_dictionary/dialects/oracle/sql/partitions.sql +44 -0
  712. sqlspec/data_dictionary/dialects/oracle/sql/routines.sql +21 -0
  713. sqlspec/data_dictionary/dialects/oracle/sql/schemas.sql +13 -0
  714. sqlspec/data_dictionary/dialects/oracle/sql/sequences.sql +21 -0
  715. sqlspec/data_dictionary/dialects/oracle/sql/source.sql +13 -0
  716. sqlspec/data_dictionary/dialects/oracle/sql/system.sql +37 -0
  717. sqlspec/data_dictionary/dialects/oracle/sql/tables.sql +48 -0
  718. sqlspec/data_dictionary/dialects/oracle/sql/triggers.sql +29 -0
  719. sqlspec/data_dictionary/dialects/oracle/sql/version.sql +25 -0
  720. sqlspec/data_dictionary/dialects/oracle/sql/views.sql +49 -0
  721. sqlspec/data_dictionary/dialects/postgres/__init__.py +19 -0
  722. sqlspec/data_dictionary/dialects/postgres/config.cp315-win_amd64.pyd +0 -0
  723. sqlspec/data_dictionary/dialects/postgres/config.py +119 -0
  724. sqlspec/data_dictionary/dialects/postgres/sql/columns.sql +130 -0
  725. sqlspec/data_dictionary/dialects/postgres/sql/comments.sql +27 -0
  726. sqlspec/data_dictionary/dialects/postgres/sql/constraints.sql +53 -0
  727. sqlspec/data_dictionary/dialects/postgres/sql/ddl.sql +55 -0
  728. sqlspec/data_dictionary/dialects/postgres/sql/dependencies.sql +42 -0
  729. sqlspec/data_dictionary/dialects/postgres/sql/extensions.sql +11 -0
  730. sqlspec/data_dictionary/dialects/postgres/sql/foreign_keys.sql +72 -0
  731. sqlspec/data_dictionary/dialects/postgres/sql/indexes.sql +84 -0
  732. sqlspec/data_dictionary/dialects/postgres/sql/materialized_views.sql +17 -0
  733. sqlspec/data_dictionary/dialects/postgres/sql/objects.sql +25 -0
  734. sqlspec/data_dictionary/dialects/postgres/sql/partitions.sql +19 -0
  735. sqlspec/data_dictionary/dialects/postgres/sql/privileges.sql +29 -0
  736. sqlspec/data_dictionary/dialects/postgres/sql/routines.sql +25 -0
  737. sqlspec/data_dictionary/dialects/postgres/sql/schemas.sql +13 -0
  738. sqlspec/data_dictionary/dialects/postgres/sql/sequences.sql +32 -0
  739. sqlspec/data_dictionary/dialects/postgres/sql/system.sql +53 -0
  740. sqlspec/data_dictionary/dialects/postgres/sql/tables.sql +67 -0
  741. sqlspec/data_dictionary/dialects/postgres/sql/triggers.sql +20 -0
  742. sqlspec/data_dictionary/dialects/postgres/sql/types.sql +21 -0
  743. sqlspec/data_dictionary/dialects/postgres/sql/version.sql +3 -0
  744. sqlspec/data_dictionary/dialects/postgres/sql/views.sql +17 -0
  745. sqlspec/data_dictionary/dialects/snowflake/__init__.py +31 -0
  746. sqlspec/data_dictionary/dialects/snowflake/config.cp315-win_amd64.pyd +0 -0
  747. sqlspec/data_dictionary/dialects/snowflake/config.py +321 -0
  748. sqlspec/data_dictionary/dialects/snowflake/sql/columns.sql +48 -0
  749. sqlspec/data_dictionary/dialects/snowflake/sql/constraints.sql +64 -0
  750. sqlspec/data_dictionary/dialects/snowflake/sql/ddl.sql +3 -0
  751. sqlspec/data_dictionary/dialects/snowflake/sql/foreign_keys.sql +7 -0
  752. sqlspec/data_dictionary/dialects/snowflake/sql/objects.sql +34 -0
  753. sqlspec/data_dictionary/dialects/snowflake/sql/routines.sql +79 -0
  754. sqlspec/data_dictionary/dialects/snowflake/sql/schemas.sql +19 -0
  755. sqlspec/data_dictionary/dialects/snowflake/sql/sequences.sql +45 -0
  756. sqlspec/data_dictionary/dialects/snowflake/sql/tables.sql +29 -0
  757. sqlspec/data_dictionary/dialects/snowflake/sql/version.sql +3 -0
  758. sqlspec/data_dictionary/dialects/snowflake/sql/views.sql +37 -0
  759. sqlspec/data_dictionary/dialects/spanner/__init__.py +5 -0
  760. sqlspec/data_dictionary/dialects/spanner/config.cp315-win_amd64.pyd +0 -0
  761. sqlspec/data_dictionary/dialects/spanner/config.py +67 -0
  762. sqlspec/data_dictionary/dialects/spanner/sql/columns.sql +58 -0
  763. sqlspec/data_dictionary/dialects/spanner/sql/foreign_keys.sql +91 -0
  764. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/change_streams.sql +28 -0
  765. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/columns.sql +46 -0
  766. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/constraints.sql +63 -0
  767. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/database.sql +9 -0
  768. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/foreign_keys.sql +91 -0
  769. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/indexes.sql +66 -0
  770. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/objects.sql +10 -0
  771. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/placements.sql +8 -0
  772. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/privileges.sql +13 -0
  773. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/property_graphs.sql +11 -0
  774. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/routines.sql +33 -0
  775. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/sequences.sql +14 -0
  776. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/system.sql +28 -0
  777. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/tables.sql +30 -0
  778. sqlspec/data_dictionary/dialects/spanner/sql/googlesql/views.sql +13 -0
  779. sqlspec/data_dictionary/dialects/spanner/sql/indexes.sql +30 -0
  780. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/change_streams.sql +28 -0
  781. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/columns.sql +34 -0
  782. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/constraints.sql +63 -0
  783. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/foreign_keys.sql +91 -0
  784. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/indexes.sql +52 -0
  785. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/objects.sql +10 -0
  786. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/sequences.sql +14 -0
  787. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/system.sql +28 -0
  788. sqlspec/data_dictionary/dialects/spanner/sql/postgresql/tables.sql +22 -0
  789. sqlspec/data_dictionary/dialects/spanner/sql/tables.sql +9 -0
  790. sqlspec/data_dictionary/dialects/spanner/sql/version.sql +3 -0
  791. sqlspec/data_dictionary/dialects/sqlanywhere/__init__.py +31 -0
  792. sqlspec/data_dictionary/dialects/sqlanywhere/config.cp315-win_amd64.pyd +0 -0
  793. sqlspec/data_dictionary/dialects/sqlanywhere/config.py +191 -0
  794. sqlspec/data_dictionary/dialects/sqlanywhere/sql/columns.sql +97 -0
  795. sqlspec/data_dictionary/dialects/sqlanywhere/sql/constraints.sql +43 -0
  796. sqlspec/data_dictionary/dialects/sqlanywhere/sql/foreign_keys.sql +45 -0
  797. sqlspec/data_dictionary/dialects/sqlanywhere/sql/indexes.sql +39 -0
  798. sqlspec/data_dictionary/dialects/sqlanywhere/sql/objects.sql +18 -0
  799. sqlspec/data_dictionary/dialects/sqlanywhere/sql/schemas.sql +15 -0
  800. sqlspec/data_dictionary/dialects/sqlanywhere/sql/tables.sql +86 -0
  801. sqlspec/data_dictionary/dialects/sqlanywhere/sql/version.sql +3 -0
  802. sqlspec/data_dictionary/dialects/sqlanywhere/sql/views.sql +15 -0
  803. sqlspec/data_dictionary/dialects/sqlite/__init__.py +19 -0
  804. sqlspec/data_dictionary/dialects/sqlite/config.cp315-win_amd64.pyd +0 -0
  805. sqlspec/data_dictionary/dialects/sqlite/config.py +412 -0
  806. sqlspec/data_dictionary/dialects/sqlite/sql/columns.sql +59 -0
  807. sqlspec/data_dictionary/dialects/sqlite/sql/compile_options.sql +3 -0
  808. sqlspec/data_dictionary/dialects/sqlite/sql/constraints.sql +67 -0
  809. sqlspec/data_dictionary/dialects/sqlite/sql/ddl.sql +37 -0
  810. sqlspec/data_dictionary/dialects/sqlite/sql/foreign_keys.sql +45 -0
  811. sqlspec/data_dictionary/dialects/sqlite/sql/functions.sql +3 -0
  812. sqlspec/data_dictionary/dialects/sqlite/sql/indexes.sql +76 -0
  813. sqlspec/data_dictionary/dialects/sqlite/sql/modules.sql +3 -0
  814. sqlspec/data_dictionary/dialects/sqlite/sql/objects.sql +13 -0
  815. sqlspec/data_dictionary/dialects/sqlite/sql/schemas.sql +3 -0
  816. sqlspec/data_dictionary/dialects/sqlite/sql/system.sql +7 -0
  817. sqlspec/data_dictionary/dialects/sqlite/sql/tables.sql +64 -0
  818. sqlspec/data_dictionary/dialects/sqlite/sql/triggers.sql +10 -0
  819. sqlspec/data_dictionary/dialects/sqlite/sql/version.sql +3 -0
  820. sqlspec/data_dictionary/dialects/sqlite/sql/views.sql +10 -0
  821. sqlspec/data_dictionary/dialects/sybase/__init__.py +31 -0
  822. sqlspec/data_dictionary/dialects/sybase/config.cp315-win_amd64.pyd +0 -0
  823. sqlspec/data_dictionary/dialects/sybase/config.py +187 -0
  824. sqlspec/data_dictionary/dialects/sybase/sql/columns.sql +137 -0
  825. sqlspec/data_dictionary/dialects/sybase/sql/constraints.sql +85 -0
  826. sqlspec/data_dictionary/dialects/sybase/sql/foreign_keys.sql +81 -0
  827. sqlspec/data_dictionary/dialects/sybase/sql/indexes.sql +51 -0
  828. sqlspec/data_dictionary/dialects/sybase/sql/objects.sql +21 -0
  829. sqlspec/data_dictionary/dialects/sybase/sql/schemas.sql +16 -0
  830. sqlspec/data_dictionary/dialects/sybase/sql/tables.sql +46 -0
  831. sqlspec/data_dictionary/dialects/sybase/sql/version.sql +3 -0
  832. sqlspec/data_dictionary/dialects/sybase/sql/views.sql +19 -0
  833. sqlspec/data_dictionary/dialects/teradata/__init__.py +33 -0
  834. sqlspec/data_dictionary/dialects/teradata/config.cp315-win_amd64.pyd +0 -0
  835. sqlspec/data_dictionary/dialects/teradata/config.py +228 -0
  836. sqlspec/data_dictionary/dialects/teradata/sql/columns.sql +22 -0
  837. sqlspec/data_dictionary/dialects/teradata/sql/constraints.sql +19 -0
  838. sqlspec/data_dictionary/dialects/teradata/sql/foreign_keys.sql +9 -0
  839. sqlspec/data_dictionary/dialects/teradata/sql/indexes.sql +9 -0
  840. sqlspec/data_dictionary/dialects/teradata/sql/objects.sql +4 -0
  841. sqlspec/data_dictionary/dialects/teradata/sql/schemas.sql +9 -0
  842. sqlspec/data_dictionary/dialects/teradata/sql/tables.sql +22 -0
  843. sqlspec/data_dictionary/dialects/teradata/sql/version.sql +4 -0
  844. sqlspec/data_dictionary/dialects/teradata/sql/views.sql +4 -0
  845. sqlspec/dialects/__init__.py +44 -0
  846. sqlspec/dialects/db2/__init__.py +111 -0
  847. sqlspec/dialects/db2/_generators.cp315-win_amd64.pyd +0 -0
  848. sqlspec/dialects/db2/_generators.py +376 -0
  849. sqlspec/dialects/db2/_parsers.cp315-win_amd64.pyd +0 -0
  850. sqlspec/dialects/db2/_parsers.py +657 -0
  851. sqlspec/dialects/db2/_transforms.cp315-win_amd64.pyd +0 -0
  852. sqlspec/dialects/db2/_transforms.py +175 -0
  853. sqlspec/dialects/postgres/__init__.py +10 -0
  854. sqlspec/dialects/postgres/_generators.cp315-win_amd64.pyd +0 -0
  855. sqlspec/dialects/postgres/_generators.py +81 -0
  856. sqlspec/dialects/postgres/_operators.cp315-win_amd64.pyd +0 -0
  857. sqlspec/dialects/postgres/_operators.py +95 -0
  858. sqlspec/dialects/postgres/_paradedb.py +44 -0
  859. sqlspec/dialects/postgres/_pg_textsearch.py +38 -0
  860. sqlspec/dialects/postgres/_pgvector.py +36 -0
  861. sqlspec/dialects/spanner/__init__.py +69 -0
  862. sqlspec/dialects/spanner/_expressions.py +247 -0
  863. sqlspec/dialects/spanner/_generators.cp315-win_amd64.pyd +0 -0
  864. sqlspec/dialects/spanner/_generators.py +961 -0
  865. sqlspec/dialects/spanner/_parsers.cp315-win_amd64.pyd +0 -0
  866. sqlspec/dialects/spanner/_parsers.py +871 -0
  867. sqlspec/dialects/spanner/_spangres.py +43 -0
  868. sqlspec/dialects/spanner/_spanner.py +57 -0
  869. sqlspec/dialects/sybase/__init__.py +115 -0
  870. sqlspec/dialects/sybase/_generators.cp315-win_amd64.pyd +0 -0
  871. sqlspec/dialects/sybase/_generators.py +379 -0
  872. sqlspec/dialects/sybase/_parsers.cp315-win_amd64.pyd +0 -0
  873. sqlspec/dialects/sybase/_parsers.py +225 -0
  874. sqlspec/dialects/sybase/_transforms.cp315-win_amd64.pyd +0 -0
  875. sqlspec/dialects/sybase/_transforms.py +68 -0
  876. sqlspec/dialects/teradata/__init__.py +42 -0
  877. sqlspec/dialects/teradata/_generators.cp315-win_amd64.pyd +0 -0
  878. sqlspec/dialects/teradata/_generators.py +203 -0
  879. sqlspec/driver/__init__.py +151 -0
  880. sqlspec/driver/_async.cp315-win_amd64.pyd +0 -0
  881. sqlspec/driver/_async.py +3244 -0
  882. sqlspec/driver/_common.cp315-win_amd64.pyd +0 -0
  883. sqlspec/driver/_common.py +4765 -0
  884. sqlspec/driver/_deferred.cp315-win_amd64.pyd +0 -0
  885. sqlspec/driver/_deferred.py +232 -0
  886. sqlspec/driver/_exception_handler.cp315-win_amd64.pyd +0 -0
  887. sqlspec/driver/_exception_handler.py +224 -0
  888. sqlspec/driver/_routing.cp315-win_amd64.pyd +0 -0
  889. sqlspec/driver/_routing.py +2891 -0
  890. sqlspec/driver/_session.cp315-win_amd64.pyd +0 -0
  891. sqlspec/driver/_session.py +180 -0
  892. sqlspec/driver/_sql_helpers.cp315-win_amd64.pyd +0 -0
  893. sqlspec/driver/_sql_helpers.py +140 -0
  894. sqlspec/driver/_stream.cp315-win_amd64.pyd +0 -0
  895. sqlspec/driver/_stream.py +392 -0
  896. sqlspec/driver/_sync.cp315-win_amd64.pyd +0 -0
  897. sqlspec/driver/_sync.py +3107 -0
  898. sqlspec/driver/_tenant.cp315-win_amd64.pyd +0 -0
  899. sqlspec/driver/_tenant.py +326 -0
  900. sqlspec/exceptions.cp315-win_amd64.pyd +0 -0
  901. sqlspec/exceptions.py +568 -0
  902. sqlspec/extensions/__init__.py +3 -0
  903. sqlspec/extensions/adk/__init__.py +136 -0
  904. sqlspec/extensions/adk/_config_utils.py +306 -0
  905. sqlspec/extensions/adk/_table_utils.cp315-win_amd64.pyd +0 -0
  906. sqlspec/extensions/adk/_table_utils.py +126 -0
  907. sqlspec/extensions/adk/_types.cp315-win_amd64.pyd +0 -0
  908. sqlspec/extensions/adk/_types.py +59 -0
  909. sqlspec/extensions/adk/artifact/__init__.py +18 -0
  910. sqlspec/extensions/adk/artifact/_types.cp315-win_amd64.pyd +0 -0
  911. sqlspec/extensions/adk/artifact/_types.py +41 -0
  912. sqlspec/extensions/adk/artifact/service.py +657 -0
  913. sqlspec/extensions/adk/artifact/store.py +444 -0
  914. sqlspec/extensions/adk/converters.py +230 -0
  915. sqlspec/extensions/adk/maintenance.py +262 -0
  916. sqlspec/extensions/adk/memory/__init__.py +36 -0
  917. sqlspec/extensions/adk/memory/_types.cp315-win_amd64.pyd +0 -0
  918. sqlspec/extensions/adk/memory/_types.py +48 -0
  919. sqlspec/extensions/adk/memory/converters.py +271 -0
  920. sqlspec/extensions/adk/memory/service.py +474 -0
  921. sqlspec/extensions/adk/memory/store.py +586 -0
  922. sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +181 -0
  923. sqlspec/extensions/adk/migrations/0002_create_mssql_python_memory.py +51 -0
  924. sqlspec/extensions/adk/migrations/__init__.py +3 -0
  925. sqlspec/extensions/adk/migrations/reconcile.py +282 -0
  926. sqlspec/extensions/adk/service.py +463 -0
  927. sqlspec/extensions/adk/store.py +1239 -0
  928. sqlspec/extensions/events/__init__.py +132 -0
  929. sqlspec/extensions/events/_buffer.cp315-win_amd64.pyd +0 -0
  930. sqlspec/extensions/events/_buffer.py +38 -0
  931. sqlspec/extensions/events/_channel.cp315-win_amd64.pyd +0 -0
  932. sqlspec/extensions/events/_channel.py +1144 -0
  933. sqlspec/extensions/events/_hints.cp315-win_amd64.pyd +0 -0
  934. sqlspec/extensions/events/_hints.py +38 -0
  935. sqlspec/extensions/events/_models.cp315-win_amd64.pyd +0 -0
  936. sqlspec/extensions/events/_models.py +22 -0
  937. sqlspec/extensions/events/_names.cp315-win_amd64.pyd +0 -0
  938. sqlspec/extensions/events/_names.py +27 -0
  939. sqlspec/extensions/events/_payload.cp315-win_amd64.pyd +0 -0
  940. sqlspec/extensions/events/_payload.py +139 -0
  941. sqlspec/extensions/events/_protocols.py +154 -0
  942. sqlspec/extensions/events/_queue.cp315-win_amd64.pyd +0 -0
  943. sqlspec/extensions/events/_queue.py +1147 -0
  944. sqlspec/extensions/events/_store.py +318 -0
  945. sqlspec/extensions/events/migrations/0001_create_event_queue.py +106 -0
  946. sqlspec/extensions/events/migrations/__init__.py +3 -0
  947. sqlspec/extensions/events/migrations/reconcile.py +145 -0
  948. sqlspec/extensions/events/primitives.cp315-win_amd64.pyd +0 -0
  949. sqlspec/extensions/events/primitives.py +91 -0
  950. sqlspec/extensions/fastapi/__init__.py +26 -0
  951. sqlspec/extensions/fastapi/extension.py +360 -0
  952. sqlspec/extensions/fastapi/providers.cp315-win_amd64.pyd +0 -0
  953. sqlspec/extensions/fastapi/providers.py +1091 -0
  954. sqlspec/extensions/flask/__init__.py +20 -0
  955. sqlspec/extensions/flask/_portal.cp315-win_amd64.pyd +0 -0
  956. sqlspec/extensions/flask/_portal.py +212 -0
  957. sqlspec/extensions/flask/_state.cp315-win_amd64.pyd +0 -0
  958. sqlspec/extensions/flask/_state.py +135 -0
  959. sqlspec/extensions/flask/_utils.cp315-win_amd64.pyd +0 -0
  960. sqlspec/extensions/flask/_utils.py +171 -0
  961. sqlspec/extensions/flask/extension.py +1234 -0
  962. sqlspec/extensions/litestar/__init__.py +52 -0
  963. sqlspec/extensions/litestar/_tenant_resolution.cp315-win_amd64.pyd +0 -0
  964. sqlspec/extensions/litestar/_tenant_resolution.py +314 -0
  965. sqlspec/extensions/litestar/_utils.cp315-win_amd64.pyd +0 -0
  966. sqlspec/extensions/litestar/_utils.py +222 -0
  967. sqlspec/extensions/litestar/channels.py +249 -0
  968. sqlspec/extensions/litestar/cli.py +100 -0
  969. sqlspec/extensions/litestar/config.py +5 -0
  970. sqlspec/extensions/litestar/handlers.py +796 -0
  971. sqlspec/extensions/litestar/migrations/0001_create_session_table.py +138 -0
  972. sqlspec/extensions/litestar/migrations/__init__.py +3 -0
  973. sqlspec/extensions/litestar/migrations/reconcile.py +132 -0
  974. sqlspec/extensions/litestar/plugin.py +2172 -0
  975. sqlspec/extensions/litestar/providers.cp315-win_amd64.pyd +0 -0
  976. sqlspec/extensions/litestar/providers.py +1239 -0
  977. sqlspec/extensions/litestar/store.py +613 -0
  978. sqlspec/extensions/litestar/tenant.py +292 -0
  979. sqlspec/extensions/otel/__init__.py +58 -0
  980. sqlspec/extensions/prometheus/__init__.py +5 -0
  981. sqlspec/extensions/prometheus/_observer.cp315-win_amd64.pyd +0 -0
  982. sqlspec/extensions/prometheus/_observer.py +152 -0
  983. sqlspec/extensions/sanic/__init__.py +28 -0
  984. sqlspec/extensions/sanic/_state.cp315-win_amd64.pyd +0 -0
  985. sqlspec/extensions/sanic/_state.py +102 -0
  986. sqlspec/extensions/sanic/_utils.cp315-win_amd64.pyd +0 -0
  987. sqlspec/extensions/sanic/_utils.py +234 -0
  988. sqlspec/extensions/sanic/extension.py +1467 -0
  989. sqlspec/extensions/starlette/__init__.py +31 -0
  990. sqlspec/extensions/starlette/_state.cp315-win_amd64.pyd +0 -0
  991. sqlspec/extensions/starlette/_state.py +103 -0
  992. sqlspec/extensions/starlette/_utils.cp315-win_amd64.pyd +0 -0
  993. sqlspec/extensions/starlette/_utils.py +267 -0
  994. sqlspec/extensions/starlette/extension.py +691 -0
  995. sqlspec/extensions/starlette/middleware.py +845 -0
  996. sqlspec/loader.cp315-win_amd64.pyd +0 -0
  997. sqlspec/loader.py +1733 -0
  998. sqlspec/migrations/__init__.py +104 -0
  999. sqlspec/migrations/_backup.cp315-win_amd64.pyd +0 -0
  1000. sqlspec/migrations/_backup.py +36 -0
  1001. sqlspec/migrations/base.cp315-win_amd64.pyd +0 -0
  1002. sqlspec/migrations/base.py +1688 -0
  1003. sqlspec/migrations/commands.py +4002 -0
  1004. sqlspec/migrations/context.cp315-win_amd64.pyd +0 -0
  1005. sqlspec/migrations/context.py +158 -0
  1006. sqlspec/migrations/fix.cp315-win_amd64.pyd +0 -0
  1007. sqlspec/migrations/fix.py +193 -0
  1008. sqlspec/migrations/loaders.cp315-win_amd64.pyd +0 -0
  1009. sqlspec/migrations/loaders.py +835 -0
  1010. sqlspec/migrations/runner.cp315-win_amd64.pyd +0 -0
  1011. sqlspec/migrations/runner.py +2144 -0
  1012. sqlspec/migrations/schema.cp315-win_amd64.pyd +0 -0
  1013. sqlspec/migrations/schema.py +1266 -0
  1014. sqlspec/migrations/squash.cp315-win_amd64.pyd +0 -0
  1015. sqlspec/migrations/squash.py +2452 -0
  1016. sqlspec/migrations/templates.cp315-win_amd64.pyd +0 -0
  1017. sqlspec/migrations/templates.py +310 -0
  1018. sqlspec/migrations/tracker.cp315-win_amd64.pyd +0 -0
  1019. sqlspec/migrations/tracker.py +1529 -0
  1020. sqlspec/migrations/utils.cp315-win_amd64.pyd +0 -0
  1021. sqlspec/migrations/utils.py +534 -0
  1022. sqlspec/migrations/validation.cp315-win_amd64.pyd +0 -0
  1023. sqlspec/migrations/validation.py +355 -0
  1024. sqlspec/migrations/version.cp315-win_amd64.pyd +0 -0
  1025. sqlspec/migrations/version.py +455 -0
  1026. sqlspec/observability/__init__.py +122 -0
  1027. sqlspec/observability/_common.cp315-win_amd64.pyd +0 -0
  1028. sqlspec/observability/_common.py +307 -0
  1029. sqlspec/observability/_config.cp315-win_amd64.pyd +0 -0
  1030. sqlspec/observability/_config.py +362 -0
  1031. sqlspec/observability/_diagnostics.cp315-win_amd64.pyd +0 -0
  1032. sqlspec/observability/_diagnostics.py +75 -0
  1033. sqlspec/observability/_dispatcher.cp315-win_amd64.pyd +0 -0
  1034. sqlspec/observability/_dispatcher.py +320 -0
  1035. sqlspec/observability/_formatters/__init__.py +13 -0
  1036. sqlspec/observability/_formatters/_aws.cp315-win_amd64.pyd +0 -0
  1037. sqlspec/observability/_formatters/_aws.py +90 -0
  1038. sqlspec/observability/_formatters/_azure.cp315-win_amd64.pyd +0 -0
  1039. sqlspec/observability/_formatters/_azure.py +84 -0
  1040. sqlspec/observability/_formatters/_base.cp315-win_amd64.pyd +0 -0
  1041. sqlspec/observability/_formatters/_base.py +40 -0
  1042. sqlspec/observability/_formatters/_gcp.cp315-win_amd64.pyd +0 -0
  1043. sqlspec/observability/_formatters/_gcp.py +119 -0
  1044. sqlspec/observability/_formatting.cp315-win_amd64.pyd +0 -0
  1045. sqlspec/observability/_formatting.py +76 -0
  1046. sqlspec/observability/_observer.cp315-win_amd64.pyd +0 -0
  1047. sqlspec/observability/_observer.py +445 -0
  1048. sqlspec/observability/_runtime.cp315-win_amd64.pyd +0 -0
  1049. sqlspec/observability/_runtime.py +740 -0
  1050. sqlspec/observability/_sampling.cp315-win_amd64.pyd +0 -0
  1051. sqlspec/observability/_sampling.py +169 -0
  1052. sqlspec/observability/_spans.cp315-win_amd64.pyd +0 -0
  1053. sqlspec/observability/_spans.py +212 -0
  1054. sqlspec/protocols.py +1235 -0
  1055. sqlspec/py.typed +0 -0
  1056. sqlspec/service/__init__.py +5 -0
  1057. sqlspec/service/_base.py +1051 -0
  1058. sqlspec/service/_core.cp315-win_amd64.pyd +0 -0
  1059. sqlspec/service/_core.py +625 -0
  1060. sqlspec/storage/__init__.py +111 -0
  1061. sqlspec/storage/_arrow_payload.py +802 -0
  1062. sqlspec/storage/_arrow_stream.cp315-win_amd64.pyd +0 -0
  1063. sqlspec/storage/_arrow_stream.py +134 -0
  1064. sqlspec/storage/_ingest.cp315-win_amd64.pyd +0 -0
  1065. sqlspec/storage/_ingest.py +810 -0
  1066. sqlspec/storage/_paths.cp315-win_amd64.pyd +0 -0
  1067. sqlspec/storage/_paths.py +313 -0
  1068. sqlspec/storage/_staging_sql.cp315-win_amd64.pyd +0 -0
  1069. sqlspec/storage/_staging_sql.py +695 -0
  1070. sqlspec/storage/_utils.cp315-win_amd64.pyd +0 -0
  1071. sqlspec/storage/_utils.py +174 -0
  1072. sqlspec/storage/backends/__init__.py +43 -0
  1073. sqlspec/storage/backends/base.cp315-win_amd64.pyd +0 -0
  1074. sqlspec/storage/backends/base.py +399 -0
  1075. sqlspec/storage/backends/fsspec.cp315-win_amd64.pyd +0 -0
  1076. sqlspec/storage/backends/fsspec.py +1390 -0
  1077. sqlspec/storage/backends/local.cp315-win_amd64.pyd +0 -0
  1078. sqlspec/storage/backends/local.py +968 -0
  1079. sqlspec/storage/backends/obstore.cp315-win_amd64.pyd +0 -0
  1080. sqlspec/storage/backends/obstore.py +1974 -0
  1081. sqlspec/storage/errors.cp315-win_amd64.pyd +0 -0
  1082. sqlspec/storage/errors.py +127 -0
  1083. sqlspec/storage/pipeline.cp315-win_amd64.pyd +0 -0
  1084. sqlspec/storage/pipeline.py +1270 -0
  1085. sqlspec/storage/registry.cp315-win_amd64.pyd +0 -0
  1086. sqlspec/storage/registry.py +318 -0
  1087. sqlspec/typing.py +261 -0
  1088. sqlspec/utils/__init__.py +9 -0
  1089. sqlspec/utils/adapters.cp315-win_amd64.pyd +0 -0
  1090. sqlspec/utils/adapters.py +186 -0
  1091. sqlspec/utils/arrow_helpers.py +2157 -0
  1092. sqlspec/utils/config_tools.cp315-win_amd64.pyd +0 -0
  1093. sqlspec/utils/config_tools.py +712 -0
  1094. sqlspec/utils/correlation.cp315-win_amd64.pyd +0 -0
  1095. sqlspec/utils/correlation.py +137 -0
  1096. sqlspec/utils/deprecation.cp315-win_amd64.pyd +0 -0
  1097. sqlspec/utils/deprecation.py +222 -0
  1098. sqlspec/utils/dispatch.cp315-win_amd64.pyd +0 -0
  1099. sqlspec/utils/dispatch.py +104 -0
  1100. sqlspec/utils/env.cp315-win_amd64.pyd +0 -0
  1101. sqlspec/utils/env.py +437 -0
  1102. sqlspec/utils/fixtures.cp315-win_amd64.pyd +0 -0
  1103. sqlspec/utils/fixtures.py +2470 -0
  1104. sqlspec/utils/logging.cp315-win_amd64.pyd +0 -0
  1105. sqlspec/utils/logging.py +267 -0
  1106. sqlspec/utils/module_loader.cp315-win_amd64.pyd +0 -0
  1107. sqlspec/utils/module_loader.py +399 -0
  1108. sqlspec/utils/portal.cp315-win_amd64.pyd +0 -0
  1109. sqlspec/utils/portal.py +411 -0
  1110. sqlspec/utils/routing.cp315-win_amd64.pyd +0 -0
  1111. sqlspec/utils/routing.py +645 -0
  1112. sqlspec/utils/schema.cp315-win_amd64.pyd +0 -0
  1113. sqlspec/utils/schema.py +1050 -0
  1114. sqlspec/utils/serializers/__init__.py +69 -0
  1115. sqlspec/utils/serializers/_json.cp315-win_amd64.pyd +0 -0
  1116. sqlspec/utils/serializers/_json.py +525 -0
  1117. sqlspec/utils/serializers/_numpy.cp315-win_amd64.pyd +0 -0
  1118. sqlspec/utils/serializers/_numpy.py +65 -0
  1119. sqlspec/utils/serializers/_schema.cp315-win_amd64.pyd +0 -0
  1120. sqlspec/utils/serializers/_schema.py +340 -0
  1121. sqlspec/utils/sync_tools.cp315-win_amd64.pyd +0 -0
  1122. sqlspec/utils/sync_tools.py +502 -0
  1123. sqlspec/utils/tenant/__init__.py +71 -0
  1124. sqlspec/utils/tenant/_context.cp315-win_amd64.pyd +0 -0
  1125. sqlspec/utils/tenant/_context.py +550 -0
  1126. sqlspec/utils/tenant/_cursor.cp315-win_amd64.pyd +0 -0
  1127. sqlspec/utils/tenant/_cursor.py +43 -0
  1128. sqlspec/utils/tenant/_mssql.cp315-win_amd64.pyd +0 -0
  1129. sqlspec/utils/tenant/_mssql.py +189 -0
  1130. sqlspec/utils/tenant/_postgres.cp315-win_amd64.pyd +0 -0
  1131. sqlspec/utils/tenant/_postgres.py +142 -0
  1132. sqlspec/utils/text.cp315-win_amd64.pyd +0 -0
  1133. sqlspec/utils/text.py +317 -0
  1134. sqlspec/utils/type_converters.cp315-win_amd64.pyd +0 -0
  1135. sqlspec/utils/type_converters.py +220 -0
  1136. sqlspec/utils/type_guards.cp315-win_amd64.pyd +0 -0
  1137. sqlspec/utils/type_guards.py +1505 -0
  1138. sqlspec/utils/uuids.cp315-win_amd64.pyd +0 -0
  1139. sqlspec/utils/uuids.py +263 -0
  1140. sqlspec-0.72.0.dist-info/METADATA +228 -0
  1141. sqlspec-0.72.0.dist-info/RECORD +1144 -0
  1142. sqlspec-0.72.0.dist-info/WHEEL +4 -0
  1143. sqlspec-0.72.0.dist-info/entry_points.txt +13 -0
  1144. sqlspec-0.72.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2172 @@
1
+ """Litestar plugin for SQLSpec database configuration, lifecycle, and dependency injection."""
2
+
3
+ import asyncio
4
+ import datetime as dt
5
+ import logging
6
+ from collections.abc import Iterable, Mapping, MutableMapping, Sequence
7
+ from contextlib import suppress
8
+ from dataclasses import dataclass, field
9
+ from typing import TYPE_CHECKING, Any, Literal, NoReturn, TypeAlias, cast, overload
10
+
11
+ from litestar.constants import HTTP_RESPONSE_START
12
+ from litestar.di import Provide
13
+ from litestar.enums import ScopeType
14
+ from litestar.exceptions import ClientException, HTTPException, NotFoundException
15
+ from litestar.exceptions.responses import create_exception_response
16
+ from litestar.middleware import DefineMiddleware
17
+ from litestar.plugins import CLIPlugin, InitPluginProtocol, OpenAPISchemaPlugin
18
+ from litestar.status_codes import HTTP_409_CONFLICT, HTTP_500_INTERNAL_SERVER_ERROR
19
+ from litestar.utils.scope.state import ScopeState
20
+
21
+ from sqlspec.base import SQLSpec, coerce_sqlspec
22
+ from sqlspec.config import (
23
+ AsyncConfigT,
24
+ AsyncDatabaseConfig,
25
+ DatabaseConfigProtocol,
26
+ DriverT,
27
+ NoPoolAsyncConfig,
28
+ NoPoolSyncConfig,
29
+ SyncConfigT,
30
+ SyncDatabaseConfig,
31
+ )
32
+ from sqlspec.core import CorrelationExtractor, OffsetPagination
33
+ from sqlspec.core._cursor import resolve_plugin_cursor_settings
34
+ from sqlspec.core.sqlcommenter import SQLCommenterContext
35
+ from sqlspec.driver import DeferredAsyncSession, raise_async_connection_required
36
+ from sqlspec.driver._routing import AsyncRoutingSession
37
+ from sqlspec.exceptions import ImproperConfigurationError, IntegrityError, NotFoundError
38
+ from sqlspec.extensions.litestar._utils import (
39
+ delete_sqlspec_scope_state,
40
+ get_sqlspec_scope_state,
41
+ publish_request_session,
42
+ request_session_scope,
43
+ set_sqlspec_scope_state,
44
+ )
45
+ from sqlspec.extensions.litestar.cli import database_group
46
+ from sqlspec.extensions.litestar.handlers import (
47
+ _REQUEST_EXCEPTION_KEY,
48
+ _finalize_request_transaction,
49
+ _open_request_resource_async,
50
+ _open_request_resource_sync,
51
+ _release_request_connection,
52
+ _resolve_connection_tenant_async,
53
+ _resolve_connection_tenant_sync,
54
+ autocommit_handler_maker,
55
+ build_db_session,
56
+ db_connection_provider_maker,
57
+ db_pool_provider_maker,
58
+ db_replica_connection_provider_maker,
59
+ db_replica_pool_provider_maker,
60
+ db_replica_session_provider_maker,
61
+ db_routing_session_provider_maker,
62
+ db_session_provider_maker,
63
+ has_tenant_strategy,
64
+ lifespan_handler_maker,
65
+ manual_handler_maker,
66
+ record_request_exception,
67
+ tenant_payload_key,
68
+ )
69
+ from sqlspec.extensions.litestar.tenant import (
70
+ TenantResolutionSettings,
71
+ raise_missing_tenant_http_exception,
72
+ resolve_route_tenant,
73
+ tenant_receipt_key,
74
+ )
75
+ from sqlspec.typing import NUMPY_INSTALLED, ConnectionT, PoolT, SchemaT, import_optional_attr
76
+ from sqlspec.utils.config_tools import resolve_extension_commit_mode
77
+ from sqlspec.utils.correlation import CorrelationContext
78
+ from sqlspec.utils.deprecation import deprecated
79
+ from sqlspec.utils.logging import get_logger, log_with_context
80
+ from sqlspec.utils.routing import (
81
+ RoutingContext,
82
+ RoutingContextPayload,
83
+ RoutingEntry,
84
+ apply_request_routing_hints,
85
+ extract_asgi_routing_headers,
86
+ validate_routing_middleware_settings,
87
+ )
88
+ from sqlspec.utils.serializers import DEFAULT_TYPE_ENCODERS, numpy_array_dec_hook
89
+ from sqlspec.utils.tenant import TenantContext, TenantRequestBinding
90
+
91
+ if TYPE_CHECKING:
92
+ from collections.abc import AsyncGenerator, Callable
93
+ from contextlib import AbstractAsyncContextManager, AbstractContextManager
94
+
95
+ from litestar import Litestar, Request, Response
96
+ from litestar._openapi.schema_generation.schema import SchemaCreator
97
+ from litestar.config.app import AppConfig
98
+ from litestar.datastructures.state import State
99
+ from litestar.openapi.spec import Schema
100
+ from litestar.types import (
101
+ ASGIApp,
102
+ BeforeMessageSendHookHandler,
103
+ ExceptionHandlersMap,
104
+ Message,
105
+ Middleware,
106
+ Receive,
107
+ Scope,
108
+ Send,
109
+ )
110
+ from litestar.typing import FieldDefinition
111
+ from rich_click import Group
112
+
113
+ from sqlspec.config import LitestarConfig
114
+ from sqlspec.driver import AsyncDriverAdapterBase, SyncDriverAdapterBase
115
+ from sqlspec.loader import SQLFileLoader
116
+
117
+ AnyDatabaseConfig: TypeAlias = (
118
+ SyncDatabaseConfig[Any, Any, Any]
119
+ | NoPoolSyncConfig[Any, Any]
120
+ | AsyncDatabaseConfig[Any, Any, Any]
121
+ | NoPoolAsyncConfig[Any, Any]
122
+ )
123
+
124
+ __all__ = (
125
+ "CORRELATION_STATE_KEY",
126
+ "DEFAULT_COMMIT_MODE",
127
+ "DEFAULT_CONNECTION_KEY",
128
+ "DEFAULT_CORRELATION_HEADER",
129
+ "DEFAULT_POOL_KEY",
130
+ "DEFAULT_SESSION_KEY",
131
+ "TRACE_CONTEXT_FALLBACK_HEADERS",
132
+ "CommitMode",
133
+ "ConnectionCleanupMiddleware",
134
+ "CorrelationMiddleware",
135
+ "PluginConfigState",
136
+ "SQLSpecPlugin",
137
+ "_OffsetPaginationSchemaPlugin",
138
+ "integrity_error_handler",
139
+ "not_found_error_handler",
140
+ )
141
+
142
+ logger = get_logger("sqlspec.extensions.litestar")
143
+
144
+ CommitMode = Literal["manual", "autocommit", "autocommit_include_redirect"]
145
+ DEFAULT_COMMIT_MODE: CommitMode = "autocommit"
146
+ DEFAULT_CONNECTION_KEY = "db_connection"
147
+ DEFAULT_POOL_KEY = "db_pool"
148
+ DEFAULT_SESSION_KEY = "db_session"
149
+ DEFAULT_CORRELATION_HEADER = "x-request-id"
150
+ TRACE_CONTEXT_FALLBACK_HEADERS: tuple[str, ...] = (
151
+ DEFAULT_CORRELATION_HEADER,
152
+ "x-correlation-id",
153
+ "traceparent",
154
+ "x-cloud-trace-context",
155
+ "grpc-trace-bin",
156
+ "x-amzn-trace-id",
157
+ "x-b3-traceid",
158
+ "x-client-trace-id",
159
+ )
160
+ CORRELATION_STATE_KEY = "sqlspec_correlation_id"
161
+ _LITESTAR_NUMPY_ARRAY_TYPE: type[Any] | None = None
162
+
163
+
164
+ def not_found_error_handler(request: "Request[Any, Any, Any]", exc: NotFoundError) -> "Response[Any]":
165
+ """Return a 404 response with the static detail ``"Not Found"``.
166
+
167
+ A handler for status 404 or for the HTTP exception type renders it, otherwise Litestar's
168
+ default exception response. Handlers for :class:`~sqlspec.exceptions.NotFoundError` or a
169
+ subclass take precedence; handlers for its base classes or status 500 do not.
170
+ """
171
+ http_exc = NotFoundException(detail="Not Found")
172
+ http_exc.__cause__ = exc
173
+ return _render_http_exception(request, http_exc, _resolve_exception_handlers(request))
174
+
175
+
176
+ def integrity_error_handler(request: "Request[Any, Any, Any]", exc: IntegrityError) -> "Response[Any]":
177
+ """Return a 409 response with the generic detail ``"Conflict"``.
178
+
179
+ A handler for status 409 or for the HTTP exception type renders it, otherwise Litestar's
180
+ default exception response. Handlers for :class:`~sqlspec.exceptions.IntegrityError` or a
181
+ subclass take precedence, and handlers for a later class in the error's MRO or for status
182
+ 500 receive the original exception.
183
+ """
184
+ handlers = _resolve_exception_handlers(request)
185
+ exc_mro = type(exc).__mro__
186
+ broader_handler = next(
187
+ (handlers[cls] for cls in exc_mro[exc_mro.index(IntegrityError) + 1 :] if cls in handlers),
188
+ handlers.get(HTTP_500_INTERNAL_SERVER_ERROR),
189
+ )
190
+ if broader_handler is not None:
191
+ return broader_handler(request, exc)
192
+ http_exc = ClientException(status_code=HTTP_409_CONFLICT, detail="Conflict")
193
+ http_exc.__cause__ = exc
194
+ return _render_http_exception(request, http_exc, handlers)
195
+
196
+
197
+ class CorrelationMiddleware:
198
+ """ASGI middleware that binds a correlation ID to each HTTP request.
199
+
200
+ Only headers matching the configured ``headers`` allowlist are decoded from
201
+ the ASGI header list (using ``latin-1`` over precomputed lowercase ``bytes``
202
+ names). Checked in priority order, the first header whose bounded, single-line
203
+ ASCII trace value passes validation becomes the correlation ID; invalid values
204
+ fall through to subsequent headers, or to a newly generated ID when none
205
+ qualify. Non-HTTP scopes, and instances created with an empty ``headers``
206
+ tuple, pass through unchanged.
207
+
208
+ Args:
209
+ app: The downstream ASGI application.
210
+ headers: Request header names to check, in priority order.
211
+ """
212
+
213
+ __slots__ = ("_app", "_extractor", "_header_bytes", "_headers")
214
+
215
+ def __init__(self, app: "ASGIApp", *, headers: tuple[str, ...]) -> None:
216
+ self._app = app
217
+ self._headers = headers
218
+ self._extractor = (
219
+ CorrelationExtractor(
220
+ primary_header=headers[0],
221
+ additional_headers=headers[1:] if len(headers) > 1 else None,
222
+ auto_trace_headers=False,
223
+ )
224
+ if headers
225
+ else None
226
+ )
227
+ self._header_bytes: frozenset[bytes] = (
228
+ frozenset(header.lower().encode("latin-1") for header in self._extractor.headers)
229
+ if self._extractor is not None
230
+ else frozenset()
231
+ )
232
+
233
+ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
234
+ scope_type = scope.get("type")
235
+ if str(scope_type) != "http" or self._extractor is None:
236
+ await self._app(scope, receive, send)
237
+ return
238
+
239
+ raw_headers = scope.get("headers") or []
240
+ matched_headers: dict[str, str] = {}
241
+ for raw_name, raw_value in raw_headers:
242
+ lowered = raw_name.lower()
243
+ if lowered in self._header_bytes:
244
+ matched_headers.setdefault(lowered.decode("latin-1"), raw_value.decode("latin-1"))
245
+ header_value = self._extractor.extract(matched_headers.get)
246
+
247
+ previous_correlation_id = CorrelationContext.get()
248
+ CorrelationContext.set(header_value)
249
+ set_sqlspec_scope_state(scope, CORRELATION_STATE_KEY, header_value)
250
+ try:
251
+ await self._app(scope, receive, send)
252
+ finally:
253
+ with suppress(KeyError):
254
+ delete_sqlspec_scope_state(scope, CORRELATION_STATE_KEY)
255
+ CorrelationContext.set(previous_correlation_id)
256
+
257
+
258
+ @dataclass(frozen=True)
259
+ class _TenantResolutionTarget:
260
+ """Resolution inputs for one tenant-enabled configuration."""
261
+
262
+ config: Any
263
+ settings: TenantResolutionSettings
264
+ receipt_state_keys: tuple[str, ...]
265
+
266
+
267
+ class SQLSpecTenantRequestMiddleware:
268
+ """Bind one lazy tenant resolver for each HTTP or WebSocket request.
269
+
270
+ Installed only when a registered configuration enables ``tenant_strategy``. Request start
271
+ costs one context variable assignment; route bypass, connection receipts, the extractor, and
272
+ verified auth resolution run when a lease, session, or ``TenantContext`` first needs the
273
+ tenant. Pending resolutions finish before the final response message, and the binding is
274
+ reset when the ASGI call returns.
275
+ """
276
+
277
+ __slots__ = ("_app", "_default", "_keys", "_targets")
278
+
279
+ def __init__(self, app: "ASGIApp", *, targets: "tuple[_TenantResolutionTarget, ...]") -> None:
280
+ self._app = app
281
+ self._targets = {id(target.config): target for target in targets}
282
+ self._keys = tuple(target.config for target in targets)
283
+ self._default = targets[0] if targets else None
284
+
285
+ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
286
+ if scope.get("type") not in {ScopeType.HTTP, ScopeType.WEBSOCKET} or self._default is None:
287
+ await self._app(scope, receive, send)
288
+ return
289
+ binding = TenantRequestBinding(
290
+ lambda key: self._resolve(scope, key),
291
+ keys=self._keys,
292
+ ambient=TenantContext.current_binding(),
293
+ missing=lambda _key: raise_missing_tenant_http_exception(cast("Mapping[str, Any]", scope)),
294
+ )
295
+ token = TenantContext.bind_request(binding)
296
+ try:
297
+ if scope.get("type") == ScopeType.HTTP:
298
+
299
+ async def frozen_send(message: "Message") -> None:
300
+ message_type = cast("str", message["type"])
301
+ if message_type == "http.response.pathsend" or (
302
+ message_type == "http.response.body" and not message.get("more_body", False)
303
+ ):
304
+ await binding.freeze_async()
305
+ await send(message)
306
+
307
+ await self._app(scope, receive, frozen_send)
308
+ else:
309
+ await self._app(scope, receive, send)
310
+ finally:
311
+ TenantContext.reset(token)
312
+
313
+ def _resolve(self, scope: "Scope", key: Any) -> Any:
314
+ target = self._targets.get(id(key), self._default)
315
+ if target is None:
316
+ return None
317
+ return resolve_route_tenant(cast("MutableMapping[str, Any]", scope), target.settings, target.receipt_state_keys)
318
+
319
+
320
+ class ConnectionCleanupMiddleware:
321
+ """ASGI middleware guaranteeing residual HTTP request connections are finalized and released.
322
+
323
+ Installs the request session holder that dependency providers fill and session stores
324
+ borrow from, and cleans up handed-over injected connections when a request aborts before
325
+ ``http.response.start`` as well as on-demand connections acquired after
326
+ ``http.response.start`` during streaming responses or ``after_response`` hooks.
327
+ """
328
+
329
+ __slots__ = ("_app", "_routing_targets", "_targets")
330
+
331
+ def __init__(self, app: "ASGIApp", *, targets: "tuple[_ConnectionCleanupTarget, ...]") -> None:
332
+ self._app = app
333
+ self._targets = targets
334
+ self._routing_targets = tuple(target for target in targets if target.enable_routing_middleware)
335
+
336
+ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
337
+ if scope.get("type") not in {ScopeType.HTTP, ScopeType.WEBSOCKET} or not self._targets:
338
+ await self._app(scope, receive, send)
339
+ return
340
+ with request_session_scope():
341
+ await self._route_request(scope, receive, send)
342
+
343
+ async def _route_request(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
344
+ if not self._routing_targets:
345
+ await self._run_request(scope, receive, send)
346
+ return
347
+ payload = RoutingContext.current() or RoutingContextPayload()
348
+ for target in self._routing_targets:
349
+ if target.default_routing_mode == "primary" and payload.get(target.bind_key) is None:
350
+ payload = payload.with_entry(target.bind_key, RoutingEntry("primary"))
351
+ cookie_header, routing_header_value = extract_asgi_routing_headers(
352
+ scope, target.routing_header_bytes, include_cookies=target.primary_pin_cookie is not None
353
+ )
354
+ payload = apply_request_routing_hints(
355
+ payload,
356
+ bind_key=target.bind_key,
357
+ routing_header_value=routing_header_value,
358
+ cookie_header=cookie_header,
359
+ primary_pin_cookie=target.primary_pin_cookie,
360
+ primary_pin_secret=target.primary_pin_secret,
361
+ )
362
+ async with RoutingContext.scope(payload):
363
+ await self._run_request(scope, receive, send)
364
+
365
+ async def _run_request(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
366
+ if not self._targets:
367
+ await self._app(scope, receive, send)
368
+ return
369
+
370
+ response_started = False
371
+ response_complete = False
372
+ response_status: int | None = None
373
+
374
+ async def send_wrapper(message: "Message") -> None:
375
+ nonlocal response_complete, response_started, response_status
376
+ if message["type"] == HTTP_RESPONSE_START:
377
+ response_started = True
378
+ response_status = message["status"]
379
+ elif str(message["type"]) == "http.response.pathsend" or (
380
+ message["type"] == "http.response.body" and not message.get("more_body", False)
381
+ ):
382
+ response_complete = True
383
+ await send(message)
384
+
385
+ caught_exc: BaseException | None = None
386
+ try:
387
+ await self._app(scope, receive, send_wrapper)
388
+ except BaseException as exc:
389
+ caught_exc = exc
390
+ raise
391
+ finally:
392
+ started = response_started or bool(ScopeState.from_scope(scope).response_started)
393
+ try:
394
+ await self._cleanup_scope(
395
+ scope,
396
+ caught_exc=caught_exc,
397
+ response_started=started,
398
+ response_complete=response_complete,
399
+ response_status=response_status,
400
+ )
401
+ except Exception:
402
+ if caught_exc is None or isinstance(caught_exc, Exception):
403
+ raise
404
+
405
+ async def _cleanup_scope(
406
+ self,
407
+ scope: "Scope",
408
+ *,
409
+ caught_exc: BaseException | None,
410
+ response_started: bool,
411
+ response_complete: bool,
412
+ response_status: int | None,
413
+ ) -> None:
414
+ recorded_exc = get_sqlspec_scope_state(scope, _REQUEST_EXCEPTION_KEY)
415
+ if caught_exc is not None:
416
+ effective_exc: BaseException | None = caught_exc
417
+ elif recorded_exc is not None:
418
+ effective_exc = recorded_exc
419
+ elif not response_started or not response_complete:
420
+ effective_exc = asyncio.CancelledError()
421
+ else:
422
+ effective_exc = None
423
+
424
+ primary_exc: BaseException | None = None
425
+ for target in self._targets:
426
+ try:
427
+ ctx_scope_key = f"{target.connection_key}_ctx"
428
+ session_scope_key = f"{target.session_key}_instance"
429
+ deferred_scope_key = f"{target.session_key}_deferred"
430
+ stream_deferred_scope_key = f"{target.connection_key}_stream_deferred"
431
+ lock_scope_key = f"{target.connection_key}_lock"
432
+ connection = get_sqlspec_scope_state(scope, target.connection_key)
433
+ connection_cm = get_sqlspec_scope_state(scope, ctx_scope_key)
434
+
435
+ if connection is None and connection_cm is None:
436
+ delete_sqlspec_scope_state(scope, session_scope_key)
437
+ _pop_and_close_session(scope, deferred_scope_key)
438
+ delete_sqlspec_scope_state(scope, lock_scope_key)
439
+ delete_sqlspec_scope_state(scope, stream_deferred_scope_key)
440
+ continue
441
+
442
+ if effective_exc is not None and get_sqlspec_scope_state(scope, _REQUEST_EXCEPTION_KEY) is None:
443
+ set_sqlspec_scope_state(scope, _REQUEST_EXCEPTION_KEY, effective_exc)
444
+
445
+ session = get_sqlspec_scope_state(scope, session_scope_key)
446
+ transaction_target = (
447
+ session
448
+ if session is not None
449
+ else get_sqlspec_scope_state(scope, f"{target.connection_key}_session")
450
+ )
451
+ exc_override: BaseException | None = None
452
+ try:
453
+ if connection is not None and getattr(transaction_target or connection, "pinned_to_primary", True):
454
+ if effective_exc is not None:
455
+ with suppress(Exception):
456
+ await _finalize_request_transaction(transaction_target, connection, commit=False)
457
+ elif target.commit_mode == "manual":
458
+ await _finalize_request_transaction(transaction_target, connection, commit=False)
459
+ else:
460
+ commit_range = range(
461
+ 200, 400 if target.commit_mode == "autocommit_include_redirect" else 300
462
+ )
463
+ should_commit = (
464
+ response_status is not None
465
+ and (response_status in commit_range or response_status in target.extra_commit_statuses)
466
+ and response_status not in target.extra_rollback_statuses
467
+ )
468
+ await _finalize_request_transaction(transaction_target, connection, commit=should_commit)
469
+ except BaseException as finalization_exc:
470
+ exc_override = finalization_exc
471
+ raise
472
+ finally:
473
+ try:
474
+ await _release_request_connection(
475
+ scope, target.connection_key, session_scope_key, connection, exc_override=exc_override
476
+ )
477
+ finally:
478
+ _pop_and_close_session(scope, deferred_scope_key)
479
+ delete_sqlspec_scope_state(scope, stream_deferred_scope_key)
480
+ delete_sqlspec_scope_state(scope, lock_scope_key)
481
+ except BaseException as exc:
482
+ primary_exc = _select_teardown_exception(primary_exc, exc)
483
+
484
+ if primary_exc is not None:
485
+ raise primary_exc
486
+
487
+
488
+ @dataclass
489
+ class PluginConfigState:
490
+ """Internal state for each database configuration."""
491
+
492
+ config: "DatabaseConfigProtocol[Any, Any, Any]"
493
+ connection_key: str
494
+ pool_key: str
495
+ session_key: str
496
+ commit_mode: CommitMode
497
+ extra_commit_statuses: "set[int] | None"
498
+ extra_rollback_statuses: "set[int] | None"
499
+ enable_correlation_middleware: bool
500
+ correlation_header: str
501
+ enable_sqlcommenter_middleware: bool
502
+ correlation_headers: tuple[str, ...] = field(init=False)
503
+ disable_di: bool
504
+ manage_lifespan: bool
505
+ tenant_settings: TenantResolutionSettings = field(default_factory=TenantResolutionSettings)
506
+ replica_connection_key: str = "db_replica_connection"
507
+ replica_pool_key: str = "db_replica_pool"
508
+ replica_session_key: str = "db_replica_session"
509
+ routing_session_key: str | None = None
510
+ default_routing_mode: str = "auto"
511
+ enable_routing_middleware: bool = True
512
+ routing_header: str | None = None
513
+ primary_pin_cookie: str | None = None
514
+ primary_pin_secret: bytes | None = None
515
+ connection_provider: "Callable[[State, Scope], AsyncGenerator[Any, None]] | None" = field(default=None, init=False)
516
+ pool_provider: "Callable[[State, Scope], Any] | None" = field(default=None, init=False)
517
+ session_provider: "Callable[..., AsyncGenerator[Any, None]] | None" = field(default=None, init=False)
518
+ before_send_handler: "BeforeMessageSendHookHandler | None" = field(default=None, init=False)
519
+ lifespan_handler: "Callable[[Litestar], AbstractAsyncContextManager[None]] | None" = field(default=None, init=False)
520
+ annotation: "type[DatabaseConfigProtocol[Any, Any, Any]] | None" = field(default=None, init=False)
521
+
522
+
523
+ class SQLSpecPlugin(InitPluginProtocol, CLIPlugin):
524
+ """Litestar plugin for SQLSpec database integration.
525
+
526
+ Automatically configures NumPy array serialization when NumPy is installed,
527
+ enabling seamless bidirectional conversion between NumPy arrays and JSON
528
+ for vector embedding workflows.
529
+
530
+ Session Table Migrations:
531
+ The Litestar extension includes migrations for creating session storage tables.
532
+ To include these migrations in your database migration workflow, add 'litestar'
533
+ to the include_extensions list in your migration configuration.
534
+ """
535
+
536
+ __slots__ = (
537
+ "_correlation_headers",
538
+ "_enable_sqlcommenter_middleware",
539
+ "_pagination_cursor_encrypted",
540
+ "_pagination_cursor_secret",
541
+ "_pagination_cursor_ttl",
542
+ "_plugin_configs",
543
+ "_sqlspec",
544
+ )
545
+
546
+ def __init__(
547
+ self,
548
+ sqlspec: "SQLSpec | AnyDatabaseConfig | Sequence[DatabaseConfigProtocol[Any, Any, Any]]",
549
+ *,
550
+ loader: "SQLFileLoader | None" = None,
551
+ pagination_cursor_secret: str | bytes | None = None,
552
+ pagination_cursor_ttl: float | dt.timedelta | None = None,
553
+ pagination_cursor_encrypted: bool | None = None,
554
+ ) -> None:
555
+ """Initialize SQLSpec plugin.
556
+
557
+ Args:
558
+ sqlspec: Pre-configured SQLSpec registry, a single database
559
+ configuration, or a sequence of database configurations.
560
+ loader: Optional SQL file loader instance attached to the registry.
561
+ pagination_cursor_secret: Optional application-wide cursor signing secret.
562
+ pagination_cursor_ttl: Optional default cursor expiration window.
563
+ pagination_cursor_encrypted: Optional default cursor encryption flag.
564
+ """
565
+ self._sqlspec = coerce_sqlspec(sqlspec, loader=loader)
566
+
567
+ self._plugin_configs: list[PluginConfigState] = []
568
+ extracted_settings: list[dict[str, Any]] = []
569
+ for cfg in self._sqlspec.configs.values():
570
+ config_union = cast("AnyDatabaseConfig", cfg)
571
+ settings = self._extract_extension_settings(config_union)
572
+ extracted_settings.append(settings)
573
+ state = self._config_state(config_union, settings)
574
+ self._plugin_configs.append(state)
575
+
576
+ self._pagination_cursor_secret, self._pagination_cursor_ttl, self._pagination_cursor_encrypted = (
577
+ resolve_plugin_cursor_settings(
578
+ extracted_settings,
579
+ pagination_cursor_secret=pagination_cursor_secret,
580
+ pagination_cursor_ttl=pagination_cursor_ttl,
581
+ pagination_cursor_encrypted=pagination_cursor_encrypted,
582
+ )
583
+ )
584
+
585
+ correlation_headers: list[str] = []
586
+ enable_sqlcommenter = False
587
+ for state in self._plugin_configs:
588
+ if state.enable_sqlcommenter_middleware and state.config.statement_config.enable_sqlcommenter:
589
+ enable_sqlcommenter = True
590
+ if not state.enable_correlation_middleware:
591
+ continue
592
+ for header in state.correlation_headers:
593
+ if header not in correlation_headers:
594
+ correlation_headers.append(header)
595
+ self._correlation_headers = tuple(correlation_headers)
596
+ self._enable_sqlcommenter_middleware = enable_sqlcommenter
597
+ log_with_context(
598
+ logger,
599
+ logging.DEBUG,
600
+ "extension.init",
601
+ framework="litestar",
602
+ stage="init",
603
+ config_count=len(self._plugin_configs),
604
+ correlation_headers=len(self._correlation_headers),
605
+ )
606
+
607
+ def _tenant_configs(self) -> "tuple[Any, ...]":
608
+ """Return the tenant-enabled configurations in registration order."""
609
+ return tuple(state.config for state in self._plugin_configs if has_tenant_strategy(state.config))
610
+
611
+ @property
612
+ def pagination_cursor_secret(self) -> str | bytes | None:
613
+ """Return resolved application-wide cursor secret."""
614
+ return self._pagination_cursor_secret
615
+
616
+ @property
617
+ def pagination_cursor_ttl(self) -> int | float | dt.timedelta | None:
618
+ """Return resolved application-wide cursor TTL."""
619
+ return self._pagination_cursor_ttl
620
+
621
+ @property
622
+ def pagination_cursor_encrypted(self) -> bool | None:
623
+ """Return resolved application-wide cursor encryption setting."""
624
+ return self._pagination_cursor_encrypted
625
+
626
+ @property
627
+ def sqlspec(self) -> SQLSpec:
628
+ """Return the underlying SQLSpec registry."""
629
+ return self._sqlspec
630
+
631
+ @property
632
+ def config(self) -> "list[AnyDatabaseConfig]":
633
+ """Return the plugin configurations.
634
+
635
+ Returns:
636
+ List of database configurations.
637
+ """
638
+ return [cast("AnyDatabaseConfig", state.config) for state in self._plugin_configs]
639
+
640
+ def on_cli_init(self, cli: "Group") -> None:
641
+ """Configure CLI commands for SQLSpec database operations.
642
+
643
+ Args:
644
+ cli: The Click command group to add commands to.
645
+ """
646
+ cli.add_command(database_group)
647
+
648
+ def on_app_init(self, app_config: "AppConfig") -> "AppConfig":
649
+ """Configure Litestar application with SQLSpec database integration.
650
+
651
+ Automatically registers NumPy array serialization when NumPy is installed.
652
+
653
+ Args:
654
+ app_config: The Litestar application configuration instance.
655
+
656
+ Returns:
657
+ The updated application configuration instance.
658
+ """
659
+ self._ensure_dependency_keys()
660
+ app_config.state.sqlspec = self
661
+ existing_plugins = cast("tuple[SQLSpecPlugin, ...]", getattr(app_config.state, "_sqlspec_plugins", ()))
662
+ if self not in existing_plugins:
663
+ app_config.state._sqlspec_plugins = (*existing_plugins, self)
664
+ app_config.signature_types.extend([SQLSpec, DatabaseConfigProtocol, SyncConfigT, AsyncConfigT])
665
+
666
+ signature_namespace = {"ConnectionT": ConnectionT, "PoolT": PoolT, "DriverT": DriverT, "SchemaT": SchemaT}
667
+
668
+ for state in self._plugin_configs:
669
+ state.annotation = type(state.config)
670
+ app_config.signature_types.append(state.annotation)
671
+ app_config.signature_types.append(state.config.connection_type)
672
+ app_config.signature_types.append(state.config.driver_type)
673
+
674
+ signature_namespace.update(state.config.get_signature_namespace())
675
+
676
+ if state.manage_lifespan:
677
+ if state.lifespan_handler is None:
678
+ self._raise_lifespan_handler_not_initialized(state.session_key)
679
+ app_config.lifespan.append(state.lifespan_handler)
680
+
681
+ if not state.disable_di:
682
+ if (
683
+ state.connection_provider is None
684
+ or state.pool_provider is None
685
+ or state.session_provider is None
686
+ or state.before_send_handler is None
687
+ ):
688
+ self._raise_di_handlers_not_initialized(state.session_key)
689
+ app_config.before_send.append(state.before_send_handler)
690
+ app_config.dependencies.update({
691
+ state.connection_key: Provide(state.connection_provider),
692
+ state.pool_key: Provide(state.pool_provider),
693
+ state.session_key: Provide(state.session_provider),
694
+ state.replica_connection_key: Provide(
695
+ db_replica_connection_provider_maker(state.config, state.replica_connection_key)
696
+ ),
697
+ state.replica_pool_key: Provide(
698
+ db_replica_pool_provider_maker(state.pool_key, state.replica_pool_key)
699
+ ),
700
+ state.replica_session_key: Provide(
701
+ db_replica_session_provider_maker(state.config, state.replica_session_key)
702
+ ),
703
+ })
704
+ if state.routing_session_key is not None:
705
+ app_config.dependencies[state.routing_session_key] = Provide(
706
+ db_routing_session_provider_maker(state.config, state.routing_session_key)
707
+ )
708
+
709
+ if self._plugin_configs:
710
+ if app_config.after_exception is None:
711
+ app_config.after_exception = []
712
+ if record_request_exception not in app_config.after_exception:
713
+ app_config.after_exception.append(record_request_exception)
714
+
715
+ if signature_namespace:
716
+ app_config.signature_namespace.update(signature_namespace)
717
+
718
+ if NUMPY_INSTALLED and (ndarray_type := _get_litestar_numpy_array_type()) is not None:
719
+ import numpy as np
720
+
721
+ numpy_namespace = _NumpySignatureNamespace(np, ndarray_type)
722
+ app_config.signature_namespace.update({
723
+ "np": numpy_namespace,
724
+ "numpy": numpy_namespace,
725
+ "ndarray": ndarray_type,
726
+ })
727
+
728
+ if not any(isinstance(p, _OffsetPaginationSchemaPlugin) for p in app_config.plugins):
729
+ app_config.plugins.append(_OffsetPaginationSchemaPlugin())
730
+
731
+ if app_config.exception_handlers is None:
732
+ app_config.exception_handlers = {}
733
+ app_config.exception_handlers.setdefault(NotFoundError, not_found_error_handler)
734
+ app_config.exception_handlers.setdefault(IntegrityError, integrity_error_handler)
735
+
736
+ app_config.type_encoders = {**DEFAULT_TYPE_ENCODERS, **(app_config.type_encoders or {})}
737
+ sqlspec_decoders = _build_litestar_type_decoders()
738
+ if sqlspec_decoders:
739
+ app_config.type_decoders = [*(app_config.type_decoders or []), *sqlspec_decoders]
740
+
741
+ new_middlewares: list[DefineMiddleware] = []
742
+ tenant_targets = self._tenant_targets()
743
+ if self._correlation_headers:
744
+ existing_correlation = _find_correlation_middleware(app_config.middleware)
745
+ if existing_correlation is not None:
746
+ headers_honored = self._correlation_headers == TRACE_CONTEXT_FALLBACK_HEADERS or (
747
+ isinstance(existing_correlation, DefineMiddleware)
748
+ and tuple(existing_correlation.kwargs.get("headers", ())) == self._correlation_headers
749
+ )
750
+ log_with_context(
751
+ logger,
752
+ logging.DEBUG if headers_honored else logging.WARNING,
753
+ "extension.init",
754
+ framework="litestar",
755
+ stage="correlation_middleware_skipped",
756
+ reason="already_installed",
757
+ unapplied_correlation_headers=None if headers_honored else list(self._correlation_headers),
758
+ )
759
+ else:
760
+ new_middlewares.append(DefineMiddleware(CorrelationMiddleware, headers=self._correlation_headers))
761
+ if self._enable_sqlcommenter_middleware:
762
+ new_middlewares.append(DefineMiddleware(SQLCommenterMiddleware))
763
+ cleanup_targets = tuple(
764
+ _ConnectionCleanupTarget(
765
+ connection_key=state.connection_key,
766
+ session_key=state.session_key,
767
+ commit_mode=state.commit_mode,
768
+ bind_key=state.config.bind_key,
769
+ default_routing_mode=state.default_routing_mode,
770
+ enable_routing_middleware=_uses_request_routing(state),
771
+ routing_header_bytes=state.routing_header.lower().encode("ascii")
772
+ if state.routing_header is not None
773
+ else None,
774
+ primary_pin_cookie=state.primary_pin_cookie,
775
+ primary_pin_secret=state.primary_pin_secret,
776
+ extra_commit_statuses=frozenset(state.extra_commit_statuses or ()),
777
+ extra_rollback_statuses=frozenset(state.extra_rollback_statuses or ()),
778
+ )
779
+ for state in self._plugin_configs
780
+ ) + tuple(
781
+ _ConnectionCleanupTarget(
782
+ connection_key=key,
783
+ session_key=key,
784
+ commit_mode=mode,
785
+ extra_commit_statuses=frozenset(state.extra_commit_statuses or ()),
786
+ extra_rollback_statuses=frozenset(state.extra_rollback_statuses or ()),
787
+ )
788
+ for state in self._plugin_configs
789
+ for key, mode in _resource_cleanup_modes(state)
790
+ if key is not None
791
+ )
792
+ if cleanup_targets:
793
+ existing_cleanup = _find_cleanup_middleware(app_config.middleware)
794
+ if isinstance(existing_cleanup, DefineMiddleware):
795
+ prior_targets = tuple(existing_cleanup.kwargs.get("targets", ()))
796
+ seen_keys = {item.connection_key for item in prior_targets}
797
+ merged_targets = prior_targets + tuple(
798
+ item for item in cleanup_targets if item.connection_key not in seen_keys
799
+ )
800
+ existing_cleanup.kwargs["targets"] = merged_targets
801
+ elif existing_cleanup is None:
802
+ new_middlewares.append(DefineMiddleware(ConnectionCleanupMiddleware, targets=cleanup_targets))
803
+ if new_middlewares:
804
+ app_config.middleware = [*new_middlewares, *(app_config.middleware or [])]
805
+ if tenant_targets:
806
+ app_config.middleware = [
807
+ *(app_config.middleware or []),
808
+ DefineMiddleware(SQLSpecTenantRequestMiddleware, targets=tenant_targets),
809
+ ]
810
+
811
+ log_with_context(
812
+ logger,
813
+ logging.DEBUG,
814
+ "extension.init",
815
+ framework="litestar",
816
+ stage="configured",
817
+ config_count=len(self._plugin_configs),
818
+ correlation_headers=len(self._correlation_headers),
819
+ numpy_enabled=bool(NUMPY_INSTALLED),
820
+ )
821
+ return app_config
822
+
823
+ def get_annotations(self) -> "list[type[AnyDatabaseConfig]]":
824
+ """Return the list of annotations.
825
+
826
+ Returns:
827
+ List of annotations.
828
+ """
829
+ annotations: list[type[AnyDatabaseConfig]] = []
830
+ for state in self._plugin_configs:
831
+ if state.annotation is None:
832
+ self._raise_plugin_not_registered()
833
+ annotations.append(cast("type[AnyDatabaseConfig]", state.annotation))
834
+ return annotations
835
+
836
+ def get_annotation(self, key: "str | AnyDatabaseConfig | type[AnyDatabaseConfig]") -> "type[AnyDatabaseConfig]":
837
+ """Return the annotation for the given configuration.
838
+
839
+ Args:
840
+ key: The configuration instance or key to lookup.
841
+
842
+ Raises:
843
+ KeyError: If no configuration is found for the given key.
844
+
845
+ Returns:
846
+ The annotation for the configuration.
847
+ """
848
+ state = self._get_plugin_state(cast("Any", key))
849
+ if state.annotation is None:
850
+ self._raise_plugin_not_registered()
851
+ return cast("type[AnyDatabaseConfig]", state.annotation)
852
+
853
+ @overload
854
+ def get_config(self, name: None = None) -> "AnyDatabaseConfig": ...
855
+ @overload
856
+ def get_config(
857
+ self, name: "type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]"
858
+ ) -> "SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]": ...
859
+ @overload
860
+ def get_config(
861
+ self, name: "type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]"
862
+ ) -> "AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]": ...
863
+ @overload
864
+ def get_config(self, name: "SyncConfigT") -> "SyncConfigT": ...
865
+ @overload
866
+ def get_config(self, name: "AsyncConfigT") -> "AsyncConfigT": ...
867
+ @overload
868
+ def get_config(self, name: str) -> "AnyDatabaseConfig": ...
869
+ def get_config(
870
+ self, name: "type[DatabaseConfigProtocol[Any, Any, Any]] | str | Any" = None
871
+ ) -> "DatabaseConfigProtocol[Any, Any, Any]":
872
+ """Get a configuration instance by name, or the sole configuration when omitted.
873
+
874
+ Registry identifiers are available as soon as the plugin is constructed: a
875
+ config instance, its concrete config type when exactly one configuration has
876
+ that type, or a non-null ``bind_key``. A ``bind_key`` wins over a dependency
877
+ key of the same value. The generated Litestar dependency keys
878
+ (``session_key``, ``connection_key``, ``pool_key``) resolve only after the
879
+ plugin is registered with a Litestar application.
880
+
881
+ Args:
882
+ name: Optional configuration identifier. Defaults to the sole registered
883
+ configuration when ``None``.
884
+
885
+ Raises:
886
+ KeyError: If no configuration is found for ``name``, if ``name`` is
887
+ ``None`` when zero or multiple configurations are registered, or if
888
+ several configurations share the requested concrete type.
889
+
890
+ Returns:
891
+ The configuration instance for the specified identifier.
892
+ """
893
+ if name is None:
894
+ if len(self._plugin_configs) == 1:
895
+ return self._plugin_configs[0].config
896
+ if not self._plugin_configs:
897
+ msg = "No database configurations are registered on SQLSpecPlugin."
898
+ raise KeyError(msg)
899
+ msg = (
900
+ "Multiple database configurations are registered on SQLSpecPlugin; "
901
+ f"pass a configuration key, type, or instance. Available keys: {self._get_available_keys()}"
902
+ )
903
+ raise KeyError(msg)
904
+ state = self._registry_state(name) or self._dependency_state(name)
905
+ return cast("DatabaseConfigProtocol[Any, Any, Any]", state.config) # type: ignore[redundant-cast]
906
+
907
+ def resolve_tenant_settings(
908
+ self, key: "str | AnyDatabaseConfig | type[AnyDatabaseConfig] | None" = None
909
+ ) -> TenantResolutionSettings:
910
+ """Resolve tenant extraction settings for a registered Litestar configuration.
911
+
912
+ Args:
913
+ key: Optional configuration key, concrete type, or instance. When
914
+ omitted, prefers the sole tenant-enforced configuration, then the
915
+ sole configuration, or raises when multiple tenant databases define
916
+ distinct settings.
917
+
918
+ Returns:
919
+ The active ``TenantResolutionSettings`` for ``key``.
920
+
921
+ Raises:
922
+ KeyError: ``key`` does not match any registered configuration.
923
+ ImproperConfigurationError: ``key`` is omitted and multiple tenant
924
+ databases configure distinct ``TenantResolutionSettings``.
925
+ """
926
+ if key is not None:
927
+ state = self._registry_state(key) or self._dependency_state(key)
928
+ return state.tenant_settings
929
+ tenant_states = [state for state in self._plugin_configs if has_tenant_strategy(state.config)]
930
+ if len(tenant_states) == 1:
931
+ return tenant_states[0].tenant_settings
932
+ if tenant_states:
933
+ first = tenant_states[0].tenant_settings
934
+ if any(state.tenant_settings != first for state in tenant_states[1:]):
935
+ msg = (
936
+ "Multiple tenant-scoped Litestar configurations have distinct tenant resolution settings; "
937
+ "pass config_key=... to require_tenant()."
938
+ )
939
+ raise ImproperConfigurationError(msg)
940
+ return first
941
+ if len(self._plugin_configs) == 1:
942
+ return self._plugin_configs[0].tenant_settings
943
+ if self._plugin_configs and all(
944
+ state.tenant_settings == self._plugin_configs[0].tenant_settings for state in self._plugin_configs[1:]
945
+ ):
946
+ return self._plugin_configs[0].tenant_settings
947
+ return TenantResolutionSettings()
948
+
949
+ def get_db_replica_session(self, request: Any, key: Any = None) -> Any:
950
+ """Return the request's lazy replica session view."""
951
+ selected, state, scope = self._read_request_parts(request, key)
952
+ return self._request_resource(selected.config, state, scope, "session")
953
+
954
+ def provide_db_replica_session(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
955
+ """Return the request-owned replica session without eager async checkout."""
956
+ return self._request_resource(key, state, scope, "session")
957
+
958
+ def provide_db_replica_session_sync(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
959
+ """Return the synchronous request replica session view."""
960
+ return self._request_resource(key, state, scope, "session")
961
+
962
+ async def provide_db_replica_session_async(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
963
+ """Open and return the request-owned replica session."""
964
+ selected = self._plugin_configs[0] if key is None else self._registry_state(key)
965
+ if selected is None:
966
+ selected = self._get_plugin_state(cast("Any", key))
967
+ resource_key = selected.replica_session_key
968
+ if resource_key is None or scope is None:
969
+ msg = "A request scope and configured resource key are required"
970
+ raise ImproperConfigurationError(msg)
971
+ return await _open_request_resource_async(selected.config, scope, resource_key, "session")
972
+
973
+ def get_db_replica_connection(self, request: Any, key: Any = None) -> Any:
974
+ """Return the request's lazy replica connection view."""
975
+ selected, state, scope = self._read_request_parts(request, key)
976
+ return self._request_resource(selected.config, state, scope, "connection")
977
+
978
+ def provide_db_replica_connection(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
979
+ """Return the request-owned replica connection without eager async checkout."""
980
+ return self._request_resource(key, state, scope, "connection")
981
+
982
+ def provide_db_replica_connection_sync(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
983
+ """Return the synchronous request replica connection view."""
984
+ return self._request_resource(key, state, scope, "connection")
985
+
986
+ async def provide_db_replica_connection_async(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
987
+ """Open and return the request-owned replica connection."""
988
+ selected = self._plugin_configs[0] if key is None else self._registry_state(key)
989
+ if selected is None:
990
+ selected = self._get_plugin_state(cast("Any", key))
991
+ resource_key = selected.replica_connection_key
992
+ if resource_key is None or scope is None:
993
+ msg = "A request scope and configured resource key are required"
994
+ raise ImproperConfigurationError(msg)
995
+ return await _open_request_resource_async(selected.config, scope, resource_key, "connection")
996
+
997
+ def get_db_routing_session(self, request: Any, key: Any = None) -> Any:
998
+ """Return the request's lazy routing session view."""
999
+ selected, state, scope = self._read_request_parts(request, key)
1000
+ return self._request_resource(selected.config, state, scope, "routing")
1001
+
1002
+ def provide_db_routing_session(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
1003
+ """Return the request-owned routing session without eager async checkout."""
1004
+ return self._request_resource(key, state, scope, "routing")
1005
+
1006
+ def provide_db_routing_session_sync(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
1007
+ """Return the synchronous request routing session view."""
1008
+ return self._request_resource(key, state, scope, "routing")
1009
+
1010
+ async def provide_db_routing_session_async(self, key: Any = None, state: Any = None, scope: Any = None) -> Any:
1011
+ """Open and return the request-owned routing session."""
1012
+ selected = self._plugin_configs[0] if key is None else self._registry_state(key)
1013
+ if selected is None:
1014
+ selected = self._get_plugin_state(cast("Any", key))
1015
+ resource_key = selected.routing_session_key
1016
+ if resource_key is None or scope is None:
1017
+ msg = "A request scope and configured resource key are required"
1018
+ raise ImproperConfigurationError(msg)
1019
+ return await _open_request_resource_async(selected.config, scope, resource_key, "routing")
1020
+
1021
+ @overload
1022
+ def provide_request_session(
1023
+ self,
1024
+ key: "SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT] | type[SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]]",
1025
+ state: "State",
1026
+ scope: "Scope",
1027
+ ) -> "DriverT": ...
1028
+ @overload
1029
+ def provide_request_session(
1030
+ self,
1031
+ key: "AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT] | type[AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]]",
1032
+ state: "State",
1033
+ scope: "Scope",
1034
+ ) -> "DriverT": ...
1035
+ @overload
1036
+ def provide_request_session(
1037
+ self, key: str, state: "State", scope: "Scope"
1038
+ ) -> "SyncDriverAdapterBase | AsyncDriverAdapterBase": ...
1039
+ @deprecated("0.72.0", removal_in="0.74.0", alternative="provide_db_session", kind="method")
1040
+ def provide_request_session(
1041
+ self, key: "str | AnyDatabaseConfig | type[AnyDatabaseConfig]", state: "State", scope: "Scope"
1042
+ ) -> "SyncDriverAdapterBase | AsyncDriverAdapterBase":
1043
+ """Deprecated alias of :meth:`provide_db_session`."""
1044
+ return self.provide_db_session(key, state, scope)
1045
+
1046
+ @overload
1047
+ def provide_request_session_sync(
1048
+ self,
1049
+ key: "SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]",
1050
+ state: "State",
1051
+ scope: "Scope",
1052
+ ) -> "DriverT": ...
1053
+ @overload
1054
+ def provide_request_session_sync(
1055
+ self,
1056
+ key: "type[SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]]",
1057
+ state: "State",
1058
+ scope: "Scope",
1059
+ ) -> "DriverT": ...
1060
+ @overload
1061
+ def provide_request_session_sync(self, key: str, state: "State", scope: "Scope") -> "SyncDriverAdapterBase": ...
1062
+ @deprecated("0.72.0", removal_in="0.74.0", alternative="provide_db_session_sync", kind="method")
1063
+ def provide_request_session_sync(
1064
+ self,
1065
+ key: "str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]",
1066
+ state: "State",
1067
+ scope: "Scope",
1068
+ ) -> "SyncDriverAdapterBase | Any":
1069
+ """Deprecated alias of :meth:`provide_db_session_sync`."""
1070
+ return self.provide_db_session_sync(key, state, scope)
1071
+
1072
+ @overload
1073
+ async def provide_request_session_async(
1074
+ self,
1075
+ key: "AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]",
1076
+ state: "State",
1077
+ scope: "Scope",
1078
+ ) -> "DriverT": ...
1079
+ @overload
1080
+ async def provide_request_session_async(
1081
+ self,
1082
+ key: "type[AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]]",
1083
+ state: "State",
1084
+ scope: "Scope",
1085
+ ) -> "DriverT": ...
1086
+ @overload
1087
+ async def provide_request_session_async(
1088
+ self, key: str, state: "State", scope: "Scope"
1089
+ ) -> "AsyncDriverAdapterBase": ...
1090
+ @deprecated("0.72.0", removal_in="0.74.0", alternative="provide_db_session_async", kind="method")
1091
+ async def provide_request_session_async(
1092
+ self,
1093
+ key: "str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]",
1094
+ state: "State",
1095
+ scope: "Scope",
1096
+ ) -> "AsyncDriverAdapterBase | Any":
1097
+ """Deprecated alias of :meth:`provide_db_session_async`."""
1098
+ return await self.provide_db_session_async(key, state, scope)
1099
+
1100
+ @overload
1101
+ def provide_request_connection(
1102
+ self,
1103
+ key: "SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any] | AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]",
1104
+ state: "State",
1105
+ scope: "Scope",
1106
+ ) -> "ConnectionT": ...
1107
+ @overload
1108
+ def provide_request_connection(
1109
+ self,
1110
+ key: "type[SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any] | AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]]",
1111
+ state: "State",
1112
+ scope: "Scope",
1113
+ ) -> "ConnectionT": ...
1114
+ @overload
1115
+ def provide_request_connection(self, key: str, state: "State", scope: "Scope") -> Any: ...
1116
+ @deprecated("0.72.0", removal_in="0.74.0", alternative="provide_db_connection", kind="method")
1117
+ def provide_request_connection(
1118
+ self, key: "str | AnyDatabaseConfig | type[AnyDatabaseConfig]", state: "State", scope: "Scope"
1119
+ ) -> Any:
1120
+ """Deprecated alias of :meth:`provide_db_connection`."""
1121
+ return self.provide_db_connection(key, state, scope)
1122
+
1123
+ @overload
1124
+ def provide_request_connection_sync(
1125
+ self,
1126
+ key: "SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any]",
1127
+ state: "State",
1128
+ scope: "Scope",
1129
+ ) -> "ConnectionT": ...
1130
+ @overload
1131
+ def provide_request_connection_sync(
1132
+ self,
1133
+ key: "type[SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any]]",
1134
+ state: "State",
1135
+ scope: "Scope",
1136
+ ) -> "ConnectionT": ...
1137
+ @overload
1138
+ def provide_request_connection_sync(self, key: str, state: "State", scope: "Scope") -> Any: ...
1139
+ @deprecated("0.72.0", removal_in="0.74.0", alternative="provide_db_connection_sync", kind="method")
1140
+ def provide_request_connection_sync(
1141
+ self,
1142
+ key: "str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]",
1143
+ state: "State",
1144
+ scope: "Scope",
1145
+ ) -> Any:
1146
+ """Deprecated alias of :meth:`provide_db_connection_sync`."""
1147
+ return self.provide_db_connection_sync(key, state, scope)
1148
+
1149
+ @overload
1150
+ async def provide_request_connection_async(
1151
+ self,
1152
+ key: "AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]",
1153
+ state: "State",
1154
+ scope: "Scope",
1155
+ ) -> "ConnectionT": ...
1156
+ @overload
1157
+ async def provide_request_connection_async(
1158
+ self,
1159
+ key: "type[AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]]",
1160
+ state: "State",
1161
+ scope: "Scope",
1162
+ ) -> "ConnectionT": ...
1163
+ @overload
1164
+ async def provide_request_connection_async(self, key: str, state: "State", scope: "Scope") -> Any: ...
1165
+ @deprecated("0.72.0", removal_in="0.74.0", alternative="provide_db_connection_async", kind="method")
1166
+ async def provide_request_connection_async(
1167
+ self,
1168
+ key: "str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]",
1169
+ state: "State",
1170
+ scope: "Scope",
1171
+ ) -> Any:
1172
+ """Deprecated alias of :meth:`provide_db_connection_async`."""
1173
+ return await self.provide_db_connection_async(key, state, scope)
1174
+
1175
+ @overload
1176
+ def provide_db_session(
1177
+ self,
1178
+ key: "SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT] | type[SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]]",
1179
+ state: "State",
1180
+ scope: "Scope",
1181
+ ) -> "DriverT": ...
1182
+ @overload
1183
+ def provide_db_session(
1184
+ self,
1185
+ key: "AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT] | type[AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]]",
1186
+ state: "State",
1187
+ scope: "Scope",
1188
+ ) -> "DriverT": ...
1189
+ @overload
1190
+ def provide_db_session(
1191
+ self, key: str, state: "State", scope: "Scope"
1192
+ ) -> "SyncDriverAdapterBase | AsyncDriverAdapterBase": ...
1193
+ def provide_db_session(
1194
+ self, key: "str | AnyDatabaseConfig | type[AnyDatabaseConfig]", state: "State", scope: "Scope"
1195
+ ) -> "SyncDriverAdapterBase | AsyncDriverAdapterBase":
1196
+ """Provide a database session for the specified configuration key from request scope.
1197
+
1198
+ For a synchronous configuration the connection must already exist in scope; use
1199
+ ``provide_db_session_sync`` to check one out on demand. For an asynchronous
1200
+ configuration whose connection is not open yet, the session opens it on the first
1201
+ awaited call, with the same tenant resolution and commit or rollback handling as
1202
+ ``provide_db_session_async``.
1203
+
1204
+ Args:
1205
+ key: The configuration identifier (same as get_config).
1206
+ state: The Litestar application State object.
1207
+ scope: The ASGI scope containing the request context.
1208
+
1209
+ Returns:
1210
+ A driver session instance for the specified database configuration.
1211
+ """
1212
+ plugin_state = self._get_plugin_state(cast("Any", key))
1213
+ deferred_key = f"{plugin_state.session_key}_deferred"
1214
+ deferred = get_sqlspec_scope_state(scope, deferred_key)
1215
+ if deferred is not None:
1216
+ return cast("AsyncDriverAdapterBase", deferred)
1217
+ connection = get_sqlspec_scope_state(scope, plugin_state.connection_key)
1218
+ if connection is None:
1219
+ if plugin_state.config.is_async:
1220
+ deferred = self._create_deferred_session(plugin_state, state, scope)
1221
+ set_sqlspec_scope_state(scope, deferred_key, deferred)
1222
+ return cast("AsyncDriverAdapterBase", deferred)
1223
+ self._raise_missing_connection(plugin_state.connection_key)
1224
+ return self._get_or_create_db_session(plugin_state, connection, scope)
1225
+
1226
+ @overload
1227
+ def provide_db_session_sync(
1228
+ self,
1229
+ key: "SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]",
1230
+ state: "State",
1231
+ scope: "Scope",
1232
+ ) -> "DriverT": ...
1233
+ @overload
1234
+ def provide_db_session_sync(
1235
+ self,
1236
+ key: "type[SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]]",
1237
+ state: "State",
1238
+ scope: "Scope",
1239
+ ) -> "DriverT": ...
1240
+ @overload
1241
+ def provide_db_session_sync(self, key: str, state: "State", scope: "Scope") -> "SyncDriverAdapterBase": ...
1242
+ def provide_db_session_sync(
1243
+ self,
1244
+ key: "str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]",
1245
+ state: "State",
1246
+ scope: "Scope",
1247
+ ) -> "SyncDriverAdapterBase | Any":
1248
+ """Provide a sync database session for the specified configuration key from request scope.
1249
+
1250
+ If no connection exists in scope, one will be created from the pool and stored
1251
+ in scope for reuse. The connection will be cleaned up by the before_send handler.
1252
+ An asynchronous configuration returns the same deferred session as
1253
+ ``provide_db_session``.
1254
+
1255
+ Args:
1256
+ key: The configuration identifier (same as get_config).
1257
+ state: The Litestar application State object.
1258
+ scope: The ASGI scope containing the request context.
1259
+
1260
+ Returns:
1261
+ A sync driver session instance for the specified database configuration.
1262
+ """
1263
+ plugin_state = self._get_plugin_state(cast("Any", key))
1264
+ if plugin_state.config.is_async:
1265
+ return self.provide_db_session(plugin_state.session_key, state, scope)
1266
+ connection = self._ensure_connection_sync(plugin_state, state, scope)
1267
+ return cast("SyncDriverAdapterBase", self._get_or_create_db_session(plugin_state, connection, scope))
1268
+
1269
+ @overload
1270
+ async def provide_db_session_async(
1271
+ self,
1272
+ key: "AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]",
1273
+ state: "State",
1274
+ scope: "Scope",
1275
+ ) -> "DriverT": ...
1276
+ @overload
1277
+ async def provide_db_session_async(
1278
+ self,
1279
+ key: "type[AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]]",
1280
+ state: "State",
1281
+ scope: "Scope",
1282
+ ) -> "DriverT": ...
1283
+ @overload
1284
+ async def provide_db_session_async(self, key: str, state: "State", scope: "Scope") -> "AsyncDriverAdapterBase": ...
1285
+ async def provide_db_session_async(
1286
+ self,
1287
+ key: "str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]",
1288
+ state: "State",
1289
+ scope: "Scope",
1290
+ ) -> "AsyncDriverAdapterBase | Any":
1291
+ """Provide an async database session for the specified configuration key from request scope.
1292
+
1293
+ If no connection exists in scope, one will be created from the pool and stored
1294
+ in scope for reuse. The connection will be cleaned up by the before_send handler.
1295
+
1296
+ For sync configurations, use ``provide_db_session`` instead.
1297
+
1298
+ Args:
1299
+ key: The configuration identifier (same as get_config).
1300
+ state: The Litestar application State object.
1301
+ scope: The ASGI scope containing the request context.
1302
+
1303
+ Returns:
1304
+ An async driver session instance for the specified database configuration.
1305
+ """
1306
+ plugin_state = self._get_plugin_state(cast("Any", key))
1307
+ connection = await self._ensure_connection_async(plugin_state, state, scope)
1308
+ return cast(
1309
+ "AsyncDriverAdapterBase", await self._get_or_create_db_session_async(plugin_state, connection, scope)
1310
+ )
1311
+
1312
+ @overload
1313
+ def provide_db_connection(
1314
+ self,
1315
+ key: "SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any] | AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]",
1316
+ state: "State",
1317
+ scope: "Scope",
1318
+ ) -> "ConnectionT": ...
1319
+ @overload
1320
+ def provide_db_connection(
1321
+ self,
1322
+ key: "type[SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any] | AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]]",
1323
+ state: "State",
1324
+ scope: "Scope",
1325
+ ) -> "ConnectionT": ...
1326
+ @overload
1327
+ def provide_db_connection(self, key: str, state: "State", scope: "Scope") -> Any: ...
1328
+ def provide_db_connection(
1329
+ self, key: "str | AnyDatabaseConfig | type[AnyDatabaseConfig]", state: "State", scope: "Scope"
1330
+ ) -> Any:
1331
+ """Provide a database connection for the specified configuration key from request scope.
1332
+
1333
+ This method requires the connection to already exist in scope.
1334
+ For on-demand connection creation, use ``provide_db_connection_sync`` or
1335
+ ``provide_db_connection_async`` instead.
1336
+
1337
+ Args:
1338
+ key: The configuration identifier (same as get_config).
1339
+ state: The Litestar application State object.
1340
+ scope: The ASGI scope containing the request context.
1341
+
1342
+ Raises:
1343
+ ImproperConfigurationError: The connection is not open yet.
1344
+
1345
+ Returns:
1346
+ A database connection instance for the specified database configuration.
1347
+ """
1348
+ plugin_state = self._get_plugin_state(cast("Any", key))
1349
+ connection = get_sqlspec_scope_state(scope, plugin_state.connection_key)
1350
+ if connection is None:
1351
+ if plugin_state.config.is_async:
1352
+ raise_async_connection_required("await plugin.provide_db_connection_async(key, state, scope)")
1353
+ self._raise_missing_connection(plugin_state.connection_key)
1354
+ return connection
1355
+
1356
+ @overload
1357
+ def provide_db_connection_sync(
1358
+ self,
1359
+ key: "SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any]",
1360
+ state: "State",
1361
+ scope: "Scope",
1362
+ ) -> "ConnectionT": ...
1363
+ @overload
1364
+ def provide_db_connection_sync(
1365
+ self,
1366
+ key: "type[SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any]]",
1367
+ state: "State",
1368
+ scope: "Scope",
1369
+ ) -> "ConnectionT": ...
1370
+ @overload
1371
+ def provide_db_connection_sync(self, key: str, state: "State", scope: "Scope") -> Any: ...
1372
+ def provide_db_connection_sync(
1373
+ self,
1374
+ key: "str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]",
1375
+ state: "State",
1376
+ scope: "Scope",
1377
+ ) -> Any:
1378
+ """Provide a sync database connection for the specified configuration key from request scope.
1379
+
1380
+ If no connection exists in scope, one will be created from the pool and stored
1381
+ in scope for reuse. The connection will be cleaned up by the before_send handler.
1382
+
1383
+ For async configurations, use ``provide_db_connection_async`` instead.
1384
+
1385
+ Args:
1386
+ key: The configuration identifier (same as get_config).
1387
+ state: The Litestar application State object.
1388
+ scope: The ASGI scope containing the request context.
1389
+
1390
+ Raises:
1391
+ ImproperConfigurationError: The configuration is asynchronous and its connection is not open yet.
1392
+
1393
+ Returns:
1394
+ A database connection instance for the specified database configuration.
1395
+ """
1396
+ plugin_state = self._get_plugin_state(cast("Any", key))
1397
+ if plugin_state.config.is_async:
1398
+ return self.provide_db_connection(plugin_state.connection_key, state, scope)
1399
+ return self._ensure_connection_sync(plugin_state, state, scope)
1400
+
1401
+ @overload
1402
+ async def provide_db_connection_async(
1403
+ self,
1404
+ key: "AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]",
1405
+ state: "State",
1406
+ scope: "Scope",
1407
+ ) -> "ConnectionT": ...
1408
+ @overload
1409
+ async def provide_db_connection_async(
1410
+ self,
1411
+ key: "type[AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]]",
1412
+ state: "State",
1413
+ scope: "Scope",
1414
+ ) -> "ConnectionT": ...
1415
+ @overload
1416
+ async def provide_db_connection_async(self, key: str, state: "State", scope: "Scope") -> Any: ...
1417
+ async def provide_db_connection_async(
1418
+ self,
1419
+ key: "str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]",
1420
+ state: "State",
1421
+ scope: "Scope",
1422
+ ) -> Any:
1423
+ """Provide an async database connection for the specified configuration key from request scope.
1424
+
1425
+ If no connection exists in scope, one will be created from the pool and stored
1426
+ in scope for reuse. The connection will be cleaned up by the before_send handler.
1427
+
1428
+ For sync configurations, use ``provide_db_connection`` instead.
1429
+
1430
+ Args:
1431
+ key: The configuration identifier (same as get_config).
1432
+ state: The Litestar application State object.
1433
+ scope: The ASGI scope containing the request context.
1434
+
1435
+ Returns:
1436
+ A database connection instance for the specified database configuration.
1437
+ """
1438
+ plugin_state = self._get_plugin_state(cast("Any", key))
1439
+ return await self._ensure_connection_async(plugin_state, state, scope)
1440
+
1441
+ def _tenant_targets(self) -> "tuple[_TenantResolutionTarget, ...]":
1442
+ """Return the resolution inputs of every tenant-enabled configuration."""
1443
+ return tuple(
1444
+ _TenantResolutionTarget(
1445
+ config=state.config,
1446
+ settings=state.tenant_settings,
1447
+ receipt_state_keys=tuple(
1448
+ tenant_receipt_key(key)
1449
+ for key in (state.session_key, state.connection_key, getattr(state.config, "bind_key", None))
1450
+ if isinstance(key, str) and key
1451
+ ),
1452
+ )
1453
+ for state in self._plugin_configs
1454
+ if has_tenant_strategy(state.config)
1455
+ )
1456
+
1457
+ def _read_request_parts(self, request: Any, key: Any = None) -> tuple[PluginConfigState, Any, Any]:
1458
+ scope = request if isinstance(request, dict) else request.scope
1459
+ app = scope.get("app")
1460
+ state = app.state if app is not None else None
1461
+ selected = self._plugin_configs[0] if key is None else self._registry_state(key)
1462
+ if selected is None:
1463
+ selected = self._get_plugin_state(cast("Any", key))
1464
+ return selected, state, scope
1465
+
1466
+ def _request_resource(self, key: Any, state: Any, scope: Any, kind: str) -> Any:
1467
+ selected = self._plugin_configs[0] if key is None else self._registry_state(key)
1468
+ if selected is None:
1469
+ selected = self._get_plugin_state(cast("Any", key))
1470
+ if scope is None:
1471
+ msg = "A request scope is required"
1472
+ raise ImproperConfigurationError(msg)
1473
+ resource_key = (
1474
+ selected.replica_session_key
1475
+ if kind == "session"
1476
+ else selected.replica_connection_key
1477
+ if kind == "connection"
1478
+ else selected.routing_session_key
1479
+ )
1480
+ if resource_key is None:
1481
+ msg = "routing_session_key must be configured to use request routing sessions"
1482
+ raise ImproperConfigurationError(msg)
1483
+ current = get_sqlspec_scope_state(scope, resource_key)
1484
+ if current is not None:
1485
+ return current
1486
+ if selected.config.is_async:
1487
+ if kind == "connection":
1488
+ raise_async_connection_required("await plugin.provide_db_replica_connection_async(key, state, scope)")
1489
+ deferred_key = f"{resource_key}_deferred"
1490
+ deferred = get_sqlspec_scope_state(scope, deferred_key)
1491
+ if deferred is None:
1492
+ accessor = (
1493
+ "await plugin.provide_db_routing_session_async(key, state, scope)"
1494
+ if kind == "routing"
1495
+ else "await plugin.provide_db_replica_session_async(key, state, scope)"
1496
+ )
1497
+ deferred = DeferredAsyncSession(
1498
+ selected.config,
1499
+ lambda: _open_request_resource_async(selected.config, scope, resource_key, kind),
1500
+ lambda: get_sqlspec_scope_state(scope, resource_key),
1501
+ accessor,
1502
+ target_type=AsyncRoutingSession if kind == "routing" else None,
1503
+ )
1504
+ set_sqlspec_scope_state(scope, deferred_key, deferred)
1505
+ return deferred
1506
+ return _open_request_resource_sync(selected.config, scope, resource_key, kind)
1507
+
1508
+ def _extract_extension_settings(self, config: "AnyDatabaseConfig") -> "dict[str, Any]":
1509
+ """Extract Litestar settings from config.extension_config."""
1510
+ litestar_config = cast("LitestarConfig", config.extension_config.get("litestar", {}))
1511
+
1512
+ connection_key = litestar_config.get("connection_key", DEFAULT_CONNECTION_KEY)
1513
+ pool_key = litestar_config.get("pool_key", DEFAULT_POOL_KEY)
1514
+ session_key = litestar_config.get("session_key", DEFAULT_SESSION_KEY)
1515
+ commit_mode = resolve_extension_commit_mode(config, litestar_config, DEFAULT_COMMIT_MODE)
1516
+
1517
+ if not config.supports_connection_pooling and pool_key == DEFAULT_POOL_KEY:
1518
+ pool_key = f"_{DEFAULT_POOL_KEY}_{id(config)}"
1519
+
1520
+ correlation_header = str(litestar_config.get("correlation_header", DEFAULT_CORRELATION_HEADER)).lower()
1521
+ configured_headers = _normalize_header_list(litestar_config.get("correlation_headers"))
1522
+ auto_trace_headers = bool(litestar_config.get("auto_trace_headers", True))
1523
+
1524
+ disable_di = litestar_config.get("disable_di", False)
1525
+
1526
+ enable_routing, routing_header, primary_pin_cookie, primary_pin_secret = validate_routing_middleware_settings(
1527
+ enable_routing_middleware=litestar_config.get("enable_routing_middleware", True),
1528
+ routing_header=litestar_config.get("routing_header"),
1529
+ primary_pin_cookie=litestar_config.get("primary_pin_cookie"),
1530
+ primary_pin_secret=litestar_config.get("primary_pin_secret"),
1531
+ )
1532
+
1533
+ return {
1534
+ "tenant_settings": TenantResolutionSettings.from_extension_config(litestar_config),
1535
+ "connection_key": connection_key,
1536
+ "pool_key": pool_key,
1537
+ "session_key": session_key,
1538
+ "replica_connection_key": litestar_config.get(
1539
+ "replica_connection_key",
1540
+ "db_replica_connection" if connection_key == DEFAULT_CONNECTION_KEY else f"{connection_key}_replica",
1541
+ ),
1542
+ "replica_pool_key": litestar_config.get(
1543
+ "replica_pool_key", "db_replica_pool" if pool_key == DEFAULT_POOL_KEY else f"{pool_key}_replica"
1544
+ ),
1545
+ "replica_session_key": litestar_config.get(
1546
+ "replica_session_key",
1547
+ "db_replica_session" if session_key == DEFAULT_SESSION_KEY else f"{session_key}_replica",
1548
+ ),
1549
+ "routing_session_key": litestar_config.get("routing_session_key"),
1550
+ "default_routing_mode": litestar_config.get("default_routing_mode", "auto"),
1551
+ "enable_routing_middleware": enable_routing,
1552
+ "routing_header": routing_header,
1553
+ "primary_pin_cookie": primary_pin_cookie,
1554
+ "primary_pin_secret": primary_pin_secret,
1555
+ "commit_mode": commit_mode,
1556
+ "extra_commit_statuses": litestar_config.get("extra_commit_statuses"),
1557
+ "extra_rollback_statuses": litestar_config.get("extra_rollback_statuses"),
1558
+ "enable_correlation_middleware": litestar_config.get("enable_correlation_middleware", True),
1559
+ "correlation_header": correlation_header,
1560
+ "correlation_headers": _build_correlation_headers(
1561
+ primary=correlation_header, configured=configured_headers, auto_trace_headers=auto_trace_headers
1562
+ ),
1563
+ "disable_di": disable_di,
1564
+ "manage_lifespan": litestar_config.get("manage_lifespan", not disable_di),
1565
+ "enable_sqlcommenter_middleware": litestar_config.get("enable_sqlcommenter_middleware", True),
1566
+ "pagination_cursor_secret": litestar_config.get("pagination_cursor_secret"),
1567
+ "pagination_cursor_ttl": litestar_config.get("pagination_cursor_ttl"),
1568
+ "pagination_cursor_encrypted": litestar_config.get("pagination_cursor_encrypted"),
1569
+ }
1570
+
1571
+ def _config_state(self, config: "AnyDatabaseConfig", settings: "dict[str, Any]") -> PluginConfigState:
1572
+ """Create plugin state with handlers for the given configuration."""
1573
+ state = PluginConfigState(
1574
+ config=config,
1575
+ connection_key=settings["connection_key"],
1576
+ pool_key=settings["pool_key"],
1577
+ session_key=settings["session_key"],
1578
+ commit_mode=settings["commit_mode"],
1579
+ extra_commit_statuses=settings.get("extra_commit_statuses"),
1580
+ extra_rollback_statuses=settings.get("extra_rollback_statuses"),
1581
+ enable_correlation_middleware=settings["enable_correlation_middleware"],
1582
+ correlation_header=settings["correlation_header"],
1583
+ enable_sqlcommenter_middleware=settings["enable_sqlcommenter_middleware"],
1584
+ disable_di=settings["disable_di"],
1585
+ manage_lifespan=settings["manage_lifespan"],
1586
+ tenant_settings=settings["tenant_settings"],
1587
+ replica_connection_key=settings["replica_connection_key"],
1588
+ replica_pool_key=settings["replica_pool_key"],
1589
+ replica_session_key=settings["replica_session_key"],
1590
+ routing_session_key=settings["routing_session_key"],
1591
+ default_routing_mode=settings["default_routing_mode"],
1592
+ enable_routing_middleware=settings["enable_routing_middleware"],
1593
+ routing_header=settings["routing_header"],
1594
+ primary_pin_cookie=settings["primary_pin_cookie"],
1595
+ primary_pin_secret=settings["primary_pin_secret"],
1596
+ )
1597
+ state.correlation_headers = tuple(settings["correlation_headers"])
1598
+
1599
+ if state.manage_lifespan:
1600
+ state.lifespan_handler = lifespan_handler_maker(
1601
+ config, state.pool_key, replica_pool_key=state.replica_pool_key
1602
+ )
1603
+ if not state.disable_di:
1604
+ self._setup_di_handlers(state)
1605
+ return state
1606
+
1607
+ def _setup_di_handlers(self, state: PluginConfigState) -> None:
1608
+ """Build the dependency providers and before-send handler for the plugin state."""
1609
+ connection_key = state.connection_key
1610
+ pool_key = state.pool_key
1611
+ session_scope_key = f"{state.session_key}_instance"
1612
+ commit_mode = state.commit_mode
1613
+ config = state.config
1614
+
1615
+ state.connection_provider = db_connection_provider_maker(config, pool_key, connection_key)
1616
+ state.pool_provider = db_pool_provider_maker(config, pool_key)
1617
+ state.session_provider = db_session_provider_maker(
1618
+ config, connection_key, session_scope_key=session_scope_key, commit_mode=commit_mode
1619
+ )
1620
+
1621
+ if commit_mode == "manual":
1622
+ state.before_send_handler = manual_handler_maker(connection_key, session_scope_key=session_scope_key)
1623
+ else:
1624
+ commit_on_redirect = commit_mode == "autocommit_include_redirect"
1625
+ state.before_send_handler = autocommit_handler_maker(
1626
+ connection_key,
1627
+ commit_on_redirect,
1628
+ state.extra_commit_statuses,
1629
+ state.extra_rollback_statuses,
1630
+ session_scope_key=session_scope_key,
1631
+ )
1632
+
1633
+ def _ensure_connection_sync(self, plugin_state: PluginConfigState, state: "State", scope: "Scope") -> Any:
1634
+ """Ensure a connection exists in scope, creating one from the pool if needed (sync)."""
1635
+ connection = get_sqlspec_scope_state(scope, plugin_state.connection_key)
1636
+ if connection is not None:
1637
+ return connection
1638
+
1639
+ pool = state.get(plugin_state.pool_key)
1640
+ if pool is None:
1641
+ self._raise_missing_connection(plugin_state.connection_key)
1642
+
1643
+ payload = _resolve_connection_tenant_sync(plugin_state.config, scope, plugin_state.connection_key)
1644
+ payload_key = tenant_payload_key(plugin_state.connection_key)
1645
+ set_sqlspec_scope_state(scope, payload_key, payload)
1646
+ try:
1647
+ with TenantContext.bind(payload):
1648
+ cm = cast("AbstractContextManager[Any]", plugin_state.config.provide_connection(pool))
1649
+ connection = cm.__enter__()
1650
+ except BaseException:
1651
+ delete_sqlspec_scope_state(scope, payload_key)
1652
+ raise
1653
+ set_sqlspec_scope_state(scope, f"{plugin_state.connection_key}_ctx", cm)
1654
+ set_sqlspec_scope_state(scope, plugin_state.connection_key, connection)
1655
+ return connection
1656
+
1657
+ async def _ensure_connection_async(self, plugin_state: PluginConfigState, state: "State", scope: "Scope") -> Any:
1658
+ """Ensure a connection exists in scope, creating one from the pool if needed (async)."""
1659
+ connection = get_sqlspec_scope_state(scope, plugin_state.connection_key)
1660
+ if connection is not None:
1661
+ return connection
1662
+
1663
+ pool = state.get(plugin_state.pool_key)
1664
+ if pool is None:
1665
+ self._raise_missing_connection(plugin_state.connection_key)
1666
+
1667
+ payload = await _resolve_connection_tenant_async(plugin_state.config, scope, plugin_state.connection_key)
1668
+ try:
1669
+ with TenantContext.bind(payload):
1670
+ cm = cast("AbstractAsyncContextManager[Any]", plugin_state.config.provide_connection(pool))
1671
+ connection = await cm.__aenter__()
1672
+ except BaseException:
1673
+ delete_sqlspec_scope_state(scope, tenant_payload_key(plugin_state.connection_key))
1674
+ raise
1675
+ set_sqlspec_scope_state(scope, f"{plugin_state.connection_key}_ctx", cm)
1676
+ set_sqlspec_scope_state(scope, plugin_state.connection_key, connection)
1677
+ return connection
1678
+
1679
+ def _create_deferred_session(self, plugin_state: PluginConfigState, state: "State", scope: "Scope") -> Any:
1680
+ """Return a session that opens the asynchronous request connection on its first awaited call."""
1681
+
1682
+ def current_session() -> Any:
1683
+ connection = get_sqlspec_scope_state(scope, plugin_state.connection_key)
1684
+ return None if connection is None else self._get_or_create_db_session(plugin_state, connection, scope)
1685
+
1686
+ return DeferredAsyncSession(
1687
+ plugin_state.config,
1688
+ lambda: self.provide_db_session_async(plugin_state.session_key, state, scope),
1689
+ current_session,
1690
+ "await plugin.provide_db_session_async(key, state, scope)",
1691
+ )
1692
+
1693
+ def _resolve_or_build_db_session(
1694
+ self, plugin_state: PluginConfigState, connection: Any, scope: "Scope"
1695
+ ) -> "tuple[SyncDriverAdapterBase | AsyncDriverAdapterBase, bool]":
1696
+ """Return the cached request session for this connection or build and cache a fresh one."""
1697
+ session_scope_key = f"{plugin_state.session_key}_instance"
1698
+ session = get_sqlspec_scope_state(scope, session_scope_key)
1699
+ if session is not None and getattr(session, "connection", None) is connection:
1700
+ set_sqlspec_scope_state(scope, f"{plugin_state.connection_key}_session", session)
1701
+ publish_request_session(plugin_state.config, session, manual=plugin_state.commit_mode == "manual")
1702
+ return cast("SyncDriverAdapterBase | AsyncDriverAdapterBase", session), False
1703
+
1704
+ session = build_db_session(plugin_state.config, connection, plugin_state.commit_mode)
1705
+ set_sqlspec_scope_state(scope, session_scope_key, session)
1706
+ set_sqlspec_scope_state(scope, f"{plugin_state.connection_key}_session", session)
1707
+ publish_request_session(plugin_state.config, session, manual=plugin_state.commit_mode == "manual")
1708
+ return cast("SyncDriverAdapterBase | AsyncDriverAdapterBase", session), True
1709
+
1710
+ def _get_or_create_db_session(
1711
+ self, plugin_state: PluginConfigState, connection: Any, scope: "Scope"
1712
+ ) -> "SyncDriverAdapterBase | AsyncDriverAdapterBase":
1713
+ """Create a session from a connection and store it in scope."""
1714
+ session, created = self._resolve_or_build_db_session(plugin_state, connection, scope)
1715
+ if created:
1716
+ runtime = session.observability
1717
+ if not runtime.is_idle:
1718
+ runtime.emit_session_start_sync(session)
1719
+ return session
1720
+
1721
+ async def _get_or_create_db_session_async(
1722
+ self, plugin_state: PluginConfigState, connection: Any, scope: "Scope"
1723
+ ) -> "SyncDriverAdapterBase | AsyncDriverAdapterBase":
1724
+ """Create a session from a connection, await async start hooks, and store it in scope."""
1725
+ session, created = self._resolve_or_build_db_session(plugin_state, connection, scope)
1726
+ if created:
1727
+ runtime = session.observability
1728
+ if not runtime.is_idle:
1729
+ await runtime.emit_session_start_async(session)
1730
+ return session
1731
+
1732
+ def _registry_state(self, name: Any) -> "PluginConfigState | None":
1733
+ """Resolve plugin state from registry identity, independent of Litestar registration.
1734
+
1735
+ Args:
1736
+ name: A ``bind_key``, a config instance, or a concrete config type.
1737
+
1738
+ Raises:
1739
+ KeyError: If several configurations share the requested concrete type.
1740
+
1741
+ Returns:
1742
+ The matching plugin state, or ``None`` when the identifier is not a
1743
+ registry identity.
1744
+ """
1745
+ if isinstance(name, str):
1746
+ for state in self._plugin_configs:
1747
+ if state.config.bind_key == name:
1748
+ return state
1749
+ return None
1750
+
1751
+ if isinstance(name, type):
1752
+ matches = [state for state in self._plugin_configs if type(state.config) is name]
1753
+ if len(matches) > 1:
1754
+ self._raise_ambiguous_config_type(name, matches)
1755
+ return matches[0] if matches else None
1756
+
1757
+ for state in self._plugin_configs:
1758
+ if state.config is name:
1759
+ return state
1760
+ return None
1761
+
1762
+ def _dependency_state(self, name: Any) -> PluginConfigState:
1763
+ """Resolve plugin state from a Litestar dependency key, which exists only after registration.
1764
+
1765
+ Args:
1766
+ name: A ``session_key``, ``connection_key``, or ``pool_key``.
1767
+
1768
+ Raises:
1769
+ KeyError: If ``name`` is not a known dependency key.
1770
+
1771
+ Returns:
1772
+ The matching plugin state.
1773
+ """
1774
+ if isinstance(name, str) and any(
1775
+ name
1776
+ in {
1777
+ state.connection_key,
1778
+ state.pool_key,
1779
+ state.session_key,
1780
+ state.replica_connection_key,
1781
+ state.replica_pool_key,
1782
+ state.replica_session_key,
1783
+ state.routing_session_key,
1784
+ }
1785
+ for state in self._plugin_configs
1786
+ ):
1787
+ if any(state.annotation is None for state in self._plugin_configs):
1788
+ self._raise_plugin_not_registered()
1789
+ return self._get_plugin_state(name)
1790
+ self._raise_config_not_found(name)
1791
+ msg = "unreachable"
1792
+ raise AssertionError(msg)
1793
+
1794
+ def _get_plugin_state(
1795
+ self, key: "str | DatabaseConfigProtocol[Any, Any, Any] | type[DatabaseConfigProtocol[Any, Any, Any]]"
1796
+ ) -> PluginConfigState:
1797
+ """Get plugin state for a configuration by Litestar dependency key, instance, or annotation."""
1798
+ if isinstance(key, str):
1799
+ for state in self._plugin_configs:
1800
+ if key in {
1801
+ state.connection_key,
1802
+ state.pool_key,
1803
+ state.session_key,
1804
+ state.replica_connection_key,
1805
+ state.replica_pool_key,
1806
+ state.replica_session_key,
1807
+ state.routing_session_key,
1808
+ }:
1809
+ return state
1810
+
1811
+ matches: list[PluginConfigState] = []
1812
+ for state in self._plugin_configs:
1813
+ if state.annotation is None:
1814
+ self._raise_plugin_not_registered()
1815
+ if key in {state.config, state.annotation}:
1816
+ matches.append(state)
1817
+
1818
+ if len(matches) > 1 and isinstance(key, type):
1819
+ self._raise_ambiguous_config_type(key, matches)
1820
+ if matches:
1821
+ return matches[0]
1822
+
1823
+ self._raise_config_not_found(key)
1824
+ msg = "unreachable"
1825
+ raise AssertionError(msg)
1826
+
1827
+ def _get_available_keys(self) -> "list[str]":
1828
+ """Get a list of all available configuration keys for error messages."""
1829
+ keys: list[str] = []
1830
+ for state in self._plugin_configs:
1831
+ for key in (state.config.bind_key, state.connection_key, state.pool_key, state.session_key):
1832
+ if key is not None and key not in keys:
1833
+ keys.append(key)
1834
+ return keys
1835
+
1836
+ def _ensure_dependency_keys(self) -> None:
1837
+ """Validate that connection and pool keys are unique across configurations."""
1838
+ seen: set[str] = set()
1839
+ for state in self._plugin_configs:
1840
+ for key in (
1841
+ state.connection_key,
1842
+ state.pool_key,
1843
+ state.session_key,
1844
+ state.replica_connection_key,
1845
+ state.replica_pool_key,
1846
+ state.replica_session_key,
1847
+ state.routing_session_key,
1848
+ ):
1849
+ if key is None:
1850
+ continue
1851
+ if key in seen:
1852
+ msg = f"Database dependency key {key!r} must be unique across connection_key, pool_key, session_key, read and routing keys"
1853
+ raise ImproperConfigurationError(msg)
1854
+ seen.add(key)
1855
+
1856
+ def _raise_missing_connection(self, connection_key: str) -> NoReturn:
1857
+ """Raise error when connection is not found in scope."""
1858
+ msg = f"No database connection found in scope for key '{connection_key}'. "
1859
+ msg += "Ensure the connection dependency is properly configured and available."
1860
+ raise ImproperConfigurationError(detail=msg)
1861
+
1862
+ def _raise_plugin_not_registered(self) -> NoReturn:
1863
+ """Raise error when plugin state is accessed before app registration."""
1864
+ msg = (
1865
+ "SQLSpec plugin has not been registered with a Litestar application. "
1866
+ "Register the plugin via Litestar(plugins=[...]) so on_app_init runs before accessing annotations."
1867
+ )
1868
+ raise ImproperConfigurationError(msg)
1869
+
1870
+ def _raise_di_handlers_not_initialized(self, session_key: str) -> NoReturn:
1871
+ """Raise error when DI handlers are missing for a DI-enabled configuration."""
1872
+ msg = (
1873
+ f"Dependency injection handlers were not initialized for configuration '{session_key}'. "
1874
+ "Handlers are created during plugin construction for configurations with dependency injection enabled."
1875
+ )
1876
+ raise ImproperConfigurationError(msg)
1877
+
1878
+ def _raise_lifespan_handler_not_initialized(self, session_key: str) -> NoReturn:
1879
+ """Raise error when the lifespan handler is missing for a lifespan-managed configuration."""
1880
+ msg = (
1881
+ f"Lifespan handler was not initialized for configuration '{session_key}'. "
1882
+ "Handlers are created during plugin construction for configurations with lifespan management enabled."
1883
+ )
1884
+ raise ImproperConfigurationError(msg)
1885
+
1886
+ def _raise_config_not_found(self, key: Any) -> NoReturn:
1887
+ """Raise error when configuration is not found."""
1888
+ msg = f"No database configuration found for name '{key}'. Available keys: {self._get_available_keys()}"
1889
+ raise KeyError(msg)
1890
+
1891
+ def _raise_ambiguous_config_type(self, config_type: type, candidates: "list[PluginConfigState]") -> NoReturn:
1892
+ """Raise error when several configurations share one concrete config type."""
1893
+ bind_keys = [state.config.bind_key or "<unbound>" for state in candidates]
1894
+ msg = (
1895
+ f"Multiple database configurations use the type '{config_type.__name__}'. "
1896
+ f"Pass the configuration instance instead. Candidate bind keys: {bind_keys}"
1897
+ )
1898
+ raise KeyError(msg)
1899
+
1900
+
1901
+ class SQLCommenterMiddleware:
1902
+ """ASGI middleware that populates SQLCommenterContext with Litestar request attributes.
1903
+
1904
+ Extracts route, controller, and action from the Litestar scope and sets them
1905
+ in :class:`~sqlspec.core.sqlcommenter.SQLCommenterContext` for the
1906
+ duration of the request.
1907
+ """
1908
+
1909
+ __slots__ = ("app",)
1910
+
1911
+ def __init__(self, app: "ASGIApp") -> None:
1912
+ self.app = app
1913
+
1914
+ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
1915
+ if str(scope.get("type")) != "http":
1916
+ await self.app(scope, receive, send)
1917
+ return
1918
+
1919
+ attrs: dict[str, str] = {"route": scope.get("path", ""), "framework": "litestar"}
1920
+ handler = scope.get("route_handler")
1921
+ if handler is not None and hasattr(handler, "fn") and hasattr(handler, "owner"):
1922
+ fn = handler.fn
1923
+ if fn is not None:
1924
+ fn_name = getattr(fn, "__name__", None)
1925
+ if isinstance(fn_name, str):
1926
+ attrs["action"] = fn_name
1927
+ owner = handler.owner
1928
+ if owner is not None:
1929
+ owner_name = getattr(owner, "__name__", None)
1930
+ if isinstance(owner_name, str):
1931
+ attrs["controller"] = owner_name
1932
+
1933
+ previous = SQLCommenterContext.get()
1934
+ SQLCommenterContext.set(attrs)
1935
+ try:
1936
+ await self.app(scope, receive, send)
1937
+ finally:
1938
+ SQLCommenterContext.set(previous)
1939
+
1940
+
1941
+ @dataclass(frozen=True, slots=True)
1942
+ class _ConnectionCleanupTarget:
1943
+ """Configuration descriptor for ASGI residual connection cleanup."""
1944
+
1945
+ connection_key: str
1946
+ session_key: str
1947
+ commit_mode: CommitMode
1948
+ extra_commit_statuses: frozenset[int]
1949
+ extra_rollback_statuses: frozenset[int]
1950
+ bind_key: str | None = None
1951
+ default_routing_mode: str = "auto"
1952
+ enable_routing_middleware: bool = False
1953
+ routing_header_bytes: bytes | None = None
1954
+ primary_pin_cookie: str | None = None
1955
+ primary_pin_secret: bytes | None = None
1956
+
1957
+
1958
+ class _OffsetPaginationSchemaPlugin(OpenAPISchemaPlugin):
1959
+ """OpenAPI schema plugin expanding OffsetPagination[T] into a concrete schema.
1960
+
1961
+ Expands the dataclass container into an object schema with items, limit,
1962
+ offset, and total, independently of Litestar's dataclass introspection.
1963
+ """
1964
+
1965
+ @staticmethod
1966
+ def is_plugin_supported_type(value: Any) -> bool:
1967
+ origin = getattr(value, "__origin__", value)
1968
+ return isinstance(origin, type) and issubclass(origin, OffsetPagination)
1969
+
1970
+ def to_openapi_schema(self, field_definition: "FieldDefinition", schema_creator: "SchemaCreator") -> "Schema":
1971
+ from litestar.openapi.spec import OpenAPIType, Schema
1972
+ from litestar.typing import FieldDefinition
1973
+
1974
+ inner_type: Any = Any
1975
+ inner_args = getattr(field_definition, "inner_types", ())
1976
+ if inner_args:
1977
+ inner_type = inner_args[0].annotation
1978
+
1979
+ item_schema = schema_creator.for_field_definition(FieldDefinition.from_annotation(inner_type))
1980
+
1981
+ return Schema(
1982
+ type=OpenAPIType.OBJECT,
1983
+ properties={
1984
+ "items": Schema(type=OpenAPIType.ARRAY, items=item_schema),
1985
+ "limit": Schema(type=OpenAPIType.INTEGER),
1986
+ "offset": Schema(type=OpenAPIType.INTEGER),
1987
+ "total": Schema(type=OpenAPIType.INTEGER),
1988
+ },
1989
+ required=["items", "limit", "offset", "total"],
1990
+ )
1991
+
1992
+
1993
+ class _NumpySignatureNamespace:
1994
+ """Proxy ``numpy`` module namespace that maps ``ndarray`` to SQLSpec's decoder-safe subclass."""
1995
+
1996
+ __slots__ = ("_numpy", "ndarray")
1997
+
1998
+ def __init__(self, numpy_module: Any, ndarray_type: type[Any]) -> None:
1999
+ self._numpy = numpy_module
2000
+ self.ndarray = ndarray_type
2001
+
2002
+ def __getattr__(self, name: str) -> Any:
2003
+ return getattr(self._numpy, name)
2004
+
2005
+
2006
+ def _resource_cleanup_modes(state: PluginConfigState) -> tuple[tuple[str | None, CommitMode], ...]:
2007
+ return (
2008
+ (state.replica_connection_key, "manual"),
2009
+ (state.replica_session_key, "manual"),
2010
+ (state.routing_session_key, state.commit_mode),
2011
+ )
2012
+
2013
+
2014
+ def _select_teardown_exception(current: BaseException | None, candidate: BaseException) -> BaseException:
2015
+ """Select the primary teardown exception to re-raise after completing all targets."""
2016
+ if current is None:
2017
+ return candidate
2018
+ if isinstance(current, Exception) and not isinstance(candidate, Exception):
2019
+ return candidate
2020
+ return current
2021
+
2022
+
2023
+ def _normalize_header_list(headers: Any) -> list[str]:
2024
+ if headers is None:
2025
+ return []
2026
+ if isinstance(headers, str):
2027
+ return [headers.lower()]
2028
+ if isinstance(headers, Iterable):
2029
+ normalized: list[str] = []
2030
+ for header in headers:
2031
+ if not isinstance(header, str):
2032
+ msg = "litestar correlation headers must be strings"
2033
+ raise ImproperConfigurationError(msg)
2034
+ normalized.append(header.lower())
2035
+ return normalized
2036
+ msg = "litestar correlation_headers must be a string or iterable of strings"
2037
+ raise ImproperConfigurationError(msg)
2038
+
2039
+
2040
+ def _dedupe_headers(headers: Iterable[str]) -> list[str]:
2041
+ seen: set[str] = set()
2042
+ ordered: list[str] = []
2043
+ for header in headers:
2044
+ lowered = header.lower()
2045
+ if lowered in seen or not lowered:
2046
+ continue
2047
+ seen.add(lowered)
2048
+ ordered.append(lowered)
2049
+ return ordered
2050
+
2051
+
2052
+ def _build_correlation_headers(*, primary: str, configured: list[str], auto_trace_headers: bool) -> tuple[str, ...]:
2053
+ header_order: list[str] = [primary.lower()]
2054
+ header_order.extend(configured)
2055
+ if auto_trace_headers:
2056
+ header_order.extend(TRACE_CONTEXT_FALLBACK_HEADERS)
2057
+ return tuple(_dedupe_headers(header_order))
2058
+
2059
+
2060
+ def _find_correlation_middleware(middleware: "Iterable[Middleware] | None") -> "Middleware | None":
2061
+ """Return the first entry in the middleware stack that installs :class:`CorrelationMiddleware`.
2062
+
2063
+ Matches :class:`CorrelationMiddleware` or a subclass, either as a bare class or wrapped in
2064
+ :class:`litestar.middleware.DefineMiddleware`. Factories such as :func:`functools.partial`,
2065
+ middleware added after the plugin's ``on_app_init`` runs, and router, controller, or route
2066
+ middleware are not detected.
2067
+ """
2068
+ for entry in middleware or ():
2069
+ candidate = entry.middleware if isinstance(entry, DefineMiddleware) else entry
2070
+ if isinstance(candidate, type) and issubclass(candidate, CorrelationMiddleware):
2071
+ return entry
2072
+ return None
2073
+
2074
+
2075
+ def _find_cleanup_middleware(middleware: "Iterable[Middleware] | None") -> "Middleware | None":
2076
+ """Return the first entry in the middleware stack that installs :class:`ConnectionCleanupMiddleware`."""
2077
+ for entry in middleware or ():
2078
+ candidate = entry.middleware if isinstance(entry, DefineMiddleware) else entry
2079
+ if isinstance(candidate, type) and issubclass(candidate, ConnectionCleanupMiddleware):
2080
+ return entry
2081
+ return None
2082
+
2083
+
2084
+ def _resolve_exception_handlers(request: "Request[Any, Any, Any]") -> "ExceptionHandlersMap":
2085
+ """Return the exception handlers resolved for the request's route, or the application's handlers."""
2086
+ route_handler = request.scope.get("route_handler")
2087
+ if route_handler is not None:
2088
+ return route_handler.resolve_exception_handlers()
2089
+ return request.app.exception_handlers
2090
+
2091
+
2092
+ def _render_http_exception(
2093
+ request: "Request[Any, Any, Any]", http_exc: HTTPException, handlers: "ExceptionHandlersMap"
2094
+ ) -> "Response[Any]":
2095
+ """Render an HTTP exception with the handler Litestar would select for it.
2096
+
2097
+ A handler for the status code wins, then a handler for the first class in the exception's
2098
+ MRO; Litestar's default exception response is used when no handler matches.
2099
+ """
2100
+ handler = handlers.get(http_exc.status_code) or next(
2101
+ (handlers[cls] for cls in type(http_exc).__mro__ if cls in handlers), None
2102
+ )
2103
+ if handler is None:
2104
+ return create_exception_response(request=request, exc=http_exc)
2105
+ return handler(request, http_exc)
2106
+
2107
+
2108
+ def _get_litestar_numpy_array_type() -> type[Any] | None:
2109
+ """Return a mutable ndarray subclass Litestar can attach a decoder to."""
2110
+ if not NUMPY_INSTALLED:
2111
+ return None
2112
+
2113
+ global _LITESTAR_NUMPY_ARRAY_TYPE
2114
+ if _LITESTAR_NUMPY_ARRAY_TYPE is None:
2115
+ import numpy as np
2116
+
2117
+ class SQLSpecNumpyArray(np.ndarray):
2118
+ pass
2119
+
2120
+ _LITESTAR_NUMPY_ARRAY_TYPE = SQLSpecNumpyArray
2121
+ return _LITESTAR_NUMPY_ARRAY_TYPE
2122
+
2123
+
2124
+ def _litestar_numpy_array_predicate(target_type: Any) -> bool:
2125
+ ndarray_type = _get_litestar_numpy_array_type()
2126
+ return ndarray_type is not None and target_type is ndarray_type
2127
+
2128
+
2129
+ def _litestar_numpy_array_dec_hook(target_type: type[Any], value: Any) -> Any:
2130
+ decoded = numpy_array_dec_hook(target_type, value)
2131
+ if NUMPY_INSTALLED:
2132
+ import numpy as np
2133
+
2134
+ if isinstance(decoded, np.ndarray) and isinstance(target_type, type) and not isinstance(decoded, target_type):
2135
+ return decoded.view(target_type)
2136
+ return decoded
2137
+
2138
+
2139
+ def _build_litestar_type_decoders() -> "list[tuple[Callable[[Any], bool], Callable[[type, Any], Any]]]":
2140
+ """Build the Litestar-specific ``type_decoders`` list.
2141
+
2142
+ Decoders are predicate-tuples consumed by Litestar's request-body parsing,
2143
+ not part of sqlspec's serializer registry — so they live here rather than
2144
+ in :data:`sqlspec.utils.serializers.DEFAULT_TYPE_ENCODERS`.
2145
+ """
2146
+ decoders: list[tuple[Callable[[Any], bool], Callable[[type, Any], Any]]] = []
2147
+ if NUMPY_INSTALLED:
2148
+ decoders.append((_litestar_numpy_array_predicate, _litestar_numpy_array_dec_hook))
2149
+ uuid_utils_uuid = import_optional_attr("uuid_utils", "UUID")
2150
+ if uuid_utils_uuid is not None:
2151
+ decoders.append((lambda t: t is uuid_utils_uuid, lambda t, v: t(str(v))))
2152
+ return decoders
2153
+
2154
+
2155
+ def _pop_and_close_session(scope: "Scope", key: str) -> None:
2156
+ """Pop one deferred session from scope state and mark it closed when present."""
2157
+ deferred: DeferredAsyncSession | None = get_sqlspec_scope_state(scope, key, pop=True)
2158
+ if deferred is not None:
2159
+ deferred._mark_closed()
2160
+
2161
+
2162
+ def _uses_request_routing(state: PluginConfigState) -> bool:
2163
+ return bool(
2164
+ state.enable_routing_middleware
2165
+ and (
2166
+ getattr(state.config, "has_replicas", False)
2167
+ or getattr(state.config, "supports_read_routing", False)
2168
+ or state.routing_header is not None
2169
+ or state.primary_pin_cookie is not None
2170
+ or state.default_routing_mode != "auto"
2171
+ )
2172
+ )