-
Notifications
You must be signed in to change notification settings - Fork 264
/
Queries.hs
2135 lines (1921 loc) · 77 KB
/
Queries.hs
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
-- | Some naming conventions used in this module:
--
-- * @32@: the base32 representation of a hash
-- * @expect@: retrieve something that's known to exist
-- * @load@: retrieve something that's not known to exist (so the return type is a Maybe, or another container that
-- could be empty)
-- * @save@: idempotent (on conflict do nothing) insert, and return the id of the thing (usually)
module U.Codebase.Sqlite.Queries
( -- * text table
saveText,
saveTexts,
loadTextId,
expectTextId,
expectText,
expectTextCheck,
-- * hash table
saveHash,
saveHashes,
saveHashHash,
loadHashId,
expectHash,
expectHash32,
expectBranchHash,
loadHashIdByHash,
expectHashIdByHash,
saveCausalHash,
expectCausalHash,
saveBranchHash,
-- * hash_object table
saveHashObject,
expectHashIdsForObject,
hashIdWithVersionForObject,
loadObjectIdForPrimaryHashId,
expectObjectIdForPrimaryHashId,
loadObjectIdForPrimaryHash,
expectObjectIdForPrimaryHash,
loadPatchObjectIdForPrimaryHash,
loadObjectIdForAnyHash,
loadObjectIdForAnyHashId,
expectObjectIdForAnyHashId,
recordObjectRehash,
-- * object table
saveObject,
isObjectHash,
expectObject,
expectPrimaryHashByObjectId,
expectPrimaryHashIdForObject,
expectObjectWithHashIdAndType,
expectDeclObject,
loadDeclObject,
expectNamespaceObject,
loadNamespaceObject,
expectPatchObject,
loadPatchObject,
loadTermObject,
expectTermObject,
-- * namespace_root table
loadNamespaceRoot,
setNamespaceRoot,
expectNamespaceRoot,
-- * causals
-- ** causal table
saveCausal,
isCausalHash,
expectCausal,
loadCausalHashIdByCausalHash,
expectCausalHashIdByCausalHash,
expectCausalValueHashId,
loadCausalByCausalHash,
expectCausalByCausalHash,
loadBranchObjectIdByCausalHashId,
expectBranchObjectIdByCausalHashId,
-- ** causal_parent table
saveCausalParents,
loadCausalParents,
loadCausalParentsByHash,
before,
lca,
-- * watch table
saveWatch,
loadWatch,
loadWatchesByWatchKind,
loadWatchKindsByReference,
clearWatches,
-- * indexes
-- ** dependents index
addToDependentsIndex,
getDependentsForDependency,
getDependentsForDependencyComponent,
getDependenciesForDependent,
getDependencyIdsForDependent,
-- ** migrations
countObjects,
countCausals,
countWatches,
getCausalsWithoutBranchObjects,
removeHashObjectsByHashingVersion,
-- ** type index
addToTypeIndex,
getReferentsByType,
getTypeReferenceForReferent,
getTypeReferencesForComponent,
-- ** type mentions index
addToTypeMentionsIndex,
getReferentsByTypeMention,
getTypeMentionsReferencesForComponent,
-- * hash prefix lookup
objectIdByBase32Prefix,
namespaceHashIdByBase32Prefix,
causalHashIdByBase32Prefix,
-- * Name Lookup
resetNameLookupTables,
insertTermNames,
insertTypeNames,
rootTermNamesByPath,
rootTypeNamesByPath,
getNamespaceDefinitionCount,
-- * garbage collection
garbageCollectObjectsWithoutHashes,
garbageCollectWatchesWithoutObjects,
-- * sync temp entities
EntityLocation (..),
entityExists,
entityLocation,
expectEntity,
syncToTempEntity,
insertTempEntity,
saveTempEntityInMain,
expectTempEntity,
deleteTempEntity,
-- * elaborate hashes
elaborateHashes,
-- * db misc
addTempEntityTables,
addTypeMentionsToIndexForTerm,
addTypeToIndexForTerm,
c2xTerm,
createSchema,
expectSchemaVersion,
localIdsToLookups,
s2cDecl,
s2cTermWithType,
saveDeclComponent,
saveReferenceH,
saveSyncEntity,
saveTermComponent,
schemaVersion,
setSchemaVersion,
x2cTType,
x2cTerm,
)
where
import Control.Lens (Lens')
import qualified Control.Lens as Lens
import Control.Monad.Extra ((||^))
import Control.Monad.State (MonadState, evalStateT)
import Control.Monad.Writer (MonadWriter, runWriterT)
import qualified Control.Monad.Writer as Writer
import Data.Bifunctor (Bifunctor (bimap))
import Data.Bitraversable (bitraverse)
import Data.Bytes.Put (runPutS)
import qualified Data.Foldable as Foldable
import qualified Data.List.Extra as List
import qualified Data.List.NonEmpty as List (NonEmpty)
import qualified Data.List.NonEmpty as Nel
import qualified Data.Map as Map
import Data.Map.NonEmpty (NEMap)
import qualified Data.Map.NonEmpty as NEMap
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.String.Here.Uninterpolated (here, hereFile)
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified U.Codebase.Decl as C
import qualified U.Codebase.Decl as C.Decl
import U.Codebase.HashTags (BranchHash (..), CausalHash (..), PatchHash (..))
import U.Codebase.Reference (Reference' (..))
import qualified U.Codebase.Reference as C
import qualified U.Codebase.Reference as C.Reference
import qualified U.Codebase.Referent as C.Referent
import qualified U.Codebase.Sqlite.Branch.Format as NamespaceFormat
import qualified U.Codebase.Sqlite.Causal as Causal
import qualified U.Codebase.Sqlite.Causal as Sqlite.Causal
import U.Codebase.Sqlite.DbId
( BranchHashId (..),
BranchObjectId (..),
CausalHashId (..),
HashId (..),
HashVersion,
ObjectId (..),
PatchObjectId (..),
SchemaVersion,
TextId,
)
import qualified U.Codebase.Sqlite.Decl.Format as DeclFormat
import qualified U.Codebase.Sqlite.Decl.Format as S.Decl
import U.Codebase.Sqlite.Decode
import U.Codebase.Sqlite.Entity (SyncEntity)
import qualified U.Codebase.Sqlite.Entity as Entity
import U.Codebase.Sqlite.HashHandle (HashHandle (..))
import U.Codebase.Sqlite.LocalIds
( LocalDefnId (..),
LocalIds,
LocalIds' (..),
LocalTextId (..),
)
import qualified U.Codebase.Sqlite.LocalIds as LocalIds
import U.Codebase.Sqlite.NamedRef (NamedRef)
import qualified U.Codebase.Sqlite.NamedRef as NamedRef
import U.Codebase.Sqlite.ObjectType (ObjectType (DeclComponent, Namespace, Patch, TermComponent))
import qualified U.Codebase.Sqlite.ObjectType as ObjectType
import U.Codebase.Sqlite.Orphans ()
import qualified U.Codebase.Sqlite.Patch.Format as PatchFormat
import qualified U.Codebase.Sqlite.Reference as Reference
import qualified U.Codebase.Sqlite.Reference as S
import qualified U.Codebase.Sqlite.Reference as S.Reference
import qualified U.Codebase.Sqlite.Referent as Referent
import qualified U.Codebase.Sqlite.Referent as S.Referent
import U.Codebase.Sqlite.Serialization as Serialization
import U.Codebase.Sqlite.Symbol (Symbol)
import U.Codebase.Sqlite.TempEntity (TempEntity)
import qualified U.Codebase.Sqlite.TempEntity as TempEntity
import U.Codebase.Sqlite.TempEntityType (TempEntityType)
import qualified U.Codebase.Sqlite.TempEntityType as TempEntityType
import qualified U.Codebase.Sqlite.Term.Format as S.Term
import qualified U.Codebase.Sqlite.Term.Format as TermFormat
import qualified U.Codebase.Term as C
import qualified U.Codebase.Term as C.Term
import qualified U.Codebase.Type as C.Type
import U.Codebase.WatchKind (WatchKind)
import qualified U.Core.ABT as ABT
import qualified U.Util.Alternative as Alternative
import U.Util.Hash (Hash)
import qualified U.Util.Hash as Hash
import U.Util.Hash32 (Hash32)
import qualified U.Util.Hash32 as Hash32
import U.Util.Hash32.Orphans.Sqlite ()
import qualified U.Util.Lens as Lens
import qualified U.Util.Serialization as S
import qualified U.Util.Term as TermUtil
import Unison.Prelude
import Unison.Sqlite
-- * main squeeze
createSchema :: Transaction ()
createSchema = do
executeFile [hereFile|unison/sql/create.sql|]
addTempEntityTables
addTempEntityTables :: Transaction ()
addTempEntityTables =
executeFile [hereFile|unison/sql/001-temp-entity-tables.sql|]
executeFile :: String -> Transaction ()
executeFile =
traverse_ (execute_ . fromString) . filter (not . null) . List.splitOn ";"
schemaVersion :: Transaction SchemaVersion
schemaVersion = queryOneCol_ sql
where
sql = "SELECT version from schema_version;"
data UnexpectedSchemaVersion = UnexpectedSchemaVersion
{ actual :: SchemaVersion,
expected :: SchemaVersion
}
deriving stock (Show)
deriving anyclass (SqliteExceptionReason)
-- | Expect the given schema version.
expectSchemaVersion :: SchemaVersion -> Transaction ()
expectSchemaVersion expected =
queryOneColCheck_
[here|
SELECT version
FROM schema_version
|]
(\actual -> if actual /= expected then Left UnexpectedSchemaVersion {actual, expected} else Right ())
setSchemaVersion :: SchemaVersion -> Transaction ()
setSchemaVersion schemaVersion = execute sql (Only schemaVersion)
where
sql = "UPDATE schema_version SET version = ?"
{- ORMOLU_DISABLE -}
{- Please don't try to format the SQL blocks —AI -}
countObjects :: Transaction Int
countObjects = queryOneCol_ [here| SELECT COUNT(*) FROM object |]
countCausals :: Transaction Int
countCausals = queryOneCol_ [here| SELECT COUNT(*) FROM causal |]
countWatches :: Transaction Int
countWatches = queryOneCol_ [here| SELECT COUNT(*) FROM watch |]
saveHash :: Hash32 -> Transaction HashId
saveHash hash = execute sql (Only hash) >> expectHashId hash
where sql = [here|
INSERT INTO hash (base32) VALUES (?)
ON CONFLICT DO NOTHING
|]
saveHashes :: Traversable f => f Hash32 -> Transaction (f HashId)
saveHashes hashes = do
executeMany sql (coerce @[Hash32] @[Only Hash32] (Foldable.toList hashes))
traverse expectHashId hashes
where sql = [here|
INSERT INTO hash (base32) VALUES (?)
ON CONFLICT DO NOTHING
|]
saveHashHash :: Hash -> Transaction HashId
saveHashHash = saveHash . Hash32.fromHash
loadHashId :: Hash32 -> Transaction (Maybe HashId)
loadHashId hash = queryMaybeCol loadHashIdSql (Only hash)
expectHashId :: Hash32 -> Transaction HashId
expectHashId hash = queryOneCol loadHashIdSql (Only hash)
loadHashIdSql :: Sql
loadHashIdSql =
[here| SELECT id FROM hash WHERE base32 = ? COLLATE NOCASE |]
loadHashIdByHash :: Hash -> Transaction (Maybe HashId)
loadHashIdByHash = loadHashId . Hash32.fromHash
saveCausalHash :: CausalHash -> Transaction CausalHashId
saveCausalHash = fmap CausalHashId . saveHashHash . unCausalHash
saveBranchHash :: BranchHash -> Transaction BranchHashId
saveBranchHash = fmap BranchHashId . saveHashHash . unBranchHash
loadCausalHashIdByCausalHash :: CausalHash -> Transaction (Maybe CausalHashId)
loadCausalHashIdByCausalHash ch = runMaybeT do
hId <- MaybeT $ loadHashIdByHash (unCausalHash ch)
Alternative.whenM (lift (isCausalHash hId)) (CausalHashId hId)
expectCausalHashIdByCausalHash :: CausalHash -> Transaction CausalHashId
expectCausalHashIdByCausalHash ch = do
hId <- expectHashIdByHash (unCausalHash ch)
pure (CausalHashId hId)
loadCausalByCausalHash :: CausalHash -> Transaction (Maybe (CausalHashId, BranchHashId))
loadCausalByCausalHash ch = runMaybeT do
hId <- MaybeT $ loadHashIdByHash (unCausalHash ch)
bhId <- MaybeT $ loadCausalValueHashId hId
pure (CausalHashId hId, bhId)
expectCausalByCausalHash :: CausalHash -> Transaction (CausalHashId, BranchHashId)
expectCausalByCausalHash ch = do
hId <- expectCausalHashIdByCausalHash ch
bhId <- expectCausalValueHashId hId
pure (hId, bhId)
expectHashIdByHash :: Hash -> Transaction HashId
expectHashIdByHash = expectHashId . Hash32.fromHash
expectHash :: HashId -> Transaction Hash
expectHash h = Hash32.toHash <$> expectHash32 h
expectHash32 :: HashId -> Transaction Hash32
expectHash32 h = queryOneCol sql (Only h)
where sql = [here| SELECT base32 FROM hash WHERE id = ? |]
expectBranchHash :: BranchHashId -> Transaction BranchHash
expectBranchHash = coerce expectHash
saveText :: Text -> Transaction TextId
saveText t = execute saveTextSql (Only t) >> expectTextId t
saveTexts :: Traversable f => f Text -> Transaction (f TextId)
saveTexts texts = do
executeMany saveTextSql (coerce @[Text] @[Only Text] (Foldable.toList texts))
traverse expectTextId texts
saveTextSql :: Sql
saveTextSql =
[here|
INSERT INTO text (text)
VALUES (?)
ON CONFLICT DO NOTHING
|]
loadTextId :: Text -> Transaction (Maybe TextId)
loadTextId t = queryMaybeCol loadTextIdSql (Only t)
expectTextId :: Text -> Transaction TextId
expectTextId t = queryOneCol loadTextIdSql (Only t)
loadTextIdSql :: Sql
loadTextIdSql =
[here| SELECT id FROM text WHERE text = ? |]
expectText :: TextId -> Transaction Text
expectText h = queryOneCol loadTextSql (Only h)
expectTextCheck :: SqliteExceptionReason e => TextId -> (Text -> Either e a) -> Transaction a
expectTextCheck h = queryOneColCheck loadTextSql (Only h)
loadTextSql :: Sql
loadTextSql =
[here| SELECT text FROM text WHERE id = ? |]
saveHashObject :: HashId -> ObjectId -> HashVersion -> Transaction ()
saveHashObject hId oId version = execute sql (hId, oId, version) where
sql = [here|
INSERT INTO hash_object (hash_id, object_id, hash_version)
VALUES (?, ?, ?)
ON CONFLICT DO NOTHING
|]
saveObject ::
HashHandle ->
HashId ->
ObjectType ->
ByteString ->
Transaction ObjectId
saveObject hh h t blob = do
oId <- execute sql (h, t, blob) >> expectObjectIdForPrimaryHashId h
saveHashObject h oId 2 -- todo: remove this from here, and add it to other relevant places once there are v1 and v2 hashes
rowsModified >>= \case
0 -> pure ()
_ -> do
hash <- expectHash32 h
tryMoveTempEntityDependents hh hash
pure oId
where
sql = [here|
INSERT INTO object (primary_hash_id, type_id, bytes)
VALUES (?, ?, ?)
ON CONFLICT DO NOTHING
|]
expectObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction a
expectObject oId check = do
result <- queryOneColCheck sql (Only oId) check
pure result
where sql = [here|
SELECT bytes FROM object WHERE id = ?
|]
loadObjectOfType ::
SqliteExceptionReason e =>
ObjectId ->
ObjectType ->
(ByteString -> Either e a) ->
Transaction (Maybe a)
loadObjectOfType oid ty =
queryMaybeColCheck loadObjectOfTypeSql (oid, ty)
expectObjectOfType :: SqliteExceptionReason e => ObjectId -> ObjectType -> (ByteString -> Either e a) -> Transaction a
expectObjectOfType oid ty =
queryOneColCheck loadObjectOfTypeSql (oid, ty)
loadObjectOfTypeSql :: Sql
loadObjectOfTypeSql =
[here|
SELECT bytes
FROM object
WHERE id = ?
AND type_id = ?
|]
-- | Load a decl component object.
loadDeclObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction (Maybe a)
loadDeclObject oid =
loadObjectOfType oid DeclComponent
-- | Expect a decl component object.
expectDeclObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction a
expectDeclObject oid =
expectObjectOfType oid DeclComponent
-- | Load a namespace object.
loadNamespaceObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction (Maybe a)
loadNamespaceObject oid =
loadObjectOfType oid Namespace
-- | Expect a namespace object.
expectNamespaceObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction a
expectNamespaceObject oid =
expectObjectOfType oid Namespace
-- | Load a patch object.
loadPatchObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction (Maybe a)
loadPatchObject oid =
loadObjectOfType oid Patch
-- | Expect a patch object.
expectPatchObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction a
expectPatchObject oid =
expectObjectOfType oid Patch
-- | Load a term component object.
loadTermObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction (Maybe a)
loadTermObject oid =
loadObjectOfType oid TermComponent
-- | Expect a term component object.
expectTermObject :: SqliteExceptionReason e => ObjectId -> (ByteString -> Either e a) -> Transaction a
expectTermObject oid =
expectObjectOfType oid TermComponent
expectPrimaryHashIdForObject :: ObjectId -> Transaction HashId
expectPrimaryHashIdForObject oId = do
queryOneCol sql (Only oId)
where
sql = "SELECT primary_hash_id FROM object WHERE id = ?"
expectObjectWithType :: SqliteExceptionReason e => ObjectId -> (ObjectType -> ByteString -> Either e a) -> Transaction a
expectObjectWithType oId check = queryOneRowCheck sql (Only oId) (\(typ, bytes) -> check typ bytes)
where sql = [here|
SELECT type_id, bytes FROM object WHERE id = ?
|]
expectObjectWithHashIdAndType :: ObjectId -> Transaction (HashId, ObjectType, ByteString)
expectObjectWithHashIdAndType oId = queryOneRow sql (Only oId)
where sql = [here|
SELECT primary_hash_id, type_id, bytes FROM object WHERE id = ?
|]
loadObjectIdForPrimaryHashId :: HashId -> Transaction (Maybe ObjectId)
loadObjectIdForPrimaryHashId h =
queryMaybeCol loadObjectIdForPrimaryHashIdSql (Only h)
-- | Not all hashes have corresponding objects; e.g., hashes of term types
expectObjectIdForPrimaryHashId :: HashId -> Transaction ObjectId
expectObjectIdForPrimaryHashId h =
queryOneCol loadObjectIdForPrimaryHashIdSql (Only h)
loadObjectIdForPrimaryHashIdSql :: Sql
loadObjectIdForPrimaryHashIdSql =
[here|
SELECT id
FROM object
WHERE primary_hash_id = ?
|]
loadObjectIdForPrimaryHash :: Hash -> Transaction (Maybe ObjectId)
loadObjectIdForPrimaryHash h =
loadHashIdByHash h >>= \case
Nothing -> pure Nothing
Just hashId -> loadObjectIdForPrimaryHashId hashId
expectObjectIdForPrimaryHash :: Hash -> Transaction ObjectId
expectObjectIdForPrimaryHash =
expectObjectIdForHash32 . Hash32.fromHash
expectObjectIdForHash32 :: Hash32 -> Transaction ObjectId
expectObjectIdForHash32 hash = do
queryOneCol
[here|
SELECT object.id
FROM object
JOIN hash ON object.primary_hash_id = hash.id
WHERE hash.base32 = ? COLLATE NOCASE
|]
(Only hash)
expectBranchObjectIdForHash32 :: Hash32 -> Transaction BranchObjectId
expectBranchObjectIdForHash32 =
fmap BranchObjectId . expectObjectIdForHash32
expectPatchObjectIdForHash32 :: Hash32 -> Transaction PatchObjectId
expectPatchObjectIdForHash32 =
fmap PatchObjectId . expectObjectIdForHash32
expectBranchHashIdForHash32 :: Hash32 -> Transaction BranchHashId
expectBranchHashIdForHash32 = queryOneCol sql . Only
where
sql =
[here|
SELECT hash.id FROM object
INNER JOIN hash_object ON hash_object.object_id = object.id
INNER JOIN hash ON hash_object.hash_id = hash.id
WHERE object.type_id = 2
AND hash.base32 = ? COLLATE NOCASE
|]
expectCausalHashIdForHash32 :: Hash32 -> Transaction CausalHashId
expectCausalHashIdForHash32 = queryOneCol sql . Only
where
sql =
[here|
SELECT self_hash_id
FROM causal INNER JOIN hash ON hash.id = self_hash_id
WHERE base32 = ? COLLATE NOCASE
|]
loadPatchObjectIdForPrimaryHash :: PatchHash -> Transaction (Maybe PatchObjectId)
loadPatchObjectIdForPrimaryHash =
(fmap . fmap) PatchObjectId . loadObjectIdForPrimaryHash . unPatchHash
loadObjectIdForAnyHash :: Hash -> Transaction (Maybe ObjectId)
loadObjectIdForAnyHash h =
loadHashIdByHash h >>= \case
Nothing -> pure Nothing
Just hashId -> loadObjectIdForAnyHashId hashId
loadObjectIdForAnyHashId :: HashId -> Transaction (Maybe ObjectId)
loadObjectIdForAnyHashId h =
queryMaybeCol loadObjectIdForAnyHashIdSql (Only h)
expectObjectIdForAnyHashId :: HashId -> Transaction ObjectId
expectObjectIdForAnyHashId h =
queryOneCol loadObjectIdForAnyHashIdSql (Only h)
loadObjectIdForAnyHashIdSql :: Sql
loadObjectIdForAnyHashIdSql =
[here| SELECT object_id FROM hash_object WHERE hash_id = ? |]
-- | Does a hash correspond to an object?
isObjectHash :: HashId -> Transaction Bool
isObjectHash h =
queryOneCol sql (Only h)
where
sql = [here|
SELECT EXISTS (SELECT 1 FROM object WHERE primary_hash_id = ?)
|]
-- | All objects have corresponding hashes.
expectPrimaryHashByObjectId :: ObjectId -> Transaction Hash
expectPrimaryHashByObjectId =
fmap Hash32.toHash . expectPrimaryHash32ByObjectId
expectPrimaryHash32ByObjectId :: ObjectId -> Transaction Hash32
expectPrimaryHash32ByObjectId oId = queryOneCol sql (Only oId)
where sql = [here|
SELECT hash.base32
FROM hash INNER JOIN object ON object.primary_hash_id = hash.id
WHERE object.id = ?
|]
expectHashIdsForObject :: ObjectId -> Transaction (List.NonEmpty HashId)
expectHashIdsForObject oId = do
primaryHashId <- queryOneCol sql1 (Only oId)
hashIds <- queryListCol sql2 (Only oId)
pure $ primaryHashId Nel.:| filter (/= primaryHashId) hashIds
where
sql1 = "SELECT primary_hash_id FROM object WHERE id = ?"
sql2 = "SELECT hash_id FROM hash_object WHERE object_id = ?"
hashIdWithVersionForObject :: ObjectId -> Transaction [(HashId, HashVersion)]
hashIdWithVersionForObject = queryListRow sql . Only where sql = [here|
SELECT hash_id, hash_version FROM hash_object WHERE object_id = ?
|]
-- | @recordObjectRehash old new@ records that object @old@ was rehashed and inserted as a new object, @new@.
--
-- This function rewrites @old@'s @hash_object@ rows in place to point at the new object.
recordObjectRehash :: ObjectId -> ObjectId -> Transaction ()
recordObjectRehash old new =
execute sql (new, old)
where
sql = [here|
UPDATE hash_object
SET object_id = ?
WHERE object_id = ?
|]
-- |Maybe we would generalize this to something other than NamespaceHash if we
-- end up wanting to store other kinds of Causals here too.
saveCausal ::
HashHandle ->
CausalHashId ->
BranchHashId ->
[CausalHashId] ->
Transaction ()
saveCausal hh self value parents = do
execute insertCausalSql (self, value)
rowsModified >>= \case
0 -> pure ()
_ -> do
executeMany insertCausalParentsSql (fmap (self,) parents)
flushCausalDependents hh self
where
insertCausalSql = [here|
INSERT INTO causal (self_hash_id, value_hash_id)
VALUES (?, ?)
ON CONFLICT DO NOTHING
|]
insertCausalParentsSql = [here|
INSERT INTO causal_parent (causal_id, parent_id) VALUES (?, ?)
|]
flushCausalDependents ::
HashHandle ->
CausalHashId ->
Transaction ()
flushCausalDependents hh chId = do
hash <- expectHash32 (unCausalHashId chId)
tryMoveTempEntityDependents hh hash
-- | `tryMoveTempEntityDependents #foo` does this:
-- 0. Precondition: We just inserted object #foo.
-- 1. Look up the dependents of #foo
-- 2. Delete #foo as dependency from temp_entity_missing_dependency. e.g. (#bar, #foo), (#baz, #foo)
-- 3. For each like #bar and #baz with no more rows in temp_entity_missing_dependency,
-- insert_entity them.
tryMoveTempEntityDependents ::
HashHandle ->
Hash32 ->
Transaction ()
tryMoveTempEntityDependents hh dependency = do
dependents <-
queryListCol
[here|
DELETE FROM temp_entity_missing_dependency
WHERE dependency = ?
RETURNING dependent
|]
(Only dependency)
traverse_ flushIfReadyToFlush dependents
where
flushIfReadyToFlush :: Hash32 -> Transaction ()
flushIfReadyToFlush dependent = do
readyToFlush dependent >>= \case
True -> moveTempEntityToMain hh dependent
False -> pure ()
readyToFlush :: Hash32 -> Transaction Bool
readyToFlush hash = queryOneCol [here|
SELECT EXISTS (
SELECT 1
FROM temp_entity
WHERE hash = ?
) AND NOT EXISTS (
SELECT 1
FROM temp_entity_missing_dependency
WHERE dependent = ?
)
|] (hash, hash)
expectCausal :: CausalHashId -> Transaction Causal.SyncCausalFormat
expectCausal hashId = do
valueHash <-
queryOneCol
[here|
SELECT value_hash_id
FROM causal
WHERE self_hash_id = ?
|]
(Only hashId)
parents <-
fmap Vector.fromList do
-- is the random ordering from the database ok? (seems so, for now)
queryListCol
[here|
SELECT parent_id
FROM causal_parent
WHERE causal_id = ?
|]
(Only hashId)
pure Causal.SyncCausalFormat {parents, valueHash}
-- | Read an entity out of main storage.
expectEntity :: Hash32 -> Transaction SyncEntity
expectEntity hash = do
hashId <- expectHashId hash
-- We don't know if this is an object or a causal, so just try one, then the other.
loadObjectIdForPrimaryHashId hashId >>= \case
Nothing -> Entity.C <$> expectCausal (CausalHashId hashId)
Just objectId ->
expectObjectWithType objectId \typ bytes ->
case typ of
TermComponent -> Entity.TC <$> decodeSyncTermFormat bytes
DeclComponent -> Entity.DC <$> decodeSyncDeclFormat bytes
Namespace -> Entity.N <$> decodeSyncNamespaceFormat bytes
Patch -> Entity.P <$> decodeSyncPatchFormat bytes
-- | Read an entity out of temp storage.
expectTempEntity :: Hash32 -> Transaction TempEntity
expectTempEntity hash = do
queryOneRowCheck sql (Only hash) \(blob, typeId) ->
case typeId of
TempEntityType.TermComponentType -> Entity.TC <$> decodeTempTermFormat blob
TempEntityType.DeclComponentType -> Entity.DC <$> decodeTempDeclFormat blob
TempEntityType.NamespaceType -> Entity.N <$> decodeTempNamespaceFormat blob
TempEntityType.PatchType -> Entity.P <$> decodeTempPatchFormat blob
TempEntityType.CausalType -> Entity.C <$> decodeTempCausalFormat blob
where sql = [here|
SELECT blob, type_id
FROM temp_entity
WHERE hash = ?
|]
{- ORMOLU_ENABLE -}
-- | look up all of the input entity's dependencies in the main table, to convert it to a sync entity
tempToSyncEntity :: TempEntity -> Transaction SyncEntity
tempToSyncEntity = \case
Entity.TC term -> Entity.TC <$> tempToSyncTermComponent term
Entity.DC decl -> Entity.DC <$> tempToSyncDeclComponent decl
Entity.N namespace -> Entity.N <$> tempToSyncNamespace namespace
Entity.P patch -> Entity.P <$> tempToSyncPatch patch
Entity.C causal -> Entity.C <$> tempToSyncCausal causal
where
tempToSyncCausal :: TempEntity.TempCausalFormat -> Transaction Causal.SyncCausalFormat
tempToSyncCausal Causal.SyncCausalFormat {valueHash, parents} =
Causal.SyncCausalFormat
<$> expectBranchHashIdForHash32 valueHash
<*> traverse expectCausalHashIdForHash32 parents
tempToSyncDeclComponent :: TempEntity.TempDeclFormat -> Transaction DeclFormat.SyncDeclFormat
tempToSyncDeclComponent = \case
DeclFormat.SyncDecl (DeclFormat.SyncLocallyIndexedComponent decls) ->
DeclFormat.SyncDecl . DeclFormat.SyncLocallyIndexedComponent
<$> Lens.traverseOf
(traverse . Lens._1)
( \LocalIds.LocalIds {textLookup, defnLookup} ->
LocalIds.LocalIds
<$> saveTexts textLookup
<*> traverse expectObjectIdForHash32 defnLookup
)
decls
tempToSyncNamespace :: TempEntity.TempNamespaceFormat -> Transaction NamespaceFormat.SyncBranchFormat
tempToSyncNamespace = \case
NamespaceFormat.SyncFull localIds bytes ->
NamespaceFormat.SyncFull <$> tempToSyncNamespaceLocalIds localIds <*> pure bytes
NamespaceFormat.SyncDiff parent localIds bytes ->
NamespaceFormat.SyncDiff
<$> expectBranchObjectIdForHash32 parent
<*> tempToSyncNamespaceLocalIds localIds
<*> pure bytes
tempToSyncNamespaceLocalIds :: TempEntity.TempNamespaceLocalIds -> Transaction NamespaceFormat.BranchLocalIds
tempToSyncNamespaceLocalIds (NamespaceFormat.LocalIds texts defns patches children) =
NamespaceFormat.LocalIds
<$> saveTexts texts
<*> traverse expectObjectIdForHash32 defns
<*> traverse expectPatchObjectIdForHash32 patches
<*> traverse
( \(branch, causal) ->
(,)
<$> expectBranchObjectIdForHash32 branch
<*> expectCausalHashIdForHash32 causal
)
children
tempToSyncPatch :: TempEntity.TempPatchFormat -> Transaction PatchFormat.SyncPatchFormat
tempToSyncPatch = \case
PatchFormat.SyncFull localIds bytes -> PatchFormat.SyncFull <$> tempToSyncPatchLocalIds localIds <*> pure bytes
PatchFormat.SyncDiff parent localIds bytes ->
PatchFormat.SyncDiff
<$> expectPatchObjectIdForHash32 parent
<*> tempToSyncPatchLocalIds localIds
<*> pure bytes
tempToSyncPatchLocalIds :: TempEntity.TempPatchLocalIds -> Transaction PatchFormat.PatchLocalIds
tempToSyncPatchLocalIds (PatchFormat.LocalIds texts hashes defns) =
PatchFormat.LocalIds
<$> saveTexts texts
<*> saveHashes hashes
<*> traverse expectObjectIdForHash32 defns
tempToSyncTermComponent :: TempEntity.TempTermFormat -> Transaction TermFormat.SyncTermFormat
tempToSyncTermComponent = \case
TermFormat.SyncTerm (TermFormat.SyncLocallyIndexedComponent terms) ->
TermFormat.SyncTerm . TermFormat.SyncLocallyIndexedComponent
<$> Lens.traverseOf
(traverse . Lens._1)
( \LocalIds.LocalIds {textLookup, defnLookup} ->
LocalIds.LocalIds
<$> saveTexts textLookup
<*> traverse expectObjectIdForHash32 defnLookup
)
terms
{- ORMOLU_DISABLE -}
-- | looking up all of the text and hashes is the first step of converting a SyncEntity to a Share.Entity
syncToTempEntity :: SyncEntity -> Transaction TempEntity
syncToTempEntity = \case
Entity.TC term -> Entity.TC <$> syncToTempTermComponent term
Entity.DC decl -> Entity.DC <$> syncToTempDeclComponent decl
Entity.N namespace -> Entity.N <$> syncToTempNamespace namespace
Entity.P patch -> Entity.P <$> syncToTempPatch patch
Entity.C causal -> Entity.C <$> syncToTempCausal causal
where
syncToTempCausal :: Causal.SyncCausalFormat -> Transaction TempEntity.TempCausalFormat
syncToTempCausal Causal.SyncCausalFormat {valueHash, parents} =
Causal.SyncCausalFormat
<$> expectHash32 (unBranchHashId valueHash)
<*> traverse (expectHash32 . unCausalHashId) parents
syncToTempDeclComponent :: DeclFormat.SyncDeclFormat -> Transaction TempEntity.TempDeclFormat
syncToTempDeclComponent = \case
DeclFormat.SyncDecl (DeclFormat.SyncLocallyIndexedComponent decls) ->
DeclFormat.SyncDecl . DeclFormat.SyncLocallyIndexedComponent
<$> Lens.traverseOf (traverse . Lens._1) (bitraverse expectText expectPrimaryHash32ByObjectId) decls
syncToTempNamespace :: NamespaceFormat.SyncBranchFormat -> Transaction TempEntity.TempNamespaceFormat
syncToTempNamespace = \case
NamespaceFormat.SyncFull localIds bytes ->
NamespaceFormat.SyncFull <$> syncToTempNamespaceLocalIds localIds <*> pure bytes
NamespaceFormat.SyncDiff parent localIds bytes ->
NamespaceFormat.SyncDiff
<$> expectPrimaryHash32ByObjectId (unBranchObjectId parent)
<*> syncToTempNamespaceLocalIds localIds
<*> pure bytes
syncToTempNamespaceLocalIds :: NamespaceFormat.BranchLocalIds -> Transaction TempEntity.TempNamespaceLocalIds
syncToTempNamespaceLocalIds (NamespaceFormat.LocalIds texts defns patches children) =
NamespaceFormat.LocalIds
<$> traverse expectText texts
<*> traverse expectPrimaryHash32ByObjectId defns
<*> traverse (expectPrimaryHash32ByObjectId . unPatchObjectId) patches
<*> traverse
( \(branch, causal) ->
(,)
<$> expectPrimaryHash32ByObjectId (unBranchObjectId branch)
<*> expectHash32 (unCausalHashId causal)
)
children
syncToTempPatch :: PatchFormat.SyncPatchFormat -> Transaction TempEntity.TempPatchFormat
syncToTempPatch = \case
PatchFormat.SyncFull localIds bytes -> PatchFormat.SyncFull <$> syncToTempPatchLocalIds localIds <*> pure bytes
PatchFormat.SyncDiff parent localIds bytes ->
PatchFormat.SyncDiff
<$> expectPrimaryHash32ByObjectId (unPatchObjectId parent)
<*> syncToTempPatchLocalIds localIds
<*> pure bytes
syncToTempPatchLocalIds :: PatchFormat.PatchLocalIds -> Transaction TempEntity.TempPatchLocalIds
syncToTempPatchLocalIds (PatchFormat.LocalIds texts hashes defns) =
PatchFormat.LocalIds
<$> traverse expectText texts
<*> traverse expectHash32 hashes
<*> traverse expectPrimaryHash32ByObjectId defns
syncToTempTermComponent :: TermFormat.SyncTermFormat -> Transaction TempEntity.TempTermFormat
syncToTempTermComponent = \case
TermFormat.SyncTerm (TermFormat.SyncLocallyIndexedComponent terms) ->
TermFormat.SyncTerm . TermFormat.SyncLocallyIndexedComponent
<$> Lens.traverseOf (traverse . Lens._1) (bitraverse expectText expectPrimaryHash32ByObjectId) terms
-- -- maybe: look at whether parent causal is "committed"; if so, then increment;
-- -- otherwise, don't.
-- getNurseryGeneration :: DB m => m Generation
-- getNurseryGeneration = query_ sql <&> \case
-- [] -> Generation 0
-- [fromOnly -> g] -> Generation $ fromMaybe 0 g
-- (fmap fromOnly -> gs) ->
-- error $ "How did I get multiple values out of a MAX()? " ++ show gs
-- where sql = [here|
-- SELECT MAX(gc_generation) FROM causal;
-- |]
expectCausalValueHashId :: CausalHashId -> Transaction BranchHashId
expectCausalValueHashId (CausalHashId id) =
queryOneCol loadCausalValueHashIdSql (Only id)
expectCausalHash :: CausalHashId -> Transaction CausalHash
expectCausalHash = coerce expectHash
loadCausalValueHashId :: HashId -> Transaction (Maybe BranchHashId)
loadCausalValueHashId id =
queryMaybeCol loadCausalValueHashIdSql (Only id)
loadCausalValueHashIdSql :: Sql
loadCausalValueHashIdSql =
[here| SELECT value_hash_id FROM causal WHERE self_hash_id = ? |]
isCausalHash :: HashId -> Transaction Bool
isCausalHash = queryOneCol sql . Only where sql = [here|
SELECT EXISTS (SELECT 1 FROM causal WHERE self_hash_id = ?)
|]
loadBranchObjectIdByCausalHashId :: CausalHashId -> Transaction (Maybe BranchObjectId)
loadBranchObjectIdByCausalHashId id = queryMaybeCol loadBranchObjectIdByCausalHashIdSql (Only id)
expectBranchObjectIdByCausalHashId :: CausalHashId -> Transaction BranchObjectId
expectBranchObjectIdByCausalHashId id = queryOneCol loadBranchObjectIdByCausalHashIdSql (Only id)
loadBranchObjectIdByCausalHashIdSql :: Sql
loadBranchObjectIdByCausalHashIdSql =