main.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. package gorm
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. // DB contains information for current db connection
  12. type DB struct {
  13. sync.RWMutex
  14. Value interface{}
  15. Error error
  16. RowsAffected int64
  17. // single db
  18. db SQLCommon
  19. blockGlobalUpdate bool
  20. logMode logModeValue
  21. logger logger
  22. search *search
  23. values sync.Map
  24. // global db
  25. parent *DB
  26. callbacks *Callback
  27. dialect Dialect
  28. singularTable bool
  29. }
  30. type logModeValue int
  31. const (
  32. defaultLogMode logModeValue = iota
  33. noLogMode
  34. detailedLogMode
  35. )
  36. // Open initialize a new db connection, need to import driver first, e.g:
  37. //
  38. // import _ "github.com/go-sql-driver/mysql"
  39. // func main() {
  40. // db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
  41. // }
  42. // GORM has wrapped some drivers, for easier to remember driver's import path, so you could import the mysql driver with
  43. // import _ "github.com/jinzhu/gorm/dialects/mysql"
  44. // // import _ "github.com/jinzhu/gorm/dialects/postgres"
  45. // // import _ "github.com/jinzhu/gorm/dialects/sqlite"
  46. // // import _ "github.com/jinzhu/gorm/dialects/mssql"
  47. func Open(dialect string, args ...interface{}) (db *DB, err error) {
  48. if len(args) == 0 {
  49. err = errors.New("invalid database source")
  50. return nil, err
  51. }
  52. var source string
  53. var dbSQL SQLCommon
  54. var ownDbSQL bool
  55. switch value := args[0].(type) {
  56. case string:
  57. var driver = dialect
  58. if len(args) == 1 {
  59. source = value
  60. } else if len(args) >= 2 {
  61. driver = value
  62. source = args[1].(string)
  63. }
  64. dbSQL, err = sql.Open(driver, source)
  65. ownDbSQL = true
  66. case SQLCommon:
  67. dbSQL = value
  68. ownDbSQL = false
  69. default:
  70. return nil, fmt.Errorf("invalid database source: %v is not a valid type", value)
  71. }
  72. db = &DB{
  73. db: dbSQL,
  74. logger: defaultLogger,
  75. callbacks: DefaultCallback,
  76. dialect: newDialect(dialect, dbSQL),
  77. }
  78. db.parent = db
  79. if err != nil {
  80. return
  81. }
  82. // Send a ping to make sure the database connection is alive.
  83. if d, ok := dbSQL.(*sql.DB); ok {
  84. if err = d.Ping(); err != nil && ownDbSQL {
  85. d.Close()
  86. }
  87. }
  88. return
  89. }
  90. // New clone a new db connection without search conditions
  91. func (s *DB) New() *DB {
  92. clone := s.clone()
  93. clone.search = nil
  94. clone.Value = nil
  95. return clone
  96. }
  97. type closer interface {
  98. Close() error
  99. }
  100. // Close close current db connection. If database connection is not an io.Closer, returns an error.
  101. func (s *DB) Close() error {
  102. if db, ok := s.parent.db.(closer); ok {
  103. return db.Close()
  104. }
  105. return errors.New("can't close current db")
  106. }
  107. // DB get `*sql.DB` from current connection
  108. // If the underlying database connection is not a *sql.DB, returns nil
  109. func (s *DB) DB() *sql.DB {
  110. db, _ := s.db.(*sql.DB)
  111. return db
  112. }
  113. // CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-GORM code.
  114. func (s *DB) CommonDB() SQLCommon {
  115. return s.db
  116. }
  117. // Dialect get dialect
  118. func (s *DB) Dialect() Dialect {
  119. return s.dialect
  120. }
  121. // Callback return `Callbacks` container, you could add/change/delete callbacks with it
  122. // db.Callback().Create().Register("update_created_at", updateCreated)
  123. // Refer https://jinzhu.github.io/gorm/development.html#callbacks
  124. func (s *DB) Callback() *Callback {
  125. s.parent.callbacks = s.parent.callbacks.clone()
  126. return s.parent.callbacks
  127. }
  128. // SetLogger replace default logger
  129. func (s *DB) SetLogger(log logger) {
  130. s.logger = log
  131. }
  132. // LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs
  133. func (s *DB) LogMode(enable bool) *DB {
  134. if enable {
  135. s.logMode = detailedLogMode
  136. } else {
  137. s.logMode = noLogMode
  138. }
  139. return s
  140. }
  141. // BlockGlobalUpdate if true, generates an error on update/delete without where clause.
  142. // This is to prevent eventual error with empty objects updates/deletions
  143. func (s *DB) BlockGlobalUpdate(enable bool) *DB {
  144. s.blockGlobalUpdate = enable
  145. return s
  146. }
  147. // HasBlockGlobalUpdate return state of block
  148. func (s *DB) HasBlockGlobalUpdate() bool {
  149. return s.blockGlobalUpdate
  150. }
  151. // SingularTable use singular table by default
  152. func (s *DB) SingularTable(enable bool) {
  153. s.parent.Lock()
  154. defer s.parent.Unlock()
  155. s.parent.singularTable = enable
  156. }
  157. // NewScope create a scope for current operation
  158. func (s *DB) NewScope(value interface{}) *Scope {
  159. dbClone := s.clone()
  160. dbClone.Value = value
  161. scope := &Scope{db: dbClone, Value: value}
  162. if s.search != nil {
  163. scope.Search = s.search.clone()
  164. } else {
  165. scope.Search = &search{}
  166. }
  167. return scope
  168. }
  169. // QueryExpr returns the query as expr object
  170. func (s *DB) QueryExpr() *expr {
  171. scope := s.NewScope(s.Value)
  172. scope.InstanceSet("skip_bindvar", true)
  173. scope.prepareQuerySQL()
  174. return Expr(scope.SQL, scope.SQLVars...)
  175. }
  176. // SubQuery returns the query as sub query
  177. func (s *DB) SubQuery() *expr {
  178. scope := s.NewScope(s.Value)
  179. scope.InstanceSet("skip_bindvar", true)
  180. scope.prepareQuerySQL()
  181. return Expr(fmt.Sprintf("(%v)", scope.SQL), scope.SQLVars...)
  182. }
  183. // Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
  184. func (s *DB) Where(query interface{}, args ...interface{}) *DB {
  185. return s.clone().search.Where(query, args...).db
  186. }
  187. // Or filter records that match before conditions or this one, similar to `Where`
  188. func (s *DB) Or(query interface{}, args ...interface{}) *DB {
  189. return s.clone().search.Or(query, args...).db
  190. }
  191. // Not filter records that don't match current conditions, similar to `Where`
  192. func (s *DB) Not(query interface{}, args ...interface{}) *DB {
  193. return s.clone().search.Not(query, args...).db
  194. }
  195. // Limit specify the number of records to be retrieved
  196. func (s *DB) Limit(limit interface{}) *DB {
  197. return s.clone().search.Limit(limit).db
  198. }
  199. // Offset specify the number of records to skip before starting to return the records
  200. func (s *DB) Offset(offset interface{}) *DB {
  201. return s.clone().search.Offset(offset).db
  202. }
  203. // Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions
  204. // db.Order("name DESC")
  205. // db.Order("name DESC", true) // reorder
  206. // db.Order(gorm.Expr("name = ? DESC", "first")) // sql expression
  207. func (s *DB) Order(value interface{}, reorder ...bool) *DB {
  208. return s.clone().search.Order(value, reorder...).db
  209. }
  210. // Select specify fields that you want to retrieve from database when querying, by default, will select all fields;
  211. // When creating/updating, specify fields that you want to save to database
  212. func (s *DB) Select(query interface{}, args ...interface{}) *DB {
  213. return s.clone().search.Select(query, args...).db
  214. }
  215. // Omit specify fields that you want to ignore when saving to database for creating, updating
  216. func (s *DB) Omit(columns ...string) *DB {
  217. return s.clone().search.Omit(columns...).db
  218. }
  219. // Group specify the group method on the find
  220. func (s *DB) Group(query string) *DB {
  221. return s.clone().search.Group(query).db
  222. }
  223. // Having specify HAVING conditions for GROUP BY
  224. func (s *DB) Having(query interface{}, values ...interface{}) *DB {
  225. return s.clone().search.Having(query, values...).db
  226. }
  227. // Joins specify Joins conditions
  228. // db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
  229. func (s *DB) Joins(query string, args ...interface{}) *DB {
  230. return s.clone().search.Joins(query, args...).db
  231. }
  232. // Scopes pass current database connection to arguments `func(*DB) *DB`, which could be used to add conditions dynamically
  233. // func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
  234. // return db.Where("amount > ?", 1000)
  235. // }
  236. //
  237. // func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
  238. // return func (db *gorm.DB) *gorm.DB {
  239. // return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
  240. // }
  241. // }
  242. //
  243. // db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
  244. // Refer https://jinzhu.github.io/gorm/crud.html#scopes
  245. func (s *DB) Scopes(funcs ...func(*DB) *DB) *DB {
  246. for _, f := range funcs {
  247. s = f(s)
  248. }
  249. return s
  250. }
  251. // Unscoped return all record including deleted record, refer Soft Delete https://jinzhu.github.io/gorm/crud.html#soft-delete
  252. func (s *DB) Unscoped() *DB {
  253. return s.clone().search.unscoped().db
  254. }
  255. // Attrs initialize struct with argument if record not found with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
  256. func (s *DB) Attrs(attrs ...interface{}) *DB {
  257. return s.clone().search.Attrs(attrs...).db
  258. }
  259. // Assign assign result with argument regardless it is found or not with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate
  260. func (s *DB) Assign(attrs ...interface{}) *DB {
  261. return s.clone().search.Assign(attrs...).db
  262. }
  263. // First find first record that match given conditions, order by primary key
  264. func (s *DB) First(out interface{}, where ...interface{}) *DB {
  265. newScope := s.NewScope(out)
  266. newScope.Search.Limit(1)
  267. return newScope.Set("gorm:order_by_primary_key", "ASC").
  268. inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
  269. }
  270. // Take return a record that match given conditions, the order will depend on the database implementation
  271. func (s *DB) Take(out interface{}, where ...interface{}) *DB {
  272. newScope := s.NewScope(out)
  273. newScope.Search.Limit(1)
  274. return newScope.inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
  275. }
  276. // Last find last record that match given conditions, order by primary key
  277. func (s *DB) Last(out interface{}, where ...interface{}) *DB {
  278. newScope := s.NewScope(out)
  279. newScope.Search.Limit(1)
  280. return newScope.Set("gorm:order_by_primary_key", "DESC").
  281. inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
  282. }
  283. // Find find records that match given conditions
  284. func (s *DB) Find(out interface{}, where ...interface{}) *DB {
  285. return s.NewScope(out).inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
  286. }
  287. //Preloads preloads relations, don`t touch out
  288. func (s *DB) Preloads(out interface{}) *DB {
  289. return s.NewScope(out).InstanceSet("gorm:only_preload", 1).callCallbacks(s.parent.callbacks.queries).db
  290. }
  291. // Scan scan value to a struct
  292. func (s *DB) Scan(dest interface{}) *DB {
  293. return s.NewScope(s.Value).Set("gorm:query_destination", dest).callCallbacks(s.parent.callbacks.queries).db
  294. }
  295. // Row return `*sql.Row` with given conditions
  296. func (s *DB) Row() *sql.Row {
  297. return s.NewScope(s.Value).row()
  298. }
  299. // Rows return `*sql.Rows` with given conditions
  300. func (s *DB) Rows() (*sql.Rows, error) {
  301. return s.NewScope(s.Value).rows()
  302. }
  303. // ScanRows scan `*sql.Rows` to give struct
  304. func (s *DB) ScanRows(rows *sql.Rows, result interface{}) error {
  305. var (
  306. scope = s.NewScope(result)
  307. clone = scope.db
  308. columns, err = rows.Columns()
  309. )
  310. if clone.AddError(err) == nil {
  311. scope.scan(rows, columns, scope.Fields())
  312. }
  313. return clone.Error
  314. }
  315. // Pluck used to query single column from a model as a map
  316. // var ages []int64
  317. // db.Find(&users).Pluck("age", &ages)
  318. func (s *DB) Pluck(column string, value interface{}) *DB {
  319. return s.NewScope(s.Value).pluck(column, value).db
  320. }
  321. // Count get how many records for a model
  322. func (s *DB) Count(value interface{}) *DB {
  323. return s.NewScope(s.Value).count(value).db
  324. }
  325. // Related get related associations
  326. func (s *DB) Related(value interface{}, foreignKeys ...string) *DB {
  327. return s.NewScope(s.Value).related(value, foreignKeys...).db
  328. }
  329. // FirstOrInit find first matched record or initialize a new one with given conditions (only works with struct, map conditions)
  330. // https://jinzhu.github.io/gorm/crud.html#firstorinit
  331. func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB {
  332. c := s.clone()
  333. if result := c.First(out, where...); result.Error != nil {
  334. if !result.RecordNotFound() {
  335. return result
  336. }
  337. c.NewScope(out).inlineCondition(where...).initialize()
  338. } else {
  339. c.NewScope(out).updatedAttrsWithValues(c.search.assignAttrs)
  340. }
  341. return c
  342. }
  343. // FirstOrCreate find first matched record or create a new one with given conditions (only works with struct, map conditions)
  344. // https://jinzhu.github.io/gorm/crud.html#firstorcreate
  345. func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB {
  346. c := s.clone()
  347. if result := s.First(out, where...); result.Error != nil {
  348. if !result.RecordNotFound() {
  349. return result
  350. }
  351. return c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(c.parent.callbacks.creates).db
  352. } else if len(c.search.assignAttrs) > 0 {
  353. return c.NewScope(out).InstanceSet("gorm:update_interface", c.search.assignAttrs).callCallbacks(c.parent.callbacks.updates).db
  354. }
  355. return c
  356. }
  357. // Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
  358. func (s *DB) Update(attrs ...interface{}) *DB {
  359. return s.Updates(toSearchableMap(attrs...), true)
  360. }
  361. // Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
  362. func (s *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) *DB {
  363. return s.NewScope(s.Value).
  364. Set("gorm:ignore_protected_attrs", len(ignoreProtectedAttrs) > 0).
  365. InstanceSet("gorm:update_interface", values).
  366. callCallbacks(s.parent.callbacks.updates).db
  367. }
  368. // UpdateColumn update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
  369. func (s *DB) UpdateColumn(attrs ...interface{}) *DB {
  370. return s.UpdateColumns(toSearchableMap(attrs...))
  371. }
  372. // UpdateColumns update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
  373. func (s *DB) UpdateColumns(values interface{}) *DB {
  374. return s.NewScope(s.Value).
  375. Set("gorm:update_column", true).
  376. Set("gorm:save_associations", false).
  377. InstanceSet("gorm:update_interface", values).
  378. callCallbacks(s.parent.callbacks.updates).db
  379. }
  380. // Save update value in database, if the value doesn't have primary key, will insert it
  381. func (s *DB) Save(value interface{}) *DB {
  382. scope := s.NewScope(value)
  383. if !scope.PrimaryKeyZero() {
  384. newDB := scope.callCallbacks(s.parent.callbacks.updates).db
  385. if newDB.Error == nil && newDB.RowsAffected == 0 {
  386. return s.New().FirstOrCreate(value)
  387. }
  388. return newDB
  389. }
  390. return scope.callCallbacks(s.parent.callbacks.creates).db
  391. }
  392. // Create insert the value into database
  393. func (s *DB) Create(value interface{}) *DB {
  394. scope := s.NewScope(value)
  395. return scope.callCallbacks(s.parent.callbacks.creates).db
  396. }
  397. // Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition
  398. func (s *DB) Delete(value interface{}, where ...interface{}) *DB {
  399. return s.NewScope(value).inlineCondition(where...).callCallbacks(s.parent.callbacks.deletes).db
  400. }
  401. // Raw use raw sql as conditions, won't run it unless invoked by other methods
  402. // db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)
  403. func (s *DB) Raw(sql string, values ...interface{}) *DB {
  404. return s.clone().search.Raw(true).Where(sql, values...).db
  405. }
  406. // Exec execute raw sql
  407. func (s *DB) Exec(sql string, values ...interface{}) *DB {
  408. scope := s.NewScope(nil)
  409. generatedSQL := scope.buildCondition(map[string]interface{}{"query": sql, "args": values}, true)
  410. generatedSQL = strings.TrimSuffix(strings.TrimPrefix(generatedSQL, "("), ")")
  411. scope.Raw(generatedSQL)
  412. return scope.Exec().db
  413. }
  414. // Model specify the model you would like to run db operations
  415. // // update all users's name to `hello`
  416. // db.Model(&User{}).Update("name", "hello")
  417. // // if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
  418. // db.Model(&user).Update("name", "hello")
  419. func (s *DB) Model(value interface{}) *DB {
  420. c := s.clone()
  421. c.Value = value
  422. return c
  423. }
  424. // Table specify the table you would like to run db operations
  425. func (s *DB) Table(name string) *DB {
  426. clone := s.clone()
  427. clone.search.Table(name)
  428. clone.Value = nil
  429. return clone
  430. }
  431. // Debug start debug mode
  432. func (s *DB) Debug() *DB {
  433. return s.clone().LogMode(true)
  434. }
  435. // Begin begin a transaction
  436. func (s *DB) Begin() *DB {
  437. c := s.clone()
  438. if db, ok := c.db.(sqlDb); ok && db != nil {
  439. tx, err := db.Begin()
  440. c.db = interface{}(tx).(SQLCommon)
  441. c.dialect.SetDB(c.db)
  442. c.AddError(err)
  443. } else {
  444. c.AddError(ErrCantStartTransaction)
  445. }
  446. return c
  447. }
  448. // Commit commit a transaction
  449. func (s *DB) Commit() *DB {
  450. var emptySQLTx *sql.Tx
  451. if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx {
  452. s.AddError(db.Commit())
  453. } else {
  454. s.AddError(ErrInvalidTransaction)
  455. }
  456. return s
  457. }
  458. // Rollback rollback a transaction
  459. func (s *DB) Rollback() *DB {
  460. var emptySQLTx *sql.Tx
  461. if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx {
  462. s.AddError(db.Rollback())
  463. } else {
  464. s.AddError(ErrInvalidTransaction)
  465. }
  466. return s
  467. }
  468. // NewRecord check if value's primary key is blank
  469. func (s *DB) NewRecord(value interface{}) bool {
  470. return s.NewScope(value).PrimaryKeyZero()
  471. }
  472. // RecordNotFound check if returning ErrRecordNotFound error
  473. func (s *DB) RecordNotFound() bool {
  474. for _, err := range s.GetErrors() {
  475. if err == ErrRecordNotFound {
  476. return true
  477. }
  478. }
  479. return false
  480. }
  481. // CreateTable create table for models
  482. func (s *DB) CreateTable(models ...interface{}) *DB {
  483. db := s.Unscoped()
  484. for _, model := range models {
  485. db = db.NewScope(model).createTable().db
  486. }
  487. return db
  488. }
  489. // DropTable drop table for models
  490. func (s *DB) DropTable(values ...interface{}) *DB {
  491. db := s.clone()
  492. for _, value := range values {
  493. if tableName, ok := value.(string); ok {
  494. db = db.Table(tableName)
  495. }
  496. db = db.NewScope(value).dropTable().db
  497. }
  498. return db
  499. }
  500. // DropTableIfExists drop table if it is exist
  501. func (s *DB) DropTableIfExists(values ...interface{}) *DB {
  502. db := s.clone()
  503. for _, value := range values {
  504. if s.HasTable(value) {
  505. db.AddError(s.DropTable(value).Error)
  506. }
  507. }
  508. return db
  509. }
  510. // HasTable check has table or not
  511. func (s *DB) HasTable(value interface{}) bool {
  512. var (
  513. scope = s.NewScope(value)
  514. tableName string
  515. )
  516. if name, ok := value.(string); ok {
  517. tableName = name
  518. } else {
  519. tableName = scope.TableName()
  520. }
  521. has := scope.Dialect().HasTable(tableName)
  522. s.AddError(scope.db.Error)
  523. return has
  524. }
  525. // AutoMigrate run auto migration for given models, will only add missing fields, won't delete/change current data
  526. func (s *DB) AutoMigrate(values ...interface{}) *DB {
  527. db := s.Unscoped()
  528. for _, value := range values {
  529. db = db.NewScope(value).autoMigrate().db
  530. }
  531. return db
  532. }
  533. // ModifyColumn modify column to type
  534. func (s *DB) ModifyColumn(column string, typ string) *DB {
  535. scope := s.NewScope(s.Value)
  536. scope.modifyColumn(column, typ)
  537. return scope.db
  538. }
  539. // DropColumn drop a column
  540. func (s *DB) DropColumn(column string) *DB {
  541. scope := s.NewScope(s.Value)
  542. scope.dropColumn(column)
  543. return scope.db
  544. }
  545. // AddIndex add index for columns with given name
  546. func (s *DB) AddIndex(indexName string, columns ...string) *DB {
  547. scope := s.Unscoped().NewScope(s.Value)
  548. scope.addIndex(false, indexName, columns...)
  549. return scope.db
  550. }
  551. // AddUniqueIndex add unique index for columns with given name
  552. func (s *DB) AddUniqueIndex(indexName string, columns ...string) *DB {
  553. scope := s.Unscoped().NewScope(s.Value)
  554. scope.addIndex(true, indexName, columns...)
  555. return scope.db
  556. }
  557. // RemoveIndex remove index with name
  558. func (s *DB) RemoveIndex(indexName string) *DB {
  559. scope := s.NewScope(s.Value)
  560. scope.removeIndex(indexName)
  561. return scope.db
  562. }
  563. // AddForeignKey Add foreign key to the given scope, e.g:
  564. // db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
  565. func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate string) *DB {
  566. scope := s.NewScope(s.Value)
  567. scope.addForeignKey(field, dest, onDelete, onUpdate)
  568. return scope.db
  569. }
  570. // RemoveForeignKey Remove foreign key from the given scope, e.g:
  571. // db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
  572. func (s *DB) RemoveForeignKey(field string, dest string) *DB {
  573. scope := s.clone().NewScope(s.Value)
  574. scope.removeForeignKey(field, dest)
  575. return scope.db
  576. }
  577. // Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
  578. func (s *DB) Association(column string) *Association {
  579. var err error
  580. var scope = s.Set("gorm:association:source", s.Value).NewScope(s.Value)
  581. if primaryField := scope.PrimaryField(); primaryField.IsBlank {
  582. err = errors.New("primary key can't be nil")
  583. } else {
  584. if field, ok := scope.FieldByName(column); ok {
  585. if field.Relationship == nil || len(field.Relationship.ForeignFieldNames) == 0 {
  586. err = fmt.Errorf("invalid association %v for %v", column, scope.IndirectValue().Type())
  587. } else {
  588. return &Association{scope: scope, column: column, field: field}
  589. }
  590. } else {
  591. err = fmt.Errorf("%v doesn't have column %v", scope.IndirectValue().Type(), column)
  592. }
  593. }
  594. return &Association{Error: err}
  595. }
  596. // Preload preload associations with given conditions
  597. // db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  598. func (s *DB) Preload(column string, conditions ...interface{}) *DB {
  599. return s.clone().search.Preload(column, conditions...).db
  600. }
  601. // Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting
  602. func (s *DB) Set(name string, value interface{}) *DB {
  603. return s.clone().InstantSet(name, value)
  604. }
  605. // InstantSet instant set setting, will affect current db
  606. func (s *DB) InstantSet(name string, value interface{}) *DB {
  607. s.values.Store(name, value)
  608. return s
  609. }
  610. // Get get setting by name
  611. func (s *DB) Get(name string) (value interface{}, ok bool) {
  612. value, ok = s.values.Load(name)
  613. return
  614. }
  615. // SetJoinTableHandler set a model's join table handler for a relation
  616. func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface) {
  617. scope := s.NewScope(source)
  618. for _, field := range scope.GetModelStruct().StructFields {
  619. if field.Name == column || field.DBName == column {
  620. if many2many, _ := field.TagSettingsGet("MANY2MANY"); many2many != "" {
  621. source := (&Scope{Value: source}).GetModelStruct().ModelType
  622. destination := (&Scope{Value: reflect.New(field.Struct.Type).Interface()}).GetModelStruct().ModelType
  623. handler.Setup(field.Relationship, many2many, source, destination)
  624. field.Relationship.JoinTableHandler = handler
  625. if table := handler.Table(s); scope.Dialect().HasTable(table) {
  626. s.Table(table).AutoMigrate(handler)
  627. }
  628. }
  629. }
  630. }
  631. }
  632. // AddError add error to the db
  633. func (s *DB) AddError(err error) error {
  634. if err != nil {
  635. if err != ErrRecordNotFound {
  636. if s.logMode == defaultLogMode {
  637. go s.print("error", fileWithLineNum(), err)
  638. } else {
  639. s.log(err)
  640. }
  641. errors := Errors(s.GetErrors())
  642. errors = errors.Add(err)
  643. if len(errors) > 1 {
  644. err = errors
  645. }
  646. }
  647. s.Error = err
  648. }
  649. return err
  650. }
  651. // GetErrors get happened errors from the db
  652. func (s *DB) GetErrors() []error {
  653. if errs, ok := s.Error.(Errors); ok {
  654. return errs
  655. } else if s.Error != nil {
  656. return []error{s.Error}
  657. }
  658. return []error{}
  659. }
  660. ////////////////////////////////////////////////////////////////////////////////
  661. // Private Methods For DB
  662. ////////////////////////////////////////////////////////////////////////////////
  663. func (s *DB) clone() *DB {
  664. db := &DB{
  665. db: s.db,
  666. parent: s.parent,
  667. logger: s.logger,
  668. logMode: s.logMode,
  669. Value: s.Value,
  670. Error: s.Error,
  671. blockGlobalUpdate: s.blockGlobalUpdate,
  672. dialect: newDialect(s.dialect.GetName(), s.db),
  673. }
  674. s.values.Range(func(k, v interface{}) bool {
  675. db.values.Store(k, v)
  676. return true
  677. })
  678. if s.search == nil {
  679. db.search = &search{limit: -1, offset: -1}
  680. } else {
  681. db.search = s.search.clone()
  682. }
  683. db.search.db = db
  684. return db
  685. }
  686. func (s *DB) print(v ...interface{}) {
  687. s.logger.Print(v...)
  688. }
  689. func (s *DB) log(v ...interface{}) {
  690. if s != nil && s.logMode == detailedLogMode {
  691. s.print(append([]interface{}{"log", fileWithLineNum()}, v...)...)
  692. }
  693. }
  694. func (s *DB) slog(sql string, t time.Time, vars ...interface{}) {
  695. if s.logMode == detailedLogMode {
  696. s.print("sql", fileWithLineNum(), NowFunc().Sub(t), sql, vars, s.RowsAffected)
  697. }
  698. }