Debian Codegraph @

chainable_api.go

raw
1 package gorm
2
3 import (
4 "fmt"
5 "regexp"
6 "strings"
7
8 "gorm.io/gorm/clause"
9 "gorm.io/gorm/utils"
10 )
11
12 // Model specify the model you would like to run db operations
13 //
14 // // update all users's name to `hello`
15 // db.Model(&User{}).Update("name", "hello")
16 // // if user's primary key is non-blank, will use it as condition, then will only update that user's name to `hello`
17 // db.Model(&user).Update("name", "hello")
18 func (db *DB) Model(value interface{}) (tx *DB) {
19 tx = db.getInstance()
20 tx.Statement.Model = value
21 return
22 }
23
24 // Clauses Add clauses
25 //
26 // This supports both standard clauses (clause.OrderBy, clause.Limit, clause.Where) and more
27 // advanced techniques like specifying lock strength and optimizer hints. See the
28 // [docs] for more depth.
29 //
30 // // add a simple limit clause
31 // db.Clauses(clause.Limit{Limit: 1}).Find(&User{})
32 // // tell the optimizer to use the `idx_user_name` index
33 // db.Clauses(hints.UseIndex("idx_user_name")).Find(&User{})
34 // // specify the lock strength to UPDATE
35 // db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)
36 //
37 // [docs]: https://gorm.io/docs/sql_builder.html#Clauses
38 func (db *DB) Clauses(conds ...clause.Expression) (tx *DB) {
39 tx = db.getInstance()
40 var whereConds []interface{}
41
42 for _, cond := range conds {
43 if c, ok := cond.(clause.Interface); ok {
44 tx.Statement.AddClause(c)
45 } else if optimizer, ok := cond.(StatementModifier); ok {
46 optimizer.ModifyStatement(tx.Statement)
47 } else {
48 whereConds = append(whereConds, cond)
49 }
50 }
51
52 if len(whereConds) > 0 {
53 tx.Statement.AddClause(clause.Where{Exprs: tx.Statement.BuildCondition(whereConds[0], whereConds[1:]...)})
54 }
55 return
56 }
57
58 var tableRegexp = regexp.MustCompile(`(?i)(?:.+? AS (\w+)\s*(?:$|,)|^\w+\s+(\w+)$)`)
59
60 // Table specify the table you would like to run db operations
61 //
62 // // Get a user
63 // db.Table("users").Take(&result)
64 func (db *DB) Table(name string, args ...interface{}) (tx *DB) {
65 tx = db.getInstance()
66 if strings.Contains(name, " ") || strings.Contains(name, "`") || len(args) > 0 {
67 tx.Statement.TableExpr = &clause.Expr{SQL: name, Vars: args}
68 if results := tableRegexp.FindStringSubmatch(name); len(results) == 3 {
69 if results[1] != "" {
70 tx.Statement.Table = results[1]
71 } else {
72 tx.Statement.Table = results[2]
73 }
74 }
75 } else if tables := strings.Split(name, "."); len(tables) == 2 {
76 tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}
77 tx.Statement.Table = tables[1]
78 } else if name != "" {
79 tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}
80 tx.Statement.Table = name
81 } else {
82 tx.Statement.TableExpr = nil
83 tx.Statement.Table = ""
84 }
85 return
86 }
87
88 // Distinct specify distinct fields that you want querying
89 //
90 // // Select distinct names of users
91 // db.Distinct("name").Find(&results)
92 // // Select distinct name/age pairs from users
93 // db.Distinct("name", "age").Find(&results)
94 func (db *DB) Distinct(args ...interface{}) (tx *DB) {
95 tx = db.getInstance()
96 tx.Statement.Distinct = true
97 if len(args) > 0 {
98 tx = tx.Select(args[0], args[1:]...)
99 }
100 return
101 }
102
103 // Select specify fields that you want when querying, creating, updating
104 //
105 // Use Select when you only want a subset of the fields. By default, GORM will select all fields.
106 // Select accepts both string arguments and arrays.
107 //
108 // // Select name and age of user using multiple arguments
109 // db.Select("name", "age").Find(&users)
110 // // Select name and age of user using an array
111 // db.Select([]string{"name", "age"}).Find(&users)
112 func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
113 tx = db.getInstance()
114
115 switch v := query.(type) {
116 case []string:
117 tx.Statement.Selects = v
118
119 for _, arg := range args {
120 switch arg := arg.(type) {
121 case string:
122 tx.Statement.Selects = append(tx.Statement.Selects, arg)
123 case []string:
124 tx.Statement.Selects = append(tx.Statement.Selects, arg...)
125 default:
126 tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
127 return
128 }
129 }
130
131 if clause, ok := tx.Statement.Clauses["SELECT"]; ok {
132 clause.Expression = nil
133 tx.Statement.Clauses["SELECT"] = clause
134 }
135 case string:
136 if strings.Count(v, "?") >= len(args) && len(args) > 0 {
137 tx.Statement.AddClause(clause.Select{
138 Distinct: db.Statement.Distinct,
139 Expression: clause.Expr{SQL: v, Vars: args},
140 })
141 } else if strings.Count(v, "@") > 0 && len(args) > 0 {
142 tx.Statement.AddClause(clause.Select{
143 Distinct: db.Statement.Distinct,
144 Expression: clause.NamedExpr{SQL: v, Vars: args},
145 })
146 } else {
147 tx.Statement.Selects = []string{v}
148
149 for _, arg := range args {
150 switch arg := arg.(type) {
151 case string:
152 tx.Statement.Selects = append(tx.Statement.Selects, arg)
153 case []string:
154 tx.Statement.Selects = append(tx.Statement.Selects, arg...)
155 default:
156 tx.Statement.AddClause(clause.Select{
157 Distinct: db.Statement.Distinct,
158 Expression: clause.Expr{SQL: v, Vars: args},
159 })
160 return
161 }
162 }
163
164 if clause, ok := tx.Statement.Clauses["SELECT"]; ok {
165 clause.Expression = nil
166 tx.Statement.Clauses["SELECT"] = clause
167 }
168 }
169 default:
170 tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
171 }
172
173 return
174 }
175
176 // Omit specify fields that you want to ignore when creating, updating and querying
177 func (db *DB) Omit(columns ...string) (tx *DB) {
178 tx = db.getInstance()
179
180 if len(columns) == 1 && strings.ContainsRune(columns[0], ',') {
181 tx.Statement.Omits = strings.FieldsFunc(columns[0], utils.IsInvalidDBNameChar)
182 } else {
183 tx.Statement.Omits = columns
184 }
185 return
186 }
187
188 // MapColumns modify the column names in the query results to facilitate align to the corresponding structural fields
189 func (db *DB) MapColumns(m map[string]string) (tx *DB) {
190 tx = db.getInstance()
191 tx.Statement.ColumnMapping = m
192 return
193 }
194
195 // Where add conditions
196 //
197 // See the [docs] for details on the various formats that where clauses can take. By default, where clauses chain with AND.
198 //
199 // // Find the first user with name jinzhu
200 // db.Where("name = ?", "jinzhu").First(&user)
201 // // Find the first user with name jinzhu and age 20
202 // db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
203 // // Find the first user with name jinzhu and age not equal to 20
204 // db.Where("name = ?", "jinzhu").Where("age <> ?", "20").First(&user)
205 //
206 // [docs]: https://gorm.io/docs/query.html#Conditions
207 func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB) {
208 tx = db.getInstance()
209 if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
210 tx.Statement.AddClause(clause.Where{Exprs: conds})
211 }
212 return
213 }
214
215 // Not add NOT conditions
216 //
217 // Not works similarly to where, and has the same syntax.
218 //
219 // // Find the first user with name not equal to jinzhu
220 // db.Not("name = ?", "jinzhu").First(&user)
221 func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB) {
222 tx = db.getInstance()
223 if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
224 tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Not(conds...)}})
225 }
226 return
227 }
228
229 // Or add OR conditions
230 //
231 // Or is used to chain together queries with an OR.
232 //
233 // // Find the first user with name equal to jinzhu or john
234 // db.Where("name = ?", "jinzhu").Or("name = ?", "john").First(&user)
235 func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
236 tx = db.getInstance()
237 if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
238 tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Or(clause.And(conds...))}})
239 }
240 return
241 }
242
243 // Joins specify Joins conditions
244 //
245 // db.Joins("Account").Find(&user)
246 // db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "[email protected]").Find(&user)
247 // db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))
248 func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
249 return joins(db, clause.LeftJoin, query, args...)
250 }
251
252 // InnerJoins specify inner joins conditions
253 // db.InnerJoins("Account").Find(&user)
254 func (db *DB) InnerJoins(query string, args ...interface{}) (tx *DB) {
255 return joins(db, clause.InnerJoin, query, args...)
256 }
257
258 func joins(db *DB, joinType clause.JoinType, query string, args ...interface{}) (tx *DB) {
259 tx = db.getInstance()
260
261 if len(args) == 1 {
262 if db, ok := args[0].(*DB); ok {
263 j := join{
264 Name: query, Conds: args, Selects: db.Statement.Selects,
265 Omits: db.Statement.Omits, JoinType: joinType,
266 }
267 if where, ok := db.Statement.Clauses["WHERE"].Expression.(clause.Where); ok {
268 j.On = &where
269 }
270 tx.Statement.Joins = append(tx.Statement.Joins, j)
271 return
272 }
273 }
274
275 tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args, JoinType: joinType})
276 return
277 }
278
279 // Group specify the group method on the find
280 //
281 // // Select the sum age of users with given names
282 // db.Model(&User{}).Select("name, sum(age) as total").Group("name").Find(&results)
283 func (db *DB) Group(name string) (tx *DB) {
284 tx = db.getInstance()
285
286 fields := strings.FieldsFunc(name, utils.IsInvalidDBNameChar)
287 tx.Statement.AddClause(clause.GroupBy{
288 Columns: []clause.Column{{Name: name, Raw: len(fields) != 1}},
289 })
290 return
291 }
292
293 // Having specify HAVING conditions for GROUP BY
294 //
295 // // Select the sum age of users with name jinzhu
296 // db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("name = ?", "jinzhu").Find(&result)
297 func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB) {
298 tx = db.getInstance()
299 tx.Statement.AddClause(clause.GroupBy{
300 Having: tx.Statement.BuildCondition(query, args...),
301 })
302 return
303 }
304
305 // Order specify order when retrieving records from database
306 //
307 // db.Order("name DESC")
308 // db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})
309 // db.Order(clause.OrderBy{Columns: []clause.OrderByColumn{
310 // {Column: clause.Column{Name: "name"}, Desc: true},
311 // {Column: clause.Column{Name: "age"}, Desc: true},
312 // }})
313 func (db *DB) Order(value interface{}) (tx *DB) {
314 tx = db.getInstance()
315
316 switch v := value.(type) {
317 case clause.OrderBy:
318 tx.Statement.AddClause(v)
319 case clause.OrderByColumn:
320 tx.Statement.AddClause(clause.OrderBy{
321 Columns: []clause.OrderByColumn{v},
322 })
323 case string:
324 if v != "" {
325 tx.Statement.AddClause(clause.OrderBy{
326 Columns: []clause.OrderByColumn{{
327 Column: clause.Column{Name: v, Raw: true},
328 }},
329 })
330 }
331 }
332 return
333 }
334
335 // Limit specify the number of records to be retrieved
336 //
337 // Limit conditions can be cancelled by using `Limit(-1)`.
338 //
339 // // retrieve 3 users
340 // db.Limit(3).Find(&users)
341 // // retrieve 3 users into users1, and all users into users2
342 // db.Limit(3).Find(&users1).Limit(-1).Find(&users2)
343 func (db *DB) Limit(limit int) (tx *DB) {
344 tx = db.getInstance()
345 tx.Statement.AddClause(clause.Limit{Limit: &limit})
346 return
347 }
348
349 // Offset specify the number of records to skip before starting to return the records
350 //
351 // Offset conditions can be cancelled by using `Offset(-1)`.
352 //
353 // // select the third user
354 // db.Offset(2).First(&user)
355 // // select the first user by cancelling an earlier chained offset
356 // db.Offset(5).Offset(-1).First(&user)
357 func (db *DB) Offset(offset int) (tx *DB) {
358 tx = db.getInstance()
359 tx.Statement.AddClause(clause.Limit{Offset: offset})
360 return
361 }
362
363 // Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically
364 //
365 // func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
366 // return db.Where("amount > ?", 1000)
367 // }
368 //
369 // func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
370 // return func (db *gorm.DB) *gorm.DB {
371 // return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
372 // }
373 // }
374 //
375 // db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
376 func (db *DB) Scopes(funcs ...func(*DB) *DB) (tx *DB) {
377 tx = db.getInstance()
378 tx.Statement.scopes = append(tx.Statement.scopes, funcs...)
379 return tx
380 }
381
382 func (db *DB) executeScopes() (tx *DB) {
383 scopes := db.Statement.scopes
384 db.Statement.scopes = nil
385 for _, scope := range scopes {
386 db = scope(db)
387 }
388 return db
389 }
390
391 // Preload preload associations with given conditions
392 //
393 // // get all users, and preload all non-cancelled orders
394 // db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
395 func (db *DB) Preload(query string, args ...interface{}) (tx *DB) {
396 tx = db.getInstance()
397 if tx.Statement.Preloads == nil {
398 tx.Statement.Preloads = map[string][]interface{}{}
399 }
400 tx.Statement.Preloads[query] = args
401 return
402 }
403
404 // Attrs provide attributes used in [FirstOrCreate] or [FirstOrInit]
405 //
406 // Attrs only adds attributes if the record is not found.
407 //
408 // // assign an email if the record is not found
409 // db.Where(User{Name: "non_existing"}).Attrs(User{Email: "[email protected]"}).FirstOrInit(&user)
410 // // user -> User{Name: "non_existing", Email: "[email protected]"}
411 //
412 // // assign an email if the record is not found, otherwise ignore provided email
413 // db.Where(User{Name: "jinzhu"}).Attrs(User{Email: "[email protected]"}).FirstOrInit(&user)
414 // // user -> User{Name: "jinzhu", Age: 20}
415 //
416 // [FirstOrCreate]: https://gorm.io/docs/advanced_query.html#FirstOrCreate
417 // [FirstOrInit]: https://gorm.io/docs/advanced_query.html#FirstOrInit
418 func (db *DB) Attrs(attrs ...interface{}) (tx *DB) {
419 tx = db.getInstance()
420 tx.Statement.attrs = attrs
421 return
422 }
423
424 // Assign provide attributes used in [FirstOrCreate] or [FirstOrInit]
425 //
426 // Assign adds attributes even if the record is found. If using FirstOrCreate, this means that
427 // records will be updated even if they are found.
428 //
429 // // assign an email regardless of if the record is not found
430 // db.Where(User{Name: "non_existing"}).Assign(User{Email: "[email protected]"}).FirstOrInit(&user)
431 // // user -> User{Name: "non_existing", Email: "[email protected]"}
432 //
433 // // assign email regardless of if record is found
434 // db.Where(User{Name: "jinzhu"}).Assign(User{Email: "[email protected]"}).FirstOrInit(&user)
435 // // user -> User{Name: "jinzhu", Age: 20, Email: "[email protected]"}
436 //
437 // [FirstOrCreate]: https://gorm.io/docs/advanced_query.html#FirstOrCreate
438 // [FirstOrInit]: https://gorm.io/docs/advanced_query.html#FirstOrInit
439 func (db *DB) Assign(attrs ...interface{}) (tx *DB) {
440 tx = db.getInstance()
441 tx.Statement.assigns = attrs
442 return
443 }
444
445 // Unscoped disables the global scope of soft deletion in a query.
446 // By default, GORM uses soft deletion, marking records as "deleted"
447 // by setting a timestamp on a specific field (e.g., `deleted_at`).
448 // Unscoped allows queries to include records marked as deleted,
449 // overriding the soft deletion behavior.
450 // Example:
451 //
452 // var users []User
453 // db.Unscoped().Find(&users)
454 // // Retrieves all users, including deleted ones.
455 func (db *DB) Unscoped() (tx *DB) {
456 tx = db.getInstance()
457 tx.Statement.Unscoped = true
458 return
459 }
460
461 func (db *DB) Raw(sql string, values ...interface{}) (tx *DB) {
462 tx = db.getInstance()
463 tx.Statement.SQL = strings.Builder{}
464
465 if strings.Contains(sql, "@") {
466 clause.NamedExpr{SQL: sql, Vars: values}.Build(tx.Statement)
467 } else {
468 clause.Expr{SQL: sql, Vars: values}.Build(tx.Statement)
469 }
470 return
471 }