Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/wasm/api/sqlite3-api-glue.c-pp.js # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / wasm / api / sqlite3-api-glue.c-pp.js` 2164 lines ยท 89512 bytes Raw Blame History 1 /* 2 2022-07-22 3 4 The author disclaims copyright to this source code. In place of a 5 legal notice, here is a blessing: 6 7 * May you do good and not evil. 8 * May you find forgiveness for yourself and forgive others. 9 * May you share freely, never taking more than you give. 10 11 *********************************************************************** 12 13 This file glues together disparate pieces of JS which are loaded in 14 previous steps of the sqlite3-api.js bootstrapping process: 15 sqlite3-api-prologue.js, whwasmutil.js, and jaccwabyt.js. It 16 initializes the main API pieces so that the downstream components 17 (e.g. sqlite3-api-oo1.js) have all of the infrastructure that they 18 need. 19 */ 20 sqlite3ApiBootstrap.initializers.push(function(sqlite3){ 21 'use strict'; 22 const toss = (...args)=>{throw new Error(args.join(' '))}; 23 const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util; 24 WhWasmUtilInstaller(wasm)/*injected via preprocessor*/; 25 26 //#if 0 27 /** 28 Please keep this block around as a maintenance reminder 29 that we cannot rely on this type of check. 30 31 This block fails on Safari, per a report at 32 https://sqlite.org/forum/forumpost/`e5b20e1feb`. 33 34 It turns out that what Safari serves from the indirect function 35 table (e.g. wasm.functionEntry(X)) is anonymous functions which 36 wrap the WASM functions, rather than returning the WASM 37 functions themselves. That means comparison of such functions 38 is useless for determining whether or not we have a specific 39 function from wasm.exports. i.e. if function X is indirection 40 function table entry N then wasm.exports.X is not equal to 41 wasm.functionEntry(N) in Safari, despite being so in the other 42 browsers. 43 */ 44 /** 45 Find a mapping for SQLITE_WASM_DEALLOC, which the API 46 guarantees is a WASM pointer to the same underlying function as 47 wasm.dealloc() (noting that wasm.dealloc() is permitted to be a 48 JS wrapper around the WASM function). There is unfortunately no 49 O(1) algorithm for finding this pointer: we have to walk the 50 WASM indirect function table to find it. However, experience 51 indicates that that particular function is always very close to 52 the front of the table (it's been entry #3 in all relevant 53 tests). 54 */ 55 const dealloc = wasm.exports[sqlite3.config.deallocExportName]; 56 const nFunc = wasm.functionTable().length; 57 let i; 58 for(i = 0; i < nFunc; ++i){ 59 const e = wasm.functionEntry(i); 60 if(dealloc === e){ 61 capi.SQLITE_WASM_DEALLOC = i; 62 break; 63 } 64 } 65 if(dealloc !== wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)){ 66 toss("Internal error: cannot find function pointer for SQLITE_WASM_DEALLOC."); 67 } 68 //#/if 69 70 /** 71 Signatures for the WASM-exported C-side functions. Each entry 72 is an array with 2+ elements: 73 74 [ "c-side name", 75 "result type" (wasm.xWrap() syntax), 76 [arg types in xWrap() syntax] 77 // ^^^ this needn't strictly be an array: it can be subsequent 78 // elements instead: [x,y,z] is equivalent to x,y,z 79 ] 80 81 Support for the API-specific data types in the result/argument 82 type strings gets plugged in at a later phase in the API 83 initialization process. 84 */ 85 const bindingSignatures = { 86 core: [ 87 /* Please keep these sorted by function name! No algos rely 88 on that but it helps human eyeballs. */ 89 ["sqlite3_aggregate_context","void*", "sqlite3_context*", "int"], 90 /* sqlite3_auto_extension() has a hand-written binding. */ 91 ["sqlite3_backup_init", "sqlite3_backup*", "sqlite3*", "string", "sqlite3*", "string"], 92 ["sqlite3_backup_step", "int", "sqlite3_backup*", "int"], 93 ["sqlite3_backup_finish", "int", "sqlite3_backup*"], 94 ["sqlite3_backup_remaining", "int", "sqlite3_backup*"], 95 ["sqlite3_backup_pagecount", "int", "sqlite3_backup*"], 96 /* sqlite3_bind_blob() and sqlite3_bind_text() have hand-written 97 bindings to permit more flexible inputs. */ 98 ["sqlite3_bind_double","int", "sqlite3_stmt*", "int", "f64"], 99 ["sqlite3_bind_int","int", "sqlite3_stmt*", "int", "int"], 100 ["sqlite3_bind_null",undefined, "sqlite3_stmt*", "int"], 101 ["sqlite3_bind_parameter_count", "int", "sqlite3_stmt*"], 102 ["sqlite3_bind_parameter_index","int", "sqlite3_stmt*", "string"], 103 ["sqlite3_bind_parameter_name", "string", "sqlite3_stmt*", "int"], 104 ["sqlite3_bind_pointer", "int", 105 "sqlite3_stmt*", "int", "*", "string:static", "*"], 106 /* sqlite_bind_text() is hand-written */ 107 ["sqlite3_bind_zeroblob", "int", "sqlite3_stmt*", "int", "int"], 108 ["sqlite3_busy_handler","int", [ 109 "sqlite3*", 110 new wasm.xWrap.FuncPtrAdapter({ 111 signature: 'i(pi)', 112 contextKey: (argv,argIndex)=>argv[0/* sqlite3* */] 113 }), 114 "*" 115 ]], 116 ["sqlite3_busy_timeout","int", "sqlite3*", "int"], 117 /* sqlite3_cancel_auto_extension() has a hand-written binding. */ 118 ["sqlite3_changes", "int", "sqlite3*"], 119 ["sqlite3_clear_bindings","int", "sqlite3_stmt*"], 120 ["sqlite3_close_v2", "int", "sqlite3*"], 121 ["sqlite3_collation_needed", "int", "sqlite3*", "*", "*"/*=>v(ppis)*/], 122 ["sqlite3_column_blob","*", "sqlite3_stmt*", "int"], 123 ["sqlite3_column_bytes","int", "sqlite3_stmt*", "int"], 124 ["sqlite3_column_count", "int", "sqlite3_stmt*"], 125 ["sqlite3_column_decltype", "string", "sqlite3_stmt*", "int"], 126 ["sqlite3_column_double","f64", "sqlite3_stmt*", "int"], 127 ["sqlite3_column_int","int", "sqlite3_stmt*", "int"], 128 ["sqlite3_column_name","string", "sqlite3_stmt*", "int"], 129 //#define proxy-text-apis 1 130 //#if not proxy-text-apis 131 /* Search this file for tag:proxy-text-apis to see what this is about. */ 132 ["sqlite3_column_text","string", "sqlite3_stmt*", "int"], 133 //#/if 134 ["sqlite3_column_type","int", "sqlite3_stmt*", "int"], 135 ["sqlite3_column_value","sqlite3_value*", "sqlite3_stmt*", "int"], 136 ["sqlite3_commit_hook", "void*", [ 137 "sqlite3*", 138 new wasm.xWrap.FuncPtrAdapter({ 139 name: 'sqlite3_commit_hook', 140 signature: 'i(p)', 141 contextKey: (argv)=>argv[0/* sqlite3* */] 142 }), 143 '*' 144 ]], 145 ["sqlite3_compileoption_get", "string", "int"], 146 ["sqlite3_compileoption_used", "int", "string"], 147 ["sqlite3_complete", "int", "string:flexible"], 148 ["sqlite3_context_db_handle", "sqlite3*", "sqlite3_context*"], 149 /* sqlite3_create_collation() and sqlite3_create_collation_v2() 150 use hand-written bindings to simplify passing of the callback 151 function. */ 152 /* sqlite3_create_function(), sqlite3_create_function_v2(), and 153 sqlite3_create_window_function() use hand-written bindings to 154 simplify handling of their function-type arguments. */ 155 ["sqlite3_data_count", "int", "sqlite3_stmt*"], 156 ["sqlite3_db_filename", "string", "sqlite3*", "string"], 157 ["sqlite3_db_handle", "sqlite3*", "sqlite3_stmt*"], 158 ["sqlite3_db_name", "string", "sqlite3*", "int"], 159 ["sqlite3_db_readonly", "int", "sqlite3*", "string"], 160 ["sqlite3_db_status", "int", "sqlite3*", "int", "*", "*", "int"], 161 ["sqlite3_errcode", "int", "sqlite3*"], 162 ["sqlite3_errmsg", "string", "sqlite3*"], 163 ["sqlite3_error_offset", "int", "sqlite3*"], 164 ["sqlite3_errstr", "string", "int"], 165 ["sqlite3_exec", "int", [ 166 "sqlite3*", "string:flexible", 167 new wasm.xWrap.FuncPtrAdapter({ 168 signature: 'i(pipp)', 169 bindScope: 'transient', 170 callProxy: (callback)=>{ 171 let aNames; 172 return (pVoid, nCols, pColVals, pColNames)=>{ 173 try { 174 const aVals = wasm.cArgvToJs(nCols, pColVals); 175 if(!aNames) aNames = wasm.cArgvToJs(nCols, pColNames); 176 return callback(aVals, aNames) | 0; 177 }catch(e){ 178 /* If we set the db error state here, the higher-level 179 exec() call replaces it with its own, so we have no way 180 of reporting the exception message except the console. We 181 must not propagate exceptions through the C API. Though 182 we make an effort to report OOM here, sqlite3_exec() 183 translates that into SQLITE_ABORT as well. */ 184 return e.resultCode || capi.SQLITE_ERROR; 185 } 186 } 187 } 188 }), 189 "*", "**" 190 ]], 191 ["sqlite3_expanded_sql", "string", "sqlite3_stmt*"], 192 ["sqlite3_extended_errcode", "int", "sqlite3*"], 193 ["sqlite3_extended_result_codes", "int", "sqlite3*", "int"], 194 ["sqlite3_file_control", "int", "sqlite3*", "string", "int", "*"], 195 ["sqlite3_finalize", "int", "sqlite3_stmt*"], 196 ["sqlite3_free", undefined,"*"], 197 ["sqlite3_get_autocommit", "int", "sqlite3*"], 198 ["sqlite3_get_auxdata", "*", "sqlite3_context*", "int"], 199 ["sqlite3_initialize", undefined], 200 ["sqlite3_interrupt", undefined, "sqlite3*"], 201 ["sqlite3_is_interrupted", "int", "sqlite3*"], 202 ["sqlite3_keyword_count", "int"], 203 ["sqlite3_keyword_name", "int", ["int", "**", "*"]], 204 ["sqlite3_keyword_check", "int", ["string", "int"]], 205 ["sqlite3_libversion", "string"], 206 ["sqlite3_libversion_number", "int"], 207 ["sqlite3_limit", "int", ["sqlite3*", "int", "int"]], 208 ["sqlite3_malloc", "*","int"], 209 ["sqlite3_next_stmt", "sqlite3_stmt*", ["sqlite3*","sqlite3_stmt*"]], 210 ["sqlite3_open", "int", "string", "*"], 211 ["sqlite3_open_v2", "int", "string", "*", "int", "string"], 212 /* sqlite3_prepare_v2() and sqlite3_prepare_v3() are handled 213 separately due to us requiring two different sets of semantics 214 for those, depending on how their SQL argument is provided. */ 215 /* sqlite3_randomness() uses a hand-written wrapper to extend 216 the range of supported argument types. */ 217 ["sqlite3_realloc", "*","*","int"], 218 ["sqlite3_reset", "int", "sqlite3_stmt*"], 219 /* sqlite3_reset_auto_extension() has a hand-written binding. */ 220 ["sqlite3_result_blob", undefined, "sqlite3_context*", "*", "int", "*"], 221 ["sqlite3_result_double", undefined, "sqlite3_context*", "f64"], 222 ["sqlite3_result_error", undefined, "sqlite3_context*", "string", "int"], 223 ["sqlite3_result_error_code", undefined, "sqlite3_context*", "int"], 224 ["sqlite3_result_error_nomem", undefined, "sqlite3_context*"], 225 ["sqlite3_result_error_toobig", undefined, "sqlite3_context*"], 226 ["sqlite3_result_int", undefined, "sqlite3_context*", "int"], 227 ["sqlite3_result_null", undefined, "sqlite3_context*"], 228 ["sqlite3_result_pointer", undefined, 229 "sqlite3_context*", "*", "string:static", "*"], 230 ["sqlite3_result_subtype", undefined, "sqlite3_value*", "int"], 231 ["sqlite3_result_text", undefined, "sqlite3_context*", "string", "int", "*"], 232 ["sqlite3_result_zeroblob", undefined, "sqlite3_context*", "int"], 233 ["sqlite3_rollback_hook", "void*", [ 234 "sqlite3*", 235 new wasm.xWrap.FuncPtrAdapter({ 236 name: 'sqlite3_rollback_hook', 237 signature: 'v(p)', 238 contextKey: (argv)=>argv[0/* sqlite3* */] 239 }), 240 '*' 241 ]], 242 /** 243 We do not have a way to automatically clean up destructors 244 which are automatically converted from JS functions via the 245 final argument to sqlite3_set_auxdata(). Because of that, 246 automatic function conversion is not supported for this 247 function. Clients should use wasm.installFunction() to create 248 such callbacks, then pass that pointer to 249 sqlite3_set_auxdata(). Relying on automated conversions here 250 would lead to leaks of JS/WASM proxy functions because 251 sqlite3_set_auxdata() is frequently called in UDFs. 252 253 The sqlite3.oo1.DB class's onclose handlers can be used for this 254 purpose. For example: 255 256 const pAuxDtor = wasm.installFunction('v(p)', function(ptr){ 257 //free ptr 258 }); 259 myDb.onclose = { 260 after: ()=>{ 261 wasm.uninstallFunction(pAuxDtor); 262 } 263 }; 264 265 Then pass pAuxDtor as the final argument to appropriate 266 sqlite3_set_auxdata() calls. 267 268 Prior to 3.49.0 this binding ostensibly had automatic 269 function conversion here but a typo prevented it from 270 working. Rather than fix it, it was removed because testing 271 the fix brought the huge potential for memory leaks to the 272 forefront. 273 274 275 */ 276 ["sqlite3_set_auxdata", undefined, [ 277 "sqlite3_context*", "int", "*","*"]], 278 ['sqlite3_set_errmsg', 'int', 'sqlite3*', 'int', 'string'], 279 ["sqlite3_shutdown", undefined], 280 ["sqlite3_sourceid", "string"], 281 ["sqlite3_sql", "string", "sqlite3_stmt*"], 282 ["sqlite3_status", "int", "int", "*", "*", "int"], 283 ["sqlite3_step", "int", "sqlite3_stmt*"], 284 ["sqlite3_stmt_busy", "int", "sqlite3_stmt*"], 285 ["sqlite3_stmt_readonly", "int", "sqlite3_stmt*"], 286 ["sqlite3_stmt_status", "int", "sqlite3_stmt*", "int", "int"], 287 ["sqlite3_strglob", "int", "string","string"], 288 ["sqlite3_stricmp", "int", "string", "string"], 289 ["sqlite3_strlike", "int", "string", "string","int"], 290 ["sqlite3_strnicmp", "int", "string", "string", "int"], 291 ["sqlite3_table_column_metadata", "int", 292 "sqlite3*", "string", "string", "string", 293 "**", "**", "*", "*", "*"], 294 ["sqlite3_total_changes", "int", "sqlite3*"], 295 ["sqlite3_trace_v2", "int", [ 296 "sqlite3*", "int", 297 new wasm.xWrap.FuncPtrAdapter({ 298 name: 'sqlite3_trace_v2::callback', 299 signature: 'i(ippp)', 300 contextKey: (argv,argIndex)=>argv[0/* sqlite3* */] 301 }), 302 "*" 303 ]], 304 ["sqlite3_txn_state", "int", ["sqlite3*","string"]], 305 /* sqlite3_uri_...() have very specific requirements for their 306 first C-string arguments, so we cannot perform any 307 string-type conversion on their first argument. */ 308 ["sqlite3_uri_boolean", "int", "sqlite3_filename", "string", "int"], 309 ["sqlite3_uri_key", "string", "sqlite3_filename", "int"], 310 ["sqlite3_uri_parameter", "string", "sqlite3_filename", "string"], 311 ["sqlite3_user_data","void*", "sqlite3_context*"], 312 ["sqlite3_value_blob", "*", "sqlite3_value*"], 313 ["sqlite3_value_bytes","int", "sqlite3_value*"], 314 ["sqlite3_value_double","f64", "sqlite3_value*"], 315 ["sqlite3_value_dup", "sqlite3_value*", "sqlite3_value*"], 316 ["sqlite3_value_free", undefined, "sqlite3_value*"], 317 ["sqlite3_value_frombind", "int", "sqlite3_value*"], 318 ["sqlite3_value_int","int", "sqlite3_value*"], 319 ["sqlite3_value_nochange", "int", "sqlite3_value*"], 320 ["sqlite3_value_numeric_type", "int", "sqlite3_value*"], 321 ["sqlite3_value_pointer", "*", "sqlite3_value*", "string:static"], 322 ["sqlite3_value_subtype", "int", "sqlite3_value*"], 323 //#if not proxy-text-apis 324 ["sqlite3_value_text", "string", "sqlite3_value*"], 325 //#/if 326 ["sqlite3_value_type", "int", "sqlite3_value*"], 327 ["sqlite3_vfs_find", "*", "string"], 328 ["sqlite3_vfs_register", "int", "sqlite3_vfs*", "int"], 329 ["sqlite3_vfs_unregister", "int", "sqlite3_vfs*"] 330 331 /* This list gets extended with optional pieces below */ 332 ]/*.core*/, 333 /** 334 Functions which require BigInt (int64) support are separated 335 from the others because we need to conditionally bind them or 336 apply dummy impls, depending on the capabilities of the 337 environment. (That said: we never actually build without 338 BigInt support, and such builds are untested.) 339 340 Not all of these functions directly require int64 but are only 341 for use with APIs which require int64. For example, the 342 vtab-related functions. 343 */ 344 int64: [ 345 ["sqlite3_bind_int64","int", ["sqlite3_stmt*", "int", "i64"]], 346 ["sqlite3_changes64","i64", ["sqlite3*"]], 347 ["sqlite3_column_int64","i64", ["sqlite3_stmt*", "int"]], 348 ["sqlite3_deserialize", "int", "sqlite3*", "string", "*", "i64", "i64", "int"] 349 /* Careful! Short version: de/serialize() are problematic because they 350 might use a different allocator than the user for managing the 351 deserialized block. de/serialize() are ONLY safe to use with 352 sqlite3_malloc(), sqlite3_free(), and its 64-bit variants. Because 353 of this, the canonical builds of sqlite3.wasm/js guarantee that 354 sqlite3.wasm.alloc() and friends use those allocators. Custom builds 355 may not guarantee that, however. */, 356 ["sqlite3_last_insert_rowid", "i64", ["sqlite3*"]], 357 ["sqlite3_malloc64", "*","i64"], 358 ["sqlite3_msize", "i64", "*"], 359 ["sqlite3_overload_function", "int", ["sqlite3*","string","int"]], 360 ["sqlite3_realloc64", "*","*", "i64"], 361 ["sqlite3_result_int64", undefined, "*", "i64"], 362 ["sqlite3_result_zeroblob64", "int", "*", "i64"], 363 ["sqlite3_serialize","*", "sqlite3*", "string", "*", "int"], 364 ["sqlite3_set_last_insert_rowid", undefined, ["sqlite3*", "i64"]], 365 ["sqlite3_status64", "int", "int", "*", "*", "int"], 366 ["sqlite3_db_status64", "int", "sqlite3*", "int", "*", "*", "int"], 367 ["sqlite3_total_changes64", "i64", ["sqlite3*"]], 368 ["sqlite3_update_hook", "*", [ 369 "sqlite3*", 370 new wasm.xWrap.FuncPtrAdapter({ 371 name: 'sqlite3_update_hook::callback', 372 signature: "v(pippj)", 373 contextKey: (argv)=>argv[0/* sqlite3* */], 374 callProxy: (callback)=>{ 375 return (p,op,z0,z1,rowid)=>{ 376 callback(p, op, wasm.cstrToJs(z0), wasm.cstrToJs(z1), rowid); 377 }; 378 } 379 }), 380 "*" 381 ]], 382 ["sqlite3_uri_int64", "i64", ["sqlite3_filename", "string", "i64"]], 383 ["sqlite3_value_int64","i64", "sqlite3_value*"] 384 /* This list gets extended with optional pieces below */ 385 ]/*.int64*/, 386 /** 387 Functions which are intended solely for API-internal use by the 388 WASM components, not client code. These get installed into 389 sqlite3.util. Some of them get exposed to clients via variants 390 in sqlite3_js_...(). 391 392 2024-01-11: these were renamed, with two underscores in the 393 prefix, to ensure that clients do not accidentally depend on 394 them. They have always been documented as internal-use-only, 395 so no clients "should" be depending on the old names. 396 */ 397 wasmInternal: [ 398 ["sqlite3__wasm_db_reset", "int", "sqlite3*"], 399 ["sqlite3__wasm_db_vfs", "sqlite3_vfs*", "sqlite3*","string"], 400 [/* DO NOT USE. This is deprecated since 2023-08-11 because it 401 can trigger assert() in debug builds when used with file 402 sizes which are not an exact multiple of a valid db page 403 size. This function is retained only so that 404 sqlite3_js_vfs_create_file() can continue to work (for a 405 given value of work), but that function emits a 406 config.warn() log message directing the reader to 407 alternatives. */ 408 "sqlite3__wasm_vfs_create_file", "int", "sqlite3_vfs*","string","*", "int" 409 ], 410 ["sqlite3__wasm_posix_create_file", "int", "string","*", "int"], 411 ["sqlite3__wasm_vfs_unlink", "int", "sqlite3_vfs*","string"], 412 ["sqlite3__wasm_qfmt_token","string:dealloc", "string","int"] 413 ]/*.wasmInternal*/ 414 } /*bindingSignatures*/; 415 416 if( !!wasm.exports.sqlite3_progress_handler ){ 417 bindingSignatures.core.push( 418 ["sqlite3_progress_handler", undefined, [ 419 "sqlite3*", "int", new wasm.xWrap.FuncPtrAdapter({ 420 name: 'xProgressHandler', 421 signature: 'i(p)', 422 bindScope: 'context', 423 contextKey: (argv,argIndex)=>argv[0/* sqlite3* */] 424 }), "*" 425 ]] 426 ); 427 } 428 429 if( !!wasm.exports.sqlite3_stmt_explain ){ 430 bindingSignatures.core.push( 431 ["sqlite3_stmt_explain", "int", "sqlite3_stmt*", "int"], 432 ["sqlite3_stmt_isexplain", "int", "sqlite3_stmt*"] 433 ); 434 } 435 436 if( !!wasm.exports.sqlite3_set_authorizer ){ 437 bindingSignatures.core.push( 438 ["sqlite3_set_authorizer", "int", [ 439 "sqlite3*", 440 new wasm.xWrap.FuncPtrAdapter({ 441 name: "sqlite3_set_authorizer::xAuth", 442 signature: "i(pi"+"ssss)", 443 contextKey: (argv, argIndex)=>argv[0/*(sqlite3*)*/], 444 /** 445 We use callProxy here to ensure (A) that exceptions 446 thrown from callback() have well-defined behavior and (B) 447 that its result is coerced to an integer. 448 */ 449 callProxy: (callback)=>{ 450 return (pV, iCode, s0, s1, s2, s3)=>{ 451 try{ 452 s0 = s0 && wasm.cstrToJs(s0); s1 = s1 && wasm.cstrToJs(s1); 453 s2 = s2 && wasm.cstrToJs(s2); s3 = s3 && wasm.cstrToJs(s3); 454 return callback(pV, iCode, s0, s1, s2, s3) | 0; 455 }catch(e){ 456 return e.resultCode || capi.SQLITE_ERROR; 457 } 458 } 459 } 460 }), 461 "*"/*pUserData*/ 462 ]] 463 ); 464 }/* sqlite3_set_authorizer() */ 465 466 if( !!wasm.exports.sqlite3_column_origin_name ){ 467 bindingSignatures.core.push( 468 ["sqlite3_column_database_name","string", "sqlite3_stmt*", "int"], 469 ["sqlite3_column_origin_name","string", "sqlite3_stmt*", "int"], 470 ["sqlite3_column_table_name","string", "sqlite3_stmt*", "int"] 471 ); 472 } 473 474 if(false && wasm.compileOptionUsed('SQLITE_ENABLE_NORMALIZE')){ 475 /* ^^^ "the problem" is that this is an optional feature and the 476 build-time function-export list does not currently take 477 optional features into account. */ 478 bindingSignatures.core.push(["sqlite3_normalized_sql", "string", "sqlite3_stmt*"]); 479 } 480 481 //#if enable-see 482 if( !!wasm.exports.sqlite3_key_v2 ){ 483 /** 484 This code is capable of using an SEE build but an SEE WASM 485 build is generally incompatible with SEE's license conditions. 486 The project's official stance on WASM builds of SEE is: it is 487 permitted for use internally within organizations which have 488 licensed SEE, but not for sites made available to the public or 489 to unlicensed end users because exposing an SEE build of 490 sqlite3.wasm effectively provides all clients with a working 491 copy of SEE. 492 */ 493 bindingSignatures.core.push( 494 ["sqlite3_key", "int", "sqlite3*", "string", "int"], 495 ["sqlite3_key_v2","int","sqlite3*","string","*","int"], 496 ["sqlite3_rekey", "int", "sqlite3*", "string", "int"], 497 ["sqlite3_rekey_v2", "int", "sqlite3*", "string", "*", "int"], 498 ["sqlite3_activate_see", undefined, "string"] 499 ); 500 } 501 //#/if enable-see 502 503 if( wasm.bigIntEnabled && !!wasm.exports.sqlite3_declare_vtab ){ 504 bindingSignatures.int64.push( 505 ["sqlite3_create_module", "int", 506 ["sqlite3*","string","sqlite3_module*","*"]], 507 ["sqlite3_create_module_v2", "int", 508 ["sqlite3*","string","sqlite3_module*","*","*"]], 509 ["sqlite3_declare_vtab", "int", ["sqlite3*", "string:flexible"]], 510 ["sqlite3_drop_modules", "int", ["sqlite3*", "**"]], 511 ["sqlite3_vtab_collation","string","sqlite3_index_info*","int"], 512 /*["sqlite3_vtab_config" is variadic and requires a hand-written 513 proxy.] */ 514 ["sqlite3_vtab_distinct","int", "sqlite3_index_info*"], 515 ["sqlite3_vtab_in","int", "sqlite3_index_info*", "int", "int"], 516 ["sqlite3_vtab_in_first", "int", "sqlite3_value*", "**"], 517 ["sqlite3_vtab_in_next", "int", "sqlite3_value*", "**"], 518 ["sqlite3_vtab_nochange","int", "sqlite3_context*"], 519 ["sqlite3_vtab_on_conflict","int", "sqlite3*"], 520 ["sqlite3_vtab_rhs_value","int", "sqlite3_index_info*", "int", "**"] 521 ); 522 }/* virtual table APIs */ 523 524 if(wasm.bigIntEnabled && !!wasm.exports.sqlite3_preupdate_hook){ 525 bindingSignatures.int64.push( 526 ["sqlite3_preupdate_blobwrite", "int", "sqlite3*"], 527 ["sqlite3_preupdate_count", "int", "sqlite3*"], 528 ["sqlite3_preupdate_depth", "int", "sqlite3*"], 529 ["sqlite3_preupdate_hook", "*", [ 530 "sqlite3*", 531 new wasm.xWrap.FuncPtrAdapter({ 532 name: 'sqlite3_preupdate_hook', 533 signature: "v(ppippjj)", 534 contextKey: (argv)=>argv[0/* sqlite3* */], 535 callProxy: (callback)=>{ 536 return (p,db,op,zDb,zTbl,iKey1,iKey2)=>{ 537 callback(p, db, op, wasm.cstrToJs(zDb), wasm.cstrToJs(zTbl), 538 iKey1, iKey2); 539 }; 540 } 541 }), 542 "*" 543 ]], 544 ["sqlite3_preupdate_new", "int", ["sqlite3*", "int", "**"]], 545 ["sqlite3_preupdate_old", "int", ["sqlite3*", "int", "**"]] 546 ); 547 } /* preupdate API */ 548 549 // Add session/changeset APIs... 550 if(wasm.bigIntEnabled 551 && !!wasm.exports.sqlite3changegroup_add 552 && !!wasm.exports.sqlite3session_create 553 && !!wasm.exports.sqlite3_preupdate_hook /* required by the session API */){ 554 /** 555 FuncPtrAdapter options for session-related callbacks with the 556 native signature "i(ps)". This proxy converts the 2nd argument 557 from a C string to a JS string before passing the arguments on 558 to the client-provided JS callback. 559 */ 560 const __ipsProxy = { 561 signature: 'i(ps)', 562 callProxy:(callback)=>{ 563 return (p,s)=>{ 564 try{return callback(p, wasm.cstrToJs(s)) | 0} 565 catch(e){return e.resultCode || capi.SQLITE_ERROR} 566 } 567 } 568 }; 569 570 bindingSignatures.int64.push( 571 ['sqlite3changegroup_add', 'int', ['sqlite3_changegroup*', 'int', 'void*']], 572 ['sqlite3changegroup_add_strm', 'int', [ 573 'sqlite3_changegroup*', 574 new wasm.xWrap.FuncPtrAdapter({ 575 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 576 }), 577 'void*' 578 ]], 579 ['sqlite3changegroup_delete', undefined, ['sqlite3_changegroup*']], 580 ['sqlite3changegroup_new', 'int', ['**']], 581 ['sqlite3changegroup_output', 'int', ['sqlite3_changegroup*', 'int*', '**']], 582 ['sqlite3changegroup_output_strm', 'int', [ 583 'sqlite3_changegroup*', 584 new wasm.xWrap.FuncPtrAdapter({ 585 name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient' 586 }), 587 'void*' 588 ]], 589 ['sqlite3changeset_apply', 'int', [ 590 'sqlite3*', 'int', 'void*', 591 new wasm.xWrap.FuncPtrAdapter({ 592 name: 'xFilter', bindScope: 'transient', ...__ipsProxy 593 }), 594 new wasm.xWrap.FuncPtrAdapter({ 595 name: 'xConflict', signature: 'i(pip)', bindScope: 'transient' 596 }), 597 'void*' 598 ]], 599 ['sqlite3changeset_apply_strm', 'int', [ 600 'sqlite3*', 601 new wasm.xWrap.FuncPtrAdapter({ 602 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 603 }), 604 'void*', 605 new wasm.xWrap.FuncPtrAdapter({ 606 name: 'xFilter', bindScope: 'transient', ...__ipsProxy 607 }), 608 new wasm.xWrap.FuncPtrAdapter({ 609 name: 'xConflict', signature: 'i(pip)', bindScope: 'transient' 610 }), 611 'void*' 612 ]], 613 ['sqlite3changeset_apply_v2', 'int', [ 614 'sqlite3*', 'int', 'void*', 615 new wasm.xWrap.FuncPtrAdapter({ 616 name: 'xFilter', bindScope: 'transient', ...__ipsProxy 617 }), 618 new wasm.xWrap.FuncPtrAdapter({ 619 name: 'xConflict', signature: 'i(pip)', bindScope: 'transient' 620 }), 621 'void*', '**', 'int*', 'int' 622 623 ]], 624 ['sqlite3changeset_apply_v2_strm', 'int', [ 625 'sqlite3*', 626 new wasm.xWrap.FuncPtrAdapter({ 627 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 628 }), 629 'void*', 630 new wasm.xWrap.FuncPtrAdapter({ 631 name: 'xFilter', bindScope: 'transient', ...__ipsProxy 632 }), 633 new wasm.xWrap.FuncPtrAdapter({ 634 name: 'xConflict', signature: 'i(pip)', bindScope: 'transient' 635 }), 636 'void*', '**', 'int*', 'int' 637 ]], 638 ['sqlite3changeset_apply_v3', 'int', [ 639 'sqlite3*', 'int', 'void*', 640 new wasm.xWrap.FuncPtrAdapter({ 641 name: 'xFilter', signature: 'i(pp)', bindScope: 'transient' 642 }), 643 new wasm.xWrap.FuncPtrAdapter({ 644 name: 'xConflict', signature: 'i(pip)', bindScope: 'transient' 645 }), 646 'void*', '**', 'int*', 'int' 647 648 ]], 649 ['sqlite3changeset_apply_v3_strm', 'int', [ 650 'sqlite3*', 651 new wasm.xWrap.FuncPtrAdapter({ 652 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 653 }), 654 'void*', 655 new wasm.xWrap.FuncPtrAdapter({ 656 name: 'xFilter', signature: 'i(pp)', bindScope: 'transient' 657 }), 658 new wasm.xWrap.FuncPtrAdapter({ 659 name: 'xConflict', signature: 'i(pip)', bindScope: 'transient' 660 }), 661 'void*', '**', 'int*', 'int' 662 ]], 663 ['sqlite3changeset_concat', 'int', ['int','void*', 'int', 'void*', 'int*', '**']], 664 ['sqlite3changeset_concat_strm', 'int', [ 665 new wasm.xWrap.FuncPtrAdapter({ 666 name: 'xInputA', signature: 'i(ppp)', bindScope: 'transient' 667 }), 668 'void*', 669 new wasm.xWrap.FuncPtrAdapter({ 670 name: 'xInputB', signature: 'i(ppp)', bindScope: 'transient' 671 }), 672 'void*', 673 new wasm.xWrap.FuncPtrAdapter({ 674 name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient' 675 }), 676 'void*' 677 ]], 678 ['sqlite3changeset_conflict', 'int', ['sqlite3_changeset_iter*', 'int', '**']], 679 ['sqlite3changeset_finalize', 'int', ['sqlite3_changeset_iter*']], 680 ['sqlite3changeset_fk_conflicts', 'int', ['sqlite3_changeset_iter*', 'int*']], 681 ['sqlite3changeset_invert', 'int', ['int', 'void*', 'int*', '**']], 682 ['sqlite3changeset_invert_strm', 'int', [ 683 new wasm.xWrap.FuncPtrAdapter({ 684 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 685 }), 686 'void*', 687 new wasm.xWrap.FuncPtrAdapter({ 688 name: 'xOutput', signature: 'i(ppi)', bindScope: 'transient' 689 }), 690 'void*' 691 ]], 692 ['sqlite3changeset_new', 'int', ['sqlite3_changeset_iter*', 'int', '**']], 693 ['sqlite3changeset_next', 'int', ['sqlite3_changeset_iter*']], 694 ['sqlite3changeset_old', 'int', ['sqlite3_changeset_iter*', 'int', '**']], 695 ['sqlite3changeset_op', 'int', [ 696 'sqlite3_changeset_iter*', '**', 'int*', 'int*','int*' 697 ]], 698 ['sqlite3changeset_pk', 'int', ['sqlite3_changeset_iter*', '**', 'int*']], 699 ['sqlite3changeset_start', 'int', ['**', 'int', '*']], 700 ['sqlite3changeset_start_strm', 'int', [ 701 '**', 702 new wasm.xWrap.FuncPtrAdapter({ 703 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 704 }), 705 'void*' 706 ]], 707 ['sqlite3changeset_start_v2', 'int', ['**', 'int', '*', 'int']], 708 ['sqlite3changeset_start_v2_strm', 'int', [ 709 '**', 710 new wasm.xWrap.FuncPtrAdapter({ 711 name: 'xInput', signature: 'i(ppp)', bindScope: 'transient' 712 }), 713 'void*', 'int' 714 ]], 715 ['sqlite3session_attach', 'int', ['sqlite3_session*', 'string']], 716 ['sqlite3session_changeset', 'int', ['sqlite3_session*', 'int*', '**']], 717 ['sqlite3session_changeset_size', 'i64', ['sqlite3_session*']], 718 ['sqlite3session_changeset_strm', 'int', [ 719 'sqlite3_session*', 720 new wasm.xWrap.FuncPtrAdapter({ 721 name: 'xOutput', signature: 'i(ppp)', bindScope: 'transient' 722 }), 723 'void*' 724 ]], 725 ['sqlite3session_config', 'int', ['int', 'void*']], 726 ['sqlite3session_create', 'int', ['sqlite3*', 'string', '**']], 727 //sqlite3session_delete() is bound manually 728 ['sqlite3session_diff', 'int', ['sqlite3_session*', 'string', 'string', '**']], 729 ['sqlite3session_enable', 'int', ['sqlite3_session*', 'int']], 730 ['sqlite3session_indirect', 'int', ['sqlite3_session*', 'int']], 731 ['sqlite3session_isempty', 'int', ['sqlite3_session*']], 732 ['sqlite3session_memory_used', 'i64', ['sqlite3_session*']], 733 ['sqlite3session_object_config', 'int', ['sqlite3_session*', 'int', 'void*']], 734 ['sqlite3session_patchset', 'int', ['sqlite3_session*', '*', '**']], 735 ['sqlite3session_patchset_strm', 'int', [ 736 'sqlite3_session*', 737 new wasm.xWrap.FuncPtrAdapter({ 738 name: 'xOutput', signature: 'i(ppp)', bindScope: 'transient' 739 }), 740 'void*' 741 ]], 742 ['sqlite3session_table_filter', undefined, [ 743 'sqlite3_session*', 744 new wasm.xWrap.FuncPtrAdapter({ 745 name: 'xFilter', ...__ipsProxy, 746 contextKey: (argv,argIndex)=>argv[0/* (sqlite3_session*) */] 747 }), 748 '*' 749 ]] 750 ); 751 }/*session/changeset APIs*/ 752 753 /** 754 Prepare JS<->C struct bindings for the non-opaque struct types we 755 need... 756 */ 757 sqlite3.StructBinder = Jaccwabyt({/*injected via preprocessor*/ 758 heap: wasm.heap8u, 759 alloc: wasm.alloc, 760 dealloc: wasm.dealloc, 761 bigIntEnabled: wasm.bigIntEnabled, 762 pointerIR: wasm.ptr.ir, 763 memberPrefix: /* Never change this: this prefix is baked into any 764 amount of code and client-facing docs. (Much 765 later: it probably should have been '$$', but see 766 the previous sentence.) */ '$' 767 }); 768 769 {// wasm.xWrap() bindings... 770 771 /* Convert Arrays and certain TypedArrays to strings for 772 'string:flexible'-type arguments */ 773 const __xString = wasm.xWrap.argAdapter('string'); 774 wasm.xWrap.argAdapter( 775 'string:flexible', (v)=>__xString(util.flexibleString(v)) 776 ); 777 778 /** 779 The 'string:static' argument adapter treats its argument as 780 either... 781 782 - If wasm.isPtr(v) is true it is assumed to be a long-lived 783 C-string pointer which gets returned as-is. 784 785 - Anything else: gets coerced to a JS string for use as a map 786 key. If a matching entry is found (as described next), it is 787 returned, else wasm.allocCString() is used to create a a new 788 string, map its pointer to a copy of (''+v) for the remainder 789 of the application's life, and returns that pointer value for 790 this call and all future calls which are passed a 791 string-equivalent argument. 792 793 Use case: sqlite3_bind_pointer(), sqlite3_result_pointer(), and 794 sqlite3_value_pointer() call for "a static string and 795 preferably a string literal". This converter is used to ensure 796 that the string value seen by those functions is long-lived and 797 behaves as they need it to, at the cost of a one-time leak of 798 each distinct key. 799 */ 800 wasm.xWrap.argAdapter( 801 'string:static', 802 function(v){ 803 if(wasm.isPtr(v)) return v; 804 v = ''+v; 805 return this[v] ??= wasm.allocCString(v); 806 }.bind(Object.create(null)) 807 ); 808 809 /** 810 Add some descriptive xWrap() aliases for '*' intended to (A) 811 improve readability/correctness of bindingSignatures and (B) 812 provide automatic conversion from higher-level representations, 813 e.g. capi.sqlite3_vfs to `sqlite3_vfs*` via (capi.sqlite3_vfs 814 instance).pointer. 815 */ 816 const __xArgPtr = wasm.xWrap.argAdapter('*'); 817 const nilType = function(){ 818 /*a class which no value can ever be an instance of*/ 819 }; 820 wasm.xWrap.argAdapter('sqlite3_filename', __xArgPtr) 821 ('sqlite3_backup*', __xArgPtr) 822 ('sqlite3_context*', __xArgPtr) 823 ('sqlite3_value*', __xArgPtr) 824 ('void*', __xArgPtr) 825 ('sqlite3_changegroup*', __xArgPtr) 826 ('sqlite3_changeset_iter*', __xArgPtr) 827 ('sqlite3_session*', __xArgPtr) 828 ('sqlite3_stmt*', (v)=> 829 __xArgPtr((v instanceof (sqlite3?.oo1?.Stmt || nilType)) 830 ? v.pointer : v)) 831 ('sqlite3*', (v)=> 832 __xArgPtr((v instanceof (sqlite3?.oo1?.DB || nilType)) 833 ? v.pointer : v)) 834 /** 835 `sqlite3_vfs*`: 836 837 - v is-a string: use the result of sqlite3_vfs_find(v) but 838 throw if it returns 0. 839 - v is-a capi.sqlite3_vfs: use v.pointer. 840 - Else return the same as the `'*'` argument conversion. 841 */ 842 ('sqlite3_vfs*', (v)=>{ 843 if('string'===typeof v){ 844 /* A NULL sqlite3_vfs pointer will be treated as the default 845 VFS in many contexts. We specifically do not want that 846 behavior here. */ 847 return capi.sqlite3_vfs_find(v) 848 || sqlite3.SQLite3Error.toss( 849 capi.SQLITE_NOTFOUND, 850 "Unknown sqlite3_vfs name:", v 851 ); 852 } 853 return __xArgPtr((v instanceof (capi.sqlite3_vfs || nilType)) 854 ? v.pointer : v); 855 }); 856 if( wasm.exports.sqlite3_declare_vtab ){ 857 wasm.xWrap.argAdapter('sqlite3_index_info*', (v)=> 858 __xArgPtr((v instanceof (capi.sqlite3_index_info || nilType)) 859 ? v.pointer : v)) 860 ('sqlite3_module*', (v)=> 861 __xArgPtr((v instanceof (capi.sqlite3_module || nilType)) 862 ? v.pointer : v) 863 ); 864 } 865 866 /** 867 Alias `T*` to `*` for return type conversions for common T 868 types, primarily to improve legibility of their binding 869 signatures. 870 */ 871 const __xRcPtr = wasm.xWrap.resultAdapter('*'); 872 wasm.xWrap.resultAdapter('sqlite3*', __xRcPtr) 873 ('sqlite3_backup*', __xRcPtr) 874 ('sqlite3_context*', __xRcPtr) 875 ('sqlite3_stmt*', __xRcPtr) 876 ('sqlite3_value*', __xRcPtr) 877 ('sqlite3_vfs*', __xRcPtr) 878 ('void*', __xRcPtr); 879 880 /** 881 Populate api object with sqlite3_...() by binding the "raw" wasm 882 exports into type-converting proxies using wasm.xWrap(). 883 */ 884 for(const e of bindingSignatures.core){ 885 capi[e[0]] = wasm.xWrap.apply(null, e); 886 } 887 for(const e of bindingSignatures.wasmInternal){ 888 util[e[0]] = wasm.xWrap.apply(null, e); 889 } 890 891 /* For C API functions which cannot work properly unless 892 wasm.bigIntEnabled is true, install a bogus impl which throws 893 if called when bigIntEnabled is false. The alternative would be 894 to elide these functions altogether, which seems likely to 895 cause more confusion, as documented APIs would resolve to the 896 undefined value in incompatible builds. */ 897 for(const e of bindingSignatures.int64){ 898 capi[e[0]] = wasm.bigIntEnabled 899 ? wasm.xWrap.apply(null, e) 900 : ()=>toss(e[0]+"() is unavailable due to lack", 901 "of BigInt support in this build."); 902 } 903 904 /* We're done with bindingSignatures but it's const, so... */ 905 delete bindingSignatures.core; 906 delete bindingSignatures.int64; 907 delete bindingSignatures.wasmInternal; 908 909 /** 910 Sets the given db's error state. Accepts: 911 912 - (sqlite3*, int code, string msg) 913 - (sqlite3*, Error e [,string msg = ''+e]) 914 915 If passed a WasmAllocError, the message is ignored and the 916 result code is SQLITE_NOMEM. If passed any other Error type, 917 the result code defaults to SQLITE_ERROR unless the Error 918 object has a resultCode property, in which case that is used 919 (e.g. SQLite3Error has that). If passed a non-WasmAllocError 920 exception, the message string defaults to ''+theError. 921 922 Returns either the final result code, capi.SQLITE_NOMEM if 923 setting the message string triggers an OOM, or 924 capi.SQLITE_MISUSE if pDb is NULL or invalid (with the caveat 925 that behavior in the later case is undefined if pDb is not 926 "valid enough"). 927 928 Pass (pDb,0,0) to clear the error state. 929 */ 930 util.sqlite3__wasm_db_error = function(pDb, resultCode, message){ 931 if( !pDb ) return capi.SQLITE_MISUSE; 932 if(resultCode instanceof sqlite3.WasmAllocError){ 933 resultCode = capi.SQLITE_NOMEM; 934 message = 0 /*avoid allocating message string*/; 935 }else if(resultCode instanceof Error){ 936 message = message || ''+resultCode; 937 resultCode = (resultCode.resultCode || capi.SQLITE_ERROR); 938 } 939 return capi.sqlite3_set_errmsg(pDb, resultCode, message) || resultCode; 940 }; 941 }/*xWrap() bindings*/ 942 943 {/* Import C-level constants and structs... */ 944 const cJson = wasm.xCall('sqlite3__wasm_enum_json'); 945 if(!cJson){ 946 toss("Maintenance required: increase sqlite3__wasm_enum_json()'s", 947 "static buffer size!"); 948 } 949 const j = wasm.cstrToJs(cJson); 950 //sqlite3.config.error("cJson JSON length:",j.length); 951 wasm.ctype = JSON.parse(j); 952 if( wasm.exports.sqlite3__wasm_disposal_notifier ){ 953 /* Redirect the SQLITE_DISPOSAL_NOTIFIER callback installed by 954 sqlite3-wasm.c to JS. */ 955 util.disposers = Object.assign(Object.create(null),{ 956 /* Lists of disposer callbacks which are passed the WASM pointer 957 of an object which is currently being finalized from 958 WASM. These are triggered via the SQLITE_DISPOSAL_NOTIFIER 959 callback which sqlite3-wasm.c installs. The C side of this 960 ensures that these callbacks are never passed NULL. 961 Downstream library bootstrapping code may append callbacks to 962 these (e.g. oo1 does so). */ 963 db: [], stmt: [] 964 }); 965 /* Map type IDs to names to simplify $callback() below. */ 966 util.disposers[1] = util.disposers.db; 967 util.disposers[2] = util.disposers.stmt; 968 const funcNr = wasm.installFunction("v(ip)", (tid,ptr)=>{ 969 //sqlite3.config.debug("WasmDisposalNotifier:",tid,ptr); 970 const li = util.disposers[tid] 971 ?? toss("Internal bug: invalid disposal type ID",tid); 972 for(const d of li){ 973 try{d(ptr)} 974 catch(e){ 975 sqlite3.config.error("on-dispose handler type", 976 tid,"threw:",e,d); 977 } 978 } 979 }); 980 wasm.pokePtr(wasm.exports.sqlite3__wasm_disposal_notifier(), funcNr); 981 //#if 0 982 // Just for testing... 983 util.disposers.stmt.push((p)=>sqlite3.config.warn("disposing stmt",p)); 984 util.disposers.db.push((p)=>sqlite3.config.warn("disposing db",p)); 985 //#/if 986 }else{ 987 toss("Expecting WasmDisposalNotifier to have been exported."); 988 } 989 990 // Groups of SQLITE_xyz macros... 991 const defineGroups = ['access', 'authorizer', 992 'blobFinalizers', 'changeset', 993 'config', 'dataTypes', 994 'dbConfig', 'dbStatus', 995 'encodings', 'fcntl', 'flock', 'ioCap', 996 'limits', 'openFlags', 997 'prepareFlags', 'resultCodes', 998 'sqlite3Status', 999 'stmtStatus', 'syncFlags', 1000 'trace', 'txnState', 'udfFlags', 1001 'version']; 1002 if(wasm.bigIntEnabled){ 1003 defineGroups.push('serialize', 'session', 'vtab'); 1004 } 1005 for(const t of defineGroups){ 1006 for(const e of Object.entries(wasm.ctype[t])){ 1007 // ^^^ [k,v] there triggers a buggy code transformation via 1008 // one of the Emscripten-driven optimizers. 1009 capi[e[0]] = e[1]; 1010 } 1011 } 1012 if(!wasm.functionEntry(capi.SQLITE_WASM_DEALLOC)){ 1013 toss("Internal error: cannot resolve exported function", 1014 "entry SQLITE_WASM_DEALLOC (=="+capi.SQLITE_WASM_DEALLOC+")."); 1015 } 1016 const __rcMap = Object.create(null); 1017 for(const e of Object.entries(wasm.ctype['resultCodes'])){ 1018 __rcMap[e[1]] = e[0]; 1019 } 1020 /** 1021 For the given integer, returns the SQLITE_xxx result code as a 1022 string, or undefined if no such mapping is found. 1023 */ 1024 capi.sqlite3_js_rc_str = (rc)=>__rcMap[rc]; 1025 1026 /* Bind all registered C-side structs... */ 1027 const notThese = Object.assign(Object.create(null),{ 1028 // For each struct to NOT register, map its name to true: 1029 WasmTestStruct: true, 1030 WasmDisposalNotifier: true, 1031 /* sqlite3_index_info and friends require int64: */ 1032 sqlite3_index_info: !wasm.bigIntEnabled, 1033 sqlite3_index_constraint: !wasm.bigIntEnabled, 1034 sqlite3_index_orderby: !wasm.bigIntEnabled, 1035 sqlite3_index_constraint_usage: !wasm.bigIntEnabled 1036 }); 1037 for(const s of wasm.ctype.structs){ 1038 if(!notThese[s.name]){ 1039 capi[s.name] = sqlite3.StructBinder(s); 1040 } 1041 } 1042 if(capi.sqlite3_index_info){ 1043 /* Move these inner structs into sqlite3_index_info. Binding 1044 ** them to WASM requires that we create top-level structs to 1045 ** model them with, but those are no longer needed after we've 1046 ** passed them to StructBinder. */ 1047 for(const k of ['sqlite3_index_constraint', 1048 'sqlite3_index_orderby', 1049 'sqlite3_index_constraint_usage']){ 1050 capi.sqlite3_index_info[k] = capi[k]; 1051 delete capi[k]; 1052 } 1053 capi.sqlite3_vtab_config = wasm.xWrap( 1054 'sqlite3__wasm_vtab_config','int',[ 1055 'sqlite3*', 'int', 'int'] 1056 ); 1057 }/* end vtab-related setup */ 1058 }/*end C constant and struct imports*/ 1059 1060 /** 1061 Internal helper to assist in validating call argument counts in 1062 the hand-written sqlite3_xyz() wrappers. We do this only for 1063 consistency with non-special-case wrappings. 1064 */ 1065 const __dbArgcMismatch = (pDb,f,n)=>{ 1066 return util.sqlite3__wasm_db_error(pDb, capi.SQLITE_MISUSE, 1067 f+"() requires "+n+" argument"+ 1068 (1===n?"":'s')+"."); 1069 }; 1070 1071 /** Code duplication reducer for functions which take an encoding 1072 argument and require SQLITE_UTF8. Sets the db error code to 1073 SQLITE_FORMAT, installs a descriptive error message, 1074 and returns SQLITE_FORMAT. */ 1075 const __errEncoding = (pDb)=>{ 1076 return util.sqlite3__wasm_db_error( 1077 pDb, capi.SQLITE_FORMAT, "SQLITE_UTF8 is the only supported encoding." 1078 ); 1079 }; 1080 1081 /** 1082 __dbCleanupMap is infrastructure for recording registration of 1083 UDFs and collations so that sqlite3_close_v2() can clean up any 1084 automated JS-to-WASM function conversions installed by those. 1085 */ 1086 const __argPDb = wasm.xWrap.argAdapter('sqlite3*'); 1087 const __argStr = (str)=>wasm.isPtr(str) ? wasm.cstrToJs(str) : str; 1088 const __dbCleanupMap = function( 1089 pDb, mode/*0=remove, >0=create if needed, <0=do not create if missing*/ 1090 ){ 1091 pDb = __argPDb(pDb); 1092 let m = this.dbMap.get(pDb); 1093 if(!mode){ 1094 this.dbMap.delete(pDb); 1095 return m; 1096 }else if(!m && mode>0){ 1097 this.dbMap.set(pDb, (m = Object.create(null))); 1098 } 1099 return m; 1100 }.bind(Object.assign(Object.create(null),{ 1101 dbMap: new Map 1102 })); 1103 1104 __dbCleanupMap.addCollation = function(pDb, name){ 1105 const m = __dbCleanupMap(pDb, 1); 1106 if(!m.collation) m.collation = new Set; 1107 m.collation.add(__argStr(name).toLowerCase()); 1108 }; 1109 1110 __dbCleanupMap._addUDF = function(pDb, name, arity, map){ 1111 /* Map UDF name to a Set of arity values */ 1112 name = __argStr(name).toLowerCase(); 1113 let u = map.get(name); 1114 if(!u) map.set(name, (u = new Set)); 1115 u.add((arity<0) ? -1 : arity); 1116 }; 1117 1118 __dbCleanupMap.addFunction = function(pDb, name, arity){ 1119 const m = __dbCleanupMap(pDb, 1); 1120 if(!m.udf) m.udf = new Map; 1121 this._addUDF(pDb, name, arity, m.udf); 1122 }; 1123 1124 if( wasm.exports.sqlite3_create_window_function ){ 1125 __dbCleanupMap.addWindowFunc = function(pDb, name, arity){ 1126 const m = __dbCleanupMap(pDb, 1); 1127 if(!m.wudf) m.wudf = new Map; 1128 this._addUDF(pDb, name, arity, m.wudf); 1129 }; 1130 } 1131 1132 /** 1133 Intended to be called _only_ from sqlite3_close_v2(), 1134 passed its non-0 db argument. 1135 1136 This function frees up certain automatically-installed WASM 1137 function bindings which were installed on behalf of the given db, 1138 as those may otherwise leak. 1139 1140 Notable caveat: this is only ever run via 1141 sqlite3.capi.sqlite3_close_v2(). If a client, for whatever 1142 reason, uses sqlite3.wasm.exports.sqlite3_close_v2() (the 1143 function directly exported from WASM), this cleanup will not 1144 happen. 1145 1146 This is not a silver bullet for avoiding automation-related 1147 leaks but represents "an honest effort." 1148 1149 The issue being addressed here is covered at: 1150 1151 https://sqlite.org/wasm/doc/trunk/api-c-style.md#convert-func-ptr 1152 */ 1153 __dbCleanupMap.cleanup = function(pDb){ 1154 pDb = __argPDb(pDb); 1155 //sqlite3.config.warn("disposing pDb",pDb); 1156 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = false; 1157 /** 1158 Installing NULL functions in the C API will remove those 1159 bindings. The FuncPtrAdapter which sits between us and the C 1160 API will also treat that as an opportunity to 1161 wasm.uninstallFunction() any WASM function bindings it has 1162 installed for pDb. 1163 */ 1164 for(const obj of [ 1165 /* pairs of [funcName, itsArityInC] */ 1166 ['sqlite3_busy_handler',3], 1167 ['sqlite3_commit_hook',3], 1168 ['sqlite3_preupdate_hook',3], 1169 ['sqlite3_progress_handler',4], 1170 ['sqlite3_rollback_hook',3], 1171 ['sqlite3_set_authorizer',3], 1172 ['sqlite3_trace_v2', 4], 1173 ['sqlite3_update_hook',3] 1174 /* 1175 We do not yet have a way to clean up automatically-converted 1176 sqlite3_set_auxdata() finalizers. 1177 */ 1178 ]){ 1179 const [name, arity] = obj; 1180 const x = wasm.exports[name]; 1181 if( !x ){ 1182 /* assume it was built without this API */ 1183 continue; 1184 } 1185 const closeArgs = [pDb]; 1186 closeArgs.length = arity 1187 /* Recall that: (A) undefined entries translate to 0 when 1188 passed to WASM and (B) Safari wraps wasm.exports.* in 1189 nullary functions so x.length is 0 there. */; 1190 //wasm.xWrap.debug = true; 1191 try{ capi[name](...closeArgs) } 1192 catch(e){ 1193 /* This "cannot happen" unless something is well and truly sideways. */ 1194 sqlite3.config.warn("close-time call of",name+"(",closeArgs,") threw:",e); 1195 } 1196 //wasm.xWrap.debug = false; 1197 } 1198 const m = __dbCleanupMap(pDb, 0); 1199 if(!m) return; 1200 if(m.collation){ 1201 for(const name of m.collation){ 1202 try{ 1203 capi.sqlite3_create_collation_v2( 1204 pDb, name, capi.SQLITE_UTF8, 0, 0, 0 1205 ); 1206 }catch(e){ 1207 /*ignored*/ 1208 } 1209 } 1210 delete m.collation; 1211 } 1212 let i; 1213 for(i = 0; i < 2; ++i){ /* Clean up UDFs... */ 1214 const fmap = i ? m.wudf : m.udf; 1215 if(!fmap) continue; 1216 const func = i 1217 ? capi.sqlite3_create_window_function 1218 : capi.sqlite3_create_function_v2; 1219 for(const e of fmap){ 1220 const name = e[0], arities = e[1]; 1221 const fargs = [pDb, name, 0/*arity*/, capi.SQLITE_UTF8, 0, 0, 0, 0, 0]; 1222 if(i) fargs.push(0); 1223 for(const arity of arities){ 1224 try{ fargs[2] = arity; func.apply(null, fargs); } 1225 catch(e){/*ignored*/} 1226 } 1227 arities.clear(); 1228 } 1229 fmap.clear(); 1230 } 1231 delete m.udf; 1232 delete m.wudf; 1233 }/*__dbCleanupMap.cleanup()*/; 1234 1235 util.disposers.db.push( 1236 /* When a db is disposed from C, this will clean up the various 1237 state we've bound in __dbCleanupMap, e.g. JS-to-WASM function 1238 conversions for the tracer. */ 1239 __dbCleanupMap.cleanup 1240 ); 1241 1242 if(capi.sqlite3session_create){ 1243 const __sqlite3SessionDelete = wasm.xWrap( 1244 'sqlite3session_delete', undefined, ['sqlite3_session*'] 1245 ); 1246 capi.sqlite3session_delete = function(pSession){ 1247 if(1!==arguments.length){ 1248 return __dbArgcMismatch(pDb, 'sqlite3session_delete', 1); 1249 /* Yes, we're returning a value from a void function. That seems 1250 like the lesser evil compared to not maintaining arg-count 1251 consistency as we do with other similar bindings. */ 1252 } 1253 else if(pSession){ 1254 //wasm.xWrap.FuncPtrAdapter.debugFuncInstall = true; 1255 capi.sqlite3session_table_filter(pSession, 0, 0); 1256 } 1257 __sqlite3SessionDelete(pSession); 1258 }; 1259 } 1260 1261 {/* Bindings for sqlite3_create_collation[_v2]() */ 1262 // contextKey() impl for wasm.xWrap.FuncPtrAdapter 1263 const contextKey = (argv,argIndex)=>{ 1264 return 'argv['+argIndex+']:'+argv[0/* sqlite3* */]+ 1265 ':'+wasm.cstrToJs(argv[1/* collation name */]).toLowerCase() 1266 }; 1267 const __sqlite3CreateCollationV2 = wasm.xWrap( 1268 'sqlite3_create_collation_v2', 'int', [ 1269 'sqlite3*', 'string', 'int', '*', 1270 new wasm.xWrap.FuncPtrAdapter({ 1271 /* int(*xCompare)(void*,int,const void*,int,const void*) */ 1272 name: 'xCompare', signature: 'i(pipip)', contextKey 1273 }), 1274 new wasm.xWrap.FuncPtrAdapter({ 1275 /* void(*xDestroy(void*) */ 1276 name: 'xDestroy', signature: 'v(p)', contextKey 1277 }) 1278 ] 1279 ); 1280 1281 /** 1282 Works exactly like C's sqlite3_create_collation_v2() except that: 1283 1284 1) It returns capi.SQLITE_FORMAT if the 3rd argument contains 1285 any encoding-related value other than capi.SQLITE_UTF8. No 1286 other encodings are supported. As a special case, if the 1287 bottom 4 bits of that argument are 0, SQLITE_UTF8 is 1288 assumed. 1289 1290 2) It accepts JS functions for its function-pointer arguments, 1291 for which it will install WASM-bound proxies. The bindings 1292 are "permanent," in that they will stay in the WASM 1293 environment until it shuts down unless the client calls this 1294 again with the same collation name and a value of 0 or null 1295 for the the function pointer(s). sqlite3_close_v2() will 1296 also clean up such automatically-installed WASM functions. 1297 1298 For consistency with the C API, it requires the same number of 1299 arguments. It returns capi.SQLITE_MISUSE if passed any other 1300 argument count. 1301 1302 Returns 0 on success, non-0 on error, in which case the error 1303 state of pDb (of type `sqlite3*` or argument-convertible to it) 1304 may contain more information. 1305 */ 1306 capi.sqlite3_create_collation_v2 = function(pDb,zName,eTextRep,pArg,xCompare,xDestroy){ 1307 if(6!==arguments.length) return __dbArgcMismatch(pDb, 'sqlite3_create_collation_v2', 6); 1308 else if( 0 === (eTextRep & 0xf) ){ 1309 eTextRep |= capi.SQLITE_UTF8; 1310 }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){ 1311 return __errEncoding(pDb); 1312 } 1313 try{ 1314 const rc = __sqlite3CreateCollationV2(pDb, zName, eTextRep, pArg, xCompare, xDestroy); 1315 if(0===rc && xCompare instanceof Function){ 1316 __dbCleanupMap.addCollation(pDb, zName); 1317 } 1318 return rc; 1319 }catch(e){ 1320 return util.sqlite3__wasm_db_error(pDb, e); 1321 } 1322 }; 1323 1324 capi.sqlite3_create_collation = (pDb,zName,eTextRep,pArg,xCompare)=>{ 1325 return (5===arguments.length) 1326 ? capi.sqlite3_create_collation_v2(pDb,zName,eTextRep,pArg,xCompare,0) 1327 : __dbArgcMismatch(pDb, 'sqlite3_create_collation', 5); 1328 }; 1329 1330 }/*sqlite3_create_collation() and friends*/ 1331 1332 {/* Special-case handling of sqlite3_create_function_v2() 1333 and sqlite3_create_window_function(). */ 1334 /** FuncPtrAdapter for contextKey() for sqlite3_create_function() 1335 and friends. */ 1336 const contextKey = function(argv,argIndex){ 1337 return ( 1338 argv[0/* sqlite3* */] 1339 +':'+(argv[2/*number of UDF args*/] < 0 ? -1 : argv[2]) 1340 +':'+argIndex/*distinct for each xAbc callback type*/ 1341 +':'+wasm.cstrToJs(argv[1]).toLowerCase() 1342 ) 1343 }; 1344 1345 /** 1346 JS proxies for the various sqlite3_create[_window]_function() 1347 callbacks, structured in a form usable by wasm.xWrap.FuncPtrAdapter. 1348 */ 1349 const __cfProxy = Object.assign(Object.create(null), { 1350 xInverseAndStep: { 1351 signature:'v(pip)', contextKey, 1352 callProxy: (callback)=>{ 1353 return (pCtx, argc, pArgv)=>{ 1354 try{ callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv)) } 1355 catch(e){ capi.sqlite3_result_error_js(pCtx, e) } 1356 }; 1357 } 1358 }, 1359 xFinalAndValue: { 1360 signature:'v(p)', contextKey, 1361 callProxy: (callback)=>{ 1362 return (pCtx)=>{ 1363 try{ capi.sqlite3_result_js(pCtx, callback(pCtx)) } 1364 catch(e){ capi.sqlite3_result_error_js(pCtx, e) } 1365 }; 1366 } 1367 }, 1368 xFunc: { 1369 signature:'v(pip)', contextKey, 1370 callProxy: (callback)=>{ 1371 return (pCtx, argc, pArgv)=>{ 1372 try{ 1373 capi.sqlite3_result_js( 1374 pCtx, 1375 callback(pCtx, ...capi.sqlite3_values_to_js(argc, pArgv)) 1376 ); 1377 }catch(e){ 1378 //sqlite3.config.error('xFunc() caught:',e); 1379 capi.sqlite3_result_error_js(pCtx, e); 1380 } 1381 }; 1382 } 1383 }, 1384 xDestroy: { 1385 signature:'v(p)', contextKey, 1386 //Arguable: a well-behaved destructor doesn't require a proxy. 1387 callProxy: (callback)=>{ 1388 return (pVoid)=>{ 1389 try{ callback(pVoid) } 1390 catch(e){ sqlite3.config.error("UDF xDestroy(",pVoid,") threw:",e) } 1391 }; 1392 } 1393 } 1394 })/*__cfProxy*/; 1395 1396 const __sqlite3CreateFunction = wasm.xWrap( 1397 "sqlite3_create_function_v2", "int", [ 1398 "sqlite3*", "string"/*funcName*/, "int"/*nArg*/, 1399 "int"/*eTextRep*/, "*"/*pApp*/, 1400 new wasm.xWrap.FuncPtrAdapter({name: 'xFunc', ...__cfProxy.xFunc}), 1401 new wasm.xWrap.FuncPtrAdapter({name: 'xStep', ...__cfProxy.xInverseAndStep}), 1402 new wasm.xWrap.FuncPtrAdapter({name: 'xFinal', ...__cfProxy.xFinalAndValue}), 1403 new wasm.xWrap.FuncPtrAdapter({name: 'xDestroy', ...__cfProxy.xDestroy}) 1404 ] 1405 ); 1406 1407 const __sqlite3CreateWindowFunction = 1408 wasm.exports.sqlite3_create_window_function 1409 ? wasm.xWrap( 1410 "sqlite3_create_window_function", "int", [ 1411 "sqlite3*", "string"/*funcName*/, "int"/*nArg*/, 1412 "int"/*eTextRep*/, "*"/*pApp*/, 1413 new wasm.xWrap.FuncPtrAdapter({name: 'xStep', ...__cfProxy.xInverseAndStep}), 1414 new wasm.xWrap.FuncPtrAdapter({name: 'xFinal', ...__cfProxy.xFinalAndValue}), 1415 new wasm.xWrap.FuncPtrAdapter({name: 'xValue', ...__cfProxy.xFinalAndValue}), 1416 new wasm.xWrap.FuncPtrAdapter({name: 'xInverse', ...__cfProxy.xInverseAndStep}), 1417 new wasm.xWrap.FuncPtrAdapter({name: 'xDestroy', ...__cfProxy.xDestroy}) 1418 ] 1419 ) 1420 : undefined; 1421 1422 /* Documented in the api object's initializer. */ 1423 capi.sqlite3_create_function_v2 = function f( 1424 pDb, funcName, nArg, eTextRep, pApp, 1425 xFunc, //void (*xFunc)(sqlite3_context*,int,sqlite3_value**) 1426 xStep, //void (*xStep)(sqlite3_context*,int,sqlite3_value**) 1427 xFinal, //void (*xFinal)(sqlite3_context*) 1428 xDestroy //void (*xDestroy)(void*) 1429 ){ 1430 if( f.length!==arguments.length ){ 1431 return __dbArgcMismatch(pDb,"sqlite3_create_function_v2",f.length); 1432 }else if( 0 === (eTextRep & 0xf) ){ 1433 eTextRep |= capi.SQLITE_UTF8; 1434 }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){ 1435 return __errEncoding(pDb); 1436 } 1437 try{ 1438 const rc = __sqlite3CreateFunction(pDb, funcName, nArg, eTextRep, 1439 pApp, xFunc, xStep, xFinal, xDestroy); 1440 if(0===rc && (xFunc instanceof Function 1441 || xStep instanceof Function 1442 || xFinal instanceof Function 1443 || xDestroy instanceof Function)){ 1444 __dbCleanupMap.addFunction(pDb, funcName, nArg); 1445 } 1446 return rc; 1447 }catch(e){ 1448 sqlite3.config.error("sqlite3_create_function_v2() setup threw:",e); 1449 return util.sqlite3__wasm_db_error(pDb, e, "Creation of UDF threw: "+e); 1450 } 1451 }; 1452 1453 /* Documented in the api object's initializer. */ 1454 capi.sqlite3_create_function = function f( 1455 pDb, funcName, nArg, eTextRep, pApp, 1456 xFunc, xStep, xFinal 1457 ){ 1458 return (f.length===arguments.length) 1459 ? capi.sqlite3_create_function_v2(pDb, funcName, nArg, eTextRep, 1460 pApp, xFunc, xStep, xFinal, 0) 1461 : __dbArgcMismatch(pDb,"sqlite3_create_function",f.length); 1462 }; 1463 1464 /* Documented in the api object's initializer. */ 1465 if( __sqlite3CreateWindowFunction ){ 1466 capi.sqlite3_create_window_function = function f( 1467 pDb, funcName, nArg, eTextRep, pApp, 1468 xStep, //void (*xStep)(sqlite3_context*,int,sqlite3_value**) 1469 xFinal, //void (*xFinal)(sqlite3_context*) 1470 xValue, //void (*xValue)(sqlite3_context*) 1471 xInverse,//void (*xInverse)(sqlite3_context*,int,sqlite3_value**) 1472 xDestroy //void (*xDestroy)(void*) 1473 ){ 1474 if( f.length!==arguments.length ){ 1475 return __dbArgcMismatch(pDb,"sqlite3_create_window_function",f.length); 1476 }else if( 0 === (eTextRep & 0xf) ){ 1477 eTextRep |= capi.SQLITE_UTF8; 1478 }else if( capi.SQLITE_UTF8 !== (eTextRep & 0xf) ){ 1479 return __errEncoding(pDb); 1480 } 1481 try{ 1482 const rc = __sqlite3CreateWindowFunction(pDb, funcName, nArg, eTextRep, 1483 pApp, xStep, xFinal, xValue, 1484 xInverse, xDestroy); 1485 if(0===rc && (xStep instanceof Function 1486 || xFinal instanceof Function 1487 || xValue instanceof Function 1488 || xInverse instanceof Function 1489 || xDestroy instanceof Function)){ 1490 __dbCleanupMap.addWindowFunc(pDb, funcName, nArg); 1491 } 1492 return rc; 1493 }catch(e){ 1494 sqlite3.config.error("sqlite3_create_window_function() setup threw:",e); 1495 return util.sqlite3__wasm_db_error(pDb, e, "Creation of UDF threw: "+e); 1496 } 1497 }; 1498 }else{ 1499 delete capi.sqlite3_create_window_function; 1500 } 1501 /** 1502 A _deprecated_ alias for capi.sqlite3_result_js() which 1503 predates the addition of that function in the public API. 1504 */ 1505 capi.sqlite3_create_function_v2.udfSetResult = 1506 capi.sqlite3_create_function.udfSetResult = capi.sqlite3_result_js; 1507 if(capi.sqlite3_create_window_function){ 1508 capi.sqlite3_create_window_function.udfSetResult = capi.sqlite3_result_js; 1509 } 1510 1511 /** 1512 A _deprecated_ alias for capi.sqlite3_values_to_js() which 1513 predates the addition of that function in the public API. 1514 */ 1515 capi.sqlite3_create_function_v2.udfConvertArgs = 1516 capi.sqlite3_create_function.udfConvertArgs = capi.sqlite3_values_to_js; 1517 if(capi.sqlite3_create_window_function){ 1518 capi.sqlite3_create_window_function.udfConvertArgs = capi.sqlite3_values_to_js; 1519 } 1520 1521 /** 1522 A _deprecated_ alias for capi.sqlite3_result_error_js() which 1523 predates the addition of that function in the public API. 1524 */ 1525 capi.sqlite3_create_function_v2.udfSetError = 1526 capi.sqlite3_create_function.udfSetError = capi.sqlite3_result_error_js; 1527 if(capi.sqlite3_create_window_function){ 1528 capi.sqlite3_create_window_function.udfSetError = capi.sqlite3_result_error_js; 1529 } 1530 1531 }/*sqlite3_create_function_v2() and sqlite3_create_window_function() proxies*/; 1532 1533 /* Warn if client-level code makes use of FuncPtrAdapter. */ 1534 wasm.xWrap.FuncPtrAdapter.warnOnUse = true; 1535 1536 {/* Special-case handling of sqlite3_prepare_v2() and 1537 sqlite3_prepare_v3() */ 1538 1539 /** 1540 Helper for string:flexible conversions which requires a 1541 byte-length counterpart argument. Passed a value and its 1542 ostensible length, this function returns [V,N], where V is 1543 either v or a to-string transformed copy of v and N is either n 1544 (if v is a WASM pointer, in which case n might be a BigInt), -1 1545 (if v is a string or Array), or the byte length of v (if it's a 1546 byte array or ArrayBuffer). 1547 */ 1548 const __flexiString = (v,n)=>{ 1549 if('string'===typeof v){ 1550 n = -1; 1551 }else if(util.isSQLableTypedArray(v)){ 1552 n = v.byteLength; 1553 v = wasm.typedArrayToString( 1554 (v instanceof ArrayBuffer) ? new Uint8Array(v) : v 1555 ); 1556 }else if(Array.isArray(v)){ 1557 v = v.join(""); 1558 n = -1; 1559 } 1560 return [v, n]; 1561 }; 1562 1563 /** 1564 Scope-local holder of the two impls of sqlite3_prepare_v2/v3(). 1565 */ 1566 const __prepare = { 1567 /** 1568 This binding expects a JS string as its 2nd argument and 1569 null as its final argument. In order to compile multiple 1570 statements from a single string, the "full" impl (see 1571 below) must be used. 1572 */ 1573 basic: wasm.xWrap('sqlite3_prepare_v3', 1574 "int", ["sqlite3*", "string", 1575 "int"/*ignored for this impl!*/, 1576 "int", "**", 1577 "**"/*MUST be 0 or null or undefined!*/]), 1578 /** 1579 Impl which requires that the 2nd argument be a pointer to the 1580 SQL string, instead of being converted to a JS string. This 1581 variant is necessary for cases where we require a non-NULL 1582 value for the final argument (prepare/step of multiple 1583 statements from one input string). For simpler cases, where 1584 only the first statement in the SQL string is required, the 1585 wrapper named sqlite3_prepare_v2() is sufficient and easier 1586 to use because it doesn't require dealing with pointers. 1587 */ 1588 full: wasm.xWrap('sqlite3_prepare_v3', 1589 "int", ["sqlite3*", "*", "int", "int", 1590 "**", "**"]) 1591 }; 1592 1593 /* Documented in the capi object's initializer. */ 1594 capi.sqlite3_prepare_v3 = function f(pDb, sql, sqlLen, prepFlags, ppStmt, pzTail){ 1595 if(f.length!==arguments.length){ 1596 return __dbArgcMismatch(pDb,"sqlite3_prepare_v3",f.length); 1597 } 1598 const [xSql, xSqlLen] = __flexiString(sql, Number(sqlLen)); 1599 switch(typeof xSql){ 1600 case 'string': return __prepare.basic(pDb, xSql, xSqlLen, prepFlags, ppStmt, null); 1601 case (typeof wasm.ptr.null): 1602 return __prepare.full(pDb, wasm.ptr.coerce(xSql), xSqlLen, prepFlags, 1603 ppStmt, pzTail); 1604 default: 1605 return util.sqlite3__wasm_db_error( 1606 pDb, capi.SQLITE_MISUSE, 1607 "Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+(typeof xSql) 1608 ); 1609 } 1610 }; 1611 1612 /* Documented in the capi object's initializer. */ 1613 capi.sqlite3_prepare_v2 = function f(pDb, sql, sqlLen, ppStmt, pzTail){ 1614 return (f.length===arguments.length) 1615 ? capi.sqlite3_prepare_v3(pDb, sql, sqlLen, 0, ppStmt, pzTail) 1616 : __dbArgcMismatch(pDb,"sqlite3_prepare_v2",f.length); 1617 }; 1618 1619 }/*sqlite3_prepare_v2/v3()*/ 1620 1621 {/*sqlite3_bind_text/blob()*/ 1622 const __bindText = wasm.xWrap("sqlite3_bind_text", "int", [ 1623 "sqlite3_stmt*", "int", "string", "int", "*" 1624 ]); 1625 const __bindBlob = wasm.xWrap("sqlite3_bind_blob", "int", [ 1626 "sqlite3_stmt*", "int", "*", "int", "*" 1627 ]); 1628 1629 /** Documented in the capi object's initializer. */ 1630 capi.sqlite3_bind_text = function f(pStmt, iCol, text, nText, xDestroy){ 1631 if(f.length!==arguments.length){ 1632 return __dbArgcMismatch(capi.sqlite3_db_handle(pStmt), 1633 "sqlite3_bind_text", f.length); 1634 }else if(wasm.isPtr(text) || null===text){ 1635 return __bindText(pStmt, iCol, text, nText, xDestroy); 1636 }else if(text instanceof ArrayBuffer){ 1637 text = new Uint8Array(text); 1638 }else if(Array.isArray(text)){ 1639 text = text.join(''); 1640 } 1641 let p, n; 1642 try{ 1643 if(util.isSQLableTypedArray(text)){ 1644 p = wasm.allocFromTypedArray(text); 1645 n = text.byteLength; 1646 }else if('string'===typeof text){ 1647 [p, n] = wasm.allocCString(text, true); 1648 }else{ 1649 return util.sqlite3__wasm_db_error( 1650 capi.sqlite3_db_handle(pStmt), capi.SQLITE_MISUSE, 1651 "Invalid 3rd argument type for sqlite3_bind_text()." 1652 ); 1653 } 1654 return __bindText(pStmt, iCol, p, n, capi.SQLITE_WASM_DEALLOC); 1655 }catch(e){ 1656 wasm.dealloc(p); 1657 return util.sqlite3__wasm_db_error( 1658 capi.sqlite3_db_handle(pStmt), e 1659 ); 1660 } 1661 }/*sqlite3_bind_text()*/; 1662 1663 /** Documented in the capi object's initializer. */ 1664 capi.sqlite3_bind_blob = function f(pStmt, iCol, pMem, nMem, xDestroy){ 1665 if(f.length!==arguments.length){ 1666 return __dbArgcMismatch(capi.sqlite3_db_handle(pStmt), 1667 "sqlite3_bind_blob", f.length); 1668 }else if(wasm.isPtr(pMem) || null===pMem){ 1669 return __bindBlob(pStmt, iCol, pMem, nMem, xDestroy); 1670 }else if(pMem instanceof ArrayBuffer){ 1671 pMem = new Uint8Array(pMem); 1672 }else if(Array.isArray(pMem)){ 1673 pMem = pMem.join(''); 1674 } 1675 let p, n; 1676 try{ 1677 if(util.isBindableTypedArray(pMem)){ 1678 p = wasm.allocFromTypedArray(pMem); 1679 n = nMem>=0 ? nMem : pMem.byteLength; 1680 }else if('string'===typeof pMem){ 1681 [p, n] = wasm.allocCString(pMem, true); 1682 }else{ 1683 return util.sqlite3__wasm_db_error( 1684 capi.sqlite3_db_handle(pStmt), capi.SQLITE_MISUSE, 1685 "Invalid 3rd argument type for sqlite3_bind_blob()." 1686 ); 1687 } 1688 return __bindBlob(pStmt, iCol, p, n, capi.SQLITE_WASM_DEALLOC); 1689 }catch(e){ 1690 wasm.dealloc(p); 1691 return util.sqlite3__wasm_db_error( 1692 capi.sqlite3_db_handle(pStmt), e 1693 ); 1694 } 1695 }/*sqlite3_bind_blob()*/; 1696 1697 }/*sqlite3_bind_text/blob()*/ 1698 1699 //#if proxy-text-apis 1700 if(!capi.sqlite3_column_text){ 1701 /*[tag:proxy-text-apis] 1702 As discussed at: 1703 1704 https://sqlite.org/forum/forumpost/`d77281aec2df9ada` 1705 1706 Summary: there are opinions that sqlite3_column_text() and 1707 sqlite3_value_text() should handle strings such that embedded 1708 NULs are retained. This block does that. This block does _not_ 1709 apply that special-case behavior to any number of _other_ 1710 APIs which return C-strings. That discrepancy makes this 1711 block highly arguable, but one can also argue that these two 1712 specific functions can get away with such acrobatics without 1713 it being called voodoo in a pejorative sense. 1714 */ 1715 const argStmt = wasm.xWrap.argAdapter('sqlite3_stmt*'), 1716 argInt = wasm.xWrap.argAdapter('int'), 1717 argValue = wasm.xWrap.argAdapter('sqlite3_value*'), 1718 newStr = 1719 (cstr,n)=>wasm.typedArrayToString(wasm.heap8u(), 1720 Number(cstr), Number(cstr)+n) 1721 capi.sqlite3_column_text = function(stmt, colIndex){ 1722 const a0 = argStmt(stmt), a1 = argInt(colIndex); 1723 const cstr = wasm.exports.sqlite3_column_text(a0, a1); 1724 return cstr 1725 ? newStr(cstr,wasm.exports.sqlite3_column_bytes(a0, a1)) 1726 : null; 1727 }; 1728 capi.sqlite3_value_text = function(val){ 1729 const a0 = argValue(val); 1730 const cstr = wasm.exports.sqlite3_value_text(a0); 1731 return cstr 1732 ? newStr(cstr,wasm.exports.sqlite3_value_bytes(a0)) 1733 : null; 1734 }; 1735 }/*text-return-related bindings*/ 1736 //#/if proxy-text-apis 1737 1738 {/* sqlite3_config() */ 1739 /** 1740 Wraps a small subset of the C API's sqlite3_config() options. 1741 Unsupported options trigger the return of capi.SQLITE_NOTFOUND. 1742 Passing fewer than 2 arguments triggers return of 1743 capi.SQLITE_MISUSE. 1744 */ 1745 capi.sqlite3_config = function(op, ...args){ 1746 if(arguments.length<2) return capi.SQLITE_MISUSE; 1747 switch(op){ 1748 case capi.SQLITE_CONFIG_COVERING_INDEX_SCAN: // 20 /* int */ 1749 case capi.SQLITE_CONFIG_MEMSTATUS:// 9 /* boolean */ 1750 case capi.SQLITE_CONFIG_SMALL_MALLOC: // 27 /* boolean */ 1751 case capi.SQLITE_CONFIG_SORTERREF_SIZE: // 28 /* int nByte */ 1752 case capi.SQLITE_CONFIG_STMTJRNL_SPILL: // 26 /* int nByte */ 1753 case capi.SQLITE_CONFIG_URI:// 17 /* int */ 1754 return wasm.exports.sqlite3__wasm_config_i(op, args[0]); 1755 case capi.SQLITE_CONFIG_LOOKASIDE: // 13 /* int int */ 1756 return wasm.exports.sqlite3__wasm_config_ii(op, args[0], args[1]); 1757 case capi.SQLITE_CONFIG_MEMDB_MAXSIZE: // 29 /* sqlite3_int64 */ 1758 return wasm.exports.sqlite3__wasm_config_j(op, args[0]); 1759 case capi.SQLITE_CONFIG_GETMALLOC: // 5 /* sqlite3_mem_methods* */ 1760 case capi.SQLITE_CONFIG_GETMUTEX: // 11 /* sqlite3_mutex_methods* */ 1761 case capi.SQLITE_CONFIG_GETPCACHE2: // 19 /* sqlite3_pcache_methods2* */ 1762 case capi.SQLITE_CONFIG_GETPCACHE: // 15 /* no-op */ 1763 case capi.SQLITE_CONFIG_HEAP: // 8 /* void*, int nByte, int min */ 1764 case capi.SQLITE_CONFIG_LOG: // 16 /* xFunc, void* */ 1765 case capi.SQLITE_CONFIG_MALLOC:// 4 /* sqlite3_mem_methods* */ 1766 case capi.SQLITE_CONFIG_MMAP_SIZE: // 22 /* sqlite3_int64, sqlite3_int64 */ 1767 case capi.SQLITE_CONFIG_MULTITHREAD: // 2 /* nil */ 1768 case capi.SQLITE_CONFIG_MUTEX: // 10 /* sqlite3_mutex_methods* */ 1769 case capi.SQLITE_CONFIG_PAGECACHE: // 7 /* void*, int sz, int N */ 1770 case capi.SQLITE_CONFIG_PCACHE2: // 18 /* sqlite3_pcache_methods2* */ 1771 case capi.SQLITE_CONFIG_PCACHE: // 14 /* no-op */ 1772 case capi.SQLITE_CONFIG_PCACHE_HDRSZ: // 24 /* int *psz */ 1773 case capi.SQLITE_CONFIG_PMASZ: // 25 /* unsigned int szPma */ 1774 case capi.SQLITE_CONFIG_SERIALIZED: // 3 /* nil */ 1775 case capi.SQLITE_CONFIG_SINGLETHREAD: // 1 /* nil */: 1776 case capi.SQLITE_CONFIG_SQLLOG: // 21 /* xSqllog, void* */ 1777 case capi.SQLITE_CONFIG_WIN32_HEAPSIZE: // 23 /* int nByte */ 1778 default: 1779 /* maintenance note: we specifically do not include 1780 SQLITE_CONFIG_ROWID_IN_VIEW here, on the grounds that 1781 it's only for legacy support and no apps written with 1782 this API require that. */ 1783 return capi.SQLITE_NOTFOUND; 1784 } 1785 }; 1786 }/* sqlite3_config() */ 1787 1788 {/*auto-extension bindings.*/ 1789 const __autoExtFptr = new Set; 1790 1791 capi.sqlite3_auto_extension = function(fPtr){ 1792 if( fPtr instanceof Function ){ 1793 fPtr = wasm.installFunction('i(ppp)', fPtr); 1794 }else if( 1!==arguments.length || !wasm.isPtr(fPtr) ){ 1795 return capi.SQLITE_MISUSE; 1796 } 1797 const rc = wasm.exports.sqlite3_auto_extension(fPtr); 1798 if( fPtr!==arguments[0] ){ 1799 if(0===rc) __autoExtFptr.add(fPtr); 1800 else wasm.uninstallFunction(fPtr); 1801 } 1802 return rc; 1803 }; 1804 1805 capi.sqlite3_cancel_auto_extension = function(fPtr){ 1806 /* We do not do an automatic JS-to-WASM function conversion here 1807 because it would be senseless: the converted pointer would 1808 never possibly match an already-installed one. */; 1809 if(!fPtr || 1!==arguments.length || !wasm.isPtr(fPtr)) return 0; 1810 return wasm.exports.sqlite3_cancel_auto_extension(fPtr); 1811 /* Note that it "cannot happen" that a client passes a pointer which 1812 is in __autoExtFptr because __autoExtFptr only contains automatic 1813 conversions created inside sqlite3_auto_extension() and 1814 never exposed to the client. */ 1815 }; 1816 1817 capi.sqlite3_reset_auto_extension = function(){ 1818 wasm.exports.sqlite3_reset_auto_extension(); 1819 for(const fp of __autoExtFptr) wasm.uninstallFunction(fp); 1820 __autoExtFptr.clear(); 1821 }; 1822 }/* auto-extension */ 1823 1824 {/* sqlite3_js_on_pointer_dispose() */ 1825 const __jsOnDisposeTypes = (()=>{ 1826 /* Map of type names to Map(ptr, Set) */ 1827 const jodt = util.nu({ 1828 /* Lazily populated. */ 1829 "sqlite3*": null, 1830 "sqlite3_stmt*": null 1831 }); 1832 for( const e of [['db','sqlite3*'], ['stmt','sqlite3_stmt*']] ){ 1833 const [disposerKey, typeName] = e; 1834 util.disposers[disposerKey].push((ptr)=>{ 1835 /* Call all callbacks queued for the given ptr/typeName 1836 combination and clear that queue. */ 1837 const di = jodt[typeName]; 1838 const set = di?.get?.(ptr); 1839 if( !set /* pointers for _all_ disposals come through here 1840 but we only act on the ones in our Set. */ ) return; 1841 //sqlite3.config.debug("jopd",ptr,di,set); 1842 di.delete(ptr); 1843 for(const f of set){ 1844 try{f(ptr)} catch(e){ 1845 sqlite3.config.error( 1846 "sqlite3_js_on_pointer_dispose(", 1847 t,ptr,f,") callback threw", e 1848 ); 1849 } 1850 } 1851 }); 1852 } 1853 return jodt; 1854 })(); 1855 1856 /** 1857 Sets up the given callback to be called when the given WASM 1858 pointer is finalized by the library. The purposes of this is to 1859 provide client code with a way to map JS state to native 1860 pointers in such a way that the state can be cleaned up 1861 regardless of how the natives are finalized. 1862 1863 typeName describes what data type ptr is. It must be one of: 1864 1865 "sqlite3*", "sqlite3_stmt*" 1866 1867 and the ptr argument must be a non-null pointer to that type. 1868 1869 The callback must be either a Function or a WASM function 1870 pointer[^1] to a function with the signature `void(*)(void*)`, 1871 a.k.a. "v(p)" in the library's function-binding parlance. 1872 1873 It is legal to call this multiple times for a given combination 1874 of pointer and callback. Each callback will be added to the 1875 queue only once for each distinct callback reference, with the 1876 caveat noted below regarding callback references. That is, 1877 calling it N times with the same ptr/callback combination will 1878 only install the callback once, but N calls with N distinct 1879 callbacks will install all N. 1880 1881 When used in loops or client functions which may see the same 1882 pointer multiple times, it is generally important to **not pass 1883 function literals**, as each such literal is a different 1884 instance, so an identical callback may be added N times for a 1885 given pointer. Functions should be assigned to symbols and 1886 those symbols should be passed in so that callback 1887 deduplication works: 1888 1889 ``` 1890 // NO: 1891 sqlite3_js_on_pointer_dispose(..., (x)=>...); 1892 // YES: 1893 const myFunc = (x)=>...; 1894 ... 1895 sqlite3_js_on_pointer_dispose(..., myFunc); 1896 // Also YES: 1897 let myFunc; 1898 ... 1899 sqlite3_js_on_pointer_dispose(..., (myFunc ??= (x)=>...)); 1900 ``` 1901 1902 For single-call cases, e.g. when passing a newly-initialized db 1903 or statement, a function literal is perfectly fine. Within 1904 loops and client-defined functions which are called more than 1905 once per native instance, function literals will cause grief in 1906 the form of potentially registering a separate callback for 1907 each invocation of the SQL function. 1908 1909 On success it returns an unspecified truthy value. On error 1910 (argument validation issues) it returns an unspecified falsy 1911 value and has no side-effects. It does not throw because it's 1912 intended to be usable from cases where throwing is not 1913 permitted, but it only fails for argument validation. 1914 1915 When SQLite is about to free that pointer, all callbacks 1916 queued for it will be passed that pointer and then the 1917 callback queue for that pointer is cleared. 1918 1919 Because the callback is called during the native-level 1920 finalization process, it must observe certain limitations: 1921 1922 - It absolutely must not finalize the object, or results are 1923 well and truly undefined. Best case, a WASM crash. 1924 1925 - Because multiple on-dispose listeners may be installed for 1926 any given pointer, the callback must not leave the object in an 1927 unusable state. 1928 1929 - It should not perform "real work" with the pointer. e.g. a 1930 finalizing statement must not be stepped nor its columns 1931 fetched. A finalizing db should probably not run new 1932 queries. 1933 1934 - Any exceptions are ignored but may trigger an alert via 1935 sqlite3.config.error(). 1936 1937 Ideally, such callbacks do nothing more than remove any state 1938 which they have mapped to the given pointer value, without 1939 actually trying to use the object referred to by that pointer. 1940 Sometimes, however, cleanup work may be necessary which 1941 involves judicious use of that type's methods. 1942 1943 Added in 3.55.0. 1944 1945 Design note: ideally we could support `sqlite3_context*`, as 1946 that would neatly tie in cleanup for user-defined SQL 1947 functions. However, the C APIs do not guaranty stability of 1948 those pointers across calls. It currently provides 1949 _unguaranteed_ stability in two cases but does not for any 1950 aggregate-specific cases, making it unsuitable for the problem 1951 this API addresses (pun not intended). 1952 1953 [^1]: Though callback may be a WASM function pointer, that is 1954 actually less efficient than passing a JS function. The 1955 on-dispose dispatching is called from native code, invoking a 1956 JS function which the library connects to it during 1957 bootstrapping. sqlite3_js_on_pointer_dispose() receives the 1958 notifications "second hand" through that mechanism. If 1959 callback is a WASM function, invoking it adds one more step 1960 from JS-space into C-space and back. 1961 */ 1962 capi.sqlite3_js_on_pointer_dispose = function(typeName, ptr, callback){ 1963 if( !ptr || !wasm.isPtr(ptr) ) return null; 1964 else if( !(callback instanceof Function) 1965 && !(callback = wasm.functionEntry(callback)) ){ 1966 return undefined; 1967 } 1968 else if( !Object.prototype.hasOwnProperty.call(__jsOnDisposeTypes, typeName) ){ 1969 return false; 1970 } 1971 const map = __jsOnDisposeTypes[typeName] ??= new Map; 1972 if( !map.get(ptr)?.add?.(callback) ){ 1973 map.set(ptr, new Set([callback])); 1974 } 1975 //#if 0 1976 //sqlite3.config.debug("jopd map",map); 1977 /* Potential TODO: return the Set.size (number of callbacks). It 1978 does not provide any actionable info except possibly for 1979 detecting errant cases of the function-literal problem 1980 described in the API docs. Catching that would, however, 1981 require that clients check the result code, which they don't 1982 need to do if they'll apply the suggestion from the docs. */ 1983 //#/if 1984 return true; 1985 }; 1986 } 1987 1988 const StructBinder = sqlite3.StructBinder 1989 /* we require a local alias b/c StructBinder is removed from the sqlite3 1990 object during the final steps of the API cleanup. */; 1991 /** 1992 Installs a StructBinder-bound function pointer member of the 1993 given name and function in the given StructBinder.StructType 1994 target object. 1995 1996 It creates a WASM proxy for the given function and arranges for 1997 that proxy to be cleaned up when tgt.dispose() is called. Throws 1998 on the slightest hint of error, e.g. tgt is-not-a StructType, 1999 name does not map to a struct-bound member, etc. 2000 2001 As a special case, if the given function is a pointer, then 2002 `wasm.functionEntry()` is used to validate that it is a known 2003 function. If so, it is used as-is with no extra level of proxying 2004 or cleanup, else an exception is thrown. It is legal to pass a 2005 value of 0, indicating a NULL pointer, with the caveat that 0 2006 _is_ a legal function pointer in WASM but it will not be accepted 2007 as such _here_. (Justification: the function at address zero must 2008 be one which initially came from the WASM module, not a method we 2009 want to bind to a virtual table or VFS.) 2010 2011 This function returns a proxy for itself which is bound to tgt 2012 and takes 2 args (name,func). That function returns the same 2013 thing as this one, permitting calls to be chained. 2014 2015 If called with only 1 arg, it has no side effects but returns a 2016 func proxying this one which takes (name,func) arguments and 2017 curries the other two. 2018 2019 ACHTUNG: because we cannot generically know how to transform JS 2020 exceptions into result codes, the installed functions do no 2021 automatic catching of exceptions. It is critical, to avoid 2022 undefined behavior in the C layer, that methods mapped via 2023 this function do not throw. The exception, as it were, to that 2024 rule is... 2025 2026 If applyArgcCheck is true then each JS function (as opposed to 2027 function pointers) gets wrapped in a proxy which asserts that it 2028 is passed the expected number of arguments, throwing if the 2029 argument count does not match expectations. That is only intended 2030 for dev-time usage for sanity checking, and may leave the C 2031 environment in an undefined state. 2032 */ 2033 const installMethod = function callee( 2034 tgt, name, func, applyArgcCheck = callee.installMethodArgcCheck 2035 ){ 2036 if(1===arguments.length){ 2037 return (n,f)=>callee(tgt, n, f, applyArgcCheck); 2038 } 2039 if(!(tgt instanceof StructBinder.StructType)){ 2040 toss("Usage error: target object is-not-a StructType."); 2041 }else if(!(func instanceof Function) && !wasm.functionEntry(func)){ 2042 toss("Usage error: expecting a Function or WASM pointer to one."); 2043 } 2044 if(!callee.argcProxy){ 2045 callee.argcProxy = function(tgt, funcName, func,sig){ 2046 return function(...args){ 2047 if(func.length!==arguments.length){ 2048 toss("Argument mismatch for", 2049 tgt.structInfo.name+"::"+funcName 2050 +": Native signature is:",sig); 2051 } 2052 return func.apply(this, args); 2053 } 2054 }; 2055 /* An ondispose() callback for use with StructBinder-created 2056 instances. It removes all WASM functions which were installed 2057 as proxies into `this` by installMethod(). */ 2058 callee.removeFuncList = function(){ 2059 if(this.ondispose.__removeFuncList){ 2060 this.ondispose.__removeFuncList.forEach( 2061 (v,ndx)=>{ 2062 if(wasm.isPtr(v)){ 2063 try{wasm.uninstallFunction(v)} 2064 catch(e){/*ignore*/} 2065 } 2066 /* else it's a descriptive label for the next number in 2067 the list. */ 2068 } 2069 ); 2070 delete this.ondispose.__removeFuncList; 2071 } 2072 }; 2073 }/*static init*/ 2074 const sigN = tgt.memberSignature(name); 2075 if(sigN.length<2){ 2076 toss("Member",name,"does not have a function pointer signature:",sigN); 2077 } 2078 const memKey = tgt.memberKey(name); 2079 const fProxy = (applyArgcCheck && !wasm.isPtr(func)) 2080 /** This middle-man proxy is only for use during development, to 2081 confirm that we always pass the proper number of 2082 arguments. We know that the C-level code will always use the 2083 correct argument count. */ 2084 ? callee.argcProxy(tgt, memKey, func, sigN) 2085 : func; 2086 if(wasm.isPtr(fProxy)){ 2087 if(!fProxy || !wasm.functionEntry(fProxy)){ 2088 toss("Pointer",fProxy,"is not a WASM function table entry."); 2089 } 2090 tgt[memKey] = fProxy; 2091 }else{ 2092 const pFunc = wasm.installFunction(fProxy, sigN); 2093 tgt[memKey] = pFunc; 2094 if( !tgt.ondispose?.__removeFuncList ){ 2095 tgt.addOnDispose('ondispose.__removeFuncList handler', 2096 callee.removeFuncList); 2097 tgt.ondispose.__removeFuncList = []; 2098 } 2099 tgt.ondispose.__removeFuncList.push(memKey, pFunc); 2100 } 2101 return (n,f)=>callee(tgt, n, f, applyArgcCheck); 2102 }/*installMethod*/; 2103 installMethod.installMethodArgcCheck = false; 2104 2105 /** 2106 Installs methods into the given StructBinder.StructType-type 2107 instance. Each entry in the given methods object must map to a 2108 known member of the given StructType, else an exception will be 2109 triggered. See installMethod() for more details, including the 2110 semantics of the 3rd argument. 2111 2112 As an exception to the above, if any two or more methods in the 2113 2nd argument are the exact same function, installMethod() is 2114 _not_ called for the 2nd and subsequent instances, and instead 2115 those instances get assigned the same method pointer which is 2116 created for the first instance. This optimization is primarily to 2117 accommodate special handling of sqlite3_module::xConnect and 2118 xCreate methods. 2119 2120 On success, returns its first argument. Throws on error. 2121 */ 2122 const installMethods = function( 2123 structInstance, methods, applyArgcCheck = installMethod.installMethodArgcCheck 2124 ){ 2125 const seen = new Map /* map of */; 2126 for(const k of Object.keys(methods)){ 2127 const m = methods[k]; 2128 const prior = seen.get(m); 2129 if(prior){ 2130 const mkey = structInstance.memberKey(k); 2131 structInstance[mkey] = structInstance[structInstance.memberKey(prior)]; 2132 }else{ 2133 installMethod(structInstance, k, m, applyArgcCheck); 2134 seen.set(m, k); 2135 } 2136 } 2137 return structInstance; 2138 }; 2139 2140 /** 2141 Equivalent to calling installMethod(this,...arguments) with a 2142 first argument of this object. If called with 1 or 2 arguments 2143 and the first is an object, it's instead equivalent to calling 2144 installMethods(this,...arguments). 2145 */ 2146 StructBinder.StructType.prototype.installMethod = function callee( 2147 name, func, applyArgcCheck = installMethod.installMethodArgcCheck 2148 ){ 2149 return (arguments.length < 3 && name && 'object'===typeof name) 2150 ? installMethods(this, ...arguments) 2151 : installMethod(this, ...arguments); 2152 }; 2153 2154 /** 2155 Equivalent to calling installMethods() with a first argument 2156 of this object. 2157 */ 2158 StructBinder.StructType.prototype.installMethods = function( 2159 methods, applyArgcCheck = installMethod.installMethodArgcCheck 2160 ){ 2161 return installMethods(this, methods, applyArgcCheck); 2162 }; 2163 2164 });