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-vtab-helper.c-pp.js
| 1 | //#if not omit-vtab |
| 2 | /* |
| 3 | ** 2022-11-30 |
| 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 installs sqlite3.vtab, a namespace of helpers for use in |
| 15 | the creation of JavaScript implementations virtual tables. If built |
| 16 | without virtual table support then this function does nothing. |
| 17 | */ |
| 18 | 'use strict'; |
| 19 | sqlite3ApiBootstrap.initializers.push(function(sqlite3){ |
| 20 | if( !sqlite3.wasm.exports.sqlite3_declare_vtab ){ |
| 21 | return; |
| 22 | } |
| 23 | const wasm = sqlite3.wasm, capi = sqlite3.capi, toss = sqlite3.util.toss3; |
| 24 | const vtab = Object.create(null); |
| 25 | sqlite3.vtab = vtab; |
| 26 | |
| 27 | const sii = capi.sqlite3_index_info; |
| 28 | /** |
| 29 | If n is >=0 and less than this.$nConstraint, this function |
| 30 | returns either a WASM pointer to the 0-based nth entry of |
| 31 | this.$aConstraint (if passed a truthy 2nd argument) or an |
| 32 | sqlite3_index_info.sqlite3_index_constraint object wrapping that |
| 33 | address (if passed a falsy value or no 2nd argument). Returns a |
| 34 | falsy value if n is out of range. |
| 35 | */ |
| 36 | sii.prototype.nthConstraint = function(n, asPtr=false){ |
| 37 | if(n<0 || n>=this.$nConstraint) return false; |
| 38 | const ptr = wasm.ptr.add( |
| 39 | this.$aConstraint, |
| 40 | sii.sqlite3_index_constraint.structInfo.sizeof * n |
| 41 | ); |
| 42 | return asPtr ? ptr : new sii.sqlite3_index_constraint(ptr); |
| 43 | }; |
| 44 | |
| 45 | /** |
| 46 | Works identically to nthConstraint() but returns state from |
| 47 | this.$aConstraintUsage, so returns an |
| 48 | sqlite3_index_info.sqlite3_index_constraint_usage instance |
| 49 | if passed no 2nd argument or a falsy 2nd argument. |
| 50 | */ |
| 51 | sii.prototype.nthConstraintUsage = function(n, asPtr=false){ |
| 52 | if(n<0 || n>=this.$nConstraint) return false; |
| 53 | const ptr = wasm.ptr.add( |
| 54 | this.$aConstraintUsage, |
| 55 | sii.sqlite3_index_constraint_usage.structInfo.sizeof * n |
| 56 | ); |
| 57 | return asPtr ? ptr : new sii.sqlite3_index_constraint_usage(ptr); |
| 58 | }; |
| 59 | |
| 60 | /** |
| 61 | If n is >=0 and less than this.$nOrderBy, this function |
| 62 | returns either a WASM pointer to the 0-based nth entry of |
| 63 | this.$aOrderBy (if passed a truthy 2nd argument) or an |
| 64 | sqlite3_index_info.sqlite3_index_orderby object wrapping that |
| 65 | address (if passed a falsy value or no 2nd argument). Returns a |
| 66 | falsy value if n is out of range. |
| 67 | */ |
| 68 | sii.prototype.nthOrderBy = function(n, asPtr=false){ |
| 69 | if(n<0 || n>=this.$nOrderBy) return false; |
| 70 | const ptr = wasm.ptr.add( |
| 71 | this.$aOrderBy, |
| 72 | sii.sqlite3_index_orderby.structInfo.sizeof * n |
| 73 | ); |
| 74 | return asPtr ? ptr : new sii.sqlite3_index_orderby(ptr); |
| 75 | }; |
| 76 | |
| 77 | /** |
| 78 | Internal factory function for xVtab and xCursor impls. |
| 79 | |
| 80 | methodName is the JS-string name of the wrapper. StructType must |
| 81 | be a jaccwabyt StructType constructor. |
| 82 | */ |
| 83 | const __xWrapFactory = function(methodName,StructType){ |
| 84 | /** |
| 85 | If called with no arguments: creates a new StructType, |
| 86 | records its pointer-to-object mapping, and returns |
| 87 | it. |
| 88 | |
| 89 | If called with arguments, ptr must (A) be a StructType object |
| 90 | or (B) a WASM point (which is assumed to be a native pointer |
| 91 | for a StructType instance). For (A), it behaves like the |
| 92 | no-args case and returns its first argument. For B then it |
| 93 | fetches the associated StructType object and returns it, |
| 94 | unmapping that object if removeMapping is true. |
| 95 | */ |
| 96 | return function(ptr,removeMapping=false){ |
| 97 | if(0===arguments.length) ptr = new StructType; |
| 98 | if(ptr instanceof StructType){ |
| 99 | //T.assert(!this.has(ptr.pointer)); |
| 100 | this.set(ptr.pointer, ptr); |
| 101 | return ptr; |
| 102 | }else if(!wasm.isPtr(ptr)){ |
| 103 | sqlite3.SQLite3Error.toss("Invalid argument to",methodName+"()"); |
| 104 | } |
| 105 | let rc = this.get(ptr); |
| 106 | if(removeMapping) this.delete(ptr); |
| 107 | return rc; |
| 108 | }.bind(new Map); |
| 109 | }; |
| 110 | |
| 111 | /** |
| 112 | A factory function which implements a simple lifetime manager for |
| 113 | mappings between C struct pointers and their JS-level wrappers. |
| 114 | The first argument must be the logical name of the manager |
| 115 | (e.g. 'xVtab' or 'xCursor'), which is only used for error |
| 116 | reporting. The second must be the capi.XYZ struct-type value, |
| 117 | e.g. capi.sqlite3_vtab or capi.sqlite3_vtab_cursor. |
| 118 | |
| 119 | Returns an object with 4 methods: create(), get(), unget(), and |
| 120 | dispose(), plus a StructType member with the value of the 2nd |
| 121 | argument. The methods are documented in the body of this |
| 122 | function. |
| 123 | */ |
| 124 | const StructPtrMapper = function(name, StructType){ |
| 125 | const __xWrap = __xWrapFactory(name,StructType); |
| 126 | /** |
| 127 | This object houses a small API for managing mappings of (`T*`) |
| 128 | to StructType<T> objects, specifically within the lifetime |
| 129 | requirements of sqlite3_module methods. |
| 130 | */ |
| 131 | return Object.assign(Object.create(null),{ |
| 132 | /** The StructType object for this object's API. */ |
| 133 | StructType, |
| 134 | /** |
| 135 | Creates a new StructType object, writes its `pointer` |
| 136 | value to the given output pointer, and returns that |
| 137 | object. Its intended usage depends on StructType: |
| 138 | |
| 139 | sqlite3_vtab: to be called from sqlite3_module::xConnect() |
| 140 | or xCreate() implementations. |
| 141 | |
| 142 | sqlite3_vtab_cursor: to be called from xOpen(). |
| 143 | |
| 144 | This will throw if allocation of the StructType instance |
| 145 | fails or if ppOut is not a pointer-type value. |
| 146 | */ |
| 147 | create: (ppOut)=>{ |
| 148 | const rc = __xWrap(); |
| 149 | wasm.pokePtr(ppOut, rc.pointer); |
| 150 | return rc; |
| 151 | }, |
| 152 | /** |
| 153 | Returns the StructType object previously mapped to the |
| 154 | given pointer using create(). Its intended usage depends |
| 155 | on StructType: |
| 156 | |
| 157 | sqlite3_vtab: to be called from sqlite3_module methods which |
| 158 | take a (sqlite3_vtab*) pointer _except_ for |
| 159 | xDestroy()/xDisconnect(), which should use unget() or dispose(). |
| 160 | |
| 161 | sqlite3_vtab_cursor: to be called from any sqlite3_module methods |
| 162 | which take a `sqlite3_vtab_cursor*` argument except xClose(), |
| 163 | which should use unget() or dispose(). |
| 164 | |
| 165 | Rule to remember: _never_ call dispose() on an instance |
| 166 | returned by this function. |
| 167 | */ |
| 168 | get: (pCObj)=>__xWrap(pCObj), |
| 169 | /** |
| 170 | Identical to get() but also disconnects the mapping between the |
| 171 | given pointer and the returned StructType object, such that |
| 172 | future calls to this function or get() with the same pointer |
| 173 | will return the undefined value. Its intended usage depends |
| 174 | on StructType: |
| 175 | |
| 176 | sqlite3_vtab: to be called from sqlite3_module::xDisconnect() or |
| 177 | xDestroy() implementations or in error handling of a failed |
| 178 | xCreate() or xConnect(). |
| 179 | |
| 180 | sqlite3_vtab_cursor: to be called from xClose() or during |
| 181 | cleanup in a failed xOpen(). |
| 182 | |
| 183 | Calling this method obligates the caller to call dispose() on |
| 184 | the returned object when they're done with it. |
| 185 | */ |
| 186 | unget: (pCObj)=>__xWrap(pCObj,true), |
| 187 | /** |
| 188 | Works like unget() plus it calls dispose() on the |
| 189 | StructType object. |
| 190 | */ |
| 191 | dispose: (pCObj)=>__xWrap(pCObj,true)?.dispose?.() |
| 192 | }); |
| 193 | }; |
| 194 | |
| 195 | /** |
| 196 | A lifetime-management object for mapping `sqlite3_vtab*` |
| 197 | instances in sqlite3_module methods to capi.sqlite3_vtab |
| 198 | objects. |
| 199 | |
| 200 | The API docs are in the API-internal StructPtrMapper(). |
| 201 | */ |
| 202 | vtab.xVtab = StructPtrMapper('xVtab', capi.sqlite3_vtab); |
| 203 | |
| 204 | /** |
| 205 | A lifetime-management object for mapping `sqlite3_vtab_cursor*` |
| 206 | instances in sqlite3_module methods to capi.sqlite3_vtab_cursor |
| 207 | objects. |
| 208 | |
| 209 | The API docs are in the API-internal StructPtrMapper(). |
| 210 | */ |
| 211 | vtab.xCursor = StructPtrMapper('xCursor', capi.sqlite3_vtab_cursor); |
| 212 | |
| 213 | /** |
| 214 | Convenience form of creating an sqlite3_index_info wrapper, |
| 215 | intended for use in xBestIndex implementations. Note that the |
| 216 | caller is expected to call dispose() on the returned object |
| 217 | before returning. Though not _strictly_ required, as that object |
| 218 | does not own the pIdxInfo memory, it is nonetheless good form. |
| 219 | */ |
| 220 | vtab.xIndexInfo = (pIdxInfo)=>new capi.sqlite3_index_info(pIdxInfo); |
| 221 | |
| 222 | /** |
| 223 | Given an sqlite3_module method name and error object, this |
| 224 | function returns sqlite3.capi.SQLITE_NOMEM if (err instanceof |
| 225 | sqlite3.WasmAllocError), else it returns its second argument. Its |
| 226 | intended usage is in the methods of a sqlite3_vfs or |
| 227 | sqlite3_module: |
| 228 | |
| 229 | ``` |
| 230 | try{ |
| 231 | let rc = ... |
| 232 | return rc; |
| 233 | }catch(e){ |
| 234 | return sqlite3.vtab.xError( |
| 235 | 'xColumn', e, sqlite3.capi.SQLITE_XYZ); |
| 236 | // where SQLITE_XYZ is some call-appropriate result code. |
| 237 | } |
| 238 | ``` |
| 239 | |
| 240 | If no 3rd argument is provided, its default depends on |
| 241 | the error type: |
| 242 | |
| 243 | - An sqlite3.WasmAllocError always resolves to capi.SQLITE_NOMEM. |
| 244 | |
| 245 | - If err is an SQLite3Error then its `resultCode` property |
| 246 | is used. |
| 247 | |
| 248 | - If all else fails, capi.SQLITE_ERROR is used. |
| 249 | |
| 250 | If xError.errorReporter is a function, it is called in |
| 251 | order to report the error, else the error is not reported. |
| 252 | If that function throws, that exception is ignored. |
| 253 | */ |
| 254 | vtab.xError = function f(methodName, err, defaultRc){ |
| 255 | if(f.errorReporter instanceof Function){ |
| 256 | try{f.errorReporter("sqlite3_module::"+methodName+"(): "+err.message);} |
| 257 | catch(e){/*ignored*/} |
| 258 | } |
| 259 | let rc; |
| 260 | if(err instanceof sqlite3.WasmAllocError) rc = capi.SQLITE_NOMEM; |
| 261 | else if(arguments.length>2) rc = defaultRc; |
| 262 | else if(err instanceof sqlite3.SQLite3Error) rc = err.resultCode; |
| 263 | return rc || capi.SQLITE_ERROR; |
| 264 | }; |
| 265 | /** |
| 266 | Used by vtab.xError to report errors if it is a function. Clients |
| 267 | are free to replace this with their own function, or to a |
| 268 | non-function to disable it. |
| 269 | */ |
| 270 | vtab.xError.errorReporter = 1 ? sqlite3.config.error.bind(sqlite3.config) : false; |
| 271 | |
| 272 | /** |
| 273 | A helper for sqlite3_vtab::xRowid() and xUpdate() |
| 274 | implementations. It must be passed the final argument to one of |
| 275 | those methods (an output pointer to an int64 row ID) and the |
| 276 | value to store at the output pointer's address. Returns the same |
| 277 | as wasm.poke() and will throw if the 1st or 2nd arguments are |
| 278 | invalid for that function. |
| 279 | |
| 280 | Example xRowid impl: |
| 281 | |
| 282 | ``` |
| 283 | const xRowid = (pCursor, ppRowid64)=>{ |
| 284 | const c = vtab.xCursor(pCursor); |
| 285 | vtab.xRowid(ppRowid64, c.myRowId); |
| 286 | return 0; |
| 287 | }; |
| 288 | ``` |
| 289 | */ |
| 290 | vtab.xRowid = (ppRowid64, value)=>wasm.poke(ppRowid64, value, 'i64'); |
| 291 | |
| 292 | /** |
| 293 | A helper to initialize and set up an sqlite3_module object for |
| 294 | later installation into individual databases using |
| 295 | sqlite3_create_module(). Requires an object with the following |
| 296 | properties: |
| 297 | |
| 298 | - `methods`: an object containing a mapping of properties with |
| 299 | the C-side names of the sqlite3_module methods, e.g. xCreate, |
| 300 | xBestIndex, etc., to JS implementations for those functions. |
| 301 | Certain special-case handling is performed, as described below. |
| 302 | |
| 303 | - `catchExceptions` (default=false): if truthy, the given methods |
| 304 | are not mapped as-is, but are instead wrapped inside wrappers |
| 305 | which translate exceptions into result codes of SQLITE_ERROR or |
| 306 | SQLITE_NOMEM, depending on whether the exception is an |
| 307 | sqlite3.WasmAllocError. |
| 308 | |
| 309 | - OPTIONAL `struct`: a sqlite3.capi.sqlite3_module() instance. If |
| 310 | not set, one will be created automatically. If the current |
| 311 | "this" is-a sqlite3_module then it is unconditionally used in |
| 312 | place of `struct`. |
| 313 | |
| 314 | - OPTIONAL `iVersion`: if set, it must be an integer value and it |
| 315 | gets assigned to the `$iVersion` member of the struct object. |
| 316 | If it's _not_ set, and the passed-in `struct` object's `$iVersion` |
| 317 | is 0 (the default) then this function attempts to define a value |
| 318 | for that property based on the list of methods it has. |
| 319 | |
| 320 | If `catchExceptions` is false, it is up to the client to ensure |
| 321 | that no exceptions escape the methods, as doing so would move |
| 322 | them through the C API, leading to undefined |
| 323 | behavior. vtab.xError() is intended to assist in reporting |
| 324 | such exceptions. |
| 325 | |
| 326 | Certain methods may refer to the same implementation. To simplify |
| 327 | the definition of such methods: |
| 328 | |
| 329 | - If `methods.xConnect` is `true` then the value of |
| 330 | `methods.xCreate` is used in its place, and vice versa. sqlite |
| 331 | treats xConnect/xCreate functions specially if they are exactly |
| 332 | the same function (same pointer value). |
| 333 | |
| 334 | - If `methods.xDisconnect` is true then the value of |
| 335 | `methods.xDestroy` is used in its place, and vice versa. |
| 336 | |
| 337 | This is to facilitate creation of those methods inline in the |
| 338 | passed-in object without requiring the client to explicitly get a |
| 339 | reference to one of them in order to assign it to the other |
| 340 | one. |
| 341 | |
| 342 | The `catchExceptions`-installed handlers will account for |
| 343 | identical references to the above functions and will install the |
| 344 | same wrapper function for both. |
| 345 | |
| 346 | The given methods are expected to return integer values, as |
| 347 | expected by the C API. If `catchExceptions` is truthy, the return |
| 348 | value of the wrapped function will be used as-is and will be |
| 349 | translated to 0 if the function returns a falsy value (e.g. if it |
| 350 | does not have an explicit return). If `catchExceptions` is _not_ |
| 351 | active, the method implementations must explicitly return integer |
| 352 | values (because this method does not wrap such calls to coerce |
| 353 | returns to integers). |
| 354 | |
| 355 | Throws on error. On success, returns the sqlite3_module object |
| 356 | (`this` or `opt.struct` or a new sqlite3_module instance, |
| 357 | depending on how it's called). |
| 358 | */ |
| 359 | vtab.setupModule = function(opt){ |
| 360 | let createdMod = false; |
| 361 | const mod = (this instanceof capi.sqlite3_module) |
| 362 | ? this : (opt.struct || (createdMod = new capi.sqlite3_module())); |
| 363 | try{ |
| 364 | const methods = opt.methods || toss("Missing 'methods' object."); |
| 365 | for(const e of Object.entries({ |
| 366 | // -----^ ==> [k,v] triggers a broken code transformation in |
| 367 | // some versions of the emsdk toolchain. |
| 368 | xConnect: 'xCreate', xDisconnect: 'xDestroy' |
| 369 | })){ |
| 370 | // Remap X=true to X=Y for certain X/Y combinations |
| 371 | const k = e[0], v = e[1]; |
| 372 | if(true === methods[k]) methods[k] = methods[v]; |
| 373 | else if(true === methods[v]) methods[v] = methods[k]; |
| 374 | } |
| 375 | if(opt.catchExceptions){ |
| 376 | const fwrap = function(methodName, func){ |
| 377 | if(['xConnect','xCreate'].indexOf(methodName) >= 0){ |
| 378 | return function(pDb, pAux, argc, argv, ppVtab, pzErr){ |
| 379 | try{return func(...arguments) || 0} |
| 380 | catch(e){ |
| 381 | if(!(e instanceof sqlite3.WasmAllocError)){ |
| 382 | wasm.dealloc(wasm.peekPtr(pzErr)); |
| 383 | wasm.pokePtr(pzErr, wasm.allocCString(e.message)); |
| 384 | } |
| 385 | return vtab.xError(methodName, e); |
| 386 | } |
| 387 | }; |
| 388 | }else{ |
| 389 | return function(...args){ |
| 390 | try{return func(...args) || 0} |
| 391 | catch(e){ |
| 392 | return vtab.xError(methodName, e); |
| 393 | } |
| 394 | }; |
| 395 | } |
| 396 | }; |
| 397 | const mnames = [ |
| 398 | 'xCreate', 'xConnect', 'xBestIndex', 'xDisconnect', |
| 399 | 'xDestroy', 'xOpen', 'xClose', 'xFilter', 'xNext', |
| 400 | 'xEof', 'xColumn', 'xRowid', 'xUpdate', |
| 401 | 'xBegin', 'xSync', 'xCommit', 'xRollback', |
| 402 | 'xFindFunction', 'xRename', 'xSavepoint', 'xRelease', |
| 403 | 'xRollbackTo', 'xShadowName' |
| 404 | ]; |
| 405 | const remethods = Object.create(null); |
| 406 | for(const k of mnames){ |
| 407 | const m = methods[k]; |
| 408 | if(!(m instanceof Function)) continue; |
| 409 | else if('xConnect'===k && methods.xCreate===m){ |
| 410 | remethods[k] = methods.xCreate; |
| 411 | }else if('xCreate'===k && methods.xConnect===m){ |
| 412 | remethods[k] = methods.xConnect; |
| 413 | }else{ |
| 414 | remethods[k] = fwrap(k, m); |
| 415 | } |
| 416 | } |
| 417 | mod.installMethods(remethods, false); |
| 418 | }else{ |
| 419 | // No automatic exception handling. Trust the client |
| 420 | // to not throw. |
| 421 | mod.installMethods( |
| 422 | methods, !!opt.applyArgcCheck/*undocumented option*/ |
| 423 | ); |
| 424 | } |
| 425 | if(0===mod.$iVersion){ |
| 426 | let v; |
| 427 | if('number'===typeof opt.iVersion) v = opt.iVersion; |
| 428 | else if(mod.$xIntegrity) v = 4; |
| 429 | else if(mod.$xShadowName) v = 3; |
| 430 | else if(mod.$xSavePoint || mod.$xRelease || mod.$xRollbackTo) v = 2; |
| 431 | else v = 1; |
| 432 | mod.$iVersion = v; |
| 433 | } |
| 434 | }catch(e){ |
| 435 | if(createdMod) createdMod.dispose(); |
| 436 | throw e; |
| 437 | } |
| 438 | return mod; |
| 439 | }/*setupModule()*/; |
| 440 | |
| 441 | /** |
| 442 | Equivalent to calling vtab.setupModule() with this sqlite3_module |
| 443 | object as the call's `this`. |
| 444 | */ |
| 445 | capi.sqlite3_module.prototype.setupModule = function(opt){ |
| 446 | return vtab.setupModule.call(this, opt); |
| 447 | }; |
| 448 | }/*sqlite3ApiBootstrap.initializers.push()*/); |
| 449 | //#/if global snip |