Snapshot of upstream SQLite 3.46.1
[sqlcipher.git] / ext / wasm / test-opfs-vfs.js
blob96d0eacfc9c261373890645c223aad82a6850de1
1 /*
2 2022-09-17
4 The author disclaims copyright to this source code. In place of a
5 legal notice, here is a blessing:
7 * May you do good and not evil.
8 * May you find forgiveness for yourself and forgive others.
9 * May you share freely, never taking more than you give.
11 ***********************************************************************
13 A testing ground for the OPFS VFS.
15 'use strict';
16 const tryOpfsVfs = async function(sqlite3){
17 const toss = function(...args){throw new Error(args.join(' '))};
18 const logPrefix = "OPFS tester:";
19 const log = (...args)=>console.log(logPrefix,...args);
20 const warn = (...args)=>console.warn(logPrefix,...args);
21 const error = (...args)=>console.error(logPrefix,...args);
22 const opfs = sqlite3.opfs;
23 log("tryOpfsVfs()");
24 if(!sqlite3.opfs){
25 const e = new Error("OPFS is not available.");
26 error(e);
27 throw e;
29 const capi = sqlite3.capi;
30 const pVfs = capi.sqlite3_vfs_find("opfs") || toss("Missing 'opfs' VFS.");
31 const oVfs = new capi.sqlite3_vfs(pVfs);
32 log("OPFS VFS:",pVfs, oVfs);
34 const wait = async (ms)=>{
35 return new Promise((resolve)=>setTimeout(resolve, ms));
38 const urlArgs = new URL(self.location.href).searchParams;
39 const dbFile = "my-persistent.db";
40 if(urlArgs.has('delete')) sqlite3.opfs.unlink(dbFile);
42 const db = new sqlite3.oo1.OpfsDb(dbFile,'ct');
43 log("db file:",db.filename);
44 try{
45 if(opfs.entryExists(dbFile)){
46 let n = db.selectValue("select count(*) from sqlite_schema");
47 log("Persistent data found. sqlite_schema entry count =",n);
49 db.transaction((db)=>{
50 db.exec({
51 sql:[
52 "create table if not exists t(a);",
53 "insert into t(a) values(?),(?),(?);",
55 bind: [performance.now() | 0,
56 (performance.now() |0) / 2,
57 (performance.now() |0) / 4]
58 });
59 });
60 log("count(*) from t =",db.selectValue("select count(*) from t"));
62 // Some sanity checks of the opfs utility functions...
63 const testDir = '/sqlite3-opfs-'+opfs.randomFilename(12);
64 const aDir = testDir+'/test/dir';
65 await opfs.mkdir(aDir) || toss("mkdir failed");
66 await opfs.mkdir(aDir) || toss("mkdir must pass if the dir exists");
67 await opfs.unlink(testDir+'/test') && toss("delete 1 should have failed (dir not empty)");
68 //await opfs.entryExists(testDir)
69 await opfs.unlink(testDir+'/test/dir') || toss("delete 2 failed");
70 await opfs.unlink(testDir+'/test/dir') && toss("delete 2b should have failed (dir already deleted)");
71 await opfs.unlink(testDir, true) || toss("delete 3 failed");
72 await opfs.entryExists(testDir) && toss("entryExists(",testDir,") should have failed");
73 }finally{
74 db.close();
77 log("Done!");
78 }/*tryOpfsVfs()*/;
80 importScripts('jswasm/sqlite3.js');
81 self.sqlite3InitModule()
82 .then((sqlite3)=>tryOpfsVfs(sqlite3))
83 .catch((e)=>{
84 console.error("Error initializing module:",e);
85 });