forked from sfreiberg/powerrest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
domain.go
148 lines (117 loc) · 2.5 KB
/
domain.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package main
import (
"log"
"time"
)
type Domain struct {
Id int `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
}
func NewDomain(name string) *Domain {
return &Domain{Name: name, Type: "NATIVE"}
}
func FindDomain(id int) (*Domain, error) {
sql := "SELECT id, name, type FROM domains WHERE id = $1"
if conf.DbType == "mysql" {
sql = "SELECT id, name, type FROM domains WHERE id = ?"
}
row := db.QueryRow(sql, id)
d := &Domain{}
err := row.Scan(
&d.Id,
&d.Name,
&d.Type,
)
return d, err
}
func AllDomains() []*Domain {
rows, err := db.Query("select id, name, type from domains")
if err != nil {
log.Fatal(err)
}
domains := []*Domain{}
for rows.Next() {
d := &Domain{}
err := rows.Scan(
&d.Id,
&d.Name,
&d.Type,
)
if err != nil {
log.Fatal(err)
}
domains = append(domains, d)
}
return domains
}
// Create new domain, returning the id
func (d *Domain) Create() error {
if conf.DbType == "mysql" {
// MySQL supports LastInsertId()
sql := "INSERT INTO domains (name, type) VALUES (?, ?)"
res, err := db.Exec(
sql,
d.Name,
d.Type,
)
if err != nil {
return err
}
domain_id, id_err := res.LastInsertId()
if id_err != nil {
return id_err
}
d.Id = int(domain_id)
return err
} else {
// PostgreSQL driver does not support it, use RETURNING instead
sql := "INSERT INTO domains (name, type) VALUES ($1, $2) RETURNING id"
var domain_id int64
err := db.QueryRow(
sql,
d.Name,
d.Type,
).Scan(&domain_id)
if err != nil {
return err
}
d.Id = int(domain_id)
return err
}
}
func (d *Domain) Update() error {
sql := "UPDATE domains SET name=$1 WHERE id=$2"
if conf.DbType == "mysql" {
sql = "UPDATE domains SET name=? WHERE id=?"
}
_, err := db.Exec(sql, d.Name, d.Id)
return err
}
func (d *Domain) Delete() error {
sql := "DELETE FROM domains WHERE id = $1"
recSql := "DELETE FROM records WHERE domain_id = $1"
if conf.DbType == "mysql" {
sql = "DELETE FROM domains WHERE id = ?"
recSql = "DELETE FROM records WHERE domain_id = ?"
}
tx, err := db.Begin()
if err != nil {
return err
}
// Delete records that belong to this domain and rollback on err
_, err = tx.Exec(recSql, d.Id)
if err != nil {
tx.Rollback()
return err
}
// Delete domain and rollback on err
_, err = tx.Exec(sql, d.Id)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}