package db import ( "context" "fmt" "log" "os" "github.com/jackc/pgx/v5/pgxpool" "github.com/joho/godotenv" ) var Pool *pgxpool.Pool func InitDB() { err := godotenv.Load() if err != nil { log.Fatalf("Error loading .env file: %v", err) } connString := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s", os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_NAME"), ) ctx := context.Background() config, err := pgxpool.ParseConfig(connString) if err != nil { log.Fatalf("Unable to parse database config: %v", err) } Pool, err = pgxpool.NewWithConfig(ctx, config) if err != nil { log.Fatalf("Unable to create connection pool: %v", err) } err = Pool.Ping(ctx) if err != nil { log.Fatalf("Unable to ping database: %v", err) } fmt.Println("Database connection established successfully") if err := CreateTables(); err != nil { log.Fatalf("Failed to create tables: %v", err) } } func CreateTables() error { ctx := context.Background() _, err := Pool.Exec(ctx, ` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, is_verified BOOLEAN DEFAULT FALSE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS verification_codes ( id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id) ON DELETE CASCADE, code VARCHAR(6) NOT NULL, expires_at TIMESTAMP WITH TIME ZONE NOT NULL, used BOOLEAN DEFAULT FALSE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS messages ( id SERIAL PRIMARY KEY, sender_id INT REFERENCES users(id), receiver_id INT REFERENCES users(id), content TEXT NOT NULL, sent_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); `) return err } func Close() { if Pool != nil { Pool.Close() } }