diff options
| author | Wayne-Cole <77279425+Wacky404@users.noreply.github.com> | 2026-02-17 20:39:32 -0600 |
|---|---|---|
| committer | Wayne-Cole <77279425+Wacky404@users.noreply.github.com> | 2026-02-17 20:39:32 -0600 |
| commit | 46794376469f5460b1f3a6beac747e2f0ba140ff (patch) | |
| tree | 0389eba4890de17d2721d5164b4da525c55fd9ab /internal/db/connect.go | |
| parent | a3151074722294f050e8d37fa973c55ed93ffdd2 (diff) | |
| download | lurchers-46794376469f5460b1f3a6beac747e2f0ba140ff.tar.xz lurchers-46794376469f5460b1f3a6beac747e2f0ba140ff.zip | |
feat: progress...
Diffstat (limited to 'internal/db/connect.go')
| -rw-r--r-- | internal/db/connect.go | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/internal/db/connect.go b/internal/db/connect.go new file mode 100644 index 0000000..2588e63 --- /dev/null +++ b/internal/db/connect.go @@ -0,0 +1,60 @@ +package db + +import ( + "context" + "database/sql" + "fmt" + "log/slog" + "strconv" + + "github.com/Wacky404/lurchers/internal" +) + +type Database struct { + conn *sql.DB + ctx *context.Context + host string + port int64 + user string + password string + name string + sql *DbStatements +} + +// creates an instance of the Database struct and loads in env vars +func LoadConfig(ctx *context.Context) (*Database, error) { + port, err := strconv.ParseInt(internal.GetVar("DB_PORT", ""), 10, 64) + if err != nil { + slog.Error("error loading .env var port", slog.Any("error", err)) + return nil, err + } + db := &Database{ + ctx: ctx, + host: internal.GetVar("DB_HOST", ""), + port: port, + user: internal.GetVar("DB_USER", ""), + password: internal.GetVar("DB_PASSWORD", ""), + name: internal.GetVar("DB_NAME", ""), + sql: NewDbStatements(), + } + + return db, nil +} + +// connecting to the precious +func (d *Database) Connect(service string) error { + psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ + "password=%s dbname=%s sslmode=disable", + d.host, d.port, d.user, d.password, d.name) + conn, err := sql.Open(service, psqlInfo) + if err != nil { + slog.Error("error connecting to the database", slog.Any("error", err)) + } + + if err := conn.Ping(); err != nil { + return err + } + + d.conn = conn + return nil +} |
