本站源代码
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.

1660 lines
44KB

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