@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/physical.ts ADDED
@@ -0,0 +1,434 @@
1
+ import {
2
+ catalogue,
3
+ columnAsWritten,
4
+ fullLayout,
5
+ revision,
6
+ stored,
7
+ tableAsWritten,
8
+ } from '@yaks/sql'
9
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
10
+ import {
11
+ col,
12
+ type Driver,
13
+ eq,
14
+ type Param,
15
+ type Row,
16
+ type SchemaObject,
17
+ select,
18
+ type Stmt,
19
+ table,
20
+ val,
21
+ } from '@yaks/sql'
22
+
23
+ /** Whether a table is not the file's own: SQLite's catalogue, or one the host
24
+ * keeps inside it. A Durable Object's `_cf_KV` and `_cf_METADATA` are listed
25
+ * by `table_list` like any other, and workerd's authorizer refuses every
26
+ * statement naming them, a pragma included, with SQLITE_AUTH (T-34019). */
27
+ export let foreign = (name: string): boolean => /^(sqlite_|_+cf_)/i.test(name)
28
+
29
+ type MainTable = { name: string; type: unknown; withoutRowid: boolean }
30
+ let listedTables = new WeakMap<Driver, {
31
+ at: number
32
+ physical: readonly MainTable[]
33
+ written?: { v?: Vocab; tables: readonly MainTable[] }
34
+ }>()
35
+
36
+ // The engine's catalogue of main tables, as the file names them.
37
+ let main = (driver: Driver) => {
38
+ let at = revision(driver, 'schema')
39
+ let held = listedTables.get(driver)
40
+ if (held?.at === at) return held
41
+ let physical = driver.query({ t: 'pragma', name: 'table_list' })
42
+ .filter((r) => r.schema == 'main' && !foreign(String(r.name)))
43
+ .map((r) => ({
44
+ name: String(r.name),
45
+ type: r.type,
46
+ withoutRowid: r.wr == 1,
47
+ }))
48
+ listedTables.set(driver, held = { at, physical })
49
+ return held
50
+ }
51
+
52
+ /** The main schema's tables under the names statements write them by. */
53
+ export let mainTables = (driver: Driver): readonly MainTable[] => {
54
+ let held = main(driver), v = driver.stored?.v
55
+ if (!v) return held.physical
56
+ v = fullLayout(v)
57
+ if (held.written?.v === v) return held.written!.tables
58
+ let tables = held.physical.map((r) => ({
59
+ ...r,
60
+ name: tableAsWritten(v, r.name),
61
+ }))
62
+ held.written = { v, tables }
63
+ return tables
64
+ }
65
+
66
+ /** The main schema's tables as the file names them. */
67
+ export let storedTables = (driver: Driver): string[] =>
68
+ main(driver).physical.map((r) => r.name)
69
+
70
+ /** Every table the file's schema lists, with the statement it was made by. */
71
+ export let defined: Stmt = select({
72
+ cols: [col('name'), col('sql')],
73
+ from: table('sqlite_schema'),
74
+ where: eq(col('type'), val('table')),
75
+ order: [col('name')],
76
+ })
77
+
78
+ // Every table the file's schema lists, with the statement it was made by:
79
+ // what {@link defined} answers, off the catalogue the schema is read into once.
80
+ let listed = (driver: Driver) =>
81
+ catalogue(driver).filter((o) => o.type == 'table')
82
+
83
+ /** Every table the file's schema lists, by name. */
84
+ export let tables = (driver: Driver): string[] =>
85
+ listed(driver).map((o) => o.name)
86
+
87
+ /** A table as the file holds it: its columns (`pragma table_info`), the
88
+ * columns it keys to another table, and what each column checks
89
+ * ({@link checks}). */
90
+ export type Stood = {
91
+ cols: Row[]
92
+ keys: string[]
93
+ checks: Record<string, string>
94
+ }
95
+
96
+ /** What is asked of each table `names` names: its columns, then its keys. */
97
+ export let asked = (names: string[]): Stmt[] =>
98
+ names.flatMap((arg): Stmt[] => [
99
+ { t: 'pragma', name: 'table_info', arg },
100
+ { t: 'pragma', name: 'foreign_key_list', arg },
101
+ ])
102
+
103
+ /** The answers to {@link asked}, as each table's {@link Stood}. `defs` is what
104
+ * {@link defined} answered. */
105
+ export let heard = (
106
+ defs: Row[],
107
+ names: string[],
108
+ answers: Row[][],
109
+ ): Record<string, Stood> =>
110
+ Object.fromEntries(names.map((name, i) => [name, {
111
+ cols: answers[2 * i],
112
+ keys: answers[2 * i + 1].map((r) => String(r.from)),
113
+ checks: checks(String(defs.find((d) => d.name == name)?.sql ?? '')),
114
+ }]))
115
+
116
+ /** Each table `pick` keeps, as the file holds it now, read through a driver
117
+ * that answers at once. */
118
+ export let stood = (
119
+ driver: Driver,
120
+ pick: (name: string) => boolean,
121
+ ): Record<string, Stood> => {
122
+ let defs = listed(driver)
123
+ let names = defs.map((d) => d.name).filter(pick)
124
+ return heard(defs, names, asked(names).map((s) => driver.query(s)))
125
+ }
126
+
127
+ // SQLite's tokens, as far as reading a definition back needs them: a string, a
128
+ // quoted name, a word or a number, or one character of punctuation.
129
+ let TOKEN =
130
+ /'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[\w$]+|[^\s\w]/g
131
+
132
+ // A token as SQLite compares it: a name unquoted, a name or a keyword in lower
133
+ // case, a string as written.
134
+ let norm = (t: string): string =>
135
+ t[0] == "'" ? t : (/^["`[]/.test(t) ? t.slice(1, -1) : t).toLowerCase()
136
+
137
+ /** Every name and keyword a definition says, as SQLite compares them: what
138
+ * tells which tables and columns an index, a trigger or a view names. */
139
+ export let words = (sql: string): Set<string> =>
140
+ new Set((sql.match(TOKEN) ?? []).map(norm))
141
+
142
+ // The index of the parenthesis that closes the one at `at`.
143
+ let close = (tokens: string[], at: number): number => {
144
+ for (let i = at, depth = 0; i < tokens.length; i++) {
145
+ depth += tokens[i] == '(' ? 1 : tokens[i] == ')' ? -1 : 0
146
+ if (!depth) return i
147
+ }
148
+ return tokens.length
149
+ }
150
+
151
+ // Each parenthesized run directly in `tokens`, as the tokens it encloses and
152
+ // the token before it.
153
+ let runs = (tokens: string[]): [string, string[]][] => {
154
+ let out: [string, string[]][] = []
155
+ for (let i = tokens.indexOf('('); i >= 0; i = tokens.indexOf('(', i + 1)) {
156
+ let end = close(tokens, i)
157
+ out.push([tokens[i - 1] ?? '', tokens.slice(i + 1, end)])
158
+ i = end
159
+ }
160
+ return out
161
+ }
162
+
163
+ // A table's columns and constraints, each as its tokens: the first run of its
164
+ // definition, split at the commas directly inside it.
165
+ let defs = (tokens: string[]): string[][] => {
166
+ let [[, inner] = ['', []]] = runs(tokens)
167
+ let out: string[][] = [[]]
168
+ for (let i = 0; i < inner.length; i++) {
169
+ let end = inner[i] == '(' ? close(inner, i) : i
170
+ if (inner[i] == ',') out.push([])
171
+ else out.at(-1)!.push(...inner.slice(i, end + 1))
172
+ i = end
173
+ }
174
+ return out
175
+ }
176
+
177
+ // The keywords a table constraint starts with, where a column starts with its
178
+ // name.
179
+ let CONSTRAINT = new Set([
180
+ 'constraint',
181
+ 'primary',
182
+ 'unique',
183
+ 'check',
184
+ 'foreign',
185
+ ])
186
+
187
+ /**
188
+ * What a table's definition checks, by the column each check sits on (a table
189
+ * constraint's under `''`): the expression as its tokens compare, so one check
190
+ * reads the same however it was spaced, cased or quoted. Read off the statement
191
+ * `sqlite_schema` keeps, because SQLite lists a table's columns and keys by
192
+ * pragma and has no pragma for a check.
193
+ *
194
+ * ```ts
195
+ * import { assertEquals } from '@std/assert'
196
+ * import { checks } from '@yaks/sqlite'
197
+ *
198
+ * let kind = { kind: "kind in ( 'A' , 'b' )" }
199
+ * assertEquals(
200
+ * checks(`CREATE TABLE "t" (id integer, "kind" text check("kind" in ('A', 'b')))`),
201
+ * kind,
202
+ * )
203
+ * assertEquals(checks(`create table t (Kind TEXT CHECK (kind IN ('A','b')))`), kind)
204
+ * assertEquals(checks(`create table t (id integer, check (id > 0))`), {
205
+ * '': 'id > 0',
206
+ * })
207
+ * assertEquals(checks(`create table t (id integer)`), {})
208
+ * ```
209
+ */
210
+ export let checks = (sql: string): Record<string, string> => {
211
+ let found: Record<string, string[]> = {}
212
+ for (let def of defs(sql.match(TOKEN) ?? [])) {
213
+ let [head = ''] = def
214
+ let on = CONSTRAINT.has(head.toLowerCase()) ? '' : norm(head)
215
+ for (let [before, expr] of runs(def)) {
216
+ if (before.toLowerCase() != 'check') continue
217
+ found[on] = [...found[on] ?? [], expr.map(norm).join(' ')]
218
+ }
219
+ }
220
+ return Object.fromEntries(
221
+ Object.entries(found).map(([on, all]) => [on, all.join(' and ')]),
222
+ )
223
+ }
224
+
225
+ /**
226
+ * The columns a table's own definition holds in place, which SQLite refuses
227
+ * to drop: one its definition makes a key or unique, and every one a table
228
+ * constraint names. A column whose own check is all that names it drops with
229
+ * its check.
230
+ *
231
+ * ```ts
232
+ * import { assertEquals } from '@std/assert'
233
+ * import { pinned } from '@yaks/sqlite'
234
+ *
235
+ * let held = pinned(`create table t (entity integer primary key,
236
+ * "Slug" text unique, a text, b text check (b > ''), c text, check (a > ''))`)
237
+ * assertEquals(
238
+ * ['entity', 'slug', 'a', 'b', 'c'].filter((c) => held.has(c)),
239
+ * ['entity', 'slug', 'a'],
240
+ * )
241
+ * ```
242
+ */
243
+ export let pinned = (sql: string): Set<string> =>
244
+ new Set(
245
+ defs(sql.match(TOKEN) ?? []).flatMap((def) => {
246
+ let said = def.map(norm).filter((w) => /^[\w$]/.test(w))
247
+ if (CONSTRAINT.has(said[0] ?? '')) return said
248
+ return said.includes('primary') || said.includes('unique')
249
+ ? [said[0]]
250
+ : []
251
+ }),
252
+ )
253
+
254
+ /** What the file's schema holds — each table, index, view and trigger, with
255
+ * the table it is on and its definition — or the entries these fields name. */
256
+ export let objects = (
257
+ driver: Driver,
258
+ fields: Record<string, Param> = {},
259
+ ): SchemaObject[] =>
260
+ catalogue(driver).filter((o) =>
261
+ Object.entries(fields).every(([k, v]) => o[k as keyof typeof o] == v)
262
+ )
263
+
264
+ /** Whether the spine keeps `num` unique by itself, as every spine made
265
+ * before series had letters did (`num integer unique`). */
266
+ export let sole = (driver: Driver): boolean =>
267
+ driver.query({ t: 'pragma', name: 'index_list', arg: 'entity' })
268
+ .filter((i) => Number(i.unique))
269
+ .some((i) => {
270
+ let cols = driver.query({
271
+ t: 'pragma',
272
+ name: 'index_info',
273
+ arg: String(i.name),
274
+ })
275
+ return cols.length == 1 && cols[0].name == 'num'
276
+ })
277
+
278
+ /** A table's columns, in declaration order. */
279
+ export let columns = (driver: Driver, name: string): string[] =>
280
+ driver.query({ t: 'pragma', name: 'table_info', arg: name })
281
+ .map((c) => String(c.name))
282
+
283
+ // A table's columns by the statement SQLite keeps for it, which an added,
284
+ // dropped or renamed column rewrites: a store whose tables were made as
285
+ // another's were asks the engine nothing.
286
+ let made = new Map<string, readonly string[]>()
287
+ let MADE = 4096
288
+
289
+ /** A table's columns, in declaration order, given the statement the file's
290
+ * schema keeps for it (@yaks/sql `catalogue`): asked of the engine once a
291
+ * statement. */
292
+ export let columnsBy = (
293
+ driver: Driver,
294
+ name: string,
295
+ sql: string | null | undefined,
296
+ ): readonly string[] => {
297
+ if (sql == null) return columns(driver, name)
298
+ let held = made.get(sql), v = driver.stored?.v
299
+ if (!held) {
300
+ let found = columns(driver, name)
301
+ held = v ? found.map((n) => stored(v, name, n)) : found
302
+ if (made.size >= MADE) made.delete(made.keys().next().value!)
303
+ made.set(sql, held)
304
+ }
305
+ return v ? held.map((n) => columnAsWritten(v, name, n)) : held
306
+ }
307
+
308
+ /** The columns a table requires a value for: not null, with no default, as
309
+ * the file holds them. Asked once a table while the connection's schema
310
+ * stands. */
311
+ let requirements = new WeakMap<
312
+ object,
313
+ { at: number; v?: Vocab; tables: Map<string, string[]> }
314
+ >()
315
+
316
+ export let required = (driver: Driver, name: string): string[] => {
317
+ let at = revision(driver, 'schema')
318
+ let key = driver.connection ?? driver
319
+ let held = requirements.get(key), v = driver.stored?.v
320
+ if (v) v = fullLayout(v)
321
+ if (held?.at != at || held.v != v) {
322
+ requirements.set(key, held = { at, v, tables: new Map() })
323
+ }
324
+ let need = held.tables.get(name)
325
+ if (!need) {
326
+ need = driver.query({ t: 'pragma', name: 'table_info', arg: name })
327
+ .filter((r) =>
328
+ r.name != 'entity' && Number(r.notnull) != 0 && r.dflt_value == null
329
+ ).map((r) => String(r.name))
330
+ held.tables.set(name, need)
331
+ }
332
+ return need
333
+ }
334
+
335
+ /**
336
+ * Component tables actually in the file, irrespective of the loaded vocabulary.
337
+ * Virtual/FTS shadow tables and infrastructure are not component tables. A
338
+ * component table has an integer entity primary key. Tombstone and archetype
339
+ * are component tables (the latter's own archetype is the one-element fixed
340
+ * point). `known` names tables the caller already accounts for: they are left
341
+ * out without being asked about. A name starting `_yaks_` is a table being
342
+ * rebuilt beside a component's, or one's old rows waiting to be cleared
343
+ * (./owe.ts). No other name is reserved: an app may call a component `journal`
344
+ * (@yaks/journal keeps its own rows in `journal_*`).
345
+ */
346
+ let components = new WeakMap<
347
+ Driver,
348
+ {
349
+ revision: number
350
+ v?: Vocab
351
+ tables: string[]
352
+ checked: Map<string, boolean>
353
+ }
354
+ >()
355
+
356
+ // Whether a table is a component's, by the statement SQLite keeps for it: the
357
+ // same statement makes the same columns, so a store whose tables were made as
358
+ // another's were (every app store's core words) asks the engine nothing, and
359
+ // a schema that moved asks only of the tables it changed.
360
+ let shaped = new Map<string, boolean>()
361
+ let SHAPED = 4096
362
+
363
+ export function componentTables(
364
+ driver: Driver,
365
+ known: readonly string[] = [],
366
+ candidates?: readonly string[],
367
+ ): string[] {
368
+ let current = revision(driver, 'schema')
369
+ let held = components.get(driver), v = driver.stored?.v
370
+ if (v) v = fullLayout(v)
371
+ if (!held || held.revision != current || held.v != v) {
372
+ let found = mainTables(driver)
373
+ .filter(({ name, type }) =>
374
+ type == 'table' && name != 'entity' && !name.startsWith('_yaks_')
375
+ )
376
+ .map(({ name }) => name)
377
+ .sort()
378
+ held = { revision: current, v, tables: found, checked: new Map() }
379
+ components.set(driver, held)
380
+ }
381
+ let accounted = new Set(known)
382
+ let wanted = candidates && new Set(candidates)
383
+ let made: Map<string, string | null> | undefined
384
+ let { checked } = held
385
+ return held.tables.filter((name) => {
386
+ if (accounted.has(name) || wanted && !wanted.has(name)) return false
387
+ let component = checked.get(name)
388
+ if (component === undefined) {
389
+ made ??= new Map(catalogue(driver).map((o) => [o.name, o.sql]))
390
+ let sql = made.get(name)
391
+ component = sql == null ? undefined : shaped.get(sql)
392
+ if (component === undefined) {
393
+ component = driver.query({
394
+ t: 'pragma',
395
+ name: 'table_info',
396
+ schema: 'main',
397
+ arg: name,
398
+ })
399
+ .some((r) =>
400
+ r.name == 'entity' && Number(r.pk) == 1 &&
401
+ String(r.type).toLowerCase() == 'integer'
402
+ )
403
+ if (sql != null) {
404
+ if (shaped.size >= SHAPED) shaped.delete(shaped.keys().next().value!)
405
+ shaped.set(sql, component)
406
+ }
407
+ }
408
+ checked.set(name, component)
409
+ }
410
+ return component
411
+ })
412
+ }
413
+
414
+ /**
415
+ * How many of the named objects the file's schema holds and how long their
416
+ * definitions run together, in characters: what moves when one of them is
417
+ * created, dropped or altered, by any connection (a file's revision sees
418
+ * another connection's). Read off `sqlite_schema`, since a Durable Object's
419
+ * SQLite refuses `pragma schema_version`. Only the named objects count, so
420
+ * what is kept beside them (a search index and its triggers, a plugin's own
421
+ * table, the `sqlite_stat1` the first analyze creates) is no change to them.
422
+ */
423
+ export let shape = (driver: Driver, names: readonly string[]): string => {
424
+ let asked = new Set(names)
425
+ let found = catalogue(driver).filter((o) => asked.has(o.name))
426
+ let bytes = found.reduce((n, o) => n + characters(o.sql ?? ''), 0)
427
+ return `${found.length}/${bytes}`
428
+ }
429
+
430
+ // A string's characters, as code points: its UTF-16 units, one fewer for each
431
+ // surrogate pair, worked out without splitting it.
432
+ let PAIR = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
433
+ let characters = (text: string): number =>
434
+ text.length - (text.match(PAIR)?.length ?? 0)
package/plan.js ADDED
@@ -0,0 +1,78 @@
1
+ import { POPULATION_VERSION } from "./population.js";
2
+ import { render } from "@yaks/sql/core";
3
+ import { digest, sha256 } from "@yaks/graph/sha256";
4
+ import { FIT, indexed, tabled } from "./ddl.js";
5
+ import { RAISED, rests } from "./raise.js";
6
+ let makes = (s)=>s.t == 'create table' || s.t == 'create index' || s.t == 'create view' || s.t == 'create trigger';
7
+ let plans = [
8
+ new WeakMap(),
9
+ new WeakMap()
10
+ ];
11
+ let NONE = {};
12
+ // Where the plan for a vocabulary and its read overrides is kept.
13
+ let shelf = (vocab, file)=>{
14
+ let held = plans[Number(file)];
15
+ let by = held.get(vocab) ?? new WeakMap();
16
+ held.set(vocab, by);
17
+ return by;
18
+ };
19
+ // A plan but its print, and the text its print digests.
20
+ let draft = (vocab, derived, file)=>{
21
+ let stmts = [
22
+ ...tabled(vocab, derived, file),
23
+ ...indexed(vocab, true)
24
+ ];
25
+ let raised = stmts.filter(makes);
26
+ // What every install makes: a component's own objects are made by its
27
+ // first write (./raise.ts), and are no part of what an install answers for.
28
+ let on = rests(vocab, stmts);
29
+ return {
30
+ // The fitting's revision rides beside them (ddl.ts `FIT`): what fitting
31
+ // changes is read off the file, so a fitting that learns something new
32
+ // installs again over a file whose statements are as they were. So does
33
+ // when a component's objects are made (./raise.ts `RAISED`).
34
+ text: [
35
+ FIT,
36
+ POPULATION_VERSION,
37
+ RAISED,
38
+ ...stmts.map((s)=>render(s, undefined, undefined, vocab).sql)
39
+ ].join(';\n'),
40
+ raised,
41
+ made: stmts.flatMap((s, i)=>makes(s) && !on[i].length ? [
42
+ s.name
43
+ ] : []),
44
+ on: stmts.flatMap((s, i)=>makes(s) ? [
45
+ on[i]
46
+ ] : [])
47
+ };
48
+ };
49
+ export let plan = (vocab, derived = NONE, file = false)=>{
50
+ let by = shelf(vocab, file);
51
+ let known = by.get(derived);
52
+ if (known) return known;
53
+ let { text, ...rest } = draft(vocab, derived, file);
54
+ let fresh = {
55
+ print: sha256(text),
56
+ ...rest
57
+ };
58
+ by.set(derived, fresh);
59
+ return fresh;
60
+ };
61
+ /** {@link plan}, its print digested by the platform rather than in script,
62
+ * and kept where `plan` finds it. A schema's statements are a hundred
63
+ * kilobytes, which the script digest takes milliseconds over in a process
64
+ * that has not compiled it yet, as every command starts; a host that can wait
65
+ * before it binds its store asks this first. */ export let planned = async (vocab, derived = NONE, file = false)=>{
66
+ let by = shelf(vocab, file);
67
+ let known = by.get(derived);
68
+ if (known) return known;
69
+ let { text, ...rest } = draft(vocab, derived, file);
70
+ let print = await digest(text);
71
+ // One `plan` made while the digest ran is the same plan, and stays.
72
+ if (!by.has(derived)) by.set(derived, {
73
+ print,
74
+ ...rest
75
+ });
76
+ return by.get(derived);
77
+ };
78
+ //# sourceMappingURL=plan.js.map
package/plan.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan.js","sources":["./plan.ts"],"names":[],"mappings":"AAAA,SAAS,kBAAkB,0BAAyB;AAOpD,SAAS,MAAM,8BAAmC;AAElD,SAAS,MAAM,EAAE,MAAM,kCAAuC;AAC9D,SAAS,GAAG,EAAE,OAAO,EAAE,MAAM,mBAAkB;AAC/C,SAAS,MAAM,EAAE,KAAK,qBAAoB;AAmB1C,IAAI,QAAQ,CAAC,IACX,EAAE,CAAC,IAAI,kBAAkB,EAAE,CAAC,IAAI,kBAAkB,EAAE,CAAC,IAAI,iBACzD,EAAE,CAAC,IAAI;AACT,IAAI,QAAQ;EACV,IAAI;EACJ,IAAI;CACL;AACD,IAAI,OAAgB,CAAC;AAErB,kEAAkE;AAClE,IAAI,QAAQ,CAAC,OAAc;EACzB,IAAI,OAAO,KAAK,CAAC,OAAO,MAAM;EAC9B,IAAI,KAAK,KAAK,GAAG,CAAC,UAAU,IAAI;EAChC,KAAK,GAAG,CAAC,OAAO;EAChB,OAAO;AACT;AAEA,wDAAwD;AACxD,IAAI,QAAQ,CAAC,OAAc,SAAkB;EAC3C,IAAI,QAAQ;OAAI,OAAO,OAAO,SAAS;OAAU,QAAQ,OAAO;GAAM;EACtE,IAAI,SAAS,MAAM,MAAM,CAAC;EAC1B,sEAAsE;EACtE,4EAA4E;EAC5E,IAAI,KAAK,MAAM,OAAO;EACtB,OAAO;IACL,wEAAwE;IACxE,uEAAuE;IACvE,wEAAwE;IACxE,6DAA6D;IAC7D,MAAM;MACJ;MACA;MACA;SACG,MAAM,GAAG,CAAC,CAAC,IAAM,OAAO,GAAG,WAAW,WAAW,OAAO,GAAG;KAC/D,CAAC,IAAI,CAAC;IACP;IACA,MAAM,MAAM,OAAO,CAAC,CAAC,GAAG,IAAM,MAAM,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,MAAM,GAAG;QAAC,EAAE,IAAI;OAAC,GAAG,EAAE;IACvE,IAAI,MAAM,OAAO,CAAC,CAAC,GAAG,IAAM,MAAM,KAAK;QAAC,EAAE,CAAC,EAAE;OAAC,GAAG,EAAE;EACrD;AACF;AAEA,OAAO,IAAI,OAAO,CAChB,OACA,UAAmB,IAAI,EACvB,OAAO,KAAK;EAEZ,IAAI,KAAK,MAAM,OAAO;EACtB,IAAI,QAAQ,GAAG,GAAG,CAAC;EACnB,IAAI,OAAO,OAAO;EAClB,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,GAAG,MAAM,OAAO,SAAS;EAC9C,IAAI,QAAQ;IAAE,OAAO,OAAO;IAAO,GAAG,IAAI;EAAC;EAC3C,GAAG,GAAG,CAAC,SAAS;EAChB,OAAO;AACT,EAAC;AAED;;;;8CAI8C,GAC9C,OAAO,IAAI,UAAU,OACnB,OACA,UAAmB,IAAI,EACvB,OAAO,KAAK;EAEZ,IAAI,KAAK,MAAM,OAAO;EACtB,IAAI,QAAQ,GAAG,GAAG,CAAC;EACnB,IAAI,OAAO,OAAO;EAClB,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,GAAG,MAAM,OAAO,SAAS;EAC9C,IAAI,QAAQ,MAAM,OAAO;EACzB,oEAAoE;EACpE,IAAI,CAAC,GAAG,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,SAAS;IAAE;IAAO,GAAG,IAAI;EAAC;EACvD,OAAO,GAAG,GAAG,CAAC;AAChB,EAAC"}
package/plan.ts ADDED
@@ -0,0 +1,104 @@
1
+ import { POPULATION_VERSION } from './population.js'
2
+ // What a store's `install()` runs, known once per vocabulary and read
3
+ // overrides, and the store's part of a composed schema's print (./follow.ts).
4
+ // Shared by the writing store (./mod.ts) and the reading one (./read-store.ts),
5
+ // which reads the print and nothing else.
6
+
7
+ import type { Derived, Stmt } from 'jsr:@yaks/sql@0.2.36'
8
+ import { render } from '@yaks/sql/core'
9
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
10
+ import { digest, sha256 } from '@yaks/graph/sha256'
11
+ import { FIT, indexed, tabled } from './ddl.js'
12
+ import { RAISED, rests } from './raise.js'
13
+
14
+ // What `install()` runs, known once per vocabulary and read overrides: the
15
+ // fingerprint of its statements, the statements that create an object where
16
+ // it is missing, and the objects they create. Over a current file the
17
+ // rendering and the hashing were most of what an install cost, and none of it
18
+ // moves while a process holds the same vocabulary: a Vocab is a value nobody
19
+ // mutates once it is loaded, so the object itself is the key.
20
+ type Make = Extract<
21
+ Stmt,
22
+ { t: 'create table' | 'create index' | 'create view' | 'create trigger' }
23
+ >
24
+ export type Plan = {
25
+ print: string
26
+ raised: Make[]
27
+ made: string[]
28
+ /** the component tables each of `raised` rests on (./raise.ts) */
29
+ on: string[][]
30
+ }
31
+ let makes = (s: Stmt): s is Make =>
32
+ s.t == 'create table' || s.t == 'create index' || s.t == 'create view' ||
33
+ s.t == 'create trigger'
34
+ let plans = [
35
+ new WeakMap<Vocab, WeakMap<Derived, Plan>>(),
36
+ new WeakMap<Vocab, WeakMap<Derived, Plan>>(),
37
+ ]
38
+ let NONE: Derived = {}
39
+
40
+ // Where the plan for a vocabulary and its read overrides is kept.
41
+ let shelf = (vocab: Vocab, file: boolean) => {
42
+ let held = plans[Number(file)]
43
+ let by = held.get(vocab) ?? new WeakMap<Derived, Plan>()
44
+ held.set(vocab, by)
45
+ return by
46
+ }
47
+
48
+ // A plan but its print, and the text its print digests.
49
+ let draft = (vocab: Vocab, derived: Derived, file: boolean) => {
50
+ let stmts = [...tabled(vocab, derived, file), ...indexed(vocab, true)]
51
+ let raised = stmts.filter(makes)
52
+ // What every install makes: a component's own objects are made by its
53
+ // first write (./raise.ts), and are no part of what an install answers for.
54
+ let on = rests(vocab, stmts)
55
+ return {
56
+ // The fitting's revision rides beside them (ddl.ts `FIT`): what fitting
57
+ // changes is read off the file, so a fitting that learns something new
58
+ // installs again over a file whose statements are as they were. So does
59
+ // when a component's objects are made (./raise.ts `RAISED`).
60
+ text: [
61
+ FIT,
62
+ POPULATION_VERSION,
63
+ RAISED,
64
+ ...stmts.map((s) => render(s, undefined, undefined, vocab).sql),
65
+ ].join(';\n'),
66
+ raised,
67
+ made: stmts.flatMap((s, i) => makes(s) && !on[i].length ? [s.name] : []),
68
+ on: stmts.flatMap((s, i) => makes(s) ? [on[i]] : []),
69
+ }
70
+ }
71
+
72
+ export let plan = (
73
+ vocab: Vocab,
74
+ derived: Derived = NONE,
75
+ file = false,
76
+ ): Plan => {
77
+ let by = shelf(vocab, file)
78
+ let known = by.get(derived)
79
+ if (known) return known
80
+ let { text, ...rest } = draft(vocab, derived, file)
81
+ let fresh = { print: sha256(text), ...rest }
82
+ by.set(derived, fresh)
83
+ return fresh
84
+ }
85
+
86
+ /** {@link plan}, its print digested by the platform rather than in script,
87
+ * and kept where `plan` finds it. A schema's statements are a hundred
88
+ * kilobytes, which the script digest takes milliseconds over in a process
89
+ * that has not compiled it yet, as every command starts; a host that can wait
90
+ * before it binds its store asks this first. */
91
+ export let planned = async (
92
+ vocab: Vocab,
93
+ derived: Derived = NONE,
94
+ file = false,
95
+ ): Promise<Plan> => {
96
+ let by = shelf(vocab, file)
97
+ let known = by.get(derived)
98
+ if (known) return known
99
+ let { text, ...rest } = draft(vocab, derived, file)
100
+ let print = await digest(text)
101
+ // One `plan` made while the digest ran is the same plan, and stays.
102
+ if (!by.has(derived)) by.set(derived, { print, ...rest })
103
+ return by.get(derived)!
104
+ }