engine.go 44 KB

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