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.
 
 
 
 

1345 line
38 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. "context"
  7. "database/sql"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "os"
  12. "reflect"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "xorm.io/xorm/caches"
  18. "xorm.io/xorm/contexts"
  19. "xorm.io/xorm/core"
  20. "xorm.io/xorm/dialects"
  21. "xorm.io/xorm/internal/utils"
  22. "xorm.io/xorm/log"
  23. "xorm.io/xorm/names"
  24. "xorm.io/xorm/schemas"
  25. "xorm.io/xorm/tags"
  26. )
  27. // Engine is the major struct of xorm, it means a database manager.
  28. // Commonly, an application only need one engine
  29. type Engine struct {
  30. cacherMgr *caches.Manager
  31. defaultContext context.Context
  32. dialect dialects.Dialect
  33. engineGroup *EngineGroup
  34. logger log.ContextLogger
  35. tagParser *tags.Parser
  36. db *core.DB
  37. driverName string
  38. dataSourceName string
  39. TZLocation *time.Location // The timezone of the application
  40. DatabaseTZ *time.Location // The timezone of the database
  41. logSessionID bool // create session id
  42. }
  43. // NewEngine new a db manager according to the parameter. Currently support four
  44. // drivers
  45. func NewEngine(driverName string, dataSourceName string) (*Engine, error) {
  46. dialect, err := dialects.OpenDialect(driverName, dataSourceName)
  47. if err != nil {
  48. return nil, err
  49. }
  50. db, err := core.Open(driverName, dataSourceName)
  51. if err != nil {
  52. return nil, err
  53. }
  54. cacherMgr := caches.NewManager()
  55. mapper := names.NewCacheMapper(new(names.SnakeMapper))
  56. tagParser := tags.NewParser("xorm", dialect, mapper, mapper, cacherMgr)
  57. engine := &Engine{
  58. dialect: dialect,
  59. TZLocation: time.Local,
  60. defaultContext: context.Background(),
  61. cacherMgr: cacherMgr,
  62. tagParser: tagParser,
  63. driverName: driverName,
  64. dataSourceName: dataSourceName,
  65. db: db,
  66. logSessionID: false,
  67. }
  68. if dialect.URI().DBType == schemas.SQLITE {
  69. engine.DatabaseTZ = time.UTC
  70. } else {
  71. engine.DatabaseTZ = time.Local
  72. }
  73. logger := log.NewSimpleLogger(os.Stdout)
  74. logger.SetLevel(log.LOG_INFO)
  75. engine.SetLogger(log.NewLoggerAdapter(logger))
  76. runtime.SetFinalizer(engine, func(engine *Engine) {
  77. engine.Close()
  78. })
  79. return engine, nil
  80. }
  81. // NewEngineWithParams new a db manager with params. The params will be passed to dialects.
  82. func NewEngineWithParams(driverName string, dataSourceName string, params map[string]string) (*Engine, error) {
  83. engine, err := NewEngine(driverName, dataSourceName)
  84. engine.dialect.SetParams(params)
  85. return engine, err
  86. }
  87. // EnableSessionID if enable session id
  88. func (engine *Engine) EnableSessionID(enable bool) {
  89. engine.logSessionID = enable
  90. }
  91. // SetCacher sets cacher for the table
  92. func (engine *Engine) SetCacher(tableName string, cacher caches.Cacher) {
  93. engine.cacherMgr.SetCacher(tableName, cacher)
  94. }
  95. // GetCacher returns the cachher of the special table
  96. func (engine *Engine) GetCacher(tableName string) caches.Cacher {
  97. return engine.cacherMgr.GetCacher(tableName)
  98. }
  99. // SetQuotePolicy sets the special quote policy
  100. func (engine *Engine) SetQuotePolicy(quotePolicy dialects.QuotePolicy) {
  101. engine.dialect.SetQuotePolicy(quotePolicy)
  102. }
  103. // BufferSize sets buffer size for iterate
  104. func (engine *Engine) BufferSize(size int) *Session {
  105. session := engine.NewSession()
  106. session.isAutoClose = true
  107. return session.BufferSize(size)
  108. }
  109. // ShowSQL show SQL statement or not on logger if log level is great than INFO
  110. func (engine *Engine) ShowSQL(show ...bool) {
  111. engine.logger.ShowSQL(show...)
  112. engine.DB().Logger = engine.logger
  113. }
  114. // Logger return the logger interface
  115. func (engine *Engine) Logger() log.ContextLogger {
  116. return engine.logger
  117. }
  118. // SetLogger set the new logger
  119. func (engine *Engine) SetLogger(logger interface{}) {
  120. var realLogger log.ContextLogger
  121. switch t := logger.(type) {
  122. case log.Logger:
  123. realLogger = log.NewLoggerAdapter(t)
  124. case log.ContextLogger:
  125. realLogger = t
  126. }
  127. engine.logger = realLogger
  128. engine.DB().Logger = realLogger
  129. }
  130. // SetLogLevel sets the logger level
  131. func (engine *Engine) SetLogLevel(level log.LogLevel) {
  132. engine.logger.SetLevel(level)
  133. }
  134. // SetDisableGlobalCache disable global cache or not
  135. func (engine *Engine) SetDisableGlobalCache(disable bool) {
  136. engine.cacherMgr.SetDisableGlobalCache(disable)
  137. }
  138. // DriverName return the current sql driver's name
  139. func (engine *Engine) DriverName() string {
  140. return engine.driverName
  141. }
  142. // DataSourceName return the current connection string
  143. func (engine *Engine) DataSourceName() string {
  144. return engine.dataSourceName
  145. }
  146. // SetMapper set the name mapping rules
  147. func (engine *Engine) SetMapper(mapper names.Mapper) {
  148. engine.SetTableMapper(mapper)
  149. engine.SetColumnMapper(mapper)
  150. }
  151. // SetTableMapper set the table name mapping rule
  152. func (engine *Engine) SetTableMapper(mapper names.Mapper) {
  153. engine.tagParser.SetTableMapper(mapper)
  154. }
  155. // SetColumnMapper set the column name mapping rule
  156. func (engine *Engine) SetColumnMapper(mapper names.Mapper) {
  157. engine.tagParser.SetColumnMapper(mapper)
  158. }
  159. // Quote Use QuoteStr quote the string sql
  160. func (engine *Engine) Quote(value string) string {
  161. value = strings.TrimSpace(value)
  162. if len(value) == 0 {
  163. return value
  164. }
  165. buf := strings.Builder{}
  166. engine.QuoteTo(&buf, value)
  167. return buf.String()
  168. }
  169. // QuoteTo quotes string and writes into the buffer
  170. func (engine *Engine) QuoteTo(buf *strings.Builder, value string) {
  171. if buf == nil {
  172. return
  173. }
  174. value = strings.TrimSpace(value)
  175. if value == "" {
  176. return
  177. }
  178. engine.dialect.Quoter().QuoteTo(buf, value)
  179. }
  180. // SQLType A simple wrapper to dialect's core.SqlType method
  181. func (engine *Engine) SQLType(c *schemas.Column) string {
  182. return engine.dialect.SQLType(c)
  183. }
  184. // AutoIncrStr Database's autoincrement statement
  185. func (engine *Engine) AutoIncrStr() string {
  186. return engine.dialect.AutoIncrStr()
  187. }
  188. // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
  189. func (engine *Engine) SetConnMaxLifetime(d time.Duration) {
  190. engine.DB().SetConnMaxLifetime(d)
  191. }
  192. // SetMaxOpenConns is only available for go 1.2+
  193. func (engine *Engine) SetMaxOpenConns(conns int) {
  194. engine.DB().SetMaxOpenConns(conns)
  195. }
  196. // SetMaxIdleConns set the max idle connections on pool, default is 2
  197. func (engine *Engine) SetMaxIdleConns(conns int) {
  198. engine.DB().SetMaxIdleConns(conns)
  199. }
  200. // SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
  201. func (engine *Engine) SetDefaultCacher(cacher caches.Cacher) {
  202. engine.cacherMgr.SetDefaultCacher(cacher)
  203. }
  204. // GetDefaultCacher returns the default cacher
  205. func (engine *Engine) GetDefaultCacher() caches.Cacher {
  206. return engine.cacherMgr.GetDefaultCacher()
  207. }
  208. // NoCache If you has set default cacher, and you want temporilly stop use cache,
  209. // you can use NoCache()
  210. func (engine *Engine) NoCache() *Session {
  211. session := engine.NewSession()
  212. session.isAutoClose = true
  213. return session.NoCache()
  214. }
  215. // NoCascade If you do not want to auto cascade load object
  216. func (engine *Engine) NoCascade() *Session {
  217. session := engine.NewSession()
  218. session.isAutoClose = true
  219. return session.NoCascade()
  220. }
  221. // MapCacher Set a table use a special cacher
  222. func (engine *Engine) MapCacher(bean interface{}, cacher caches.Cacher) error {
  223. engine.SetCacher(dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean, true), cacher)
  224. return nil
  225. }
  226. // NewDB provides an interface to operate database directly
  227. func (engine *Engine) NewDB() (*core.DB, error) {
  228. return core.Open(engine.driverName, engine.dataSourceName)
  229. }
  230. // DB return the wrapper of sql.DB
  231. func (engine *Engine) DB() *core.DB {
  232. return engine.db
  233. }
  234. // Dialect return database dialect
  235. func (engine *Engine) Dialect() dialects.Dialect {
  236. return engine.dialect
  237. }
  238. // NewSession New a session
  239. func (engine *Engine) NewSession() *Session {
  240. return newSession(engine)
  241. }
  242. // Close the engine
  243. func (engine *Engine) Close() error {
  244. return engine.DB().Close()
  245. }
  246. // Ping tests if database is alive
  247. func (engine *Engine) Ping() error {
  248. session := engine.NewSession()
  249. defer session.Close()
  250. return session.Ping()
  251. }
  252. // SQL method let's you manually write raw SQL and operate
  253. // For example:
  254. //
  255. // engine.SQL("select * from user").Find(&users)
  256. //
  257. // This code will execute "select * from user" and set the records to users
  258. func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session {
  259. session := engine.NewSession()
  260. session.isAutoClose = true
  261. return session.SQL(query, args...)
  262. }
  263. // NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields
  264. // will automatically be filled with current time when Insert or Update
  265. // invoked. Call NoAutoTime if you dont' want to fill automatically.
  266. func (engine *Engine) NoAutoTime() *Session {
  267. session := engine.NewSession()
  268. session.isAutoClose = true
  269. return session.NoAutoTime()
  270. }
  271. // NoAutoCondition disable auto generate Where condition from bean or not
  272. func (engine *Engine) NoAutoCondition(no ...bool) *Session {
  273. session := engine.NewSession()
  274. session.isAutoClose = true
  275. return session.NoAutoCondition(no...)
  276. }
  277. func (engine *Engine) loadTableInfo(table *schemas.Table) error {
  278. colSeq, cols, err := engine.dialect.GetColumns(engine.db, engine.defaultContext, table.Name)
  279. if err != nil {
  280. return err
  281. }
  282. for _, name := range colSeq {
  283. table.AddColumn(cols[name])
  284. }
  285. indexes, err := engine.dialect.GetIndexes(engine.db, engine.defaultContext, table.Name)
  286. if err != nil {
  287. return err
  288. }
  289. table.Indexes = indexes
  290. var seq int
  291. for _, index := range indexes {
  292. for _, name := range index.Cols {
  293. parts := strings.Split(name, " ")
  294. if len(parts) > 1 {
  295. if parts[1] == "DESC" {
  296. seq = 1
  297. }
  298. }
  299. if col := table.GetColumn(parts[0]); col != nil {
  300. col.Indexes[index.Name] = index.Type
  301. } else {
  302. return fmt.Errorf("Unknown col %s seq %d, in index %v of table %v, columns %v", name, seq, index.Name, table.Name, table.ColumnsSeq())
  303. }
  304. }
  305. }
  306. return nil
  307. }
  308. // DBMetas Retrieve all tables, columns, indexes' informations from database.
  309. func (engine *Engine) DBMetas() ([]*schemas.Table, error) {
  310. tables, err := engine.dialect.GetTables(engine.db, engine.defaultContext)
  311. if err != nil {
  312. return nil, err
  313. }
  314. for _, table := range tables {
  315. if err = engine.loadTableInfo(table); err != nil {
  316. return nil, err
  317. }
  318. }
  319. return tables, nil
  320. }
  321. // DumpAllToFile dump database all table structs and data to a file
  322. func (engine *Engine) DumpAllToFile(fp string, tp ...schemas.DBType) error {
  323. f, err := os.Create(fp)
  324. if err != nil {
  325. return err
  326. }
  327. defer f.Close()
  328. return engine.DumpAll(f, tp...)
  329. }
  330. // DumpAll dump database all table structs and data to w
  331. func (engine *Engine) DumpAll(w io.Writer, tp ...schemas.DBType) error {
  332. tables, err := engine.DBMetas()
  333. if err != nil {
  334. return err
  335. }
  336. return engine.DumpTables(tables, w, tp...)
  337. }
  338. // DumpTablesToFile dump specified tables to SQL file.
  339. func (engine *Engine) DumpTablesToFile(tables []*schemas.Table, fp string, tp ...schemas.DBType) error {
  340. f, err := os.Create(fp)
  341. if err != nil {
  342. return err
  343. }
  344. defer f.Close()
  345. return engine.DumpTables(tables, f, tp...)
  346. }
  347. // DumpTables dump specify tables to io.Writer
  348. func (engine *Engine) DumpTables(tables []*schemas.Table, w io.Writer, tp ...schemas.DBType) error {
  349. return engine.dumpTables(tables, w, tp...)
  350. }
  351. // dumpTables dump database all table structs and data to w with specify db type
  352. func (engine *Engine) dumpTables(tables []*schemas.Table, w io.Writer, tp ...schemas.DBType) error {
  353. var dstDialect dialects.Dialect
  354. if len(tp) == 0 {
  355. dstDialect = engine.dialect
  356. } else {
  357. dstDialect = dialects.QueryDialect(tp[0])
  358. if dstDialect == nil {
  359. return errors.New("Unsupported database type")
  360. }
  361. uri := engine.dialect.URI()
  362. destURI := *uri
  363. dstDialect.Init(&destURI)
  364. }
  365. _, err := io.WriteString(w, fmt.Sprintf("/*Generated by xorm %s, from %s to %s*/\n\n",
  366. time.Now().In(engine.TZLocation).Format("2006-01-02 15:04:05"), engine.dialect.URI().DBType, dstDialect.URI().DBType))
  367. if err != nil {
  368. return err
  369. }
  370. for i, table := range tables {
  371. tableName := table.Name
  372. if dstDialect.URI().Schema != "" {
  373. tableName = fmt.Sprintf("%s.%s", dstDialect.URI().Schema, table.Name)
  374. }
  375. originalTableName := table.Name
  376. if engine.dialect.URI().Schema != "" {
  377. originalTableName = fmt.Sprintf("%s.%s", engine.dialect.URI().Schema, table.Name)
  378. }
  379. if i > 0 {
  380. _, err = io.WriteString(w, "\n")
  381. if err != nil {
  382. return err
  383. }
  384. }
  385. sqls, _ := dstDialect.CreateTableSQL(table, tableName)
  386. for _, s := range sqls {
  387. _, err = io.WriteString(w, s+";\n")
  388. if err != nil {
  389. return err
  390. }
  391. }
  392. if len(table.PKColumns()) > 0 && dstDialect.URI().DBType == schemas.MSSQL {
  393. fmt.Fprintf(w, "SET IDENTITY_INSERT [%s] ON;\n", table.Name)
  394. }
  395. for _, index := range table.Indexes {
  396. _, err = io.WriteString(w, dstDialect.CreateIndexSQL(table.Name, index)+";\n")
  397. if err != nil {
  398. return err
  399. }
  400. }
  401. cols := table.ColumnsSeq()
  402. colNames := engine.dialect.Quoter().Join(cols, ", ")
  403. destColNames := dstDialect.Quoter().Join(cols, ", ")
  404. rows, err := engine.DB().QueryContext(engine.defaultContext, "SELECT "+colNames+" FROM "+engine.Quote(originalTableName))
  405. if err != nil {
  406. return err
  407. }
  408. defer rows.Close()
  409. for rows.Next() {
  410. dest := make([]interface{}, len(cols))
  411. err = rows.ScanSlice(&dest)
  412. if err != nil {
  413. return err
  414. }
  415. _, err = io.WriteString(w, "INSERT INTO "+dstDialect.Quoter().Quote(tableName)+" ("+destColNames+") VALUES (")
  416. if err != nil {
  417. return err
  418. }
  419. var temp string
  420. for i, d := range dest {
  421. col := table.GetColumn(cols[i])
  422. if col == nil {
  423. return errors.New("unknow column error")
  424. }
  425. if d == nil {
  426. temp += ", NULL"
  427. } else if col.SQLType.IsText() || col.SQLType.IsTime() {
  428. var v = fmt.Sprintf("%s", d)
  429. if strings.HasSuffix(v, " +0000 UTC") {
  430. temp += fmt.Sprintf(", '%s'", v[0:len(v)-len(" +0000 UTC")])
  431. } else {
  432. temp += ", '" + strings.Replace(v, "'", "''", -1) + "'"
  433. }
  434. } else if col.SQLType.IsBlob() {
  435. if reflect.TypeOf(d).Kind() == reflect.Slice {
  436. temp += fmt.Sprintf(", %s", dstDialect.FormatBytes(d.([]byte)))
  437. } else if reflect.TypeOf(d).Kind() == reflect.String {
  438. temp += fmt.Sprintf(", '%s'", d.(string))
  439. }
  440. } else if col.SQLType.IsNumeric() {
  441. switch reflect.TypeOf(d).Kind() {
  442. case reflect.Slice:
  443. if col.SQLType.Name == schemas.Bool {
  444. temp += fmt.Sprintf(", %v", strconv.FormatBool(d.([]byte)[0] != byte('0')))
  445. } else {
  446. temp += fmt.Sprintf(", %s", string(d.([]byte)))
  447. }
  448. case reflect.Int16, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Int:
  449. if col.SQLType.Name == schemas.Bool {
  450. temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Int() > 0))
  451. } else {
  452. temp += fmt.Sprintf(", %v", d)
  453. }
  454. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  455. if col.SQLType.Name == schemas.Bool {
  456. temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Uint() > 0))
  457. } else {
  458. temp += fmt.Sprintf(", %v", d)
  459. }
  460. default:
  461. temp += fmt.Sprintf(", %v", d)
  462. }
  463. } else {
  464. s := fmt.Sprintf("%v", d)
  465. if strings.Contains(s, ":") || strings.Contains(s, "-") {
  466. if strings.HasSuffix(s, " +0000 UTC") {
  467. temp += fmt.Sprintf(", '%s'", s[0:len(s)-len(" +0000 UTC")])
  468. } else {
  469. temp += fmt.Sprintf(", '%s'", s)
  470. }
  471. } else {
  472. temp += fmt.Sprintf(", %s", s)
  473. }
  474. }
  475. }
  476. _, err = io.WriteString(w, temp[2:]+");\n")
  477. if err != nil {
  478. return err
  479. }
  480. }
  481. // FIXME: Hack for postgres
  482. if dstDialect.URI().DBType == schemas.POSTGRES && table.AutoIncrColumn() != nil {
  483. _, err = io.WriteString(w, "SELECT setval('"+tableName+"_id_seq', COALESCE((SELECT MAX("+table.AutoIncrColumn().Name+") + 1 FROM "+dstDialect.Quoter().Quote(tableName)+"), 1), false);\n")
  484. if err != nil {
  485. return err
  486. }
  487. }
  488. }
  489. return nil
  490. }
  491. // Cascade use cascade or not
  492. func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
  493. session := engine.NewSession()
  494. session.isAutoClose = true
  495. return session.Cascade(trueOrFalse...)
  496. }
  497. // Where method provide a condition query
  498. func (engine *Engine) Where(query interface{}, args ...interface{}) *Session {
  499. session := engine.NewSession()
  500. session.isAutoClose = true
  501. return session.Where(query, args...)
  502. }
  503. // ID method provoide a condition as (id) = ?
  504. func (engine *Engine) ID(id interface{}) *Session {
  505. session := engine.NewSession()
  506. session.isAutoClose = true
  507. return session.ID(id)
  508. }
  509. // Before apply before Processor, affected bean is passed to closure arg
  510. func (engine *Engine) Before(closures func(interface{})) *Session {
  511. session := engine.NewSession()
  512. session.isAutoClose = true
  513. return session.Before(closures)
  514. }
  515. // After apply after insert Processor, affected bean is passed to closure arg
  516. func (engine *Engine) After(closures func(interface{})) *Session {
  517. session := engine.NewSession()
  518. session.isAutoClose = true
  519. return session.After(closures)
  520. }
  521. // Charset set charset when create table, only support mysql now
  522. func (engine *Engine) Charset(charset string) *Session {
  523. session := engine.NewSession()
  524. session.isAutoClose = true
  525. return session.Charset(charset)
  526. }
  527. // StoreEngine set store engine when create table, only support mysql now
  528. func (engine *Engine) StoreEngine(storeEngine string) *Session {
  529. session := engine.NewSession()
  530. session.isAutoClose = true
  531. return session.StoreEngine(storeEngine)
  532. }
  533. // Distinct use for distinct columns. Caution: when you are using cache,
  534. // distinct will not be cached because cache system need id,
  535. // but distinct will not provide id
  536. func (engine *Engine) Distinct(columns ...string) *Session {
  537. session := engine.NewSession()
  538. session.isAutoClose = true
  539. return session.Distinct(columns...)
  540. }
  541. // Select customerize your select columns or contents
  542. func (engine *Engine) Select(str string) *Session {
  543. session := engine.NewSession()
  544. session.isAutoClose = true
  545. return session.Select(str)
  546. }
  547. // Cols only use the parameters as select or update columns
  548. func (engine *Engine) Cols(columns ...string) *Session {
  549. session := engine.NewSession()
  550. session.isAutoClose = true
  551. return session.Cols(columns...)
  552. }
  553. // AllCols indicates that all columns should be use
  554. func (engine *Engine) AllCols() *Session {
  555. session := engine.NewSession()
  556. session.isAutoClose = true
  557. return session.AllCols()
  558. }
  559. // MustCols specify some columns must use even if they are empty
  560. func (engine *Engine) MustCols(columns ...string) *Session {
  561. session := engine.NewSession()
  562. session.isAutoClose = true
  563. return session.MustCols(columns...)
  564. }
  565. // UseBool xorm automatically retrieve condition according struct, but
  566. // if struct has bool field, it will ignore them. So use UseBool
  567. // to tell system to do not ignore them.
  568. // If no parameters, it will use all the bool field of struct, or
  569. // it will use parameters's columns
  570. func (engine *Engine) UseBool(columns ...string) *Session {
  571. session := engine.NewSession()
  572. session.isAutoClose = true
  573. return session.UseBool(columns...)
  574. }
  575. // Omit only not use the parameters as select or update columns
  576. func (engine *Engine) Omit(columns ...string) *Session {
  577. session := engine.NewSession()
  578. session.isAutoClose = true
  579. return session.Omit(columns...)
  580. }
  581. // Nullable set null when column is zero-value and nullable for update
  582. func (engine *Engine) Nullable(columns ...string) *Session {
  583. session := engine.NewSession()
  584. session.isAutoClose = true
  585. return session.Nullable(columns...)
  586. }
  587. // In will generate "column IN (?, ?)"
  588. func (engine *Engine) In(column string, args ...interface{}) *Session {
  589. session := engine.NewSession()
  590. session.isAutoClose = true
  591. return session.In(column, args...)
  592. }
  593. // NotIn will generate "column NOT IN (?, ?)"
  594. func (engine *Engine) NotIn(column string, args ...interface{}) *Session {
  595. session := engine.NewSession()
  596. session.isAutoClose = true
  597. return session.NotIn(column, args...)
  598. }
  599. // Incr provides a update string like "column = column + ?"
  600. func (engine *Engine) Incr(column string, arg ...interface{}) *Session {
  601. session := engine.NewSession()
  602. session.isAutoClose = true
  603. return session.Incr(column, arg...)
  604. }
  605. // Decr provides a update string like "column = column - ?"
  606. func (engine *Engine) Decr(column string, arg ...interface{}) *Session {
  607. session := engine.NewSession()
  608. session.isAutoClose = true
  609. return session.Decr(column, arg...)
  610. }
  611. // SetExpr provides a update string like "column = {expression}"
  612. func (engine *Engine) SetExpr(column string, expression interface{}) *Session {
  613. session := engine.NewSession()
  614. session.isAutoClose = true
  615. return session.SetExpr(column, expression)
  616. }
  617. // Table temporarily change the Get, Find, Update's table
  618. func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
  619. session := engine.NewSession()
  620. session.isAutoClose = true
  621. return session.Table(tableNameOrBean)
  622. }
  623. // Alias set the table alias
  624. func (engine *Engine) Alias(alias string) *Session {
  625. session := engine.NewSession()
  626. session.isAutoClose = true
  627. return session.Alias(alias)
  628. }
  629. // Limit will generate "LIMIT start, limit"
  630. func (engine *Engine) Limit(limit int, start ...int) *Session {
  631. session := engine.NewSession()
  632. session.isAutoClose = true
  633. return session.Limit(limit, start...)
  634. }
  635. // Desc will generate "ORDER BY column1 DESC, column2 DESC"
  636. func (engine *Engine) Desc(colNames ...string) *Session {
  637. session := engine.NewSession()
  638. session.isAutoClose = true
  639. return session.Desc(colNames...)
  640. }
  641. // Asc will generate "ORDER BY column1,column2 Asc"
  642. // This method can chainable use.
  643. //
  644. // engine.Desc("name").Asc("age").Find(&users)
  645. // // SELECT * FROM user ORDER BY name DESC, age ASC
  646. //
  647. func (engine *Engine) Asc(colNames ...string) *Session {
  648. session := engine.NewSession()
  649. session.isAutoClose = true
  650. return session.Asc(colNames...)
  651. }
  652. // OrderBy will generate "ORDER BY order"
  653. func (engine *Engine) OrderBy(order string) *Session {
  654. session := engine.NewSession()
  655. session.isAutoClose = true
  656. return session.OrderBy(order)
  657. }
  658. // Prepare enables prepare statement
  659. func (engine *Engine) Prepare() *Session {
  660. session := engine.NewSession()
  661. session.isAutoClose = true
  662. return session.Prepare()
  663. }
  664. // Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
  665. func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
  666. session := engine.NewSession()
  667. session.isAutoClose = true
  668. return session.Join(joinOperator, tablename, condition, args...)
  669. }
  670. // GroupBy generate group by statement
  671. func (engine *Engine) GroupBy(keys string) *Session {
  672. session := engine.NewSession()
  673. session.isAutoClose = true
  674. return session.GroupBy(keys)
  675. }
  676. // Having generate having statement
  677. func (engine *Engine) Having(conditions string) *Session {
  678. session := engine.NewSession()
  679. session.isAutoClose = true
  680. return session.Having(conditions)
  681. }
  682. // Table table struct
  683. type Table struct {
  684. *schemas.Table
  685. Name string
  686. }
  687. // IsValid if table is valid
  688. func (t *Table) IsValid() bool {
  689. return t.Table != nil && len(t.Name) > 0
  690. }
  691. // TableInfo get table info according to bean's content
  692. func (engine *Engine) TableInfo(bean interface{}) (*schemas.Table, error) {
  693. v := utils.ReflectValue(bean)
  694. return engine.tagParser.ParseWithCache(v)
  695. }
  696. // IsTableEmpty if a table has any reocrd
  697. func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
  698. session := engine.NewSession()
  699. defer session.Close()
  700. return session.IsTableEmpty(bean)
  701. }
  702. // IsTableExist if a table is exist
  703. func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) {
  704. session := engine.NewSession()
  705. defer session.Close()
  706. return session.IsTableExist(beanOrTableName)
  707. }
  708. // IDOf get id from one struct
  709. func (engine *Engine) IDOf(bean interface{}) (schemas.PK, error) {
  710. return engine.IDOfV(reflect.ValueOf(bean))
  711. }
  712. // TableName returns table name with schema prefix if has
  713. func (engine *Engine) TableName(bean interface{}, includeSchema ...bool) string {
  714. return dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean, includeSchema...)
  715. }
  716. // IDOfV get id from one value of struct
  717. func (engine *Engine) IDOfV(rv reflect.Value) (schemas.PK, error) {
  718. return engine.idOfV(rv)
  719. }
  720. func (engine *Engine) idOfV(rv reflect.Value) (schemas.PK, error) {
  721. v := reflect.Indirect(rv)
  722. table, err := engine.tagParser.ParseWithCache(v)
  723. if err != nil {
  724. return nil, err
  725. }
  726. pk := make([]interface{}, len(table.PrimaryKeys))
  727. for i, col := range table.PKColumns() {
  728. var err error
  729. fieldName := col.FieldName
  730. for {
  731. parts := strings.SplitN(fieldName, ".", 2)
  732. if len(parts) == 1 {
  733. break
  734. }
  735. v = v.FieldByName(parts[0])
  736. if v.Kind() == reflect.Ptr {
  737. v = v.Elem()
  738. }
  739. if v.Kind() != reflect.Struct {
  740. return nil, ErrUnSupportedType
  741. }
  742. fieldName = parts[1]
  743. }
  744. pkField := v.FieldByName(fieldName)
  745. switch pkField.Kind() {
  746. case reflect.String:
  747. pk[i], err = engine.idTypeAssertion(col, pkField.String())
  748. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  749. pk[i], err = engine.idTypeAssertion(col, strconv.FormatInt(pkField.Int(), 10))
  750. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  751. // id of uint will be converted to int64
  752. pk[i], err = engine.idTypeAssertion(col, strconv.FormatUint(pkField.Uint(), 10))
  753. }
  754. if err != nil {
  755. return nil, err
  756. }
  757. }
  758. return schemas.PK(pk), nil
  759. }
  760. func (engine *Engine) idTypeAssertion(col *schemas.Column, sid string) (interface{}, error) {
  761. if col.SQLType.IsNumeric() {
  762. n, err := strconv.ParseInt(sid, 10, 64)
  763. if err != nil {
  764. return nil, err
  765. }
  766. return n, nil
  767. } else if col.SQLType.IsText() {
  768. return sid, nil
  769. } else {
  770. return nil, errors.New("not supported")
  771. }
  772. }
  773. // CreateIndexes create indexes
  774. func (engine *Engine) CreateIndexes(bean interface{}) error {
  775. session := engine.NewSession()
  776. defer session.Close()
  777. return session.CreateIndexes(bean)
  778. }
  779. // CreateUniques create uniques
  780. func (engine *Engine) CreateUniques(bean interface{}) error {
  781. session := engine.NewSession()
  782. defer session.Close()
  783. return session.CreateUniques(bean)
  784. }
  785. // ClearCacheBean if enabled cache, clear the cache bean
  786. func (engine *Engine) ClearCacheBean(bean interface{}, id string) error {
  787. tableName := dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean)
  788. cacher := engine.GetCacher(tableName)
  789. if cacher != nil {
  790. cacher.ClearIds(tableName)
  791. cacher.DelBean(tableName, id)
  792. }
  793. return nil
  794. }
  795. // ClearCache if enabled cache, clear some tables' cache
  796. func (engine *Engine) ClearCache(beans ...interface{}) error {
  797. for _, bean := range beans {
  798. tableName := dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean)
  799. cacher := engine.GetCacher(tableName)
  800. if cacher != nil {
  801. cacher.ClearIds(tableName)
  802. cacher.ClearBeans(tableName)
  803. }
  804. }
  805. return nil
  806. }
  807. // UnMapType remove table from tables cache
  808. func (engine *Engine) UnMapType(t reflect.Type) {
  809. engine.tagParser.ClearCacheTable(t)
  810. }
  811. // Sync the new struct changes to database, this method will automatically add
  812. // table, column, index, unique. but will not delete or change anything.
  813. // If you change some field, you should change the database manually.
  814. func (engine *Engine) Sync(beans ...interface{}) error {
  815. session := engine.NewSession()
  816. defer session.Close()
  817. for _, bean := range beans {
  818. v := utils.ReflectValue(bean)
  819. tableNameNoSchema := dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean)
  820. table, err := engine.tagParser.ParseWithCache(v)
  821. if err != nil {
  822. return err
  823. }
  824. isExist, err := session.Table(bean).isTableExist(tableNameNoSchema)
  825. if err != nil {
  826. return err
  827. }
  828. if !isExist {
  829. err = session.createTable(bean)
  830. if err != nil {
  831. return err
  832. }
  833. }
  834. /*isEmpty, err := engine.IsEmptyTable(bean)
  835. if err != nil {
  836. return err
  837. }*/
  838. var isEmpty bool
  839. if isEmpty {
  840. err = session.dropTable(bean)
  841. if err != nil {
  842. return err
  843. }
  844. err = session.createTable(bean)
  845. if err != nil {
  846. return err
  847. }
  848. } else {
  849. for _, col := range table.Columns() {
  850. isExist, err := engine.dialect.IsColumnExist(engine.db, session.ctx, tableNameNoSchema, col.Name)
  851. if err != nil {
  852. return err
  853. }
  854. if !isExist {
  855. if err := session.statement.SetRefBean(bean); err != nil {
  856. return err
  857. }
  858. err = session.addColumn(col.Name)
  859. if err != nil {
  860. return err
  861. }
  862. }
  863. }
  864. for name, index := range table.Indexes {
  865. if err := session.statement.SetRefBean(bean); err != nil {
  866. return err
  867. }
  868. if index.Type == schemas.UniqueType {
  869. isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, true)
  870. if err != nil {
  871. return err
  872. }
  873. if !isExist {
  874. if err := session.statement.SetRefBean(bean); err != nil {
  875. return err
  876. }
  877. err = session.addUnique(tableNameNoSchema, name)
  878. if err != nil {
  879. return err
  880. }
  881. }
  882. } else if index.Type == schemas.IndexType {
  883. isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, false)
  884. if err != nil {
  885. return err
  886. }
  887. if !isExist {
  888. if err := session.statement.SetRefBean(bean); err != nil {
  889. return err
  890. }
  891. err = session.addIndex(tableNameNoSchema, name)
  892. if err != nil {
  893. return err
  894. }
  895. }
  896. } else {
  897. return errors.New("unknow index type")
  898. }
  899. }
  900. }
  901. }
  902. return nil
  903. }
  904. // Sync2 synchronize structs to database tables
  905. func (engine *Engine) Sync2(beans ...interface{}) error {
  906. s := engine.NewSession()
  907. defer s.Close()
  908. return s.Sync2(beans...)
  909. }
  910. // CreateTables create tabls according bean
  911. func (engine *Engine) CreateTables(beans ...interface{}) error {
  912. session := engine.NewSession()
  913. defer session.Close()
  914. err := session.Begin()
  915. if err != nil {
  916. return err
  917. }
  918. for _, bean := range beans {
  919. err = session.createTable(bean)
  920. if err != nil {
  921. session.Rollback()
  922. return err
  923. }
  924. }
  925. return session.Commit()
  926. }
  927. // DropTables drop specify tables
  928. func (engine *Engine) DropTables(beans ...interface{}) error {
  929. session := engine.NewSession()
  930. defer session.Close()
  931. err := session.Begin()
  932. if err != nil {
  933. return err
  934. }
  935. for _, bean := range beans {
  936. err = session.dropTable(bean)
  937. if err != nil {
  938. session.Rollback()
  939. return err
  940. }
  941. }
  942. return session.Commit()
  943. }
  944. // DropIndexes drop indexes of a table
  945. func (engine *Engine) DropIndexes(bean interface{}) error {
  946. session := engine.NewSession()
  947. defer session.Close()
  948. return session.DropIndexes(bean)
  949. }
  950. // Exec raw sql
  951. func (engine *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
  952. session := engine.NewSession()
  953. defer session.Close()
  954. return session.Exec(sqlOrArgs...)
  955. }
  956. // Query a raw sql and return records as []map[string][]byte
  957. func (engine *Engine) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) {
  958. session := engine.NewSession()
  959. defer session.Close()
  960. return session.Query(sqlOrArgs...)
  961. }
  962. // QueryString runs a raw sql and return records as []map[string]string
  963. func (engine *Engine) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) {
  964. session := engine.NewSession()
  965. defer session.Close()
  966. return session.QueryString(sqlOrArgs...)
  967. }
  968. // QueryInterface runs a raw sql and return records as []map[string]interface{}
  969. func (engine *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) {
  970. session := engine.NewSession()
  971. defer session.Close()
  972. return session.QueryInterface(sqlOrArgs...)
  973. }
  974. // Insert one or more records
  975. func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
  976. session := engine.NewSession()
  977. defer session.Close()
  978. return session.Insert(beans...)
  979. }
  980. // InsertOne insert only one record
  981. func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
  982. session := engine.NewSession()
  983. defer session.Close()
  984. return session.InsertOne(bean)
  985. }
  986. // Update records, bean's non-empty fields are updated contents,
  987. // condiBean' non-empty filds are conditions
  988. // CAUTION:
  989. // 1.bool will defaultly be updated content nor conditions
  990. // You should call UseBool if you have bool to use.
  991. // 2.float32 & float64 may be not inexact as conditions
  992. func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
  993. session := engine.NewSession()
  994. defer session.Close()
  995. return session.Update(bean, condiBeans...)
  996. }
  997. // Delete records, bean's non-empty fields are conditions
  998. func (engine *Engine) Delete(bean interface{}) (int64, error) {
  999. session := engine.NewSession()
  1000. defer session.Close()
  1001. return session.Delete(bean)
  1002. }
  1003. // Get retrieve one record from table, bean's non-empty fields
  1004. // are conditions
  1005. func (engine *Engine) Get(bean interface{}) (bool, error) {
  1006. session := engine.NewSession()
  1007. defer session.Close()
  1008. return session.Get(bean)
  1009. }
  1010. // Exist returns true if the record exist otherwise return false
  1011. func (engine *Engine) Exist(bean ...interface{}) (bool, error) {
  1012. session := engine.NewSession()
  1013. defer session.Close()
  1014. return session.Exist(bean...)
  1015. }
  1016. // Find retrieve records from table, condiBeans's non-empty fields
  1017. // are conditions. beans could be []Struct, []*Struct, map[int64]Struct
  1018. // map[int64]*Struct
  1019. func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
  1020. session := engine.NewSession()
  1021. defer session.Close()
  1022. return session.Find(beans, condiBeans...)
  1023. }
  1024. // FindAndCount find the results and also return the counts
  1025. func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
  1026. session := engine.NewSession()
  1027. defer session.Close()
  1028. return session.FindAndCount(rowsSlicePtr, condiBean...)
  1029. }
  1030. // Iterate record by record handle records from table, bean's non-empty fields
  1031. // are conditions.
  1032. func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
  1033. session := engine.NewSession()
  1034. defer session.Close()
  1035. return session.Iterate(bean, fun)
  1036. }
  1037. // Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
  1038. // are conditions.
  1039. func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
  1040. session := engine.NewSession()
  1041. return session.Rows(bean)
  1042. }
  1043. // Count counts the records. bean's non-empty fields are conditions.
  1044. func (engine *Engine) Count(bean ...interface{}) (int64, error) {
  1045. session := engine.NewSession()
  1046. defer session.Close()
  1047. return session.Count(bean...)
  1048. }
  1049. // Sum sum the records by some column. bean's non-empty fields are conditions.
  1050. func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) {
  1051. session := engine.NewSession()
  1052. defer session.Close()
  1053. return session.Sum(bean, colName)
  1054. }
  1055. // SumInt sum the records by some column. bean's non-empty fields are conditions.
  1056. func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error) {
  1057. session := engine.NewSession()
  1058. defer session.Close()
  1059. return session.SumInt(bean, colName)
  1060. }
  1061. // Sums sum the records by some columns. bean's non-empty fields are conditions.
  1062. func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) {
  1063. session := engine.NewSession()
  1064. defer session.Close()
  1065. return session.Sums(bean, colNames...)
  1066. }
  1067. // SumsInt like Sums but return slice of int64 instead of float64.
  1068. func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) {
  1069. session := engine.NewSession()
  1070. defer session.Close()
  1071. return session.SumsInt(bean, colNames...)
  1072. }
  1073. // ImportFile SQL DDL file
  1074. func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
  1075. session := engine.NewSession()
  1076. defer session.Close()
  1077. return session.ImportFile(ddlPath)
  1078. }
  1079. // Import SQL DDL from io.Reader
  1080. func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
  1081. session := engine.NewSession()
  1082. defer session.Close()
  1083. return session.Import(r)
  1084. }
  1085. // nowTime return current time
  1086. func (engine *Engine) nowTime(col *schemas.Column) (interface{}, time.Time) {
  1087. t := time.Now()
  1088. var tz = engine.DatabaseTZ
  1089. if !col.DisableTimeZone && col.TimeZone != nil {
  1090. tz = col.TimeZone
  1091. }
  1092. return dialects.FormatTime(engine.dialect, col.SQLType.Name, t.In(tz)), t.In(engine.TZLocation)
  1093. }
  1094. // GetColumnMapper returns the column name mapper
  1095. func (engine *Engine) GetColumnMapper() names.Mapper {
  1096. return engine.tagParser.GetColumnMapper()
  1097. }
  1098. // GetTableMapper returns the table name mapper
  1099. func (engine *Engine) GetTableMapper() names.Mapper {
  1100. return engine.tagParser.GetTableMapper()
  1101. }
  1102. // GetTZLocation returns time zone of the application
  1103. func (engine *Engine) GetTZLocation() *time.Location {
  1104. return engine.TZLocation
  1105. }
  1106. // SetTZLocation sets time zone of the application
  1107. func (engine *Engine) SetTZLocation(tz *time.Location) {
  1108. engine.TZLocation = tz
  1109. }
  1110. // GetTZDatabase returns time zone of the database
  1111. func (engine *Engine) GetTZDatabase() *time.Location {
  1112. return engine.DatabaseTZ
  1113. }
  1114. // SetTZDatabase sets time zone of the database
  1115. func (engine *Engine) SetTZDatabase(tz *time.Location) {
  1116. engine.DatabaseTZ = tz
  1117. }
  1118. // SetSchema sets the schema of database
  1119. func (engine *Engine) SetSchema(schema string) {
  1120. engine.dialect.URI().SetSchema(schema)
  1121. }
  1122. func (engine *Engine) AddHook(hook contexts.Hook) {
  1123. engine.db.AddHook(hook)
  1124. }
  1125. // Unscoped always disable struct tag "deleted"
  1126. func (engine *Engine) Unscoped() *Session {
  1127. session := engine.NewSession()
  1128. session.isAutoClose = true
  1129. return session.Unscoped()
  1130. }
  1131. func (engine *Engine) tbNameWithSchema(v string) string {
  1132. return dialects.TableNameWithSchema(engine.dialect, v)
  1133. }
  1134. // ContextHook creates a session with the context
  1135. func (engine *Engine) Context(ctx context.Context) *Session {
  1136. session := engine.NewSession()
  1137. session.isAutoClose = true
  1138. return session.Context(ctx)
  1139. }
  1140. // SetDefaultContext set the default context
  1141. func (engine *Engine) SetDefaultContext(ctx context.Context) {
  1142. engine.defaultContext = ctx
  1143. }
  1144. // PingContext tests if database is alive
  1145. func (engine *Engine) PingContext(ctx context.Context) error {
  1146. session := engine.NewSession()
  1147. defer session.Close()
  1148. return session.PingContext(ctx)
  1149. }
  1150. // Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
  1151. func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {
  1152. session := engine.NewSession()
  1153. defer session.Close()
  1154. if err := session.Begin(); err != nil {
  1155. return nil, err
  1156. }
  1157. result, err := f(session)
  1158. if err != nil {
  1159. return nil, err
  1160. }
  1161. if err := session.Commit(); err != nil {
  1162. return nil, err
  1163. }
  1164. return result, nil
  1165. }