-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrud.go
279 lines (249 loc) · 6.18 KB
/
crud.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package crud
import (
"database/sql"
"errors"
"fmt"
"github.com/cadyrov/govalidation"
"strconv"
"strings"
)
//ActiveRecord analog
type Cruder interface {
Columns() (names []string, attributeLinks []interface{})
PrimaryKey() (names []string, attributeLinks []interface{})
Sequences() (names []string, attributeLinks []interface{})
TableName() string
Validate() (err error)
}
//SQL tx and dbo
type DSLer interface {
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
Exec(query string, args ...interface{}) (sql.Result, error)
}
type Crud struct {
}
// SQL load Query
func GetLoadQuery(m Cruder) string {
columns := columnNames(m)
table := m.TableName()
sql, _ := getSqlPrimary(m, 0)
return "SELECT " + columns + " FROM " + table + " WHERE " + sql + " ;"
}
func getSqlPrimary(m Cruder, cnt int) (sql string, count int) {
count = cnt
sql = ""
nms, _ := m.PrimaryKey()
for key, value := range nms {
nm := value
count++
if key == 0 {
sql += " " + nm + " = " + fmt.Sprintf("$%v", count) + " "
} else {
sql += " and " + nm + " = " + fmt.Sprintf("$%v", count) + " "
}
}
return
}
func columnNames(m Cruder) string {
names := make([]string, 0)
primary, _ := m.PrimaryKey()
names = append(names, primary...)
nms, _ := m.Columns()
names = append(names, nms...)
return strings.Join(names, ", ")
}
func scans(m Cruder) (values []interface{}) {
_, attributeLink := m.PrimaryKey()
values = append(values, attributeLink...)
_, attributeLinks := m.Columns()
values = append(values, attributeLinks...)
return
}
func insertionColumns(m Cruder) (names []string, attributeLinks []interface{}) {
prNames, prLinks := m.PrimaryKey()
for key, value := range prNames {
if !inSequense(m, value) {
nm := value
attrLink := prLinks[key]
names = append(names, nm)
attributeLinks = append(attributeLinks, attrLink)
}
}
stNames, stLinks := m.Columns()
names = append(names, stNames...)
attributeLinks = append(attributeLinks, stLinks...)
return
}
func inSequense(m Cruder, name string) bool {
names, _ := m.Sequences()
for _, value := range names {
if value == name {
return true
}
}
return false
}
func parse(rows *sql.Rows, m Cruder) (err error) {
errScan := rows.Scan(scans(m)...)
err = errScan
return
}
// Load model
func Load(dbo DSLer, m Cruder) (find bool, err error) {
_, idlinks := m.PrimaryKey()
if primaryExists(idlinks) {
var iterator *sql.Rows
iterator, errQuery := dbo.Query(GetLoadQuery(m), idlinks...)
if errQuery != nil {
err = errQuery
return
}
defer iterator.Close()
if iterator.Next() == false {
return
}
err = parse(iterator, m)
if err == nil {
find = true
}
return
} else {
err = errors.New("no primary key specified, nothing for load")
}
return
}
// SQL delete Query
func getDeleteQuery(m Cruder) string {
sql, _ := getSqlPrimary(m, 0)
return "DELETE FROM " + m.TableName() + " WHERE " + sql + " ;"
}
// Delete method
func Delete(dbo DSLer, m Cruder) error {
_, idlinks := m.PrimaryKey()
_, err := dbo.Exec(getDeleteQuery(m), idlinks...)
return err
}
// SQL update Query
func getUpdateQuery(m Cruder) (query string, insertions []interface{}) {
_, attr := m.PrimaryKey()
insertions = append(insertions, attr...)
cols, ins := insertionColumns(m)
insertions = append(insertions, ins...)
sqlPrm, iStrt := getSqlPrimary(m, 0)
updateCols := ""
for i, colname := range cols {
updateCols = updateCols + " " + colname + " = $" + strconv.Itoa(i+1+iStrt)
if i < (len(cols) - 1) {
updateCols = updateCols + ", "
}
}
query = `UPDATE ` + m.TableName() + ` SET ` + updateCols + `
WHERE ` + sqlPrm + `
RETURNING ` + columnNames(m) + `;`
return
}
func getInsertOnConflictQuery(m Cruder) (query string, insertions []interface{}) {
names, insertions := insertionColumns(m)
columns := strings.Join(names, ",")
params := ""
for i, _ := range names {
params = params + " $" + strconv.Itoa(i+1)
if i < (len(names) - 1) {
params = params + ", "
}
}
updateCols := ""
for i, colname := range names {
updateCols = updateCols + " " + colname + " = $" + strconv.Itoa(i+1)
if i < (len(names) - 1) {
updateCols = updateCols + ", "
}
}
pnames, _ := m.PrimaryKey()
onconf := strings.Join(pnames, ",")
query = `INSERT INTO ` + m.TableName() + ` (` + columns + `) VALUES (` + params + `)
ON CONFLICT (` + onconf + `)
DO UPDATE SET
` + updateCols + `
RETURNING ` + columnNames(m) + `
;`
return
}
func getSaveQuery(m Cruder) (query string, insertions []interface{}) {
names, insertions := insertionColumns(m)
columns := strings.Join(names, ",")
params := ""
for i, _ := range names {
params = params + " $" + strconv.Itoa(i+1)
if i < (len(names) - 1) {
params = params + ", "
}
}
query = `INSERT INTO ` + m.TableName() + ` (` + columns + `) VALUES (` + params + `)
RETURNING ` + columnNames(m) + `;`
return
}
//Model saver method
func Save(ds DSLer, m Cruder) (err error) {
_, attrLink := m.Sequences()
ok:= isUpdate(m)
if len(attrLink) == 0 {
err = insertOnConflict(ds,m)
} else if ok {
err = update(ds,m)
} else {
err = create(ds,m)
}
return
}
func create(ds DSLer, m Cruder) (err error) {
if err = m.Validate(); err == nil {
query, insertions := getSaveQuery(m)
err = ds.QueryRow(query, insertions...).Scan(scans(m)...)
}
return
}
func update(ds DSLer, m Cruder) (err error) {
if err = m.Validate(); err == nil {
query, insertions := getUpdateQuery(m)
err = ds.QueryRow(query, insertions...).Scan(scans(m)...)
}
return
}
func insertOnConflict(ds DSLer, m Cruder) (err error) {
if err = m.Validate(); err == nil {
query, insertions := getInsertOnConflictQuery(m)
err = ds.QueryRow(query, insertions...).Scan(scans(m)...)
}
return
}
func isUpdate(m Cruder) (ok bool) {
_, attrLink := m.Sequences()
if len(attrLink) == 0 {
return
}
for _, value := range attrLink {
err := validation.Validate(value, validation.Required)
if err != nil {
ok = false
return
}
}
ok = true
return
}
func primaryExists(input []interface{}) (ok bool) {
if input == nil {
return
}
ok = true
for _, value := range input {
err := validation.Validate(value, validation.Required)
if err != nil {
ok = false
return
}
}
return
}