MCPcopy Create free account
hub / github.com/dagger/dagger / Open

Method Open

engine/clientdb/dbs.go:47–126  ·  view source on GitHub ↗

Open open a database for the given clientID if not open already and runs the schema migration if needed.

(ctx context.Context, clientID string)

Source from the content-addressed store, hash-verified

45// Open open a database for the given clientID if not open already and
46// runs the schema migration if needed.
47func (dbs *DBs) Open(ctx context.Context, clientID string) (_ *DB, rerr error) {
48 lg := slog.Default().With("clientID", clientID)
49
50 dbs.perDBLock.Lock(clientID)
51 defer dbs.perDBLock.Unlock(clientID)
52
53 dbs.mu.Lock()
54 db, ok := dbs.open[clientID]
55 if !ok {
56 db = &DB{
57 dbs: dbs,
58 clientID: clientID,
59 }
60 dbs.open[clientID] = db
61 }
62 dbs.mu.Unlock()
63
64 db.refCount++ // increment now to handle case of context cancelled before we return
65 lg = lg.With("aquiredRefCount", db.refCount)
66 defer func() {
67 if rerr != nil {
68 rerr = errors.Join(rerr, dbs.close(db, lg))
69 }
70 }()
71
72 if db.inner == nil {
73 lg.ExtraDebug("opening client DB", "clientID", clientID)
74
75 dbPath := db.dbs.path(db.clientID)
76 if err := os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil {
77 return nil, fmt.Errorf("mkdir %s: %w", filepath.Dir(dbPath), err)
78 }
79
80 // check whether the file exists already
81 _, statErr := os.Lstat(dbPath)
82 alreadyExists := statErr == nil
83
84 connURL := &url.URL{
85 Scheme: "file",
86 Host: "",
87 Path: dbPath,
88 RawQuery: url.Values{
89 "_pragma": []string{
90 "foreign_keys=ON", // we don't use em yet, but makes sense anyway
91 "journal_mode=WAL", // readers don't block writers and vice versa
92 "synchronous=OFF", // we don't care about durability and don't want to be surprised by syncs
93 "busy_timeout=10000", // wait up to 10s when there are concurrent writers
94 },
95 "_txlock": []string{"immediate"}, // use BEGIN IMMEDIATE for transactions
96 }.Encode(),
97 }
98 sqlDB, err := sql.Open("sqlite", connURL.String())
99 if err != nil {
100 return nil, fmt.Errorf("open %s: %w", connURL, err)
101 }
102 if err := sqlDB.Ping(); err != nil {
103 return nil, fmt.Errorf("ping %s: %w", connURL, err)
104 }

Callers 2

TestDBRefCountFunction · 0.95
TestOpenWithNonDirRootFunction · 0.95

Calls 15

closeMethod · 0.95
DefaultFunction · 0.92
ExtraDebugMethod · 0.80
MkdirAllMethod · 0.80
LstatMethod · 0.80
TraceMethod · 0.80
PrepareFunction · 0.70
OpenMethod · 0.65
StringMethod · 0.65
PingMethod · 0.65
ExecMethod · 0.65
WithMethod · 0.45

Tested by 2

TestDBRefCountFunction · 0.76
TestOpenWithNonDirRootFunction · 0.76