Kitxuuu commited on
Commit
2dec00b
·
verified ·
1 Parent(s): 5142533

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5ac.test +278 -0
  2. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5ae.test +311 -0
  3. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5auxdata.test +114 -0
  4. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5corrupt3.test +0 -0
  5. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5corrupt7.test +128 -0
  6. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5determin.test +65 -0
  7. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5expr.test +52 -0
  8. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5full.test +42 -0
  9. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5query.test +91 -0
  10. local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5tokenizer3.test +77 -0
  11. local-test-sqlite3-delta-02/afc-sqlite3/ext/recover/recoverpgsz.test +97 -0
  12. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/EXPORTED_FUNCTIONS.sqlite3-see +5 -0
  13. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/extern-post-js.c-pp.js +126 -0
  14. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/extern-pre-js.js +7 -0
  15. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-api-glue.c-pp.js +1922 -0
  16. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-opfs-async-proxy.js +805 -0
  17. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-vfs-helper.c-pp.js +103 -0
  18. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js +1301 -0
  19. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-vtab-helper.c-pp.js +427 -0
  20. local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-worker1.c-pp.js +54 -0
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5ac.test ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2014 June 17
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #*************************************************************************
11
+ # This file implements regression tests for SQLite library. The
12
+ # focus of this script is testing the FTS5 module.
13
+ #
14
+ #
15
+
16
+ source [file join [file dirname [info script]] fts5_common.tcl]
17
+ set testprefix fts5ac
18
+
19
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
20
+ ifcapable !fts5 {
21
+ finish_test
22
+ return
23
+ }
24
+
25
+ foreach_detail_mode $testprefix {
26
+
27
+ set data {
28
+ 0 {p o q e z k z p n f y u z y n y} {l o o l v v k}
29
+ 1 {p k h h p y l l h i p v n} {p p l u r i f a j g e r r x w}
30
+ 2 {l s z j k i m p s} {l w e j t j e e i t w r o p o}
31
+ 3 {x g y m y m h p} {k j j b r e y y a k y}
32
+ 4 {q m a i y i z} {o w a g k x g j m w e u k}
33
+ 5 {k o a w y b s z} {s g l m m l m g p}
34
+ 6 {d a q i z h b l c p k j g k} {p x u j x t v c z}
35
+ 7 {f d a g o c t i} {w f c x l d r k i j}
36
+ 8 {y g w u b q p o m j y b p a e k} {r i d k y w o z q m a t p}
37
+ 9 {r k o m c c j s x m x m x m q r} {y r c a q d z k n x n}
38
+ 10 {k j q m g q a j d} {d d e z g w h c d o o g x d}
39
+ 11 {j z u m o y q j f w e e w t r j w} {g m o r x n t n w i f g l z f}
40
+ 12 {s y w a w d o h x m k} {c w k z b p o r a}
41
+ 13 {u t h x e g s k n g i} {f j w g c s r}
42
+ 14 {b f i c s u z t k} {c k q s j u i z o}
43
+ 15 {n a f n u s w h y n s i q e w} {x g e g a s s h n}
44
+ 16 {k s q e j n p} {t r j f t o e k k l m i}
45
+ 17 {g d t u w r o p m n m n p h b o u} {h s w o s l j e}
46
+ 18 {f l q y q q g e e x j r} {n b r r g e i r t x q k}
47
+ 19 {f i r g o a w e p i l o a w} {e k r z t d g h g i b d i e m}
48
+ 20 {l d u u f p y} {g o m m u x m g l j t t x x u}
49
+ 21 {m c d k x i c z l} {m i a i e u h}
50
+ 22 {w b f o c g x y j} {z d w x d f h i p}
51
+ 23 {w u i u x t c h k i b} {b y k h b v r t g j}
52
+ 24 {h f d j s w s b a p k} {a q y u z e y m m j q r}
53
+ 25 {d i x y x x k i y f s d j h z p n} {l l q m e t c w g y h t s v g}
54
+ 26 {g s q w t d k x g f m j p k y} {r m b x e l t d}
55
+ 27 {j l s q u g y v e c l o} {m f l m m m h g x x l n c}
56
+ 28 {c t j g v r s b z j} {l c f y d t q n}
57
+ 29 {e x z y w i h l} {b n b x e y q e n u m}
58
+ 30 {g y y h j b w r} {q b q f u s k c k g r}
59
+ 31 {g u l x l b r c m z b u c} {k g t b x k x n t e z d h o}
60
+ 32 {w g v l z f b z h p s c v h} {g e w v m h k r g w a r f q}
61
+ 33 {c g n f u d o y o b} {e y o h x x y y i z s b h a j}
62
+ 34 {v y h c q u u s q y x x k s q} {d n r m y k n t i r n w e}
63
+ 35 {o u c x l e b t a} {y b a x y f z x r}
64
+ 36 {x p h l j a a u u j h} {x o f s z m b c q p}
65
+ 37 {k q t i c a q n m v v} {v r z e f m y o}
66
+ 38 {r w t t t t r v v o e p g h} {l w x a g a u h y}
67
+ 39 {o p v g v b a g o} {j t q c r b b g y z}
68
+ 40 {f s o r o d t h q f x l} {r d b m k i f s t d l m y x j w}
69
+ 41 {t m o t m f m f} {i p i q j v n v m b q}
70
+ 42 {t x w a r l w d t b c o d o} {a h f h w z d n s}
71
+ 43 {t u q c d g p q x j o l c x c} {m n t o z z j a y}
72
+ 44 {v d i i k b f s z r v r z y} {g n q y s x x m b x c l w}
73
+ 45 {p v v a c s z y e o l} {m v t u d k m k q b d c v z r}
74
+ 46 {f y k l d r q w r s t r e} {h m v r r l r r t f q e x y}
75
+ 47 {w l n l t y x} {n h s l a f c h u f l x x m v n o}
76
+ 48 {t n v i k e b p z p d j j l i o} {i v z p g u e j s i k n h w d c}
77
+ 49 {z v x p n l t a j c} {e j l e n c e t a d}
78
+ 50 {w u b x u i v h a i y m m r p m s} {s r h d o g z y f f x e}
79
+ 51 {d c c x b c a x g} {p r a j v u y}
80
+ 52 {f w g r c o d l t u e z h i} {j l l s s b j m}
81
+ 53 {p m t f k i x} {u v y a z g w v v m x h i}
82
+ 54 {l c z g l o j i c d e b} {b f v y w u i b e i y}
83
+ 55 {r h c x f x a d s} {z x y k f l r b q c v}
84
+ 56 {v x x c y h z x b g m o q n c} {h n b i t g h a q b c o r u}
85
+ 57 {d g l o h t b s b r} {n u e p t i m u}
86
+ 58 {t d y e t d c w u o s w x f c h} {i o s v y b r d r}
87
+ 59 {l b a p q n d r} {k d c c d n y q h g a o p e x}
88
+ 60 {f r z v m p k r} {x x r i s b a g f c}
89
+ 61 {s a z i e r f i w c n y v z t k s} {y y i r y n l s b w i e k n}
90
+ 62 {n x p r e x q r m v i b y} {f o o z n b s r q j}
91
+ 63 {y j s u j x o n r q t f} {f v k n v x u s o a d e f e}
92
+ 64 {u s i l y c x q} {r k c h p c h b o s s u s p b}
93
+ 65 {m p i o s h o} {s w h u n d m n q t y k b w c}
94
+ 66 {l d f g m x x x o} {s w d d f b y j j h h t i y p j o}
95
+ 67 {c b m h f n v w n h} {i r w i e x r w l z p x u g u l s}
96
+ 68 {y a h u h i m a y q} {d d r x h e v q n z y c j}
97
+ 69 {c x f d x o n p o b r t b l p l} {m i t k b x v f p t m l l y r o}
98
+ 70 {u t l w w m s} {m f m o l t k o p e}
99
+ 71 {f g q e l n d m z x q} {z s i i i m f w w f n g p e q}
100
+ 72 {n l h a v u o d f j d e x} {v v s l f g d g r a j x i f z x}
101
+ 73 {x v m v f i g q e w} {r y s j i k m j j e d g r n o i f}
102
+ 74 {g d y n o h p s y q z j d w n h w} {x o d l t j i b r d o r y}
103
+ 75 {p g b i u r b e q d v o a g w m k} {q y z s f q o h}
104
+ 76 {u z a q u f i f f b} {b s p b a a d x r r i q f}
105
+ 77 {w h h z t h p o a h h e e} {h w r p h k z v y f r x}
106
+ 78 {c a r k i a p u x} {f w l p t e m l}
107
+ 79 {q q u k o t r k z} {f b m c w p s s o z}
108
+ 80 {t i g v y q s r x m r x z e f} {x o j w a u e y s j c b u p p r o}
109
+ 81 {n j n h r l a r e o z w e} {v o r r j a v b}
110
+ 82 {i f i d k w d n h} {o i d z i z l m w s b q v u}
111
+ 83 {m d g q q b k b w f q q p p} {j m q f b y c i z k y q p l e a}
112
+ 84 {m x o n y f g} {y c n x n q j i y c l h b r q z}
113
+ 85 {v o z l n p c} {g n j n t b b x n c l d a g j v}
114
+ 86 {z n a y f b t k k t d b z a v} {r p c n r u k u}
115
+ 87 {b q t x z e c w} {q a o a l o a h i m j r}
116
+ 88 {j f h o x x a z g b a f a m i b} {j z c z y x e x w t}
117
+ 89 {t c t p r s u c q n} {z x l i k n f q l n t}
118
+ 90 {w t d q j g m r f k n} {l e w f w w a l y q k i q t p c t}
119
+ 91 {c b o k l i c b s j n m b l} {y f p q o w g}
120
+ 92 {f y d j o q t c c q m f j s t} {f h e d y m o k}
121
+ 93 {k x j r m a d o i z j} {r t t t f e b r x i v j v g o}
122
+ 94 {s f e a e t i h h d q p z t q} {b k m k w h c}
123
+ 95 {h b n j t k i h o q u} {w n g i t o k c a m y p f l x c p}
124
+ 96 {f c x p y r b m o l m o a} {p c a q s u n n x d c f a o}
125
+ 97 {u h h k m n k} {u b v n u a o c}
126
+ 98 {s p e t c z d f n w f} {l s f j b l c e s h}
127
+ 99 {r c v w i v h a t a c v c r e} {h h u m g o f b a e o}
128
+ }
129
+
130
+ foreach {tn2 sql} {
131
+ 1 {}
132
+ 2 {BEGIN}
133
+ } {
134
+ reset_db
135
+ fts5_aux_test_functions db
136
+
137
+ do_execsql_test 1.$tn2.0 {
138
+ CREATE VIRTUAL TABLE xx USING fts5(x,y, detail=%DETAIL%);
139
+ INSERT INTO xx(xx, rank) VALUES('pgsz', 32);
140
+ }
141
+
142
+ execsql $sql
143
+
144
+ do_test 1.$tn2.1.1 {
145
+ foreach {id x y} $data {
146
+ execsql { INSERT INTO xx(rowid, x, y) VALUES($id, $x, $y) }
147
+ }
148
+ execsql { INSERT INTO xx(xx) VALUES('integrity-check') }
149
+ } {}
150
+
151
+
152
+ #-------------------------------------------------------------------------
153
+ #
154
+ do_execsql_test 1.$tn2.integrity {
155
+ INSERT INTO xx(xx) VALUES('integrity-check');
156
+ }
157
+
158
+ #-------------------------------------------------------------------------
159
+ #
160
+ foreach {tn expr} {
161
+ 1.1 "a AND b"
162
+ 1.2 "a OR b"
163
+ 1.3 "o"
164
+ 1.4 "b q"
165
+ 1.5 "e a e"
166
+ 1.6 "m d g q q b k b w f q q p p"
167
+ 1.7 "l o o l v v k"
168
+ 1.8 "a"
169
+ 1.9 "b"
170
+ 1.10 "c"
171
+ 1.11 "no"
172
+ 1.12 "L O O L V V K"
173
+ 1.13 "a AND b AND c"
174
+ 1.14 "x:a"
175
+
176
+ 2.1 "x:a"
177
+ 2.2 "y:a"
178
+ 2.3 "x:b"
179
+ 2.4 "y:b"
180
+
181
+ 3.1 "{x}:a"
182
+ 3.2 "{y}:a"
183
+ 3.3 "{x}:b"
184
+ 3.4 "{y}:b"
185
+
186
+ 4.1 "{x y}:a"
187
+ 4.2 "{y x}:a"
188
+ 4.3 "{x x}:b"
189
+ 4.4 "{y y}:b"
190
+
191
+ 5.1 {{"x" "y"}:a}
192
+ 5.2 {{"y" x}:a}
193
+ 5.3 {{x "x"}:b}
194
+ 5.4 {{"y" y}:b}
195
+
196
+ 6.1 "b + q"
197
+ 6.2 "e + a + e"
198
+ 6.3 "m + d + g + q + q + b + k + b + w + f + q + q + p + p"
199
+ 6.4 "l + o + o + l + v + v + k"
200
+ 6.5 "L + O + O + L + V + V + K"
201
+
202
+ 7.1 "a+b AND c"
203
+ 7.2 "d+c AND u"
204
+ 7.3 "d+c AND u+d"
205
+ 7.4 "a+b OR c"
206
+ 7.5 "d+c OR u"
207
+ 7.6 "d+c OR u+d"
208
+
209
+ 8.1 "NEAR(a b)"
210
+ 8.2 "NEAR(r c)"
211
+ 8.2 { NEAR(r c, 5) }
212
+ 8.3 { NEAR(r c, 3) }
213
+ 8.4 { NEAR(r c, 2) }
214
+ 8.5 { NEAR(r c, 0) }
215
+ 8.6 { NEAR(a b c) }
216
+ 8.7 { NEAR(a b c, 8) }
217
+ 8.8 { x : NEAR(r c) }
218
+ 8.9 { y : NEAR(r c) }
219
+
220
+ 9.1 { NEAR(r c) }
221
+ 9.2 { NEAR(r c, 5) }
222
+ 9.3 { NEAR(r c, 3) }
223
+ 9.4 { NEAR(r c, 2) }
224
+ 9.5 { NEAR(r c, 0) }
225
+ 9.6 { NEAR(a b c) }
226
+ 9.7 { NEAR(a b c, 8) }
227
+ 9.8 { x : NEAR(r c) }
228
+ 9.9 { y : NEAR(r c) }
229
+ 9.10 { x : "r c" }
230
+ 9.11 { y : "r c" }
231
+ 9.12 { a AND b }
232
+ 9.13 { a AND b AND c }
233
+ 9.14a { a }
234
+ 9.14b { a OR b }
235
+ 9.15 { a OR b AND c }
236
+ 9.16 { c AND b OR a }
237
+ 9.17 { c AND (b OR a) }
238
+ 9.18 { c NOT (b OR a) }
239
+ 9.19 { (c NOT b) OR (a AND d) }
240
+ } {
241
+
242
+ if {[fts5_expr_ok $expr xx]==0} {
243
+ do_test 1.$tn2.$tn.OMITTED { list } [list]
244
+ continue
245
+ }
246
+
247
+ set res [fts5_query_data $expr xx]
248
+ do_execsql_test 1.$tn2.$tn.[llength $res].asc {
249
+ SELECT rowid, fts5_test_poslist(xx), fts5_test_collist(xx)
250
+ FROM xx WHERE xx match $expr
251
+ } $res
252
+
253
+ set res [fts5_query_data $expr xx DESC]
254
+ do_execsql_test 1.$tn2.$tn.[llength $res].desc {
255
+ SELECT rowid, fts5_test_poslist(xx), fts5_test_collist(xx)
256
+ FROM xx WHERE xx match $expr ORDER BY 1 DESC
257
+ } $res
258
+ }
259
+ }
260
+
261
+ }
262
+
263
+ do_execsql_test 2.1 {
264
+ SELECT fts5_expr_tcl('a AND b');
265
+ } {{AND [nearset -- {a}] [nearset -- {b}]}}
266
+
267
+ do_test 2.2.1 { nearset {{a b c}} -- a } {0.0.0}
268
+ do_test 2.2.2 { nearset {{a b c}} -- c } {0.0.2}
269
+
270
+ foreach {tn expr tclexpr} {
271
+ 1 {a b} {AND [N $x -- {a}] [N $x -- {b}]}
272
+ } {
273
+ do_execsql_test 2.3.$tn {
274
+ SELECT fts5_expr_tcl($expr, 'N $x')
275
+ } [list $tclexpr]
276
+ }
277
+
278
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5ae.test ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2014 June 17
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #*************************************************************************
11
+ # This file implements regression tests for SQLite library. The
12
+ # focus of this script is testing the FTS5 module.
13
+ #
14
+ #
15
+
16
+ source [file join [file dirname [info script]] fts5_common.tcl]
17
+ set testprefix fts5ae
18
+
19
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
20
+ ifcapable !fts5 {
21
+ finish_test
22
+ return
23
+ }
24
+
25
+ foreach_detail_mode $testprefix {
26
+
27
+ do_execsql_test 1.0 {
28
+ CREATE VIRTUAL TABLE t1 USING fts5(a, b, detail=%DETAIL%);
29
+ INSERT INTO t1(t1, rank) VALUES('pgsz', 32);
30
+ }
31
+
32
+ do_execsql_test 1.1 {
33
+ INSERT INTO t1 VALUES('hello', 'world');
34
+ SELECT rowid FROM t1 WHERE t1 MATCH 'hello' ORDER BY rowid ASC;
35
+ } {1}
36
+
37
+ do_execsql_test 1.2 {
38
+ INSERT INTO t1 VALUES('world', 'hello');
39
+ SELECT rowid FROM t1 WHERE t1 MATCH 'hello' ORDER BY rowid ASC;
40
+ } {1 2}
41
+
42
+ do_execsql_test 1.3 {
43
+ INSERT INTO t1 VALUES('world', 'world');
44
+ SELECT rowid FROM t1 WHERE t1 MATCH 'hello' ORDER BY rowid ASC;
45
+ } {1 2}
46
+
47
+ do_execsql_test 1.4.1 {
48
+ INSERT INTO t1 VALUES('hello', 'hello');
49
+ }
50
+
51
+ do_execsql_test 1.4.2 {
52
+ SELECT rowid FROM t1 WHERE t1 MATCH 'hello' ORDER BY rowid ASC;
53
+ } {1 2 4}
54
+
55
+ fts5_aux_test_functions db
56
+
57
+ #-------------------------------------------------------------------------
58
+ #
59
+ do_execsql_test 2.0 {
60
+ CREATE VIRTUAL TABLE t2 USING fts5(x, y, detail=%DETAIL%);
61
+ INSERT INTO t2 VALUES('u t l w w m s', 'm f m o l t k o p e');
62
+ INSERT INTO t2 VALUES('f g q e l n d m z x q', 'z s i i i m f w w f n g p');
63
+ }
64
+
65
+ do_execsql_test 2.1 {
66
+ SELECT rowid, fts5_test_poslist(t2) FROM t2
67
+ WHERE t2 MATCH 'm' ORDER BY rowid;
68
+ } {
69
+ 1 {0.0.5 0.1.0 0.1.2}
70
+ 2 {0.0.7 0.1.5}
71
+ }
72
+
73
+ do_execsql_test 2.2 {
74
+ SELECT rowid, fts5_test_poslist(t2) FROM t2
75
+ WHERE t2 MATCH 'u OR q' ORDER BY rowid;
76
+ } {
77
+ 1 {0.0.0}
78
+ 2 {1.0.2 1.0.10}
79
+ }
80
+
81
+ if {[detail_is_full]} {
82
+ do_execsql_test 2.3 {
83
+ SELECT rowid, fts5_test_poslist(t2) FROM t2
84
+ WHERE t2 MATCH 'y:o' ORDER BY rowid;
85
+ } {
86
+ 1 {0.1.3 0.1.7}
87
+ }
88
+ }
89
+
90
+ #-------------------------------------------------------------------------
91
+ #
92
+ do_execsql_test 3.0 {
93
+ CREATE VIRTUAL TABLE t3 USING fts5(x, y, detail=%DETAIL%);
94
+ INSERT INTO t3 VALUES( 'j f h o x x a z g b a f a m i b', 'j z c z y x w t');
95
+ INSERT INTO t3 VALUES( 'r c', '');
96
+ }
97
+
98
+ if {[detail_is_full]} {
99
+ do_execsql_test 3.1 {
100
+ SELECT rowid, fts5_test_poslist(t3) FROM t3 WHERE t3 MATCH 'NEAR(a b)';
101
+ } {
102
+ 1 {0.0.6 1.0.9 0.0.10 0.0.12 1.0.15}
103
+ }
104
+
105
+ do_execsql_test 3.2 {
106
+ SELECT rowid, fts5_test_poslist(t3) FROM t3 WHERE t3 MATCH 'NEAR(r c)';
107
+ } {
108
+ 2 {0.0.0 1.0.1}
109
+ }
110
+ }
111
+
112
+ do_execsql_test 3.3 {
113
+ INSERT INTO t3
114
+ VALUES('k x j r m a d o i z j', 'r t t t f e b r x i v j v g o');
115
+ SELECT rowid, fts5_test_poslist(t3)
116
+ FROM t3 WHERE t3 MATCH 'a OR b AND c';
117
+ } {
118
+ 1 {0.0.6 1.0.9 0.0.10 0.0.12 1.0.15 2.1.2}
119
+ 3 0.0.5
120
+ }
121
+
122
+ #-------------------------------------------------------------------------
123
+ #
124
+ do_execsql_test 4.0 {
125
+ CREATE VIRTUAL TABLE t4 USING fts5(x, y, detail=%DETAIL%);
126
+ INSERT INTO t4
127
+ VALUES('k x j r m a d o i z j', 'r t t t f e b r x i v j v g o');
128
+ }
129
+
130
+ do_execsql_test 4.1 {
131
+ SELECT rowid, fts5_test_poslist(t4) FROM t4 WHERE t4 MATCH 'a OR b AND c';
132
+ } {
133
+ 1 0.0.5
134
+ }
135
+
136
+ #-------------------------------------------------------------------------
137
+ # Test that the xColumnSize() and xColumnAvgsize() APIs work.
138
+ #
139
+ reset_db
140
+ fts5_aux_test_functions db
141
+
142
+ do_execsql_test 5.1 {
143
+ CREATE VIRTUAL TABLE t5 USING fts5(x, y, detail=%DETAIL%);
144
+ INSERT INTO t5 VALUES('a b c d', 'e f g h i j');
145
+ INSERT INTO t5 VALUES('', 'a');
146
+ INSERT INTO t5 VALUES('a', '');
147
+ }
148
+ do_execsql_test 5.2 {
149
+ SELECT rowid, fts5_test_columnsize(t5) FROM t5 WHERE t5 MATCH 'a'
150
+ ORDER BY rowid DESC;
151
+ } {
152
+ 3 {1 0}
153
+ 2 {0 1}
154
+ 1 {4 6}
155
+ }
156
+
157
+ do_execsql_test 5.3 {
158
+ SELECT rowid, fts5_test_columntext(t5) FROM t5 WHERE t5 MATCH 'a'
159
+ ORDER BY rowid DESC;
160
+ } {
161
+ 3 {a {}}
162
+ 2 {{} a}
163
+ 1 {{a b c d} {e f g h i j}}
164
+ }
165
+
166
+ do_execsql_test 5.4 {
167
+ SELECT rowid, fts5_test_columntotalsize(t5) FROM t5 WHERE t5 MATCH 'a'
168
+ ORDER BY rowid DESC;
169
+ } {
170
+ 3 {5 7}
171
+ 2 {5 7}
172
+ 1 {5 7}
173
+ }
174
+
175
+ do_execsql_test 5.5 {
176
+ INSERT INTO t5 VALUES('x y z', 'v w x y z');
177
+ SELECT rowid, fts5_test_columntotalsize(t5) FROM t5 WHERE t5 MATCH 'a'
178
+ ORDER BY rowid DESC;
179
+ } {
180
+ 3 {8 12}
181
+ 2 {8 12}
182
+ 1 {8 12}
183
+ }
184
+
185
+ #-------------------------------------------------------------------------
186
+ # Test the xTokenize() API
187
+ #
188
+ reset_db
189
+ fts5_aux_test_functions db
190
+ do_execsql_test 6.1 {
191
+ CREATE VIRTUAL TABLE t6 USING fts5(x, y, detail=%DETAIL%);
192
+ INSERT INTO t6 VALUES('There are more', 'things in heaven and earth');
193
+ INSERT INTO t6 VALUES(', Horatio, Than are', 'dreamt of in your philosophy.');
194
+ }
195
+
196
+ do_execsql_test 6.2 {
197
+ SELECT rowid, fts5_test_tokenize(t6) FROM t6 WHERE t6 MATCH 't*'
198
+ } {
199
+ 1 {{there are more} {things in heaven and earth}}
200
+ 2 {{horatio than are} {dreamt of in your philosophy}}
201
+ }
202
+
203
+ #-------------------------------------------------------------------------
204
+ # Test the xQueryPhrase() API
205
+ #
206
+ reset_db
207
+ fts5_aux_test_functions db
208
+ do_execsql_test 7.1 {
209
+ CREATE VIRTUAL TABLE t7 USING fts5(x, y, detail=%DETAIL%);
210
+ }
211
+ do_test 7.2 {
212
+ foreach {x y} {
213
+ {q i b w s a a e l o} {i b z a l f p t e u}
214
+ {b a z t a l o x d i} {b p a d b f h d w y}
215
+ {z m h n p p u i e g} {v h d v b x j j c z}
216
+ {a g i m v a u c b i} {p k s o t l r t b m}
217
+ {v v c j o d a s c p} {f f v o k p o f o g}
218
+ } {
219
+ execsql {INSERT INTO t7 VALUES($x, $y)}
220
+ }
221
+ execsql { SELECT count(*) FROM t7 }
222
+ } {5}
223
+
224
+ foreach {tn q res} {
225
+ 1 a {{4 2}}
226
+ 2 b {{3 4}}
227
+ 3 c {{2 1}}
228
+ 4 d {{2 2}}
229
+ 5 {a AND b} {{4 2} {3 4}}
230
+ 6 {a OR b OR c OR d} {{4 2} {3 4} {2 1} {2 2}}
231
+ } {
232
+ do_execsql_test 7.3.$tn {
233
+ SELECT fts5_test_queryphrase(t7) FROM t7 WHERE t7 MATCH $q LIMIT 1
234
+ } [list $res]
235
+ }
236
+
237
+ do_execsql_test 7.4 {
238
+ SELECT fts5_test_rowcount(t7) FROM t7 WHERE t7 MATCH 'a';
239
+ } {5 5 5 5}
240
+
241
+ #do_execsql_test 7.4 {
242
+ # SELECT rowid, bm25debug(t7) FROM t7 WHERE t7 MATCH 'a';
243
+ #} {5 5 5 5}
244
+ #
245
+
246
+ #-------------------------------------------------------------------------
247
+ #
248
+ do_test 8.1 {
249
+ execsql { CREATE VIRTUAL TABLE t8 USING fts5(x, y, detail=%DETAIL%) }
250
+ foreach {rowid x y} {
251
+ 0 {A o} {o o o C o o o o o o o o}
252
+ 1 {o o B} {o o o C C o o o o o o o}
253
+ 2 {A o o} {o o o o D D o o o o o o}
254
+ 3 {o B} {o o o o o D o o o o o o}
255
+ 4 {E o G} {H o o o o o o o o o o o}
256
+ 5 {F o G} {I o J o o o o o o o o o}
257
+ 6 {E o o} {H o J o o o o o o o o o}
258
+ 7 {o o o} {o o o o o o o o o o o o}
259
+ 9 {o o o} {o o o o o o o o o o o o}
260
+ } {
261
+ execsql { INSERT INTO t8(rowid, x, y) VALUES($rowid, $x, $y) }
262
+ }
263
+ } {}
264
+
265
+ foreach {tn q res} {
266
+ 1 {a} {0 2}
267
+ 2 {b} {3 1}
268
+ 3 {c} {1 0}
269
+ 4 {d} {2 3}
270
+ 5 {g AND (e OR f)} {5 4}
271
+ 6 {j AND (h OR i)} {5 6}
272
+ } {
273
+ do_execsql_test 8.2.$tn.1 {
274
+ SELECT rowid FROM t8 WHERE t8 MATCH $q ORDER BY bm25(t8);
275
+ } $res
276
+
277
+ do_execsql_test 8.2.$tn.2 {
278
+ SELECT rowid FROM t8 WHERE t8 MATCH $q ORDER BY +rank;
279
+ } $res
280
+
281
+ do_execsql_test 8.2.$tn.3 {
282
+ SELECT rowid FROM t8 WHERE t8 MATCH $q ORDER BY rank;
283
+ } $res
284
+ }
285
+
286
+ #-------------------------------------------------------------------------
287
+ # Test xPhraseCount() for some different queries.
288
+ #
289
+ do_test 9.1 {
290
+ execsql { CREATE VIRTUAL TABLE t9 USING fts5(x) }
291
+ foreach x {
292
+ "a b c" "d e f"
293
+ } {
294
+ execsql { INSERT INTO t9 VALUES($x) }
295
+ }
296
+ } {}
297
+
298
+ foreach {tn q cnt} {
299
+ 1 {a AND b} 2
300
+ 2 {a OR b} 2
301
+ 3 {a OR b OR c} 3
302
+ 4 {NEAR(a b)} 2
303
+ } {
304
+ do_execsql_test 9.2.$tn {
305
+ SELECT fts5_test_phrasecount(t9) FROM t9 WHERE t9 MATCH $q LIMIT 1
306
+ } $cnt
307
+ }
308
+
309
+ }
310
+
311
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5auxdata.test ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2014 Dec 20
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #***********************************************************************
11
+ #
12
+ # Tests focusing on the fts5 xSetAuxdata() and xGetAuxdata() APIs.
13
+ #
14
+
15
+ source [file join [file dirname [info script]] fts5_common.tcl]
16
+ set testprefix fts5auxdata
17
+
18
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
19
+ ifcapable !fts5 {
20
+ finish_test
21
+ return
22
+ }
23
+
24
+ do_execsql_test 1.0 {
25
+ CREATE VIRTUAL TABLE f1 USING fts5(a, b);
26
+ INSERT INTO f1(rowid, a, b) VALUES(1, 'a', 'b1');
27
+ INSERT INTO f1(rowid, a, b) VALUES(2, 'a', 'b2');
28
+ INSERT INTO f1(rowid, a, b) VALUES(3, 'a', 'b3');
29
+ INSERT INTO f1(rowid, a, b) VALUES(4, 'a', 'b4');
30
+ INSERT INTO f1(rowid, a, b) VALUES(5, 'a', 'b5');
31
+ }
32
+
33
+ proc aux_function_1 {cmd tn} {
34
+ switch [$cmd xRowid] {
35
+ 1 {
36
+ do_test $tn.1 [list $cmd xGetAuxdata 0 ] {}
37
+ $cmd xSetAuxdata "one"
38
+ }
39
+
40
+ 2 {
41
+ do_test $tn.2 [list $cmd xGetAuxdata 0 ] {one}
42
+ $cmd xSetAuxdata "two"
43
+ }
44
+
45
+ 3 {
46
+ do_test $tn.3 [list $cmd xGetAuxdata 0 ] {two}
47
+ }
48
+
49
+ 4 {
50
+ do_test $tn.4 [list $cmd xGetAuxdata 1 ] {two}
51
+ }
52
+
53
+ 5 {
54
+ do_test $tn.5 [list $cmd xGetAuxdata 0 ] {}
55
+ }
56
+ }
57
+ }
58
+
59
+ sqlite3_fts5_create_function db aux_function_1 aux_function_1
60
+ db eval {
61
+ SELECT aux_function_1(f1, 1) FROM f1 WHERE f1 MATCH 'a'
62
+ ORDER BY rowid ASC
63
+ }
64
+
65
+ proc aux_function_2 {cmd tn inst} {
66
+ if {$inst == "A"} {
67
+ switch [$cmd xRowid] {
68
+ 1 {
69
+ do_test $tn.1.$inst [list $cmd xGetAuxdata 0 ] {}
70
+ $cmd xSetAuxdata "one $inst"
71
+ }
72
+ 2 {
73
+ do_test $tn.2.$inst [list $cmd xGetAuxdata 0 ] "one $inst"
74
+ $cmd xSetAuxdata "two $inst"
75
+ }
76
+ 3 {
77
+ do_test $tn.3.$inst [list $cmd xGetAuxdata 0 ] "two $inst"
78
+ }
79
+ 4 {
80
+ do_test $tn.4.$inst [list $cmd xGetAuxdata 1 ] "two $inst"
81
+ }
82
+ 5 {
83
+ do_test $tn.5.$inst [list $cmd xGetAuxdata 0 ] {}
84
+ }
85
+ }
86
+ } else {
87
+ switch [$cmd xRowid] {
88
+ 1 {
89
+ do_test $tn.1.$inst [list $cmd xGetAuxdata 0 ] "one A"
90
+ }
91
+ 2 {
92
+ do_test $tn.2.$inst [list $cmd xGetAuxdata 0 ] "two A"
93
+ }
94
+ 3 {
95
+ do_test $tn.3.$inst [list $cmd xGetAuxdata 0 ] "two A"
96
+ }
97
+ 4 {
98
+ do_test $tn.4.$inst [list $cmd xGetAuxdata 0 ] {}
99
+ }
100
+ 5 {
101
+ do_test $tn.5.$inst [list $cmd xGetAuxdata 0 ] {}
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ sqlite3_fts5_create_function db aux_function_2 aux_function_2
108
+ db eval {
109
+ SELECT aux_function_2(f1, 2, 'A'), aux_function_2(f1, 2, 'B')
110
+ FROM f1 WHERE f1 MATCH 'a'
111
+ ORDER BY rowid ASC
112
+ }
113
+
114
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5corrupt3.test ADDED
The diff for this file is too large to render. See raw diff
 
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5corrupt7.test ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2023 April 30
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #***********************************************************************
11
+ #
12
+
13
+ source [file join [file dirname [info script]] fts5_common.tcl]
14
+ set testprefix fts5corrupt7
15
+
16
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
17
+ ifcapable !fts5 {
18
+ finish_test
19
+ return
20
+ }
21
+ sqlite3_fts5_may_be_corrupt 1
22
+
23
+ do_execsql_test 1.0 {
24
+ CREATE VIRTUAL TABLE t1 USING fts5(x);
25
+ INSERT INTO t1(t1, rank) VALUES('pgsz', 32);
26
+ }
27
+
28
+ set doc [string repeat "a b " 30]
29
+
30
+ do_execsql_test 1.1 {
31
+ BEGIN;
32
+ INSERT INTO t1(rowid, x) VALUES(123, $doc);
33
+ INSERT INTO t1(rowid, x) VALUES(124, $doc);
34
+ COMMIT;
35
+ }
36
+
37
+ execsql_pp {
38
+ SELECT id, fts5_decode(id, block), quote(block) FROM t1_data
39
+ }
40
+
41
+ set rows [db eval { SELECT rowid FROM t1_data }]
42
+ db_save_and_close
43
+
44
+ foreach r $rows {
45
+ db_restore_and_reopen
46
+
47
+ proc edit_block {b} {
48
+ binary scan $b c* in
49
+ set out [lreplace $in 0 1 255 255]
50
+ binary format c* $out
51
+ }
52
+ db func edit_block edit_block
53
+
54
+ do_execsql_test 1.2.$r.1 {
55
+ UPDATE t1_data SET block = edit_block(block) WHERE rowid=$r;
56
+ }
57
+
58
+ do_execsql_test 1.2.$r.2 {
59
+ INSERT INTO t1(t1, rank) VALUES('secure-delete', 1);
60
+ }
61
+
62
+ do_test 1.2.$r.3 {
63
+ catchsql { DELETE FROM t1 WHERE rowid=123; }
64
+ catchsql { DELETE FROM t1 WHERE rowid=124; }
65
+ set {} {}
66
+ } {}
67
+
68
+ db close
69
+ }
70
+
71
+ foreach r $rows {
72
+ set r 137438953475
73
+ db_restore_and_reopen
74
+
75
+ proc edit_block {b} {
76
+ binary scan $b c* in
77
+ set out [lreplace $in end end 127]
78
+ binary format c* $out
79
+ }
80
+ db func edit_block edit_block
81
+
82
+ do_execsql_test 1.2.$r.1 {
83
+ UPDATE t1_data SET block = edit_block(block) WHERE rowid=$r;
84
+ }
85
+
86
+ do_execsql_test 1.2.$r.2 {
87
+ INSERT INTO t1(t1, rank) VALUES('secure-delete', 1);
88
+ }
89
+
90
+ do_test 1.2.$r.3 {
91
+ catchsql { DELETE FROM t1 WHERE rowid=124; }
92
+ catchsql { DELETE FROM t1 WHERE rowid=123; }
93
+ set {} {}
94
+ } {}
95
+
96
+ db close
97
+ }
98
+
99
+ #-------------------------------------------------------------------------
100
+ reset_db
101
+ do_execsql_test 2.0 {
102
+ CREATE VIRTUAL TABLE t1 USING fts5(x);
103
+ BEGIN;
104
+ INSERT INTO t1 VALUES('abc');
105
+ INSERT INTO t1 VALUES('b d d d');
106
+ COMMIT;
107
+ INSERT INTO t1(t1, rank) VALUES('secure-delete', 1);
108
+ }
109
+
110
+ execsql_pp {
111
+ SELECT id, quote(block) FROM t1_data
112
+ }
113
+
114
+ do_execsql_test 2.1 {
115
+ SELECT quote(block) FROM t1_data WHERE id > 10;
116
+ } {X'0000001A04306162630102020101620202020101640206030303040806'}
117
+
118
+ do_execsql_test 2.2 {
119
+ UPDATE t1_data SET
120
+ block=X'0000001A04306162630102025501620202020101640206030303040806'
121
+ WHERE id>10
122
+ }
123
+
124
+ do_catchsql_test 2.3 {
125
+ DELETE FROM t1 WHERE rowid = 1
126
+ } {1 {database disk image is malformed}}
127
+
128
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5determin.test ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2016 March 21
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #*************************************************************************
11
+ # This file implements regression tests for SQLite library. The
12
+ # focus of this script is testing the FTS5 module.
13
+ #
14
+ # Specifically, that the fts5 module is deterministic. At one point, when
15
+ # segment ids were allocated using sqlite3_randomness(), this was not the
16
+ # case.
17
+ #
18
+
19
+ source [file join [file dirname [info script]] fts5_common.tcl]
20
+ set testprefix fts5aa
21
+ return_if_no_fts5
22
+
23
+ proc do_determin_test {tn} {
24
+ uplevel [list
25
+ do_execsql_test $tn {
26
+ SELECT (SELECT md5sum(id, block) FROM t1_data)==
27
+ (SELECT md5sum(id, block) FROM t2_data),
28
+ (SELECT md5sum(id, block) FROM t1_data)==
29
+ (SELECT md5sum(id, block) FROM t3_data)
30
+ } {1 1}
31
+ ]
32
+ }
33
+
34
+ foreach_detail_mode $::testprefix {
35
+ do_execsql_test 1.0 {
36
+ CREATE VIRTUAL TABLE t1 USING fts5(a, b, prefix="1 2", detail=%DETAIL%);
37
+ CREATE VIRTUAL TABLE t2 USING fts5(a, b, prefix="1 2", detail=%DETAIL%);
38
+ CREATE VIRTUAL TABLE t3 USING fts5(a, b, prefix="1 2", detail=%DETAIL%);
39
+ }
40
+
41
+ do_test 1.1 {
42
+ foreach t {t1 t2 t3} {
43
+ execsql [string map [list TBL $t] {
44
+ INSERT INTO TBL VALUES('a b c', 'd e f');
45
+ INSERT INTO TBL VALUES('c1 c2 c3', 'c1 c2 c3');
46
+ INSERT INTO TBL VALUES('xyzxyzxyz', 'xyzxyzxyz');
47
+ }]
48
+ }
49
+ } {}
50
+
51
+ do_determin_test 1.2
52
+
53
+ do_test 1.3 {
54
+ foreach t {t1 t2 t3} {
55
+ execsql [string map [list TBL $t] {
56
+ INSERT INTO TBL(TBL) VALUES('optimize');
57
+ }]
58
+ }
59
+ } {}
60
+
61
+ do_determin_test 1.4
62
+ }
63
+
64
+
65
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5expr.test ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2024 August 8
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #*************************************************************************
11
+ # This file implements regression tests for SQLite library. The
12
+ # focus of this script is testing the FTS5 module.
13
+ #
14
+
15
+ source [file join [file dirname [info script]] fts5_common.tcl]
16
+ set testprefix fts5expr
17
+
18
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
19
+ ifcapable !fts5 {
20
+ finish_test
21
+ return
22
+ }
23
+
24
+ do_execsql_test 1.0 {
25
+ CREATE VIRTUAL TABLE x1 USING fts5(a);
26
+ INSERT INTO x1(rowid, a) VALUES (113, 'fts5 expr test');
27
+ }
28
+
29
+ do_execsql_test 1.1 {
30
+ SELECT rowid FROM x1('expr');
31
+ } {113}
32
+
33
+ for {set ii 0} {$ii < 300} {incr ii} {
34
+ set expr "expr "
35
+ append expr [string repeat "NOT abcd " $ii]
36
+
37
+ if {$ii<257} {
38
+ set res {0 113}
39
+ } else {
40
+ set res {1 {fts5 expression tree is too large (maximum depth 256)}}
41
+ }
42
+ do_catchsql_test 1.1.$ii {
43
+ SELECT rowid FROM x1($expr)
44
+ } $res
45
+ }
46
+
47
+ do_execsql_test 1.2 {
48
+ SELECT rowid FROM x1 WHERE a MATCH '"..."'
49
+ } {}
50
+
51
+ finish_test
52
+
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5full.test ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2014 Dec 20
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #***********************************************************************
11
+ #
12
+ # Test that SQLITE_FULL is returned if the FTS5 table cannot find a free
13
+ # segid to use. In practice this can only really happen when automerge and
14
+ # crisismerge are both disabled.
15
+ #
16
+
17
+ source [file join [file dirname [info script]] fts5_common.tcl]
18
+ set testprefix fts5full
19
+
20
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
21
+ ifcapable !fts5 {
22
+ finish_test
23
+ return
24
+ }
25
+
26
+ do_execsql_test 1.0 {
27
+ CREATE VIRTUAL TABLE x8 USING fts5(i);
28
+ INSERT INTO x8(x8, rank) VALUES('automerge', 0);
29
+ INSERT INTO x8(x8, rank) VALUES('crisismerge', 100000);
30
+ }
31
+
32
+ db func rnddoc fts5_rnddoc
33
+ do_test 1.1 {
34
+ list [catch {
35
+ for {set i 0} {$i < 2500} {incr i} {
36
+ execsql { INSERT INTO x8 VALUES( rnddoc(5) ); }
37
+ }
38
+ } msg] $msg
39
+ } {0 {}}
40
+
41
+
42
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5query.test ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2015 October 27
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #*************************************************************************
11
+ # This file implements regression tests for SQLite library. The
12
+ # focus of this script is testing the FTS5 module.
13
+ #
14
+
15
+ source [file join [file dirname [info script]] fts5_common.tcl]
16
+ set testprefix fts5query
17
+
18
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
19
+ ifcapable !fts5 {
20
+ finish_test
21
+ return
22
+ }
23
+
24
+ for {set tn 1 ; set pgsz 64} {$tn<32} {incr tn; incr pgsz 16} {
25
+ reset_db
26
+ do_test 1.$tn.1 {
27
+ execsql {
28
+ CREATE VIRTUAL TABLE t1 USING fts5(x);
29
+ INSERT INTO t1(t1, rank) VALUES('pgsz', $pgsz);
30
+ BEGIN;
31
+ }
32
+ foreach x [list aaa bbb ccc ddd eee fff ggg hhh iii jjj] {
33
+ set doc [string repeat "$x " 30]
34
+ execsql { INSERT INTO t1 VALUES($doc) }
35
+ }
36
+ execsql COMMIT
37
+ } {}
38
+
39
+ do_execsql_test 1.$tn.2 {
40
+ INSERT INTO t1(t1) VALUES('integrity-check');
41
+ }
42
+
43
+ set ret 1
44
+ foreach x [list a b c d e f g h i j] {
45
+ do_execsql_test 1.$tn.3.$ret {
46
+ SELECT rowid FROM t1 WHERE t1 MATCH $x || '*';
47
+ } $ret
48
+ incr ret
49
+ }
50
+ }
51
+
52
+ for {set tn 1 ; set pgsz 64} {$tn<32} {incr tn; incr pgsz 16} {
53
+ reset_db
54
+ do_test 2.$tn.1 {
55
+ execsql {
56
+ CREATE VIRTUAL TABLE t1 USING fts5(x);
57
+ INSERT INTO t1(t1, rank) VALUES('pgsz', $pgsz);
58
+ BEGIN;
59
+ }
60
+ foreach x [list bbb ddd fff hhh jjj lll nnn ppp rrr ttt] {
61
+ set doc [string repeat "$x " 30]
62
+ execsql { INSERT INTO t1 VALUES($doc) }
63
+ }
64
+ execsql COMMIT
65
+ } {}
66
+
67
+ do_execsql_test 2.$tn.2 {
68
+ INSERT INTO t1(t1) VALUES('integrity-check');
69
+ }
70
+
71
+ set ret 1
72
+ foreach x [list a c e g i k m o q s u] {
73
+ do_execsql_test 2.$tn.3.$ret {
74
+ SELECT rowid FROM t1 WHERE t1 MATCH $x || '*';
75
+ } {}
76
+ incr ret
77
+ }
78
+ }
79
+
80
+ reset_db
81
+ do_execsql_test 3.0 {
82
+ CREATE VIRTUAL TABLE x1 USING fts5(a);
83
+ INSERT INTO x1(rowid, a) VALUES(-1000000000000, 'toyota');
84
+ INSERT INTO x1(rowid, a) VALUES(1, 'tarago');
85
+ }
86
+ do_execsql_test 3.1 {
87
+ SELECT rowid FROM x1('t*');
88
+ } {-1000000000000 1}
89
+
90
+
91
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/fts5/test/fts5tokenizer3.test ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2024 Aug 10
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #***********************************************************************
11
+ #
12
+ # Tests focusing on the built-in fts5 tokenizers.
13
+ #
14
+
15
+ source [file join [file dirname [info script]] fts5_common.tcl]
16
+ set testprefix fts5tokenizer3
17
+
18
+ # If SQLITE_ENABLE_FTS5 is not defined, omit this file.
19
+ ifcapable !fts5 {
20
+ finish_test
21
+ return
22
+ }
23
+
24
+
25
+ proc get_sod {args} { return "split_on_dot" }
26
+ proc get_lowercase {args} { return "lowercase" }
27
+
28
+ proc lowercase {flags txt} {
29
+ set n [string length $txt]
30
+ sqlite3_fts5_token [string tolower $txt] 0 $n
31
+ return 0
32
+ }
33
+
34
+ proc split_on_dot {flags txt} {
35
+ set iOff 0
36
+ foreach t [split $txt "."] {
37
+ set n [string length $txt]
38
+ sqlite3_fts5_token $t $iOff [expr $iOff+$n]
39
+ incr iOff [expr {$n+1}]
40
+ }
41
+ return ""
42
+ }
43
+
44
+ foreach {tn script} {
45
+ 1 {
46
+ sqlite3_fts5_create_tokenizer db lowercase get_lowercase
47
+ sqlite3_fts5_create_tokenizer -parent lowercase db split_on_dot get_sod
48
+ }
49
+ 2 {
50
+ sqlite3_fts5_create_tokenizer -v2 db lowercase get_lowercase
51
+ sqlite3_fts5_create_tokenizer -parent lowercase db split_on_dot get_sod
52
+ }
53
+ 3 {
54
+ sqlite3_fts5_create_tokenizer db lowercase get_lowercase
55
+ sqlite3_fts5_create_tokenizer -v2 -parent lowercase db split_on_dot get_sod
56
+ }
57
+ 4 {
58
+ sqlite3_fts5_create_tokenizer -v2 db lowercase get_lowercase
59
+ sqlite3_fts5_create_tokenizer -v2 -parent lowercase db split_on_dot get_sod
60
+ }
61
+ } {
62
+ reset_db
63
+ eval $script
64
+
65
+ do_execsql_test 1.$tn.0 {
66
+ CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize=split_on_dot);
67
+ CREATE VIRTUAL TABLE t1vocab USING fts5vocab(t1, instance);
68
+ INSERT INTO t1 VALUES('ABC.Def.ghi');
69
+ }
70
+
71
+ do_execsql_test 1.$tn.1 {
72
+ SELECT term FROM t1vocab ORDER BY 1
73
+ } {abc def ghi}
74
+ }
75
+
76
+
77
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/recover/recoverpgsz.test ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2022 October 14
2
+ #
3
+ # The author disclaims copyright to this source code. In place of
4
+ # a legal notice, here is a blessing:
5
+ #
6
+ # May you do good and not evil.
7
+ # May you find forgiveness for yourself and forgive others.
8
+ # May you share freely, never taking more than you give.
9
+ #
10
+ #***********************************************************************
11
+ #
12
+
13
+ source [file join [file dirname [info script]] recover_common.tcl]
14
+
15
+ db close
16
+ sqlite3_test_control_pending_byte 0x1000000
17
+
18
+ set testprefix recoverpgsz
19
+
20
+ foreach {pgsz bOverflow} {
21
+ 512 0 1024 0 2048 0 4096 0 8192 0 16384 0 32768 0 65536 0
22
+ 512 1 1024 1 2048 1 4096 1 8192 1 16384 1 32768 1 65536 1
23
+ } {
24
+ reset_db
25
+ execsql "PRAGMA page_size = $pgsz"
26
+ execsql "PRAGMA auto_vacuum = 0"
27
+ do_execsql_test 1.$pgsz.$bOverflow.1 {
28
+ CREATE TABLE t1(a, b, c);
29
+ CREATE INDEX i1 ON t1(b, a, c);
30
+ INSERT INTO t1(a, b) VALUES(1, 2), (3, 4), (5, 6);
31
+ DELETE FROM t1 WHERE a=3;
32
+ }
33
+ if {$bOverflow} {
34
+ do_execsql_test 1.$pgsz.$bOverflow.1a {
35
+ UPDATE t1 SET c = randomblob(100000);
36
+ }
37
+ }
38
+ db close
39
+
40
+
41
+ set fd [open test.db]
42
+ fconfigure $fd -translation binary
43
+ seek $fd $pgsz
44
+ set pg1 [read $fd $pgsz]
45
+ set pg2 [read $fd $pgsz]
46
+ close $fd
47
+
48
+ set fd2 [open test.db2 w]
49
+ fconfigure $fd2 -translation binary
50
+ seek $fd2 $pgsz
51
+ puts -nonewline $fd2 $pg1
52
+ close $fd2
53
+
54
+ sqlite3 db2 test.db2
55
+ do_test 1.$pgsz.$bOverflow.2 {
56
+ set R [sqlite3_recover_init db2 main test.db3]
57
+ $R run
58
+ $R finish
59
+ } {}
60
+
61
+ sqlite3 db3 test.db3
62
+ do_test 1.$pgsz.$bOverflow.3 {
63
+ db3 eval { SELECT * FROM sqlite_schema }
64
+ db3 eval { PRAGMA page_size }
65
+ } $pgsz
66
+
67
+ db2 close
68
+ db3 close
69
+
70
+ forcedelete test.db3
71
+ forcedelete test.db2
72
+
73
+ set fd2 [open test.db2 w]
74
+ fconfigure $fd2 -translation binary
75
+ seek $fd2 $pgsz
76
+ puts -nonewline $fd2 $pg2
77
+ close $fd2
78
+
79
+ sqlite3 db2 test.db2
80
+ do_test 1.$pgsz.$bOverflow.4 {
81
+ set R [sqlite3_recover_init db2 main test.db3]
82
+ $R run
83
+ $R finish
84
+ } {}
85
+
86
+ sqlite3 db3 test.db3
87
+ do_test 1.$pgsz.$bOverflow.5 {
88
+ db3 eval { SELECT * FROM sqlite_schema }
89
+ db3 eval { PRAGMA page_size }
90
+ } $pgsz
91
+
92
+ db2 close
93
+ db3 close
94
+ }
95
+
96
+
97
+ finish_test
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/EXPORTED_FUNCTIONS.sqlite3-see ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ _sqlite3_key
2
+ _sqlite3_key_v2
3
+ _sqlite3_rekey
4
+ _sqlite3_rekey_v2
5
+ _sqlite3_activate_see
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/extern-post-js.c-pp.js ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ /* ^^^^ ACHTUNG: blank line at the start is necessary because
3
+ Emscripten will not add a newline in some cases and we need
4
+ a blank line for a sed-based kludge for the ES6 build. */
5
+ /* extern-post-js.js must be appended to the resulting sqlite3.js
6
+ file. It gets its name from being used as the value for the
7
+ --extern-post-js=... Emscripten flag. Note that this code, unlike
8
+ most of the associated JS code, runs outside of the
9
+ Emscripten-generated module init scope, in the current
10
+ global scope. */
11
+ //#if target=es6-module
12
+ const toExportForESM =
13
+ //#endif
14
+ (function(){
15
+ /**
16
+ In order to hide the sqlite3InitModule()'s resulting
17
+ Emscripten module from downstream clients (and simplify our
18
+ documentation by being able to elide those details), we hide that
19
+ function and expose a hand-written sqlite3InitModule() to return
20
+ the sqlite3 object (most of the time).
21
+
22
+ Unfortunately, we cannot modify the module-loader/exporter-based
23
+ impls which Emscripten installs at some point in the file above
24
+ this.
25
+ */
26
+ const originalInit = sqlite3InitModule;
27
+ if(!originalInit){
28
+ throw new Error("Expecting globalThis.sqlite3InitModule to be defined by the Emscripten build.");
29
+ }
30
+ /**
31
+ We need to add some state which our custom Module.locateFile()
32
+ can see, but an Emscripten limitation currently prevents us from
33
+ attaching it to the sqlite3InitModule function object:
34
+
35
+ https://github.com/emscripten-core/emscripten/issues/18071
36
+
37
+ The only(?) current workaround is to temporarily stash this state
38
+ into the global scope and delete it when sqlite3InitModule()
39
+ is called.
40
+ */
41
+ const initModuleState = globalThis.sqlite3InitModuleState = Object.assign(Object.create(null),{
42
+ moduleScript: globalThis?.document?.currentScript,
43
+ isWorker: ('undefined' !== typeof WorkerGlobalScope),
44
+ location: globalThis.location,
45
+ urlParams: globalThis?.location?.href
46
+ ? new URL(globalThis.location.href).searchParams
47
+ : new URLSearchParams()
48
+ });
49
+ initModuleState.debugModule =
50
+ initModuleState.urlParams.has('sqlite3.debugModule')
51
+ ? (...args)=>console.warn('sqlite3.debugModule:',...args)
52
+ : ()=>{};
53
+
54
+ if(initModuleState.urlParams.has('sqlite3.dir')){
55
+ initModuleState.sqlite3Dir = initModuleState.urlParams.get('sqlite3.dir') +'/';
56
+ }else if(initModuleState.moduleScript){
57
+ const li = initModuleState.moduleScript.src.split('/');
58
+ li.pop();
59
+ initModuleState.sqlite3Dir = li.join('/') + '/';
60
+ }
61
+
62
+ globalThis.sqlite3InitModule = function ff(...args){
63
+ //console.warn("Using replaced sqlite3InitModule()",globalThis.location);
64
+ return originalInit(...args).then((EmscriptenModule)=>{
65
+ //#if wasmfs
66
+ if('undefined'!==typeof WorkerGlobalScope &&
67
+ EmscriptenModule['ENVIRONMENT_IS_PTHREAD']){
68
+ /** Workaround for wasmfs-generated worker, which calls this
69
+ routine from each individual thread and requires that its
70
+ argument be returned. The conditional criteria above are
71
+ fragile, based solely on inspection of the offending code,
72
+ not public Emscripten details. */
73
+ //console.warn("sqlite3InitModule() returning E-module.",EmscriptenModule);
74
+ return EmscriptenModule;
75
+ }
76
+ //#endif
77
+ //console.warn("sqlite3InitModule() returning sqlite3 object.");
78
+ const s = EmscriptenModule.sqlite3;
79
+ s.scriptInfo = initModuleState;
80
+ //console.warn("sqlite3.scriptInfo =",s.scriptInfo);
81
+ if(ff.__isUnderTest) s.__isUnderTest = true;
82
+ const f = s.asyncPostInit;
83
+ delete s.asyncPostInit;
84
+ return f();
85
+ }).catch((e)=>{
86
+ console.error("Exception loading sqlite3 module:",e);
87
+ throw e;
88
+ });
89
+ };
90
+ globalThis.sqlite3InitModule.ready = originalInit.ready;
91
+
92
+ if(globalThis.sqlite3InitModuleState.moduleScript){
93
+ const sim = globalThis.sqlite3InitModuleState;
94
+ let src = sim.moduleScript.src.split('/');
95
+ src.pop();
96
+ sim.scriptDir = src.join('/') + '/';
97
+ }
98
+ initModuleState.debugModule('sqlite3InitModuleState =',initModuleState);
99
+ if(0){
100
+ console.warn("Replaced sqlite3InitModule()");
101
+ console.warn("globalThis.location.href =",globalThis.location.href);
102
+ if('undefined' !== typeof document){
103
+ console.warn("document.currentScript.src =",
104
+ document?.currentScript?.src);
105
+ }
106
+ }
107
+ //#ifnot target=es6-module
108
+ // Emscripten does not inject these module-loader bits in ES6 module
109
+ // builds and including them here breaks JS bundlers, so elide them
110
+ // from ESM builds.
111
+ /* Replace the various module exports performed by the Emscripten
112
+ glue... */
113
+ if (typeof exports === 'object' && typeof module === 'object'){
114
+ module.exports = sqlite3InitModule;
115
+ }else if (typeof exports === 'object'){
116
+ exports["sqlite3InitModule"] = sqlite3InitModule;
117
+ }
118
+ /* AMD modules get injected in a way we cannot override,
119
+ so we can't handle those here. */
120
+ //#endif // !target=es6-module
121
+ return globalThis.sqlite3InitModule /* required for ESM */;
122
+ })();
123
+ //#if target=es6-module
124
+ sqlite3InitModule = toExportForESM;
125
+ export default sqlite3InitModule;
126
+ //#endif
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/extern-pre-js.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /* extern-pre-js.js must be prepended to the resulting sqlite3.js
2
+ file. This file is currently only used for holding snippets during
3
+ test and development.
4
+
5
+ It gets its name from being used as the value for the
6
+ --extern-pre-js=... Emscripten flag.
7
+ */
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-api-glue.c-pp.js ADDED
@@ -0,0 +1,1922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ 2022-07-22
3
+
4
+ The author disclaims copyright to this source code. In place of a
5
+ legal notice, here is a blessing:
6
+
7
+ * May you do good and not evil.
8
+ * May you find forgiveness for yourself and forgive others.
9
+ * May you share freely, never taking more than you give.
10
+
11
+ ***********************************************************************
12
+
13
+ This file glues together disparate pieces of JS which are loaded in
14
+ previous steps of the sqlite3-api.js bootstrapping process:
15
+ sqlite3-api-prologue.js, whwasmutil.js, and jaccwabyt.js. It
16
+ initializes the main API pieces so that the downstream components
17
+ (e.g. sqlite3-api-oo1.js) have all of the infrastructure that they
18
+ need.
19
+ */
20
+ globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
21
+ 'use strict';
22
+ const toss = (...args)=>{throw new Error(args.join(' '))};
23
+ const toss3 = sqlite3.SQLite3Error.toss;
24
+ const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util;
25
+ globalThis.WhWasmUtilInstaller(wasm);
26
+ delete globalThis.WhWasmUtilInstaller;
27
+
28
+ if(0){
29
+ /**
30
+ Please keep this block around as a maintenance reminder
31
+ that we cannot rely on this type of check.
32
+
33
+ This block fails on Safari, per a report at
34
+ https://sqlite.org/forum/forumpost/e5b20e1feb.
35
+
36
+ It turns out that what Safari serves from the indirect function
37
+ table (e.g. wasm.functionEntry(X)) is anonymous functions which
38
+ wrap the WASM functions, rather than returning the WASM
39
+ functions themselves. That means comparison of such functions
40
+ is useless for determining whether or not we have a specific
41
+ function from wasm.exports. i.e. if function X is indirection
42
+ function table entry N then wasm.exports.X is not equal to
43
+ wasm.functionEntry(N) in Safari, despite being so in the other
44
+ browsers.
45
+ */
46
+ /**
47
+ Find a mapping for SQLITE_WASM_DEALLOC, which the API
48
+ guarantees is a WASM pointer to the same underlying function as
49
+ wasm.dealloc() (noting that wasm.dealloc() is permitted to be a
50
+ JS wrapper around the WASM function). There is unfortunately no
51
+ O(1) algorithm for finding this pointer: we have to walk the
52
+ WASM indirect function table to find it. However, experience
53
+ indicates that that particular function is always very close to
54
+ the front of the table (it's been entry #3 in all relevant
55
+ tests).
56
+ */
57
+ const dealloc = wasm.exports[sqlite3.config.deallocExportName];
58
+ const nFunc = wasm.functionTable().length;
59
+ let i;
60
+ for(i = 0; i < nFunc; ++i){
61
+ const e = wasm.functionEntry(i);
62
+ if(dealloc === e){
63
+ capi.SQLITE_WASM_DEALLOC = i;
64
+ break;
65
+ }
66
+ }
67
+ if(dealloc !== wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)){
68
+ toss("Internal error: cannot find function pointer for SQLITE_WASM_DEALLOC.");
69
+ }
70
+ }
71
+
72
+ /**
73
+ Signatures for the WASM-exported C-side functions. Each entry
74
+ is an array with 2+ elements:
75
+
76
+ [ "c-side name",
77
+ "result type" (wasm.xWrap() syntax),
78
+ [arg types in xWrap() syntax]
79
+ // ^^^ this needn't strictly be an array: it can be subsequent
80
+ // elements instead: [x,y,z] is equivalent to x,y,z
81
+ ]
82
+
83
+ Note that support for the API-specific data types in the
84
+ result/argument type strings gets plugged in at a later phase in
85
+ the API initialization process.
86
+ */
87
+ wasm.bindingSignatures = [
88
+ // Please keep these sorted by function name!
89
+ ["sqlite3_aggregate_context","void*", "sqlite3_context*", "int"],
90
+ /* sqlite3_auto_extension() has a hand-written binding. */
91
+ /* sqlite3_bind_blob() and sqlite3_bind_text() have hand-written
92
+ bindings to permit more flexible inputs. */
93
+ ["sqlite3_bind_double","int", "sqlite3_stmt*", "int", "f64"],
94
+ ["sqlite3_bind_int","int", "sqlite3_stmt*", "int", "int"],
95
+ ["sqlite3_bind_null",undefined, "sqlite3_stmt*", "int"],
96
+ ["sqlite3_bind_parameter_count", "int", "sqlite3_stmt*"],
97
+ ["sqlite3_bind_parameter_index","int", "sqlite3_stmt*", "string"],
98
+ ["sqlite3_bind_parameter_name", "string", "sqlite3_stmt*", "int"],
99
+ ["sqlite3_bind_pointer", "int",
100
+ "sqlite3_stmt*", "int", "*", "string:static", "*"],
101
+ ["sqlite3_busy_handler","int", [
102
+ "sqlite3*",
103
+ new wasm.xWrap.FuncPtrAdapter({
104
+ signature: 'i(pi)',
105
+ contextKey: (argv,argIndex)=>argv[0/* sqlite3* */]
106
+ }),
107
+ "*"
108
+ ]],
109
+ ["sqlite3_busy_timeout","int", "sqlite3*", "int"],
110
+ /* sqlite3_cancel_auto_extension() has a hand-written binding. */
111
+ /* sqlite3_close_v2() is implemented by hand to perform some
112
+ extra work. */
113
+ ["sqlite3_changes", "int", "sqlite3*"],
114
+ ["sqlite3_clear_bindings","int", "sqlite3_stmt*"],
115
+ ["sqlite3_collation_needed", "int", "sqlite3*", "*", "*"/*=>v(ppis)*/],
116
+ ["sqlite3_column_blob","*", "sqlite3_stmt*", "int"],
117
+ ["sqlite3_column_bytes","int", "sqlite3_stmt*", "int"],
118
+ ["sqlite3_column_count", "int", "sqlite3_stmt*"],
119
+ ["sqlite3_column_decltype", "string", "sqlite3_stmt*", "int"],
120
+ ["sqlite3_column_double","f64", "sqlite3_stmt*", "int"],
121
+ ["sqlite3_column_int","int", "sqlite3_stmt*", "int"],
122
+ ["sqlite3_column_name","string", "sqlite3_stmt*", "int"],
123
+ ["sqlite3_column_text","string", "sqlite3_stmt*", "int"],
124
+ ["sqlite3_column_type","int", "sqlite3_stmt*", "int"],
125
+ ["sqlite3_column_value","sqlite3_value*", "sqlite3_stmt*", "int"],
126
+ ["sqlite3_commit_hook", "void*", [
127
+ "sqlite3*",
128
+ new wasm.xWrap.FuncPtrAdapter({
129
+ name: 'sqlite3_commit_hook',
130
+ signature: 'i(p)',
131
+ contextKey: (argv)=>argv[0/* sqlite3* */]
132
+ }),
133
+ '*'
134
+ ]],
135
+ ["sqlite3_compileoption_get", "string", "int"],
136
+ ["sqlite3_compileoption_used", "int", "string"],
137
+ ["sqlite3_complete", "int", "string:flexible"],
138
+ ["sqlite3_context_db_handle", "sqlite3*", "sqlite3_context*"],
139
+ /* sqlite3_create_collation() and sqlite3_create_collation_v2()
140
+ use hand-written bindings to simplify passing of the callback
141
+ function. */
142
+ /* sqlite3_create_function(), sqlite3_create_function_v2(), and
143
+ sqlite3_create_window_function() use hand-written bindings to
144
+ simplify handling of their function-type arguments. */
145
+ ["sqlite3_data_count", "int", "sqlite3_stmt*"],
146
+ ["sqlite3_db_filename", "string", "sqlite3*", "string"],
147
+ ["sqlite3_db_handle", "sqlite3*", "sqlite3_stmt*"],
148
+ ["sqlite3_db_name", "string", "sqlite3*", "int"],
149
+ ["sqlite3_db_readonly", "int", "sqlite3*", "string"],
150
+ ["sqlite3_db_status", "int", "sqlite3*", "int", "*", "*", "int"],
151
+ ["sqlite3_errcode", "int", "sqlite3*"],
152
+ ["sqlite3_errmsg", "string", "sqlite3*"],
153
+ ["sqlite3_error_offset", "int", "sqlite3*"],
154
+ ["sqlite3_errstr", "string", "int"],
155
+ ["sqlite3_exec", "int", [
156
+ "sqlite3*", "string:flexible",
157
+ new wasm.xWrap.FuncPtrAdapter({
158
+ signature: 'i(pipp)',
159
+ bindScope: 'transient',
160
+ callProxy: (callback)=>{
161
+ let aNames;
162
+ return (pVoid, nCols, pColVals, pColNames)=>{
163
+ try {
164
+ const aVals = wasm.cArgvToJs(nCols, pColVals);
165
+ if(!aNames) aNames = wasm.cArgvToJs(nCols, pColNames);
166
+ return callback(aVals, aNames) | 0;
167
+ }catch(e){
168
+ /* If we set the db error state here, the higher-level
169
+ exec() call replaces it with its own, so we have no way
170
+ of reporting the exception message except the console. We
171
+ must not propagate exceptions through the C API. Though
172
+ we make an effort to report OOM here, sqlite3_exec()
173
+ translates that into SQLITE_ABORT as well. */
174
+ return e.resultCode || capi.SQLITE_ERROR;
175
+ }
176
+ }
177
+ }
178
+ }),
179
+ "*", "**"
180
+ ]],
181
+ ["sqlite3_expanded_sql", "string", "sqlite3_stmt*"],
182
+ ["sqlite3_extended_errcode", "int", "sqlite3*"],
183
+ ["sqlite3_extended_result_codes", "int", "sqlite3*", "int"],
184
+ ["sqlite3_file_control", "int", "sqlite3*", "string", "int", "*"],
185
+ ["sqlite3_finalize", "int", "sqlite3_stmt*"],
186
+ ["sqlite3_free", undefined,"*"],
187
+ ["sqlite3_get_autocommit", "int", "sqlite3*"],
188
+ ["sqlite3_get_auxdata", "*", "sqlite3_context*", "int"],
189
+ ["sqlite3_initialize", undefined],
190
+ ["sqlite3_interrupt", undefined, "sqlite3*"],
191
+ ["sqlite3_is_interrupted", "int", "sqlite3*"],
192
+ ["sqlite3_keyword_count", "int"],
193
+ ["sqlite3_keyword_name", "int", ["int", "**", "*"]],
194
+ ["sqlite3_keyword_check", "int", ["string", "int"]],
195
+ ["sqlite3_libversion", "string"],
196
+ ["sqlite3_libversion_number", "int"],
197
+ ["sqlite3_limit", "int", ["sqlite3*", "int", "int"]],
198
+ ["sqlite3_malloc", "*","int"],
199
+ ["sqlite3_open", "int", "string", "*"],
200
+ ["sqlite3_open_v2", "int", "string", "*", "int", "string"],
201
+ /* sqlite3_prepare_v2() and sqlite3_prepare_v3() are handled
202
+ separately due to us requiring two different sets of semantics
203
+ for those, depending on how their SQL argument is provided. */
204
+ /* sqlite3_randomness() uses a hand-written wrapper to extend
205
+ the range of supported argument types. */
206
+ ["sqlite3_realloc", "*","*","int"],
207
+ ["sqlite3_reset", "int", "sqlite3_stmt*"],
208
+ /* sqlite3_reset_auto_extension() has a hand-written binding. */
209
+ ["sqlite3_result_blob", undefined, "sqlite3_context*", "*", "int", "*"],
210
+ ["sqlite3_result_double", undefined, "sqlite3_context*", "f64"],
211
+ ["sqlite3_result_error", undefined, "sqlite3_context*", "string", "int"],
212
+ ["sqlite3_result_error_code", undefined, "sqlite3_context*", "int"],
213
+ ["sqlite3_result_error_nomem", undefined, "sqlite3_context*"],
214
+ ["sqlite3_result_error_toobig", undefined, "sqlite3_context*"],
215
+ ["sqlite3_result_int", undefined, "sqlite3_context*", "int"],
216
+ ["sqlite3_result_null", undefined, "sqlite3_context*"],
217
+ ["sqlite3_result_pointer", undefined,
218
+ "sqlite3_context*", "*", "string:static", "*"],
219
+ ["sqlite3_result_subtype", undefined, "sqlite3_value*", "int"],
220
+ ["sqlite3_result_text", undefined, "sqlite3_context*", "string", "int", "*"],
221
+ ["sqlite3_result_zeroblob", undefined, "sqlite3_context*", "int"],
222
+ ["sqlite3_rollback_hook", "void*", [
223
+ "sqlite3*",
224
+ new wasm.xWrap.FuncPtrAdapter({
225
+ name: 'sqlite3_rollback_hook',
226
+ signature: 'v(p)',
227
+ contextKey: (argv)=>argv[0/* sqlite3* */]
228
+ }),
229
+ '*'
230
+ ]],
231
+ ["sqlite3_set_auxdata", undefined, [
232
+ "sqlite3_context*", "int", "*",
233
+ new wasm.xWrap.FuncPtrAdapter({
234
+ name: 'xDestroyAuxData',
235
+ signature: 'v(*)',
236
+ contextKey: (argv, argIndex)=>argv[0/* sqlite3_context* */]
237
+ })
238
+ ]],
239
+ ["sqlite3_shutdown", undefined],
240
+ ["sqlite3_sourceid", "string"],
241
+ ["sqlite3_sql", "string", "sqlite3_stmt*"],
242
+ ["sqlite3_status", "int", "int", "*", "*", "int"],
243
+ ["sqlite3_step", "int", "sqlite3_stmt*"],
244
+ ["sqlite3_stmt_busy", "int", "sqlite3_stmt*"],
245
+ ["sqlite3_stmt_readonly", "int", "sqlite3_stmt*"],
246
+ ["sqlite3_stmt_status", "int", "sqlite3_stmt*", "int", "int"],
247
+ ["sqlite3_strglob", "int", "string","string"],
248
+ ["sqlite3_stricmp", "int", "string", "string"],
249
+ ["sqlite3_strlike", "int", "string", "string","int"],
250
+ ["sqlite3_strnicmp", "int", "string", "string", "int"],
251
+ ["sqlite3_table_column_metadata", "int",
252
+ "sqlite3*", "string", "string", "string",
253
+ "**", "**", "*", "*", "*"],
254
+ ["sqlite3_total_changes", "int", "sqlite3*"],
255
+ ["sqlite3_trace_v2", "int", [
256
+ "sqlite3*", "int",
257
+ new wasm.xWrap.FuncPtrAdapter({
258
+ name: 'sqlite3_trace_v2::callback',
259
+ signature: 'i(ippp)',
260
+ contextKey: (argv,argIndex)=>argv[0/* sqlite3* */]
261
+ }),
262
+ "*"
263
+ ]],
264
+ ["sqlite3_txn_state", "int", ["sqlite3*","string"]],
265
+ /* Note that sqlite3_uri_...() have very specific requirements for
266
+ their first C-string arguments, so we cannot perform any value
267
+ conversion on those. */
268
+ ["sqlite3_uri_boolean", "int", "sqlite3_filename", "string", "int"],
269
+ ["sqlite3_uri_key", "string", "sqlite3_filename", "int"],
270
+ ["sqlite3_uri_parameter", "string", "sqlite3_filename", "string"],
271
+ ["sqlite3_user_data","void*", "sqlite3_context*"],
272
+ ["sqlite3_value_blob", "*", "sqlite3_value*"],
273
+ ["sqlite3_value_bytes","int", "sqlite3_value*"],
274
+ ["sqlite3_value_double","f64", "sqlite3_value*"],
275
+ ["sqlite3_value_dup", "sqlite3_value*", "sqlite3_value*"],
276
+ ["sqlite3_value_free", undefined, "sqlite3_value*"],
277
+ ["sqlite3_value_frombind", "int", "sqlite3_value*"],
278
+ ["sqlite3_value_int","int", "sqlite3_value*"],
279
+ ["sqlite3_value_nochange", "int", "sqlite3_value*"],
280
+ ["sqlite3_value_numeric_type", "int", "sqlite3_value*"],
281
+ ["sqlite3_value_pointer", "*", "sqlite3_value*", "string:static"],
282
+ ["sqlite3_value_subtype", "int", "sqlite3_value*"],
283
+ ["sqlite3_value_text", "string", "sqlite3_value*"],
284
+ ["sqlite3_value_type", "int", "sqlite3_value*"],
285
+ ["sqlite3_vfs_find", "*", "string"],
286
+ ["sqlite3_vfs_register", "int", "sqlite3_vfs*", "int"],
287
+ ["sqlite3_vfs_unregister", "int", "sqlite3_vfs*"]
288
+ ]/*wasm.bindingSignatures*/;
289
+
290
+ if( !!wasm.exports.sqlite3_progress_handler ){
291
+ wasm.bindingSignatures.push(
292
+ ["sqlite3_progress_handler", undefined, [
293
+ "sqlite3*", "int", new wasm.xWrap.FuncPtrAdapter({
294
+ name: 'xProgressHandler',
295
+ signature: 'i(p)',
296
+ bindScope: 'context',
297
+ contextKey: (argv,argIndex)=>argv[0/* sqlite3* */]
298
+ }), "*"
299
+ ]]
300
+ );
301
+ }
302
+
303
+ if( !!wasm.exports.sqlite3_stmt_explain ){
304
+ wasm.bindingSignatures.push(
305
+ ["sqlite3_stmt_explain", "int", "sqlite3_stmt*", "int"],
306
+ ["sqlite3_stmt_isexplain", "int", "sqlite3_stmt*"]
307
+ );
308
+ }
309
+
310
+ if( !!wasm.exports.sqlite3_set_authorizer ){
311
+ wasm.bindingSignatures.push(
312
+ ["sqlite3_set_authorizer", "int", [
313
+ "sqlite3*",
314
+ new wasm.xWrap.FuncPtrAdapter({
315
+ name: "sqlite3_set_authorizer::xAuth",
316
+ signature: "i(pi"+"ssss)",
317
+ contextKey: (argv, argIndex)=>argv[0/*(sqlite3*)*/],
318
+ callProxy: (callback)=>{
319
+ return (pV, iCode, s0, s1, s2, s3)=>{
320
+ try{
321
+ s0 = s0 && wasm.cstrToJs(s0); s1 = s1 && wasm.cstrToJs(s1);
322
+ s2 = s2 && wasm.cstrToJs(s2); s3 = s3 && wasm.cstrToJs(s3);
323
+ return callback(pV, iCode, s0, s1, s2, s3) || 0;
324
+ }catch(e){
325
+ return e.resultCode || capi.SQLITE_ERROR;
326
+ }
327
+ }
328
+ }
329
+ }),
330
+ "*"/*pUserData*/
331
+ ]]
332
+ );
333
+ }/* sqlite3_set_authorizer() */
334
+
335
+ if(false && wasm.compileOptionUsed('SQLITE_ENABLE_NORMALIZE')){
336
+ /* ^^^ "the problem" is that this is an optional feature and the
337
+ build-time function-export list does not currently take
338
+ optional features into account. */
339
+ wasm.bindingSignatures.push(["sqlite3_normalized_sql", "string", "sqlite3_stmt*"]);
340
+ }
341
+
342
+ //#if enable-see
343
+ if(wasm.exports.sqlite3_key_v2 instanceof Function){
344
+ /**
345
+ This code is capable of using an SEE build but note that an SEE
346
+ WASM build is generally incompatible with SEE's license
347
+ conditions. It is permitted for use internally in organizations
348
+ which have licensed SEE, but not for public sites because
349
+ exposing an SEE build of sqlite3.wasm effectively provides all
350
+ clients with a working copy of the commercial SEE code.
351
+ */
352
+ wasm.bindingSignatures.push(
353
+ ["sqlite3_key", "int", "sqlite3*", "string", "int"],
354
+ ["sqlite3_key_v2","int","sqlite3*","string","*","int"],
355
+ ["sqlite3_rekey", "int", "sqlite3*", "string", "int"],
356
+ ["sqlite3_rekey_v2", "int", "sqlite3*", "string", "*", "int"],
357
+ ["sqlite3_activate_see", undefined, "string"]
358
+ );
359
+ }
360
+ //#endif enable-see
361
+
362
+ /**
363
+ Functions which require BigInt (int64) support are separated from
364
+ the others because we need to conditionally bind them or apply
365
+ dummy impls, depending on the capabilities of the environment.
366
+ (That said: we never actually build without BigInt support,
367
+ and such builds are untested.)
368
+
369
+ Note that not all of these functions directly require int64
370
+ but are only for use with APIs which require int64. For example,
371
+ the vtab-related functions.
372
+ */
373
+ wasm.bindingSignatures.int64 = [
374
+ ["sqlite3_bind_int64","int", ["sqlite3_stmt*", "int", "i64"]],
375
+ ["sqlite3_changes64","i64", ["sqlite3*"]],
376
+ ["sqlite3_column_int64","i64", ["sqlite3_stmt*", "int"]],
377
+ ["sqlite3_deserialize", "int", "sqlite3*", "string", "*", "i64", "i64", "int"]
378
+ /* Careful! Short version: de/serialize() are problematic because they
379
+ might use a different allocator than the user for managing the
380
+ deserialized block. de/serialize() are ONLY safe to use with
381
+ sqlite3_malloc(), sqlite3_free(), and its 64-bit variants. Because
382
+ of this, the canonical builds of sqlite3.wasm/js guarantee that
383
+ sqlite3.wasm.alloc() and friends use those allocators. Custom builds
384
+ may not guarantee that, however. */,
385
+ ["sqlite3_last_insert_rowid", "i64", ["sqlite3*"]],
386
+ ["sqlite3_malloc64", "*","i64"],
387
+ ["sqlite3_msize", "i64", "*"],
388
+ ["sqlite3_overload_function", "int", ["sqlite3*","string","int"]],
389
+ ["sqlite3_realloc64", "*","*", "i64"],
390
+ ["sqlite3_result_int64", undefined, "*", "i64"],
391
+ ["sqlite3_result_zeroblob64", "int", "*", "i64"],
392
+ ["sqlite3_serialize","*", "sqlite3*", "string", "*", "int"],
393
+ ["sqlite3_set_last_insert_rowid", undefined, ["sqlite3*", "i64"]],
394
+ ["sqlite3_status64", "int", "int", "*", "*", "int"],
395
+ ["sqlite3_total_changes64", "i64", ["sqlite3*"]],
396
+ ["sqlite3_update_hook", "*", [
397
+ "sqlite3*",
398
+ new wasm.xWrap.FuncPtrAdapter({
399
+ name: 'sqlite3_update_hook',
400
+ signature: "v(iippj)",
401
+ contextKey: (argv)=>argv[0/* sqlite3* */],
402
+ callProxy: (callback)=>{
403
+ return (p,op,z0,z1,rowid)=>{
404
+ callback(p, op, wasm.cstrToJs(z0), wasm.cstrToJs(z1), rowid);
405
+ };
406
+ }
407
+ }),
408
+ "*"
409
+ ]],
410
+ ["sqlite3_uri_int64", "i64", ["sqlite3_filename", "string", "i64"]],
411
+ ["sqlite3_value_int64","i64", "sqlite3_value*"]
412
+ ];
413
+
414
+ if( wasm.bigIntEnabled && !!wasm.exports.sqlite3_declare_vtab ){
415
+ wasm.bindingSignatures.int64.push(
416
+ ["sqlite3_create_module", "int",
417
+ ["sqlite3*","string","sqlite3_module*","*"]],
418
+ ["sqlite3_create_module_v2", "int",
419
+ ["sqlite3*","string","sqlite3_module*","*","*"]],
420
+ ["sqlite3_declare_vtab", "int", ["sqlite3*", "string:flexible"]],
421
+ ["sqlite3_drop_modules", "int", ["sqlite3*", "**"]],
422
+ ["sqlite3_vtab_collation","string","sqlite3_index_info*","int"],
423
+ ["sqlite3_vtab_distinct","int", "sqlite3_index_info*"],
424
+ ["sqlite3_vtab_in","int", "sqlite3_index_info*", "int", "int"],
425
+ ["sqlite3_vtab_in_first", "int", "sqlite3_value*", "**"],
426
+ ["sqlite3_vtab_in_next", "int", "sqlite3_value*", "**"],
427
+ /*["sqlite3_vtab_config" is variadic and requires a hand-written
428
+ proxy.] */
429
+ ["sqlite3_vtab_nochange","int", "sqlite3_context*"],
430
+ ["sqlite3_vtab_on_conflict","int", "sqlite3*"],
431
+ ["sqlite3_vtab_rhs_value","int", "sqlite3_index_info*", "int", "**"]
432
+ );
433
+ }/* virtual table APIs */
434
+
435
+ if(wasm.bigIntEnabled && !!wasm.exports.sqlite3_preupdate_hook){
436
+ wasm.bindingSignatures.int64.push(
437
+ ["sqlite3_preupdate_blobwrite", "int", "sqlite3*"],
438
+ ["sqlite3_preupdate_count", "int", "sqlite3*"],
439
+ ["sqlite3_preupdate_depth", "int", "sqlite3*"],
440
+ ["sqlite3_preupdate_hook", "*", [
441
+ "sqlite3*",
442
+ new wasm.xWrap.FuncPtrAdapter({
443
+ name: 'sqlite3_preupdate_hook',
444
+ signature: "v(ppippjj)",
445
+ contextKey: (argv)=>argv[0/* sqlite3* */],
446
+ callProxy: (callback)=>{
447
+ return (p,db,op,zDb,zTbl,iKey1,iKey2)=>{
448
+ callback(p, db, op, wasm.cstrToJs(zDb), wasm.cstrToJs(zTbl),
449
+ iKey1, iKey2);
450
+ };
451
+ }
452
+ }),
453
+ "*"
454
+ ]],
455
+ ["sqlite3_preupdate_new", "int", ["sqlite3*", "int", "**"]],
456
+ ["sqlite3_preupdate_old", "int", ["sqlite3*", "int", "**"]]
457
+ );
458
+ } /* preupdate API */
459
+
460
+ // Add session/changeset APIs...
461
+ if(wasm.bigIntEnabled
462
+ && !!wasm.exports.sqlite3changegroup_add
463
+ && !!wasm.exports.sqlite3session_create
464
+ && !!wasm.exports.sqlite3_preupdate_hook /* required by the session API */){
465
+ /**
466
+ FuncPtrAdapter options for session-related callbacks with the
467
+ native signature "i(ps)". This proxy converts the 2nd argument
468
+ from a C string to a JS string before passing the arguments on
469
+ to the client-provided JS callback.
470
+ */
471
+ const __ipsProxy = {
472
+ signature: 'i(ps)',
473
+ callProxy:(callback)=>{
474
+ return (p,s)=>{
475
+ try{return callback(p, wasm.cstrToJs(s)) | 0}
476
+ catch(e){return e.resultCode || capi.SQLITE_ERROR}
477
+ }
478
+ }
479
+ };
480
+
481
+ wasm.bindingSignatures.int64.push(...[
482
+ ['sqlite3changegroup_add', 'int', ['sqlite3_changegroup*', 'int', 'void*']],
483
+ ['sqlite3changegroup_add_strm', 'int', [
484
+ 'sqlite3_changegroup*',
485
+ new wasm.xWrap.FuncPtrAdapter({
486
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
487
+ }),
488
+ 'void*'
489
+ ]],
490
+ ['sqlite3changegroup_delete', undefined, ['sqlite3_changegroup*']],
491
+ ['sqlite3changegroup_new', 'int', ['**']],
492
+ ['sqlite3changegroup_output', 'int', ['sqlite3_changegroup*', 'int*', '**']],
493
+ ['sqlite3changegroup_output_strm', 'int', [
494
+ 'sqlite3_changegroup*',
495
+ new wasm.xWrap.FuncPtrAdapter({
496
+ name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient'
497
+ }),
498
+ 'void*'
499
+ ]],
500
+ ['sqlite3changeset_apply', 'int', [
501
+ 'sqlite3*', 'int', 'void*',
502
+ new wasm.xWrap.FuncPtrAdapter({
503
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
504
+ }),
505
+ new wasm.xWrap.FuncPtrAdapter({
506
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
507
+ }),
508
+ 'void*'
509
+ ]],
510
+ ['sqlite3changeset_apply_strm', 'int', [
511
+ 'sqlite3*',
512
+ new wasm.xWrap.FuncPtrAdapter({
513
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
514
+ }),
515
+ 'void*',
516
+ new wasm.xWrap.FuncPtrAdapter({
517
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
518
+ }),
519
+ new wasm.xWrap.FuncPtrAdapter({
520
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
521
+ }),
522
+ 'void*'
523
+ ]],
524
+ ['sqlite3changeset_apply_v2', 'int', [
525
+ 'sqlite3*', 'int', 'void*',
526
+ new wasm.xWrap.FuncPtrAdapter({
527
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
528
+ }),
529
+ new wasm.xWrap.FuncPtrAdapter({
530
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
531
+ }),
532
+ 'void*', '**', 'int*', 'int'
533
+
534
+ ]],
535
+ ['sqlite3changeset_apply_v2_strm', 'int', [
536
+ 'sqlite3*',
537
+ new wasm.xWrap.FuncPtrAdapter({
538
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
539
+ }),
540
+ 'void*',
541
+ new wasm.xWrap.FuncPtrAdapter({
542
+ name: 'xFilter', bindScope: 'transient', ...__ipsProxy
543
+ }),
544
+ new wasm.xWrap.FuncPtrAdapter({
545
+ name: 'xConflict', signature: 'i(pip)', bindScope: 'transient'
546
+ }),
547
+ 'void*', '**', 'int*', 'int'
548
+ ]],
549
+ ['sqlite3changeset_concat', 'int', ['int','void*', 'int', 'void*', 'int*', '**']],
550
+ ['sqlite3changeset_concat_strm', 'int', [
551
+ new wasm.xWrap.FuncPtrAdapter({
552
+ name: 'xInputA', signature: 'i(ppp)', bindScope: 'transient'
553
+ }),
554
+ 'void*',
555
+ new wasm.xWrap.FuncPtrAdapter({
556
+ name: 'xInputB', signature: 'i(ppp)', bindScope: 'transient'
557
+ }),
558
+ 'void*',
559
+ new wasm.xWrap.FuncPtrAdapter({
560
+ name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient'
561
+ }),
562
+ 'void*'
563
+ ]],
564
+ ['sqlite3changeset_conflict', 'int', ['sqlite3_changeset_iter*', 'int', '**']],
565
+ ['sqlite3changeset_finalize', 'int', ['sqlite3_changeset_iter*']],
566
+ ['sqlite3changeset_fk_conflicts', 'int', ['sqlite3_changeset_iter*', 'int*']],
567
+ ['sqlite3changeset_invert', 'int', ['int', 'void*', 'int*', '**']],
568
+ ['sqlite3changeset_invert_strm', 'int', [
569
+ new wasm.xWrap.FuncPtrAdapter({
570
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
571
+ }),
572
+ 'void*',
573
+ new wasm.xWrap.FuncPtrAdapter({
574
+ name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient'
575
+ }),
576
+ 'void*'
577
+ ]],
578
+ ['sqlite3changeset_new', 'int', ['sqlite3_changeset_iter*', 'int', '**']],
579
+ ['sqlite3changeset_next', 'int', ['sqlite3_changeset_iter*']],
580
+ ['sqlite3changeset_old', 'int', ['sqlite3_changeset_iter*', 'int', '**']],
581
+ ['sqlite3changeset_op', 'int', [
582
+ 'sqlite3_changeset_iter*', '**', 'int*', 'int*','int*'
583
+ ]],
584
+ ['sqlite3changeset_pk', 'int', ['sqlite3_changeset_iter*', '**', 'int*']],
585
+ ['sqlite3changeset_start', 'int', ['**', 'int', '*']],
586
+ ['sqlite3changeset_start_strm', 'int', [
587
+ '**',
588
+ new wasm.xWrap.FuncPtrAdapter({
589
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
590
+ }),
591
+ 'void*'
592
+ ]],
593
+ ['sqlite3changeset_start_v2', 'int', ['**', 'int', '*', 'int']],
594
+ ['sqlite3changeset_start_v2_strm', 'int', [
595
+ '**',
596
+ new wasm.xWrap.FuncPtrAdapter({
597
+ name: 'xInput', signature: 'i(ppp)', bindScope: 'transient'
598
+ }),
599
+ 'void*', 'int'
600
+ ]],
601
+ ['sqlite3session_attach', 'int', ['sqlite3_session*', 'string']],
602
+ ['sqlite3session_changeset', 'int', ['sqlite3_session*', 'int*', '**']],
603
+ ['sqlite3session_changeset_size', 'i64', ['sqlite3_session*']],
604
+ ['sqlite3session_changeset_strm', 'int', [
605
+ 'sqlite3_session*',
606
+ new wasm.xWrap.FuncPtrAdapter({
607
+ name: 'xOutput', signature: 'i(ppp)', bindScope: 'transient'
608
+ }),
609
+ 'void*'
610
+ ]],
611
+ ['sqlite3session_config', 'int', ['int', 'void*']],
612
+ ['sqlite3session_create', 'int', ['sqlite3*', 'string', '**']],
613
+ //sqlite3session_delete() is bound manually
614
+ ['sqlite3session_diff', 'int', ['sqlite3_session*', 'string', 'string', '**']],
615
+ ['sqlite3session_enable', 'int', ['sqlite3_session*', 'int']],
616
+ ['sqlite3session_indirect', 'int', ['sqlite3_session*', 'int']],
617
+ ['sqlite3session_isempty', 'int', ['sqlite3_session*']],
618
+ ['sqlite3session_memory_used', 'i64', ['sqlite3_session*']],
619
+ ['sqlite3session_object_config', 'int', ['sqlite3_session*', 'int', 'void*']],
620
+ ['sqlite3session_patchset', 'int', ['sqlite3_session*', '*', '**']],
621
+ ['sqlite3session_patchset_strm', 'int', [
622
+ 'sqlite3_session*',
623
+ new wasm.xWrap.FuncPtrAdapter({
624
+ name: 'xOutput', signature: 'i(ppp)', bindScope: 'transient'
625
+ }),
626
+ 'void*'
627
+ ]],
628
+ ['sqlite3session_table_filter', undefined, [
629
+ 'sqlite3_session*',
630
+ new wasm.xWrap.FuncPtrAdapter({
631
+ name: 'xFilter', ...__ipsProxy,
632
+ contextKey: (argv,argIndex)=>argv[0/* (sqlite3_session*) */]
633
+ }),
634
+ '*'
635
+ ]]
636
+ ]);
637
+ }/*session/changeset APIs*/
638
+
639
+ /**
640
+ Functions which are intended solely for API-internal use by the
641
+ WASM components, not client code. These get installed into
642
+ sqlite3.util. Some of them get exposed to clients via variants
643
+ in sqlite3_js_...().
644
+
645
+ 2024-01-11: these were renamed, with two underscores in the
646
+ prefix, to ensure that clients do not accidentally depend on
647
+ them. They have always been documented as internal-use-only, so
648
+ no clients "should" be depending on the old names.
649
+ */
650
+ wasm.bindingSignatures.wasmInternal = [
651
+ ["sqlite3__wasm_db_reset", "int", "sqlite3*"],
652
+ ["sqlite3__wasm_db_vfs", "sqlite3_vfs*", "sqlite3*","string"],
653
+ [/* DO NOT USE. This is deprecated since 2023-08-11 because it can
654
+ trigger assert() in debug builds when used with file sizes
655
+ which are not sizes to a multiple of a valid db page size. */
656
+ "sqlite3__wasm_vfs_create_file", "int", "sqlite3_vfs*","string","*", "int"
657
+ ],
658
+ ["sqlite3__wasm_posix_create_file", "int", "string","*", "int"],
659
+ ["sqlite3__wasm_vfs_unlink", "int", "sqlite3_vfs*","string"],
660
+ ["sqlite3__wasm_qfmt_token","string:dealloc", "string","int"]
661
+ ];
662
+
663
+ /**
664
+ Install JS<->C struct bindings for the non-opaque struct types we
665
+ need... */
666
+ sqlite3.StructBinder = globalThis.Jaccwabyt({
667
+ heap: 0 ? wasm.memory : wasm.heap8u,
668
+ alloc: wasm.alloc,
669
+ dealloc: wasm.dealloc,
670
+ bigIntEnabled: wasm.bigIntEnabled,
671
+ memberPrefix: /* Never change this: this prefix is baked into any
672
+ amount of code and client-facing docs. */ '$'
673
+ });
674
+ delete globalThis.Jaccwabyt;
675
+
676
+ {// wasm.xWrap() bindings...
677
+
678
+ /* Convert Arrays and certain TypedArrays to strings for
679
+ 'string:flexible'-type arguments */
680
+ const __xString = wasm.xWrap.argAdapter('string');
681
+ wasm.xWrap.argAdapter(
682
+ 'string:flexible', (v)=>__xString(util.flexibleString(v))
683
+ );
684
+
685
+ /**
686
+ The 'string:static' argument adapter treats its argument as
687
+ either...
688
+
689
+ - WASM pointer: assumed to be a long-lived C-string which gets
690
+ returned as-is.
691
+
692
+ - Anything else: gets coerced to a JS string for use as a map
693
+ key. If a matching entry is found (as described next), it is
694
+ returned, else wasm.allocCString() is used to create a a new
695
+ string, map its pointer to (''+v) for the remainder of the
696
+ application's life, and returns that pointer value for this
697
+ call and all future calls which are passed a
698
+ string-equivalent argument.
699
+
700
+ Use case: sqlite3_bind_pointer() and sqlite3_result_pointer()
701
+ call for "a static string and preferably a string
702
+ literal." This converter is used to ensure that the string
703
+ value seen by those functions is long-lived and behaves as they
704
+ need it to.
705
+ */
706
+ wasm.xWrap.argAdapter(
707
+ 'string:static',
708
+ function(v){
709
+ if(wasm.isPtr(v)) return v;
710
+ v = ''+v;
711
+ let rc = this[v];
712
+ return rc || (this[v] = wasm.allocCString(v));
713
+ }.bind(Object.create(null))
714
+ );
715
+
716
+ /**
717
+ Add some descriptive xWrap() aliases for '*' intended to (A)
718
+ initially improve readability/correctness of
719
+ wasm.bindingSignatures and (B) provide automatic conversion
720
+ from higher-level representations, e.g. capi.sqlite3_vfs to
721
+ `sqlite3_vfs*` via capi.sqlite3_vfs.pointer.
722
+ */
723
+ const __xArgPtr = wasm.xWrap.argAdapter('*');
724
+ const nilType = function(){
725
+ /*a class which no value can ever be an instance of*/
726
+ };
727
+ wasm.xWrap.argAdapter('sqlite3_filename', __xArgPtr)
728
+ ('sqlite3_context*', __xArgPtr)
729
+ ('sqlite3_value*', __xArgPtr)
730
+ ('void*', __xArgPtr)
731
+ ('sqlite3_changegroup*', __xArgPtr)
732
+ ('sqlite3_changeset_iter*', __xArgPtr)
733
+ ('sqlite3_session*', __xArgPtr)
734
+ ('sqlite3_stmt*', (v)=>
735
+ __xArgPtr((v instanceof (sqlite3?.oo1?.Stmt || nilType))
736
+ ? v.pointer : v))
737
+ ('sqlite3*', (v)=>
738
+ __xArgPtr((v instanceof (sqlite3?.oo1?.DB || nilType))
739
+ ? v.pointer : v))
740
+ /**
741
+ `sqlite3_vfs*`:
742
+
743
+ - v is-a string: use the result of sqlite3_vfs_find(v) but
744
+ throw if it returns 0.
745
+ - v is-a capi.sqlite3_vfs: use v.pointer.
746
+ - Else return the same as the `'*'` argument conversion.
747
+ */
748
+ ('sqlite3_vfs*', (v)=>{
749
+ if('string'===typeof v){
750
+ /* A NULL sqlite3_vfs pointer will be treated as the default
751
+ VFS in many contexts. We specifically do not want that
752
+ behavior here. */
753
+ return capi.sqlite3_vfs_find(v)
754
+ || sqlite3.SQLite3Error.toss(
755
+ capi.SQLITE_NOTFOUND,
756
+ "Unknown sqlite3_vfs name:", v
757
+ );
758
+ }
759
+ return __xArgPtr((v instanceof (capi.sqlite3_vfs || nilType))
760
+ ? v.pointer : v);
761
+ });
762
+ if( wasm.exports.sqlite3_declare_vtab ){
763
+ wasm.xWrap.argAdapter('sqlite3_index_info*', (v)=>
764
+ __xArgPtr((v instanceof (capi.sqlite3_index_info || nilType))
765
+ ? v.pointer : v))
766
+ ('sqlite3_module*', (v)=>
767
+ __xArgPtr((v instanceof (capi.sqlite3_module || nilType))
768
+ ? v.pointer : v)
769
+ );
770
+ }
771
+
772
+ const __xRcPtr = wasm.xWrap.resultAdapter('*');
773
+ wasm.xWrap.resultAdapter('sqlite3*', __xRcPtr)
774
+ ('sqlite3_context*', __xRcPtr)
775
+ ('sqlite3_stmt*', __xRcPtr)
776
+ ('sqlite3_value*', __xRcPtr)
777
+ ('sqlite3_vfs*', __xRcPtr)
778
+ ('void*', __xRcPtr);
779
+
780
+ /**
781
+ Populate api object with sqlite3_...() by binding the "raw" wasm
782
+ exports into type-converting proxies using wasm.xWrap().
783
+ */
784
+ if(0 === wasm.exports.sqlite3_step.length){
785
+ /* This environment wraps exports in nullary functions, which means
786
+ we must disable the arg-count validation we otherwise perform
787
+ on the wrappers. */
788
+ wasm.xWrap.doArgcCheck = false;
789
+ sqlite3.config.warn(
790
+ "Disabling sqlite3.wasm.xWrap.doArgcCheck due to environmental quirks."
791
+ );
792
+ }
793
+ for(const e of wasm.bindingSignatures){
794
+ capi[e[0]] = wasm.xWrap.apply(null, e);
795
+ }
796
+ for(const e of wasm.bindingSignatures.wasmInternal){
797
+ util[e[0]] = wasm.xWrap.apply(null, e);
798
+ }
799
+
800
+ /* For C API functions which cannot work properly unless
801
+ wasm.bigIntEnabled is true, install a bogus impl which throws
802
+ if called when bigIntEnabled is false. The alternative would be
803
+ to elide these functions altogether, which seems likely to
804
+ cause more confusion. */
805
+ const fI64Disabled = function(fname){
806
+ return ()=>toss(fname+"() is unavailable due to lack",
807
+ "of BigInt support in this build.");
808
+ };
809
+ for(const e of wasm.bindingSignatures.int64){
810
+ capi[e[0]] = wasm.bigIntEnabled
811
+ ? wasm.xWrap.apply(null, e)
812
+ : fI64Disabled(e[0]);
813
+ }
814
+
815
+ /* There's no need to expose bindingSignatures to clients,
816
+ implicitly making it part of the public interface. */
817
+ delete wasm.bindingSignatures;
818
+
819
+ if(wasm.exports.sqlite3__wasm_db_error){
820
+ const __db_err = wasm.xWrap(
821
+ 'sqlite3__wasm_db_error', 'int', 'sqlite3*', 'int', 'string'
822
+ );
823
+ /**
824
+ Sets the given db's error state. Accepts:
825
+
826
+ - (sqlite3*, int code, string msg)
827
+ - (sqlite3*, Error e [,string msg = ''+e])
828
+
829
+ If passed a WasmAllocError, the message is ignored and the
830
+ result code is SQLITE_NOMEM. If passed any other Error type,
831
+ the result code defaults to SQLITE_ERROR unless the Error
832
+ object has a resultCode property, in which case that is used
833
+ (e.g. SQLite3Error has that). If passed a non-WasmAllocError
834
+ exception, the message string defaults to theError.message.
835
+
836
+ Returns the resulting code. Pass (pDb,0,0) to clear the error
837
+ state.
838
+ */
839
+ util.sqlite3__wasm_db_error = function(pDb, resultCode, message){
840
+ if(resultCode instanceof sqlite3.WasmAllocError){
841
+ resultCode = capi.SQLITE_NOMEM;
842
+ message = 0 /*avoid allocating message string*/;
843
+ }else if(resultCode instanceof Error){
844
+ message = message || ''+resultCode;
845
+ resultCode = (resultCode.resultCode || capi.SQLITE_ERROR);
846
+ }
847
+ return pDb ? __db_err(pDb, resultCode, message) : resultCode;
848
+ };
849
+ }else{
850
+ util.sqlite3__wasm_db_error = function(pDb,errCode,msg){
851
+ console.warn("sqlite3__wasm_db_error() is not exported.",arguments);
852
+ return errCode;
853
+ };
854
+ }
855
+ }/*xWrap() bindings*/
856
+
857
+ {/* Import C-level constants and structs... */
858
+ const cJson = wasm.xCall('sqlite3__wasm_enum_json');
859
+ if(!cJson){
860
+ toss("Maintenance required: increase sqlite3__wasm_enum_json()'s",
861
+ "static buffer size!");
862
+ }
863
+ //console.debug('wasm.ctype length =',wasm.cstrlen(cJson));
864
+ wasm.ctype = JSON.parse(wasm.cstrToJs(cJson));
865
+ // Groups of SQLITE_xyz macros...
866
+ const defineGroups = ['access', 'authorizer',
867
+ 'blobFinalizers', 'changeset',
868
+ 'config', 'dataTypes',
869
+ 'dbConfig', 'dbStatus',
870
+ 'encodings', 'fcntl', 'flock', 'ioCap',
871
+ 'limits', 'openFlags',
872
+ 'prepareFlags', 'resultCodes',
873
+ 'sqlite3Status',
874
+ 'stmtStatus', 'syncFlags',
875
+ 'trace', 'txnState', 'udfFlags',
876
+ 'version' ];
877
+ if(wasm.bigIntEnabled){
878
+ defineGroups.push('serialize', 'session', 'vtab');
879
+ }
880
+ for(const t of defineGroups){
881
+ for(const e of Object.entries(wasm.ctype[t])){
882
+ // ^^^ [k,v] there triggers a buggy code transformation via
883
+ // one of the Emscripten-driven optimizers.
884
+ capi[e[0]] = e[1];
885
+ }
886
+ }
887
+ if(!wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)){
888
+ toss("Internal error: cannot resolve exported function",
889
+ "entry SQLITE_WASM_DEALLOC (=="+capi.SQLITE_WASM_DEALLOC+").");
890
+ }
891
+ const __rcMap = Object.create(null);
892
+ for(const t of ['resultCodes']){
893
+ for(const e of Object.entries(wasm.ctype[t])){
894
+ __rcMap[e[1]] = e[0];
895
+ }
896
+ }
897
+ /**
898
+ For the given integer, returns the SQLITE_xxx result code as a
899
+ string, or undefined if no such mapping is found.
900
+ */
901
+ capi.sqlite3_js_rc_str = (rc)=>__rcMap[rc];
902
+ /* Bind all registered C-side structs... */
903
+ const notThese = Object.assign(Object.create(null),{
904
+ // For each struct to NOT register, map its name to true:
905
+ WasmTestStruct: true,
906
+ /* We unregister the kvvfs VFS from Worker threads below. */
907
+ sqlite3_kvvfs_methods: !util.isUIThread(),
908
+ /* sqlite3_index_info and friends require int64: */
909
+ sqlite3_index_info: !wasm.bigIntEnabled,
910
+ sqlite3_index_constraint: !wasm.bigIntEnabled,
911
+ sqlite3_index_orderby: !wasm.bigIntEnabled,
912
+ sqlite3_index_constraint_usage: !wasm.bigIntEnabled
913
+ });
914
+ for(const s of wasm.ctype.structs){
915
+ if(!notThese[s.name]){
916
+ capi[s.name] = sqlite3.StructBinder(s);
917
+ }
918
+ }
919
+ if(capi.sqlite3_index_info){
920
+ /* Move these inner structs into sqlite3_index_info. Binding
921
+ ** them to WASM requires that we create global-scope structs to
922
+ ** model them with, but those are no longer needed after we've
923
+ ** passed them to StructBinder. */
924
+ for(const k of ['sqlite3_index_constraint',
925
+ 'sqlite3_index_orderby',
926
+ 'sqlite3_index_constraint_usage']){
927
+ capi.sqlite3_index_info[k] = capi[k];
928
+ delete capi[k];
929
+ }
930
+ capi.sqlite3_vtab_config = wasm.xWrap(
931
+ 'sqlite3__wasm_vtab_config','int',[
932
+ 'sqlite3*', 'int', 'int']
933
+ );
934
+ }/* end vtab-related setup */
935
+ }/*end C constant and struct imports*/
936
+
937
+ /**
938
+ Internal helper to assist in validating call argument counts in
939
+ the hand-written sqlite3_xyz() wrappers. We do this only for
940
+ consistency with non-special-case wrappings.
941
+ */
942
+ const __dbArgcMismatch = (pDb,f,n)=>{
943
+ return util.sqlite3__wasm_db_error(pDb, capi.SQLITE_MISUSE,
944
+ f+"() requires "+n+" argument"+
945
+ (1===n?"":'s')+".");
946
+ };
947
+
948
+ /** Code duplication reducer for functions which take an encoding
949
+ argument and require SQLITE_UTF8. Sets the db error code to
950
+ SQLITE_FORMAT, installs a descriptive error message,
951
+ and returns SQLITE_FORMAT. */
952
+ const __errEncoding = (pDb)=>{
953
+ return util.sqlite3__wasm_db_error(
954
+ pDb, capi.SQLITE_FORMAT, "SQLITE_UTF8 is the only supported encoding."
955
+ );
956
+ };
957
+
958
+ /**
959
+ __dbCleanupMap is infrastructure for recording registration of
960
+ UDFs and collations so that sqlite3_close_v2() can clean up any
961
+ automated JS-to-WASM function conversions installed by those.
962
+ */
963
+ const __argPDb = (pDb)=>wasm.xWrap.argAdapter('sqlite3*')(pDb);
964
+ const __argStr = (str)=>wasm.isPtr(str) ? wasm.cstrToJs(str) : str;
965
+ const __dbCleanupMap = function(
966
+ pDb, mode/*0=remove, >0=create if needed, <0=do not create if missing*/
967
+ ){
968
+ pDb = __argPDb(pDb);
969
+ let m = this.dbMap.get(pDb);
970
+ if(!mode){
971
+ this.dbMap.delete(pDb);
972
+ return m;
973
+ }else if(!m && mode>0){
974
+ this.dbMap.set(pDb, (m = Object.create(null)));
975
+ }
976
+ return m;
977
+ }.bind(Object.assign(Object.create(null),{
978
+ dbMap: new Map
979
+ }));
980
+
981
+ __dbCleanupMap.addCollation = function(pDb, name){
982
+ const m = __dbCleanupMap(pDb, 1);
983
+ if(!m.collation) m.collation = new Set;
984
+ m.collation.add(__argStr(name).toLowerCase());
985
+ };
986
+
987
+ __dbCleanupMap._addUDF = function(pDb, name, arity, map){
988
+ /* Map UDF name to a Set of arity values */
989
+ name = __argStr(name).toLowerCase();
990
+ let u = map.get(name);
991
+ if(!u) map.set(name, (u = new Set));
992
+ u.add((arity<0) ? -1 : arity);
993
+ };
994
+
995
+ __dbCleanupMap.addFunction = function(pDb, name, arity){
996
+ const m = __dbCleanupMap(pDb, 1);
997
+ if(!m.udf) m.udf = new Map;
998
+ this._addUDF(pDb, name, arity, m.udf);
999
+ };
1000
+
1001
+ if( wasm.exports.sqlite3_create_window_function ){
1002
+ __dbCleanupMap.addWindowFunc = function(pDb, name, arity){
1003
+ const m = __dbCleanupMap(pDb, 1);
1004
+ if(!m.wudf) m.wudf = new Map;
1005
+ this._addUDF(pDb, name, arity, m.wudf);
1006
+ };
1007
+ }
1008
+
1009
+ /**
1010
+ Intended to be called _only_ from sqlite3_close_v2(),
1011
+ passed its non-0 db argument.
1012
+
1013
+ This function frees up certain automatically-installed WASM
1014
+ function bindings which were installed on behalf of the given db,
1015
+ as those may otherwise leak.
1016
+
1017
+ Notable caveat: this is only ever run via
1018
+ sqlite3.capi.sqlite3_close_v2(). If a client, for whatever
1019
+ reason, uses sqlite3.wasm.exports.sqlite3_close_v2() (the
1020
+ function directly exported from WASM), this cleanup will not
1021
+ happen.
1022
+
1023
+ This is not a silver bullet for avoiding automation-related
1024
+ leaks but represents "an honest effort."
1025
+
1026
+ The issue being addressed here is covered at:
1027
+
1028
+ https://sqlite.org/wasm/doc/trunk/api-c-style.md#convert-func-ptr
1029
+ */
1030
+ __dbCleanupMap.cleanup = function(pDb){
1031
+ pDb = __argPDb(pDb);
1032
+ //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = false;
1033
+ /**
1034
+ Installing NULL functions in the C API will remove those
1035
+ bindings. The FuncPtrAdapter which sits between us and the C
1036
+ API will also treat that as an opportunity to
1037
+ wasm.uninstallFunction() any WASM function bindings it has
1038
+ installed for pDb.
1039
+ */
1040
+ const closeArgs = [pDb];
1041
+ for(const name of [
1042
+ 'sqlite3_busy_handler',
1043
+ 'sqlite3_commit_hook',
1044
+ 'sqlite3_preupdate_hook',
1045
+ 'sqlite3_progress_handler',
1046
+ 'sqlite3_rollback_hook',
1047
+ 'sqlite3_set_authorizer',
1048
+ 'sqlite3_trace_v2',
1049
+ 'sqlite3_update_hook'
1050
+ ]) {
1051
+ const x = wasm.exports[name];
1052
+ if( !x ){
1053
+ /* assume it was built without this API */
1054
+ continue;
1055
+ }
1056
+ closeArgs.length = x.length/*==argument count*/
1057
+ /* recall that undefined entries translate to 0 when passed to
1058
+ WASM. */;
1059
+ try{ capi[name](...closeArgs) }
1060
+ catch(e){
1061
+ sqlite3.config.warn("close-time call of",name+"(",closeArgs,") threw:",e);
1062
+ }
1063
+ }
1064
+ const m = __dbCleanupMap(pDb, 0);
1065
+ if(!m) return;
1066
+ if(m.collation){
1067
+ for(const name of m.collation){
1068
+ try{
1069
+ capi.sqlite3_create_collation_v2(
1070
+ pDb, name, capi.SQLITE_UTF8, 0, 0, 0
1071
+ );
1072
+ }catch(e){
1073
+ /*ignored*/
1074
+ }
1075
+ }
1076
+ delete m.collation;
1077
+ }
1078
+ let i;
1079
+ for(i = 0; i < 2; ++i){ /* Clean up UDFs... */
1080
+ const fmap = i ? m.wudf : m.udf;
1081
+ if(!fmap) continue;
1082
+ const func = i
1083
+ ? capi.sqlite3_create_window_function
1084
+ : capi.sqlite3_create_function_v2;
1085
+ for(const e of fmap){
1086
+ const name = e[0], arities = e[1];
1087
+ const fargs = [pDb, name, 0/*arity*/, capi.SQLITE_UTF8, 0, 0, 0, 0, 0];
1088
+ if(i) fargs.push(0);
1089
+ for(const arity of arities){
1090
+ try{ fargs[2] = arity; func.apply(null, fargs); }
1091
+ catch(e){/*ignored*/}
1092
+ }
1093
+ arities.clear();
1094
+ }
1095
+ fmap.clear();
1096
+ }
1097
+ delete m.udf;
1098
+ delete m.wudf;
1099
+ }/*__dbCleanupMap.cleanup()*/;
1100
+
1101
+ {/* Binding of sqlite3_close_v2() */
1102
+ const __sqlite3CloseV2 = wasm.xWrap("sqlite3_close_v2", "int", "sqlite3*");
1103
+ capi.sqlite3_close_v2 = function(pDb){
1104
+ if(1!==arguments.length) return __dbArgcMismatch(pDb, 'sqlite3_close_v2', 1);
1105
+ if(pDb){
1106
+ try{__dbCleanupMap.cleanup(pDb)} catch(e){/*ignored*/}
1107
+ }
1108
+ return __sqlite3CloseV2(pDb);
1109
+ };
1110
+ }/*sqlite3_close_v2()*/
1111
+
1112
+ if(capi.sqlite3session_create){
1113
+ const __sqlite3SessionDelete = wasm.xWrap(
1114
+ 'sqlite3session_delete', undefined, ['sqlite3_session*']
1115
+ );
1116
+ capi.sqlite3session_delete = function(pSession){
1117
+ if(1!==arguments.length){
1118
+ return __dbArgcMismatch(pDb, 'sqlite3session_delete', 1);
1119
+ /* Yes, we're returning a value from a void function. That seems
1120
+ like the lesser evil compared to not maintaining arg-count
1121
+ consistency as we do with other similar bindings. */
1122
+ }
1123
+ else if(pSession){
1124
+ //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = true;
1125
+ capi.sqlite3session_table_filter(pSession, 0, 0);
1126
+ }
1127
+ __sqlite3SessionDelete(pSession);
1128
+ };
1129
+ }
1130
+
1131
+ {/* Bindings for sqlite3_create_collation[_v2]() */
1132
+ // contextKey() impl for wasm.xWrap.FuncPtrAdapter
1133
+ const contextKey = (argv,argIndex)=>{
1134
+ return 'argv['+argIndex+']:'+argv[0/* sqlite3* */]+
1135
+ ':'+wasm.cstrToJs(argv[1/* collation name */]).toLowerCase()
1136
+ };
1137
+ const __sqlite3CreateCollationV2 = wasm.xWrap(
1138
+ 'sqlite3_create_collation_v2', 'int', [
1139
+ 'sqlite3*', 'string', 'int', '*',
1140
+ new wasm.xWrap.FuncPtrAdapter({
1141
+ /* int(*xCompare)(void*,int,const void*,int,const void*) */
1142
+ name: 'xCompare', signature: 'i(pipip)', contextKey
1143
+ }),
1144
+ new wasm.xWrap.FuncPtrAdapter({
1145
+ /* void(*xDestroy(void*) */
1146
+ name: 'xDestroy', signature: 'v(p)', contextKey
1147
+ })
1148
+ ]
1149
+ );
1150
+
1151
+ /**
1152
+ Works exactly like C's sqlite3_create_collation_v2() except that:
1153
+
1154
+ 1) It returns capi.SQLITE_FORMAT if the 3rd argument contains
1155
+ any encoding-related value other than capi.SQLITE_UTF8. No
1156
+ other encodings are supported. As a special case, if the
1157
+ bottom 4 bits of that argument are 0, SQLITE_UTF8 is
1158
+ assumed.
1159
+
1160
+ 2) It accepts JS functions for its function-pointer arguments,
1161
+ for which it will install WASM-bound proxies. The bindings
1162
+ are "permanent," in that they will stay in the WASM environment
1163
+ until it shuts down unless the client calls this again with the
1164
+ same collation name and a value of 0 or null for the
1165
+ the function pointer(s).
1166
+
1167
+ For consistency with the C API, it requires the same number of
1168
+ arguments. It returns capi.SQLITE_MISUSE if passed any other
1169
+ argument count.
1170
+
1171
+ Returns 0 on success, non-0 on error, in which case the error
1172
+ state of pDb (of type `sqlite3*` or argument-convertible to it)
1173
+ may contain more information.
1174
+ */
1175
+ capi.sqlite3_create_collation_v2 = function(pDb,zName,eTextRep,pArg,xCompare,xDestroy){
1176
+ if(6!==arguments.length) return __dbArgcMismatch(pDb, 'sqlite3_create_collation_v2', 6);
1177
+ else if( 0 === (eTextRep & 0xf) ){
1178
+ eTextRep |= capi.SQLITE_UTF8;
1179
+ }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){
1180
+ return __errEncoding(pDb);
1181
+ }
1182
+ try{
1183
+ const rc = __sqlite3CreateCollationV2(pDb, zName, eTextRep, pArg, xCompare, xDestroy);
1184
+ if(0===rc && xCompare instanceof Function){
1185
+ __dbCleanupMap.addCollation(pDb, zName);
1186
+ }
1187
+ return rc;
1188
+ }catch(e){
1189
+ return util.sqlite3__wasm_db_error(pDb, e);
1190
+ }
1191
+ };
1192
+
1193
+ capi.sqlite3_create_collation = (pDb,zName,eTextRep,pArg,xCompare)=>{
1194
+ return (5===arguments.length)
1195
+ ? capi.sqlite3_create_collation_v2(pDb,zName,eTextRep,pArg,xCompare,0)
1196
+ : __dbArgcMismatch(pDb, 'sqlite3_create_collation', 5);
1197
+ };
1198
+
1199
+ }/*sqlite3_create_collation() and friends*/
1200
+
1201
+ {/* Special-case handling of sqlite3_create_function_v2()
1202
+ and sqlite3_create_window_function(). */
1203
+ /** FuncPtrAdapter for contextKey() for sqlite3_create_function()
1204
+ and friends. */
1205
+ const contextKey = function(argv,argIndex){
1206
+ return (
1207
+ argv[0/* sqlite3* */]
1208
+ +':'+(argv[2/*number of UDF args*/] < 0 ? -1 : argv[2])
1209
+ +':'+argIndex/*distinct for each xAbc callback type*/
1210
+ +':'+wasm.cstrToJs(argv[1]).toLowerCase()
1211
+ )
1212
+ };
1213
+
1214
+ /**
1215
+ JS proxies for the various sqlite3_create[_window]_function()
1216
+ callbacks, structured in a form usable by wasm.xWrap.FuncPtrAdapter.
1217
+ */
1218
+ const __cfProxy = Object.assign(Object.create(null), {
1219
+ xInverseAndStep: {
1220
+ signature:'v(pip)', contextKey,
1221
+ callProxy: (callback)=>{
1222
+ return (pCtx, argc, pArgv)=>{
1223
+ try{ callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv)) }
1224
+ catch(e){ capi.sqlite3_result_error_js(pCtx, e) }
1225
+ };
1226
+ }
1227
+ },
1228
+ xFinalAndValue: {
1229
+ signature:'v(p)', contextKey,
1230
+ callProxy: (callback)=>{
1231
+ return (pCtx)=>{
1232
+ try{ capi.sqlite3_result_js(pCtx, callback(pCtx)) }
1233
+ catch(e){ capi.sqlite3_result_error_js(pCtx, e) }
1234
+ };
1235
+ }
1236
+ },
1237
+ xFunc: {
1238
+ signature:'v(pip)', contextKey,
1239
+ callProxy: (callback)=>{
1240
+ return (pCtx, argc, pArgv)=>{
1241
+ try{
1242
+ capi.sqlite3_result_js(
1243
+ pCtx,
1244
+ callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv))
1245
+ );
1246
+ }catch(e){
1247
+ //console.error('xFunc() caught:',e);
1248
+ capi.sqlite3_result_error_js(pCtx, e);
1249
+ }
1250
+ };
1251
+ }
1252
+ },
1253
+ xDestroy: {
1254
+ signature:'v(p)', contextKey,
1255
+ //Arguable: a well-behaved destructor doesn't require a proxy.
1256
+ callProxy: (callback)=>{
1257
+ return (pVoid)=>{
1258
+ try{ callback(pVoid) }
1259
+ catch(e){ console.error("UDF xDestroy method threw:",e) }
1260
+ };
1261
+ }
1262
+ }
1263
+ })/*__cfProxy*/;
1264
+
1265
+ const __sqlite3CreateFunction = wasm.xWrap(
1266
+ "sqlite3_create_function_v2", "int", [
1267
+ "sqlite3*", "string"/*funcName*/, "int"/*nArg*/,
1268
+ "int"/*eTextRep*/, "*"/*pApp*/,
1269
+ new wasm.xWrap.FuncPtrAdapter({name: 'xFunc', ...__cfProxy.xFunc}),
1270
+ new wasm.xWrap.FuncPtrAdapter({name: 'xStep', ...__cfProxy.xInverseAndStep}),
1271
+ new wasm.xWrap.FuncPtrAdapter({name: 'xFinal', ...__cfProxy.xFinalAndValue}),
1272
+ new wasm.xWrap.FuncPtrAdapter({name: 'xDestroy', ...__cfProxy.xDestroy})
1273
+ ]
1274
+ );
1275
+
1276
+ const __sqlite3CreateWindowFunction =
1277
+ wasm.exports.sqlite3_create_window_function
1278
+ ? wasm.xWrap(
1279
+ "sqlite3_create_window_function", "int", [
1280
+ "sqlite3*", "string"/*funcName*/, "int"/*nArg*/,
1281
+ "int"/*eTextRep*/, "*"/*pApp*/,
1282
+ new wasm.xWrap.FuncPtrAdapter({name: 'xStep', ...__cfProxy.xInverseAndStep}),
1283
+ new wasm.xWrap.FuncPtrAdapter({name: 'xFinal', ...__cfProxy.xFinalAndValue}),
1284
+ new wasm.xWrap.FuncPtrAdapter({name: 'xValue', ...__cfProxy.xFinalAndValue}),
1285
+ new wasm.xWrap.FuncPtrAdapter({name: 'xInverse', ...__cfProxy.xInverseAndStep}),
1286
+ new wasm.xWrap.FuncPtrAdapter({name: 'xDestroy', ...__cfProxy.xDestroy})
1287
+ ]
1288
+ )
1289
+ : undefined;
1290
+
1291
+ /* Documented in the api object's initializer. */
1292
+ capi.sqlite3_create_function_v2 = function f(
1293
+ pDb, funcName, nArg, eTextRep, pApp,
1294
+ xFunc, //void (*xFunc)(sqlite3_context*,int,sqlite3_value**)
1295
+ xStep, //void (*xStep)(sqlite3_context*,int,sqlite3_value**)
1296
+ xFinal, //void (*xFinal)(sqlite3_context*)
1297
+ xDestroy //void (*xDestroy)(void*)
1298
+ ){
1299
+ if( f.length!==arguments.length ){
1300
+ return __dbArgcMismatch(pDb,"sqlite3_create_function_v2",f.length);
1301
+ }else if( 0 === (eTextRep & 0xf) ){
1302
+ eTextRep |= capi.SQLITE_UTF8;
1303
+ }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){
1304
+ return __errEncoding(pDb);
1305
+ }
1306
+ try{
1307
+ const rc = __sqlite3CreateFunction(pDb, funcName, nArg, eTextRep,
1308
+ pApp, xFunc, xStep, xFinal, xDestroy);
1309
+ if(0===rc && (xFunc instanceof Function
1310
+ || xStep instanceof Function
1311
+ || xFinal instanceof Function
1312
+ || xDestroy instanceof Function)){
1313
+ __dbCleanupMap.addFunction(pDb, funcName, nArg);
1314
+ }
1315
+ return rc;
1316
+ }catch(e){
1317
+ console.error("sqlite3_create_function_v2() setup threw:",e);
1318
+ return util.sqlite3__wasm_db_error(pDb, e, "Creation of UDF threw: "+e);
1319
+ }
1320
+ };
1321
+
1322
+ /* Documented in the api object's initializer. */
1323
+ capi.sqlite3_create_function = function f(
1324
+ pDb, funcName, nArg, eTextRep, pApp,
1325
+ xFunc, xStep, xFinal
1326
+ ){
1327
+ return (f.length===arguments.length)
1328
+ ? capi.sqlite3_create_function_v2(pDb, funcName, nArg, eTextRep,
1329
+ pApp, xFunc, xStep, xFinal, 0)
1330
+ : __dbArgcMismatch(pDb,"sqlite3_create_function",f.length);
1331
+ };
1332
+
1333
+ /* Documented in the api object's initializer. */
1334
+ if( __sqlite3CreateWindowFunction ){
1335
+ capi.sqlite3_create_window_function = function f(
1336
+ pDb, funcName, nArg, eTextRep, pApp,
1337
+ xStep, //void (*xStep)(sqlite3_context*,int,sqlite3_value**)
1338
+ xFinal, //void (*xFinal)(sqlite3_context*)
1339
+ xValue, //void (*xValue)(sqlite3_context*)
1340
+ xInverse,//void (*xInverse)(sqlite3_context*,int,sqlite3_value**)
1341
+ xDestroy //void (*xDestroy)(void*)
1342
+ ){
1343
+ if( f.length!==arguments.length ){
1344
+ return __dbArgcMismatch(pDb,"sqlite3_create_window_function",f.length);
1345
+ }else if( 0 === (eTextRep & 0xf) ){
1346
+ eTextRep |= capi.SQLITE_UTF8;
1347
+ }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){
1348
+ return __errEncoding(pDb);
1349
+ }
1350
+ try{
1351
+ const rc = __sqlite3CreateWindowFunction(pDb, funcName, nArg, eTextRep,
1352
+ pApp, xStep, xFinal, xValue,
1353
+ xInverse, xDestroy);
1354
+ if(0===rc && (xStep instanceof Function
1355
+ || xFinal instanceof Function
1356
+ || xValue instanceof Function
1357
+ || xInverse instanceof Function
1358
+ || xDestroy instanceof Function)){
1359
+ __dbCleanupMap.addWindowFunc(pDb, funcName, nArg);
1360
+ }
1361
+ return rc;
1362
+ }catch(e){
1363
+ console.error("sqlite3_create_window_function() setup threw:",e);
1364
+ return util.sqlite3__wasm_db_error(pDb, e, "Creation of UDF threw: "+e);
1365
+ }
1366
+ };
1367
+ }else{
1368
+ delete capi.sqlite3_create_window_function;
1369
+ }
1370
+ /**
1371
+ A _deprecated_ alias for capi.sqlite3_result_js() which
1372
+ predates the addition of that function in the public API.
1373
+ */
1374
+ capi.sqlite3_create_function_v2.udfSetResult =
1375
+ capi.sqlite3_create_function.udfSetResult = capi.sqlite3_result_js;
1376
+ if(capi.sqlite3_create_window_function){
1377
+ capi.sqlite3_create_window_function.udfSetResult = capi.sqlite3_result_js;
1378
+ }
1379
+
1380
+ /**
1381
+ A _deprecated_ alias for capi.sqlite3_values_to_js() which
1382
+ predates the addition of that function in the public API.
1383
+ */
1384
+ capi.sqlite3_create_function_v2.udfConvertArgs =
1385
+ capi.sqlite3_create_function.udfConvertArgs = capi.sqlite3_values_to_js;
1386
+ if(capi.sqlite3_create_window_function){
1387
+ capi.sqlite3_create_window_function.udfConvertArgs = capi.sqlite3_values_to_js;
1388
+ }
1389
+
1390
+ /**
1391
+ A _deprecated_ alias for capi.sqlite3_result_error_js() which
1392
+ predates the addition of that function in the public API.
1393
+ */
1394
+ capi.sqlite3_create_function_v2.udfSetError =
1395
+ capi.sqlite3_create_function.udfSetError = capi.sqlite3_result_error_js;
1396
+ if(capi.sqlite3_create_window_function){
1397
+ capi.sqlite3_create_window_function.udfSetError = capi.sqlite3_result_error_js;
1398
+ }
1399
+
1400
+ }/*sqlite3_create_function_v2() and sqlite3_create_window_function() proxies*/;
1401
+
1402
+ {/* Special-case handling of sqlite3_prepare_v2() and
1403
+ sqlite3_prepare_v3() */
1404
+
1405
+ /**
1406
+ Helper for string:flexible conversions which require a
1407
+ byte-length counterpart argument. Passed a value and its
1408
+ ostensible length, this function returns [V,N], where V is
1409
+ either v or a transformed copy of v and N is either n, -1, or
1410
+ the byte length of v (if it's a byte array or ArrayBuffer).
1411
+ */
1412
+ const __flexiString = (v,n)=>{
1413
+ if('string'===typeof v){
1414
+ n = -1;
1415
+ }else if(util.isSQLableTypedArray(v)){
1416
+ n = v.byteLength;
1417
+ v = util.typedArrayToString(
1418
+ (v instanceof ArrayBuffer) ? new Uint8Array(v) : v
1419
+ );
1420
+ }else if(Array.isArray(v)){
1421
+ v = v.join("");
1422
+ n = -1;
1423
+ }
1424
+ return [v, n];
1425
+ };
1426
+
1427
+ /**
1428
+ Scope-local holder of the two impls of sqlite3_prepare_v2/v3().
1429
+ */
1430
+ const __prepare = {
1431
+ /**
1432
+ This binding expects a JS string as its 2nd argument and
1433
+ null as its final argument. In order to compile multiple
1434
+ statements from a single string, the "full" impl (see
1435
+ below) must be used.
1436
+ */
1437
+ basic: wasm.xWrap('sqlite3_prepare_v3',
1438
+ "int", ["sqlite3*", "string",
1439
+ "int"/*ignored for this impl!*/,
1440
+ "int", "**",
1441
+ "**"/*MUST be 0 or null or undefined!*/]),
1442
+ /**
1443
+ Impl which requires that the 2nd argument be a pointer
1444
+ to the SQL string, instead of being converted to a
1445
+ string. This variant is necessary for cases where we
1446
+ require a non-NULL value for the final argument
1447
+ (exec()'ing multiple statements from one input
1448
+ string). For simpler cases, where only the first
1449
+ statement in the SQL string is required, the wrapper
1450
+ named sqlite3_prepare_v2() is sufficient and easier to
1451
+ use because it doesn't require dealing with pointers.
1452
+ */
1453
+ full: wasm.xWrap('sqlite3_prepare_v3',
1454
+ "int", ["sqlite3*", "*", "int", "int",
1455
+ "**", "**"])
1456
+ };
1457
+
1458
+ /* Documented in the capi object's initializer. */
1459
+ capi.sqlite3_prepare_v3 = function f(pDb, sql, sqlLen, prepFlags, ppStmt, pzTail){
1460
+ if(f.length!==arguments.length){
1461
+ return __dbArgcMismatch(pDb,"sqlite3_prepare_v3",f.length);
1462
+ }
1463
+ const [xSql, xSqlLen] = __flexiString(sql, sqlLen);
1464
+ switch(typeof xSql){
1465
+ case 'string': return __prepare.basic(pDb, xSql, xSqlLen, prepFlags, ppStmt, null);
1466
+ case 'number': return __prepare.full(pDb, xSql, xSqlLen, prepFlags, ppStmt, pzTail);
1467
+ default:
1468
+ return util.sqlite3__wasm_db_error(
1469
+ pDb, capi.SQLITE_MISUSE,
1470
+ "Invalid SQL argument type for sqlite3_prepare_v2/v3()."
1471
+ );
1472
+ }
1473
+ };
1474
+
1475
+ /* Documented in the capi object's initializer. */
1476
+ capi.sqlite3_prepare_v2 = function f(pDb, sql, sqlLen, ppStmt, pzTail){
1477
+ return (f.length===arguments.length)
1478
+ ? capi.sqlite3_prepare_v3(pDb, sql, sqlLen, 0, ppStmt, pzTail)
1479
+ : __dbArgcMismatch(pDb,"sqlite3_prepare_v2",f.length);
1480
+ };
1481
+
1482
+ }/*sqlite3_prepare_v2/v3()*/
1483
+
1484
+ {/*sqlite3_bind_text/blob()*/
1485
+ const __bindText = wasm.xWrap("sqlite3_bind_text", "int", [
1486
+ "sqlite3_stmt*", "int", "string", "int", "*"
1487
+ ]);
1488
+ const __bindBlob = wasm.xWrap("sqlite3_bind_blob", "int", [
1489
+ "sqlite3_stmt*", "int", "*", "int", "*"
1490
+ ]);
1491
+
1492
+ /** Documented in the capi object's initializer. */
1493
+ capi.sqlite3_bind_text = function f(pStmt, iCol, text, nText, xDestroy){
1494
+ if(f.length!==arguments.length){
1495
+ return __dbArgcMismatch(capi.sqlite3_db_handle(pStmt),
1496
+ "sqlite3_bind_text", f.length);
1497
+ }else if(wasm.isPtr(text) || null===text){
1498
+ return __bindText(pStmt, iCol, text, nText, xDestroy);
1499
+ }else if(text instanceof ArrayBuffer){
1500
+ text = new Uint8Array(text);
1501
+ }else if(Array.isArray(pMem)){
1502
+ text = pMem.join('');
1503
+ }
1504
+ let p, n;
1505
+ try{
1506
+ if(util.isSQLableTypedArray(text)){
1507
+ p = wasm.allocFromTypedArray(text);
1508
+ n = text.byteLength;
1509
+ }else if('string'===typeof text){
1510
+ [p, n] = wasm.allocCString(text);
1511
+ }else{
1512
+ return util.sqlite3__wasm_db_error(
1513
+ capi.sqlite3_db_handle(pStmt), capi.SQLITE_MISUSE,
1514
+ "Invalid 3rd argument type for sqlite3_bind_text()."
1515
+ );
1516
+ }
1517
+ return __bindText(pStmt, iCol, p, n, capi.SQLITE_WASM_DEALLOC);
1518
+ }catch(e){
1519
+ wasm.dealloc(p);
1520
+ return util.sqlite3__wasm_db_error(
1521
+ capi.sqlite3_db_handle(pStmt), e
1522
+ );
1523
+ }
1524
+ }/*sqlite3_bind_text()*/;
1525
+
1526
+ /** Documented in the capi object's initializer. */
1527
+ capi.sqlite3_bind_blob = function f(pStmt, iCol, pMem, nMem, xDestroy){
1528
+ if(f.length!==arguments.length){
1529
+ return __dbArgcMismatch(capi.sqlite3_db_handle(pStmt),
1530
+ "sqlite3_bind_blob", f.length);
1531
+ }else if(wasm.isPtr(pMem) || null===pMem){
1532
+ return __bindBlob(pStmt, iCol, pMem, nMem, xDestroy);
1533
+ }else if(pMem instanceof ArrayBuffer){
1534
+ pMem = new Uint8Array(pMem);
1535
+ }else if(Array.isArray(pMem)){
1536
+ pMem = pMem.join('');
1537
+ }
1538
+ let p, n;
1539
+ try{
1540
+ if(util.isBindableTypedArray(pMem)){
1541
+ p = wasm.allocFromTypedArray(pMem);
1542
+ n = nMem>=0 ? nMem : pMem.byteLength;
1543
+ }else if('string'===typeof pMem){
1544
+ [p, n] = wasm.allocCString(pMem);
1545
+ }else{
1546
+ return util.sqlite3__wasm_db_error(
1547
+ capi.sqlite3_db_handle(pStmt), capi.SQLITE_MISUSE,
1548
+ "Invalid 3rd argument type for sqlite3_bind_blob()."
1549
+ );
1550
+ }
1551
+ return __bindBlob(pStmt, iCol, p, n, capi.SQLITE_WASM_DEALLOC);
1552
+ }catch(e){
1553
+ wasm.dealloc(p);
1554
+ return util.sqlite3__wasm_db_error(
1555
+ capi.sqlite3_db_handle(pStmt), e
1556
+ );
1557
+ }
1558
+ }/*sqlite3_bind_blob()*/;
1559
+
1560
+ }/*sqlite3_bind_text/blob()*/
1561
+
1562
+ {/* sqlite3_config() */
1563
+ /**
1564
+ Wraps a small subset of the C API's sqlite3_config() options.
1565
+ Unsupported options trigger the return of capi.SQLITE_NOTFOUND.
1566
+ Passing fewer than 2 arguments triggers return of
1567
+ capi.SQLITE_MISUSE.
1568
+ */
1569
+ capi.sqlite3_config = function(op, ...args){
1570
+ if(arguments.length<2) return capi.SQLITE_MISUSE;
1571
+ switch(op){
1572
+ case capi.SQLITE_CONFIG_COVERING_INDEX_SCAN: // 20 /* int */
1573
+ case capi.SQLITE_CONFIG_MEMSTATUS:// 9 /* boolean */
1574
+ case capi.SQLITE_CONFIG_SMALL_MALLOC: // 27 /* boolean */
1575
+ case capi.SQLITE_CONFIG_SORTERREF_SIZE: // 28 /* int nByte */
1576
+ case capi.SQLITE_CONFIG_STMTJRNL_SPILL: // 26 /* int nByte */
1577
+ case capi.SQLITE_CONFIG_URI:// 17 /* int */
1578
+ return wasm.exports.sqlite3__wasm_config_i(op, args[0]);
1579
+ case capi.SQLITE_CONFIG_LOOKASIDE: // 13 /* int int */
1580
+ return wasm.exports.sqlite3__wasm_config_ii(op, args[0], args[1]);
1581
+ case capi.SQLITE_CONFIG_MEMDB_MAXSIZE: // 29 /* sqlite3_int64 */
1582
+ return wasm.exports.sqlite3__wasm_config_j(op, args[0]);
1583
+ case capi.SQLITE_CONFIG_GETMALLOC: // 5 /* sqlite3_mem_methods* */
1584
+ case capi.SQLITE_CONFIG_GETMUTEX: // 11 /* sqlite3_mutex_methods* */
1585
+ case capi.SQLITE_CONFIG_GETPCACHE2: // 19 /* sqlite3_pcache_methods2* */
1586
+ case capi.SQLITE_CONFIG_GETPCACHE: // 15 /* no-op */
1587
+ case capi.SQLITE_CONFIG_HEAP: // 8 /* void*, int nByte, int min */
1588
+ case capi.SQLITE_CONFIG_LOG: // 16 /* xFunc, void* */
1589
+ case capi.SQLITE_CONFIG_MALLOC:// 4 /* sqlite3_mem_methods* */
1590
+ case capi.SQLITE_CONFIG_MMAP_SIZE: // 22 /* sqlite3_int64, sqlite3_int64 */
1591
+ case capi.SQLITE_CONFIG_MULTITHREAD: // 2 /* nil */
1592
+ case capi.SQLITE_CONFIG_MUTEX: // 10 /* sqlite3_mutex_methods* */
1593
+ case capi.SQLITE_CONFIG_PAGECACHE: // 7 /* void*, int sz, int N */
1594
+ case capi.SQLITE_CONFIG_PCACHE2: // 18 /* sqlite3_pcache_methods2* */
1595
+ case capi.SQLITE_CONFIG_PCACHE: // 14 /* no-op */
1596
+ case capi.SQLITE_CONFIG_PCACHE_HDRSZ: // 24 /* int *psz */
1597
+ case capi.SQLITE_CONFIG_PMASZ: // 25 /* unsigned int szPma */
1598
+ case capi.SQLITE_CONFIG_SERIALIZED: // 3 /* nil */
1599
+ case capi.SQLITE_CONFIG_SINGLETHREAD: // 1 /* nil */:
1600
+ case capi.SQLITE_CONFIG_SQLLOG: // 21 /* xSqllog, void* */
1601
+ case capi.SQLITE_CONFIG_WIN32_HEAPSIZE: // 23 /* int nByte */
1602
+ default:
1603
+ /* maintenance note: we specifically do not include
1604
+ SQLITE_CONFIG_ROWID_IN_VIEW here, on the grounds that
1605
+ it's only for legacy support and no apps written with
1606
+ this API require that. */
1607
+ return capi.SQLITE_NOTFOUND;
1608
+ }
1609
+ };
1610
+ }/* sqlite3_config() */
1611
+
1612
+ {/*auto-extension bindings.*/
1613
+ const __autoExtFptr = new Set;
1614
+
1615
+ capi.sqlite3_auto_extension = function(fPtr){
1616
+ if( fPtr instanceof Function ){
1617
+ fPtr = wasm.installFunction('i(ppp)', fPtr);
1618
+ }else if( 1!==arguments.length || !wasm.isPtr(fPtr) ){
1619
+ return capi.SQLITE_MISUSE;
1620
+ }
1621
+ const rc = wasm.exports.sqlite3_auto_extension(fPtr);
1622
+ if( fPtr!==arguments[0] ){
1623
+ if(0===rc) __autoExtFptr.add(fPtr);
1624
+ else wasm.uninstallFunction(fPtr);
1625
+ }
1626
+ return rc;
1627
+ };
1628
+
1629
+ capi.sqlite3_cancel_auto_extension = function(fPtr){
1630
+ /* We do not do an automatic JS-to-WASM function conversion here
1631
+ because it would be senseless: the converted pointer would
1632
+ never possibly match an already-installed one. */;
1633
+ if(!fPtr || 1!==arguments.length || !wasm.isPtr(fPtr)) return 0;
1634
+ return wasm.exports.sqlite3_cancel_auto_extension(fPtr);
1635
+ /* Note that it "cannot happen" that a client passes a pointer which
1636
+ is in __autoExtFptr because __autoExtFptr only contains automatic
1637
+ conversions created inside sqlite3_auto_extension() and
1638
+ never exposed to the client. */
1639
+ };
1640
+
1641
+ capi.sqlite3_reset_auto_extension = function(){
1642
+ wasm.exports.sqlite3_reset_auto_extension();
1643
+ for(const fp of __autoExtFptr) wasm.uninstallFunction(fp);
1644
+ __autoExtFptr.clear();
1645
+ };
1646
+ }/* auto-extension */
1647
+
1648
+ const pKvvfs = capi.sqlite3_vfs_find("kvvfs");
1649
+ if( pKvvfs ){/* kvvfs-specific glue */
1650
+ if(util.isUIThread()){
1651
+ const kvvfsMethods = new capi.sqlite3_kvvfs_methods(
1652
+ wasm.exports.sqlite3__wasm_kvvfs_methods()
1653
+ );
1654
+ delete capi.sqlite3_kvvfs_methods;
1655
+
1656
+ const kvvfsMakeKey = wasm.exports.sqlite3__wasm_kvvfsMakeKeyOnPstack,
1657
+ pstack = wasm.pstack;
1658
+
1659
+ const kvvfsStorage = (zClass)=>
1660
+ ((115/*=='s'*/===wasm.peek(zClass))
1661
+ ? sessionStorage : localStorage);
1662
+
1663
+ /**
1664
+ Implementations for members of the object referred to by
1665
+ sqlite3__wasm_kvvfs_methods(). We swap out the native
1666
+ implementations with these, which use localStorage or
1667
+ sessionStorage for their backing store.
1668
+ */
1669
+ const kvvfsImpls = {
1670
+ xRead: (zClass, zKey, zBuf, nBuf)=>{
1671
+ const stack = pstack.pointer,
1672
+ astack = wasm.scopedAllocPush();
1673
+ try {
1674
+ const zXKey = kvvfsMakeKey(zClass,zKey);
1675
+ if(!zXKey) return -3/*OOM*/;
1676
+ const jKey = wasm.cstrToJs(zXKey);
1677
+ const jV = kvvfsStorage(zClass).getItem(jKey);
1678
+ if(!jV) return -1;
1679
+ const nV = jV.length /* Note that we are relying 100% on v being
1680
+ ASCII so that jV.length is equal to the
1681
+ C-string's byte length. */;
1682
+ if(nBuf<=0) return nV;
1683
+ else if(1===nBuf){
1684
+ wasm.poke(zBuf, 0);
1685
+ return nV;
1686
+ }
1687
+ const zV = wasm.scopedAllocCString(jV);
1688
+ if(nBuf > nV + 1) nBuf = nV + 1;
1689
+ wasm.heap8u().copyWithin(zBuf, zV, zV + nBuf - 1);
1690
+ wasm.poke(zBuf + nBuf - 1, 0);
1691
+ return nBuf - 1;
1692
+ }catch(e){
1693
+ console.error("kvstorageRead()",e);
1694
+ return -2;
1695
+ }finally{
1696
+ pstack.restore(stack);
1697
+ wasm.scopedAllocPop(astack);
1698
+ }
1699
+ },
1700
+ xWrite: (zClass, zKey, zData)=>{
1701
+ const stack = pstack.pointer;
1702
+ try {
1703
+ const zXKey = kvvfsMakeKey(zClass,zKey);
1704
+ if(!zXKey) return 1/*OOM*/;
1705
+ const jKey = wasm.cstrToJs(zXKey);
1706
+ kvvfsStorage(zClass).setItem(jKey, wasm.cstrToJs(zData));
1707
+ return 0;
1708
+ }catch(e){
1709
+ console.error("kvstorageWrite()",e);
1710
+ return capi.SQLITE_IOERR;
1711
+ }finally{
1712
+ pstack.restore(stack);
1713
+ }
1714
+ },
1715
+ xDelete: (zClass, zKey)=>{
1716
+ const stack = pstack.pointer;
1717
+ try {
1718
+ const zXKey = kvvfsMakeKey(zClass,zKey);
1719
+ if(!zXKey) return 1/*OOM*/;
1720
+ kvvfsStorage(zClass).removeItem(wasm.cstrToJs(zXKey));
1721
+ return 0;
1722
+ }catch(e){
1723
+ console.error("kvstorageDelete()",e);
1724
+ return capi.SQLITE_IOERR;
1725
+ }finally{
1726
+ pstack.restore(stack);
1727
+ }
1728
+ }
1729
+ }/*kvvfsImpls*/;
1730
+ for(const k of Object.keys(kvvfsImpls)){
1731
+ kvvfsMethods[kvvfsMethods.memberKey(k)] =
1732
+ wasm.installFunction(
1733
+ kvvfsMethods.memberSignature(k),
1734
+ kvvfsImpls[k]
1735
+ );
1736
+ }
1737
+ }else{
1738
+ /* Worker thread: unregister kvvfs to avoid it being used
1739
+ for anything other than local/sessionStorage. It "can"
1740
+ be used that way but it's not really intended to be. */
1741
+ capi.sqlite3_vfs_unregister(pKvvfs);
1742
+ }
1743
+ }/*pKvvfs*/
1744
+
1745
+ /* Warn if client-level code makes use of FuncPtrAdapter. */
1746
+ wasm.xWrap.FuncPtrAdapter.warnOnUse = true;
1747
+
1748
+ const StructBinder = sqlite3.StructBinder
1749
+ /* we require a local alias b/c StructBinder is removed from the sqlite3
1750
+ object during the final steps of the API cleanup. */;
1751
+ /**
1752
+ Installs a StructBinder-bound function pointer member of the
1753
+ given name and function in the given StructBinder.StructType
1754
+ target object.
1755
+
1756
+ It creates a WASM proxy for the given function and arranges for
1757
+ that proxy to be cleaned up when tgt.dispose() is called. Throws
1758
+ on the slightest hint of error, e.g. tgt is-not-a StructType,
1759
+ name does not map to a struct-bound member, etc.
1760
+
1761
+ As a special case, if the given function is a pointer, then
1762
+ `wasm.functionEntry()` is used to validate that it is a known
1763
+ function. If so, it is used as-is with no extra level of proxying
1764
+ or cleanup, else an exception is thrown. It is legal to pass a
1765
+ value of 0, indicating a NULL pointer, with the caveat that 0
1766
+ _is_ a legal function pointer in WASM but it will not be accepted
1767
+ as such _here_. (Justification: the function at address zero must
1768
+ be one which initially came from the WASM module, not a method we
1769
+ want to bind to a virtual table or VFS.)
1770
+
1771
+ This function returns a proxy for itself which is bound to tgt
1772
+ and takes 2 args (name,func). That function returns the same
1773
+ thing as this one, permitting calls to be chained.
1774
+
1775
+ If called with only 1 arg, it has no side effects but returns a
1776
+ func with the same signature as described above.
1777
+
1778
+ ACHTUNG: because we cannot generically know how to transform JS
1779
+ exceptions into result codes, the installed functions do no
1780
+ automatic catching of exceptions. It is critical, to avoid
1781
+ undefined behavior in the C layer, that methods mapped via
1782
+ this function do not throw. The exception, as it were, to that
1783
+ rule is...
1784
+
1785
+ If applyArgcCheck is true then each JS function (as opposed to
1786
+ function pointers) gets wrapped in a proxy which asserts that it
1787
+ is passed the expected number of arguments, throwing if the
1788
+ argument count does not match expectations. That is only intended
1789
+ for dev-time usage for sanity checking, and may leave the C
1790
+ environment in an undefined state.
1791
+ */
1792
+ const installMethod = function callee(
1793
+ tgt, name, func, applyArgcCheck = callee.installMethodArgcCheck
1794
+ ){
1795
+ if(!(tgt instanceof StructBinder.StructType)){
1796
+ toss("Usage error: target object is-not-a StructType.");
1797
+ }else if(!(func instanceof Function) && !wasm.isPtr(func)){
1798
+ toss("Usage errror: expecting a Function or WASM pointer to one.");
1799
+ }
1800
+ if(1===arguments.length){
1801
+ return (n,f)=>callee(tgt, n, f, applyArgcCheck);
1802
+ }
1803
+ if(!callee.argcProxy){
1804
+ callee.argcProxy = function(tgt, funcName, func,sig){
1805
+ return function(...args){
1806
+ if(func.length!==arguments.length){
1807
+ toss("Argument mismatch for",
1808
+ tgt.structInfo.name+"::"+funcName
1809
+ +": Native signature is:",sig);
1810
+ }
1811
+ return func.apply(this, args);
1812
+ }
1813
+ };
1814
+ /* An ondispose() callback for use with
1815
+ StructBinder-created types. */
1816
+ callee.removeFuncList = function(){
1817
+ if(this.ondispose.__removeFuncList){
1818
+ this.ondispose.__removeFuncList.forEach(
1819
+ (v,ndx)=>{
1820
+ if('number'===typeof v){
1821
+ try{wasm.uninstallFunction(v)}
1822
+ catch(e){/*ignore*/}
1823
+ }
1824
+ /* else it's a descriptive label for the next number in
1825
+ the list. */
1826
+ }
1827
+ );
1828
+ delete this.ondispose.__removeFuncList;
1829
+ }
1830
+ };
1831
+ }/*static init*/
1832
+ const sigN = tgt.memberSignature(name);
1833
+ if(sigN.length<2){
1834
+ toss("Member",name,"does not have a function pointer signature:",sigN);
1835
+ }
1836
+ const memKey = tgt.memberKey(name);
1837
+ const fProxy = (applyArgcCheck && !wasm.isPtr(func))
1838
+ /** This middle-man proxy is only for use during development, to
1839
+ confirm that we always pass the proper number of
1840
+ arguments. We know that the C-level code will always use the
1841
+ correct argument count. */
1842
+ ? callee.argcProxy(tgt, memKey, func, sigN)
1843
+ : func;
1844
+ if(wasm.isPtr(fProxy)){
1845
+ if(fProxy && !wasm.functionEntry(fProxy)){
1846
+ toss("Pointer",fProxy,"is not a WASM function table entry.");
1847
+ }
1848
+ tgt[memKey] = fProxy;
1849
+ }else{
1850
+ const pFunc = wasm.installFunction(fProxy, tgt.memberSignature(name, true));
1851
+ tgt[memKey] = pFunc;
1852
+ if(!tgt.ondispose || !tgt.ondispose.__removeFuncList){
1853
+ tgt.addOnDispose('ondispose.__removeFuncList handler',
1854
+ callee.removeFuncList);
1855
+ tgt.ondispose.__removeFuncList = [];
1856
+ }
1857
+ tgt.ondispose.__removeFuncList.push(memKey, pFunc);
1858
+ }
1859
+ return (n,f)=>callee(tgt, n, f, applyArgcCheck);
1860
+ }/*installMethod*/;
1861
+ installMethod.installMethodArgcCheck = false;
1862
+
1863
+ /**
1864
+ Installs methods into the given StructBinder.StructType-type
1865
+ instance. Each entry in the given methods object must map to a
1866
+ known member of the given StructType, else an exception will be
1867
+ triggered. See installMethod() for more details, including the
1868
+ semantics of the 3rd argument.
1869
+
1870
+ As an exception to the above, if any two or more methods in the
1871
+ 2nd argument are the exact same function, installMethod() is
1872
+ _not_ called for the 2nd and subsequent instances, and instead
1873
+ those instances get assigned the same method pointer which is
1874
+ created for the first instance. This optimization is primarily to
1875
+ accommodate special handling of sqlite3_module::xConnect and
1876
+ xCreate methods.
1877
+
1878
+ On success, returns its first argument. Throws on error.
1879
+ */
1880
+ const installMethods = function(
1881
+ structInstance, methods, applyArgcCheck = installMethod.installMethodArgcCheck
1882
+ ){
1883
+ const seen = new Map /* map of <Function, memberName> */;
1884
+ for(const k of Object.keys(methods)){
1885
+ const m = methods[k];
1886
+ const prior = seen.get(m);
1887
+ if(prior){
1888
+ const mkey = structInstance.memberKey(k);
1889
+ structInstance[mkey] = structInstance[structInstance.memberKey(prior)];
1890
+ }else{
1891
+ installMethod(structInstance, k, m, applyArgcCheck);
1892
+ seen.set(m, k);
1893
+ }
1894
+ }
1895
+ return structInstance;
1896
+ };
1897
+
1898
+ /**
1899
+ Equivalent to calling installMethod(this,...arguments) with a
1900
+ first argument of this object. If called with 1 or 2 arguments
1901
+ and the first is an object, it's instead equivalent to calling
1902
+ installMethods(this,...arguments).
1903
+ */
1904
+ StructBinder.StructType.prototype.installMethod = function callee(
1905
+ name, func, applyArgcCheck = installMethod.installMethodArgcCheck
1906
+ ){
1907
+ return (arguments.length < 3 && name && 'object'===typeof name)
1908
+ ? installMethods(this, ...arguments)
1909
+ : installMethod(this, ...arguments);
1910
+ };
1911
+
1912
+ /**
1913
+ Equivalent to calling installMethods() with a first argument
1914
+ of this object.
1915
+ */
1916
+ StructBinder.StructType.prototype.installMethods = function(
1917
+ methods, applyArgcCheck = installMethod.installMethodArgcCheck
1918
+ ){
1919
+ return installMethods(this, methods, applyArgcCheck);
1920
+ };
1921
+
1922
+ });
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-opfs-async-proxy.js ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ 2022-09-16
3
+
4
+ The author disclaims copyright to this source code. In place of a
5
+ legal notice, here is a blessing:
6
+
7
+ * May you do good and not evil.
8
+ * May you find forgiveness for yourself and forgive others.
9
+ * May you share freely, never taking more than you give.
10
+
11
+ ***********************************************************************
12
+
13
+ A Worker which manages asynchronous OPFS handles on behalf of a
14
+ synchronous API which controls it via a combination of Worker
15
+ messages, SharedArrayBuffer, and Atomics. It is the asynchronous
16
+ counterpart of the API defined in sqlite3-vfs-opfs.js.
17
+
18
+ Highly indebted to:
19
+
20
+ https://github.com/rhashimoto/wa-sqlite/blob/master/src/examples/OriginPrivateFileSystemVFS.js
21
+
22
+ for demonstrating how to use the OPFS APIs.
23
+
24
+ This file is to be loaded as a Worker. It does not have any direct
25
+ access to the sqlite3 JS/WASM bits, so any bits which it needs (most
26
+ notably SQLITE_xxx integer codes) have to be imported into it via an
27
+ initialization process.
28
+
29
+ This file represents an implementation detail of a larger piece of
30
+ code, and not a public interface. Its details may change at any time
31
+ and are not intended to be used by any client-level code.
32
+
33
+ 2022-11-27: Chrome v108 changes some async methods to synchronous, as
34
+ documented at:
35
+
36
+ https://developer.chrome.com/blog/sync-methods-for-accesshandles/
37
+
38
+ Firefox v111 and Safari 16.4, both released in March 2023, also
39
+ include this.
40
+
41
+ We cannot change to the sync forms at this point without breaking
42
+ clients who use Chrome v104-ish or higher. truncate(), getSize(),
43
+ flush(), and close() are now (as of v108) synchronous. Calling them
44
+ with an "await", as we have to for the async forms, is still legal
45
+ with the sync forms but is superfluous. Calling the async forms with
46
+ theFunc().then(...) is not compatible with the change to
47
+ synchronous, but we do do not use those APIs that way. i.e. we don't
48
+ _need_ to change anything for this, but at some point (after Chrome
49
+ versions (approximately) 104-107 are extinct) should change our
50
+ usage of those methods to remove the "await".
51
+ */
52
+ "use strict";
53
+ const wPost = (type,...args)=>postMessage({type, payload:args});
54
+ const installAsyncProxy = function(){
55
+ const toss = function(...args){throw new Error(args.join(' '))};
56
+ if(globalThis.window === globalThis){
57
+ toss("This code cannot run from the main thread.",
58
+ "Load it as a Worker from a separate Worker.");
59
+ }else if(!navigator?.storage?.getDirectory){
60
+ toss("This API requires navigator.storage.getDirectory.");
61
+ }
62
+
63
+ /**
64
+ Will hold state copied to this object from the syncronous side of
65
+ this API.
66
+ */
67
+ const state = Object.create(null);
68
+
69
+ /**
70
+ verbose:
71
+
72
+ 0 = no logging output
73
+ 1 = only errors
74
+ 2 = warnings and errors
75
+ 3 = debug, warnings, and errors
76
+ */
77
+ state.verbose = 1;
78
+
79
+ const loggers = {
80
+ 0:console.error.bind(console),
81
+ 1:console.warn.bind(console),
82
+ 2:console.log.bind(console)
83
+ };
84
+ const logImpl = (level,...args)=>{
85
+ if(state.verbose>level) loggers[level]("OPFS asyncer:",...args);
86
+ };
87
+ const log = (...args)=>logImpl(2, ...args);
88
+ const warn = (...args)=>logImpl(1, ...args);
89
+ const error = (...args)=>logImpl(0, ...args);
90
+
91
+ /**
92
+ __openFiles is a map of sqlite3_file pointers (integers) to
93
+ metadata related to a given OPFS file handles. The pointers are, in
94
+ this side of the interface, opaque file handle IDs provided by the
95
+ synchronous part of this constellation. Each value is an object
96
+ with a structure demonstrated in the xOpen() impl.
97
+ */
98
+ const __openFiles = Object.create(null);
99
+ /**
100
+ __implicitLocks is a Set of sqlite3_file pointers (integers) which were
101
+ "auto-locked". i.e. those for which we obtained a sync access
102
+ handle without an explicit xLock() call. Such locks will be
103
+ released during db connection idle time, whereas a sync access
104
+ handle obtained via xLock(), or subsequently xLock()'d after
105
+ auto-acquisition, will not be released until xUnlock() is called.
106
+
107
+ Maintenance reminder: if we relinquish auto-locks at the end of the
108
+ operation which acquires them, we pay a massive performance
109
+ penalty: speedtest1 benchmarks take up to 4x as long. By delaying
110
+ the lock release until idle time, the hit is negligible.
111
+ */
112
+ const __implicitLocks = new Set();
113
+
114
+ /**
115
+ Expects an OPFS file path. It gets resolved, such that ".."
116
+ components are properly expanded, and returned. If the 2nd arg is
117
+ true, the result is returned as an array of path elements, else an
118
+ absolute path string is returned.
119
+ */
120
+ const getResolvedPath = function(filename,splitIt){
121
+ const p = new URL(
122
+ filename, 'file://irrelevant'
123
+ ).pathname;
124
+ return splitIt ? p.split('/').filter((v)=>!!v) : p;
125
+ };
126
+
127
+ /**
128
+ Takes the absolute path to a filesystem element. Returns an array
129
+ of [handleOfContainingDir, filename]. If the 2nd argument is truthy
130
+ then each directory element leading to the file is created along
131
+ the way. Throws if any creation or resolution fails.
132
+ */
133
+ const getDirForFilename = async function f(absFilename, createDirs = false){
134
+ const path = getResolvedPath(absFilename, true);
135
+ const filename = path.pop();
136
+ let dh = state.rootDir;
137
+ for(const dirName of path){
138
+ if(dirName){
139
+ dh = await dh.getDirectoryHandle(dirName, {create: !!createDirs});
140
+ }
141
+ }
142
+ return [dh, filename];
143
+ };
144
+
145
+ /**
146
+ If the given file-holding object has a sync handle attached to it,
147
+ that handle is removed and asynchronously closed. Though it may
148
+ sound sensible to continue work as soon as the close() returns
149
+ (noting that it's asynchronous), doing so can cause operations
150
+ performed soon afterwards, e.g. a call to getSyncHandle(), to fail
151
+ because they may happen out of order from the close(). OPFS does
152
+ not guaranty that the actual order of operations is retained in
153
+ such cases. i.e. always "await" on the result of this function.
154
+ */
155
+ const closeSyncHandle = async (fh)=>{
156
+ if(fh.syncHandle){
157
+ log("Closing sync handle for",fh.filenameAbs);
158
+ const h = fh.syncHandle;
159
+ delete fh.syncHandle;
160
+ delete fh.xLock;
161
+ __implicitLocks.delete(fh.fid);
162
+ return h.close();
163
+ }
164
+ };
165
+
166
+ /**
167
+ A proxy for closeSyncHandle() which is guaranteed to not throw.
168
+
169
+ This function is part of a lock/unlock step in functions which
170
+ require a sync access handle but may be called without xLock()
171
+ having been called first. Such calls need to release that
172
+ handle to avoid locking the file for all of time. This is an
173
+ _attempt_ at reducing cross-tab contention but it may prove
174
+ to be more of a problem than a solution and may need to be
175
+ removed.
176
+ */
177
+ const closeSyncHandleNoThrow = async (fh)=>{
178
+ try{await closeSyncHandle(fh)}
179
+ catch(e){
180
+ warn("closeSyncHandleNoThrow() ignoring:",e,fh);
181
+ }
182
+ };
183
+
184
+ /* Release all auto-locks. */
185
+ const releaseImplicitLocks = async ()=>{
186
+ if(__implicitLocks.size){
187
+ /* Release all auto-locks. */
188
+ for(const fid of __implicitLocks){
189
+ const fh = __openFiles[fid];
190
+ await closeSyncHandleNoThrow(fh);
191
+ log("Auto-unlocked",fid,fh.filenameAbs);
192
+ }
193
+ }
194
+ };
195
+
196
+ /**
197
+ An experiment in improving concurrency by freeing up implicit locks
198
+ sooner. This is known to impact performance dramatically but it has
199
+ also shown to improve concurrency considerably.
200
+
201
+ If fh.releaseImplicitLocks is truthy and fh is in __implicitLocks,
202
+ this routine returns closeSyncHandleNoThrow(), else it is a no-op.
203
+ */
204
+ const releaseImplicitLock = async (fh)=>{
205
+ if(fh.releaseImplicitLocks && __implicitLocks.has(fh.fid)){
206
+ return closeSyncHandleNoThrow(fh);
207
+ }
208
+ };
209
+
210
+ /**
211
+ An error class specifically for use with getSyncHandle(), the goal
212
+ of which is to eventually be able to distinguish unambiguously
213
+ between locking-related failures and other types, noting that we
214
+ cannot currently do so because createSyncAccessHandle() does not
215
+ define its exceptions in the required level of detail.
216
+
217
+ 2022-11-29: according to:
218
+
219
+ https://github.com/whatwg/fs/pull/21
220
+
221
+ NoModificationAllowedError will be the standard exception thrown
222
+ when acquisition of a sync access handle fails due to a locking
223
+ error. As of this writing, that error type is not visible in the
224
+ dev console in Chrome v109, nor is it documented in MDN, but an
225
+ error with that "name" property is being thrown from the OPFS
226
+ layer.
227
+ */
228
+ class GetSyncHandleError extends Error {
229
+ constructor(errorObject, ...msg){
230
+ super([
231
+ ...msg, ': '+errorObject.name+':',
232
+ errorObject.message
233
+ ].join(' '), {
234
+ cause: errorObject
235
+ });
236
+ this.name = 'GetSyncHandleError';
237
+ }
238
+ };
239
+
240
+ /**
241
+ Attempts to find a suitable SQLITE_xyz result code for Error
242
+ object e. Returns either such a translation or rc if if it does
243
+ not know how to translate the exception.
244
+ */
245
+ GetSyncHandleError.convertRc = (e,rc)=>{
246
+ if( e instanceof GetSyncHandleError ){
247
+ if( e.cause.name==='NoModificationAllowedError'
248
+ /* Inconsistent exception.name from Chrome/ium with the
249
+ same exception.message text: */
250
+ || (e.cause.name==='DOMException'
251
+ && 0===e.cause.message.indexOf('Access Handles cannot')) ){
252
+ return state.sq3Codes.SQLITE_BUSY;
253
+ }else if( 'NotFoundError'===e.cause.name ){
254
+ /**
255
+ Maintenance reminder: SQLITE_NOTFOUND, though it looks like
256
+ a good match, has different semantics than NotFoundError
257
+ and is not suitable here.
258
+ */
259
+ return state.sq3Codes.SQLITE_CANTOPEN;
260
+ }
261
+ }else if( 'NotFoundError'===e?.name ){
262
+ return state.sq3Codes.SQLITE_CANTOPEN;
263
+ }
264
+ return rc;
265
+ };
266
+
267
+ /**
268
+ Returns the sync access handle associated with the given file
269
+ handle object (which must be a valid handle object, as created by
270
+ xOpen()), lazily opening it if needed.
271
+
272
+ In order to help alleviate cross-tab contention for a dabase, if
273
+ an exception is thrown while acquiring the handle, this routine
274
+ will wait briefly and try again, up to some fixed number of
275
+ times. If acquisition still fails at that point it will give up
276
+ and propagate the exception. Client-level code will see that as
277
+ an I/O error.
278
+
279
+ 2024-06-12: there is a rare race condition here which has been
280
+ reported a single time:
281
+
282
+ https://sqlite.org/forum/forumpost/9ee7f5340802d600
283
+
284
+ What appears to be happening is that file we're waiting for a
285
+ lock on is deleted while we wait. What currently happens here is
286
+ that a locking exception is thrown but the exception type is
287
+ NotFoundError. In such cases, we very probably should attempt to
288
+ re-open/re-create the file an obtain the lock on it (noting that
289
+ there's another race condition there). That's easy to say but
290
+ creating a viable test for that condition has proven challenging
291
+ so far.
292
+ */
293
+ const getSyncHandle = async (fh,opName)=>{
294
+ if(!fh.syncHandle){
295
+ const t = performance.now();
296
+ log("Acquiring sync handle for",fh.filenameAbs);
297
+ const maxTries = 6,
298
+ msBase = state.asyncIdleWaitTime * 2;
299
+ let i = 1, ms = msBase;
300
+ for(; true; ms = msBase * ++i){
301
+ try {
302
+ //if(i<3) toss("Just testing getSyncHandle() wait-and-retry.");
303
+ //TODO? A config option which tells it to throw here
304
+ //randomly every now and then, for testing purposes.
305
+ fh.syncHandle = await fh.fileHandle.createSyncAccessHandle();
306
+ break;
307
+ }catch(e){
308
+ if(i === maxTries){
309
+ throw new GetSyncHandleError(
310
+ e, "Error getting sync handle for",opName+"().",maxTries,
311
+ "attempts failed.",fh.filenameAbs
312
+ );
313
+ }
314
+ warn("Error getting sync handle for",opName+"(). Waiting",ms,
315
+ "ms and trying again.",fh.filenameAbs,e);
316
+ Atomics.wait(state.sabOPView, state.opIds.retry, 0, ms);
317
+ }
318
+ }
319
+ log("Got",opName+"() sync handle for",fh.filenameAbs,
320
+ 'in',performance.now() - t,'ms');
321
+ if(!fh.xLock){
322
+ __implicitLocks.add(fh.fid);
323
+ log("Acquired implicit lock for",opName+"()",fh.fid,fh.filenameAbs);
324
+ }
325
+ }
326
+ return fh.syncHandle;
327
+ };
328
+
329
+ /**
330
+ Stores the given value at state.sabOPView[state.opIds.rc] and then
331
+ Atomics.notify()'s it.
332
+ */
333
+ const storeAndNotify = (opName, value)=>{
334
+ log(opName+"() => notify(",value,")");
335
+ Atomics.store(state.sabOPView, state.opIds.rc, value);
336
+ Atomics.notify(state.sabOPView, state.opIds.rc);
337
+ };
338
+
339
+ /**
340
+ Throws if fh is a file-holding object which is flagged as read-only.
341
+ */
342
+ const affirmNotRO = function(opName,fh){
343
+ if(fh.readOnly) toss(opName+"(): File is read-only: "+fh.filenameAbs);
344
+ };
345
+
346
+ /**
347
+ Gets set to true by the 'opfs-async-shutdown' command to quit the
348
+ wait loop. This is only intended for debugging purposes: we cannot
349
+ inspect this file's state while the tight waitLoop() is running and
350
+ need a way to stop that loop for introspection purposes.
351
+ */
352
+ let flagAsyncShutdown = false;
353
+
354
+ /**
355
+ Asynchronous wrappers for sqlite3_vfs and sqlite3_io_methods
356
+ methods, as well as helpers like mkdir().
357
+ */
358
+ const vfsAsyncImpls = {
359
+ 'opfs-async-shutdown': async ()=>{
360
+ flagAsyncShutdown = true;
361
+ storeAndNotify('opfs-async-shutdown', 0);
362
+ },
363
+ mkdir: async (dirname)=>{
364
+ let rc = 0;
365
+ try {
366
+ await getDirForFilename(dirname+"/filepart", true);
367
+ }catch(e){
368
+ state.s11n.storeException(2,e);
369
+ rc = state.sq3Codes.SQLITE_IOERR;
370
+ }
371
+ storeAndNotify('mkdir', rc);
372
+ },
373
+ xAccess: async (filename)=>{
374
+ /* OPFS cannot support the full range of xAccess() queries
375
+ sqlite3 calls for. We can essentially just tell if the file
376
+ is accessible, but if it is then it's automatically writable
377
+ (unless it's locked, which we cannot(?) know without trying
378
+ to open it). OPFS does not have the notion of read-only.
379
+
380
+ The return semantics of this function differ from sqlite3's
381
+ xAccess semantics because we are limited in what we can
382
+ communicate back to our synchronous communication partner: 0 =
383
+ accessible, non-0 means not accessible.
384
+ */
385
+ let rc = 0;
386
+ try{
387
+ const [dh, fn] = await getDirForFilename(filename);
388
+ await dh.getFileHandle(fn);
389
+ }catch(e){
390
+ state.s11n.storeException(2,e);
391
+ rc = state.sq3Codes.SQLITE_IOERR;
392
+ }
393
+ storeAndNotify('xAccess', rc);
394
+ },
395
+ xClose: async function(fid/*sqlite3_file pointer*/){
396
+ const opName = 'xClose';
397
+ __implicitLocks.delete(fid);
398
+ const fh = __openFiles[fid];
399
+ let rc = 0;
400
+ if(fh){
401
+ delete __openFiles[fid];
402
+ await closeSyncHandle(fh);
403
+ if(fh.deleteOnClose){
404
+ try{ await fh.dirHandle.removeEntry(fh.filenamePart) }
405
+ catch(e){ warn("Ignoring dirHandle.removeEntry() failure of",fh,e) }
406
+ }
407
+ }else{
408
+ state.s11n.serialize();
409
+ rc = state.sq3Codes.SQLITE_NOTFOUND;
410
+ }
411
+ storeAndNotify(opName, rc);
412
+ },
413
+ xDelete: async function(...args){
414
+ const rc = await vfsAsyncImpls.xDeleteNoWait(...args);
415
+ storeAndNotify('xDelete', rc);
416
+ },
417
+ xDeleteNoWait: async function(filename, syncDir = 0, recursive = false){
418
+ /* The syncDir flag is, for purposes of the VFS API's semantics,
419
+ ignored here. However, if it has the value 0x1234 then: after
420
+ deleting the given file, recursively try to delete any empty
421
+ directories left behind in its wake (ignoring any errors and
422
+ stopping at the first failure).
423
+
424
+ That said: we don't know for sure that removeEntry() fails if
425
+ the dir is not empty because the API is not documented. It has,
426
+ however, a "recursive" flag which defaults to false, so
427
+ presumably it will fail if the dir is not empty and that flag
428
+ is false.
429
+ */
430
+ let rc = 0;
431
+ try {
432
+ while(filename){
433
+ const [hDir, filenamePart] = await getDirForFilename(filename, false);
434
+ if(!filenamePart) break;
435
+ await hDir.removeEntry(filenamePart, {recursive});
436
+ if(0x1234 !== syncDir) break;
437
+ recursive = false;
438
+ filename = getResolvedPath(filename, true);
439
+ filename.pop();
440
+ filename = filename.join('/');
441
+ }
442
+ }catch(e){
443
+ state.s11n.storeException(2,e);
444
+ rc = state.sq3Codes.SQLITE_IOERR_DELETE;
445
+ }
446
+ return rc;
447
+ },
448
+ xFileSize: async function(fid/*sqlite3_file pointer*/){
449
+ const fh = __openFiles[fid];
450
+ let rc = 0;
451
+ try{
452
+ const sz = await (await getSyncHandle(fh,'xFileSize')).getSize();
453
+ state.s11n.serialize(Number(sz));
454
+ }catch(e){
455
+ state.s11n.storeException(1,e);
456
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR);
457
+ }
458
+ await releaseImplicitLock(fh);
459
+ storeAndNotify('xFileSize', rc);
460
+ },
461
+ xLock: async function(fid/*sqlite3_file pointer*/,
462
+ lockType/*SQLITE_LOCK_...*/){
463
+ const fh = __openFiles[fid];
464
+ let rc = 0;
465
+ const oldLockType = fh.xLock;
466
+ fh.xLock = lockType;
467
+ if( !fh.syncHandle ){
468
+ try {
469
+ await getSyncHandle(fh,'xLock');
470
+ __implicitLocks.delete(fid);
471
+ }catch(e){
472
+ state.s11n.storeException(1,e);
473
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_LOCK);
474
+ fh.xLock = oldLockType;
475
+ }
476
+ }
477
+ storeAndNotify('xLock',rc);
478
+ },
479
+ xOpen: async function(fid/*sqlite3_file pointer*/, filename,
480
+ flags/*SQLITE_OPEN_...*/,
481
+ opfsFlags/*OPFS_...*/){
482
+ const opName = 'xOpen';
483
+ const create = (state.sq3Codes.SQLITE_OPEN_CREATE & flags);
484
+ try{
485
+ let hDir, filenamePart;
486
+ try {
487
+ [hDir, filenamePart] = await getDirForFilename(filename, !!create);
488
+ }catch(e){
489
+ state.s11n.storeException(1,e);
490
+ storeAndNotify(opName, state.sq3Codes.SQLITE_NOTFOUND);
491
+ return;
492
+ }
493
+ if( state.opfsFlags.OPFS_UNLINK_BEFORE_OPEN & opfsFlags ){
494
+ try{
495
+ await hDir.removeEntry(filenamePart);
496
+ }catch(e){
497
+ /* ignoring */
498
+ //warn("Ignoring failed Unlink of",filename,":",e);
499
+ }
500
+ }
501
+ const hFile = await hDir.getFileHandle(filenamePart, {create});
502
+ const fh = Object.assign(Object.create(null),{
503
+ fid: fid,
504
+ filenameAbs: filename,
505
+ filenamePart: filenamePart,
506
+ dirHandle: hDir,
507
+ fileHandle: hFile,
508
+ sabView: state.sabFileBufView,
509
+ readOnly: !create && !!(state.sq3Codes.SQLITE_OPEN_READONLY & flags),
510
+ deleteOnClose: !!(state.sq3Codes.SQLITE_OPEN_DELETEONCLOSE & flags)
511
+ });
512
+ fh.releaseImplicitLocks =
513
+ (opfsFlags & state.opfsFlags.OPFS_UNLOCK_ASAP)
514
+ || state.opfsFlags.defaultUnlockAsap;
515
+ __openFiles[fid] = fh;
516
+ storeAndNotify(opName, 0);
517
+ }catch(e){
518
+ error(opName,e);
519
+ state.s11n.storeException(1,e);
520
+ storeAndNotify(opName, state.sq3Codes.SQLITE_IOERR);
521
+ }
522
+ },
523
+ xRead: async function(fid/*sqlite3_file pointer*/,n,offset64){
524
+ let rc = 0, nRead;
525
+ const fh = __openFiles[fid];
526
+ try{
527
+ nRead = (await getSyncHandle(fh,'xRead')).read(
528
+ fh.sabView.subarray(0, n),
529
+ {at: Number(offset64)}
530
+ );
531
+ if(nRead < n){/* Zero-fill remaining bytes */
532
+ fh.sabView.fill(0, nRead, n);
533
+ rc = state.sq3Codes.SQLITE_IOERR_SHORT_READ;
534
+ }
535
+ }catch(e){
536
+ error("xRead() failed",e,fh);
537
+ state.s11n.storeException(1,e);
538
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_READ);
539
+ }
540
+ await releaseImplicitLock(fh);
541
+ storeAndNotify('xRead',rc);
542
+ },
543
+ xSync: async function(fid/*sqlite3_file pointer*/,flags/*ignored*/){
544
+ const fh = __openFiles[fid];
545
+ let rc = 0;
546
+ if(!fh.readOnly && fh.syncHandle){
547
+ try {
548
+ await fh.syncHandle.flush();
549
+ }catch(e){
550
+ state.s11n.storeException(2,e);
551
+ rc = state.sq3Codes.SQLITE_IOERR_FSYNC;
552
+ }
553
+ }
554
+ storeAndNotify('xSync',rc);
555
+ },
556
+ xTruncate: async function(fid/*sqlite3_file pointer*/,size){
557
+ let rc = 0;
558
+ const fh = __openFiles[fid];
559
+ try{
560
+ affirmNotRO('xTruncate', fh);
561
+ await (await getSyncHandle(fh,'xTruncate')).truncate(size);
562
+ }catch(e){
563
+ error("xTruncate():",e,fh);
564
+ state.s11n.storeException(2,e);
565
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_TRUNCATE);
566
+ }
567
+ await releaseImplicitLock(fh);
568
+ storeAndNotify('xTruncate',rc);
569
+ },
570
+ xUnlock: async function(fid/*sqlite3_file pointer*/,
571
+ lockType/*SQLITE_LOCK_...*/){
572
+ let rc = 0;
573
+ const fh = __openFiles[fid];
574
+ if( fh.syncHandle
575
+ && state.sq3Codes.SQLITE_LOCK_NONE===lockType
576
+ /* Note that we do not differentiate between lock types in
577
+ this VFS. We're either locked or unlocked. */ ){
578
+ try { await closeSyncHandle(fh) }
579
+ catch(e){
580
+ state.s11n.storeException(1,e);
581
+ rc = state.sq3Codes.SQLITE_IOERR_UNLOCK;
582
+ }
583
+ }
584
+ storeAndNotify('xUnlock',rc);
585
+ },
586
+ xWrite: async function(fid/*sqlite3_file pointer*/,n,offset64){
587
+ let rc;
588
+ const fh = __openFiles[fid];
589
+ try{
590
+ affirmNotRO('xWrite', fh);
591
+ rc = (
592
+ n === (await getSyncHandle(fh,'xWrite'))
593
+ .write(fh.sabView.subarray(0, n),
594
+ {at: Number(offset64)})
595
+ ) ? 0 : state.sq3Codes.SQLITE_IOERR_WRITE;
596
+ }catch(e){
597
+ error("xWrite():",e,fh);
598
+ state.s11n.storeException(1,e);
599
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_WRITE);
600
+ }
601
+ await releaseImplicitLock(fh);
602
+ storeAndNotify('xWrite',rc);
603
+ }
604
+ }/*vfsAsyncImpls*/;
605
+
606
+ const initS11n = ()=>{
607
+ /**
608
+ ACHTUNG: this code is 100% duplicated in the other half of this
609
+ proxy! The documentation is maintained in the "synchronous half".
610
+ */
611
+ if(state.s11n) return state.s11n;
612
+ const textDecoder = new TextDecoder(),
613
+ textEncoder = new TextEncoder('utf-8'),
614
+ viewU8 = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize),
615
+ viewDV = new DataView(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
616
+ state.s11n = Object.create(null);
617
+ const TypeIds = Object.create(null);
618
+ TypeIds.number = { id: 1, size: 8, getter: 'getFloat64', setter: 'setFloat64' };
619
+ TypeIds.bigint = { id: 2, size: 8, getter: 'getBigInt64', setter: 'setBigInt64' };
620
+ TypeIds.boolean = { id: 3, size: 4, getter: 'getInt32', setter: 'setInt32' };
621
+ TypeIds.string = { id: 4 };
622
+ const getTypeId = (v)=>(
623
+ TypeIds[typeof v]
624
+ || toss("Maintenance required: this value type cannot be serialized.",v)
625
+ );
626
+ const getTypeIdById = (tid)=>{
627
+ switch(tid){
628
+ case TypeIds.number.id: return TypeIds.number;
629
+ case TypeIds.bigint.id: return TypeIds.bigint;
630
+ case TypeIds.boolean.id: return TypeIds.boolean;
631
+ case TypeIds.string.id: return TypeIds.string;
632
+ default: toss("Invalid type ID:",tid);
633
+ }
634
+ };
635
+ state.s11n.deserialize = function(clear=false){
636
+ const argc = viewU8[0];
637
+ const rc = argc ? [] : null;
638
+ if(argc){
639
+ const typeIds = [];
640
+ let offset = 1, i, n, v;
641
+ for(i = 0; i < argc; ++i, ++offset){
642
+ typeIds.push(getTypeIdById(viewU8[offset]));
643
+ }
644
+ for(i = 0; i < argc; ++i){
645
+ const t = typeIds[i];
646
+ if(t.getter){
647
+ v = viewDV[t.getter](offset, state.littleEndian);
648
+ offset += t.size;
649
+ }else{/*String*/
650
+ n = viewDV.getInt32(offset, state.littleEndian);
651
+ offset += 4;
652
+ v = textDecoder.decode(viewU8.slice(offset, offset+n));
653
+ offset += n;
654
+ }
655
+ rc.push(v);
656
+ }
657
+ }
658
+ if(clear) viewU8[0] = 0;
659
+ //log("deserialize:",argc, rc);
660
+ return rc;
661
+ };
662
+ state.s11n.serialize = function(...args){
663
+ if(args.length){
664
+ //log("serialize():",args);
665
+ const typeIds = [];
666
+ let i = 0, offset = 1;
667
+ viewU8[0] = args.length & 0xff /* header = # of args */;
668
+ for(; i < args.length; ++i, ++offset){
669
+ /* Write the TypeIds.id value into the next args.length
670
+ bytes. */
671
+ typeIds.push(getTypeId(args[i]));
672
+ viewU8[offset] = typeIds[i].id;
673
+ }
674
+ for(i = 0; i < args.length; ++i) {
675
+ /* Deserialize the following bytes based on their
676
+ corresponding TypeIds.id from the header. */
677
+ const t = typeIds[i];
678
+ if(t.setter){
679
+ viewDV[t.setter](offset, args[i], state.littleEndian);
680
+ offset += t.size;
681
+ }else{/*String*/
682
+ const s = textEncoder.encode(args[i]);
683
+ viewDV.setInt32(offset, s.byteLength, state.littleEndian);
684
+ offset += 4;
685
+ viewU8.set(s, offset);
686
+ offset += s.byteLength;
687
+ }
688
+ }
689
+ //log("serialize() result:",viewU8.slice(0,offset));
690
+ }else{
691
+ viewU8[0] = 0;
692
+ }
693
+ };
694
+
695
+ state.s11n.storeException = state.asyncS11nExceptions
696
+ ? ((priority,e)=>{
697
+ if(priority<=state.asyncS11nExceptions){
698
+ state.s11n.serialize([e.name,': ',e.message].join(""));
699
+ }
700
+ })
701
+ : ()=>{};
702
+
703
+ return state.s11n;
704
+ }/*initS11n()*/;
705
+
706
+ const waitLoop = async function f(){
707
+ const opHandlers = Object.create(null);
708
+ for(let k of Object.keys(state.opIds)){
709
+ const vi = vfsAsyncImpls[k];
710
+ if(!vi) continue;
711
+ const o = Object.create(null);
712
+ opHandlers[state.opIds[k]] = o;
713
+ o.key = k;
714
+ o.f = vi;
715
+ }
716
+ while(!flagAsyncShutdown){
717
+ try {
718
+ if('not-equal'!==Atomics.wait(
719
+ state.sabOPView, state.opIds.whichOp, 0, state.asyncIdleWaitTime
720
+ )){
721
+ /* Maintenance note: we compare against 'not-equal' because
722
+
723
+ https://github.com/tomayac/sqlite-wasm/issues/12
724
+
725
+ is reporting that this occassionally, under high loads,
726
+ returns 'ok', which leads to the whichOp being 0 (which
727
+ isn't a valid operation ID and leads to an exception,
728
+ along with a corresponding ugly console log
729
+ message). Unfortunately, the conditions for that cannot
730
+ be reliably reproduced. The only place in our code which
731
+ writes a 0 to the state.opIds.whichOp SharedArrayBuffer
732
+ index is a few lines down from here, and that instance
733
+ is required in order for clear communication between
734
+ the sync half of this proxy and this half.
735
+ */
736
+ await releaseImplicitLocks();
737
+ continue;
738
+ }
739
+ const opId = Atomics.load(state.sabOPView, state.opIds.whichOp);
740
+ Atomics.store(state.sabOPView, state.opIds.whichOp, 0);
741
+ const hnd = opHandlers[opId] ?? toss("No waitLoop handler for whichOp #",opId);
742
+ const args = state.s11n.deserialize(
743
+ true /* clear s11n to keep the caller from confusing this with
744
+ an exception string written by the upcoming
745
+ operation */
746
+ ) || [];
747
+ //warn("waitLoop() whichOp =",opId, hnd, args);
748
+ if(hnd.f) await hnd.f(...args);
749
+ else error("Missing callback for opId",opId);
750
+ }catch(e){
751
+ error('in waitLoop():',e);
752
+ }
753
+ }
754
+ };
755
+
756
+ navigator.storage.getDirectory().then(function(d){
757
+ state.rootDir = d;
758
+ globalThis.onmessage = function({data}){
759
+ switch(data.type){
760
+ case 'opfs-async-init':{
761
+ /* Receive shared state from synchronous partner */
762
+ const opt = data.args;
763
+ for(const k in opt) state[k] = opt[k];
764
+ state.verbose = opt.verbose ?? 1;
765
+ state.sabOPView = new Int32Array(state.sabOP);
766
+ state.sabFileBufView = new Uint8Array(state.sabIO, 0, state.fileBufferSize);
767
+ state.sabS11nView = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
768
+ Object.keys(vfsAsyncImpls).forEach((k)=>{
769
+ if(!Number.isFinite(state.opIds[k])){
770
+ toss("Maintenance required: missing state.opIds[",k,"]");
771
+ }
772
+ });
773
+ initS11n();
774
+ log("init state",state);
775
+ wPost('opfs-async-inited');
776
+ waitLoop();
777
+ break;
778
+ }
779
+ case 'opfs-async-restart':
780
+ if(flagAsyncShutdown){
781
+ warn("Restarting after opfs-async-shutdown. Might or might not work.");
782
+ flagAsyncShutdown = false;
783
+ waitLoop();
784
+ }
785
+ break;
786
+ }
787
+ };
788
+ wPost('opfs-async-loaded');
789
+ }).catch((e)=>error("error initializing OPFS asyncer:",e));
790
+ }/*installAsyncProxy()*/;
791
+ if(!globalThis.SharedArrayBuffer){
792
+ wPost('opfs-unavailable', "Missing SharedArrayBuffer API.",
793
+ "The server must emit the COOP/COEP response headers to enable that.");
794
+ }else if(!globalThis.Atomics){
795
+ wPost('opfs-unavailable', "Missing Atomics API.",
796
+ "The server must emit the COOP/COEP response headers to enable that.");
797
+ }else if(!globalThis.FileSystemHandle ||
798
+ !globalThis.FileSystemDirectoryHandle ||
799
+ !globalThis.FileSystemFileHandle ||
800
+ !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle ||
801
+ !navigator?.storage?.getDirectory){
802
+ wPost('opfs-unavailable',"Missing required OPFS APIs.");
803
+ }else{
804
+ installAsyncProxy();
805
+ }
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-vfs-helper.c-pp.js ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ ** 2022-11-30
3
+ **
4
+ ** The author disclaims copyright to this source code. In place of a
5
+ ** legal notice, here is a blessing:
6
+ **
7
+ ** * May you do good and not evil.
8
+ ** * May you find forgiveness for yourself and forgive others.
9
+ ** * May you share freely, never taking more than you give.
10
+ */
11
+
12
+ /**
13
+ This file installs sqlite3.vfs, a namespace of helpers for use in
14
+ the creation of JavaScript implementations of sqlite3_vfs.
15
+ */
16
+ 'use strict';
17
+ globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
18
+ const wasm = sqlite3.wasm, capi = sqlite3.capi, toss = sqlite3.util.toss3;
19
+ const vfs = Object.create(null);
20
+ sqlite3.vfs = vfs;
21
+
22
+ /**
23
+ Uses sqlite3_vfs_register() to register this
24
+ sqlite3.capi.sqlite3_vfs instance. This object must have already
25
+ been filled out properly. If the first argument is truthy, the
26
+ VFS is registered as the default VFS, else it is not.
27
+
28
+ On success, returns this object. Throws on error.
29
+ */
30
+ capi.sqlite3_vfs.prototype.registerVfs = function(asDefault=false){
31
+ if(!(this instanceof sqlite3.capi.sqlite3_vfs)){
32
+ toss("Expecting a sqlite3_vfs-type argument.");
33
+ }
34
+ const rc = capi.sqlite3_vfs_register(this, asDefault ? 1 : 0);
35
+ if(rc){
36
+ toss("sqlite3_vfs_register(",this,") failed with rc",rc);
37
+ }
38
+ if(this.pointer !== capi.sqlite3_vfs_find(this.$zName)){
39
+ toss("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",
40
+ this);
41
+ }
42
+ return this;
43
+ };
44
+
45
+ /**
46
+ A wrapper for
47
+ sqlite3.StructBinder.StructType.prototype.installMethods() or
48
+ registerVfs() to reduce installation of a VFS and/or its I/O
49
+ methods to a single call.
50
+
51
+ Accepts an object which contains the properties "io" and/or
52
+ "vfs", each of which is itself an object with following properties:
53
+
54
+ - `struct`: an sqlite3.StructBinder.StructType-type struct. This
55
+ must be a populated (except for the methods) object of type
56
+ sqlite3_io_methods (for the "io" entry) or sqlite3_vfs (for the
57
+ "vfs" entry).
58
+
59
+ - `methods`: an object mapping sqlite3_io_methods method names
60
+ (e.g. 'xClose') to JS implementations of those methods. The JS
61
+ implementations must be call-compatible with their native
62
+ counterparts.
63
+
64
+ For each of those object, this function passes its (`struct`,
65
+ `methods`, (optional) `applyArgcCheck`) properties to
66
+ installMethods().
67
+
68
+ If the `vfs` entry is set then:
69
+
70
+ - Its `struct` property's registerVfs() is called. The
71
+ `vfs` entry may optionally have an `asDefault` property, which
72
+ gets passed as the argument to registerVfs().
73
+
74
+ - If `struct.$zName` is falsy and the entry has a string-type
75
+ `name` property, `struct.$zName` is set to the C-string form of
76
+ that `name` value before registerVfs() is called. That string
77
+ gets added to the on-dispose state of the struct.
78
+
79
+ On success returns this object. Throws on error.
80
+ */
81
+ vfs.installVfs = function(opt){
82
+ let count = 0;
83
+ const propList = ['io','vfs'];
84
+ for(const key of propList){
85
+ const o = opt[key];
86
+ if(o){
87
+ ++count;
88
+ o.struct.installMethods(o.methods, !!o.applyArgcCheck);
89
+ if('vfs'===key){
90
+ if(!o.struct.$zName && 'string'===typeof o.name){
91
+ o.struct.addOnDispose(
92
+ o.struct.$zName = wasm.allocCString(o.name)
93
+ );
94
+ }
95
+ o.struct.registerVfs(!!o.asDefault);
96
+ }
97
+ }
98
+ }
99
+ if(!count) toss("Misuse: installVfs() options object requires at least",
100
+ "one of:", propList);
101
+ return this;
102
+ };
103
+ }/*sqlite3ApiBootstrap.initializers.push()*/);
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js ADDED
@@ -0,0 +1,1301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //#ifnot target=node
2
+ /*
3
+ 2023-07-14
4
+
5
+ The author disclaims copyright to this source code. In place of a
6
+ legal notice, here is a blessing:
7
+
8
+ * May you do good and not evil.
9
+ * May you find forgiveness for yourself and forgive others.
10
+ * May you share freely, never taking more than you give.
11
+
12
+ ***********************************************************************
13
+
14
+ This file holds a sqlite3_vfs backed by OPFS storage which uses a
15
+ different implementation strategy than the "opfs" VFS. This one is a
16
+ port of Roy Hashimoto's OPFS SyncAccessHandle pool:
17
+
18
+ https://github.com/rhashimoto/wa-sqlite/blob/master/src/examples/AccessHandlePoolVFS.js
19
+
20
+ As described at:
21
+
22
+ https://github.com/rhashimoto/wa-sqlite/discussions/67
23
+
24
+ with Roy's explicit permission to permit us to port his to our
25
+ infrastructure rather than having to clean-room reverse-engineer it:
26
+
27
+ https://sqlite.org/forum/forumpost/e140d84e71
28
+
29
+ Primary differences from the "opfs" VFS include:
30
+
31
+ - This one avoids the need for a sub-worker to synchronize
32
+ communication between the synchronous C API and the
33
+ only-partly-synchronous OPFS API.
34
+
35
+ - It does so by opening a fixed number of OPFS files at
36
+ library-level initialization time, obtaining SyncAccessHandles to
37
+ each, and manipulating those handles via the synchronous sqlite3_vfs
38
+ interface. If it cannot open them (e.g. they are already opened by
39
+ another tab) then the VFS will not be installed.
40
+
41
+ - Because of that, this one lacks all library-level concurrency
42
+ support.
43
+
44
+ - Also because of that, it does not require the SharedArrayBuffer,
45
+ so can function without the COOP/COEP HTTP response headers.
46
+
47
+ - It can hypothetically support Safari 16.4+, whereas the "opfs" VFS
48
+ requires v17 due to a subworker/storage bug in 16.x which makes it
49
+ incompatible with that VFS.
50
+
51
+ - This VFS requires the "semi-fully-sync" FileSystemSyncAccessHandle
52
+ (hereafter "SAH") APIs released with Chrome v108 (and all other
53
+ major browsers released since March 2023). If that API is not
54
+ detected, the VFS is not registered.
55
+ */
56
+ globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
57
+ 'use strict';
58
+ const toss = sqlite3.util.toss;
59
+ const toss3 = sqlite3.util.toss3;
60
+ const initPromises = Object.create(null) /* cache of (name:result) of VFS init results */;
61
+ const capi = sqlite3.capi;
62
+ const util = sqlite3.util;
63
+ const wasm = sqlite3.wasm;
64
+ // Config opts for the VFS...
65
+ const SECTOR_SIZE = 4096;
66
+ const HEADER_MAX_PATH_SIZE = 512;
67
+ const HEADER_FLAGS_SIZE = 4;
68
+ const HEADER_DIGEST_SIZE = 8;
69
+ const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
70
+ const HEADER_OFFSET_FLAGS = HEADER_MAX_PATH_SIZE;
71
+ const HEADER_OFFSET_DIGEST = HEADER_CORPUS_SIZE;
72
+ const HEADER_OFFSET_DATA = SECTOR_SIZE;
73
+ /* Bitmask of file types which may persist across sessions.
74
+ SQLITE_OPEN_xyz types not listed here may be inadvertently
75
+ left in OPFS but are treated as transient by this VFS and
76
+ they will be cleaned up during VFS init. */
77
+ const PERSISTENT_FILE_TYPES =
78
+ capi.SQLITE_OPEN_MAIN_DB |
79
+ capi.SQLITE_OPEN_MAIN_JOURNAL |
80
+ capi.SQLITE_OPEN_SUPER_JOURNAL |
81
+ capi.SQLITE_OPEN_WAL;
82
+
83
+ /** Subdirectory of the VFS's space where "opaque" (randomly-named)
84
+ files are stored. Changing this effectively invalidates the data
85
+ stored under older names (orphaning it), so don't do that. */
86
+ const OPAQUE_DIR_NAME = ".opaque";
87
+
88
+ /**
89
+ Returns short a string of random alphanumeric characters
90
+ suitable for use as a random filename.
91
+ */
92
+ const getRandomName = ()=>Math.random().toString(36).slice(2);
93
+
94
+ const textDecoder = new TextDecoder();
95
+ const textEncoder = new TextEncoder();
96
+
97
+ const optionDefaults = Object.assign(Object.create(null),{
98
+ name: 'opfs-sahpool',
99
+ directory: undefined /* derived from .name */,
100
+ initialCapacity: 6,
101
+ clearOnInit: false,
102
+ /* Logging verbosity 3+ == everything, 2 == warnings+errors, 1 ==
103
+ errors only. */
104
+ verbosity: 2,
105
+ forceReinitIfPreviouslyFailed: false
106
+ });
107
+
108
+ /** Logging routines, from most to least serious. */
109
+ const loggers = [
110
+ sqlite3.config.error,
111
+ sqlite3.config.warn,
112
+ sqlite3.config.log
113
+ ];
114
+ const log = sqlite3.config.log;
115
+ const warn = sqlite3.config.warn;
116
+ const error = sqlite3.config.error;
117
+
118
+ /* Maps (sqlite3_vfs*) to OpfsSAHPool instances */
119
+ const __mapVfsToPool = new Map();
120
+ const getPoolForVfs = (pVfs)=>__mapVfsToPool.get(pVfs);
121
+ const setPoolForVfs = (pVfs,pool)=>{
122
+ if(pool) __mapVfsToPool.set(pVfs, pool);
123
+ else __mapVfsToPool.delete(pVfs);
124
+ };
125
+ /* Maps (sqlite3_file*) to OpfsSAHPool instances */
126
+ const __mapSqlite3File = new Map();
127
+ const getPoolForPFile = (pFile)=>__mapSqlite3File.get(pFile);
128
+ const setPoolForPFile = (pFile,pool)=>{
129
+ if(pool) __mapSqlite3File.set(pFile, pool);
130
+ else __mapSqlite3File.delete(pFile);
131
+ };
132
+
133
+ /**
134
+ Impls for the sqlite3_io_methods methods. Maintenance reminder:
135
+ members are in alphabetical order to simplify finding them.
136
+ */
137
+ const ioMethods = {
138
+ xCheckReservedLock: function(pFile,pOut){
139
+ const pool = getPoolForPFile(pFile);
140
+ pool.log('xCheckReservedLock');
141
+ pool.storeErr();
142
+ wasm.poke32(pOut, 1);
143
+ return 0;
144
+ },
145
+ xClose: function(pFile){
146
+ const pool = getPoolForPFile(pFile);
147
+ pool.storeErr();
148
+ const file = pool.getOFileForS3File(pFile);
149
+ if(file) {
150
+ try{
151
+ pool.log(`xClose ${file.path}`);
152
+ pool.mapS3FileToOFile(pFile, false);
153
+ file.sah.flush();
154
+ if(file.flags & capi.SQLITE_OPEN_DELETEONCLOSE){
155
+ pool.deletePath(file.path);
156
+ }
157
+ }catch(e){
158
+ return pool.storeErr(e, capi.SQLITE_IOERR);
159
+ }
160
+ }
161
+ return 0;
162
+ },
163
+ xDeviceCharacteristics: function(pFile){
164
+ return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
165
+ },
166
+ xFileControl: function(pFile, opId, pArg){
167
+ return capi.SQLITE_NOTFOUND;
168
+ },
169
+ xFileSize: function(pFile,pSz64){
170
+ const pool = getPoolForPFile(pFile);
171
+ pool.log(`xFileSize`);
172
+ const file = pool.getOFileForS3File(pFile);
173
+ const size = file.sah.getSize() - HEADER_OFFSET_DATA;
174
+ //log(`xFileSize ${file.path} ${size}`);
175
+ wasm.poke64(pSz64, BigInt(size));
176
+ return 0;
177
+ },
178
+ xLock: function(pFile,lockType){
179
+ const pool = getPoolForPFile(pFile);
180
+ pool.log(`xLock ${lockType}`);
181
+ pool.storeErr();
182
+ const file = pool.getOFileForS3File(pFile);
183
+ file.lockType = lockType;
184
+ return 0;
185
+ },
186
+ xRead: function(pFile,pDest,n,offset64){
187
+ const pool = getPoolForPFile(pFile);
188
+ pool.storeErr();
189
+ const file = pool.getOFileForS3File(pFile);
190
+ pool.log(`xRead ${file.path} ${n} @ ${offset64}`);
191
+ try {
192
+ const nRead = file.sah.read(
193
+ wasm.heap8u().subarray(pDest, pDest+n),
194
+ {at: HEADER_OFFSET_DATA + Number(offset64)}
195
+ );
196
+ if(nRead < n){
197
+ wasm.heap8u().fill(0, pDest + nRead, pDest + n);
198
+ return capi.SQLITE_IOERR_SHORT_READ;
199
+ }
200
+ return 0;
201
+ }catch(e){
202
+ return pool.storeErr(e, capi.SQLITE_IOERR);
203
+ }
204
+ },
205
+ xSectorSize: function(pFile){
206
+ return SECTOR_SIZE;
207
+ },
208
+ xSync: function(pFile,flags){
209
+ const pool = getPoolForPFile(pFile);
210
+ pool.log(`xSync ${flags}`);
211
+ pool.storeErr();
212
+ const file = pool.getOFileForS3File(pFile);
213
+ //log(`xSync ${file.path} ${flags}`);
214
+ try{
215
+ file.sah.flush();
216
+ return 0;
217
+ }catch(e){
218
+ return pool.storeErr(e, capi.SQLITE_IOERR);
219
+ }
220
+ },
221
+ xTruncate: function(pFile,sz64){
222
+ const pool = getPoolForPFile(pFile);
223
+ pool.log(`xTruncate ${sz64}`);
224
+ pool.storeErr();
225
+ const file = pool.getOFileForS3File(pFile);
226
+ //log(`xTruncate ${file.path} ${iSize}`);
227
+ try{
228
+ file.sah.truncate(HEADER_OFFSET_DATA + Number(sz64));
229
+ return 0;
230
+ }catch(e){
231
+ return pool.storeErr(e, capi.SQLITE_IOERR);
232
+ }
233
+ },
234
+ xUnlock: function(pFile,lockType){
235
+ const pool = getPoolForPFile(pFile);
236
+ pool.log('xUnlock');
237
+ const file = pool.getOFileForS3File(pFile);
238
+ file.lockType = lockType;
239
+ return 0;
240
+ },
241
+ xWrite: function(pFile,pSrc,n,offset64){
242
+ const pool = getPoolForPFile(pFile);
243
+ pool.storeErr();
244
+ const file = pool.getOFileForS3File(pFile);
245
+ pool.log(`xWrite ${file.path} ${n} ${offset64}`);
246
+ try{
247
+ const nBytes = file.sah.write(
248
+ wasm.heap8u().subarray(pSrc, pSrc+n),
249
+ { at: HEADER_OFFSET_DATA + Number(offset64) }
250
+ );
251
+ return n===nBytes ? 0 : toss("Unknown write() failure.");
252
+ }catch(e){
253
+ return pool.storeErr(e, capi.SQLITE_IOERR);
254
+ }
255
+ }
256
+ }/*ioMethods*/;
257
+
258
+ const opfsIoMethods = new capi.sqlite3_io_methods();
259
+ opfsIoMethods.$iVersion = 1;
260
+ sqlite3.vfs.installVfs({
261
+ io: {struct: opfsIoMethods, methods: ioMethods}
262
+ });
263
+
264
+ /**
265
+ Impls for the sqlite3_vfs methods. Maintenance reminder: members
266
+ are in alphabetical order to simplify finding them.
267
+ */
268
+ const vfsMethods = {
269
+ xAccess: function(pVfs,zName,flags,pOut){
270
+ //log(`xAccess ${wasm.cstrToJs(zName)}`);
271
+ const pool = getPoolForVfs(pVfs);
272
+ pool.storeErr();
273
+ try{
274
+ const name = pool.getPath(zName);
275
+ wasm.poke32(pOut, pool.hasFilename(name) ? 1 : 0);
276
+ }catch(e){
277
+ /*ignored*/
278
+ wasm.poke32(pOut, 0);
279
+ }
280
+ return 0;
281
+ },
282
+ xCurrentTime: function(pVfs,pOut){
283
+ wasm.poke(pOut, 2440587.5 + (new Date().getTime()/86400000),
284
+ 'double');
285
+ return 0;
286
+ },
287
+ xCurrentTimeInt64: function(pVfs,pOut){
288
+ wasm.poke(pOut, (2440587.5 * 86400000) + new Date().getTime(),
289
+ 'i64');
290
+ return 0;
291
+ },
292
+ xDelete: function(pVfs, zName, doSyncDir){
293
+ const pool = getPoolForVfs(pVfs);
294
+ pool.log(`xDelete ${wasm.cstrToJs(zName)}`);
295
+ pool.storeErr();
296
+ try{
297
+ pool.deletePath(pool.getPath(zName));
298
+ return 0;
299
+ }catch(e){
300
+ pool.storeErr(e);
301
+ return capi.SQLITE_IOERR_DELETE;
302
+ }
303
+ },
304
+ xFullPathname: function(pVfs,zName,nOut,pOut){
305
+ //const pool = getPoolForVfs(pVfs);
306
+ //pool.log(`xFullPathname ${wasm.cstrToJs(zName)}`);
307
+ const i = wasm.cstrncpy(pOut, zName, nOut);
308
+ return i<nOut ? 0 : capi.SQLITE_CANTOPEN;
309
+ },
310
+ xGetLastError: function(pVfs,nOut,pOut){
311
+ const pool = getPoolForVfs(pVfs);
312
+ const e = pool.popErr();
313
+ pool.log(`xGetLastError ${nOut} e =`,e);
314
+ if(e){
315
+ const scope = wasm.scopedAllocPush();
316
+ try{
317
+ const [cMsg, n] = wasm.scopedAllocCString(e.message, true);
318
+ wasm.cstrncpy(pOut, cMsg, nOut);
319
+ if(n > nOut) wasm.poke8(pOut + nOut - 1, 0);
320
+ }catch(e){
321
+ return capi.SQLITE_NOMEM;
322
+ }finally{
323
+ wasm.scopedAllocPop(scope);
324
+ }
325
+ }
326
+ return e ? (e.sqlite3Rc || capi.SQLITE_IOERR) : 0;
327
+ },
328
+ //xSleep is optionally defined below
329
+ xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){
330
+ const pool = getPoolForVfs(pVfs);
331
+ try{
332
+ pool.log(`xOpen ${wasm.cstrToJs(zName)} ${flags}`);
333
+ // First try to open a path that already exists in the file system.
334
+ const path = (zName && wasm.peek8(zName))
335
+ ? pool.getPath(zName)
336
+ : getRandomName();
337
+ let sah = pool.getSAHForPath(path);
338
+ if(!sah && (flags & capi.SQLITE_OPEN_CREATE)) {
339
+ // File not found so try to create it.
340
+ if(pool.getFileCount() < pool.getCapacity()) {
341
+ // Choose an unassociated OPFS file from the pool.
342
+ sah = pool.nextAvailableSAH();
343
+ pool.setAssociatedPath(sah, path, flags);
344
+ }else{
345
+ // File pool is full.
346
+ toss('SAH pool is full. Cannot create file',path);
347
+ }
348
+ }
349
+ if(!sah){
350
+ toss('file not found:',path);
351
+ }
352
+ // Subsequent I/O methods are only passed the sqlite3_file
353
+ // pointer, so map the relevant info we need to that pointer.
354
+ const file = {path, flags, sah};
355
+ pool.mapS3FileToOFile(pFile, file);
356
+ file.lockType = capi.SQLITE_LOCK_NONE;
357
+ const sq3File = new capi.sqlite3_file(pFile);
358
+ sq3File.$pMethods = opfsIoMethods.pointer;
359
+ sq3File.dispose();
360
+ wasm.poke32(pOutFlags, flags);
361
+ return 0;
362
+ }catch(e){
363
+ pool.storeErr(e);
364
+ return capi.SQLITE_CANTOPEN;
365
+ }
366
+ }/*xOpen()*/
367
+ }/*vfsMethods*/;
368
+
369
+ /**
370
+ Creates and initializes an sqlite3_vfs instance for an
371
+ OpfsSAHPool. The argument is the VFS's name (JS string).
372
+
373
+ Throws if the VFS name is already registered or if something
374
+ goes terribly wrong via sqlite3.vfs.installVfs().
375
+
376
+ Maintenance reminder: the only detail about the returned object
377
+ which is specific to any given OpfsSAHPool instance is the $zName
378
+ member. All other state is identical.
379
+ */
380
+ const createOpfsVfs = function(vfsName){
381
+ if( sqlite3.capi.sqlite3_vfs_find(vfsName)){
382
+ toss3("VFS name is already registered:", vfsName);
383
+ }
384
+ const opfsVfs = new capi.sqlite3_vfs();
385
+ /* We fetch the default VFS so that we can inherit some
386
+ methods from it. */
387
+ const pDVfs = capi.sqlite3_vfs_find(null);
388
+ const dVfs = pDVfs
389
+ ? new capi.sqlite3_vfs(pDVfs)
390
+ : null /* dVfs will be null when sqlite3 is built with
391
+ SQLITE_OS_OTHER. */;
392
+ opfsVfs.$iVersion = 2/*yes, two*/;
393
+ opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
394
+ opfsVfs.$mxPathname = HEADER_MAX_PATH_SIZE;
395
+ opfsVfs.addOnDispose(
396
+ opfsVfs.$zName = wasm.allocCString(vfsName),
397
+ ()=>setPoolForVfs(opfsVfs.pointer, 0)
398
+ );
399
+
400
+ if(dVfs){
401
+ /* Inherit certain VFS members from the default VFS,
402
+ if available. */
403
+ opfsVfs.$xRandomness = dVfs.$xRandomness;
404
+ opfsVfs.$xSleep = dVfs.$xSleep;
405
+ dVfs.dispose();
406
+ }
407
+ if(!opfsVfs.$xRandomness && !vfsMethods.xRandomness){
408
+ /* If the default VFS has no xRandomness(), add a basic JS impl... */
409
+ vfsMethods.xRandomness = function(pVfs, nOut, pOut){
410
+ const heap = wasm.heap8u();
411
+ let i = 0;
412
+ for(; i < nOut; ++i) heap[pOut + i] = (Math.random()*255000) & 0xFF;
413
+ return i;
414
+ };
415
+ }
416
+ if(!opfsVfs.$xSleep && !vfsMethods.xSleep){
417
+ vfsMethods.xSleep = (pVfs,ms)=>0;
418
+ }
419
+ sqlite3.vfs.installVfs({
420
+ vfs: {struct: opfsVfs, methods: vfsMethods}
421
+ });
422
+ return opfsVfs;
423
+ };
424
+
425
+ /**
426
+ Class for managing OPFS-related state for the
427
+ OPFS SharedAccessHandle Pool sqlite3_vfs.
428
+ */
429
+ class OpfsSAHPool {
430
+ /* OPFS dir in which VFS metadata is stored. */
431
+ vfsDir;
432
+ /* Directory handle to this.vfsDir. */
433
+ #dhVfsRoot;
434
+ /* Directory handle to the subdir of this.#dhVfsRoot which holds
435
+ the randomly-named "opaque" files. This subdir exists in the
436
+ hope that we can eventually support client-created files in
437
+ this.#dhVfsRoot. */
438
+ #dhOpaque;
439
+ /* Directory handle to this.dhVfsRoot's parent dir. Needed
440
+ for a VFS-wipe op. */
441
+ #dhVfsParent;
442
+ /* Maps SAHs to their opaque file names. */
443
+ #mapSAHToName = new Map();
444
+ /* Maps client-side file names to SAHs. */
445
+ #mapFilenameToSAH = new Map();
446
+ /* Set of currently-unused SAHs. */
447
+ #availableSAH = new Set();
448
+ /* Maps (sqlite3_file*) to xOpen's file objects. */
449
+ #mapS3FileToOFile_ = new Map();
450
+
451
+ /* Maps SAH to an abstract File Object which contains
452
+ various metadata about that handle. */
453
+ //#mapSAHToMeta = new Map();
454
+
455
+ /** Buffer used by [sg]etAssociatedPath(). */
456
+ #apBody = new Uint8Array(HEADER_CORPUS_SIZE);
457
+ // DataView for this.#apBody
458
+ #dvBody;
459
+
460
+ // associated sqlite3_vfs instance
461
+ #cVfs;
462
+
463
+ // Logging verbosity. See optionDefaults.verbosity.
464
+ #verbosity;
465
+
466
+ constructor(options = Object.create(null)){
467
+ this.#verbosity = options.verbosity ?? optionDefaults.verbosity;
468
+ this.vfsName = options.name || optionDefaults.name;
469
+ this.#cVfs = createOpfsVfs(this.vfsName);
470
+ setPoolForVfs(this.#cVfs.pointer, this);
471
+ this.vfsDir = options.directory || ("."+this.vfsName);
472
+ this.#dvBody =
473
+ new DataView(this.#apBody.buffer, this.#apBody.byteOffset);
474
+ this.isReady = this
475
+ .reset(!!(options.clearOnInit ?? optionDefaults.clearOnInit))
476
+ .then(()=>{
477
+ if(this.$error) throw this.$error;
478
+ return this.getCapacity()
479
+ ? Promise.resolve(undefined)
480
+ : this.addCapacity(options.initialCapacity
481
+ || optionDefaults.initialCapacity);
482
+ });
483
+ }
484
+
485
+ #logImpl(level,...args){
486
+ if(this.#verbosity>level) loggers[level](this.vfsName+":",...args);
487
+ };
488
+ log(...args){this.#logImpl(2, ...args)};
489
+ warn(...args){this.#logImpl(1, ...args)};
490
+ error(...args){this.#logImpl(0, ...args)};
491
+
492
+ getVfs(){return this.#cVfs}
493
+
494
+ /* Current pool capacity. */
495
+ getCapacity(){return this.#mapSAHToName.size}
496
+
497
+ /* Current number of in-use files from pool. */
498
+ getFileCount(){return this.#mapFilenameToSAH.size}
499
+
500
+ /* Returns an array of the names of all
501
+ currently-opened client-specified filenames. */
502
+ getFileNames(){
503
+ const rc = [];
504
+ const iter = this.#mapFilenameToSAH.keys();
505
+ for(const n of iter) rc.push(n);
506
+ return rc;
507
+ }
508
+
509
+ // #createFileObject(sah,clientName,opaqueName){
510
+ // const f = Object.assign(Object.create(null),{
511
+ // clientName, opaqueName
512
+ // });
513
+ // this.#mapSAHToMeta.set(sah, f);
514
+ // return f;
515
+ // }
516
+ // #unmapFileObject(sah){
517
+ // this.#mapSAHToMeta.delete(sah);
518
+ // }
519
+
520
+ /**
521
+ Adds n files to the pool's capacity. This change is
522
+ persistent across settings. Returns a Promise which resolves
523
+ to the new capacity.
524
+ */
525
+ async addCapacity(n){
526
+ for(let i = 0; i < n; ++i){
527
+ const name = getRandomName();
528
+ const h = await this.#dhOpaque.getFileHandle(name, {create:true});
529
+ const ah = await h.createSyncAccessHandle();
530
+ this.#mapSAHToName.set(ah,name);
531
+ this.setAssociatedPath(ah, '', 0);
532
+ //this.#createFileObject(ah,undefined,name);
533
+ }
534
+ return this.getCapacity();
535
+ }
536
+
537
+ /**
538
+ Reduce capacity by n, but can only reduce up to the limit
539
+ of currently-available SAHs. Returns a Promise which resolves
540
+ to the number of slots really removed.
541
+ */
542
+ async reduceCapacity(n){
543
+ let nRm = 0;
544
+ for(const ah of Array.from(this.#availableSAH)){
545
+ if(nRm === n || this.getFileCount() === this.getCapacity()){
546
+ break;
547
+ }
548
+ const name = this.#mapSAHToName.get(ah);
549
+ //this.#unmapFileObject(ah);
550
+ ah.close();
551
+ await this.#dhOpaque.removeEntry(name);
552
+ this.#mapSAHToName.delete(ah);
553
+ this.#availableSAH.delete(ah);
554
+ ++nRm;
555
+ }
556
+ return nRm;
557
+ }
558
+
559
+ /**
560
+ Releases all currently-opened SAHs. The only legal
561
+ operation after this is acquireAccessHandles().
562
+ */
563
+ releaseAccessHandles(){
564
+ for(const ah of this.#mapSAHToName.keys()) ah.close();
565
+ this.#mapSAHToName.clear();
566
+ this.#mapFilenameToSAH.clear();
567
+ this.#availableSAH.clear();
568
+ }
569
+
570
+ /**
571
+ Opens all files under this.vfsDir/this.#dhOpaque and acquires
572
+ a SAH for each. returns a Promise which resolves to no value
573
+ but completes once all SAHs are acquired. If acquiring an SAH
574
+ throws, SAHPool.$error will contain the corresponding
575
+ exception.
576
+
577
+ If clearFiles is true, the client-stored state of each file is
578
+ cleared when its handle is acquired, including its name, flags,
579
+ and any data stored after the metadata block.
580
+ */
581
+ async acquireAccessHandles(clearFiles){
582
+ const files = [];
583
+ for await (const [name,h] of this.#dhOpaque){
584
+ if('file'===h.kind){
585
+ files.push([name,h]);
586
+ }
587
+ }
588
+ return Promise.all(files.map(async([name,h])=>{
589
+ try{
590
+ const ah = await h.createSyncAccessHandle()
591
+ this.#mapSAHToName.set(ah, name);
592
+ if(clearFiles){
593
+ ah.truncate(HEADER_OFFSET_DATA);
594
+ this.setAssociatedPath(ah, '', 0);
595
+ }else{
596
+ const path = this.getAssociatedPath(ah);
597
+ if(path){
598
+ this.#mapFilenameToSAH.set(path, ah);
599
+ }else{
600
+ this.#availableSAH.add(ah);
601
+ }
602
+ }
603
+ }catch(e){
604
+ this.storeErr(e);
605
+ this.releaseAccessHandles();
606
+ throw e;
607
+ }
608
+ }));
609
+ }
610
+
611
+ /**
612
+ Given an SAH, returns the client-specified name of
613
+ that file by extracting it from the SAH's header.
614
+
615
+ On error, it disassociates SAH from the pool and
616
+ returns an empty string.
617
+ */
618
+ getAssociatedPath(sah){
619
+ sah.read(this.#apBody, {at: 0});
620
+ // Delete any unexpected files left over by previous
621
+ // untimely errors...
622
+ const flags = this.#dvBody.getUint32(HEADER_OFFSET_FLAGS);
623
+ if(this.#apBody[0] &&
624
+ ((flags & capi.SQLITE_OPEN_DELETEONCLOSE) ||
625
+ (flags & PERSISTENT_FILE_TYPES)===0)){
626
+ warn(`Removing file with unexpected flags ${flags.toString(16)}`,
627
+ this.#apBody);
628
+ this.setAssociatedPath(sah, '', 0);
629
+ return '';
630
+ }
631
+
632
+ const fileDigest = new Uint32Array(HEADER_DIGEST_SIZE / 4);
633
+ sah.read(fileDigest, {at: HEADER_OFFSET_DIGEST});
634
+ const compDigest = this.computeDigest(this.#apBody);
635
+ if(fileDigest.every((v,i) => v===compDigest[i])){
636
+ // Valid digest
637
+ const pathBytes = this.#apBody.findIndex((v)=>0===v);
638
+ if(0===pathBytes){
639
+ // This file is unassociated, so truncate it to avoid
640
+ // leaving stale db data laying around.
641
+ sah.truncate(HEADER_OFFSET_DATA);
642
+ }
643
+ return pathBytes
644
+ ? textDecoder.decode(this.#apBody.subarray(0,pathBytes))
645
+ : '';
646
+ }else{
647
+ // Invalid digest
648
+ warn('Disassociating file with bad digest.');
649
+ this.setAssociatedPath(sah, '', 0);
650
+ return '';
651
+ }
652
+ }
653
+
654
+ /**
655
+ Stores the given client-defined path and SQLITE_OPEN_xyz flags
656
+ into the given SAH. If path is an empty string then the file is
657
+ disassociated from the pool but its previous name is preserved
658
+ in the metadata.
659
+ */
660
+ setAssociatedPath(sah, path, flags){
661
+ const enc = textEncoder.encodeInto(path, this.#apBody);
662
+ if(HEADER_MAX_PATH_SIZE <= enc.written + 1/*NUL byte*/){
663
+ toss("Path too long:",path);
664
+ }
665
+ this.#apBody.fill(0, enc.written, HEADER_MAX_PATH_SIZE);
666
+ this.#dvBody.setUint32(HEADER_OFFSET_FLAGS, flags);
667
+
668
+ const digest = this.computeDigest(this.#apBody);
669
+ sah.write(this.#apBody, {at: 0});
670
+ sah.write(digest, {at: HEADER_OFFSET_DIGEST});
671
+ sah.flush();
672
+
673
+ if(path){
674
+ this.#mapFilenameToSAH.set(path, sah);
675
+ this.#availableSAH.delete(sah);
676
+ }else{
677
+ // This is not a persistent file, so eliminate the contents.
678
+ sah.truncate(HEADER_OFFSET_DATA);
679
+ this.#availableSAH.add(sah);
680
+ }
681
+ }
682
+
683
+ /**
684
+ Computes a digest for the given byte array and returns it as a
685
+ two-element Uint32Array. This digest gets stored in the
686
+ metadata for each file as a validation check. Changing this
687
+ algorithm invalidates all existing databases for this VFS, so
688
+ don't do that.
689
+ */
690
+ computeDigest(byteArray){
691
+ let h1 = 0xdeadbeef;
692
+ let h2 = 0x41c6ce57;
693
+ for(const v of byteArray){
694
+ h1 = 31 * h1 + (v * 307);
695
+ h2 = 31 * h2 + (v * 307);
696
+ }
697
+ return new Uint32Array([h1>>>0, h2>>>0]);
698
+ }
699
+
700
+ /**
701
+ Re-initializes the state of the SAH pool, releasing and
702
+ re-acquiring all handles.
703
+
704
+ See acquireAccessHandles() for the specifics of the clearFiles
705
+ argument.
706
+ */
707
+ async reset(clearFiles){
708
+ await this.isReady;
709
+ let h = await navigator.storage.getDirectory();
710
+ let prev, prevName;
711
+ for(const d of this.vfsDir.split('/')){
712
+ if(d){
713
+ prev = h;
714
+ h = await h.getDirectoryHandle(d,{create:true});
715
+ }
716
+ }
717
+ this.#dhVfsRoot = h;
718
+ this.#dhVfsParent = prev;
719
+ this.#dhOpaque = await this.#dhVfsRoot.getDirectoryHandle(
720
+ OPAQUE_DIR_NAME,{create:true}
721
+ );
722
+ this.releaseAccessHandles();
723
+ return this.acquireAccessHandles(clearFiles);
724
+ }
725
+
726
+ /**
727
+ Returns the pathname part of the given argument,
728
+ which may be any of:
729
+
730
+ - a URL object
731
+ - A JS string representing a file name
732
+ - Wasm C-string representing a file name
733
+
734
+ All "../" parts and duplicate slashes are resolve/removed from
735
+ the returned result.
736
+ */
737
+ getPath(arg) {
738
+ if(wasm.isPtr(arg)) arg = wasm.cstrToJs(arg);
739
+ return ((arg instanceof URL)
740
+ ? arg
741
+ : new URL(arg, 'file://localhost/')).pathname;
742
+ }
743
+
744
+ /**
745
+ Removes the association of the given client-specified file
746
+ name (JS string) from the pool. Returns true if a mapping
747
+ is found, else false.
748
+ */
749
+ deletePath(path) {
750
+ const sah = this.#mapFilenameToSAH.get(path);
751
+ if(sah) {
752
+ // Un-associate the name from the SAH.
753
+ this.#mapFilenameToSAH.delete(path);
754
+ this.setAssociatedPath(sah, '', 0);
755
+ }
756
+ return !!sah;
757
+ }
758
+
759
+ /**
760
+ Sets e (an Error object) as this object's current error. Pass a
761
+ falsy (or no) value to clear it. If code is truthy it is
762
+ assumed to be an SQLITE_xxx result code, defaulting to
763
+ SQLITE_IOERR if code is falsy.
764
+
765
+ Returns the 2nd argument.
766
+ */
767
+ storeErr(e,code){
768
+ if(e){
769
+ e.sqlite3Rc = code || capi.SQLITE_IOERR;
770
+ this.error(e);
771
+ }
772
+ this.$error = e;
773
+ return code;
774
+ }
775
+ /**
776
+ Pops this object's Error object and returns
777
+ it (a falsy value if no error is set).
778
+ */
779
+ popErr(){
780
+ const rc = this.$error;
781
+ this.$error = undefined;
782
+ return rc;
783
+ }
784
+
785
+ /**
786
+ Returns the next available SAH without removing
787
+ it from the set.
788
+ */
789
+ nextAvailableSAH(){
790
+ const [rc] = this.#availableSAH.keys();
791
+ return rc;
792
+ }
793
+
794
+ /**
795
+ Given an (sqlite3_file*), returns the mapped
796
+ xOpen file object.
797
+ */
798
+ getOFileForS3File(pFile){
799
+ return this.#mapS3FileToOFile_.get(pFile);
800
+ }
801
+ /**
802
+ Maps or unmaps (if file is falsy) the given (sqlite3_file*)
803
+ to an xOpen file object and to this pool object.
804
+ */
805
+ mapS3FileToOFile(pFile,file){
806
+ if(file){
807
+ this.#mapS3FileToOFile_.set(pFile, file);
808
+ setPoolForPFile(pFile, this);
809
+ }else{
810
+ this.#mapS3FileToOFile_.delete(pFile);
811
+ setPoolForPFile(pFile, false);
812
+ }
813
+ }
814
+
815
+ /**
816
+ Returns true if the given client-defined file name is in this
817
+ object's name-to-SAH map.
818
+ */
819
+ hasFilename(name){
820
+ return this.#mapFilenameToSAH.has(name)
821
+ }
822
+
823
+ /**
824
+ Returns the SAH associated with the given
825
+ client-defined file name.
826
+ */
827
+ getSAHForPath(path){
828
+ return this.#mapFilenameToSAH.get(path);
829
+ }
830
+
831
+ /**
832
+ Removes this object's sqlite3_vfs registration and shuts down
833
+ this object, releasing all handles, mappings, and whatnot,
834
+ including deleting its data directory. There is currently no
835
+ way to "revive" the object and reaquire its resources.
836
+
837
+ This function is intended primarily for testing.
838
+
839
+ Resolves to true if it did its job, false if the
840
+ VFS has already been shut down.
841
+ */
842
+ async removeVfs(){
843
+ if(!this.#cVfs.pointer || !this.#dhOpaque) return false;
844
+ capi.sqlite3_vfs_unregister(this.#cVfs.pointer);
845
+ this.#cVfs.dispose();
846
+ delete initPromises[this.vfsName];
847
+ try{
848
+ this.releaseAccessHandles();
849
+ await this.#dhVfsRoot.removeEntry(OPAQUE_DIR_NAME, {recursive: true});
850
+ this.#dhOpaque = undefined;
851
+ await this.#dhVfsParent.removeEntry(
852
+ this.#dhVfsRoot.name, {recursive: true}
853
+ );
854
+ this.#dhVfsRoot = this.#dhVfsParent = undefined;
855
+ }catch(e){
856
+ sqlite3.config.error(this.vfsName,"removeVfs() failed:",e);
857
+ /*otherwise ignored - there is no recovery strategy*/
858
+ }
859
+ return true;
860
+ }
861
+
862
+
863
+ //! Documented elsewhere in this file.
864
+ exportFile(name){
865
+ const sah = this.#mapFilenameToSAH.get(name) || toss("File not found:",name);
866
+ const n = sah.getSize() - HEADER_OFFSET_DATA;
867
+ const b = new Uint8Array(n>0 ? n : 0);
868
+ if(n>0){
869
+ const nRead = sah.read(b, {at: HEADER_OFFSET_DATA});
870
+ if(nRead != n){
871
+ toss("Expected to read "+n+" bytes but read "+nRead+".");
872
+ }
873
+ }
874
+ return b;
875
+ }
876
+
877
+ //! Impl for importDb() when its 2nd arg is a function.
878
+ async importDbChunked(name, callback){
879
+ const sah = this.#mapFilenameToSAH.get(name)
880
+ || this.nextAvailableSAH()
881
+ || toss("No available handles to import to.");
882
+ sah.truncate(0);
883
+ let nWrote = 0, chunk, checkedHeader = false, err = false;
884
+ try{
885
+ while( undefined !== (chunk = await callback()) ){
886
+ if(chunk instanceof ArrayBuffer) chunk = new Uint8Array(chunk);
887
+ if( 0===nWrote && chunk.byteLength>=15 ){
888
+ util.affirmDbHeader(chunk);
889
+ checkedHeader = true;
890
+ }
891
+ sah.write(chunk, {at: HEADER_OFFSET_DATA + nWrote});
892
+ nWrote += chunk.byteLength;
893
+ }
894
+ if( nWrote < 512 || 0!==nWrote % 512 ){
895
+ toss("Input size",nWrote,"is not correct for an SQLite database.");
896
+ }
897
+ if( !checkedHeader ){
898
+ const header = new Uint8Array(20);
899
+ sah.read( header, {at: 0} );
900
+ util.affirmDbHeader( header );
901
+ }
902
+ sah.write(new Uint8Array([1,1]), {
903
+ at: HEADER_OFFSET_DATA + 18
904
+ }/*force db out of WAL mode*/);
905
+ }catch(e){
906
+ this.setAssociatedPath(sah, '', 0);
907
+ throw e;
908
+ }
909
+ this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
910
+ return nWrote;
911
+ }
912
+
913
+ //! Documented elsewhere in this file.
914
+ importDb(name, bytes){
915
+ if( bytes instanceof ArrayBuffer ) bytes = new Uint8Array(bytes);
916
+ else if( bytes instanceof Function ) return this.importDbChunked(name, bytes);
917
+ const sah = this.#mapFilenameToSAH.get(name)
918
+ || this.nextAvailableSAH()
919
+ || toss("No available handles to import to.");
920
+ const n = bytes.byteLength;
921
+ if(n<512 || n%512!=0){
922
+ toss("Byte array size is invalid for an SQLite db.");
923
+ }
924
+ const header = "SQLite format 3";
925
+ for(let i = 0; i < header.length; ++i){
926
+ if( header.charCodeAt(i) !== bytes[i] ){
927
+ toss("Input does not contain an SQLite database header.");
928
+ }
929
+ }
930
+ const nWrote = sah.write(bytes, {at: HEADER_OFFSET_DATA});
931
+ if(nWrote != n){
932
+ this.setAssociatedPath(sah, '', 0);
933
+ toss("Expected to write "+n+" bytes but wrote "+nWrote+".");
934
+ }else{
935
+ sah.write(new Uint8Array([1,1]), {at: HEADER_OFFSET_DATA+18}
936
+ /* force db out of WAL mode */);
937
+ this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
938
+ }
939
+ return nWrote;
940
+ }
941
+
942
+ }/*class OpfsSAHPool*/;
943
+
944
+
945
+ /**
946
+ A OpfsSAHPoolUtil instance is exposed to clients in order to
947
+ manipulate an OpfsSAHPool object without directly exposing that
948
+ object and allowing for some semantic changes compared to that
949
+ class.
950
+
951
+ Class docs are in the client-level docs for
952
+ installOpfsSAHPoolVfs().
953
+ */
954
+ class OpfsSAHPoolUtil {
955
+ /* This object's associated OpfsSAHPool. */
956
+ #p;
957
+
958
+ constructor(sahPool){
959
+ this.#p = sahPool;
960
+ this.vfsName = sahPool.vfsName;
961
+ }
962
+
963
+ async addCapacity(n){ return this.#p.addCapacity(n) }
964
+
965
+ async reduceCapacity(n){ return this.#p.reduceCapacity(n) }
966
+
967
+ getCapacity(){ return this.#p.getCapacity(this.#p) }
968
+
969
+ getFileCount(){ return this.#p.getFileCount() }
970
+ getFileNames(){ return this.#p.getFileNames() }
971
+
972
+ async reserveMinimumCapacity(min){
973
+ const c = this.#p.getCapacity();
974
+ return (c < min) ? this.#p.addCapacity(min - c) : c;
975
+ }
976
+
977
+ exportFile(name){ return this.#p.exportFile(name) }
978
+
979
+ importDb(name, bytes){ return this.#p.importDb(name,bytes) }
980
+
981
+ async wipeFiles(){ return this.#p.reset(true) }
982
+
983
+ unlink(filename){ return this.#p.deletePath(filename) }
984
+
985
+ async removeVfs(){ return this.#p.removeVfs() }
986
+
987
+ }/* class OpfsSAHPoolUtil */;
988
+
989
+ /**
990
+ Returns a resolved Promise if the current environment
991
+ has a "fully-sync" SAH impl, else a rejected Promise.
992
+ */
993
+ const apiVersionCheck = async ()=>{
994
+ const dh = await navigator.storage.getDirectory();
995
+ const fn = '.opfs-sahpool-sync-check-'+getRandomName();
996
+ const fh = await dh.getFileHandle(fn, { create: true });
997
+ const ah = await fh.createSyncAccessHandle();
998
+ const close = ah.close();
999
+ await close;
1000
+ await dh.removeEntry(fn);
1001
+ if(close?.then){
1002
+ toss("The local OPFS API is too old for opfs-sahpool:",
1003
+ "it has an async FileSystemSyncAccessHandle.close() method.");
1004
+ }
1005
+ return true;
1006
+ };
1007
+
1008
+ /**
1009
+ installOpfsSAHPoolVfs() asynchronously initializes the OPFS
1010
+ SyncAccessHandle (a.k.a. SAH) Pool VFS. It returns a Promise which
1011
+ either resolves to a utility object described below or rejects with
1012
+ an Error value.
1013
+
1014
+ Initialization of this VFS is not automatic because its
1015
+ registration requires that it lock all resources it
1016
+ will potentially use, even if client code does not want
1017
+ to use them. That, in turn, can lead to locking errors
1018
+ when, for example, one page in a given origin has loaded
1019
+ this VFS but does not use it, then another page in that
1020
+ origin tries to use the VFS. If the VFS were automatically
1021
+ registered, the second page would fail to load the VFS
1022
+ due to OPFS locking errors.
1023
+
1024
+ If this function is called more than once with a given "name"
1025
+ option (see below), it will return the same Promise. Calls for
1026
+ different names will return different Promises which resolve to
1027
+ independent objects and refer to different VFS registrations.
1028
+
1029
+ On success, the resulting Promise resolves to a utility object
1030
+ which can be used to query and manipulate the pool. Its API is
1031
+ described at the end of these docs.
1032
+
1033
+ This function accepts an options object to configure certain
1034
+ parts but it is only acknowledged for the very first call and
1035
+ ignored for all subsequent calls.
1036
+
1037
+ The options, in alphabetical order:
1038
+
1039
+ - `clearOnInit`: (default=false) if truthy, contents and filename
1040
+ mapping are removed from each SAH it is acquired during
1041
+ initalization of the VFS, leaving the VFS's storage in a pristine
1042
+ state. Use this only for databases which need not survive a page
1043
+ reload.
1044
+
1045
+ - `initialCapacity`: (default=6) Specifies the default capacity of
1046
+ the VFS. This should not be set unduly high because the VFS has
1047
+ to open (and keep open) a file for each entry in the pool. This
1048
+ setting only has an effect when the pool is initially empty. It
1049
+ does not have any effect if a pool already exists.
1050
+
1051
+ - `directory`: (default="."+`name`) Specifies the OPFS directory
1052
+ name in which to store metadata for the `"opfs-sahpool"`
1053
+ sqlite3_vfs. Only one instance of this VFS can be installed per
1054
+ JavaScript engine, and any two engines with the same storage
1055
+ directory name will collide with each other, leading to locking
1056
+ errors and the inability to register the VFS in the second and
1057
+ subsequent engine. Using a different directory name for each
1058
+ application enables different engines in the same HTTP origin to
1059
+ co-exist, but their data are invisible to each other. Changing
1060
+ this name will effectively orphan any databases stored under
1061
+ previous names. The default is unspecified but descriptive. This
1062
+ option may contain multiple path elements, e.g. "foo/bar/baz",
1063
+ and they are created automatically. In practice there should be
1064
+ no driving need to change this. ACHTUNG: all files in this
1065
+ directory are assumed to be managed by the VFS. Do not place
1066
+ other files in that directory, as they may be deleted or
1067
+ otherwise modified by the VFS.
1068
+
1069
+ - `name`: (default="opfs-sahpool") sets the name to register this
1070
+ VFS under. Normally this should not be changed, but it is
1071
+ possible to register this VFS under multiple names so long as
1072
+ each has its own separate directory to work from. The storage for
1073
+ each is invisible to all others. The name must be a string
1074
+ compatible with `sqlite3_vfs_register()` and friends and suitable
1075
+ for use in URI-style database file names.
1076
+
1077
+ Achtung: if a custom `name` is provided, a custom `directory`
1078
+ must also be provided if any other instance is registered with
1079
+ the default directory. If no directory is explicitly provided
1080
+ then a directory name is synthesized from the `name` option.
1081
+
1082
+
1083
+ - `forceReinitIfPreviouslyFailed`: (default=`false`) Is a fallback option
1084
+ to assist in working around certain flaky environments which may
1085
+ mysteriously fail to permit access to OPFS sync access handles on
1086
+ an initial attempt but permit it on a second attemp. This option
1087
+ should never be used but is provided for those who choose to
1088
+ throw caution to the wind and trust such environments. If this
1089
+ option is truthy _and_ the previous attempt to initialize this
1090
+ VFS with the same `name` failed, the VFS will attempt to
1091
+ initialize a second time instead of returning the cached
1092
+ failure. See discussion at:
1093
+ <https://github.com/sqlite/sqlite-wasm/issues/79>
1094
+
1095
+
1096
+ Peculiarities of this VFS vis a vis other SQLite VFSes:
1097
+
1098
+ - Paths given to it _must_ be absolute. Relative paths will not
1099
+ be properly recognized. This is arguably a bug but correcting it
1100
+ requires some hoop-jumping in routines which have no business
1101
+ doing such tricks.
1102
+
1103
+ - It is possible to install multiple instances under different
1104
+ names, each sandboxed from one another inside their own private
1105
+ directory. This feature exists primarily as a way for disparate
1106
+ applications within a given HTTP origin to use this VFS without
1107
+ introducing locking issues between them.
1108
+
1109
+
1110
+ The API for the utility object passed on by this function's
1111
+ Promise, in alphabetical order...
1112
+
1113
+ - [async] number addCapacity(n)
1114
+
1115
+ Adds `n` entries to the current pool. This change is persistent
1116
+ across sessions so should not be called automatically at each app
1117
+ startup (but see `reserveMinimumCapacity()`). Its returned Promise
1118
+ resolves to the new capacity. Because this operation is necessarily
1119
+ asynchronous, the C-level VFS API cannot call this on its own as
1120
+ needed.
1121
+
1122
+ - byteArray exportFile(name)
1123
+
1124
+ Synchronously reads the contents of the given file into a Uint8Array
1125
+ and returns it. This will throw if the given name is not currently
1126
+ in active use or on I/O error. Note that the given name is _not_
1127
+ visible directly in OPFS (or, if it is, it's not from this VFS).
1128
+
1129
+ - number getCapacity()
1130
+
1131
+ Returns the number of files currently contained
1132
+ in the SAH pool. The default capacity is only large enough for one
1133
+ or two databases and their associated temp files.
1134
+
1135
+ - number getFileCount()
1136
+
1137
+ Returns the number of files from the pool currently allocated to
1138
+ slots. This is not the same as the files being "opened".
1139
+
1140
+ - array getFileNames()
1141
+
1142
+ Returns an array of the names of the files currently allocated to
1143
+ slots. This list is the same length as getFileCount().
1144
+
1145
+ - void importDb(name, bytes)
1146
+
1147
+ Imports the contents of an SQLite database, provided as a byte
1148
+ array or ArrayBuffer, under the given name, overwriting any
1149
+ existing content. Throws if the pool has no available file slots,
1150
+ on I/O error, or if the input does not appear to be a
1151
+ database. In the latter case, only a cursory examination is made.
1152
+ Results are undefined if the given db name refers to an opened
1153
+ db. Note that this routine is _only_ for importing database
1154
+ files, not arbitrary files, the reason being that this VFS will
1155
+ automatically clean up any non-database files so importing them
1156
+ is pointless.
1157
+
1158
+ If passed a function for its second argument, its behavior
1159
+ changes to asynchronous and it imports its data in chunks fed to
1160
+ it by the given callback function. It calls the callback (which
1161
+ may be async) repeatedly, expecting either a Uint8Array or
1162
+ ArrayBuffer (to denote new input) or undefined (to denote
1163
+ EOF). For so long as the callback continues to return
1164
+ non-undefined, it will append incoming data to the given
1165
+ VFS-hosted database file. The result of the resolved Promise when
1166
+ called this way is the size of the resulting database.
1167
+
1168
+ On succes this routine rewrites the database header bytes in the
1169
+ output file (not the input array) to force disabling of WAL mode.
1170
+
1171
+ On a write error, the handle is removed from the pool and made
1172
+ available for re-use.
1173
+
1174
+ - [async] number reduceCapacity(n)
1175
+
1176
+ Removes up to `n` entries from the pool, with the caveat that it can
1177
+ only remove currently-unused entries. It returns a Promise which
1178
+ resolves to the number of entries actually removed.
1179
+
1180
+ - [async] boolean removeVfs()
1181
+
1182
+ Unregisters the opfs-sahpool VFS and removes its directory from OPFS
1183
+ (which means that _all client content_ is removed). After calling
1184
+ this, the VFS may no longer be used and there is no way to re-add it
1185
+ aside from reloading the current JavaScript context.
1186
+
1187
+ Results are undefined if a database is currently in use with this
1188
+ VFS.
1189
+
1190
+ The returned Promise resolves to true if it performed the removal
1191
+ and false if the VFS was not installed.
1192
+
1193
+ If the VFS has a multi-level directory, e.g. "/foo/bar/baz", _only_
1194
+ the bottom-most directory is removed because this VFS cannot know for
1195
+ certain whether the higher-level directories contain data which
1196
+ should be removed.
1197
+
1198
+ - [async] number reserveMinimumCapacity(min)
1199
+
1200
+ If the current capacity is less than `min`, the capacity is
1201
+ increased to `min`, else this returns with no side effects. The
1202
+ resulting Promise resolves to the new capacity.
1203
+
1204
+ - boolean unlink(filename)
1205
+
1206
+ If a virtual file exists with the given name, disassociates it from
1207
+ the pool and returns true, else returns false without side
1208
+ effects. Results are undefined if the file is currently in active
1209
+ use.
1210
+
1211
+ - string vfsName
1212
+
1213
+ The SQLite VFS name under which this pool's VFS is registered.
1214
+
1215
+ - [async] void wipeFiles()
1216
+
1217
+ Clears all client-defined state of all SAHs and makes all of them
1218
+ available for re-use by the pool. Results are undefined if any such
1219
+ handles are currently in use, e.g. by an sqlite3 db.
1220
+ */
1221
+ sqlite3.installOpfsSAHPoolVfs = async function(options=Object.create(null)){
1222
+ options = Object.assign(Object.create(null), optionDefaults, (options||{}));
1223
+ const vfsName = options.name;
1224
+ if(options.$testThrowPhase1){
1225
+ throw options.$testThrowPhase1;
1226
+ }
1227
+ if(initPromises[vfsName]){
1228
+ try {
1229
+ const p = await initPromises[vfsName];
1230
+ //log("installOpfsSAHPoolVfs() returning cached result",options,vfsName,p);
1231
+ return p;
1232
+ }catch(e){
1233
+ //log("installOpfsSAHPoolVfs() got cached failure",options,vfsName,e);
1234
+ if( options.forceReinitIfPreviouslyFailed ){
1235
+ delete initPromises[vfsName];
1236
+ /* Fall through and try again. */
1237
+ }else{
1238
+ throw e;
1239
+ }
1240
+ }
1241
+ }
1242
+ if(!globalThis.FileSystemHandle ||
1243
+ !globalThis.FileSystemDirectoryHandle ||
1244
+ !globalThis.FileSystemFileHandle ||
1245
+ !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle ||
1246
+ !navigator?.storage?.getDirectory){
1247
+ return (initPromises[vfsName] = Promise.reject(new Error("Missing required OPFS APIs.")));
1248
+ }
1249
+
1250
+ /**
1251
+ Maintenance reminder: the order of ASYNC ops in this function
1252
+ is significant. We need to have them all chained at the very
1253
+ end in order to be able to catch a race condition where
1254
+ installOpfsSAHPoolVfs() is called twice in rapid succession,
1255
+ e.g.:
1256
+
1257
+ installOpfsSAHPoolVfs().then(console.warn.bind(console));
1258
+ installOpfsSAHPoolVfs().then(console.warn.bind(console));
1259
+
1260
+ If the timing of the async calls is not "just right" then that
1261
+ second call can end up triggering the init a second time and chaos
1262
+ ensues.
1263
+ */
1264
+ return initPromises[vfsName] = apiVersionCheck().then(async function(){
1265
+ if(options.$testThrowPhase2){
1266
+ throw options.$testThrowPhase2;
1267
+ }
1268
+ const thePool = new OpfsSAHPool(options);
1269
+ return thePool.isReady.then(async()=>{
1270
+ /** The poolUtil object will be the result of the
1271
+ resolved Promise. */
1272
+ const poolUtil = new OpfsSAHPoolUtil(thePool);
1273
+ if(sqlite3.oo1){
1274
+ const oo1 = sqlite3.oo1;
1275
+ const theVfs = thePool.getVfs();
1276
+ const OpfsSAHPoolDb = function(...args){
1277
+ const opt = oo1.DB.dbCtorHelper.normalizeArgs(...args);
1278
+ opt.vfs = theVfs.$zName;
1279
+ oo1.DB.dbCtorHelper.call(this, opt);
1280
+ };
1281
+ OpfsSAHPoolDb.prototype = Object.create(oo1.DB.prototype);
1282
+ poolUtil.OpfsSAHPoolDb = OpfsSAHPoolDb;
1283
+ }/*extend sqlite3.oo1*/
1284
+ thePool.log("VFS initialized.");
1285
+ return poolUtil;
1286
+ }).catch(async (e)=>{
1287
+ await thePool.removeVfs().catch(()=>{});
1288
+ throw e;
1289
+ });
1290
+ }).catch((err)=>{
1291
+ //error("rejecting promise:",err);
1292
+ return initPromises[vfsName] = Promise.reject(err);
1293
+ });
1294
+ }/*installOpfsSAHPoolVfs()*/;
1295
+ }/*sqlite3ApiBootstrap.initializers*/);
1296
+ //#else
1297
+ /*
1298
+ The OPFS SAH Pool VFS parts are elided from builds targeting
1299
+ node.js.
1300
+ */
1301
+ //#endif target=node
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-vtab-helper.c-pp.js ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ ** 2022-11-30
3
+ **
4
+ ** The author disclaims copyright to this source code. In place of a
5
+ ** legal notice, here is a blessing:
6
+ **
7
+ ** * May you do good and not evil.
8
+ ** * May you find forgiveness for yourself and forgive others.
9
+ ** * May you share freely, never taking more than you give.
10
+ */
11
+
12
+ /**
13
+ This file installs sqlite3.vtab, a namespace of helpers for use in
14
+ the creation of JavaScript implementations virtual tables. If built
15
+ without virtual table support then this function does nothing.
16
+ */
17
+ 'use strict';
18
+ globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
19
+ if( !sqlite3.wasm.exports.sqlite3_declare_vtab ){
20
+ return;
21
+ }
22
+ const wasm = sqlite3.wasm, capi = sqlite3.capi, toss = sqlite3.util.toss3;
23
+ const vtab = Object.create(null);
24
+ sqlite3.vtab = vtab;
25
+
26
+ const sii = capi.sqlite3_index_info;
27
+ /**
28
+ If n is >=0 and less than this.$nConstraint, this function
29
+ returns either a WASM pointer to the 0-based nth entry of
30
+ this.$aConstraint (if passed a truthy 2nd argument) or an
31
+ sqlite3_index_info.sqlite3_index_constraint object wrapping that
32
+ address (if passed a falsy value or no 2nd argument). Returns a
33
+ falsy value if n is out of range.
34
+ */
35
+ sii.prototype.nthConstraint = function(n, asPtr=false){
36
+ if(n<0 || n>=this.$nConstraint) return false;
37
+ const ptr = this.$aConstraint + (
38
+ sii.sqlite3_index_constraint.structInfo.sizeof * n
39
+ );
40
+ return asPtr ? ptr : new sii.sqlite3_index_constraint(ptr);
41
+ };
42
+
43
+ /**
44
+ Works identically to nthConstraint() but returns state from
45
+ this.$aConstraintUsage, so returns an
46
+ sqlite3_index_info.sqlite3_index_constraint_usage instance
47
+ if passed no 2nd argument or a falsy 2nd argument.
48
+ */
49
+ sii.prototype.nthConstraintUsage = function(n, asPtr=false){
50
+ if(n<0 || n>=this.$nConstraint) return false;
51
+ const ptr = this.$aConstraintUsage + (
52
+ sii.sqlite3_index_constraint_usage.structInfo.sizeof * n
53
+ );
54
+ return asPtr ? ptr : new sii.sqlite3_index_constraint_usage(ptr);
55
+ };
56
+
57
+ /**
58
+ If n is >=0 and less than this.$nOrderBy, this function
59
+ returns either a WASM pointer to the 0-based nth entry of
60
+ this.$aOrderBy (if passed a truthy 2nd argument) or an
61
+ sqlite3_index_info.sqlite3_index_orderby object wrapping that
62
+ address (if passed a falsy value or no 2nd argument). Returns a
63
+ falsy value if n is out of range.
64
+ */
65
+ sii.prototype.nthOrderBy = function(n, asPtr=false){
66
+ if(n<0 || n>=this.$nOrderBy) return false;
67
+ const ptr = this.$aOrderBy + (
68
+ sii.sqlite3_index_orderby.structInfo.sizeof * n
69
+ );
70
+ return asPtr ? ptr : new sii.sqlite3_index_orderby(ptr);
71
+ };
72
+
73
+ /**
74
+ Internal factory function for xVtab and xCursor impls.
75
+ */
76
+ const __xWrapFactory = function(methodName,StructType){
77
+ return function(ptr,removeMapping=false){
78
+ if(0===arguments.length) ptr = new StructType;
79
+ if(ptr instanceof StructType){
80
+ //T.assert(!this.has(ptr.pointer));
81
+ this.set(ptr.pointer, ptr);
82
+ return ptr;
83
+ }else if(!wasm.isPtr(ptr)){
84
+ sqlite3.SQLite3Error.toss("Invalid argument to",methodName+"()");
85
+ }
86
+ let rc = this.get(ptr);
87
+ if(removeMapping) this.delete(ptr);
88
+ return rc;
89
+ }.bind(new Map);
90
+ };
91
+
92
+ /**
93
+ A factory function which implements a simple lifetime manager for
94
+ mappings between C struct pointers and their JS-level wrappers.
95
+ The first argument must be the logical name of the manager
96
+ (e.g. 'xVtab' or 'xCursor'), which is only used for error
97
+ reporting. The second must be the capi.XYZ struct-type value,
98
+ e.g. capi.sqlite3_vtab or capi.sqlite3_vtab_cursor.
99
+
100
+ Returns an object with 4 methods: create(), get(), unget(), and
101
+ dispose(), plus a StructType member with the value of the 2nd
102
+ argument. The methods are documented in the body of this
103
+ function.
104
+ */
105
+ const StructPtrMapper = function(name, StructType){
106
+ const __xWrap = __xWrapFactory(name,StructType);
107
+ /**
108
+ This object houses a small API for managing mappings of (`T*`)
109
+ to StructType<T> objects, specifically within the lifetime
110
+ requirements of sqlite3_module methods.
111
+ */
112
+ return Object.assign(Object.create(null),{
113
+ /** The StructType object for this object's API. */
114
+ StructType,
115
+ /**
116
+ Creates a new StructType object, writes its `pointer`
117
+ value to the given output pointer, and returns that
118
+ object. Its intended usage depends on StructType:
119
+
120
+ sqlite3_vtab: to be called from sqlite3_module::xConnect()
121
+ or xCreate() implementations.
122
+
123
+ sqlite3_vtab_cursor: to be called from xOpen().
124
+
125
+ This will throw if allocation of the StructType instance
126
+ fails or if ppOut is not a pointer-type value.
127
+ */
128
+ create: (ppOut)=>{
129
+ const rc = __xWrap();
130
+ wasm.pokePtr(ppOut, rc.pointer);
131
+ return rc;
132
+ },
133
+ /**
134
+ Returns the StructType object previously mapped to the
135
+ given pointer using create(). Its intended usage depends
136
+ on StructType:
137
+
138
+ sqlite3_vtab: to be called from sqlite3_module methods which
139
+ take a (sqlite3_vtab*) pointer _except_ for
140
+ xDestroy()/xDisconnect(), in which case unget() or dispose().
141
+
142
+ sqlite3_vtab_cursor: to be called from any sqlite3_module methods
143
+ which take a `sqlite3_vtab_cursor*` argument except xClose(),
144
+ in which case use unget() or dispose().
145
+
146
+ Rule to remember: _never_ call dispose() on an instance
147
+ returned by this function.
148
+ */
149
+ get: (pCObj)=>__xWrap(pCObj),
150
+ /**
151
+ Identical to get() but also disconnects the mapping between the
152
+ given pointer and the returned StructType object, such that
153
+ future calls to this function or get() with the same pointer
154
+ will return the undefined value. Its intended usage depends
155
+ on StructType:
156
+
157
+ sqlite3_vtab: to be called from sqlite3_module::xDisconnect() or
158
+ xDestroy() implementations or in error handling of a failed
159
+ xCreate() or xConnect().
160
+
161
+ sqlite3_vtab_cursor: to be called from xClose() or during
162
+ cleanup in a failed xOpen().
163
+
164
+ Calling this method obligates the caller to call dispose() on
165
+ the returned object when they're done with it.
166
+ */
167
+ unget: (pCObj)=>__xWrap(pCObj,true),
168
+ /**
169
+ Works like unget() plus it calls dispose() on the
170
+ StructType object.
171
+ */
172
+ dispose: (pCObj)=>{
173
+ const o = __xWrap(pCObj,true);
174
+ if(o) o.dispose();
175
+ }
176
+ });
177
+ };
178
+
179
+ /**
180
+ A lifetime-management object for mapping `sqlite3_vtab*`
181
+ instances in sqlite3_module methods to capi.sqlite3_vtab
182
+ objects.
183
+
184
+ The API docs are in the API-internal StructPtrMapper().
185
+ */
186
+ vtab.xVtab = StructPtrMapper('xVtab', capi.sqlite3_vtab);
187
+
188
+ /**
189
+ A lifetime-management object for mapping `sqlite3_vtab_cursor*`
190
+ instances in sqlite3_module methods to capi.sqlite3_vtab_cursor
191
+ objects.
192
+
193
+ The API docs are in the API-internal StructPtrMapper().
194
+ */
195
+ vtab.xCursor = StructPtrMapper('xCursor', capi.sqlite3_vtab_cursor);
196
+
197
+ /**
198
+ Convenience form of creating an sqlite3_index_info wrapper,
199
+ intended for use in xBestIndex implementations. Note that the
200
+ caller is expected to call dispose() on the returned object
201
+ before returning. Though not _strictly_ required, as that object
202
+ does not own the pIdxInfo memory, it is nonetheless good form.
203
+ */
204
+ vtab.xIndexInfo = (pIdxInfo)=>new capi.sqlite3_index_info(pIdxInfo);
205
+
206
+ /**
207
+ Given an sqlite3_module method name and error object, this
208
+ function returns sqlite3.capi.SQLITE_NOMEM if (e instanceof
209
+ sqlite3.WasmAllocError), else it returns its second argument. Its
210
+ intended usage is in the methods of a sqlite3_vfs or
211
+ sqlite3_module:
212
+
213
+ ```
214
+ try{
215
+ let rc = ...
216
+ return rc;
217
+ }catch(e){
218
+ return sqlite3.vtab.xError(
219
+ 'xColumn', e, sqlite3.capi.SQLITE_XYZ);
220
+ // where SQLITE_XYZ is some call-appropriate result code.
221
+ }
222
+ ```
223
+
224
+ If no 3rd argument is provided, its default depends on
225
+ the error type:
226
+
227
+ - An sqlite3.WasmAllocError always resolves to capi.SQLITE_NOMEM.
228
+
229
+ - If err is an SQLite3Error then its `resultCode` property
230
+ is used.
231
+
232
+ - If all else fails, capi.SQLITE_ERROR is used.
233
+
234
+ If xError.errorReporter is a function, it is called in
235
+ order to report the error, else the error is not reported.
236
+ If that function throws, that exception is ignored.
237
+ */
238
+ vtab.xError = function f(methodName, err, defaultRc){
239
+ if(f.errorReporter instanceof Function){
240
+ try{f.errorReporter("sqlite3_module::"+methodName+"(): "+err.message);}
241
+ catch(e){/*ignored*/}
242
+ }
243
+ let rc;
244
+ if(err instanceof sqlite3.WasmAllocError) rc = capi.SQLITE_NOMEM;
245
+ else if(arguments.length>2) rc = defaultRc;
246
+ else if(err instanceof sqlite3.SQLite3Error) rc = err.resultCode;
247
+ return rc || capi.SQLITE_ERROR;
248
+ };
249
+ vtab.xError.errorReporter = 1 ? console.error.bind(console) : false;
250
+
251
+ /**
252
+ A helper for sqlite3_vtab::xRowid() and xUpdate()
253
+ implementations. It must be passed the final argument to one of
254
+ those methods (an output pointer to an int64 row ID) and the
255
+ value to store at the output pointer's address. Returns the same
256
+ as wasm.poke() and will throw if the 1st or 2nd arguments
257
+ are invalid for that function.
258
+
259
+ Example xRowid impl:
260
+
261
+ ```
262
+ const xRowid = (pCursor, ppRowid64)=>{
263
+ const c = vtab.xCursor(pCursor);
264
+ vtab.xRowid(ppRowid64, c.myRowId);
265
+ return 0;
266
+ };
267
+ ```
268
+ */
269
+ vtab.xRowid = (ppRowid64, value)=>wasm.poke(ppRowid64, value, 'i64');
270
+
271
+ /**
272
+ A helper to initialize and set up an sqlite3_module object for
273
+ later installation into individual databases using
274
+ sqlite3_create_module(). Requires an object with the following
275
+ properties:
276
+
277
+ - `methods`: an object containing a mapping of properties with
278
+ the C-side names of the sqlite3_module methods, e.g. xCreate,
279
+ xBestIndex, etc., to JS implementations for those functions.
280
+ Certain special-case handling is performed, as described below.
281
+
282
+ - `catchExceptions` (default=false): if truthy, the given methods
283
+ are not mapped as-is, but are instead wrapped inside wrappers
284
+ which translate exceptions into result codes of SQLITE_ERROR or
285
+ SQLITE_NOMEM, depending on whether the exception is an
286
+ sqlite3.WasmAllocError. In the case of the xConnect and xCreate
287
+ methods, the exception handler also sets the output error
288
+ string to the exception's error string.
289
+
290
+ - OPTIONAL `struct`: a sqlite3.capi.sqlite3_module() instance. If
291
+ not set, one will be created automatically. If the current
292
+ "this" is-a sqlite3_module then it is unconditionally used in
293
+ place of `struct`.
294
+
295
+ - OPTIONAL `iVersion`: if set, it must be an integer value and it
296
+ gets assigned to the `$iVersion` member of the struct object.
297
+ If it's _not_ set, and the passed-in `struct` object's `$iVersion`
298
+ is 0 (the default) then this function attempts to define a value
299
+ for that property based on the list of methods it has.
300
+
301
+ If `catchExceptions` is false, it is up to the client to ensure
302
+ that no exceptions escape the methods, as doing so would move
303
+ them through the C API, leading to undefined
304
+ behavior. (vtab.xError() is intended to assist in reporting
305
+ such exceptions.)
306
+
307
+ Certain methods may refer to the same implementation. To simplify
308
+ the definition of such methods:
309
+
310
+ - If `methods.xConnect` is `true` then the value of
311
+ `methods.xCreate` is used in its place, and vice versa. sqlite
312
+ treats xConnect/xCreate functions specially if they are exactly
313
+ the same function (same pointer value).
314
+
315
+ - If `methods.xDisconnect` is true then the value of
316
+ `methods.xDestroy` is used in its place, and vice versa.
317
+
318
+ This is to facilitate creation of those methods inline in the
319
+ passed-in object without requiring the client to explicitly get a
320
+ reference to one of them in order to assign it to the other
321
+ one.
322
+
323
+ The `catchExceptions`-installed handlers will account for
324
+ identical references to the above functions and will install the
325
+ same wrapper function for both.
326
+
327
+ The given methods are expected to return integer values, as
328
+ expected by the C API. If `catchExceptions` is truthy, the return
329
+ value of the wrapped function will be used as-is and will be
330
+ translated to 0 if the function returns a falsy value (e.g. if it
331
+ does not have an explicit return). If `catchExceptions` is _not_
332
+ active, the method implementations must explicitly return integer
333
+ values.
334
+
335
+ Throws on error. On success, returns the sqlite3_module object
336
+ (`this` or `opt.struct` or a new sqlite3_module instance,
337
+ depending on how it's called).
338
+ */
339
+ vtab.setupModule = function(opt){
340
+ let createdMod = false;
341
+ const mod = (this instanceof capi.sqlite3_module)
342
+ ? this : (opt.struct || (createdMod = new capi.sqlite3_module()));
343
+ try{
344
+ const methods = opt.methods || toss("Missing 'methods' object.");
345
+ for(const e of Object.entries({
346
+ // -----^ ==> [k,v] triggers a broken code transformation in
347
+ // some versions of the emsdk toolchain.
348
+ xConnect: 'xCreate', xDisconnect: 'xDestroy'
349
+ })){
350
+ // Remap X=true to X=Y for certain X/Y combinations
351
+ const k = e[0], v = e[1];
352
+ if(true === methods[k]) methods[k] = methods[v];
353
+ else if(true === methods[v]) methods[v] = methods[k];
354
+ }
355
+ if(opt.catchExceptions){
356
+ const fwrap = function(methodName, func){
357
+ if(['xConnect','xCreate'].indexOf(methodName) >= 0){
358
+ return function(pDb, pAux, argc, argv, ppVtab, pzErr){
359
+ try{return func(...arguments) || 0}
360
+ catch(e){
361
+ if(!(e instanceof sqlite3.WasmAllocError)){
362
+ wasm.dealloc(wasm.peekPtr(pzErr));
363
+ wasm.pokePtr(pzErr, wasm.allocCString(e.message));
364
+ }
365
+ return vtab.xError(methodName, e);
366
+ }
367
+ };
368
+ }else{
369
+ return function(...args){
370
+ try{return func(...args) || 0}
371
+ catch(e){
372
+ return vtab.xError(methodName, e);
373
+ }
374
+ };
375
+ }
376
+ };
377
+ const mnames = [
378
+ 'xCreate', 'xConnect', 'xBestIndex', 'xDisconnect',
379
+ 'xDestroy', 'xOpen', 'xClose', 'xFilter', 'xNext',
380
+ 'xEof', 'xColumn', 'xRowid', 'xUpdate',
381
+ 'xBegin', 'xSync', 'xCommit', 'xRollback',
382
+ 'xFindFunction', 'xRename', 'xSavepoint', 'xRelease',
383
+ 'xRollbackTo', 'xShadowName'
384
+ ];
385
+ const remethods = Object.create(null);
386
+ for(const k of mnames){
387
+ const m = methods[k];
388
+ if(!(m instanceof Function)) continue;
389
+ else if('xConnect'===k && methods.xCreate===m){
390
+ remethods[k] = methods.xCreate;
391
+ }else if('xCreate'===k && methods.xConnect===m){
392
+ remethods[k] = methods.xConnect;
393
+ }else{
394
+ remethods[k] = fwrap(k, m);
395
+ }
396
+ }
397
+ mod.installMethods(remethods, false);
398
+ }else{
399
+ // No automatic exception handling. Trust the client
400
+ // to not throw.
401
+ mod.installMethods(
402
+ methods, !!opt.applyArgcCheck/*undocumented option*/
403
+ );
404
+ }
405
+ if(0===mod.$iVersion){
406
+ let v;
407
+ if('number'===typeof opt.iVersion) v = opt.iVersion;
408
+ else if(mod.$xShadowName) v = 3;
409
+ else if(mod.$xSavePoint || mod.$xRelease || mod.$xRollbackTo) v = 2;
410
+ else v = 1;
411
+ mod.$iVersion = v;
412
+ }
413
+ }catch(e){
414
+ if(createdMod) createdMod.dispose();
415
+ throw e;
416
+ }
417
+ return mod;
418
+ }/*setupModule()*/;
419
+
420
+ /**
421
+ Equivalent to calling vtab.setupModule() with this sqlite3_module
422
+ object as the call's `this`.
423
+ */
424
+ capi.sqlite3_module.prototype.setupModule = function(opt){
425
+ return vtab.setupModule.call(this, opt);
426
+ };
427
+ }/*sqlite3ApiBootstrap.initializers.push()*/);
local-test-sqlite3-delta-02/afc-sqlite3/ext/wasm/api/sqlite3-worker1.c-pp.js ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //#ifnot omit-oo1
2
+ /*
3
+ 2022-05-23
4
+
5
+ The author disclaims copyright to this source code. In place of a
6
+ legal notice, here is a blessing:
7
+
8
+ * May you do good and not evil.
9
+ * May you find forgiveness for yourself and forgive others.
10
+ * May you share freely, never taking more than you give.
11
+
12
+ ***********************************************************************
13
+
14
+ This is a JS Worker file for the main sqlite3 api. It loads
15
+ sqlite3.js, initializes the module, and postMessage()'s a message
16
+ after the module is initialized:
17
+
18
+ {type: 'sqlite3-api', result: 'worker1-ready'}
19
+
20
+ This seemingly superfluous level of indirection is necessary when
21
+ loading sqlite3.js via a Worker. Instantiating a worker with new
22
+ Worker("sqlite.js") will not (cannot) call sqlite3InitModule() to
23
+ initialize the module due to a timing/order-of-operations conflict
24
+ (and that symbol is not exported in a way that a Worker loading it
25
+ that way can see it). Thus JS code wanting to load the sqlite3
26
+ Worker-specific API needs to pass _this_ file (or equivalent) to the
27
+ Worker constructor and then listen for an event in the form shown
28
+ above in order to know when the module has completed initialization.
29
+
30
+ This file accepts a URL arguments to adjust how it loads sqlite3.js:
31
+
32
+ - `sqlite3.dir`, if set, treats the given directory name as the
33
+ directory from which `sqlite3.js` will be loaded.
34
+ */
35
+ //#if target=es6-bundler-friendly
36
+ import {default as sqlite3InitModule} from './sqlite3-bundler-friendly.mjs';
37
+ //#else
38
+ "use strict";
39
+ {
40
+ const urlParams = globalThis.location
41
+ ? new URL(globalThis.location.href).searchParams
42
+ : new URLSearchParams();
43
+ let theJs = 'sqlite3.js';
44
+ if(urlParams.has('sqlite3.dir')){
45
+ theJs = urlParams.get('sqlite3.dir') + '/' + theJs;
46
+ }
47
+ //console.warn("worker1 theJs =",theJs);
48
+ importScripts(theJs);
49
+ }
50
+ //#endif
51
+ sqlite3InitModule().then(sqlite3 => sqlite3.initWorker1API());
52
+ //#else
53
+ /* Built with the omit-oo1 flag. */
54
+ //#endif ifnot omit-oo1