diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2024-01-06 11:15:53 -0500 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2024-01-06 11:15:53 -0500 |
| commit | 3d66d23b7f1f8d496711f01a164ac1d7717527ca (patch) | |
| tree | b4ce8a4deda41c57b1ab13ac4e89bfb9e6978cf0 /internal/storage/storage.go | |
| parent | Add to changelog (diff) | |
| download | cli-3d66d23b7f1f8d496711f01a164ac1d7717527ca.zip | |
Add database integration tests
Diffstat (limited to 'internal/storage/storage.go')
| -rw-r--r-- | internal/storage/storage.go | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/internal/storage/storage.go b/internal/storage/storage.go new file mode 100644 index 0000000..cd6e514 --- /dev/null +++ b/internal/storage/storage.go @@ -0,0 +1,40 @@ +package storage + +import ( + "database/sql" + "fmt" + + "github.com/eugenetriguba/bolt/internal/configloader" + _ "github.com/lib/pq" +) + +// DBConnect to the database using the driver and connection +// information. +func DBConnect(driver string, connectionInfo string) (*sql.DB, error) { + db, err := sql.Open(driver, connectionInfo) + if err != nil { + return nil, err + } + + // Note: `sql.Open` only validates the connection string we provided + // it is sane. It doesn't actually open up a connection to the database. + // For that, we ping the database to ensure the connection string is fully + // valid. + err = db.Ping() + if err != nil { + return nil, err + } + + return db, nil +} + +// DBConnectionString generates a properly formatted connection +// string to be passed to a database management system to initiate +// a connection. It uses the passed in configuration values to create +// the string. Note that sslmode is always disabled. +func DBConnectionString(cfg *configloader.ConnectionConfig) string { + return fmt.Sprintf( + "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", + cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, + ) +} |