-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathWASQLiteDBAdapter.ts
300 lines (268 loc) · 9.44 KB
/
WASQLiteDBAdapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import {
type DBAdapter,
type DBAdapterListener,
type DBGetUtils,
type DBLockOptions,
type LockContext,
type PowerSyncOpenFactoryOptions,
type QueryResult,
type Transaction,
BaseObserver
} from '@powersync/common';
import * as Comlink from 'comlink';
import Logger, { type ILogger } from 'js-logger';
import type { DBFunctionsInterface, OpenDB } from '../../../shared/types';
import { _openDB } from '../../../shared/open-db';
import { getWorkerDatabaseOpener } from '../../../worker/db/open-worker-database';
import { WebSQLFlags } from '../web-sql-flags';
/**
* These flags are the same as {@link WebSQLFlags}.
* This export is maintained only for API consistency
*/
export type WASQLiteFlags = WebSQLFlags;
export interface WASQLiteDBAdapterOptions extends Omit<PowerSyncOpenFactoryOptions, 'schema'> {
flags?: WASQLiteFlags;
/**
* Use an existing port to an initialized worker.
* A worker will be initialized if none is provided
*/
workerPort?: MessagePort;
}
/**
* Adapter for WA-SQLite SQLite connections.
*/
export class WASQLiteDBAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {
private initialized: Promise<void>;
private logger: ILogger;
private dbGetHelpers: DBGetUtils | null;
private methods: DBFunctionsInterface | null;
private debugMode: boolean;
constructor(protected options: WASQLiteDBAdapterOptions) {
super();
this.logger = Logger.get('WASQLite');
this.dbGetHelpers = null;
this.methods = null;
this.debugMode = options.debugMode ?? false;
if (this.debugMode) {
const originalExecute = this._execute.bind(this);
this._execute = async (sql, bindings) => {
const start = performance.now();
try {
const r = await originalExecute(sql, bindings);
const end = performance.now();
performance.measure(`[SQL] ${sql}`, { start, end });
const duration = end - start;
if (duration >= 10) {
const rw = await originalExecute(`EXPLAIN QUERY PLAN ${sql}`, bindings);
const explain = rw.rows?._array ?? [];
const sqlMessage = sql.trim();
const newline = sqlMessage.indexOf('\n');
const firstLine = newline >= 0 ? sqlMessage.substring(0, newline) + '...' : sqlMessage;
console.groupCollapsed(
'%c[SQL] %c%s %c%s',
'color: grey; font-weight: normal',
durationStyle(duration),
`[${duration.toFixed(1)}ms]`,
'color: grey; font-weight: normal',
firstLine
);
if (newline >= 0) {
console.log('%c%s', 'color: grey', sqlMessage);
}
if (explain.length > 0) {
const emessage = explain.map((r) => ` ${r.detail}`).join('\n');
console.log('%c%s\n%c%s', 'color: blue', '[EXPLAIN QUERY PLAN]', 'color: grey', emessage);
}
console.groupEnd();
}
return r;
} catch (e: any) {
performance.measure(`[SQL] [ERROR: ${e.message}] ${sql}`, { start });
throw e;
}
};
}
this.initialized = this.init();
this.dbGetHelpers = this.generateDBHelpers({
execute: (query, params) => this.acquireLock(() => this._execute(query, params))
});
}
get name() {
return this.options.dbFilename;
}
protected get flags(): WASQLiteFlags {
return this.options.flags ?? {};
}
getWorker() {}
protected async init() {
const { enableMultiTabs, useWebWorker } = this.flags;
if (!enableMultiTabs) {
this.logger.warn('Multiple tabs are not enabled in this browser');
}
if (useWebWorker) {
const dbOpener = this.options.workerPort
? Comlink.wrap<OpenDB>(this.options.workerPort)
: getWorkerDatabaseOpener(this.options.dbFilename, enableMultiTabs);
this.methods = await dbOpener(this.options.dbFilename);
this.methods.registerOnTableChange(
Comlink.proxy((opType: number, tableName: string, rowId: number) => {
this.iterateListeners((cb) => cb.tablesUpdated?.({ opType, table: tableName, rowId }));
})
);
return;
}
this.methods = await _openDB(this.options.dbFilename, { useWebWorker: false });
this.methods.registerOnTableChange((opType: number, tableName: string, rowId: number) => {
this.iterateListeners((cb) => cb.tablesUpdated?.({ opType, table: tableName, rowId }));
});
}
async execute(query: string, params?: any[] | undefined): Promise<QueryResult> {
return this.writeLock((ctx) => ctx.execute(query, params));
}
async executeBatch(query: string, params?: any[][]): Promise<QueryResult> {
return this.writeLock((ctx) => this._executeBatch(query, params));
}
/**
* Wraps the worker execute function, awaiting for it to be available
*/
private _execute = async (sql: string, bindings?: any[]): Promise<QueryResult> => {
await this.initialized;
const result = await this.methods!.execute!(sql, bindings);
return {
...result,
rows: {
...result.rows,
item: (idx: number) => result.rows._array[idx]
}
};
};
/**
* Wraps the worker executeBatch function, awaiting for it to be available
*/
private _executeBatch = async (query: string, params?: any[]): Promise<QueryResult> => {
await this.initialized;
const result = await this.methods!.executeBatch!(query, params);
return {
...result,
rows: undefined
};
};
/**
* Attempts to close the connection.
* Shared workers might not actually close the connection if other
* tabs are still using it.
*/
close() {
this.methods?.close?.();
}
async getAll<T>(sql: string, parameters?: any[] | undefined): Promise<T[]> {
await this.initialized;
return this.dbGetHelpers!.getAll(sql, parameters);
}
async getOptional<T>(sql: string, parameters?: any[] | undefined): Promise<T | null> {
await this.initialized;
return this.dbGetHelpers!.getOptional(sql, parameters);
}
async get<T>(sql: string, parameters?: any[] | undefined): Promise<T> {
await this.initialized;
return this.dbGetHelpers!.get(sql, parameters);
}
async readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
await this.initialized;
return this.acquireLock(async () => fn(this.generateDBHelpers({ execute: this._execute })));
}
async writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
await this.initialized;
return this.acquireLock(async () => fn(this.generateDBHelpers({ execute: this._execute })));
}
protected acquireLock(callback: () => Promise<any>): Promise<any> {
return navigator.locks.request(`db-lock-${this.options.dbFilename}`, callback);
}
async readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
return this.readLock(this.wrapTransaction(fn));
}
writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
return this.writeLock(this.wrapTransaction(fn));
}
/**
* Wraps a lock context into a transaction context
*/
private wrapTransaction<T>(cb: (tx: Transaction) => Promise<T>) {
return async (tx: LockContext): Promise<T> => {
await this._execute('BEGIN TRANSACTION');
let finalized = false;
const commit = async (): Promise<QueryResult> => {
if (finalized) {
return { rowsAffected: 0 };
}
finalized = true;
return this._execute('COMMIT');
};
const rollback = () => {
finalized = true;
return this._execute('ROLLBACK');
};
try {
const result = await cb({
...tx,
commit,
rollback
});
if (!finalized) {
await commit();
}
return result;
} catch (ex) {
this.logger.debug('Caught ex in transaction', ex);
try {
await rollback();
} catch (ex2) {
// In rare cases, a rollback may fail.
// Safe to ignore.
}
throw ex;
}
};
}
private generateDBHelpers<T extends { execute: (sql: string, params?: any[]) => Promise<QueryResult> }>(
tx: T
): T & DBGetUtils {
return {
...tx,
/**
* Execute a read-only query and return results
*/
async getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
const res = await tx.execute(sql, parameters);
return res.rows?._array ?? [];
},
/**
* Execute a read-only query and return the first result, or null if the ResultSet is empty.
*/
async getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
const res = await tx.execute(sql, parameters);
return res.rows?.item(0) ?? null;
},
/**
* Execute a read-only query and return the first result, error if the ResultSet is empty.
*/
async get<T>(sql: string, parameters?: any[]): Promise<T> {
const res = await tx.execute(sql, parameters);
const first = res.rows?.item(0);
if (!first) {
throw new Error('Result set is empty');
}
return first;
}
};
}
}
function durationStyle(duration: number) {
if (duration < 30) {
return 'color: grey; font-weight: normal';
} else if (duration < 300) {
return 'color: blue; font-weight: normal';
} else {
return 'color: red; font-weight: normal';
}
}