Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1681 lines
45KB

  1. // Copyright 2015 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "bufio"
  7. "bytes"
  8. "context"
  9. "database/sql"
  10. "encoding/gob"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "os"
  15. "reflect"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "xorm.io/builder"
  21. "xorm.io/core"
  22. )
  23. // Engine is the major struct of xorm, it means a database manager.
  24. // Commonly, an application only need one engine
  25. type Engine struct {
  26. db *core.DB
  27. dialect core.Dialect
  28. ColumnMapper core.IMapper
  29. TableMapper core.IMapper
  30. TagIdentifier string
  31. Tables map[reflect.Type]*core.Table
  32. mutex *sync.RWMutex
  33. Cacher core.Cacher
  34. showSQL bool
  35. showExecTime bool
  36. logger core.ILogger
  37. TZLocation *time.Location // The timezone of the application
  38. DatabaseTZ *time.Location // The timezone of the database
  39. disableGlobalCache bool
  40. tagHandlers map[string]tagHandler
  41. engineGroup *EngineGroup
  42. cachers map[string]core.Cacher
  43. cacherLock sync.RWMutex
  44. defaultContext context.Context
  45. }
  46. func (engine *Engine) setCacher(tableName string, cacher core.Cacher) {
  47. engine.cacherLock.Lock()
  48. engine.cachers[tableName] = cacher
  49. engine.cacherLock.Unlock()
  50. }
  51. func (engine *Engine) SetCacher(tableName string, cacher core.Cacher) {
  52. engine.setCacher(tableName, cacher)
  53. }
  54. func (engine *Engine) getCacher(tableName string) core.Cacher {
  55. var cacher core.Cacher
  56. var ok bool
  57. engine.cacherLock.RLock()
  58. cacher, ok = engine.cachers[tableName]
  59. engine.cacherLock.RUnlock()
  60. if !ok && !engine.disableGlobalCache {
  61. cacher = engine.Cacher
  62. }
  63. return cacher
  64. }
  65. func (engine *Engine) GetCacher(tableName string) core.Cacher {
  66. return engine.getCacher(tableName)
  67. }
  68. // BufferSize sets buffer size for iterate
  69. func (engine *Engine) BufferSize(size int) *Session {
  70. session := engine.NewSession()
  71. session.isAutoClose = true
  72. return session.BufferSize(size)
  73. }
  74. // CondDeleted returns the conditions whether a record is soft deleted.
  75. func (engine *Engine) CondDeleted(colName string) builder.Cond {
  76. if engine.dialect.DBType() == core.MSSQL {
  77. return builder.IsNull{colName}
  78. }
  79. return builder.IsNull{colName}.Or(builder.Eq{colName: zeroTime1})
  80. }
  81. // ShowSQL show SQL statement or not on logger if log level is great than INFO
  82. func (engine *Engine) ShowSQL(show ...bool) {
  83. engine.logger.ShowSQL(show...)
  84. if len(show) == 0 {
  85. engine.showSQL = true
  86. } else {
  87. engine.showSQL = show[0]
  88. }
  89. }
  90. // ShowExecTime show SQL statement and execute time or not on logger if log level is great than INFO
  91. func (engine *Engine) ShowExecTime(show ...bool) {
  92. if len(show) == 0 {
  93. engine.showExecTime = true
  94. } else {
  95. engine.showExecTime = show[0]
  96. }
  97. }
  98. // Logger return the logger interface
  99. func (engine *Engine) Logger() core.ILogger {
  100. return engine.logger
  101. }
  102. // SetLogger set the new logger
  103. func (engine *Engine) SetLogger(logger core.ILogger) {
  104. engine.logger = logger
  105. engine.showSQL = logger.IsShowSQL()
  106. engine.dialect.SetLogger(logger)
  107. }
  108. // SetLogLevel sets the logger level
  109. func (engine *Engine) SetLogLevel(level core.LogLevel) {
  110. engine.logger.SetLevel(level)
  111. }
  112. // SetDisableGlobalCache disable global cache or not
  113. func (engine *Engine) SetDisableGlobalCache(disable bool) {
  114. if engine.disableGlobalCache != disable {
  115. engine.disableGlobalCache = disable
  116. }
  117. }
  118. // DriverName return the current sql driver's name
  119. func (engine *Engine) DriverName() string {
  120. return engine.dialect.DriverName()
  121. }
  122. // DataSourceName return the current connection string
  123. func (engine *Engine) DataSourceName() string {
  124. return engine.dialect.DataSourceName()
  125. }
  126. // SetMapper set the name mapping rules
  127. func (engine *Engine) SetMapper(mapper core.IMapper) {
  128. engine.SetTableMapper(mapper)
  129. engine.SetColumnMapper(mapper)
  130. }
  131. // SetTableMapper set the table name mapping rule
  132. func (engine *Engine) SetTableMapper(mapper core.IMapper) {
  133. engine.TableMapper = mapper
  134. }
  135. // SetColumnMapper set the column name mapping rule
  136. func (engine *Engine) SetColumnMapper(mapper core.IMapper) {
  137. engine.ColumnMapper = mapper
  138. }
  139. // SupportInsertMany If engine's database support batch insert records like
  140. // "insert into user values (name, age), (name, age)".
  141. // When the return is ture, then engine.Insert(&users) will
  142. // generate batch sql and exeute.
  143. func (engine *Engine) SupportInsertMany() bool {
  144. return engine.dialect.SupportInsertMany()
  145. }
  146. func (engine *Engine) quoteColumns(columnStr string) string {
  147. columns := strings.Split(columnStr, ",")
  148. for i := 0; i < len(columns); i++ {
  149. columns[i] = engine.Quote(strings.TrimSpace(columns[i]))
  150. }
  151. return strings.Join(columns, ",")
  152. }
  153. // Quote Use QuoteStr quote the string sql
  154. func (engine *Engine) Quote(value string) string {
  155. value = strings.TrimSpace(value)
  156. if len(value) == 0 {
  157. return value
  158. }
  159. buf := strings.Builder{}
  160. engine.QuoteTo(&buf, value)
  161. return buf.String()
  162. }
  163. // QuoteTo quotes string and writes into the buffer
  164. func (engine *Engine) QuoteTo(buf *strings.Builder, value string) {
  165. if buf == nil {
  166. return
  167. }
  168. value = strings.TrimSpace(value)
  169. if value == "" {
  170. return
  171. }
  172. quoteTo(buf, engine.dialect.Quote(""), value)
  173. }
  174. func quoteTo(buf *strings.Builder, quotePair string, value string) {
  175. if len(quotePair) < 2 { // no quote
  176. _, _ = buf.WriteString(value)
  177. return
  178. }
  179. prefix, suffix := quotePair[0], quotePair[1]
  180. i := 0
  181. for i < len(value) {
  182. // start of a token; might be already quoted
  183. if value[i] == '.' {
  184. _ = buf.WriteByte('.')
  185. i++
  186. } else if value[i] == prefix || value[i] == '`' {
  187. // Has quotes; skip/normalize `name` to prefix+name+sufix
  188. var ch byte
  189. if value[i] == prefix {
  190. ch = suffix
  191. } else {
  192. ch = '`'
  193. }
  194. i++
  195. _ = buf.WriteByte(prefix)
  196. for ; i < len(value) && value[i] != ch; i++ {
  197. _ = buf.WriteByte(value[i])
  198. }
  199. _ = buf.WriteByte(suffix)
  200. i++
  201. } else {
  202. // Requires quotes
  203. _ = buf.WriteByte(prefix)
  204. for ; i < len(value) && value[i] != '.'; i++ {
  205. _ = buf.WriteByte(value[i])
  206. }
  207. _ = buf.WriteByte(suffix)
  208. }
  209. }
  210. }
  211. func (engine *Engine) quote(sql string) string {
  212. return engine.dialect.Quote(sql)
  213. }
  214. // SqlType will be deprecated, please use SQLType instead
  215. //
  216. // Deprecated: use SQLType instead
  217. func (engine *Engine) SqlType(c *core.Column) string {
  218. return engine.SQLType(c)
  219. }
  220. // SQLType A simple wrapper to dialect's core.SqlType method
  221. func (engine *Engine) SQLType(c *core.Column) string {
  222. return engine.dialect.SqlType(c)
  223. }
  224. // AutoIncrStr Database's autoincrement statement
  225. func (engine *Engine) AutoIncrStr() string {
  226. return engine.dialect.AutoIncrStr()
  227. }
  228. // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
  229. func (engine *Engine) SetConnMaxLifetime(d time.Duration) {
  230. engine.db.SetConnMaxLifetime(d)
  231. }
  232. // SetMaxOpenConns is only available for go 1.2+
  233. func (engine *Engine) SetMaxOpenConns(conns int) {
  234. engine.db.SetMaxOpenConns(conns)
  235. }
  236. // SetMaxIdleConns set the max idle connections on pool, default is 2
  237. func (engine *Engine) SetMaxIdleConns(conns int) {
  238. engine.db.SetMaxIdleConns(conns)
  239. }
  240. // SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
  241. func (engine *Engine) SetDefaultCacher(cacher core.Cacher) {
  242. engine.Cacher = cacher
  243. }
  244. // GetDefaultCacher returns the default cacher
  245. func (engine *Engine) GetDefaultCacher() core.Cacher {
  246. return engine.Cacher
  247. }
  248. // NoCache If you has set default cacher, and you want temporilly stop use cache,
  249. // you can use NoCache()
  250. func (engine *Engine) NoCache() *Session {
  251. session := engine.NewSession()
  252. session.isAutoClose = true
  253. return session.NoCache()
  254. }
  255. // NoCascade If you do not want to auto cascade load object
  256. func (engine *Engine) NoCascade() *Session {
  257. session := engine.NewSession()
  258. session.isAutoClose = true
  259. return session.NoCascade()
  260. }
  261. // MapCacher Set a table use a special cacher
  262. func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher) error {
  263. engine.setCacher(engine.TableName(bean, true), cacher)
  264. return nil
  265. }
  266. // NewDB provides an interface to operate database directly
  267. func (engine *Engine) NewDB() (*core.DB, error) {
  268. return core.OpenDialect(engine.dialect)
  269. }
  270. // DB return the wrapper of sql.DB
  271. func (engine *Engine) DB() *core.DB {
  272. return engine.db
  273. }
  274. // Dialect return database dialect
  275. func (engine *Engine) Dialect() core.Dialect {
  276. return engine.dialect
  277. }
  278. // NewSession New a session
  279. func (engine *Engine) NewSession() *Session {
  280. session := &Session{engine: engine}
  281. session.Init()
  282. return session
  283. }
  284. // Close the engine
  285. func (engine *Engine) Close() error {
  286. return engine.db.Close()
  287. }
  288. // Ping tests if database is alive
  289. func (engine *Engine) Ping() error {
  290. session := engine.NewSession()
  291. defer session.Close()
  292. return session.Ping()
  293. }
  294. // logSQL save sql
  295. func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) {
  296. if engine.showSQL && !engine.showExecTime {
  297. if len(sqlArgs) > 0 {
  298. engine.logger.Infof("[SQL] %v %#v", sqlStr, sqlArgs)
  299. } else {
  300. engine.logger.Infof("[SQL] %v", sqlStr)
  301. }
  302. }
  303. }
  304. // Sql provides raw sql input parameter. When you have a complex SQL statement
  305. // and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
  306. //
  307. // Deprecated: use SQL instead.
  308. func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
  309. return engine.SQL(querystring, args...)
  310. }
  311. // SQL method let's you manually write raw SQL and operate
  312. // For example:
  313. //
  314. // engine.SQL("select * from user").Find(&users)
  315. //
  316. // This code will execute "select * from user" and set the records to users
  317. func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session {
  318. session := engine.NewSession()
  319. session.isAutoClose = true
  320. return session.SQL(query, args...)
  321. }
  322. // NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields
  323. // will automatically be filled with current time when Insert or Update
  324. // invoked. Call NoAutoTime if you dont' want to fill automatically.
  325. func (engine *Engine) NoAutoTime() *Session {
  326. session := engine.NewSession()
  327. session.isAutoClose = true
  328. return session.NoAutoTime()
  329. }
  330. // NoAutoCondition disable auto generate Where condition from bean or not
  331. func (engine *Engine) NoAutoCondition(no ...bool) *Session {
  332. session := engine.NewSession()
  333. session.isAutoClose = true
  334. return session.NoAutoCondition(no...)
  335. }
  336. func (engine *Engine) loadTableInfo(table *core.Table) error {
  337. colSeq, cols, err := engine.dialect.GetColumns(table.Name)
  338. if err != nil {
  339. return err
  340. }
  341. for _, name := range colSeq {
  342. table.AddColumn(cols[name])
  343. }
  344. indexes, err := engine.dialect.GetIndexes(table.Name)
  345. if err != nil {
  346. return err
  347. }
  348. table.Indexes = indexes
  349. for _, index := range indexes {
  350. for _, name := range index.Cols {
  351. if col := table.GetColumn(name); col != nil {
  352. col.Indexes[index.Name] = index.Type
  353. } else {
  354. return fmt.Errorf("Unknown col %s in index %v of table %v, columns %v", name, index.Name, table.Name, table.ColumnsSeq())
  355. }
  356. }
  357. }
  358. return nil
  359. }
  360. // DBMetas Retrieve all tables, columns, indexes' informations from database.
  361. func (engine *Engine) DBMetas() ([]*core.Table, error) {
  362. tables, err := engine.dialect.GetTables()
  363. if err != nil {
  364. return nil, err
  365. }
  366. for _, table := range tables {
  367. if err = engine.loadTableInfo(table); err != nil {
  368. return nil, err
  369. }
  370. }
  371. return tables, nil
  372. }
  373. // DumpAllToFile dump database all table structs and data to a file
  374. func (engine *Engine) DumpAllToFile(fp string, tp ...core.DbType) error {
  375. f, err := os.Create(fp)
  376. if err != nil {
  377. return err
  378. }
  379. defer f.Close()
  380. return engine.DumpAll(f, tp...)
  381. }
  382. // DumpAll dump database all table structs and data to w
  383. func (engine *Engine) DumpAll(w io.Writer, tp ...core.DbType) error {
  384. tables, err := engine.DBMetas()
  385. if err != nil {
  386. return err
  387. }
  388. return engine.DumpTables(tables, w, tp...)
  389. }
  390. // DumpTablesToFile dump specified tables to SQL file.
  391. func (engine *Engine) DumpTablesToFile(tables []*core.Table, fp string, tp ...core.DbType) error {
  392. f, err := os.Create(fp)
  393. if err != nil {
  394. return err
  395. }
  396. defer f.Close()
  397. return engine.DumpTables(tables, f, tp...)
  398. }
  399. // DumpTables dump specify tables to io.Writer
  400. func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error {
  401. return engine.dumpTables(tables, w, tp...)
  402. }
  403. // dumpTables dump database all table structs and data to w with specify db type
  404. func (engine *Engine) dumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error {
  405. var dialect core.Dialect
  406. var distDBName string
  407. if len(tp) == 0 {
  408. dialect = engine.dialect
  409. distDBName = string(engine.dialect.DBType())
  410. } else {
  411. dialect = core.QueryDialect(tp[0])
  412. if dialect == nil {
  413. return errors.New("Unsupported database type")
  414. }
  415. dialect.Init(nil, engine.dialect.URI(), "", "")
  416. distDBName = string(tp[0])
  417. }
  418. _, err := io.WriteString(w, fmt.Sprintf("/*Generated by xorm v%s %s, from %s to %s*/\n\n",
  419. Version, time.Now().In(engine.TZLocation).Format("2006-01-02 15:04:05"), engine.dialect.DBType(), strings.ToUpper(distDBName)))
  420. if err != nil {
  421. return err
  422. }
  423. for i, table := range tables {
  424. if i > 0 {
  425. _, err = io.WriteString(w, "\n")
  426. if err != nil {
  427. return err
  428. }
  429. }
  430. _, err = io.WriteString(w, dialect.CreateTableSql(table, "", table.StoreEngine, "")+";\n")
  431. if err != nil {
  432. return err
  433. }
  434. for _, index := range table.Indexes {
  435. _, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n")
  436. if err != nil {
  437. return err
  438. }
  439. }
  440. cols := table.ColumnsSeq()
  441. colNames := engine.dialect.Quote(strings.Join(cols, engine.dialect.Quote(", ")))
  442. destColNames := dialect.Quote(strings.Join(cols, dialect.Quote(", ")))
  443. rows, err := engine.DB().Query("SELECT " + colNames + " FROM " + engine.Quote(table.Name))
  444. if err != nil {
  445. return err
  446. }
  447. defer rows.Close()
  448. for rows.Next() {
  449. dest := make([]interface{}, len(cols))
  450. err = rows.ScanSlice(&dest)
  451. if err != nil {
  452. return err
  453. }
  454. _, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+destColNames+") VALUES (")
  455. if err != nil {
  456. return err
  457. }
  458. var temp string
  459. for i, d := range dest {
  460. col := table.GetColumn(cols[i])
  461. if col == nil {
  462. return errors.New("unknow column error")
  463. }
  464. if d == nil {
  465. temp += ", NULL"
  466. } else if col.SQLType.IsText() || col.SQLType.IsTime() {
  467. var v = fmt.Sprintf("%s", d)
  468. if strings.HasSuffix(v, " +0000 UTC") {
  469. temp += fmt.Sprintf(", '%s'", v[0:len(v)-len(" +0000 UTC")])
  470. } else {
  471. temp += ", '" + strings.Replace(v, "'", "''", -1) + "'"
  472. }
  473. } else if col.SQLType.IsBlob() {
  474. if reflect.TypeOf(d).Kind() == reflect.Slice {
  475. temp += fmt.Sprintf(", %s", dialect.FormatBytes(d.([]byte)))
  476. } else if reflect.TypeOf(d).Kind() == reflect.String {
  477. temp += fmt.Sprintf(", '%s'", d.(string))
  478. }
  479. } else if col.SQLType.IsNumeric() {
  480. switch reflect.TypeOf(d).Kind() {
  481. case reflect.Slice:
  482. if col.SQLType.Name == core.Bool {
  483. temp += fmt.Sprintf(", %v", strconv.FormatBool(d.([]byte)[0] != byte('0')))
  484. } else {
  485. temp += fmt.Sprintf(", %s", string(d.([]byte)))
  486. }
  487. case reflect.Int16, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Int:
  488. if col.SQLType.Name == core.Bool {
  489. temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Int() > 0))
  490. } else {
  491. temp += fmt.Sprintf(", %v", d)
  492. }
  493. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  494. if col.SQLType.Name == core.Bool {
  495. temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Uint() > 0))
  496. } else {
  497. temp += fmt.Sprintf(", %v", d)
  498. }
  499. default:
  500. temp += fmt.Sprintf(", %v", d)
  501. }
  502. } else {
  503. s := fmt.Sprintf("%v", d)
  504. if strings.Contains(s, ":") || strings.Contains(s, "-") {
  505. if strings.HasSuffix(s, " +0000 UTC") {
  506. temp += fmt.Sprintf(", '%s'", s[0:len(s)-len(" +0000 UTC")])
  507. } else {
  508. temp += fmt.Sprintf(", '%s'", s)
  509. }
  510. } else {
  511. temp += fmt.Sprintf(", %s", s)
  512. }
  513. }
  514. }
  515. _, err = io.WriteString(w, temp[2:]+");\n")
  516. if err != nil {
  517. return err
  518. }
  519. }
  520. // FIXME: Hack for postgres
  521. if string(dialect.DBType()) == core.POSTGRES && table.AutoIncrColumn() != nil {
  522. _, err = io.WriteString(w, "SELECT setval('"+table.Name+"_id_seq', COALESCE((SELECT MAX("+table.AutoIncrColumn().Name+") + 1 FROM "+dialect.Quote(table.Name)+"), 1), false);\n")
  523. if err != nil {
  524. return err
  525. }
  526. }
  527. }
  528. return nil
  529. }
  530. // Cascade use cascade or not
  531. func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
  532. session := engine.NewSession()
  533. session.isAutoClose = true
  534. return session.Cascade(trueOrFalse...)
  535. }
  536. // Where method provide a condition query
  537. func (engine *Engine) Where(query interface{}, args ...interface{}) *Session {
  538. session := engine.NewSession()
  539. session.isAutoClose = true
  540. return session.Where(query, args...)
  541. }
  542. // Id will be deprecated, please use ID instead
  543. func (engine *Engine) Id(id interface{}) *Session {
  544. session := engine.NewSession()
  545. session.isAutoClose = true
  546. return session.Id(id)
  547. }
  548. // ID method provoide a condition as (id) = ?
  549. func (engine *Engine) ID(id interface{}) *Session {
  550. session := engine.NewSession()
  551. session.isAutoClose = true
  552. return session.ID(id)
  553. }
  554. // Before apply before Processor, affected bean is passed to closure arg
  555. func (engine *Engine) Before(closures func(interface{})) *Session {
  556. session := engine.NewSession()
  557. session.isAutoClose = true
  558. return session.Before(closures)
  559. }
  560. // After apply after insert Processor, affected bean is passed to closure arg
  561. func (engine *Engine) After(closures func(interface{})) *Session {
  562. session := engine.NewSession()
  563. session.isAutoClose = true
  564. return session.After(closures)
  565. }
  566. // Charset set charset when create table, only support mysql now
  567. func (engine *Engine) Charset(charset string) *Session {
  568. session := engine.NewSession()
  569. session.isAutoClose = true
  570. return session.Charset(charset)
  571. }
  572. // StoreEngine set store engine when create table, only support mysql now
  573. func (engine *Engine) StoreEngine(storeEngine string) *Session {
  574. session := engine.NewSession()
  575. session.isAutoClose = true
  576. return session.StoreEngine(storeEngine)
  577. }
  578. // Distinct use for distinct columns. Caution: when you are using cache,
  579. // distinct will not be cached because cache system need id,
  580. // but distinct will not provide id
  581. func (engine *Engine) Distinct(columns ...string) *Session {
  582. session := engine.NewSession()
  583. session.isAutoClose = true
  584. return session.Distinct(columns...)
  585. }
  586. // Select customerize your select columns or contents
  587. func (engine *Engine) Select(str string) *Session {
  588. session := engine.NewSession()
  589. session.isAutoClose = true
  590. return session.Select(str)
  591. }
  592. // Cols only use the parameters as select or update columns
  593. func (engine *Engine) Cols(columns ...string) *Session {
  594. session := engine.NewSession()
  595. session.isAutoClose = true
  596. return session.Cols(columns...)
  597. }
  598. // AllCols indicates that all columns should be use
  599. func (engine *Engine) AllCols() *Session {
  600. session := engine.NewSession()
  601. session.isAutoClose = true
  602. return session.AllCols()
  603. }
  604. // MustCols specify some columns must use even if they are empty
  605. func (engine *Engine) MustCols(columns ...string) *Session {
  606. session := engine.NewSession()
  607. session.isAutoClose = true
  608. return session.MustCols(columns...)
  609. }
  610. // UseBool xorm automatically retrieve condition according struct, but
  611. // if struct has bool field, it will ignore them. So use UseBool
  612. // to tell system to do not ignore them.
  613. // If no parameters, it will use all the bool field of struct, or
  614. // it will use parameters's columns
  615. func (engine *Engine) UseBool(columns ...string) *Session {
  616. session := engine.NewSession()
  617. session.isAutoClose = true
  618. return session.UseBool(columns...)
  619. }
  620. // Omit only not use the parameters as select or update columns
  621. func (engine *Engine) Omit(columns ...string) *Session {
  622. session := engine.NewSession()
  623. session.isAutoClose = true
  624. return session.Omit(columns...)
  625. }
  626. // Nullable set null when column is zero-value and nullable for update
  627. func (engine *Engine) Nullable(columns ...string) *Session {
  628. session := engine.NewSession()
  629. session.isAutoClose = true
  630. return session.Nullable(columns...)
  631. }
  632. // In will generate "column IN (?, ?)"
  633. func (engine *Engine) In(column string, args ...interface{}) *Session {
  634. session := engine.NewSession()
  635. session.isAutoClose = true
  636. return session.In(column, args...)
  637. }
  638. // NotIn will generate "column NOT IN (?, ?)"
  639. func (engine *Engine) NotIn(column string, args ...interface{}) *Session {
  640. session := engine.NewSession()
  641. session.isAutoClose = true
  642. return session.NotIn(column, args...)
  643. }
  644. // Incr provides a update string like "column = column + ?"
  645. func (engine *Engine) Incr(column string, arg ...interface{}) *Session {
  646. session := engine.NewSession()
  647. session.isAutoClose = true
  648. return session.Incr(column, arg...)
  649. }
  650. // Decr provides a update string like "column = column - ?"
  651. func (engine *Engine) Decr(column string, arg ...interface{}) *Session {
  652. session := engine.NewSession()
  653. session.isAutoClose = true
  654. return session.Decr(column, arg...)
  655. }
  656. // SetExpr provides a update string like "column = {expression}"
  657. func (engine *Engine) SetExpr(column string, expression interface{}) *Session {
  658. session := engine.NewSession()
  659. session.isAutoClose = true
  660. return session.SetExpr(column, expression)
  661. }
  662. // Table temporarily change the Get, Find, Update's table
  663. func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
  664. session := engine.NewSession()
  665. session.isAutoClose = true
  666. return session.Table(tableNameOrBean)
  667. }
  668. // Alias set the table alias
  669. func (engine *Engine) Alias(alias string) *Session {
  670. session := engine.NewSession()
  671. session.isAutoClose = true
  672. return session.Alias(alias)
  673. }
  674. // Limit will generate "LIMIT start, limit"
  675. func (engine *Engine) Limit(limit int, start ...int) *Session {
  676. session := engine.NewSession()
  677. session.isAutoClose = true
  678. return session.Limit(limit, start...)
  679. }
  680. // Desc will generate "ORDER BY column1 DESC, column2 DESC"
  681. func (engine *Engine) Desc(colNames ...string) *Session {
  682. session := engine.NewSession()
  683. session.isAutoClose = true
  684. return session.Desc(colNames...)
  685. }
  686. // Asc will generate "ORDER BY column1,column2 Asc"
  687. // This method can chainable use.
  688. //
  689. // engine.Desc("name").Asc("age").Find(&users)
  690. // // SELECT * FROM user ORDER BY name DESC, age ASC
  691. //
  692. func (engine *Engine) Asc(colNames ...string) *Session {
  693. session := engine.NewSession()
  694. session.isAutoClose = true
  695. return session.Asc(colNames...)
  696. }
  697. // OrderBy will generate "ORDER BY order"
  698. func (engine *Engine) OrderBy(order string) *Session {
  699. session := engine.NewSession()
  700. session.isAutoClose = true
  701. return session.OrderBy(order)
  702. }
  703. // Prepare enables prepare statement
  704. func (engine *Engine) Prepare() *Session {
  705. session := engine.NewSession()
  706. session.isAutoClose = true
  707. return session.Prepare()
  708. }
  709. // Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
  710. func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
  711. session := engine.NewSession()
  712. session.isAutoClose = true
  713. return session.Join(joinOperator, tablename, condition, args...)
  714. }
  715. // GroupBy generate group by statement
  716. func (engine *Engine) GroupBy(keys string) *Session {
  717. session := engine.NewSession()
  718. session.isAutoClose = true
  719. return session.GroupBy(keys)
  720. }
  721. // Having generate having statement
  722. func (engine *Engine) Having(conditions string) *Session {
  723. session := engine.NewSession()
  724. session.isAutoClose = true
  725. return session.Having(conditions)
  726. }
  727. // UnMapType removes the datbase mapper of a type
  728. func (engine *Engine) UnMapType(t reflect.Type) {
  729. engine.mutex.Lock()
  730. defer engine.mutex.Unlock()
  731. delete(engine.Tables, t)
  732. }
  733. func (engine *Engine) autoMapType(v reflect.Value) (*core.Table, error) {
  734. t := v.Type()
  735. engine.mutex.Lock()
  736. defer engine.mutex.Unlock()
  737. table, ok := engine.Tables[t]
  738. if !ok {
  739. var err error
  740. table, err = engine.mapType(v)
  741. if err != nil {
  742. return nil, err
  743. }
  744. engine.Tables[t] = table
  745. if engine.Cacher != nil {
  746. if v.CanAddr() {
  747. engine.GobRegister(v.Addr().Interface())
  748. } else {
  749. engine.GobRegister(v.Interface())
  750. }
  751. }
  752. }
  753. return table, nil
  754. }
  755. // GobRegister register one struct to gob for cache use
  756. func (engine *Engine) GobRegister(v interface{}) *Engine {
  757. gob.Register(v)
  758. return engine
  759. }
  760. // Table table struct
  761. type Table struct {
  762. *core.Table
  763. Name string
  764. }
  765. // IsValid if table is valid
  766. func (t *Table) IsValid() bool {
  767. return t.Table != nil && len(t.Name) > 0
  768. }
  769. // TableInfo get table info according to bean's content
  770. func (engine *Engine) TableInfo(bean interface{}) *Table {
  771. v := rValue(bean)
  772. tb, err := engine.autoMapType(v)
  773. if err != nil {
  774. engine.logger.Error(err)
  775. }
  776. return &Table{tb, engine.TableName(bean)}
  777. }
  778. func addIndex(indexName string, table *core.Table, col *core.Column, indexType int) {
  779. if index, ok := table.Indexes[indexName]; ok {
  780. index.AddColumn(col.Name)
  781. col.Indexes[index.Name] = indexType
  782. } else {
  783. index := core.NewIndex(indexName, indexType)
  784. index.AddColumn(col.Name)
  785. table.AddIndex(index)
  786. col.Indexes[index.Name] = indexType
  787. }
  788. }
  789. // TableName table name interface to define customerize table name
  790. type TableName interface {
  791. TableName() string
  792. }
  793. var (
  794. tpTableName = reflect.TypeOf((*TableName)(nil)).Elem()
  795. )
  796. func (engine *Engine) mapType(v reflect.Value) (*core.Table, error) {
  797. t := v.Type()
  798. table := core.NewEmptyTable()
  799. table.Type = t
  800. table.Name = engine.tbNameForMap(v)
  801. var idFieldColName string
  802. var hasCacheTag, hasNoCacheTag bool
  803. for i := 0; i < t.NumField(); i++ {
  804. tag := t.Field(i).Tag
  805. ormTagStr := tag.Get(engine.TagIdentifier)
  806. var col *core.Column
  807. fieldValue := v.Field(i)
  808. fieldType := fieldValue.Type()
  809. if ormTagStr != "" {
  810. col = &core.Column{
  811. FieldName: t.Field(i).Name,
  812. Nullable: true,
  813. IsPrimaryKey: false,
  814. IsAutoIncrement: false,
  815. MapType: core.TWOSIDES,
  816. Indexes: make(map[string]int),
  817. DefaultIsEmpty: true,
  818. }
  819. tags := splitTag(ormTagStr)
  820. if len(tags) > 0 {
  821. if tags[0] == "-" {
  822. continue
  823. }
  824. var ctx = tagContext{
  825. table: table,
  826. col: col,
  827. fieldValue: fieldValue,
  828. indexNames: make(map[string]int),
  829. engine: engine,
  830. }
  831. if strings.HasPrefix(strings.ToUpper(tags[0]), "EXTENDS") {
  832. pStart := strings.Index(tags[0], "(")
  833. if pStart > -1 && strings.HasSuffix(tags[0], ")") {
  834. var tagPrefix = strings.TrimFunc(tags[0][pStart+1:len(tags[0])-1], func(r rune) bool {
  835. return r == '\'' || r == '"'
  836. })
  837. ctx.params = []string{tagPrefix}
  838. }
  839. if err := ExtendsTagHandler(&ctx); err != nil {
  840. return nil, err
  841. }
  842. continue
  843. }
  844. for j, key := range tags {
  845. if ctx.ignoreNext {
  846. ctx.ignoreNext = false
  847. continue
  848. }
  849. k := strings.ToUpper(key)
  850. ctx.tagName = k
  851. ctx.params = []string{}
  852. pStart := strings.Index(k, "(")
  853. if pStart == 0 {
  854. return nil, errors.New("( could not be the first charactor")
  855. }
  856. if pStart > -1 {
  857. if !strings.HasSuffix(k, ")") {
  858. return nil, fmt.Errorf("field %s tag %s cannot match ) charactor", col.FieldName, key)
  859. }
  860. ctx.tagName = k[:pStart]
  861. ctx.params = strings.Split(key[pStart+1:len(k)-1], ",")
  862. }
  863. if j > 0 {
  864. ctx.preTag = strings.ToUpper(tags[j-1])
  865. }
  866. if j < len(tags)-1 {
  867. ctx.nextTag = tags[j+1]
  868. } else {
  869. ctx.nextTag = ""
  870. }
  871. if h, ok := engine.tagHandlers[ctx.tagName]; ok {
  872. if err := h(&ctx); err != nil {
  873. return nil, err
  874. }
  875. } else {
  876. if strings.HasPrefix(key, "'") && strings.HasSuffix(key, "'") {
  877. col.Name = key[1 : len(key)-1]
  878. } else {
  879. col.Name = key
  880. }
  881. }
  882. if ctx.hasCacheTag {
  883. hasCacheTag = true
  884. }
  885. if ctx.hasNoCacheTag {
  886. hasNoCacheTag = true
  887. }
  888. }
  889. if col.SQLType.Name == "" {
  890. col.SQLType = core.Type2SQLType(fieldType)
  891. }
  892. engine.dialect.SqlType(col)
  893. if col.Length == 0 {
  894. col.Length = col.SQLType.DefaultLength
  895. }
  896. if col.Length2 == 0 {
  897. col.Length2 = col.SQLType.DefaultLength2
  898. }
  899. if col.Name == "" {
  900. col.Name = engine.ColumnMapper.Obj2Table(t.Field(i).Name)
  901. }
  902. if ctx.isUnique {
  903. ctx.indexNames[col.Name] = core.UniqueType
  904. } else if ctx.isIndex {
  905. ctx.indexNames[col.Name] = core.IndexType
  906. }
  907. for indexName, indexType := range ctx.indexNames {
  908. addIndex(indexName, table, col, indexType)
  909. }
  910. }
  911. } else {
  912. var sqlType core.SQLType
  913. if fieldValue.CanAddr() {
  914. if _, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  915. sqlType = core.SQLType{Name: core.Text}
  916. }
  917. }
  918. if _, ok := fieldValue.Interface().(core.Conversion); ok {
  919. sqlType = core.SQLType{Name: core.Text}
  920. } else {
  921. sqlType = core.Type2SQLType(fieldType)
  922. }
  923. col = core.NewColumn(engine.ColumnMapper.Obj2Table(t.Field(i).Name),
  924. t.Field(i).Name, sqlType, sqlType.DefaultLength,
  925. sqlType.DefaultLength2, true)
  926. if fieldType.Kind() == reflect.Int64 && (strings.ToUpper(col.FieldName) == "ID" || strings.HasSuffix(strings.ToUpper(col.FieldName), ".ID")) {
  927. idFieldColName = col.Name
  928. }
  929. }
  930. if col.IsAutoIncrement {
  931. col.Nullable = false
  932. }
  933. table.AddColumn(col)
  934. } // end for
  935. if idFieldColName != "" && len(table.PrimaryKeys) == 0 {
  936. col := table.GetColumn(idFieldColName)
  937. col.IsPrimaryKey = true
  938. col.IsAutoIncrement = true
  939. col.Nullable = false
  940. table.PrimaryKeys = append(table.PrimaryKeys, col.Name)
  941. table.AutoIncrement = col.Name
  942. }
  943. if hasCacheTag {
  944. if engine.Cacher != nil { // !nash! use engine's cacher if provided
  945. engine.logger.Info("enable cache on table:", table.Name)
  946. engine.setCacher(table.Name, engine.Cacher)
  947. } else {
  948. engine.logger.Info("enable LRU cache on table:", table.Name)
  949. engine.setCacher(table.Name, NewLRUCacher2(NewMemoryStore(), time.Hour, 10000))
  950. }
  951. }
  952. if hasNoCacheTag {
  953. engine.logger.Info("disable cache on table:", table.Name)
  954. engine.setCacher(table.Name, nil)
  955. }
  956. return table, nil
  957. }
  958. // IsTableEmpty if a table has any reocrd
  959. func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
  960. session := engine.NewSession()
  961. defer session.Close()
  962. return session.IsTableEmpty(bean)
  963. }
  964. // IsTableExist if a table is exist
  965. func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) {
  966. session := engine.NewSession()
  967. defer session.Close()
  968. return session.IsTableExist(beanOrTableName)
  969. }
  970. // IdOf get id from one struct
  971. //
  972. // Deprecated: use IDOf instead.
  973. func (engine *Engine) IdOf(bean interface{}) core.PK {
  974. return engine.IDOf(bean)
  975. }
  976. // IDOf get id from one struct
  977. func (engine *Engine) IDOf(bean interface{}) core.PK {
  978. return engine.IdOfV(reflect.ValueOf(bean))
  979. }
  980. // IdOfV get id from one value of struct
  981. //
  982. // Deprecated: use IDOfV instead.
  983. func (engine *Engine) IdOfV(rv reflect.Value) core.PK {
  984. return engine.IDOfV(rv)
  985. }
  986. // IDOfV get id from one value of struct
  987. func (engine *Engine) IDOfV(rv reflect.Value) core.PK {
  988. pk, err := engine.idOfV(rv)
  989. if err != nil {
  990. engine.logger.Error(err)
  991. return nil
  992. }
  993. return pk
  994. }
  995. func (engine *Engine) idOfV(rv reflect.Value) (core.PK, error) {
  996. v := reflect.Indirect(rv)
  997. table, err := engine.autoMapType(v)
  998. if err != nil {
  999. return nil, err
  1000. }
  1001. pk := make([]interface{}, len(table.PrimaryKeys))
  1002. for i, col := range table.PKColumns() {
  1003. var err error
  1004. fieldName := col.FieldName
  1005. for {
  1006. parts := strings.SplitN(fieldName, ".", 2)
  1007. if len(parts) == 1 {
  1008. break
  1009. }
  1010. v = v.FieldByName(parts[0])
  1011. if v.Kind() == reflect.Ptr {
  1012. v = v.Elem()
  1013. }
  1014. if v.Kind() != reflect.Struct {
  1015. return nil, ErrUnSupportedType
  1016. }
  1017. fieldName = parts[1]
  1018. }
  1019. pkField := v.FieldByName(fieldName)
  1020. switch pkField.Kind() {
  1021. case reflect.String:
  1022. pk[i], err = engine.idTypeAssertion(col, pkField.String())
  1023. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1024. pk[i], err = engine.idTypeAssertion(col, strconv.FormatInt(pkField.Int(), 10))
  1025. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  1026. // id of uint will be converted to int64
  1027. pk[i], err = engine.idTypeAssertion(col, strconv.FormatUint(pkField.Uint(), 10))
  1028. }
  1029. if err != nil {
  1030. return nil, err
  1031. }
  1032. }
  1033. return core.PK(pk), nil
  1034. }
  1035. func (engine *Engine) idTypeAssertion(col *core.Column, sid string) (interface{}, error) {
  1036. if col.SQLType.IsNumeric() {
  1037. n, err := strconv.ParseInt(sid, 10, 64)
  1038. if err != nil {
  1039. return nil, err
  1040. }
  1041. return n, nil
  1042. } else if col.SQLType.IsText() {
  1043. return sid, nil
  1044. } else {
  1045. return nil, errors.New("not supported")
  1046. }
  1047. }
  1048. // CreateIndexes create indexes
  1049. func (engine *Engine) CreateIndexes(bean interface{}) error {
  1050. session := engine.NewSession()
  1051. defer session.Close()
  1052. return session.CreateIndexes(bean)
  1053. }
  1054. // CreateUniques create uniques
  1055. func (engine *Engine) CreateUniques(bean interface{}) error {
  1056. session := engine.NewSession()
  1057. defer session.Close()
  1058. return session.CreateUniques(bean)
  1059. }
  1060. // ClearCacheBean if enabled cache, clear the cache bean
  1061. func (engine *Engine) ClearCacheBean(bean interface{}, id string) error {
  1062. tableName := engine.TableName(bean)
  1063. cacher := engine.getCacher(tableName)
  1064. if cacher != nil {
  1065. cacher.ClearIds(tableName)
  1066. cacher.DelBean(tableName, id)
  1067. }
  1068. return nil
  1069. }
  1070. // ClearCache if enabled cache, clear some tables' cache
  1071. func (engine *Engine) ClearCache(beans ...interface{}) error {
  1072. for _, bean := range beans {
  1073. tableName := engine.TableName(bean)
  1074. cacher := engine.getCacher(tableName)
  1075. if cacher != nil {
  1076. cacher.ClearIds(tableName)
  1077. cacher.ClearBeans(tableName)
  1078. }
  1079. }
  1080. return nil
  1081. }
  1082. // Sync the new struct changes to database, this method will automatically add
  1083. // table, column, index, unique. but will not delete or change anything.
  1084. // If you change some field, you should change the database manually.
  1085. func (engine *Engine) Sync(beans ...interface{}) error {
  1086. session := engine.NewSession()
  1087. defer session.Close()
  1088. for _, bean := range beans {
  1089. v := rValue(bean)
  1090. tableNameNoSchema := engine.TableName(bean)
  1091. table, err := engine.autoMapType(v)
  1092. if err != nil {
  1093. return err
  1094. }
  1095. isExist, err := session.Table(bean).isTableExist(tableNameNoSchema)
  1096. if err != nil {
  1097. return err
  1098. }
  1099. if !isExist {
  1100. err = session.createTable(bean)
  1101. if err != nil {
  1102. return err
  1103. }
  1104. }
  1105. /*isEmpty, err := engine.IsEmptyTable(bean)
  1106. if err != nil {
  1107. return err
  1108. }*/
  1109. var isEmpty bool
  1110. if isEmpty {
  1111. err = session.dropTable(bean)
  1112. if err != nil {
  1113. return err
  1114. }
  1115. err = session.createTable(bean)
  1116. if err != nil {
  1117. return err
  1118. }
  1119. } else {
  1120. for _, col := range table.Columns() {
  1121. isExist, err := engine.dialect.IsColumnExist(tableNameNoSchema, col.Name)
  1122. if err != nil {
  1123. return err
  1124. }
  1125. if !isExist {
  1126. if err := session.statement.setRefBean(bean); err != nil {
  1127. return err
  1128. }
  1129. err = session.addColumn(col.Name)
  1130. if err != nil {
  1131. return err
  1132. }
  1133. }
  1134. }
  1135. for name, index := range table.Indexes {
  1136. if err := session.statement.setRefBean(bean); err != nil {
  1137. return err
  1138. }
  1139. if index.Type == core.UniqueType {
  1140. isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, true)
  1141. if err != nil {
  1142. return err
  1143. }
  1144. if !isExist {
  1145. if err := session.statement.setRefBean(bean); err != nil {
  1146. return err
  1147. }
  1148. err = session.addUnique(tableNameNoSchema, name)
  1149. if err != nil {
  1150. return err
  1151. }
  1152. }
  1153. } else if index.Type == core.IndexType {
  1154. isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, false)
  1155. if err != nil {
  1156. return err
  1157. }
  1158. if !isExist {
  1159. if err := session.statement.setRefBean(bean); err != nil {
  1160. return err
  1161. }
  1162. err = session.addIndex(tableNameNoSchema, name)
  1163. if err != nil {
  1164. return err
  1165. }
  1166. }
  1167. } else {
  1168. return errors.New("unknow index type")
  1169. }
  1170. }
  1171. }
  1172. }
  1173. return nil
  1174. }
  1175. // Sync2 synchronize structs to database tables
  1176. func (engine *Engine) Sync2(beans ...interface{}) error {
  1177. s := engine.NewSession()
  1178. defer s.Close()
  1179. return s.Sync2(beans...)
  1180. }
  1181. // CreateTables create tabls according bean
  1182. func (engine *Engine) CreateTables(beans ...interface{}) error {
  1183. session := engine.NewSession()
  1184. defer session.Close()
  1185. err := session.Begin()
  1186. if err != nil {
  1187. return err
  1188. }
  1189. for _, bean := range beans {
  1190. err = session.createTable(bean)
  1191. if err != nil {
  1192. session.Rollback()
  1193. return err
  1194. }
  1195. }
  1196. return session.Commit()
  1197. }
  1198. // DropTables drop specify tables
  1199. func (engine *Engine) DropTables(beans ...interface{}) error {
  1200. session := engine.NewSession()
  1201. defer session.Close()
  1202. err := session.Begin()
  1203. if err != nil {
  1204. return err
  1205. }
  1206. for _, bean := range beans {
  1207. err = session.dropTable(bean)
  1208. if err != nil {
  1209. session.Rollback()
  1210. return err
  1211. }
  1212. }
  1213. return session.Commit()
  1214. }
  1215. // DropIndexes drop indexes of a table
  1216. func (engine *Engine) DropIndexes(bean interface{}) error {
  1217. session := engine.NewSession()
  1218. defer session.Close()
  1219. return session.DropIndexes(bean)
  1220. }
  1221. // Exec raw sql
  1222. func (engine *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
  1223. session := engine.NewSession()
  1224. defer session.Close()
  1225. return session.Exec(sqlOrArgs...)
  1226. }
  1227. // Query a raw sql and return records as []map[string][]byte
  1228. func (engine *Engine) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) {
  1229. session := engine.NewSession()
  1230. defer session.Close()
  1231. return session.Query(sqlOrArgs...)
  1232. }
  1233. // QueryString runs a raw sql and return records as []map[string]string
  1234. func (engine *Engine) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) {
  1235. session := engine.NewSession()
  1236. defer session.Close()
  1237. return session.QueryString(sqlOrArgs...)
  1238. }
  1239. // QueryInterface runs a raw sql and return records as []map[string]interface{}
  1240. func (engine *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) {
  1241. session := engine.NewSession()
  1242. defer session.Close()
  1243. return session.QueryInterface(sqlOrArgs...)
  1244. }
  1245. // Insert one or more records
  1246. func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
  1247. session := engine.NewSession()
  1248. defer session.Close()
  1249. return session.Insert(beans...)
  1250. }
  1251. // InsertOne insert only one record
  1252. func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
  1253. session := engine.NewSession()
  1254. defer session.Close()
  1255. return session.InsertOne(bean)
  1256. }
  1257. // Update records, bean's non-empty fields are updated contents,
  1258. // condiBean' non-empty filds are conditions
  1259. // CAUTION:
  1260. // 1.bool will defaultly be updated content nor conditions
  1261. // You should call UseBool if you have bool to use.
  1262. // 2.float32 & float64 may be not inexact as conditions
  1263. func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
  1264. session := engine.NewSession()
  1265. defer session.Close()
  1266. return session.Update(bean, condiBeans...)
  1267. }
  1268. // Delete records, bean's non-empty fields are conditions
  1269. func (engine *Engine) Delete(bean interface{}) (int64, error) {
  1270. session := engine.NewSession()
  1271. defer session.Close()
  1272. return session.Delete(bean)
  1273. }
  1274. // Get retrieve one record from table, bean's non-empty fields
  1275. // are conditions
  1276. func (engine *Engine) Get(bean interface{}) (bool, error) {
  1277. session := engine.NewSession()
  1278. defer session.Close()
  1279. return session.Get(bean)
  1280. }
  1281. // Exist returns true if the record exist otherwise return false
  1282. func (engine *Engine) Exist(bean ...interface{}) (bool, error) {
  1283. session := engine.NewSession()
  1284. defer session.Close()
  1285. return session.Exist(bean...)
  1286. }
  1287. // Find retrieve records from table, condiBeans's non-empty fields
  1288. // are conditions. beans could be []Struct, []*Struct, map[int64]Struct
  1289. // map[int64]*Struct
  1290. func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
  1291. session := engine.NewSession()
  1292. defer session.Close()
  1293. return session.Find(beans, condiBeans...)
  1294. }
  1295. // FindAndCount find the results and also return the counts
  1296. func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
  1297. session := engine.NewSession()
  1298. defer session.Close()
  1299. return session.FindAndCount(rowsSlicePtr, condiBean...)
  1300. }
  1301. // Iterate record by record handle records from table, bean's non-empty fields
  1302. // are conditions.
  1303. func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
  1304. session := engine.NewSession()
  1305. defer session.Close()
  1306. return session.Iterate(bean, fun)
  1307. }
  1308. // Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
  1309. // are conditions.
  1310. func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
  1311. session := engine.NewSession()
  1312. return session.Rows(bean)
  1313. }
  1314. // Count counts the records. bean's non-empty fields are conditions.
  1315. func (engine *Engine) Count(bean ...interface{}) (int64, error) {
  1316. session := engine.NewSession()
  1317. defer session.Close()
  1318. return session.Count(bean...)
  1319. }
  1320. // Sum sum the records by some column. bean's non-empty fields are conditions.
  1321. func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) {
  1322. session := engine.NewSession()
  1323. defer session.Close()
  1324. return session.Sum(bean, colName)
  1325. }
  1326. // SumInt sum the records by some column. bean's non-empty fields are conditions.
  1327. func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error) {
  1328. session := engine.NewSession()
  1329. defer session.Close()
  1330. return session.SumInt(bean, colName)
  1331. }
  1332. // Sums sum the records by some columns. bean's non-empty fields are conditions.
  1333. func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) {
  1334. session := engine.NewSession()
  1335. defer session.Close()
  1336. return session.Sums(bean, colNames...)
  1337. }
  1338. // SumsInt like Sums but return slice of int64 instead of float64.
  1339. func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) {
  1340. session := engine.NewSession()
  1341. defer session.Close()
  1342. return session.SumsInt(bean, colNames...)
  1343. }
  1344. // ImportFile SQL DDL file
  1345. func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
  1346. file, err := os.Open(ddlPath)
  1347. if err != nil {
  1348. return nil, err
  1349. }
  1350. defer file.Close()
  1351. return engine.Import(file)
  1352. }
  1353. // Import SQL DDL from io.Reader
  1354. func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
  1355. var results []sql.Result
  1356. var lastError error
  1357. scanner := bufio.NewScanner(r)
  1358. semiColSpliter := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  1359. if atEOF && len(data) == 0 {
  1360. return 0, nil, nil
  1361. }
  1362. if i := bytes.IndexByte(data, ';'); i >= 0 {
  1363. return i + 1, data[0:i], nil
  1364. }
  1365. // If we're at EOF, we have a final, non-terminated line. Return it.
  1366. if atEOF {
  1367. return len(data), data, nil
  1368. }
  1369. // Request more data.
  1370. return 0, nil, nil
  1371. }
  1372. scanner.Split(semiColSpliter)
  1373. for scanner.Scan() {
  1374. query := strings.Trim(scanner.Text(), " \t\n\r")
  1375. if len(query) > 0 {
  1376. engine.logSQL(query)
  1377. result, err := engine.DB().Exec(query)
  1378. results = append(results, result)
  1379. if err != nil {
  1380. return nil, err
  1381. }
  1382. }
  1383. }
  1384. return results, lastError
  1385. }
  1386. // nowTime return current time
  1387. func (engine *Engine) nowTime(col *core.Column) (interface{}, time.Time) {
  1388. t := time.Now()
  1389. var tz = engine.DatabaseTZ
  1390. if !col.DisableTimeZone && col.TimeZone != nil {
  1391. tz = col.TimeZone
  1392. }
  1393. return engine.formatTime(col.SQLType.Name, t.In(tz)), t.In(engine.TZLocation)
  1394. }
  1395. func (engine *Engine) formatColTime(col *core.Column, t time.Time) (v interface{}) {
  1396. if t.IsZero() {
  1397. if col.Nullable {
  1398. return nil
  1399. }
  1400. return ""
  1401. }
  1402. if col.TimeZone != nil {
  1403. return engine.formatTime(col.SQLType.Name, t.In(col.TimeZone))
  1404. }
  1405. return engine.formatTime(col.SQLType.Name, t.In(engine.DatabaseTZ))
  1406. }
  1407. // formatTime format time as column type
  1408. func (engine *Engine) formatTime(sqlTypeName string, t time.Time) (v interface{}) {
  1409. switch sqlTypeName {
  1410. case core.Time:
  1411. s := t.Format("2006-01-02 15:04:05") // time.RFC3339
  1412. v = s[11:19]
  1413. case core.Date:
  1414. v = t.Format("2006-01-02")
  1415. case core.DateTime, core.TimeStamp:
  1416. v = t.Format("2006-01-02 15:04:05")
  1417. case core.TimeStampz:
  1418. if engine.dialect.DBType() == core.MSSQL {
  1419. v = t.Format("2006-01-02T15:04:05.9999999Z07:00")
  1420. } else {
  1421. v = t.Format(time.RFC3339Nano)
  1422. }
  1423. case core.BigInt, core.Int:
  1424. v = t.Unix()
  1425. default:
  1426. v = t
  1427. }
  1428. return
  1429. }
  1430. // GetColumnMapper returns the column name mapper
  1431. func (engine *Engine) GetColumnMapper() core.IMapper {
  1432. return engine.ColumnMapper
  1433. }
  1434. // GetTableMapper returns the table name mapper
  1435. func (engine *Engine) GetTableMapper() core.IMapper {
  1436. return engine.TableMapper
  1437. }
  1438. // GetTZLocation returns time zone of the application
  1439. func (engine *Engine) GetTZLocation() *time.Location {
  1440. return engine.TZLocation
  1441. }
  1442. // SetTZLocation sets time zone of the application
  1443. func (engine *Engine) SetTZLocation(tz *time.Location) {
  1444. engine.TZLocation = tz
  1445. }
  1446. // GetTZDatabase returns time zone of the database
  1447. func (engine *Engine) GetTZDatabase() *time.Location {
  1448. return engine.DatabaseTZ
  1449. }
  1450. // SetTZDatabase sets time zone of the database
  1451. func (engine *Engine) SetTZDatabase(tz *time.Location) {
  1452. engine.DatabaseTZ = tz
  1453. }
  1454. // SetSchema sets the schema of database
  1455. func (engine *Engine) SetSchema(schema string) {
  1456. engine.dialect.URI().Schema = schema
  1457. }
  1458. // Unscoped always disable struct tag "deleted"
  1459. func (engine *Engine) Unscoped() *Session {
  1460. session := engine.NewSession()
  1461. session.isAutoClose = true
  1462. return session.Unscoped()
  1463. }