engine.go 45 KB

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