45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
// package db serves as a database wrapper for adonis
|
|
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type Database struct {
|
|
conn *pgxpool.Pool
|
|
}
|
|
|
|
func NewDatabase(username, password, hostname, database string) *Database {
|
|
|
|
// pool ensures thread safety
|
|
url := url(username, password, hostname, database)
|
|
dbpool, err := pgxpool.New(context.Background(), url)
|
|
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Unable to create connection pool: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
var greeting string
|
|
err = dbpool.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
fmt.Println(greeting)
|
|
|
|
return &Database{conn: dbpool}
|
|
}
|
|
|
|
// this function assumes default port because i cant be bothered
|
|
func url(username, password, hostname, database string) string {
|
|
// generate url based on passed params
|
|
// safe to disable SSL as comms occur over docker network
|
|
return fmt.Sprintf("postgresql://%s:%s@%s/%s?sslmode=disable",
|
|
username, password, hostname, database)
|
|
}
|