-
Notifications
You must be signed in to change notification settings - Fork 1
/
namespace.go
110 lines (93 loc) · 1.84 KB
/
namespace.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package namespace
import (
"database/sql"
"sync"
)
type Namespace string
type rowQuery interface {
QueryRow(string, ...any) *sql.Row
}
// namespaces hold all namespaces and their id
var (
mut sync.RWMutex
namespaces = map[Namespace]int{}
)
// New will return the namespace id, creating it if necessary
func New(db rowQuery, namespaceStr string) (Namespace, int, error) {
var namespace = Namespace(namespaceStr)
id, err := namespace.ID(db)
if err == nil || err != sql.ErrNoRows {
return namespace, id, err
}
id, err = insert(db, namespace)
return namespace, id, err
}
// ID returns the namespace, querying the database if necessary
func (n Namespace) ID(db rowQuery) (int, error) {
id, ok := readFromMap(n)
if ok {
return id, nil
}
return query(db, n)
}
func (n Namespace) Create(db rowQuery) (int, error) {
var id int
err := db.QueryRow(`
SELECT id
FROM namespaces
WHERE nspace = $1
`,
n,
).Scan(&id)
if err != nil {
if err != sql.ErrNoRows {
return id, err
}
err = db.QueryRow(`
INSERT INTO namespaces(nspace)
VALUES($1)
RETURNING id
`,
n,
).Scan(&id)
}
return id, err
}
func insert(db rowQuery, namespace Namespace) (int, error) {
return queryIntoMap(
db,
`INSERT INTO namespaces(nspace)
VALUES($1)
RETURNING id`,
namespace,
)
}
func query(db rowQuery, namespace Namespace) (int, error) {
return queryIntoMap(
db,
`SELECT id
FROM namespaces
WHERE nspace = $1`,
namespace,
)
}
func queryIntoMap(db rowQuery, q string, namespace Namespace) (int, error) {
var (
id int
err error
)
err = db.QueryRow(q, namespace).Scan(&id)
if err != nil {
return 0, err
}
mut.Lock()
defer mut.Unlock()
namespaces[namespace] = id
return id, err
}
func readFromMap(namespace Namespace) (int, bool) {
mut.RLock()
defer mut.RUnlock()
id, ok := namespaces[namespace]
return id, ok
}