aboutsummaryrefslogtreecommitdiffstats
path: root/internal/db/db.go
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2023-12-30 16:00:20 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2023-12-30 16:00:20 -0500
commit809fc4639e58ca9ca082ce68b5c62b463b2f1e1d (patch)
tree1cb7b9951a80509b827b8e5bd1eb2dd09e87aec1 /internal/db/db.go
parentInitial Commit (diff)
downloadcli-809fc4639e58ca9ca082ce68b5c62b463b2f1e1d.zip
Add initial code
Diffstat (limited to 'internal/db/db.go')
-rw-r--r--internal/db/db.go48
1 files changed, 48 insertions, 0 deletions
diff --git a/internal/db/db.go b/internal/db/db.go
new file mode 100644
index 0000000..df5934c
--- /dev/null
+++ b/internal/db/db.go
@@ -0,0 +1,48 @@
+package db
+
+import (
+ "database/sql"
+ "fmt"
+
+ "github.com/eugenetriguba/bolt/internal/config"
+ _ "github.com/lib/pq"
+)
+
+var db *sql.DB
+
+// Connect to the database using the driver and connection
+// parameter that are specified in the bolt configuration file.
+//
+// Note that subsequent calls to Connect return the same database
+// handle.
+func Connect() (*sql.DB, error) {
+ if db == nil {
+ config, err := config.NewConfig()
+ if err != nil {
+ return nil, err
+ }
+
+ connInfo := fmt.Sprintf(
+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
+ config.Connection.Host, config.Connection.Port, config.Connection.User,
+ config.Connection.Password, config.Connection.DBName,
+ )
+ newDb, err := sql.Open(config.Connection.Driver, connInfo)
+ 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 = newDb.Ping()
+ if err != nil {
+ return nil, err
+ }
+
+ db = newDb
+ }
+
+ return db, nil
+}