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