-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
78 lines (70 loc) · 1.56 KB
/
database.go
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
78
// Copyright Banrai LLC. All rights reserved. Use of this source code is
// governed by the license that can be found in the LICENSE file.
package database
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
)
type DBConnection struct {
DBName string
User string
Pass string
SSLMode bool
}
// Connect to the database with the given coordinates, and invoke the
// function, which gets passed a map of all the prepared statements
func WithDatabase(dbCoords DBConnection, fn func(map[string]*sql.Stmt)) {
preparedStatements := []string{PERSON_INSERT,
PERSON_UPDATE,
PERSON_DELETE,
PERSON_LOOKUP_BY_ID,
PERSON_LOOKUP_BY_EMAIL,
SESSION_INSERT,
SESSION_UPDATE,
SESSION_CLEANUP,
SESSION_LOOKUP_BY_CODE,
SESSION_LOOKUP_BY_ID,
SESSION_LOOKUP_BY_PERSON,
PK_INSERT,
PK_UPDATE,
PK_DELETE,
PK_LOOKUP,
MESSAGE_INSERT,
MESSAGE_DELETE,
MESSAGE_CLEANUP,
RECIPIENT_INSERT,
RECIPIENT_DELETE,
RECIPIENT_CLEANUP,
MESSAGES_BY_AUTHOR,
MESSAGES_BY_RECIPIENT,
LATEST_MESSAGES,
LATEST_MESSAGES_INVOLVING_PERSON,
MESSAGE_BY_ID,
RECIPIENTS_BY_MESSAGE}
sslMode := "disable"
if dbCoords.SSLMode {
sslMode = "enable"
}
db, dbErr := sql.Open("postgres",
fmt.Sprintf("user=%s dbname=%s password=%s sslmode=%s",
dbCoords.User,
dbCoords.DBName,
dbCoords.Pass,
sslMode))
if dbErr != nil {
log.Fatal(dbErr)
}
defer db.Close()
statements := map[string]*sql.Stmt{}
for _, p := range preparedStatements {
stmt, err := db.Prepare(p)
if err != nil {
log.Fatal(err)
} else {
statements[p] = stmt
}
}
fn(statements)
}