@yaks/sqlite 0.0.0-stage → 0.2.36

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 (289) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1596 -2
  3. package/_dist/archetype.d.ts +75 -0
  4. package/_dist/archetype.d.ts.map +1 -0
  5. package/_dist/branches.d.ts +23 -0
  6. package/_dist/branches.d.ts.map +1 -0
  7. package/_dist/budget.d.ts +52 -0
  8. package/_dist/budget.d.ts.map +1 -0
  9. package/_dist/bundle.d.ts +2 -0
  10. package/_dist/bundle.d.ts.map +1 -0
  11. package/_dist/cache.d.ts +24 -0
  12. package/_dist/cache.d.ts.map +1 -0
  13. package/_dist/catalog.d.ts +9 -0
  14. package/_dist/catalog.d.ts.map +1 -0
  15. package/_dist/check.d.ts +4 -0
  16. package/_dist/check.d.ts.map +1 -0
  17. package/_dist/db.d.ts +36 -0
  18. package/_dist/db.d.ts.map +1 -0
  19. package/_dist/ddl.d.ts +143 -0
  20. package/_dist/ddl.d.ts.map +1 -0
  21. package/_dist/doom.d.ts +22 -0
  22. package/_dist/doom.d.ts.map +1 -0
  23. package/_dist/follow.d.ts +74 -0
  24. package/_dist/follow.d.ts.map +1 -0
  25. package/_dist/history-shapes.d.ts +3 -0
  26. package/_dist/history-shapes.d.ts.map +1 -0
  27. package/_dist/history.d.ts +18 -0
  28. package/_dist/history.d.ts.map +1 -0
  29. package/_dist/inspect.d.ts +43 -0
  30. package/_dist/inspect.d.ts.map +1 -0
  31. package/_dist/jsonb.d.ts +17 -0
  32. package/_dist/jsonb.d.ts.map +1 -0
  33. package/_dist/layout.d.ts +7 -0
  34. package/_dist/layout.d.ts.map +1 -0
  35. package/_dist/ledger.d.ts +41 -0
  36. package/_dist/ledger.d.ts.map +1 -0
  37. package/_dist/meta.d.ts +89 -0
  38. package/_dist/meta.d.ts.map +1 -0
  39. package/_dist/migration.d.ts +41 -0
  40. package/_dist/migration.d.ts.map +1 -0
  41. package/_dist/mod.d.ts +201 -0
  42. package/_dist/mod.d.ts.map +1 -0
  43. package/_dist/mode.d.ts +14 -0
  44. package/_dist/mode.d.ts.map +1 -0
  45. package/_dist/overlay.d.ts +30 -0
  46. package/_dist/overlay.d.ts.map +1 -0
  47. package/_dist/owe.d.ts +180 -0
  48. package/_dist/owe.d.ts.map +1 -0
  49. package/_dist/physical.d.ts +89 -0
  50. package/_dist/physical.d.ts.map +1 -0
  51. package/_dist/point.d.ts +10 -0
  52. package/_dist/point.d.ts.map +1 -0
  53. package/_dist/raise.d.ts +22 -0
  54. package/_dist/raise.d.ts.map +1 -0
  55. package/_dist/read-db.d.ts +9 -0
  56. package/_dist/read-db.d.ts.map +1 -0
  57. package/_dist/read-store.d.ts +10 -0
  58. package/_dist/read-store.d.ts.map +1 -0
  59. package/_dist/read.d.ts +59 -0
  60. package/_dist/read.d.ts.map +1 -0
  61. package/_dist/reader.d.ts +11 -0
  62. package/_dist/reader.d.ts.map +1 -0
  63. package/_dist/rules.d.ts +19 -0
  64. package/_dist/rules.d.ts.map +1 -0
  65. package/_dist/service.d.ts +12 -0
  66. package/_dist/service.d.ts.map +1 -0
  67. package/_dist/shape.d.ts +12 -0
  68. package/_dist/shape.d.ts.map +1 -0
  69. package/_dist/statements.d.ts +4 -0
  70. package/_dist/statements.d.ts.map +1 -0
  71. package/_dist/survey.d.ts +31 -0
  72. package/_dist/survey.d.ts.map +1 -0
  73. package/_dist/tools.d.ts +15 -0
  74. package/_dist/tools.d.ts.map +1 -0
  75. package/_dist/trash.d.ts +18 -0
  76. package/_dist/trash.d.ts.map +1 -0
  77. package/_dist/unit.d.ts +11 -0
  78. package/_dist/unit.d.ts.map +1 -0
  79. package/_dist/vocab.d.ts +6 -0
  80. package/_dist/vocab.d.ts.map +1 -0
  81. package/_dist/write.d.ts +169 -0
  82. package/_dist/write.d.ts.map +1 -0
  83. package/answer.js +110 -0
  84. package/answer.js.map +1 -0
  85. package/answer.ts +122 -0
  86. package/archetype.js +730 -0
  87. package/archetype.js.map +1 -0
  88. package/archetype.ts +790 -0
  89. package/binary_cases.ts +240 -0
  90. package/branches.js +195 -0
  91. package/branches.js.map +1 -0
  92. package/branches.ts +257 -0
  93. package/budget.js +89 -0
  94. package/budget.js.map +1 -0
  95. package/budget.ts +117 -0
  96. package/builtin.js +34 -0
  97. package/builtin.js.map +1 -0
  98. package/builtin.ts +31 -0
  99. package/bundle.js +21 -0
  100. package/bundle.js.map +1 -0
  101. package/bundle.ts +22 -0
  102. package/buried.js +95 -0
  103. package/buried.js.map +1 -0
  104. package/buried.ts +124 -0
  105. package/cache.js +153 -0
  106. package/cache.js.map +1 -0
  107. package/cache.ts +154 -0
  108. package/cache_worker.ts +16 -0
  109. package/catalog.js +173 -0
  110. package/catalog.js.map +1 -0
  111. package/catalog.ts +224 -0
  112. package/check.js +80 -0
  113. package/check.js.map +1 -0
  114. package/check.ts +92 -0
  115. package/checkpoint.js +98 -0
  116. package/checkpoint.js.map +1 -0
  117. package/checkpoint.ts +129 -0
  118. package/checkpoint_worker.ts +37 -0
  119. package/db.js +170 -0
  120. package/db.js.map +1 -0
  121. package/db.ts +173 -0
  122. package/ddl.js +1441 -0
  123. package/ddl.js.map +1 -0
  124. package/ddl.ts +1508 -0
  125. package/deno.json +1 -0
  126. package/doom.js +59 -0
  127. package/doom.js.map +1 -0
  128. package/doom.ts +75 -0
  129. package/driver.js +69 -0
  130. package/driver.js.map +1 -0
  131. package/driver.ts +101 -0
  132. package/error.js +30 -0
  133. package/error.js.map +1 -0
  134. package/error.ts +46 -0
  135. package/ffi/LICENSE +202 -0
  136. package/ffi/blob.js +99 -0
  137. package/ffi/blob.js.map +1 -0
  138. package/ffi/blob.ts +156 -0
  139. package/ffi/constants.js +65 -0
  140. package/ffi/constants.js.map +1 -0
  141. package/ffi/constants.ts +67 -0
  142. package/ffi/database.js +613 -0
  143. package/ffi/database.js.map +1 -0
  144. package/ffi/database.ts +931 -0
  145. package/ffi/ffi.js +535 -0
  146. package/ffi/ffi.js.map +1 -0
  147. package/ffi/ffi.ts +604 -0
  148. package/ffi/mod.js +15 -0
  149. package/ffi/mod.js.map +1 -0
  150. package/ffi/mod.ts +28 -0
  151. package/ffi/statement.js +555 -0
  152. package/ffi/statement.js.map +1 -0
  153. package/ffi/statement.ts +788 -0
  154. package/ffi/util.js +32 -0
  155. package/ffi/util.js.map +1 -0
  156. package/ffi/util.ts +48 -0
  157. package/follow.js +342 -0
  158. package/follow.js.map +1 -0
  159. package/follow.ts +401 -0
  160. package/history-branch.js +166 -0
  161. package/history-branch.js.map +1 -0
  162. package/history-branch.ts +140 -0
  163. package/history-shapes.js +254 -0
  164. package/history-shapes.js.map +1 -0
  165. package/history-shapes.ts +268 -0
  166. package/history.js +620 -0
  167. package/history.js.map +1 -0
  168. package/history.ts +674 -0
  169. package/inspect.js +120 -0
  170. package/inspect.js.map +1 -0
  171. package/inspect.ts +164 -0
  172. package/jsonb.js +73 -0
  173. package/jsonb.js.map +1 -0
  174. package/jsonb.ts +108 -0
  175. package/layout.js +22 -0
  176. package/layout.js.map +1 -0
  177. package/layout.ts +26 -0
  178. package/ledger.js +210 -0
  179. package/ledger.js.map +1 -0
  180. package/ledger.ts +210 -0
  181. package/legacy.js +4 -0
  182. package/legacy.js.map +1 -0
  183. package/legacy.ts +3 -0
  184. package/maintenance.js +148 -0
  185. package/maintenance.js.map +1 -0
  186. package/maintenance.ts +154 -0
  187. package/measure.js +133 -0
  188. package/measure.js.map +1 -0
  189. package/measure.ts +167 -0
  190. package/measure_worker.ts +18 -0
  191. package/memo.js +1250 -0
  192. package/memo.js.map +1 -0
  193. package/memo.ts +1480 -0
  194. package/meta.js +265 -0
  195. package/meta.js.map +1 -0
  196. package/meta.ts +321 -0
  197. package/migration.js +272 -0
  198. package/migration.js.map +1 -0
  199. package/migration.ts +286 -0
  200. package/mod.js +1103 -0
  201. package/mod.js.map +1 -0
  202. package/mod.ts +1762 -0
  203. package/mode.js +192 -0
  204. package/mode.js.map +1 -0
  205. package/mode.ts +207 -0
  206. package/native.js +544 -0
  207. package/native.js.map +1 -0
  208. package/native.ts +544 -0
  209. package/overlay.js +408 -0
  210. package/overlay.js.map +1 -0
  211. package/overlay.ts +485 -0
  212. package/owe.js +719 -0
  213. package/owe.js.map +1 -0
  214. package/owe.ts +873 -0
  215. package/package.json +99 -4
  216. package/physical.js +350 -0
  217. package/physical.js.map +1 -0
  218. package/physical.ts +434 -0
  219. package/plan.js +78 -0
  220. package/plan.js.map +1 -0
  221. package/plan.ts +104 -0
  222. package/point.js +81 -0
  223. package/point.js.map +1 -0
  224. package/point.ts +52 -0
  225. package/population.js +639 -0
  226. package/population.js.map +1 -0
  227. package/population.ts +630 -0
  228. package/purge.js +117 -0
  229. package/purge.js.map +1 -0
  230. package/purge.ts +127 -0
  231. package/raise.js +270 -0
  232. package/raise.js.map +1 -0
  233. package/raise.ts +316 -0
  234. package/read-db.js +381 -0
  235. package/read-db.js.map +1 -0
  236. package/read-db.ts +282 -0
  237. package/read-store.js +74 -0
  238. package/read-store.js.map +1 -0
  239. package/read-store.ts +86 -0
  240. package/read.js +1100 -0
  241. package/read.js.map +1 -0
  242. package/read.ts +1441 -0
  243. package/reader.js +141 -0
  244. package/reader.js.map +1 -0
  245. package/reader.ts +159 -0
  246. package/rules.js +88 -0
  247. package/rules.js.map +1 -0
  248. package/rules.ts +113 -0
  249. package/service.js +27 -0
  250. package/service.js.map +1 -0
  251. package/service.ts +41 -0
  252. package/shape.js +76 -0
  253. package/shape.js.map +1 -0
  254. package/shape.ts +108 -0
  255. package/sparse_presence_fixture.ts +45 -0
  256. package/sqlitepath.js +24 -0
  257. package/sqlitepath.js.map +1 -0
  258. package/sqlitepath.ts +29 -0
  259. package/statements.js +78 -0
  260. package/statements.js.map +1 -0
  261. package/statements.ts +96 -0
  262. package/survey.js +135 -0
  263. package/survey.js.map +1 -0
  264. package/survey.ts +196 -0
  265. package/tools.js +17 -0
  266. package/tools.js.map +1 -0
  267. package/tools.ts +50 -0
  268. package/trash.js +144 -0
  269. package/trash.js.map +1 -0
  270. package/trash.ts +187 -0
  271. package/unit.js +215 -0
  272. package/unit.js.map +1 -0
  273. package/unit.ts +211 -0
  274. package/versions.js +115 -0
  275. package/versions.js.map +1 -0
  276. package/versions.ts +110 -0
  277. package/vocab.js +19 -0
  278. package/vocab.js.map +1 -0
  279. package/vocab.json +27 -0
  280. package/vocab.ts +19 -0
  281. package/watch.js +33 -0
  282. package/watch.js.map +1 -0
  283. package/watch.ts +42 -0
  284. package/write.js +1164 -0
  285. package/write.js.map +1 -0
  286. package/write.ts +1356 -0
  287. package/written.js +200 -0
  288. package/written.js.map +1 -0
  289. package/written.ts +202 -0
package/native.ts ADDED
@@ -0,0 +1,544 @@
1
+ // The {@link Driver} over one native @db/sqlite handle. Internal to this
2
+ // package: ./db.ts `open()` is the door, and the handle never leaves it. The
3
+ // one other caller is ./testing.ts, whose stand-ins imitate engines that take
4
+ // text.
5
+
6
+ import { sqlitePath } from './sqlitepath.js'
7
+ import { Database, Statement } from './legacy.js'
8
+ import { driver as connection } from './driver.js'
9
+ import { meter } from './budget.js'
10
+ import { EPOCH, epochAt, meta } from './meta.js'
11
+ import { scope } from '@yaks/trace'
12
+ import {
13
+ call,
14
+ col,
15
+ type Driver,
16
+ eq,
17
+ lit,
18
+ type Param,
19
+ render,
20
+ type Row,
21
+ select,
22
+ type Stmt,
23
+ table,
24
+ val,
25
+ } from '@yaks/sql'
26
+
27
+ // Database images belong to the testing facet. The native handle and SQLite's
28
+ // allocator stay here; each restored image gets its own resizeable buffer,
29
+ // which SQLite releases when the database closes.
30
+ let images: ReturnType<typeof bindImages> | undefined
31
+ let bindImages = () =>
32
+ Deno.dlopen(sqlitePath, {
33
+ sqlite3_serialize: {
34
+ parameters: ['pointer', 'buffer', 'buffer', 'u32'],
35
+ result: 'pointer',
36
+ },
37
+ sqlite3_deserialize: {
38
+ parameters: ['pointer', 'buffer', 'pointer', 'i64', 'i64', 'u32'],
39
+ result: 'i32',
40
+ },
41
+ sqlite3_malloc64: { parameters: ['u64'], result: 'pointer' },
42
+ sqlite3_free: { parameters: ['pointer'], result: 'void' },
43
+ })
44
+ let mainImage = new TextEncoder().encode('main\0')
45
+
46
+ export let serialize = (db: Database): Uint8Array => {
47
+ let api = (images ??= bindImages()).symbols
48
+ let size = new BigInt64Array(1)
49
+ let pointer = api.sqlite3_serialize(db.unsafeHandle, mainImage, size, 0)
50
+ if (!pointer) throw new Error('SQLite cannot serialize the database')
51
+ try {
52
+ let bytes = new Uint8Array(Number(size[0]))
53
+ new Deno.UnsafePointerView(pointer).copyInto(bytes)
54
+ return bytes
55
+ } finally {
56
+ api.sqlite3_free(pointer)
57
+ }
58
+ }
59
+
60
+ export let deserialize = (db: Database, bytes: Uint8Array): void => {
61
+ let api = (images ??= bindImages()).symbols
62
+ let size = BigInt(bytes.length)
63
+ let pointer = api.sqlite3_malloc64(size)
64
+ if (!pointer) throw new Error('SQLite cannot allocate a database image')
65
+ new Uint8Array(
66
+ new Deno.UnsafePointerView(pointer).getArrayBuffer(bytes.length),
67
+ )
68
+ .set(bytes)
69
+ // FREEONCLOSE | RESIZEABLE: writes may grow this private copy.
70
+ let code = api.sqlite3_deserialize(
71
+ db.unsafeHandle,
72
+ mainImage,
73
+ pointer,
74
+ size,
75
+ size,
76
+ 3,
77
+ )
78
+ if (code) {
79
+ throw new Error(`SQLite cannot deserialize the database (${code})`)
80
+ }
81
+ }
82
+
83
+ /*
84
+ * Text in, rows out, over one open embedded database: what {@link driver}
85
+ * renders every statement into.
86
+ *
87
+ * It keeps the statements it prepares. The adapter asks the same
88
+ * parameterized gathers and writes thousands of times a session, and
89
+ * preparing each one afresh costs a compile for nothing; the cache is bounded
90
+ * and `Database.close()` finalizes what it holds. A kept statement lives
91
+ * through a schema change, whoever made it: SQLite recompiles the statement at
92
+ * its next step, against the schema as it is then. Its columns are read once
93
+ * that step has made a row, since a `select *` can answer with more, fewer or
94
+ * other columns than it was prepared with.
95
+ *
96
+ * Text a stand-in was handed can hold several statements, as a Durable
97
+ * Object's `exec` takes; they all run, and answer no rows. Parameters bind to
98
+ * one statement, so such a string with parameters is refused rather than cut
99
+ * short. A rendered statement is always one.
100
+ */
101
+ // The dependency's generated decoder closes over only its column reader. The
102
+ // connection, integer width and JSON options arrive with each row, so a column
103
+ // projection can share its compiled function across statements and databases.
104
+ type Decoder = ReturnType<Statement['getRowObject']>
105
+ let decoders = new Map<string, Decoder>()
106
+ // The reader of a statement that answers no columns.
107
+ let nothing: Decoder = () => undefined
108
+ // What a kept statement asks of SQLite that @db/sqlite does not bind.
109
+ let steps: ReturnType<typeof bindSteps> | undefined
110
+ let bindSteps = () =>
111
+ Deno.dlopen(sqlitePath, {
112
+ sqlite3_stmt_status: {
113
+ parameters: ['pointer', 'i32', 'i32'],
114
+ result: 'i32',
115
+ },
116
+ sqlite3_reset: { parameters: ['pointer'], result: 'i32' },
117
+ sqlite3_db_config: {
118
+ parameters: ['pointer', 'i32', 'i32', 'pointer'],
119
+ result: 'i32',
120
+ },
121
+ sqlite3_file_control: {
122
+ parameters: ['pointer', 'pointer', 'i32', 'buffer'],
123
+ result: 'i32',
124
+ },
125
+ sqlite3_wal_hook: {
126
+ parameters: ['pointer', 'function', 'pointer'],
127
+ result: 'pointer',
128
+ },
129
+ })
130
+ let decoder = (names: string[], compile: Statement['getRowObject']) => {
131
+ let key = JSON.stringify(names)
132
+ let kept = decoders.get(key)
133
+ if (kept) return kept
134
+ if (decoders.size >= 256) decoders.delete(decoders.keys().next().value!)
135
+ let made = compile()
136
+ decoders.set(key, made)
137
+ return made
138
+ }
139
+
140
+ export let prepared = (db: Database) => {
141
+ // SQLite integers are 64-bit. The library's default reader truncates them
142
+ // to 32 bits; safe JS integers must round-trip through every driver caller.
143
+ db.int64 = true
144
+ let { sqlite3_stmt_status: recompiled, sqlite3_reset: reset } =
145
+ (steps ??= bindSteps()).symbols
146
+ let commands = new WeakSet<ReturnType<Database['prepare']>>()
147
+ let prepare = (sql: string) => {
148
+ let statement = db.prepare(sql)
149
+ // DDL, transaction boundaries and writes without RETURNING have no row
150
+ // shape. Running them needs no decoder or repeated column-name reads. One
151
+ // may still step more than once, as `pragma incremental_vacuum(n)` gives
152
+ // back a page a step, so each is stepped to its end through a reader that
153
+ // builds nothing.
154
+ let names = statement.columnNames()
155
+ if (!names.length) {
156
+ statement.getRowObject = () => nothing
157
+ commands.add(statement)
158
+ return statement
159
+ }
160
+ let original = statement.getRowObject.bind(statement)
161
+ let standard = statement.getRowObject == Statement.prototype.getRowObject
162
+ let decode: Decoder | undefined
163
+ // The columns the statement answers with now. Only the generated decoder
164
+ // is reusable: it reads each value's live type and receives the
165
+ // integer/JSON options for this call.
166
+ let current = () => {
167
+ // SQLite also recompiles for schema edits from another connection,
168
+ // including temp/attached schemas and rollback. It alone knows when
169
+ // the kept statement's metadata needs reading again.
170
+ let changed = recompiled(statement.unsafeHandle, 5, 1) // REPREPARE
171
+ if (!decode || changed) {
172
+ if (changed) names = statement.columnNames()
173
+ decode = standard ? decoder(names, original) : original()
174
+ }
175
+ return decode
176
+ }
177
+ // @db/sqlite asks for the decoder before its first step, while a
178
+ // statement the schema has moved under still describes its old plan; the
179
+ // step recompiles it. So the decoder it is handed reads the columns at
180
+ // the first row, after that step, and decodes every row of the read
181
+ // with what it found, each counted against the read running
182
+ // (./budget.ts) before the next is made.
183
+ statement.getRowObject = () => {
184
+ let decode: Decoder | undefined
185
+ return (h, int64, json) => {
186
+ let row = (decode ??= current())(h, int64, json)
187
+ meter(row)
188
+ return row
189
+ }
190
+ }
191
+ return statement
192
+ }
193
+ let cache = new Map<string, ReturnType<Database['prepare']>>()
194
+ return (sql: string, params: Param[] = []): Row[] => {
195
+ // @db/sqlite closes and finalizes its native handles without invalidating
196
+ // the JS Statement objects. Calling a cached one after close is a SIGSEGV,
197
+ // not a catchable SQLite error. Refuse at the boundary, before any FFI.
198
+ if (!db.open) throw new Error('the database is closed')
199
+ let statement = cache.get(sql)
200
+ if (statement) {
201
+ cache.delete(sql)
202
+ } else {
203
+ statement = prepare(sql)
204
+ if (sql.slice(statement.sql.length).trim()) {
205
+ statement.finalize()
206
+ if (params.length) {
207
+ throw new Error(`parameters bind to one statement, not several`)
208
+ }
209
+ db.exec(sql)
210
+ return []
211
+ }
212
+ if (cache.size >= 1024) {
213
+ let oldest = cache.keys().next().value!
214
+ cache.get(oldest)!.finalize()
215
+ cache.delete(oldest)
216
+ }
217
+ }
218
+ cache.set(sql, statement)
219
+ try {
220
+ if (commands.has(statement)) {
221
+ statement.all(...params)
222
+ return []
223
+ }
224
+ return statement.all(...params)
225
+ } catch (error) {
226
+ // @db/sqlite resets a statement when its step succeeds, but leaves one
227
+ // whose step failed where it stopped: a RETURNING statement whose row
228
+ // failed to decode is still at SQLITE_ROW, and would prevent every
229
+ // later SAVEPOINT on this connection. Reset, it is done, and stays
230
+ // kept: a statement that fails, as a refused write does, is often asked
231
+ // again. Resetting reports the step's failure again, so the step's
232
+ // error is the one thrown; nothing with possible side effects retries.
233
+ reset(statement.unsafeHandle)
234
+ throw error
235
+ }
236
+ }
237
+ }
238
+
239
+ // The schemas this process's databases in memory were made with, each kept as
240
+ // a database of its own under what made it and what stood before
241
+ // (Driver.template): the TEMPLATES used last, and the spares made from them.
242
+ // A test runtime meets a schema for nearly every vocabulary its files
243
+ // declare, and kept them all, a few hundred kilobytes of pages each, until it
244
+ // exited.
245
+ let templates = new Map<string, Database>()
246
+ let TEMPLATES = 32
247
+
248
+ /** The template kept under `at`, now the one used last. */
249
+ let recall = (at: string): Database | undefined => {
250
+ let db = templates.get(at)
251
+ if (db) templates.delete(at), templates.set(at, db)
252
+ return db
253
+ }
254
+
255
+ /** Keeps `db` as the template under `at`, closing the one used longest ago,
256
+ * and its spares, once there are more than TEMPLATES. */
257
+ let keep = (at: string, db: Database) => {
258
+ templates.set(at, db)
259
+ for (let [old, template] of templates) {
260
+ if (templates.size <= TEMPLATES) break
261
+ templates.delete(old)
262
+ template.close()
263
+ for (let spare of spares.get(old) ?? []) spare.close()
264
+ spares.delete(old)
265
+ }
266
+ }
267
+
268
+ // What a database holds before its schema is made: each object's text, and
269
+ // whether any of its tables has a row. A template stands for a database that
270
+ // held those same objects and nothing in them.
271
+ let holding = (query: (s: Stmt) => Row[]) => {
272
+ let objects = query(select({
273
+ cols: [col('type'), col('name'), col('sql')],
274
+ from: table('sqlite_schema'),
275
+ order: [col('name')],
276
+ }))
277
+ let held = (name: string) =>
278
+ query(select({ cols: [lit(1)], from: table(name), limit: lit(1) })).length
279
+ let empty = !objects.some((o) => o.type == 'table' && held(String(o.name)))
280
+ return { objects: JSON.stringify(objects), empty }
281
+ }
282
+
283
+ // Another connection's commit to a file moves its data_version, a pragma that
284
+ // reads no page, so looking every LOOK ms hears each process's commits within
285
+ // a few milliseconds for a few microseconds a look. (Deno's file watcher could
286
+ // hear them sooner, but closing one while events are in flight can block the
287
+ // thread for good.) The timer holds no process open and runs outside any
288
+ // trace, so its reads are nobody's spans. A look that fails stops looking:
289
+ // whoever listens still passes on a timer of its own.
290
+ let LOOK = 5
291
+ let listen = (version: () => unknown) => (changed: () => void): () => void => {
292
+ let last = version()
293
+ let look = () => {
294
+ try {
295
+ let now = version()
296
+ if (now === last) return
297
+ last = now
298
+ changed()
299
+ } catch (error) {
300
+ clearInterval(timer)
301
+ console.error('sqlite watch —', error)
302
+ }
303
+ }
304
+ let timer = scope(undefined, () => setInterval(look, LOOK))
305
+ Deno.unrefTimer(timer)
306
+ return () => clearInterval(timer)
307
+ }
308
+
309
+ // The `sqlite3_db_config` switches this package turns, by their C names.
310
+ let CONFIGS = {
311
+ SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: 1006,
312
+ SQLITE_DBCONFIG_DQS_DDL: 1014,
313
+ }
314
+
315
+ /** Turn one of a connection's `sqlite3_db_config` switches on or off. */
316
+ export let configure = (
317
+ db: Database,
318
+ name: keyof typeof CONFIGS,
319
+ on: boolean,
320
+ ): void => {
321
+ let code = (steps ??= bindSteps()).symbols.sqlite3_db_config(
322
+ db.unsafeHandle,
323
+ CONFIGS[name],
324
+ on ? 1 : 0,
325
+ null,
326
+ )
327
+ if (code) throw new Error(`SQLite refused ${name} (${code})`)
328
+ }
329
+
330
+ /** Grow the main database's file `bytes` at a time
331
+ * (`SQLITE_FCNTL_CHUNK_SIZE`), so most writes land in blocks the file already
332
+ * has, and syncing them changes no size. */
333
+ export let chunk = (db: Database, bytes: number): void => {
334
+ let code = (steps ??= bindSteps()).symbols.sqlite3_file_control(
335
+ db.unsafeHandle,
336
+ null,
337
+ 6,
338
+ new Int32Array([bytes]),
339
+ )
340
+ if (code) throw new Error(`SQLite refused a chunk size of ${bytes} (${code})`)
341
+ }
342
+
343
+ /** Call `heard` with the pages in the WAL after each commit
344
+ * (`sqlite3_wal_hook`), on the thread that committed, before its COMMIT
345
+ * returns. The hook takes the place of SQLite's own checkpoint every thousand
346
+ * pages, which ran there. The returned close comes after the database's. */
347
+ export let walHook = (
348
+ db: Database,
349
+ heard: (pages: number) => void,
350
+ ): { close: () => void } => {
351
+ let hook = new Deno.UnsafeCallback(
352
+ { parameters: ['pointer', 'pointer', 'pointer', 'i32'], result: 'i32' },
353
+ (_arg, _db, _name, pages) => {
354
+ heard(pages)
355
+ return 0
356
+ },
357
+ )
358
+ ;(steps ??= bindSteps()).symbols.sqlite3_wal_hook(
359
+ db.unsafeHandle,
360
+ hook.pointer,
361
+ null,
362
+ )
363
+ return hook
364
+ }
365
+
366
+ /**
367
+ * The {@link Driver} over one open embedded database.
368
+ *
369
+ * A database on disk is a file other processes may have open too, so the
370
+ * driver reports that ({@link Driver.file}) and the outermost unit takes the
371
+ * write lock up front. An in-memory one belongs to this process alone and sets
372
+ * nothing.
373
+ */
374
+ export let driver = (
375
+ db: Database,
376
+ { lend = false }: { lend?: boolean } = {},
377
+ ): Driver & { close: () => void; database: () => Database } => {
378
+ let run = runner(db)
379
+ // Memory and temporary names have no file. For every other name ask SQLite:
380
+ // the flags may still have made it a database in memory.
381
+ let main = render(select({
382
+ cols: [col('file')],
383
+ from: call('pragma_database_list', []),
384
+ where: eq(col('name'), val('main')),
385
+ }))
386
+ let file = db.path != ':memory:' && db.path != '' &&
387
+ !!run(main.sql, main.params)[0]?.file
388
+ let version = render({ t: 'pragma', name: 'data_version' })
389
+ // Refuse unknown double-quoted columns in DDL rather than letting SQLite
390
+ // interpret them as string literals. The parser checks expressions and WHERE
391
+ // clauses too, without one table_info query per index on every startup.
392
+ configure(db, 'SQLITE_DBCONFIG_DQS_DDL', false)
393
+ // The key of the template this connection holds under its savepoint, while
394
+ // it is lent (`spares`).
395
+ let lent: string | undefined
396
+ let closed = false
397
+ // How deep the templates being made here are nested.
398
+ let making = 0
399
+ let d = connection((sql, params) => {
400
+ if (closed) throw new Error('the database is closed')
401
+ return run(sql, params)
402
+ }, {
403
+ file,
404
+ changes: () => db.changes,
405
+ inTransaction: () => db.inTransaction,
406
+ })
407
+ let query = d.query
408
+ // A lent connection is already inside its savepoint, so a caller's own
409
+ // transaction is a savepoint within it, as nested units already are. A
410
+ // setting said outside any of them, which SQLite would ignore inside a
411
+ // transaction, ends the loan first: the store keeps what it wrote, and the
412
+ // connection, no longer its template, closes with it.
413
+ let nested: string[] = []
414
+ d.query = (s) => {
415
+ if (!lent) return query(s)
416
+ if (s.t == 'rollback' && s.ifActive && !db.inTransaction) {
417
+ lent = undefined
418
+ nested.length = 0
419
+ return query(s)
420
+ }
421
+ if (s.t == 'pragma' && s.value !== undefined && !nested.length) {
422
+ query({ t: 'release', name: LENT })
423
+ lent = undefined
424
+ return query(s)
425
+ }
426
+ let said = standing(s)
427
+ for (let t of said) {
428
+ if (t.t == 'savepoint') nested.push(t.name)
429
+ else if (t.t == 'release' && nested.includes(t.name)) {
430
+ nested.splice(nested.lastIndexOf(t.name))
431
+ }
432
+ }
433
+ return said.flatMap(query)
434
+ }
435
+ let watch = listen(() => run(version.sql, version.params)[0]?.data_version)
436
+ let lendFrom = (at: string, spare?: Database) => {
437
+ if (spare) {
438
+ db.close()
439
+ db = spare
440
+ run = runner(spare)
441
+ }
442
+ query({ t: 'savepoint', name: LENT })
443
+ lent = at
444
+ }
445
+ return Object.assign(d, {
446
+ // A database in memory is this process's alone, and copying a schema into
447
+ // one is a page copy where making it is hundreds of statements. One on
448
+ // disk is made in place: another process may have it open.
449
+ ...file ? { watch } : {
450
+ template: (key: string, make: () => void) => {
451
+ let before = holding(query)
452
+ if (!before.empty || db.inTransaction) return make()
453
+ let at = key + '\n' + before.objects
454
+ // A schema made inside another's making (the store's own, inside its
455
+ // host's) is part of the outer template, which alone is lent.
456
+ let lending = lend && !making
457
+ let kept = recall(at)
458
+ let spare = lending ? spares.get(at)?.pop() : undefined
459
+ if (spare || kept) {
460
+ if (!spare) kept!.backup(db)
461
+ if (lending) lendFrom(at, spare)
462
+ // A copy is a store of its own: it never takes the lineage
463
+ // identity of the one its template was made in (./meta.ts `epoch`).
464
+ if (epochAt(d)) meta(d).set(EPOCH, crypto.randomUUID())
465
+ return
466
+ }
467
+ making++
468
+ try {
469
+ make()
470
+ } finally {
471
+ making--
472
+ }
473
+ let copy = new Database(':memory:')
474
+ db.backup(copy)
475
+ keep(at, copy)
476
+ if (lending) lendFrom(at)
477
+ },
478
+ },
479
+ database: () => db,
480
+ // A lent connection goes back as its template, rolled back to the
481
+ // savepoint it was lent at, with every statement it compiled kept.
482
+ close: () => {
483
+ if (closed) return
484
+ closed = true
485
+ let at = lent
486
+ lent = undefined
487
+ if (at && db.inTransaction) {
488
+ try {
489
+ for (let s of LEAVE) run(s.sql, s.params)
490
+ } catch (error) {
491
+ db.close()
492
+ throw error
493
+ }
494
+ let held = spares.get(at) ?? []
495
+ if (
496
+ !db.inTransaction && templates.has(at) && held.length < SPARES
497
+ ) {
498
+ spares.set(at, [...held, db])
499
+ return
500
+ }
501
+ }
502
+ db.close()
503
+ },
504
+ })
505
+ }
506
+
507
+ // The savepoint a lent connection stands in: what it rolls back to when its
508
+ // store closes.
509
+ let LENT = 'yaks_lent'
510
+ let LEAVE = [
511
+ render({ t: 'rollback', to: LENT }),
512
+ render({ t: 'release', name: LENT }),
513
+ ]
514
+
515
+ // A caller's transaction, said to a lent connection: one savepoint within the
516
+ // one it stands in, as a nested unit's is (./unit.ts).
517
+ let standing = (s: Stmt): Stmt[] =>
518
+ s.t == 'begin'
519
+ ? [{ t: 'savepoint', name: 'yaks_begun' }]
520
+ : s.t == 'commit'
521
+ ? [{ t: 'release', name: 'yaks_begun' }]
522
+ : s.t == 'rollback' && !s.to
523
+ ? [{ t: 'rollback', to: 'yaks_begun' }, {
524
+ t: 'release',
525
+ name: 'yaks_begun',
526
+ }]
527
+ : [s]
528
+
529
+ // Connections in memory whose stores have closed, each holding the template
530
+ // it was made from, by that template's key. A store lent one starts with
531
+ // every statement the last compiled for that same schema: SQLite compiles
532
+ // per connection, and a statement survives a rollback, where a copy of the
533
+ // template recompiles all of them. A test suite opens thousands of stores in
534
+ // memory, each of whose first model turn compiled two hundred statements.
535
+ let spares = new Map<string, Database[]>()
536
+ let SPARES = 8
537
+
538
+ // Each connection's statements, kept with it however many stores it serves.
539
+ let runners = new WeakMap<Database, ReturnType<typeof prepared>>()
540
+ let runner = (db: Database) => {
541
+ let run = runners.get(db)
542
+ if (!run) runners.set(db, run = prepared(db))
543
+ return run
544
+ }