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-oo1.c-pp.js
| 1 | //#if not omit-oo1 |
| 2 | /* |
| 3 | 2022-07-22 |
| 4 | |
| 5 | The author disclaims copyright to this source code. In place of a |
| 6 | legal notice, here is a blessing: |
| 7 | |
| 8 | * May you do good and not evil. |
| 9 | * May you find forgiveness for yourself and forgive others. |
| 10 | * May you share freely, never taking more than you give. |
| 11 | |
| 12 | *********************************************************************** |
| 13 | |
| 14 | This file contains the so-called OO #1 API wrapper for the sqlite3 |
| 15 | WASM build. It requires that sqlite3-api-glue.js has already run |
| 16 | and it installs its deliverable as sqlite3.oo1. |
| 17 | */ |
| 18 | sqlite3ApiBootstrap.initializers.push(function(sqlite3){ |
| 19 | const toss3 = (...args)=>{throw new sqlite3.SQLite3Error(...args)}; |
| 20 | |
| 21 | const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util; |
| 22 | /* What follows is colloquially known as "OO API #1". It is a |
| 23 | binding of the sqlite3 API which is designed to be run within |
| 24 | the same thread (main or worker) as the one in which the |
| 25 | sqlite3 WASM binding was initialized. This wrapper cannot use |
| 26 | the sqlite3 binding if, e.g., the wrapper is in the main thread |
| 27 | and the sqlite3 API is in a worker. */ |
| 28 | |
| 29 | const outWrapper = function(f){ |
| 30 | return (...args)=>f("sqlite3.oo1:",...args); |
| 31 | }; |
| 32 | |
| 33 | const debug = sqlite3.__isUnderTest |
| 34 | ? outWrapper(console.debug.bind(console)) |
| 35 | : outWrapper(sqlite3.config.debug); |
| 36 | const warn = sqlite3.__isUnderTest |
| 37 | ? outWrapper(console.warn.bind(console)) |
| 38 | : outWrapper(sqlite3.config.warn); |
| 39 | const error = sqlite3.__isUnderTest |
| 40 | ? outWrapper(console.error.bind(console)) |
| 41 | : outWrapper(sqlite3.config.error); |
| 42 | |
| 43 | /** |
| 44 | In order to keep clients from manipulating, perhaps |
| 45 | inadvertently, the underlying pointer values of DB and Stmt |
| 46 | instances, we'll gate access to them via the `pointer` property |
| 47 | accessor and store their real values in this map. Keys = DB/Stmt |
| 48 | objects, values = pointer values. This also unifies how those are |
| 49 | accessed, for potential use downstream via custom |
| 50 | wasm.xWrap() function signatures which know how to extract |
| 51 | it. |
| 52 | */ |
| 53 | const __ptrMap = new WeakMap(); |
| 54 | /** |
| 55 | Map of (cPointer to X): |
| 56 | |
| 57 | - (sqlite3*) to DB instances, but only to instances which own |
| 58 | their db handle pointer. It's possible to share a C handle across |
| 59 | multiple DB instances but integrating a clean disconnect from |
| 60 | those using this mechanism has proven tricky. |
| 61 | |
| 62 | - (sqlite3_stmt*) to DB.Stmt |
| 63 | |
| 64 | For use by the disposer hook, so that we can properly unplug |
| 65 | native handles from their JS objects if the native handle is |
| 66 | closed using sqlite3_close_v2() resp. sqlite3_finalize(). |
| 67 | |
| 68 | This cannot be a WeakMap because their keys must be objects. |
| 69 | */ |
| 70 | const __disposerMap = new Map(); |
| 71 | /** |
| 72 | A Set of oo1.DB or oo1.Stmt objects which are proxies for |
| 73 | (sqlite3*) resp. (sqlite3_stmt*) pointers which themselves are |
| 74 | owned elsewhere. Objects in this Set do not own their underlying |
| 75 | handle and that handle must be guaranteed (by the client) to |
| 76 | outlive the proxy. DB.close()/Stmt.finalize() methods will remove |
| 77 | the object from this Set _instead_ of closing/finalizing the |
| 78 | pointer. These proxies are primarily intended as a way to briefly |
| 79 | wrap an (sqlite3[_stmt]*) object as an oo1.DB/Stmt without taking |
| 80 | over ownership, to take advantage of simplifies usage compared to |
| 81 | the C API while not imposing any change of ownership. |
| 82 | |
| 83 | See DB.wrapHandle() and Stmt.wrapHandle(). |
| 84 | */ |
| 85 | const __doesNotOwnHandle = new Set(); |
| 86 | /** |
| 87 | Map of DB instances to objects, each object being a map of |
| 88 | sqlite3_stmt wasm pointers to Stmt objects. |
| 89 | */ |
| 90 | const __stmtMap = new WeakMap(); |
| 91 | |
| 92 | /** If object opts has _its own_ property named p then that |
| 93 | property's value is returned, else dflt is returned. */ |
| 94 | const getOwnOption = (opts, p, dflt)=>{ |
| 95 | const d = Object.getOwnPropertyDescriptor(opts,p); |
| 96 | return d ? d.value : dflt; |
| 97 | }; |
| 98 | |
| 99 | // Documented in DB.checkRc() |
| 100 | const checkSqlite3Rc = function(dbPtr, sqliteResultCode){ |
| 101 | if(sqliteResultCode){ |
| 102 | if(dbPtr instanceof DB) dbPtr = dbPtr.pointer; |
| 103 | toss3( |
| 104 | sqliteResultCode, |
| 105 | "sqlite3 result code",sqliteResultCode+":", |
| 106 | (dbPtr |
| 107 | ? capi.sqlite3_errmsg(dbPtr) |
| 108 | : capi.sqlite3_errstr(sqliteResultCode)) |
| 109 | ); |
| 110 | } |
| 111 | return arguments[0]; |
| 112 | }; |
| 113 | |
| 114 | /** |
| 115 | sqlite3_trace_v2() callback which gets installed by the DB ctor |
| 116 | if its open-flags contain "t". |
| 117 | */ |
| 118 | const __dbTraceToConsole = |
| 119 | wasm.installFunction('i(ippp)', function(t,c,p,x){ |
| 120 | if(capi.SQLITE_TRACE_STMT===t){ |
| 121 | // x == SQL, p == sqlite3_stmt* |
| 122 | console.log("SQL TRACE #"+(++this.counter), |
| 123 | 'via sqlite3@'+c+'['+capi.sqlite3_db_filename(c,null)+']', |
| 124 | wasm.cstrToJs(x)); |
| 125 | } |
| 126 | }.bind({counter: 0})); |
| 127 | |
| 128 | /** |
| 129 | A map of sqlite3_vfs pointers to SQL code or a callback function |
| 130 | to run when the DB constructor opens a database with the given |
| 131 | VFS. In the latter case, the call signature is |
| 132 | (theDbObject,sqlite3Namespace) and the callback is expected to |
| 133 | throw on error. |
| 134 | */ |
| 135 | const __vfsPostOpenCallback = Object.create(null); |
| 136 | |
| 137 | //#if enable-see |
| 138 | /** |
| 139 | Converts ArrayBuffer or Uint8Array ba into a string of hex |
| 140 | digits. |
| 141 | */ |
| 142 | const byteArrayToHex = function(ba){ |
| 143 | if( ba instanceof ArrayBuffer ){ |
| 144 | ba = new Uint8Array(ba); |
| 145 | } |
| 146 | const li = []; |
| 147 | const digits = "0123456789abcdef"; |
| 148 | for( const d of ba ){ |
| 149 | li.push( digits[(d & 0xf0) >> 4], digits[d & 0x0f] ); |
| 150 | } |
| 151 | return li.join(''); |
| 152 | }; |
| 153 | |
| 154 | /** |
| 155 | Internal helper to apply an SEE key to a just-opened |
| 156 | database. Requires that db be-a DB object which has just been |
| 157 | opened, opt be the options object processed by its ctor, and opt |
| 158 | must have either the key, hexkey, or textkey properties, either |
| 159 | as a string, an ArrayBuffer, or a Uint8Array. |
| 160 | |
| 161 | This is a no-op in non-SEE builds. It throws on error and returns |
| 162 | without side effects if none of the key/textkey/hexkey options |
| 163 | are set. It throws if more than one is set or if any are set to |
| 164 | values of an invalid type. |
| 165 | |
| 166 | Returns true if it applies the key, else an unspecified falsy |
| 167 | value. Note that applying the key does not imply that the key is |
| 168 | correct, only that it was passed on to the db. |
| 169 | */ |
| 170 | const dbCtorApplySEEKey = function(db,opt){ |
| 171 | if( !capi.sqlite3_key_v2 ) return; |
| 172 | let keytype; |
| 173 | let key; |
| 174 | const check = (opt.key ? 1 : 0) + (opt.hexkey ? 1 : 0) + (opt.textkey ? 1 : 0); |
| 175 | if( !check ) return; |
| 176 | else if( check>1 ){ |
| 177 | toss3(capi.SQLITE_MISUSE, |
| 178 | "Only ONE of (key, hexkey, textkey) may be provided."); |
| 179 | } |
| 180 | if( opt.key ){ |
| 181 | /* It is not legal to bind an argument to PRAGMA key=?, so we |
| 182 | convert it to a hexkey... */ |
| 183 | keytype = 'key'; |
| 184 | key = opt.key; |
| 185 | if('string'===typeof key){ |
| 186 | key = new TextEncoder().encode(key); |
| 187 | } |
| 188 | if((key instanceof ArrayBuffer) || (key instanceof Uint8Array)){ |
| 189 | key = byteArrayToHex(key); |
| 190 | keytype = 'hexkey'; |
| 191 | }else{ |
| 192 | toss3(capi.SQLITE_MISUSE, |
| 193 | "Invalid value for the 'key' option. Expecting a string,", |
| 194 | "ArrayBuffer, or Uint8Array."); |
| 195 | return; |
| 196 | } |
| 197 | }else if( opt.textkey ){ |
| 198 | /* For textkey we need it to be in string form, so convert it to |
| 199 | a string if it's a byte array... */ |
| 200 | keytype = 'textkey'; |
| 201 | key = opt.textkey; |
| 202 | if(key instanceof ArrayBuffer){ |
| 203 | key = new Uint8Array(key); |
| 204 | } |
| 205 | if(key instanceof Uint8Array){ |
| 206 | key = new TextDecoder('utf-8').decode(key); |
| 207 | }else if('string'!==typeof key){ |
| 208 | toss3(capi.SQLITE_MISUSE, |
| 209 | "Invalid value for the 'textkey' option. Expecting a string,", |
| 210 | "ArrayBuffer, or Uint8Array."); |
| 211 | } |
| 212 | }else if( opt.hexkey ){ |
| 213 | keytype = 'hexkey'; |
| 214 | key = opt.hexkey; |
| 215 | if((key instanceof ArrayBuffer) || (key instanceof Uint8Array)){ |
| 216 | key = byteArrayToHex(key); |
| 217 | }else if('string'!==typeof key){ |
| 218 | toss3(capi.SQLITE_MISUSE, |
| 219 | "Invalid value for the 'hexkey' option. Expecting a string,", |
| 220 | "ArrayBuffer, or Uint8Array."); |
| 221 | } |
| 222 | /* else assume it's valid hex codes */ |
| 223 | }else{ |
| 224 | return; |
| 225 | } |
| 226 | let stmt; |
| 227 | try{ |
| 228 | stmt = db.prepare("PRAGMA "+keytype+"="+util.sqlite3__wasm_qfmt_token(key, 1)); |
| 229 | stmt.step(); |
| 230 | return true; |
| 231 | }finally{ |
| 232 | if(stmt) stmt.finalize(); |
| 233 | } |
| 234 | }; |
| 235 | //#/if enable-see |
| 236 | |
| 237 | /** |
| 238 | A proxy for DB class constructors. It must be called with the |
| 239 | being-construct DB object as its "this". See the DB constructor |
| 240 | for the argument docs. This is split into a separate function |
| 241 | in order to enable simple creation of special-case DB constructors, |
| 242 | e.g. JsStorageDb and OpfsDb. |
| 243 | |
| 244 | Expects to be passed a configuration object with the following |
| 245 | properties: |
| 246 | |
| 247 | - `.filename`: the db filename. It may be a special name like ":memory:" |
| 248 | or "". It may also be a URI-style name. |
| 249 | |
| 250 | - `.flags`: as documented in the DB constructor. |
| 251 | |
| 252 | - `.vfs`: as documented in the DB constructor. |
| 253 | |
| 254 | It also accepts those as the first 3 arguments. |
| 255 | |
| 256 | In non-default builds it may accept additional configuration |
| 257 | options. |
| 258 | */ |
| 259 | const dbCtorHelper = function ctor(...args){ |
| 260 | const opt = ctor.normalizeArgs(...args); |
| 261 | //sqlite3.config.debug("DB ctor",opt); |
| 262 | let pDb; |
| 263 | if( (pDb = opt['sqlite3*']) ){ |
| 264 | /* This property ^^^^^ is very specifically NOT DOCUMENTED and |
| 265 | NOT part of the public API. This is a back door for functions |
| 266 | like DB.wrapDbHandle(). */ |
| 267 | //sqlite3.config.debug("creating proxy db from",opt); |
| 268 | if( !opt['sqlite3*:takeOwnership'] ){ |
| 269 | /* This is object does not own its handle. */ |
| 270 | __doesNotOwnHandle.add(this); |
| 271 | } |
| 272 | this.filename = capi.sqlite3_db_filename(pDb,'main'); |
| 273 | }else{ |
| 274 | let fn = opt.filename, vfsName = opt.vfs, flagsStr = opt.flags; |
| 275 | if( ('string'!==typeof fn && !wasm.isPtr(fn)) |
| 276 | || 'string'!==typeof flagsStr |
| 277 | || (vfsName && ('string'!==typeof vfsName && !wasm.isPtr(vfsName))) ){ |
| 278 | sqlite3.config.error("Invalid DB ctor args",opt,arguments); |
| 279 | toss3("Invalid arguments for DB constructor:", arguments, "opts:", opt); |
| 280 | } |
| 281 | let oflags = 0; |
| 282 | if( flagsStr.indexOf('c')>=0 ){ |
| 283 | oflags |= capi.SQLITE_OPEN_CREATE | capi.SQLITE_OPEN_READWRITE; |
| 284 | } |
| 285 | if( flagsStr.indexOf('w')>=0 ) oflags |= capi.SQLITE_OPEN_READWRITE; |
| 286 | if( 0===oflags ) oflags |= capi.SQLITE_OPEN_READONLY; |
| 287 | oflags |= capi.SQLITE_OPEN_EXRESCODE; |
| 288 | const stack = wasm.pstack.pointer; |
| 289 | try { |
| 290 | const pPtr = wasm.pstack.allocPtr() /* output (sqlite3**) arg */; |
| 291 | let rc = capi.sqlite3_open_v2(fn, pPtr, oflags, vfsName || wasm.ptr.null); |
| 292 | pDb = wasm.peekPtr(pPtr); |
| 293 | checkSqlite3Rc(pDb, rc); |
| 294 | capi.sqlite3_extended_result_codes(pDb, 1); |
| 295 | if(flagsStr.indexOf('t')>=0){ |
| 296 | capi.sqlite3_trace_v2(pDb, capi.SQLITE_TRACE_STMT, |
| 297 | __dbTraceToConsole, pDb); |
| 298 | } |
| 299 | }catch( e ){ |
| 300 | if( pDb ) capi.sqlite3_close_v2(pDb); |
| 301 | throw e; |
| 302 | }finally{ |
| 303 | wasm.pstack.restore(stack); |
| 304 | } |
| 305 | this.filename = |
| 306 | /* A poor design choice we have to keep: this.filename may be |
| 307 | in the form "file:....?....". It really should have been |
| 308 | sqlite3_db_filename(pDb) but that discrepancy went too long |
| 309 | unnoticed to be able to change without risk of |
| 310 | breakage. DB.dbFilename() can be used to fetch _just_ the |
| 311 | name part. |
| 312 | */ wasm.isPtr(fn) ? wasm.cstrToJs(fn) : fn; |
| 313 | |
| 314 | } |
| 315 | __ptrMap.set(this, pDb); |
| 316 | __stmtMap.set(this, Object.create(null)); |
| 317 | if( !__disposerMap.has(pDb) ){ |
| 318 | /* Only register the prime instance with the disposer. */ |
| 319 | __disposerMap.set(pDb, this); |
| 320 | } |
| 321 | if( !opt['sqlite3*'] ){ |
| 322 | try{ |
| 323 | //#if enable-see |
| 324 | dbCtorApplySEEKey(this,opt); |
| 325 | //#/if |
| 326 | // Check for per-VFS post-open SQL/callback... |
| 327 | const pVfs = capi.sqlite3_js_db_vfs(pDb) |
| 328 | || toss3("Internal error: cannot get VFS for new db handle."); |
| 329 | const postInitSql = __vfsPostOpenCallback[pVfs]; |
| 330 | if(postInitSql){ |
| 331 | /** |
| 332 | Reminder: if this db is encrypted and the client did _not_ pass |
| 333 | in the key, any init code will fail, causing the ctor to throw. |
| 334 | We don't actually know whether the db is encrypted, so we cannot |
| 335 | sensibly apply any heuristics which skip the init code only for |
| 336 | encrypted databases for which no key has yet been supplied. |
| 337 | */ |
| 338 | if(postInitSql instanceof Function){ |
| 339 | postInitSql(this, sqlite3); |
| 340 | }else{ |
| 341 | checkSqlite3Rc( |
| 342 | pDb, capi.sqlite3_exec(pDb, postInitSql, 0, 0, 0) |
| 343 | ); |
| 344 | } |
| 345 | } |
| 346 | }catch(e){ |
| 347 | this.close(); |
| 348 | throw e; |
| 349 | } |
| 350 | } |
| 351 | }; |
| 352 | |
| 353 | /** |
| 354 | Sets a callback which should be called after a db is opened with |
| 355 | the given sqlite3_vfs pointer. The 2nd argument must be a |
| 356 | function, which gets called with |
| 357 | (theOo1DbObject,sqlite3Namespace) at the end of the DB() |
| 358 | constructor. The function must throw on error, in which case the |
| 359 | db is closed and the exception is propagated. This function is |
| 360 | intended only for use by DB subclasses or sqlite3_vfs |
| 361 | implementations. |
| 362 | |
| 363 | Prior to 2024-07-22, it was legal to pass SQL code as the second |
| 364 | argument, but that can interfere with a client's ability to run |
| 365 | pragmas which must be run before anything else, namely (pragma |
| 366 | locking_mode=exclusive) for use with WAL mode. That capability |
| 367 | had only ever been used as an internal detail of the two OPFS |
| 368 | VFSes, and they no longer use it that way. |
| 369 | */ |
| 370 | dbCtorHelper.setVfsPostOpenCallback = function(pVfs, callback){ |
| 371 | if( !(callback instanceof Function)){ |
| 372 | toss3("dbCtorHelper.setVfsPostOpenCallback() should not be used with "+ |
| 373 | "a non-function argument.",arguments); |
| 374 | } |
| 375 | __vfsPostOpenCallback[pVfs] = callback; |
| 376 | }; |
| 377 | |
| 378 | /** |
| 379 | A helper for DB constructors. It accepts either a single |
| 380 | config-style object or up to 3 arguments (filename, dbOpenFlags, |
| 381 | dbVfsName). It returns a new object containing: |
| 382 | |
| 383 | { filename: ..., flags: ..., vfs: ... } |
| 384 | |
| 385 | If passed an object, any additional properties it has are copied |
| 386 | as-is into the new object. |
| 387 | */ |
| 388 | dbCtorHelper.normalizeArgs = function(filename=':memory:',flags = 'c',vfs = null){ |
| 389 | const arg = {}; |
| 390 | if(1===arguments.length && arguments[0] && 'object'===typeof arguments[0]){ |
| 391 | Object.assign(arg, arguments[0]); |
| 392 | if(undefined===arg.flags) arg.flags = 'c'; |
| 393 | if(undefined===arg.vfs) arg.vfs = null; |
| 394 | if(undefined===arg.filename) arg.filename = ':memory:'; |
| 395 | }else{ |
| 396 | arg.filename = filename; |
| 397 | arg.flags = flags; |
| 398 | arg.vfs = vfs; |
| 399 | } |
| 400 | return arg; |
| 401 | }; |
| 402 | /** |
| 403 | The DB class provides a high-level OO wrapper around an sqlite3 |
| 404 | db handle. |
| 405 | |
| 406 | The given db filename must be resolvable using whatever |
| 407 | filesystem layer (virtual or otherwise) is set up for the default |
| 408 | sqlite3 VFS or a VFS which can resolve it must be specified. |
| 409 | |
| 410 | The special sqlite3 db names ":memory:" and "" (temporary db) |
| 411 | have their normal special meanings here and need not resolve to |
| 412 | real filenames, but "" uses an on-storage temporary database and |
| 413 | requires that the VFS support that. |
| 414 | |
| 415 | The second argument specifies the open/create mode for the |
| 416 | database. It must be string containing a sequence of letters (in |
| 417 | any order, but case sensitive) specifying the mode: |
| 418 | |
| 419 | - "c": create if it does not exist, else fail if it does not |
| 420 | exist. Implies the "w" flag. |
| 421 | |
| 422 | - "w": write. Implies "r": a db cannot be write-only. |
| 423 | |
| 424 | - "r": read-only if neither "w" nor "c" are provided, else it |
| 425 | is ignored. |
| 426 | |
| 427 | - "t": enable tracing of SQL executed on this database handle, |
| 428 | sending it to `console.log()`. To disable it later, call |
| 429 | `sqlite3.capi.sqlite3_trace_v2(thisDb.pointer, 0, 0, 0)`. |
| 430 | |
| 431 | If "w" is not provided, the db is implicitly read-only, noting |
| 432 | that "rc" is meaningless |
| 433 | |
| 434 | Any other letters are currently ignored. The default is |
| 435 | "c". These modes are ignored for the special ":memory:" and "" |
| 436 | names and _may_ be ignored altogether for certain VFSes. |
| 437 | |
| 438 | The final argument is analogous to the final argument of |
| 439 | sqlite3_open_v2(): the name of an sqlite3 VFS. Pass a falsy value, |
| 440 | or none at all, to use the default. If passed a value, it must |
| 441 | be the string name of a VFS. |
| 442 | |
| 443 | The constructor optionally (and preferably) takes its arguments |
| 444 | in the form of a single configuration object with the following |
| 445 | properties: |
| 446 | |
| 447 | - `filename`: database file name |
| 448 | - `flags`: open-mode flags |
| 449 | - `vfs`: the VFS fname |
| 450 | |
| 451 | //#if enable-see |
| 452 | SEE-capable builds optionally support ONE of the following |
| 453 | additional options: |
| 454 | |
| 455 | - `key`, `hexkey`, or `textkey`: encryption key as a string, |
| 456 | ArrayBuffer, or Uint8Array. These flags function as documented |
| 457 | for the SEE pragmas of the same names. Using a byte array for |
| 458 | `hexkey` is equivalent to the same series of hex codes in |
| 459 | string form, so `'666f6f'` is equivalent to |
| 460 | `Uint8Array([0x66,0x6f,0x6f])`. A `textkey` byte array is |
| 461 | assumed to be UTF-8. A `key` string is transformed into a UTF-8 |
| 462 | byte array, and a `key` byte array is transformed into a |
| 463 | `hexkey` with the same bytes. |
| 464 | |
| 465 | In non-SEE builds, these options are ignored. In SEE builds, |
| 466 | `PRAGMA key/textkey/hexkey=X` is executed immediately after |
| 467 | opening the db. If more than one of the options is provided, |
| 468 | or any option has an invalid argument type, an exception is |
| 469 | thrown. |
| 470 | |
| 471 | Note that some DB subclasses may run post-initialization SQL |
| 472 | code, e.g. to set a busy-handler timeout or tweak the page cache |
| 473 | size. Such code is run _after_ the SEE key is applied. If no key |
| 474 | is supplied and the database is encrypted, execution of the |
| 475 | post-initialization SQL will fail, causing the constructor to |
| 476 | throw. |
| 477 | //#/if enable-see |
| 478 | |
| 479 | The `filename` and `vfs` arguments may be either JS strings or |
| 480 | C-strings allocated via WASM. `flags` is required to be a JS |
| 481 | string (because it's specific to this API, which is specific |
| 482 | to JS). |
| 483 | |
| 484 | For purposes of passing a DB instance to C-style sqlite3 |
| 485 | functions, the DB object's read-only `pointer` property holds its |
| 486 | `sqlite3*` pointer value. That property can also be used to check |
| 487 | whether this DB instance is still open: it will evaluate to |
| 488 | `undefined` after the DB object's close() method is called. |
| 489 | |
| 490 | In the main window thread, the filenames `":localStorage:"` and |
| 491 | `":sessionStorage:"` are special: they cause the db to use either |
| 492 | localStorage or sessionStorage for storing the database using |
| 493 | the kvvfs. If one of these names are used, they trump |
| 494 | any vfs name set in the arguments. |
| 495 | */ |
| 496 | const DB = function(...args){ |
| 497 | dbCtorHelper.apply(this, args); |
| 498 | }; |
| 499 | DB.dbCtorHelper = dbCtorHelper; |
| 500 | |
| 501 | /** |
| 502 | Internal-use enum for mapping JS types to DB-bindable types. |
| 503 | These do not (and need not) line up with the SQLITE_type |
| 504 | values. All values in this enum must be truthy and (mostly) |
| 505 | distinct but they need not be numbers. |
| 506 | */ |
| 507 | const BindTypes = { |
| 508 | null: 1, |
| 509 | number: 2, |
| 510 | string: 3, |
| 511 | boolean: 4, |
| 512 | blob: 5 |
| 513 | }; |
| 514 | if(wasm.bigIntEnabled){ |
| 515 | BindTypes.bigint = BindTypes.number; |
| 516 | } |
| 517 | |
| 518 | /** |
| 519 | This class wraps sqlite3_stmt. Calling this constructor |
| 520 | directly will trigger an exception. Use DB.prepare() to create |
| 521 | new instances. |
| 522 | |
| 523 | For purposes of passing a Stmt instance to C-style sqlite3 |
| 524 | functions, its read-only `pointer` property holds its `sqlite3_stmt*` |
| 525 | pointer value. |
| 526 | |
| 527 | Other non-function properties include: |
| 528 | |
| 529 | - `db`: the DB object which created the statement. |
| 530 | |
| 531 | - `columnCount`: the number of result columns in the query, or 0 |
| 532 | for queries which cannot return results. This property is a |
| 533 | read-only proxy for sqlite3_column_count() and its use in loops |
| 534 | should be avoided because of the call overhead associated with |
| 535 | that. The `columnCount` is not cached when the Stmt is created |
| 536 | because a schema change made between this statement's preparation |
| 537 | and when it is stepped may invalidate it. |
| 538 | |
| 539 | - `parameterCount`: the number of bindable parameters in the |
| 540 | query. Like `columnCount`, this property is ready-only and is a |
| 541 | proxy for a C API call. |
| 542 | |
| 543 | As a general rule, most methods of this class will throw if |
| 544 | called on an instance which has been finalized. For brevity's |
| 545 | sake, the method docs do not all repeat this warning. |
| 546 | */ |
| 547 | const Stmt = function(/*oo1db, stmtPtr, BindTypes [,takeOwnership=true] */){ |
| 548 | if(BindTypes!==arguments[2]){ |
| 549 | toss3(capi.SQLITE_MISUSE, "Do not call the Stmt constructor directly. Use DB.prepare()."); |
| 550 | } |
| 551 | this.db = arguments[0]; |
| 552 | __ptrMap.set(this, arguments[1]); |
| 553 | if( arguments.length>3 && !arguments[3] ){ |
| 554 | __doesNotOwnHandle.add(this); |
| 555 | }else{ |
| 556 | /* Only the prime instances go into __disposerMap. */ |
| 557 | __disposerMap.set(arguments[1], this); |
| 558 | } |
| 559 | }; |
| 560 | |
| 561 | /** Throws if the given DB has been closed, else it is returned. */ |
| 562 | const affirmDbOpen = function(db){ |
| 563 | if(!db.pointer) toss3("DB has been closed."); |
| 564 | return db; |
| 565 | }; |
| 566 | |
| 567 | /** Throws if ndx is not an integer or if it is out of range |
| 568 | for stmt.columnCount, else returns stmt. |
| 569 | |
| 570 | Reminder: this will also fail after the statement is finalized |
| 571 | but the resulting error will be about an out-of-bounds column |
| 572 | index rather than a statement-is-finalized error. |
| 573 | */ |
| 574 | const affirmColIndex = function(stmt,ndx){ |
| 575 | if((ndx !== (ndx|0)) || ndx<0 || ndx>=stmt.columnCount){ |
| 576 | toss3("Column index",ndx,"is out of range."); |
| 577 | } |
| 578 | return stmt; |
| 579 | }; |
| 580 | |
| 581 | /** |
| 582 | Expects to be passed the `arguments` object from DB.exec(). Does |
| 583 | the argument processing/validation, throws on error, and returns |
| 584 | a new object on success: |
| 585 | |
| 586 | { sql: the SQL, opt: optionsObj, cbArg: function} |
| 587 | |
| 588 | The opt object is a normalized copy of any passed to this |
| 589 | function. The sql will be converted to a string if it is provided |
| 590 | in one of the supported non-string formats. |
| 591 | |
| 592 | cbArg is only set if the opt.callback or opt.resultRows are set, |
| 593 | in which case it's a function which expects to be passed the |
| 594 | current Stmt and returns the callback argument of the type |
| 595 | indicated by the input arguments. |
| 596 | */ |
| 597 | const parseExecArgs = function(db, args){ |
| 598 | const out = Object.create(null); |
| 599 | out.opt = Object.create(null); |
| 600 | switch(args.length){ |
| 601 | case 1: |
| 602 | if('string'===typeof args[0] || util.isSQLableTypedArray(args[0])){ |
| 603 | out.sql = args[0]; |
| 604 | }else if(Array.isArray(args[0])){ |
| 605 | out.sql = args[0]; |
| 606 | }else if(args[0] && 'object'===typeof args[0]){ |
| 607 | out.opt = args[0]; |
| 608 | out.sql = out.opt.sql; |
| 609 | } |
| 610 | break; |
| 611 | case 2: |
| 612 | out.sql = args[0]; |
| 613 | out.opt = args[1]; |
| 614 | break; |
| 615 | default: toss3("Invalid argument count for exec()."); |
| 616 | }; |
| 617 | out.sql = util.flexibleString(out.sql); |
| 618 | if('string'!==typeof out.sql){ |
| 619 | toss3("Missing SQL argument or unsupported SQL value type."); |
| 620 | } |
| 621 | const opt = out.opt; |
| 622 | switch(opt.returnValue){ |
| 623 | case 'resultRows': |
| 624 | if(!opt.resultRows) opt.resultRows = []; |
| 625 | out.returnVal = ()=>opt.resultRows; |
| 626 | break; |
| 627 | case 'saveSql': |
| 628 | if(!opt.saveSql) opt.saveSql = []; |
| 629 | out.returnVal = ()=>opt.saveSql; |
| 630 | break; |
| 631 | case undefined: |
| 632 | case 'this': |
| 633 | out.returnVal = ()=>db; |
| 634 | break; |
| 635 | default: |
| 636 | toss3("Invalid returnValue value:",opt.returnValue); |
| 637 | } |
| 638 | if(!opt.callback && !opt.returnValue && undefined!==opt.rowMode){ |
| 639 | if(!opt.resultRows) opt.resultRows = []; |
| 640 | out.returnVal = ()=>opt.resultRows; |
| 641 | } |
| 642 | if(opt.callback || opt.resultRows){ |
| 643 | switch((undefined===opt.rowMode) ? 'array' : opt.rowMode) { |
| 644 | case 'object': |
| 645 | out.cbArg = (stmt,cache)=>{ |
| 646 | if( !cache.columnNames ) cache.columnNames = stmt.getColumnNames([]); |
| 647 | /* https://sqlite.org/forum/forumpost/3632183d2470617d: |
| 648 | conversion of rows to objects (key/val pairs) is |
| 649 | somewhat expensive for large data sets because of the |
| 650 | native-to-JS conversion of the column names. If we |
| 651 | instead cache the names and build objects from that |
| 652 | list of strings, it can run twice as fast. The |
| 653 | difference is not noticeable for small data sets but |
| 654 | becomes human-perceivable when enough rows are |
| 655 | involved. */ |
| 656 | const row = stmt.get([]); |
| 657 | const rv = Object.create(null); |
| 658 | for( const i in cache.columnNames ) rv[cache.columnNames[i]] = row[i]; |
| 659 | return rv; |
| 660 | }; |
| 661 | break; |
| 662 | case 'array': out.cbArg = (stmt)=>stmt.get([]); break; |
| 663 | case 'stmt': |
| 664 | if(Array.isArray(opt.resultRows)){ |
| 665 | toss3("exec(): invalid rowMode for a resultRows array: must", |
| 666 | "be one of 'array', 'object',", |
| 667 | "a result column number, or column name reference."); |
| 668 | } |
| 669 | out.cbArg = (stmt)=>stmt; |
| 670 | break; |
| 671 | default: |
| 672 | if(util.isInt32(opt.rowMode)){ |
| 673 | out.cbArg = (stmt)=>stmt.get(opt.rowMode); |
| 674 | break; |
| 675 | }else if('string'===typeof opt.rowMode |
| 676 | && opt.rowMode.length>1 |
| 677 | && '$'===opt.rowMode[0]){ |
| 678 | /* "$X": fetch column named "X" (case-sensitive!). Prior |
| 679 | to 2022-12-14 ":X" and "@X" were also permitted, but |
| 680 | having so many options is unnecessary and likely to |
| 681 | cause confusion. */ |
| 682 | const $colName = opt.rowMode.substr(1); |
| 683 | out.cbArg = (stmt)=>{ |
| 684 | const rc = stmt.get(Object.create(null))[$colName]; |
| 685 | return (undefined===rc) |
| 686 | ? toss3(capi.SQLITE_NOTFOUND, |
| 687 | "exec(): unknown result column:",$colName) |
| 688 | : rc; |
| 689 | }; |
| 690 | break; |
| 691 | } |
| 692 | toss3("Invalid rowMode:",opt.rowMode); |
| 693 | } |
| 694 | } |
| 695 | return out; |
| 696 | }; |
| 697 | |
| 698 | /** |
| 699 | Internal impl of the DB.selectValue(), selectArray(), and |
| 700 | selectObject() methods. |
| 701 | */ |
| 702 | const __selectFirstRow = (db, sql, bind, ...getArgs)=>{ |
| 703 | const stmt = db.prepare(sql); |
| 704 | try { |
| 705 | const rc = stmt.bind(bind).step() ? stmt.get(...getArgs) : undefined; |
| 706 | stmt.reset(/*for INSERT...RETURNING locking case |
| 707 | https://sqlite.org/forum/forumpost/c411b3a9143d02dce */); |
| 708 | return rc; |
| 709 | }finally{ |
| 710 | stmt.finalize(); |
| 711 | } |
| 712 | }; |
| 713 | |
| 714 | /** |
| 715 | Internal impl of the DB.selectArrays() and selectObjects() |
| 716 | methods. |
| 717 | */ |
| 718 | const __selectAll = |
| 719 | (db, sql, bind, rowMode)=>db.exec({ |
| 720 | sql, bind, rowMode, returnValue: 'resultRows' |
| 721 | }); |
| 722 | |
| 723 | /** |
| 724 | Internal impl of DB.Stmt APIs which fetch a column. The caller is |
| 725 | required to have validated the ndx value before calling this (see |
| 726 | affirmColIndex()). The purpose of this impl is to speed up such |
| 727 | operations which loop, to avoid having to validate the index on |
| 728 | each iteration. The arguments are as documented for Stmt.get() |
| 729 | with the exception that ndx must be an in-range interger (that |
| 730 | function handles the other cases and proxies them to this one). |
| 731 | */ |
| 732 | const __stmtGetColumn = (stmt, ndx, asType)=>{ |
| 733 | switch(undefined===asType |
| 734 | ? capi.sqlite3_column_type(stmt.pointer, ndx) |
| 735 | : asType){ |
| 736 | case capi.SQLITE_NULL: return null; |
| 737 | case capi.SQLITE_INTEGER:{ |
| 738 | if(wasm.bigIntEnabled){ |
| 739 | const rc = capi.sqlite3_column_int64(stmt.pointer, ndx); |
| 740 | if(rc>=Number.MIN_SAFE_INTEGER && rc<=Number.MAX_SAFE_INTEGER){ |
| 741 | return Number(rc).valueOf(); |
| 742 | } |
| 743 | return rc; |
| 744 | }else{ |
| 745 | const rc = capi.sqlite3_column_double(stmt.pointer, ndx); |
| 746 | if(rc>Number.MAX_SAFE_INTEGER || rc<Number.MIN_SAFE_INTEGER){ |
| 747 | toss3("Integer is out of range for JS integer range: "+rc); |
| 748 | } |
| 749 | return util.isInt32(rc) ? (rc | 0) : rc; |
| 750 | } |
| 751 | } |
| 752 | case capi.SQLITE_FLOAT: |
| 753 | return capi.sqlite3_column_double(stmt.pointer, ndx); |
| 754 | case capi.SQLITE_TEXT: |
| 755 | return capi.sqlite3_column_text(stmt.pointer, ndx); |
| 756 | case capi.SQLITE_BLOB: { |
| 757 | const n = capi.sqlite3_column_bytes(stmt.pointer, ndx), |
| 758 | ptr = capi.sqlite3_column_blob(stmt.pointer, ndx), |
| 759 | rc = new Uint8Array(n); |
| 760 | if(n){ |
| 761 | rc.set(wasm.heap8u().slice(Number(ptr), Number(ptr)+n), 0); |
| 762 | if(stmt.db._blobXfer instanceof Array){ |
| 763 | stmt.db._blobXfer.push(rc.buffer); |
| 764 | } |
| 765 | } |
| 766 | return rc; |
| 767 | } |
| 768 | default: toss3("Don't know how to translate", |
| 769 | "type of result column #"+ndx+"."); |
| 770 | } |
| 771 | toss3("Not reached."); |
| 772 | }; |
| 773 | |
| 774 | /** |
| 775 | Expects to be given a DB instance or an `sqlite3*` pointer (may |
| 776 | be null) and an sqlite3 API result code. If the result code is |
| 777 | not falsy, this function throws an SQLite3Error with an error |
| 778 | message from sqlite3_errmsg(), using db (or, if db is-a DB, |
| 779 | db.pointer) as the db handle, or sqlite3_errstr() if db is |
| 780 | falsy. Note that if it's passed a non-error code like SQLITE_ROW |
| 781 | or SQLITE_DONE, it will still throw but the error string might be |
| 782 | "Not an error." The various non-0 non-error codes need to be |
| 783 | checked for in client code where they are expected. |
| 784 | |
| 785 | The thrown exception's `resultCode` property will be the value of |
| 786 | the second argument to this function. |
| 787 | |
| 788 | If it does not throw, it returns its first argument. |
| 789 | */ |
| 790 | DB.checkRc = (db,resultCode)=>checkSqlite3Rc(db,resultCode); |
| 791 | |
| 792 | /** |
| 793 | Internal helper for __oo1NativeDisposerDB and |
| 794 | __oo1NativeDisposerStmt. Detaches any non-owning handles shared |
| 795 | via DB/Stmt.wrapHandle() which refer to the owning pointer ptr, |
| 796 | cleanly invalidating them so that they do not point to stale |
| 797 | pointers. |
| 798 | */ |
| 799 | const __disposerUnowned = (lbl, ptr, disposer)=>{ |
| 800 | const unowned = Array.from(__doesNotOwnHandle).filter(x=>ptr===x.pointer); |
| 801 | if( unowned.length ){ |
| 802 | sqlite3.config.warn("Closing",lbl,"handle", |
| 803 | ptr,"out from under shared holders.", |
| 804 | unowned); |
| 805 | /* Two-pass to prevent further recursion. */ |
| 806 | for(const u of unowned) __doesNotOwnHandle.delete(u); |
| 807 | for(const u of unowned) disposer(ptr, u); |
| 808 | } |
| 809 | }; |
| 810 | /** |
| 811 | Hook for SQLITE_DISPOSAL_NOTIFIER. Expects ptr to be an |
| 812 | (sqlite3*), for which it unmaps any state to its partner DB |
| 813 | object (if any). The o arg is intended to be `this` from |
| 814 | DB.close(). |
| 815 | */ |
| 816 | const __oo1NativeDisposerDB = (ptr, o)=>{ |
| 817 | o ??= __disposerMap.get(ptr); |
| 818 | //sqlite3.config.warn("__oo1NativeDisposerDB", ptr, o); |
| 819 | if( !o ) return; |
| 820 | __doesNotOwnHandle.delete(o); |
| 821 | if( o===__disposerMap.get(ptr) ){ |
| 822 | /* The prime instance. */ |
| 823 | __disposerMap.delete(ptr); |
| 824 | __disposerUnowned('DB', ptr, __oo1NativeDisposerDB); |
| 825 | } |
| 826 | const st = __stmtMap.get(o); |
| 827 | __stmtMap.delete(o); |
| 828 | if( st ){ |
| 829 | for(const s of Object.values(st)){ |
| 830 | try{s.finalize()} |
| 831 | catch(ex){/*ignore*/} |
| 832 | } |
| 833 | } |
| 834 | __ptrMap.delete(o); |
| 835 | }; |
| 836 | |
| 837 | /** DB.Stmt counterpart of __oo1NativeDisposerDB(). The o arg is |
| 838 | intended to be `this` from Stmt.finalize(). */ |
| 839 | const __oo1NativeDisposerStmt = (ptr, o)=>{ |
| 840 | o ??= __disposerMap.get(ptr); |
| 841 | //sqlite3.config.warn("__oo1NativeDisposerStmt", ptr, o); |
| 842 | if( !o ) return; |
| 843 | delete __stmtMap.get(o.db)?.[ptr]; |
| 844 | delete o.db; |
| 845 | __execLock.delete(o); |
| 846 | __stmtMayGet.delete(o); |
| 847 | __doesNotOwnHandle.delete(o); |
| 848 | if( o===__disposerMap.get(ptr) ){ |
| 849 | /* The prime instance. */ |
| 850 | __disposerMap.delete(ptr); |
| 851 | __disposerUnowned('Stmt', ptr, __oo1NativeDisposerStmt); |
| 852 | } |
| 853 | __ptrMap.delete(o); |
| 854 | }; |
| 855 | util.disposers.db.push(__oo1NativeDisposerDB); |
| 856 | util.disposers.stmt.push(__oo1NativeDisposerStmt); |
| 857 | |
| 858 | DB.prototype = { |
| 859 | /** Returns true if this db handle is open, else false. */ |
| 860 | isOpen: function(){ |
| 861 | return !!this.pointer; |
| 862 | }, |
| 863 | /** Throws if this given DB has been closed, else returns `this`. */ |
| 864 | affirmOpen: function(){ |
| 865 | return affirmDbOpen(this); |
| 866 | }, |
| 867 | /** |
| 868 | Finalizes all open statements and closes this database |
| 869 | connection (with one exception noted below). This is a no-op if |
| 870 | the db has already been closed. After calling close(), |
| 871 | `this.pointer` will resolve to `undefined`, and that can be |
| 872 | used to check whether the db instance is still opened. |
| 873 | |
| 874 | If this.onclose.before is a function then it is called before |
| 875 | any close-related cleanup. |
| 876 | |
| 877 | If this.onclose.after is a function then it is called after the |
| 878 | db is closed but before auxiliary state like this.filename is |
| 879 | cleared. |
| 880 | |
| 881 | Both onclose handlers are passed this object, with the onclose |
| 882 | object as their "this," noting that the db will have been |
| 883 | closed when onclose.after is called. If this db is not opened |
| 884 | when close() is called, neither of the handlers are called. Any |
| 885 | exceptions the handlers throw are ignored because "destructors |
| 886 | must not throw". |
| 887 | |
| 888 | Garbage collection of a db handle, if it happens at all, will |
| 889 | never trigger close(), so onclose handlers are not a reliable |
| 890 | way to implement close-time cleanup or maintenance of a db. |
| 891 | |
| 892 | If this instance was created using DB.wrapHandle() and does not |
| 893 | own this.pointer then it does not close the db handle but it |
| 894 | does perform all other work, such as calling onclose callbacks |
| 895 | (which are local to that instance) and disassociating this |
| 896 | object from its native this.pointer. |
| 897 | |
| 898 | As of version 3.55.0, DB objects are disassociated from their |
| 899 | native counterpart if the native is passed to |
| 900 | sqlite3_close_v2(). A side-effect of that is that this |
| 901 | function becomes a no-op if a db handle is closed that way. |
| 902 | i.e. onclose handlers will not be called. Prior to that change, |
| 903 | passing such a pointer to sqlite3_close_v2() invoked undefined |
| 904 | behavior. Design note: the onclose handlers are not called in |
| 905 | that case because they are feature of this method, not of the |
| 906 | db handle. We "could", with only a small amount of acrobatics, |
| 907 | call onclose handlers even in that case, but it does not seem |
| 908 | like the right thing to do. Clients wishing to apply the |
| 909 | callbacks regardless of how the handle is closed simply need to |
| 910 | bind the onclose handlers to the underlying db pointer using |
| 911 | sqlite3_js_on_pointer_dispose(). |
| 912 | */ |
| 913 | close: function(){ |
| 914 | const pDb = this.pointer; |
| 915 | if(pDb){ |
| 916 | const owns = !__doesNotOwnHandle.delete(this); |
| 917 | const onclose = this.onclose; |
| 918 | delete this.onclose/*avoid a recursion case*/; |
| 919 | if(onclose?.before instanceof Function){ |
| 920 | try{onclose.before(this)} |
| 921 | catch(e){/*ignore*/} |
| 922 | } |
| 923 | __oo1NativeDisposerDB(pDb, this); |
| 924 | if( owns ) capi.sqlite3_close_v2(pDb); |
| 925 | if(onclose?.after instanceof Function){ |
| 926 | try{this.onclose.after(this)} |
| 927 | catch(e){/*ignore*/} |
| 928 | } |
| 929 | delete this.filename; |
| 930 | } |
| 931 | }, |
| 932 | /** |
| 933 | Returns the number of changes, as per sqlite3_changes() |
| 934 | (if the first argument is false) or sqlite3_total_changes() |
| 935 | (if it's true). If the 2nd argument is true, it uses |
| 936 | sqlite3_changes64() or sqlite3_total_changes64(), which |
| 937 | will trigger an exception if this build does not have |
| 938 | BigInt support enabled. |
| 939 | */ |
| 940 | changes: function(total=false,sixtyFour=false){ |
| 941 | const p = affirmDbOpen(this).pointer; |
| 942 | if(total){ |
| 943 | return sixtyFour |
| 944 | ? capi.sqlite3_total_changes64(p) |
| 945 | : capi.sqlite3_total_changes(p); |
| 946 | }else{ |
| 947 | return sixtyFour |
| 948 | ? capi.sqlite3_changes64(p) |
| 949 | : capi.sqlite3_changes(p); |
| 950 | } |
| 951 | }, |
| 952 | /** |
| 953 | Similar to the this.filename but returns the |
| 954 | sqlite3_db_filename() value for the given database name, |
| 955 | defaulting to "main". The argument may be either a JS string |
| 956 | or a pointer to a WASM-allocated C-string. |
| 957 | |
| 958 | this.filename may be in the form of a URI-style string, whereas |
| 959 | the returned string contains only the filename part. |
| 960 | */ |
| 961 | dbFilename: function(dbName='main'){ |
| 962 | return capi.sqlite3_db_filename(affirmDbOpen(this).pointer, dbName); |
| 963 | }, |
| 964 | /** |
| 965 | Returns the name of the given 0-based db number, as documented |
| 966 | for sqlite3_db_name(). |
| 967 | */ |
| 968 | dbName: function(dbNumber=0){ |
| 969 | return capi.sqlite3_db_name(affirmDbOpen(this).pointer, dbNumber); |
| 970 | }, |
| 971 | /** |
| 972 | Returns the name of the sqlite3_vfs used by the given database |
| 973 | of this connection (defaulting to 'main'). The argument may be |
| 974 | either a JS string or a WASM C-string. Returns undefined if the |
| 975 | given db name is invalid. Throws if this object has been |
| 976 | close()d. |
| 977 | */ |
| 978 | dbVfsName: function(dbName=0){ |
| 979 | let rc; |
| 980 | const pVfs = capi.sqlite3_js_db_vfs( |
| 981 | affirmDbOpen(this).pointer, dbName |
| 982 | ); |
| 983 | if(pVfs){ |
| 984 | const v = new capi.sqlite3_vfs(pVfs); |
| 985 | try{ rc = wasm.cstrToJs(v.$zName) } |
| 986 | finally { v.dispose() } |
| 987 | } |
| 988 | return rc; |
| 989 | }, |
| 990 | /** |
| 991 | Compiles the given SQL and returns a prepared Stmt. This is |
| 992 | the only way to create new Stmt objects. Throws on error. |
| 993 | |
| 994 | The given SQL must be a string, a Uint8Array holding SQL, a |
| 995 | WASM pointer to memory holding the NUL-terminated SQL string, |
| 996 | or an array of strings. In the latter case, the array is |
| 997 | concatenated together, with no separators, to form the SQL |
| 998 | string (arrays are often a convenient way to formulate long |
| 999 | statements). If the SQL contains no statements, an |
| 1000 | SQLite3Error is thrown. |
| 1001 | |
| 1002 | Design note: the C API permits empty SQL, reporting it as a 0 |
| 1003 | result code and a NULL stmt pointer. Supporting that case here |
| 1004 | would cause extra work for all clients: any use of the Stmt API |
| 1005 | on such a statement will necessarily throw, so clients would be |
| 1006 | required to check `stmt.pointer` after calling `prepare()` in |
| 1007 | order to determine whether the Stmt instance is empty or not. |
| 1008 | Long-time practice (with other sqlite3 script bindings) |
| 1009 | suggests that the empty-prepare case is sufficiently rare that |
| 1010 | supporting it here would simply hurt overall usability. |
| 1011 | */ |
| 1012 | prepare: function(sql){ |
| 1013 | affirmDbOpen(this); |
| 1014 | const stack = wasm.pstack.pointer; |
| 1015 | let ppStmt, pStmt; |
| 1016 | try{ |
| 1017 | ppStmt = wasm.pstack.alloc(8)/* output (sqlite3_stmt**) arg */; |
| 1018 | DB.checkRc(this, capi.sqlite3_prepare_v2(this.pointer, sql, -1, ppStmt, null)); |
| 1019 | pStmt = wasm.peekPtr(ppStmt); |
| 1020 | } |
| 1021 | finally { |
| 1022 | wasm.pstack.restore(stack); |
| 1023 | } |
| 1024 | if(!pStmt) toss3("Cannot prepare empty SQL."); |
| 1025 | const stmt = new Stmt(this, pStmt, BindTypes); |
| 1026 | __stmtMap.get(this)[pStmt] = stmt; |
| 1027 | return stmt; |
| 1028 | }, |
| 1029 | /** |
| 1030 | Executes one or more SQL statements in the form of a single |
| 1031 | string. Its arguments must be either (sql,optionsObject) or |
| 1032 | (optionsObject). In the latter case, optionsObject.sql must |
| 1033 | contain the SQL to execute. By default it returns this object |
| 1034 | but that can be changed via the `returnValue` option as |
| 1035 | described below. Throws on error. |
| 1036 | |
| 1037 | If no SQL is provided, or a non-string is provided, an |
| 1038 | exception is triggered. Empty SQL, on the other hand, is |
| 1039 | simply a no-op. |
| 1040 | |
| 1041 | The optional options object may contain any of the following |
| 1042 | properties: |
| 1043 | |
| 1044 | - `sql` = the SQL to run (unless it's provided as the first |
| 1045 | argument). This must be of type string, Uint8Array, or an array |
| 1046 | of strings. In the latter case they're concatenated together |
| 1047 | as-is, _with no separator_ between elements, before evaluation. |
| 1048 | The array form is often simpler for long hand-written queries. |
| 1049 | |
| 1050 | - `bind` = a single value valid as an argument for |
| 1051 | Stmt.bind(). This is _only_ applied to the _first_ non-empty |
| 1052 | statement in the SQL which has any bindable parameters. (Empty |
| 1053 | statements are skipped entirely.) |
| 1054 | |
| 1055 | - `saveSql` = an optional array. If set, the SQL of each |
| 1056 | executed statement is appended to this array before the |
| 1057 | statement is executed (but after it is prepared - we don't have |
| 1058 | the string until after that). Empty SQL statements are elided |
| 1059 | but can have odd effects in the output. e.g. SQL of: `"select |
| 1060 | 1; -- empty\n; select 2"` will result in an array containing |
| 1061 | `["select 1;", "--empty \n; select 2"]`. That's simply how |
| 1062 | sqlite3 records the SQL for the 2nd statement. |
| 1063 | |
| 1064 | ================================================================== |
| 1065 | The following options apply _only_ to the _first_ statement |
| 1066 | which has a non-zero result column count, regardless of whether |
| 1067 | the statement actually produces any result rows. |
| 1068 | ================================================================== |
| 1069 | |
| 1070 | - `columnNames`: if this is an array, the column names of the |
| 1071 | result set are stored in this array before the callback (if |
| 1072 | any) is triggered (regardless of whether the query produces any |
| 1073 | result rows). If no statement has result columns, this value is |
| 1074 | unchanged. Achtung: an SQL result may have multiple columns |
| 1075 | with identical names. |
| 1076 | |
| 1077 | - `callback` = a function which gets called for each row of the |
| 1078 | result set, but only if that statement has any result rows. The |
| 1079 | callback's "this" is the options object, noting that this |
| 1080 | function synthesizes one if the caller does not pass one to |
| 1081 | exec(). The first argument passed to the callback is described |
| 1082 | below. The second argument is always the current Stmt object, |
| 1083 | as it's needed if the caller wants to fetch the column names or |
| 1084 | some such (noting that they could also be fetched via |
| 1085 | `this.columnNames`, if the client provides the `columnNames` |
| 1086 | option). If the callback returns a literal `false` (as opposed |
| 1087 | to any other falsy value, e.g. an implicit `undefined` return), |
| 1088 | any ongoing statement-`step()` iteration stops without an |
| 1089 | error. The return value of the callback is otherwise ignored. |
| 1090 | |
| 1091 | ACHTUNG: The callback MUST NOT modify the Stmt object. Calling |
| 1092 | any of the Stmt.get() variants, Stmt.getColumnName(), or |
| 1093 | similar, is legal, but calling step() or finalize() is |
| 1094 | not. Member methods which are illegal in this context will |
| 1095 | trigger an exception, but clients must also refrain from using |
| 1096 | any lower-level (C-style) APIs which might modify the |
| 1097 | statement. |
| 1098 | |
| 1099 | The first argument passed to the callback defaults to an array of |
| 1100 | values from the current result row but may be changed with ... |
| 1101 | |
| 1102 | - `rowMode` = specifies the type of he callback's first argument. |
| 1103 | It may be any of... |
| 1104 | |
| 1105 | A) A string describing what type of argument should be passed |
| 1106 | as the first argument to the callback: |
| 1107 | |
| 1108 | A.1) `'array'` (the default) causes the results of |
| 1109 | `stmt.get([])` to be passed to the `callback` and/or appended |
| 1110 | to `resultRows`. |
| 1111 | |
| 1112 | A.2) `'object'` causes the results of |
| 1113 | `stmt.get(Object.create(null))` to be passed to the |
| 1114 | `callback` and/or appended to `resultRows`. Achtung: an SQL |
| 1115 | result may have multiple columns with identical names. In |
| 1116 | that case, the right-most column will be the one set in this |
| 1117 | object! |
| 1118 | |
| 1119 | A.3) `'stmt'` causes the current Stmt to be passed to the |
| 1120 | callback, but this mode will trigger an exception if |
| 1121 | `resultRows` is an array because appending the transient |
| 1122 | statement to the array would be downright unhelpful. This |
| 1123 | option is a legacy feature, retained for backwards |
| 1124 | compatibility. The statement object is passed as the second |
| 1125 | argument to the callback, as described above. |
| 1126 | |
| 1127 | B) An integer, indicating a zero-based column in the result |
| 1128 | row. Only that one single value, in JS form, will be passed on. |
| 1129 | |
| 1130 | C) A string with a minimum length of 2 and leading character of |
| 1131 | '$' will fetch the row as an object, extract that one field, |
| 1132 | and pass that field's value to the callback. These keys are |
| 1133 | case-sensitive so must match the case used in the |
| 1134 | SQL. e.g. `"select a A from t"` with a `rowMode` of `'$A'` |
| 1135 | would work but `'$a'` would not. A reference to a column not in |
| 1136 | the result set will trigger an exception on the first row (as |
| 1137 | the check is not performed until rows are fetched). Note that |
| 1138 | `$` is a legal identifier character in JS so need not be |
| 1139 | quoted. |
| 1140 | |
| 1141 | Any other `rowMode` value triggers an exception. |
| 1142 | |
| 1143 | - `resultRows`: if this is an array, it functions similarly to |
| 1144 | the `callback` option: each row of the result set (if any), |
| 1145 | with the exception that the `rowMode` 'stmt' is not legal. It |
| 1146 | is legal to use both `resultRows` and `callback`, but |
| 1147 | `resultRows` is likely much simpler to use for small data sets |
| 1148 | and can be used over a WebWorker-style message interface. |
| 1149 | exec() throws if `resultRows` is set and `rowMode` is 'stmt'. |
| 1150 | |
| 1151 | - `returnValue`: is a string specifying what this function |
| 1152 | should return: |
| 1153 | |
| 1154 | A) The default value is (usually) `"this"`, meaning that the |
| 1155 | DB object itself should be returned. The exception is if |
| 1156 | the caller passes neither of `callback` nor `returnValue` |
| 1157 | but does pass an explicit `rowMode` then the default |
| 1158 | `returnValue` is `"resultRows"`, described below. |
| 1159 | |
| 1160 | B) `"resultRows"` means to return the value of the |
| 1161 | `resultRows` option. If `resultRows` is not set, this |
| 1162 | function behaves as if it were set to an empty array. |
| 1163 | |
| 1164 | C) `"saveSql"` means to return the value of the |
| 1165 | `saveSql` option. If `saveSql` is not set, this |
| 1166 | function behaves as if it were set to an empty array. |
| 1167 | |
| 1168 | Potential TODOs: |
| 1169 | |
| 1170 | - `bind`: permit an array of arrays/objects to bind. The first |
| 1171 | sub-array would act on the first statement which has bindable |
| 1172 | parameters (as it does now). The 2nd would act on the next such |
| 1173 | statement, etc. |
| 1174 | |
| 1175 | - `callback` and `resultRows`: permit an array entries with |
| 1176 | semantics similar to those described for `bind` above. |
| 1177 | |
| 1178 | OTOH, this function already does too much. |
| 1179 | */ |
| 1180 | exec: function(/*(sql [,obj]) || (obj)*/){ |
| 1181 | affirmDbOpen(this); |
| 1182 | const arg = parseExecArgs(this, arguments); |
| 1183 | if(!arg.sql){ |
| 1184 | return toss3("exec() requires an SQL string."); |
| 1185 | } |
| 1186 | const opt = arg.opt; |
| 1187 | const callback = opt.callback; |
| 1188 | const resultRows = |
| 1189 | Array.isArray(opt.resultRows) ? opt.resultRows : undefined; |
| 1190 | let stmt; |
| 1191 | let bind = opt.bind; |
| 1192 | let evalFirstResult = !!( |
| 1193 | arg.cbArg || opt.columnNames || resultRows |
| 1194 | ) /* true to step through the first result-returning statement */; |
| 1195 | const stack = wasm.scopedAllocPush(); |
| 1196 | const saveSql = Array.isArray(opt.saveSql) ? opt.saveSql : undefined; |
| 1197 | try{ |
| 1198 | const isTA = util.isSQLableTypedArray(arg.sql) |
| 1199 | /* Optimization: if the SQL is a TypedArray we can save some string |
| 1200 | conversion costs. */; |
| 1201 | /* Allocate the two output pointers (ppStmt, pzTail) and heap |
| 1202 | space for the SQL (pSql). When prepare_v3() returns, pzTail |
| 1203 | will point to somewhere in pSql. */ |
| 1204 | let sqlByteLen = isTA ? arg.sql.byteLength : wasm.jstrlen(arg.sql); |
| 1205 | const ppStmt = wasm.scopedAlloc( |
| 1206 | /* output (sqlite3_stmt**) arg and pzTail */ |
| 1207 | (2 * wasm.ptr.size) + (sqlByteLen + 1/* SQL + NUL */) |
| 1208 | ); |
| 1209 | const pzTail = wasm.ptr.add(ppStmt, wasm.ptr.size) /* final arg to sqlite3_prepare_v2() */; |
| 1210 | let pSql = wasm.ptr.add(pzTail, wasm.ptr.size); |
| 1211 | const pSqlEnd = wasm.ptr.add(pSql, sqlByteLen); |
| 1212 | if(isTA) wasm.heap8().set(arg.sql, pSql); |
| 1213 | else wasm.jstrcpy(arg.sql, wasm.heap8(), pSql, sqlByteLen, false); |
| 1214 | wasm.poke8(wasm.ptr.add(pSql, sqlByteLen), 0/*NUL terminator*/); |
| 1215 | while(pSql && wasm.peek8(pSql) |
| 1216 | /* Maintenance reminder:^^^ _must_ be 'i8' or else we |
| 1217 | will very likely cause an endless loop. What that's |
| 1218 | doing is checking for a terminating NUL byte. If we |
| 1219 | use i32 or similar then we read 4 bytes, read stuff |
| 1220 | around the NUL terminator, and get stuck in and |
| 1221 | endless loop at the end of the SQL, endlessly |
| 1222 | re-preparing an empty statement. */ ){ |
| 1223 | wasm.pokePtr([ppStmt, pzTail], 0); |
| 1224 | DB.checkRc(this, capi.sqlite3_prepare_v3( |
| 1225 | this.pointer, pSql, sqlByteLen, 0, ppStmt, pzTail |
| 1226 | )); |
| 1227 | const pStmt = wasm.peekPtr(ppStmt); |
| 1228 | pSql = wasm.peekPtr(pzTail); |
| 1229 | sqlByteLen = Number(wasm.ptr.add(pSqlEnd,-pSql)); |
| 1230 | if(!pStmt) continue; |
| 1231 | //sqlite3.config.debug("exec() pSql =",capi.sqlite3_sql(pStmt)); |
| 1232 | if(saveSql) saveSql.push(capi.sqlite3_sql(pStmt).trim()); |
| 1233 | stmt = new Stmt(this, pStmt, BindTypes); |
| 1234 | if(bind && stmt.parameterCount){ |
| 1235 | stmt.bind(bind); |
| 1236 | bind = null; |
| 1237 | } |
| 1238 | if(evalFirstResult && stmt.columnCount){ |
| 1239 | /* Only forward SELECT-style results for the FIRST query |
| 1240 | in the SQL which potentially has them. */ |
| 1241 | let gotColNames = Array.isArray( |
| 1242 | opt.columnNames |
| 1243 | /* As reported in |
| 1244 | https://sqlite.org/forum/forumpost/7774b773937cbe0a |
| 1245 | we need to delay fetching of the column names until |
| 1246 | after the first step() (if we step() at all) because |
| 1247 | a schema change between the prepare() and step(), via |
| 1248 | another connection, may invalidate the column count |
| 1249 | and names. */) ? 0 : 1; |
| 1250 | evalFirstResult = false; |
| 1251 | if(arg.cbArg || resultRows){ |
| 1252 | const cbArgCache = Object.create(null) |
| 1253 | /* 2nd arg for arg.cbArg, used by (at least) row-to-object |
| 1254 | converter */; |
| 1255 | for( ; stmt.step(); __execLock.delete(stmt) ){ |
| 1256 | if(0===gotColNames++){ |
| 1257 | stmt.getColumnNames(cbArgCache.columnNames = (opt.columnNames || [])); |
| 1258 | } |
| 1259 | __execLock.add(stmt); |
| 1260 | const row = arg.cbArg(stmt,cbArgCache); |
| 1261 | if(resultRows) resultRows.push(row); |
| 1262 | if(callback && false === callback.call(opt, row, stmt)){ |
| 1263 | break; |
| 1264 | } |
| 1265 | } |
| 1266 | __execLock.delete(stmt); |
| 1267 | } |
| 1268 | if(0===gotColNames){ |
| 1269 | /* opt.columnNames was provided but we visited no result rows */ |
| 1270 | stmt.getColumnNames(opt.columnNames); |
| 1271 | } |
| 1272 | }else{ |
| 1273 | stmt.step(); |
| 1274 | } |
| 1275 | stmt.reset( |
| 1276 | /* In order to trigger an exception in the |
| 1277 | INSERT...RETURNING locking scenario: |
| 1278 | https://sqlite.org/forum/forumpost/36f7a2e7494897df |
| 1279 | [tag:insert-returning-reset] |
| 1280 | */).finalize(); |
| 1281 | stmt = null; |
| 1282 | }/*prepare() loop*/ |
| 1283 | }/*catch(e){ |
| 1284 | sqlite3.config.warn("DB.exec() is propagating exception",opt,e); |
| 1285 | throw e; |
| 1286 | }*/finally{ |
| 1287 | if(stmt){ |
| 1288 | __execLock.delete(stmt); |
| 1289 | stmt.finalize(); |
| 1290 | } |
| 1291 | wasm.scopedAllocPop(stack); |
| 1292 | } |
| 1293 | return arg.returnVal(); |
| 1294 | }/*exec()*/, |
| 1295 | |
| 1296 | //#if 0 |
| 1297 | /** |
| 1298 | Experimental and untested - do not use. |
| 1299 | |
| 1300 | Prepares one or more SQL statements, passing each to a callback |
| 1301 | for processing. |
| 1302 | |
| 1303 | It requires an options object with the following properties: |
| 1304 | |
| 1305 | - "sql": SQL in any format accepted by exec(). |
| 1306 | |
| 1307 | - "callback" (function): gets passed each prepared statement, |
| 1308 | as described below. |
| 1309 | |
| 1310 | - "asPointer" (bool=false): if true, the callback is passed the |
| 1311 | WASM (sqlite3*) pointer instead of a Stmt object. |
| 1312 | |
| 1313 | - "saveSql" (array): if set, the SQL of each prepared statement |
| 1314 | is appended to this array. This can be used without a callback |
| 1315 | to split SQL into its component statements. Purely empty |
| 1316 | statements (for for which sqlite3_prepare() returns a NULL |
| 1317 | sqlite3_stmt, i.e. spaces and comments) are not added to this |
| 1318 | list unless... |
| 1319 | |
| 1320 | - "saveEmpty" (bool=false): If true, empty statements are |
| 1321 | retained in opt.saveSql, but their leading/trailing whitespace |
| 1322 | is trimmed (as for queries) so they may be empty. |
| 1323 | |
| 1324 | For each statement in the input SQL: |
| 1325 | |
| 1326 | 1) If opt.saveSql is set, the SQL is appended to it. |
| 1327 | |
| 1328 | 2) If callback is set, callback(S) is called, where S is either |
| 1329 | a Stmt object (by default) or an (sqlite3*) WASM pointer (if |
| 1330 | opt.asPointer is true). If the callback returns a literal true |
| 1331 | (as opposed to any other truthy value), ownership of S is |
| 1332 | transferred to the callback, otherwise S is reset and finalized |
| 1333 | as soon as the callback returns. If the callback throws, S is |
| 1334 | unconditionally finalized. |
| 1335 | |
| 1336 | If neither of opt.saveSql nor opt.callback are set, this |
| 1337 | function does nothing more than prepare and finalize each |
| 1338 | statement, which will trigger an exception if any of them |
| 1339 | contain invalid SQL. |
| 1340 | */ |
| 1341 | forEachStmt: function(opt){ |
| 1342 | affirmDbOpen(this); |
| 1343 | opt ??= Object.create(null); |
| 1344 | if(!opt.sql){ |
| 1345 | return toss3("exec() requires an SQL string."); |
| 1346 | } |
| 1347 | const sql = util.flexibleString(opt.sql); |
| 1348 | const callback = opt.callback; |
| 1349 | let stmt, pStmt; |
| 1350 | const stack = wasm.scopedAllocPush(); |
| 1351 | const saveSql = Array.isArray(opt.saveSql) ? opt.saveSql : undefined; |
| 1352 | try{ |
| 1353 | const isTA = util.isSQLableTypedArray(opt.sql) |
| 1354 | /* Optimization: if the SQL is a TypedArray we can save some string |
| 1355 | conversion costs. */; |
| 1356 | /* Allocate the two output pointers (ppStmt, pzTail) and heap |
| 1357 | space for the SQL (pSql). When prepare_v3() returns, pzTail |
| 1358 | will point to somewhere in pSql. */ |
| 1359 | let sqlByteLen = isTA ? opt.sql.byteLength : wasm.jstrlen(sql); |
| 1360 | const ppStmt = wasm.scopedAlloc( |
| 1361 | /* output (sqlite3_stmt**) arg and pzTail */ |
| 1362 | (2 * wasm.ptr.size) + (sqlByteLen + 1/* SQL + NUL */) |
| 1363 | ); |
| 1364 | const pzTail = wasm.ptr.add(ppStmt, wasm.ptr.size) /* final arg to sqlite3_prepare_v2() */; |
| 1365 | let pSql = wasm.ptr.add(pzTail, wasm.ptr.size) /* start of the SQL string */; |
| 1366 | const pSqlEnd = wasm.ptr.add(pSql, sqlByteLen); |
| 1367 | if(isTA) wasm.heap8().set(sql, pSql); |
| 1368 | else wasm.jstrcpy(sql, wasm.heap8(), pSql, sqlByteLen, false); |
| 1369 | wasm.poke8(wasm.ptr.add(pSql, sqlByteLen), 0/*NUL terminator*/); |
| 1370 | while( pSql && wasm.peek8(pSql) ){ |
| 1371 | pStmt = stmt = null; |
| 1372 | wasm.pokePtr([ppStmt, pzTail], 0); |
| 1373 | const zHead = pSql; |
| 1374 | DB.checkRc(this, capi.sqlite3_prepare_v3( |
| 1375 | this.pointer, pSql, sqlByteLen, 0, ppStmt, pzTail |
| 1376 | )); |
| 1377 | [pStmt, pSql] = wasm.peekPtr([ppStmt, pzTail]); |
| 1378 | sqlByteLen = wasm.ptr.addn(pSqlEnd,-pSql); |
| 1379 | if(opt.saveSql){ |
| 1380 | if( pStmt ) opt.saveSql.push(capi.sqlite3_sql(pStmt).trim()); |
| 1381 | else if( opt.saveEmpty ){ |
| 1382 | saveSql.push(wasm.typedArrayToString( |
| 1383 | wasm.heap8u(), Number(zHead), |
| 1384 | wasm.ptr.addn(zHead, sqlByteLen) |
| 1385 | ).trim(/*arguable*/)); |
| 1386 | } |
| 1387 | } |
| 1388 | if(!pStmt) continue; |
| 1389 | //sqlite3.config.debug("forEachStmt() pSql =",capi.sqlite3_sql(pStmt)); |
| 1390 | if( !opt.callback ){ |
| 1391 | capi.sqlite3_finalize(pStmt); |
| 1392 | pStmt = null; |
| 1393 | continue; |
| 1394 | } |
| 1395 | stmt = opt.asPointer ? null : new Stmt(this, pStmt, BindTypes); |
| 1396 | if( true===callaback(stmt || pStmt) ){ |
| 1397 | stmt = pStmt = null /*callback took ownership */; |
| 1398 | }else if(stmt){ |
| 1399 | pStmt = null; |
| 1400 | stmt.reset( |
| 1401 | /* See [tag:insert-returning-reset]. The thinking here is |
| 1402 | that if the callback didn't throw for this, it |
| 1403 | probably should have. |
| 1404 | */).finalize(); |
| 1405 | stmt = null; |
| 1406 | }else{ |
| 1407 | const rx = capi.sqlite3_reset(pStmt/*[tag:insert-returning-reset]*/); |
| 1408 | capi.sqlite3_finalize(pStmt); |
| 1409 | pStmt = null; |
| 1410 | DB.checkRc(this, rx); |
| 1411 | } |
| 1412 | }/*prepare() loop*/ |
| 1413 | }finally{ |
| 1414 | if(stmt) stmt.finalize(); |
| 1415 | else if(pStmt) capi.sqlite3_finalize(pStmt); |
| 1416 | wasm.scopedAllocPop(stack); |
| 1417 | } |
| 1418 | return this; |
| 1419 | }/*forEachStmt()*/, |
| 1420 | //#/if nope |
| 1421 | |
| 1422 | /** |
| 1423 | Creates a new UDF (User-Defined Function) which is accessible |
| 1424 | via SQL code. This function may be called in any of the |
| 1425 | following forms: |
| 1426 | |
| 1427 | - (name, function) |
| 1428 | - (name, function, optionsObject) |
| 1429 | - (name, optionsObject) |
| 1430 | - (optionsObject) |
| 1431 | |
| 1432 | In the final two cases, the function must be defined as the |
| 1433 | `callback` property of the options object (optionally called |
| 1434 | `xFunc` to align with the C API documentation). In the final |
| 1435 | case, the function's name must be the 'name' property. |
| 1436 | |
| 1437 | The first two call forms can only be used for creating scalar |
| 1438 | functions. Creating an aggregate or window function requires |
| 1439 | the options-object form (see below for details). |
| 1440 | |
| 1441 | UDFs can be removed as documented for |
| 1442 | sqlite3_create_function_v2() and |
| 1443 | sqlite3_create_window_function(), but doing so will "leak" the |
| 1444 | JS-created WASM binding of those functions (meaning that their |
| 1445 | entries in the WASM indirect function table still |
| 1446 | exist). Eliminating that potential leak is a pending TODO. |
| 1447 | |
| 1448 | On success, returns this object. Throws on error. |
| 1449 | |
| 1450 | When called from SQL arguments to the UDF, and its result, |
| 1451 | will be converted between JS and SQL with as much fidelity as |
| 1452 | is feasible, triggering an exception if a type conversion |
| 1453 | cannot be determined. The docs for sqlite3_create_function_v2() |
| 1454 | describe the conversions in more detail. |
| 1455 | |
| 1456 | The values set in the options object differ for scalar and |
| 1457 | aggregate functions: |
| 1458 | |
| 1459 | - Scalar: set the `xFunc` function-type property to the UDF |
| 1460 | function. |
| 1461 | |
| 1462 | - Aggregate: set the `xStep` and `xFinal` function-type |
| 1463 | properties to the "step" and "final" callbacks for the |
| 1464 | aggregate. Do not set the `xFunc` property. |
| 1465 | |
| 1466 | - Window: set the `xStep`, `xFinal`, `xValue`, and `xInverse` |
| 1467 | function-type properties. Do not set the `xFunc` property. |
| 1468 | |
| 1469 | The options object may optionally have an `xDestroy` |
| 1470 | function-type property, as per sqlite3_create_function_v2(). |
| 1471 | Its argument will be the WASM-pointer-type value of the `pApp` |
| 1472 | property, and this function will throw if `pApp` is defined but |
| 1473 | is not null, undefined, or a numeric (WASM pointer) |
| 1474 | value. i.e. `pApp`, if set, must be value suitable for use as a |
| 1475 | WASM pointer argument, noting that `null` or `undefined` will |
| 1476 | translate to 0 for that purpose. |
| 1477 | |
| 1478 | The options object may contain flags to modify how |
| 1479 | the function is defined: |
| 1480 | |
| 1481 | - `arity`: the number of arguments which SQL calls to this |
| 1482 | function expect or require. The default value is `xFunc.length` |
| 1483 | or `xStep.length` (i.e. the number of declared parameters it |
| 1484 | has) **MINUS 1** (see below for why). As a special case, if the |
| 1485 | `length` is 0, its arity is also 0 instead of -1. A negative |
| 1486 | arity value means that the function is variadic and may accept |
| 1487 | any number of arguments, up to sqlite3's compile-time |
| 1488 | limits. sqlite3 will enforce the argument count if is zero or |
| 1489 | greater. The callback always receives a pointer to an |
| 1490 | `sqlite3_context` object as its first argument. Any arguments |
| 1491 | after that are from SQL code. The leading context argument does |
| 1492 | _not_ count towards the function's arity. See the docs for |
| 1493 | sqlite3.capi.sqlite3_create_function_v2() for why that argument |
| 1494 | is needed in the interface. |
| 1495 | |
| 1496 | The following options-object properties correspond to flags |
| 1497 | documented at: |
| 1498 | |
| 1499 | https://sqlite.org/c3ref/create_function.html |
| 1500 | |
| 1501 | - `deterministic` = sqlite3.capi.SQLITE_DETERMINISTIC |
| 1502 | - `directOnly` = sqlite3.capi.SQLITE_DIRECTONLY |
| 1503 | - `innocuous` = sqlite3.capi.SQLITE_INNOCUOUS |
| 1504 | |
| 1505 | Sidebar: the ability to add new WASM-accessible functions to |
| 1506 | the runtime requires that the WASM build is compiled with the |
| 1507 | equivalent functionality as that provided by Emscripten's |
| 1508 | `-sALLOW_TABLE_GROWTH` flag. |
| 1509 | */ |
| 1510 | createFunction: function f(name, xFunc, opt){ |
| 1511 | const isFunc = (f)=>(f instanceof Function); |
| 1512 | switch(arguments.length){ |
| 1513 | case 1: /* (optionsObject) */ |
| 1514 | opt = name; |
| 1515 | name = opt.name; |
| 1516 | xFunc = opt.xFunc || 0; |
| 1517 | break; |
| 1518 | case 2: /* (name, callback|optionsObject) */ |
| 1519 | if(!isFunc(xFunc)){ |
| 1520 | opt = xFunc; |
| 1521 | xFunc = opt.xFunc || 0; |
| 1522 | } |
| 1523 | break; |
| 1524 | case 3: /* name, xFunc, opt */ |
| 1525 | break; |
| 1526 | default: break; |
| 1527 | } |
| 1528 | if(!opt) opt = {}; |
| 1529 | if('string' !== typeof name){ |
| 1530 | toss3("Invalid arguments: missing function name."); |
| 1531 | } |
| 1532 | let xStep = opt.xStep || 0; |
| 1533 | let xFinal = opt.xFinal || 0; |
| 1534 | const xValue = opt.xValue || 0; |
| 1535 | const xInverse = opt.xInverse || 0; |
| 1536 | let isWindow = undefined; |
| 1537 | if(isFunc(xFunc)){ |
| 1538 | isWindow = false; |
| 1539 | if(isFunc(xStep) || isFunc(xFinal)){ |
| 1540 | toss3("Ambiguous arguments: scalar or aggregate?"); |
| 1541 | } |
| 1542 | xStep = xFinal = null; |
| 1543 | }else if(isFunc(xStep)){ |
| 1544 | if(!isFunc(xFinal)){ |
| 1545 | toss3("Missing xFinal() callback for aggregate or window UDF."); |
| 1546 | } |
| 1547 | xFunc = null; |
| 1548 | }else if(isFunc(xFinal)){ |
| 1549 | toss3("Missing xStep() callback for aggregate or window UDF."); |
| 1550 | }else{ |
| 1551 | toss3("Missing function-type properties."); |
| 1552 | } |
| 1553 | if(false === isWindow){ |
| 1554 | if(isFunc(xValue) || isFunc(xInverse)){ |
| 1555 | toss3("xValue and xInverse are not permitted for non-window UDFs."); |
| 1556 | } |
| 1557 | }else if(isFunc(xValue)){ |
| 1558 | if(!isFunc(xInverse)){ |
| 1559 | toss3("xInverse must be provided if xValue is."); |
| 1560 | } |
| 1561 | isWindow = true; |
| 1562 | }else if(isFunc(xInverse)){ |
| 1563 | toss3("xValue must be provided if xInverse is."); |
| 1564 | } |
| 1565 | const pApp = opt.pApp; |
| 1566 | if( undefined!==pApp |
| 1567 | && null!==pApp |
| 1568 | && !wasm.isPtr(pApp) ){ |
| 1569 | toss3("Invalid value for pApp property. Must be a legal WASM pointer value."); |
| 1570 | } |
| 1571 | const xDestroy = opt.xDestroy || 0; |
| 1572 | if(xDestroy && !isFunc(xDestroy)){ |
| 1573 | toss3("xDestroy property must be a function."); |
| 1574 | } |
| 1575 | let fFlags = 0 /*flags for sqlite3_create_function_v2()*/; |
| 1576 | if(getOwnOption(opt, 'deterministic')) fFlags |= capi.SQLITE_DETERMINISTIC; |
| 1577 | if(getOwnOption(opt, 'directOnly')) fFlags |= capi.SQLITE_DIRECTONLY; |
| 1578 | if(getOwnOption(opt, 'innocuous')) fFlags |= capi.SQLITE_INNOCUOUS; |
| 1579 | name = name.toLowerCase(); |
| 1580 | const xArity = xFunc || xStep; |
| 1581 | const arity = getOwnOption(opt, 'arity'); |
| 1582 | const arityArg = ('number'===typeof arity |
| 1583 | ? arity |
| 1584 | : (xArity.length ? xArity.length-1/*for pCtx arg*/ : 0)); |
| 1585 | let rc; |
| 1586 | if( isWindow ){ |
| 1587 | rc = capi.sqlite3_create_window_function( |
| 1588 | this.pointer, name, arityArg, |
| 1589 | capi.SQLITE_UTF8 | fFlags, pApp || 0, |
| 1590 | xStep, xFinal, xValue, xInverse, xDestroy); |
| 1591 | }else{ |
| 1592 | rc = capi.sqlite3_create_function_v2( |
| 1593 | this.pointer, name, arityArg, |
| 1594 | capi.SQLITE_UTF8 | fFlags, pApp || 0, |
| 1595 | xFunc, xStep, xFinal, xDestroy); |
| 1596 | } |
| 1597 | DB.checkRc(this, rc); |
| 1598 | return this; |
| 1599 | }/*createFunction()*/, |
| 1600 | /** |
| 1601 | Prepares the given SQL, step()s it one time, and returns |
| 1602 | the value of the first result column. If it has no results, |
| 1603 | undefined is returned. |
| 1604 | |
| 1605 | If passed a second argument, it is treated like an argument |
| 1606 | to Stmt.bind(), so may be any type supported by that |
| 1607 | function. Passing the undefined value is the same as passing |
| 1608 | no value, which is useful when... |
| 1609 | |
| 1610 | If passed a 3rd argument, it is expected to be one of the |
| 1611 | SQLITE_{typename} constants. Passing the undefined value is |
| 1612 | the same as not passing a value. |
| 1613 | |
| 1614 | Throws on error (e.g. malformed SQL). |
| 1615 | */ |
| 1616 | selectValue: function(sql,bind,asType){ |
| 1617 | return __selectFirstRow(this, sql, bind, 0, asType); |
| 1618 | }, |
| 1619 | |
| 1620 | /** |
| 1621 | Runs the given query and returns an array of the values from |
| 1622 | the first result column of each row of the result set. The 2nd |
| 1623 | argument is an optional value for use in a single-argument call |
| 1624 | to Stmt.bind(). The 3rd argument may be any value suitable for |
| 1625 | use as the 2nd argument to Stmt.get(). If a 3rd argument is |
| 1626 | desired but no bind data are needed, pass `undefined` for the 2nd |
| 1627 | argument. |
| 1628 | |
| 1629 | If there are no result rows, an empty array is returned. |
| 1630 | */ |
| 1631 | selectValues: function(sql,bind,asType){ |
| 1632 | const stmt = this.prepare(sql), rc = []; |
| 1633 | try { |
| 1634 | affirmColIndex(stmt, 0); |
| 1635 | stmt.bind(bind); |
| 1636 | while(stmt.step()) rc.push( |
| 1637 | __stmtGetColumn(stmt, 0, asType) |
| 1638 | ); |
| 1639 | stmt.reset(/*for INSERT...RETURNING locking case*/); |
| 1640 | }finally{ |
| 1641 | stmt.finalize(); |
| 1642 | } |
| 1643 | return rc; |
| 1644 | }, |
| 1645 | |
| 1646 | /** |
| 1647 | Prepares the given SQL, step()s it one time, and returns an |
| 1648 | array containing the values of the first result row. If it has |
| 1649 | no results, `undefined` is returned. |
| 1650 | |
| 1651 | If passed a second argument other than `undefined`, it is |
| 1652 | treated like an argument to Stmt.bind(), so may be any type |
| 1653 | supported by that function. |
| 1654 | |
| 1655 | Throws on error (e.g. malformed SQL). |
| 1656 | */ |
| 1657 | selectArray: function(sql,bind){ |
| 1658 | return __selectFirstRow(this, sql, bind, []); |
| 1659 | }, |
| 1660 | |
| 1661 | /** |
| 1662 | Prepares the given SQL, step()s it one time, and returns an |
| 1663 | object containing the key/value pairs of the first result |
| 1664 | row. If it has no results, `undefined` is returned. |
| 1665 | |
| 1666 | Note that the order of returned object's keys is not guaranteed |
| 1667 | to be the same as the order of the fields in the query string. |
| 1668 | |
| 1669 | If passed a second argument other than `undefined`, it is |
| 1670 | treated like an argument to Stmt.bind(), so may be any type |
| 1671 | supported by that function. |
| 1672 | |
| 1673 | Throws on error (e.g. malformed SQL). |
| 1674 | */ |
| 1675 | selectObject: function(sql,bind){ |
| 1676 | return __selectFirstRow(this, sql, bind, {}); |
| 1677 | }, |
| 1678 | |
| 1679 | /** |
| 1680 | Runs the given SQL and returns an array of all results, with |
| 1681 | each row represented as an array, as per the 'array' `rowMode` |
| 1682 | option to `exec()`. An empty result set resolves |
| 1683 | to an empty array. The second argument, if any, is treated as |
| 1684 | the 'bind' option to a call to exec(). |
| 1685 | */ |
| 1686 | selectArrays: function(sql,bind){ |
| 1687 | return __selectAll(this, sql, bind, 'array'); |
| 1688 | }, |
| 1689 | |
| 1690 | /** |
| 1691 | Works identically to selectArrays() except that each value |
| 1692 | in the returned array is an object, as per the 'object' `rowMode` |
| 1693 | option to `exec()`. |
| 1694 | */ |
| 1695 | selectObjects: function(sql,bind){ |
| 1696 | return __selectAll(this, sql, bind, 'object'); |
| 1697 | }, |
| 1698 | |
| 1699 | /** |
| 1700 | Returns the number of currently-opened Stmt handles for this db |
| 1701 | handle, or 0 if this DB instance is closed. Only handles |
| 1702 | prepared via this.prepare() are counted, and not handles |
| 1703 | prepared using capi.sqlite3_prepare_v3() (or equivalent). |
| 1704 | */ |
| 1705 | openStatementCount: function(){ |
| 1706 | return this.pointer ? Object.keys(__stmtMap.get(this)).length : 0; |
| 1707 | }, |
| 1708 | |
| 1709 | /** |
| 1710 | Starts a transaction, calls the given callback, and then either |
| 1711 | rolls back or commits the transaction, depending on whether the |
| 1712 | callback throws. The callback is passed this db object as its |
| 1713 | only argument. On success, returns the result of the |
| 1714 | callback. Throws on error. |
| 1715 | |
| 1716 | Transactions may not be nested, so this will throw if it is |
| 1717 | called recursively. For nested transactions, use the |
| 1718 | savepoint() method or manually manage SAVEPOINTs using exec(). |
| 1719 | |
| 1720 | If called with 2 arguments, the first must be a keyword which |
| 1721 | is legal immediately after a BEGIN statement, e.g. one of |
| 1722 | "DEFERRED", "IMMEDIATE", or "EXCLUSIVE", though the exact list |
| 1723 | of supported keywords is not hard-coded here, in order to be |
| 1724 | future-compatible, if the argument does not look like a single |
| 1725 | keyword then an exception is triggered with a description of |
| 1726 | the problem. |
| 1727 | */ |
| 1728 | transaction: function(/* [beginQualifier,] */callback){ |
| 1729 | let opener = 'BEGIN'; |
| 1730 | if(arguments.length>1){ |
| 1731 | if(/[^a-zA-Z]/.test(arguments[0])){ |
| 1732 | toss3(capi.SQLITE_MISUSE, "Invalid argument for BEGIN qualifier."); |
| 1733 | } |
| 1734 | opener += ' '+arguments[0]; |
| 1735 | callback = arguments[1]; |
| 1736 | } |
| 1737 | affirmDbOpen(this).exec(opener); |
| 1738 | try { |
| 1739 | const rc = callback(this); |
| 1740 | this.exec("COMMIT"); |
| 1741 | return rc; |
| 1742 | }catch(e){ |
| 1743 | this.exec("ROLLBACK"); |
| 1744 | throw e; |
| 1745 | } |
| 1746 | }, |
| 1747 | |
| 1748 | /** |
| 1749 | This works similarly to transaction() but uses sqlite3's SAVEPOINT |
| 1750 | feature. This function starts a savepoint (with an unspecified name) |
| 1751 | and calls the given callback function, passing it this db object. |
| 1752 | If the callback returns, the savepoint is released (committed). If |
| 1753 | the callback throws, the savepoint is rolled back. If it does not |
| 1754 | throw, it returns the result of the callback. |
| 1755 | */ |
| 1756 | savepoint: function(callback){ |
| 1757 | affirmDbOpen(this).exec("SAVEPOINT oo1"); |
| 1758 | try { |
| 1759 | const rc = callback(this); |
| 1760 | this.exec("RELEASE oo1"); |
| 1761 | return rc; |
| 1762 | }catch(e){ |
| 1763 | this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"); |
| 1764 | throw e; |
| 1765 | } |
| 1766 | }, |
| 1767 | |
| 1768 | /** |
| 1769 | A convenience form of DB.checkRc(this,resultCode). If it does |
| 1770 | not throw, it returns this object. |
| 1771 | */ |
| 1772 | checkRc: function(resultCode){ |
| 1773 | return checkSqlite3Rc(this, resultCode); |
| 1774 | }, |
| 1775 | }/*DB.prototype*/; |
| 1776 | |
| 1777 | /** |
| 1778 | Returns a new oo1.DB instance which wraps the given (sqlite3*) |
| 1779 | WASM pointer, optionally with or without taking over ownership of |
| 1780 | that pointer. |
| 1781 | |
| 1782 | The first argument must be either a non-NULL (sqlite3*) WASM |
| 1783 | pointer. |
| 1784 | |
| 1785 | The second argument, defaulting to false, specifies ownership of |
| 1786 | the first argument. If it is truthy, the returned object will |
| 1787 | pass that pointer to sqlite3_close() when its close() method is |
| 1788 | called, otherwise it will not. |
| 1789 | |
| 1790 | Throws if pDb is not a non-0 WASM pointer. |
| 1791 | |
| 1792 | The caller MUST GUARANTEE that the passed-in handle will outlive |
| 1793 | the returned object, i.e. that it will not be closed. If it is closed, |
| 1794 | this object will hold a stale pointer and results are undefined. |
| 1795 | |
| 1796 | Aside from its lifetime, the proxy is to be treated as any other |
| 1797 | DB instance, including the requirement of calling close() on |
| 1798 | it. close() will free up internal resources owned by the proxy |
| 1799 | and disassociate the proxy from that handle but will not |
| 1800 | actually close the proxied db handle unless this function is |
| 1801 | passed a thruthy second argument. |
| 1802 | |
| 1803 | To stress: |
| 1804 | |
| 1805 | - DO NOT call sqlite3_close() (or similar) on the being-proxied |
| 1806 | pointer while a proxy is active. |
| 1807 | |
| 1808 | - ALWAYS eventually call close() on the returned object. If the |
| 1809 | proxy does not own the underlying handle then its MUST be |
| 1810 | closed BEFORE the being-proxied handle is closed. |
| 1811 | |
| 1812 | Design notes: |
| 1813 | |
| 1814 | - wrapHandle() "could" accept a DB object instance as its first |
| 1815 | argument and proxy thatDb.pointer but there is currently no use |
| 1816 | case where doing so would be useful, so it does not allow |
| 1817 | that. That restriction may be lifted in a future version. |
| 1818 | */ |
| 1819 | DB.wrapHandle = function(pDb, takeOwnership=false){ |
| 1820 | if( !pDb || !wasm.isPtr(pDb) ){ |
| 1821 | throw new sqlite3.SQLite3Error(capi.SQLITE_MISUSE, |
| 1822 | "Argument must be a WASM sqlite3 pointer"); |
| 1823 | } |
| 1824 | return new DB({ |
| 1825 | /* This ctor call style is very specifically internal-use-only. |
| 1826 | It is not documented and may change at any time. */ |
| 1827 | "sqlite3*": pDb, |
| 1828 | "sqlite3*:takeOwnership": !!takeOwnership |
| 1829 | }); |
| 1830 | }; |
| 1831 | |
| 1832 | /** Throws if the given Stmt has been finalized, else stmt is |
| 1833 | returned. */ |
| 1834 | const affirmStmtOpen = function(stmt){ |
| 1835 | if(!stmt.pointer) toss3("Stmt has been closed."); |
| 1836 | return stmt; |
| 1837 | }; |
| 1838 | |
| 1839 | /** Returns an opaque truthy value from the BindTypes |
| 1840 | enum if v's type is a valid bindable type, else |
| 1841 | returns a falsy value. As a special case, a value of |
| 1842 | undefined is treated as a bind type of null. */ |
| 1843 | const isSupportedBindType = function(v){ |
| 1844 | let t = BindTypes[(null===v||undefined===v) ? 'null' : typeof v]; |
| 1845 | switch(t){ |
| 1846 | case BindTypes.boolean: |
| 1847 | case BindTypes.null: |
| 1848 | case BindTypes.number: |
| 1849 | case BindTypes.string: |
| 1850 | return t; |
| 1851 | case BindTypes.bigint: |
| 1852 | return wasm.bigIntEnabled ? t : undefined; |
| 1853 | default: |
| 1854 | return util.isBindableTypedArray(v) ? BindTypes.blob : undefined; |
| 1855 | } |
| 1856 | }; |
| 1857 | |
| 1858 | /** |
| 1859 | If isSupportedBindType(v) returns a truthy value, this |
| 1860 | function returns that value, else it throws. |
| 1861 | */ |
| 1862 | const affirmSupportedBindType = function(v){ |
| 1863 | //sqlite3.config.log('affirmSupportedBindType',v); |
| 1864 | return isSupportedBindType(v) || toss3("Unsupported bind() argument type:",typeof v); |
| 1865 | }; |
| 1866 | |
| 1867 | /** |
| 1868 | If key is a number and within range of stmt's bound parameter |
| 1869 | count, key is returned. |
| 1870 | |
| 1871 | If key is not a number then it must be a JS string (not a WASM |
| 1872 | string) and it is checked against named parameters. If a match is |
| 1873 | found, its index is returned. |
| 1874 | |
| 1875 | Else it throws. |
| 1876 | */ |
| 1877 | const affirmParamIndex = function(stmt,key){ |
| 1878 | const n = ('number'===typeof key) |
| 1879 | ? key : capi.sqlite3_bind_parameter_index(stmt.pointer, key); |
| 1880 | if( 0===n || !util.isInt32(n) ) toss3("Invalid bind() parameter name: "+key); |
| 1881 | else if( n<1 || n>stmt.parameterCount ) toss3("Bind index",key,"is out of range."); |
| 1882 | return n; |
| 1883 | }; |
| 1884 | |
| 1885 | /** |
| 1886 | Each Stmt object which is "locked" by DB.exec() gets an entry |
| 1887 | here to note that "lock". |
| 1888 | |
| 1889 | The reason this is in place is because exec({callback:...})'s |
| 1890 | callback gets access to the Stmt objects created internally by |
| 1891 | exec() but it must not use certain Stmt APIs. |
| 1892 | */ |
| 1893 | const __execLock = new Set(); |
| 1894 | /** |
| 1895 | This is a Stmt.get() counterpart of __execLock. Each time |
| 1896 | Stmt.step() returns true, the statement is added to this set, |
| 1897 | indicating that Stmt.get() is legal. Stmt APIs which invalidate |
| 1898 | that status remove the Stmt object from this set, which will |
| 1899 | cause Stmt.get() to throw with a descriptive error message |
| 1900 | instead of a more generic "API misuse" if we were to allow that |
| 1901 | call to reach the C API. |
| 1902 | */ |
| 1903 | const __stmtMayGet = new Set(); |
| 1904 | |
| 1905 | /** |
| 1906 | Stmt APIs which are prohibited on locked objects must call |
| 1907 | affirmNotLockedByExec() before doing any work. |
| 1908 | |
| 1909 | If __execLock.has(stmt) is truthy, this throws an exception |
| 1910 | complaining that the 2nd argument (an operation name, |
| 1911 | e.g. "bind()") is not legal while the statement is "locked". |
| 1912 | Locking happens before an exec()-like callback is passed a |
| 1913 | statement, to ensure that the callback does not mutate or |
| 1914 | finalize the statement. If it does not throw, it returns stmt. |
| 1915 | */ |
| 1916 | const affirmNotLockedByExec = function(stmt,currentOpName){ |
| 1917 | if(__execLock.has(stmt)){ |
| 1918 | toss3("Operation is illegal when statement is locked:",currentOpName); |
| 1919 | } |
| 1920 | return stmt; |
| 1921 | }; |
| 1922 | |
| 1923 | /** |
| 1924 | Binds a single bound parameter value on the given stmt at the |
| 1925 | given index (numeric or named) using the given bindType (see |
| 1926 | the BindTypes enum) and value. Throws on error. Returns stmt on |
| 1927 | success. |
| 1928 | */ |
| 1929 | const bindOne = function f(stmt,ndx,bindType,val){ |
| 1930 | affirmNotLockedByExec(affirmStmtOpen(stmt), 'bind()'); |
| 1931 | if(!f._){ |
| 1932 | f._tooBigInt = (v)=>toss3( |
| 1933 | "BigInt value is too big to store without precision loss:", v |
| 1934 | ); |
| 1935 | f._ = { |
| 1936 | string: function(stmt, ndx, val, asBlob){ |
| 1937 | const [pStr, n] = wasm.allocCString(val, true); |
| 1938 | const f = asBlob ? capi.sqlite3_bind_blob : capi.sqlite3_bind_text; |
| 1939 | return f(stmt.pointer, ndx, pStr, n, capi.SQLITE_WASM_DEALLOC); |
| 1940 | } |
| 1941 | }; |
| 1942 | }/* static init */ |
| 1943 | affirmSupportedBindType(val); |
| 1944 | ndx = affirmParamIndex(stmt,ndx); |
| 1945 | let rc = 0; |
| 1946 | switch((null===val || undefined===val) ? BindTypes.null : bindType){ |
| 1947 | case BindTypes.null: |
| 1948 | rc = capi.sqlite3_bind_null(stmt.pointer, ndx); |
| 1949 | break; |
| 1950 | case BindTypes.string: |
| 1951 | rc = f._.string(stmt, ndx, val, false); |
| 1952 | break; |
| 1953 | case BindTypes.number: { |
| 1954 | let m; |
| 1955 | if(util.isInt32(val)) m = capi.sqlite3_bind_int; |
| 1956 | else if('bigint'===typeof val){ |
| 1957 | if(!util.bigIntFits64(val)){ |
| 1958 | f._tooBigInt(val); |
| 1959 | }else if(wasm.bigIntEnabled){ |
| 1960 | m = capi.sqlite3_bind_int64; |
| 1961 | }else if(util.bigIntFitsDouble(val)){ |
| 1962 | val = Number(val); |
| 1963 | m = capi.sqlite3_bind_double; |
| 1964 | }else{ |
| 1965 | f._tooBigInt(val); |
| 1966 | } |
| 1967 | }else{ // !int32, !bigint |
| 1968 | val = Number(val); |
| 1969 | if(wasm.bigIntEnabled && Number.isInteger(val)){ |
| 1970 | m = capi.sqlite3_bind_int64; |
| 1971 | }else{ |
| 1972 | m = capi.sqlite3_bind_double; |
| 1973 | } |
| 1974 | } |
| 1975 | rc = m(stmt.pointer, ndx, val); |
| 1976 | break; |
| 1977 | } |
| 1978 | case BindTypes.boolean: |
| 1979 | rc = capi.sqlite3_bind_int(stmt.pointer, ndx, val ? 1 : 0); |
| 1980 | break; |
| 1981 | case BindTypes.blob: { |
| 1982 | if('string'===typeof val){ |
| 1983 | rc = f._.string(stmt, ndx, val, true); |
| 1984 | break; |
| 1985 | }else if(val instanceof ArrayBuffer){ |
| 1986 | val = new Uint8Array(val); |
| 1987 | }else if(!util.isBindableTypedArray(val)){ |
| 1988 | toss3("Binding a value as a blob requires", |
| 1989 | "that it be a string, Uint8Array, Int8Array, or ArrayBuffer."); |
| 1990 | } |
| 1991 | const pBlob = wasm.alloc(val.byteLength || 1); |
| 1992 | wasm.heap8().set(val.byteLength ? val : [0], Number(pBlob)) |
| 1993 | rc = capi.sqlite3_bind_blob(stmt.pointer, ndx, pBlob, val.byteLength, |
| 1994 | capi.SQLITE_WASM_DEALLOC); |
| 1995 | break; |
| 1996 | } |
| 1997 | default: |
| 1998 | sqlite3.config.warn("Unsupported bind() argument type:",val); |
| 1999 | toss3("Unsupported bind() argument type: "+(typeof val)); |
| 2000 | } |
| 2001 | if(rc) DB.checkRc(stmt.db.pointer, rc); |
| 2002 | return stmt; |
| 2003 | }; |
| 2004 | |
| 2005 | Stmt.prototype = { |
| 2006 | /** |
| 2007 | "Finalizes" this statement. This is a no-op if the statement |
| 2008 | has already been finalized. Returns the result of |
| 2009 | sqlite3_finalize() (0 on success, non-0 on error), or the |
| 2010 | undefined value if the statement has already been |
| 2011 | finalized. Regardless of success or failure, most methods in |
| 2012 | this class will throw if called after this is. |
| 2013 | |
| 2014 | This method always throws if called when it is illegal to do |
| 2015 | so. Namely, when triggered via a per-row callback handler of a |
| 2016 | DB.exec() call. |
| 2017 | |
| 2018 | If Stmt does not own its underlying (sqlite3_stmt*) (see |
| 2019 | Stmt.wrapHandle()) then this function will not pass it to |
| 2020 | sqlite3_finalize() and will return 0. |
| 2021 | |
| 2022 | As of version 3.55, passing this object to sqlite3_finalize() |
| 2023 | is well-behaved, in that it will clean up the various |
| 2024 | oo1-related internal bookkeeping. It will, however, also bypass |
| 2025 | the statement-locking checks, enabling it to be (illegally) |
| 2026 | finalized at times when this method would otherwise throw. |
| 2027 | In prior versions doing so would leave this object holding |
| 2028 | a stale pointer. |
| 2029 | */ |
| 2030 | finalize: function(){ |
| 2031 | const ptr = this.pointer; |
| 2032 | if(ptr){ |
| 2033 | affirmNotLockedByExec(this,'finalize()'); |
| 2034 | if( __doesNotOwnHandle.delete(this) ){ |
| 2035 | __oo1NativeDisposerStmt(ptr, this); |
| 2036 | return 0; |
| 2037 | } |
| 2038 | return capi.sqlite3_finalize( |
| 2039 | ptr /* triggers __oo1NativeDisposerStmt */ |
| 2040 | ); |
| 2041 | } |
| 2042 | }, |
| 2043 | /** |
| 2044 | Clears all bound values. Returns this object. Throws if this |
| 2045 | statement has been finalized or if modification of the |
| 2046 | statement is currently illegal (e.g. in the per-row callback of |
| 2047 | a DB.exec() call). |
| 2048 | */ |
| 2049 | clearBindings: function(){ |
| 2050 | affirmNotLockedByExec(affirmStmtOpen(this), 'clearBindings()') |
| 2051 | capi.sqlite3_clear_bindings(this.pointer); |
| 2052 | __stmtMayGet.delete(this); |
| 2053 | return this; |
| 2054 | }, |
| 2055 | /** |
| 2056 | Resets this statement so that it may be step()ed again from the |
| 2057 | beginning. Returns this object. Throws if this statement has |
| 2058 | been finalized, if it may not legally be reset because it is |
| 2059 | currently being used from a DB.exec() callback, or if the |
| 2060 | underlying call to sqlite3_reset() returns non-0. |
| 2061 | |
| 2062 | If passed a truthy argument then this.clearBindings() is |
| 2063 | also called, otherwise any existing bindings, along with |
| 2064 | any memory allocated for them, are retained. |
| 2065 | |
| 2066 | Clients must not use capi.sqlite3_reset() with this object |
| 2067 | because this method does book-keeping specific to this class, |
| 2068 | e.g. the pieces which ensure that the column-fetching methods |
| 2069 | throw when called without a corresponding step(). |
| 2070 | |
| 2071 | In versions 3.42.0 and earlier, this function did not throw if |
| 2072 | sqlite3_reset() returns non-0, but it was discovered that |
| 2073 | throwing (or significant extra client-side code) is necessary |
| 2074 | in order to avoid certain silent failure scenarios, as |
| 2075 | discussed at: |
| 2076 | |
| 2077 | https://sqlite.org/forum/forumpost/36f7a2e7494897df |
| 2078 | */ |
| 2079 | reset: function(alsoClearBinds){ |
| 2080 | affirmNotLockedByExec(this,'reset()'); |
| 2081 | if(alsoClearBinds) this.clearBindings(); |
| 2082 | const rc = capi.sqlite3_reset(affirmStmtOpen(this).pointer); |
| 2083 | __stmtMayGet.delete(this); |
| 2084 | checkSqlite3Rc(this.db, rc); |
| 2085 | return this; |
| 2086 | }, |
| 2087 | |
| 2088 | /** |
| 2089 | Works like reset() except that it returns the underlying |
| 2090 | C-level result code instead of throwing if that code represents |
| 2091 | an error. |
| 2092 | |
| 2093 | Clients must not use capi.sqlite3_reset() for this purpose |
| 2094 | because this method (like reset()) does book-keeping specific |
| 2095 | to this class. |
| 2096 | |
| 2097 | Throws if an exec() is underway. |
| 2098 | |
| 2099 | The use case this addresses is when a step() fails due to, |
| 2100 | e.g., a locking error: a following reset() will report that |
| 2101 | locking error by throwing and that's sometimes inconvenient. |
| 2102 | |
| 2103 | Added in 3.54. |
| 2104 | */ |
| 2105 | resetNoThrow: function(alsoClearBinds){ |
| 2106 | affirmNotLockedByExec(this,'reset()'); |
| 2107 | if(alsoClearBinds) this.clearBindings(); |
| 2108 | const rc = capi.sqlite3_reset(affirmStmtOpen(this).pointer); |
| 2109 | __stmtMayGet.delete(this); |
| 2110 | return rc; |
| 2111 | }, |
| 2112 | |
| 2113 | /** |
| 2114 | Binds one or more values to its bindable parameters. It |
| 2115 | accepts 1 or 2 arguments: |
| 2116 | |
| 2117 | If passed a single argument, it must be either an array, an |
| 2118 | object, or a value of a bindable type (see below). |
| 2119 | |
| 2120 | If passed 2 arguments, the first one is the 1-based bind |
| 2121 | index or bindable parameter name and the second one must be |
| 2122 | a value of a bindable type. |
| 2123 | |
| 2124 | Bindable value types: |
| 2125 | |
| 2126 | - null is bound as NULL. |
| 2127 | |
| 2128 | - undefined as a standalone value is a no-op intended to |
| 2129 | simplify certain client-side use cases: passing undefined as |
| 2130 | a value to this function will not actually bind anything and |
| 2131 | this function will skip confirmation that binding is even |
| 2132 | legal. (Those semantics simplify certain client-side uses.) |
| 2133 | Conversely, a value of undefined as an array or object |
| 2134 | property when binding an array/object (see below) is treated |
| 2135 | the same as null. |
| 2136 | |
| 2137 | - Numbers are bound as either doubles or integers: doubles if |
| 2138 | they are larger than 32 bits, else double or int32, depending |
| 2139 | on whether they have a fractional part. Booleans are bound as |
| 2140 | integer 0 or 1. It is not expected the distinction of binding |
| 2141 | doubles which have no fractional parts and integers is |
| 2142 | significant for the majority of clients due to sqlite3's data |
| 2143 | typing model. If BigInt support is enabled then this routine |
| 2144 | will bind BigInt values as 64-bit integers if they'll fit in |
| 2145 | 64 bits. If that support disabled, it will store the BigInt |
| 2146 | as an int32 or a double if it can do so without loss of |
| 2147 | precision. If the BigInt is _too BigInt_ then it will throw. |
| 2148 | |
| 2149 | - Strings are bound as strings (use bindAsBlob() to force |
| 2150 | blob binding). |
| 2151 | |
| 2152 | - Uint8Array, Int8Array, and ArrayBuffer instances are bound as |
| 2153 | blobs. |
| 2154 | |
| 2155 | If passed an array, each element of the array is bound at |
| 2156 | the parameter index equal to the array index plus 1 |
| 2157 | (because arrays are 0-based but binding is 1-based). |
| 2158 | |
| 2159 | If passed an object, each object key is treated as a |
| 2160 | bindable parameter name. The object keys _must_ match any |
| 2161 | bindable parameter names, including any `$`, `@`, or `:` |
| 2162 | prefix. Because `$` is a legal identifier chararacter in |
| 2163 | JavaScript, that is the suggested prefix for bindable |
| 2164 | parameters: `stmt.bind({$a: 1, $b: 2})`. |
| 2165 | |
| 2166 | It returns this object on success and throws on |
| 2167 | error. Errors include: |
| 2168 | |
| 2169 | - Any bind index is out of range, a named bind parameter |
| 2170 | does not match, or this statement has no bindable |
| 2171 | parameters. |
| 2172 | |
| 2173 | - Any value to bind is of an unsupported type. |
| 2174 | |
| 2175 | - Passed no arguments or more than two. |
| 2176 | |
| 2177 | - The statement has been finalized. |
| 2178 | */ |
| 2179 | bind: function(/*[ndx,] arg*/){ |
| 2180 | affirmStmtOpen(this); |
| 2181 | let ndx, arg; |
| 2182 | switch(arguments.length){ |
| 2183 | case 1: ndx = 1; arg = arguments[0]; break; |
| 2184 | case 2: ndx = arguments[0]; arg = arguments[1]; break; |
| 2185 | default: toss3("Invalid bind() arguments."); |
| 2186 | } |
| 2187 | if(undefined===arg){ |
| 2188 | /* It might seem intuitive to bind undefined as NULL |
| 2189 | but this approach simplifies certain client-side |
| 2190 | uses when passing on arguments between 2+ levels of |
| 2191 | functions. */ |
| 2192 | return this; |
| 2193 | }else if(!this.parameterCount){ |
| 2194 | toss3("This statement has no bindable parameters."); |
| 2195 | } |
| 2196 | __stmtMayGet.delete(this); |
| 2197 | if(null===arg){ |
| 2198 | /* bind NULL */ |
| 2199 | return bindOne(this, ndx, BindTypes.null, arg); |
| 2200 | } |
| 2201 | else if(Array.isArray(arg)){ |
| 2202 | /* bind each entry by index */ |
| 2203 | if(1!==arguments.length){ |
| 2204 | toss3("When binding an array, an index argument is not permitted."); |
| 2205 | } |
| 2206 | arg.forEach((v,i)=>bindOne(this, i+1, affirmSupportedBindType(v), v)); |
| 2207 | return this; |
| 2208 | }else if(arg instanceof ArrayBuffer){ |
| 2209 | arg = new Uint8Array(arg); |
| 2210 | } |
| 2211 | if('object'===typeof arg/*null was checked above*/ |
| 2212 | && !util.isBindableTypedArray(arg)){ |
| 2213 | /* Treat each property of arg as a named bound parameter. */ |
| 2214 | if(1!==arguments.length){ |
| 2215 | toss3("When binding an object, an index argument is not permitted."); |
| 2216 | } |
| 2217 | Object.keys(arg) |
| 2218 | .forEach(k=>bindOne(this, k, |
| 2219 | affirmSupportedBindType(arg[k]), |
| 2220 | arg[k])); |
| 2221 | return this; |
| 2222 | }else{ |
| 2223 | return bindOne(this, ndx, affirmSupportedBindType(arg), arg); |
| 2224 | } |
| 2225 | toss3("Should not reach this point."); |
| 2226 | }, |
| 2227 | /** |
| 2228 | Special case of bind() which binds the given value using the |
| 2229 | BLOB binding mechanism instead of the default selected one for |
| 2230 | the value. The ndx may be a numbered or named bind index. The |
| 2231 | value must be of type string, null/undefined (both get treated |
| 2232 | as null), or a TypedArray of a type supported by the bind() |
| 2233 | API. This API cannot bind numbers as blobs. |
| 2234 | |
| 2235 | If passed a single argument, a bind index of 1 is assumed and |
| 2236 | the first argument is the value. |
| 2237 | */ |
| 2238 | bindAsBlob: function(ndx,arg){ |
| 2239 | affirmStmtOpen(this); |
| 2240 | if(1===arguments.length){ |
| 2241 | arg = ndx; |
| 2242 | ndx = 1; |
| 2243 | } |
| 2244 | const t = affirmSupportedBindType(arg); |
| 2245 | if(BindTypes.string !== t && BindTypes.blob !== t |
| 2246 | && BindTypes.null !== t){ |
| 2247 | toss3("Invalid value type for bindAsBlob()"); |
| 2248 | } |
| 2249 | return bindOne(this, ndx, BindTypes.blob, arg); |
| 2250 | }, |
| 2251 | /** |
| 2252 | Steps the statement one time. If the result indicates that a |
| 2253 | row of data is available, a truthy value is returned. If no |
| 2254 | row of data is available, a falsy value is returned. Throws on |
| 2255 | error. |
| 2256 | */ |
| 2257 | step: function(){ |
| 2258 | affirmNotLockedByExec(this, 'step()'); |
| 2259 | const rc = capi.sqlite3_step(affirmStmtOpen(this).pointer); |
| 2260 | switch(rc){ |
| 2261 | case capi.SQLITE_DONE: |
| 2262 | __stmtMayGet.delete(this); |
| 2263 | return false; |
| 2264 | case capi.SQLITE_ROW: |
| 2265 | __stmtMayGet.add(this); |
| 2266 | return true; |
| 2267 | default: |
| 2268 | __stmtMayGet.delete(this); |
| 2269 | sqlite3.config.warn("sqlite3_step() rc=",rc, |
| 2270 | capi.sqlite3_js_rc_str(rc), |
| 2271 | "SQL =", capi.sqlite3_sql(this.pointer)); |
| 2272 | DB.checkRc(this.db.pointer, rc); |
| 2273 | } |
| 2274 | }, |
| 2275 | /** |
| 2276 | Functions exactly like step() except that... |
| 2277 | |
| 2278 | 1) On success, it calls this.reset() and returns this object. |
| 2279 | |
| 2280 | 2) On error, it throws and does not call reset(). |
| 2281 | |
| 2282 | This is intended to simplify constructs like: |
| 2283 | |
| 2284 | ``` |
| 2285 | for(...) { |
| 2286 | stmt.bind(...).stepReset(); |
| 2287 | } |
| 2288 | ``` |
| 2289 | |
| 2290 | Note that the reset() call makes it illegal to call this.get() |
| 2291 | after the step. |
| 2292 | */ |
| 2293 | stepReset: function(){ |
| 2294 | this.step(); |
| 2295 | return this.reset(); |
| 2296 | }, |
| 2297 | /** |
| 2298 | Functions like step() except that it calls finalize() on this |
| 2299 | statement immediately after stepping, even if the step() call |
| 2300 | throws. |
| 2301 | |
| 2302 | On success, it returns true if the step indicated that a row of |
| 2303 | data was available, else it returns a falsy value. |
| 2304 | |
| 2305 | This is intended to simplify use cases such as: |
| 2306 | |
| 2307 | ``` |
| 2308 | aDb.prepare("insert into foo(a) values(?)").bind(123).stepFinalize(); |
| 2309 | ``` |
| 2310 | */ |
| 2311 | stepFinalize: function(){ |
| 2312 | try{ |
| 2313 | const rc = this.step(); |
| 2314 | this.reset(/*for INSERT...RETURNING locking case*/); |
| 2315 | return rc; |
| 2316 | }finally{ |
| 2317 | try{this.finalize()} |
| 2318 | catch(e){/*ignored*/} |
| 2319 | } |
| 2320 | }, |
| 2321 | |
| 2322 | /** |
| 2323 | Fetches the value from the given 0-based column index of |
| 2324 | the current data row, throwing if index is out of range. |
| 2325 | |
| 2326 | Requires that step() has just returned a truthy value, else |
| 2327 | an exception is thrown. |
| 2328 | |
| 2329 | By default it will determine the data type of the result |
| 2330 | automatically. If passed a second argument, it must be one of |
| 2331 | the enumeration values for sqlite3 types, which are defined as |
| 2332 | members of the sqlite3.capi namespace: SQLITE_INTEGER, |
| 2333 | SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB. Any other value, except |
| 2334 | for undefined, will trigger an exception. Passing undefined is |
| 2335 | the same as not passing a value. It is legal to, e.g., fetch an |
| 2336 | integer value as a string, in which case sqlite3 will convert |
| 2337 | the value to a string. |
| 2338 | |
| 2339 | Blobs are returned as Uint8Array instances. |
| 2340 | |
| 2341 | If ndx is an array, this function behaves a differently: it |
| 2342 | assigns the indexes of the array, from 0 to the number of |
| 2343 | result columns, to the values of the corresponding column, |
| 2344 | and returns that array. |
| 2345 | |
| 2346 | If ndx is a plain object, this function behaves even |
| 2347 | differentlier: it assigns the properties of the object to |
| 2348 | the values of their corresponding result columns and returns |
| 2349 | that object. |
| 2350 | |
| 2351 | Performance note: this class does not cache its column names |
| 2352 | because a reprepare may change them and we have(?) no(?) way of |
| 2353 | hooking into that to invalidate the cache. A side effect of |
| 2354 | that is that this function, when ndx is an object, has to copy |
| 2355 | those names from the WASM side on each call. When fetching many |
| 2356 | objects, DB.exec() can do so more efficiently by caching those |
| 2357 | names for the duration of the query. In large result sets the |
| 2358 | runtime difference is human-perceivable. |
| 2359 | |
| 2360 | Behavior change notice: prior to 3.54, the asType argument was |
| 2361 | ignored when ndx is an array or object, the justification being |
| 2362 | that we're generally fetching rows of mixed data types. As of |
| 2363 | 3.54, it still behaves that way when passed the undefined value |
| 2364 | resp. is not passed a value, but will coerce each column to the |
| 2365 | requested type if it is not the undefined value. It is not |
| 2366 | believed that this change adversely affects any existing |
| 2367 | client-level code because this argument was ignored and |
| 2368 | applications passing a non-undefined value were not necessarily |
| 2369 | getting back what they had specified (or did so only because |
| 2370 | all of the data was of that type, in which case the new |
| 2371 | behavior is identical for those queries). |
| 2372 | |
| 2373 | Potential TODO: add type ID SQLITE_JSON, which fetches the |
| 2374 | result as a string and passes it (if it's not null) to |
| 2375 | JSON.parse(), returning the result of that. Until then, |
| 2376 | getJSON() can be used for that. |
| 2377 | */ |
| 2378 | get: function(ndx,asType){ |
| 2379 | if(!__stmtMayGet.has(affirmStmtOpen(this))){ |
| 2380 | toss3("Stmt.step() has not (recently) returned true."); |
| 2381 | } |
| 2382 | if(Array.isArray(ndx)){ |
| 2383 | let i = 0; |
| 2384 | const n = this.columnCount; |
| 2385 | while(i<n){ |
| 2386 | ndx[i] = __stmtGetColumn(this, i, asType); |
| 2387 | ++i; |
| 2388 | } |
| 2389 | return ndx; |
| 2390 | }else if(ndx && 'object'===typeof ndx){ |
| 2391 | let i = 0; |
| 2392 | const n = this.columnCount; |
| 2393 | while(i<n){ |
| 2394 | ndx[capi.sqlite3_column_name(this.pointer,i)] = |
| 2395 | __stmtGetColumn(this, i, asType); |
| 2396 | ++i; |
| 2397 | } |
| 2398 | return ndx; |
| 2399 | } |
| 2400 | affirmColIndex(this, ndx); |
| 2401 | return __stmtGetColumn(this, ndx, asType); |
| 2402 | }, |
| 2403 | /** Equivalent to get(ndx) but coerces the result to an |
| 2404 | integer. */ |
| 2405 | getInt: function(ndx){return this.get(ndx,capi.SQLITE_INTEGER)}, |
| 2406 | /** Equivalent to get(ndx) but coerces the result to a |
| 2407 | float. */ |
| 2408 | getFloat: function(ndx){return this.get(ndx,capi.SQLITE_FLOAT)}, |
| 2409 | /** Equivalent to get(ndx) but coerces the result to a |
| 2410 | string. */ |
| 2411 | getString: function(ndx){return this.get(ndx,capi.SQLITE_TEXT)}, |
| 2412 | /** Equivalent to get(ndx) but coerces the result to a |
| 2413 | Uint8Array. */ |
| 2414 | getBlob: function(ndx){return this.get(ndx,capi.SQLITE_BLOB)}, |
| 2415 | /** |
| 2416 | A convenience wrapper around get() which fetches the value |
| 2417 | as a string and then, if it is not null, passes it to |
| 2418 | JSON.parse(), returning that result. Throws if parsing |
| 2419 | fails. If the result is null, null is returned. An empty |
| 2420 | string, on the other hand, will trigger an exception. |
| 2421 | */ |
| 2422 | getJSON: function(ndx){ |
| 2423 | const s = this.get(ndx, capi.SQLITE_STRING); |
| 2424 | return null===s ? s : JSON.parse(s); |
| 2425 | }, |
| 2426 | // Design note: the only reason most of these getters have a 'get' |
| 2427 | // prefix is for consistency with getVALUE_TYPE(). The latter |
| 2428 | // arguably really need that prefix for API readability and the |
| 2429 | // rest arguably don't, but consistency is a powerful thing. |
| 2430 | /** |
| 2431 | Returns the result column name of the given index, or |
| 2432 | throws if index is out of bounds or this statement has been |
| 2433 | finalized. This can be used without having run step() |
| 2434 | first. |
| 2435 | */ |
| 2436 | getColumnName: function(ndx){ |
| 2437 | return capi.sqlite3_column_name( |
| 2438 | affirmColIndex(affirmStmtOpen(this),ndx).pointer, ndx |
| 2439 | ); |
| 2440 | }, |
| 2441 | /** |
| 2442 | If this statement potentially has result columns, this function |
| 2443 | returns an array of all such names. If passed an array, it is |
| 2444 | used as the target and all names are appended to it. Returns |
| 2445 | the target array. Throws if this statement cannot have result |
| 2446 | columns. This object's columnCount property holds the number of |
| 2447 | columns. |
| 2448 | */ |
| 2449 | getColumnNames: function(tgt=[]){ |
| 2450 | affirmColIndex(affirmStmtOpen(this),0); |
| 2451 | const n = this.columnCount; |
| 2452 | for(let i = 0; i < n; ++i){ |
| 2453 | tgt.push(capi.sqlite3_column_name(this.pointer, i)); |
| 2454 | } |
| 2455 | return tgt; |
| 2456 | }, |
| 2457 | /** |
| 2458 | If this statement has named bindable parameters and the |
| 2459 | given name matches one, its 1-based bind index is |
| 2460 | returned. If no match is found, 0 is returned. If it has no |
| 2461 | bindable parameters, the undefined value is returned. |
| 2462 | */ |
| 2463 | getParamIndex: function(name){ |
| 2464 | return (affirmStmtOpen(this).parameterCount |
| 2465 | ? capi.sqlite3_bind_parameter_index(this.pointer, name) |
| 2466 | : undefined); |
| 2467 | }, |
| 2468 | /** |
| 2469 | If this statement has named bindable parameters and the given |
| 2470 | index refers to one, its name is returned, else null is |
| 2471 | returned. If this statement has no bound parameters, undefined |
| 2472 | is returned. |
| 2473 | |
| 2474 | Added in 3.47. |
| 2475 | */ |
| 2476 | getParamName: function(ndx){ |
| 2477 | return (affirmStmtOpen(this).parameterCount |
| 2478 | ? capi.sqlite3_bind_parameter_name(this.pointer, ndx) |
| 2479 | : undefined); |
| 2480 | }, |
| 2481 | |
| 2482 | /** |
| 2483 | Behaves like sqlite3_stmt_busy() but throws if this statement |
| 2484 | is closed and returns a value of type boolean instead of integer. |
| 2485 | |
| 2486 | Added in 3.47. |
| 2487 | */ |
| 2488 | isBusy: function(){ |
| 2489 | return 0!==capi.sqlite3_stmt_busy(affirmStmtOpen(this)); |
| 2490 | }, |
| 2491 | |
| 2492 | /** |
| 2493 | Behaves like sqlite3_stmt_readonly() but throws if this statement |
| 2494 | is closed and returns a value of type boolean instead of integer. |
| 2495 | |
| 2496 | Added in 3.47. |
| 2497 | */ |
| 2498 | isReadOnly: function(){ |
| 2499 | return 0!==capi.sqlite3_stmt_readonly(affirmStmtOpen(this)); |
| 2500 | } |
| 2501 | }/*Stmt.prototype*/; |
| 2502 | |
| 2503 | {/* Add the `pointer` property to DB and Stmt. */ |
| 2504 | const prop = { |
| 2505 | enumerable: true, |
| 2506 | get: function(){return __ptrMap.get(this)}, |
| 2507 | set: ()=>toss3("The pointer property is read-only.") |
| 2508 | } |
| 2509 | Object.defineProperty(Stmt.prototype, 'pointer', prop); |
| 2510 | Object.defineProperty(DB.prototype, 'pointer', prop); |
| 2511 | } |
| 2512 | /** |
| 2513 | Stmt.columnCount is an interceptor for sqlite3_column_count(). |
| 2514 | |
| 2515 | This requires an unfortunate performance hit compared to caching |
| 2516 | columnCount when the Stmt is created/prepared (as was done in |
| 2517 | SQLite <=3.42.0), but is necessary in order to handle certain |
| 2518 | corner cases, as described in |
| 2519 | https://sqlite.org/forum/forumpost/7774b773937cbe0a. |
| 2520 | */ |
| 2521 | Object.defineProperty(Stmt.prototype, 'columnCount', { |
| 2522 | enumerable: false, |
| 2523 | get: function(){return capi.sqlite3_column_count(this.pointer)}, |
| 2524 | set: ()=>toss3("The columnCount property is read-only.") |
| 2525 | }); |
| 2526 | |
| 2527 | Object.defineProperty(Stmt.prototype, 'parameterCount', { |
| 2528 | enumerable: false, |
| 2529 | get: function(){return capi.sqlite3_bind_parameter_count(this.pointer)}, |
| 2530 | set: ()=>toss3("The parameterCount property is read-only.") |
| 2531 | }); |
| 2532 | |
| 2533 | /** |
| 2534 | The Stmt counterpart of oo1.DB.wrapHandle(), this creates a Stmt |
| 2535 | instance which wraps a WASM (sqlite3_stmt*) in the oo1 API, |
| 2536 | optionally with or without taking over ownership of that pointer. |
| 2537 | |
| 2538 | The first argument must be an oo1.DB instance[^1]. |
| 2539 | |
| 2540 | The second argument must be a valid WASM (sqlite3_stmt*), as |
| 2541 | produced by sqlite3_prepare_v2() and sqlite3_prepare_v3(). |
| 2542 | |
| 2543 | The third argument, defaulting to false, specifies whether the |
| 2544 | returned Stmt object takes over ownership of the underlying |
| 2545 | (sqlite3_stmt*). If true, the returned object's finalize() method |
| 2546 | will finalize that handle, else it will not. If it is false, |
| 2547 | ownership of pStmt is unchanged and pStmt MUST outlive the |
| 2548 | returned object or results are undefined. |
| 2549 | |
| 2550 | This function throws if the arguments are invalid. On success it |
| 2551 | returns a new Stmt object which wraps the given statement |
| 2552 | pointer. |
| 2553 | |
| 2554 | Like all Stmt objects, the finalize() method must eventually be |
| 2555 | called on the returned object to free up internal resources, |
| 2556 | regardless of whether this function's third argument is true or |
| 2557 | not. |
| 2558 | |
| 2559 | [^1]: The first argument cannot be a (sqlite3*) because the |
| 2560 | resulting Stmt object requires a parent DB object. It is not yet |
| 2561 | determined whether it would be of general benefit to refactor the |
| 2562 | DB/Stmt pair internals to communicate in terms of the underlying |
| 2563 | (sqlite3*) rather than a DB object. If so, we could laxen the |
| 2564 | first argument's requirement and allow an (sqlite3*). Because |
| 2565 | DB.wrapHandle() enables multiple DB objects to proxy the same |
| 2566 | (sqlite3*), we cannot unambiguously translate the first arugment |
| 2567 | from (sqlite3*) to DB instances for us with this function's first |
| 2568 | argument. |
| 2569 | */ |
| 2570 | Stmt.wrapHandle = function(oo1db, pStmt, takeOwnership=false){ |
| 2571 | let ctor = Stmt; |
| 2572 | if( !(oo1db instanceof DB) || !oo1db.pointer ){ |
| 2573 | throw new sqlite3.SQLite3Error(sqlite3.SQLITE_MISUSE, |
| 2574 | "First argument must be an opened "+ |
| 2575 | "sqlite3.oo1.DB instance"); |
| 2576 | } |
| 2577 | if( !pStmt || !wasm.isPtr(pStmt) ){ |
| 2578 | throw new sqlite3.SQLite3Error(sqlite3.SQLITE_MISUSE, |
| 2579 | "Second argument must be a WASM "+ |
| 2580 | "sqlite3_stmt pointer"); |
| 2581 | } |
| 2582 | return new Stmt(oo1db, pStmt, BindTypes, !!takeOwnership); |
| 2583 | } |
| 2584 | |
| 2585 | /** The OO API's public namespace. */ |
| 2586 | sqlite3.oo1 = { |
| 2587 | DB, |
| 2588 | Stmt |
| 2589 | }/*oo1 object*/; |
| 2590 | |
| 2591 | }); |
| 2592 | //#else |
| 2593 | /* Built with the omit-oo1 flag. */ |
| 2594 | //#/if if not omit-oo1 |