|
| 1 | +import { |
| 2 | + sqlite3Worker1Promiser, |
| 3 | + type SQLiteWorker, |
| 4 | +} from '@sqlite.org/sqlite-wasm'; |
| 5 | + |
| 6 | +import { |
| 7 | + type DBAdapter, |
| 8 | + type PgPrimitive, |
| 9 | + type ExecuteOptions, |
| 10 | + Deferred, |
| 11 | +} from '@cardstack/runtime-common'; |
| 12 | + |
| 13 | +export default class SQLiteAdapter implements DBAdapter { |
| 14 | + private _sqlite: typeof SQLiteWorker | undefined; |
| 15 | + private _dbId: string | undefined; |
| 16 | + |
| 17 | + constructor(private schemaSQL?: string) {} |
| 18 | + |
| 19 | + async startClient() { |
| 20 | + let ready = new Deferred<typeof SQLiteWorker>(); |
| 21 | + const promisedWorker = sqlite3Worker1Promiser({ |
| 22 | + onready: () => ready.fulfill(promisedWorker), |
| 23 | + }); |
| 24 | + this._sqlite = await ready.promise; |
| 25 | + |
| 26 | + let response = await this.sqlite('open', { |
| 27 | + // It is possible to write to the local |
| 28 | + // filesystem via Origin Private Filesystem, but it requires _very_ |
| 29 | + // restrictive response headers that would cause our host app to break |
| 30 | + // "Cross-Origin-Embedder-Policy: require-corp" |
| 31 | + // "Cross-Origin-Opener-Policy: same-origin" |
| 32 | + // https://webkit.org/blog/12257/the-file-system-access-api-with-origin-private-file-system/ |
| 33 | + |
| 34 | + // Otherwise, local storage and session storage are off limits to the |
| 35 | + // worker (they are available in the synchronous interface), so only |
| 36 | + // ephemeral memory storage is available |
| 37 | + filename: ':memory:', |
| 38 | + }); |
| 39 | + const { dbId } = response; |
| 40 | + this._dbId = dbId; |
| 41 | + |
| 42 | + if (this.schemaSQL) { |
| 43 | + try { |
| 44 | + await this.sqlite('exec', { |
| 45 | + dbId: this.dbId, |
| 46 | + sql: this.schemaSQL, |
| 47 | + }); |
| 48 | + } catch (e: any) { |
| 49 | + console.error( |
| 50 | + `Error executing SQL: ${e.result.message}\n${this.schemaSQL}`, |
| 51 | + e, |
| 52 | + ); |
| 53 | + throw e; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + async execute(sql: string, opts?: ExecuteOptions) { |
| 59 | + return await this.query(sql, opts); |
| 60 | + } |
| 61 | + |
| 62 | + async close() { |
| 63 | + await this.sqlite('close', { dbId: this.dbId }); |
| 64 | + } |
| 65 | + |
| 66 | + private get sqlite() { |
| 67 | + if (!this._sqlite) { |
| 68 | + throw new Error( |
| 69 | + `could not get sqlite worker--has createClient() been run?`, |
| 70 | + ); |
| 71 | + } |
| 72 | + return this._sqlite; |
| 73 | + } |
| 74 | + |
| 75 | + private get dbId() { |
| 76 | + if (!this._dbId) { |
| 77 | + throw new Error( |
| 78 | + `could not obtain db identifier--has createClient() been run?`, |
| 79 | + ); |
| 80 | + } |
| 81 | + return this._dbId; |
| 82 | + } |
| 83 | + |
| 84 | + private async query(sql: string, opts?: ExecuteOptions) { |
| 85 | + let results: Record<string, PgPrimitive>[] = []; |
| 86 | + try { |
| 87 | + await this.sqlite('exec', { |
| 88 | + dbId: this.dbId, |
| 89 | + sql, |
| 90 | + bind: opts?.bind, |
| 91 | + // Nested execs are not possible with this async interface--we can't call |
| 92 | + // into the exec in this callback due to the way we communicate to the |
| 93 | + // worker thread via postMessage. if we need nesting do it all in the SQL |
| 94 | + callback: ({ columnNames, row }) => { |
| 95 | + let rowObject: Record<string, any> = {}; |
| 96 | + // row === undefined indicates that the end of the result set has been reached |
| 97 | + if (row) { |
| 98 | + for (let [index, col] of columnNames.entries()) { |
| 99 | + let coerceAs = opts?.coerceTypes?.[col]; |
| 100 | + if (coerceAs) { |
| 101 | + switch (coerceAs) { |
| 102 | + case 'JSON': { |
| 103 | + rowObject[col] = JSON.parse(row[index]); |
| 104 | + break; |
| 105 | + } |
| 106 | + case 'BOOLEAN': { |
| 107 | + let value = row[index]; |
| 108 | + rowObject[col] = |
| 109 | + // respect DB NULL values |
| 110 | + value === null ? value : Boolean(row[index]); |
| 111 | + break; |
| 112 | + } |
| 113 | + default: |
| 114 | + assertNever(coerceAs); |
| 115 | + } |
| 116 | + } else { |
| 117 | + rowObject[col] = row[index]; |
| 118 | + } |
| 119 | + } |
| 120 | + results.push(rowObject); |
| 121 | + } |
| 122 | + }, |
| 123 | + }); |
| 124 | + } catch (e: any) { |
| 125 | + console.error( |
| 126 | + `Error executing SQL ${e.result.message}:\n${sql}${ |
| 127 | + opts?.bind ? ' with bindings: ' + JSON.stringify(opts?.bind) : '' |
| 128 | + }`, |
| 129 | + e, |
| 130 | + ); |
| 131 | + throw e; |
| 132 | + } |
| 133 | + |
| 134 | + return results; |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +function assertNever(value: never) { |
| 139 | + return new Error(`should never happen ${value}`); |
| 140 | +} |
0 commit comments