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

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