turbine-orm 0.93.1 → 0.94.0

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 (619) hide show
  1. package/README.md +49 -23
  2. package/dist/adapters/cockroachdb.d.ts +3 -3
  3. package/dist/adapters/cockroachdb.js +7 -11
  4. package/dist/adapters/index.d.ts +1 -1
  5. package/dist/adapters/yugabytedb.js +1 -1
  6. package/dist/better-sqlite3.d.ts +132 -0
  7. package/dist/better-sqlite3.js +303 -0
  8. package/dist/catalog-metadata.d.ts +250 -0
  9. package/dist/catalog-metadata.js +730 -0
  10. package/dist/cjs/adapters/cockroachdb.d.ts +3 -3
  11. package/dist/cjs/adapters/cockroachdb.js +7 -11
  12. package/dist/cjs/adapters/index.d.ts +1 -1
  13. package/dist/cjs/adapters/yugabytedb.js +1 -1
  14. package/dist/cjs/better-sqlite3.d.ts +132 -0
  15. package/dist/cjs/better-sqlite3.js +311 -0
  16. package/dist/cjs/catalog-metadata.d.ts +250 -0
  17. package/dist/cjs/catalog-metadata.js +747 -0
  18. package/dist/cjs/cli/compile-query.d.ts +6 -3
  19. package/dist/cjs/cli/compile-query.js +24 -3
  20. package/dist/cjs/cli/config.d.ts +35 -10
  21. package/dist/cjs/cli/config.js +173 -42
  22. package/dist/cjs/cli/d1-config.d.ts +14 -0
  23. package/dist/cjs/cli/d1-config.js +9 -0
  24. package/dist/cjs/cli/d1-local.d.ts +31 -0
  25. package/dist/cjs/cli/d1-local.js +298 -0
  26. package/dist/cjs/cli/d1-migrations.d.ts +16 -0
  27. package/dist/cjs/cli/d1-migrations.js +156 -0
  28. package/dist/cjs/cli/d1-project.d.ts +23 -0
  29. package/dist/cjs/cli/d1-project.js +314 -0
  30. package/dist/cjs/cli/d1-seed.d.ts +35 -0
  31. package/dist/cjs/cli/d1-seed.js +220 -0
  32. package/dist/cjs/cli/destructive.js +1 -2
  33. package/dist/cjs/cli/error-catalog.d.ts +3 -3
  34. package/dist/cjs/cli/error-catalog.js +21 -3
  35. package/dist/cjs/cli/index.d.ts +13 -8
  36. package/dist/cjs/cli/index.js +503 -71
  37. package/dist/cjs/cli/libsql-migrate-command.d.ts +5 -0
  38. package/dist/cjs/cli/libsql-migrate-command.js +82 -0
  39. package/dist/cjs/cli/libsql-migrate-status.d.ts +33 -0
  40. package/dist/cjs/cli/libsql-migrate-status.js +189 -0
  41. package/dist/cjs/cli/libsql-migrate.d.ts +14 -0
  42. package/dist/cjs/cli/libsql-migrate.js +522 -0
  43. package/dist/cjs/cli/libsql-project-config.d.ts +11 -0
  44. package/dist/cjs/cli/libsql-project-config.js +59 -0
  45. package/dist/cjs/cli/libsql-project.d.ts +52 -0
  46. package/dist/cjs/cli/libsql-project.js +409 -0
  47. package/dist/cjs/cli/libsql-seed-command.d.ts +29 -0
  48. package/dist/cjs/cli/libsql-seed-command.js +93 -0
  49. package/dist/cjs/cli/loader.d.ts +6 -5
  50. package/dist/cjs/cli/loader.js +53 -9
  51. package/dist/cjs/cli/mcp.d.ts +16 -1
  52. package/dist/cjs/cli/mcp.js +219 -125
  53. package/dist/cjs/cli/migrate.d.ts +2 -2
  54. package/dist/cjs/cli/migrate.js +29 -14
  55. package/dist/cjs/cli/mssql-doctor.d.ts +44 -0
  56. package/dist/cjs/cli/mssql-doctor.js +277 -0
  57. package/dist/cjs/cli/mssql-migrate-command.d.ts +9 -0
  58. package/dist/cjs/cli/mssql-migrate-command.js +230 -0
  59. package/dist/cjs/cli/mssql-migrate-connection.d.ts +51 -0
  60. package/dist/cjs/cli/mssql-migrate-connection.js +255 -0
  61. package/dist/cjs/cli/mssql-migrate-sql.d.ts +12 -0
  62. package/dist/cjs/cli/mssql-migrate-sql.js +282 -0
  63. package/dist/cjs/cli/mssql-migrate.d.ts +45 -0
  64. package/dist/cjs/cli/mssql-migrate.js +296 -0
  65. package/dist/cjs/cli/mssql-project.d.ts +34 -0
  66. package/dist/cjs/cli/mssql-project.js +171 -0
  67. package/dist/cjs/cli/mssql-seed.d.ts +7 -0
  68. package/dist/cjs/cli/mssql-seed.js +78 -0
  69. package/dist/cjs/cli/mssql-tools.d.ts +37 -0
  70. package/dist/cjs/cli/mssql-tools.js +354 -0
  71. package/dist/cjs/cli/mysql-doctor.d.ts +48 -0
  72. package/dist/cjs/cli/mysql-doctor.js +323 -0
  73. package/dist/cjs/cli/mysql-migrate-command.d.ts +7 -0
  74. package/dist/cjs/cli/mysql-migrate-command.js +290 -0
  75. package/dist/cjs/cli/mysql-migrate-sql.d.ts +18 -0
  76. package/dist/cjs/cli/mysql-migrate-sql.js +166 -0
  77. package/dist/cjs/cli/mysql-migrate.d.ts +77 -0
  78. package/dist/cjs/cli/mysql-migrate.js +619 -0
  79. package/dist/cjs/cli/mysql-project.d.ts +49 -0
  80. package/dist/cjs/cli/mysql-project.js +284 -0
  81. package/dist/cjs/cli/mysql-push-command.d.ts +7 -0
  82. package/dist/cjs/cli/mysql-push-command.js +94 -0
  83. package/dist/cjs/cli/mysql-push.d.ts +15 -0
  84. package/dist/cjs/cli/mysql-push.js +98 -0
  85. package/dist/cjs/cli/mysql-schema-command.d.ts +5 -0
  86. package/dist/cjs/cli/mysql-schema-command.js +58 -0
  87. package/dist/cjs/cli/mysql-schema-ddl.d.ts +37 -0
  88. package/dist/cjs/cli/mysql-schema-ddl.js +234 -0
  89. package/dist/cjs/cli/mysql-schema-snapshot.d.ts +21 -0
  90. package/dist/cjs/cli/mysql-schema-snapshot.js +127 -0
  91. package/dist/cjs/cli/mysql-schema.d.ts +27 -0
  92. package/dist/cjs/cli/mysql-schema.js +206 -0
  93. package/dist/cjs/cli/mysql-seed-loader.cjs +58 -0
  94. package/dist/cjs/cli/mysql-seed-loader.d.cts +3 -0
  95. package/dist/cjs/cli/mysql-seed.d.ts +6 -0
  96. package/dist/cjs/cli/mysql-seed.js +83 -0
  97. package/dist/cjs/cli/mysql-tools.d.ts +44 -0
  98. package/dist/cjs/cli/mysql-tools.js +336 -0
  99. package/dist/cjs/cli/no-follow.d.ts +29 -0
  100. package/dist/cjs/cli/no-follow.js +73 -0
  101. package/dist/cjs/cli/pii-predicate-guard.d.ts +1 -1
  102. package/dist/cjs/cli/pii-predicate-guard.js +2 -2
  103. package/dist/cjs/cli/pii-tags.d.ts +2 -2
  104. package/dist/cjs/cli/pii-tags.js +1 -1
  105. package/dist/cjs/cli/prisma-schema.js +2 -2
  106. package/dist/cjs/cli/sql-statements.d.ts +1 -1
  107. package/dist/cjs/cli/sql-statements.js +1 -1
  108. package/dist/cjs/cli/sqlite-doctor.d.ts +35 -0
  109. package/dist/cjs/cli/sqlite-doctor.js +400 -0
  110. package/dist/cjs/cli/sqlite-migrate-command.d.ts +4 -0
  111. package/dist/cjs/cli/sqlite-migrate-command.js +175 -0
  112. package/dist/cjs/cli/sqlite-migrate.d.ts +61 -0
  113. package/dist/cjs/cli/sqlite-migrate.js +692 -0
  114. package/dist/cjs/cli/sqlite-project.d.ts +42 -0
  115. package/dist/cjs/cli/sqlite-project.js +254 -0
  116. package/dist/cjs/cli/sqlite-schema-command.d.ts +4 -0
  117. package/dist/cjs/cli/sqlite-schema-command.js +82 -0
  118. package/dist/cjs/cli/sqlite-schema-ddl.d.ts +25 -0
  119. package/dist/cjs/cli/sqlite-schema-ddl.js +252 -0
  120. package/dist/cjs/cli/sqlite-schema.d.ts +25 -0
  121. package/dist/cjs/cli/sqlite-schema.js +334 -0
  122. package/dist/cjs/cli/sqlite-seed.d.ts +4 -0
  123. package/dist/cjs/cli/sqlite-seed.js +94 -0
  124. package/dist/cjs/cli/sqlite-tools.d.ts +24 -0
  125. package/dist/cjs/cli/sqlite-tools.js +169 -0
  126. package/dist/cjs/cli/studio.js +9 -9
  127. package/dist/cjs/cli/tool-capabilities.d.ts +72 -0
  128. package/dist/cjs/cli/tool-capabilities.js +120 -0
  129. package/dist/cjs/cli/tool-command.d.ts +11 -0
  130. package/dist/cjs/cli/tool-command.js +49 -0
  131. package/dist/cjs/cli/ui.d.ts +1 -1
  132. package/dist/cjs/cli/ui.js +1 -1
  133. package/dist/cjs/client.d.ts +20 -20
  134. package/dist/cjs/client.js +65 -344
  135. package/dist/cjs/connection-url.d.ts +1 -1
  136. package/dist/cjs/connection-url.js +1 -1
  137. package/dist/cjs/core.d.ts +58 -0
  138. package/dist/cjs/core.js +225 -0
  139. package/dist/cjs/d1/catalog-metadata.d.ts +5 -0
  140. package/dist/cjs/d1/catalog-metadata.js +230 -0
  141. package/dist/cjs/d1/catalog.d.ts +15 -0
  142. package/dist/cjs/d1/catalog.js +88 -0
  143. package/dist/cjs/d1/generate.d.ts +8 -0
  144. package/dist/cjs/d1/generate.js +163 -0
  145. package/dist/cjs/d1/introspect.d.ts +21 -0
  146. package/dist/cjs/d1/introspect.js +74 -0
  147. package/dist/cjs/d1/migrate.d.ts +29 -0
  148. package/dist/cjs/d1/migrate.js +222 -0
  149. package/dist/cjs/d1/migrations/sql.d.ts +2 -0
  150. package/dist/cjs/d1/migrations/sql.js +109 -0
  151. package/dist/cjs/d1/pool.d.ts +14 -0
  152. package/dist/cjs/d1/pool.js +90 -0
  153. package/dist/cjs/d1/sql.d.ts +5 -0
  154. package/dist/cjs/d1/sql.js +140 -0
  155. package/dist/cjs/d1/sqlite-dialect.d.ts +16 -0
  156. package/dist/cjs/d1/sqlite-dialect.js +579 -0
  157. package/dist/cjs/d1/types.d.ts +29 -0
  158. package/dist/cjs/d1/types.js +2 -0
  159. package/dist/cjs/d1.d.ts +53 -0
  160. package/dist/cjs/d1.js +220 -0
  161. package/dist/cjs/dialect.d.ts +33 -5
  162. package/dist/cjs/dialect.js +8 -6
  163. package/dist/cjs/errors.d.ts +38 -1
  164. package/dist/cjs/errors.js +72 -18
  165. package/dist/cjs/generate.d.ts +19 -3
  166. package/dist/cjs/generate.js +330 -97
  167. package/dist/cjs/global-filters-config.js +4 -4
  168. package/dist/cjs/index-advisor.js +6 -6
  169. package/dist/cjs/index.d.ts +1 -1
  170. package/dist/cjs/index.js +3 -2
  171. package/dist/cjs/introspect.d.ts +59 -356
  172. package/dist/cjs/introspect.js +158 -984
  173. package/dist/cjs/libsql/bindings.d.ts +2 -0
  174. package/dist/cjs/libsql/bindings.js +78 -0
  175. package/dist/cjs/libsql/dialect.d.ts +3 -0
  176. package/dist/cjs/libsql/dialect.js +48 -0
  177. package/dist/cjs/libsql/generate.d.ts +4 -0
  178. package/dist/cjs/libsql/generate.js +56 -0
  179. package/dist/cjs/libsql/introspect.d.ts +16 -0
  180. package/dist/cjs/libsql/introspect.js +295 -0
  181. package/dist/cjs/libsql/pool.d.ts +42 -0
  182. package/dist/cjs/libsql/pool.js +275 -0
  183. package/dist/cjs/libsql/seed-cleanup.d.ts +2 -0
  184. package/dist/cjs/libsql/seed-cleanup.js +19 -0
  185. package/dist/cjs/libsql/values.d.ts +20 -0
  186. package/dist/cjs/libsql/values.js +75 -0
  187. package/dist/cjs/libsql-seed.d.ts +19 -0
  188. package/dist/cjs/libsql-seed.js +50 -0
  189. package/dist/cjs/libsql.d.ts +28 -0
  190. package/dist/cjs/libsql.js +88 -0
  191. package/dist/cjs/live-query.d.ts +33 -0
  192. package/dist/cjs/live-query.js +172 -0
  193. package/dist/cjs/log-codes.d.ts +1 -1
  194. package/dist/cjs/log-codes.js +4 -0
  195. package/dist/cjs/mssql-seed.d.ts +27 -0
  196. package/dist/cjs/mssql-seed.js +118 -0
  197. package/dist/cjs/mssql.d.ts +7 -7
  198. package/dist/cjs/mssql.js +365 -53
  199. package/dist/cjs/mysql-seed.d.ts +25 -0
  200. package/dist/cjs/mysql-seed.js +169 -0
  201. package/dist/cjs/mysql.d.ts +18 -6
  202. package/dist/cjs/mysql.js +602 -94
  203. package/dist/cjs/neon-http/client.d.ts +95 -0
  204. package/dist/cjs/neon-http/client.js +291 -0
  205. package/dist/cjs/neon-http/sql.d.ts +3 -0
  206. package/dist/cjs/neon-http/sql.js +116 -0
  207. package/dist/cjs/neon-http.d.ts +5 -0
  208. package/dist/cjs/neon-http.js +8 -0
  209. package/dist/cjs/neon-ws/load-driver.cjs +44 -0
  210. package/dist/cjs/neon-ws/load-driver.d.cts +9 -0
  211. package/dist/cjs/neon-ws/recovery.d.ts +14 -0
  212. package/dist/cjs/neon-ws/recovery.js +69 -0
  213. package/dist/cjs/neon-ws/snapshot.d.ts +3 -0
  214. package/dist/cjs/neon-ws/snapshot.js +17 -0
  215. package/dist/cjs/neon-ws/transport.d.ts +112 -0
  216. package/dist/cjs/neon-ws/transport.js +290 -0
  217. package/dist/cjs/neon-ws.d.ts +26 -0
  218. package/dist/cjs/neon-ws.js +189 -0
  219. package/dist/cjs/nested-write.d.ts +34 -3
  220. package/dist/cjs/nested-write.js +117 -24
  221. package/dist/cjs/notification-hub/consumer.d.ts +22 -0
  222. package/dist/cjs/notification-hub/consumer.js +111 -0
  223. package/dist/cjs/notification-hub.d.ts +41 -0
  224. package/dist/cjs/notification-hub.js +373 -0
  225. package/dist/cjs/pg-catalog-text.d.ts +96 -0
  226. package/dist/cjs/pg-catalog-text.js +213 -0
  227. package/dist/cjs/pg-types.d.ts +46 -2
  228. package/dist/cjs/pipeline-submittable.d.ts +15 -5
  229. package/dist/cjs/pipeline-submittable.js +103 -48
  230. package/dist/cjs/pipeline.d.ts +5 -2
  231. package/dist/cjs/pipeline.js +111 -41
  232. package/dist/cjs/plan-divergence.d.ts +1 -1
  233. package/dist/cjs/plan-divergence.js +1 -1
  234. package/dist/cjs/powdb-introspect.d.ts +1 -1
  235. package/dist/cjs/powdb-introspect.js +5 -5
  236. package/dist/cjs/powdb-shared.d.ts +5 -5
  237. package/dist/cjs/powdb-shared.js +6 -5
  238. package/dist/cjs/powdb.d.ts +28 -10
  239. package/dist/cjs/powdb.js +80 -28
  240. package/dist/cjs/powql.d.ts +50 -28
  241. package/dist/cjs/powql.js +47 -33
  242. package/dist/cjs/prisma-compat.js +4 -5
  243. package/dist/cjs/prisma-schema-fingerprint.d.ts +1 -1
  244. package/dist/cjs/prisma-schema-fingerprint.js +1 -1
  245. package/dist/cjs/query/aggregates.d.ts +0 -13
  246. package/dist/cjs/query/aggregates.js +105 -238
  247. package/dist/cjs/query/batched-loader.d.ts +1 -1
  248. package/dist/cjs/query/batched-loader.js +18 -20
  249. package/dist/cjs/query/builder.d.ts +108 -144
  250. package/dist/cjs/query/builder.js +592 -893
  251. package/dist/cjs/query/compound-unique.d.ts +18 -3
  252. package/dist/cjs/query/compound-unique.js +110 -43
  253. package/dist/cjs/query/cursor-tuple.d.ts +17 -0
  254. package/dist/cjs/query/cursor-tuple.js +121 -0
  255. package/dist/cjs/query/expr.d.ts +2 -0
  256. package/dist/cjs/query/expr.js +40 -23
  257. package/dist/cjs/query/filters.d.ts +39 -7
  258. package/dist/cjs/query/filters.js +77 -19
  259. package/dist/cjs/query/normalize-args.d.ts +1 -1
  260. package/dist/cjs/query/normalize-args.js +7 -5
  261. package/dist/cjs/query/option-surface.d.ts +1 -1
  262. package/dist/cjs/query/option-surface.js +5 -3
  263. package/dist/cjs/query/pg-type-parsers.d.ts +126 -0
  264. package/dist/cjs/query/pg-type-parsers.js +306 -0
  265. package/dist/cjs/query/relation-names.d.ts +4 -2
  266. package/dist/cjs/query/relation-names.js +21 -12
  267. package/dist/cjs/query/relations.d.ts +19 -7
  268. package/dist/cjs/query/relations.js +329 -260
  269. package/dist/cjs/query/row-lock.js +3 -3
  270. package/dist/cjs/query/sql-comment.js +3 -3
  271. package/dist/cjs/query/stream-idle.d.ts +11 -1
  272. package/dist/cjs/query/stream-idle.js +53 -13
  273. package/dist/cjs/query/stream-signal.d.ts +21 -0
  274. package/dist/cjs/query/stream-signal.js +132 -0
  275. package/dist/cjs/query/temporal-parsers.d.ts +101 -0
  276. package/dist/cjs/query/temporal-parsers.js +362 -0
  277. package/dist/cjs/query/types.d.ts +67 -20
  278. package/dist/cjs/query/utils.d.ts +2 -878
  279. package/dist/cjs/query/utils.js +25 -2058
  280. package/dist/cjs/query/warn-registry.d.ts +1 -1
  281. package/dist/cjs/query/warn-registry.js +1 -1
  282. package/dist/cjs/query/where-compile.d.ts +4 -1
  283. package/dist/cjs/query/where-compile.js +18 -14
  284. package/dist/cjs/query/where.d.ts +14 -7
  285. package/dist/cjs/query/where.js +244 -436
  286. package/dist/cjs/query/writes.d.ts +33 -2
  287. package/dist/cjs/query/writes.js +104 -77
  288. package/dist/cjs/query-utils.d.ts +687 -0
  289. package/dist/cjs/query-utils.js +1444 -0
  290. package/dist/cjs/realtime.d.ts +1 -1
  291. package/dist/cjs/realtime.js +3 -3
  292. package/dist/cjs/schema-builder.js +2 -2
  293. package/dist/cjs/schema-metadata.d.ts +13 -3
  294. package/dist/cjs/schema-metadata.js +33 -5
  295. package/dist/cjs/schema-sql.d.ts +15 -24
  296. package/dist/cjs/schema-sql.js +53 -63
  297. package/dist/cjs/schema.d.ts +37 -2
  298. package/dist/cjs/schema.js +29 -2
  299. package/dist/cjs/seed.js +5 -5
  300. package/dist/cjs/serverless.d.ts +24 -71
  301. package/dist/cjs/serverless.js +24 -71
  302. package/dist/cjs/sql.d.ts +111 -0
  303. package/dist/cjs/sql.js +335 -0
  304. package/dist/cjs/sqlite-seed.d.ts +17 -0
  305. package/dist/cjs/sqlite-seed.js +31 -0
  306. package/dist/cjs/sqlite.d.ts +32 -19
  307. package/dist/cjs/sqlite.js +865 -652
  308. package/dist/cjs/supplied-pool-types.js +10 -9
  309. package/dist/cjs/transaction-control.js +6 -1
  310. package/dist/cjs/transaction-outcome.d.ts +61 -0
  311. package/dist/cjs/transaction-outcome.js +239 -0
  312. package/dist/cjs/transaction-state.d.ts +82 -13
  313. package/dist/cjs/transaction-state.js +222 -56
  314. package/dist/cjs/transaction-transport.d.ts +38 -0
  315. package/dist/cjs/transaction-transport.js +157 -0
  316. package/dist/cjs/typed-sql.d.ts +1 -1
  317. package/dist/cjs/typed-sql.js +1 -1
  318. package/dist/cli/compile-query.d.ts +6 -3
  319. package/dist/cli/compile-query.js +25 -4
  320. package/dist/cli/config.d.ts +35 -10
  321. package/dist/cli/config.js +170 -43
  322. package/dist/cli/d1-config.d.ts +14 -0
  323. package/dist/cli/d1-config.js +6 -0
  324. package/dist/cli/d1-local.d.ts +31 -0
  325. package/dist/cli/d1-local.js +285 -0
  326. package/dist/cli/d1-migrations.d.ts +16 -0
  327. package/dist/cli/d1-migrations.js +151 -0
  328. package/dist/cli/d1-project.d.ts +23 -0
  329. package/dist/cli/d1-project.js +304 -0
  330. package/dist/cli/d1-seed.d.ts +35 -0
  331. package/dist/cli/d1-seed.js +213 -0
  332. package/dist/cli/destructive.js +1 -2
  333. package/dist/cli/error-catalog.d.ts +3 -3
  334. package/dist/cli/error-catalog.js +21 -3
  335. package/dist/cli/index.d.ts +13 -8
  336. package/dist/cli/index.js +500 -71
  337. package/dist/cli/libsql-migrate-command.d.ts +5 -0
  338. package/dist/cli/libsql-migrate-command.js +77 -0
  339. package/dist/cli/libsql-migrate-status.d.ts +33 -0
  340. package/dist/cli/libsql-migrate-status.js +182 -0
  341. package/dist/cli/libsql-migrate.d.ts +14 -0
  342. package/dist/cli/libsql-migrate.js +516 -0
  343. package/dist/cli/libsql-project-config.d.ts +11 -0
  344. package/dist/cli/libsql-project-config.js +55 -0
  345. package/dist/cli/libsql-project.d.ts +52 -0
  346. package/dist/cli/libsql-project.js +391 -0
  347. package/dist/cli/libsql-seed-command.d.ts +29 -0
  348. package/dist/cli/libsql-seed-command.js +85 -0
  349. package/dist/cli/loader.d.ts +6 -5
  350. package/dist/cli/loader.js +50 -9
  351. package/dist/cli/mcp.d.ts +16 -1
  352. package/dist/cli/mcp.js +220 -127
  353. package/dist/cli/migrate.d.ts +2 -2
  354. package/dist/cli/migrate.js +29 -14
  355. package/dist/cli/mssql-doctor.d.ts +44 -0
  356. package/dist/cli/mssql-doctor.js +237 -0
  357. package/dist/cli/mssql-migrate-command.d.ts +9 -0
  358. package/dist/cli/mssql-migrate-command.js +192 -0
  359. package/dist/cli/mssql-migrate-connection.d.ts +51 -0
  360. package/dist/cli/mssql-migrate-connection.js +245 -0
  361. package/dist/cli/mssql-migrate-sql.d.ts +12 -0
  362. package/dist/cli/mssql-migrate-sql.js +275 -0
  363. package/dist/cli/mssql-migrate.d.ts +45 -0
  364. package/dist/cli/mssql-migrate.js +290 -0
  365. package/dist/cli/mssql-project.d.ts +34 -0
  366. package/dist/cli/mssql-project.js +160 -0
  367. package/dist/cli/mssql-seed.d.ts +7 -0
  368. package/dist/cli/mssql-seed.js +73 -0
  369. package/dist/cli/mssql-tools.d.ts +37 -0
  370. package/dist/cli/mssql-tools.js +341 -0
  371. package/dist/cli/mysql-doctor.d.ts +48 -0
  372. package/dist/cli/mysql-doctor.js +316 -0
  373. package/dist/cli/mysql-migrate-command.d.ts +7 -0
  374. package/dist/cli/mysql-migrate-command.js +285 -0
  375. package/dist/cli/mysql-migrate-sql.d.ts +18 -0
  376. package/dist/cli/mysql-migrate-sql.js +162 -0
  377. package/dist/cli/mysql-migrate.d.ts +77 -0
  378. package/dist/cli/mysql-migrate.js +606 -0
  379. package/dist/cli/mysql-project.d.ts +49 -0
  380. package/dist/cli/mysql-project.js +272 -0
  381. package/dist/cli/mysql-push-command.d.ts +7 -0
  382. package/dist/cli/mysql-push-command.js +89 -0
  383. package/dist/cli/mysql-push.d.ts +15 -0
  384. package/dist/cli/mysql-push.js +95 -0
  385. package/dist/cli/mysql-schema-command.d.ts +5 -0
  386. package/dist/cli/mysql-schema-command.js +54 -0
  387. package/dist/cli/mysql-schema-ddl.d.ts +37 -0
  388. package/dist/cli/mysql-schema-ddl.js +227 -0
  389. package/dist/cli/mysql-schema-snapshot.d.ts +21 -0
  390. package/dist/cli/mysql-schema-snapshot.js +119 -0
  391. package/dist/cli/mysql-schema.d.ts +27 -0
  392. package/dist/cli/mysql-schema.js +200 -0
  393. package/dist/cli/mysql-seed-loader.cjs +25 -0
  394. package/dist/cli/mysql-seed-loader.d.cts +3 -0
  395. package/dist/cli/mysql-seed.d.ts +6 -0
  396. package/dist/cli/mysql-seed.js +75 -0
  397. package/dist/cli/mysql-tools.d.ts +44 -0
  398. package/dist/cli/mysql-tools.js +290 -0
  399. package/dist/cli/no-follow.d.ts +29 -0
  400. package/dist/cli/no-follow.js +67 -0
  401. package/dist/cli/pii-predicate-guard.d.ts +1 -1
  402. package/dist/cli/pii-predicate-guard.js +2 -2
  403. package/dist/cli/pii-tags.d.ts +2 -2
  404. package/dist/cli/pii-tags.js +1 -1
  405. package/dist/cli/prisma-schema.js +2 -2
  406. package/dist/cli/sql-statements.d.ts +1 -1
  407. package/dist/cli/sql-statements.js +1 -1
  408. package/dist/cli/sqlite-doctor.d.ts +35 -0
  409. package/dist/cli/sqlite-doctor.js +392 -0
  410. package/dist/cli/sqlite-migrate-command.d.ts +4 -0
  411. package/dist/cli/sqlite-migrate-command.js +171 -0
  412. package/dist/cli/sqlite-migrate.d.ts +61 -0
  413. package/dist/cli/sqlite-migrate.js +681 -0
  414. package/dist/cli/sqlite-project.d.ts +42 -0
  415. package/dist/cli/sqlite-project.js +244 -0
  416. package/dist/cli/sqlite-schema-command.d.ts +4 -0
  417. package/dist/cli/sqlite-schema-command.js +79 -0
  418. package/dist/cli/sqlite-schema-ddl.d.ts +25 -0
  419. package/dist/cli/sqlite-schema-ddl.js +248 -0
  420. package/dist/cli/sqlite-schema.d.ts +25 -0
  421. package/dist/cli/sqlite-schema.js +330 -0
  422. package/dist/cli/sqlite-seed.d.ts +4 -0
  423. package/dist/cli/sqlite-seed.js +57 -0
  424. package/dist/cli/sqlite-tools.d.ts +24 -0
  425. package/dist/cli/sqlite-tools.js +163 -0
  426. package/dist/cli/studio.js +9 -9
  427. package/dist/cli/tool-capabilities.d.ts +72 -0
  428. package/dist/cli/tool-capabilities.js +114 -0
  429. package/dist/cli/tool-command.d.ts +11 -0
  430. package/dist/cli/tool-command.js +45 -0
  431. package/dist/cli/ui.d.ts +1 -1
  432. package/dist/cli/ui.js +1 -1
  433. package/dist/client.d.ts +20 -20
  434. package/dist/client.js +62 -341
  435. package/dist/connection-url.d.ts +1 -1
  436. package/dist/connection-url.js +1 -1
  437. package/dist/core.d.ts +58 -0
  438. package/dist/core.js +220 -0
  439. package/dist/d1/catalog-metadata.d.ts +5 -0
  440. package/dist/d1/catalog-metadata.js +227 -0
  441. package/dist/d1/catalog.d.ts +15 -0
  442. package/dist/d1/catalog.js +82 -0
  443. package/dist/d1/generate.d.ts +8 -0
  444. package/dist/d1/generate.js +160 -0
  445. package/dist/d1/introspect.d.ts +21 -0
  446. package/dist/d1/introspect.js +71 -0
  447. package/dist/d1/migrate.d.ts +29 -0
  448. package/dist/d1/migrate.js +217 -0
  449. package/dist/d1/migrations/sql.d.ts +2 -0
  450. package/dist/d1/migrations/sql.js +106 -0
  451. package/dist/d1/pool.d.ts +14 -0
  452. package/dist/d1/pool.js +86 -0
  453. package/dist/d1/sql.d.ts +5 -0
  454. package/dist/d1/sql.js +135 -0
  455. package/dist/d1/sqlite-dialect.d.ts +16 -0
  456. package/dist/d1/sqlite-dialect.js +572 -0
  457. package/dist/d1/types.d.ts +29 -0
  458. package/dist/d1/types.js +1 -0
  459. package/dist/d1.d.ts +53 -0
  460. package/dist/d1.js +215 -0
  461. package/dist/dialect.d.ts +33 -5
  462. package/dist/dialect.js +6 -4
  463. package/dist/errors.d.ts +38 -1
  464. package/dist/errors.js +68 -17
  465. package/dist/generate.d.ts +19 -3
  466. package/dist/generate.js +330 -97
  467. package/dist/global-filters-config.js +2 -2
  468. package/dist/index-advisor.js +1 -1
  469. package/dist/index.d.ts +1 -1
  470. package/dist/index.js +1 -1
  471. package/dist/introspect.d.ts +59 -356
  472. package/dist/introspect.js +116 -943
  473. package/dist/libsql/bindings.d.ts +2 -0
  474. package/dist/libsql/bindings.js +75 -0
  475. package/dist/libsql/dialect.d.ts +3 -0
  476. package/dist/libsql/dialect.js +45 -0
  477. package/dist/libsql/generate.d.ts +4 -0
  478. package/dist/libsql/generate.js +53 -0
  479. package/dist/libsql/introspect.d.ts +16 -0
  480. package/dist/libsql/introspect.js +289 -0
  481. package/dist/libsql/pool.d.ts +42 -0
  482. package/dist/libsql/pool.js +270 -0
  483. package/dist/libsql/seed-cleanup.d.ts +2 -0
  484. package/dist/libsql/seed-cleanup.js +15 -0
  485. package/dist/libsql/values.d.ts +20 -0
  486. package/dist/libsql/values.js +68 -0
  487. package/dist/libsql-seed.d.ts +19 -0
  488. package/dist/libsql-seed.js +46 -0
  489. package/dist/libsql.d.ts +28 -0
  490. package/dist/libsql.js +79 -0
  491. package/dist/live-query.d.ts +33 -0
  492. package/dist/live-query.js +169 -0
  493. package/dist/log-codes.d.ts +1 -1
  494. package/dist/log-codes.js +4 -0
  495. package/dist/mssql-seed.d.ts +27 -0
  496. package/dist/mssql-seed.js +114 -0
  497. package/dist/mssql.d.ts +7 -7
  498. package/dist/mssql.js +366 -54
  499. package/dist/mysql-seed.d.ts +25 -0
  500. package/dist/mysql-seed.js +165 -0
  501. package/dist/mysql.d.ts +18 -6
  502. package/dist/mysql.js +603 -95
  503. package/dist/neon-http/client.d.ts +95 -0
  504. package/dist/neon-http/client.js +286 -0
  505. package/dist/neon-http/sql.d.ts +3 -0
  506. package/dist/neon-http/sql.js +112 -0
  507. package/dist/neon-http.d.ts +5 -0
  508. package/dist/neon-http.js +2 -0
  509. package/dist/neon-ws/load-driver.cjs +11 -0
  510. package/dist/neon-ws/load-driver.d.cts +9 -0
  511. package/dist/neon-ws/recovery.d.ts +14 -0
  512. package/dist/neon-ws/recovery.js +66 -0
  513. package/dist/neon-ws/snapshot.d.ts +3 -0
  514. package/dist/neon-ws/snapshot.js +15 -0
  515. package/dist/neon-ws/transport.d.ts +112 -0
  516. package/dist/neon-ws/transport.js +286 -0
  517. package/dist/neon-ws.d.ts +26 -0
  518. package/dist/neon-ws.js +182 -0
  519. package/dist/nested-write.d.ts +34 -3
  520. package/dist/nested-write.js +114 -22
  521. package/dist/notification-hub/consumer.d.ts +22 -0
  522. package/dist/notification-hub/consumer.js +106 -0
  523. package/dist/notification-hub.d.ts +41 -0
  524. package/dist/notification-hub.js +370 -0
  525. package/dist/pg-catalog-text.d.ts +96 -0
  526. package/dist/pg-catalog-text.js +208 -0
  527. package/dist/pg-types.d.ts +46 -2
  528. package/dist/pipeline-submittable.d.ts +15 -5
  529. package/dist/pipeline-submittable.js +105 -50
  530. package/dist/pipeline.d.ts +5 -2
  531. package/dist/pipeline.js +113 -43
  532. package/dist/plan-divergence.d.ts +1 -1
  533. package/dist/plan-divergence.js +1 -1
  534. package/dist/powdb-introspect.d.ts +1 -1
  535. package/dist/powdb-introspect.js +5 -5
  536. package/dist/powdb-shared.d.ts +5 -5
  537. package/dist/powdb-shared.js +6 -5
  538. package/dist/powdb.d.ts +28 -10
  539. package/dist/powdb.js +80 -28
  540. package/dist/powql.d.ts +50 -28
  541. package/dist/powql.js +49 -35
  542. package/dist/prisma-compat.js +4 -5
  543. package/dist/prisma-schema-fingerprint.d.ts +1 -1
  544. package/dist/prisma-schema-fingerprint.js +1 -1
  545. package/dist/query/aggregates.d.ts +0 -13
  546. package/dist/query/aggregates.js +97 -230
  547. package/dist/query/batched-loader.d.ts +1 -1
  548. package/dist/query/batched-loader.js +5 -7
  549. package/dist/query/builder.d.ts +108 -144
  550. package/dist/query/builder.js +563 -864
  551. package/dist/query/compound-unique.d.ts +18 -3
  552. package/dist/query/compound-unique.js +99 -33
  553. package/dist/query/cursor-tuple.d.ts +17 -0
  554. package/dist/query/cursor-tuple.js +114 -0
  555. package/dist/query/expr.d.ts +2 -0
  556. package/dist/query/expr.js +32 -16
  557. package/dist/query/filters.d.ts +39 -7
  558. package/dist/query/filters.js +69 -14
  559. package/dist/query/normalize-args.d.ts +1 -1
  560. package/dist/query/normalize-args.js +4 -2
  561. package/dist/query/option-surface.d.ts +1 -1
  562. package/dist/query/option-surface.js +4 -2
  563. package/dist/query/pg-type-parsers.d.ts +126 -0
  564. package/dist/query/pg-type-parsers.js +296 -0
  565. package/dist/query/relation-names.d.ts +4 -2
  566. package/dist/query/relation-names.js +15 -7
  567. package/dist/query/relations.d.ts +19 -7
  568. package/dist/query/relations.js +293 -227
  569. package/dist/query/row-lock.js +1 -1
  570. package/dist/query/sql-comment.js +1 -1
  571. package/dist/query/stream-idle.d.ts +11 -1
  572. package/dist/query/stream-idle.js +51 -13
  573. package/dist/query/stream-signal.d.ts +21 -0
  574. package/dist/query/stream-signal.js +125 -0
  575. package/dist/query/temporal-parsers.d.ts +101 -0
  576. package/dist/query/temporal-parsers.js +354 -0
  577. package/dist/query/types.d.ts +67 -20
  578. package/dist/query/utils.d.ts +2 -878
  579. package/dist/query/utils.js +5 -2003
  580. package/dist/query/warn-registry.d.ts +1 -1
  581. package/dist/query/warn-registry.js +1 -1
  582. package/dist/query/where-compile.d.ts +4 -1
  583. package/dist/query/where-compile.js +14 -10
  584. package/dist/query/where.d.ts +14 -7
  585. package/dist/query/where.js +236 -430
  586. package/dist/query/writes.d.ts +33 -2
  587. package/dist/query/writes.js +90 -65
  588. package/dist/query-utils.d.ts +687 -0
  589. package/dist/query-utils.js +1390 -0
  590. package/dist/realtime.d.ts +1 -1
  591. package/dist/realtime.js +3 -3
  592. package/dist/schema-builder.js +2 -2
  593. package/dist/schema-metadata.d.ts +13 -3
  594. package/dist/schema-metadata.js +33 -5
  595. package/dist/schema-sql.d.ts +15 -24
  596. package/dist/schema-sql.js +50 -60
  597. package/dist/schema.d.ts +37 -2
  598. package/dist/schema.js +29 -2
  599. package/dist/seed.js +5 -5
  600. package/dist/serverless.d.ts +24 -71
  601. package/dist/serverless.js +24 -71
  602. package/dist/sql.d.ts +111 -0
  603. package/dist/sql.js +321 -0
  604. package/dist/sqlite-seed.d.ts +17 -0
  605. package/dist/sqlite-seed.js +27 -0
  606. package/dist/sqlite.d.ts +32 -19
  607. package/dist/sqlite.js +859 -648
  608. package/dist/supplied-pool-types.js +2 -1
  609. package/dist/transaction-control.js +6 -1
  610. package/dist/transaction-outcome.d.ts +61 -0
  611. package/dist/transaction-outcome.js +234 -0
  612. package/dist/transaction-state.d.ts +82 -13
  613. package/dist/transaction-state.js +220 -57
  614. package/dist/transaction-transport.d.ts +38 -0
  615. package/dist/transaction-transport.js +153 -0
  616. package/dist/typed-sql.d.ts +1 -1
  617. package/dist/typed-sql.js +1 -1
  618. package/package.json +239 -13
  619. package/skills/turbine-orm/SKILL.md +6 -5
@@ -85,21 +85,24 @@
85
85
  * ```
86
86
  */
87
87
  Object.defineProperty(exports, "__esModule", { value: true });
88
- exports.sqliteDialect = exports.SqlitePool = void 0;
89
- exports.sqliteTypeToTs = sqliteTypeToTs;
88
+ exports.sqliteDialect = exports.SqlitePool = exports.sqliteTypeToTs = void 0;
89
+ exports.recordSqliteBulkInsert = recordSqliteBulkInsert;
90
90
  exports.introspectSqliteDatabase = introspectSqliteDatabase;
91
91
  exports.introspectSqlite = introspectSqlite;
92
92
  exports.turbineSqlite = turbineSqlite;
93
+ exports.createSqliteBindingClient = createSqliteBindingClient;
93
94
  const node_async_hooks_1 = require("node:async_hooks");
94
95
  const node_module_1 = require("node:module");
96
+ const catalog_metadata_js_1 = require("./catalog-metadata.js");
95
97
  const client_js_1 = require("./client.js");
96
- const dialect_js_1 = require("./dialect.js");
98
+ const sqlite_dialect_js_1 = require("./d1/sqlite-dialect.js");
97
99
  const errors_js_1 = require("./errors.js");
98
100
  const introspect_js_1 = require("./introspect.js");
99
101
  const sql_comment_js_1 = require("./query/sql-comment.js");
100
- const utils_js_1 = require("./query/utils.js");
101
102
  const schema_js_1 = require("./schema.js");
102
103
  const sql_placeholders_js_1 = require("./sql-placeholders.js");
104
+ var sqlite_dialect_js_2 = require("./d1/sqlite-dialect.js");
105
+ Object.defineProperty(exports, "sqliteTypeToTs", { enumerable: true, get: function () { return sqlite_dialect_js_2.sqliteTypeToTs; } });
103
106
  let cachedDatabaseSync;
104
107
  /**
105
108
  * Lazily load `node:sqlite`'s `DatabaseSync` constructor.
@@ -133,76 +136,6 @@ function loadDatabaseSync() {
133
136
  cachedDatabaseSync = ctor;
134
137
  return cachedDatabaseSync;
135
138
  }
136
- /**
137
- * Coerce an arbitrary JS value into something `node:sqlite` can bind.
138
- *
139
- * `node:sqlite` throws on `boolean`, `undefined`, `Date`, and plain objects, so
140
- * we normalize: booleans → 1/0, a safe integer → INTEGER (see below),
141
- * `undefined`/`null` → NULL, `Date` → ISO text,
142
- * `Uint8Array`/`Buffer` → BLOB, and any remaining object/array → JSON text
143
- * (matches how Turbine already pre-serializes JSON filter params).
144
- */
145
- function toSqliteParam(value) {
146
- if (value === undefined || value === null)
147
- return null;
148
- switch (typeof value) {
149
- case 'boolean':
150
- return value ? 1 : 0;
151
- case 'number':
152
- // `node:sqlite` binds every JS number as REAL, so `views / 2` divided as
153
- // floats (75 / 2 = 37.5, stored in an INTEGER column) and an integral
154
- // number written to a TEXT column was stored as '3.0'. Binding a safe
155
- // integer as an INTEGER gives the arithmetic and text PostgreSQL gives.
156
- // -0 stays REAL: as an integer it would lose its sign.
157
- return Number.isSafeInteger(value) && !Object.is(value, -0) ? BigInt(value) : value;
158
- case 'bigint':
159
- case 'string':
160
- return value;
161
- }
162
- if (value instanceof Date)
163
- return value.toISOString();
164
- if (value instanceof Uint8Array)
165
- return value; // also covers Buffer
166
- return JSON.stringify(value);
167
- }
168
- /**
169
- * The JSON text an `in` / `notIn` list binds as, element by element in the
170
- * form {@link toSqliteParam} would bind it, so a list element compares exactly
171
- * as the same value given to `equals` does. A bigint is written as a JSON
172
- * integer (exact to 64 bits; `JSON.stringify` refuses one), an infinity as the
173
- * overflowing literal SQLite's JSON parser reads as one, and a binary value as
174
- * `{"b": "<hex>"}`, which {@link sqliteDialect.buildInClause} turns back into a
175
- * BLOB. Any other object binds as its JSON text, as it would on its own.
176
- */
177
- function sqliteInListJson(values) {
178
- const parts = values.map((value) => {
179
- if (value === undefined || value === null)
180
- return 'null';
181
- switch (typeof value) {
182
- case 'boolean':
183
- return value ? '1' : '0';
184
- case 'number':
185
- if (Number.isFinite(value))
186
- return JSON.stringify(value);
187
- if (Number.isNaN(value))
188
- return 'null';
189
- return value > 0 ? '9e999' : '-9e999';
190
- case 'bigint':
191
- return value.toString();
192
- case 'string':
193
- return JSON.stringify(value);
194
- }
195
- if (value instanceof Uint8Array) {
196
- let hex = '';
197
- for (const byte of value)
198
- hex += byte.toString(16).padStart(2, '0');
199
- return `{"b":"${hex}"}`;
200
- }
201
- const bound = toSqliteParam(value);
202
- return JSON.stringify(bound);
203
- });
204
- return `[${parts.join(',')}]`;
205
- }
206
139
  /**
207
140
  * Normalize a single column value read from SQLite. With `setReadBigInts(true)`
208
141
  * every integer column comes back as a `bigint`; apply the same safe-integer
@@ -215,38 +148,33 @@ function normalizeValue(value) {
215
148
  const asNumber = Number(value);
216
149
  return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
217
150
  }
151
+ // Compatible native bindings can return Buffer for BLOBs. Keep the builtin's
152
+ // Uint8Array contract without exposing a driver-specific prototype.
153
+ if (value instanceof Uint8Array && Buffer.isBuffer(value))
154
+ return Uint8Array.from(value);
218
155
  return value;
219
156
  }
220
- /**
221
- * The decode a column of `type` needs on SQLite, or `undefined`. `type` is a
222
- * declared SQLite type or a schema type (`bool`, `jsonb`). The ONE answer both
223
- * read paths use: the driver shim for direct reads and {@link sqliteDialect}'s
224
- * `jsonWireRule` for `with` rows, so the two cannot disagree about a column.
225
- */
226
- function sqliteValueDecode(type) {
227
- const t = type.toUpperCase();
228
- if (t.includes('BOOL'))
229
- return 'boolean';
230
- if (t === 'JSON' || t === 'JSONB')
231
- return 'json';
232
- return undefined;
233
- }
234
157
  function declaredDecoders(schema) {
235
158
  if (!schema)
236
159
  return null;
237
160
  let out = null;
161
+ let hasJsonView = false;
238
162
  for (const [table, meta] of Object.entries(schema.tables)) {
239
163
  for (const column of meta.columns) {
240
164
  const type = column.pgType ?? meta.pgTypes?.[column.name];
241
- const decode = typeof type === 'string' ? sqliteValueDecode(type) : undefined;
165
+ const decode = typeof type === 'string' ? (0, sqlite_dialect_js_1.sqliteValueDecode)(type) : undefined;
242
166
  if (decode === undefined)
243
167
  continue;
244
168
  if (out === null)
245
169
  out = new Map();
246
170
  out.set(`${table}\u0000${column.name}`, decode);
171
+ if (decode === 'json' && meta.isView === true)
172
+ hasJsonView = true;
247
173
  }
248
174
  }
249
- return out;
175
+ return out === null
176
+ ? null
177
+ : { byOrigin: out, knownTablesForJsonViews: hasJsonView ? new Set(Object.keys(schema.tables)) : null };
250
178
  }
251
179
  /**
252
180
  * A decimal integer or float as SQLite prints it (`printf('%!.17g')` / `CAST(... AS TEXT)`).
@@ -257,53 +185,6 @@ function declaredDecoders(schema) {
257
185
  * place, which made a long non-numeric cell take seconds to reject (quadratic:
258
186
  * 40,000 digits and an `x` took 0.8 s, a million take 1.5 ms now).
259
187
  */
260
- const SQLITE_NUMBER_TEXT = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
261
- /**
262
- * The text SQLite's INTEGER, REAL and NUMERIC affinities convert to a number,
263
- * measured against SQLite 3.51: an optional sign, a decimal integer or float,
264
- * an optional exponent, and ASCII whitespace around it. Anything else
265
- * (`'abc'`, `''`, `'Infinity'`, `'0x10'`, `'1_000'`) is stored as TEXT in the
266
- * numeric column. Linear for the same reason as {@link SQLITE_NUMBER_TEXT}.
267
- */
268
- const SQLITE_NUMERIC_LITERAL = /^[ \t\n\v\f\r]*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?[ \t\n\v\f\r]*$/i;
269
- /**
270
- * Declared column types whose SQLite affinity is numeric (INTEGER, REAL or
271
- * NUMERIC), boolean included (stored 1/0). Matched whole, not by SQLite's own
272
- * "contains INT" rule: the type a schema records for a column can be an enum's
273
- * name (`point_kind`), which that rule reads as INTEGER while the column is
274
- * TEXT. A type this misses is written as SQLite always wrote it, so a miss
275
- * costs a refusal, never a wrong one.
276
- */
277
- const SQLITE_NUMERIC_COLUMN_TYPE = /^(?:(?:tiny|small|medium|big)?int(?:eger)?|int[248]|(?:small|big)?serial|unsigned big int|real|float[48]?|double(?: precision)?|numeric|decimal|money|bool(?:ean)?)(?:\(\s*\d+\s*(?:,\s*\d+\s*)?\))?$/i;
278
- /**
279
- * Decode a REAL / NUMERIC cell carried as text through a `with` join back to
280
- * the value a direct read returns: an integer by the safe-integer policy, a
281
- * double as the number its 17 digits name, `Inf` / `-Inf` as infinities.
282
- */
283
- function decodeRealText(value) {
284
- if (typeof value !== 'string')
285
- return value;
286
- if (/^-?\d+$/.test(value)) {
287
- const asNumber = Number(value);
288
- return Number.isSafeInteger(asNumber) ? asNumber : value;
289
- }
290
- if (value === 'Inf')
291
- return Number.POSITIVE_INFINITY;
292
- if (value === '-Inf')
293
- return Number.NEGATIVE_INFINITY;
294
- return SQLITE_NUMBER_TEXT.test(value) ? Number(value) : value;
295
- }
296
- /** Read a JSON column's stored text as its value; text that is not JSON is returned as stored. */
297
- function parseJsonCell(value) {
298
- if (typeof value !== 'string')
299
- return value;
300
- try {
301
- return JSON.parse(value);
302
- }
303
- catch {
304
- return value;
305
- }
306
- }
307
188
  /**
308
189
  * Convert a `node:sqlite` null-prototype row into a normalized plain object.
309
190
  *
@@ -317,17 +198,83 @@ function normalizeRow(row, decoders) {
317
198
  for (const key of Object.keys(row)) {
318
199
  const value = normalizeValue(row[key]);
319
200
  const decode = decoders?.get(key);
201
+ if (key === '__proto__')
202
+ Object.defineProperty(out, key, { writable: true, enumerable: true, configurable: true });
320
203
  out[key] =
321
204
  decode === undefined
322
205
  ? value
323
206
  : decode === 'json'
324
- ? parseJsonCell(value)
207
+ ? (0, sqlite_dialect_js_1.parseJsonCell)(value)
325
208
  : value === 1 || value === 0
326
209
  ? value === 1
327
210
  : value;
328
211
  }
329
212
  return out;
330
213
  }
214
+ /**
215
+ * Pin a native iterator's projection after its first step (which can reprepare
216
+ * after DDL). Resolve keys/decoders once, rather than enumerate and Map.get for
217
+ * every cell. Array-capable drivers also avoid allocating a keyed native row.
218
+ * The first row stays in object mode so missing/failed descriptions can always
219
+ * fall back to the driver's actual keys without guessing a projection.
220
+ */
221
+ function streamRowNormalizer(stmt, first, decoders, switchArrays = true) {
222
+ let keys = Object.keys(first);
223
+ let arrays = false;
224
+ if (switchArrays && typeof stmt.setReturnArrays === 'function' && typeof stmt.columns === 'function') {
225
+ let described;
226
+ try {
227
+ described = stmt.columns();
228
+ }
229
+ catch {
230
+ // Compatible drivers can omit descriptions. Object rows remain sound.
231
+ }
232
+ // Duplicate output names collapse in object mode. Keep that path rather
233
+ // than infer which positional cell the compatible driver retained.
234
+ if (described?.length === keys.length &&
235
+ described.every((c) => typeof c.name === 'string' && Object.hasOwn(first, c.name)) &&
236
+ new Set(described.map((c) => c.name)).size === keys.length) {
237
+ keys = described.map((c) => c.name);
238
+ stmt.setReturnArrays(true);
239
+ arrays = true;
240
+ }
241
+ }
242
+ return resultRowNormalizer(keys, decoders, arrays ? keys.map((_, i) => i) : undefined);
243
+ }
244
+ /** A projection pinned to one fully stepped result or one active iterator. */
245
+ function resultRowNormalizer(keys, decoders, indices) {
246
+ const decode = keys.map((key) => decoders?.get(key));
247
+ return (r) => {
248
+ const row = {};
249
+ for (let i = 0; i < keys.length; i++) {
250
+ const key = keys[i];
251
+ const value = normalizeValue((indices ? r[indices[i]] : r[key]));
252
+ const columnDecode = decode[i];
253
+ if (key === '__proto__')
254
+ Object.defineProperty(row, key, { writable: true, enumerable: true, configurable: true });
255
+ row[key] =
256
+ columnDecode === undefined
257
+ ? value
258
+ : columnDecode === 'json'
259
+ ? (0, sqlite_dialect_js_1.parseJsonCell)(value)
260
+ : value === 1 || value === 0
261
+ ? value === 1
262
+ : value;
263
+ }
264
+ return row;
265
+ };
266
+ }
267
+ /** Native all() rows share a projection; this plan lives only for this result. */
268
+ function normalizeResultRows(raw, decoders, columns, projectionOrder) {
269
+ // Repeated names retain the last cell in the first name's insertion order.
270
+ const positions = columns ? new Map(columns.map((c, i) => [c.name, i])) : undefined;
271
+ // Builtin arrays retain projection order; compatible object producers visit
272
+ // integer keys first. Preserve each producer's raw assignment/setter order.
273
+ const keys = projectionOrder
274
+ ? [...positions.keys()]
275
+ : Object.keys(positions ? Object.fromEntries(positions) : raw[0]);
276
+ return raw.map(resultRowNormalizer(keys, decoders, positions ? keys.map((key) => positions.get(key)) : undefined));
277
+ }
331
278
  /**
332
279
  * The result columns of a prepared statement that need decoding, or `null`
333
280
  * when there are none (the overwhelmingly common case).
@@ -347,42 +294,264 @@ function normalizeRow(row, decoders) {
347
294
  * - The client's schema: an origin column declared boolean or json/jsonb there.
348
295
  * Turbine's own DDL stores those as INTEGER and TEXT, so the declared type
349
296
  * alone missed every table Turbine created.
297
+ * - A selected JSON view can expose native main-database JSON origins whose
298
+ * base tables were filtered out. Known schema origins keep their declared
299
+ * meaning; no-schema/table-only pools and expressions retain their behavior.
350
300
  *
351
301
  * Node gained `columns()` in 22.16 / 23.11 while this engine's floor is 22.5, so
352
302
  * it is feature-detected: on the narrow band without it, these columns keep
353
303
  * reading back as stored rather than the engine refusing to run.
354
304
  */
355
- function resultColumnDecoders(stmt, declared) {
356
- const columnsFn = stmt.columns;
357
- if (typeof columnsFn !== 'function')
358
- return null;
359
- let described;
360
- try {
361
- described = columnsFn.call(stmt);
305
+ function resultColumnDecoders(stmt, declared, memo, columns) {
306
+ let described = columns;
307
+ if (described === undefined) {
308
+ const columnsFn = stmt.columns;
309
+ if (typeof columnsFn !== 'function')
310
+ return null;
311
+ try {
312
+ described = columnsFn.call(stmt);
313
+ }
314
+ catch {
315
+ // A statement the driver cannot describe (some PRAGMA forms) is not worth
316
+ // failing a query over; skip the decoding for it.
317
+ return null;
318
+ }
362
319
  }
363
- catch {
364
- // A statement the driver cannot describe (some PRAGMA forms) is not worth
365
- // failing a query over; skip the decoding for it.
366
- return null;
320
+ const previous = memo.columns;
321
+ if (previous?.length === described.length) {
322
+ let same = true;
323
+ for (let i = 0; i < described.length; i++) {
324
+ const a = previous[i];
325
+ const b = described[i];
326
+ if (a.name !== b.name ||
327
+ a.type !== b.type ||
328
+ a.table !== b.table ||
329
+ a.column !== b.column ||
330
+ a.database !== b.database) {
331
+ same = false;
332
+ break;
333
+ }
334
+ }
335
+ if (same)
336
+ return memo.decoders;
367
337
  }
368
338
  let out = null;
369
339
  for (const c of described) {
370
340
  if (typeof c.name !== 'string')
371
341
  continue;
372
342
  let decode;
373
- if (typeof c.type === 'string' && sqliteValueDecode(c.type) === 'boolean')
343
+ const nativeDecode = typeof c.type === 'string' ? (0, sqlite_dialect_js_1.sqliteValueDecode)(c.type) : undefined;
344
+ if (nativeDecode === 'boolean')
374
345
  decode = 'boolean';
375
346
  else if (declared !== null && typeof c.table === 'string' && typeof c.column === 'string') {
376
- decode = declared.get(`${c.table}\u0000${c.column}`);
347
+ decode = declared.byOrigin.get(`${c.table}\u0000${c.column}`);
348
+ if (decode === undefined &&
349
+ nativeDecode === 'json' &&
350
+ declared.knownTablesForJsonViews !== null &&
351
+ c.database === 'main' &&
352
+ !declared.knownTablesForJsonViews.has(c.table))
353
+ decode = 'json';
377
354
  }
378
- if (decode === undefined)
355
+ // Object rows retain the last cell for a repeated output name. Its type
356
+ // must also replace an earlier boolean/JSON origin, including expressions.
357
+ if (decode === undefined) {
358
+ out?.delete(c.name);
379
359
  continue;
360
+ }
380
361
  if (out === null)
381
362
  out = new Map();
382
363
  out.set(c.name, decode);
383
364
  }
365
+ // Snapshot the fields: a compatible driver can reuse/mutate its own array.
366
+ // SQL text and schema-version equality never stand in for fresh metadata.
367
+ memo.columns = described.map(({ name, type, table, column, database }) => ({ name, type, table, column, database }));
368
+ memo.decoders = out;
384
369
  return out;
385
370
  }
371
+ /**
372
+ * The builtin methods a wildcard read goes through, or `null` when every read
373
+ * uses the statement's own all(). `undefined` until the first wildcard read.
374
+ */
375
+ let wildcardRead;
376
+ /**
377
+ * Some builtin all() implementations (Node 22.16 and 24.10, for example) fix
378
+ * the result width before the first step. When SQLite reprepares a star there,
379
+ * because DDL ran since prepare or another connection changed the schema, a
380
+ * grown table loses its new cells and a repeated name keeps an earlier cell.
381
+ * Ask this runtime once: all() is trusted only if it returns the reprepared
382
+ * projection. Without iterate() (Node before 22.13) there is no complete
383
+ * route, so all() stays, as documented. A replaced prototype all() keeps its
384
+ * own contract.
385
+ */
386
+ function probeWildcardRead() {
387
+ let sqlite;
388
+ try {
389
+ sqlite = (0, node_module_1.createRequire)(process.cwd())('node:sqlite');
390
+ }
391
+ catch {
392
+ return null;
393
+ }
394
+ const { all, iterate } = sqlite.StatementSync.prototype;
395
+ if (typeof iterate !== 'function' || !Function.prototype.toString.call(all).includes('[native code]'))
396
+ return null;
397
+ let probe;
398
+ try {
399
+ probe = new sqlite.DatabaseSync(':memory:');
400
+ probe.exec('CREATE TABLE t(a); INSERT INTO t VALUES(1)');
401
+ const stmt = probe.prepare('SELECT *, 2 AS b FROM t');
402
+ probe.exec('ALTER TABLE t ADD COLUMN b DEFAULT 3');
403
+ // The executed projection is a, b, b: one row, the last b wins.
404
+ const [row, ...rest] = Reflect.apply(all, stmt, []);
405
+ if (row && rest.length === 0 && Object.keys(row).length === 2 && row.a === 1 && row.b === 2)
406
+ return null;
407
+ }
408
+ catch {
409
+ // An all() that cannot answer the probe is not trusted with a wildcard.
410
+ }
411
+ finally {
412
+ probe?.close();
413
+ }
414
+ return { all, iterate };
415
+ }
416
+ let wildcardReuse;
417
+ /**
418
+ * Whether a statement containing `*` may be kept for reuse: trial the reader a
419
+ * wildcard read will use on a statement executed once and then reprepared by
420
+ * DDL that grows and then shrinks its table. Asked once per process.
421
+ */
422
+ function wildcardReuseSafe() {
423
+ if (wildcardReuse !== undefined)
424
+ return wildcardReuse;
425
+ let sqlite;
426
+ try {
427
+ sqlite = (0, node_module_1.createRequire)(process.cwd())('node:sqlite');
428
+ }
429
+ catch {
430
+ wildcardReuse = false;
431
+ return wildcardReuse;
432
+ }
433
+ if (typeof sqlite.StatementSync.prototype.iterate !== 'function') {
434
+ wildcardReuse = false;
435
+ return wildcardReuse;
436
+ }
437
+ if (wildcardRead === undefined)
438
+ wildcardRead = probeWildcardRead();
439
+ const reader = wildcardRead ? wildcardRead.iterate : sqlite.StatementSync.prototype.all;
440
+ let probe;
441
+ try {
442
+ probe = new sqlite.DatabaseSync(':memory:');
443
+ probe.exec('CREATE TABLE t(a); INSERT INTO t VALUES(1)');
444
+ const stmt = probe.prepare('SELECT * FROM t');
445
+ [...Reflect.apply(reader, stmt, [])];
446
+ probe.exec('ALTER TABLE t ADD COLUMN b DEFAULT 3');
447
+ const grown = [...Reflect.apply(reader, stmt, [])];
448
+ probe.exec('ALTER TABLE t DROP COLUMN b');
449
+ const shrunk = [...Reflect.apply(reader, stmt, [])];
450
+ wildcardReuse =
451
+ grown.length === 1 &&
452
+ Object.keys(grown[0]).length === 2 &&
453
+ grown[0].b === 3 &&
454
+ shrunk.length === 1 &&
455
+ Object.keys(shrunk[0]).length === 1 &&
456
+ shrunk[0].a === 1;
457
+ }
458
+ catch {
459
+ wildcardReuse = false;
460
+ }
461
+ finally {
462
+ probe?.close();
463
+ }
464
+ return wildcardReuse;
465
+ }
466
+ /**
467
+ * Read a stepped result. On a runtime whose probe trusts all(), this is all()
468
+ * after one null test. Elsewhere builtin statements containing `*` are read by
469
+ * native iteration, which reads the width after each step. Wrapped/compatible
470
+ * all() methods keep control of their own row contract.
471
+ */
472
+ function readResultRows(stmt, sql, binding, positionalParams) {
473
+ if (wildcardRead !== null && sql.includes('*')) {
474
+ wildcardRead ??= probeWildcardRead();
475
+ if (wildcardRead && stmt.all === wildcardRead.all) {
476
+ const iterator = Reflect.apply(wildcardRead.iterate, stmt, positionalParams ?? (binding ? [binding] : []));
477
+ try {
478
+ return [...iterator];
479
+ }
480
+ finally {
481
+ iterator.return?.();
482
+ }
483
+ }
484
+ }
485
+ return positionalParams ? stmt.all(...positionalParams) : binding ? stmt.all(binding) : stmt.all();
486
+ }
487
+ /**
488
+ * Which array readers return the executed projection on this runtime, or
489
+ * `null` when neither can be trusted (or there is no builtin). `undefined`
490
+ * until the first wildcard array candidate.
491
+ *
492
+ * Both readers are trialled, because which one runs is not this probe's
493
+ * choice: {@link readResultRows} iterates a wildcard when the OBJECT probe
494
+ * distrusts all(), whatever the array all() trial said. Measured, not
495
+ * assumed: Node 26.12 passes both trials and its object probe trusts all();
496
+ * Node 24.10 fails both all() trials (the width is fixed at prepare in BOTH
497
+ * row modes) and passes iteration, which is the route its object probe
498
+ * selects anyway. A runtime whose array all() passed while its object all()
499
+ * failed would iterate arrays, so {@link wildcardArraysEligible} requires
500
+ * the trial for the reader that will actually run, never the other one.
501
+ */
502
+ let wildcardArrayRead;
503
+ function probeWildcardArrayRead() {
504
+ let sqlite;
505
+ try {
506
+ sqlite = (0, node_module_1.createRequire)(process.cwd())('node:sqlite');
507
+ }
508
+ catch {
509
+ return null;
510
+ }
511
+ const { all, iterate, setReturnArrays } = sqlite.StatementSync.prototype;
512
+ if (typeof setReturnArrays !== 'function' ||
513
+ !Function.prototype.toString.call(setReturnArrays).includes('[native code]'))
514
+ return null;
515
+ // One trial per reader: prepare, grow the table, then read as arrays. The
516
+ // executed projection is a, b with the new column's default in b.
517
+ const trial = (read) => {
518
+ let probe;
519
+ try {
520
+ probe = new sqlite.DatabaseSync(':memory:');
521
+ probe.exec('CREATE TABLE t(a); INSERT INTO t VALUES(1)');
522
+ const stmt = probe.prepare('SELECT * FROM t');
523
+ probe.exec('ALTER TABLE t ADD COLUMN b DEFAULT 3');
524
+ Reflect.apply(setReturnArrays, stmt, [true]);
525
+ const [row, ...rest] = read(stmt);
526
+ return rest.length === 0 && Array.isArray(row) && row.length === 2 && row[0] === 1 && row[1] === 3;
527
+ }
528
+ catch {
529
+ return false;
530
+ }
531
+ finally {
532
+ probe?.close();
533
+ }
534
+ };
535
+ const allOk = trial((stmt) => Reflect.apply(all, stmt, []));
536
+ const iterateOk = typeof iterate === 'function' && trial((stmt) => [...Reflect.apply(iterate, stmt, [])]);
537
+ return allOk || iterateOk ? { all: allOk, iterate: iterateOk } : null;
538
+ }
539
+ /**
540
+ * May a wildcard statement read array rows on this runtime? The probe answer
541
+ * is per-process, like {@link wildcardRead}. The object probe decides the
542
+ * reader ({@link readResultRows} iterates exactly when it distrusts all()),
543
+ * so eligibility is the ARRAY trial for that same reader: iteration when
544
+ * {@link wildcardRead} holds the builtin methods, all() when it is `null`.
545
+ */
546
+ function wildcardArraysEligible(sql) {
547
+ if (wildcardArrayRead === undefined)
548
+ wildcardArrayRead = probeWildcardArrayRead();
549
+ if (!wildcardArrayRead)
550
+ return false;
551
+ if (wildcardRead === undefined && sql.includes('*'))
552
+ wildcardRead = probeWildcardRead();
553
+ return wildcardRead ? wildcardArrayRead.iterate : wildcardArrayRead.all;
554
+ }
386
555
  /**
387
556
  * The `node:sqlite` namespace, looked up once, or `null` when this Node build
388
557
  * has no such builtin. Deliberately separate from {@link loadDatabaseSync},
@@ -580,12 +749,12 @@ function normalizeQueryArgs(arg, values) {
580
749
  * guarantee Postgres' numbered `$N` gives. Returns `undefined` when there are no
581
750
  * params so parameter-less statements (BEGIN/COMMIT/DDL) bind nothing.
582
751
  */
583
- function toNamedBinding(values) {
752
+ function toNamedBinding(values, qualified = false) {
584
753
  if (values.length === 0)
585
754
  return undefined;
586
755
  const named = {};
587
756
  for (let i = 0; i < values.length; i++) {
588
- named[`p${i + 1}`] = toSqliteParam(values[i]);
757
+ named[qualified ? `:p${i + 1}` : `p${i + 1}`] = (0, sqlite_dialect_js_1.toSqliteParam)(values[i]);
589
758
  }
590
759
  return named;
591
760
  }
@@ -593,35 +762,280 @@ function toNamedBinding(values) {
593
762
  function refusePlaceholder(message) {
594
763
  throw new errors_js_1.ValidationError(message);
595
764
  }
596
- function runStatement(db, text, values, decoderCache, declared = null) {
597
- const binding = toNamedBinding(values);
765
+ /**
766
+ * `sql` with each quoted run replaced by `x` and each comment by a space, in one
767
+ * scan from the left. A `[` with no `]` after it stays as written. Past the last
768
+ * `]` no `[` can close, so an unclosed one is known without scanning to the end
769
+ * again from each `[`, which made a run of them quadratic.
770
+ */
771
+ function maskQuotedRunsAndComments(sql) {
772
+ const token = /'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)|\[/g;
773
+ const lastClose = sql.lastIndexOf(']');
774
+ let masked = '';
775
+ let end = 0;
776
+ for (let match = token.exec(sql); match; match = token.exec(sql)) {
777
+ if (match[0] === '[') {
778
+ if (match.index > lastClose)
779
+ continue;
780
+ token.lastIndex = sql.indexOf(']', match.index) + 1;
781
+ }
782
+ masked += sql.slice(end, match.index) + (/^(?:--|\/\*)/.test(match[0]) ? ' ' : 'x');
783
+ end = token.lastIndex;
784
+ }
785
+ return masked + sql.slice(end);
786
+ }
787
+ /** Let SQLite parse triggers/quoted SQL, then refuse any unconsumed statement before stepping. */
788
+ function prepareSingleStatement(db, sql) {
789
+ const refuse = () => {
790
+ throw new errors_js_1.ValidationError('SQLite query accepts one statement; execute additional statements separately.');
791
+ };
792
+ if (sql.includes('\0'))
793
+ refuse();
794
+ // Some PRAGMAs take effect during prepare. Screen their separators first;
795
+ // quoted runs remain code markers, while SQLite comments disappear.
796
+ if (sql.includes(';')) {
797
+ const code = maskQuotedRunsAndComments(sql).replace(/^[;\s]+/, '');
798
+ // Refuse code after a separator. Everything from the first `;` to the next
799
+ // code character is a separator, so the first `;` decides it.
800
+ const separator = code.indexOf(';');
801
+ if (/^(?:EXPLAIN\s+(?:QUERY\s+PLAN\s+)?)?PRAGMA\b/i.test(code) &&
802
+ separator >= 0 &&
803
+ /[^;\s]/.test(code.slice(separator + 1)))
804
+ refuse();
805
+ }
806
+ const stmt = db.prepare(sql);
807
+ // Node 22.5 exposed this as a method; later runtimes use a getter.
808
+ const source = stmt.sourceSQL;
809
+ const parsed = typeof source === 'function' ? source.call(stmt) : source;
810
+ if (!sql.startsWith(parsed) ||
811
+ sql.slice(parsed.length).replace(/--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)|[;\t\n\r\f ]/g, '')) {
812
+ refuse();
813
+ }
814
+ return stmt;
815
+ }
816
+ // Only a factory-opened, never exposed handle has no caller-installed prepare
817
+ // callbacks (notably an authorizer whose policy can change between calls).
818
+ const unexposedNativeDatabases = new WeakSet();
819
+ function sqliteQueryPlan(text, valueCount, memo) {
820
+ // Avoid hashing oversized text on every execution, even when it cannot fit.
821
+ const cacheable = text.length <= 32768;
822
+ const previous = cacheable ? memo.entries.get(text) : undefined;
823
+ // Parameter count is part of the identity: rewriting validates $n bounds,
824
+ // and zero parameters deliberately bypass rewriting altogether.
825
+ if (previous?.valueCount === valueCount)
826
+ return previous;
827
+ const sql = (0, sql_placeholders_js_1.rewritePositionalPlaceholders)(text, 'sqlite', valueCount, (i) => `:p${i}`, refusePlaceholder);
828
+ // Conservative UTF-16 payload accounting, including both strings even when
829
+ // rewriting returns the input. The cap is not a JavaScript/native heap bound.
830
+ const bytes = (text.length + sql.length) * 2;
831
+ const plan = { valueCount, sql, returnsRows: statementReturnsRows(sql), bytes };
832
+ if (previous) {
833
+ memo.entries.delete(text);
834
+ memo.bytes -= previous.bytes;
835
+ }
836
+ // Keep the first shapes that fit. Churning SQL cannot evict hot entries or
837
+ // impose per-miss eviction/accounting work once the memo is full.
838
+ if (cacheable && memo.entries.size < 128 && memo.bytes + bytes <= 131072) {
839
+ memo.entries.set(text, plan);
840
+ memo.bytes += bytes;
841
+ }
842
+ return plan;
843
+ }
844
+ let nativeResultMethods;
845
+ const bindingArrayStatements = new WeakMap();
846
+ /** Array results require builtin descriptions; compatible/wrapped methods keep object rows. */
847
+ function nativeArrayResults(db, stmt) {
848
+ const binding = bindingArrayStatements.get(db)?.get(stmt);
849
+ if (binding) {
850
+ return stmt.all === binding.all &&
851
+ stmt.columns === binding.columns &&
852
+ stmt.setReturnArrays === binding.setReturnArrays
853
+ ? binding
854
+ : undefined;
855
+ }
856
+ if (nativeResultMethods === undefined) {
857
+ try {
858
+ const { StatementSync } = (0, node_module_1.createRequire)(process.cwd())('node:sqlite');
859
+ const p = StatementSync.prototype;
860
+ const methods = { all: p.all, columns: p.columns, setReturnArrays: p.setReturnArrays };
861
+ nativeResultMethods = Object.values(methods).every((fn) => typeof fn === 'function' && Function.prototype.toString.call(fn).includes('[native code]'))
862
+ ? methods
863
+ : null;
864
+ }
865
+ catch {
866
+ nativeResultMethods = null;
867
+ }
868
+ }
869
+ if (nativeResultMethods &&
870
+ stmt.all === nativeResultMethods.all &&
871
+ stmt.columns === nativeResultMethods.columns &&
872
+ stmt.setReturnArrays === nativeResultMethods.setReturnArrays)
873
+ return nativeResultMethods;
874
+ return undefined;
875
+ }
876
+ const bulkInsertBindings = new WeakMap();
877
+ /**
878
+ * The `?` spelling of a generated bulk INSERT, or `undefined` unless the SQL
879
+ * holds exactly `:p1 … :p<count>` in order and nothing else that looks like
880
+ * one. The strict sequence check is what makes a textual rewrite sound: a
881
+ * quoted identifier containing `:p7` would break the run or the count and the
882
+ * statement keeps named binding.
883
+ */
884
+ function positionalBulkSql(sql, count) {
885
+ if (count === 0)
886
+ return undefined;
887
+ let seen = 0;
888
+ let inOrder = true;
889
+ const out = sql.replace(/:p(\d+)/g, (_token, digits) => {
890
+ seen += 1;
891
+ if (Number(digits) !== seen)
892
+ inOrder = false;
893
+ return '?';
894
+ });
895
+ return inOrder && seen === count ? out : undefined;
896
+ }
897
+ /**
898
+ * @internal Record a generated bulk INSERT for the binding shortcuts above. Called by
899
+ * the SQLite dialects at statement-build time with the exact params array the
900
+ * statement will execute with.
901
+ */
902
+ function recordSqliteBulkInsert(params, sql, qualifiedNames = true) {
903
+ bulkInsertBindings.set(params, { sql, count: params.length, qualifiedNames });
904
+ }
905
+ let nativePrepareFn;
906
+ /**
907
+ * May this handle receive the positional spelling? Only when nothing can
908
+ * observe the difference: a genuine `node:sqlite` handle whose `prepare` is
909
+ * still the native prototype method (a wrapped or proxied handle, or a
910
+ * compatible driver object, keeps the generated SQL and named binding it has
911
+ * always seen), or the better-sqlite3 adapter over a handle this package
912
+ * opened itself (registered for array results in {@link bindingArrayStatements}).
913
+ */
914
+ function bulkPositionalEligible(db) {
915
+ if (bindingArrayStatements.has(db))
916
+ return true;
917
+ if (nativePrepareFn === undefined) {
918
+ try {
919
+ const { DatabaseSync } = (0, node_module_1.createRequire)(process.cwd())('node:sqlite');
920
+ const fn = DatabaseSync.prototype.prepare;
921
+ nativePrepareFn =
922
+ typeof fn === 'function' && Function.prototype.toString.call(fn).includes('[native code]') ? fn : null;
923
+ }
924
+ catch {
925
+ nativePrepareFn = null;
926
+ }
927
+ }
928
+ return nativePrepareFn !== null && db.prepare === nativePrepareFn;
929
+ }
930
+ /**
931
+ * The positional spelling and spread values for a generated bulk insert on
932
+ * an eligible handle, or `undefined` to keep named binding. Kept out of
933
+ * {@link runStatement} so the path every statement takes stays as it was;
934
+ * only a recorded bulk insert calls this. The derived text is memoized on
935
+ * the WeakMap entry, so a statement executed more than once (a deferred
936
+ * query run twice) derives once.
937
+ */
938
+ function bulkPositionalBinding(db, bulk, values) {
939
+ if (!bulkPositionalEligible(db))
940
+ return undefined;
941
+ bulk.positional ??= positionalBulkSql(bulk.sql, bulk.count) ?? null;
942
+ if (bulk.positional === null)
943
+ return undefined;
944
+ // Read each slot by index, never `map`: a sparse params array binds NULL in
945
+ // its holes (toSqliteParam(undefined)) without shifting later values, the
946
+ // same contract the named loop in toNamedBinding keeps.
947
+ const params = new Array(values.length);
948
+ for (let i = 0; i < values.length; i++)
949
+ params[i] = (0, sqlite_dialect_js_1.toSqliteParam)(values[i]);
950
+ return { sql: bulk.positional, params };
951
+ }
952
+ /** Account the actual native bindings, never the caller's pre-conversion objects. */
953
+ function retainStatementBindings(binding) {
954
+ let bytes = 0;
955
+ for (const name in binding) {
956
+ const value = binding[name];
957
+ if (value instanceof Uint8Array)
958
+ return false;
959
+ bytes += typeof value === 'string' ? value.length * 2 : 8;
960
+ if (bytes > 8192)
961
+ return false;
962
+ }
963
+ return true;
964
+ }
965
+ function runStatement(db, text, values, declared, memo, plans, statements) {
966
+ const generated = bulkInsertBindings.get(values);
967
+ const bulk = generated?.sql === text && generated.count === values.length ? generated : undefined;
968
+ const positional = bulk ? bulkPositionalBinding(db, bulk, values) : undefined;
969
+ const binding = positional ? undefined : toNamedBinding(values, bulk?.qualifiedNames ?? false);
598
970
  // `$n` is the spelling `rawUnsafe` documents for every engine; SQLite would
599
971
  // read `$1` as a parameter NAMED "1", which the `{ p1, ... }` binding lacks.
600
- const sql = (0, sql_placeholders_js_1.rewritePositionalPlaceholders)(text, 'sqlite', values.length, (i) => `:p${i}`, refusePlaceholder);
972
+ const plan = sqliteQueryPlan(text, values.length, plans);
973
+ const { sql, returnsRows } = plan;
974
+ // Only genuine native preparation is unobservable to a caller's wrapper.
975
+ // Keep the admitted SQL's bounded slot, never a SQL-to-type cache: SQLite
976
+ // can reprepare this statement on step, and metadata is still read after it.
977
+ let reusable = statements !== undefined &&
978
+ !bulk &&
979
+ /^\s*(?:SELECT|INSERT|UPDATE|DELETE|REPLACE|BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i.test(sql) &&
980
+ bulkPositionalEligible(db) &&
981
+ !bindingArrayStatements.has(db);
601
982
  let stmt;
602
983
  try {
603
- stmt = db.prepare(sql);
984
+ stmt = (reusable && statements.get(plan)) || prepareSingleStatement(db, positional?.sql ?? sql);
985
+ // A recursive call must never check out a statement that is being stepped.
986
+ statements?.delete(plan);
604
987
  }
605
988
  catch (err) {
606
989
  throw augmentSqliteError(err);
607
990
  }
991
+ // Some runtimes fix a wildcard's width before stepping, even in iterate()
992
+ // (Node 22.13 to 22.15). A statement kept across DDL there would keep its old
993
+ // columns, so a star is retained only where the reader it will use follows a
994
+ // reprepare; elsewhere it is prepared fresh, as before.
995
+ if (reusable && sql.includes('*') && !wildcardReuseSafe())
996
+ reusable = false;
608
997
  stmt.setReadBigInts(true);
998
+ // node:sqlite builds a bare-name map on every execution when enabled. The
999
+ // generated statement binds exact :pN names, so that extra lookup is unused.
1000
+ if (bulk?.qualifiedNames && !positional)
1001
+ stmt.setAllowBareNamedParameters?.(false);
609
1002
  try {
610
- if (statementReturnsRows(sql)) {
611
- // Describe each distinct statement ONCE. `null` (nothing to decode) is a
612
- // cached answer too, so the ordinary query pays a single Map hit per call
613
- // and nothing per row.
614
- let decoders = decoderCache?.get(sql);
615
- if (decoders === undefined) {
616
- decoders = resultColumnDecoders(stmt, declared);
617
- decoderCache?.set(sql, decoders);
618
- }
619
- const rows = (binding ? stmt.all(binding) : stmt.all()).map((r) => normalizeRow(r, decoders ?? undefined));
1003
+ if (returnsRows) {
1004
+ // With no wildcard, SELECT's result width is fixed by its expressions.
1005
+ // A wildcard SELECT joins the array path when this runtime's array
1006
+ // read returns the executed projection (probeWildcardArrayRead); the
1007
+ // keys still come from columns() after stepping, never a pre-step
1008
+ // shape. A LIMIT 1 read stays on object rows: its one row cannot
1009
+ // repay the columns() call and decode-plan setup.
1010
+ const arrays = bindingArrayStatements.get(db)?.has(stmt) ||
1011
+ (/^\s*SELECT\b/i.test(sql) &&
1012
+ (!sql.includes('*') || (!/\bLIMIT\s+1\b/.test(sql) && wildcardArraysEligible(sql))))
1013
+ ? nativeArrayResults(db, stmt)
1014
+ : undefined;
1015
+ if (arrays)
1016
+ arrays.setReturnArrays.call(stmt, true);
1017
+ const raw = readResultRows(stmt, positional?.sql ?? sql, binding, positional?.params);
1018
+ // SQL text cannot identify column types across DDL, rollback or namespace
1019
+ // changes. Describe this execution after stepping, when SQLite may have
1020
+ // automatically reprepared it. A matching description can reuse decoding.
1021
+ // Pin the builtin method before stepping: SQL functions can run JS while
1022
+ // all() executes. Neither types nor keys may come from a pre-step shape.
1023
+ const columns = arrays && raw.length > 0 ? arrays.columns.call(stmt) : undefined;
1024
+ const decoders = raw.length === 0 ? null : resultColumnDecoders(stmt, declared, memo, columns);
1025
+ const rows = raw.length > 0 && (arrays || raw.length > 1)
1026
+ ? normalizeResultRows(raw, decoders, columns, arrays && arrays === nativeResultMethods)
1027
+ : raw.map((r) => normalizeRow(r, decoders ?? undefined));
1028
+ // Preparation is a fixed cost. Large results keep fresh statements:
1029
+ // retaining them does not repay the native reader's result-sized work.
1030
+ if (reusable && raw.length <= 128 && retainStatementBindings(binding))
1031
+ statements.set(plan, stmt);
620
1032
  return { rows, rowCount: rows.length };
621
1033
  }
622
- const info = binding ? stmt.run(binding) : stmt.run();
1034
+ const info = positional ? stmt.run(...positional.params) : binding ? stmt.run(binding) : stmt.run();
623
1035
  const changes = typeof info.changes === 'bigint' ? Number(info.changes) : info.changes;
624
1036
  const lastID = typeof info.lastInsertRowid === 'bigint' ? Number(info.lastInsertRowid) : info.lastInsertRowid;
1037
+ if (reusable && retainStatementBindings(binding))
1038
+ statements.set(plan, stmt);
625
1039
  return { rows: [], rowCount: changes, lastID, insertId: lastID };
626
1040
  }
627
1041
  catch (err) {
@@ -635,6 +1049,8 @@ const sqliteTxStorage = new node_async_hooks_1.AsyncLocalStorage();
635
1049
  const TX_OPEN_HEAD = /^\s*(?:begin|savepoint)\b/i;
636
1050
  /** Statement heads that end the transaction (not `ROLLBACK TO`, which keeps it open). */
637
1051
  const TX_CLOSE_HEAD = /^\s*(?:commit|end|rollback(?!\s+(?:transaction\s+)?to\b))\b/i;
1052
+ /** A transaction boundary invalidates a suspended native iterator before executing. */
1053
+ const TX_BOUNDARY_HEAD = /^\s*(?:begin|savepoint|release|commit|end|rollback)\b/i;
638
1054
  /**
639
1055
  * The one statement the pool can never run: something on the handle while the
640
1056
  * transaction that owns it is waiting for that very statement.
@@ -645,11 +1061,11 @@ function statementInsideTransactionError() {
645
1061
  'it) or wait for it forever. Use the `tx` client the callback receives, or make the call after the ' +
646
1062
  'transaction completes.');
647
1063
  }
648
- /** The error a caller gets when an open transaction holds the handle past `busyTimeoutMs`. */
1064
+ /** The error when a transaction or iterator holds the handle past `busyTimeoutMs`. */
649
1065
  function handleBusyError(timeoutMs) {
650
1066
  return new errors_js_1.SerializationFailureError({
651
- message: `SQLite database is busy: a transaction on this client held it for longer than busyTimeoutMs (${timeoutMs} ms). ` +
652
- 'Retry the operation (withRetry does), keep transactions short, or raise busyTimeoutMs.',
1067
+ message: `SQLite database is busy: a transaction or stream on this client held it for longer than busyTimeoutMs (${timeoutMs} ms). ` +
1068
+ 'Retry the operation (withRetry does), keep transactions short, close streams with return(), or raise busyTimeoutMs.',
653
1069
  });
654
1070
  }
655
1071
  /**
@@ -663,19 +1079,15 @@ function handleBusyError(timeoutMs) {
663
1079
  * wait their turn in FIFO order (bounded by `busyTimeoutMs`) instead of running
664
1080
  * inside it. Without that, a write issued outside an open transaction joined
665
1081
  * it, reported success, and was rolled back with it, and reads saw its
666
- * uncommitted rows. A checkout that does not open a transaction (a stream, a
667
- * connectivity check) holds nothing, so other callers keep running beside it.
1082
+ * uncommitted rows. A native iterator also owns the handle until it is closed;
1083
+ * a connectivity check holds it only while its statement runs.
668
1084
  */
669
1085
  class SqlitePool {
670
- /** The underlying `node:sqlite` handle, exposed as an escape hatch (seed/DDL). */
671
- db;
1086
+ nativeDb;
672
1087
  closed = false;
673
- /**
674
- * `sql -> result columns to decode` (or `null` for none). Bounded like
675
- * the query builder's SQL-template cache, since a caller can generate
676
- * unbounded distinct statements (raw SQL, an IN-list that inlines).
677
- */
678
- decoderCache = new utils_js_1.LRUCache(1000);
1088
+ decoderMemo = { decoders: null };
1089
+ queryPlans = { entries: new Map(), bytes: 0 };
1090
+ statements;
679
1091
  /** Schema columns whose stored form is not their declared JS type (see {@link declaredDecoders}). */
680
1092
  declared;
681
1093
  busyTimeoutMs;
@@ -686,8 +1098,23 @@ class SqlitePool {
686
1098
  poolOwner = {};
687
1099
  /** Transaction state when the driver cannot report it (`isTransaction` arrived in Node 22.16). */
688
1100
  trackedTransaction = false;
1101
+ /** Only transactions opened through this pool may be rolled back on release. */
1102
+ transactionOwner = null;
1103
+ activeIterator;
689
1104
  constructor(db, options = {}) {
690
- this.db = db;
1105
+ this.nativeDb = db;
1106
+ // Capture the owner so readonly proxies can expose the handle without
1107
+ // forwarding private reads or writes through their public interface.
1108
+ Object.defineProperty(this, 'db', {
1109
+ get: () => {
1110
+ this.statements = undefined;
1111
+ return db;
1112
+ },
1113
+ enumerable: true,
1114
+ configurable: true,
1115
+ });
1116
+ if (unexposedNativeDatabases.delete(db))
1117
+ this.statements = new WeakMap();
691
1118
  const t = Number(options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS);
692
1119
  this.busyTimeoutMs = Number.isFinite(t) && t >= 0 ? t : DEFAULT_BUSY_TIMEOUT_MS;
693
1120
  this.declared = declaredDecoders(options.schema);
@@ -710,8 +1137,9 @@ class SqlitePool {
710
1137
  'run the statement through the client or a new transaction.');
711
1138
  }
712
1139
  const { text: sql, params } = normalizeQueryArgs(text, values);
713
- return this.runAs(owner, sql, params);
1140
+ return this.runAs(owner, sql, params, () => released);
714
1141
  },
1142
+ streamBatches: (text, values, batchSize) => this.iterateAs(owner, text, values, batchSize, () => released),
715
1143
  wrapTransactionCallback: (fn) => sqliteTxStorage.run({ pool: this, owner, parent: sqliteTxStorage.getStore() }, fn),
716
1144
  release: () => {
717
1145
  if (released)
@@ -724,18 +1152,32 @@ class SqlitePool {
724
1152
  async end() {
725
1153
  if (this.closed)
726
1154
  return;
727
- this.closed = true;
728
- this.db.close();
1155
+ try {
1156
+ this.activeIterator?.close();
1157
+ }
1158
+ finally {
1159
+ this.closed = true;
1160
+ this.decoderMemo.columns = undefined;
1161
+ this.decoderMemo.decoders = null;
1162
+ this.statements = undefined;
1163
+ this.queryPlans.entries.clear();
1164
+ this.queryPlans.bytes = 0;
1165
+ this.nativeDb.close();
1166
+ }
729
1167
  }
730
1168
  /** Is the handle inside a transaction right now? */
731
1169
  inTransaction() {
732
- const reported = this.db.isTransaction;
1170
+ const reported = this.nativeDb.isTransaction;
733
1171
  return typeof reported === 'boolean' ? reported : this.trackedTransaction;
734
1172
  }
735
1173
  /** Run one statement for `owner`, waiting first if another caller's transaction holds the handle. */
736
- async runAs(owner, sql, params) {
1174
+ async runAs(owner, sql, params, released) {
737
1175
  if (this.closed)
738
1176
  throw new errors_js_1.ConnectionError('This SQLite client has been disconnected.');
1177
+ if (this.inTransaction() && this.transactionOwner === null && this.owner !== owner) {
1178
+ throw new errors_js_1.UnsupportedFeatureError('A pooled statement inside an externally opened transaction', 'sqlite', 'The supplied DatabaseSync has a caller-owned transaction. Use that handle for statements until ' +
1179
+ 'the caller commits or rolls back; the pool cannot assign unrelated statements to that transaction safely.');
1180
+ }
739
1181
  if (this.owner !== owner) {
740
1182
  if (this.owner !== null || this.waiters.length > 0) {
741
1183
  if (this.calledFromOwnersCallback())
@@ -747,19 +1189,143 @@ class SqlitePool {
747
1189
  }
748
1190
  }
749
1191
  try {
750
- const result = runStatement(this.db, sql, params, this.decoderCache, this.declared);
1192
+ if (this.closed || released?.())
1193
+ throw new errors_js_1.ConnectionError('This SQLite connection was closed or released.');
1194
+ if (this.activeIterator?.owner === owner) {
1195
+ if (TX_BOUNDARY_HEAD.test(sql))
1196
+ this.activeIterator.close();
1197
+ else
1198
+ throw new errors_js_1.ValidationError('Close the active SQLite stream with return() before issuing another statement on its connection.');
1199
+ }
1200
+ const wasInTransaction = this.inTransaction();
1201
+ const result = runStatement(this.nativeDb, sql, params, this.declared, this.decoderMemo, this.queryPlans, this.statements);
751
1202
  if (TX_OPEN_HEAD.test(sql))
752
1203
  this.trackedTransaction = true;
753
1204
  else if (TX_CLOSE_HEAD.test(sql))
754
1205
  this.trackedTransaction = false;
1206
+ if (!wasInTransaction && this.inTransaction())
1207
+ this.transactionOwner = owner;
1208
+ else if (!this.inTransaction())
1209
+ this.transactionOwner = null;
755
1210
  return result;
756
1211
  }
757
1212
  finally {
758
1213
  // A statement that leaves no transaction open hands the handle on.
759
- if (this.owner === owner && !this.inTransaction())
1214
+ if (this.owner === owner && !this.inTransaction() && !this.activeIterator)
760
1215
  this.handOff();
761
1216
  }
762
1217
  }
1218
+ /**
1219
+ * Step on this checkout's handle, never `.all()`. Stepping is synchronous:
1220
+ * timers/cancellation run between pulls, not during sqlite3_step(). A batch
1221
+ * bounds row count only; one BLOB/JSON row, nested relation or SQLite sort
1222
+ * can still be arbitrarily large. No nested results are truncated.
1223
+ */
1224
+ async *iterateAs(owner, text, values, batchSize, released) {
1225
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1)
1226
+ throw new errors_js_1.ValidationError('SQLite stream batchSize must be a positive safe integer.');
1227
+ if (this.closed || released())
1228
+ throw new errors_js_1.ConnectionError('This SQLite connection was closed or released.');
1229
+ // The SQL-head fallback tracks only statements sent through this pool. It
1230
+ // cannot distinguish an external transaction on a supplied handle, so it
1231
+ // cannot safely support the native iterator's ownership contract.
1232
+ if (typeof this.nativeDb.isTransaction !== 'boolean')
1233
+ throw new errors_js_1.UnsupportedFeatureError('Native incremental streaming', 'sqlite', 'DatabaseSync.isTransaction is required (Node 22.x >= 22.16, or Node >= 24). Upgrade Node for native streaming.');
1234
+ if (this.inTransaction() && this.transactionOwner === null && this.owner !== null && this.owner !== owner) {
1235
+ throw new errors_js_1.UnsupportedFeatureError('Concurrent streams inside an externally opened transaction', 'sqlite', 'Close the active stream before opening another stream on the supplied DatabaseSync.');
1236
+ }
1237
+ if (this.owner !== owner) {
1238
+ if (this.owner !== null || this.waiters.length > 0) {
1239
+ if (this.calledFromOwnersCallback())
1240
+ throw statementInsideTransactionError();
1241
+ await this.waitForHandle(owner);
1242
+ }
1243
+ else
1244
+ this.owner = owner;
1245
+ }
1246
+ let active;
1247
+ let failed = false;
1248
+ try {
1249
+ if (this.closed || released())
1250
+ throw new errors_js_1.ConnectionError('This SQLite connection was closed or released.');
1251
+ if (this.activeIterator)
1252
+ throw new errors_js_1.ValidationError('Close the active SQLite stream with return() before opening another stream on its connection.');
1253
+ const binding = toNamedBinding(values);
1254
+ const { sql } = sqliteQueryPlan(text, values.length, this.queryPlans);
1255
+ const stmt = prepareSingleStatement(this.nativeDb, sql);
1256
+ stmt.setReadBigInts(true);
1257
+ if (typeof stmt.iterate !== 'function')
1258
+ throw new errors_js_1.UnsupportedFeatureError('Native incremental streaming', 'sqlite', 'The SQLite driver must provide StatementSync.iterate().');
1259
+ let normalize;
1260
+ const iterator = binding ? stmt.iterate(binding) : stmt.iterate();
1261
+ if (typeof iterator.return !== 'function')
1262
+ throw new errors_js_1.UnsupportedFeatureError('Native incremental streaming', 'sqlite', 'The SQLite iterator must provide return() so a suspended statement can be closed.');
1263
+ let closed = false;
1264
+ active = {
1265
+ owner,
1266
+ close: () => {
1267
+ if (closed)
1268
+ return;
1269
+ closed = true;
1270
+ try {
1271
+ iterator.return();
1272
+ }
1273
+ finally {
1274
+ if (this.activeIterator === active)
1275
+ this.activeIterator = undefined;
1276
+ }
1277
+ },
1278
+ };
1279
+ this.activeIterator = active;
1280
+ while (true) {
1281
+ if (closed)
1282
+ throw new errors_js_1.ValidationError('This SQLite stream was closed when its transaction or connection ended.');
1283
+ const batch = [];
1284
+ let done = false;
1285
+ for (let i = 0; i < batchSize; i++) {
1286
+ const step = iterator.next();
1287
+ if (step.done) {
1288
+ done = true;
1289
+ break;
1290
+ }
1291
+ // The first step can reprepare after external DDL. Validate its fresh
1292
+ // description, then pin the decoder map for this iterator's snapshot.
1293
+ if (normalize === undefined) {
1294
+ const decoders = resultColumnDecoders(stmt, this.declared, this.decoderMemo);
1295
+ batch.push(normalizeRow(step.value, decoders ?? undefined));
1296
+ normalize = streamRowNormalizer(stmt, step.value, decoders, !bindingArrayStatements.has(this.nativeDb));
1297
+ }
1298
+ else
1299
+ batch.push(normalize(step.value));
1300
+ }
1301
+ if (done)
1302
+ active.close();
1303
+ if (batch.length > 0)
1304
+ yield batch;
1305
+ if (done)
1306
+ return;
1307
+ }
1308
+ }
1309
+ catch (err) {
1310
+ failed = true;
1311
+ throw augmentSqliteError(err);
1312
+ }
1313
+ finally {
1314
+ try {
1315
+ active?.close();
1316
+ }
1317
+ catch (err) {
1318
+ // A step failure remains the primary error if cleanup also failed.
1319
+ // biome-ignore lint/correctness/noUnsafeFinally: only replaces a successful return, never a step failure.
1320
+ if (!failed)
1321
+ throw augmentSqliteError(err);
1322
+ }
1323
+ finally {
1324
+ if (this.owner === owner && !this.activeIterator && this.transactionOwner !== owner)
1325
+ this.handOff();
1326
+ }
1327
+ }
1328
+ }
763
1329
  /** True when the current async context is the callback of the transaction that owns the handle. */
764
1330
  calledFromOwnersCallback() {
765
1331
  for (let m = sqliteTxStorage.getStore(); m; m = m.parent) {
@@ -813,16 +1379,23 @@ class SqlitePool {
813
1379
  releaseOwner(owner) {
814
1380
  if (this.owner !== owner)
815
1381
  return;
816
- if (this.inTransaction() && !this.closed) {
817
- try {
818
- this.db.exec('ROLLBACK');
819
- }
820
- catch {
821
- // Nothing left to roll back.
1382
+ try {
1383
+ if (this.activeIterator?.owner === owner)
1384
+ this.activeIterator.close();
1385
+ }
1386
+ finally {
1387
+ if (this.transactionOwner === owner && this.inTransaction() && !this.closed) {
1388
+ try {
1389
+ this.nativeDb.exec('ROLLBACK');
1390
+ }
1391
+ catch {
1392
+ // Nothing left to roll back.
1393
+ }
1394
+ this.trackedTransaction = false;
1395
+ this.transactionOwner = null;
822
1396
  }
823
- this.trackedTransaction = false;
1397
+ this.handOff();
824
1398
  }
825
- this.handOff();
826
1399
  }
827
1400
  }
828
1401
  exports.SqlitePool = SqlitePool;
@@ -831,52 +1404,13 @@ exports.SqlitePool = SqlitePool;
831
1404
  // ---------------------------------------------------------------------------
832
1405
  /**
833
1406
  * Map a SQLite declared column type (type affinity) to a TypeScript type.
834
- * SQLite is dynamically typed; we read the declared `PRAGMA table_info` type.
1407
+ * SQLite is dynamically typed; use the declared `PRAGMA table_info` type.
835
1408
  */
836
- function sqliteTypeToTs(declaredType, nullable) {
837
- const t = declaredType.toLowerCase();
838
- let base;
839
- if (/int/.test(t))
840
- base = 'number';
841
- else if (/(real|floa|doub)/.test(t))
842
- base = 'number';
843
- else if (/bool/.test(t))
844
- base = 'boolean';
845
- else if (/(timestamp|datetime|date)/.test(t))
846
- base = 'Date';
847
- else if (/(char|clob|text)/.test(t))
848
- base = 'string';
849
- else if (/blob/.test(t))
850
- base = 'Uint8Array';
851
- else if (/(numeric|decimal)/.test(t))
852
- base = 'string';
853
- else if (t === '')
854
- base = 'unknown'; // no declared affinity (BLOB affinity)
855
- else
856
- base = 'unknown';
857
- return nullable ? `${base} | null` : base;
858
- }
859
1409
  /** Is a SQLite declared type a date/time type (so values coerce back to `Date`)? */
860
1410
  function isSqliteDateType(declaredType) {
861
1411
  const t = declaredType.toLowerCase();
862
1412
  return (0, schema_js_1.isDateType)(t) || /(timestamp|datetime|date)/.test(t);
863
1413
  }
864
- /** Map a schema-builder (Postgres-flavored) column type to a SQLite affinity. */
865
- function sqliteColumnAffinity(type) {
866
- const t = type.toUpperCase();
867
- if (/SERIAL|INT/.test(t))
868
- return 'INTEGER';
869
- if (/REAL|FLOAT|DOUBLE/.test(t))
870
- return 'REAL';
871
- if (/NUMERIC|DECIMAL|MONEY/.test(t))
872
- return 'NUMERIC';
873
- if (/BLOB|BYTEA/.test(t))
874
- return 'BLOB';
875
- if (/BOOL/.test(t))
876
- return 'INTEGER';
877
- // TEXT, VARCHAR, CHAR, UUID, JSON(B), TIMESTAMP(TZ), DATE, TIME, ENUM, …
878
- return 'TEXT';
879
- }
880
1414
  // ---------------------------------------------------------------------------
881
1415
  // sqliteDialect, the full Dialect contract for SQLite
882
1416
  // ---------------------------------------------------------------------------
@@ -890,402 +1424,11 @@ function sqliteColumnAffinity(type) {
890
1424
  * LISTEN/NOTIFY, RLS, advisory locks).
891
1425
  */
892
1426
  exports.sqliteDialect = {
893
- ...dialect_js_1.postgresDialect,
894
- name: 'sqlite',
895
- capabilities: Object.freeze({
896
- distinctOn: false,
897
- positionalJson: false,
898
- // NULLS FIRST / LAST since 3.30; NULL is the smallest value.
899
- nullsOrderingClause: true,
900
- nullsSortHigh: false,
901
- insensitiveInList: false,
902
- jsonDocumentEquality: 'text',
903
- jsonExtractTyped: true,
904
- jsonExactNumericCast: false,
905
- numericTextComparison: false,
906
- // Enforced only on a connection that turned `foreign_keys` on.
907
- enforcesForeignKeys: false,
908
- partitionLimitPushdown: false,
909
- utcTimestampRewrite: false,
910
- paramTypeCasts: false,
911
- namedEnumTypes: false,
912
- structuredValueColumns: 'scalars',
913
- // The default SQLITE_MAX_VARIABLE_NUMBER.
914
- maxBindParameters: 32766,
915
- maxInsertRows: Number.POSITIVE_INFINITY,
916
- // Measured: 40,000 rows insert 70 to 140 times faster in statements of 250
917
- // parameters than of 32,766 (named-parameter lookup is a linear search).
918
- chunkBindParameters: 250,
919
- upsertConflictTarget: 'explicit',
920
- setClauseOrder: 'snapshot',
921
- reselectLocksRows: false,
922
- integerDivision: '/',
923
- updateExpressions: true,
924
- bulkUpsertAppliesRepeatedKeys: true,
925
- skipDuplicatesCountsSkipped: false,
926
- readOnlyTransactions: false,
927
- connectionParameters: false,
928
- backendCancel: false,
929
- idleTransactionTimeout: false,
930
- abortsTransactionOnError: false,
931
- connectionDriver: 'engine-driver',
932
- preparesEveryStatement: false,
933
- statementSyntax: 'sqlite',
934
- inlineForeignKeys: true,
935
- unboundedTextKeys: true,
1427
+ ...(0, sqlite_dialect_js_1.createPortableSqliteDialect)({
1428
+ declaredTypes: driverReportsDeclaredTypes,
1429
+ decodeBlob: (value) => Uint8Array.from(Buffer.from(value, 'hex')),
1430
+ recordBulkInsert: recordSqliteBulkInsert,
936
1431
  }),
937
- resultStrategy: 'returning', // SQLite ≥ 3.35 has RETURNING
938
- supportsReturning: true,
939
- supportsILike: false,
940
- supportsVector: false,
941
- supportsJsonContains: false,
942
- // FTS5 is a virtual-table feature with its own MATCH syntax, not the
943
- // `to_tsvector @@ to_tsquery` shape Turbine's `search` filter emits.
944
- supportsFullTextSearch: false,
945
- // No array column type (a JSON column is not an array column).
946
- supportsArrayColumns: false,
947
- supportsListenNotify: false,
948
- supportsRLS: false,
949
- supportsAdvisoryLock: false,
950
- // No FROM-clause LATERAL: the opt-in lateral pick plan is Postgres-only.
951
- supportsLateralJoin: false,
952
- supportsPlanCacheMode: false,
953
- // No row locks: a write transaction locks the whole database.
954
- rowLockModes: [],
955
- // percentile_cont / percentile_disc exist only in builds compiled with
956
- // SQLITE_ENABLE_PERCENTILE, which node:sqlite cannot be assumed to have.
957
- supportsPercentileAggregates: false,
958
- // INSERT ... ON CONFLICT (cols) DO UPDATE ... RETURNING (3.24 + 3.35).
959
- supportsBulkUpsert: true,
960
- // SQLite explains a compiled query with `EXPLAIN QUERY PLAN` (four columns:
961
- // id, parent, notused, detail), overriding the inherited Postgres `EXPLAIN`.
962
- explainQuery: { prefix: 'EXPLAIN QUERY PLAN' },
963
- // json_group_array / json_object have no inline ORDER BY argument, so every
964
- // ordered to-many relation is forced through the inner-subquery rewrite.
965
- aggSupportsInlineOrderBy: false,
966
- jsonPathSupport: 'function',
967
- emptyJsonArrayLiteral: "json('[]')",
968
- nullJsonLiteral: 'NULL',
969
- // Named placeholders (`:p1`, `:p2`, …), NOT positional `?`. Turbine pushes
970
- // params in 1-indexed generation order but may EMIT them in a different SQL
971
- // text position (e.g. a `with`-relation LIMIT lands in the SELECT list, ahead
972
- // of the outer WHERE). Postgres reconciles this via numbered `$N`; positional
973
- // `?` cannot. SQLite named parameters bind by name, so `:pN` ↔ `params[N-1]`
974
- // exactly mirrors Postgres' `$N` semantics regardless of text order. The
975
- // driver binds via a `{ p1, p2, … }` object built from the positional array.
976
- paramPlaceholder(index) {
977
- return `:p${index}`;
978
- },
979
- quoteIdentifier(name) {
980
- return `"${name.replace(/"/g, '""')}"`;
981
- },
982
- buildJsonObject(pairs) {
983
- const args = pairs.map(([key, expr]) => `'${this.escapeStringLiteral(key)}', ${expr}`);
984
- return `json_object(${args.join(', ')})`;
985
- },
986
- buildJsonArrayAgg(jsonObjectExpr, orderBy) {
987
- // json() wraps each aggregated object so SQLite stores real JSON, not an
988
- // escaped string; COALESCE handles the empty-group NULL.
989
- const suffix = orderBy ? ` ${orderBy}` : '';
990
- return `COALESCE(json_group_array(json(${jsonObjectExpr}))${suffix}, json('[]'))`;
991
- },
992
- /**
993
- * SQLite's `json_group_array` double-encodes nested objects unless each nested
994
- * subresult is `json(...)`-wrapped. This is the whole point of the hook: it
995
- * keeps `users[0].posts[0].author.name` a real parsed tree instead of a string
996
- * containing a string containing JSON.
997
- */
998
- wrapJsonSubresult(subquery, fallback) {
999
- return `COALESCE(json((${subquery})), ${fallback})`;
1000
- },
1001
- jsonWireRule(columnType) {
1002
- // SQLite's storage classes, as introspection records them.
1003
- const t = columnType.toUpperCase();
1004
- // INTEGER is 64-bit, and `json_object` renders it as a JSON number, which
1005
- // is an IEEE double: 9007199254740993 came back through a `with` join as
1006
- // …992 while a top-level read and the batched loader both returned the
1007
- // exact decimal string. Carry the text and re-apply the SAME safe-integer
1008
- // policy `normalizeValue` applies to the driver's bigint, so all three
1009
- // paths agree for both small and large values.
1010
- if (t.includes('INT')) {
1011
- return {
1012
- sql: (ref) => `CAST(${ref} AS TEXT)`,
1013
- decode: (value) => {
1014
- if (typeof value !== 'string' || !/^-?\d+$/.test(value))
1015
- return value;
1016
- const asNumber = Number(value);
1017
- return Number.isSafeInteger(asNumber) ? asNumber : value;
1018
- },
1019
- };
1020
- }
1021
- // A declared-boolean column is 1/0 in storage, and the driver shim turns
1022
- // that back into true/false on every direct read (see
1023
- // resultColumnDecoders). `json_object` sees the raw integer and has no
1024
- // decltype to consult, so the join strategy alone would have kept handing
1025
- // back 1/0 while the top-level read, the batched loader and the flatten
1026
- // plan returned booleans, which is the same strategy-dependent type flip
1027
- // the bigint rule above exists to prevent. No cast is needed, only the
1028
- // decode: the JSON number IS the stored value, it just has to be read the
1029
- // same way.
1030
- //
1031
- // Gated on the SAME capability the direct-read half feature-detects (see
1032
- // driverReportsDeclaredTypes). Without it the shim cannot name a boolean
1033
- // result column, so 1/0 is the answer everywhere; converting here alone
1034
- // would put the flip back, pointing the other way.
1035
- const decode = sqliteValueDecode(columnType);
1036
- if (decode === 'boolean' && driverReportsDeclaredTypes()) {
1037
- return {
1038
- // Carried as TEXT because that is how the decode half is reached at
1039
- // all: the parser only runs `decode` on a string cell, so a rule that
1040
- // left the JSON number alone would never fire. The CASE narrows the
1041
- // carrier to EXACTLY the two values that mean true/false, so anything
1042
- // else a declared-boolean column happens to hold (SQLite does not
1043
- // enforce the type) stays in its own JSON form and reads back as the
1044
- // driver would have returned it, rather than being stringified.
1045
- sql: (ref) => `CASE WHEN ${ref} IN (0, 1) THEN CAST(${ref} AS TEXT) ELSE ${ref} END`,
1046
- decode: (value) => (value === '1' ? true : value === '0' ? false : value),
1047
- };
1048
- }
1049
- // A json/jsonb column is JSON text in storage, which the shim parses on
1050
- // every direct read (see resultColumnDecoders). `json_object` embeds the
1051
- // same text as a JSON string, so the decode is the same parse. No cast: the
1052
- // column reference already yields the text. Gated like the boolean rule,
1053
- // since the direct-read half needs the same driver capability.
1054
- if (decode === 'json' && driverReportsDeclaredTypes()) {
1055
- return { sql: (ref) => ref, decode: parseJsonCell };
1056
- }
1057
- // `json_object` renders a REAL with 15 significant digits on the SQLite
1058
- // that Node 22 and 24 bundle (3.47 to 3.51; 3.53 renders 17), so 0.1 + 0.2
1059
- // came back 0.3 through a join and a NUMERIC past 15 digits was rounded
1060
- // again on top of its REAL storage, while the top-level read and the
1061
- // batched loader return the stored double. `printf('%!.17g')` prints every
1062
- // double with enough digits to rebuild it, on every version; an INTEGER in
1063
- // the same column is carried as its text and decoded by the safe-integer
1064
- // policy above; text and NULL pass through as stored.
1065
- if (/REAL|FLOA|DOUB|NUMERIC|DECIMAL|MONEY/.test(t)) {
1066
- return {
1067
- sql: (ref) => `CASE typeof(${ref}) WHEN 'real' THEN printf('%!.17g', ${ref}) ` +
1068
- `WHEN 'integer' THEN CAST(${ref} AS TEXT) ELSE ${ref} END`,
1069
- decode: decodeRealText,
1070
- };
1071
- }
1072
- // A BLOB cannot go into JSON at all: SQLite raises "JSON cannot hold BLOB
1073
- // values" and the whole query fails with a raw SQL logic error, where the
1074
- // batched loader returns the row fine. Carry hex and rebuild the bytes.
1075
- if (t.includes('BLOB')) {
1076
- return {
1077
- sql: (ref) => `hex(${ref})`,
1078
- decode: (value) => (typeof value === 'string' ? Uint8Array.from(Buffer.from(value, 'hex')) : value),
1079
- };
1080
- }
1081
- return undefined;
1082
- },
1083
- castAggregate(expr, target) {
1084
- return `CAST(${expr} AS ${target === 'int' ? 'INTEGER' : 'REAL'})`;
1085
- },
1086
- // SQLite's grammar only allows OFFSET after LIMIT, so `offset` without
1087
- // `limit` (valid on Postgres, which the default path is written for) is a
1088
- // syntax error here. A negative LIMIT is SQLite's documented "no upper
1089
- // bound", so that shape becomes `LIMIT -1 OFFSET n`. The other shapes emit
1090
- // byte-identically to the default path.
1091
- buildLimitOffset(input) {
1092
- const { limitPlaceholder, offsetPlaceholder } = input;
1093
- if (limitPlaceholder === undefined && offsetPlaceholder === undefined)
1094
- return '';
1095
- if (limitPlaceholder === undefined)
1096
- return ` LIMIT -1 OFFSET ${offsetPlaceholder}`;
1097
- let s = ` LIMIT ${limitPlaceholder}`;
1098
- if (offsetPlaceholder !== undefined)
1099
- s += ` OFFSET ${offsetPlaceholder}`;
1100
- return s;
1101
- },
1102
- // No `= ANY(array)` in SQLite. `json_each` expands a single JSON-array param
1103
- // into a row set, keeping ONE placeholder (so the SQL cache stays valid
1104
- // regardless of list length) and handling the empty-list case correctly.
1105
- // `x IN (SELECT ...)` compares like `x = ?`: the column's affinity and
1106
- // collation apply to each element, as they do to a bound operand. JSON has no
1107
- // bytes, so a binary element travels as `{"b": "<hex>"}` and is decoded back
1108
- // to a BLOB here (see sqliteInListJson).
1109
- buildInClause(expr, paramRef, negated) {
1110
- return (`${expr} ${negated ? 'NOT IN' : 'IN'} ` +
1111
- `(SELECT CASE WHEN type = 'object' THEN unhex(json_extract(value, '$.b')) ELSE value END ` +
1112
- `FROM json_each(${paramRef}))`);
1113
- },
1114
- inClauseParam(values) {
1115
- return sqliteInListJson(Array.isArray(values) ? values : []);
1116
- },
1117
- /**
1118
- * A string written to a numeric or boolean column. SQLite's type affinity
1119
- * keeps text it cannot convert as TEXT in that column, where PostgreSQL
1120
- * refuses it at the server: `'abc'` in an INTEGER column, or `'true'` in a
1121
- * boolean one (stored 1/0), which `{ flag: true }` then never matches. A
1122
- * string that is a number (`'12.5'`, `'9007199254740993'`, `' 7 '`) is
1123
- * accepted and converted by SQLite, as before.
1124
- */
1125
- checkTextWrite(table, column, columnType, value) {
1126
- if (!SQLITE_NUMERIC_COLUMN_TYPE.test(columnType.trim()))
1127
- return undefined;
1128
- if (SQLITE_NUMERIC_LITERAL.test(value))
1129
- return undefined;
1130
- const boolean = /BOOL/i.test(columnType);
1131
- return (`The string written to "${column}" on "${table}", a column of type ${columnType}, is not a number, so SQLite ` +
1132
- `would store it as text in that column; PostgreSQL refuses it. ` +
1133
- (boolean ? 'Write true or false.' : 'Write a number, or a string holding one, such as "12.5".'));
1134
- },
1135
- buildReturningClause(selection = '*') {
1136
- if (selection !== '*' && selection.length === 0)
1137
- return '';
1138
- return ` RETURNING ${selection === '*' ? '*' : selection.join(', ')}`;
1139
- },
1140
- buildInsertStatement(input) {
1141
- return (`INSERT INTO ${input.table} (${input.columns.join(', ')}) ` +
1142
- `VALUES (${input.valuePlaceholders.join(', ')})${this.buildReturningClause(input.returning)}`);
1143
- },
1144
- buildBulkInsertStatement(input) {
1145
- // No UNNEST in SQLite, emit multi-row VALUES with flattened, named
1146
- // placeholders (`:p1`, `:p2`, …) matching the flat param order.
1147
- let n = 0;
1148
- const placeholders = input.rowValues
1149
- .map((row) => `(${row.map(() => this.paramPlaceholder(++n)).join(', ')})`)
1150
- .join(', ');
1151
- const conflict = input.skipDuplicates ? ' ON CONFLICT DO NOTHING' : '';
1152
- return {
1153
- sql: `INSERT INTO ${input.table} (${input.columns.join(', ')}) VALUES ${placeholders}` +
1154
- `${conflict}${this.buildReturningClause(input.returning)}`,
1155
- params: input.rowValues.flat(),
1156
- };
1157
- },
1158
- buildBulkUpsertStatement(input) {
1159
- // VALUES, not `INSERT ... SELECT`: after a SELECT, SQLite cannot tell a
1160
- // trailing `ON CONFLICT` from the SELECT's own clauses. The rest is the
1161
- // PostgreSQL grammar (3.24 upsert, 3.35 RETURNING), `excluded` included.
1162
- let n = 0;
1163
- const tuples = input.rowValues.map((row) => `(${row.map(() => this.paramPlaceholder(++n)).join(', ')})`).join(', ');
1164
- const params = input.rowValues.flat();
1165
- return {
1166
- sql: `INSERT INTO ${input.table} (${input.columns.join(', ')}) VALUES ${tuples} ` +
1167
- `ON CONFLICT (${input.conflictColumns.join(', ')}) ` +
1168
- (0, dialect_js_1.onConflictAction)(input, params, { target: input.table, incoming: 'excluded' }) +
1169
- this.buildReturningClause(input.returning),
1170
- params,
1171
- };
1172
- },
1173
- buildDefaultValuesInsertStatement(input) {
1174
- // SQLite's `DEFAULT VALUES` inserts exactly one row and the engine accepts
1175
- // neither `VALUES (DEFAULT, …)` nor MySQL's empty `VALUES ()` tuple, so
1176
- // there is no multi-row all-defaults statement to emit.
1177
- if (input.rowCount !== 1) {
1178
- throw new errors_js_1.UnsupportedFeatureError(`createMany with ${input.rowCount} empty data rows`, 'sqlite', 'SQLite INSERT … DEFAULT VALUES inserts a single row and has no multi-row form; ' +
1179
- 'issue one create({ data: {} }) per row.');
1180
- }
1181
- const conflict = input.skipDuplicates ? ' ON CONFLICT DO NOTHING' : '';
1182
- return `INSERT INTO ${input.table} DEFAULT VALUES${conflict}${this.buildReturningClause(input.returning)}`;
1183
- },
1184
- buildUpsertStatement(input) {
1185
- return (`INSERT INTO ${input.table} (${input.insertColumns.join(', ')}) VALUES (${input.valuePlaceholders.join(', ')})` +
1186
- ` ON CONFLICT (${input.conflictColumns.join(', ')}) DO UPDATE SET ${input.updateSetClauses.join(', ')}` +
1187
- // SQLite's upsert takes the same trailing conflict-UPDATE predicate as
1188
- // Postgres, so `supportsUpsertUpdateWhere` (inherited true) is honest and
1189
- // global filters restrict the UPDATE branch here too.
1190
- (input.updateWhere ? ` WHERE ${input.updateWhere}` : '') +
1191
- this.buildReturningClause(input.returning));
1192
- },
1193
- // A SQLite transaction is always SERIALIZABLE, which satisfies every level
1194
- // `$transaction({ isolationLevel })` can ask for, and the inherited
1195
- // `BEGIN ISOLATION LEVEL ...` is a syntax error here.
1196
- beginStatement() {
1197
- return 'BEGIN';
1198
- },
1199
- buildInsensitiveLike(column, paramRef) {
1200
- // COLLATE NOCASE is ASCII-only (no Unicode case folding), documented limit.
1201
- return `${column} LIKE ${paramRef} COLLATE NOCASE`;
1202
- },
1203
- // UNREACHABLE while `supportsJsonContains` is false, and kept deliberately:
1204
- // it is the emulation this dialect would use if the encoding mismatch were
1205
- // repaired, and deleting it would delete the record of what was tried. The
1206
- // param is bound as JSON text (`'"gold"'`) while `json_each.value` yields the
1207
- // decoded SQL value (`gold`), so this predicate never holds for ANY operand.
1208
- // See `supportsJsonContains` in dialect.ts for the measurements and the shape
1209
- // a faithful version needs (`json_each.type` alongside the value).
1210
- buildJsonContains(column, paramRef) {
1211
- return `EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${paramRef})`;
1212
- },
1213
- buildJsonPathExtract(column, pathParamRef) {
1214
- return `json_extract(${column}, ${pathParamRef})`;
1215
- },
1216
- // ---- Type mapping -------------------------------------------------------
1217
- typeToTypeScript(dialectType, nullable) {
1218
- return sqliteTypeToTs(dialectType, nullable);
1219
- },
1220
- // SQLite has no true array columns; bulk insert uses multi-row VALUES, so no
1221
- // array cast is ever needed. Returning undefined disables the UNNEST path.
1222
- arrayType: undefined,
1223
- // ---- DDL ----------------------------------------------------------------
1224
- buildColumnType(input) {
1225
- return sqliteColumnAffinity(input.type);
1226
- },
1227
- /** SQLite has no enum type: a TEXT column, and a CHECK that admits only the labels (compared exactly, BINARY collation). */
1228
- buildEnumColumn(column, labels) {
1229
- const literals = labels.map((label) => `'${label.replace(/'/g, "''")}'`);
1230
- return { type: 'TEXT', check: `${column} IN (${literals.join(', ')})` };
1231
- },
1232
- buildColumnDefinition(input) {
1233
- const isSerial = /serial/i.test(input.type);
1234
- const parts = [input.name];
1235
- if (input.primaryKey && isSerial) {
1236
- // The canonical SQLite auto-increment PK (implicitly NOT NULL).
1237
- parts.push('INTEGER PRIMARY KEY AUTOINCREMENT');
1238
- }
1239
- else {
1240
- parts.push(this.buildColumnType(input));
1241
- if (input.primaryKey)
1242
- parts.push('PRIMARY KEY');
1243
- if (input.unique && !input.primaryKey)
1244
- parts.push('UNIQUE');
1245
- if (input.notNull)
1246
- parts.push('NOT NULL');
1247
- }
1248
- if (input.defaultValue != null)
1249
- parts.push(`DEFAULT ${input.defaultValue}`);
1250
- if (input.references)
1251
- parts.push(`REFERENCES ${input.references.table}(${input.references.column})`);
1252
- return parts.join(' ');
1253
- },
1254
- buildCreateIndexStatement(input) {
1255
- return `CREATE INDEX IF NOT EXISTS ${input.name} ON ${input.table}(${input.columns.join(', ')});`;
1256
- },
1257
- buildCreateTableStatement(input) {
1258
- const body = input.definitions.map((d) => ` ${d}`).join(',\n');
1259
- return `CREATE TABLE ${input.table} (\n${body}\n);`;
1260
- },
1261
- // ---- Migration tracking -------------------------------------------------
1262
- // buildMigrationSelectApplied / UpdateChecksum / InsertApplied / DeleteApplied
1263
- // are inherited from postgresDialect: they call `this.paramPlaceholder(n)`
1264
- // (→ `?`) and `ON CONFLICT (name) DO NOTHING`, both valid SQLite. Only the
1265
- // tracking-table DDL (SERIAL / TIMESTAMPTZ) needs a SQLite-specific override.
1266
- buildMigrationTrackingTable(table) {
1267
- return `
1268
- CREATE TABLE IF NOT EXISTS ${table} (
1269
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1270
- name TEXT NOT NULL UNIQUE,
1271
- checksum TEXT NOT NULL,
1272
- applied_at TEXT NOT NULL DEFAULT (datetime('now'))
1273
- );
1274
- `;
1275
- },
1276
- // ---- Streaming ----------------------------------------------------------
1277
- /**
1278
- * SQLite is in-process: the whole result set already lives in memory, so the
1279
- * "stream" simply fetches once via the pooled connection and yields the rows
1280
- * in `batchSize` chunks. No server-side cursor (and none needed).
1281
- */
1282
- async *openStream(connection, sql, params, batchSize) {
1283
- const result = await connection.query(sql, params);
1284
- for (let i = 0; i < result.rows.length; i += batchSize) {
1285
- yield result.rows.slice(i, i + batchSize);
1286
- }
1287
- },
1288
- // ---- Introspection ------------------------------------------------------
1289
1432
  introspector: {
1290
1433
  async introspect(options) {
1291
1434
  return introspectSqlite(options);
@@ -1310,32 +1453,63 @@ function pragma(db, sql) {
1310
1453
  */
1311
1454
  function introspectSqliteDatabase(db, options = {}) {
1312
1455
  // ----- Tables (skip SQLite internal + the migration tracking table) -----
1313
- const candidateTables = pragma(db, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").map((r) => r.name);
1314
- // include / exclude + default bookkeeping-table exclusions (F12), shared with
1315
- // every other introspector via applyTableFilters.
1316
- const tableNames = (0, introspect_js_1.applyTableFilters)(candidateTables, options);
1456
+ const catalogTables = pragma(db, options.includeViews === true
1457
+ ? "SELECT name, sql FROM main.sqlite_master WHERE type IN ('table', 'view') AND substr(name, 1, 7) <> 'sqlite_' ORDER BY name"
1458
+ : "SELECT name, sql FROM main.sqlite_master WHERE type = 'table' AND substr(name, 1, 7) <> 'sqlite_' ORDER BY name");
1459
+ const candidateTables = catalogTables.map((t) => t.name);
1460
+ const tableDefinitions = new Map(catalogTables.map((t) => [t.name, t.sql ?? '']));
1461
+ let tableFlags;
1462
+ // Keep option access before the existing table-list read. Native shadow
1463
+ // classification adds per-call defaults; explicit include still restores them.
1464
+ const tableNames = (0, introspect_js_1.applyTableFilters)(candidateTables, options, (defaults) => {
1465
+ tableFlags = new Map(pragma(db, 'PRAGMA main.table_list').map((t) => {
1466
+ if (t.type === 'shadow')
1467
+ defaults.add(t.name);
1468
+ return [t.name, t];
1469
+ }));
1470
+ });
1317
1471
  const tableSet = new Set(tableNames);
1318
1472
  const columnsByTable = new Map();
1319
1473
  const pkByTable = new Map();
1320
1474
  const uniqueByTable = new Map();
1475
+ const relationUniqueByTable = new Map();
1321
1476
  const indexesByTable = new Map();
1322
1477
  const foreignKeys = [];
1323
1478
  for (const tableName of tableNames) {
1324
1479
  const q = (name) => `"${name.replace(/"/g, '""')}"`;
1325
1480
  // ----- Columns + primary key -----
1326
- const cols = pragma(db, `PRAGMA table_info(${q(tableName)})`);
1481
+ // table_xinfo also exposes computed columns (hidden = 2/3). Virtual-table
1482
+ // hidden inputs (1) are not ordinary projected/writable columns.
1483
+ const cols = pragma(db, `PRAGMA main.table_xinfo(${q(tableName)})`).filter((c) => c.hidden !== 1);
1484
+ const idxList = pragma(db, `PRAGMA main.index_list(${q(tableName)})`);
1485
+ const flags = tableFlags.get(tableName);
1486
+ const primaryColumns = cols.filter((c) => c.pk > 0);
1487
+ // Only a sole INTEGER PK on a rowid table aliases the rowid. A separate
1488
+ // PK index distinguishes the historical inline PRIMARY KEY DESC exception
1489
+ // without parsing DDL; INT/BIGINT and WITHOUT ROWID keys never qualify.
1490
+ const rowidKey = flags?.wr === 0 && primaryColumns.length === 1 && !idxList.some((idx) => idx.origin === 'pk')
1491
+ ? primaryColumns.find((c) => c.type.toUpperCase() === 'INTEGER')?.name
1492
+ : undefined;
1327
1493
  const colMeta = [];
1328
1494
  const pkCols = [];
1329
1495
  for (const c of cols) {
1330
1496
  const declared = c.type || '';
1497
+ const generated = c.hidden === 2 || c.hidden === 3;
1498
+ const nullable = c.notnull === 0 && c.name !== rowidKey && !(c.pk > 0 && (flags?.wr === 1 || flags?.strict === 1));
1499
+ const tsType = (0, sqlite_dialect_js_1.sqliteTypeToTs)(declared, nullable);
1331
1500
  colMeta.push({
1332
1501
  name: c.name,
1333
1502
  field: (0, schema_js_1.snakeToCamel)(c.name),
1334
1503
  dialectType: declared,
1335
1504
  pgType: declared,
1336
- tsType: sqliteTypeToTs(declared, c.notnull === 0 && c.pk === 0),
1337
- nullable: c.notnull === 0 && c.pk === 0,
1338
- hasDefault: c.dflt_value !== null || c.pk === 1,
1505
+ tsType,
1506
+ ...(tsType === `Uint8Array${nullable ? ' | null' : ''}` ? { inferredBinaryType: 'Uint8Array' } : {}),
1507
+ nullable,
1508
+ hasDefault: c.dflt_value !== null || c.name === rowidKey || generated,
1509
+ ...(c.name === rowidKey ? { isGenerated: true } : {}),
1510
+ // This existing flag means computed/non-writable to the generator and
1511
+ // write guards, which is true for both SQLite VIRTUAL and STORED values.
1512
+ ...(generated ? { isGeneratedStored: true } : {}),
1339
1513
  isArray: false,
1340
1514
  arrayType: undefined,
1341
1515
  pgArrayType: 'text[]',
@@ -1346,7 +1520,7 @@ function introspectSqliteDatabase(db, options = {}) {
1346
1520
  columnsByTable.set(tableName, colMeta);
1347
1521
  pkByTable.set(tableName, pkCols.sort((a, b) => a.order - b.order).map((p) => p.name));
1348
1522
  // ----- Foreign keys -----
1349
- const fks = pragma(db, `PRAGMA foreign_key_list(${q(tableName)})`);
1523
+ const fks = pragma(db, `PRAGMA main.foreign_key_list(${q(tableName)})`);
1350
1524
  // Group by FK id (composite FKs share an id), ordered by seq.
1351
1525
  const fkById = new Map();
1352
1526
  for (const fk of fks.sort((a, b) => a.id - b.id || a.seq - b.seq)) {
@@ -1369,7 +1543,7 @@ function introspectSqliteDatabase(db, options = {}) {
1369
1543
  for (const entry of fkById.values()) {
1370
1544
  if (entry.targetColumns.length === 0) {
1371
1545
  // Implicit reference → the target table's primary key.
1372
- const targetPk = pragma(db, `PRAGMA table_info(${q(entry.targetTable)})`)
1546
+ const targetPk = pragma(db, `PRAGMA main.table_xinfo(${q(entry.targetTable)})`)
1373
1547
  .filter((c) => c.pk > 0)
1374
1548
  .sort((a, b) => a.pk - b.pk)
1375
1549
  .map((c) => c.name);
@@ -1379,24 +1553,44 @@ function introspectSqliteDatabase(db, options = {}) {
1379
1553
  foreignKeys.push(entry);
1380
1554
  }
1381
1555
  // ----- Indexes + unique constraints -----
1382
- const idxList = pragma(db, `PRAGMA index_list(${q(tableName)})`);
1383
1556
  const idxMeta = [];
1384
1557
  const uniques = [];
1558
+ // An index's collation can differ from the relation comparison's column
1559
+ // collation: UNIQUE BINARY can admit both 'a' and 'A' under NOCASE joins.
1560
+ // Column collations are absent from table_xinfo. Conservatively keep the
1561
+ // to-many shape if the table/index DDL mentions COLLATE (even in a comment
1562
+ // or identifier), rather than promise a to-one on incomplete facts.
1563
+ const tableHasCollation = /\bCOLLATE\b/i.test(tableDefinitions.get(tableName) ?? '');
1564
+ const relationUniques = tableHasCollation ? [] : [pkByTable.get(tableName) ?? []];
1385
1565
  for (const idx of idxList) {
1386
- const idxCols = pragma(db, `PRAGMA index_info(${q(idx.name)})`)
1387
- .sort((a, b) => a.seqno - b.seqno)
1388
- .map((c) => c.name);
1566
+ const keys = pragma(db, `PRAGMA main.index_info(${q(idx.name)})`).sort((a, b) => a.seqno - b.seqno);
1567
+ const plain = keys.length > 0 && keys.every((c) => c.cid >= 0 && c.name !== null);
1568
+ // Expression keys have no column name. Never let their null catalog
1569
+ // placeholders reach metadata/codegen or treat the remaining names as a
1570
+ // unique set. Keep the real DDL for partial/expression index consumers.
1571
+ // `columns` must describe a complete plain key: shared consumers also
1572
+ // derive compound selectors from it without parsing the definition.
1573
+ const idxCols = plain ? keys.map((c) => c.name) : [];
1574
+ const catalog = db
1575
+ .prepare("SELECT sql FROM main.sqlite_master WHERE type = 'index' AND name = ?")
1576
+ .get(idx.name);
1389
1577
  idxMeta.push({
1390
1578
  name: idx.name,
1391
1579
  columns: idxCols,
1392
1580
  unique: idx.unique === 1,
1393
- definition: `${idx.unique === 1 ? 'UNIQUE ' : ''}INDEX ${idx.name} ON ${tableName}(${idxCols.join(', ')})`,
1581
+ definition: catalog?.sql ??
1582
+ `${idx.unique === 1 ? 'UNIQUE ' : ''}INDEX ${q(idx.name)} ON ${q(tableName)}(${idxCols.map(q).join(', ')})`,
1583
+ ...(idx.partial === 1 ? { partial: true } : {}),
1394
1584
  });
1395
- if (idx.unique === 1 && idxCols.length > 0)
1585
+ if (idx.unique === 1 && idx.partial === 0 && plain) {
1396
1586
  uniques.push(idxCols);
1587
+ if (!tableHasCollation && !/\bCOLLATE\b/i.test(catalog?.sql ?? ''))
1588
+ relationUniques.push(idxCols);
1589
+ }
1397
1590
  }
1398
1591
  indexesByTable.set(tableName, idxMeta);
1399
1592
  uniqueByTable.set(tableName, uniques);
1593
+ relationUniqueByTable.set(tableName, relationUniques);
1400
1594
  }
1401
1595
  // ----- Build relations from foreign keys (belongsTo + hasMany + m2m) -----
1402
1596
  // Delegated to the SHARED introspection pipeline (introspect.ts) so SQLite
@@ -1407,7 +1601,12 @@ function introspectSqliteDatabase(db, options = {}) {
1407
1601
  // One field per column, as the PostgreSQL introspector requires.
1408
1602
  for (const [tableName, cols] of columnsByTable)
1409
1603
  (0, introspect_js_1.assertDistinctColumnFields)(tableName, cols);
1410
- const relationsByTable = (0, introspect_js_1.deriveEngineRelations)(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger);
1604
+ // A to-one is decided per foreign key BEFORE naming, so it is named as
1605
+ // PostgreSQL names it (`users.profile`); the shared test is the libSQL and D1
1606
+ // one, so every SQLite introspector gives the same answer.
1607
+ const relationsByTable = (0, introspect_js_1.deriveEngineRelations)(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
1608
+ ? undefined
1609
+ : (0, catalog_metadata_js_1.sqliteToOneForeignKey)(columnsByTable, relationUniqueByTable, tableDefinitions, tableFlags));
1411
1610
  // ----- Assemble TableMetadata -----
1412
1611
  const tables = (0, introspect_js_1.nullRecord)();
1413
1612
  for (const tableName of tableNames) {
@@ -1440,6 +1639,7 @@ function introspectSqliteDatabase(db, options = {}) {
1440
1639
  uniqueColumns: uniqueByTable.get(tableName) ?? [],
1441
1640
  relations: relationsByTable.get(tableName) ?? (0, introspect_js_1.nullRecord)(),
1442
1641
  indexes: indexesByTable.get(tableName) ?? [],
1642
+ ...(tableFlags.get(tableName)?.type === 'view' ? { isView: true } : {}),
1443
1643
  };
1444
1644
  }
1445
1645
  return { tables, enums: {} };
@@ -1463,7 +1663,13 @@ async function introspectSqlite(options) {
1463
1663
  throw new errors_js_1.ConnectionError(`Failed to open SQLite database "${options.connectionString}": ${err.message}`);
1464
1664
  }
1465
1665
  try {
1466
- return introspectSqliteDatabase(db, { include: options.include, exclude: options.exclude, logger: options.logger });
1666
+ return introspectSqliteDatabase(db, {
1667
+ include: options.include,
1668
+ exclude: options.exclude,
1669
+ logger: options.logger,
1670
+ legacyToManyUniques: options.legacyToManyUniques,
1671
+ includeViews: options.includeViews,
1672
+ });
1467
1673
  }
1468
1674
  finally {
1469
1675
  db.close();
@@ -1497,6 +1703,7 @@ function openSqliteDatabase(target, options) {
1497
1703
  // Some filesystems (network mounts) reject WAL, fall back silently.
1498
1704
  }
1499
1705
  }
1706
+ unexposedNativeDatabases.add(db);
1500
1707
  return db;
1501
1708
  }
1502
1709
  /**
@@ -1521,9 +1728,15 @@ function openSqliteDatabase(target, options) {
1521
1728
  function turbineSqlite(target, schema, options = {}) {
1522
1729
  const owns = typeof target === 'string';
1523
1730
  const db = owns ? openSqliteDatabase(target, options) : target;
1731
+ return createSqliteBindingClient(db, schema, options, owns, exports.sqliteDialect);
1732
+ }
1733
+ /** @internal Shared native SQLite lifecycle; bindings retain their own open and decode policy. */
1734
+ function createSqliteBindingClient(db, schema, options, owns, dialect, arrayStatements) {
1524
1735
  let pool;
1525
1736
  let client;
1526
1737
  try {
1738
+ if (arrayStatements)
1739
+ bindingArrayStatements.set(db, arrayStatements);
1527
1740
  pool = new SqlitePool(db, { busyTimeoutMs: options.busyTimeoutMs, schema });
1528
1741
  // Everything that is not a SQLite pragma is client config and rides through
1529
1742
  // untouched, so a new TurbineConfig option works here the day it lands. The
@@ -1532,7 +1745,7 @@ function turbineSqlite(target, schema, options = {}) {
1532
1745
  client = new client_js_1.TurbineClient({
1533
1746
  ...clientConfig,
1534
1747
  pool,
1535
- dialect: exports.sqliteDialect,
1748
+ dialect,
1536
1749
  preparedStatements: false,
1537
1750
  }, schema);
1538
1751
  }