Open open a database for the given clientID if not open already and runs the schema migration if needed.
(ctx context.Context, clientID string)
| 45 | // Open open a database for the given clientID if not open already and |
| 46 | // runs the schema migration if needed. |
| 47 | func (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 | } |