-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgql.go
More file actions
329 lines (282 loc) · 7.52 KB
/
Copy pathgql.go
File metadata and controls
329 lines (282 loc) · 7.52 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
package gql
import (
"context"
"database/sql"
"errors"
"strconv"
)
var sqlDBS = make(map[string]*sql.DB)
const defaultConnection = "master"
func Connect(connectionName string, driver string, dataSource string) *sql.DB {
db, err := sql.Open(driver, dataSource)
if err != nil {
panic(err.Error())
}
err = db.Ping()
if err != nil {
panic(err.Error())
}
if connectionName == "" {
connectionName = defaultConnection
}
sqlDBS[connectionName] = db
return db
}
func (m *Model) Select(cols ...string) *Model {
for _, col := range cols {
if inStringArray(m.query.selected, col) == false {
m.query.selected = append(m.query.selected, col)
}
}
return m
}
func (m *Model) UseScanner(scanner func() interface{}) *Model {
m.Scanner = scanner
return m
}
func (m *Model) Exists() (bool, error) {
m.query.exists = true
m.UseScanner(func() interface{} {
return &BoolScanner{}
})
data, err := m.Get()
if err != nil {
return false, err
}
result := data[0].(*BoolScanner)
return result.Result, err
}
func (m *Model) Where(column string, op string, value string) *Model {
if m.query.whereCombination != true {
if stringHasDot(column) == false {
column = m.Table + "." + column
}
m.query.query = append(m.query.query, whereQuery{
column: column,
op: op,
value: value,
query: "where",
})
}
return m
}
func (m *Model) OrWhere(column string, op string, value string) *Model {
m.query.query = append(m.query.query, whereQuery{
column: column,
op: op,
value: value,
query: "or",
})
return m
}
func (m *Model) WhereCombination(query func(m *Model)) *Model {
lastQueryIndex := len(m.query.query)
query(m)
currentQueryIndex := len(m.query.query) - 1
checkWhereCombinationMap(m)
m.query.combinationWhere[lastQueryIndex] = currentQueryIndex
return m
}
func (m *Model) WhereExists(query func() *Model) *Model {
model := query()
queryString, params := buildQuery(model)
m.query.query = append(m.query.query, whereQuery{
query: "exists",
existsParams: params,
existsQuery: queryString,
})
return m
}
func (m *Model) Union(query func() *Model) *Model {
model := query()
queryString, params := buildQuery(model)
m.query.union = append(m.query.union, unionQuery{
unionQuery: queryString,
unionParams: params,
})
return m
}
func (m *Model) WhereIn(column string, value []string) *Model {
m.query.query = append(m.query.query, whereQuery{
column: column,
in: value,
query: "in",
})
return m
}
func (m *Model) GroupBy(groupBy ...string) *Model {
for _, col := range groupBy {
if inStringArray(m.query.groupBy, col) == false {
m.query.groupBy = append(m.query.groupBy, col)
}
}
return m
}
func (m *Model) OrderBy(column string, orderType string) *Model {
m.query.order = column + " " + orderType
return m
}
func (m *Model) With(relationName string) *Model {
m.query.joins = append(m.query.joins, relationName)
return m
}
func (m *Model) Find(primaryKeyValue int64) (DataItem, error) {
m.Limit(1)
m.query.query = []whereQuery{}
m.query.query = append(m.query.query, whereQuery{
column: getPrimaryKey(m),
op: "=",
value: strconv.FormatInt(primaryKeyValue, 10),
query: "where",
})
items, err := m.Get()
if err != nil {
return nil, err
}
//check if not found result
if len(items) < 1 {
err = errors.New("no result found")
return nil, err
}
//return first item
return items[0], err
}
func (m *Model) Count(column string) (int64, error) {
m.query.countColumn = column
m.UseScanner(func() interface{} {
return &CountScanner{}
})
data, err := m.Get()
if err != nil {
return 0, err
}
return data[0].(*CountScanner).Count, err
}
func (m *Model) Limit(limit int) *Model {
m.query.limit = strconv.Itoa(limit)
return m
}
func (m *Model) Offset(offset int) *Model {
m.query.offset = strconv.Itoa(offset)
return m
}
func (m *Model) First() (DataItem, error) {
m.Limit(1)
m.OrderBy(getPrimaryKey(m), "asc")
items, err := m.Get()
if err != nil {
return nil, err
}
//check if not found result
if len(items) < 1 {
err = errors.New("no result found")
return nil, err
}
return items[0], err
}
func (m *Model) Latest() (DataItem, error) {
m.Limit(1)
m.OrderBy(getPrimaryKey(m), "desc")
items, err := m.Get()
if err != nil {
return nil, err
}
//check if not found result
if len(items) < 1 {
err = errors.New("no result found")
return nil, err
}
return items[0], err
}
func (m *Model) Get() ([]DataItem, error) {
return sqlSelectQuery(m)
}
func (m *Model) HasRelation(relationName string, relatedTable string, foreignKey string, localKey string) *Model {
checkRelationsMap(m)
m.Relations[relationName] = Relation{relationType: "hasRelation", relationTable: relatedTable, foreignKey: foreignKey, localKey: localKey}
return m
}
func (m *Model) BelongsToMany(relationName string, relatedTable string, foreignKey string, localKey string, relatedForeignKey string, relatedLocalKey string, middleTable string) *Model {
checkRelationsMap(m)
m.Relations[relationName] = Relation{relationType: "belongsToMany", relationTable: relatedTable, foreignKey: foreignKey, localKey: localKey, relationModelForeignKey: relatedForeignKey, relationModelLocalKey: relatedLocalKey, middleTable: middleTable}
return m
}
func (m *Model) Insert(insertObject interface{}) (int64, error) {
insertStmt, params := buildInsertStmt(m, insertObject)
result, err := prepareAndExec(m, insertStmt, params, true)
return result.LastId, err
}
func (m *Model) InsertAndReturn(insertObject interface{}) (DataItem, error) {
id, err := m.Insert(insertObject)
if err != nil {
return -1, err
}
return m.Find(id)
}
func (m *Model) Update(updatedObject interface{}) (int64, error) {
updateStmt, params := buildUpdateStmt(m, updatedObject)
result, err := prepareAndExec(m, updateStmt, params, false)
return result.Affected, err
}
func (m *Model) UpdateAndReturn(updatedObject interface{}) ([]DataItem, error) {
updateStmt, params := buildUpdateStmt(m, updatedObject)
_, err := prepareAndExec(m, updateStmt, params, false)
if err != nil {
return nil, err
}
return m.Get()
}
func (m *Model) Delete() (int64, error) {
if len(m.query.query) == 0 {
return 0, errors.New("you want to delete with out any conditions , so will delete all data, if you want this please use Truncate func")
}
var deleteStmt string
var params []interface{}
deleteStmt += "DELETE FROM " + m.Table
buildWhereQuery(m, &deleteStmt, ¶ms)
result, err := prepareAndExec(m, &deleteStmt, ¶ms, false)
return result.Affected, err
}
func (m *Model) Truncate() error {
_, err := m.getConnection().Query("truncate table " + m.Table)
return err
}
func (m *Model) Transaction(Tx *sql.Tx) *Model {
m.query.transaction = true
m.query.sqlTransaction = Tx
return m
}
func Transaction(ConnectionName string, BeginContext *context.Context, TxOptions *sql.TxOptions, transaction func(tx *sql.Tx) error) error {
tx, err := GetSqlConnection(ConnectionName).BeginTx(*BeginContext, TxOptions)
if err != nil {
return err
}
err = transaction(tx)
if err != nil {
_ = tx.Rollback()
return err
}
err = tx.Commit()
return err
}
func (m *Model) Context(Context *context.Context) *Model {
m.query.queryContext = Context
return m
}
func (m *Model) LockForUpdate() *Model {
m.query.lock = " for update"
return m
}
func (m *Model) ToSql() string {
queryString, _ := buildQuery(m)
return *queryString
}
func GetSqlConnection(ConnectionName string) *sql.DB {
if ConnectionName == "" {
return sqlDBS[defaultConnection]
}
return sqlDBS[ConnectionName]
}
func (m *Model) getConnection() *sql.DB {
return GetSqlConnection(m.Connection)
}