You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

engine.go 45KB

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