engine.go 42 KB

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