@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/follow.ts ADDED
@@ -0,0 +1,401 @@
1
+ // A graph's schema follows its vocabulary wherever the graph is opened for
2
+ // writing (D-121389). Everything a file needs is one composed schema, and the
3
+ // schema has one print. A file records each print it has been brought to, as
4
+ // the `server_meta` row `schema:<print>`; an opener whose print is recorded
5
+ // opens with no DDL and no write lock, and one whose print is missing runs the
6
+ // pass that brings the file to it, then records it. A recorded print stays
7
+ // recorded while the file only grows, so a process still running the
8
+ // vocabulary a landing replaced finds its own print and changes nothing; a
9
+ // pass that sheds what its vocabulary stopped naming forgets the others.
10
+ //
11
+ // Two openers that find the same print missing both run the pass: every step
12
+ // of it reads the file under the write lock before it changes anything, so the
13
+ // second one finds nothing left to do. An index over a populated table, a
14
+ // text index over one, and a big table's refit are written down instead, for
15
+ // the effects worker to do in windows (./owe.ts).
16
+
17
+ import {
18
+ catalogue,
19
+ type Column,
20
+ type Driver,
21
+ render,
22
+ type SchemaObject,
23
+ type Stmt,
24
+ stored,
25
+ } from '@yaks/sql/core'
26
+ import {
27
+ col,
28
+ type Derived,
29
+ field,
30
+ lit,
31
+ notNull,
32
+ select,
33
+ tagOf,
34
+ } from '@yaks/sql'
35
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
36
+ import { sha256 } from '@yaks/graph/sha256'
37
+ import {
38
+ analyzedAt,
39
+ installation,
40
+ installed,
41
+ meta,
42
+ PRINTED,
43
+ printed,
44
+ prints,
45
+ SCHEMA,
46
+ } from './meta.js'
47
+ import { unit } from './unit.js'
48
+ import { build, holds as rowed } from './owe.js'
49
+ import { plan, planned } from './plan.js'
50
+ import { behind, declares, exact } from './ddl.js'
51
+ import { tables } from './layout.js'
52
+ import { recorded, unraised } from './raise.js'
53
+ import {
54
+ columns,
55
+ columnsBy,
56
+ componentTables,
57
+ pinned,
58
+ words,
59
+ } from './physical.js'
60
+
61
+ /** The print of a composed schema: a store's own print (`Store.print`) and
62
+ * every further statement the file needs, rendered. */
63
+ export let printOf = (store: string, stmts: Stmt[]): string =>
64
+ sha256([store, ...stmts.map((s) => render(s).sql)].join(';\n'))
65
+
66
+ /** What `Store.print` says, known from the vocabulary alone: for a host that
67
+ * composes its print before it binds the store it will open with it, the way
68
+ * a yaks.app store keeps one print per vocabulary it has seen. */
69
+ export let printFor = (
70
+ vocab: Vocab,
71
+ derived: Derived = {},
72
+ file = false,
73
+ ): string => plan(vocab, derived, file).print
74
+
75
+ /** {@link printFor}, digested by the platform: a host that can wait before it
76
+ * binds the store it opens asks this first, and the store finds its print
77
+ * made rather than digesting a hundred kilobytes of statements in script. */
78
+ export let printing = (
79
+ vocab: Vocab,
80
+ derived: Derived = {},
81
+ file = false,
82
+ ): Promise<string> => planned(vocab, derived, file).then((p) => p.print)
83
+
84
+ // A column as `add column` takes it onto a standing table: SQLite refuses a
85
+ // key or a unique column there, a NOT NULL without a literal default, and a
86
+ // default that is an expression. The CHECK waits for the table's refit, since
87
+ // adding one reads every row; admission holds the writes meanwhile.
88
+ let added = (c: Column): Column => {
89
+ let d = c.default?.t == 'lit' ? c.default : undefined
90
+ return {
91
+ name: c.name,
92
+ type: c.type,
93
+ notNull: c.notNull && !!d,
94
+ default: d,
95
+ ref: c.ref,
96
+ }
97
+ }
98
+
99
+ /** The `add column` statements the tables `stmts` create are missing where
100
+ * they already stand: `create table if not exists` does nothing to a table
101
+ * that is there, so a column a table gained after it was made arrives here.
102
+ * `held` is the schema as it stood before `stmts` ran (`catalogue`): a table
103
+ * it lacks was made whole by the first statement naming it, and one it holds
104
+ * as a statement declares it has every column, so neither is asked about. */
105
+ export let grow = (
106
+ driver: Driver,
107
+ stmts: Stmt[],
108
+ held: readonly SchemaObject[] = catalogue(driver),
109
+ ): Stmt[] => {
110
+ let stood = new Map(held.map((o) => [o.name, o.sql]))
111
+ let made = new Set<string>()
112
+ return stmts.flatMap((s) => {
113
+ if (s.t != 'create table') return []
114
+ if (!stood.has(s.name) && !made.has(s.name)) {
115
+ made.add(s.name)
116
+ return []
117
+ }
118
+ if (declares(stood.get(s.name) ?? null, s, driver.stored?.v)) return []
119
+ let has = new Set(
120
+ driver.query({ t: 'pragma', name: 'table_info', arg: s.name })
121
+ .map((r) => String(r.name)),
122
+ )
123
+ if (!has.size) return []
124
+ return s.cols.filter((c) => !has.has(c.name)).map((c) => ({
125
+ t: 'alter table' as const,
126
+ table: s.name,
127
+ add: added(c),
128
+ }))
129
+ })
130
+ }
131
+
132
+ /** Run `stmts`, each of which only adds what is missing, then the columns
133
+ * their standing tables lack, in one unit under the write lock. An index over
134
+ * a populated table is owed rather than built, and a unique index the rows
135
+ * already there break is left unbuilt and returned for the caller to report
136
+ * (./owe.ts). */
137
+ export let add = (driver: Driver, stmts: Stmt[]): Error[] =>
138
+ unit(driver, () => {
139
+ let held = catalogue(driver)
140
+ let left = build(driver, stmts)
141
+ for (let s of grow(driver, stmts, held)) driver.query(s)
142
+ return left
143
+ })
144
+
145
+ /** What a composed schema names, for {@link follow} to shed what a file holds
146
+ * beyond it: the tables and columns the store of `vocab` makes, and the tables
147
+ * `beside` makes. */
148
+ export type Named = { vocab: Vocab; beside?: readonly Stmt[] }
149
+
150
+ // Whether any row of `name` holds a value in its column `c`.
151
+ let valued = (driver: Driver, name: string, c: string): boolean => {
152
+ let v = driver.stored?.v
153
+ return driver.query(select({
154
+ cols: [lit(1)],
155
+ from: { t: 'table', name: v ? stored(v, name) : name, physical: true },
156
+ where: notNull(col(v ? stored(v, name, c) : c)),
157
+ limit: lit(1),
158
+ })).length > 0
159
+ }
160
+
161
+ /** A component's table, or a table and one of its columns. */
162
+ export type Seat = readonly [table: string, column?: string]
163
+
164
+ type Kind = 'index' | 'trigger' | 'view'
165
+ let dropOf = (kind: Kind, name: string): Stmt => ({
166
+ t: 'drop',
167
+ kind,
168
+ name,
169
+ ifExists: true,
170
+ })
171
+
172
+ // The statements dropping `seat`: each view and trigger naming its table, or
173
+ // each index, trigger and view naming the table and its column, which SQLite
174
+ // refuses a column's drop for while they stand and a table's drop leaves
175
+ // standing over nothing, and then the table or the column.
176
+ let unseating = (driver: Driver, [t, c]: Seat): Stmt[] => [
177
+ ...catalogue(driver).flatMap((o) => {
178
+ if (o.type == 'table' || o.sql == null || !c && o.type == 'index') {
179
+ return []
180
+ }
181
+ let said = words(o.sql)
182
+ let v = driver.stored?.v
183
+ let name = v ? stored(v, t) : t
184
+ let prop = c && v ? stored(v, t, c) : c
185
+ let names = said.has(name.toLowerCase()) &&
186
+ (!prop || said.has(prop.toLowerCase()))
187
+ return names ? [dropOf(o.type as Kind, o.name)] : []
188
+ }),
189
+ c
190
+ ? { t: 'alter table', table: t, drop: c }
191
+ : { t: 'drop', kind: 'table', name: t, ifExists: true },
192
+ ]
193
+
194
+ // The view or trigger SQLite says will not stand once a column goes, which a
195
+ // reading of the file did not find naming it: one over a table that is gone,
196
+ // or one that names the column in a way its words do not show.
197
+ let blocker = (e: unknown): Stmt | undefined => {
198
+ let said = e instanceof Error ? e.message : String(e)
199
+ let [, kind, name] = said.match(/error in (view|trigger) ([^\s:]+)/i) ?? []
200
+ return kind ? dropOf(kind.toLowerCase() as Kind, name) : undefined
201
+ }
202
+
203
+ // Run `stmts` in one unit; where SQLite names a view or a trigger that stops
204
+ // them, run them again with it dropped first, once for each such.
205
+ let run = (driver: Driver, stmts: Stmt[]): void => {
206
+ for (let first: Stmt[] = [];;) {
207
+ try {
208
+ return unit(driver, () => {
209
+ for (let s of [...first, ...stmts]) driver.query(s)
210
+ })
211
+ } catch (e) {
212
+ let more = blocker(e)
213
+ let again = more && first.some((s) => render(s).sql == render(more).sql)
214
+ if (!more || again) throw e
215
+ first = [...first, more]
216
+ }
217
+ }
218
+ }
219
+
220
+ // Where something may have changed what a store's install made (a drop that
221
+ // took an index, a trigger or a view, or a writer that keeps no print), the
222
+ // schema its receipt says goes, so the next install looks at the file rather
223
+ // than taking it as it left it. The planner statistics it keeps beside stay.
224
+ let unreceipted = (driver: Driver) => {
225
+ let held = installation(driver)
226
+ if (!held?.schema) return
227
+ if (held.statistics) analyzedAt(driver, '', held.statistics)
228
+ else meta(driver).del(SCHEMA)
229
+ }
230
+
231
+ // Where the file's schema moved under what it recorded (a drop), it stands at
232
+ // no print it recorded but `kept`: its tables are surveyed again, its install
233
+ // receipt goes, and so does every other print, so the next opener of any of
234
+ // them runs its pass over the file as it now is.
235
+ let moved = (driver: Driver, kept?: string) => {
236
+ recorded(driver)
237
+ unreceipted(driver)
238
+ for (let p of prints(driver)) {
239
+ if (p != kept) meta(driver).del(PRINTED + p)
240
+ }
241
+ }
242
+
243
+ /** Drop each of `seats` the file holds, a component's table or a column,
244
+ * whatever it holds, in one unit: for a host contracting what its words
245
+ * decided to let go of. Each view and trigger naming a table goes with it,
246
+ * and each index, trigger and view naming a column, which SQLite refuses the
247
+ * drop for while they stand; the next pass (`install`) makes again what the
248
+ * schema still wants of those. */
249
+ export let unseat = (driver: Driver, seats: readonly Seat[]): void => {
250
+ let held = seats.filter(([t, c]) => {
251
+ let cols = columns(driver, t)
252
+ return c ? cols.includes(c) : cols.length > 0
253
+ })
254
+ if (!held.length) return
255
+ unit(driver, () => {
256
+ for (let seat of held) run(driver, unseating(driver, seat))
257
+ moved(driver)
258
+ })
259
+ }
260
+
261
+ /** The drops of what a file holds that `named` stopped naming ({@link
262
+ * unseat}): a component table (./physical.ts `componentTables`) no statement
263
+ * makes and no word names, once it holds no rows, and a column the statement
264
+ * making its table lacks, once no row holds a value in it. A table that holds
265
+ * a row, a column that holds a value, and a column its table's own definition
266
+ * holds in place (./physical.ts `pinned`) stay as they stand. */
267
+ export let shed = (driver: Driver, { vocab, beside = [] }: Named): Seat[] => {
268
+ let made = new Map<string, Set<string>>()
269
+ for (let s of [...plan(vocab, {}, !!driver.file).raised, ...beside]) {
270
+ if (s.t != 'create table') continue
271
+ let cols = made.get(s.name) ?? new Set()
272
+ for (let c of s.cols) cols.add(c.name.toLowerCase())
273
+ made.set(s.name, cols)
274
+ }
275
+ let gone = componentTables(driver, [...made.keys(), ...vocab.all])
276
+ .filter((name) => !rowed(driver, name, 1))
277
+ let defined = new Map(catalogue(driver).map((o) => [o.name, o.sql ?? '']))
278
+ let unnamed = componentTables(driver, [], [...made.keys()]).flatMap(
279
+ (name) => {
280
+ let sql = defined.get(name)
281
+ let held = pinned(sql ?? '')
282
+ return columnsBy(driver, name, sql)
283
+ .filter((c) => {
284
+ let low = c.toLowerCase()
285
+ return !made.get(name)!.has(low) &&
286
+ !held.has(stored(vocab, name, c).toLowerCase()) &&
287
+ !valued(driver, name, c)
288
+ })
289
+ .map((c): Seat => [name, c])
290
+ },
291
+ )
292
+ return [...gone.map((name): Seat => [name]), ...unnamed]
293
+ }
294
+
295
+ // Drop one seat whole, or, where SQLite refuses it (a key, a unique column, a
296
+ // check on another column naming it), leave it standing. Whether it went.
297
+ let shedding = (driver: Driver, seat: Seat): boolean => {
298
+ try {
299
+ run(driver, unseating(driver, seat))
300
+ return true
301
+ } catch (e) {
302
+ if (/cannot drop|error in table/i.test(String(e))) return false
303
+ throw e
304
+ }
305
+ }
306
+
307
+ /** Bring a file to the composed schema `print` names: nothing, where the file
308
+ * has recorded it; otherwise `pass`, which adds what is missing, and then the
309
+ * record. A pass that left something it could not do (a table it could not
310
+ * fit) answers false, and the print stays unrecorded so the next opener tries
311
+ * again. True when the pass ran.
312
+ *
313
+ * Given what the schema names, the pass first sheds what the file holds
314
+ * beyond it ({@link shed}), which the pass makes again where the schema still
315
+ * wants it (a view or a trigger that named a column shed with it). What SQLite
316
+ * refuses to drop stands, and the pass runs over it. A file
317
+ * that shed something no longer stands at any other print it recorded, so
318
+ * those are forgotten: an opener of the vocabulary that named it runs its pass
319
+ * again. A host whose vocabulary may shrink for a while and grow back (an
320
+ * application's older release, a rollback away) gives nothing, and the file
321
+ * keeps all it holds. */
322
+ export let follow = (
323
+ driver: Driver,
324
+ print: string,
325
+ pass: () => boolean | void,
326
+ named?: Named,
327
+ ): boolean => {
328
+ if (printed(driver, print)) return false
329
+ if (named) {
330
+ unit(driver, () => {
331
+ let drops = shed(driver, named).filter((seat) => shedding(driver, seat))
332
+ if (!drops.length) return
333
+ moved(driver, print)
334
+ })
335
+ }
336
+ if (pass() === false) return true
337
+ unit(
338
+ driver,
339
+ () => meta(driver).set(PRINTED + print, new Date().toISOString()),
340
+ )
341
+ return true
342
+ }
343
+
344
+ /** Forget that a file stands at `print`, so its next opener runs the pass
345
+ * again: for a host whose file something that keeps no print may have changed,
346
+ * the way a yaks.app store's older release, still a rollback away, installs
347
+ * over whatever a print stands for. The store's own install receipt is
348
+ * forgotten with it, so that install looks at the file again too. */
349
+ export let forget = (driver: Driver, print: string): void => {
350
+ if (!printed(driver, print) && !installed(driver)) return
351
+ unit(driver, () => {
352
+ meta(driver).del(PRINTED + print)
353
+ unreceipted(driver)
354
+ })
355
+ }
356
+
357
+ /**
358
+ * What a reader binds over a file no writer has brought to its vocabulary yet:
359
+ * each stored property whose column the file's table lacks, read as null, the
360
+ * way an entity reads a property it was never given, and each component whose
361
+ * table the file lacks, read as a table no entity wears (@yaks/sql
362
+ * `absent`). A reader never changes the schema, so it reads what the file
363
+ * holds. Nothing, where the store's tables are as this vocabulary makes them,
364
+ * which costs the store's print and one read of `server_meta`.
365
+ */
366
+ export let lacking = (
367
+ driver: Driver,
368
+ vocab: Vocab,
369
+ derived: Derived = {},
370
+ physical = false,
371
+ ): { derived: Derived; absent: string[] } => {
372
+ let mark = installed(driver)?.split(' ')[0]
373
+ // Installed as this vocabulary says, the file lacks no column, and no table
374
+ // but those of the words nothing has written yet (./raise.ts).
375
+ if (!physical && mark == plan(vocab, derived, !!driver.file).print) {
376
+ return { derived: {}, absent: unraised(driver, vocab) }
377
+ }
378
+ // Only a table declared otherwise than the vocabulary does can lack a
379
+ // column, so only those are asked about, two statements each, rather than
380
+ // every table on every open.
381
+ let kept = exact(driver, vocab)
382
+ let was = behind(driver, vocab, kept)
383
+ let held = tables(vocab)
384
+ return {
385
+ absent: held.filter((comp) => !kept.has(comp) && !(comp in was)),
386
+ derived: Object.fromEntries(
387
+ held.filter((comp) => comp in was).flatMap((comp) => {
388
+ let has = new Set(was[comp].cols.map((r) => String(r.name)))
389
+ return vocab.props(comp).map((p) => vocab.prop(comp, p)!)
390
+ .filter((c) =>
391
+ !c.computed && !has.has(field(c.prop)) &&
392
+ !derived[`${comp}.${c.prop}`]
393
+ )
394
+ .map((c) => [`${comp}.${c.prop}`, {
395
+ tag: tagOf(c),
396
+ expr: () => lit(null),
397
+ }])
398
+ }),
399
+ ),
400
+ }
401
+ }
@@ -0,0 +1,166 @@
1
+ // A branch's writes touch its version rows, leaving main's rows alone.
2
+ import { among, and, col, eq, exists, lit, select, table, val } from "@yaks/sql";
3
+ import { stored } from "./history.js";
4
+ import { beside, BRANCH, FROM, TO } from "./history-shapes.js";
5
+ // An insert's query with more columns after its own.
6
+ let appended = (q, es)=>{
7
+ if (q.t != 'select') throw new Error('a versioned insert from a compound');
8
+ return {
9
+ ...q,
10
+ cols: [
11
+ ...q.cols ?? [],
12
+ ...es
13
+ ]
14
+ };
15
+ };
16
+ // The entities an insert names: its rows' owners, or its query's.
17
+ let entities = (w)=>{
18
+ let at = w.cols?.indexOf('entity') ?? -1;
19
+ if (at < 0) {
20
+ throw new Error(`a versioned insert into ${w.into} names no owner`);
21
+ }
22
+ if (w.rows) return w.rows.map((r)=>r[at]);
23
+ if (w.q?.t != 'select') throw new Error('a versioned insert from a compound');
24
+ return {
25
+ ...w.q,
26
+ with: w.q.with ?? w.with,
27
+ cols: [
28
+ w.q.cols[at]
29
+ ]
30
+ };
31
+ };
32
+ // ---- writes on a branch ----
33
+ // The branch's open row of the entity a write's condition names.
34
+ let open = (branch)=>and(eq(col(BRANCH), val(branch)), eq(col(TO), lit(0)));
35
+ /**
36
+ * A write on branch `b`, as a write to the branch's rows beside. Every read in
37
+ * it names the live table, which on a branch's connection is the branch's view
38
+ * of it (./mode.ts), so it sees the branch.
39
+ *
40
+ * Before any write, each entity's component as the branch sees it is copied
41
+ * into an open row of the branch's own, where it has none: an insert then
42
+ * lands on that row as it would on main's, an update changes it, and a removal
43
+ * closes it, so it goes on hiding main's. A branch keeps no versions of its
44
+ * own: its rows are what it holds now, and what it removed.
45
+ */ export let branched = (vocab, comp, w, b, tx)=>{
46
+ let cols = stored(vocab, comp);
47
+ let to = beside(comp);
48
+ let seed = (where)=>({
49
+ t: 'insert',
50
+ or: 'ignore',
51
+ into: to,
52
+ cols: [
53
+ 'entity',
54
+ ...cols,
55
+ BRANCH,
56
+ FROM,
57
+ TO
58
+ ],
59
+ q: select({
60
+ cols: [
61
+ col('entity'),
62
+ ...cols.map((c)=>col(c)),
63
+ val(b),
64
+ val(tx),
65
+ lit(0)
66
+ ],
67
+ from: table(comp),
68
+ where
69
+ })
70
+ });
71
+ if (w.t == 'insert') {
72
+ let e = entities(w);
73
+ return {
74
+ before: [
75
+ seed(among(col('entity'), e))
76
+ ],
77
+ write: {
78
+ ...w,
79
+ into: to,
80
+ cols: [
81
+ ...w.cols,
82
+ BRANCH,
83
+ FROM,
84
+ TO
85
+ ],
86
+ ...w.rows ? {
87
+ rows: w.rows.map((r)=>[
88
+ ...r,
89
+ val(b),
90
+ val(tx),
91
+ lit(0)
92
+ ])
93
+ } : {},
94
+ ...w.q ? {
95
+ q: appended(w.q, [
96
+ val(b),
97
+ val(tx),
98
+ lit(0)
99
+ ])
100
+ } : {},
101
+ ...w.upsert ? {
102
+ upsert: w.upsert.map((u)=>({
103
+ ...u,
104
+ on: [
105
+ col('entity'),
106
+ col(BRANCH),
107
+ col(TO)
108
+ ]
109
+ }))
110
+ } : {}
111
+ }
112
+ };
113
+ }
114
+ let where = w.where ?? lit(true);
115
+ let mine = and(where, open(b));
116
+ if (w.t == 'update') {
117
+ return {
118
+ before: [
119
+ seed(where)
120
+ ],
121
+ write: {
122
+ t: 'update',
123
+ table: to,
124
+ set: {
125
+ ...w.set,
126
+ [FROM]: val(tx)
127
+ },
128
+ where: mine,
129
+ ...w.returning ? {
130
+ returning: w.returning
131
+ } : {}
132
+ }
133
+ };
134
+ }
135
+ // A row this transaction both opened and closed already has its closed
136
+ // twin at `tx`; it goes. Any other open row is closed where it stands.
137
+ let twin = exists(select({
138
+ cols: [
139
+ lit(1)
140
+ ],
141
+ from: table(to, '__twin'),
142
+ where: and(eq(col('entity', '__twin'), col('entity', to)), eq(col(BRANCH, '__twin'), val(b)), eq(col(TO, '__twin'), val(tx)))
143
+ }));
144
+ return {
145
+ before: [
146
+ seed(where),
147
+ {
148
+ t: 'delete',
149
+ from: to,
150
+ where: and(mine, twin)
151
+ }
152
+ ],
153
+ write: {
154
+ t: 'update',
155
+ table: to,
156
+ set: {
157
+ [TO]: val(tx)
158
+ },
159
+ where: mine,
160
+ ...w.returning ? {
161
+ returning: w.returning
162
+ } : {}
163
+ }
164
+ };
165
+ };
166
+ //# sourceMappingURL=history-branch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history-branch.js","sources":["./history-branch.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,SACE,KAAK,EACL,GAAG,EACH,GAAG,EACH,EAAE,EACF,MAAM,EAEN,GAAG,EAEH,MAAM,EAEN,KAAK,EACL,GAAG,yBACwB;AAE7B,SAAoB,MAAM,uBAAsB;AAChD,SAAS,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,8BAA6B;AAI9D,qDAAqD;AACrD,IAAI,WAAW,CAAC,GAA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