-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathSQLJSAdapter.ts
More file actions
336 lines (294 loc) · 9.37 KB
/
SQLJSAdapter.ts
File metadata and controls
336 lines (294 loc) · 9.37 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import {
BaseListener,
BaseObserver,
BatchedUpdateNotification,
ControlledExecutor,
createLogger,
DBAdapter,
DBAdapterListener,
DBLockOptions,
ILogger,
LockContext,
QueryResult,
SQLOpenFactory,
SQLOpenOptions,
Transaction
} from '@powersync/common';
import { Mutex } from 'async-mutex';
// This uses a pure JS version which avoids the need for WebAssembly, which is not supported in React Native.
import SQLJs from '@powersync/sql-js/dist/sql-asm.js';
export interface SQLJSPersister {
readFile: () => Promise<ArrayLike<number> | Buffer | null>;
writeFile: (data: ArrayLike<number> | Buffer) => Promise<void>;
}
export interface SQLJSOpenOptions extends SQLOpenOptions {
persister?: SQLJSPersister;
logger?: ILogger;
}
export interface ResolvedSQLJSOpenOptions extends SQLJSOpenOptions {
persister?: SQLJSPersister;
logger: ILogger;
}
export class SQLJSOpenFactory implements SQLOpenFactory {
constructor(protected options: SQLJSOpenOptions) {}
openDB(): DBAdapter {
return new SQLJSDBAdapter(this.options);
}
}
(globalThis as any).onSqliteUpdate = (
dbP: number,
operation: string,
database: string,
table: string,
rowId: number
) => {
SQLJSDBAdapter.sharedObserver.iterateListeners((l) => l.tablesUpdated?.(dbP, operation, database, table, rowId));
};
interface TableObserverListener extends BaseListener {
tablesUpdated?: (dpP: number, operation: string, database: string, table: string, rowId: number) => void;
}
class TableObserver extends BaseObserver<TableObserverListener> {}
export class SQLJSDBAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {
protected initPromise: Promise<SQLJs.Database>;
protected _db: SQLJs.Database | null;
protected tableUpdateCache: Set<string>;
protected dbP: number | null;
protected writeScheduler: ControlledExecutor<SQLJs.Database>;
protected options: ResolvedSQLJSOpenOptions;
static sharedObserver = new TableObserver();
protected disposeListener: () => void;
protected mutex: Mutex;
protected getDB(): Promise<SQLJs.Database> {
return this.initPromise;
}
get name() {
return this.options.dbFilename;
}
constructor(options: SQLJSOpenOptions) {
super();
this.options = this.resolveOptions(options);
this.initPromise = this.init();
this._db = null;
this.tableUpdateCache = new Set<string>();
this.mutex = new Mutex();
this.dbP = null;
this.disposeListener = SQLJSDBAdapter.sharedObserver.registerListener({
tablesUpdated: (dbP: number, operation: string, database: string, table: string, rowId: number) => {
if (this.dbP !== dbP) {
// Ignore updates from other databases.
return;
}
this.tableUpdateCache.add(table);
}
});
this.writeScheduler = new ControlledExecutor(async (db: SQLJs.Database) => {
if (!this.options.persister) {
return;
}
await this.options.persister.writeFile(db.export());
});
}
protected resolveOptions(options: SQLJSOpenOptions): ResolvedSQLJSOpenOptions {
const logger = options.logger ?? createLogger('SQLJSDBAdapter');
return {
...options,
logger
};
}
protected async init(): Promise<SQLJs.Database> {
const SQL = await SQLJs({
locateFile: (filename: any) => `../dist/${filename}`,
print: (text) => {
this.options.logger.info(text);
},
printErr: (text) => {
this.options.logger.error('[stderr]', text);
}
});
const existing = await this.options.persister?.readFile();
const db = new SQL.Database(existing);
this.dbP = db['db'];
this._db = db;
return db;
}
async close() {
const db = await this.getDB();
this.disposeListener();
db.close();
}
protected generateLockContext(): LockContext {
const execute = async (query: string, params?: any[]): Promise<QueryResult> => {
const db = await this.getDB();
const statement = db.prepare(query);
const rawResults: any[][] = [];
let columnNames: string[] | null = null;
try {
if (params) {
statement.bind(params);
}
while (statement.step()) {
if (!columnNames) {
columnNames = statement.getColumnNames();
}
rawResults.push(statement.get());
}
const rows = rawResults.map((row) => {
return Object.fromEntries(row.map((value, index) => [columnNames![index], value]));
});
return {
// `lastInsertId` is not available in the original version of SQL.js or its types, but it's available in the fork we use.
insertId: (db as any).lastInsertId(),
rowsAffected: db.getRowsModified(),
rows: {
_array: rows,
length: rows.length,
item: (idx: number) => rows[idx]
}
};
} finally {
statement.free();
}
};
const getAll = async <T>(query: string, params?: any[]): Promise<T[]> => {
const result = await execute(query, params);
return result.rows?._array ?? ([] as T[]);
};
const getOptional = async <T>(query: string, params?: any[]): Promise<T | null> => {
const results = await getAll<T>(query, params);
return results.length > 0 ? results[0] : null;
};
const get = async <T>(query: string, params?: any[]): Promise<T> => {
const result = await getOptional<T>(query, params);
if (!result) {
throw new Error(`No results for query: ${query}`);
}
return result;
};
const executeRaw = async (query: string, params?: any[]): Promise<any[][]> => {
const db = await this.getDB();
const statement = db.prepare(query);
const rawResults: any[][] = [];
try {
if (params) {
statement.bind(params);
}
while (statement.step()) {
rawResults.push(statement.get());
}
return rawResults;
} finally {
statement.free();
}
};
return {
getAll,
getOptional,
get,
executeRaw,
execute
};
}
execute(query: string, params?: any[]): Promise<QueryResult> {
return this.writeLock((tx) => tx.execute(query, params));
}
executeRaw(query: string, params?: any[]): Promise<any[][]> {
return this.writeLock((tx) => tx.executeRaw(query, params));
}
async executeBatch(query: string, params: any[][] = []): Promise<QueryResult> {
let totalRowsAffected = 0;
const db = await this.getDB();
const stmt = db.prepare(query);
try {
for (const paramSet of params) {
stmt.run(paramSet);
totalRowsAffected += db.getRowsModified();
}
return {
rowsAffected: totalRowsAffected
};
} finally {
stmt.free();
}
}
/**
* We're not using separate read/write locks here because we can't implement connection pools on top of SQL.js.
*/
readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {
return this.writeLock(fn, options);
}
readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {
return this.readLock(async (ctx) => {
return this.internalTransaction(ctx, fn);
});
}
writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {
return this.mutex.runExclusive(async () => {
const db = await this.getDB();
const result = await fn(this.generateLockContext());
// No point to schedule a write if there's no persister.
if (this.options.persister) {
this.writeScheduler.schedule(db);
}
const notification: BatchedUpdateNotification = {
rawUpdates: [],
tables: Array.from(this.tableUpdateCache),
groupedUpdates: {}
};
this.tableUpdateCache.clear();
this.iterateListeners((l) => l.tablesUpdated?.(notification));
return result;
});
}
writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T> {
return this.writeLock(async (ctx) => {
return this.internalTransaction(ctx, fn);
});
}
refreshSchema(): Promise<void> {
return this.get("PRAGMA table_info('sqlite_master')");
}
getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
return this.readLock((tx) => tx.getAll<T>(sql, parameters));
}
getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
return this.readLock((tx) => tx.getOptional<T>(sql, parameters));
}
get<T>(sql: string, parameters?: any[]): Promise<T> {
return this.readLock((tx) => tx.get<T>(sql, parameters));
}
protected async internalTransaction<T>(ctx: LockContext, fn: (tx: Transaction) => Promise<T>): Promise<T> {
let finalized = false;
const commit = async (): Promise<QueryResult> => {
if (finalized) {
return { rowsAffected: 0 };
}
finalized = true;
return ctx.execute('COMMIT');
};
const rollback = async (): Promise<QueryResult> => {
if (finalized) {
return { rowsAffected: 0 };
}
finalized = true;
return ctx.execute('ROLLBACK');
};
try {
await ctx.execute('BEGIN');
const result = await fn({
...ctx,
commit,
rollback
});
await commit();
return result;
} catch (ex) {
try {
await rollback();
} catch (ex2) {
// In rare cases, a rollback may fail.
// Safe to ignore.
}
throw ex;
}
}
}