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.

engine.go 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. // TableName returns table name with schema prefix if has
  709. func (engine *Engine) TableName(bean interface{}, includeSchema ...bool) string {
  710. return dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean, includeSchema...)
  711. }
  712. // CreateIndexes create indexes
  713. func (engine *Engine) CreateIndexes(bean interface{}) error {
  714. session := engine.NewSession()
  715. defer session.Close()
  716. return session.CreateIndexes(bean)
  717. }
  718. // CreateUniques create uniques
  719. func (engine *Engine) CreateUniques(bean interface{}) error {
  720. session := engine.NewSession()
  721. defer session.Close()
  722. return session.CreateUniques(bean)
  723. }
  724. // ClearCacheBean if enabled cache, clear the cache bean
  725. func (engine *Engine) ClearCacheBean(bean interface{}, id string) error {
  726. tableName := dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean)
  727. cacher := engine.GetCacher(tableName)
  728. if cacher != nil {
  729. cacher.ClearIds(tableName)
  730. cacher.DelBean(tableName, id)
  731. }
  732. return nil
  733. }
  734. // ClearCache if enabled cache, clear some tables' cache
  735. func (engine *Engine) ClearCache(beans ...interface{}) error {
  736. for _, bean := range beans {
  737. tableName := dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean)
  738. cacher := engine.GetCacher(tableName)
  739. if cacher != nil {
  740. cacher.ClearIds(tableName)
  741. cacher.ClearBeans(tableName)
  742. }
  743. }
  744. return nil
  745. }
  746. // UnMapType remove table from tables cache
  747. func (engine *Engine) UnMapType(t reflect.Type) {
  748. engine.tagParser.ClearCacheTable(t)
  749. }
  750. // Sync the new struct changes to database, this method will automatically add
  751. // table, column, index, unique. but will not delete or change anything.
  752. // If you change some field, you should change the database manually.
  753. func (engine *Engine) Sync(beans ...interface{}) error {
  754. session := engine.NewSession()
  755. defer session.Close()
  756. for _, bean := range beans {
  757. v := utils.ReflectValue(bean)
  758. tableNameNoSchema := dialects.FullTableName(engine.dialect, engine.GetTableMapper(), bean)
  759. table, err := engine.tagParser.ParseWithCache(v)
  760. if err != nil {
  761. return err
  762. }
  763. isExist, err := session.Table(bean).isTableExist(tableNameNoSchema)
  764. if err != nil {
  765. return err
  766. }
  767. if !isExist {
  768. err = session.createTable(bean)
  769. if err != nil {
  770. return err
  771. }
  772. }
  773. /*isEmpty, err := engine.IsEmptyTable(bean)
  774. if err != nil {
  775. return err
  776. }*/
  777. var isEmpty bool
  778. if isEmpty {
  779. err = session.dropTable(bean)
  780. if err != nil {
  781. return err
  782. }
  783. err = session.createTable(bean)
  784. if err != nil {
  785. return err
  786. }
  787. } else {
  788. for _, col := range table.Columns() {
  789. isExist, err := engine.dialect.IsColumnExist(engine.db, session.ctx, tableNameNoSchema, col.Name)
  790. if err != nil {
  791. return err
  792. }
  793. if !isExist {
  794. if err := session.statement.SetRefBean(bean); err != nil {
  795. return err
  796. }
  797. err = session.addColumn(col.Name)
  798. if err != nil {
  799. return err
  800. }
  801. }
  802. }
  803. for name, index := range table.Indexes {
  804. if err := session.statement.SetRefBean(bean); err != nil {
  805. return err
  806. }
  807. if index.Type == schemas.UniqueType {
  808. isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, true)
  809. if err != nil {
  810. return err
  811. }
  812. if !isExist {
  813. if err := session.statement.SetRefBean(bean); err != nil {
  814. return err
  815. }
  816. err = session.addUnique(tableNameNoSchema, name)
  817. if err != nil {
  818. return err
  819. }
  820. }
  821. } else if index.Type == schemas.IndexType {
  822. isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, false)
  823. if err != nil {
  824. return err
  825. }
  826. if !isExist {
  827. if err := session.statement.SetRefBean(bean); err != nil {
  828. return err
  829. }
  830. err = session.addIndex(tableNameNoSchema, name)
  831. if err != nil {
  832. return err
  833. }
  834. }
  835. } else {
  836. return errors.New("unknow index type")
  837. }
  838. }
  839. }
  840. }
  841. return nil
  842. }
  843. // Sync2 synchronize structs to database tables
  844. func (engine *Engine) Sync2(beans ...interface{}) error {
  845. s := engine.NewSession()
  846. defer s.Close()
  847. return s.Sync2(beans...)
  848. }
  849. // CreateTables create tabls according bean
  850. func (engine *Engine) CreateTables(beans ...interface{}) error {
  851. session := engine.NewSession()
  852. defer session.Close()
  853. err := session.Begin()
  854. if err != nil {
  855. return err
  856. }
  857. for _, bean := range beans {
  858. err = session.createTable(bean)
  859. if err != nil {
  860. session.Rollback()
  861. return err
  862. }
  863. }
  864. return session.Commit()
  865. }
  866. // DropTables drop specify tables
  867. func (engine *Engine) DropTables(beans ...interface{}) error {
  868. session := engine.NewSession()
  869. defer session.Close()
  870. err := session.Begin()
  871. if err != nil {
  872. return err
  873. }
  874. for _, bean := range beans {
  875. err = session.dropTable(bean)
  876. if err != nil {
  877. session.Rollback()
  878. return err
  879. }
  880. }
  881. return session.Commit()
  882. }
  883. // DropIndexes drop indexes of a table
  884. func (engine *Engine) DropIndexes(bean interface{}) error {
  885. session := engine.NewSession()
  886. defer session.Close()
  887. return session.DropIndexes(bean)
  888. }
  889. // Exec raw sql
  890. func (engine *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
  891. session := engine.NewSession()
  892. defer session.Close()
  893. return session.Exec(sqlOrArgs...)
  894. }
  895. // Query a raw sql and return records as []map[string][]byte
  896. func (engine *Engine) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) {
  897. session := engine.NewSession()
  898. defer session.Close()
  899. return session.Query(sqlOrArgs...)
  900. }
  901. // QueryString runs a raw sql and return records as []map[string]string
  902. func (engine *Engine) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) {
  903. session := engine.NewSession()
  904. defer session.Close()
  905. return session.QueryString(sqlOrArgs...)
  906. }
  907. // QueryInterface runs a raw sql and return records as []map[string]interface{}
  908. func (engine *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) {
  909. session := engine.NewSession()
  910. defer session.Close()
  911. return session.QueryInterface(sqlOrArgs...)
  912. }
  913. // Insert one or more records
  914. func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
  915. session := engine.NewSession()
  916. defer session.Close()
  917. return session.Insert(beans...)
  918. }
  919. // InsertOne insert only one record
  920. func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
  921. session := engine.NewSession()
  922. defer session.Close()
  923. return session.InsertOne(bean)
  924. }
  925. // Update records, bean's non-empty fields are updated contents,
  926. // condiBean' non-empty filds are conditions
  927. // CAUTION:
  928. // 1.bool will defaultly be updated content nor conditions
  929. // You should call UseBool if you have bool to use.
  930. // 2.float32 & float64 may be not inexact as conditions
  931. func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
  932. session := engine.NewSession()
  933. defer session.Close()
  934. return session.Update(bean, condiBeans...)
  935. }
  936. // Delete records, bean's non-empty fields are conditions
  937. func (engine *Engine) Delete(bean interface{}) (int64, error) {
  938. session := engine.NewSession()
  939. defer session.Close()
  940. return session.Delete(bean)
  941. }
  942. // Get retrieve one record from table, bean's non-empty fields
  943. // are conditions
  944. func (engine *Engine) Get(bean interface{}) (bool, error) {
  945. session := engine.NewSession()
  946. defer session.Close()
  947. return session.Get(bean)
  948. }
  949. // Exist returns true if the record exist otherwise return false
  950. func (engine *Engine) Exist(bean ...interface{}) (bool, error) {
  951. session := engine.NewSession()
  952. defer session.Close()
  953. return session.Exist(bean...)
  954. }
  955. // Find retrieve records from table, condiBeans's non-empty fields
  956. // are conditions. beans could be []Struct, []*Struct, map[int64]Struct
  957. // map[int64]*Struct
  958. func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
  959. session := engine.NewSession()
  960. defer session.Close()
  961. return session.Find(beans, condiBeans...)
  962. }
  963. // FindAndCount find the results and also return the counts
  964. func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
  965. session := engine.NewSession()
  966. defer session.Close()
  967. return session.FindAndCount(rowsSlicePtr, condiBean...)
  968. }
  969. // Iterate record by record handle records from table, bean's non-empty fields
  970. // are conditions.
  971. func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
  972. session := engine.NewSession()
  973. defer session.Close()
  974. return session.Iterate(bean, fun)
  975. }
  976. // Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
  977. // are conditions.
  978. func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
  979. session := engine.NewSession()
  980. return session.Rows(bean)
  981. }
  982. // Count counts the records. bean's non-empty fields are conditions.
  983. func (engine *Engine) Count(bean ...interface{}) (int64, error) {
  984. session := engine.NewSession()
  985. defer session.Close()
  986. return session.Count(bean...)
  987. }
  988. // Sum sum the records by some column. bean's non-empty fields are conditions.
  989. func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) {
  990. session := engine.NewSession()
  991. defer session.Close()
  992. return session.Sum(bean, colName)
  993. }
  994. // SumInt sum the records by some column. bean's non-empty fields are conditions.
  995. func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error) {
  996. session := engine.NewSession()
  997. defer session.Close()
  998. return session.SumInt(bean, colName)
  999. }
  1000. // Sums sum the records by some columns. bean's non-empty fields are conditions.
  1001. func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) {
  1002. session := engine.NewSession()
  1003. defer session.Close()
  1004. return session.Sums(bean, colNames...)
  1005. }
  1006. // SumsInt like Sums but return slice of int64 instead of float64.
  1007. func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) {
  1008. session := engine.NewSession()
  1009. defer session.Close()
  1010. return session.SumsInt(bean, colNames...)
  1011. }
  1012. // ImportFile SQL DDL file
  1013. func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
  1014. session := engine.NewSession()
  1015. defer session.Close()
  1016. return session.ImportFile(ddlPath)
  1017. }
  1018. // Import SQL DDL from io.Reader
  1019. func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
  1020. session := engine.NewSession()
  1021. defer session.Close()
  1022. return session.Import(r)
  1023. }
  1024. // nowTime return current time
  1025. func (engine *Engine) nowTime(col *schemas.Column) (interface{}, time.Time) {
  1026. t := time.Now()
  1027. var tz = engine.DatabaseTZ
  1028. if !col.DisableTimeZone && col.TimeZone != nil {
  1029. tz = col.TimeZone
  1030. }
  1031. return dialects.FormatTime(engine.dialect, col.SQLType.Name, t.In(tz)), t.In(engine.TZLocation)
  1032. }
  1033. // GetColumnMapper returns the column name mapper
  1034. func (engine *Engine) GetColumnMapper() names.Mapper {
  1035. return engine.tagParser.GetColumnMapper()
  1036. }
  1037. // GetTableMapper returns the table name mapper
  1038. func (engine *Engine) GetTableMapper() names.Mapper {
  1039. return engine.tagParser.GetTableMapper()
  1040. }
  1041. // GetTZLocation returns time zone of the application
  1042. func (engine *Engine) GetTZLocation() *time.Location {
  1043. return engine.TZLocation
  1044. }
  1045. // SetTZLocation sets time zone of the application
  1046. func (engine *Engine) SetTZLocation(tz *time.Location) {
  1047. engine.TZLocation = tz
  1048. }
  1049. // GetTZDatabase returns time zone of the database
  1050. func (engine *Engine) GetTZDatabase() *time.Location {
  1051. return engine.DatabaseTZ
  1052. }
  1053. // SetTZDatabase sets time zone of the database
  1054. func (engine *Engine) SetTZDatabase(tz *time.Location) {
  1055. engine.DatabaseTZ = tz
  1056. }
  1057. // SetSchema sets the schema of database
  1058. func (engine *Engine) SetSchema(schema string) {
  1059. engine.dialect.URI().SetSchema(schema)
  1060. }
  1061. func (engine *Engine) AddHook(hook contexts.Hook) {
  1062. engine.db.AddHook(hook)
  1063. }
  1064. // Unscoped always disable struct tag "deleted"
  1065. func (engine *Engine) Unscoped() *Session {
  1066. session := engine.NewSession()
  1067. session.isAutoClose = true
  1068. return session.Unscoped()
  1069. }
  1070. func (engine *Engine) tbNameWithSchema(v string) string {
  1071. return dialects.TableNameWithSchema(engine.dialect, v)
  1072. }
  1073. // ContextHook creates a session with the context
  1074. func (engine *Engine) Context(ctx context.Context) *Session {
  1075. session := engine.NewSession()
  1076. session.isAutoClose = true
  1077. return session.Context(ctx)
  1078. }
  1079. // SetDefaultContext set the default context
  1080. func (engine *Engine) SetDefaultContext(ctx context.Context) {
  1081. engine.defaultContext = ctx
  1082. }
  1083. // PingContext tests if database is alive
  1084. func (engine *Engine) PingContext(ctx context.Context) error {
  1085. session := engine.NewSession()
  1086. defer session.Close()
  1087. return session.PingContext(ctx)
  1088. }
  1089. // Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
  1090. func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {
  1091. session := engine.NewSession()
  1092. defer session.Close()
  1093. if err := session.Begin(); err != nil {
  1094. return nil, err
  1095. }
  1096. result, err := f(session)
  1097. if err != nil {
  1098. return nil, err
  1099. }
  1100. if err := session.Commit(); err != nil {
  1101. return nil, err
  1102. }
  1103. return result, nil
  1104. }