-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathCOSQLiteStore.m
More file actions
1220 lines (977 loc) · 40.7 KB
/
COSQLiteStore.m
File metadata and controls
1220 lines (977 loc) · 40.7 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
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
/*
Copyright (C) 2012 Eric Wasylishen
Date: November 2012
License: MIT (see COPYING)
*/
#import "COSQLiteStore.h"
#import "COSQLiteStore+Private.h"
#import "COSQLiteStorePersistentRootBackingStore.h"
#import "CORevisionInfo.h"
#import <EtoileFoundation/Macros.h>
#import "COItem.h"
#import "COSQLiteStore+Attachments.h"
#import "COSQLiteUtilities.h"
#import "COBasicHistoryCompaction.h"
#import "COJSONSerialization.h"
#import "COStoreTransaction.h"
#import "COStoreAction.h"
#if TARGET_OS_IPHONE
#import "NSDistributedNotificationCenter.h"
#endif
#import "FMDatabaseAdditions.h"
/* For dispatch_get_current_queue() deprecated on iOS (to prevent to people to
use it beside debugging) */
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSString *const COStorePersistentRootsDidChangeNotification = @"COStorePersistentRootsDidChangeNotification";
NSString *const kCOStorePersistentRootTransactionIDs = @"COPersistentRootTransactionIDs";
NSString *const kCOStoreInsertedPersistentRoots = @"COStoreInsertedPersistentRoots";
NSString *const kCOStoreUpdatedPersistentRoots = @"COStoreUpdatedPersistentRoots";
NSString *const kCOStoreDeletedPersistentRoots = @"COStoreDeletedPersistentRoots";
NSString *const kCOStoreCompactedPersistentRoots = @"COStoreCompactedPersistentRoots";
NSString *const kCOStoreFinalizedPersistentRoots = @"COStoreFinalizedPersistentRoots";
NSString *const kCOStoreUUID = @"COStoreUUID";
NSString *const kCOStoreURL = @"COStoreURL";
NSString *const COPersistentRootAttributeExportSize = @"COPersistentRootAttributeExportSize";
NSString *const COPersistentRootAttributeUsedSize = @"COPersistentRootAttributeUsedSize";
@interface COSQLiteStore (AttachmentsPrivate)
@property (nonatomic, readonly) NSArray *attachments;
- (BOOL)deleteAttachment: (COAttachmentID *)hash;
@end
@implementation COSQLiteStore
@synthesize maxNumberOfDeltaCommits = _maxNumberOfDeltaCommits;
- (instancetype)initWithURL: (NSURL *)aURL
{
NILARG_EXCEPTION_TEST(aURL);
SUPERINIT;
queue_ = dispatch_queue_create([[NSString stringWithFormat: @"COSQLiteStore-%p",
self] UTF8String], NULL);
url_ = aURL;
backingStores_ = [[NSMutableDictionary alloc] init];
backingStoreUUIDForPersistentRootUUID_ = [[NSMutableDictionary alloc] init];
_maxNumberOfDeltaCommits = 50;
__block BOOL ok = YES;
dispatch_sync(queue_, ^()
{
// Ignore if this fails (it will fail if the directory already exists.)
// If it really fails, we will notice later when we try to open the sqlite db
[[NSFileManager defaultManager] createDirectoryAtPath: url_.path
withIntermediateDirectories: YES
attributes: nil
error: NULL];
db_ = [[FMDatabase alloc] initWithPath: [url_.path stringByAppendingPathComponent: @"index.sqlite"]];
[db_ setShouldCacheStatements: YES];
[db_ setCrashOnErrors: NO];
[db_ setLogsErrors: YES];
[db_ open];
// Use write-ahead-log mode
{
NSString *result = [db_ stringForQuery: @"PRAGMA journal_mode=WAL"];
if (![@"wal" isEqualToString: result])
{
NSLog(@"Enabling WAL mode failed.");
}
}
// Set up schema
ok = [self setupSchema];
});
if (!ok)
{
return nil;
}
return self;
}
- (instancetype)init
{
return [self initWithURL: nil];
}
- (void)dealloc
{
dispatch_sync(queue_, ^()
{
[db_ close];
db_ = nil;
});
#if defined(GNUSTEP)
// N.B.: We are using deployment target 10.8, so ARC will manage
// libdispatch objects automatically. For GNUstep, ARC doesn't
// manage libdispatch objects since libobjc2 doesn't support it
// currently (we compile CoreObject with -DOS_OBJECT_USE_OBJC=0).
dispatch_release(_queue);
#endif
}
- (BOOL)setupSchema
{
assert(dispatch_get_current_queue() == queue_);
[db_ beginDeferredTransaction];
/* Store Metadata tables (including schema version) */
if (![db_ tableExists: @"storeMetadata"])
{
_uuid = [ETUUID UUID];
[db_ executeUpdate: @"CREATE TABLE storeMetadata(version INTEGER, uuid BLOB)"];
[db_ executeUpdate: @"INSERT INTO storeMetadata VALUES(1, ?)", [_uuid dataValue]];
}
else
{
int version = [db_ intForQuery: @"SELECT version FROM storeMetadata"];
if (1 != version)
{
NSLog(@"Error, store version %d, only version 1 is supported", version);
[db_ rollback];
return NO;
}
_uuid = [ETUUID UUIDWithData: [db_ dataForQuery: @"SELECT uuid FROM storeMetadata"]];
}
// Persistent Root and Branch tables
[db_ executeUpdate: @"CREATE TABLE IF NOT EXISTS persistentroots ("
"uuid BLOB PRIMARY KEY NOT NULL, currentbranch BLOB, deleted BOOLEAN DEFAULT 0, transactionid INTEGER, metadata BLOB)"];
[db_ executeUpdate: @"CREATE TABLE IF NOT EXISTS branches (uuid BLOB NOT NULL PRIMARY KEY, "
"proot BLOB NOT NULL, current_revid BLOB NOT NULL, "
"head_revid BLOB NOT NULL, metadata BLOB, deleted BOOLEAN DEFAULT 0, parentbranch BLOB)"];
[db_ executeUpdate: @"CREATE INDEX IF NOT EXISTS branches_by_proot ON branches(proot)"];
[db_ executeUpdate: @"CREATE TABLE IF NOT EXISTS persistentroot_backingstores ("
"uuid BLOB PRIMARY KEY NOT NULL, backingstore BLOB NOT NULL)"];
// FTS indexes & reference caching tables (in theory, could be regenerated - although not supported)
/**
* In inner_object_uuid in revid of backing store root_id, there was a reference to dest_root_id
*/
[db_ executeUpdate: @"CREATE TABLE IF NOT EXISTS proot_refs (root_id BLOB, revid BOLB, inner_object_uuid BLOB, dest_root_id BLOB)"];
[db_ executeUpdate: @"CREATE TABLE IF NOT EXISTS attachment_refs (root_id BLOB, revid BLOB, attachment_hash BLOB)"];
// FIXME: This is a bit ugly. Verify that usage is consistent across fts3/4
if (sqlite3_libversion_number() >= 3007011)
{
[db_ executeUpdate: @"CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts4(content=\"\", text)"]; // implicit column docid
}
else
{
if (nil == [db_ stringForQuery: @"SELECT name FROM sqlite_master WHERE type = 'table' and name = 'fts'"])
{
[db_ executeUpdate: @"CREATE VIRTUAL TABLE fts USING fts3(text)"]; // implicit column docid
}
}
[db_ executeUpdate: @"CREATE TABLE IF NOT EXISTS fts_docid_to_revisionid ("
"docid INTEGER PRIMARY KEY, backingstore BLOB, revid BLOB)"];
[db_ commit];
if ([db_ hadError])
{
NSLog(@"Error %d: %@", [db_ lastErrorCode], [db_ lastErrorMessage]);
return NO;
}
return YES;
}
- (NSURL *)URL
{
return url_;
}
@synthesize UUID = _uuid;
#pragma mark Transactions -
- (BOOL)commitStoreTransaction: (COStoreTransaction *)aTransaction
{
__block BOOL ok = YES;
assert(dispatch_get_current_queue() != queue_);
NSMutableDictionary *txnIDForPersistentRoot = [[NSMutableDictionary alloc] init];
NSMutableArray *insertedUUIDs = [[NSMutableArray alloc] init];
NSMutableArray *deletedUUIDs = [[NSMutableArray alloc] init];
dispatch_sync(queue_, ^()
{
[db_ beginTransaction];
// update the last transaction field before we commit.
// setup
for (ETUUID *modifiedUUID in aTransaction.persistentRootUUIDs)
{
const BOOL isPresent = [db_ boolForQuery: @"SELECT COUNT(*) > 0 FROM persistentroots WHERE uuid = ?",
[modifiedUUID dataValue]];
const BOOL modifiesMutableState = [aTransaction touchesMutableStateForPersistentRootUUID: modifiedUUID];
int64_t currentValue = [db_ int64ForQuery: @"SELECT transactionid FROM persistentroots WHERE uuid = ?",
[modifiedUUID dataValue]];
int64_t clientValue = [aTransaction oldTransactionIDForPersistentRoot: modifiedUUID];
const BOOL wasLoaded = [aTransaction hasOldTransactionIDForPersistentRoot: modifiedUUID];
if (!modifiesMutableState)
continue;
// Sort of a hack: we allow committing without providing a transaction ID. (if wasLoaded is NO)
if (!wasLoaded)
{
clientValue = currentValue;
}
if (clientValue != currentValue && isPresent)
{
ok = NO;
NSLog(@"Transaction id mismatch for %@. DB had %d, transaction had %d",
modifiedUUID, (int)currentValue, (int)clientValue);
[db_ rollback];
return;
}
if (!isPresent)
[insertedUUIDs addObject: modifiedUUID];
int64_t newValue = clientValue + 1;
[db_ executeUpdate: @"UPDATE persistentroots SET transactionid = ? WHERE uuid = ?",
@(newValue), [modifiedUUID dataValue]];
txnIDForPersistentRoot[modifiedUUID] = @(newValue);
}
// perform actions
for (id <COStoreAction> op in aTransaction.operations)
{
BOOL opOk = [op execute: self inTransaction: aTransaction];
if (!opOk)
{
NSLog(@"store action failed: %@", op);
ok = NO;
break;
}
ok = ok && opOk;
}
// gather deleted persistent root UUIDs
/* Since we don't allow committing to a deleted persistent root, this
means these deleted UUIDs won't include persistent roots deleted in
a previous commit. */
for (ETUUID *modifiedUUID in aTransaction.persistentRootUUIDs)
{
const BOOL isPresent = [db_ boolForQuery: @"SELECT COUNT(*) > 0 FROM persistentroots WHERE uuid = ? AND deleted = 1",
[modifiedUUID dataValue]];
if (isPresent)
[deletedUUIDs addObject: modifiedUUID];
}
// TODO: Turn on if we decide to write history compaction changes with
// this method.
#if 0
// gather finalized persistent root UUIDs
for (ETUUID *modifiedUUID in aTransaction.persistentRootUUIDs)
{
const BOOL isPresent = [db_ boolForQuery: @"SELECT COUNT(*) > 0 FROM persistentroots WHERE uuid = ?", [modifiedUUID dataValue]];
if (!isPresent)
[finalizedUUIDs addObject: modifiedUUID];
}
#endif
if (!ok)
{
[db_ rollback];
ok = NO;
}
else
{
ok = [db_ commit];
}
});
if (ok)
{
[self postCommitNotificationsWithTransactionIDForPersistentRootUUID: txnIDForPersistentRoot
insertedPersistentRoots: insertedUUIDs
deletedPersistentRoots: deletedUUIDs
compactedPersistentRoots: @[]
finalizedPersistentRoots: @[]];
}
else
{
NSLog(@"Commit failed");
}
return ok;
}
- (NSArray *)allBackingUUIDs
{
NSMutableArray *result = [NSMutableArray array];
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT DISTINCT backingstore FROM persistentroot_backingstores"];
sqlite3_stmt *statement = [[rs statement] statement];
while ([rs next])
{
const void *data = sqlite3_column_blob(statement, 0);
const int dataSize = sqlite3_column_bytes(statement, 0);
assert(dataSize == 16);
ETUUID *uuid = [[ETUUID alloc] initWithUUID: data];
[result addObject: uuid];
}
[rs close];
});
return result;
}
- (ETUUID *)headRevisionUUIDForBranchUUID: (ETUUID *)aBranchUUID
{
NILARG_EXCEPTION_TEST(aBranchUUID);
__block ETUUID *revUUID = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT head_revid FROM branches WHERE uuid = ?",
[aBranchUUID dataValue]];
if ([rs next])
{
revUUID = [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]];
ETAssert(![rs next]);
}
[rs close];
});
return revUUID;
}
- (NSArray *)revisionInfosForBranchUUID: (ETUUID *)aBranchUUID
options: (COBranchRevisionReadingOptions)options
{
ETUUID *prootUUID = [self persistentRootUUIDForBranchUUID: aBranchUUID];
if (prootUUID == nil)
{
[NSException raise: NSInternalInconsistencyException
format: @"For branch %@, the persistent root doesn't exist "
"in the store. This usually means the persistent "
"root has been finalized and this branch doesn't "
"exist anymore.", aBranchUUID];
}
ETUUID *headRevUUID = [self headRevisionUUIDForBranchUUID: aBranchUUID];
__block NSArray *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
COSQLiteStorePersistentRootBackingStore *backingStore =
[self backingStoreForPersistentRootUUID: prootUUID createIfNotPresent: YES];
result = [backingStore revisionInfosForBranchUUID: aBranchUUID
headRevisionUUID: headRevUUID
options: options];
});
return result;
}
- (NSArray *)revisionInfosForBackingStoreOfPersistentRootUUID: (ETUUID *)aPersistentRoot
{
__block NSArray *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
COSQLiteStorePersistentRootBackingStore *backingStore =
[self backingStoreForPersistentRootUUID: aPersistentRoot createIfNotPresent: YES];
result = backingStore.revisionInfos;
});
return result;
}
- (ETUUID *)backingUUIDForPersistentRootUUID: (ETUUID *)aUUID
createIfNotPresent: (BOOL)createIfNotPresent
{
assert(dispatch_get_current_queue() == queue_);
ETUUID *backingUUID = backingStoreUUIDForPersistentRootUUID_[aUUID];
if (backingUUID == nil)
{
NSData *data = [db_ dataForQuery: @"SELECT backingstore FROM persistentroot_backingstores WHERE uuid = ?",
[aUUID dataValue]];
if (data != nil)
{
backingUUID = [ETUUID UUIDWithData: data];
}
else
{
if (createIfNotPresent)
{
backingUUID = aUUID;
}
else
{
return nil;
}
}
backingStoreUUIDForPersistentRootUUID_[aUUID] = backingUUID;
}
return backingUUID;
}
- (COSQLiteStorePersistentRootBackingStore *)backingStoreForPersistentRootUUID: (ETUUID *)aUUID
createIfNotPresent: (BOOL)createIfNotPresent
{
assert(dispatch_get_current_queue() == queue_);
ETUUID *bsUUID = [self backingUUIDForPersistentRootUUID: aUUID
createIfNotPresent: createIfNotPresent];
if (bsUUID == nil)
{
return nil;
}
return [self backingStoreForUUID: bsUUID
error: NULL];
}
- (COSQLiteStorePersistentRootBackingStore *)backingStoreForUUID: (ETUUID *)aUUID
error: (NSError **)error
{
COSQLiteStorePersistentRootBackingStore *result = backingStores_[aUUID];
if (result == nil)
{
result = [[COSQLiteStorePersistentRootBackingStore alloc] initWithPersistentRootUUID: aUUID
store: self
useStoreDB: BACKING_STORES_SHARE_SAME_SQLITE_DB
error: error];
if (result == nil)
{
return nil;
}
backingStores_[aUUID] = result;
}
return result;
}
- (NSString *)backingStorePathForUUID: (ETUUID *)aUUID
{
return [self.URL.path stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.sqlite",
aUUID]];
}
- (void)deleteBackingStoreWithUUID: (ETUUID *)aUUID
{
#if BACKING_STORES_SHARE_SAME_SQLITE_DB == 1
[db_ executeUpdate: [NSString stringWithFormat: @"DROP TABLE IF EXISTS `commits-%@`", aUUID]];
[db_ executeUpdate: [NSString stringWithFormat: @"DROP TABLE IF EXISTS `metadata-%@`", aUUID]];
#else
// FIXME: Test this
{
COSQLiteStorePersistentRootBackingStore *backing = [backingStores_ objectForKey: aUUID];
if (backing != nil)
{
[backing close];
[backingStores_ removeObjectForKey: aUUID];
}
}
assert([[NSFileManager defaultManager] removeItemAtPath:
[self backingStorePathForUUID: aUUID] error: NULL]);
#endif
}
#pragma mark Reading States -
- (CORevisionInfo *)revisionInfoForRevisionUUID: (ETUUID *)aRevision
persistentRootUUID: (ETUUID *)aPersistentRoot
{
NSParameterAssert(aRevision != nil);
NSParameterAssert(aPersistentRoot != nil);
__block CORevisionInfo *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
COSQLiteStorePersistentRootBackingStore *backing = [self backingStoreForPersistentRootUUID: aPersistentRoot
createIfNotPresent: YES];
result = [backing revisionInfoForRevisionUUID: aRevision];
});
return result;
}
- (COItemGraph *)partialItemGraphFromRevisionUUID: (ETUUID *)baseRevid
toRevisionUUID: (ETUUID *)finalRevid
persistentRoot: (ETUUID *)aPersistentRoot
{
NSParameterAssert(baseRevid != nil);
NSParameterAssert(finalRevid != nil);
NSParameterAssert(aPersistentRoot != nil);
__block COItemGraph *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
COSQLiteStorePersistentRootBackingStore *backing = [self backingStoreForPersistentRootUUID: aPersistentRoot
createIfNotPresent: YES];
result = [backing partialItemGraphFromRevid: [backing revidForUUID: baseRevid]
toRevid: [backing revidForUUID: finalRevid]];
});
return result;
}
- (COItemGraph *)itemGraphForRevisionUUID: (ETUUID *)aRevisionUUID
persistentRoot: (ETUUID *)aPersistentRoot
{
NSParameterAssert(aRevisionUUID != nil);
NSParameterAssert(aPersistentRoot != nil);
__block COItemGraph *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
COSQLiteStorePersistentRootBackingStore *backing = [self backingStoreForPersistentRootUUID: aPersistentRoot
createIfNotPresent: YES];
result = [backing itemGraphForRevid: [backing revidForUUID: aRevisionUUID]];
});
return result;
}
- (ETUUID *)rootObjectUUIDForPersistentRoot: (ETUUID *)aPersistentRoot
{
NSParameterAssert(aPersistentRoot != nil);
__block ETUUID *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
COSQLiteStorePersistentRootBackingStore *backing = [self backingStoreForPersistentRootUUID: aPersistentRoot
createIfNotPresent: YES];
result = backing.rootUUID;
});
return result;
}
#pragma mark writing states -
/**
* Updates SQL indexes so given a search query containing contents of
* the items mentioned by modifiedItems, we can get back aRevision.
*
* We'll then have to search to see which persistent roots
* and which branches reference that revision ID, but that should be really fast.
*/
- (void)updateSearchIndexesForItemTree: (id <COItemGraph>)anItemTree
revisionIDBeingWritten: (ETUUID *)aRevision
persistentRootBeingWritten: (ETUUID *)aPersistentRoot
{
assert(dispatch_get_current_queue() == queue_);
[db_ savepoint: @"updateSearchIndexesForItemUUIDs"];
ETUUID *backingStoreUUID = [self backingUUIDForPersistentRootUUID: aPersistentRoot
createIfNotPresent: YES];
NSData *backingUUIDData = [backingStoreUUID dataValue];
NSMutableArray *ftsContent = [NSMutableArray array];
for (ETUUID *uuid in anItemTree.itemUUIDs)
{
COItem *itemToIndex = [anItemTree itemForUUID: uuid];
NSString *itemFtsContent = itemToIndex.fullTextSearchContent;
[ftsContent addObject: itemFtsContent];
// Look for references to other persistent roots.
for (ETUUID *referenced in itemToIndex.allReferencedPersistentRootUUIDs)
{
[db_ executeUpdate: @"INSERT INTO proot_refs(root_id, revid, inner_object_uuid, dest_root_id) VALUES(?,?,?,?)",
backingUUIDData,
[aRevision dataValue],
[uuid dataValue],
[referenced dataValue]];
}
// Look for attachments
for (COAttachmentID *attachment in itemToIndex.attachments)
{
if ((id)attachment != [NSNull null])
{
[db_ executeUpdate: @"INSERT INTO attachment_refs(root_id, revid, attachment_hash) VALUES(?,?,?)",
backingUUIDData,
[aRevision dataValue],
attachment.dataValue];
}
}
}
NSString *allItemsFtsContent = [ftsContent componentsJoinedByString: @" "];
[db_ executeUpdate: @"INSERT INTO fts_docid_to_revisionid(backingstore, revid) VALUES(?, ?)",
backingUUIDData,
[aRevision dataValue]];
[db_ executeUpdate: @"INSERT INTO fts(docid, text) VALUES(?,?)",
@([db_ lastInsertRowId]),
allItemsFtsContent];
[db_ releaseSavepoint: @"updateSearchIndexesForItemUUIDs"];
//NSLog(@"Index text '%@' at revision id %@", allItemsFtsContent, aRevision);
assert(![db_ hadError]);
}
- (NSArray *)searchResultsForQuery: (NSString *)aQuery
{
NSMutableArray *result = [NSMutableArray array];
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT uuid, revid FROM "
"(SELECT backingstore, revid FROM fts_docid_to_revisionid WHERE docid IN (SELECT docid FROM fts WHERE text MATCH ?)) "
"INNER JOIN persistentroot_backingstores USING(backingstore)",
aQuery];
while ([rs next])
{
COSearchResult *searchResult = [[COSearchResult alloc] init];
searchResult.innerObjectUUID = nil;
searchResult.revision = [ETUUID UUIDWithData: [rs dataForColumnIndex: 1]];
searchResult.persistentRoot = [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]];
[result addObject: searchResult];
}
[rs close];
});
return result;
}
// Actual implementation used by action
- (BOOL)writeRevisionWithModifiedItems: (COItemGraph *)anItemTree
revisionUUID: (ETUUID *)aRevisionUUID
metadata: (NSDictionary *)metadata
parentRevisionID: (ETUUID *)aParent
mergeParentRevisionID: (ETUUID *)aMergeParent
persistentRootUUID: (ETUUID *)aUUID
branchUUID: (ETUUID *)branch
{
assert(dispatch_get_current_queue() == queue_);
COSQLiteStorePersistentRootBackingStore *backing = [self backingStoreForPersistentRootUUID: aUUID
createIfNotPresent: YES];
if (backing == nil)
{
return NO;
}
const int64_t parentRevid = [backing revidForUUID: aParent];
const int64_t mergeParentRevid = [backing revidForUUID: aMergeParent];
if (aParent != nil && parentRevid == -1)
{
NSLog(@"Parent revision not found: %@", aParent);
// FIXME: If we're going to support writing revisions with missing parents
// we should probably preserve the parent UUID?
}
if (aMergeParent != nil && mergeParentRevid == -1)
{
NSLog(@"Merge parent revision not found: %@", aMergeParent);
}
BOOL ok = [backing writeItemGraph: anItemTree
revisionUUID: aRevisionUUID
withMetadata: metadata
withParent: parentRevid
withMergeParent: mergeParentRevid
branchUUID: branch
persistentrootUUID: aUUID
error: NULL];
if (!ok)
{
NSLog(@"Error creating revision");
return NO;
}
[self updateSearchIndexesForItemTree: anItemTree
revisionIDBeingWritten: aRevisionUUID
persistentRootBeingWritten: aUUID];
return YES;
}
#pragma mark Persistent Roots -
- (NSArray *)persistentRootUUIDs
{
NSMutableArray *result = [NSMutableArray array];
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT uuid FROM persistentroots WHERE deleted = 0"];
while ([rs next])
{
[result addObject: [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]]];
}
[rs close];
});
return result;
}
- (NSArray *)deletedPersistentRootUUIDs
{
NSMutableArray *result = [NSMutableArray array];
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT uuid FROM persistentroots WHERE deleted = 1"];
while ([rs next])
{
[result addObject: [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]]];
}
[rs close];
});
return result;
}
- (COPersistentRootInfo *)persistentRootInfoForUUID: (ETUUID *)aUUID
{
if (aUUID == nil)
{
return nil;
}
__block COPersistentRootInfo *result = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
ETUUID *currBranch = nil;
BOOL deleted = NO;
int64_t transactionID = -1;
NSMutableDictionary *branchDict = [NSMutableDictionary dictionary];
id persistentRootMetadata = nil;
[db_ savepoint: @"persistentRootInfoForUUID"]; // N.B. The transaction is so the two SELECTs see the same DB. Needed?
{
FMResultSet *rs = [db_ executeQuery: @"SELECT currentbranch, deleted, transactionid, metadata FROM persistentroots WHERE uuid = ?",
[aUUID dataValue]];
if ([rs next])
{
currBranch = [rs dataForColumnIndex: 0] != nil
? [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]]
: nil;
deleted = [rs boolForColumnIndex: 1];
transactionID = [rs int64ForColumnIndex: 2];
persistentRootMetadata = [self readMetadata: [rs dataForColumnIndex: 3]];
}
else
{
[rs close];
[db_ releaseSavepoint: @"persistentRootInfoForUUID"];
return;
}
[rs close];
}
{
FMResultSet *rs = [db_ executeQuery: @"SELECT uuid, current_revid, head_revid, metadata, deleted, parentbranch FROM branches WHERE proot = ?",
[aUUID dataValue]];
while ([rs next])
{
ETUUID *branch = [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]];
ETUUID *currentRevid = [ETUUID UUIDWithData: [rs dataForColumnIndex: 1]];
ETUUID *headRevid = [ETUUID UUIDWithData: [rs dataForColumnIndex: 2]];
id branchMeta = [self readMetadata: [rs dataForColumnIndex: 3]];
COBranchInfo *state = [[COBranchInfo alloc] init];
state.UUID = branch;
state.persistentRootUUID = aUUID;
state.currentRevisionUUID = currentRevid;
state.headRevisionUUID = headRevid;
state.metadata = branchMeta;
state.deleted = [rs boolForColumnIndex: 4];
state.parentBranchUUID = [rs dataForColumnIndex: 5] != nil
? [ETUUID UUIDWithData: [rs dataForColumnIndex: 5]]
: nil;
branchDict[branch] = state;
}
[rs close];
}
[db_ releaseSavepoint: @"persistentRootInfoForUUID"];
result = [[COPersistentRootInfo alloc] init];
result.UUID = aUUID;
result.branchForUUID = branchDict;
result.currentBranchUUID = currBranch;
result.deleted = deleted;
result.transactionID = transactionID;
result.metadata = persistentRootMetadata;
});
return result;
}
- (ETUUID *)persistentRootUUIDForBranchUUID: (ETUUID *)aBranchUUID
{
NILARG_EXCEPTION_TEST(aBranchUUID);
__block ETUUID *prootUUID = nil;
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT proot FROM branches WHERE uuid = ?",
[aBranchUUID dataValue]];
if ([rs next])
{
prootUUID = [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]];
ETAssert(![rs next]);
}
[rs close];
});
return prootUUID;
}
#pragma mark Writing persistent roots -
- (NSDictionary *)readMetadata: (NSData *)data
{
if (data != nil)
{
return COJSONObjectWithData(data, NULL);
}
return nil;
}
- (BOOL)finalizeGarbageAttachments
{
assert(dispatch_get_current_queue() == queue_);
NSMutableSet *garbage = [NSMutableSet setWithArray: self.attachments];
FMResultSet *rs = [db_ executeQuery: @"SELECT attachment_hash FROM attachment_refs"];
while ([rs next])
{
[garbage removeObject: [[COAttachmentID alloc] initWithData: [rs dataForColumnIndex: 0]]];
}
[rs close];
for (COAttachmentID *hash in garbage)
{
if (![self deleteAttachment: hash])
{
return NO;
}
}
return YES;
}
- (BOOL)finalizeDeletionsForPersistentRoots: (NSSet *)persistentRootUUIDs
error: (NSError **)error
{
NILARG_EXCEPTION_TEST(persistentRootUUIDs);
COBasicHistoryCompaction *compaction = [COBasicHistoryCompaction new];
compaction.finalizablePersistentRootUUIDs = persistentRootUUIDs;
compaction.compactablePersistentRootUUIDs = persistentRootUUIDs;
return [self compactHistory: compaction];
}
// Must not be wrapped in a transaction
- (BOOL)finalizeDeletionsForPersistentRoot: (ETUUID *)aRoot
error: (NSError **)error
{
return [self finalizeDeletionsForPersistentRoots: [NSSet setWithObject: aRoot]
error: error];
}
/**
* @returns an array of COSearchResult
*/
- (NSArray *)referencesToPersistentRoot: (ETUUID *)aUUID
{
NSMutableArray *results = [NSMutableArray array];
assert(dispatch_get_current_queue() != queue_);
dispatch_sync(queue_, ^()
{
FMResultSet *rs = [db_ executeQuery: @"SELECT root_id, revid, inner_object_uuid FROM proot_refs WHERE dest_root_id = ?",
[aUUID dataValue]];
while ([rs next])
{
ETUUID *root = [ETUUID UUIDWithData: [rs dataForColumnIndex: 0]];
ETUUID *revUUID = [ETUUID UUIDWithData: [rs dataForColumnIndex: 1]];
ETUUID *inner_object_uuid = [ETUUID UUIDWithData: [rs dataForColumnIndex: 2]];
COSearchResult *searchResult = [[COSearchResult alloc] init];
searchResult.innerObjectUUID = inner_object_uuid;
searchResult.revision = revUUID;
searchResult.persistentRoot = root;
[results addObject: searchResult];