-
-
Notifications
You must be signed in to change notification settings - Fork 346
/
Copy pathDocStorage.ts
1877 lines (1721 loc) · 78.5 KB
/
DocStorage.ts
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Module to handle the storage of Grist documents.
*
* A Grist document is stored as a SQLite database file. We keep everything in a single database
* file, including attachments, for the sake of having a single file represent a single "document"
* or "data set".
*/
import {LocalActionBundle} from 'app/common/ActionBundle';
import {BulkColValues, DocAction, TableColValues, TableDataAction, toTableDataAction} from 'app/common/DocActions';
import * as gristTypes from 'app/common/gristTypes';
import {isList, isListType, isRefListType} from 'app/common/gristTypes';
import * as marshal from 'app/common/marshal';
import * as schema from 'app/common/schema';
import {SingleCell} from 'app/common/TableData';
import {GristObjCode} from "app/plugin/GristData";
import {ActionHistoryImpl} from 'app/server/lib/ActionHistoryImpl';
import {ExpandedQuery} from 'app/server/lib/ExpandedQuery';
import {IDocStorageManager} from 'app/server/lib/IDocStorageManager';
import log from 'app/server/lib/log';
import assert from 'assert';
import * as bluebird from 'bluebird';
import * as _ from 'underscore';
import * as util from 'util';
import {v4 as uuidv4} from 'uuid';
import {OnDemandStorage} from './OnDemandActions';
import {ISQLiteDB, MigrationHooks, OpenMode, PreparedStatement, quoteIdent,
ResultRow, RunResult, SchemaInfo, SQLiteDB} from 'app/server/lib/SQLiteDB';
import chunk = require('lodash/chunk');
import cloneDeep = require('lodash/cloneDeep');
import groupBy = require('lodash/groupBy');
import { MinDBOptions } from './SqliteCommon';
// Run with environment variable NODE_DEBUG=db (may include additional comma-separated sections)
// for verbose logging.
const debuglog = util.debuglog('db');
const maxSQLiteVariables = 500; // Actually could be 999, so this is playing it safe.
const PENDING_VALUE = [GristObjCode.Pending];
// Number of days that soft-deleted attachments are kept in file storage before being completely deleted.
// Once a file is deleted it can't be restored by undo, so we want it to be impossible or at least extremely unlikely
// that someone would delete a reference to an attachment and then undo that action this many days later.
export const ATTACHMENTS_EXPIRY_DAYS = 7;
// Cleanup expired attachments every hour (also happens when shutting down).
export const REMOVE_UNUSED_ATTACHMENTS_DELAY = {delayMs: 60 * 60 * 1000, varianceMs: 30 * 1000};
export class DocStorage implements ISQLiteDB, OnDemandStorage {
// ======================================================================
// Static fields
// ======================================================================
/**
* Schema for all system tables, i.e. those that are NOT known by the data engine. Regular
* metadata tables (such as _grist_DocInfo) are created via DocActions received from
* InitNewDoc useraction.
*
* The current "Storage Version" used by Grist is the length of the migrations list in its
* Schema. We use it to track changes to how data is stored on disk, and changes to the schema
* of non-data-engine tables (such as _gristsys_* tables). By contrast, "Schema Version" keeps
* track of the version of data-engine metadata. In SQLite, we use "PRAGMA user_version" to
* store the storage version number.
*/
public static docStorageSchema: SchemaInfo = {
async create(db: SQLiteDB): Promise<void> {
await db.exec(`CREATE TABLE _gristsys_Files (
id INTEGER PRIMARY KEY,
ident TEXT UNIQUE,
data BLOB,
storageId TEXT
)`);
await db.exec(`CREATE TABLE _gristsys_Action (
id INTEGER PRIMARY KEY,
"actionNum" BLOB DEFAULT 0,
"time" BLOB DEFAULT 0,
"user" BLOB DEFAULT '',
"desc" BLOB DEFAULT '',
"otherId" BLOB DEFAULT 0,
"linkId" BLOB DEFAULT 0,
"json" BLOB DEFAULT ''
)`);
await db.exec(`CREATE TABLE _gristsys_Action_step (
id INTEGER PRIMARY KEY,
"parentId" BLOB DEFAULT 0,
"type" BLOB DEFAULT '',
"name" BLOB DEFAULT '',
"tableId" BLOB DEFAULT '',
"colIds" BLOB DEFAULT '',
"rowIds" BLOB DEFAULT '',
"values" BLOB DEFAULT '',
"json" BLOB DEFAULT ''
)`);
await db.exec(`CREATE TABLE _gristsys_ActionHistory (
id INTEGER PRIMARY KEY, -- Plain integer action ID ("actionRef")
actionHash TEXT UNIQUE, -- Action checksum
parentRef INTEGER, -- id of parent of this action
actionNum INTEGER, -- distance from root of tree in actions
body BLOB -- content of action
)`);
await db.exec(`CREATE TABLE _gristsys_ActionHistoryBranch (
id INTEGER PRIMARY KEY, -- Numeric branch ID
name TEXT UNIQUE, -- Branch name
actionRef INTEGER -- Latest action on branch
)`);
for (const branchName of ['shared', 'local_sent', 'local_unsent']) {
await db.run("INSERT INTO _gristsys_ActionHistoryBranch(name) VALUES(?)",
branchName);
}
// This is a single row table (enforced by the CHECK on 'id'), containing non-shared info.
// - ownerInstanceId is the id of the instance which owns this copy of the Grist doc.
// - docId is also kept here because it should not be changeable by UserActions.
await db.exec(`CREATE TABLE _gristsys_FileInfo (
id INTEGER PRIMARY KEY CHECK (id = 0),
docId TEXT DEFAULT '',
ownerInstanceId TEXT DEFAULT ''
)`);
await db.exec("INSERT INTO _gristsys_FileInfo (id) VALUES (0)");
await db.exec(`CREATE TABLE _gristsys_PluginData (
id INTEGER PRIMARY KEY, -- Plain integer plugin data id
pluginId TEXT NOT NULL, -- Plugin id
key TEXT NOT NULL, -- the key
value BLOB DEFAULT '' -- the value associated with the key
);
-- Plugins have unique keys.
CREATE UNIQUE INDEX _gristsys_PluginData_unique_key on _gristsys_PluginData(pluginId, key);`);
},
migrations: [
async function(db: SQLiteDB): Promise<void> {
// Storage version 1 does not require a migration. Docs at v1 (or before) may not all
// be the same, and are only made uniform by v2.
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 2. We change the types of all columns to BLOBs.
// This applies to all Grist tables, including metadata.
const migrationLabel = "DocStorage.docStorageSchema.migrations[v1->v2]";
const oldMaxPosDefault = String(Math.pow(2, 31) - 1);
function _upgradeTable(tableId: string) {
log.debug(`${migrationLabel}: table ${tableId}`);
// This returns rows with (at least) {name, type, dflt_value}.
return db.all(`PRAGMA table_info(${quoteIdent(tableId)})`)
.then(infoRows => {
const colListSql = infoRows.map(info => quoteIdent(info.name)).join(', ');
const colSpecSql = infoRows.map(_sqlColSpec).join(', ');
const tmpTableId = DocStorage._makeTmpTableId(tableId);
debuglog(`${migrationLabel}: ${tableId} (${colSpecSql})`);
return db.runEach(
`CREATE TABLE ${quoteIdent(tmpTableId)} (${colSpecSql})`,
`INSERT INTO ${quoteIdent(tmpTableId)} SELECT ${colListSql} FROM ${quoteIdent(tableId)}`,
`DROP TABLE ${quoteIdent(tableId)}`,
`ALTER TABLE ${quoteIdent(tmpTableId)} RENAME TO ${quoteIdent(tableId)}`
);
});
}
function _sqlColSpec(info: ResultRow): string {
if (info.name === 'id') { return 'id INTEGER PRIMARY KEY'; }
// Fix the default for PositionNumber and ManualPos types, if set to a wrong old value.
const dfltValue = (info.type === 'REAL' && info.dflt_value === oldMaxPosDefault) ?
DocStorage._formattedDefault('PositionNumber') :
// The string "undefined" is also an invalid default; fix that too.
(info.dflt_value === 'undefined' ? 'NULL' : info.dflt_value);
return DocStorage._sqlColSpecFromDBInfo(Object.assign({}, info, {
type: 'BLOB',
dflt_value: dfltValue
}));
}
// Some migration-type steps pre-date storage migrations. We can do them once for the first
// proper migration (i.e. this one, to v2), and then never worry about them for upgraded docs.
// Create table for files that wasn't always created in the past.
await db.exec(`CREATE TABLE IF NOT EXISTS _gristsys_Files (
id INTEGER PRIMARY KEY,
ident TEXT UNIQUE,
data BLOB
)`);
// Create _gristsys_Action.linkId column that wasn't always created in the past.
try {
await db.exec('ALTER TABLE _gristsys_Action ADD COLUMN linkId INTEGER');
log.debug("${migrationLabel}: Column linkId added to _gristsys_Action");
} catch (err) {
if (!(/duplicate/.test(err.message))) {
// ok if column already existed
throw err;
}
}
// Deal with the transition to blob types
const tblRows = await db.all("SELECT name FROM sqlite_master WHERE type='table'");
for (const tblRow of tblRows) {
// Note that _gristsys_Action tables in the past used Grist actions to create appropriate
// tables, so docs from that period would use BLOBs. For consistency, we upgrade those tables
// too.
if (tblRow.name.startsWith('_grist_') || !tblRow.name.startsWith('_') ||
tblRow.name.startsWith('_gristsys_Action')) {
await _upgradeTable(tblRow.name);
}
}
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 3. Convert old _gristsys_Action* tables to _gristsys_ActionHistory*.
await db.exec(`CREATE TABLE IF NOT EXISTS _gristsys_ActionHistory (
id INTEGER PRIMARY KEY,
actionHash TEXT UNIQUE,
parentRef INTEGER,
actionNum INTEGER,
body BLOB
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS _gristsys_ActionHistoryBranch (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
actionRef INTEGER
)`);
for (const branchName of ['shared', 'local_sent', 'local_unsent']) {
await db.run("INSERT OR IGNORE INTO _gristsys_ActionHistoryBranch(name) VALUES(?)",
branchName);
}
// Migrate any ActionLog information as best we can
const actions = await db.all("SELECT * FROM _gristsys_Action ORDER BY actionNum");
const steps = groupBy(await db.all("SELECT * FROM _gristsys_Action_step ORDER BY id"),
'parentId');
await db.execTransaction(async () => {
const history = new ActionHistoryImpl(db);
await history.initialize();
for (const action of actions) {
const step = steps[action.actionNum] || [];
const crudeTranslation: LocalActionBundle = {
actionNum: history.getNextHubActionNum(),
actionHash: null,
parentActionHash: null,
envelopes: [],
info: [
0,
{
time: action.time,
user: action.user,
inst: "",
desc: action.desc,
otherId: action.otherId,
linkId: action.linkId
}
],
// Take what was logged as a UserAction and treat it as a DocAction. Summarization
// currently depends on stored+undo fields to understand what changed in an ActionBundle.
// DocActions were not logged prior to this version, so we have to fudge things a little.
stored: [[0, JSON.parse(action.json) as DocAction]],
calc: [],
userActions: [JSON.parse(action.json)],
undo: step.map(row => JSON.parse(row.json))
};
await history.recordNextShared(crudeTranslation);
}
await db.run("DELETE FROM _gristsys_Action_step");
await db.run("DELETE FROM _gristsys_Action");
});
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 4. Maintain docId and ownerInstanceId in a single-row special table;
// for standalone sharing.
await db.exec(`CREATE TABLE _gristsys_FileInfo (
id INTEGER PRIMARY KEY CHECK (id = 0),
docId TEXT DEFAULT '',
ownerInstanceId TEXT DEFAULT ''
)`);
await db.exec("INSERT INTO _gristsys_FileInfo (id) VALUES (0)");
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 5. Add a table to maintain per-plugin data, for plugins' Storage API.
await db.exec(`CREATE TABLE _gristsys_PluginData (
id INTEGER PRIMARY KEY,
pluginId TEXT NOT NULL,
key TEXT NOT NULL,
value BLOB DEFAULT ''
);
CREATE UNIQUE INDEX IF NOT EXISTS _gristsys_PluginData_unique_key on _gristsys_PluginData(pluginId, key);`);
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 6. Migration to fix columns in user tables which have an incorrect
// DEFAULT for their Grist type, due to bug T462.
const migrationLabel = "DocStorage.docStorageSchema.migrations[v5->v6]";
const colRows: ResultRow[] = await db.all('SELECT t.tableId, c.colId, c.type ' +
'FROM _grist_Tables_column c JOIN _grist_Tables t ON c.parentId=t.id');
const docSchema = new Map<string, string>(); // Maps tableId.colId to grist type.
for (const {tableId, colId, type} of colRows) {
docSchema.set(`${tableId}.${colId}`, type);
}
// Fixes defaults and affected null values in a particular table.
async function _fixTable(tableId: string) {
log.debug(`${migrationLabel}: table ${tableId}`);
// This returns rows with (at least) {name, type, dflt_value}.
const infoRows: ResultRow[] = await db.all(`PRAGMA table_info(${quoteIdent(tableId)})`);
const origColSpecSql = infoRows.map(_sqlColSpec).join(', ');
// Get the column SQL for what the columns should be, and the value SQL for how to
// prepare the values to fill them in.
const fixes = infoRows.map((r) => _getInfoAndValuesSql(r, tableId));
const newColSpecSql = fixes.map(pair => pair[0]).map(_sqlColSpec).join(', ');
const valuesSql = fixes.map(pair => pair[1]).join(', ');
// Rebuild the table only if any column's SQL (e.g. DEFAULT values) have changed.
if (newColSpecSql === origColSpecSql) {
debuglog(`${migrationLabel}: ${tableId} unchanged: (${newColSpecSql})`);
} else {
debuglog(`${migrationLabel}: ${tableId} changed: (${newColSpecSql})`);
const tmpTableId = DocStorage._makeTmpTableId(tableId);
return db.runEach(
`CREATE TABLE ${quoteIdent(tmpTableId)} (${newColSpecSql})`,
`INSERT INTO ${quoteIdent(tmpTableId)} SELECT ${valuesSql} FROM ${quoteIdent(tableId)}`,
`DROP TABLE ${quoteIdent(tableId)}`,
`ALTER TABLE ${quoteIdent(tmpTableId)} RENAME TO ${quoteIdent(tableId)}`
);
}
}
// Look up the type for a single column, and if the default changed to non-NULL, construct
// the updated column SQL and the value SQL for how to prepare values.
function _getInfoAndValuesSql(info: ResultRow, tableId: string): [ResultRow, string] {
const qColId = quoteIdent(info.name);
const gristType = docSchema.get(`${tableId}.${info.name}`);
if (gristType) {
const dflt = DocStorage._formattedDefault(gristType);
if (info.dflt_value === 'NULL' && dflt !== 'NULL') {
return [{...info, dflt_value: dflt}, `IFNULL(${qColId}, ${dflt}) as ${qColId}`];
}
}
return [info, qColId];
}
function _sqlColSpec(info: ResultRow): string {
if (info.name === 'id') { return 'id INTEGER PRIMARY KEY'; }
return DocStorage._sqlColSpecFromDBInfo(info);
}
// Go through all user tables and fix them.
const tblRows = await db.all("SELECT name FROM sqlite_master WHERE type='table'");
for (const tblRow of tblRows) {
if (!tblRow.name.startsWith('_')) {
await _fixTable(tblRow.name);
}
}
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 7. Migration to store formulas in SQLite.
// Here, we only create empty columns for each formula column in the document. We let
// ActiveDoc, when it calculates formulas on open, detect that this migration just
// happened, and save the calculated results.
const colRows: ResultRow[] = await db.all('SELECT t.tableId, c.colId, c.type ' +
'FROM _grist_Tables_column c JOIN _grist_Tables t ON c.parentId=t.id WHERE c.isFormula');
// Go table by table.
const tableColRows = groupBy(colRows, 'tableId');
for (const tableId of Object.keys(tableColRows)) {
// There should be no columns conflicting with formula columns, but we check and skip
// them if there are.
const infoRows = await db.all(`PRAGMA table_info(${quoteIdent(tableId)})`);
const presentCols = new Set([...infoRows.map(row => row.name)]);
const newCols = tableColRows[tableId].filter(c => !presentCols.has(c.colId));
// Create all new columns.
for (const {colId, type} of newCols) {
await db.exec(`ALTER TABLE ${quoteIdent(tableId)} ` +
`ADD COLUMN ${DocStorage._columnDefWithBlobs(colId, type)}`);
}
// Fill them in with PENDING_VALUE. This way, on first load and Calculate, they would go
// from "Loading..." to their proper value. After the migration, they should never have
// PENDING_VALUE again.
const colListSql = newCols.map(c => `${quoteIdent(c.colId)}=?`).join(', ');
const types = newCols.map(c => c.type);
const sqlParams = DocStorage._encodeColumnsToRows(types, newCols.map(c => [PENDING_VALUE]));
await db.run(`UPDATE ${quoteIdent(tableId)} SET ${colListSql}`, ...sqlParams[0]);
}
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 8.
// Migration to add an index to _grist_Attachments.fileIdent for fast joining against _gristsys_Files.ident.
const tables = await db.all(`SELECT * FROM sqlite_master WHERE type='table' AND name='_grist_Attachments'`);
if (!tables.length) {
// _grist_Attachments is created in the first Python migration so doesn't exist here for new documents.
// createAttachmentsIndex is called separately by ActiveDoc for that.
return;
}
await createAttachmentsIndex(db);
},
async function(db: SQLiteDB): Promise<void> {
// Storage version 9.
// Migration to add `storage` column to _gristsys_Files, which can optionally refer to an external storage
// where the file is stored.
// Default should be NULL.
await db.exec(`ALTER TABLE _gristsys_Files ADD COLUMN storageId TEXT`);
},
]
};
/**
* Decodes a database row object, returning a new object with decoded values. This is needed for
* Grist data, which is encoded. Careful: doesn't handle booleans specially, should not
* be used within main Grist application.
*/
public static decodeRowValues(dbRow: ResultRow): any {
return _.mapObject(dbRow, val => DocStorage._decodeValue(val, 'Any', 'BLOB'));
}
/**
* Internal helper to distinguish which tables contain information about the metadata
* that docstorage needs to keep track of
*/
private static _isMetadataTable(tableId: string): boolean {
return tableId === "_grist_Tables" || tableId === "_grist_Tables_column";
}
/**
* Shortcut to get the SQL default for the given Grist type.
*/
private static _formattedDefault(colType: string): any {
return gristTypes.getDefaultForType(colType, {sqlFormatted: true});
}
/**
* Join array of strings by prefixing each one with sep.
*/
private static _prefixJoin(sep: string, array: string[]): string {
return array.length ? sep + array.join(sep) : '';
}
/**
* Internal helper to make a tmp table given a tableId
*
* @param {String} tableId
* @returns {String}
*/
private static _makeTmpTableId(tableId: string): string {
return '_tmp_' + tableId;
}
private static _sqlColSpecFromDBInfo(info: ResultRow): string {
return `${quoteIdent(info.name)} ${info.type} DEFAULT ${info.dflt_value}`;
}
/**
* Converts an array of columns to an array of rows (suitable to use as sqlParams), encoding all
* values as needed, according to an array of Grist type strings (must be parallel to columns).
*/
private static _encodeColumnsToRows(types: string[], valueColumns: any[]): any[][] {
const marshaller = new marshal.Marshaller({version: 2});
const rows = _.unzip(valueColumns);
for (const row of rows) {
for (let i = 0; i < row.length; i++) {
row[i] = DocStorage._encodeValue(marshaller, types[i], this._getSqlType(types[i]), row[i]);
}
}
return rows;
}
/**
* Encodes a single value for storing in SQLite. Numbers and text are stored as is, but complex
* types are marshalled and stored as BLOBs. We also marshal binary data, so that for encoded
* data, all BLOBs consistently contain marshalled data.
*
* Note that SQLite may contain tables that aren't used for Grist data (e.g. attachments), for
* which such encoding/marshalling is not used, and e.g. binary data is stored to BLOBs directly.
*/
private static _encodeValue(
marshaller: marshal.Marshaller, gristType: string, sqlType: string, val: any
): Uint8Array|string|number|boolean|null {
const marshalled = () => {
marshaller.marshal(val);
return marshaller.dump();
};
if (gristType == 'ChoiceList') {
// See also app/plugin/objtype.ts for decodeObject(). Here we manually check and decode
// the "List" object type.
if (isList(val) && val.every(tok => (typeof(tok) === 'string'))) {
return JSON.stringify(val.slice(1));
}
} else if (isRefListType(gristType)) {
if (isList(val) && val.slice(1).every((tok: any) => (typeof(tok) === 'number'))) {
return JSON.stringify(val.slice(1));
}
}
// Marshall anything non-primitive.
if (Array.isArray(val) || val instanceof Uint8Array || Buffer.isBuffer(val)) {
return marshalled();
}
// Leave nulls unchanged.
if (val === null) { return val; }
// Return undefined as null.
if (val === undefined) { return null; }
// At this point, we have a non-null primitive. Check what is the Sqlite affinity
// of the destination. May be NUMERIC, INTEGER, TEXT, or BLOB. We handle REAL
// also even though it is not currently used.
const affinity = this._getAffinity(sqlType);
// For strings, numbers, and booleans, we have distinct strategies and problems.
switch (typeof(val)) {
case 'string':
// Strings are easy with TEXT and BLOB affinity, they can be stored verbatim.
if (affinity === 'TEXT' || affinity === 'BLOB') { return val; }
// With an INTEGER, NUMERIC, or REAL affinity, we need to be careful since
// if the string looks like a number it will get cast.
// See vdbe.c:applyNumericAffinity in SQLite source code for
// details. From reading the code, anything that doesn't start
// with '+', '-' or '.', or a digit, or whitespace is certainly safe.
// Whitespace is a little bit fuzzy, could perhaps depend on locale depending
// on how compiled?
if (!/[-+ \t\n\r\v0-9.]/.test(val.charAt(0))) {
return val;
}
// We could make further tests, but that'll increase our odds of
// getting it wrong and letting a string through that gets unexpectedly
// converted. So marshall everything else.
return marshalled();
case 'number':
// Marshal with TEXT affinity, and handle some other awkward cases.
if (affinity === 'TEXT' || Number.isNaN(val) || Object.is(val, -0.0) ||
(sqlType === 'BOOLEAN' && (val === 0 || val === 1))) {
return marshalled();
}
// Otherwise, SQLite will handle numbers safely.
return val;
case 'boolean':
// Booleans are only safe to store in columns of grist type Bool
// (SQL type BOOLEAN), since they will be consistently unencoded as
// booleans.
return (sqlType === 'BOOLEAN') ? val : marshalled();
}
return marshalled();
}
/**
* Decodes Grist data received from SQLite; the inverse of _encodeValue().
* Both Grist and SQL types are expected. Used to interpret Bool/BOOLEANs, and to parse
* ChoiceList values.
*/
private static _decodeValue(val: any, gristType: string, sqlType: string): any {
if (val instanceof Uint8Array || Buffer.isBuffer(val)) {
val = marshal.loads(val);
}
if (gristType === 'Bool') {
if (val === 0 || val === 1) {
// Boolean values come in as 0/1. If the column is of type "Bool", interpret those as
// true/false (note that the data engine does this too).
return Boolean(val);
}
}
if (isListType(gristType)) {
if (typeof val === 'string' && val.startsWith('[')) {
try {
return ['L', ...JSON.parse(val)];
} catch (e) {
// Fall through without parsing
}
}
}
return val;
}
/**
* Helper to return SQL snippet for column definition, using its colId and Grist type.
*/
private static _columnDef(colId: string, colType: string): string {
const colSqlType = DocStorage._getSqlType(colType);
return `${quoteIdent(colId)} ${colSqlType} DEFAULT ${DocStorage._formattedDefault(colType)}`;
}
/**
* As _columnDef(), but column type is strictly Blobs. Used to maintain an old migration.
* TODO: could probably rip out the Blob migration and update all related tests.
*/
private static _columnDefWithBlobs(colId: string, colType: string): string {
return `${quoteIdent(colId)} BLOB DEFAULT ${DocStorage._formattedDefault(colType)}`;
}
/**
* Based on a Grist type, pick a good Sqlite SQL type name to use. Sqlite columns
* are loosely typed, and the types named here are not all distinct in terms of
* 'affinities', but they are helpful as comments. Type names chosen from:
* https://www.sqlite.org/datatype3.html#affinity_name_examples
*/
private static _getSqlType(colType: string|null): string {
switch (colType) {
case 'Bool':
return 'BOOLEAN';
case 'Choice':
case 'Text':
return 'TEXT';
case 'ChoiceList':
case 'RefList':
case 'ReferenceList':
case 'Attachments':
return 'TEXT'; // To be encoded as a JSON array of strings.
case 'Date':
return 'DATE';
case 'DateTime':
return 'DATETIME';
case 'Int':
case 'Id':
case 'Ref':
case 'Reference':
return 'INTEGER';
case 'Numeric':
case 'ManualSortPos':
case 'PositionNumber':
return 'NUMERIC';
}
if (colType) {
if (colType.startsWith('Ref:')) {
return 'INTEGER';
}
if (colType.startsWith('RefList:')) {
return 'TEXT'; // To be encoded as a JSON array of strings.
}
}
return 'BLOB';
}
/**
* For a SQL type, figure out the closest affinity in Sqlite.
* Only SQL types output by _getSqlType are recognized.
* Result is one of NUMERIC, INTEGER, TEXT, or BLOB.
* We don't use REAL, the only remaining affinity.
*/
private static _getAffinity(colType: string|null): string {
switch (colType) {
case 'TEXT':
return 'TEXT';
case 'INTEGER':
return 'INTEGER';
case 'BOOLEAN':
case 'DATE':
case 'DATETIME':
case 'NUMERIC':
return 'NUMERIC';
}
return 'BLOB';
}
// ======================================================================
// Instance fields
// ======================================================================
public docPath: string; // path to document file on disk
private _db: SQLiteDB|null; // database handle
// Maintains { tableId: { colId: gristType } } mapping for all tables, including grist metadata
// tables (obtained from auto-generated schema.js).
private _docSchema: {[tableId: string]: {[colId: string]: string}};
private _cachedDataSize: number|null = null;
public constructor(public storageManager: IDocStorageManager, public docName: string) {
this.docPath = this.storageManager.getPath(docName);
this._db = null;
this._docSchema = Object.assign({}, schema.schema);
}
/**
* Opens an existing SQLite database and prepares it for use.
*/
public openFile(hooks: MigrationHooks = {}): Promise<void> {
// It turns out to be important to return a bluebird promise, a lot of code outside
// of DocStorage ultimately depends on this.
return bluebird.Promise.resolve(this._openFile(OpenMode.OPEN_EXISTING, hooks))
.then(() => this._initDB())
.then(() => this._updateMetadata());
}
/**
* Creates a new SQLite database. Will throw an error if the database already exists.
* After a database is created it should be initialized by applying the InitNewDoc action
* or by executing the initialDocSql.
*/
public createFile(options?: {
useExisting?: boolean, // If set, it is ok if an sqlite file already exists
// where we would store the Grist document. Its content
// will not be touched. Useful when "gristifying" an
// existing SQLite DB.
}): Promise<void> {
// It turns out to be important to return a bluebird promise, a lot of code outside
// of DocStorage ultimately depends on this.
return bluebird.Promise.resolve(this._openFile(
options?.useExisting ? OpenMode.OPEN_EXISTING : OpenMode.CREATE_EXCL,
{}))
.then(() => this._initDB());
// Note that we don't call _updateMetadata() as there are no metadata tables yet anyway.
}
public isInitialized(): boolean {
return Boolean(this._db);
}
/**
* Initializes the database with proper settings.
*/
public _initDB(): Promise<void> {
// Set options for speed across multiple OSes/Filesystems.
// WAL is fast and safe (guarantees consistency across crashes), but has disadvantages
// including generating unwanted extra files that can be tricky to deal with in renaming, etc
// the options for WAL are commented out
// Setting synchronous to OFF is the fastest method, but is not as safe, and could lead to
// a database being corrupted if the computer it is running on crashes.
// TODO: Switch setting to FULL, but don't wait for SQLite transactions to finish before
// returning responses to the user. Instead send error messages on unexpected errors.
return this._getDB().exec(
// "PRAGMA wal_autochceckpoint = 1000;" +
// "PRAGMA page_size = 4096;" +
// "PRAGMA journal_size_limit = 0;" +
// "PRAGMA journal_mode = WAL;" +
// "PRAGMA auto_vacuum = 0;" +
// "PRAGMA synchronous = NORMAL"
"PRAGMA synchronous = OFF;" +
"PRAGMA trusted_schema = OFF;" // mitigation suggested by https://www.sqlite.org/security.html#untrusted_sqlite_database_files
);
}
/**
* Queries the database for Grist metadata and updates this._docSchema. It extends the auto-
* generated mapping in app/common/schema.js, to all tables, as `{tableId: {colId: gristType}}`.
*/
public _updateMetadata(): Promise<void> {
return this.all('SELECT t.tableId, c.colId, c.type ' +
'FROM _grist_Tables_column c JOIN _grist_Tables t ON c.parentId=t.id')
.then((rows: ResultRow[]) => {
const s: {[key: string]: any} = {};
for (const {tableId, colId, type} of rows) {
const table = s.hasOwnProperty(tableId) ? s[tableId] : (s[tableId] = {});
table[colId] = type;
}
// Note that schema is what's imported from app/common/schema.js
this._docSchema = Object.assign(s, schema.schema);
})
.catch(err => {
// This replicates previous logic for _updateMetadata.
// It matches errors from node-sqlite3 and better-sqlite3
if (err.message.startsWith('SQLITE_ERROR: no such table') ||
err.message.startsWith('no such table:')) {
err.message = `NO_METADATA_ERROR: ${this.docName} has no metadata`;
if (!err.cause) { err.cause = {}; }
err.cause.code = 'NO_METADATA_ERROR';
}
throw err;
});
}
/**
* Closes the SQLite database.
*/
public async shutdown(): Promise<void> {
if (!this._db) {
log.debug('DocStorage shutdown (trivial) success');
return;
}
const db = this._getDB();
this._db = null;
await db.close();
log.debug('DocStorage shutdown success');
}
/**
* Attaches the file to the document.
*
* TODO: This currently does not make the attachment available to the sandbox code. This is likely
* to be needed in the future, and a suitable API will need to be provided. Note that large blobs
* would be (very?) inefficient until node-sqlite3 adds support for incremental reading from a
* blob: https://github.com/mapbox/node-sqlite3/issues/424.
*
* @param {string} fileIdent - The unique identifier of the file in the database. ActiveDoc uses the
* checksum of the file's contents with the original extension.
* @param {Buffer | undefined} fileData - Contents of the file.
* @param {string | undefined} storageId - Identifier of the store that file is stored in.
* @returns {Promise[Boolean]} True if the file got attached; false if this ident already exists.
*/
public findOrAttachFile(
fileIdent: string,
fileData: Buffer | undefined,
storageId?: string,
): Promise<boolean> {
return this.execTransaction(db => {
// Try to insert a new record with the given ident. It'll fail UNIQUE constraint if exists.
return db.run('INSERT INTO _gristsys_Files (ident) VALUES (?)', fileIdent)
// Only if this succeeded, do the work of reading the file and inserting its data.
.then(() =>
db.run('UPDATE _gristsys_Files SET data=?, storageId=? WHERE ident=?', fileData, storageId, fileIdent))
.then(() => true)
// If UNIQUE constraint failed, this ident must already exists, so return false.
.catch(err => {
if (/^(SQLITE_CONSTRAINT: )?UNIQUE constraint failed/.test(err.message)) {
return false;
}
throw err;
});
});
}
/**
* Reads and returns the data for the given attachment.
* @param {string} fileIdent - The unique identifier of a file, as used by findOrAttachFile.
* @returns {Promise[Buffer]} The data buffer associated with fileIdent.
*/
public getFileInfo(fileIdent: string): Promise<FileInfo | null> {
return this.get('SELECT ident, storageId, data FROM _gristsys_Files WHERE ident=?', fileIdent)
.then(row => row ? ({
ident: row.ident as string,
storageId: (row.storageId ?? null) as (string | null),
data: row.data as Buffer,
}) : null);
}
/**
* Fetches the given table from the database. See fetchQuery() for return value.
*/
public fetchTable(tableId: string): Promise<Buffer> {
return this.fetchQuery({tableId, filters: {}});
}
/**
* Returns as a number the next row id for the given table.
*/
public async getNextRowId(tableId: string): Promise<number> {
const colData = await this.get(`SELECT MAX(id) as maxId FROM ${quoteIdent(tableId)}`);
if (!colData) {
throw new Error(`Error in DocStorage.getNextRowId: no table ${tableId}`);
}
return colData.maxId ? colData.maxId + 1 : 1;
}
/**
* Look up Grist type of column.
*/
public getColumnType(tableId: string, colId: string): string|undefined {
return this._docSchema[tableId]?.[colId];
}
/**
* Fetches all rows of the table with the given rowIds.
*/
public async fetchActionData(tableId: string, rowIds: number[], colIds?: string[]): Promise<TableDataAction> {
const colSpec = colIds ? ['id', ...colIds].map((c) => quoteIdent(c)).join(', ') : '*';
let fullValues: TableColValues|undefined;
// There is a limit to the number of arguments that may be passed in, so fetch data in chunks.
for (const rowIdChunk of chunk(rowIds, maxSQLiteVariables)) {
const sqlArg = rowIdChunk.map(() => '?').join(',');
const marshalled: Buffer = await this._getDB().allMarshal(
`SELECT ${colSpec} FROM ${quoteIdent(tableId)} WHERE id IN (${sqlArg})`, rowIdChunk);
const colValues: TableColValues = this.decodeMarshalledData(marshalled, tableId);
if (!fullValues) {
fullValues = colValues;
} else {
for (const col of Object.keys(colValues)) {
fullValues[col].push(...colValues[col]);
}
}
}
return toTableDataAction(tableId, fullValues || {id: []}); // Return empty TableColValues if rowIds was empty.
}
/**
* Fetches a subset of the data specified by the given query, and returns an encoded TableData
* object, which is a marshalled dict mapping column ids (including 'id') to arrays of values.
*
* This now essentially subsumes the old fetchTable() method.
* Note that text is marshalled as unicode and blobs as binary strings (used to be binary strings
* for both before 2017-11-09). This allows blobs to be used exclusively for encoding types that
* are not easily stored as sqlite's native types.
*/
public async fetchQuery(query: ExpandedQuery): Promise<Buffer> {
// Check if there are a lot of parameters, and if so, switch to a method that can support
// that.
const totalParameters = Object.values(query.filters).map(vs => vs.length).reduce((a, b) => a + b, 0);
if (totalParameters > maxSQLiteVariables) {
// Fall back on using temporary tables if there are many parameters.
return this._fetchQueryWithManyParameters(query);
}
// Convert query to SQL.
const params: any[] = [];
let whereParts: string[] = [];
for (const colId of Object.keys(query.filters)) {
const values = query.filters[colId];
// If values is empty, "IN ()" works in SQLite (always false), but wouldn't work in Postgres.
whereParts.push(`${quoteIdent(query.tableId)}.${quoteIdent(colId)} IN (${values.map(() => '?').join(', ')})`);
params.push(...values);
}
whereParts = whereParts.concat(query.wheres ?? []);
const sql = this._getSqlForQuery(query, whereParts);
return this._getDB().allMarshal(sql, ...params);
}
/**
* Fetches and returns the names of all tables in the database (including _gristsys_ tables).
*/
public async getAllTableNames(): Promise<string[]> {
const rows = await this.all("SELECT name FROM sqlite_master WHERE type='table'");
return rows.map(row => row.name);
}
/**
* Unmarshals and decodes data received from db.allMarshal() method (which we added to node-sqlite3).
* The data is a dictionary mapping column ids (including 'id') to arrays of values. This should
* be used for Grist data, which is encoded. For non-Grist data, use `marshal.loads()`.
*
* Note that we do NOT use this when loading data from a document, since the whole point of
* db.allMarshal() is to pass data directly to Python data engine without parsing in Node.
*/
public decodeMarshalledData(marshalledData: Buffer | Uint8Array, tableId: string): TableColValues {
const columnValues: TableColValues = marshal.loads(marshalledData);
// Decode in-place to avoid unnecessary array creation.
for (const col of Object.keys(columnValues)) {
const type = this._getGristType(tableId, col);
const column = columnValues[col];
for (let i = 0; i < column.length; i++) {
column[i] = DocStorage._decodeValue(column[i], type, DocStorage._getSqlType(type));
}
}
return columnValues;
}
/**
* Variant of `decodeMarshalledData` that supports decoding data containing columns from
* multiple tables.
*
* Expects all column names in `marshalledData` to be prefixed with the table id and a
* trailing period (separator).
*/
public decodeMarshalledDataFromTables(marshalledData: Buffer | Uint8Array): BulkColValues {
const columnValues: BulkColValues = marshal.loads(marshalledData);
// Decode in-place to avoid unnecessary array creation.
for (const col of Object.keys(columnValues)) {
const [tableId, colId] = col.split('.');
const type = this._getGristType(tableId, colId);
const column = columnValues[col];
for (let i = 0; i < column.length; i++) {
column[i] = DocStorage._decodeValue(column[i], type, DocStorage._getSqlType(type));
}
}
return columnValues;
}
/**
* Applies stored actions received from data engine to the database by converting them to SQL
* statements and executing a serialized transaction.
* @param {Array[DocAction]} docActions - Array of doc actions from DataEngine.
* @returns {Promise} - An empty promise, resolved if successfully committed to db.
*/
public async applyStoredActions(docActions: DocAction[]): Promise<void> {
debuglog('DocStorage.applyStoredActions');
docActions = this._compressStoredActions(docActions);
for (const action of docActions) {
try {
await this.applyStoredAction(action);
} catch (e) {
// If the table doesn't have a manualSort column, we'll try
// again without setting manualSort. This should never happen
// for regular Grist documents, but could happen for a
// "gristified" Sqlite database where we are choosing to
// leave the user tables untouched. The manualSort column doesn't
// make much sense outside the context of spreadsheets.
// TODO: it could be useful to make Grist more inherently aware of
// and tolerant of tables without manual sorting.
if (String(e).match(/no column named manualSort/)) {
const modifiedAction = this._considerWithoutManualSort(action);
if (modifiedAction) {
await this.applyStoredAction(modifiedAction);
return;
}
}
throw e;
}
}
}
// Apply a single stored action, dispatching to an appropriate
// _process_<ActionType> handler.
public async applyStoredAction(action: DocAction): Promise<void> {
const actionType = action[0];
const f = (this as any)["_process_" + actionType];
if (!_.isFunction(f)) {
log.error("Unknown action: " + actionType);
} else {
await f.apply(this, action.slice(1));
const tableId = action[1]; // The first argument is always tableId;
if (DocStorage._isMetadataTable(tableId) && actionType !== 'AddTable') {
// We only need to update the metadata for actions that change
// the metadata. We don't update on AddTable actions