pollo/lib/db.go

56 lines
1.3 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
2024-06-28 14:23:35 -06:00
);
CREATE TABLE IF NOT EXISTS rooms (
id TEXT NOT NULL PRIMARY KEY,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
userId TEXT NOT NULL,
roomName TEXT,
topicName TEXT,
visible BOOLEAN NOT NULL DEFAULT false,
scale TEXT NOT NULL DEFAULT '0.5,1,2,3,5'
);
`
2024-06-27 21:23:51 -06:00
// 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
}