-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbhandler.go
More file actions
77 lines (67 loc) · 1.78 KB
/
dbhandler.go
File metadata and controls
77 lines (67 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
)
// DB connection handle
var db *sql.DB
// SetupDB make DB connection and create necessary table
func SetupDB() (*sql.DB, error) {
// credentials and db config
const (
host = "localhost"
port = 5432
user = "postgres"
password = "12qwas"
dbname = "postgres"
)
dataSource := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
var err error
db, err = sql.Open("postgres", dataSource)
if err != nil {
return nil, err
}
// create user table
sql := `
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'role_type') THEN
CREATE TYPE role_type AS
ENUM ('admin', 'user');
END IF;
END $$;
CREATE TABLE IF NOT EXISTS public.users (
id SERIAL NOT NULL PRIMARY KEY,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
date_created TIMESTAMPTZ NOT NULL,
role role_type NOT NULL DEFAULT 'user',
CONSTRAINT user_email_key UNIQUE (email)
);
`
_, err = db.Exec(sql)
if err != nil {
log.Fatal(err)
}
// insert admin record if not exists else do nothing
sql = `INSERT INTO public.users (name, email, password, date_created, role)
VALUES ($1, $2, $3, CURRENT_TIMESTAMP, $4)
ON CONFLICT (email) DO NOTHING`
_, err = db.Exec(sql, "admin", "adminemail@site.com", HashPassword([]byte("admpwd")), "admin")
if err != nil {
log.Fatal(err)
}
return db, nil
}
// GetDB return DB connection handle
func GetDB() *sql.DB {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
return db
}