package db import ( "context" "fmt" "log" "github.com/jackc/pgx/v5/pgxpool" ) // db connection info // !MIGHT CHANGE const ( host = "localhost" port = 5432 user = "asdfuser" password = "asdfpassword" dbname = "asdfdb" ) var DbPool *pgxpool.Pool var allowedUsernames map[string]bool // initialize connection to db func ConnectToDb() (*pgxpool.Pool, error) { // this server is intended to be ran on the same system as the db dbUrl := fmt.Sprintf("postgresql://%s:%s@%s:%d/%s", user, password, host, port, dbname) config, err := pgxpool.ParseConfig((dbUrl)) if err != nil { return nil, fmt.Errorf("unable to parse data URL: %w", err) } pool, err := pgxpool.NewWithConfig(context.Background(), config) if err != nil { return nil, fmt.Errorf("unable to create connection pool: %w", err) } log.Println("Connected to DB :)") return pool, nil } // fetch existing usernames from db func FetchUsernames() (map[string]bool, error) { usernames := make(map[string]bool) rows, err := DbPool.Query(context.Background(), "SELECT username FROM users") if err != nil { return nil, fmt.Errorf("error querying users: %w", err) } defer rows.Close() for rows.Next() { var username string if err := rows.Scan(&username); err != nil { return nil, fmt.Errorf("error scanning username: %w", err) } usernames[username] = true } log.Println("Fetched usernames:", usernames) return usernames, nil }