engine.go 43 KB

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