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.
 
 
 
 

1645 lines
44 KiB

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