From 311603d0c0b04d451e9fb8e5e8335dca8425e2c4 Mon Sep 17 00:00:00 2001 From: mo khan Date: Thu, 31 Jul 2025 16:09:12 -0600 Subject: Connect to postgresql --- app/db/connection.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ app/db/url.go | 19 ++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 app/db/connection.go create mode 100644 app/db/url.go (limited to 'app/db') diff --git a/app/db/connection.go b/app/db/connection.go new file mode 100644 index 0000000..d494f6c --- /dev/null +++ b/app/db/connection.go @@ -0,0 +1,54 @@ +package db + +import ( + "context" + "database/sql" + "fmt" + + _ "github.com/lib/pq" + "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls" +) + +type Connection struct { + db *sql.DB +} + +func NewConnection(databaseURL string) (*Connection, error) { + db, err := sql.Open("postgres", databaseURL) + if err != nil { + return nil, fmt.Errorf("failed to open database connection: %w", err) + } + + return &Connection{ + db: db, + }, nil +} + +func (c *Connection) Ping(ctx context.Context) error { + if c.db == nil { + return fmt.Errorf("database connection not available") + } + + return c.db.PingContext(ctx) +} + +func (c *Connection) IsHealthy(ctx context.Context) bool { + if c.db == nil { + return false + } + + err := c.Ping(ctx) + if err != nil { + pls.LogError(ctx, err) + return false + } + + return true +} + +func (c *Connection) Close() error { + if c.db == nil { + return nil + } + return c.db.Close() +} diff --git a/app/db/url.go b/app/db/url.go new file mode 100644 index 0000000..b17c651 --- /dev/null +++ b/app/db/url.go @@ -0,0 +1,19 @@ +package db + +import ( + "fmt" + + "github.com/xlgmokha/x/pkg/env" +) + +func URL() string { + if url := env.Fetch("DATABASE_URL", ""); url != "" { + return url + } + + return fmt.Sprintf( + "postgresql://postgres:%s@localhost:5000/%s?sslmode=disable", + env.Fetch("RUNWAY_PG_USER_POSTGRES_PASSWORD_SPARKLE", ""), + env.Fetch("DATABASE_NAME", "sparkle"), + ) +} -- cgit v1.2.3