aboutsummaryrefslogtreecommitdiffstats
path: root/internal/storage/db.go
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2024-01-06 16:23:02 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2024-01-06 16:23:02 -0500
commit263ce3e4b368a50efee1a53af11a76a12af0a119 (patch)
tree8917754f3b43830604f6ad4c7115934ed633f1d8 /internal/storage/db.go
parentFix syntax (diff)
downloadcli-263ce3e4b368a50efee1a53af11a76a12af0a119.zip
Break up migration repo into fs and db with a service
Diffstat (limited to 'internal/storage/db.go')
-rw-r--r--internal/storage/db.go41
1 files changed, 41 insertions, 0 deletions
diff --git a/internal/storage/db.go b/internal/storage/db.go
new file mode 100644
index 0000000..25db283
--- /dev/null
+++ b/internal/storage/db.go
@@ -0,0 +1,41 @@
+package storage
+
+import (
+ "database/sql"
+ "fmt"
+
+ "github.com/eugenetriguba/bolt/internal/configloader"
+ _ "github.com/lib/pq"
+)
+
+// DBConnect establishes a connection to the database using the driver
+// and connection information.
+//
+// Note that only "postgres" is supported as the driver right now.
+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 that can be used to establish a database connection.
+// Note that it always creates a connection string with sslmode 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,
+ )
+}