@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/owe.js ADDED
@@ -0,0 +1,719 @@
1
+ // Work a schema change leaves whose cost grows with rows (D-121389): an index
2
+ // over a populated table, a table's refit, filling a text index. The pass that
3
+ // brings a file to its schema (./follow.ts) does what costs the same at any
4
+ // size and writes the rest down here, in `server_meta` as
5
+ // `owed:<kind>:<name>`: a JSON value holding the statements that do it and
6
+ // how far it has got. The statements are data, so a process whose vocabulary
7
+ // moved on can still finish what an older one owed.
8
+ //
9
+ // One process at a time works it off ({@link tend}), one window per unit, each
10
+ // holding the write lock for about a tenth of a second on the box's copy; on
11
+ // the box that is whichever process serves the effects role, under the
12
+ // `@yaks/sqlite/schema` lease (packages/cli/host.ts). Opening never waits for
13
+ // it, and the graph serves the shape it holds meanwhile: a query runs without
14
+ // the index it will have. A window that fails is reported and tried again an
15
+ // hour later, and nothing refuses an open on its account.
16
+ //
17
+ // The same process does a file's upkeep ({@link Daily}): the planner
18
+ // statistics an install or the day owes, a table a window, and
19
+ // whatever a host adds, such as the box's check of its text indexes. It also
20
+ // gives back the pages a bulk delete freed ({@link reclaim}), so the file
21
+ // shrinks without a VACUUM. Opening does none of it.
22
+ //
23
+ // A file in memory belongs to one process, which has nobody to owe: its work
24
+ // is done at once, as it was before any of this.
25
+ import { and, as, catalogue, col, count, eq, erect, fn, from, gt, le, lit, lt, op, over, select, stored, sub, table, val } from "@yaks/sql/core";
26
+ import { analyzed, analyzing, carried, counted, needless, tallied, tally } from "./ddl.js";
27
+ import { BUILDING, META } from "./layout.js";
28
+ import { analyzedAt, installation, meta, under } from "./meta.js";
29
+ import { unit } from "./unit.js";
30
+ /** The prefix of an owed piece of work's `server_meta` key. */ export let OWED = 'owed:';
31
+ /** The lease the process working owed work off holds. */ export let SCHEMA_DUTY = '@yaks/sqlite/schema';
32
+ /** A table holding this many rows gets a new index as owed work: on the
33
+ * box's copy an index over 10,000 rows builds in about 10 ms, and over its
34
+ * 4,057,139 `created` rows in 2.6 s. */ export let BIG = 10_000;
35
+ /** The rows one window fills into a text index. Its time goes on the text,
36
+ * not the rows: on the box's copy, whose `entry_fts` bodies run about 5 KB,
37
+ * 1,000 rows took 164 ms a window and up to 515 ms, and its 356,025 rows
38
+ * take 39 s in one `rebuild`. */ export let FILL = 500;
39
+ /** The text one window fills into a text index, past its first row: a
40
+ * substring index (@yaks/fts `contains`) takes about 190 ms a MiB, and 500 of
41
+ * the box's transcript texts held a window for up to 6.8 s. */ export let FILL_TEXT = 1 << 20;
42
+ /** The rows one window copies into a table being rebuilt: 5.6 ms for 20,000
43
+ * of the box's `created`, whose rebuild in one unit holds the lock 10.2 s. */ export let COPY = 20_000;
44
+ /** The rows one window deletes from a rebuilt table's old rows: about 65 ms
45
+ * on the box's copy. */ export let CLEAR = 10_000;
46
+ /** The rows one window counts of a table whose statistics are its row count
47
+ * (./ddl.ts `counted`): one leaf page a row at worst, so 2 MB of the box's
48
+ * 4 KiB pages. On its 10 GB file under a load of 25, a window over a text
49
+ * index's data took 0.1 to 0.9 s, where `ANALYZE` read a whole table in one
50
+ * window and held the write lock 20.4 s (bug bace8585). */ export let COUNT = 500;
51
+ /** The free pages a file keeps for its next writes to reuse; past these,
52
+ * {@link reclaim} gives the rest back. 64 MiB of the box's 4 KiB pages. */ export let SLACK = 16_384;
53
+ /** The pages one window gives back: on a 660 MB file of 4 KiB pages with a
54
+ * third of its rows deleted in runs, 1,000 pages took 28 ms a window, and up
55
+ * to 176 ms with the checkpoint that followed. */ export let RECLAIM = 1_000;
56
+ export let SIZES = {
57
+ big: BIG,
58
+ fill: FILL,
59
+ fillText: FILL_TEXT,
60
+ copy: COPY,
61
+ clear: CLEAR,
62
+ slack: SLACK,
63
+ reclaim: RECLAIM,
64
+ count: COUNT
65
+ };
66
+ /** How long a window that failed waits before it is tried again. */ export let RETRY = 3_600_000;
67
+ /** How often a file's upkeep ({@link Daily}) is done. */ export let DAY = 86_400_000;
68
+ let key = (w)=>`${OWED}${w.kind}:${w.name}`;
69
+ /** Write `work` down, replacing whatever was owed under its name. */ export let owe = (driver, work)=>meta(driver).set(key(work), JSON.stringify(work));
70
+ // The order owed work is done in: a missing index first, since queries run
71
+ // without it meanwhile, and a rebuilt table's old rows last, since nothing
72
+ // reads them.
73
+ let order = [
74
+ 'index',
75
+ 'fill',
76
+ 'refit',
77
+ 'clear'
78
+ ];
79
+ /** Everything this file owes, in the order it is worked off, then by name. */ export let owed = (driver)=>catalogue(driver).some((o)=>o.name == META) ? under(driver, OWED).map(([, v])=>JSON.parse(v)).sort((a, b)=>order.indexOf(a.kind) - order.indexOf(b.kind)) : [];
80
+ /** Whether `table` holds at least `n` rows, counting no further than that. */ export let holds = (driver, name, n)=>Number(driver.query(select({
81
+ cols: [
82
+ as(count(), 'n')
83
+ ],
84
+ from: from(select({
85
+ cols: [
86
+ lit(1)
87
+ ],
88
+ from: table(name),
89
+ limit: lit(n)
90
+ }), 'r')
91
+ }))[0]?.n ?? 0) >= n;
92
+ /** Whether the engine refused a unique index because rows already in its
93
+ * table share a key. */ let collides = (e)=>e instanceof Error && /unique constraint failed/i.test(e.message);
94
+ /** What is reported of a unique index the rows in its table break: it is not
95
+ * built, and the table serves without it. */ export let unbuilt = (s, e)=>new Error(`${s.name} is not built: rows in ${s.on} share its key and need a ` + `migration that prepares them (${e instanceof Error ? e.message : e})`, {
96
+ cause: e
97
+ });
98
+ /**
99
+ * Run `stmts` as `erect` does, owing each index a file lacks over a table of
100
+ * {@link BIG} rows or more instead of building it here. A new unique index the
101
+ * rows already in its table break is left unbuilt and returned, so the file
102
+ * opens with the shape it holds and the caller reports it; a failed statement
103
+ * undoes only itself, so the rest stands.
104
+ */ export let build = (driver, stmts, sizes = SIZES, deferred = false)=>{
105
+ let names = new Set(catalogue(driver).map((o)=>o.name));
106
+ let owing = (!!driver.file || deferred) && names.has(META);
107
+ let now = stmts.filter((s)=>{
108
+ if (!owing || s.t != 'create index' || names.has(s.name)) return true;
109
+ if (!names.has(s.on) || !holds(driver, s.on, deferred ? 1 : sizes.big)) {
110
+ return true;
111
+ }
112
+ owe(driver, {
113
+ kind: 'index',
114
+ name: s.name,
115
+ stmt: s
116
+ });
117
+ return false;
118
+ });
119
+ let unique = (s)=>s.t == 'create index' && !!s.unique && !names.has(s.name);
120
+ erect(driver, now.filter((s)=>!unique(s)));
121
+ return now.filter(unique).flatMap((s)=>{
122
+ try {
123
+ driver.query(s);
124
+ return [];
125
+ } catch (e) {
126
+ if (!collides(e)) throw e;
127
+ return [
128
+ unbuilt(s, e)
129
+ ];
130
+ }
131
+ });
132
+ };
133
+ // A daily's mark: when it is next due, and the revision that set it.
134
+ let marked = (d, ms)=>new Date(ms).toISOString() + (d.revision ? `#${d.revision}` : '');
135
+ let due = (d, at, now)=>{
136
+ if (!at) return true;
137
+ let [when, revision] = at.split('#');
138
+ return (revision ?? '') != String(d.revision ?? '') || Date.parse(when) <= now;
139
+ };
140
+ let DAILY = 'daily:';
141
+ let CHORE = 'chore:';
142
+ // One window of the first of `chores` that is not put off and finds work to
143
+ // do; one that throws is put off an hour.
144
+ let chore = (driver, chores, now)=>{
145
+ let m = meta(driver);
146
+ for (let c of chores){
147
+ let name = CHORE + c.name;
148
+ let at = m.get(name);
149
+ if (at && Date.parse(at) > now) continue;
150
+ try {
151
+ let did = unit(driver, ()=>{
152
+ if (at) m.del(name);
153
+ return c.run(driver);
154
+ });
155
+ if (did) return {
156
+ name,
157
+ done: false
158
+ };
159
+ } catch (error) {
160
+ unit(driver, ()=>m.set(name, new Date(now + RETRY).toISOString()));
161
+ return {
162
+ name,
163
+ error
164
+ };
165
+ }
166
+ }
167
+ };
168
+ /** Planner statistics (./ddl.ts `analyzed`): due once a day, and as soon as
169
+ * an index or a rebuilt table is in place, when the tables that lack them, or
170
+ * all that hold rows once the file has grown tenfold, are owed an analysis,
171
+ * which {@link work} does a table a window. */ export let statistics = {
172
+ name: 'statistics',
173
+ // 2: tables whose statistics say they hold a few rows (./ddl.ts `small`).
174
+ revision: 2,
175
+ run: (driver)=>{
176
+ let receipt = installation(driver);
177
+ let owed = analyzed(driver, receipt?.statistics);
178
+ if (owed && receipt) analyzedAt(driver, receipt.schema, owed);
179
+ }
180
+ };
181
+ /** The `server_meta` key of {@link analyze}: when it is next tried, after a
182
+ * window that failed. */ export let ANALYZING = 'analyze';
183
+ /**
184
+ * Take one window of the statistics of the first table the receipt owes them,
185
+ * and answer how many stay owed; undefined when none is. A table that is
186
+ * counted (./ddl.ts `counted`) has `count` rows read in a snapshot, holding
187
+ * no lock, and the receipt written after in a unit of its own; any other is
188
+ * analyzed in its own unit.
189
+ */ export let analyze = (driver, count = COUNT)=>{
190
+ let window = unit(driver, ()=>{
191
+ let statistics = installation(driver)?.statistics;
192
+ let first = statistics?.owed?.[0];
193
+ if (first == null || !counted(driver, first)) return;
194
+ return tally(driver, statistics, count);
195
+ }, 'read');
196
+ return unit(driver, ()=>{
197
+ let receipt = installation(driver);
198
+ let statistics = receipt?.statistics;
199
+ if (!receipt || !statistics?.owed?.length) return;
200
+ let next = !counted(driver, statistics.owed[0]) ? analyzing(driver, statistics, 1) : window ? tallied(driver, statistics, window) : statistics;
201
+ if (next != statistics) analyzedAt(driver, receipt.schema, next);
202
+ return next.owed?.length ?? 0;
203
+ });
204
+ };
205
+ // One window of the planner statistics the receipt owes; one that throws is
206
+ // put off an hour.
207
+ let analysis = (driver, now, sizes)=>{
208
+ if (!installation(driver)?.statistics?.owed?.length) return;
209
+ let at = meta(driver).get(ANALYZING);
210
+ if (at && Date.parse(at) > now) return;
211
+ try {
212
+ let left = analyze(driver, sizes.count);
213
+ return left == null ? undefined : {
214
+ name: ANALYZING,
215
+ done: !left
216
+ };
217
+ } catch (error) {
218
+ unit(driver, ()=>meta(driver).set(ANALYZING, new Date(now + RETRY).toISOString()));
219
+ return {
220
+ name: ANALYZING,
221
+ error
222
+ };
223
+ }
224
+ };
225
+ /**
226
+ * Do one window, in one unit: of the first owed work that is due, else of
227
+ * the first of `chores` with work to do, else of the first table owed an
228
+ * analysis ({@link analyze}), else of giving free pages back
229
+ * ({@link reclaim}), else of the first of `daily` that is due. Undefined
230
+ * when nothing is. A window that throws leaves its work as it was, marked to
231
+ * be tried again in an hour, and says why.
232
+ */ export let work = (driver, now = Date.now(), daily = [], sizes = SIZES, chores = [])=>{
233
+ let due = owed(driver).find((w)=>!w.next || Date.parse(w.next) <= now);
234
+ if (!due) {
235
+ return chore(driver, chores, now) ?? analysis(driver, now, sizes) ?? reclaim(driver, now, sizes) ?? upkeep(driver, daily, now);
236
+ }
237
+ try {
238
+ return unit(driver, ()=>({
239
+ name: key(due),
240
+ done: step(driver, due, sizes)
241
+ }));
242
+ } catch (error) {
243
+ unit(driver, ()=>owe(driver, {
244
+ ...due,
245
+ error: error instanceof Error ? error.message : String(error),
246
+ next: new Date(now + RETRY).toISOString()
247
+ }));
248
+ return {
249
+ name: key(due),
250
+ error
251
+ };
252
+ }
253
+ };
254
+ let pragma = (driver, name)=>Number(Object.values(driver.query({
255
+ t: 'pragma',
256
+ name
257
+ })[0] ?? {})[0] ?? 0);
258
+ /** The `server_meta` key of {@link reclaim}: when it is next tried, after a
259
+ * window that failed. */ export let RECLAIMING = 'reclaim';
260
+ /**
261
+ * Give back the free pages past {@link SLACK}, at most {@link RECLAIM} a
262
+ * window: SQLite moves pages from the end of the file into the free ones and
263
+ * cuts the end off, which the next checkpoint writes to the file. Only a file
264
+ * in incremental mode can (./db.ts `open`); one in another mode, or in
265
+ * memory, has nothing to give. Undefined when nothing is past the slack; one
266
+ * that throws is put off an hour.
267
+ */ export let reclaim = (driver, now = Date.now(), sizes = SIZES)=>{
268
+ if (!driver.file || pragma(driver, 'auto_vacuum') != 2) return;
269
+ let past = pragma(driver, 'freelist_count') - sizes.slack;
270
+ if (past <= 0) return;
271
+ let m = meta(driver);
272
+ let at = m.get(RECLAIMING);
273
+ if (at && Date.parse(at) > now) return;
274
+ let n = Math.min(past, sizes.reclaim);
275
+ try {
276
+ unit(driver, ()=>driver.query({
277
+ t: 'pragma',
278
+ name: 'incremental_vacuum',
279
+ arg: n
280
+ }));
281
+ return {
282
+ name: RECLAIMING,
283
+ done: n == past
284
+ };
285
+ } catch (error) {
286
+ unit(driver, ()=>m.set(RECLAIMING, new Date(now + RETRY).toISOString()));
287
+ return {
288
+ name: RECLAIMING,
289
+ error
290
+ };
291
+ }
292
+ };
293
+ /** Do the first of `daily` that is due, and put it off a day; one that throws
294
+ * is put off an hour. Undefined when none is due. */ export let upkeep = (driver, daily, now)=>{
295
+ let m = meta(driver);
296
+ let next = daily.find((d)=>due(d, m.get(DAILY + d.name), now));
297
+ if (!next) return;
298
+ let name = DAILY + next.name;
299
+ let later = (ms)=>m.set(name, marked(next, now + ms));
300
+ try {
301
+ unit(driver, ()=>{
302
+ next.run(driver);
303
+ later(DAY);
304
+ });
305
+ return {
306
+ name,
307
+ done: true
308
+ };
309
+ } catch (error) {
310
+ unit(driver, ()=>later(RETRY));
311
+ return {
312
+ name,
313
+ error
314
+ };
315
+ }
316
+ };
317
+ // The highest id among the next `n` rows of `source` past `cursor`, or null
318
+ // when there are none: where the window that takes them ends. A window's
319
+ // bounds are bound, never written into its text, so every window of one piece
320
+ // of work runs one prepared statement, where a text of its own would be
321
+ // compiled once and kept, pushing what a store repeats out of the driver's
322
+ // bounded cache.
323
+ let next = (driver, source, cursor, n)=>{
324
+ let [{ hi }] = driver.query(select({
325
+ cols: [
326
+ as(fn('max', col('entity')), 'hi')
327
+ ],
328
+ from: from(select({
329
+ cols: [
330
+ col('entity')
331
+ ],
332
+ from: table(source),
333
+ where: gt(col('entity'), val(cursor)),
334
+ order: [
335
+ col('entity')
336
+ ],
337
+ limit: val(n)
338
+ }), 'w')
339
+ }));
340
+ return hi == null ? null : Number(hi);
341
+ };
342
+ // The highest id among the next rows of a text index's source past `cursor`,
343
+ // at most `n` of them and as many as the text before each leaves under
344
+ // `text`, or null when there are none.
345
+ let reach = (driver, w, n, text)=>{
346
+ let size = (w.fields ?? w.props).map((p)=>fn('coalesce', fn('length', col(p)), lit(0))).reduce((a, b)=>op('+', a, b));
347
+ let rows = select({
348
+ cols: [
349
+ col('entity'),
350
+ as(size, 'size')
351
+ ],
352
+ from: table(w.source),
353
+ where: gt(col('entity'), val(w.cursor)),
354
+ order: [
355
+ col('entity')
356
+ ],
357
+ limit: val(n)
358
+ });
359
+ let before = op('-', over(fn('sum', col('size')), undefined, [
360
+ col('entity')
361
+ ]), col('size'));
362
+ let [{ hi }] = driver.query(select({
363
+ cols: [
364
+ as(fn('max', col('entity')), 'hi')
365
+ ],
366
+ from: from(select({
367
+ cols: [
368
+ col('entity'),
369
+ as(before, 'before')
370
+ ],
371
+ from: from(rows, 'w')
372
+ }), 'r'),
373
+ where: lt(col('before'), val(text))
374
+ }));
375
+ return hi == null ? null : Number(hi);
376
+ };
377
+ // The rows of `source` a window takes: past `cursor`, up to `hi`.
378
+ let window = (cursor, hi)=>and(gt(col('entity'), val(cursor)), le(col('entity'), val(hi)));
379
+ // What the triggers of work being done behind a cursor read it through: the
380
+ // owed row itself, so there is one copy of how far it has got. A row that is
381
+ // gone reads as every row passed.
382
+ let cursorOf = (w)=>fn('coalesce', sub(select({
383
+ cols: [
384
+ fn('json_extract', col('v'), lit('$.cursor'))
385
+ ],
386
+ from: table(META),
387
+ where: eq(col('k'), lit(key(w)))
388
+ })), lit(Number.MAX_SAFE_INTEGER));
389
+ /** The name a table is rebuilt under, and the name its old rows wait under
390
+ * to be cleared. Neither is a component table (./physical.ts). */ export let building = (comp)=>BUILDING + comp;
391
+ export let leaving = (comp)=>`_yaks_old_${comp}`;
392
+ // The triggers keeping a table being rebuilt in step with the rows its cursor
393
+ // has passed: a write behind the cursor is written to it too, and one ahead is
394
+ // read when its window comes.
395
+ let steps = (comp, w)=>{
396
+ let into = w.table.name;
397
+ let r = {
398
+ changed: w.changed
399
+ };
400
+ let passed = (row)=>le(col('entity', row), cursorOf(w));
401
+ let put = {
402
+ t: 'insert',
403
+ or: 'replace',
404
+ into,
405
+ cols: w.cols,
406
+ rows: [
407
+ w.cols.map((c)=>carried(r, c, 'new'))
408
+ ]
409
+ };
410
+ let trigger = (event, body)=>({
411
+ t: 'create trigger',
412
+ name: `${into}_${event}`,
413
+ ifNot: true,
414
+ timing: 'after',
415
+ event,
416
+ on: comp,
417
+ when: passed(event == 'delete' ? 'old' : 'new'),
418
+ body
419
+ });
420
+ return [
421
+ trigger('insert', [
422
+ put
423
+ ]),
424
+ trigger('update', [
425
+ put
426
+ ]),
427
+ trigger('delete', [
428
+ {
429
+ t: 'delete',
430
+ from: into,
431
+ where: eq(col('entity'), col('entity', 'old'))
432
+ }
433
+ ])
434
+ ];
435
+ };
436
+ // Give up rebuilding a table: the triggers keeping the new one in step, and
437
+ // the new one. A table its vocabulary dropped has taken the triggers already.
438
+ let quit = (driver, w)=>{
439
+ for (let t of steps(w.name, w)){
440
+ driver.query({
441
+ t: 'drop',
442
+ kind: 'trigger',
443
+ name: t.name,
444
+ ifExists: true
445
+ });
446
+ }
447
+ driver.query({
448
+ t: 'drop',
449
+ kind: 'table',
450
+ name: w.table.name,
451
+ ifExists: true
452
+ });
453
+ };
454
+ // Each kind's window, inside its unit; true when the work is finished, and
455
+ // its row then gone.
456
+ let windows = {
457
+ index: (driver, w, here)=>{
458
+ // A table a later vocabulary dropped takes its owed index with it, and
459
+ // one owed before the install stopped building it is forgotten.
460
+ if (here.has(w.stmt.on) && !needless(driver, w.stmt)) {
461
+ driver.query({
462
+ ...w.stmt,
463
+ ifNot: true
464
+ });
465
+ }
466
+ return true;
467
+ },
468
+ fill: (driver, w, here, { fill, fillText })=>{
469
+ // An index a later pass rebuilt whole, or dropped, is no longer this
470
+ // work's.
471
+ let guarded = here.get(w.triggers[0]?.name)?.sql?.includes(key(w));
472
+ if (!here.has(w.name) || !guarded) return true;
473
+ let hi = reach(driver, w, fill, fillText);
474
+ // Filled: the triggers keeping it behind the cursor give way to the ones
475
+ // it keeps for good, each under the name it just gave up.
476
+ if (hi == null) {
477
+ for (let t of w.triggers){
478
+ driver.query({
479
+ t: 'drop',
480
+ kind: 'trigger',
481
+ name: t.name,
482
+ ifExists: true
483
+ });
484
+ driver.query(t);
485
+ }
486
+ return true;
487
+ }
488
+ driver.query({
489
+ t: 'insert',
490
+ into: w.name,
491
+ cols: [
492
+ 'rowid',
493
+ ...w.props
494
+ ],
495
+ q: select({
496
+ cols: [
497
+ col('entity'),
498
+ ...(w.fields ?? w.props).map((p)=>fn('coalesce', col(p), lit('')))
499
+ ],
500
+ from: table(w.source),
501
+ where: window(w.cursor, hi)
502
+ })
503
+ });
504
+ owe(driver, {
505
+ ...w,
506
+ cursor: hi
507
+ });
508
+ return false;
509
+ },
510
+ refit: (driver, w, here, sizes)=>{
511
+ let comp = w.name, into = w.table.name;
512
+ let v = driver.stored?.v;
513
+ let old = leaving(v ? stored(v, comp) : comp);
514
+ if (!here.has(comp) || !here.has(into)) return quit(driver, w), true;
515
+ let hi = next(driver, comp, w.cursor, sizes.copy);
516
+ if (hi != null) {
517
+ let r = {
518
+ changed: w.changed
519
+ };
520
+ driver.query({
521
+ t: 'insert',
522
+ into,
523
+ cols: w.cols,
524
+ q: select({
525
+ cols: w.cols.map((c)=>carried(r, c, comp)),
526
+ from: table(comp),
527
+ where: window(w.cursor, hi)
528
+ })
529
+ });
530
+ owe(driver, {
531
+ ...w,
532
+ cursor: hi
533
+ });
534
+ return false;
535
+ }
536
+ // Every row is across: the swap, in this one unit.
537
+ if (here.has(old)) throw new Error(`${comp} waits for ${old} to clear`);
538
+ let filling = owed(driver).find((o)=>o.kind == 'fill' && o.triggers.some((t)=>t.on == comp));
539
+ if (filling) throw new Error(`${comp} waits for ${filling.name} to fill`);
540
+ for (let o of here.values()){
541
+ if (o.tbl_name != comp || o.sql == null) continue;
542
+ if (o.type != 'trigger' && o.type != 'index') continue;
543
+ driver.query({
544
+ t: 'drop',
545
+ kind: o.type,
546
+ name: o.name
547
+ });
548
+ }
549
+ // Renamed without rewriting the views and triggers that name the table,
550
+ // which name the new one once it holds the name.
551
+ let legacy = (value)=>driver.query({
552
+ t: 'pragma',
553
+ name: 'legacy_alter_table',
554
+ value
555
+ });
556
+ legacy('on');
557
+ try {
558
+ driver.query({
559
+ t: 'alter table',
560
+ table: comp,
561
+ rename: old
562
+ });
563
+ driver.query({
564
+ t: 'alter table',
565
+ table: into,
566
+ rename: comp
567
+ });
568
+ } finally{
569
+ legacy('off');
570
+ }
571
+ // An index over the rows is built in a window of its own.
572
+ build(driver, w.after, sizes);
573
+ owe(driver, {
574
+ kind: 'clear',
575
+ name: old
576
+ });
577
+ return true;
578
+ },
579
+ clear: (driver, w, here, { clear })=>{
580
+ if (!here.has(w.name)) return true;
581
+ let hi = next(driver, w.name, Number.MIN_SAFE_INTEGER, clear);
582
+ if (hi == null) {
583
+ driver.query({
584
+ t: 'drop',
585
+ kind: 'table',
586
+ name: w.name
587
+ });
588
+ return true;
589
+ }
590
+ driver.query({
591
+ t: 'delete',
592
+ from: w.name,
593
+ where: le(col('entity'), val(hi))
594
+ });
595
+ return false;
596
+ }
597
+ };
598
+ // One window of `w`, inside its unit; true when the work is finished, and its
599
+ // row then gone. An index or a rebuilt table in place makes the statistics
600
+ // due, since the planner has none for it yet.
601
+ let step = (driver, w, sizes)=>{
602
+ let here = new Map(catalogue(driver).map((o)=>[
603
+ o.name,
604
+ o
605
+ ]));
606
+ let done = windows[w.kind](driver, w, here, sizes);
607
+ if (done) meta(driver).del(key(w));
608
+ if (done && (w.kind == 'index' || w.kind == 'refit')) {
609
+ meta(driver).del(DAILY + statistics.name);
610
+ }
611
+ return done;
612
+ };
613
+ /**
614
+ * The {@link Filler} @yaks/fts `adopt` hands a new or changed text index to:
615
+ * on a file, an index whose content holds more than one window's rows is owed
616
+ * and filled {@link FILL} rows at a time; a smaller one is rebuilt at once.
617
+ */ export let filler = (driver, sizes = SIZES)=>({
618
+ pending: (fts)=>owed(driver).some((w)=>w.kind == 'fill' && w.name == fts) ? cursorOf({
619
+ kind: 'fill',
620
+ name: fts
621
+ }) : undefined,
622
+ owe: ({ fts, ...fill })=>{
623
+ let here = catalogue(driver).some((o)=>o.name == META);
624
+ if (!driver.file || !here || !holds(driver, fill.source, sizes.fill + 1)) {
625
+ return;
626
+ }
627
+ owe(driver, {
628
+ kind: 'fill',
629
+ name: fts,
630
+ ...fill,
631
+ cursor: 0
632
+ });
633
+ return cursorOf({
634
+ kind: 'fill',
635
+ name: fts
636
+ });
637
+ }
638
+ });
639
+ /**
640
+ * Take on rebuilding `comp` as `r` says, on a file where it holds {@link BIG}
641
+ * rows or more: the table it is built as and the triggers keeping it in step,
642
+ * made now, and the copying owed. `after` is what to raise on the new table
643
+ * once it holds the name: the indexes and triggers the composed schema puts
644
+ * on it. A rebuild already under way to the same shape carries on, with this
645
+ * `after`; one to another shape is abandoned first. False where the table is
646
+ * small enough to rebuild at once.
647
+ */ export let reshape = (driver, comp, r, after, sizes = SIZES)=>{
648
+ let names = new Set(catalogue(driver).map((o)=>o.name));
649
+ if (!driver.file || !names.has(META) || !holds(driver, comp, sizes.big)) {
650
+ return false;
651
+ }
652
+ let table = {
653
+ ...r.fresh,
654
+ name: building(comp),
655
+ ifNot: true
656
+ };
657
+ let was = owed(driver).find((w)=>w.kind == 'refit' && w.name == comp);
658
+ if (was?.kind == 'refit' && JSON.stringify(was.table) == JSON.stringify(table)) {
659
+ owe(driver, {
660
+ ...was,
661
+ after
662
+ });
663
+ return true;
664
+ }
665
+ let w = {
666
+ kind: 'refit',
667
+ name: comp,
668
+ table,
669
+ cols: r.cols,
670
+ changed: r.changed,
671
+ after,
672
+ cursor: 0
673
+ };
674
+ quit(driver, w);
675
+ driver.query(table);
676
+ owe(driver, w);
677
+ for (let t of steps(comp, w))driver.query(t);
678
+ return true;
679
+ };
680
+ /** Give up every table rebuild owed but those of `kept`: a pass that took on
681
+ * no rebuild of a table found it fits its vocabulary again, or cannot be
682
+ * rebuilt (./ddl.ts `fit`). */ export let forgo = (driver, kept)=>{
683
+ for (let w of owed(driver)){
684
+ if (w.kind != 'refit' || kept.has(w.name)) continue;
685
+ quit(driver, w);
686
+ meta(driver).del(key(w));
687
+ }
688
+ };
689
+ let sleep = (ms, signal)=>new Promise((done)=>{
690
+ if (signal.aborted) return done();
691
+ let at = setTimeout(stop, ms);
692
+ function stop() {
693
+ clearTimeout(at);
694
+ signal.removeEventListener('abort', stop);
695
+ done();
696
+ }
697
+ signal.addEventListener('abort', stop);
698
+ });
699
+ /**
700
+ * Work off what this file owes, and do its upkeep, until `signal` aborts: a
701
+ * window, a pause as long as the window held the lock so other writers get
702
+ * their turn, and a look every `idle` milliseconds while nothing is due.
703
+ * `daily` is the host's upkeep beside the statistics, and `chores` the work
704
+ * its rows owe. A failed window is `report`ed and waits its hour.
705
+ */ export let tend = async (driver, opts)=>{
706
+ let idle = opts.idle ?? 60_000;
707
+ let daily = [
708
+ statistics,
709
+ ...opts.daily ?? []
710
+ ];
711
+ while(!opts.signal.aborted){
712
+ let at = performance.now();
713
+ let did = work(driver, Date.now(), daily, SIZES, opts.chores);
714
+ if (did && 'error' in did) opts.report?.(did.error, did.name);
715
+ let held = performance.now() - at;
716
+ await sleep(did ? Math.max(10, held) : idle, opts.signal);
717
+ }
718
+ };
719
+ //# sourceMappingURL=owe.js.map