chainable_api.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package gorm
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/jinzhu/gorm/clause"
  6. )
  7. // Model specify the model you would like to run db operations
  8. // // update all users's name to `hello`
  9. // db.Model(&User{}).Update("name", "hello")
  10. // // if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
  11. // db.Model(&user).Update("name", "hello")
  12. func (db *DB) Model(value interface{}) (tx *DB) {
  13. tx = db.getInstance()
  14. tx.Statement.Model = value
  15. return
  16. }
  17. // Clauses Add clauses
  18. func (db *DB) Clauses(conds ...clause.Expression) (tx *DB) {
  19. tx = db.getInstance()
  20. var whereConds []interface{}
  21. for _, cond := range conds {
  22. if c, ok := cond.(clause.Interface); ok {
  23. tx.Statement.AddClause(c)
  24. } else {
  25. whereConds = append(whereConds, cond)
  26. }
  27. }
  28. if len(whereConds) > 0 {
  29. tx.Statement.AddClause(clause.Where{Exprs: tx.Statement.BuildCondtion(whereConds[0], whereConds[1:]...)})
  30. }
  31. return
  32. }
  33. // Table specify the table you would like to run db operations
  34. func (db *DB) Table(name string) (tx *DB) {
  35. tx = db.getInstance()
  36. tx.Statement.Table = name
  37. return
  38. }
  39. // Select specify fields that you want when querying, creating, updating
  40. func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB) {
  41. tx = db.getInstance()
  42. switch v := query.(type) {
  43. case []string:
  44. tx.Statement.Selects = v
  45. for _, arg := range args {
  46. switch arg := arg.(type) {
  47. case string:
  48. tx.Statement.Selects = append(tx.Statement.Selects, arg)
  49. case []string:
  50. tx.Statement.Selects = append(tx.Statement.Selects, arg...)
  51. default:
  52. tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
  53. return
  54. }
  55. }
  56. case string:
  57. fields := strings.FieldsFunc(v, isChar)
  58. // normal field names
  59. if len(fields) == 1 || (len(fields) == 3 && strings.ToUpper(fields[1]) == "AS") {
  60. tx.Statement.Selects = fields
  61. for _, arg := range args {
  62. switch arg := arg.(type) {
  63. case string:
  64. tx.Statement.Selects = append(tx.Statement.Selects, arg)
  65. case []string:
  66. tx.Statement.Selects = append(tx.Statement.Selects, arg...)
  67. default:
  68. tx.Statement.AddClause(clause.Select{
  69. Expression: clause.Expr{SQL: v, Vars: args},
  70. })
  71. return
  72. }
  73. }
  74. } else {
  75. tx.Statement.AddClause(clause.Select{
  76. Expression: clause.Expr{SQL: v, Vars: args},
  77. })
  78. }
  79. default:
  80. tx.AddError(fmt.Errorf("unsupported select args %v %v", query, args))
  81. }
  82. return
  83. }
  84. // Omit specify fields that you want to ignore when creating, updating and querying
  85. func (db *DB) Omit(columns ...string) (tx *DB) {
  86. tx = db.getInstance()
  87. if len(columns) == 1 && strings.ContainsRune(columns[0], ',') {
  88. tx.Statement.Omits = strings.FieldsFunc(columns[0], isChar)
  89. } else {
  90. tx.Statement.Omits = columns
  91. }
  92. return
  93. }
  94. func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB) {
  95. tx = db.getInstance()
  96. tx.Statement.AddClause(clause.Where{Exprs: tx.Statement.BuildCondtion(query, args...)})
  97. return
  98. }
  99. // Not add NOT condition
  100. func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB) {
  101. tx = db.getInstance()
  102. tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Not(tx.Statement.BuildCondtion(query, args...)...)}})
  103. return
  104. }
  105. // Or add OR conditions
  106. func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
  107. tx = db.getInstance()
  108. tx.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.Or(tx.Statement.BuildCondtion(query, args...)...)}})
  109. return
  110. }
  111. // Joins specify Joins conditions
  112. // db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
  113. func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
  114. tx = db.getInstance()
  115. return
  116. }
  117. // Group specify the group method on the find
  118. func (db *DB) Group(column string) (tx *DB) {
  119. tx = db.getInstance()
  120. return
  121. }
  122. // Having specify HAVING conditions for GROUP BY
  123. func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB) {
  124. tx = db.getInstance()
  125. return
  126. }
  127. // Order specify order when retrieve records from database
  128. // db.Order("name DESC")
  129. // db.Order(gorm.Expr("name = ? DESC", "first")) // sql expression
  130. func (db *DB) Order(value interface{}) (tx *DB) {
  131. tx = db.getInstance()
  132. switch v := value.(type) {
  133. case clause.OrderByColumn:
  134. tx.Statement.AddClause(clause.OrderBy{
  135. Columns: []clause.OrderByColumn{v},
  136. })
  137. default:
  138. tx.Statement.AddClause(clause.OrderBy{
  139. Columns: []clause.OrderByColumn{{
  140. Column: clause.Column{Name: fmt.Sprint(value), Raw: true},
  141. }},
  142. })
  143. }
  144. return
  145. }
  146. // Limit specify the number of records to be retrieved
  147. func (db *DB) Limit(limit int64) (tx *DB) {
  148. tx = db.getInstance()
  149. return
  150. }
  151. // Offset specify the number of records to skip before starting to return the records
  152. func (db *DB) Offset(offset int64) (tx *DB) {
  153. tx = db.getInstance()
  154. return
  155. }
  156. // Scopes pass current database connection to arguments `func(*DB) *DB`, which could be used to add conditions dynamically
  157. // func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
  158. // return db.Where("amount > ?", 1000)
  159. // }
  160. //
  161. // func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
  162. // return func (db *gorm.DB) *gorm.DB {
  163. // return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
  164. // }
  165. // }
  166. //
  167. // db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
  168. func (db *DB) Scopes(funcs ...func(*DB) *DB) *DB {
  169. for _, f := range funcs {
  170. db = f(db)
  171. }
  172. return db
  173. }
  174. // Preload preload associations with given conditions
  175. // db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  176. func (db *DB) Preload(column string, conditions ...interface{}) (tx *DB) {
  177. tx = db.getInstance()
  178. return
  179. }
  180. func (db *DB) Assign(attrs ...interface{}) (tx *DB) {
  181. tx = db.getInstance()
  182. return
  183. }
  184. func (db *DB) Attrs(attrs ...interface{}) (tx *DB) {
  185. tx = db.getInstance()
  186. return
  187. }
  188. func (db *DB) Unscoped() (tx *DB) {
  189. tx = db.getInstance()
  190. return
  191. }
  192. func (db *DB) Raw(sql string, values ...interface{}) (tx *DB) {
  193. tx = db.getInstance()
  194. tx.Statement.SQL = strings.Builder{}
  195. clause.Expr{SQL: sql, Vars: values}.Build(tx.Statement)
  196. return
  197. }