Serge Bazanski | de4e841 | 2023-02-15 23:28:04 +0100 | [diff] [blame^] | 1 | package bmdb |
| 2 | |
| 3 | import ( |
| 4 | "database/sql" |
| 5 | "fmt" |
| 6 | |
| 7 | "k8s.io/klog/v2" |
| 8 | |
| 9 | "source.monogon.dev/cloud/bmaas/bmdb/model" |
| 10 | ) |
| 11 | |
| 12 | // Open creates a new Connection to the BMDB for the calling component. Multiple |
| 13 | // connections can be opened (although there is no advantage to doing so, as |
| 14 | // Connections manage an underlying CockroachDB connection pool, which performs |
| 15 | // required reconnects and connection pooling automatically). |
| 16 | func (b *BMDB) Open(migrate bool) (*Connection, error) { |
| 17 | if migrate { |
| 18 | if b.Config.Database.Migrations == nil { |
| 19 | klog.Infof("Using default migrations source.") |
| 20 | m, err := model.MigrationsSource() |
| 21 | if err != nil { |
| 22 | klog.Exitf("failed to prepare migrations source: %w", err) |
| 23 | } |
| 24 | b.Config.Database.Migrations = m |
| 25 | } |
| 26 | if err := b.Database.MigrateUp(); err != nil { |
| 27 | return nil, fmt.Errorf("migration failed: %w", err) |
| 28 | } |
| 29 | } |
| 30 | db, err := b.Database.Connect() |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | return &Connection{ |
| 35 | bmdb: b, |
| 36 | db: db, |
| 37 | |
| 38 | DatabaseName: b.Config.Database.DatabaseName, |
| 39 | Address: b.Config.Database.EndpointHost, |
| 40 | InMemory: b.Config.Database.InMemory, |
| 41 | }, nil |
| 42 | } |
| 43 | |
| 44 | // Connection to the BMDB. Internally, this contains a sql.DB connection pool, |
| 45 | // so components can (and likely should) reuse Connections as much as possible |
| 46 | // internally. |
| 47 | type Connection struct { |
| 48 | bmdb *BMDB |
| 49 | db *sql.DB |
| 50 | |
| 51 | // The database name that we're connected to. |
| 52 | DatabaseName string |
| 53 | // The address of the CockroachDB endpoint we've connected to. |
| 54 | Address string |
| 55 | // Whether this connection is to an in-memory database. Note: this only works if |
| 56 | // this Connection came directly from calling Open on a BMDB that was defined to |
| 57 | // be in-memory. If you just connect to an in-memory CRDB manually, this will |
| 58 | // still be false. |
| 59 | InMemory bool |
| 60 | } |