Browser Persistence
Note: this guide is only relevant to browser environments. Persistence in all other environments has no special considerations.
Import the required packages and init the wasm:
return import('https://esm.sh/@vlcn.io/crsqlite-wasm@0.9.0').then(async (initWasm) => {
return self.sqlite = await initWasm.default(() => "https://esm.sh/@vlcn.io/crsqlite-wasm@0.9.0/dist/crsqlite.wasm");
});
Now create a database. To make it persisted all you need to do is pass in a filename. Omitting the filename runs the database in memory.
self.db = await sqlite.open("guide-persistence");
window.onbeforeunload = () => {
return db.close();
};
await db.exec(
`CREATE TABLE IF NOT EXISTS todo (id primary key, "text", completed)`
);
await db.exec("SELECT crsql_as_crr('todo')");
return 'created db & applied schema';
And finally, write then read some data to check it out:
const items = ['Milk', 'Bread', 'Peas', 'Carrots', 'Lentils', 'Cake', 'Squirrels'];
await db.exec(
`INSERT INTO todo (id, "text", completed) VALUES (
'${nanoid()}',
'Buy ${items[(Math.random() * items.length) | 0]}',
0
)`);
return await db.execO("SELECT * FROM todo");
To check that it did indeed persist, refresh this page a few times and see the number of todos grow!
You can also see a more detailed setup guide on ObservableHQ: https://observablehq.com/@tantaman/cr-sqlite-basic-setup