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

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