-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.go
More file actions
334 lines (280 loc) · 8.54 KB
/
builder.go
File metadata and controls
334 lines (280 loc) · 8.54 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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package gql
import (
"database/sql"
"log"
"strings"
)
func buildQuery(m *Model) (*string, *[]interface{}) {
var sqlQuery string
var params []interface{}
//check if count query
if m.query.countColumn != "" {
sqlQuery = buildCount(m)
} else {
sqlQuery = "select " + getSelected(m) + " from " + m.Table
}
if len(m.query.joins) > 0 {
buildJoins(m, &sqlQuery)
}
if len(m.query.query) > 0 {
buildWhereQuery(m, &sqlQuery, ¶ms)
}
if len(m.query.groupBy) > 0 {
sqlQuery += " group by " + strings.Join(m.query.groupBy, ",")
}
if m.query.order != "" {
sqlQuery += " order by " + m.query.order
}
if m.query.limit != "" || m.query.offset != "" {
sqlQuery += " limit ?"
if m.query.offset != "" {
params = append(params, m.query.offset)
sqlQuery += ",?"
}
params = append(params, m.query.limit)
}
if m.query.lock != "" {
sqlQuery += m.query.lock
}
//check if exists query
if m.query.exists == true {
sqlQuery = buildExists(sqlQuery)
}
buildUnion(m, &sqlQuery, ¶ms)
return &sqlQuery, ¶ms
}
func buildExists(sqlQuery string) string {
var queryWithExists string
queryWithExists = "select exists(" + sqlQuery + ") as result"
return queryWithExists
}
func buildCount(m *Model) string {
return "select count(" + m.query.countColumn + ") as result_count from " + m.Table
}
func buildUnion(m *Model, sqlQuery *string, params *[]interface{}) {
if len(m.query.union) > 0 {
for i := 0; i < len(m.query.union); i++ {
*sqlQuery += " UNION (" + *m.query.union[i].unionQuery + ")"
unionParams := *m.query.union[i].unionParams
for x := 0; x < len(unionParams); x++ {
*params = append(*params, unionParams[x])
}
}
}
}
func sqlSelectQuery(model *Model) ([]DataItem, error) {
query, params := buildQuery(model)
data := []DataItem{}
var rows *sql.Rows
var err error
if model.query.transaction == true {
rows, err = queryInTransaction(model, query, params)
} else {
rows, err = queryWithOutTransaction(model, query, params)
}
if err != nil {
log.Fatal(err)
return data, err
}
//// Get column names
columns, err := rows.Columns()
if err != nil {
return data, err
}
//get fields from struct
scanner := model.Scanner()
fields := mapColumnsFields(scanner, columns)
// Fetch rows
for rows.Next() {
Scan := model.Scanner()
err = rows.Scan(getStrutFields(Scan, columns, fields)...)
if err != nil {
return data, err
}
data = append(data, Scan)
}
if err = rows.Err(); err != nil {
return data, err
}
return data, err
}
func prepareAndExec(m *Model, stmt *string, params *[]interface{}, returnInsertId bool) (ExecResult, error) {
Result := ExecResult{
Affected: 0,
LastId: 0,
}
var sqlResult sql.Result
var err error
if m.query.transaction == true {
sqlResult, err = execInTransaction(m, stmt, params)
} else {
sqlResult, err = execWithOutTransaction(m, stmt, params)
}
if err != nil {
return Result, err
}
rowsAffected, err := sqlResult.RowsAffected()
if err != nil {
return Result, err
}
Result.Affected = rowsAffected
if returnInsertId == true {
LastId, err := sqlResult.LastInsertId()
if err != nil {
return Result, err
}
Result.LastId = LastId
}
return Result, err
}
func execInTransaction(m *Model, stmt *string, params *[]interface{}) (sql.Result, error) {
var result sql.Result
var err error
if m.query.queryContext != nil {
result, err = m.query.sqlTransaction.ExecContext(*m.query.queryContext, *stmt, *params...)
} else {
result, err = m.query.sqlTransaction.Exec(*stmt, *params...)
}
return result, err
}
func execWithOutTransaction(m *Model, stmt *string, params *[]interface{}) (sql.Result, error) {
var result sql.Result
stmtOut, err := m.getConnection().Prepare(*stmt)
if err != nil {
return result, err
}
defer stmtOut.Close()
if m.query.queryContext != nil {
result, err = stmtOut.ExecContext(*m.query.queryContext, *params...)
} else {
result, err = stmtOut.Exec(*params...)
}
if err != nil {
return result, err
}
return result, err
}
func queryInTransaction(m *Model, query *string, params *[]interface{}) (*sql.Rows, error) {
var result *sql.Rows
var err error
if m.query.queryContext != nil {
result, err = m.query.sqlTransaction.QueryContext(*m.query.queryContext, *query, *params...)
} else {
result, err = m.query.sqlTransaction.Query(*query, *params...)
}
return result, err
}
func queryWithOutTransaction(m *Model, query *string, params *[]interface{}) (*sql.Rows, error) {
stmtOut, err := m.getConnection().Prepare(*query)
var rows *sql.Rows
if err != nil {
return rows, err
}
defer stmtOut.Close()
if m.query.queryContext != nil {
rows, err = stmtOut.QueryContext(*m.query.queryContext, *params...)
} else {
rows, err = stmtOut.Query(*params...)
}
if err != nil {
return rows, err
}
return rows, err
}
func buildUpdateStmt(m *Model, updatedObject interface{}) (*string, *[]interface{}) {
var updateStmt string
columns, values := structFieldsValues(updatedObject)
updateStmt += "UPDATE " + m.Table + " set "
for i := 0; i < len(*columns); i++ {
checkPrimaryKeyValue(m, i, columns, values)
updateStmt += (*columns)[i] + " = ?,"
}
updateStmt = strings.TrimRight(updateStmt, ",")
if len(m.query.query) > 0 {
buildWhereQuery(m, &updateStmt, values)
}
return &updateStmt, values
}
func buildInsertStmt(m *Model, insertObject interface{}) (*string, *[]interface{}) {
columns, values := structFieldsValues(insertObject)
removeUnFillable(m, columns, values)
var stmtQuery string
var perpareValues []string
for i := 0; i < len(*columns); i++ {
//remove primary key from insert object when it has empty value
checkPrimaryKeyValue(m, i, columns, values)
perpareValues = append(perpareValues, "?")
}
stmtQuery += "INSERT INTO " + m.Table + " (" + strings.Join(*columns, ",") + ") VALUES (" + strings.Join(perpareValues, ",") + ")"
return &stmtQuery, values
}
func buildJoins(m *Model, sqlQuery *string) {
for i := 0; i < len(m.query.joins); i++ {
relation := m.Relations[m.query.joins[i]]
if relation.relationType == "hasRelation" {
*sqlQuery += " inner join " + relation.relationTable + " on " + m.Table + "." + relation.localKey + " = " + relation.relationTable + "." + relation.foreignKey
} else if relation.relationType == "belongsToMany" {
*sqlQuery += " inner join " + relation.middleTable + " on " + m.Table + "." + relation.localKey + " = " + relation.middleTable + "." + relation.foreignKey + " inner join " + relation.relationTable + " on " + relation.relationTable + "." + relation.relationModelLocalKey + " = " + relation.middleTable + "." + relation.relationModelForeignKey
}
}
}
func buildWhereQuery(m *Model, sqlQuery *string, params *[]interface{}) {
stmt := " where "
var lastComp int
var comp string
for i := 0; i < len(m.query.query); i++ {
_, ok := m.query.combinationWhere[i]
if ok {
lastComp = i
comp = "("
} else {
comp = ""
}
if m.query.query[i].query == "where" {
*sqlQuery += stmt + comp + m.query.query[i].column + " " + m.query.query[i].op + " ?"
*params = append(*params, m.query.query[i].value)
} else if m.query.query[i].query == "or" {
*sqlQuery += " or " + comp + m.query.query[i].column + " " + m.query.query[i].op + " ?"
*params = append(*params, m.query.query[i].value)
} else if m.query.query[i].query == "in" {
var in []string
for j := 0; j < len(m.query.query[i].in); j++ {
in = append(in, "?")
*params = append(*params, m.query.query[i].in[j])
}
*sqlQuery += stmt + comp + m.query.query[i].column + " in (" + strings.Join(in, ",") + ")"
} else if m.query.query[i].query == "exists" {
*sqlQuery += stmt + comp + " exists (" + *m.query.query[i].existsQuery + ")"
existsParams := *m.query.query[i].existsParams
for x := 0; x < len(existsParams); x++ {
*params = append(*params, existsParams[x])
}
}
stmt = " and "
_, check := m.query.combinationWhere[lastComp]
if check {
if i == m.query.combinationWhere[lastComp] {
*sqlQuery += ")"
}
}
}
}
func getSelected(m *Model) string {
if len(m.query.selected) == 0 {
m.query.selected = append(m.query.selected, "*")
}
return strings.Join(m.query.selected, ",")
}
func getPrimaryKey(m *Model) string {
if m.PrimaryKey == "" {
return "id"
}
return m.PrimaryKey
}
func checkPrimaryKeyValue(m *Model, index int, columns *[]string, values *[]interface{}) {
//remove primary key from columns and values when it has empty value
if (*columns)[index] == getPrimaryKey(m) && ((*values)[index] == "0" || (*values)[index] == "") {
*columns = append((*columns)[:index], (*columns)[index+1:]...)
*values = append((*values)[:index], (*values)[index+1:]...)
}
}