engine.go 47 KB

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