-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathSQLJSAdapter.ts
More file actions
202 lines (171 loc) · 5.58 KB
/
Copy pathSQLJSAdapter.ts
File metadata and controls
202 lines (171 loc) · 5.58 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
import {
BatchedUpdateNotification,
createConsoleLogger,
DBAdapter,
DBLockOptions,
LockContext,
LogLevels,
PowerSyncLogger,
QueryResult,
SQLOpenFactory,
SQLOpenOptions,
SqliteValue,
RawQueryResult,
queryResultWithoutRows
} from '@powersync/common';
import { Mutex, timeoutSignal, ControlledExecutor } from '@powersync/shared-internals';
// 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?: PowerSyncLogger;
}
export interface ResolvedSQLJSOpenOptions extends SQLJSOpenOptions {
persister?: SQLJSPersister;
logger: PowerSyncLogger;
}
export class SQLJSOpenFactory implements SQLOpenFactory {
constructor(protected options: SQLJSOpenOptions) {}
openDB(): DBAdapter {
return new SQLJSDBAdapter(this.options);
}
}
export class SQLJSDBAdapter extends DBAdapter {
protected initPromise: Promise<SQLJs.Database>;
protected _db: SQLJs.Database | null;
protected dbP: number | null;
protected writeScheduler: ControlledExecutor<SQLJs.Database>;
protected options: ResolvedSQLJSOpenOptions;
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.mutex = new Mutex();
this.dbP = null;
this.writeScheduler = new ControlledExecutor(async (db: SQLJs.Database) => {
const persister = this.options.persister;
if (!persister) {
return;
}
const blob = db.export();
// Calling export() closes and re-opens the database, so we need to re-install update hooks.
this.setup(db);
await persister.writeFile(blob);
});
}
protected resolveOptions(options: SQLJSOpenOptions): ResolvedSQLJSOpenOptions {
const logger = options.logger ?? createConsoleLogger({ prefix: 'SQLJSDBAdapter' });
return {
...options,
logger
};
}
protected async init(): Promise<SQLJs.Database> {
const SQL = await SQLJs({
locateFile: (filename: any) => `../dist/${filename}`,
print: (text) => {
this.options.logger.log({ level: LogLevels.info, message: text });
},
printErr: (text) => {
this.options.logger.log({ level: LogLevels.error, message: `[stderr]: ${text}` });
}
});
const existing = await this.options.persister?.readFile();
const db = new SQL.Database(existing);
this.dbP = (db as any)['db'] as number;
this._db = db;
this.setup(db);
return db;
}
private setup(db: SQLJs.Database) {
db.exec("SELECT powersync_update_hooks('install')");
}
async close() {
const db = await this.getDB();
db.close();
}
/**
* 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);
}
writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T> {
return this.mutex.runExclusive(async () => {
const db = await this.getDB();
const context = new SqlJsLockContext(db);
const result = await fn(context);
const { rawRows: rawUpdates } = await context.executeRaw("SELECT powersync_update_hooks('get')");
const updatedTables = JSON.parse(rawUpdates[0][0] as string);
if (updatedTables.length) {
const notification: BatchedUpdateNotification = {
tables: updatedTables
};
this.iterateListeners((l) => l.tablesUpdated?.(notification));
}
// No point to schedule a write if there's no persister.
if (this.options.persister) {
this.writeScheduler.schedule(db);
}
return result;
}, timeoutSignal(options?.timeoutMs));
}
async refreshSchema(): Promise<void> {
await this.writeLock((ctx) => ctx.get("PRAGMA table_info('sqlite_master')"));
}
}
class SqlJsLockContext extends LockContext {
constructor(readonly db: SQLJs.Database) {
super();
}
async executeRaw(query: string, params?: any[]): Promise<RawQueryResult> {
const db = this.db;
const statement = db.prepare(query);
const rawResults: SqliteValue[][] = [];
try {
if (params) {
statement.bind(params);
}
while (statement.step()) {
rawResults.push(statement.get());
}
return {
rowsAffected: db.getRowsModified(),
// `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(),
columnNames: statement.getColumnNames(),
rawRows: rawResults
};
} finally {
statement.free();
}
}
async executeBatch(query: string, params: any[][] = []): Promise<QueryResult<never>> {
let totalRowsAffected = 0;
const db = this.db;
const stmt = db.prepare(query);
try {
for (const paramSet of params) {
stmt.run(paramSet);
totalRowsAffected += db.getRowsModified();
}
return queryResultWithoutRows({
rowsAffected: totalRowsAffected
});
} finally {
stmt.free();
}
}
}