chainable_api.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package gorm
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. "gorm.io/gorm/clause"
  7. "gorm.io/gorm/utils"
  8. )
  9. // Model specify the model you would like to run db operations
  10. // // update all users's name to `hello`
  11. // db.Model(&User{}).Update("name", "hello")
  12. // // if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
  13. // db.Model(&user).Update("name", "hello")
  14. func (db *DB) Model(value interface{}) (tx *DB) {
  15. tx = db.getInstance()
  16. tx.Statement.Model = value
  17. return
  18. }
  19. // Clauses Add clauses
  20. func (db *DB) Clauses(conds ...clause.Expression) (tx *DB) {
  21. tx = db.getInstance()
  22. var whereConds []interface{}
  23. for _, cond := range conds {
  24. if c, ok := cond.(clause.Interface); ok {
  25. tx.Statement.AddClause(c)
  26. } else if optimizer, ok := cond.(StatementModifier); ok {
  27. optimizer.ModifyStatement(tx.Statement)
  28. } else {
  29. whereConds = append(whereConds, cond)
  30. }
  31. }
  32. if len(whereConds) > 0 {
  33. tx.Statement.AddClause(clause.Where{Exprs: tx.Statement.BuildCondition(whereConds[0], whereConds[1:]...)})
  34. }
  35. return
  36. }
  37. var tableRegexp = regexp.MustCompile(`(?i).+? AS (\w+)\s*(?:$|,)`)
  38. // Table specify the table you would like to run db operations
  39. func (db *DB) Table(name string, args ...interface{}) (tx *DB) {
  40. tx = db.getInstance()
  41. if strings.Contains(name, " ") || strings.Contains(name, "`") || len(args) > 0 {
  42. tx.Statement.TableExpr = &clause.Expr{SQL: name, Vars: args}
  43. if results := tableRegexp.FindStringSubmatch(name); len(results) == 2 {
  44. tx.Statement.Table = results[1]
  45. return
  46. }
  47. } else if tables := strings.Split(name, "."); len(tables) == 2 {
  48. tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}
  49. tx.Statement.Table = tables[1]
  50. return
  51. }
  52. tx.Statement.Table = name
  53. return
  54. }
  55. // Distinct specify distinct fields that you want querying
  56. func (db *DB) Distinct(args ...interface{}) (tx *DB) {
  57. tx = db.getInstance()
  58. tx.Statement.Distinct = true
  59. if len(args) > 0 {
  60. tx = tx.Select(args[0], args[1:]...)
  61. }
  62. return
  63. }
  64. // Select specify fields that you want when querying, creating, updating
  65. func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
  66. tx = db.getInstance()
  67. switch v := query.(type) {
  68. case []string:
  69. tx.Statement.Selects = v
  70. for _, arg := range args {
  71. switch arg := arg.(type) {
  72. case string:
  73. tx.Statement.Selects = append(tx.Statement.Selects, arg)
  74. case []string:
  75. tx.Statement.Selects = append(tx.Statement.Selects, arg...)
  76. default:
  77. tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
  78. return
  79. }
  80. }
  81. delete(tx.Statement.Clauses, "SELECT")
  82. case string:
  83. fields := strings.FieldsFunc(v, utils.IsValidDBNameChar)
  84. // normal field names
  85. if len(fields) == 1 || (len(fields) == 3 && strings.ToUpper(fields[1]) == "AS") {
  86. tx.Statement.Selects = []string{v}
  87. for _, arg := range args {
  88. switch arg := arg.(type) {
  89. case string:
  90. tx.Statement.Selects = append(tx.Statement.Selects, arg)
  91. case []string:
  92. tx.Statement.Selects = append(tx.Statement.Selects, arg...)
  93. default:
  94. tx.Statement.AddClause(clause.Select{
  95. Distinct: db.Statement.Distinct,
  96. Expression: clause.Expr{SQL: v, Vars: args},
  97. })
  98. return
  99. }
  100. }
  101. delete(tx.Statement.Clauses, "SELECT")
  102. } else {
  103. tx.Statement.AddClause(clause.Select{
  104. Distinct: db.Statement.Distinct,
  105. Expression: clause.Expr{SQL: v, Vars: args},
  106. })
  107. }
  108. default:
  109. tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
  110. }
  111. return
  112. }
  113. // Omit specify fields that you want to ignore when creating, updating and querying
  114. func (db *DB) Omit(columns ...string) (tx *DB) {
  115. tx = db.getInstance()
  116. if len(columns) == 1 && strings.ContainsRune(columns[0], ',') {
  117. tx.Statement.Omits = strings.FieldsFunc(columns[0], utils.IsValidDBNameChar)
  118. } else {
  119. tx.Statement.Omits = columns
  120. }
  121. return
  122. }
  123. // Where add conditions
  124. func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB) {
  125. tx = db.getInstance()
  126. if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
  127. tx.Statement.AddClause(clause.Where{Exprs: conds})
  128. }
  129. return
  130. }
  131. // Not add NOT conditions
  132. func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB) {
  133. tx = db.getInstance()
  134. if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
  135. tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Not(conds...)}})
  136. }
  137. return
  138. }
  139. // Or add OR conditions
  140. func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
  141. tx = db.getInstance()
  142. if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
  143. tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Or(clause.And(conds...))}})
  144. }
  145. return
  146. }
  147. // Joins specify Joins conditions
  148. // db.Joins("Account").Find(&user)
  149. // db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
  150. func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
  151. tx = db.getInstance()
  152. tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args})
  153. return
  154. }
  155. // Group specify the group method on the find
  156. func (db *DB) Group(name string) (tx *DB) {
  157. tx = db.getInstance()
  158. fields := strings.FieldsFunc(name, utils.IsValidDBNameChar)
  159. tx.Statement.AddClause(clause.GroupBy{
  160. Columns: []clause.Column{{Name: name, Raw: len(fields) != 1}},
  161. })
  162. return
  163. }
  164. // Having specify HAVING conditions for GROUP BY
  165. func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB) {
  166. tx = db.getInstance()
  167. tx.Statement.AddClause(clause.GroupBy{
  168. Having: tx.Statement.BuildCondition(query, args...),
  169. })
  170. return
  171. }
  172. // Order specify order when retrieve records from database
  173. // db.Order("name DESC")
  174. // db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})
  175. func (db *DB) Order(value interface{}) (tx *DB) {
  176. tx = db.getInstance()
  177. switch v := value.(type) {
  178. case clause.OrderByColumn:
  179. tx.Statement.AddClause(clause.OrderBy{
  180. Columns: []clause.OrderByColumn{v},
  181. })
  182. default:
  183. tx.Statement.AddClause(clause.OrderBy{
  184. Columns: []clause.OrderByColumn{{
  185. Column: clause.Column{Name: fmt.Sprint(value), Raw: true},
  186. }},
  187. })
  188. }
  189. return
  190. }
  191. // Limit specify the number of records to be retrieved
  192. func (db *DB) Limit(limit int) (tx *DB) {
  193. tx = db.getInstance()
  194. tx.Statement.AddClause(clause.Limit{Limit: limit})
  195. return
  196. }
  197. // Offset specify the number of records to skip before starting to return the records
  198. func (db *DB) Offset(offset int) (tx *DB) {
  199. tx = db.getInstance()
  200. tx.Statement.AddClause(clause.Limit{Offset: offset})
  201. return
  202. }
  203. // Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically
  204. // func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
  205. // return db.Where("amount > ?", 1000)
  206. // }
  207. //
  208. // func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
  209. // return func (db *gorm.DB) *gorm.DB {
  210. // return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
  211. // }
  212. // }
  213. //
  214. // db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
  215. func (db *DB) Scopes(funcs ...func(*DB) *DB) *DB {
  216. for _, f := range funcs {
  217. db = f(db)
  218. }
  219. return db
  220. }
  221. // Preload preload associations with given conditions
  222. // db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  223. func (db *DB) Preload(query string, args ...interface{}) (tx *DB) {
  224. tx = db.getInstance()
  225. if tx.Statement.Preloads == nil {
  226. tx.Statement.Preloads = map[string][]interface{}{}
  227. }
  228. tx.Statement.Preloads[query] = args
  229. return
  230. }
  231. func (db *DB) Attrs(attrs ...interface{}) (tx *DB) {
  232. tx = db.getInstance()
  233. tx.Statement.attrs = attrs
  234. return
  235. }
  236. func (db *DB) Assign(attrs ...interface{}) (tx *DB) {
  237. tx = db.getInstance()
  238. tx.Statement.assigns = attrs
  239. return
  240. }
  241. func (db *DB) Unscoped() (tx *DB) {
  242. tx = db.getInstance()
  243. tx.Statement.Unscoped = true
  244. return
  245. }
  246. func (db *DB) Raw(sql string, values ...interface{}) (tx *DB) {
  247. tx = db.getInstance()
  248. tx.Statement.SQL = strings.Builder{}
  249. if strings.Contains(sql, "@") {
  250. clause.NamedExpr{SQL: sql, Vars: values}.Build(tx.Statement)
  251. } else {
  252. clause.Expr{SQL: sql, Vars: values}.Build(tx.Statement)
  253. }
  254. return
  255. }