forked from Expensify/react-native-onyx
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSQLiteProvider.ts
More file actions
151 lines (137 loc) · 6.1 KB
/
SQLiteProvider.ts
File metadata and controls
151 lines (137 loc) · 6.1 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
/**
* The SQLiteStorage provider stores everything in a key/value store by
* converting the value to a JSON string
*/
import type {BatchQueryResult, NitroSQLiteConnection} from 'react-native-nitro-sqlite';
import {enableSimpleNullHandling, open} from 'react-native-nitro-sqlite';
import {getFreeDiskStorage} from 'react-native-device-info';
import type StorageProvider from './types';
import utils from '../../utils';
import type {KeyList, KeyValuePairList} 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;
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 KeyValuePairList;
});
},
setItem(key, value) {
return db.executeAsync('REPLACE INTO keyvaluepairs (record_key, valueJSON) VALUES (?, ?);', [key, JSON.stringify(value)]);
},
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}]);
},
multiMerge(pairs) {
// Note: We use `ON CONFLICT DO UPDATE` here instead of `INSERT OR REPLACE INTO`
// so the new JSON value is merged into the old one if there's an existing value
const query = `INSERT INTO keyvaluepairs (record_key, valueJSON)
VALUES (:key, JSON(:value))
ON CONFLICT DO UPDATE
SET valueJSON = JSON_PATCH(valueJSON, JSON(:value));
`;
const nonUndefinedPairs = pairs.filter((pair) => pair[1] !== undefined);
const params = nonUndefinedPairs.map((pair) => {
const value = JSON.stringify(pair[1]);
return [pair[0], value];
});
return db.executeBatchAsync([{query, params}]);
},
mergeItem(key, deltaChanges, preMergedValue, shouldSetValue) {
if (shouldSetValue) {
return this.setItem(key, preMergedValue) as Promise<BatchQueryResult>;
}
return this.multiMerge([[key, deltaChanges]]) as Promise<BatchQueryResult>;
},
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 KeyList;
}),
removeItem: (key) => db.executeAsync('DELETE FROM keyvaluepairs WHERE record_key = ?;', [key]),
removeItems: (keys) => {
const placeholders = keys.map(() => '?').join(',');
const query = `DELETE FROM keyvaluepairs WHERE record_key IN (${placeholders});`;
return db.executeAsync(query, keys);
},
clear: () => db.executeAsync('DELETE FROM keyvaluepairs;', []),
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};