pollo/lib/db.go

46 lines
1 KiB
Go
Raw Normal View History

2024-06-27 21:23:51 -06:00
package lib
import (
"context"
2024-06-27 21:51:00 -06:00
"fmt"
2024-06-27 21:23:51 -06:00
"github.com/jackc/pgx/v4/pgxpool"
)
var dbPool *pgxpool.Pool
// Initializes the global database connection pool.
2024-06-27 21:51:00 -06:00
func InitializeDBPool(host, user, password, dbname string, port int) error {
// Construct the connection string using the provided parameters
connString := fmt.Sprintf("postgres://%s:%s@%s:%d/%s", user, password, host, port, dbname)
2024-06-27 21:23:51 -06:00
var err error
dbPool, err = pgxpool.Connect(context.Background(), connString)
if err != nil {
return err
}
return nil
}
func InitializeSchema(dbPool *pgxpool.Pool) error {
const schemaSQL = `
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
2024-06-28 09:11:03 -06:00
name VARCHAR(255) NOT NULL,
2024-06-27 21:23:51 -06:00
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);`
// TODO: Add more tables to the schema
_, err := dbPool.Exec(context.Background(), schemaSQL)
if err != nil {
return err
}
return nil
}
// Returns the initialized database connection pool.
func GetDBPool() *pgxpool.Pool {
return dbPool
}