-
-
Notifications
You must be signed in to change notification settings - Fork 532
/
Copy pathdoltdb.go
2295 lines (1908 loc) · 68.1 KB
/
doltdb.go
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 2019 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doltdb
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/dolthub/go-mysql-server/sql"
"github.com/sirupsen/logrus"
"github.com/dolthub/dolt/go/libraries/doltcore/dbfactory"
"github.com/dolthub/dolt/go/libraries/doltcore/ref"
"github.com/dolthub/dolt/go/libraries/utils/earl"
"github.com/dolthub/dolt/go/libraries/utils/filesys"
"github.com/dolthub/dolt/go/store/chunks"
"github.com/dolthub/dolt/go/store/datas"
"github.com/dolthub/dolt/go/store/datas/pull"
"github.com/dolthub/dolt/go/store/hash"
"github.com/dolthub/dolt/go/store/nbs"
"github.com/dolthub/dolt/go/store/prolly"
"github.com/dolthub/dolt/go/store/prolly/tree"
"github.com/dolthub/dolt/go/store/types"
"github.com/dolthub/dolt/go/store/types/edits"
)
func init() {
types.CreateEditAccForMapEdits = edits.NewAsyncSortedEditsWithDefaults
}
// WORKING and STAGED identifiers refer to the working and staged roots in special circumstances where
// we expect to resolve a commit spec, but need working or staged
const (
Working = "WORKING"
Staged = "STAGED"
)
const (
CreationBranch = "create"
defaultChunksPerTF = 256 * 1024
)
var ErrMissingDoltDataDir = errors.New("missing dolt data directory")
// LocalDirDoltDB stores the db in the current directory
var LocalDirDoltDB = "file://./" + dbfactory.DoltDataDir
var LocalDirStatsDB = "file://./" + dbfactory.DoltStatsDir
// InMemDoltDB stores the DoltDB db in memory and is primarily used for testing
var InMemDoltDB = "mem://"
var ErrNoRootValAtHash = errors.New("there is no dolt root value at that hash")
var ErrCannotDeleteLastBranch = errors.New("cannot delete the last branch")
// DoltDB wraps access to the underlying noms database and hides some of the details of the underlying storage.
type DoltDB struct {
db hooksDatabase
vrw types.ValueReadWriter
ns tree.NodeStore
// databaseName holds the name of the database for this DoltDB instance. Note that this name may not be
// populated for all DoltDB instances. For filesystem based databases, the database name is determined
// by looking through the filepath in reverse, finding the first .dolt directory, and then taking the
// parent directory as the database name. For non-filesystem based databases, the database name will not
// currently be populated.
databaseName string
}
// DoltDBFromCS creates a DoltDB from a noms chunks.ChunkStore
func DoltDBFromCS(cs chunks.ChunkStore, databaseName string) *DoltDB {
vrw := types.NewValueStore(cs)
ns := tree.NewNodeStore(cs)
db := datas.NewTypesDatabase(vrw, ns)
return &DoltDB{db: hooksDatabase{Database: db}, vrw: vrw, ns: ns, databaseName: databaseName}
}
// GetDatabaseName returns the name of the database.
// Note: This can return an empty string if the database name is not populated.
func (ddb *DoltDB) GetDatabaseName() string {
return ddb.databaseName
}
// HackDatasDatabaseFromDoltDB unwraps a DoltDB to a datas.Database.
// Deprecated: only for use in dolt migrate.
func HackDatasDatabaseFromDoltDB(ddb *DoltDB) datas.Database {
return ddb.db
}
// LoadDoltDB will acquire a reference to the underlying noms db. If the Location is InMemDoltDB then a reference
// to a newly created in memory database will be used. If the location is LocalDirDoltDB, the directory must exist or
// this returns nil.
func LoadDoltDB(ctx context.Context, nbf *types.NomsBinFormat, urlStr string, fs filesys.Filesys) (*DoltDB, error) {
return LoadDoltDBWithParams(ctx, nbf, urlStr, fs, nil)
}
func LoadDoltDBWithParams(ctx context.Context, nbf *types.NomsBinFormat, urlStr string, fs filesys.Filesys, params map[string]interface{}) (*DoltDB, error) {
if urlStr == LocalDirDoltDB {
exists, isDir := fs.Exists(dbfactory.DoltDataDir)
if !exists {
return nil, ErrMissingDoltDataDir
} else if !isDir {
return nil, errors.New("file exists where the dolt data directory should be")
}
absPath, err := fs.Abs(dbfactory.DoltDataDir)
if err != nil {
return nil, err
}
urlStr = earl.FileUrlFromPath(filepath.ToSlash(absPath), os.PathSeparator)
if params == nil {
params = make(map[string]any)
}
params[dbfactory.ChunkJournalParam] = struct{}{}
}
// Pull the database name out of the URL string. For filesystem-based databases (e.g. in-memory or disk-based
// filesystem implementations), we can determine the database name by looking at the filesystem path. This
// won't work for other storage schemes though.
name := findParentDirectory(urlStr, ".dolt")
db, vrw, ns, err := dbfactory.CreateDB(ctx, nbf, urlStr, params)
if err != nil {
return nil, err
}
return &DoltDB{db: hooksDatabase{Database: db}, vrw: vrw, ns: ns, databaseName: name}, nil
}
// NomsRoot returns the hash of the noms dataset map
func (ddb *DoltDB) NomsRoot(ctx context.Context) (hash.Hash, error) {
return datas.ChunkStoreFromDatabase(ddb.db).Root(ctx)
}
func (ddb *DoltDB) AccessMode() chunks.ExclusiveAccessMode {
return datas.ChunkStoreFromDatabase(ddb.db).AccessMode()
}
// CommitRoot executes a chunkStore commit, atomically swapping the root hash of the database manifest
func (ddb *DoltDB) CommitRoot(ctx context.Context, current, last hash.Hash) (bool, error) {
return datas.ChunkStoreFromDatabase(ddb.db).Commit(ctx, current, last)
}
func (ddb *DoltDB) Has(ctx context.Context, h hash.Hash) (bool, error) {
return datas.ChunkStoreFromDatabase(ddb.db).Has(ctx, h)
}
func (ddb *DoltDB) CSMetricsSummary() string {
return datas.GetCSStatSummaryForDB(ddb.db)
}
// WriteEmptyRepo will create initialize the given db with a master branch which points to a commit which has valid
// metadata for the creation commit, and an empty RootValue.
func (ddb *DoltDB) WriteEmptyRepo(ctx context.Context, initBranch, name, email string) error {
return ddb.WriteEmptyRepoWithCommitMetaGenerator(ctx, initBranch, datas.MakeCommitMetaGenerator(name, email, datas.CommitterDate()))
}
func (ddb *DoltDB) WriteEmptyRepoWithCommitMetaGenerator(ctx context.Context, initBranch string, commitMeta datas.CommitMetaGenerator) error {
return ddb.WriteEmptyRepoWithCommitMetaGeneratorAndDefaultBranch(ctx, commitMeta, ref.NewBranchRef(initBranch))
}
func (ddb *DoltDB) WriteEmptyRepoWithCommitTimeAndDefaultBranch(
ctx context.Context,
name, email string,
t time.Time,
init ref.BranchRef,
) error {
return ddb.WriteEmptyRepoWithCommitMetaGeneratorAndDefaultBranch(ctx, datas.MakeCommitMetaGenerator(name, email, t), init)
}
func (ddb *DoltDB) WriteEmptyRepoWithCommitMetaGeneratorAndDefaultBranch(
ctx context.Context,
commitMetaGenerator datas.CommitMetaGenerator,
init ref.BranchRef,
) error {
ds, err := ddb.db.GetDataset(ctx, CreationBranch)
if err != nil {
return err
}
if ds.HasHead() {
return errors.New("database already exists")
}
rv, err := EmptyRootValue(ctx, ddb.vrw, ddb.ns)
if err != nil {
return err
}
rv, _, err = ddb.WriteRootValue(ctx, rv)
if err != nil {
return err
}
var firstCommit *datas.Commit
for {
cm, err := commitMetaGenerator.Next()
if err != nil {
return err
}
commitOpts := datas.CommitOptions{Meta: cm}
cb := ref.NewInternalRef(CreationBranch)
ds, err = ddb.db.GetDataset(ctx, cb.String())
if err != nil {
return err
}
firstCommit, err = ddb.db.BuildNewCommit(ctx, ds, rv.NomsValue(), commitOpts)
if err != nil {
return err
}
if commitMetaGenerator.IsGoodCommit(firstCommit) {
break
}
}
firstCommitDs, err := ddb.db.WriteCommit(ctx, ds, firstCommit)
if err != nil {
return err
}
ds, err = ddb.db.GetDataset(ctx, init.String())
if err != nil {
return err
}
headAddr, ok := firstCommitDs.MaybeHeadAddr()
if !ok {
return errors.New("commit without head")
}
_, err = ddb.db.SetHead(ctx, ds, headAddr, "")
return err
}
func (ddb *DoltDB) Close() error {
return ddb.db.Close()
}
// GetHashForRefStr resolves a ref string (such as a branch name or tag) and resolves it to a hash.Hash.
func (ddb *DoltDB) GetHashForRefStr(ctx context.Context, ref string) (*hash.Hash, error) {
if err := datas.ValidateDatasetId(ref); err != nil {
return nil, fmt.Errorf("invalid ref format: %s", ref)
}
ds, err := ddb.db.GetDataset(ctx, ref)
if err != nil {
return nil, err
}
return hashOfCommit(ds, ref)
}
func (ddb *DoltDB) GetHashForRefStrByNomsRoot(ctx context.Context, ref string, nomsRoot hash.Hash) (*hash.Hash, error) {
if err := datas.ValidateDatasetId(ref); err != nil {
return nil, fmt.Errorf("invalid ref format: %s", ref)
}
ds, err := ddb.db.GetDatasetByRootHash(ctx, ref, nomsRoot)
if err != nil {
return nil, err
}
return hashOfCommit(ds, ref)
}
// hashOfCommit returns the hash of the commit at the head of the dataset provided
func hashOfCommit(ds datas.Dataset, ref string) (*hash.Hash, error) {
if !ds.HasHead() {
return nil, ErrBranchNotFound
}
if ds.IsTag() {
_, commitHash, err := ds.HeadTag()
if err != nil {
return nil, err
}
return &commitHash, nil
} else {
commitHash, ok := ds.MaybeHeadAddr()
if !ok {
return nil, fmt.Errorf("Unable to load head for %s", ref)
}
return &commitHash, nil
}
}
func getCommitValForRefStr(ctx context.Context, ddb *DoltDB, ref string) (*datas.Commit, error) {
commitHash, err := ddb.GetHashForRefStr(ctx, ref)
if err != nil {
return nil, err
}
return datas.LoadCommitAddr(ctx, ddb.vrw, *commitHash)
}
func getCommitValForRefStrByNomsRoot(ctx context.Context, ddb *DoltDB, ref string, nomsRoot hash.Hash) (*datas.Commit, error) {
commitHash, err := ddb.GetHashForRefStrByNomsRoot(ctx, ref, nomsRoot)
if err != nil {
return nil, err
}
return datas.LoadCommitAddr(ctx, ddb.vrw, *commitHash)
}
// findParentDirectory searches the components of the specified |path| looking for a directory
// named |targetDir| and returns the name of the parent directory for |targetDir|. The search
// starts from the deepest component of |path|, so if |path| contains |targetDir| multiple times,
// the parent directory of the last occurrence in |path| is returned.
func findParentDirectory(path string, targetDir string) string {
base := filepath.Base(path)
dir := filepath.Dir(path)
if base == "." || dir == "." {
return ""
}
switch base {
case "":
return base
case targetDir:
return filepath.Base(dir)
default:
return findParentDirectory(dir, targetDir)
}
}
// Roots is a convenience struct to package up the three roots that most library functions will need to inspect and
// modify the working set. This struct is designed to be passed by value always: functions should take a Roots as a
// param and return a modified one.
//
// It contains three root values:
// Head: The root of the head of the current working branch
// Working: The root of the current working set
// Staged: The root of the staged value
//
// See doltEnvironment.Roots(context.Context)
type Roots struct {
Head RootValue
Working RootValue
Staged RootValue
}
func (ddb *DoltDB) getHashFromCommitSpec(ctx context.Context, cs *CommitSpec, cwb ref.DoltRef, nomsRoot hash.Hash) (*hash.Hash, error) {
switch cs.csType {
case hashCommitSpec:
parsedHash, ok := hash.MaybeParse(cs.baseSpec)
if !ok {
return nil, errors.New("invalid hash: " + cs.baseSpec)
}
return &parsedHash, nil
case refCommitSpec:
// For a ref in a CommitSpec, we have the following behavior.
// If it starts with `refs/`, we look for an exact match before
// we try any suffix matches. After that, we try a match on the
// user supplied input, with the following four prefixes, in
// order: `refs/`, `refs/heads/`, `refs/tags/`, `refs/remotes/`.
candidates := []string{
"refs/" + cs.baseSpec,
"refs/heads/" + cs.baseSpec,
"refs/tags/" + cs.baseSpec,
"refs/remotes/" + cs.baseSpec,
}
if strings.HasPrefix(cs.baseSpec, "refs/") {
candidates = []string{
cs.baseSpec,
"refs/" + cs.baseSpec,
"refs/heads/" + cs.baseSpec,
"refs/tags/" + cs.baseSpec,
"refs/remotes/" + cs.baseSpec,
}
}
for _, candidate := range candidates {
var valueHash *hash.Hash
var err error
if nomsRoot.IsEmpty() {
valueHash, err = ddb.GetHashForRefStr(ctx, candidate)
} else {
valueHash, err = ddb.GetHashForRefStrByNomsRoot(ctx, candidate, nomsRoot)
}
if err == nil {
return valueHash, nil
}
if err != ErrBranchNotFound {
return nil, err
}
}
return nil, fmt.Errorf("%w: %s", ErrBranchNotFound, cs.baseSpec)
case headCommitSpec:
if cwb == nil {
return nil, fmt.Errorf("cannot use a nil current working branch with a HEAD commit spec")
}
if nomsRoot.IsEmpty() {
return ddb.GetHashForRefStr(ctx, cwb.String())
} else {
return ddb.GetHashForRefStrByNomsRoot(ctx, cwb.String(), nomsRoot)
}
default:
panic("unrecognized commit spec csType: " + cs.csType)
}
}
// Resolve takes a CommitSpec and returns a Commit, or an error if the commit cannot be found.
// If the CommitSpec is HEAD, Resolve also needs the DoltRef of the current working branch.
func (ddb *DoltDB) Resolve(ctx context.Context, cs *CommitSpec, cwb ref.DoltRef) (*OptionalCommit, error) {
if cs == nil {
panic("nil commit spec")
}
hash, err := ddb.getHashFromCommitSpec(ctx, cs, cwb, hash.Hash{})
if err != nil {
return nil, err
}
commitValue, err := datas.LoadCommitAddr(ctx, ddb.vrw, *hash)
if err != nil {
return nil, err
}
if commitValue.IsGhost() {
return &OptionalCommit{nil, *hash}, nil
}
commit, err := NewCommit(ctx, ddb.vrw, ddb.ns, commitValue)
if err != nil {
return nil, err
}
return commit.GetAncestor(ctx, cs.aSpec)
}
// BootstrapShallowResolve is a special case of Resolve that is used to resolve a commit prior to pulling it's history
// in a shallow clone. In general, application code should call Resolve and get an OptionalCommit. This is a special case
// where we need to get the head commit for the commit closure used to determine what commits should skipped.
func (ddb *DoltDB) BootstrapShallowResolve(ctx context.Context, cs *CommitSpec) (prolly.CommitClosure, error) {
if cs == nil {
panic("nil commit spec")
}
hash, err := ddb.getHashFromCommitSpec(ctx, cs, nil, hash.Hash{})
if err != nil {
return prolly.CommitClosure{}, err
}
commitValue, err := datas.LoadCommitAddr(ctx, ddb.vrw, *hash)
if err != nil {
return prolly.CommitClosure{}, err
}
if commitValue.IsGhost() {
return prolly.CommitClosure{}, ErrGhostCommitEncountered
}
return getCommitClosure(ctx, commitValue, ddb.vrw, ddb.ns)
}
func (ddb *DoltDB) ResolveByNomsRoot(ctx *sql.Context, cs *CommitSpec, cwb ref.DoltRef, root hash.Hash) (*OptionalCommit, error) {
if cs == nil {
panic("nil commit spec")
}
hash, err := ddb.getHashFromCommitSpec(ctx, cs, cwb, root)
if err != nil {
return nil, err
}
commitValue, err := datas.LoadCommitAddr(ctx, ddb.vrw, *hash)
if err != nil {
return nil, err
}
if commitValue.IsGhost() {
return &OptionalCommit{nil, *hash}, nil
}
commit, err := NewCommit(ctx, ddb.vrw, ddb.ns, commitValue)
if err != nil {
return nil, err
}
return commit.GetAncestor(ctx, cs.aSpec)
}
// ResolveCommitRef takes a DoltRef and returns a Commit, or an error if the commit cannot be found. The ref given must
// point to a Commit.
func (ddb *DoltDB) ResolveCommitRef(ctx context.Context, ref ref.DoltRef) (*Commit, error) {
commitVal, err := getCommitValForRefStr(ctx, ddb, ref.String())
if err != nil {
return nil, err
}
if commitVal.IsGhost() {
return nil, ErrGhostCommitEncountered
}
return NewCommit(ctx, ddb.vrw, ddb.ns, commitVal)
}
// ResolveCommitRefAtRoot takes a DoltRef and returns a Commit, or an error if the commit cannot be found. The ref given must
// point to a Commit.
func (ddb *DoltDB) ResolveCommitRefAtRoot(ctx context.Context, ref ref.DoltRef, nomsRoot hash.Hash) (*Commit, error) {
commitVal, err := getCommitValForRefStrByNomsRoot(ctx, ddb, ref.String(), nomsRoot)
if err != nil {
return nil, err
}
if commitVal.IsGhost() {
return nil, ErrGhostCommitEncountered
}
return NewCommit(ctx, ddb.vrw, ddb.ns, commitVal)
}
// ResolveBranchRoots returns the Roots for the branch given
func (ddb *DoltDB) ResolveBranchRoots(ctx context.Context, branch ref.BranchRef) (Roots, error) {
commitRef, err := ddb.ResolveCommitRef(ctx, branch)
if err != nil {
return Roots{}, err
}
headRoot, err := commitRef.GetRootValue(ctx)
if err != nil {
return Roots{}, err
}
wsRef, err := ref.WorkingSetRefForHead(branch)
if err != nil {
return Roots{}, err
}
ws, err := ddb.ResolveWorkingSet(ctx, wsRef)
if err != nil {
return Roots{}, err
}
return Roots{
Head: headRoot,
Working: ws.WorkingRoot(),
Staged: ws.StagedRoot(),
}, nil
}
// ResolveTag takes a TagRef and returns the corresponding Tag object.
func (ddb *DoltDB) ResolveTag(ctx context.Context, tagRef ref.TagRef) (*Tag, error) {
ds, err := ddb.db.GetDataset(ctx, tagRef.String())
if err != nil {
return nil, ErrTagNotFound
}
if !ds.HasHead() {
return nil, ErrTagNotFound
}
if !ds.IsTag() {
return nil, fmt.Errorf("tagRef head is not a tag")
}
return NewTag(ctx, tagRef.GetPath(), ds, ddb.vrw, ddb.ns)
}
// TagResolver is used to late load tag metadata resolution. There are situations where we need to list all the tags, but
// don't necessarily need to load their metadata. See GetTagResolvers
type TagResolver struct {
ddb *DoltDB
ref ref.TagRef
h hash.Hash
}
// Addr returns the hash of the object storing the Tag data. It is loaded and deserialize by the Resolve method.
func (tr *TagResolver) Addr() hash.Hash {
return tr.h
}
// Resolve resolves the tag reference to a *Tag, complete with its metadata.
func (tr *TagResolver) Resolve(ctx context.Context) (*Tag, error) {
return tr.ddb.ResolveTag(ctx, tr.ref)
}
// GetTagResolvers takes a slice of TagRefs and returns the corresponding Tag objects.
func (ddb *DoltDB) GetTagResolvers(ctx context.Context, tagRefs []ref.DoltRef) ([]TagResolver, error) {
datasets, err := ddb.db.Datasets(ctx)
if err != nil {
return nil, err
}
tagMap := make(map[string]ref.TagRef)
for _, tagRef := range tagRefs {
if tr, ok := tagRef.(ref.TagRef); ok {
tagMap[tagRef.String()] = tr
} else {
panic(fmt.Sprintf("runtime error: expected TagRef, got %T", tagRef))
}
}
results := make([]TagResolver, 0, len(tagRefs))
err = datasets.IterAll(ctx, func(id string, addr hash.Hash) error {
if val, ok := tagMap[id]; ok {
tr := TagResolver{ddb: ddb, ref: val, h: addr}
results = append(results, tr)
}
return nil
})
if err != nil {
return nil, err
}
return results, nil
}
// ResolveWorkingSet takes a WorkingSetRef and returns the corresponding WorkingSet object.
func (ddb *DoltDB) ResolveWorkingSet(ctx context.Context, workingSetRef ref.WorkingSetRef) (*WorkingSet, error) {
ds, err := ddb.db.GetDataset(ctx, workingSetRef.String())
if err != nil {
return nil, ErrWorkingSetNotFound
}
return ddb.workingSetFromDataset(ctx, workingSetRef, ds)
}
// ResolveWorkingSetAtRoot returns the working set object as it existed at the given root hash.
func (ddb *DoltDB) ResolveWorkingSetAtRoot(ctx context.Context, workingSetRef ref.WorkingSetRef, nomsRoot hash.Hash) (*WorkingSet, error) {
ds, err := ddb.db.GetDatasetByRootHash(ctx, workingSetRef.String(), nomsRoot)
if err != nil {
return nil, ErrWorkingSetNotFound
}
return ddb.workingSetFromDataset(ctx, workingSetRef, ds)
}
func (ddb *DoltDB) workingSetFromDataset(ctx context.Context, workingSetRef ref.WorkingSetRef, ds datas.Dataset) (*WorkingSet, error) {
if !ds.HasHead() {
return nil, ErrWorkingSetNotFound
}
if !ds.IsWorkingSet() {
return nil, fmt.Errorf("workingSetRef head is not a workingSetRef")
}
return newWorkingSet(ctx, workingSetRef.GetPath(), ddb.vrw, ddb.ns, ds)
}
// TODO: convenience method to resolve the head commit of a branch.
// WriteRootValue will write a doltdb.RootValue instance to the database. This
// value will not be associated with a commit and can be committed by hash at a
// later time. Returns an updated root value and the hash of the value
// written. This method is the primary place in doltcore that handles setting
// the FeatureVersion of root values to the current value, so all writes of
// RootValues should happen here.
func (ddb *DoltDB) WriteRootValue(ctx context.Context, rv RootValue) (RootValue, hash.Hash, error) {
nrv, ref, err := ddb.writeRootValue(ctx, rv)
if err != nil {
return nil, hash.Hash{}, err
}
return nrv, ref.TargetHash(), nil
}
func (ddb *DoltDB) writeRootValue(ctx context.Context, rv RootValue) (RootValue, types.Ref, error) {
rv, err := rv.SetFeatureVersion(DoltFeatureVersion)
if err != nil {
return nil, types.Ref{}, err
}
ref, err := ddb.vrw.WriteValue(ctx, rv.NomsValue())
if err != nil {
return nil, types.Ref{}, err
}
return rv, ref, nil
}
// Persists all relevant root values of the WorkingSet to the database and returns all hashes reachable
// from the working set. This is used in GC, for example, where all dependencies of the in-memory working
// set value need to be accounted for.
func (ddb *DoltDB) WorkingSetHashes(ctx context.Context, ws *WorkingSet) ([]hash.Hash, error) {
spec, err := ws.writeValues(ctx, ddb, nil)
if err != nil {
return nil, err
}
ret := make([]hash.Hash, 0)
ret = append(ret, spec.StagedRoot.TargetHash())
ret = append(ret, spec.WorkingRoot.TargetHash())
if spec.MergeState != nil {
fromCommit, err := spec.MergeState.FromCommit(ctx, ddb.vrw)
if err != nil {
return nil, err
}
h, err := fromCommit.NomsValue().Hash(ddb.db.Format())
if err != nil {
return nil, err
}
ret = append(ret, h)
h, err = spec.MergeState.PreMergeWorkingAddr(ctx, ddb.vrw)
ret = append(ret, h)
}
if spec.RebaseState != nil {
ret = append(ret, spec.RebaseState.PreRebaseWorkingAddr())
commit, err := spec.RebaseState.OntoCommit(ctx, ddb.vrw)
if err != nil {
return nil, err
}
h, err := commit.NomsValue().Hash(ddb.db.Format())
if err != nil {
return nil, err
}
ret = append(ret, h)
}
return ret, nil
}
// ReadRootValue reads the RootValue associated with the hash given and returns it. Returns an error if the value cannot
// be read, or if the hash given doesn't represent a dolt RootValue.
func (ddb *DoltDB) ReadRootValue(ctx context.Context, h hash.Hash) (RootValue, error) {
val, err := ddb.vrw.ReadValue(ctx, h)
if err != nil {
return nil, err
}
return decodeRootNomsValue(ctx, ddb.vrw, ddb.ns, val)
}
// ReadCommit reads the Commit whose hash is |h|, if one exists.
func (ddb *DoltDB) ReadCommit(ctx context.Context, h hash.Hash) (*OptionalCommit, error) {
c, err := datas.LoadCommitAddr(ctx, ddb.vrw, h)
if err != nil {
return nil, err
}
if c.IsGhost() {
return &OptionalCommit{nil, h}, nil
}
newC, err := NewCommit(ctx, ddb.vrw, ddb.ns, c)
if err != nil {
return nil, err
}
return &OptionalCommit{newC, h}, nil
}
// Commit will update a branch's head value to be that of a previously committed root value hash
func (ddb *DoltDB) Commit(ctx context.Context, valHash hash.Hash, dref ref.DoltRef, cm *datas.CommitMeta) (*Commit, error) {
return ddb.CommitWithParentSpecs(ctx, valHash, dref, nil, cm)
}
// FastForwardWithWorkspaceCheck will perform a fast forward update of the branch given to the commit given, but only
// if the working set is in sync with the head of the branch given. This is used in the course of pushing to a remote.
// If the target doesn't currently have the working set ref, then no working set change will be made.
func (ddb *DoltDB) FastForwardWithWorkspaceCheck(ctx context.Context, branch ref.DoltRef, commit *Commit) error {
ds, err := ddb.db.GetDataset(ctx, branch.String())
if err != nil {
return err
}
addr, err := commit.HashOf()
if err != nil {
return err
}
ws := ""
pushConcurrencyControl := chunks.GetPushConcurrencyControl(datas.ChunkStoreFromDatabase(ddb.db))
if pushConcurrencyControl == chunks.PushConcurrencyControl_AssertWorkingSet {
wsRef, err := ref.WorkingSetRefForHead(branch)
if err != nil {
return err
}
ws = wsRef.String()
}
_, err = ddb.db.FastForward(ctx, ds, addr, ws)
return err
}
// FastForward fast-forwards the branch given to the commit given.
func (ddb *DoltDB) FastForward(ctx context.Context, branch ref.DoltRef, commit *Commit) error {
addr, err := commit.HashOf()
if err != nil {
return err
}
return ddb.FastForwardToHash(ctx, branch, addr)
}
// FastForwardToHash fast-forwards the branch given to the commit hash given.
func (ddb *DoltDB) FastForwardToHash(ctx context.Context, branch ref.DoltRef, hash hash.Hash) error {
ds, err := ddb.db.GetDataset(ctx, branch.String())
if err != nil {
return err
}
_, err = ddb.db.FastForward(ctx, ds, hash, "")
return err
}
// CanFastForward returns whether the given branch can be fast-forwarded to the commit given.
func (ddb *DoltDB) CanFastForward(ctx context.Context, branch ref.DoltRef, new *Commit) (bool, error) {
current, err := ddb.ResolveCommitRef(ctx, branch)
if err != nil {
if err == ErrBranchNotFound {
return true, nil
}
return false, err
}
return current.CanFastForwardTo(ctx, new)
}
// SetHeadToCommit sets the given ref to point at the given commit. It is used in the course of 'force' updates.
func (ddb *DoltDB) SetHeadToCommit(ctx context.Context, ref ref.DoltRef, cm *Commit) error {
addr, err := cm.HashOf()
if err != nil {
return err
}
return ddb.SetHead(ctx, ref, addr)
}
// SetHeadAndWorkingSetToCommit sets the given ref to the given commit, and ensures that working is in sync
// with the head. Used for 'force' pushes.
func (ddb *DoltDB) SetHeadAndWorkingSetToCommit(ctx context.Context, rf ref.DoltRef, cm *Commit) error {
addr, err := cm.HashOf()
if err != nil {
return err
}
wsRef, err := ref.WorkingSetRefForHead(rf)
if err != nil {
return err
}
ds, err := ddb.db.GetDataset(ctx, rf.String())
if err != nil {
return err
}
_, err = ddb.db.SetHead(ctx, ds, addr, wsRef.String())
return err
}
func (ddb *DoltDB) SetHead(ctx context.Context, ref ref.DoltRef, addr hash.Hash) error {
ds, err := ddb.db.GetDataset(ctx, ref.String())
if err != nil {
return err
}
_, err = ddb.db.SetHead(ctx, ds, addr, "")
return err
}
// CommitWithParentSpecs commits the value hash given to the branch given, using the list of parent hashes given. Returns an
// error if the value or any parents can't be resolved, or if anything goes wrong accessing the underlying storage.
func (ddb *DoltDB) CommitWithParentSpecs(ctx context.Context, valHash hash.Hash, dref ref.DoltRef, parentCmSpecs []*CommitSpec, cm *datas.CommitMeta) (*Commit, error) {
var parentCommits []*Commit
for _, parentCmSpec := range parentCmSpecs {
cm, err := ddb.Resolve(ctx, parentCmSpec, nil)
if err != nil {
return nil, err
}
hardCommit, ok := cm.ToCommit()
if !ok {
return nil, ErrGhostCommitEncountered
}
parentCommits = append(parentCommits, hardCommit)
}
return ddb.CommitWithParentCommits(ctx, valHash, dref, parentCommits, cm)
}
func (ddb *DoltDB) CommitWithParentCommits(ctx context.Context, valHash hash.Hash, dref ref.DoltRef, parentCommits []*Commit, cm *datas.CommitMeta) (*Commit, error) {
val, err := ddb.vrw.ReadValue(ctx, valHash)
if err != nil {
return nil, err
}
if !isRootValue(ddb.vrw.Format(), val) {
return nil, errors.New("can't commit a value that is not a valid root value")
}
ds, err := ddb.db.GetDataset(ctx, dref.String())
if err != nil {
return nil, err
}
var parents []hash.Hash
headAddr, hasHead := ds.MaybeHeadAddr()
if err != nil {
return nil, err
}
if hasHead {
parents = append(parents, headAddr)
}
for _, cm := range parentCommits {
addr, err := cm.HashOf()
if err != nil {
return nil, err
}
if addr != headAddr {
parents = append(parents, addr)
}
}
commitOpts := datas.CommitOptions{Parents: parents, Meta: cm}
return ddb.CommitValue(ctx, dref, val, commitOpts)
}
func (ddb *DoltDB) CommitValue(ctx context.Context, dref ref.DoltRef, val types.Value, commitOpts datas.CommitOptions) (*Commit, error) {
ds, err := ddb.db.GetDataset(ctx, dref.String())
if err != nil {
return nil, err
}
ds, err = ddb.db.Commit(ctx, ds, val, commitOpts)
if err != nil {
return nil, err
}
r, ok, err := ds.MaybeHeadRef()
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("Commit has no head but commit succeeded. This is a bug.")
}
dc, err := datas.LoadCommitRef(ctx, ddb.vrw, r)
if err != nil {
return nil, err
}
if dc.IsGhost() {
return nil, ErrGhostCommitEncountered
}
return NewCommit(ctx, ddb.vrw, ddb.ns, dc)
}
// dangling commits are unreferenced by any branch or ref. They are created in the course of programmatic updates
// such as rebase. You must create a ref to a dangling commit for it to be reachable
func (ddb *DoltDB) CommitDanglingWithParentCommits(ctx context.Context, valHash hash.Hash, parentCommits []*Commit, cm *datas.CommitMeta) (*Commit, error) {
val, err := ddb.vrw.ReadValue(ctx, valHash)
if err != nil {
return nil, err
}
if !isRootValue(ddb.vrw.Format(), val) {
return nil, errors.New("can't commit a value that is not a valid root value")
}
var parents []hash.Hash
for _, cm := range parentCommits {
addr, err := cm.HashOf()
if err != nil {
return nil, err
}
parents = append(parents, addr)
}
commitOpts := datas.CommitOptions{Parents: parents, Meta: cm}