|
| 1 | +export default async function sqlite(require) { |
| 2 | + const sql = await require("[email protected]/dist/sql-wasm.js"); |
| 3 | + return sql({locateFile: file => `https://cdn.jsdelivr.net/npm/[email protected]/dist/${file}`}); |
| 4 | +} |
| 5 | + |
| 6 | +export class SQLiteDatabaseClient { |
| 7 | + constructor(db) { |
| 8 | + Object.defineProperties(this, { |
| 9 | + _db: {value: db} |
| 10 | + }); |
| 11 | + } |
| 12 | + async query(query, params) { |
| 13 | + return await exec(this._db, query, params); |
| 14 | + } |
| 15 | + async queryRow(query, params) { |
| 16 | + return (await this.query(query, params))[0] || null; |
| 17 | + } |
| 18 | + async explain(query, params) { |
| 19 | + const rows = await this.query(`EXPLAIN QUERY PLAN ${query}`, params); |
| 20 | + return element("pre", {className: "observablehq--inspect"}, [ |
| 21 | + text(rows.map(row => row.detail).join("\n")) |
| 22 | + ]); |
| 23 | + } |
| 24 | + async describe(object) { |
| 25 | + const rows = await (object === undefined |
| 26 | + ? this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`) |
| 27 | + : this.query(`SELECT * FROM pragma_table_info(?)`, [object])); |
| 28 | + if (!rows.length) throw new Error("Not found"); |
| 29 | + const {columns} = rows; |
| 30 | + return element("table", {value: rows}, [ |
| 31 | + element("thead", [element("tr", columns.map(c => element("th", [text(c)])))]), |
| 32 | + element("tbody", rows.map(r => element("tr", columns.map(c => element("td", [text(r[c])]))))) |
| 33 | + ]); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +async function exec(db, query, params) { |
| 38 | + const [result] = await db.exec(query, params); |
| 39 | + if (!result) return []; |
| 40 | + const {columns, values} = result; |
| 41 | + const rows = values.map(row => Object.fromEntries(row.map((value, i) => [columns[i], value]))); |
| 42 | + rows.columns = columns; |
| 43 | + return rows; |
| 44 | +} |
| 45 | + |
| 46 | +function element(name, props, children) { |
| 47 | + if (arguments.length === 2) children = props, props = undefined; |
| 48 | + const element = document.createElement(name); |
| 49 | + if (props !== undefined) for (const p in props) element[p] = props[p]; |
| 50 | + if (children !== undefined) for (const c of children) element.appendChild(c); |
| 51 | + return element; |
| 52 | +} |
| 53 | + |
| 54 | +function text(value) { |
| 55 | + return document.createTextNode(value); |
| 56 | +} |
0 commit comments