chainable_api.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. if strings.Count(v, "?") >= len(args) && len(args) > 0 {
  84. tx.Statement.AddClause(clause.Select{
  85. Distinct: db.Statement.Distinct,
  86. Expression: clause.Expr{SQL: v, Vars: args},
  87. })
  88. } else {
  89. tx.Statement.Selects = []string{v}
  90. for _, arg := range args {
  91. switch arg := arg.(type) {
  92. case string:
  93. tx.Statement.Selects = append(tx.Statement.Selects, arg)
  94. case []string:
  95. tx.Statement.Selects = append(tx.Statement.Selects, arg...)
  96. default:
  97. tx.Statement.AddClause(clause.Select{
  98. Distinct: db.Statement.Distinct,
  99. Expression: clause.Expr{SQL: v, Vars: args},
  100. })
  101. return
  102. }
  103. }
  104. delete(tx.Statement.Clauses, "SELECT")
  105. }
  106. default:
  107. tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
  108. }
  109. return
  110. }
  111. // Omit specify fields that you want to ignore when creating, updating and querying
  112. func (db *DB) Omit(columns ...string) (tx *DB) {
  113. tx = db.getInstance()
  114. if len(columns) == 1 && strings.ContainsRune(columns[0], ',') {
  115. tx.Statement.Omits = strings.FieldsFunc(columns[0], utils.IsValidDBNameChar)
  116. } else {
  117. tx.Statement.Omits = columns
  118. }
  119. return
  120. }
  121. // Where add conditions
  122. func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB) {
  123. tx = db.getInstance()
  124. if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
  125. tx.Statement.AddClause(clause.Where{Exprs: conds})
  126. }
  127. return
  128. }
  129. // Not add NOT conditions
  130. func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB) {
  131. tx = db.getInstance()
  132. if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
  133. tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Not(conds...)}})
  134. }
  135. return
  136. }
  137. // Or add OR conditions
  138. func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
  139. tx = db.getInstance()
  140. if conds := tx.Statement.BuildCondition(query, args...); len(conds) > 0 {
  141. tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Or(clause.And(conds...))}})
  142. }
  143. return
  144. }
  145. // Joins specify Joins conditions
  146. // db.Joins("Account").Find(&user)
  147. // db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
  148. func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
  149. tx = db.getInstance()
  150. tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args})
  151. return
  152. }
  153. // Group specify the group method on the find
  154. func (db *DB) Group(name string) (tx *DB) {
  155. tx = db.getInstance()
  156. fields := strings.FieldsFunc(name, utils.IsValidDBNameChar)
  157. tx.Statement.AddClause(clause.GroupBy{
  158. Columns: []clause.Column{{Name: name, Raw: len(fields) != 1}},
  159. })
  160. return
  161. }
  162. // Having specify HAVING conditions for GROUP BY
  163. func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB) {
  164. tx = db.getInstance()
  165. tx.Statement.AddClause(clause.GroupBy{
  166. Having: tx.Statement.BuildCondition(query, args...),
  167. })
  168. return
  169. }
  170. // Order specify order when retrieve records from database
  171. // db.Order("name DESC")
  172. // db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})
  173. func (db *DB) Order(value interface{}) (tx *DB) {
  174. tx = db.getInstance()
  175. switch v := value.(type) {
  176. case clause.OrderByColumn:
  177. tx.Statement.AddClause(clause.OrderBy{
  178. Columns: []clause.OrderByColumn{v},
  179. })
  180. default:
  181. tx.Statement.AddClause(clause.OrderBy{
  182. Columns: []clause.OrderByColumn{{
  183. Column: clause.Column{Name: fmt.Sprint(value), Raw: true},
  184. }},
  185. })
  186. }
  187. return
  188. }
  189. // Limit specify the number of records to be retrieved
  190. func (db *DB) Limit(limit int) (tx *DB) {
  191. tx = db.getInstance()
  192. tx.Statement.AddClause(clause.Limit{Limit: limit})
  193. return
  194. }
  195. // Offset specify the number of records to skip before starting to return the records
  196. func (db *DB) Offset(offset int) (tx *DB) {
  197. tx = db.getInstance()
  198. tx.Statement.AddClause(clause.Limit{Offset: offset})
  199. return
  200. }
  201. // Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically
  202. // func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
  203. // return db.Where("amount > ?", 1000)
  204. // }
  205. //
  206. // func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
  207. // return func (db *gorm.DB) *gorm.DB {
  208. // return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
  209. // }
  210. // }
  211. //
  212. // db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
  213. func (db *DB) Scopes(funcs ...func(*DB) *DB) *DB {
  214. for _, f := range funcs {
  215. db = f(db)
  216. }
  217. return db
  218. }
  219. // Preload preload associations with given conditions
  220. // db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  221. func (db *DB) Preload(query string, args ...interface{}) (tx *DB) {
  222. tx = db.getInstance()
  223. if tx.Statement.Preloads == nil {
  224. tx.Statement.Preloads = map[string][]interface{}{}
  225. }
  226. tx.Statement.Preloads[query] = args
  227. return
  228. }
  229. func (db *DB) Attrs(attrs ...interface{}) (tx *DB) {
  230. tx = db.getInstance()
  231. tx.Statement.attrs = attrs
  232. return
  233. }
  234. func (db *DB) Assign(attrs ...interface{}) (tx *DB) {
  235. tx = db.getInstance()
  236. tx.Statement.assigns = attrs
  237. return
  238. }
  239. func (db *DB) Unscoped() (tx *DB) {
  240. tx = db.getInstance()
  241. tx.Statement.Unscoped = true
  242. return
  243. }
  244. func (db *DB) Raw(sql string, values ...interface{}) (tx *DB) {
  245. tx = db.getInstance()
  246. tx.Statement.SQL = strings.Builder{}
  247. if strings.Contains(sql, "@") {
  248. clause.NamedExpr{SQL: sql, Vars: values}.Build(tx.Statement)
  249. } else {
  250. clause.Expr{SQL: sql, Vars: values}.Build(tx.Statement)
  251. }
  252. return
  253. }