sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / wasm / api / sqlite3-api-prologue.c-pp.js
| 1 | /* |
| 2 | 2022-05-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 is intended to be combined at build-time with other |
| 14 | related code, most notably a header and footer which wraps this |
| 15 | whole file into a single callback which can be run after Emscripten |
| 16 | loads the corresponding WASM module. The sqlite3 JS API has no hard |
| 17 | requirements on Emscripten and does not expose any Emscripten APIs |
| 18 | to clients. It is structured such that its build can be tweaked to |
| 19 | include it in arbitrary WASM environments which can supply the |
| 20 | necessary underlying features (e.g. a POSIX file I/O layer). |
| 21 | |
| 22 | Main project home page: https://sqlite.org |
| 23 | |
| 24 | Documentation home page: https://sqlite.org/wasm |
| 25 | */ |
| 26 | //#// -Dcanonical-sqlite3 configures WhWasmUtil and Jaccwabyt for us. |
| 27 | //#define canonical-sqlite3 |
| 28 | /** |
| 29 | sqlite3ApiBootstrap() is intended to be called one time at the end |
| 30 | of the API amalgamation process, after the WASM file is loaded, and |
| 31 | passed configuration details for the current WASM environment. It |
| 32 | sets up and returns the sqlite3 namespace object. |
| 33 | |
| 34 | This function is not intended for client-level use. It is intended |
| 35 | for use in creating bundles configured for specific WASM |
| 36 | environments. That said, the "sqlite3-api.js" intermediary build |
| 37 | file aims to be suitable for dropping in to custom builds, and it |
| 38 | exposes only this function. |
| 39 | |
| 40 | This function expects a configuration object, intended to abstract |
| 41 | away details specific to any given WASM environment, primarily so |
| 42 | that it can be used without any direct dependency on |
| 43 | Emscripten. (Note the default values for the config object!) The |
| 44 | config object is only honored the first time this is called. |
| 45 | Subsequent calls ignore the argument and return the same |
| 46 | (configured) object which gets initialized by the first call. This |
| 47 | function will throw if any of the required config options are |
| 48 | missing. |
| 49 | |
| 50 | The config object properties include: |
| 51 | |
| 52 | - `exports`[^1]: the "exports" object for the current WASM |
| 53 | environment. In an Emscripten-based build, this should be set to |
| 54 | `Module['asm']` (versions <=3.1.43) or `Module['wasmExports']` |
| 55 | (versions >=3.1.44). |
| 56 | |
| 57 | - `memory`[^1]: optional WebAssembly.Memory object, defaulting to |
| 58 | `exports.memory`. In Emscripten environments this should be set |
| 59 | to `Module.wasmMemory` if the build uses `-sIMPORTED_MEMORY`, or be |
| 60 | left undefined/falsy to default to `exports.memory` when using |
| 61 | WASM-exported memory. |
| 62 | |
| 63 | - `functionTable`[^1]: optional WebAssembly.Table object holding |
| 64 | the indirect function table. If not set then the table is assumed |
| 65 | to be in `exports.__indirect_function_table`. |
| 66 | |
| 67 | - `bigIntEnabled`: true if BigInt support is enabled. Defaults to |
| 68 | true if `globalThis.BigInt64Array` is available, else false. Some |
| 69 | APIs are unavailable or may throw exceptions if called without |
| 70 | BigInt support, as BigInt is required for marshalling C-side |
| 71 | int64 into and out of JS. (Sidebar: it is technically possible |
| 72 | to add int64 support via marshalling of int32 pairs, but doing so |
| 73 | is unduly invasive.) |
| 74 | |
| 75 | - `allocExportName`: the name of the function, in `exports`, of the |
| 76 | `malloc(3)`-compatible routine for the WASM environment. Defaults |
| 77 | to `"sqlite3_malloc"`. Beware that using any allocator other than |
| 78 | sqlite3_malloc() may require care in certain client-side code |
| 79 | regarding which allocator is uses. Notably, sqlite3_deserialize() |
| 80 | and sqlite3_serialize() can only safely use memory from different |
| 81 | allocators under very specific conditions. The canonical builds |
| 82 | of this API guaranty that `sqlite3_malloc()` is the JS-side |
| 83 | allocator implementation. |
| 84 | |
| 85 | - `deallocExportName`: the name of the function, in `exports`, of |
| 86 | the `free(3)`-compatible routine for the WASM |
| 87 | environment. Defaults to `"sqlite3_free"`. |
| 88 | |
| 89 | - `reallocExportName`: the name of the function, in `exports`, of |
| 90 | the `realloc(3)`-compatible routine for the WASM |
| 91 | environment. Defaults to `"sqlite3_realloc"`. |
| 92 | |
| 93 | - `debug`, `log`, `warn`, and `error` may be functions equivalent |
| 94 | to the like-named methods of the global `console` object. By |
| 95 | default, these map directly to their `console` counterparts, but |
| 96 | can be replaced with (e.g.) empty functions to squelch all such |
| 97 | output. |
| 98 | |
| 99 | - `wasmfsOpfsDir`[^1]: Specifies the "mount point" of the |
| 100 | OPFS-backed filesystem in WASMFS-capable builds. This is only |
| 101 | used in WASMFS-capable builds of the library (which the canonical |
| 102 | builds do not include). |
| 103 | |
| 104 | - `disable` (as of 3.53.0) may be an object with the following |
| 105 | properties: |
| 106 | - `vfs`, an object, may contain a map of VFS names to booleans. |
| 107 | Any mapping to falsy are disabled. The supported names |
| 108 | are: "kvvfs", "opfs", "opfs-sahpool", "opfs-wl". |
| 109 | - Other disabling options may be added in the future. |
| 110 | |
| 111 | [^1] = This property may optionally be a function, in which case |
| 112 | this function calls that function to fetch the value, |
| 113 | enabling delayed evaluation. |
| 114 | |
| 115 | The returned object is the top-level sqlite3 namespace object. |
| 116 | |
| 117 | |
| 118 | Client code may optionally assign sqlite3ApiBootstrap.defaultConfig |
| 119 | an object-type value before calling sqlite3ApiBootstrap() (without |
| 120 | arguments) in order to tell that call to use this object as its |
| 121 | default config value. The intention of this is to provide |
| 122 | downstream clients with a reasonably flexible approach for plugging |
| 123 | in an environment-suitable configuration without having to define a |
| 124 | new global-scope symbol. |
| 125 | |
| 126 | However, because clients who access this library via an |
| 127 | Emscripten-hosted module will not have an opportunity to call |
| 128 | sqlite3ApiBootstrap() themselves, nor to access it before it is |
| 129 | called, an alternative option for setting the configuration is to |
| 130 | define globalThis.sqlite3ApiConfig to an object. If it is set, it |
| 131 | is used instead of sqlite3ApiBootstrap.defaultConfig if |
| 132 | sqlite3ApiBootstrap() is called without arguments. Setting the |
| 133 | `exports` and `memory` parts require already having loaded the WASM |
| 134 | module, though. |
| 135 | |
| 136 | Both sqlite3ApiBootstrap.defaultConfig and |
| 137 | globalThis.sqlite3ApiConfig get deleted during a successful call to |
| 138 | to this function because any changes to them made after that point |
| 139 | would have no useful effect. |
| 140 | |
| 141 | This function returns a Promise to the sqlite3 namespace object, |
| 142 | which resolves after the async pieces of the library init are |
| 143 | complete. |
| 144 | */ |
| 145 | 'use strict'; |
| 146 | const sqlite3ApiBootstrap = async function sqlite3ApiBootstrap( |
| 147 | apiConfig = (globalThis.sqlite3ApiConfig || sqlite3ApiBootstrap.defaultConfig) |
| 148 | ){ |
| 149 | if(sqlite3ApiBootstrap.sqlite3){ /* already initialized */ |
| 150 | (sqlite3ApiBootstrap.sqlite3.config || console).warn( |
| 151 | "sqlite3ApiBootstrap() called multiple times.", |
| 152 | "Config and external initializers are ignored on calls after the first." |
| 153 | ); |
| 154 | return sqlite3ApiBootstrap.sqlite3; |
| 155 | } |
| 156 | const nu = (...obj)=>Object.assign(Object.create(null),...obj); |
| 157 | const config = nu({ |
| 158 | exports: undefined, |
| 159 | memory: undefined, |
| 160 | bigIntEnabled: !!globalThis.BigInt64Array, |
| 161 | debug: console.debug.bind(console), |
| 162 | warn: console.warn.bind(console), |
| 163 | error: console.error.bind(console), |
| 164 | log: console.log.bind(console), |
| 165 | wasmfsOpfsDir: '/opfs', |
| 166 | /** |
| 167 | useStdAlloc is just for testing allocator discrepancies. The |
| 168 | docs guarantee that this is false in the canonical builds. For |
| 169 | 99% of purposes it doesn't matter which allocators we use, but |
| 170 | it becomes significant with, e.g., sqlite3_deserialize() and |
| 171 | certain wasm.xWrap.resultAdapter()s. |
| 172 | */ |
| 173 | useStdAlloc: false |
| 174 | }, apiConfig); |
| 175 | |
| 176 | Object.assign(config, { |
| 177 | allocExportName: config.useStdAlloc ? 'malloc' : 'sqlite3_malloc', |
| 178 | deallocExportName: config.useStdAlloc ? 'free' : 'sqlite3_free', |
| 179 | reallocExportName: config.useStdAlloc ? 'realloc' : 'sqlite3_realloc' |
| 180 | }); |
| 181 | |
| 182 | [ |
| 183 | // If any of these config options are functions, replace them with |
| 184 | // the result of calling that function. They must not be async. |
| 185 | 'exports', 'memory', 'functionTable', 'wasmfsOpfsDir' |
| 186 | ].forEach((k)=>{ |
| 187 | if('function' === typeof config[k]){ |
| 188 | config[k] = config[k](); |
| 189 | } |
| 190 | }); |
| 191 | |
| 192 | /** |
| 193 | The main sqlite3 binding API gets installed into this object, |
| 194 | mimicking the C API as closely as we can. The numerous members |
| 195 | names with prefixes 'sqlite3_' and 'SQLITE_' behave, insofar as |
| 196 | possible, identically to the C-native counterparts, as documented at: |
| 197 | |
| 198 | https://sqlite.org/c3ref/intro.html |
| 199 | |
| 200 | A very few exceptions require an additional level of proxy |
| 201 | function or may otherwise require special attention in the WASM |
| 202 | environment, and all such cases are documented somewhere below |
| 203 | in this file or in sqlite3-api-glue.js. capi members which are |
| 204 | not documented are installed as 1-to-1 proxies for their |
| 205 | C-side counterparts. |
| 206 | */ |
| 207 | const capi = nu(); |
| 208 | /** |
| 209 | Holds state which are specific to the WASM-related |
| 210 | infrastructure and glue code. |
| 211 | |
| 212 | Note that a number of members of this object are injected |
| 213 | dynamically after the api object is fully constructed, so |
| 214 | not all are documented in this file. |
| 215 | */ |
| 216 | const wasm = nu(); |
| 217 | |
| 218 | /** Internal helper for SQLite3Error ctor. */ |
| 219 | const __rcStr = (rc)=>{ |
| 220 | return (capi.sqlite3_js_rc_str && capi.sqlite3_js_rc_str(rc)) |
| 221 | || ("Unknown result code #"+rc); |
| 222 | }; |
| 223 | |
| 224 | /** Internal helper for SQLite3Error ctor. */ |
| 225 | const isInt32 = (n)=> |
| 226 | 'number'===typeof n |
| 227 | && n===(n | 0) |
| 228 | && n<=2147483647 && n>=-2147483648; |
| 229 | |
| 230 | /** |
| 231 | An Error subclass specifically for reporting DB-level errors and |
| 232 | enabling clients to unambiguously identify such exceptions. |
| 233 | The C-level APIs never throw, but some of the higher-level |
| 234 | C-style APIs do and the object-oriented APIs use exceptions |
| 235 | exclusively to report errors. |
| 236 | */ |
| 237 | class SQLite3Error extends Error { |
| 238 | /** |
| 239 | Constructs this object with a message depending on its arguments: |
| 240 | |
| 241 | If its first argument is an integer, it is assumed to be |
| 242 | an SQLITE_... result code and it is passed to |
| 243 | sqlite3.capi.sqlite3_js_rc_str() to stringify it. |
| 244 | |
| 245 | If called with exactly 2 arguments and the 2nd is an object, |
| 246 | that object is treated as the 2nd argument to the parent |
| 247 | constructor. |
| 248 | |
| 249 | The exception's message is created by concatenating its |
| 250 | arguments with a space between each, except for the |
| 251 | two-args-with-an-object form and that the first argument will |
| 252 | get coerced to a string, as described above, if it's an |
| 253 | integer. |
| 254 | |
| 255 | If passed an integer first argument, the error object's |
| 256 | `resultCode` member will be set to the given integer value, |
| 257 | else it will be set to capi.SQLITE_ERROR. |
| 258 | */ |
| 259 | constructor(...args){ |
| 260 | let rc; |
| 261 | if(args.length){ |
| 262 | if(isInt32(args[0])){ |
| 263 | rc = args[0]; |
| 264 | if(1===args.length){ |
| 265 | super(__rcStr(args[0])); |
| 266 | }else{ |
| 267 | const rcStr = __rcStr(rc); |
| 268 | if('object'===typeof args[1]){ |
| 269 | super(rcStr,args[1]); |
| 270 | }else{ |
| 271 | args[0] = rcStr+':'; |
| 272 | super(args.join(' ')); |
| 273 | } |
| 274 | } |
| 275 | }else{ |
| 276 | if(2===args.length && 'object'===typeof args[1]){ |
| 277 | super(...args); |
| 278 | }else{ |
| 279 | super(args.join(' ')); |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | this.resultCode = rc || capi.SQLITE_ERROR; |
| 284 | this.name = 'SQLite3Error'; |
| 285 | } |
| 286 | }; |
| 287 | |
| 288 | /** |
| 289 | Functionally equivalent to the SQLite3Error constructor but may |
| 290 | be used as part of an expression, e.g.: |
| 291 | |
| 292 | ``` |
| 293 | return someFunction(x) || SQLite3Error.toss(...); |
| 294 | ``` |
| 295 | */ |
| 296 | SQLite3Error.toss = (...args)=>{ |
| 297 | throw new SQLite3Error(...args); |
| 298 | }; |
| 299 | const toss3 = SQLite3Error.toss; |
| 300 | |
| 301 | if(config.wasmfsOpfsDir && !/^\/[^/]+$/.test(config.wasmfsOpfsDir)){ |
| 302 | toss3("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'."); |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | Returns true if the given BigInt value is small enough to fit |
| 307 | into an int64 value, else false. |
| 308 | */ |
| 309 | const bigIntFits64 = function f(b){ |
| 310 | if(!f._max){ |
| 311 | f._max = BigInt("0x7fffffffffffffff"); |
| 312 | f._min = ~f._max; |
| 313 | } |
| 314 | return b >= f._min && b <= f._max; |
| 315 | }; |
| 316 | |
| 317 | /** |
| 318 | Returns true if the given BigInt value is small enough to fit |
| 319 | into an int32, else false. |
| 320 | */ |
| 321 | const bigIntFits32 = (b)=>(b >= (-0x7fffffffn - 1n) && b <= 0x7fffffffn); |
| 322 | |
| 323 | /** |
| 324 | Returns true if the given BigInt value is small enough to fit |
| 325 | into a double value without loss of precision, else false. |
| 326 | */ |
| 327 | const bigIntFitsDouble = function f(b){ |
| 328 | if(!f._min){ |
| 329 | f._min = Number.MIN_SAFE_INTEGER; |
| 330 | f._max = Number.MAX_SAFE_INTEGER; |
| 331 | } |
| 332 | return b >= f._min && b <= f._max; |
| 333 | }; |
| 334 | |
| 335 | /** Returns v if v appears to be a TypedArray, else false. */ |
| 336 | const isTypedArray = (v)=>{ |
| 337 | return (v && v.constructor && isInt32(v.constructor.BYTES_PER_ELEMENT)) ? v : false; |
| 338 | }; |
| 339 | |
| 340 | /** |
| 341 | Returns true if v appears to be one of our bind()-able TypedArray |
| 342 | types: Uint8Array or Int8Array or ArrayBuffer. Support for |
| 343 | TypedArrays with element sizes >1 is a potential TODO just |
| 344 | waiting on a use case to justify them. Until then, their `buffer` |
| 345 | property can be used to pass them as an ArrayBuffer. If it's not |
| 346 | a bindable array type, a falsy value is returned. |
| 347 | */ |
| 348 | const isBindableTypedArray = (v)=> |
| 349 | v && (v instanceof Uint8Array |
| 350 | || v instanceof Int8Array |
| 351 | || v instanceof ArrayBuffer); |
| 352 | |
| 353 | /** |
| 354 | Returns true if v appears to be one of the TypedArray types |
| 355 | which is legal for holding SQL code (as opposed to binary blobs). |
| 356 | |
| 357 | Currently this is the same as isBindableTypedArray() but it |
| 358 | seems likely that we'll eventually want to add Uint32Array |
| 359 | and friends to the isBindableTypedArray() list but not to the |
| 360 | isSQLableTypedArray() list. |
| 361 | */ |
| 362 | const isSQLableTypedArray = (v)=> |
| 363 | v && (v instanceof Uint8Array |
| 364 | || v instanceof Int8Array |
| 365 | || v instanceof ArrayBuffer); |
| 366 | |
| 367 | /** Returns true if isBindableTypedArray(v) does, else throws with a message |
| 368 | that v is not a supported TypedArray value. */ |
| 369 | const affirmBindableTypedArray = (v)=> |
| 370 | isBindableTypedArray(v) |
| 371 | || toss3("Value is not of a supported TypedArray type."); |
| 372 | |
| 373 | /** |
| 374 | If v is-a Array, its join("") result is returned. If |
| 375 | isSQLableTypedArray(v) is true then wasm.typedArrayToString(v) is |
| 376 | returned. If it looks like a WASM pointer, wasm.cstrToJs(v) is |
| 377 | returned. Else v is returned as-is. |
| 378 | |
| 379 | Reminder to self: the "return as-is" instead of returning ''+v is |
| 380 | arguably a design mistake but changing it is risky at this point. |
| 381 | */ |
| 382 | const flexibleString = function(v){ |
| 383 | if(isSQLableTypedArray(v)){ |
| 384 | return wasm.typedArrayToString( |
| 385 | (v instanceof ArrayBuffer) ? new Uint8Array(v) : v, |
| 386 | 0, v.length |
| 387 | ); |
| 388 | } |
| 389 | else if(Array.isArray(v)) return v.join(""); |
| 390 | else if(wasm.isPtr(v)) v = wasm.cstrToJs(v); |
| 391 | return v; |
| 392 | }; |
| 393 | |
| 394 | /** |
| 395 | An Error subclass specifically for reporting Wasm-level malloc() |
| 396 | failure and enabling clients to unambiguously identify such |
| 397 | exceptions. |
| 398 | */ |
| 399 | class WasmAllocError extends Error { |
| 400 | /** |
| 401 | If called with 2 arguments and the 2nd one is an object, it |
| 402 | behaves like the Error constructor, else it concatenates all |
| 403 | arguments together with a single space between each to |
| 404 | construct an error message string. As a special case, if |
| 405 | called with no arguments then it uses a default error |
| 406 | message. |
| 407 | */ |
| 408 | constructor(...args){ |
| 409 | if(2===args.length && 'object'===typeof args[1]){ |
| 410 | super(...args); |
| 411 | }else if(args.length){ |
| 412 | super(args.join(' ')); |
| 413 | }else{ |
| 414 | super("Allocation failed."); |
| 415 | } |
| 416 | this.resultCode = capi.SQLITE_NOMEM; |
| 417 | this.name = 'WasmAllocError'; |
| 418 | } |
| 419 | }; |
| 420 | /** |
| 421 | Functionally equivalent to the WasmAllocError constructor but may |
| 422 | be used as part of an expression, e.g.: |
| 423 | |
| 424 | ``` |
| 425 | return someAllocatingFunction(x) || WasmAllocError.toss(...); |
| 426 | ``` |
| 427 | */ |
| 428 | WasmAllocError.toss = (...args)=>{ |
| 429 | throw new WasmAllocError(...args); |
| 430 | }; |
| 431 | |
| 432 | Object.assign(capi, { |
| 433 | /** |
| 434 | sqlite3_bind_blob() works exactly like its C counterpart unless |
| 435 | its 3rd argument is one of: |
| 436 | |
| 437 | - JS string: the 3rd argument is converted to a C string, the |
| 438 | 4th argument is ignored, and the C-string's length is used |
| 439 | in its place. |
| 440 | |
| 441 | - Array: converted to a string as defined for "flexible |
| 442 | strings" and then it's treated as a JS string. |
| 443 | |
| 444 | - Int8Array or Uint8Array: wasm.allocFromTypedArray() is used to |
| 445 | conver the memory to the WASM heap. If the 4th argument is |
| 446 | 0 or greater, it is used as-is, otherwise the array's byteLength |
| 447 | value is used. This is an exception to the C API's undefined |
| 448 | behavior for a negative 4th argument, but results are undefined |
| 449 | if the given 4th argument value is greater than the byteLength |
| 450 | of the input array. |
| 451 | |
| 452 | - If it's an ArrayBuffer, it gets wrapped in a Uint8Array and |
| 453 | treated as that type. |
| 454 | |
| 455 | In all of those cases, the final argument (destructor) is |
| 456 | ignored and capi.SQLITE_WASM_DEALLOC is assumed. |
| 457 | |
| 458 | A 3rd argument of `null` is treated as if it were a WASM pointer |
| 459 | of 0. |
| 460 | |
| 461 | If the 3rd argument is neither a WASM pointer nor one of the |
| 462 | above-described types, capi.SQLITE_MISUSE is returned. |
| 463 | |
| 464 | The first argument may be either an `sqlite3_stmt*` WASM |
| 465 | pointer or an sqlite3.oo1.Stmt instance. |
| 466 | |
| 467 | For consistency with the C API, it requires the same number of |
| 468 | arguments. It returns capi.SQLITE_MISUSE if passed any other |
| 469 | argument count. |
| 470 | */ |
| 471 | sqlite3_bind_blob: undefined/*installed later*/, |
| 472 | |
| 473 | /** |
| 474 | sqlite3_bind_text() works exactly like its C counterpart unless |
| 475 | its 3rd argument is one of: |
| 476 | |
| 477 | - JS string: the 3rd argument is converted to a C string, the |
| 478 | 4th argument is ignored, and the C-string's length is used |
| 479 | in its place. |
| 480 | |
| 481 | - Array: converted to a string as defined for "flexible |
| 482 | strings". The 4th argument is ignored and a value of -1 |
| 483 | is assumed. |
| 484 | |
| 485 | - Int8Array or Uint8Array: is assumed to contain UTF-8 text, is |
| 486 | converted to a string. The 4th argument is ignored, replaced |
| 487 | by the array's byteLength value. |
| 488 | |
| 489 | - If it's an ArrayBuffer, it gets wrapped in a Uint8Array and |
| 490 | treated as that type. |
| 491 | |
| 492 | In each of those cases, the final argument (text destructor) is |
| 493 | ignored and capi.SQLITE_WASM_DEALLOC is assumed. |
| 494 | |
| 495 | A 3rd argument of `null` is treated as if it were a WASM pointer |
| 496 | of 0. |
| 497 | |
| 498 | If the 3rd argument is neither a WASM pointer nor one of the |
| 499 | above-described types, capi.SQLITE_MISUSE is returned. |
| 500 | |
| 501 | The first argument may be either an `sqlite3_stmt*` WASM |
| 502 | pointer or an sqlite3.oo1.Stmt instance. |
| 503 | |
| 504 | For consistency with the C API, it requires the same number of |
| 505 | arguments. It returns capi.SQLITE_MISUSE if passed any other |
| 506 | argument count. |
| 507 | |
| 508 | If client code needs to bind partial strings, it needs to |
| 509 | either parcel the string up before passing it in here or it |
| 510 | must pass in a WASM pointer for the 3rd argument and a valid |
| 511 | 4th-argument value, taking care not to pass a value which |
| 512 | truncates a multi-byte UTF-8 character. When passing |
| 513 | WASM-format strings, it is important that the final argument be |
| 514 | valid or unexpected content can result, or WASM may crash if |
| 515 | the application reads past the WASM heap bounds. |
| 516 | */ |
| 517 | sqlite3_bind_text: undefined/*installed later*/, |
| 518 | |
| 519 | /** |
| 520 | sqlite3_create_function_v2() differs from its native |
| 521 | counterpart only in the following ways: |
| 522 | |
| 523 | 1) The fourth argument (`eTextRep`) argument must not specify |
| 524 | any encoding other than sqlite3.SQLITE_UTF8. The JS API does not |
| 525 | currently support any other encoding and likely never |
| 526 | will. This function does not replace that argument on its own |
| 527 | because it may contain other flags. As a special case, if |
| 528 | the bottom 4 bits of that argument are 0, SQLITE_UTF8 is |
| 529 | assumed. |
| 530 | |
| 531 | 2) Any of the four final arguments may be either WASM pointers |
| 532 | (assumed to be function pointers) or JS Functions. In the |
| 533 | latter case, each gets bound to WASM using |
| 534 | sqlite3.capi.wasm.installFunction() and that wrapper is passed |
| 535 | on to the native implementation. |
| 536 | |
| 537 | For consistency with the C API, it requires the same number of |
| 538 | arguments. It returns capi.SQLITE_MISUSE if passed any other |
| 539 | argument count. |
| 540 | |
| 541 | The semantics of JS functions are: |
| 542 | |
| 543 | xFunc: is passed `(pCtx, ...values)`. Its return value becomes |
| 544 | the new SQL function's result. |
| 545 | |
| 546 | xStep: is passed `(pCtx, ...values)`. Its return value is |
| 547 | ignored. |
| 548 | |
| 549 | xFinal: is passed `(pCtx)`. Its return value becomes the new |
| 550 | aggregate SQL function's result. |
| 551 | |
| 552 | xDestroy: is passed `(void*)`. Its return value is ignored. The |
| 553 | pointer passed to it is the one from the 5th argument to |
| 554 | sqlite3_create_function_v2(). |
| 555 | |
| 556 | Note that: |
| 557 | |
| 558 | - `pCtx` in the above descriptions is a `sqlite3_context*`. At |
| 559 | least 99 times out of a hundred, that initial argument will |
| 560 | be irrelevant for JS UDF bindings, but it needs to be there |
| 561 | so that the cases where it _is_ relevant, in particular with |
| 562 | window and aggregate functions, have full access to the |
| 563 | lower-level sqlite3 APIs. |
| 564 | |
| 565 | - When wrapping JS functions, the remaining arguments are passd |
| 566 | to them as positional arguments, not as an array of |
| 567 | arguments, because that allows callback definitions to be |
| 568 | more JS-idiomatic than C-like. For example `(pCtx,a,b)=>a+b` |
| 569 | is more intuitive and legible than |
| 570 | `(pCtx,args)=>args[0]+args[1]`. For cases where an array of |
| 571 | arguments would be more convenient, the callbacks simply need |
| 572 | to be declared like `(pCtx,...args)=>{...}`, in which case |
| 573 | `args` will be an array. |
| 574 | |
| 575 | - If a JS wrapper throws, it gets translated to |
| 576 | sqlite3_result_error() or sqlite3_result_error_nomem(), |
| 577 | depending on whether the exception is an |
| 578 | sqlite3.WasmAllocError object or not. |
| 579 | |
| 580 | - When passing on WASM function pointers, arguments are _not_ |
| 581 | converted or reformulated. They are passed on as-is in raw |
| 582 | pointer form using their native C signatures. Only JS |
| 583 | functions passed in to this routine, and thus wrapped by this |
| 584 | routine, get automatic conversions of arguments and result |
| 585 | values. The routines which perform those conversions are |
| 586 | exposed for client-side use as sqlite3_values_to_js(), |
| 587 | sqlite3_result_js(), and sqlite3_result_error_js(). |
| 588 | |
| 589 | For xFunc(), xStep(), and xFinal(): |
| 590 | |
| 591 | - When called from SQL, arguments to the UDF, and its result, |
| 592 | will be converted between JS and SQL with as much fidelity as |
| 593 | is feasible, triggering an exception if a type conversion |
| 594 | cannot be determined. Some freedom is afforded to numeric |
| 595 | conversions due to friction between the JS and C worlds: |
| 596 | integers which are larger than 32 bits may be treated as |
| 597 | doubles or BigInts. |
| 598 | |
| 599 | If any JS-side bound functions throw, those exceptions are |
| 600 | intercepted and converted to database-side errors with the |
| 601 | exception of xDestroy(): any exception from it is ignored, |
| 602 | possibly generating a console.error() message. Destructors |
| 603 | must not throw. |
| 604 | |
| 605 | Automatically-converted JS-to-WASM functions will be cleaned up |
| 606 | either when (A) this function is called again with the same |
| 607 | name, arity, and encoding, but null/0 values for the functions, |
| 608 | or (B) when pDb is passed to sqlite3_close_v2(). If this factor |
| 609 | is relevant for a given client, they can create WASM-bound JS |
| 610 | functions themselves, hold on to their pointers, and pass the |
| 611 | pointers in to here. Later on, they can free those pointers |
| 612 | (using `wasm.uninstallFunction()` or equivalent). |
| 613 | |
| 614 | C reference: https://sqlite.org/c3ref/create_function.html |
| 615 | |
| 616 | Maintenance reminder: the ability to add new |
| 617 | WASM-accessible functions to the runtime requires that the |
| 618 | WASM build is compiled with emcc's `-sALLOW_TABLE_GROWTH` |
| 619 | flag. |
| 620 | */ |
| 621 | sqlite3_create_function_v2: ( |
| 622 | pDb, funcName, nArg, eTextRep, pApp, |
| 623 | xFunc, xStep, xFinal, xDestroy |
| 624 | )=>{/*installed later*/}, |
| 625 | /** |
| 626 | Equivalent to passing the same arguments to |
| 627 | sqlite3_create_function_v2(), with 0 as the final argument. |
| 628 | */ |
| 629 | sqlite3_create_function: ( |
| 630 | pDb, funcName, nArg, eTextRep, pApp, |
| 631 | xFunc, xStep, xFinal |
| 632 | )=>{/*installed later*/}, |
| 633 | /** |
| 634 | The sqlite3_create_window_function() JS wrapper differs from |
| 635 | its native implementation in the exact same way that |
| 636 | sqlite3_create_function_v2() does. The additional function, |
| 637 | xInverse(), is treated identically to xStep() by the wrapping |
| 638 | layer. |
| 639 | */ |
| 640 | sqlite3_create_window_function: ( |
| 641 | pDb, funcName, nArg, eTextRep, pApp, |
| 642 | xStep, xFinal, xValue, xInverse, xDestroy |
| 643 | )=>{/*installed later*/}, |
| 644 | /** |
| 645 | The sqlite3_prepare_v3() binding handles two different uses |
| 646 | with differing JS/WASM semantics: |
| 647 | |
| 648 | 1) sqlite3_prepare_v3(pDb, sqlString, -1, prepFlags, ppStmt , null) |
| 649 | |
| 650 | 2) sqlite3_prepare_v3(pDb, sqlPointer, sqlByteLen, prepFlags, ppStmt, sqlPointerToPointer) |
| 651 | |
| 652 | The SQL length argument (the 3rd argument) must, for usage (1), |
| 653 | always be negative because it must be a byte length and that |
| 654 | value is expensive to calculate from JS (where only the |
| 655 | character length of strings is readily available). It is |
| 656 | retained in this API's interface for code/documentation |
| 657 | compatibility reasons but is currently _always_ ignored. With |
| 658 | usage (2), the 3rd argument is used as-is but is is still |
| 659 | critical that the C-style input string (2nd argument) be |
| 660 | terminated with a 0 byte. |
| 661 | |
| 662 | In usage (1), the 2nd argument must be of type string, |
| 663 | Uint8Array, Int8Array, or ArrayBuffer (all of which are assumed |
| 664 | to hold SQL). If it is, this function assumes case (1) and |
| 665 | calls the underyling C function with the equivalent of: |
| 666 | |
| 667 | (pDb, sqlAsString, -1, prepFlags, ppStmt, null) |
| 668 | |
| 669 | The `pzTail` argument is ignored in this case because its |
| 670 | result is meaningless when a string-type value is passed |
| 671 | through: the string goes through another level of internal |
| 672 | conversion for WASM's sake and the result pointer would refer |
| 673 | to that transient conversion's memory, not the passed-in |
| 674 | string. |
| 675 | |
| 676 | If the sql argument is not a string, it must be a _pointer_ to |
| 677 | a NUL-terminated string which was allocated in the WASM memory |
| 678 | (e.g. using capi.wasm.alloc() or equivalent). In that case, |
| 679 | the final argument may be 0/null/undefined or must be a pointer |
| 680 | to which the "tail" of the compiled SQL is written, as |
| 681 | documented for the C-side sqlite3_prepare_v3(). |
| 682 | |
| 683 | In case (2), the underlying C function is called with the |
| 684 | equivalent of: |
| 685 | |
| 686 | (pDb, sqlAsPointer, sqlByteLen, prepFlags, ppStmt, pzTail) |
| 687 | |
| 688 | It returns its result and compiled statement as documented in |
| 689 | the C API. Fetching the output pointers (5th and 6th |
| 690 | parameters) requires using `capi.wasm.peek()` (or |
| 691 | equivalent) and the `pzTail` will point to an address relative to |
| 692 | the `sqlAsPointer` value. |
| 693 | |
| 694 | If passed an invalid 2nd argument type, this function will |
| 695 | return SQLITE_MISUSE and sqlite3_errmsg() will contain a string |
| 696 | describing the problem. |
| 697 | |
| 698 | Side-note: if given an empty string, or one which contains only |
| 699 | comments or an empty SQL expression, 0 is returned but the result |
| 700 | output pointer will be NULL. |
| 701 | */ |
| 702 | sqlite3_prepare_v3: (dbPtr, sql, sqlByteLen, prepFlags, |
| 703 | stmtPtrPtr, strPtrPtr)=>{}/*installed later*/, |
| 704 | |
| 705 | /** |
| 706 | Equivalent to calling sqlite3_prapare_v3() with 0 as its 4th argument. |
| 707 | */ |
| 708 | sqlite3_prepare_v2: (dbPtr, sql, sqlByteLen, |
| 709 | stmtPtrPtr,strPtrPtr)=>{}/*installed later*/, |
| 710 | |
| 711 | /** |
| 712 | This binding enables the callback argument to be a JavaScript. |
| 713 | |
| 714 | If the callback is a function, then for the duration of the |
| 715 | sqlite3_exec() call, it installs a WASM-bound function which |
| 716 | acts as a proxy for the given callback. That proxy will also |
| 717 | perform a conversion of the callback's arguments from |
| 718 | `(char**)` to JS arrays of strings. However, for API |
| 719 | consistency's sake it will still honor the C-level callback |
| 720 | parameter order and will call it like: |
| 721 | |
| 722 | `callback(pVoid, colCount, listOfValues, listOfColNames)` |
| 723 | |
| 724 | If the callback is not a JS function then this binding performs |
| 725 | no translation of the callback, but the sql argument is still |
| 726 | converted to a WASM string for the call using the |
| 727 | "string:flexible" argument converter. |
| 728 | */ |
| 729 | sqlite3_exec: (pDb, sql, callback, pVoid, pErrMsg)=>{}/*installed later*/, |
| 730 | |
| 731 | /** |
| 732 | If passed a single argument which appears to be a byte-oriented |
| 733 | TypedArray (Int8Array or Uint8Array), this function treats that |
| 734 | TypedArray as an output target, fetches `theArray.byteLength` |
| 735 | bytes of randomness, and populates the whole array with it. As |
| 736 | a special case, if the array's length is 0, this function |
| 737 | behaves as if it were passed (0,0). When called this way, it |
| 738 | returns its argument, else it returns the `undefined` value. |
| 739 | |
| 740 | If called with any other arguments, they are passed on as-is |
| 741 | to the C API. Results are undefined if passed any incompatible |
| 742 | values. |
| 743 | */ |
| 744 | sqlite3_randomness: (n, outPtr)=>{/*installed later*/}, |
| 745 | }/*capi*/); |
| 746 | |
| 747 | /** |
| 748 | Various internal-use utilities are added here as needed. They |
| 749 | are bound to an object only so that we have access to them in |
| 750 | the differently-scoped steps of the API bootstrapping |
| 751 | process. At the end of the API setup process, this object gets |
| 752 | removed. These are NOT part of the public API. |
| 753 | */ |
| 754 | const util = { |
| 755 | affirmBindableTypedArray, flexibleString, |
| 756 | bigIntFits32, bigIntFits64, bigIntFitsDouble, |
| 757 | isBindableTypedArray, |
| 758 | isInt32, isSQLableTypedArray, isTypedArray, |
| 759 | isUIThread: ()=>(globalThis.window===globalThis && !!globalThis.document), |
| 760 | // is this true for ESM?: 'undefined'===typeof WorkerGlobalScope |
| 761 | toss: function(...args){throw new Error(args.join(' '))}, |
| 762 | toss3, |
| 763 | typedArrayPart: wasm.typedArrayPart, |
| 764 | nu, |
| 765 | assert: function(arg,msg){ |
| 766 | if( !arg ){ |
| 767 | util.toss("Assertion failed:",msg); |
| 768 | } |
| 769 | }, |
| 770 | /** |
| 771 | Given a byte array or ArrayBuffer, this function throws if the |
| 772 | lead bytes of that buffer do not hold a SQLite3 database header, |
| 773 | else it returns without side effects. |
| 774 | |
| 775 | Added in 3.44. As of 3.54 in SEE builds it performs only a |
| 776 | rudimentary length check and does not fail for invalid header |
| 777 | bytes, under the assumption that the input may be an encrypted |
| 778 | db. We cannot unambiguously distinguish an encrypted db from |
| 779 | garbage bytes. |
| 780 | */ |
| 781 | affirmDbHeader: function(bytes){ |
| 782 | if(bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes); |
| 783 | const header = "SQLite format 3"; |
| 784 | if( header.length > bytes.byteLength ){ |
| 785 | toss3("Input does not contain an SQLite3 database header."); |
| 786 | } |
| 787 | for(let i = 0; i < header.length; ++i){ |
| 788 | if( header.charCodeAt(i) !== bytes[i] ){ |
| 789 | //#if enable-see |
| 790 | break /* assume this might be an encrypted db. |
| 791 | https://sqlite.org/see/forumpost/f84bef3552 */; |
| 792 | //#else |
| 793 | toss3("Input does not contain an SQLite3 database header."); |
| 794 | //#/if |
| 795 | } |
| 796 | } |
| 797 | }, |
| 798 | /** |
| 799 | Given a byte array or ArrayBuffer, this function throws if the |
| 800 | database does not, at a cursory glance, appear to be an SQLite3 |
| 801 | database. It only examines the size and header, but further |
| 802 | checks may be added in the future. |
| 803 | |
| 804 | Added in 3.44. See notes in affirmDbHeader() regarding SEE |
| 805 | builds. |
| 806 | */ |
| 807 | affirmIsDb: function(bytes){ |
| 808 | if(bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes); |
| 809 | const n = bytes.byteLength; |
| 810 | if(n<512 || n%512!==0) { |
| 811 | toss3("Byte array size",n,"is invalid for an SQLite3 db."); |
| 812 | } |
| 813 | util.affirmDbHeader(bytes); |
| 814 | } |
| 815 | }/*util*/; |
| 816 | |
| 817 | /** |
| 818 | wasm.X properties which are used for configuring the wasm |
| 819 | environment via whwashutil.js. This object gets fleshed out with |
| 820 | a number of WASM-specific utilities, in sqlite3-api-glue.c-pp.js. |
| 821 | */ |
| 822 | Object.assign(wasm, { |
| 823 | |
| 824 | /** |
| 825 | The symbols exported by the WASM environment. |
| 826 | */ |
| 827 | exports: config.exports |
| 828 | || toss3("Missing API config.exports (WASM module exports)."), |
| 829 | |
| 830 | /** |
| 831 | When Emscripten compiles with `-sIMPORTED_MEMORY`, it |
| 832 | initializes the heap and imports it into wasm, as opposed to |
| 833 | the other way around. In this case, the memory is not available |
| 834 | via this.exports.memory so the client must pass it in via |
| 835 | config.memory. |
| 836 | */ |
| 837 | memory: config.memory |
| 838 | || config.exports['memory'] |
| 839 | || toss3("API config object requires a WebAssembly.Memory object", |
| 840 | "in either config.exports.memory (exported)", |
| 841 | "or config.memory (imported)."), |
| 842 | |
| 843 | /** |
| 844 | The WASM pointer size. If set then it MUST be one of 4 or 8 and |
| 845 | it MUST correspond to the WASM environment's pointer size. We |
| 846 | figure out the size by calling some un-JS-wrapped WASM function |
| 847 | which returns a pointer-type value. If that value is a BigInt, |
| 848 | it's 64-bit, else it's 32-bit. The pieces which populate |
| 849 | sqlite3.wasm (whwasmutil.js) can figure this out _if_ they can |
| 850 | allocate, but we have a chicken/egg situation there which makes |
| 851 | it illegal for that code to invoke wasm.dealloc() at the time |
| 852 | it would be needed. So we need to configure it ahead of time |
| 853 | (here) instead. |
| 854 | */ |
| 855 | pointerSize: ('number'===typeof config.exports.sqlite3_libversion()) ? 4 : 8, |
| 856 | |
| 857 | /** |
| 858 | True if BigInt support was enabled via (e.g.) the |
| 859 | Emscripten -sWASM_BIGINT flag, else false. When |
| 860 | enabled, certain 64-bit sqlite3 APIs are enabled which |
| 861 | are not otherwise enabled due to JS/WASM int64 |
| 862 | impedance mismatches. |
| 863 | */ |
| 864 | bigIntEnabled: !!config.bigIntEnabled, |
| 865 | |
| 866 | /** |
| 867 | WebAssembly.Table object holding the indirect function call |
| 868 | table. Defaults to exports.__indirect_function_table. |
| 869 | */ |
| 870 | functionTable: config.functionTable, |
| 871 | |
| 872 | /** |
| 873 | The API's primary point of access to the WASM-side memory |
| 874 | allocator. Works like sqlite3_malloc() but throws a |
| 875 | WasmAllocError if allocation fails. It is important that any |
| 876 | code which might pass through the sqlite3 C API NOT throw and |
| 877 | must instead return SQLITE_NOMEM (or equivalent, depending on |
| 878 | the context). |
| 879 | |
| 880 | Very few cases in the sqlite3 JS APIs can result in |
| 881 | client-defined functions propagating exceptions via the C-style |
| 882 | API. Most notably, this applies to WASM-bound JS functions |
| 883 | which are created directly by clients and passed on _as WASM |
| 884 | function pointers_ to functions such as |
| 885 | sqlite3_create_function_v2(). Such bindings created |
| 886 | transparently by this API will automatically use wrappers which |
| 887 | catch exceptions and convert them to appropriate error codes. |
| 888 | |
| 889 | For cases where non-throwing allocation is required, use |
| 890 | this.alloc.impl(), which is the unadulterated WASM-exported |
| 891 | counterpart of this wrapper. |
| 892 | |
| 893 | Design note: this function is not named "malloc" primarily |
| 894 | because Emscripten uses that name and we wanted to avoid any |
| 895 | confusion early on in this code's development, when it still |
| 896 | had close ties to Emscripten's glue code. |
| 897 | */ |
| 898 | alloc: undefined/*installed later*/, |
| 899 | |
| 900 | /** |
| 901 | Rarely necessary in JS code, this routine works like |
| 902 | sqlite3_realloc(M,N), where M is either NULL or a pointer |
| 903 | obtained from this function or this.alloc() and N is the number |
| 904 | of bytes to reallocate the block to. Returns a pointer to the |
| 905 | reallocated block or 0 if allocation fails. |
| 906 | |
| 907 | If M is NULL and N is positive, this behaves like |
| 908 | this.alloc(N). If N is 0, it behaves like this.dealloc(). |
| 909 | Results are undefined if N is negative (sqlite3_realloc() |
| 910 | treats that as 0, but if this code is built with a different |
| 911 | allocator it may misbehave with negative values). |
| 912 | |
| 913 | Like this.alloc.impl(), this.realloc.impl() is a direct binding |
| 914 | to the underlying realloc() implementation which does not throw |
| 915 | exceptions, instead returning 0 (or 0n) on allocation error. |
| 916 | */ |
| 917 | realloc: undefined/*installed later*/, |
| 918 | |
| 919 | /** |
| 920 | The API's primary point of access to the WASM-side memory |
| 921 | deallocator. Works like sqlite3_free(). |
| 922 | |
| 923 | Design note: this function is not named "free" for the same |
| 924 | reason that this.alloc() is not called this.malloc(). |
| 925 | */ |
| 926 | dealloc: undefined/*installed later*/ |
| 927 | |
| 928 | /* Many more wasm-related APIs get installed later on. */ |
| 929 | }/*wasm*/); |
| 930 | |
| 931 | /** |
| 932 | wasm.alloc()'s srcTypedArray.byteLength bytes, |
| 933 | populates them with the values from the source |
| 934 | TypedArray, and returns the pointer to that memory. The |
| 935 | returned pointer must eventually be passed to |
| 936 | wasm.dealloc() to clean it up. |
| 937 | |
| 938 | The argument may be a Uint8Array, Int8Array, or ArrayBuffer, |
| 939 | and it throws if passed any other type. |
| 940 | |
| 941 | As a special case, to avoid further special cases where |
| 942 | this is used, if srcTypedArray.byteLength is 0, it |
| 943 | allocates a single byte and sets it to the value |
| 944 | 0. Even in such cases, calls must behave as if the |
| 945 | allocated memory has exactly srcTypedArray.byteLength |
| 946 | bytes. |
| 947 | */ |
| 948 | wasm.allocFromTypedArray = function(srcTypedArray){ |
| 949 | if(srcTypedArray instanceof ArrayBuffer){ |
| 950 | srcTypedArray = new Uint8Array(srcTypedArray); |
| 951 | } |
| 952 | affirmBindableTypedArray(srcTypedArray); |
| 953 | const pRet = wasm.alloc(srcTypedArray.byteLength || 1); |
| 954 | wasm.heapForSize(srcTypedArray.constructor) |
| 955 | .set(srcTypedArray.byteLength ? srcTypedArray : [0], Number(pRet)) |
| 956 | /* Maintenance note: the order of alloc() and heapForSize() calls |
| 957 | is significant: https://sqlite.org/forum/forumpost/05b77273be104532 */; |
| 958 | return pRet; |
| 959 | }; |
| 960 | |
| 961 | { |
| 962 | // Set up allocators... |
| 963 | const keyAlloc = config.allocExportName, |
| 964 | keyDealloc = config.deallocExportName, |
| 965 | keyRealloc = config.reallocExportName; |
| 966 | for(const key of [keyAlloc, keyDealloc, keyRealloc]){ |
| 967 | const f = wasm.exports[key]; |
| 968 | if(!(f instanceof Function)) toss3("Missing required exports[",key,"] function."); |
| 969 | } |
| 970 | |
| 971 | wasm.alloc = function f(n){ |
| 972 | return f.impl(n) || WasmAllocError.toss("Failed to allocate",n," bytes."); |
| 973 | }; |
| 974 | wasm.alloc.impl = wasm.exports[keyAlloc]; |
| 975 | wasm.realloc = function f(m,n){ |
| 976 | const m2 = f.impl(wasm.ptr.coerce(m)/*tag:64bit*/,n); |
| 977 | return n ? (m2 || WasmAllocError.toss("Failed to reallocate",n," bytes.")) : wasm.ptr.null; |
| 978 | }; |
| 979 | wasm.realloc.impl = wasm.exports[keyRealloc]; |
| 980 | wasm.dealloc = function f(m){ |
| 981 | f.impl(wasm.ptr.coerce(m)/*tag:64bit*/) |
| 982 | /* This coerce() is the reason we have to set wasm.pointerSize before |
| 983 | calling WhWasmUtilInstaller(). If we don't, that code will call |
| 984 | into this very early in its init, before wasm.ptr has been set up, |
| 985 | resulting in a null deref here. */; |
| 986 | }; |
| 987 | wasm.dealloc.impl = wasm.exports[keyDealloc]; |
| 988 | } |
| 989 | |
| 990 | /** |
| 991 | Reports info about compile-time options using |
| 992 | sqlite3_compileoption_get() and sqlite3_compileoption_used(). It |
| 993 | has several distinct uses: |
| 994 | |
| 995 | If optName is an array then it is expected to be a list of |
| 996 | compilation options and this function returns an object |
| 997 | which maps each such option to true or false, indicating |
| 998 | whether or not the given option was included in this |
| 999 | build. That object is returned. |
| 1000 | |
| 1001 | If optName is an object, its keys are expected to be compilation |
| 1002 | options and this function sets each entry to true or false, |
| 1003 | indicating whether the compilation option was used or not. That |
| 1004 | object is returned. |
| 1005 | |
| 1006 | If passed no arguments then it returns an object mapping |
| 1007 | all known compilation options to their compile-time values, |
| 1008 | or boolean true if they are defined with no value. This |
| 1009 | result, which is relatively expensive to compute, is cached |
| 1010 | and returned for future no-argument calls. |
| 1011 | |
| 1012 | In all other cases it returns true if the given option was |
| 1013 | active when when compiling the sqlite3 module, else false. |
| 1014 | |
| 1015 | Compile-time option names may optionally include their |
| 1016 | "SQLITE_" prefix. When it returns an object of all options, |
| 1017 | the prefix is elided. |
| 1018 | */ |
| 1019 | wasm.compileOptionUsed = function f(optName){ |
| 1020 | if(!arguments.length){ |
| 1021 | if(f._result) return f._result; |
| 1022 | else if(!f._opt){ |
| 1023 | f._rx = /^([^=]+)=(.+)/; |
| 1024 | f._rxInt = /^-?\d+$/; |
| 1025 | f._opt = function(opt, rv){ |
| 1026 | const m = f._rx.exec(opt); |
| 1027 | rv[0] = (m ? m[1] : opt); |
| 1028 | rv[1] = m ? (f._rxInt.test(m[2]) ? +m[2] : m[2]) : true; |
| 1029 | }; |
| 1030 | } |
| 1031 | const rc = nu(), ov = [0,0]; |
| 1032 | let i = 0, k; |
| 1033 | while((k = capi.sqlite3_compileoption_get(i++))){ |
| 1034 | f._opt(k,ov); |
| 1035 | rc[ov[0]] = ov[1]; |
| 1036 | } |
| 1037 | return f._result = rc; |
| 1038 | }else if(Array.isArray(optName)){ |
| 1039 | const rc = nu(); |
| 1040 | optName.forEach((v)=>{ |
| 1041 | rc[v] = capi.sqlite3_compileoption_used(v); |
| 1042 | }); |
| 1043 | return rc; |
| 1044 | }else if('object' === typeof optName){ |
| 1045 | Object.keys(optName).forEach((k)=> { |
| 1046 | optName[k] = capi.sqlite3_compileoption_used(k); |
| 1047 | }); |
| 1048 | return optName; |
| 1049 | } |
| 1050 | return ( |
| 1051 | 'string'===typeof optName |
| 1052 | ) ? !!capi.sqlite3_compileoption_used(optName) : false; |
| 1053 | }/*compileOptionUsed()*/; |
| 1054 | |
| 1055 | /** |
| 1056 | sqlite3.wasm.pstack (pseudo-stack) holds a special-case allocator |
| 1057 | intended solely for short-lived, small data. In practice, it's |
| 1058 | primarily used to allocate output pointers. It must not be used |
| 1059 | for any memory which needs to outlive the scope in which it's |
| 1060 | obtained from pstack. |
| 1061 | |
| 1062 | The library guarantees only that a minimum of 2kb are available |
| 1063 | in this allocator, and it may provide more (it's a build-time |
| 1064 | value). pstack.quota and pstack.remaining can be used to get the |
| 1065 | total resp. remaining amount of memory. |
| 1066 | |
| 1067 | It has only a single intended usage pattern: |
| 1068 | |
| 1069 | ``` |
| 1070 | const stackPos = pstack.pointer; |
| 1071 | try{ |
| 1072 | const ptr = pstack.alloc(8); |
| 1073 | // ==> pstack.pointer === ptr |
| 1074 | const otherPtr = pstack.alloc(8); |
| 1075 | // ==> pstack.pointer === otherPtr |
| 1076 | ... |
| 1077 | }finally{ |
| 1078 | pstack.restore(stackPos); |
| 1079 | // ==> pstack.pointer === stackPos |
| 1080 | } |
| 1081 | ``` |
| 1082 | |
| 1083 | This allocator is much faster than a general-purpose one but is |
| 1084 | limited to usage patterns like the one shown above (which are |
| 1085 | pretty common when using sqlite3.capi). |
| 1086 | |
| 1087 | The memory lives in the WASM heap and can be used with routines |
| 1088 | such as wasm.poke() and wasm.heap8u().slice(). |
| 1089 | */ |
| 1090 | wasm.pstack = nu({ |
| 1091 | /** |
| 1092 | Sets the current pstack position to the given pointer. Results |
| 1093 | are undefined if the passed-in value did not come from |
| 1094 | this.pointer. |
| 1095 | |
| 1096 | In debug builds this may trigger an assert() in the WASM |
| 1097 | environment if passed an illegal value. |
| 1098 | */ |
| 1099 | restore: wasm.exports.sqlite3__wasm_pstack_restore, |
| 1100 | |
| 1101 | /** |
| 1102 | Attempts to allocate the given number of bytes from the |
| 1103 | pstack. On success, it zeroes out a block of memory of the |
| 1104 | given size, adjusts the pstack pointer, and returns a pointer |
| 1105 | to the memory. On error, throws a WasmAllocError. The |
| 1106 | memory must eventually be released using restore(). |
| 1107 | |
| 1108 | If n is a string, it must be a WASM "IR" value in the set |
| 1109 | accepted by wasm.sizeofIR(), which is mapped to the size of |
| 1110 | that data type. If passed a string not in that set, it throws a |
| 1111 | WasmAllocError. |
| 1112 | |
| 1113 | This method always adjusts the given value to be a multiple |
| 1114 | of 8 bytes because failing to do so can lead to incorrect |
| 1115 | results when reading and writing 64-bit values from/to the WASM |
| 1116 | heap. Similarly, the returned address is always 8-byte aligned. |
| 1117 | */ |
| 1118 | alloc: function(n){ |
| 1119 | if('string'===typeof n && !(n = wasm.sizeofIR(n))){ |
| 1120 | WasmAllocError.toss("Invalid value for pstack.alloc(",arguments[0],")"); |
| 1121 | } |
| 1122 | return wasm.exports.sqlite3__wasm_pstack_alloc(n) |
| 1123 | || WasmAllocError.toss("Could not allocate",n, |
| 1124 | "bytes from the pstack."); |
| 1125 | }, |
| 1126 | |
| 1127 | /** |
| 1128 | alloc()'s n chunks, each sz bytes, as a single memory block and |
| 1129 | returns the addresses as an array of n element, each holding |
| 1130 | the address of one chunk. |
| 1131 | |
| 1132 | sz may optionally be an IR string accepted by wasm.sizeofIR(). |
| 1133 | |
| 1134 | Throws a WasmAllocError if allocation fails. |
| 1135 | |
| 1136 | Example: |
| 1137 | |
| 1138 | ``` |
| 1139 | const [p1, p2, p3] = wasm.pstack.allocChunks(3, wasm.ptr.size); |
| 1140 | ``` |
| 1141 | */ |
| 1142 | allocChunks: function(n,sz){ |
| 1143 | if('string'===typeof sz && !(sz = wasm.sizeofIR(sz))){ |
| 1144 | WasmAllocError.toss("Invalid size value for allocChunks(",arguments[1],")"); |
| 1145 | } |
| 1146 | const mem = wasm.pstack.alloc(n * sz); |
| 1147 | const rc = [mem]; |
| 1148 | let i = 1, offset = sz; |
| 1149 | for(; i < n; ++i, offset += sz) rc.push(wasm.ptr.add(mem, offset)); |
| 1150 | return rc; |
| 1151 | }, |
| 1152 | |
| 1153 | /** |
| 1154 | A convenience wrapper for allocChunks() which sizes each chunk |
| 1155 | as either 8 bytes (safePtrSize is truthy) or wasm.ptr.size (if |
| 1156 | safePtrSize is falsy). |
| 1157 | |
| 1158 | How it returns its result differs depending on its first |
| 1159 | argument: if it's 1, it returns a single pointer value. If it's |
| 1160 | more than 1, it returns the same as allocChunks(). |
| 1161 | |
| 1162 | When a returned pointer will refer to a 64-bit value, e.g. a |
| 1163 | double or int64, and that value must be written or fetched, |
| 1164 | e.g. using wasm.poke() or wasm.peek(), it is |
| 1165 | important that the pointer in question be aligned to an 8-byte |
| 1166 | boundary or else it will not be fetched or written properly and |
| 1167 | will corrupt or read neighboring memory. |
| 1168 | |
| 1169 | However, when all pointers involved point to "small" data, it |
| 1170 | is safe to pass a falsy value to save a tiny bit of memory. |
| 1171 | */ |
| 1172 | allocPtr: (n=1,safePtrSize=true)=>{ |
| 1173 | return 1===n |
| 1174 | ? wasm.pstack.alloc(safePtrSize ? 8 : wasm.ptr.size) |
| 1175 | : wasm.pstack.allocChunks(n, safePtrSize ? 8 : wasm.ptr.size); |
| 1176 | }, |
| 1177 | |
| 1178 | /** |
| 1179 | Records the current pstack position, calls the given function, |
| 1180 | passing it the sqlite3 object, then restores the pstack |
| 1181 | regardless of whether the function throws. Returns the result |
| 1182 | of the call or propagates an exception on error. |
| 1183 | |
| 1184 | Added in 3.44. |
| 1185 | */ |
| 1186 | call: function(f){ |
| 1187 | const stackPos = wasm.pstack.pointer; |
| 1188 | try{ return f(sqlite3) } |
| 1189 | finally{ wasm.pstack.restore(stackPos); } |
| 1190 | } |
| 1191 | |
| 1192 | })/*wasm.pstack*/; |
| 1193 | |
| 1194 | Object.defineProperties(wasm.pstack, { |
| 1195 | /** |
| 1196 | Resolves to the current pstack position pointer either as a |
| 1197 | Number (32-bit WASM) or BigInt (64-bit WASM). This value is |
| 1198 | intended _only_ to be saved for passing to restore(). Writing |
| 1199 | to this memory, without first reserving it via |
| 1200 | wasm.pstack.alloc() and friends, leads to undefined results. |
| 1201 | */ |
| 1202 | pointer: { |
| 1203 | configurable: false, iterable: true, writeable: false, |
| 1204 | get: wasm.exports.sqlite3__wasm_pstack_ptr |
| 1205 | //Whether or not a setter as an alternative to restore() is |
| 1206 | //clearer or would just lead to confusion or misuse is unclear. |
| 1207 | //set: wasm.exports.sqlite3__wasm_pstack_restore |
| 1208 | }, |
| 1209 | |
| 1210 | /** |
| 1211 | Resolves to the total number of bytes available in the pstack |
| 1212 | allocator, including any space which is currently |
| 1213 | allocated. This value is a compile-time constant. |
| 1214 | */ |
| 1215 | quota: { |
| 1216 | configurable: false, iterable: true, writeable: false, |
| 1217 | get: wasm.exports.sqlite3__wasm_pstack_quota |
| 1218 | }, |
| 1219 | |
| 1220 | /** |
| 1221 | Resolves to the number of bytes remaining in the pstack |
| 1222 | allocator. |
| 1223 | */ |
| 1224 | remaining: { |
| 1225 | configurable: false, iterable: true, writeable: false, |
| 1226 | get: wasm.exports.sqlite3__wasm_pstack_remaining |
| 1227 | } |
| 1228 | })/*wasm.pstack properties*/; |
| 1229 | |
| 1230 | /** |
| 1231 | Docs: https://sqlite.org/wasm/doc/trunk/api-c-style.md#sqlite3_randomness |
| 1232 | */ |
| 1233 | capi.sqlite3_randomness = (...args)=>{ |
| 1234 | if(1===args.length |
| 1235 | && util.isTypedArray(args[0]) |
| 1236 | && 1===args[0].BYTES_PER_ELEMENT){ |
| 1237 | const ta = args[0]; |
| 1238 | if(0===ta.byteLength){ |
| 1239 | wasm.exports.sqlite3_randomness(0,wasm.ptr.null); |
| 1240 | return ta; |
| 1241 | } |
| 1242 | const stack = wasm.pstack.pointer; |
| 1243 | try { |
| 1244 | let n = ta.byteLength, offset = 0; |
| 1245 | const r = wasm.exports.sqlite3_randomness; |
| 1246 | const heap = wasm.heap8u(); |
| 1247 | const nAlloc = n < 512 ? n : 512; |
| 1248 | const ptr = wasm.pstack.alloc(nAlloc); |
| 1249 | do{ |
| 1250 | const j = (n>nAlloc ? nAlloc : n); |
| 1251 | r(j, ptr); |
| 1252 | ta.set(wasm.typedArrayPart(heap, ptr, wasm.ptr.add(ptr,j)), offset); |
| 1253 | n -= j; |
| 1254 | offset += j; |
| 1255 | } while(n > 0); |
| 1256 | }catch(e){ |
| 1257 | config.error("Highly unexpected (and ignored!) "+ |
| 1258 | "exception in sqlite3_randomness():",e); |
| 1259 | }finally{ |
| 1260 | wasm.pstack.restore(stack); |
| 1261 | } |
| 1262 | return ta; |
| 1263 | } |
| 1264 | wasm.exports.sqlite3_randomness(...args); |
| 1265 | }; |
| 1266 | |
| 1267 | /** |
| 1268 | If the wasm environment has a WASMFS/OPFS-backed persistent |
| 1269 | storage directory, its path is returned by this function. If it |
| 1270 | does not then it returns "" (noting that "" is a falsy value). |
| 1271 | |
| 1272 | The first time this is called, this function inspects the current |
| 1273 | environment to determine whether WASMFS persistence support is |
| 1274 | available and, if it is, enables it (if needed). After the first |
| 1275 | call it always returns the cached result. |
| 1276 | |
| 1277 | If the returned string is not empty, any files stored under the |
| 1278 | returned path (recursively) are housed in OPFS storage. If the |
| 1279 | returned string is empty, this particular persistent storage |
| 1280 | option is not available on the client. |
| 1281 | |
| 1282 | Though the mount point name returned by this function is intended |
| 1283 | to remain stable, clients should not hard-coded it anywhere. |
| 1284 | Always call this function to get the path. |
| 1285 | |
| 1286 | This function is a no-op in most builds of this library, as the |
| 1287 | WASMFS capability requires a custom build. |
| 1288 | */ |
| 1289 | capi.sqlite3_wasmfs_opfs_dir = function(){ |
| 1290 | if(undefined !== this.dir) return this.dir; |
| 1291 | // If we have no OPFS, there is no persistent dir |
| 1292 | const pdir = config.wasmfsOpfsDir; |
| 1293 | if(!pdir |
| 1294 | || !globalThis.FileSystemHandle |
| 1295 | || !globalThis.FileSystemDirectoryHandle |
| 1296 | || !globalThis.FileSystemFileHandle |
| 1297 | || !wasm.exports.sqlite3__wasm_init_wasmfs){ |
| 1298 | return this.dir = ""; |
| 1299 | } |
| 1300 | try{ |
| 1301 | if(pdir && 0===wasm.xCallWrapped( |
| 1302 | 'sqlite3__wasm_init_wasmfs', 'i32', ['string'], pdir |
| 1303 | )){ |
| 1304 | return this.dir = pdir; |
| 1305 | }else{ |
| 1306 | return this.dir = ""; |
| 1307 | } |
| 1308 | }catch(e){ |
| 1309 | // sqlite3__wasm_init_wasmfs() is not available |
| 1310 | return this.dir = ""; |
| 1311 | } |
| 1312 | }.bind(nu()); |
| 1313 | |
| 1314 | /** |
| 1315 | Returns true if sqlite3.capi.sqlite3_wasmfs_opfs_dir() is a |
| 1316 | non-empty string and the given name starts with (that string + |
| 1317 | '/'), else returns false. |
| 1318 | */ |
| 1319 | capi.sqlite3_wasmfs_filename_is_persistent = function(name){ |
| 1320 | const p = capi.sqlite3_wasmfs_opfs_dir(); |
| 1321 | return (p && name) ? name.startsWith(p+'/') : false; |
| 1322 | }; |
| 1323 | |
| 1324 | /** |
| 1325 | Given an `sqlite3*`, an sqlite3_vfs name, and an optional db name |
| 1326 | (defaulting to "main"), returns a truthy value (see below) if |
| 1327 | that db uses that VFS, else returns false. If pDb is falsy then |
| 1328 | the 3rd argument is ignored and this function returns a truthy |
| 1329 | value if the default VFS name matches that of the 2nd argument. |
| 1330 | Results are undefined if pDb is truthy but refers to an invalid |
| 1331 | pointer. The 3rd argument specifies the database name of the |
| 1332 | given database connection to check, defaulting to the main db. |
| 1333 | |
| 1334 | The 2nd and 3rd arguments may either be a JS string or a WASM |
| 1335 | C-string. If the 2nd argument is a NULL WASM pointer, the default |
| 1336 | VFS is assumed. If the 3rd is a NULL WASM pointer, "main" is |
| 1337 | assumed. |
| 1338 | |
| 1339 | The truthy value it returns is a pointer to the `sqlite3_vfs` |
| 1340 | object. |
| 1341 | |
| 1342 | To permit safe use of this function from APIs which may be called |
| 1343 | via C (like SQL UDFs), this function does not throw: if bad |
| 1344 | arguments cause a conversion error when passing into wasm-space, |
| 1345 | false is returned. |
| 1346 | */ |
| 1347 | capi.sqlite3_js_db_uses_vfs = function(pDb,vfsName,dbName=0){ |
| 1348 | try{ |
| 1349 | const pK = capi.sqlite3_vfs_find(vfsName); |
| 1350 | if(!pK) return false; |
| 1351 | else if(!pDb){ |
| 1352 | return pK===capi.sqlite3_vfs_find(0) ? pK : false; |
| 1353 | }else{ |
| 1354 | return pK===capi.sqlite3_js_db_vfs(pDb,dbName) ? pK : false; |
| 1355 | } |
| 1356 | }catch(e){ |
| 1357 | /* Ignore - probably bad args to a wasm-bound function. */ |
| 1358 | return false; |
| 1359 | } |
| 1360 | }; |
| 1361 | |
| 1362 | /** |
| 1363 | Returns an array of the names of all currently-registered sqlite3 |
| 1364 | VFSes. |
| 1365 | */ |
| 1366 | capi.sqlite3_js_vfs_list = function(){ |
| 1367 | const rc = []; |
| 1368 | let pVfs = capi.sqlite3_vfs_find(wasm.ptr.null); |
| 1369 | while(pVfs){ |
| 1370 | const oVfs = new capi.sqlite3_vfs(pVfs); |
| 1371 | rc.push(wasm.cstrToJs(oVfs.$zName)); |
| 1372 | pVfs = oVfs.$pNext; |
| 1373 | oVfs.dispose(); |
| 1374 | } |
| 1375 | return rc; |
| 1376 | }; |
| 1377 | |
| 1378 | /** |
| 1379 | A convenience wrapper around sqlite3_serialize() which serializes |
| 1380 | the given `sqlite3*` pointer to a Uint8Array. The first argument |
| 1381 | may be either an `sqlite3*` or an sqlite3.oo1.DB instance. |
| 1382 | |
| 1383 | On success it returns a Uint8Array. If the schema is empty, an |
| 1384 | empty array is returned. |
| 1385 | |
| 1386 | `schema` is the schema to serialize. It may be a WASM C-string |
| 1387 | pointer or a JS string. If it is falsy, it defaults to `"main"`. |
| 1388 | |
| 1389 | On error it throws with a description of the problem. |
| 1390 | */ |
| 1391 | capi.sqlite3_js_db_export = function(pDb, schema=0){ |
| 1392 | pDb = wasm.xWrap.testConvertArg('sqlite3*', pDb); |
| 1393 | if(!pDb) toss3('Invalid sqlite3* argument.'); |
| 1394 | if(!wasm.bigIntEnabled) toss3('BigInt support is not enabled.'); |
| 1395 | const scope = wasm.scopedAllocPush(); |
| 1396 | let pOut; |
| 1397 | try{ |
| 1398 | const pSize = wasm.scopedAlloc(8/*i64*/ + wasm.ptr.size); |
| 1399 | const ppOut = wasm.ptr.add(pSize, 8); |
| 1400 | /** |
| 1401 | Maintenance reminder, since this cost a full hour of grief |
| 1402 | and confusion: if the order of pSize/ppOut are reversed in |
| 1403 | that memory block, fetching the value of pSize after the |
| 1404 | export reads a garbage size because it's not on an 8-byte |
| 1405 | memory boundary! |
| 1406 | */ |
| 1407 | const zSchema = schema |
| 1408 | ? (wasm.isPtr(schema) ? schema : wasm.scopedAllocCString(''+schema)) |
| 1409 | : wasm.ptr.null; |
| 1410 | let rc = wasm.exports.sqlite3__wasm_db_serialize( |
| 1411 | pDb, zSchema, ppOut, pSize, 0 |
| 1412 | ); |
| 1413 | if(rc){ |
| 1414 | toss3("Database serialization failed with code", |
| 1415 | sqlite3.capi.sqlite3_js_rc_str(rc)); |
| 1416 | } |
| 1417 | pOut = wasm.peekPtr(ppOut); |
| 1418 | const nOut = wasm.peek(pSize, 'i64'); |
| 1419 | rc = nOut |
| 1420 | ? wasm.heap8u().slice(Number(pOut), Number(pOut) + Number(nOut)) |
| 1421 | : new Uint8Array(); |
| 1422 | return rc; |
| 1423 | }finally{ |
| 1424 | if(pOut) wasm.exports.sqlite3_free(pOut); |
| 1425 | wasm.scopedAllocPop(scope); |
| 1426 | } |
| 1427 | }; |
| 1428 | |
| 1429 | /** |
| 1430 | Given a `sqlite3*` and a database name (JS string or WASM |
| 1431 | C-string pointer, which may be 0), returns a pointer to the |
| 1432 | sqlite3_vfs responsible for it. If the given db name is null/0, |
| 1433 | or not provided, then "main" is assumed. |
| 1434 | */ |
| 1435 | capi.sqlite3_js_db_vfs = |
| 1436 | (dbPointer, dbName=wasm.ptr.null)=>util.sqlite3__wasm_db_vfs(dbPointer, dbName); |
| 1437 | |
| 1438 | /** |
| 1439 | A thin wrapper around capi.sqlite3_aggregate_context() which |
| 1440 | behaves the same except that it throws a WasmAllocError if that |
| 1441 | function returns 0. As a special case, if n is falsy it does |
| 1442 | _not_ throw if that function returns 0. That special case is |
| 1443 | intended for use with xFinal() implementations. |
| 1444 | */ |
| 1445 | capi.sqlite3_js_aggregate_context = (pCtx, n)=>{ |
| 1446 | return capi.sqlite3_aggregate_context(pCtx, n) |
| 1447 | || (n ? WasmAllocError.toss("Cannot allocate",n, |
| 1448 | "bytes for sqlite3_aggregate_context()") |
| 1449 | : 0); |
| 1450 | }; |
| 1451 | |
| 1452 | /** |
| 1453 | If the current environment supports the POSIX file APIs, this routine |
| 1454 | creates (or overwrites) the given file using those APIs. This is |
| 1455 | primarily intended for use in Emscripten-based builds where the POSIX |
| 1456 | APIs are transparently proxied by an in-memory virtual filesystem. |
| 1457 | It may behave differently in other environments. |
| 1458 | |
| 1459 | The first argument must be either a JS string or WASM C-string |
| 1460 | holding the filename. This routine does _not_ create intermediary |
| 1461 | directories if the filename has a directory part. |
| 1462 | |
| 1463 | The 2nd argument may either a valid WASM memory pointer, an |
| 1464 | ArrayBuffer, or a Uint8Array. The 3rd must be the length, in |
| 1465 | bytes, of the data array to copy. If the 2nd argument is an |
| 1466 | ArrayBuffer or Uint8Array and the 3rd is not a positive integer |
| 1467 | then the 3rd defaults to the array's byteLength value. |
| 1468 | |
| 1469 | Results are undefined if data is a WASM pointer and dataLen is |
| 1470 | exceeds data's bounds. |
| 1471 | |
| 1472 | Throws if any arguments are invalid or if creating or writing to |
| 1473 | the file fails. |
| 1474 | |
| 1475 | Added in 3.43 as an alternative for the deprecated |
| 1476 | sqlite3_js_vfs_create_file(). |
| 1477 | */ |
| 1478 | capi.sqlite3_js_posix_create_file = function(filename, data, dataLen){ |
| 1479 | let pData; |
| 1480 | if(data && wasm.isPtr(data)){ |
| 1481 | pData = data; |
| 1482 | }else if(data instanceof ArrayBuffer || data instanceof Uint8Array){ |
| 1483 | pData = wasm.allocFromTypedArray(data); |
| 1484 | if(arguments.length<3 || !util.isInt32(dataLen) || dataLen<0){ |
| 1485 | dataLen = data.byteLength; |
| 1486 | } |
| 1487 | }else{ |
| 1488 | SQLite3Error.toss("Invalid 2nd argument for sqlite3_js_posix_create_file()."); |
| 1489 | } |
| 1490 | try{ |
| 1491 | if(!util.isInt32(dataLen) || dataLen<0){ |
| 1492 | SQLite3Error.toss("Invalid 3rd argument for sqlite3_js_posix_create_file()."); |
| 1493 | } |
| 1494 | const rc = util.sqlite3__wasm_posix_create_file(filename, pData, dataLen); |
| 1495 | if(rc) SQLite3Error.toss("Creation of file failed with sqlite3 result code", |
| 1496 | capi.sqlite3_js_rc_str(rc)); |
| 1497 | }finally{ |
| 1498 | if( pData && pData!==data ) wasm.dealloc(pData); |
| 1499 | } |
| 1500 | }; |
| 1501 | |
| 1502 | /** |
| 1503 | Deprecation warning: this function does not work properly in |
| 1504 | debug builds of sqlite3 because its out-of-scope use of the |
| 1505 | sqlite3_vfs API triggers assertions in the core library. That |
| 1506 | was unfortunately not discovered until 2023-08-11. This function |
| 1507 | is now deprecated. It should not be used in new code and should |
| 1508 | be removed from existing code. |
| 1509 | |
| 1510 | Alternative options: |
| 1511 | |
| 1512 | - The "unix" VFS and its variants can get equivalent |
| 1513 | functionality with sqlite3_js_posix_create_file(). |
| 1514 | |
| 1515 | - OPFS: use either sqlite3.oo1.OpfsDb.importDb(), for the "opfs" |
| 1516 | VFS, or the importDb() method of the PoolUtil object provided |
| 1517 | by the "opfs-sahpool" OPFS (noting that its VFS name may differ |
| 1518 | depending on client-side configuration). We cannot proxy those |
| 1519 | from here because the former is necessarily asynchronous and |
| 1520 | the latter requires information not available to this function. |
| 1521 | |
| 1522 | Historical (deprecated) behaviour: |
| 1523 | |
| 1524 | Creates a file using the storage appropriate for the given |
| 1525 | sqlite3_vfs. The first argument may be a VFS name (JS string |
| 1526 | only, NOT a WASM C-string), WASM-managed `sqlite3_vfs*`, or |
| 1527 | a capi.sqlite3_vfs instance. Pass 0 (a NULL pointer) to use the |
| 1528 | default VFS. If passed a string which does not resolve using |
| 1529 | sqlite3_vfs_find(), an exception is thrown. (Note that a WASM |
| 1530 | C-string is not accepted because it is impossible to |
| 1531 | distinguish from a C-level `sqlite3_vfs*`.) |
| 1532 | |
| 1533 | The second argument, the filename, must be a JS or WASM C-string. |
| 1534 | |
| 1535 | The 3rd may either be falsy, a valid WASM memory pointer, an |
| 1536 | ArrayBuffer, or a Uint8Array. The 4th must be the length, in |
| 1537 | bytes, of the data array to copy. If the 3rd argument is an |
| 1538 | ArrayBuffer or Uint8Array and the 4th is not a positive integer |
| 1539 | then the 4th defaults to the array's byteLength value. |
| 1540 | |
| 1541 | If data is falsy then a file is created with dataLen bytes filled |
| 1542 | with uninitialized data (whatever truncate() leaves there). If |
| 1543 | data is not falsy then a file is created or truncated and it is |
| 1544 | filled with the first dataLen bytes of the data source. |
| 1545 | |
| 1546 | Throws if any arguments are invalid or if creating or writing to |
| 1547 | the file fails. |
| 1548 | |
| 1549 | Note that most VFSes do _not_ automatically create directory |
| 1550 | parts of filenames, nor do all VFSes have a concept of |
| 1551 | directories. If the given filename is not valid for the given |
| 1552 | VFS, an exception will be thrown. This function exists primarily |
| 1553 | to assist in implementing file-upload capability, with the caveat |
| 1554 | that clients must have some idea of the VFS into which they want |
| 1555 | to upload and that VFS must support the operation. |
| 1556 | |
| 1557 | VFS-specific notes: |
| 1558 | |
| 1559 | - "memdb": results are undefined. |
| 1560 | |
| 1561 | - "kvvfs": will fail with an I/O error due to strict internal |
| 1562 | requirements of that VFS's xTruncate(). |
| 1563 | |
| 1564 | - "unix" and related: will use the WASM build's equivalent of the |
| 1565 | POSIX I/O APIs. This will work so long as neither a specific |
| 1566 | VFS nor the WASM environment imposes requirements which break |
| 1567 | it. (Much later: it turns out that debug builds of the library |
| 1568 | impose such requirements, in that they assert() that dataLen is |
| 1569 | an even multiple of a valid db page size.) |
| 1570 | |
| 1571 | - "opfs": uses OPFS storage and creates directory parts of the |
| 1572 | filename. It can only be used to import an SQLite3 database |
| 1573 | file and will fail if given anything else. |
| 1574 | */ |
| 1575 | capi.sqlite3_js_vfs_create_file = function(vfs, filename, data, dataLen){ |
| 1576 | config.warn("sqlite3_js_vfs_create_file() is deprecated and", |
| 1577 | "should be avoided because it can lead to C-level crashes.", |
| 1578 | "See its documentation for alternatives."); |
| 1579 | let pData; |
| 1580 | if(data){ |
| 1581 | if( wasm.isPtr(data) ){ |
| 1582 | pData = data; |
| 1583 | }else{ |
| 1584 | if( data instanceof ArrayBuffer ){ |
| 1585 | data = new Uint8Array(data); |
| 1586 | } |
| 1587 | if( data instanceof Uint8Array ){ |
| 1588 | pData = wasm.allocFromTypedArray(data); |
| 1589 | if(arguments.length<4 || !util.isInt32(dataLen) || dataLen<0){ |
| 1590 | dataLen = data.byteLength; |
| 1591 | } |
| 1592 | }else{ |
| 1593 | SQLite3Error.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file()."); |
| 1594 | } |
| 1595 | } |
| 1596 | }else{ |
| 1597 | pData = 0; |
| 1598 | } |
| 1599 | if(!util.isInt32(dataLen) || dataLen<0){ |
| 1600 | if( pData && pData!==data ) wasm.dealloc(pData); |
| 1601 | SQLite3Error.toss("Invalid 4th argument for sqlite3_js_vfs_create_file()."); |
| 1602 | } |
| 1603 | try{ |
| 1604 | const rc = util.sqlite3__wasm_vfs_create_file(vfs, filename, pData, dataLen); |
| 1605 | if(rc) SQLite3Error.toss("Creation of file failed with sqlite3 result code", |
| 1606 | capi.sqlite3_js_rc_str(rc)); |
| 1607 | }finally{ |
| 1608 | if( pData && pData!==data ) wasm.dealloc(pData); |
| 1609 | } |
| 1610 | }; |
| 1611 | |
| 1612 | /** |
| 1613 | Converts SQL input from a variety of convenient formats |
| 1614 | to plain strings. |
| 1615 | |
| 1616 | If v is a string, it is returned as-is. If it is-a Array, its |
| 1617 | join("") result is returned. If is is a Uint8Array, Int8Array, |
| 1618 | or ArrayBuffer, it is assumed to hold UTF-8-encoded text and is |
| 1619 | decoded to a string. If it looks like a WASM pointer, |
| 1620 | wasm.cstrToJs(sql) is returned. Else undefined is returned. |
| 1621 | |
| 1622 | Added in 3.44 |
| 1623 | */ |
| 1624 | capi.sqlite3_js_sql_to_string = (sql)=>{ |
| 1625 | if('string' === typeof sql){ |
| 1626 | return sql; |
| 1627 | } |
| 1628 | const x = flexibleString(v); |
| 1629 | return x===v ? undefined : x; |
| 1630 | } |
| 1631 | |
| 1632 | /** |
| 1633 | Wraps all known variants of the C-side variadic |
| 1634 | sqlite3_db_config(). |
| 1635 | |
| 1636 | Full docs: https://sqlite.org/c3ref/db_config.html |
| 1637 | |
| 1638 | Returns capi.SQLITE_MISUSE if op is not a valid operation ID. |
| 1639 | |
| 1640 | The variants which take `(int, int*)` arguments treat a |
| 1641 | missing or falsy pointer argument as 0. |
| 1642 | */ |
| 1643 | capi.sqlite3_db_config = function(pDb, op, ...args){ |
| 1644 | switch(op){ |
| 1645 | case capi.SQLITE_DBCONFIG_ENABLE_FKEY: |
| 1646 | case capi.SQLITE_DBCONFIG_ENABLE_TRIGGER: |
| 1647 | case capi.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: |
| 1648 | case capi.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: |
| 1649 | case capi.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: |
| 1650 | case capi.SQLITE_DBCONFIG_ENABLE_QPSG: |
| 1651 | case capi.SQLITE_DBCONFIG_TRIGGER_EQP: |
| 1652 | case capi.SQLITE_DBCONFIG_RESET_DATABASE: |
| 1653 | case capi.SQLITE_DBCONFIG_DEFENSIVE: |
| 1654 | case capi.SQLITE_DBCONFIG_WRITABLE_SCHEMA: |
| 1655 | case capi.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: |
| 1656 | case capi.SQLITE_DBCONFIG_DQS_DML: |
| 1657 | case capi.SQLITE_DBCONFIG_DQS_DDL: |
| 1658 | case capi.SQLITE_DBCONFIG_ENABLE_VIEW: |
| 1659 | case capi.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: |
| 1660 | case capi.SQLITE_DBCONFIG_TRUSTED_SCHEMA: |
| 1661 | case capi.SQLITE_DBCONFIG_STMT_SCANSTATUS: |
| 1662 | case capi.SQLITE_DBCONFIG_REVERSE_SCANORDER: |
| 1663 | case capi.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE: |
| 1664 | case capi.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE: |
| 1665 | case capi.SQLITE_DBCONFIG_ENABLE_COMMENTS: |
| 1666 | case capi.SQLITE_DBCONFIG_FP_DIGITS: |
| 1667 | if( !this.ip ){ |
| 1668 | this.ip = wasm.xWrap('sqlite3__wasm_db_config_ip','int', |
| 1669 | ['sqlite3*', 'int', 'int', '*']); |
| 1670 | } |
| 1671 | return this.ip(pDb, op, args[0], args[1] || 0); |
| 1672 | case capi.SQLITE_DBCONFIG_LOOKASIDE: |
| 1673 | if( !this.pii ){ |
| 1674 | this.pii = wasm.xWrap('sqlite3__wasm_db_config_pii', 'int', |
| 1675 | ['sqlite3*', 'int', '*', 'int', 'int']); |
| 1676 | } |
| 1677 | return this.pii(pDb, op, args[0], args[1], args[2]); |
| 1678 | case capi.SQLITE_DBCONFIG_MAINDBNAME: |
| 1679 | if(!this.s){ |
| 1680 | this.s = wasm.xWrap('sqlite3__wasm_db_config_s','int', |
| 1681 | ['sqlite3*', 'int', 'string:static'] |
| 1682 | /* MAINDBNAME requires a static string */); |
| 1683 | } |
| 1684 | return this.s(pDb, op, args[0]); |
| 1685 | default: |
| 1686 | return capi.SQLITE_MISUSE; |
| 1687 | } |
| 1688 | }.bind(nu()); |
| 1689 | |
| 1690 | /** |
| 1691 | Given a (sqlite3_value*), this function attempts to convert it |
| 1692 | to an equivalent JS value with as much fidelity as feasible and |
| 1693 | return it. |
| 1694 | |
| 1695 | By default it throws if it cannot determine any sensible |
| 1696 | conversion. If passed a falsy second argument, it instead returns |
| 1697 | `undefined` if no suitable conversion is found. Note that there |
| 1698 | is no conversion from SQL to JS which results in the `undefined` |
| 1699 | value, so `undefined` has an unambiguous meaning here. It will |
| 1700 | always throw a WasmAllocError if allocating memory for a |
| 1701 | conversion fails. |
| 1702 | |
| 1703 | Caveats: |
| 1704 | |
| 1705 | - It does not support sqlite3_value_to_pointer() conversions |
| 1706 | because those require a type name string which this function |
| 1707 | does not have and cannot sensibly be given at the level of the |
| 1708 | API where this is used (e.g. automatically converting UDF |
| 1709 | arguments). Clients using sqlite3_value_to_pointer(), and its |
| 1710 | related APIs, will need to manage those themselves. |
| 1711 | */ |
| 1712 | capi.sqlite3_value_to_js = function(pVal,throwIfCannotConvert=true){ |
| 1713 | let arg; |
| 1714 | const valType = capi.sqlite3_value_type(pVal); |
| 1715 | switch(valType){ |
| 1716 | case capi.SQLITE_INTEGER: |
| 1717 | if(wasm.bigIntEnabled){ |
| 1718 | arg = capi.sqlite3_value_int64(pVal); |
| 1719 | if(util.bigIntFitsDouble(arg)) arg = Number(arg); |
| 1720 | } |
| 1721 | else arg = capi.sqlite3_value_double(pVal)/*yes, double, for larger integers*/; |
| 1722 | break; |
| 1723 | case capi.SQLITE_FLOAT: |
| 1724 | arg = capi.sqlite3_value_double(pVal); |
| 1725 | break; |
| 1726 | case capi.SQLITE_TEXT: |
| 1727 | arg = capi.sqlite3_value_text(pVal); |
| 1728 | break; |
| 1729 | case capi.SQLITE_BLOB:{ |
| 1730 | const n = capi.sqlite3_value_bytes(pVal); |
| 1731 | const pBlob = capi.sqlite3_value_blob(pVal); |
| 1732 | if(n && !pBlob) sqlite3.WasmAllocError.toss( |
| 1733 | "Cannot allocate memory for blob argument of",n,"byte(s)" |
| 1734 | ); |
| 1735 | arg = n |
| 1736 | ? wasm.heap8u().slice(Number(pBlob), Number(pBlob) + Number(n)) |
| 1737 | : null; |
| 1738 | break; |
| 1739 | } |
| 1740 | case capi.SQLITE_NULL: |
| 1741 | arg = null; break; |
| 1742 | default: |
| 1743 | if(throwIfCannotConvert){ |
| 1744 | toss3(capi.SQLITE_MISMATCH, |
| 1745 | "Unhandled sqlite3_value_type():",valType); |
| 1746 | } |
| 1747 | arg = undefined; |
| 1748 | } |
| 1749 | return arg; |
| 1750 | }; |
| 1751 | |
| 1752 | /** |
| 1753 | Requires a C-style array of `sqlite3_value*` objects and the |
| 1754 | number of entries in that array. Returns a JS array containing |
| 1755 | the results of passing each C array entry to |
| 1756 | sqlite3_value_to_js(). The 3rd argument to this function is |
| 1757 | passed on as the 2nd argument to that one. |
| 1758 | */ |
| 1759 | capi.sqlite3_values_to_js = function(argc,pArgv,throwIfCannotConvert=true){ |
| 1760 | let i; |
| 1761 | const tgt = []; |
| 1762 | for(i = 0; i < argc; ++i){ |
| 1763 | /** |
| 1764 | Curiously: despite ostensibly requiring 8-byte |
| 1765 | alignment, the pArgv array is parcelled into chunks of |
| 1766 | 4 bytes (1 pointer each). The values those point to |
| 1767 | have 8-byte alignment but the individual argv entries |
| 1768 | do not. |
| 1769 | */ |
| 1770 | tgt.push(capi.sqlite3_value_to_js( |
| 1771 | wasm.peekPtr(wasm.ptr.add(pArgv, wasm.ptr.size * i)), |
| 1772 | throwIfCannotConvert |
| 1773 | )); |
| 1774 | } |
| 1775 | return tgt; |
| 1776 | }; |
| 1777 | |
| 1778 | /** |
| 1779 | Calls either sqlite3_result_error_nomem(), if e is-a |
| 1780 | WasmAllocError, or sqlite3_result_error(). In the latter case, |
| 1781 | the second argument is coerced to a string to create the error |
| 1782 | message. |
| 1783 | |
| 1784 | The first argument is a (sqlite3_context*). Returns void. |
| 1785 | Does not throw. |
| 1786 | */ |
| 1787 | capi.sqlite3_result_error_js = function(pCtx,e){ |
| 1788 | if(e instanceof WasmAllocError){ |
| 1789 | capi.sqlite3_result_error_nomem(pCtx); |
| 1790 | }else{ |
| 1791 | /* Maintenance reminder: ''+e, rather than e.message, |
| 1792 | will prefix e.message with e.name, so it includes |
| 1793 | the exception's type name in the result. */; |
| 1794 | capi.sqlite3_result_error(pCtx, ''+e, -1); |
| 1795 | } |
| 1796 | }; |
| 1797 | |
| 1798 | /** |
| 1799 | This function passes its 2nd argument to one of the |
| 1800 | sqlite3_result_xyz() routines, depending on the type of that |
| 1801 | argument: |
| 1802 | |
| 1803 | - If (val instanceof Error), this function passes it to |
| 1804 | sqlite3_result_error_js(). |
| 1805 | - `null`: `sqlite3_result_null()` |
| 1806 | - `boolean`: `sqlite3_result_int()` with a value of 0 or 1. |
| 1807 | - `number`: `sqlite3_result_int()`, `sqlite3_result_int64()`, or |
| 1808 | `sqlite3_result_double()`, depending on the range of the number |
| 1809 | and whether or not int64 support is enabled. |
| 1810 | - `bigint`: similar to `number` but will trigger an error if the |
| 1811 | value is too big to store in an int64. |
| 1812 | - `string`: `sqlite3_result_text()` |
| 1813 | - Uint8Array or Int8Array or ArrayBuffer: `sqlite3_result_blob()` |
| 1814 | - `undefined`: is a no-op provided to simplify certain use cases. |
| 1815 | |
| 1816 | Anything else triggers `sqlite3_result_error()` with a |
| 1817 | description of the problem. |
| 1818 | |
| 1819 | The first argument to this function is a `(sqlite3_context*)`. |
| 1820 | Returns void. Does not throw. |
| 1821 | */ |
| 1822 | capi.sqlite3_result_js = function(pCtx,val){ |
| 1823 | if(val instanceof Error){ |
| 1824 | capi.sqlite3_result_error_js(pCtx, val); |
| 1825 | return; |
| 1826 | } |
| 1827 | try{ |
| 1828 | switch(typeof val) { |
| 1829 | case 'undefined': |
| 1830 | /* This is a no-op. This routine originated in the create_function() |
| 1831 | family of APIs and in that context, passing in undefined indicated |
| 1832 | that the caller was responsible for calling sqlite3_result_xxx() |
| 1833 | (if needed). */ |
| 1834 | break; |
| 1835 | case 'boolean': |
| 1836 | capi.sqlite3_result_int(pCtx, val ? 1 : 0); |
| 1837 | break; |
| 1838 | case 'bigint': |
| 1839 | if(util.bigIntFits32(val)){ |
| 1840 | capi.sqlite3_result_int(pCtx, Number(val)); |
| 1841 | }else if(util.bigIntFitsDouble(val)){ |
| 1842 | capi.sqlite3_result_double(pCtx, Number(val)); |
| 1843 | }else if(wasm.bigIntEnabled){ |
| 1844 | if(util.bigIntFits64(val)) capi.sqlite3_result_int64(pCtx, val); |
| 1845 | else toss3("BigInt value",val.toString(),"is too BigInt for int64."); |
| 1846 | }else{ |
| 1847 | toss3("BigInt value",val.toString(),"is too BigInt."); |
| 1848 | } |
| 1849 | break; |
| 1850 | case 'number': { |
| 1851 | let f; |
| 1852 | if(util.isInt32(val)){ |
| 1853 | f = capi.sqlite3_result_int; |
| 1854 | }else if(wasm.bigIntEnabled |
| 1855 | && Number.isInteger(val) |
| 1856 | && util.bigIntFits64(BigInt(val))){ |
| 1857 | f = capi.sqlite3_result_int64; |
| 1858 | }else{ |
| 1859 | f = capi.sqlite3_result_double; |
| 1860 | } |
| 1861 | f(pCtx, val); |
| 1862 | break; |
| 1863 | } |
| 1864 | case 'string': { |
| 1865 | const [p, n] = wasm.allocCString(val,true); |
| 1866 | capi.sqlite3_result_text(pCtx, p, n, capi.SQLITE_WASM_DEALLOC); |
| 1867 | break; |
| 1868 | } |
| 1869 | case 'object': |
| 1870 | if(null===val/*yes, typeof null === 'object'*/) { |
| 1871 | capi.sqlite3_result_null(pCtx); |
| 1872 | break; |
| 1873 | }else if(util.isBindableTypedArray(val)){ |
| 1874 | const pBlob = wasm.allocFromTypedArray(val); |
| 1875 | capi.sqlite3_result_blob( |
| 1876 | pCtx, pBlob, val.byteLength, |
| 1877 | capi.SQLITE_WASM_DEALLOC |
| 1878 | ); |
| 1879 | break; |
| 1880 | } |
| 1881 | // else fall through |
| 1882 | default: |
| 1883 | toss3("Don't not how to handle this UDF result value:",(typeof val), val); |
| 1884 | } |
| 1885 | }catch(e){ |
| 1886 | capi.sqlite3_result_error_js(pCtx, e); |
| 1887 | } |
| 1888 | }; |
| 1889 | |
| 1890 | /** |
| 1891 | Returns the result sqlite3_column_value(pStmt,iCol) passed to |
| 1892 | sqlite3_value_to_js(). The 3rd argument of this function is |
| 1893 | ignored by this function except to pass it on as the second |
| 1894 | argument of sqlite3_value_to_js(). If the sqlite3_column_value() |
| 1895 | returns NULL (e.g. because the column index is out of range), |
| 1896 | this function returns `undefined`, regardless of the 3rd |
| 1897 | argument. If the 3rd argument is falsy and conversion fails, |
| 1898 | `undefined` will be returned. |
| 1899 | |
| 1900 | Note that sqlite3_column_value() returns an "unprotected" value |
| 1901 | object, but in a single-threaded environment (like this one) |
| 1902 | there is no distinction between protected and unprotected values. |
| 1903 | */ |
| 1904 | capi.sqlite3_column_js = function(pStmt, iCol, throwIfCannotConvert=true){ |
| 1905 | const v = capi.sqlite3_column_value(pStmt, iCol); |
| 1906 | return (0===v) ? undefined : capi.sqlite3_value_to_js(v, throwIfCannotConvert); |
| 1907 | }; |
| 1908 | |
| 1909 | if( true ){ /* changeset/preupdate additions... */ |
| 1910 | /** |
| 1911 | Internal impl of sqlite3_preupdate_new/old_js() and |
| 1912 | sqlite3changeset_new/old_js(). |
| 1913 | */ |
| 1914 | const __newOldValue = function(pObj, iCol, impl){ |
| 1915 | impl = capi[impl]; |
| 1916 | if(!this.ptr) this.ptr = wasm.allocPtr(); |
| 1917 | else wasm.pokePtr(this.ptr, 0); |
| 1918 | const rc = impl(pObj, iCol, this.ptr); |
| 1919 | if(rc) return SQLite3Error.toss(rc,arguments[2]+"() failed with code "+rc); |
| 1920 | const pv = wasm.peekPtr(this.ptr); |
| 1921 | return pv ? capi.sqlite3_value_to_js( pv, true ) : undefined; |
| 1922 | }.bind(nu()); |
| 1923 | |
| 1924 | /** |
| 1925 | A wrapper around sqlite3_preupdate_new() which fetches the |
| 1926 | sqlite3_value at the given index and returns the result of |
| 1927 | passing it to sqlite3_value_to_js(). Throws on error. |
| 1928 | */ |
| 1929 | capi.sqlite3_preupdate_new_js = |
| 1930 | (pDb, iCol)=>__newOldValue(pDb, iCol, 'sqlite3_preupdate_new'); |
| 1931 | |
| 1932 | /** |
| 1933 | The sqlite3_preupdate_old() counterpart of |
| 1934 | sqlite3_preupdate_new_js(), with an identical interface. |
| 1935 | */ |
| 1936 | capi.sqlite3_preupdate_old_js = |
| 1937 | (pDb, iCol)=>__newOldValue(pDb, iCol, 'sqlite3_preupdate_old'); |
| 1938 | |
| 1939 | /** |
| 1940 | A wrapper around sqlite3changeset_new() which fetches the |
| 1941 | sqlite3_value at the given index and returns the result of |
| 1942 | passing it to sqlite3_value_to_js(). Throws on error. |
| 1943 | |
| 1944 | If sqlite3changeset_new() succeeds but has no value to report, |
| 1945 | this function returns the undefined value, noting that |
| 1946 | undefined is not a valid conversion from an `sqlite3_value`, so |
| 1947 | is unambiguous. |
| 1948 | */ |
| 1949 | capi.sqlite3changeset_new_js = |
| 1950 | (pChangesetIter, iCol) => __newOldValue(pChangesetIter, iCol, |
| 1951 | 'sqlite3changeset_new'); |
| 1952 | |
| 1953 | /** |
| 1954 | The sqlite3changeset_old() counterpart of |
| 1955 | sqlite3changeset_new_js(), with an identical interface. |
| 1956 | */ |
| 1957 | capi.sqlite3changeset_old_js = |
| 1958 | (pChangesetIter, iCol)=>__newOldValue(pChangesetIter, iCol, |
| 1959 | 'sqlite3changeset_old'); |
| 1960 | }/*changeset/preupdate additions*/ |
| 1961 | |
| 1962 | /** |
| 1963 | sqlite3_js_retry_busy(maxTimes,callback[,beforeRetry]) |
| 1964 | |
| 1965 | Calls the given _synchronous_ callback function. If that function |
| 1966 | returns sqlite3.capi.SQLITE_BUSY _or_ throws an SQLite3Error |
| 1967 | with a resultCode property of that value then it will suppress |
| 1968 | that error and try again, up to the given maximum number of |
| 1969 | times. If the callback returns any other value than that, |
| 1970 | it is returned. If the maximum number of retries has been |
| 1971 | reached, an SQLite3Error with a resultCode value of |
| 1972 | sqlite3.capi.SQLITE_BUSY is thrown. If the callback throws any |
| 1973 | exception other than the aforementioned BUSY exception, it is |
| 1974 | propagated. If it throws a BUSY exception on its final attempt, |
| 1975 | that is propagated as well. |
| 1976 | |
| 1977 | If the beforeRetry argument is given, it must be a _synchronous_ |
| 1978 | function. It is called immediately before each retry of the |
| 1979 | callback (not for the initial call), passed the attempt number |
| 1980 | (so it starts with 2, not 1). If it throws, the exception is |
| 1981 | handled as described above. Its result value is ignored. |
| 1982 | |
| 1983 | To effectively retry "forever", pass a huge maxTimes value such |
| 1984 | as Number.MAX_SAFE_INTEGER, with the caveat that there is no |
| 1985 | recovery from that unless the beforeRetry() can figure out when |
| 1986 | to throw. |
| 1987 | |
| 1988 | Added in 3.53.0. |
| 1989 | |
| 1990 | TODO?: an async variant of this. |
| 1991 | */ |
| 1992 | capi.sqlite3_js_retry_busy = function(maxTimes, callback, beforeRetry){ |
| 1993 | for(let n = 1; n <= maxTimes; ++n){ |
| 1994 | try{ |
| 1995 | if( beforeRetry && n>1 ) beforeRetry(n); |
| 1996 | const rc = callback(); |
| 1997 | if( capi.SQLITE_BUSY===rc ){ |
| 1998 | if( n===maxTimes ){ |
| 1999 | throw new SQLite3Error(rc, [ |
| 2000 | "sqlite3_js_retry_busy() max retry attempts (", |
| 2001 | maxTimes, |
| 2002 | ") reached." |
| 2003 | ].join('')); |
| 2004 | } |
| 2005 | continue; |
| 2006 | } |
| 2007 | return rc; |
| 2008 | }catch(e){ |
| 2009 | if( n<maxTimes |
| 2010 | && (e instanceof SQLite3Error) |
| 2011 | && e.resultCode===capi.SQLITE_BUSY ){ |
| 2012 | continue; |
| 2013 | } |
| 2014 | throw e; |
| 2015 | } |
| 2016 | } |
| 2017 | }; |
| 2018 | |
| 2019 | /* The remainder of the API will be set up in later steps. */ |
| 2020 | const sqlite3 = { |
| 2021 | WasmAllocError: WasmAllocError, |
| 2022 | SQLite3Error: SQLite3Error, |
| 2023 | capi, |
| 2024 | util /* internal: will get removed after library init */, |
| 2025 | wasm, |
| 2026 | config, |
| 2027 | /** |
| 2028 | Holds the version info of the sqlite3 source tree from which |
| 2029 | the generated sqlite3-api.js gets built. Its version may well |
| 2030 | differ from that reported by sqlite3_libversion(), but that |
| 2031 | should be considered a source file mismatch, as the JS and WASM |
| 2032 | files are intended to be built and distributed together. |
| 2033 | |
| 2034 | This object is initially a placeholder which gets replaced by a |
| 2035 | build-generated object. |
| 2036 | */ |
| 2037 | version: nu(), |
| 2038 | |
| 2039 | /** |
| 2040 | The library reserves the 'client' property for client-side use |
| 2041 | and promises to never define a property with this name nor to |
| 2042 | ever rely on specific contents of it. It makes no such guarantees |
| 2043 | for other properties. |
| 2044 | */ |
| 2045 | client: undefined, |
| 2046 | |
| 2047 | /** |
| 2048 | This function is not part of the public interface, but a |
| 2049 | piece of internal bootstrapping infrastructure. |
| 2050 | |
| 2051 | Performs any optional asynchronous library-level initialization |
| 2052 | which might be required. This function returns a Promise which |
| 2053 | resolves to the sqlite3 namespace object. Any error in the |
| 2054 | async init will be fatal to the init as a whole, but init |
| 2055 | routines are themselves welcome to install dummy catch() |
| 2056 | handlers which are not fatal if their failure should be |
| 2057 | considered non-fatal. |
| 2058 | |
| 2059 | Ideally this function is called as part of the Promise chain |
| 2060 | which handles the loading and bootstrapping of the API. If not |
| 2061 | then it must be called by client-level code, which must not use |
| 2062 | the library until the returned Promise resolves. |
| 2063 | |
| 2064 | If called multiple times it will return the same Promise on |
| 2065 | subsequent calls. The current build setup precludes that |
| 2066 | possibility, so it's only a hypothetical problem if/when this |
| 2067 | function ever needs to be invoked by clients. |
| 2068 | |
| 2069 | In Emscripten-based builds, this function is called |
| 2070 | automatically and deleted from this object. |
| 2071 | */ |
| 2072 | asyncPostInit: async function ff(){ |
| 2073 | if(ff.isReady instanceof Promise) return ff.isReady; |
| 2074 | let lia = this.initializersAsync; |
| 2075 | delete this.initializersAsync; |
| 2076 | const postInit = async ()=>{ |
| 2077 | if(!sqlite3.__isUnderTest){ |
| 2078 | /* Delete references to internal-only APIs which are used by |
| 2079 | some initializers. Retain them when running in test mode |
| 2080 | so that we can add tests for them. */ |
| 2081 | delete sqlite3.util; |
| 2082 | delete sqlite3.StructBinder; |
| 2083 | delete sqlite3.opfs; |
| 2084 | } |
| 2085 | return sqlite3; |
| 2086 | }; |
| 2087 | const catcher = (e)=>{ |
| 2088 | config.error("an async sqlite3 initializer failed:",e); |
| 2089 | throw e; |
| 2090 | }; |
| 2091 | if(!lia || !lia.length){ |
| 2092 | return ff.isReady = postInit().catch(catcher); |
| 2093 | } |
| 2094 | lia = lia.map((f)=>{ |
| 2095 | return (f instanceof Function) ? async x=>f(sqlite3) : f; |
| 2096 | }); |
| 2097 | lia.push(postInit); |
| 2098 | let p = Promise.resolve(sqlite3); |
| 2099 | while(lia.length) p = p.then(lia.shift()); |
| 2100 | return ff.isReady = p.catch(catcher); |
| 2101 | }.bind(sqlite3ApiBootstrap), |
| 2102 | /** |
| 2103 | scriptInfo holds information about the currenty-loading script |
| 2104 | so that we can locate the WASM file if it's somewhere other |
| 2105 | than the build-time-defined directory. It ideally gets injected |
| 2106 | into this object by the infrastructure which assembles the |
| 2107 | JS/WASM module. It contains state which must be collected |
| 2108 | before sqlite3ApiBootstrap() can be declared. It is not |
| 2109 | necessarily available to any sqlite3ApiBootstrap.initializers |
| 2110 | but "should" be in place (if it's added at all) by the time |
| 2111 | that sqlite3ApiBootstrap.initializersAsync is processed. |
| 2112 | |
| 2113 | This state is not part of the public API, only intended for use |
| 2114 | with the sqlite3 API bootstrapping and wasm-loading process. |
| 2115 | */ |
| 2116 | scriptInfo: undefined |
| 2117 | }; |
| 2118 | if( 'undefined'!==typeof sqlite3IsUnderTest/* from post-js-header.js */ ){ |
| 2119 | sqlite3.__isUnderTest = !!sqlite3IsUnderTest; |
| 2120 | } |
| 2121 | try{ |
| 2122 | sqlite3ApiBootstrap.initializers.forEach((f)=>{ |
| 2123 | f(sqlite3); |
| 2124 | }); |
| 2125 | }catch(e){ |
| 2126 | /* If we don't report this here, it can get completely swallowed |
| 2127 | up and disappear into the abyss of Promises and Workers. */ |
| 2128 | console.error("sqlite3 bootstrap initializer threw:",e); |
| 2129 | throw e; |
| 2130 | } |
| 2131 | delete sqlite3ApiBootstrap.initializers; |
| 2132 | sqlite3ApiBootstrap.sqlite3 = sqlite3; |
| 2133 | if( 'undefined'!==typeof sqlite3InitScriptInfo/* from post-js-header.js */ ){ |
| 2134 | sqlite3InitScriptInfo.debugModule( |
| 2135 | "sqlite3ApiBootstrap() complete", sqlite3 |
| 2136 | ); |
| 2137 | sqlite3.scriptInfo |
| 2138 | /* Used by some async init code. As of 2025-11-15 this is still |
| 2139 | in use by the OPFS VFS for locating its worker. In non-Emscripten |
| 2140 | builds, this would need to be injected in somewhere to get |
| 2141 | that VFS loading. */ = sqlite3InitScriptInfo; |
| 2142 | } |
| 2143 | if( sqlite3.__isUnderTest ){ |
| 2144 | if( 'undefined'!==typeof EmscriptenModule ){ |
| 2145 | sqlite3.config.emscripten = EmscriptenModule; |
| 2146 | } |
| 2147 | /* |
| 2148 | The problem with exposing these pieces (in non-testing runs) via |
| 2149 | sqlite3.wasm is that it exposes non-SQLite pieces to the |
| 2150 | clients, who may come to expect it to remain. _We_ only have |
| 2151 | these data because we've overridden Emscripten's wasm file |
| 2152 | loader, and if we lose that capability for some reason then |
| 2153 | we'll lose access to this metadata. |
| 2154 | |
| 2155 | These data are interesting for exploring how the wasm/JS pieces |
| 2156 | connect, e.g. for exploring exactly what Emscripten imports into |
| 2157 | WASM from its JS glue, but it's not SQLite-related and is not |
| 2158 | required for the library to work. |
| 2159 | */ |
| 2160 | const iw = sqlite3.scriptInfo?.instantiateWasm; |
| 2161 | if( iw ){ |
| 2162 | /* Metadata injected by the custom Module.instantiateWasm() |
| 2163 | in pre-js.c-pp.js. */ |
| 2164 | sqlite3.wasm.module = iw.module; |
| 2165 | sqlite3.wasm.instance = iw.instance; |
| 2166 | sqlite3.wasm.imports = iw.imports; |
| 2167 | } |
| 2168 | } |
| 2169 | |
| 2170 | /** |
| 2171 | Eliminate any confusion about whether these config objects may |
| 2172 | be used after library initialization by eliminating the outward-facing |
| 2173 | objects... |
| 2174 | */ |
| 2175 | delete globalThis.sqlite3ApiConfig; |
| 2176 | delete sqlite3ApiBootstrap.defaultConfig; |
| 2177 | return sqlite3.asyncPostInit().then((s)=>{ |
| 2178 | if( 'undefined'!==typeof sqlite3InitScriptInfo/* from post-js-header.js */ ){ |
| 2179 | sqlite3InitScriptInfo.debugModule( |
| 2180 | "sqlite3.asyncPostInit() complete", s |
| 2181 | ); |
| 2182 | } |
| 2183 | delete s.asyncPostInit; |
| 2184 | delete s.scriptInfo; |
| 2185 | delete s.emscripten; |
| 2186 | return s; |
| 2187 | }); |
| 2188 | }/*sqlite3ApiBootstrap()*/; |
| 2189 | |
| 2190 | /** |
| 2191 | sqlite3ApiBootstrap.initializers is an internal detail |
| 2192 | used by the various pieces of the sqlite3 API's amalgamation |
| 2193 | process. It must not be modified by client code except when plugging |
| 2194 | such code into the amalgamation process. |
| 2195 | |
| 2196 | Each component of the amalgamation is expected to append a function |
| 2197 | to this array. When sqlite3ApiBootstrap() is called for the first |
| 2198 | time, each such function will be called (in their appended order) |
| 2199 | and passed the sqlite3 namespace object, into which they can install |
| 2200 | their features. At the end of that process, this array is deleted. |
| 2201 | |
| 2202 | The order of insertion into this array is significant for |
| 2203 | some pieces. e.g. sqlite3.capi and sqlite3.wasm cannot be fully |
| 2204 | utilized until the whwasmutil.js part is plugged in via |
| 2205 | sqlite3-api-glue.js. |
| 2206 | */ |
| 2207 | sqlite3ApiBootstrap.initializers = []; |
| 2208 | |
| 2209 | /** |
| 2210 | sqlite3ApiBootstrap.initializersAsync is an internal detail |
| 2211 | used by the sqlite3 API's amalgamation process. It must not be |
| 2212 | modified by client code except when plugging such code into the |
| 2213 | amalgamation process. |
| 2214 | |
| 2215 | The counterpart of sqlite3ApiBootstrap.initializers, |
| 2216 | specifically for initializers which are asynchronous. All entries in |
| 2217 | this list must be either async functions, non-async functions which |
| 2218 | return a Promise, or a Promise. Each function in the list is called |
| 2219 | with the sqlite3 object as its only argument. |
| 2220 | |
| 2221 | The resolved value of any Promise is ignored and rejection will kill |
| 2222 | the asyncPostInit() process (at an indeterminate point because all |
| 2223 | of them are run asynchronously in parallel). |
| 2224 | |
| 2225 | This list is not processed until the client calls |
| 2226 | sqlite3.asyncPostInit(). This means, for example, that intializers |
| 2227 | added to sqlite3ApiBootstrap.initializers may push entries to |
| 2228 | this list. |
| 2229 | */ |
| 2230 | sqlite3ApiBootstrap.initializersAsync = []; |
| 2231 | |
| 2232 | /** |
| 2233 | Client code may assign sqlite3ApiBootstrap.defaultConfig an |
| 2234 | object-type value before calling sqlite3ApiBootstrap() (without |
| 2235 | arguments) in order to tell that call to use this object as its |
| 2236 | default config value. The intention of this is to provide |
| 2237 | downstream clients with a reasonably flexible approach for plugging in |
| 2238 | an environment-suitable configuration without having to define a new |
| 2239 | global-scope symbol. |
| 2240 | */ |
| 2241 | sqlite3ApiBootstrap.defaultConfig = Object.create(null); |
| 2242 | |
| 2243 | /** |
| 2244 | Placeholder: gets installed by the first call to |
| 2245 | sqlite3ApiBootstrap(). However, it is recommended that the |
| 2246 | caller of sqlite3ApiBootstrap() capture its return value and delete |
| 2247 | sqlite3ApiBootstrap after calling it. It returns the same |
| 2248 | value which will be stored here. |
| 2249 | */ |
| 2250 | sqlite3ApiBootstrap.sqlite3 = undefined; |