main.go 23 KB

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