engine.go 45 KB

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