-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplicationSQLiteStorage.ts
More file actions
66 lines (64 loc) · 2.8 KB
/
Copy pathreplicationSQLiteStorage.ts
File metadata and controls
66 lines (64 loc) · 2.8 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
import { SQLiteDBConnection } from '@capacitor-community/sqlite';
import { ReplicationState, ReplicationStorage, SQLiteConnection } from './replication';
export class ReplicationSQLiteStorage implements ReplicationStorage {
constructor(private db: SQLiteDBConnection | SQLiteConnection) {}
async getDefinedColumns(collectionName: string) {
return (
(await this.db.query(`PRAGMA table_info("${collectionName}");`)).values?.map((column) => column.name) || []
);
}
async getReplicationPushState(collectionName: string): Promise<ReplicationState> {
const state = await this.db.query(
`SELECT pushCursor as cursor,pushOffset as offset from _replicationStates where id="${collectionName}"`,
);
if (state && state.values && state.values.length) {
const { cursor, offset } = state.values[0];
return { cursor, offset };
} else return { cursor: 0, offset: 0 };
}
async getReplicationPullState(collectionName: string): Promise<ReplicationState> {
const state = await this.db.query(
`SELECT pullCursor as cursor,pullOffset as offset from _replicationStates where id="${collectionName}"`,
);
if (state && state.values && state.values.length) {
const { cursor, offset } = state.values[0];
return { cursor, offset };
} else return { cursor: 0, offset: 0 };
}
createReplicationStatesTable() {
return this.db.execute(`
CREATE TABLE IF NOT EXISTS _replicationStates (
id TEXT PRIMARY KEY NOT NULL,
pushCursor INTEGER DEFAULT 0,
pushOffset INTEGER DEFAULT 0,
pullCursor INTEGER DEFAULT 0,
pullOffset INTEGER DEFAULT 0
);`);
}
beginTransaction() {
return this.db.beginTransaction();
}
commitTransaction() {
return this.db.commitTransaction();
}
rollbackTransaction() {
return this.db.rollbackTransaction();
}
isTransactionActive() {
return this.db.isTransactionActive();
}
updateReplicationPushState(collectionName: string, offset: number, cursor: number): Promise<any> {
return this.db.execute(
`INSERT INTO _replicationStates (id, pushOffset, pushCursor) VALUES ('${collectionName}', ${offset}, ${cursor})
ON CONFLICT DO UPDATE SET pushOffset=excluded.pushOffset, pushCursor=excluded.pushCursor`,
false,
);
}
updateReplicationPullState(collectionName: string, offset: number, cursor: number): Promise<any> {
return this.db.execute(
`INSERT INTO _replicationStates (id, pullOffset, pullCursor) VALUES ('${collectionName}', ${offset}, ${cursor})
ON CONFLICT DO UPDATE SET pullOffset=excluded.pullOffset, pullCursor=excluded.pullCursor`,
false,
);
}
}