sqlite3-api-oo1.c-pp.js 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. //#ifnot omit-oo1
  2. /*
  3. 2022-07-22
  4. The author disclaims copyright to this source code. In place of a
  5. legal notice, here is a blessing:
  6. * May you do good and not evil.
  7. * May you find forgiveness for yourself and forgive others.
  8. * May you share freely, never taking more than you give.
  9. ***********************************************************************
  10. This file contains the so-called OO #1 API wrapper for the sqlite3
  11. WASM build. It requires that sqlite3-api-glue.js has already run
  12. and it installs its deliverable as globalThis.sqlite3.oo1.
  13. */
  14. globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
  15. const toss3 = (...args)=>{throw new sqlite3.SQLite3Error(...args)};
  16. const capi = sqlite3.capi, wasm = sqlite3.wasm, util = sqlite3.util;
  17. /* What follows is colloquially known as "OO API #1". It is a
  18. binding of the sqlite3 API which is designed to be run within
  19. the same thread (main or worker) as the one in which the
  20. sqlite3 WASM binding was initialized. This wrapper cannot use
  21. the sqlite3 binding if, e.g., the wrapper is in the main thread
  22. and the sqlite3 API is in a worker. */
  23. /**
  24. In order to keep clients from manipulating, perhaps
  25. inadvertently, the underlying pointer values of DB and Stmt
  26. instances, we'll gate access to them via the `pointer` property
  27. accessor and store their real values in this map. Keys = DB/Stmt
  28. objects, values = pointer values. This also unifies how those are
  29. accessed, for potential use downstream via custom
  30. wasm.xWrap() function signatures which know how to extract
  31. it.
  32. */
  33. const __ptrMap = new WeakMap();
  34. /**
  35. Map of DB instances to objects, each object being a map of Stmt
  36. wasm pointers to Stmt objects.
  37. */
  38. const __stmtMap = new WeakMap();
  39. /** If object opts has _its own_ property named p then that
  40. property's value is returned, else dflt is returned. */
  41. const getOwnOption = (opts, p, dflt)=>{
  42. const d = Object.getOwnPropertyDescriptor(opts,p);
  43. return d ? d.value : dflt;
  44. };
  45. // Documented in DB.checkRc()
  46. const checkSqlite3Rc = function(dbPtr, sqliteResultCode){
  47. if(sqliteResultCode){
  48. if(dbPtr instanceof DB) dbPtr = dbPtr.pointer;
  49. toss3(
  50. sqliteResultCode,
  51. "sqlite3 result code",sqliteResultCode+":",
  52. (dbPtr
  53. ? capi.sqlite3_errmsg(dbPtr)
  54. : capi.sqlite3_errstr(sqliteResultCode))
  55. );
  56. }
  57. return arguments[0];
  58. };
  59. /**
  60. sqlite3_trace_v2() callback which gets installed by the DB ctor
  61. if its open-flags contain "t".
  62. */
  63. const __dbTraceToConsole =
  64. wasm.installFunction('i(ippp)', function(t,c,p,x){
  65. if(capi.SQLITE_TRACE_STMT===t){
  66. // x == SQL, p == sqlite3_stmt*
  67. console.log("SQL TRACE #"+(++this.counter)+' via sqlite3@'+c+':',
  68. wasm.cstrToJs(x));
  69. }
  70. }.bind({counter: 0}));
  71. /**
  72. A map of sqlite3_vfs pointers to SQL code or a callback function
  73. to run when the DB constructor opens a database with the given
  74. VFS. In the latter case, the call signature is
  75. (theDbObject,sqlite3Namespace) and the callback is expected to
  76. throw on error.
  77. */
  78. const __vfsPostOpenCallback = Object.create(null);
  79. //#if enable-see
  80. /**
  81. Converts ArrayBuffer or Uint8Array ba into a string of hex
  82. digits.
  83. */
  84. const byteArrayToHex = function(ba){
  85. if( ba instanceof ArrayBuffer ){
  86. ba = new Uint8Array(ba);
  87. }
  88. const li = [];
  89. const digits = "0123456789abcdef";
  90. for( const d of ba ){
  91. li.push( digits[(d & 0xf0) >> 4], digits[d & 0x0f] );
  92. }
  93. return li.join('');
  94. };
  95. /**
  96. Internal helper to apply an SEE key to a just-opened
  97. database. Requires that db be-a DB object which has just been
  98. opened, opt be the options object processed by its ctor, and opt
  99. must have either the key, hexkey, or textkey properties, either
  100. as a string, an ArrayBuffer, or a Uint8Array.
  101. This is a no-op in non-SEE builds. It throws on error and returns
  102. without side effects if none of the key/textkey/hexkey options
  103. are set. It throws if more than one is set or if any are set to
  104. values of an invalid type.
  105. Returns true if it applies the key, else an unspecified falsy
  106. value. Note that applying the key does not imply that the key is
  107. correct, only that it was passed on to the db.
  108. */
  109. const dbCtorApplySEEKey = function(db,opt){
  110. if( !capi.sqlite3_key_v2 ) return;
  111. let keytype;
  112. let key;
  113. const check = (opt.key ? 1 : 0) + (opt.hexkey ? 1 : 0) + (opt.textkey ? 1 : 0);
  114. if( !check ) return;
  115. else if( check>1 ){
  116. toss3(capi.SQLITE_MISUSE,
  117. "Only ONE of (key, hexkey, textkey) may be provided.");
  118. }
  119. if( opt.key ){
  120. /* It is not legal to bind an argument to PRAGMA key=?, so we
  121. convert it to a hexkey... */
  122. keytype = 'key';
  123. key = opt.key;
  124. if('string'===typeof key){
  125. key = new TextEncoder('utf-8').encode(key);
  126. }
  127. if((key instanceof ArrayBuffer) || (key instanceof Uint8Array)){
  128. key = byteArrayToHex(key);
  129. keytype = 'hexkey';
  130. }else{
  131. toss3(capi.SQLITE_MISUSE,
  132. "Invalid value for the 'key' option. Expecting a string,",
  133. "ArrayBuffer, or Uint8Array.");
  134. return;
  135. }
  136. }else if( opt.textkey ){
  137. /* For textkey we need it to be in string form, so convert it to
  138. a string if it's a byte array... */
  139. keytype = 'textkey';
  140. key = opt.textkey;
  141. if(key instanceof ArrayBuffer){
  142. key = new Uint8Array(key);
  143. }
  144. if(key instanceof Uint8Array){
  145. key = new TextDecoder('utf-8').decode(key);
  146. }else if('string'!==typeof key){
  147. toss3(capi.SQLITE_MISUSE,
  148. "Invalid value for the 'textkey' option. Expecting a string,",
  149. "ArrayBuffer, or Uint8Array.");
  150. }
  151. }else if( opt.hexkey ){
  152. keytype = 'hexkey';
  153. key = opt.hexkey;
  154. if((key instanceof ArrayBuffer) || (key instanceof Uint8Array)){
  155. key = byteArrayToHex(key);
  156. }else if('string'!==typeof key){
  157. toss3(capi.SQLITE_MISUSE,
  158. "Invalid value for the 'hexkey' option. Expecting a string,",
  159. "ArrayBuffer, or Uint8Array.");
  160. }
  161. /* else assume it's valid hex codes */
  162. }else{
  163. return;
  164. }
  165. let stmt;
  166. try{
  167. stmt = db.prepare("PRAGMA "+keytype+"="+util.sqlite3__wasm_qfmt_token(key, 1));
  168. stmt.step();
  169. return true;
  170. }finally{
  171. if(stmt) stmt.finalize();
  172. }
  173. };
  174. //#endif enable-see
  175. /**
  176. A proxy for DB class constructors. It must be called with the
  177. being-construct DB object as its "this". See the DB constructor
  178. for the argument docs. This is split into a separate function
  179. in order to enable simple creation of special-case DB constructors,
  180. e.g. JsStorageDb and OpfsDb.
  181. Expects to be passed a configuration object with the following
  182. properties:
  183. - `.filename`: the db filename. It may be a special name like ":memory:"
  184. or "".
  185. - `.flags`: as documented in the DB constructor.
  186. - `.vfs`: as documented in the DB constructor.
  187. It also accepts those as the first 3 arguments.
  188. */
  189. const dbCtorHelper = function ctor(...args){
  190. if(!ctor._name2vfs){
  191. /**
  192. Map special filenames which we handle here (instead of in C)
  193. to some helpful metadata...
  194. As of 2022-09-20, the C API supports the names :localStorage:
  195. and :sessionStorage: for kvvfs. However, C code cannot
  196. determine (without embedded JS code, e.g. via Emscripten's
  197. EM_JS()) whether the kvvfs is legal in the current browser
  198. context (namely the main UI thread). In order to help client
  199. code fail early on, instead of it being delayed until they
  200. try to read or write a kvvfs-backed db, we'll check for those
  201. names here and throw if they're not legal in the current
  202. context.
  203. */
  204. ctor._name2vfs = Object.create(null);
  205. const isWorkerThread = ('function'===typeof importScripts/*===running in worker thread*/)
  206. ? (n)=>toss3("The VFS for",n,"is only available in the main window thread.")
  207. : false;
  208. ctor._name2vfs[':localStorage:'] = {
  209. vfs: 'kvvfs', filename: isWorkerThread || (()=>'local')
  210. };
  211. ctor._name2vfs[':sessionStorage:'] = {
  212. vfs: 'kvvfs', filename: isWorkerThread || (()=>'session')
  213. };
  214. }
  215. const opt = ctor.normalizeArgs(...args);
  216. let fn = opt.filename, vfsName = opt.vfs, flagsStr = opt.flags;
  217. if(('string'!==typeof fn && 'number'!==typeof fn)
  218. || 'string'!==typeof flagsStr
  219. || (vfsName && ('string'!==typeof vfsName && 'number'!==typeof vfsName))){
  220. sqlite3.config.error("Invalid DB ctor args",opt,arguments);
  221. toss3("Invalid arguments for DB constructor.");
  222. }
  223. let fnJs = ('number'===typeof fn) ? wasm.cstrToJs(fn) : fn;
  224. const vfsCheck = ctor._name2vfs[fnJs];
  225. if(vfsCheck){
  226. vfsName = vfsCheck.vfs;
  227. fn = fnJs = vfsCheck.filename(fnJs);
  228. }
  229. let pDb, oflags = 0;
  230. if( flagsStr.indexOf('c')>=0 ){
  231. oflags |= capi.SQLITE_OPEN_CREATE | capi.SQLITE_OPEN_READWRITE;
  232. }
  233. if( flagsStr.indexOf('w')>=0 ) oflags |= capi.SQLITE_OPEN_READWRITE;
  234. if( 0===oflags ) oflags |= capi.SQLITE_OPEN_READONLY;
  235. oflags |= capi.SQLITE_OPEN_EXRESCODE;
  236. const stack = wasm.pstack.pointer;
  237. try {
  238. const pPtr = wasm.pstack.allocPtr() /* output (sqlite3**) arg */;
  239. let rc = capi.sqlite3_open_v2(fn, pPtr, oflags, vfsName || 0);
  240. pDb = wasm.peekPtr(pPtr);
  241. checkSqlite3Rc(pDb, rc);
  242. capi.sqlite3_extended_result_codes(pDb, 1);
  243. if(flagsStr.indexOf('t')>=0){
  244. capi.sqlite3_trace_v2(pDb, capi.SQLITE_TRACE_STMT,
  245. __dbTraceToConsole, pDb);
  246. }
  247. }catch( e ){
  248. if( pDb ) capi.sqlite3_close_v2(pDb);
  249. throw e;
  250. }finally{
  251. wasm.pstack.restore(stack);
  252. }
  253. this.filename = fnJs;
  254. __ptrMap.set(this, pDb);
  255. __stmtMap.set(this, Object.create(null));
  256. try{
  257. //#if enable-see
  258. dbCtorApplySEEKey(this,opt);
  259. //#endif
  260. // Check for per-VFS post-open SQL/callback...
  261. const pVfs = capi.sqlite3_js_db_vfs(pDb)
  262. || toss3("Internal error: cannot get VFS for new db handle.");
  263. const postInitSql = __vfsPostOpenCallback[pVfs];
  264. if(postInitSql){
  265. /**
  266. Reminder: if this db is encrypted and the client did _not_ pass
  267. in the key, any init code will fail, causing the ctor to throw.
  268. We don't actually know whether the db is encrypted, so we cannot
  269. sensibly apply any heuristics which skip the init code only for
  270. encrypted databases for which no key has yet been supplied.
  271. */
  272. if(postInitSql instanceof Function){
  273. postInitSql(this, sqlite3);
  274. }else{
  275. checkSqlite3Rc(
  276. pDb, capi.sqlite3_exec(pDb, postInitSql, 0, 0, 0)
  277. );
  278. }
  279. }
  280. }catch(e){
  281. this.close();
  282. throw e;
  283. }
  284. };
  285. /**
  286. Sets a callback which should be called after a db is opened with
  287. the given sqlite3_vfs pointer. The 2nd argument must be a
  288. function, which gets called with
  289. (theOo1DbObject,sqlite3Namespace) at the end of the DB()
  290. constructor. The function must throw on error, in which case the
  291. db is closed and the exception is propagated. This function is
  292. intended only for use by DB subclasses or sqlite3_vfs
  293. implementations.
  294. Prior to 2024-07-22, it was legal to pass SQL code as the second
  295. argument, but that can interfere with a client's ability to run
  296. pragmas which must be run before anything else, namely (pragma
  297. locking_mode=exclusive) for use with WAL mode. That capability
  298. had only ever been used as an internal detail of the two OPFS
  299. VFSes, and they no longer use it that way.
  300. */
  301. dbCtorHelper.setVfsPostOpenCallback = function(pVfs, callback){
  302. if( !(callback instanceof Function)){
  303. toss3("dbCtorHelper.setVfsPostOpenCallback() should not be used with "+
  304. "a non-function argument.",arguments);
  305. }
  306. __vfsPostOpenCallback[pVfs] = callback;
  307. };
  308. /**
  309. A helper for DB constructors. It accepts either a single
  310. config-style object or up to 3 arguments (filename, dbOpenFlags,
  311. dbVfsName). It returns a new object containing:
  312. { filename: ..., flags: ..., vfs: ... }
  313. If passed an object, any additional properties it has are copied
  314. as-is into the new object.
  315. */
  316. dbCtorHelper.normalizeArgs = function(filename=':memory:',flags = 'c',vfs = null){
  317. const arg = {};
  318. if(1===arguments.length && arguments[0] && 'object'===typeof arguments[0]){
  319. Object.assign(arg, arguments[0]);
  320. if(undefined===arg.flags) arg.flags = 'c';
  321. if(undefined===arg.vfs) arg.vfs = null;
  322. if(undefined===arg.filename) arg.filename = ':memory:';
  323. }else{
  324. arg.filename = filename;
  325. arg.flags = flags;
  326. arg.vfs = vfs;
  327. }
  328. return arg;
  329. };
  330. /**
  331. The DB class provides a high-level OO wrapper around an sqlite3
  332. db handle.
  333. The given db filename must be resolvable using whatever
  334. filesystem layer (virtual or otherwise) is set up for the default
  335. sqlite3 VFS.
  336. Note that the special sqlite3 db names ":memory:" and ""
  337. (temporary db) have their normal special meanings here and need
  338. not resolve to real filenames, but "" uses an on-storage
  339. temporary database and requires that the VFS support that.
  340. The second argument specifies the open/create mode for the
  341. database. It must be string containing a sequence of letters (in
  342. any order, but case sensitive) specifying the mode:
  343. - "c": create if it does not exist, else fail if it does not
  344. exist. Implies the "w" flag.
  345. - "w": write. Implies "r": a db cannot be write-only.
  346. - "r": read-only if neither "w" nor "c" are provided, else it
  347. is ignored.
  348. - "t": enable tracing of SQL executed on this database handle,
  349. sending it to `console.log()`. To disable it later, call
  350. `sqlite3.capi.sqlite3_trace_v2(thisDb.pointer, 0, 0, 0)`.
  351. If "w" is not provided, the db is implicitly read-only, noting
  352. that "rc" is meaningless
  353. Any other letters are currently ignored. The default is
  354. "c". These modes are ignored for the special ":memory:" and ""
  355. names and _may_ be ignored altogether for certain VFSes.
  356. The final argument is analogous to the final argument of
  357. sqlite3_open_v2(): the name of an sqlite3 VFS. Pass a falsy value,
  358. or none at all, to use the default. If passed a value, it must
  359. be the string name of a VFS.
  360. The constructor optionally (and preferably) takes its arguments
  361. in the form of a single configuration object with the following
  362. properties:
  363. - `filename`: database file name
  364. - `flags`: open-mode flags
  365. - `vfs`: the VFS fname
  366. //#if enable-see
  367. SEE-capable builds optionally support ONE of the following
  368. additional options:
  369. - `key`, `hexkey`, or `textkey`: encryption key as a string,
  370. ArrayBuffer, or Uint8Array. These flags function as documented
  371. for the SEE pragmas of the same names. Using a byte array for
  372. `hexkey` is equivalent to the same series of hex codes in
  373. string form, so `'666f6f'` is equivalent to
  374. `Uint8Array([0x66,0x6f,0x6f])`. A `textkey` byte array is
  375. assumed to be UTF-8. A `key` string is transformed into a UTF-8
  376. byte array, and a `key` byte array is transformed into a
  377. `hexkey` with the same bytes.
  378. In non-SEE builds, these options are ignored. In SEE builds,
  379. `PRAGMA key/textkey/hexkey=X` is executed immediately after
  380. opening the db. If more than one of the options is provided,
  381. or any option has an invalid argument type, an exception is
  382. thrown.
  383. Note that some DB subclasses may run post-initialization SQL
  384. code, e.g. to set a busy-handler timeout or tweak the page cache
  385. size. Such code is run _after_ the SEE key is applied. If no key
  386. is supplied and the database is encrypted, execution of the
  387. post-initialization SQL will fail, causing the constructor to
  388. throw.
  389. //#endif enable-see
  390. The `filename` and `vfs` arguments may be either JS strings or
  391. C-strings allocated via WASM. `flags` is required to be a JS
  392. string (because it's specific to this API, which is specific
  393. to JS).
  394. For purposes of passing a DB instance to C-style sqlite3
  395. functions, the DB object's read-only `pointer` property holds its
  396. `sqlite3*` pointer value. That property can also be used to check
  397. whether this DB instance is still open: it will evaluate to
  398. `undefined` after the DB object's close() method is called.
  399. In the main window thread, the filenames `":localStorage:"` and
  400. `":sessionStorage:"` are special: they cause the db to use either
  401. localStorage or sessionStorage for storing the database using
  402. the kvvfs. If one of these names are used, they trump
  403. any vfs name set in the arguments.
  404. */
  405. const DB = function(...args){
  406. dbCtorHelper.apply(this, args);
  407. };
  408. DB.dbCtorHelper = dbCtorHelper;
  409. /**
  410. Internal-use enum for mapping JS types to DB-bindable types.
  411. These do not (and need not) line up with the SQLITE_type
  412. values. All values in this enum must be truthy and distinct
  413. but they need not be numbers.
  414. */
  415. const BindTypes = {
  416. null: 1,
  417. number: 2,
  418. string: 3,
  419. boolean: 4,
  420. blob: 5
  421. };
  422. BindTypes['undefined'] == BindTypes.null;
  423. if(wasm.bigIntEnabled){
  424. BindTypes.bigint = BindTypes.number;
  425. }
  426. /**
  427. This class wraps sqlite3_stmt. Calling this constructor
  428. directly will trigger an exception. Use DB.prepare() to create
  429. new instances.
  430. For purposes of passing a Stmt instance to C-style sqlite3
  431. functions, its read-only `pointer` property holds its `sqlite3_stmt*`
  432. pointer value.
  433. Other non-function properties include:
  434. - `db`: the DB object which created the statement.
  435. - `columnCount`: the number of result columns in the query, or 0
  436. for queries which cannot return results. This property is a proxy
  437. for sqlite3_column_count() and its use in loops should be avoided
  438. because of the call overhead associated with that. The
  439. `columnCount` is not cached when the Stmt is created because a
  440. schema change made via a separate db connection between this
  441. statement's preparation and when it is stepped may invalidate it.
  442. - `parameterCount`: the number of bindable parameters in the query.
  443. As a general rule, most methods of this class will throw if
  444. called on an instance which has been finalized. For brevity's
  445. sake, the method docs do not all repeat this warning.
  446. */
  447. const Stmt = function(){
  448. if(BindTypes!==arguments[2]){
  449. toss3(capi.SQLITE_MISUSE, "Do not call the Stmt constructor directly. Use DB.prepare().");
  450. }
  451. this.db = arguments[0];
  452. __ptrMap.set(this, arguments[1]);
  453. this.parameterCount = capi.sqlite3_bind_parameter_count(this.pointer);
  454. };
  455. /** Throws if the given DB has been closed, else it is returned. */
  456. const affirmDbOpen = function(db){
  457. if(!db.pointer) toss3("DB has been closed.");
  458. return db;
  459. };
  460. /** Throws if ndx is not an integer or if it is out of range
  461. for stmt.columnCount, else returns stmt.
  462. Reminder: this will also fail after the statement is finalized
  463. but the resulting error will be about an out-of-bounds column
  464. index rather than a statement-is-finalized error.
  465. */
  466. const affirmColIndex = function(stmt,ndx){
  467. if((ndx !== (ndx|0)) || ndx<0 || ndx>=stmt.columnCount){
  468. toss3("Column index",ndx,"is out of range.");
  469. }
  470. return stmt;
  471. };
  472. /**
  473. Expects to be passed the `arguments` object from DB.exec(). Does
  474. the argument processing/validation, throws on error, and returns
  475. a new object on success:
  476. { sql: the SQL, opt: optionsObj, cbArg: function}
  477. The opt object is a normalized copy of any passed to this
  478. function. The sql will be converted to a string if it is provided
  479. in one of the supported non-string formats.
  480. cbArg is only set if the opt.callback or opt.resultRows are set,
  481. in which case it's a function which expects to be passed the
  482. current Stmt and returns the callback argument of the type
  483. indicated by the input arguments.
  484. */
  485. const parseExecArgs = function(db, args){
  486. const out = Object.create(null);
  487. out.opt = Object.create(null);
  488. switch(args.length){
  489. case 1:
  490. if('string'===typeof args[0] || util.isSQLableTypedArray(args[0])){
  491. out.sql = args[0];
  492. }else if(Array.isArray(args[0])){
  493. out.sql = args[0];
  494. }else if(args[0] && 'object'===typeof args[0]){
  495. out.opt = args[0];
  496. out.sql = out.opt.sql;
  497. }
  498. break;
  499. case 2:
  500. out.sql = args[0];
  501. out.opt = args[1];
  502. break;
  503. default: toss3("Invalid argument count for exec().");
  504. };
  505. out.sql = util.flexibleString(out.sql);
  506. if('string'!==typeof out.sql){
  507. toss3("Missing SQL argument or unsupported SQL value type.");
  508. }
  509. const opt = out.opt;
  510. switch(opt.returnValue){
  511. case 'resultRows':
  512. if(!opt.resultRows) opt.resultRows = [];
  513. out.returnVal = ()=>opt.resultRows;
  514. break;
  515. case 'saveSql':
  516. if(!opt.saveSql) opt.saveSql = [];
  517. out.returnVal = ()=>opt.saveSql;
  518. break;
  519. case undefined:
  520. case 'this':
  521. out.returnVal = ()=>db;
  522. break;
  523. default:
  524. toss3("Invalid returnValue value:",opt.returnValue);
  525. }
  526. if(!opt.callback && !opt.returnValue && undefined!==opt.rowMode){
  527. if(!opt.resultRows) opt.resultRows = [];
  528. out.returnVal = ()=>opt.resultRows;
  529. }
  530. if(opt.callback || opt.resultRows){
  531. switch((undefined===opt.rowMode) ? 'array' : opt.rowMode) {
  532. case 'object':
  533. out.cbArg = (stmt,cache)=>{
  534. if( !cache.columnNames ) cache.columnNames = stmt.getColumnNames([]);
  535. /* https://sqlite.org/forum/forumpost/3632183d2470617d:
  536. conversion of rows to objects (key/val pairs) is
  537. somewhat expensive for large data sets because of the
  538. native-to-JS conversion of the column names. If we
  539. instead cache the names and build objects from that
  540. list of strings, it can run twice as fast. The
  541. difference is not noticeable for small data sets but
  542. becomes human-perceivable when enough rows are
  543. involved. */
  544. const row = stmt.get([]);
  545. const rv = Object.create(null);
  546. for( const i in cache.columnNames ) rv[cache.columnNames[i]] = row[i];
  547. return rv;
  548. };
  549. break;
  550. case 'array': out.cbArg = (stmt)=>stmt.get([]); break;
  551. case 'stmt':
  552. if(Array.isArray(opt.resultRows)){
  553. toss3("exec(): invalid rowMode for a resultRows array: must",
  554. "be one of 'array', 'object',",
  555. "a result column number, or column name reference.");
  556. }
  557. out.cbArg = (stmt)=>stmt;
  558. break;
  559. default:
  560. if(util.isInt32(opt.rowMode)){
  561. out.cbArg = (stmt)=>stmt.get(opt.rowMode);
  562. break;
  563. }else if('string'===typeof opt.rowMode
  564. && opt.rowMode.length>1
  565. && '$'===opt.rowMode[0]){
  566. /* "$X": fetch column named "X" (case-sensitive!). Prior
  567. to 2022-12-14 ":X" and "@X" were also permitted, but
  568. having so many options is unnecessary and likely to
  569. cause confusion. */
  570. const $colName = opt.rowMode.substr(1);
  571. out.cbArg = (stmt)=>{
  572. const rc = stmt.get(Object.create(null))[$colName];
  573. return (undefined===rc)
  574. ? toss3(capi.SQLITE_NOTFOUND,
  575. "exec(): unknown result column:",$colName)
  576. : rc;
  577. };
  578. break;
  579. }
  580. toss3("Invalid rowMode:",opt.rowMode);
  581. }
  582. }
  583. return out;
  584. };
  585. /**
  586. Internal impl of the DB.selectValue(), selectArray(), and
  587. selectObject() methods.
  588. */
  589. const __selectFirstRow = (db, sql, bind, ...getArgs)=>{
  590. const stmt = db.prepare(sql);
  591. try {
  592. const rc = stmt.bind(bind).step() ? stmt.get(...getArgs) : undefined;
  593. stmt.reset(/*for INSERT...RETURNING locking case*/);
  594. return rc;
  595. }finally{
  596. stmt.finalize();
  597. }
  598. };
  599. /**
  600. Internal impl of the DB.selectArrays() and selectObjects()
  601. methods.
  602. */
  603. const __selectAll =
  604. (db, sql, bind, rowMode)=>db.exec({
  605. sql, bind, rowMode, returnValue: 'resultRows'
  606. });
  607. /**
  608. Expects to be given a DB instance or an `sqlite3*` pointer (may
  609. be null) and an sqlite3 API result code. If the result code is
  610. not falsy, this function throws an SQLite3Error with an error
  611. message from sqlite3_errmsg(), using db (or, if db is-a DB,
  612. db.pointer) as the db handle, or sqlite3_errstr() if db is
  613. falsy. Note that if it's passed a non-error code like SQLITE_ROW
  614. or SQLITE_DONE, it will still throw but the error string might be
  615. "Not an error." The various non-0 non-error codes need to be
  616. checked for in client code where they are expected.
  617. The thrown exception's `resultCode` property will be the value of
  618. the second argument to this function.
  619. If it does not throw, it returns its first argument.
  620. */
  621. DB.checkRc = (db,resultCode)=>checkSqlite3Rc(db,resultCode);
  622. DB.prototype = {
  623. /** Returns true if this db handle is open, else false. */
  624. isOpen: function(){
  625. return !!this.pointer;
  626. },
  627. /** Throws if this given DB has been closed, else returns `this`. */
  628. affirmOpen: function(){
  629. return affirmDbOpen(this);
  630. },
  631. /**
  632. Finalizes all open statements and closes this database
  633. connection. This is a no-op if the db has already been
  634. closed. After calling close(), `this.pointer` will resolve to
  635. `undefined`, so that can be used to check whether the db
  636. instance is still opened.
  637. If this.onclose.before is a function then it is called before
  638. any close-related cleanup.
  639. If this.onclose.after is a function then it is called after the
  640. db is closed but before auxiliary state like this.filename is
  641. cleared.
  642. Both onclose handlers are passed this object, with the onclose
  643. object as their "this," noting that the db will have been
  644. closed when onclose.after is called. If this db is not opened
  645. when close() is called, neither of the handlers are called. Any
  646. exceptions the handlers throw are ignored because "destructors
  647. must not throw."
  648. Note that garbage collection of a db handle, if it happens at
  649. all, will never trigger close(), so onclose handlers are not a
  650. reliable way to implement close-time cleanup or maintenance of
  651. a db.
  652. */
  653. close: function(){
  654. if(this.pointer){
  655. if(this.onclose && (this.onclose.before instanceof Function)){
  656. try{this.onclose.before(this)}
  657. catch(e){/*ignore*/}
  658. }
  659. const pDb = this.pointer;
  660. Object.keys(__stmtMap.get(this)).forEach((k,s)=>{
  661. if(s && s.pointer){
  662. try{s.finalize()}
  663. catch(e){/*ignore*/}
  664. }
  665. });
  666. __ptrMap.delete(this);
  667. __stmtMap.delete(this);
  668. capi.sqlite3_close_v2(pDb);
  669. if(this.onclose && (this.onclose.after instanceof Function)){
  670. try{this.onclose.after(this)}
  671. catch(e){/*ignore*/}
  672. }
  673. delete this.filename;
  674. }
  675. },
  676. /**
  677. Returns the number of changes, as per sqlite3_changes()
  678. (if the first argument is false) or sqlite3_total_changes()
  679. (if it's true). If the 2nd argument is true, it uses
  680. sqlite3_changes64() or sqlite3_total_changes64(), which
  681. will trigger an exception if this build does not have
  682. BigInt support enabled.
  683. */
  684. changes: function(total=false,sixtyFour=false){
  685. const p = affirmDbOpen(this).pointer;
  686. if(total){
  687. return sixtyFour
  688. ? capi.sqlite3_total_changes64(p)
  689. : capi.sqlite3_total_changes(p);
  690. }else{
  691. return sixtyFour
  692. ? capi.sqlite3_changes64(p)
  693. : capi.sqlite3_changes(p);
  694. }
  695. },
  696. /**
  697. Similar to the this.filename but returns the
  698. sqlite3_db_filename() value for the given database name,
  699. defaulting to "main". The argument may be either a JS string
  700. or a pointer to a WASM-allocated C-string.
  701. */
  702. dbFilename: function(dbName='main'){
  703. return capi.sqlite3_db_filename(affirmDbOpen(this).pointer, dbName);
  704. },
  705. /**
  706. Returns the name of the given 0-based db number, as documented
  707. for sqlite3_db_name().
  708. */
  709. dbName: function(dbNumber=0){
  710. return capi.sqlite3_db_name(affirmDbOpen(this).pointer, dbNumber);
  711. },
  712. /**
  713. Returns the name of the sqlite3_vfs used by the given database
  714. of this connection (defaulting to 'main'). The argument may be
  715. either a JS string or a WASM C-string. Returns undefined if the
  716. given db name is invalid. Throws if this object has been
  717. close()d.
  718. */
  719. dbVfsName: function(dbName=0){
  720. let rc;
  721. const pVfs = capi.sqlite3_js_db_vfs(
  722. affirmDbOpen(this).pointer, dbName
  723. );
  724. if(pVfs){
  725. const v = new capi.sqlite3_vfs(pVfs);
  726. try{ rc = wasm.cstrToJs(v.$zName) }
  727. finally { v.dispose() }
  728. }
  729. return rc;
  730. },
  731. /**
  732. Compiles the given SQL and returns a prepared Stmt. This is
  733. the only way to create new Stmt objects. Throws on error.
  734. The given SQL must be a string, a Uint8Array holding SQL, a
  735. WASM pointer to memory holding the NUL-terminated SQL string,
  736. or an array of strings. In the latter case, the array is
  737. concatenated together, with no separators, to form the SQL
  738. string (arrays are often a convenient way to formulate long
  739. statements). If the SQL contains no statements, an
  740. SQLite3Error is thrown.
  741. Design note: the C API permits empty SQL, reporting it as a 0
  742. result code and a NULL stmt pointer. Supporting that case here
  743. would cause extra work for all clients: any use of the Stmt API
  744. on such a statement will necessarily throw, so clients would be
  745. required to check `stmt.pointer` after calling `prepare()` in
  746. order to determine whether the Stmt instance is empty or not.
  747. Long-time practice (with other sqlite3 script bindings)
  748. suggests that the empty-prepare case is sufficiently rare that
  749. supporting it here would simply hurt overall usability.
  750. */
  751. prepare: function(sql){
  752. affirmDbOpen(this);
  753. const stack = wasm.pstack.pointer;
  754. let ppStmt, pStmt;
  755. try{
  756. ppStmt = wasm.pstack.alloc(8)/* output (sqlite3_stmt**) arg */;
  757. DB.checkRc(this, capi.sqlite3_prepare_v2(this.pointer, sql, -1, ppStmt, null));
  758. pStmt = wasm.peekPtr(ppStmt);
  759. }
  760. finally {
  761. wasm.pstack.restore(stack);
  762. }
  763. if(!pStmt) toss3("Cannot prepare empty SQL.");
  764. const stmt = new Stmt(this, pStmt, BindTypes);
  765. __stmtMap.get(this)[pStmt] = stmt;
  766. return stmt;
  767. },
  768. /**
  769. Executes one or more SQL statements in the form of a single
  770. string. Its arguments must be either (sql,optionsObject) or
  771. (optionsObject). In the latter case, optionsObject.sql must
  772. contain the SQL to execute. By default it returns this object
  773. but that can be changed via the `returnValue` option as
  774. described below. Throws on error.
  775. If no SQL is provided, or a non-string is provided, an
  776. exception is triggered. Empty SQL, on the other hand, is
  777. simply a no-op.
  778. The optional options object may contain any of the following
  779. properties:
  780. - `sql` = the SQL to run (unless it's provided as the first
  781. argument). This must be of type string, Uint8Array, or an array
  782. of strings. In the latter case they're concatenated together
  783. as-is, _with no separator_ between elements, before evaluation.
  784. The array form is often simpler for long hand-written queries.
  785. - `bind` = a single value valid as an argument for
  786. Stmt.bind(). This is _only_ applied to the _first_ non-empty
  787. statement in the SQL which has any bindable parameters. (Empty
  788. statements are skipped entirely.)
  789. - `saveSql` = an optional array. If set, the SQL of each
  790. executed statement is appended to this array before the
  791. statement is executed (but after it is prepared - we don't have
  792. the string until after that). Empty SQL statements are elided
  793. but can have odd effects in the output. e.g. SQL of: `"select
  794. 1; -- empty\n; select 2"` will result in an array containing
  795. `["select 1;", "--empty \n; select 2"]`. That's simply how
  796. sqlite3 records the SQL for the 2nd statement.
  797. ==================================================================
  798. The following options apply _only_ to the _first_ statement
  799. which has a non-zero result column count, regardless of whether
  800. the statement actually produces any result rows.
  801. ==================================================================
  802. - `columnNames`: if this is an array, the column names of the
  803. result set are stored in this array before the callback (if
  804. any) is triggered (regardless of whether the query produces any
  805. result rows). If no statement has result columns, this value is
  806. unchanged. Achtung: an SQL result may have multiple columns
  807. with identical names.
  808. - `callback` = a function which gets called for each row of the
  809. result set, but only if that statement has any result rows. The
  810. callback's "this" is the options object, noting that this
  811. function synthesizes one if the caller does not pass one to
  812. exec(). The second argument passed to the callback is always
  813. the current Stmt object, as it's needed if the caller wants to
  814. fetch the column names or some such (noting that they could
  815. also be fetched via `this.columnNames`, if the client provides
  816. the `columnNames` option). If the callback returns a literal
  817. `false` (as opposed to any other falsy value, e.g. an implicit
  818. `undefined` return), any ongoing statement-`step()` iteration
  819. stops without an error. The return value of the callback is
  820. otherwise ignored.
  821. ACHTUNG: The callback MUST NOT modify the Stmt object. Calling
  822. any of the Stmt.get() variants, Stmt.getColumnName(), or
  823. similar, is legal, but calling step() or finalize() is
  824. not. Member methods which are illegal in this context will
  825. trigger an exception, but clients must also refrain from using
  826. any lower-level (C-style) APIs which might modify the
  827. statement.
  828. The first argument passed to the callback defaults to an array of
  829. values from the current result row but may be changed with ...
  830. - `rowMode` = specifies the type of he callback's first argument.
  831. It may be any of...
  832. A) A string describing what type of argument should be passed
  833. as the first argument to the callback:
  834. A.1) `'array'` (the default) causes the results of
  835. `stmt.get([])` to be passed to the `callback` and/or appended
  836. to `resultRows`.
  837. A.2) `'object'` causes the results of
  838. `stmt.get(Object.create(null))` to be passed to the
  839. `callback` and/or appended to `resultRows`. Achtung: an SQL
  840. result may have multiple columns with identical names. In
  841. that case, the right-most column will be the one set in this
  842. object!
  843. A.3) `'stmt'` causes the current Stmt to be passed to the
  844. callback, but this mode will trigger an exception if
  845. `resultRows` is an array because appending the transient
  846. statement to the array would be downright unhelpful.
  847. B) An integer, indicating a zero-based column in the result
  848. row. Only that one single value will be passed on.
  849. C) A string with a minimum length of 2 and leading character of
  850. '$' will fetch the row as an object, extract that one field,
  851. and pass that field's value to the callback. Note that these
  852. keys are case-sensitive so must match the case used in the
  853. SQL. e.g. `"select a A from t"` with a `rowMode` of `'$A'`
  854. would work but `'$a'` would not. A reference to a column not in
  855. the result set will trigger an exception on the first row (as
  856. the check is not performed until rows are fetched). Note also
  857. that `$` is a legal identifier character in JS so need not be
  858. quoted.
  859. Any other `rowMode` value triggers an exception.
  860. - `resultRows`: if this is an array, it functions similarly to
  861. the `callback` option: each row of the result set (if any),
  862. with the exception that the `rowMode` 'stmt' is not legal. It
  863. is legal to use both `resultRows` and `callback`, but
  864. `resultRows` is likely much simpler to use for small data sets
  865. and can be used over a WebWorker-style message interface.
  866. exec() throws if `resultRows` is set and `rowMode` is 'stmt'.
  867. - `returnValue`: is a string specifying what this function
  868. should return:
  869. A) The default value is (usually) `"this"`, meaning that the
  870. DB object itself should be returned. The exception is if
  871. the caller passes neither of `callback` nor `returnValue`
  872. but does pass an explicit `rowMode` then the default
  873. `returnValue` is `"resultRows"`, described below.
  874. B) `"resultRows"` means to return the value of the
  875. `resultRows` option. If `resultRows` is not set, this
  876. function behaves as if it were set to an empty array.
  877. C) `"saveSql"` means to return the value of the
  878. `saveSql` option. If `saveSql` is not set, this
  879. function behaves as if it were set to an empty array.
  880. Potential TODOs:
  881. - `bind`: permit an array of arrays/objects to bind. The first
  882. sub-array would act on the first statement which has bindable
  883. parameters (as it does now). The 2nd would act on the next such
  884. statement, etc.
  885. - `callback` and `resultRows`: permit an array entries with
  886. semantics similar to those described for `bind` above.
  887. */
  888. exec: function(/*(sql [,obj]) || (obj)*/){
  889. affirmDbOpen(this);
  890. const arg = parseExecArgs(this, arguments);
  891. if(!arg.sql){
  892. return toss3("exec() requires an SQL string.");
  893. }
  894. const opt = arg.opt;
  895. const callback = opt.callback;
  896. const resultRows =
  897. Array.isArray(opt.resultRows) ? opt.resultRows : undefined;
  898. let stmt;
  899. let bind = opt.bind;
  900. let evalFirstResult = !!(
  901. arg.cbArg || opt.columnNames || resultRows
  902. ) /* true to step through the first result-returning statement */;
  903. const stack = wasm.scopedAllocPush();
  904. const saveSql = Array.isArray(opt.saveSql) ? opt.saveSql : undefined;
  905. try{
  906. const isTA = util.isSQLableTypedArray(arg.sql)
  907. /* Optimization: if the SQL is a TypedArray we can save some string
  908. conversion costs. */;
  909. /* Allocate the two output pointers (ppStmt, pzTail) and heap
  910. space for the SQL (pSql). When prepare_v2() returns, pzTail
  911. will point to somewhere in pSql. */
  912. let sqlByteLen = isTA ? arg.sql.byteLength : wasm.jstrlen(arg.sql);
  913. const ppStmt = wasm.scopedAlloc(
  914. /* output (sqlite3_stmt**) arg and pzTail */
  915. (2 * wasm.ptrSizeof) + (sqlByteLen + 1/* SQL + NUL */)
  916. );
  917. const pzTail = ppStmt + wasm.ptrSizeof /* final arg to sqlite3_prepare_v2() */;
  918. let pSql = pzTail + wasm.ptrSizeof;
  919. const pSqlEnd = pSql + sqlByteLen;
  920. if(isTA) wasm.heap8().set(arg.sql, pSql);
  921. else wasm.jstrcpy(arg.sql, wasm.heap8(), pSql, sqlByteLen, false);
  922. wasm.poke(pSql + sqlByteLen, 0/*NUL terminator*/);
  923. while(pSql && wasm.peek(pSql, 'i8')
  924. /* Maintenance reminder:^^^ _must_ be 'i8' or else we
  925. will very likely cause an endless loop. What that's
  926. doing is checking for a terminating NUL byte. If we
  927. use i32 or similar then we read 4 bytes, read stuff
  928. around the NUL terminator, and get stuck in and
  929. endless loop at the end of the SQL, endlessly
  930. re-preparing an empty statement. */ ){
  931. wasm.pokePtr([ppStmt, pzTail], 0);
  932. DB.checkRc(this, capi.sqlite3_prepare_v3(
  933. this.pointer, pSql, sqlByteLen, 0, ppStmt, pzTail
  934. ));
  935. const pStmt = wasm.peekPtr(ppStmt);
  936. pSql = wasm.peekPtr(pzTail);
  937. sqlByteLen = pSqlEnd - pSql;
  938. if(!pStmt) continue;
  939. if(saveSql) saveSql.push(capi.sqlite3_sql(pStmt).trim());
  940. stmt = new Stmt(this, pStmt, BindTypes);
  941. if(bind && stmt.parameterCount){
  942. stmt.bind(bind);
  943. bind = null;
  944. }
  945. if(evalFirstResult && stmt.columnCount){
  946. /* Only forward SELECT-style results for the FIRST query
  947. in the SQL which potentially has them. */
  948. let gotColNames = Array.isArray(
  949. opt.columnNames
  950. /* As reported in
  951. https://sqlite.org/forum/forumpost/7774b773937cbe0a
  952. we need to delay fetching of the column names until
  953. after the first step() (if we step() at all) because
  954. a schema change between the prepare() and step(), via
  955. another connection, may invalidate the column count
  956. and names. */) ? 0 : 1;
  957. evalFirstResult = false;
  958. if(arg.cbArg || resultRows){
  959. const cbArgCache = Object.create(null)
  960. /* 2nd arg for arg.cbArg, used by (at least) row-to-object
  961. converter */;
  962. for( ; stmt.step(); __execLock.delete(stmt) ){
  963. if(0===gotColNames++){
  964. stmt.getColumnNames(cbArgCache.columnNames = (opt.columnNames || []));
  965. }
  966. __execLock.add(stmt);
  967. const row = arg.cbArg(stmt,cbArgCache);
  968. if(resultRows) resultRows.push(row);
  969. if(callback && false === callback.call(opt, row, stmt)){
  970. break;
  971. }
  972. }
  973. __execLock.delete(stmt);
  974. }
  975. if(0===gotColNames){
  976. /* opt.columnNames was provided but we visited no result rows */
  977. stmt.getColumnNames(opt.columnNames);
  978. }
  979. }else{
  980. stmt.step();
  981. }
  982. stmt.reset(
  983. /* In order to trigger an exception in the
  984. INSERT...RETURNING locking scenario:
  985. https://sqlite.org/forum/forumpost/36f7a2e7494897df
  986. */).finalize();
  987. stmt = null;
  988. }/*prepare() loop*/
  989. }/*catch(e){
  990. sqlite3.config.warn("DB.exec() is propagating exception",opt,e);
  991. throw e;
  992. }*/finally{
  993. wasm.scopedAllocPop(stack);
  994. if(stmt){
  995. __execLock.delete(stmt);
  996. stmt.finalize();
  997. }
  998. }
  999. return arg.returnVal();
  1000. }/*exec()*/,
  1001. /**
  1002. Creates a new UDF (User-Defined Function) which is accessible
  1003. via SQL code. This function may be called in any of the
  1004. following forms:
  1005. - (name, function)
  1006. - (name, function, optionsObject)
  1007. - (name, optionsObject)
  1008. - (optionsObject)
  1009. In the final two cases, the function must be defined as the
  1010. `callback` property of the options object (optionally called
  1011. `xFunc` to align with the C API documentation). In the final
  1012. case, the function's name must be the 'name' property.
  1013. The first two call forms can only be used for creating scalar
  1014. functions. Creating an aggregate or window function requires
  1015. the options-object form (see below for details).
  1016. UDFs can be removed as documented for
  1017. sqlite3_create_function_v2() and
  1018. sqlite3_create_window_function(), but doing so will "leak" the
  1019. JS-created WASM binding of those functions (meaning that their
  1020. entries in the WASM indirect function table still
  1021. exist). Eliminating that potential leak is a pending TODO.
  1022. On success, returns this object. Throws on error.
  1023. When called from SQL arguments to the UDF, and its result,
  1024. will be converted between JS and SQL with as much fidelity as
  1025. is feasible, triggering an exception if a type conversion
  1026. cannot be determined. The docs for sqlite3_create_function_v2()
  1027. describe the conversions in more detail.
  1028. The values set in the options object differ for scalar and
  1029. aggregate functions:
  1030. - Scalar: set the `xFunc` function-type property to the UDF
  1031. function.
  1032. - Aggregate: set the `xStep` and `xFinal` function-type
  1033. properties to the "step" and "final" callbacks for the
  1034. aggregate. Do not set the `xFunc` property.
  1035. - Window: set the `xStep`, `xFinal`, `xValue`, and `xInverse`
  1036. function-type properties. Do not set the `xFunc` property.
  1037. The options object may optionally have an `xDestroy`
  1038. function-type property, as per sqlite3_create_function_v2().
  1039. Its argument will be the WASM-pointer-type value of the `pApp`
  1040. property, and this function will throw if `pApp` is defined but
  1041. is not null, undefined, or a numeric (WASM pointer)
  1042. value. i.e. `pApp`, if set, must be value suitable for use as a
  1043. WASM pointer argument, noting that `null` or `undefined` will
  1044. translate to 0 for that purpose.
  1045. The options object may contain flags to modify how
  1046. the function is defined:
  1047. - `arity`: the number of arguments which SQL calls to this
  1048. function expect or require. The default value is `xFunc.length`
  1049. or `xStep.length` (i.e. the number of declared parameters it
  1050. has) **MINUS 1** (see below for why). As a special case, if the
  1051. `length` is 0, its arity is also 0 instead of -1. A negative
  1052. arity value means that the function is variadic and may accept
  1053. any number of arguments, up to sqlite3's compile-time
  1054. limits. sqlite3 will enforce the argument count if is zero or
  1055. greater. The callback always receives a pointer to an
  1056. `sqlite3_context` object as its first argument. Any arguments
  1057. after that are from SQL code. The leading context argument does
  1058. _not_ count towards the function's arity. See the docs for
  1059. sqlite3.capi.sqlite3_create_function_v2() for why that argument
  1060. is needed in the interface.
  1061. The following options-object properties correspond to flags
  1062. documented at:
  1063. https://sqlite.org/c3ref/create_function.html
  1064. - `deterministic` = sqlite3.capi.SQLITE_DETERMINISTIC
  1065. - `directOnly` = sqlite3.capi.SQLITE_DIRECTONLY
  1066. - `innocuous` = sqlite3.capi.SQLITE_INNOCUOUS
  1067. Sidebar: the ability to add new WASM-accessible functions to
  1068. the runtime requires that the WASM build is compiled with the
  1069. equivalent functionality as that provided by Emscripten's
  1070. `-sALLOW_TABLE_GROWTH` flag.
  1071. */
  1072. createFunction: function f(name, xFunc, opt){
  1073. const isFunc = (f)=>(f instanceof Function);
  1074. switch(arguments.length){
  1075. case 1: /* (optionsObject) */
  1076. opt = name;
  1077. name = opt.name;
  1078. xFunc = opt.xFunc || 0;
  1079. break;
  1080. case 2: /* (name, callback|optionsObject) */
  1081. if(!isFunc(xFunc)){
  1082. opt = xFunc;
  1083. xFunc = opt.xFunc || 0;
  1084. }
  1085. break;
  1086. case 3: /* name, xFunc, opt */
  1087. break;
  1088. default: break;
  1089. }
  1090. if(!opt) opt = {};
  1091. if('string' !== typeof name){
  1092. toss3("Invalid arguments: missing function name.");
  1093. }
  1094. let xStep = opt.xStep || 0;
  1095. let xFinal = opt.xFinal || 0;
  1096. const xValue = opt.xValue || 0;
  1097. const xInverse = opt.xInverse || 0;
  1098. let isWindow = undefined;
  1099. if(isFunc(xFunc)){
  1100. isWindow = false;
  1101. if(isFunc(xStep) || isFunc(xFinal)){
  1102. toss3("Ambiguous arguments: scalar or aggregate?");
  1103. }
  1104. xStep = xFinal = null;
  1105. }else if(isFunc(xStep)){
  1106. if(!isFunc(xFinal)){
  1107. toss3("Missing xFinal() callback for aggregate or window UDF.");
  1108. }
  1109. xFunc = null;
  1110. }else if(isFunc(xFinal)){
  1111. toss3("Missing xStep() callback for aggregate or window UDF.");
  1112. }else{
  1113. toss3("Missing function-type properties.");
  1114. }
  1115. if(false === isWindow){
  1116. if(isFunc(xValue) || isFunc(xInverse)){
  1117. toss3("xValue and xInverse are not permitted for non-window UDFs.");
  1118. }
  1119. }else if(isFunc(xValue)){
  1120. if(!isFunc(xInverse)){
  1121. toss3("xInverse must be provided if xValue is.");
  1122. }
  1123. isWindow = true;
  1124. }else if(isFunc(xInverse)){
  1125. toss3("xValue must be provided if xInverse is.");
  1126. }
  1127. const pApp = opt.pApp;
  1128. if(undefined!==pApp &&
  1129. null!==pApp &&
  1130. (('number'!==typeof pApp) || !util.isInt32(pApp))){
  1131. toss3("Invalid value for pApp property. Must be a legal WASM pointer value.");
  1132. }
  1133. const xDestroy = opt.xDestroy || 0;
  1134. if(xDestroy && !isFunc(xDestroy)){
  1135. toss3("xDestroy property must be a function.");
  1136. }
  1137. let fFlags = 0 /*flags for sqlite3_create_function_v2()*/;
  1138. if(getOwnOption(opt, 'deterministic')) fFlags |= capi.SQLITE_DETERMINISTIC;
  1139. if(getOwnOption(opt, 'directOnly')) fFlags |= capi.SQLITE_DIRECTONLY;
  1140. if(getOwnOption(opt, 'innocuous')) fFlags |= capi.SQLITE_INNOCUOUS;
  1141. name = name.toLowerCase();
  1142. const xArity = xFunc || xStep;
  1143. const arity = getOwnOption(opt, 'arity');
  1144. const arityArg = ('number'===typeof arity
  1145. ? arity
  1146. : (xArity.length ? xArity.length-1/*for pCtx arg*/ : 0));
  1147. let rc;
  1148. if( isWindow ){
  1149. rc = capi.sqlite3_create_window_function(
  1150. this.pointer, name, arityArg,
  1151. capi.SQLITE_UTF8 | fFlags, pApp || 0,
  1152. xStep, xFinal, xValue, xInverse, xDestroy);
  1153. }else{
  1154. rc = capi.sqlite3_create_function_v2(
  1155. this.pointer, name, arityArg,
  1156. capi.SQLITE_UTF8 | fFlags, pApp || 0,
  1157. xFunc, xStep, xFinal, xDestroy);
  1158. }
  1159. DB.checkRc(this, rc);
  1160. return this;
  1161. }/*createFunction()*/,
  1162. /**
  1163. Prepares the given SQL, step()s it one time, and returns
  1164. the value of the first result column. If it has no results,
  1165. undefined is returned.
  1166. If passed a second argument, it is treated like an argument
  1167. to Stmt.bind(), so may be any type supported by that
  1168. function. Passing the undefined value is the same as passing
  1169. no value, which is useful when...
  1170. If passed a 3rd argument, it is expected to be one of the
  1171. SQLITE_{typename} constants. Passing the undefined value is
  1172. the same as not passing a value.
  1173. Throws on error (e.g. malformed SQL).
  1174. */
  1175. selectValue: function(sql,bind,asType){
  1176. return __selectFirstRow(this, sql, bind, 0, asType);
  1177. },
  1178. /**
  1179. Runs the given query and returns an array of the values from
  1180. the first result column of each row of the result set. The 2nd
  1181. argument is an optional value for use in a single-argument call
  1182. to Stmt.bind(). The 3rd argument may be any value suitable for
  1183. use as the 2nd argument to Stmt.get(). If a 3rd argument is
  1184. desired but no bind data are needed, pass `undefined` for the 2nd
  1185. argument.
  1186. If there are no result rows, an empty array is returned.
  1187. */
  1188. selectValues: function(sql,bind,asType){
  1189. const stmt = this.prepare(sql), rc = [];
  1190. try {
  1191. stmt.bind(bind);
  1192. while(stmt.step()) rc.push(stmt.get(0,asType));
  1193. stmt.reset(/*for INSERT...RETURNING locking case*/);
  1194. }finally{
  1195. stmt.finalize();
  1196. }
  1197. return rc;
  1198. },
  1199. /**
  1200. Prepares the given SQL, step()s it one time, and returns an
  1201. array containing the values of the first result row. If it has
  1202. no results, `undefined` is returned.
  1203. If passed a second argument other than `undefined`, it is
  1204. treated like an argument to Stmt.bind(), so may be any type
  1205. supported by that function.
  1206. Throws on error (e.g. malformed SQL).
  1207. */
  1208. selectArray: function(sql,bind){
  1209. return __selectFirstRow(this, sql, bind, []);
  1210. },
  1211. /**
  1212. Prepares the given SQL, step()s it one time, and returns an
  1213. object containing the key/value pairs of the first result
  1214. row. If it has no results, `undefined` is returned.
  1215. Note that the order of returned object's keys is not guaranteed
  1216. to be the same as the order of the fields in the query string.
  1217. If passed a second argument other than `undefined`, it is
  1218. treated like an argument to Stmt.bind(), so may be any type
  1219. supported by that function.
  1220. Throws on error (e.g. malformed SQL).
  1221. */
  1222. selectObject: function(sql,bind){
  1223. return __selectFirstRow(this, sql, bind, {});
  1224. },
  1225. /**
  1226. Runs the given SQL and returns an array of all results, with
  1227. each row represented as an array, as per the 'array' `rowMode`
  1228. option to `exec()`. An empty result set resolves
  1229. to an empty array. The second argument, if any, is treated as
  1230. the 'bind' option to a call to exec().
  1231. */
  1232. selectArrays: function(sql,bind){
  1233. return __selectAll(this, sql, bind, 'array');
  1234. },
  1235. /**
  1236. Works identically to selectArrays() except that each value
  1237. in the returned array is an object, as per the 'object' `rowMode`
  1238. option to `exec()`.
  1239. */
  1240. selectObjects: function(sql,bind){
  1241. return __selectAll(this, sql, bind, 'object');
  1242. },
  1243. /**
  1244. Returns the number of currently-opened Stmt handles for this db
  1245. handle, or 0 if this DB instance is closed. Note that only
  1246. handles prepared via this.prepare() are counted, and not
  1247. handles prepared using capi.sqlite3_prepare_v3() (or
  1248. equivalent).
  1249. */
  1250. openStatementCount: function(){
  1251. return this.pointer ? Object.keys(__stmtMap.get(this)).length : 0;
  1252. },
  1253. /**
  1254. Starts a transaction, calls the given callback, and then either
  1255. rolls back or commits the transaction, depending on whether the
  1256. callback throws. The callback is passed this db object as its
  1257. only argument. On success, returns the result of the
  1258. callback. Throws on error.
  1259. Note that transactions may not be nested, so this will throw if
  1260. it is called recursively. For nested transactions, use the
  1261. savepoint() method or manually manage SAVEPOINTs using exec().
  1262. If called with 2 arguments, the first must be a keyword which
  1263. is legal immediately after a BEGIN statement, e.g. one of
  1264. "DEFERRED", "IMMEDIATE", or "EXCLUSIVE". Though the exact list
  1265. of supported keywords is not hard-coded here, in order to be
  1266. future-compatible, if the argument does not look like a single
  1267. keyword then an exception is triggered with a description of
  1268. the problem.
  1269. */
  1270. transaction: function(/* [beginQualifier,] */callback){
  1271. let opener = 'BEGIN';
  1272. if(arguments.length>1){
  1273. if(/[^a-zA-Z]/.test(arguments[0])){
  1274. toss3(capi.SQLITE_MISUSE, "Invalid argument for BEGIN qualifier.");
  1275. }
  1276. opener += ' '+arguments[0];
  1277. callback = arguments[1];
  1278. }
  1279. affirmDbOpen(this).exec(opener);
  1280. try {
  1281. const rc = callback(this);
  1282. this.exec("COMMIT");
  1283. return rc;
  1284. }catch(e){
  1285. this.exec("ROLLBACK");
  1286. throw e;
  1287. }
  1288. },
  1289. /**
  1290. This works similarly to transaction() but uses sqlite3's SAVEPOINT
  1291. feature. This function starts a savepoint (with an unspecified name)
  1292. and calls the given callback function, passing it this db object.
  1293. If the callback returns, the savepoint is released (committed). If
  1294. the callback throws, the savepoint is rolled back. If it does not
  1295. throw, it returns the result of the callback.
  1296. */
  1297. savepoint: function(callback){
  1298. affirmDbOpen(this).exec("SAVEPOINT oo1");
  1299. try {
  1300. const rc = callback(this);
  1301. this.exec("RELEASE oo1");
  1302. return rc;
  1303. }catch(e){
  1304. this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1");
  1305. throw e;
  1306. }
  1307. },
  1308. /**
  1309. A convenience form of DB.checkRc(this,resultCode). If it does
  1310. not throw, it returns this object.
  1311. */
  1312. checkRc: function(resultCode){
  1313. return checkSqlite3Rc(this, resultCode);
  1314. }
  1315. }/*DB.prototype*/;
  1316. /** Throws if the given Stmt has been finalized, else stmt is
  1317. returned. */
  1318. const affirmStmtOpen = function(stmt){
  1319. if(!stmt.pointer) toss3("Stmt has been closed.");
  1320. return stmt;
  1321. };
  1322. /** Returns an opaque truthy value from the BindTypes
  1323. enum if v's type is a valid bindable type, else
  1324. returns a falsy value. As a special case, a value of
  1325. undefined is treated as a bind type of null. */
  1326. const isSupportedBindType = function(v){
  1327. let t = BindTypes[(null===v||undefined===v) ? 'null' : typeof v];
  1328. switch(t){
  1329. case BindTypes.boolean:
  1330. case BindTypes.null:
  1331. case BindTypes.number:
  1332. case BindTypes.string:
  1333. return t;
  1334. case BindTypes.bigint:
  1335. if(wasm.bigIntEnabled) return t;
  1336. /* else fall through */
  1337. default:
  1338. return util.isBindableTypedArray(v) ? BindTypes.blob : undefined;
  1339. }
  1340. };
  1341. /**
  1342. If isSupportedBindType(v) returns a truthy value, this
  1343. function returns that value, else it throws.
  1344. */
  1345. const affirmSupportedBindType = function(v){
  1346. //sqlite3.config.log('affirmSupportedBindType',v);
  1347. return isSupportedBindType(v) || toss3("Unsupported bind() argument type:",typeof v);
  1348. };
  1349. /**
  1350. If key is a number and within range of stmt's bound parameter
  1351. count, key is returned.
  1352. If key is not a number then it is checked against named
  1353. parameters. If a match is found, its index is returned.
  1354. Else it throws.
  1355. */
  1356. const affirmParamIndex = function(stmt,key){
  1357. const n = ('number'===typeof key)
  1358. ? key : capi.sqlite3_bind_parameter_index(stmt.pointer, key);
  1359. if(0===n || !util.isInt32(n)){
  1360. toss3("Invalid bind() parameter name: "+key);
  1361. }
  1362. else if(n<1 || n>stmt.parameterCount) toss3("Bind index",key,"is out of range.");
  1363. return n;
  1364. };
  1365. /**
  1366. Each Stmt object which is "locked" by DB.exec() gets an entry
  1367. here to note that "lock".
  1368. The reason this is in place is because exec({callback:...})'s
  1369. callback gets access to the Stmt objects created internally by
  1370. exec() but it must not use certain Stmt APIs.
  1371. */
  1372. const __execLock = new Set();
  1373. /**
  1374. This is a Stmt.get() counterpart of __execLock. Each time
  1375. Stmt.step() returns true, the statement is added to this set,
  1376. indicating that Stmt.get() is legal. Stmt APIs which invalidate
  1377. that status remove the Stmt object from this set, which will
  1378. cause Stmt.get() to throw with a descriptive error message
  1379. instead of a more generic "API misuse" if we were to allow that
  1380. call to reach the C API.
  1381. */
  1382. const __stmtMayGet = new Set();
  1383. /**
  1384. Stmt APIs which are prohibited on locked objects must call
  1385. affirmNotLockedByExec() before doing any work.
  1386. If __execLock.has(stmt) is truthy, this throws an exception
  1387. complaining that the 2nd argument (an operation name,
  1388. e.g. "bind()") is not legal while the statement is "locked".
  1389. Locking happens before an exec()-like callback is passed a
  1390. statement, to ensure that the callback does not mutate or
  1391. finalize the statement. If it does not throw, it returns stmt.
  1392. */
  1393. const affirmNotLockedByExec = function(stmt,currentOpName){
  1394. if(__execLock.has(stmt)){
  1395. toss3("Operation is illegal when statement is locked:",currentOpName);
  1396. }
  1397. return stmt;
  1398. };
  1399. /**
  1400. Binds a single bound parameter value on the given stmt at the
  1401. given index (numeric or named) using the given bindType (see
  1402. the BindTypes enum) and value. Throws on error. Returns stmt on
  1403. success.
  1404. */
  1405. const bindOne = function f(stmt,ndx,bindType,val){
  1406. affirmNotLockedByExec(affirmStmtOpen(stmt), 'bind()');
  1407. if(!f._){
  1408. f._tooBigInt = (v)=>toss3(
  1409. "BigInt value is too big to store without precision loss:", v
  1410. );
  1411. f._ = {
  1412. string: function(stmt, ndx, val, asBlob){
  1413. const [pStr, n] = wasm.allocCString(val, true);
  1414. const f = asBlob ? capi.sqlite3_bind_blob : capi.sqlite3_bind_text;
  1415. return f(stmt.pointer, ndx, pStr, n, capi.SQLITE_WASM_DEALLOC);
  1416. }
  1417. };
  1418. }/* static init */
  1419. affirmSupportedBindType(val);
  1420. ndx = affirmParamIndex(stmt,ndx);
  1421. let rc = 0;
  1422. switch((null===val || undefined===val) ? BindTypes.null : bindType){
  1423. case BindTypes.null:
  1424. rc = capi.sqlite3_bind_null(stmt.pointer, ndx);
  1425. break;
  1426. case BindTypes.string:
  1427. rc = f._.string(stmt, ndx, val, false);
  1428. break;
  1429. case BindTypes.number: {
  1430. let m;
  1431. if(util.isInt32(val)) m = capi.sqlite3_bind_int;
  1432. else if('bigint'===typeof val){
  1433. if(!util.bigIntFits64(val)){
  1434. f._tooBigInt(val);
  1435. }else if(wasm.bigIntEnabled){
  1436. m = capi.sqlite3_bind_int64;
  1437. }else if(util.bigIntFitsDouble(val)){
  1438. val = Number(val);
  1439. m = capi.sqlite3_bind_double;
  1440. }else{
  1441. f._tooBigInt(val);
  1442. }
  1443. }else{ // !int32, !bigint
  1444. val = Number(val);
  1445. if(wasm.bigIntEnabled && Number.isInteger(val)){
  1446. m = capi.sqlite3_bind_int64;
  1447. }else{
  1448. m = capi.sqlite3_bind_double;
  1449. }
  1450. }
  1451. rc = m(stmt.pointer, ndx, val);
  1452. break;
  1453. }
  1454. case BindTypes.boolean:
  1455. rc = capi.sqlite3_bind_int(stmt.pointer, ndx, val ? 1 : 0);
  1456. break;
  1457. case BindTypes.blob: {
  1458. if('string'===typeof val){
  1459. rc = f._.string(stmt, ndx, val, true);
  1460. break;
  1461. }else if(val instanceof ArrayBuffer){
  1462. val = new Uint8Array(val);
  1463. }else if(!util.isBindableTypedArray(val)){
  1464. toss3("Binding a value as a blob requires",
  1465. "that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");
  1466. }
  1467. const pBlob = wasm.alloc(val.byteLength || 1);
  1468. wasm.heap8().set(val.byteLength ? val : [0], pBlob)
  1469. rc = capi.sqlite3_bind_blob(stmt.pointer, ndx, pBlob, val.byteLength,
  1470. capi.SQLITE_WASM_DEALLOC);
  1471. break;
  1472. }
  1473. default:
  1474. sqlite3.config.warn("Unsupported bind() argument type:",val);
  1475. toss3("Unsupported bind() argument type: "+(typeof val));
  1476. }
  1477. if(rc) DB.checkRc(stmt.db.pointer, rc);
  1478. return stmt;
  1479. };
  1480. Stmt.prototype = {
  1481. /**
  1482. "Finalizes" this statement. This is a no-op if the statement
  1483. has already been finalized. Returns the result of
  1484. sqlite3_finalize() (0 on success, non-0 on error), or the
  1485. undefined value if the statement has already been
  1486. finalized. Regardless of success or failure, most methods in
  1487. this class will throw if called after this is.
  1488. This method always throws if called when it is illegal to do
  1489. so. Namely, when triggered via a per-row callback handler of a
  1490. DB.exec() call.
  1491. */
  1492. finalize: function(){
  1493. if(this.pointer){
  1494. affirmNotLockedByExec(this,'finalize()');
  1495. const rc = capi.sqlite3_finalize(this.pointer);
  1496. delete __stmtMap.get(this.db)[this.pointer];
  1497. __ptrMap.delete(this);
  1498. __execLock.delete(this);
  1499. __stmtMayGet.delete(this);
  1500. delete this.parameterCount;
  1501. delete this.db;
  1502. return rc;
  1503. }
  1504. },
  1505. /**
  1506. Clears all bound values. Returns this object. Throws if this
  1507. statement has been finalized or if modification of the
  1508. statement is currently illegal (e.g. in the per-row callback of
  1509. a DB.exec() call).
  1510. */
  1511. clearBindings: function(){
  1512. affirmNotLockedByExec(affirmStmtOpen(this), 'clearBindings()')
  1513. capi.sqlite3_clear_bindings(this.pointer);
  1514. __stmtMayGet.delete(this);
  1515. return this;
  1516. },
  1517. /**
  1518. Resets this statement so that it may be step()ed again from the
  1519. beginning. Returns this object. Throws if this statement has
  1520. been finalized, if it may not legally be reset because it is
  1521. currently being used from a DB.exec() callback, or if the
  1522. underlying call to sqlite3_reset() returns non-0.
  1523. If passed a truthy argument then this.clearBindings() is
  1524. also called, otherwise any existing bindings, along with
  1525. any memory allocated for them, are retained.
  1526. In versions 3.42.0 and earlier, this function did not throw if
  1527. sqlite3_reset() returns non-0, but it was discovered that
  1528. throwing (or significant extra client-side code) is necessary
  1529. in order to avoid certain silent failure scenarios, as
  1530. discussed at:
  1531. https://sqlite.org/forum/forumpost/36f7a2e7494897df
  1532. */
  1533. reset: function(alsoClearBinds){
  1534. affirmNotLockedByExec(this,'reset()');
  1535. if(alsoClearBinds) this.clearBindings();
  1536. const rc = capi.sqlite3_reset(affirmStmtOpen(this).pointer);
  1537. __stmtMayGet.delete(this);
  1538. checkSqlite3Rc(this.db, rc);
  1539. return this;
  1540. },
  1541. /**
  1542. Binds one or more values to its bindable parameters. It
  1543. accepts 1 or 2 arguments:
  1544. If passed a single argument, it must be either an array, an
  1545. object, or a value of a bindable type (see below).
  1546. If passed 2 arguments, the first one is the 1-based bind
  1547. index or bindable parameter name and the second one must be
  1548. a value of a bindable type.
  1549. Bindable value types:
  1550. - null is bound as NULL.
  1551. - undefined as a standalone value is a no-op intended to
  1552. simplify certain client-side use cases: passing undefined as
  1553. a value to this function will not actually bind anything and
  1554. this function will skip confirmation that binding is even
  1555. legal. (Those semantics simplify certain client-side uses.)
  1556. Conversely, a value of undefined as an array or object
  1557. property when binding an array/object (see below) is treated
  1558. the same as null.
  1559. - Numbers are bound as either doubles or integers: doubles if
  1560. they are larger than 32 bits, else double or int32, depending
  1561. on whether they have a fractional part. Booleans are bound as
  1562. integer 0 or 1. It is not expected the distinction of binding
  1563. doubles which have no fractional parts and integers is
  1564. significant for the majority of clients due to sqlite3's data
  1565. typing model. If BigInt support is enabled then this routine
  1566. will bind BigInt values as 64-bit integers if they'll fit in
  1567. 64 bits. If that support disabled, it will store the BigInt
  1568. as an int32 or a double if it can do so without loss of
  1569. precision. If the BigInt is _too BigInt_ then it will throw.
  1570. - Strings are bound as strings (use bindAsBlob() to force
  1571. blob binding).
  1572. - Uint8Array, Int8Array, and ArrayBuffer instances are bound as
  1573. blobs.
  1574. If passed an array, each element of the array is bound at
  1575. the parameter index equal to the array index plus 1
  1576. (because arrays are 0-based but binding is 1-based).
  1577. If passed an object, each object key is treated as a
  1578. bindable parameter name. The object keys _must_ match any
  1579. bindable parameter names, including any `$`, `@`, or `:`
  1580. prefix. Because `$` is a legal identifier chararacter in
  1581. JavaScript, that is the suggested prefix for bindable
  1582. parameters: `stmt.bind({$a: 1, $b: 2})`.
  1583. It returns this object on success and throws on
  1584. error. Errors include:
  1585. - Any bind index is out of range, a named bind parameter
  1586. does not match, or this statement has no bindable
  1587. parameters.
  1588. - Any value to bind is of an unsupported type.
  1589. - Passed no arguments or more than two.
  1590. - The statement has been finalized.
  1591. */
  1592. bind: function(/*[ndx,] arg*/){
  1593. affirmStmtOpen(this);
  1594. let ndx, arg;
  1595. switch(arguments.length){
  1596. case 1: ndx = 1; arg = arguments[0]; break;
  1597. case 2: ndx = arguments[0]; arg = arguments[1]; break;
  1598. default: toss3("Invalid bind() arguments.");
  1599. }
  1600. if(undefined===arg){
  1601. /* It might seem intuitive to bind undefined as NULL
  1602. but this approach simplifies certain client-side
  1603. uses when passing on arguments between 2+ levels of
  1604. functions. */
  1605. return this;
  1606. }else if(!this.parameterCount){
  1607. toss3("This statement has no bindable parameters.");
  1608. }
  1609. __stmtMayGet.delete(this);
  1610. if(null===arg){
  1611. /* bind NULL */
  1612. return bindOne(this, ndx, BindTypes.null, arg);
  1613. }
  1614. else if(Array.isArray(arg)){
  1615. /* bind each entry by index */
  1616. if(1!==arguments.length){
  1617. toss3("When binding an array, an index argument is not permitted.");
  1618. }
  1619. arg.forEach((v,i)=>bindOne(this, i+1, affirmSupportedBindType(v), v));
  1620. return this;
  1621. }else if(arg instanceof ArrayBuffer){
  1622. arg = new Uint8Array(arg);
  1623. }
  1624. if('object'===typeof arg/*null was checked above*/
  1625. && !util.isBindableTypedArray(arg)){
  1626. /* Treat each property of arg as a named bound parameter. */
  1627. if(1!==arguments.length){
  1628. toss3("When binding an object, an index argument is not permitted.");
  1629. }
  1630. Object.keys(arg)
  1631. .forEach(k=>bindOne(this, k,
  1632. affirmSupportedBindType(arg[k]),
  1633. arg[k]));
  1634. return this;
  1635. }else{
  1636. return bindOne(this, ndx, affirmSupportedBindType(arg), arg);
  1637. }
  1638. toss3("Should not reach this point.");
  1639. },
  1640. /**
  1641. Special case of bind() which binds the given value using the
  1642. BLOB binding mechanism instead of the default selected one for
  1643. the value. The ndx may be a numbered or named bind index. The
  1644. value must be of type string, null/undefined (both get treated
  1645. as null), or a TypedArray of a type supported by the bind()
  1646. API. This API cannot bind numbers as blobs.
  1647. If passed a single argument, a bind index of 1 is assumed and
  1648. the first argument is the value.
  1649. */
  1650. bindAsBlob: function(ndx,arg){
  1651. affirmStmtOpen(this);
  1652. if(1===arguments.length){
  1653. arg = ndx;
  1654. ndx = 1;
  1655. }
  1656. const t = affirmSupportedBindType(arg);
  1657. if(BindTypes.string !== t && BindTypes.blob !== t
  1658. && BindTypes.null !== t){
  1659. toss3("Invalid value type for bindAsBlob()");
  1660. }
  1661. return bindOne(this, ndx, BindTypes.blob, arg);
  1662. },
  1663. /**
  1664. Steps the statement one time. If the result indicates that a
  1665. row of data is available, a truthy value is returned. If no
  1666. row of data is available, a falsy value is returned. Throws on
  1667. error.
  1668. */
  1669. step: function(){
  1670. affirmNotLockedByExec(this, 'step()');
  1671. const rc = capi.sqlite3_step(affirmStmtOpen(this).pointer);
  1672. switch(rc){
  1673. case capi.SQLITE_DONE:
  1674. __stmtMayGet.delete(this);
  1675. return false;
  1676. case capi.SQLITE_ROW:
  1677. __stmtMayGet.add(this);
  1678. return true;
  1679. default:
  1680. __stmtMayGet.delete(this);
  1681. sqlite3.config.warn("sqlite3_step() rc=",rc,
  1682. capi.sqlite3_js_rc_str(rc),
  1683. "SQL =", capi.sqlite3_sql(this.pointer));
  1684. DB.checkRc(this.db.pointer, rc);
  1685. }
  1686. },
  1687. /**
  1688. Functions exactly like step() except that...
  1689. 1) On success, it calls this.reset() and returns this object.
  1690. 2) On error, it throws and does not call reset().
  1691. This is intended to simplify constructs like:
  1692. ```
  1693. for(...) {
  1694. stmt.bind(...).stepReset();
  1695. }
  1696. ```
  1697. Note that the reset() call makes it illegal to call this.get()
  1698. after the step.
  1699. */
  1700. stepReset: function(){
  1701. this.step();
  1702. return this.reset();
  1703. },
  1704. /**
  1705. Functions like step() except that it calls finalize() on this
  1706. statement immediately after stepping, even if the step() call
  1707. throws.
  1708. On success, it returns true if the step indicated that a row of
  1709. data was available, else it returns a falsy value.
  1710. This is intended to simplify use cases such as:
  1711. ```
  1712. aDb.prepare("insert into foo(a) values(?)").bind(123).stepFinalize();
  1713. ```
  1714. */
  1715. stepFinalize: function(){
  1716. try{
  1717. const rc = this.step();
  1718. this.reset(/*for INSERT...RETURNING locking case*/);
  1719. return rc;
  1720. }finally{
  1721. try{this.finalize()}
  1722. catch(e){/*ignored*/}
  1723. }
  1724. },
  1725. /**
  1726. Fetches the value from the given 0-based column index of
  1727. the current data row, throwing if index is out of range.
  1728. Requires that step() has just returned a truthy value, else
  1729. an exception is thrown.
  1730. By default it will determine the data type of the result
  1731. automatically. If passed a second argument, it must be one
  1732. of the enumeration values for sqlite3 types, which are
  1733. defined as members of the sqlite3 module: SQLITE_INTEGER,
  1734. SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB. Any other value,
  1735. except for undefined, will trigger an exception. Passing
  1736. undefined is the same as not passing a value. It is legal
  1737. to, e.g., fetch an integer value as a string, in which case
  1738. sqlite3 will convert the value to a string.
  1739. If ndx is an array, this function behaves a differently: it
  1740. assigns the indexes of the array, from 0 to the number of
  1741. result columns, to the values of the corresponding column,
  1742. and returns that array.
  1743. If ndx is a plain object, this function behaves even
  1744. differentlier: it assigns the properties of the object to
  1745. the values of their corresponding result columns and returns
  1746. that object.
  1747. Blobs are returned as Uint8Array instances.
  1748. Potential TODO: add type ID SQLITE_JSON, which fetches the
  1749. result as a string and passes it (if it's not null) to
  1750. JSON.parse(), returning the result of that. Until then,
  1751. getJSON() can be used for that.
  1752. */
  1753. get: function(ndx,asType){
  1754. if(!__stmtMayGet.has(affirmStmtOpen(this))){
  1755. toss3("Stmt.step() has not (recently) returned true.");
  1756. }
  1757. if(Array.isArray(ndx)){
  1758. let i = 0;
  1759. const n = this.columnCount;
  1760. while(i<n){
  1761. ndx[i] = this.get(i++);
  1762. }
  1763. return ndx;
  1764. }else if(ndx && 'object'===typeof ndx){
  1765. let i = 0;
  1766. const n = this.columnCount;
  1767. while(i<n){
  1768. ndx[capi.sqlite3_column_name(this.pointer,i)] = this.get(i++);
  1769. }
  1770. return ndx;
  1771. }
  1772. affirmColIndex(this, ndx);
  1773. switch(undefined===asType
  1774. ? capi.sqlite3_column_type(this.pointer, ndx)
  1775. : asType){
  1776. case capi.SQLITE_NULL: return null;
  1777. case capi.SQLITE_INTEGER:{
  1778. if(wasm.bigIntEnabled){
  1779. const rc = capi.sqlite3_column_int64(this.pointer, ndx);
  1780. if(rc>=Number.MIN_SAFE_INTEGER && rc<=Number.MAX_SAFE_INTEGER){
  1781. /* Coerce "normal" number ranges to normal number values,
  1782. and only return BigInt-type values for numbers out of this
  1783. range. */
  1784. return Number(rc).valueOf();
  1785. }
  1786. return rc;
  1787. }else{
  1788. const rc = capi.sqlite3_column_double(this.pointer, ndx);
  1789. if(rc>Number.MAX_SAFE_INTEGER || rc<Number.MIN_SAFE_INTEGER){
  1790. /* Throwing here is arguable but, since we're explicitly
  1791. extracting an SQLITE_INTEGER-type value, it seems fair to throw
  1792. if the extracted number is out of range for that type.
  1793. This policy may be laxened to simply pass on the number and
  1794. hope for the best, as the C API would do. */
  1795. toss3("Integer is out of range for JS integer range: "+rc);
  1796. }
  1797. //sqlite3.config.log("get integer rc=",rc,isInt32(rc));
  1798. return util.isInt32(rc) ? (rc | 0) : rc;
  1799. }
  1800. }
  1801. case capi.SQLITE_FLOAT:
  1802. return capi.sqlite3_column_double(this.pointer, ndx);
  1803. case capi.SQLITE_TEXT:
  1804. return capi.sqlite3_column_text(this.pointer, ndx);
  1805. case capi.SQLITE_BLOB: {
  1806. const n = capi.sqlite3_column_bytes(this.pointer, ndx),
  1807. ptr = capi.sqlite3_column_blob(this.pointer, ndx),
  1808. rc = new Uint8Array(n);
  1809. //heap = n ? wasm.heap8() : false;
  1810. if(n) rc.set(wasm.heap8u().slice(ptr, ptr+n), 0);
  1811. //for(let i = 0; i < n; ++i) rc[i] = heap[ptr + i];
  1812. if(n && this.db._blobXfer instanceof Array){
  1813. /* This is an optimization soley for the
  1814. Worker-based API. These values will be
  1815. transfered to the main thread directly
  1816. instead of being copied. */
  1817. this.db._blobXfer.push(rc.buffer);
  1818. }
  1819. return rc;
  1820. }
  1821. default: toss3("Don't know how to translate",
  1822. "type of result column #"+ndx+".");
  1823. }
  1824. toss3("Not reached.");
  1825. },
  1826. /** Equivalent to get(ndx) but coerces the result to an
  1827. integer. */
  1828. getInt: function(ndx){return this.get(ndx,capi.SQLITE_INTEGER)},
  1829. /** Equivalent to get(ndx) but coerces the result to a
  1830. float. */
  1831. getFloat: function(ndx){return this.get(ndx,capi.SQLITE_FLOAT)},
  1832. /** Equivalent to get(ndx) but coerces the result to a
  1833. string. */
  1834. getString: function(ndx){return this.get(ndx,capi.SQLITE_TEXT)},
  1835. /** Equivalent to get(ndx) but coerces the result to a
  1836. Uint8Array. */
  1837. getBlob: function(ndx){return this.get(ndx,capi.SQLITE_BLOB)},
  1838. /**
  1839. A convenience wrapper around get() which fetches the value
  1840. as a string and then, if it is not null, passes it to
  1841. JSON.parse(), returning that result. Throws if parsing
  1842. fails. If the result is null, null is returned. An empty
  1843. string, on the other hand, will trigger an exception.
  1844. */
  1845. getJSON: function(ndx){
  1846. const s = this.get(ndx, capi.SQLITE_STRING);
  1847. return null===s ? s : JSON.parse(s);
  1848. },
  1849. // Design note: the only reason most of these getters have a 'get'
  1850. // prefix is for consistency with getVALUE_TYPE(). The latter
  1851. // arguably really need that prefix for API readability and the
  1852. // rest arguably don't, but consistency is a powerful thing.
  1853. /**
  1854. Returns the result column name of the given index, or
  1855. throws if index is out of bounds or this statement has been
  1856. finalized. This can be used without having run step()
  1857. first.
  1858. */
  1859. getColumnName: function(ndx){
  1860. return capi.sqlite3_column_name(
  1861. affirmColIndex(affirmStmtOpen(this),ndx).pointer, ndx
  1862. );
  1863. },
  1864. /**
  1865. If this statement potentially has result columns, this function
  1866. returns an array of all such names. If passed an array, it is
  1867. used as the target and all names are appended to it. Returns
  1868. the target array. Throws if this statement cannot have result
  1869. columns. This object's columnCount property holds the number of
  1870. columns.
  1871. */
  1872. getColumnNames: function(tgt=[]){
  1873. affirmColIndex(affirmStmtOpen(this),0);
  1874. const n = this.columnCount;
  1875. for(let i = 0; i < n; ++i){
  1876. tgt.push(capi.sqlite3_column_name(this.pointer, i));
  1877. }
  1878. return tgt;
  1879. },
  1880. /**
  1881. If this statement has named bindable parameters and the
  1882. given name matches one, its 1-based bind index is
  1883. returned. If no match is found, 0 is returned. If it has no
  1884. bindable parameters, the undefined value is returned.
  1885. */
  1886. getParamIndex: function(name){
  1887. return (affirmStmtOpen(this).parameterCount
  1888. ? capi.sqlite3_bind_parameter_index(this.pointer, name)
  1889. : undefined);
  1890. },
  1891. /**
  1892. If this statement has named bindable parameters and the given
  1893. index refers to one, its name is returned, else null is
  1894. returned. If this statement has no bound parameters, undefined
  1895. is returned.
  1896. Added in 3.47.
  1897. */
  1898. getParamName: function(ndx){
  1899. return (affirmStmtOpen(this).parameterCount
  1900. ? capi.sqlite3_bind_parameter_name(this.pointer, ndx)
  1901. : undefined);
  1902. },
  1903. /**
  1904. Behaves like sqlite3_stmt_busy() but throws if this statement
  1905. is closed and returns a value of type boolean instead of integer.
  1906. Added in 3.47.
  1907. */
  1908. isBusy: function(){
  1909. return 0!==capi.sqlite3_stmt_busy(affirmStmtOpen(this));
  1910. },
  1911. /**
  1912. Behaves like sqlite3_stmt_readonly() but throws if this statement
  1913. is closed and returns a value of type boolean instead of integer.
  1914. Added in 3.47.
  1915. */
  1916. isReadOnly: function(){
  1917. return 0!==capi.sqlite3_stmt_readonly(affirmStmtOpen(this));
  1918. }
  1919. }/*Stmt.prototype*/;
  1920. {/* Add the `pointer` property to DB and Stmt. */
  1921. const prop = {
  1922. enumerable: true,
  1923. get: function(){return __ptrMap.get(this)},
  1924. set: ()=>toss3("The pointer property is read-only.")
  1925. }
  1926. Object.defineProperty(Stmt.prototype, 'pointer', prop);
  1927. Object.defineProperty(DB.prototype, 'pointer', prop);
  1928. }
  1929. /**
  1930. Stmt.columnCount is an interceptor for sqlite3_column_count().
  1931. This requires an unfortunate performance hit compared to caching
  1932. columnCount when the Stmt is created/prepared (as was done in
  1933. SQLite <=3.42.0), but is necessary in order to handle certain
  1934. corner cases, as described in
  1935. https://sqlite.org/forum/forumpost/7774b773937cbe0a.
  1936. */
  1937. Object.defineProperty(Stmt.prototype, 'columnCount', {
  1938. enumerable: false,
  1939. get: function(){return capi.sqlite3_column_count(this.pointer)},
  1940. set: ()=>toss3("The columnCount property is read-only.")
  1941. });
  1942. /** The OO API's public namespace. */
  1943. sqlite3.oo1 = {
  1944. DB,
  1945. Stmt
  1946. }/*oo1 object*/;
  1947. if(util.isUIThread()){
  1948. /**
  1949. Functionally equivalent to DB(storageName,'c','kvvfs') except
  1950. that it throws if the given storage name is not one of 'local'
  1951. or 'session'.
  1952. As of version 3.46, the argument may optionally be an options
  1953. object in the form:
  1954. {
  1955. filename: 'session'|'local',
  1956. ... etc. (all options supported by the DB ctor)
  1957. }
  1958. noting that the 'vfs' option supported by main DB
  1959. constructor is ignored here: the vfs is always 'kvvfs'.
  1960. */
  1961. sqlite3.oo1.JsStorageDb = function(storageName='session'){
  1962. const opt = dbCtorHelper.normalizeArgs(...arguments);
  1963. storageName = opt.filename;
  1964. if('session'!==storageName && 'local'!==storageName){
  1965. toss3("JsStorageDb db name must be one of 'session' or 'local'.");
  1966. }
  1967. opt.vfs = 'kvvfs';
  1968. dbCtorHelper.call(this, opt);
  1969. };
  1970. const jdb = sqlite3.oo1.JsStorageDb;
  1971. jdb.prototype = Object.create(DB.prototype);
  1972. /** Equivalent to sqlite3_js_kvvfs_clear(). */
  1973. jdb.clearStorage = capi.sqlite3_js_kvvfs_clear;
  1974. /**
  1975. Clears this database instance's storage or throws if this
  1976. instance has been closed. Returns the number of
  1977. database blocks which were cleaned up.
  1978. */
  1979. jdb.prototype.clearStorage = function(){
  1980. return jdb.clearStorage(affirmDbOpen(this).filename);
  1981. };
  1982. /** Equivalent to sqlite3_js_kvvfs_size(). */
  1983. jdb.storageSize = capi.sqlite3_js_kvvfs_size;
  1984. /**
  1985. Returns the _approximate_ number of bytes this database takes
  1986. up in its storage or throws if this instance has been closed.
  1987. */
  1988. jdb.prototype.storageSize = function(){
  1989. return jdb.storageSize(affirmDbOpen(this).filename);
  1990. };
  1991. }/*main-window-only bits*/
  1992. });
  1993. //#else
  1994. /* Built with the omit-oo1 flag. */
  1995. //#endif ifnot omit-oo1