engine.go 42 KB

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