forked from Expensify/react-native-onyx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLiteProvider.ts
More file actions
193 lines (171 loc) · 7.69 KB
/
Copy pathSQLiteProvider.ts
File metadata and controls
193 lines (171 loc) · 7.69 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
/**
* The SQLiteStorage provider stores everything in a key/value store by
* converting the value to a JSON string
*/
import type {BatchQueryCommand, NitroSQLiteConnection} from 'react-native-nitro-sqlite';
import {enableSimpleNullHandling, open} from 'react-native-nitro-sqlite';
import {getFreeDiskStorage} from 'react-native-device-info';
import type {FastMergeReplaceNullPatch} from '../../utils';
import utils from '../../utils';
import type StorageProvider from './types';
import type {StorageKeyList, StorageKeyValuePair} from './types';
// By default, NitroSQLite does not accept nullish values due to current limitations in Nitro Modules.
// This flag enables a feature in NitroSQLite that allows for nullish values to be passed to operations, such as "execute" or "executeBatch".
// Simple null handling can potentially add a minor performance overhead,
// since parameters and results from SQLite queries need to be parsed from and to JavaScript nullish values.
// https://github.com/margelo/react-native-nitro-sqlite#sending-and-receiving-nullish-values
enableSimpleNullHandling();
/**
* The type of the key-value pair stored in the SQLite database
* @property record_key - the key of the record
* @property valueJSON - the value of the record in JSON string format
*/
type OnyxSQLiteKeyValuePair = {
record_key: string;
valueJSON: string;
};
/**
* The result of the `PRAGMA page_size`, which gets the page size of the SQLite database
*/
type PageSizeResult = {
page_size: number;
};
/**
* The result of the `PRAGMA page_count`, which gets the page count of the SQLite database
*/
type PageCountResult = {
page_count: number;
};
const DB_NAME = 'OnyxDB';
let db: NitroSQLiteConnection;
/**
* Prevents the stringifying of the object markers.
*/
function objectMarkRemover(key: string, value: unknown) {
if (key === utils.ONYX_INTERNALS__REPLACE_OBJECT_MARK) return undefined;
return value;
}
/**
* Transforms the replace null patches into SQL queries to be passed to JSON_REPLACE.
*/
function generateJSONReplaceSQLQueries(key: string, patches: FastMergeReplaceNullPatch[]): string[][] {
const queries = patches.map(([pathArray, value]) => {
const jsonPath = `$.${pathArray.join('.')}`;
return [jsonPath, JSON.stringify(value), key];
});
return queries;
}
const provider: StorageProvider = {
/**
* The name of the provider that can be printed to the logs
*/
name: 'SQLiteProvider',
/**
* Initializes the storage provider
*/
init() {
db = open({name: DB_NAME});
db.execute('CREATE TABLE IF NOT EXISTS keyvaluepairs (record_key TEXT NOT NULL PRIMARY KEY , valueJSON JSON NOT NULL) WITHOUT ROWID;');
// All of the 3 pragmas below were suggested by SQLite team.
// You can find more info about them here: https://www.sqlite.org/pragma.html
db.execute('PRAGMA CACHE_SIZE=-20000;');
db.execute('PRAGMA synchronous=NORMAL;');
db.execute('PRAGMA journal_mode=WAL;');
},
getItem(key) {
return db.executeAsync<OnyxSQLiteKeyValuePair>('SELECT record_key, valueJSON FROM keyvaluepairs WHERE record_key = ?;', [key]).then(({rows}) => {
if (!rows || rows?.length === 0) {
return null;
}
const result = rows?.item(0);
if (result == null) {
return null;
}
return JSON.parse(result.valueJSON);
});
},
multiGet(keys) {
const placeholders = keys.map(() => '?').join(',');
const command = `SELECT record_key, valueJSON FROM keyvaluepairs WHERE record_key IN (${placeholders});`;
return db.executeAsync<OnyxSQLiteKeyValuePair>(command, keys).then(({rows}) => {
// eslint-disable-next-line no-underscore-dangle
const result = rows?._array.map((row) => [row.record_key, JSON.parse(row.valueJSON)]);
return (result ?? []) as StorageKeyValuePair[];
});
},
setItem(key, value) {
return db.executeAsync('REPLACE INTO keyvaluepairs (record_key, valueJSON) VALUES (?, ?);', [key, JSON.stringify(value)]).then(() => undefined);
},
multiSet(pairs) {
const query = 'REPLACE INTO keyvaluepairs (record_key, valueJSON) VALUES (?, json(?));';
const params = pairs.map((pair) => [pair[0], JSON.stringify(pair[1] === undefined ? null : pair[1])]);
if (utils.isEmptyObject(params)) {
return Promise.resolve();
}
return db.executeBatchAsync([{query, params}]).then(() => undefined);
},
multiMerge(pairs) {
const commands: BatchQueryCommand[] = [];
// Query to merge the change into the DB value.
const patchQuery = `INSERT INTO keyvaluepairs (record_key, valueJSON)
VALUES (:key, JSON(:value))
ON CONFLICT DO UPDATE
SET valueJSON = JSON_PATCH(valueJSON, JSON(:value));
`;
const patchQueryArguments: string[][] = [];
// Query to fully replace the nested objects of the DB value.
const replaceQuery = `UPDATE keyvaluepairs
SET valueJSON = JSON_REPLACE(valueJSON, ?, JSON(?))
WHERE record_key = ?;
`;
const replaceQueryArguments: string[][] = [];
const nonNullishPairs = pairs.filter((pair) => pair[1] !== undefined);
for (const [key, value, replaceNullPatches] of nonNullishPairs) {
const changeWithoutMarkers = JSON.stringify(value, objectMarkRemover);
patchQueryArguments.push([key, changeWithoutMarkers]);
const patches = replaceNullPatches ?? [];
if (patches.length > 0) {
const queries = generateJSONReplaceSQLQueries(key, patches);
if (queries.length > 0) {
replaceQueryArguments.push(...queries);
}
}
}
commands.push({query: patchQuery, params: patchQueryArguments});
if (replaceQueryArguments.length > 0) {
commands.push({query: replaceQuery, params: replaceQueryArguments});
}
return db.executeBatchAsync(commands).then(() => undefined);
},
mergeItem(key, change, replaceNullPatches) {
// Since Onyx already merged the existing value with the changes, we can just set the value directly.
return this.multiMerge([[key, change, replaceNullPatches]]);
},
getAllKeys: () =>
db.executeAsync('SELECT record_key FROM keyvaluepairs;').then(({rows}) => {
// eslint-disable-next-line no-underscore-dangle
const result = rows?._array.map((row) => row.record_key);
return (result ?? []) as StorageKeyList;
}),
removeItem: (key) => db.executeAsync('DELETE FROM keyvaluepairs WHERE record_key = ?;', [key]).then(() => undefined),
removeItems: (keys) => {
const placeholders = keys.map(() => '?').join(',');
const query = `DELETE FROM keyvaluepairs WHERE record_key IN (${placeholders});`;
return db.executeAsync(query, keys).then(() => undefined);
},
clear: () => db.executeAsync('DELETE FROM keyvaluepairs;', []).then(() => undefined),
getDatabaseSize() {
return Promise.all([db.executeAsync<PageSizeResult>('PRAGMA page_size;'), db.executeAsync<PageCountResult>('PRAGMA page_count;'), getFreeDiskStorage()]).then(
([pageSizeResult, pageCountResult, bytesRemaining]) => {
const pageSize = pageSizeResult.rows?.item(0)?.page_size ?? 0;
const pageCount = pageCountResult.rows?.item(0)?.page_count ?? 0;
return {
bytesUsed: pageSize * pageCount,
bytesRemaining,
};
},
);
},
};
export default provider;
export type {OnyxSQLiteKeyValuePair};