statement.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. "bytes"
  7. "database/sql/driver"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "reflect"
  12. "strings"
  13. "time"
  14. "github.com/go-xorm/builder"
  15. "github.com/xormplus/core"
  16. )
  17. type incrParam struct {
  18. colName string
  19. arg interface{}
  20. }
  21. type decrParam struct {
  22. colName string
  23. arg interface{}
  24. }
  25. type exprParam struct {
  26. colName string
  27. expr string
  28. }
  29. // Statement save all the sql info for executing SQL
  30. type Statement struct {
  31. RefTable *core.Table
  32. Engine *Engine
  33. Start int
  34. LimitN int
  35. idParam *core.PK
  36. OrderStr string
  37. JoinStr string
  38. joinArgs []interface{}
  39. GroupByStr string
  40. HavingStr string
  41. ColumnStr string
  42. selectStr string
  43. columnMap map[string]bool
  44. useAllCols bool
  45. OmitStr string
  46. AltTableName string
  47. tableName string
  48. RawSQL string
  49. RawParams []interface{}
  50. UseCascade bool
  51. UseAutoJoin bool
  52. StoreEngine string
  53. Charset string
  54. UseCache bool
  55. UseAutoTime bool
  56. noAutoCondition bool
  57. IsDistinct bool
  58. IsForUpdate bool
  59. TableAlias string
  60. allUseBool bool
  61. checkVersion bool
  62. unscoped bool
  63. mustColumnMap map[string]bool
  64. nullableMap map[string]bool
  65. incrColumns map[string]incrParam
  66. decrColumns map[string]decrParam
  67. exprColumns map[string]exprParam
  68. cond builder.Cond
  69. }
  70. // Init reset all the statement's fields
  71. func (statement *Statement) Init() {
  72. statement.RefTable = nil
  73. statement.Start = 0
  74. statement.LimitN = 0
  75. statement.OrderStr = ""
  76. statement.UseCascade = true
  77. statement.JoinStr = ""
  78. statement.joinArgs = make([]interface{}, 0)
  79. statement.GroupByStr = ""
  80. statement.HavingStr = ""
  81. statement.ColumnStr = ""
  82. statement.OmitStr = ""
  83. statement.columnMap = make(map[string]bool)
  84. statement.AltTableName = ""
  85. statement.tableName = ""
  86. statement.idParam = nil
  87. statement.RawSQL = ""
  88. statement.RawParams = make([]interface{}, 0)
  89. statement.UseCache = true
  90. statement.UseAutoTime = true
  91. statement.noAutoCondition = false
  92. statement.IsDistinct = false
  93. statement.IsForUpdate = false
  94. statement.TableAlias = ""
  95. statement.selectStr = ""
  96. statement.allUseBool = false
  97. statement.useAllCols = false
  98. statement.mustColumnMap = make(map[string]bool)
  99. statement.nullableMap = make(map[string]bool)
  100. statement.checkVersion = true
  101. statement.unscoped = false
  102. statement.incrColumns = make(map[string]incrParam)
  103. statement.decrColumns = make(map[string]decrParam)
  104. statement.exprColumns = make(map[string]exprParam)
  105. statement.cond = builder.NewCond()
  106. }
  107. // NoAutoCondition if you do not want convert bean's field as query condition, then use this function
  108. func (statement *Statement) NoAutoCondition(no ...bool) *Statement {
  109. statement.noAutoCondition = true
  110. if len(no) > 0 {
  111. statement.noAutoCondition = no[0]
  112. }
  113. return statement
  114. }
  115. // Alias set the table alias
  116. func (statement *Statement) Alias(alias string) *Statement {
  117. statement.TableAlias = alias
  118. return statement
  119. }
  120. // SQL adds raw sql statement
  121. func (statement *Statement) SQL(query interface{}, args ...interface{}) *Statement {
  122. switch query.(type) {
  123. case (*builder.Builder):
  124. var err error
  125. statement.RawSQL, statement.RawParams, err = query.(*builder.Builder).ToSQL()
  126. if err != nil {
  127. statement.Engine.logger.Error(err)
  128. }
  129. case string:
  130. statement.RawSQL = query.(string)
  131. statement.RawParams = args
  132. default:
  133. statement.Engine.logger.Error("unsupported sql type")
  134. }
  135. return statement
  136. }
  137. // Where add Where statement
  138. func (statement *Statement) Where(query interface{}, args ...interface{}) *Statement {
  139. return statement.And(query, args...)
  140. }
  141. // And add Where & and statement
  142. func (statement *Statement) And(query interface{}, args ...interface{}) *Statement {
  143. switch query.(type) {
  144. case string:
  145. cond := builder.Expr(query.(string), args...)
  146. statement.cond = statement.cond.And(cond)
  147. case builder.Cond:
  148. cond := query.(builder.Cond)
  149. statement.cond = statement.cond.And(cond)
  150. for _, v := range args {
  151. if vv, ok := v.(builder.Cond); ok {
  152. statement.cond = statement.cond.And(vv)
  153. }
  154. }
  155. default:
  156. // TODO: not support condition type
  157. }
  158. return statement
  159. }
  160. // Or add Where & Or statement
  161. func (statement *Statement) Or(query interface{}, args ...interface{}) *Statement {
  162. switch query.(type) {
  163. case string:
  164. cond := builder.Expr(query.(string), args...)
  165. statement.cond = statement.cond.Or(cond)
  166. case builder.Cond:
  167. cond := query.(builder.Cond)
  168. statement.cond = statement.cond.Or(cond)
  169. for _, v := range args {
  170. if vv, ok := v.(builder.Cond); ok {
  171. statement.cond = statement.cond.Or(vv)
  172. }
  173. }
  174. default:
  175. // TODO: not support condition type
  176. }
  177. return statement
  178. }
  179. // In generate "Where column IN (?) " statement
  180. func (statement *Statement) In(column string, args ...interface{}) *Statement {
  181. in := builder.In(statement.Engine.Quote(column), args...)
  182. statement.cond = statement.cond.And(in)
  183. return statement
  184. }
  185. // NotIn generate "Where column NOT IN (?) " statement
  186. func (statement *Statement) NotIn(column string, args ...interface{}) *Statement {
  187. notIn := builder.NotIn(statement.Engine.Quote(column), args...)
  188. statement.cond = statement.cond.And(notIn)
  189. return statement
  190. }
  191. func (statement *Statement) setRefValue(v reflect.Value) error {
  192. var err error
  193. statement.RefTable, err = statement.Engine.autoMapType(reflect.Indirect(v))
  194. if err != nil {
  195. return err
  196. }
  197. statement.tableName = statement.Engine.tbName(v)
  198. return nil
  199. }
  200. // Table tempororily set table name, the parameter could be a string or a pointer of struct
  201. func (statement *Statement) Table(tableNameOrBean interface{}) *Statement {
  202. v := rValue(tableNameOrBean)
  203. t := v.Type()
  204. if t.Kind() == reflect.String {
  205. statement.AltTableName = tableNameOrBean.(string)
  206. } else if t.Kind() == reflect.Struct {
  207. var err error
  208. statement.RefTable, err = statement.Engine.autoMapType(v)
  209. if err != nil {
  210. statement.Engine.logger.Error(err)
  211. return statement
  212. }
  213. statement.AltTableName = statement.Engine.tbName(v)
  214. }
  215. return statement
  216. }
  217. // Auto generating update columnes and values according a struct
  218. func buildUpdates(engine *Engine, table *core.Table, bean interface{},
  219. includeVersion bool, includeUpdated bool, includeNil bool,
  220. includeAutoIncr bool, allUseBool bool, useAllCols bool,
  221. mustColumnMap map[string]bool, nullableMap map[string]bool,
  222. columnMap map[string]bool, update, unscoped bool) ([]string, []interface{}) {
  223. var colNames = make([]string, 0)
  224. var args = make([]interface{}, 0)
  225. for _, col := range table.Columns() {
  226. if !includeVersion && col.IsVersion {
  227. continue
  228. }
  229. if col.IsCreated {
  230. continue
  231. }
  232. if !includeUpdated && col.IsUpdated {
  233. continue
  234. }
  235. if !includeAutoIncr && col.IsAutoIncrement {
  236. continue
  237. }
  238. if col.IsDeleted && !unscoped {
  239. continue
  240. }
  241. if use, ok := columnMap[strings.ToLower(col.Name)]; ok && !use {
  242. continue
  243. }
  244. fieldValuePtr, err := col.ValueOf(bean)
  245. if err != nil {
  246. engine.logger.Error(err)
  247. continue
  248. }
  249. fieldValue := *fieldValuePtr
  250. fieldType := reflect.TypeOf(fieldValue.Interface())
  251. requiredField := useAllCols
  252. includeNil := useAllCols
  253. if b, ok := getFlagForColumn(mustColumnMap, col); ok {
  254. if b {
  255. requiredField = true
  256. } else {
  257. continue
  258. }
  259. }
  260. // !evalphobia! set fieldValue as nil when column is nullable and zero-value
  261. if b, ok := getFlagForColumn(nullableMap, col); ok {
  262. if b && col.Nullable && isZero(fieldValue.Interface()) {
  263. var nilValue *int
  264. fieldValue = reflect.ValueOf(nilValue)
  265. fieldType = reflect.TypeOf(fieldValue.Interface())
  266. includeNil = true
  267. }
  268. }
  269. var val interface{}
  270. if fieldValue.CanAddr() {
  271. if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  272. data, err := structConvert.ToDB()
  273. if err != nil {
  274. engine.logger.Error(err)
  275. } else {
  276. val = data
  277. }
  278. goto APPEND
  279. }
  280. }
  281. if structConvert, ok := fieldValue.Interface().(core.Conversion); ok {
  282. data, err := structConvert.ToDB()
  283. if err != nil {
  284. engine.logger.Error(err)
  285. } else {
  286. val = data
  287. }
  288. goto APPEND
  289. }
  290. if fieldType.Kind() == reflect.Ptr {
  291. if fieldValue.IsNil() {
  292. if includeNil {
  293. args = append(args, nil)
  294. colNames = append(colNames, fmt.Sprintf("%v=?", engine.Quote(col.Name)))
  295. }
  296. continue
  297. } else if !fieldValue.IsValid() {
  298. continue
  299. } else {
  300. // dereference ptr type to instance type
  301. fieldValue = fieldValue.Elem()
  302. fieldType = reflect.TypeOf(fieldValue.Interface())
  303. requiredField = true
  304. }
  305. }
  306. switch fieldType.Kind() {
  307. case reflect.Bool:
  308. if allUseBool || requiredField {
  309. val = fieldValue.Interface()
  310. } else {
  311. // if a bool in a struct, it will not be as a condition because it default is false,
  312. // please use Where() instead
  313. continue
  314. }
  315. case reflect.String:
  316. if !requiredField && fieldValue.String() == "" {
  317. continue
  318. }
  319. // for MyString, should convert to string or panic
  320. if fieldType.String() != reflect.String.String() {
  321. val = fieldValue.String()
  322. } else {
  323. val = fieldValue.Interface()
  324. }
  325. case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64:
  326. if !requiredField && fieldValue.Int() == 0 {
  327. continue
  328. }
  329. val = fieldValue.Interface()
  330. case reflect.Float32, reflect.Float64:
  331. if !requiredField && fieldValue.Float() == 0.0 {
  332. continue
  333. }
  334. val = fieldValue.Interface()
  335. case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
  336. if !requiredField && fieldValue.Uint() == 0 {
  337. continue
  338. }
  339. t := int64(fieldValue.Uint())
  340. val = reflect.ValueOf(&t).Interface()
  341. case reflect.Struct:
  342. if fieldType.ConvertibleTo(core.TimeType) {
  343. t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
  344. if !requiredField && (t.IsZero() || !fieldValue.IsValid()) {
  345. continue
  346. }
  347. val = engine.formatColTime(col, t)
  348. } else if nulType, ok := fieldValue.Interface().(driver.Valuer); ok {
  349. val, _ = nulType.Value()
  350. } else {
  351. if !col.SQLType.IsJson() {
  352. engine.autoMapType(fieldValue)
  353. if table, ok := engine.Tables[fieldValue.Type()]; ok {
  354. if len(table.PrimaryKeys) == 1 {
  355. pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName)
  356. // fix non-int pk issues
  357. if pkField.IsValid() && (!requiredField && !isZero(pkField.Interface())) {
  358. val = pkField.Interface()
  359. } else {
  360. continue
  361. }
  362. } else {
  363. //TODO: how to handler?
  364. panic("not supported")
  365. }
  366. } else {
  367. val = fieldValue.Interface()
  368. }
  369. } else {
  370. // Blank struct could not be as update data
  371. if requiredField || !isStructZero(fieldValue) {
  372. bytes, err := json.Marshal(fieldValue.Interface())
  373. if err != nil {
  374. panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface()))
  375. }
  376. if col.SQLType.IsText() {
  377. val = string(bytes)
  378. } else if col.SQLType.IsBlob() {
  379. val = bytes
  380. }
  381. } else {
  382. continue
  383. }
  384. }
  385. }
  386. case reflect.Array, reflect.Slice, reflect.Map:
  387. if !requiredField {
  388. if fieldValue == reflect.Zero(fieldType) {
  389. continue
  390. }
  391. if fieldType.Kind() == reflect.Array {
  392. if isArrayValueZero(fieldValue) {
  393. continue
  394. }
  395. } else if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 {
  396. continue
  397. }
  398. }
  399. if col.SQLType.IsText() {
  400. bytes, err := json.Marshal(fieldValue.Interface())
  401. if err != nil {
  402. engine.logger.Error(err)
  403. continue
  404. }
  405. val = string(bytes)
  406. } else if col.SQLType.IsBlob() {
  407. var bytes []byte
  408. var err error
  409. if fieldType.Kind() == reflect.Slice &&
  410. fieldType.Elem().Kind() == reflect.Uint8 {
  411. if fieldValue.Len() > 0 {
  412. val = fieldValue.Bytes()
  413. } else {
  414. continue
  415. }
  416. } else if fieldType.Kind() == reflect.Array &&
  417. fieldType.Elem().Kind() == reflect.Uint8 {
  418. val = fieldValue.Slice(0, 0).Interface()
  419. } else {
  420. bytes, err = json.Marshal(fieldValue.Interface())
  421. if err != nil {
  422. engine.logger.Error(err)
  423. continue
  424. }
  425. val = bytes
  426. }
  427. } else {
  428. continue
  429. }
  430. default:
  431. val = fieldValue.Interface()
  432. }
  433. APPEND:
  434. args = append(args, val)
  435. if col.IsPrimaryKey && engine.dialect.DBType() == "ql" {
  436. continue
  437. }
  438. colNames = append(colNames, fmt.Sprintf("%v = ?", engine.Quote(col.Name)))
  439. }
  440. return colNames, args
  441. }
  442. func (statement *Statement) needTableName() bool {
  443. return len(statement.JoinStr) > 0
  444. }
  445. func (statement *Statement) colName(col *core.Column, tableName string) string {
  446. if statement.needTableName() {
  447. var nm = tableName
  448. if len(statement.TableAlias) > 0 {
  449. nm = statement.TableAlias
  450. }
  451. return statement.Engine.Quote(nm) + "." + statement.Engine.Quote(col.Name)
  452. }
  453. return statement.Engine.Quote(col.Name)
  454. }
  455. // TableName return current tableName
  456. func (statement *Statement) TableName() string {
  457. if statement.AltTableName != "" {
  458. return statement.AltTableName
  459. }
  460. return statement.tableName
  461. }
  462. // ID generate "where id = ? " statement or for composite key "where key1 = ? and key2 = ?"
  463. func (statement *Statement) ID(id interface{}) *Statement {
  464. idValue := reflect.ValueOf(id)
  465. idType := reflect.TypeOf(idValue.Interface())
  466. switch idType {
  467. case ptrPkType:
  468. if pkPtr, ok := (id).(*core.PK); ok {
  469. statement.idParam = pkPtr
  470. return statement
  471. }
  472. case pkType:
  473. if pk, ok := (id).(core.PK); ok {
  474. statement.idParam = &pk
  475. return statement
  476. }
  477. }
  478. switch idType.Kind() {
  479. case reflect.String:
  480. statement.idParam = &core.PK{idValue.Convert(reflect.TypeOf("")).Interface()}
  481. return statement
  482. }
  483. statement.idParam = &core.PK{id}
  484. return statement
  485. }
  486. // Incr Generate "Update ... Set column = column + arg" statement
  487. func (statement *Statement) Incr(column string, arg ...interface{}) *Statement {
  488. k := strings.ToLower(column)
  489. if len(arg) > 0 {
  490. statement.incrColumns[k] = incrParam{column, arg[0]}
  491. } else {
  492. statement.incrColumns[k] = incrParam{column, 1}
  493. }
  494. return statement
  495. }
  496. // Decr Generate "Update ... Set column = column - arg" statement
  497. func (statement *Statement) Decr(column string, arg ...interface{}) *Statement {
  498. k := strings.ToLower(column)
  499. if len(arg) > 0 {
  500. statement.decrColumns[k] = decrParam{column, arg[0]}
  501. } else {
  502. statement.decrColumns[k] = decrParam{column, 1}
  503. }
  504. return statement
  505. }
  506. // SetExpr Generate "Update ... Set column = {expression}" statement
  507. func (statement *Statement) SetExpr(column string, expression string) *Statement {
  508. k := strings.ToLower(column)
  509. statement.exprColumns[k] = exprParam{column, expression}
  510. return statement
  511. }
  512. // Generate "Update ... Set column = column + arg" statement
  513. func (statement *Statement) getInc() map[string]incrParam {
  514. return statement.incrColumns
  515. }
  516. // Generate "Update ... Set column = column - arg" statement
  517. func (statement *Statement) getDec() map[string]decrParam {
  518. return statement.decrColumns
  519. }
  520. // Generate "Update ... Set column = {expression}" statement
  521. func (statement *Statement) getExpr() map[string]exprParam {
  522. return statement.exprColumns
  523. }
  524. func (statement *Statement) col2NewColsWithQuote(columns ...string) []string {
  525. newColumns := make([]string, 0)
  526. for _, col := range columns {
  527. col = strings.Replace(col, "`", "", -1)
  528. col = strings.Replace(col, statement.Engine.QuoteStr(), "", -1)
  529. ccols := strings.Split(col, ",")
  530. for _, c := range ccols {
  531. fields := strings.Split(strings.TrimSpace(c), ".")
  532. if len(fields) == 1 {
  533. newColumns = append(newColumns, statement.Engine.quote(fields[0]))
  534. } else if len(fields) == 2 {
  535. newColumns = append(newColumns, statement.Engine.quote(fields[0])+"."+
  536. statement.Engine.quote(fields[1]))
  537. } else {
  538. panic(errors.New("unwanted colnames"))
  539. }
  540. }
  541. }
  542. return newColumns
  543. }
  544. // Distinct generates "DISTINCT col1, col2 " statement
  545. func (statement *Statement) Distinct(columns ...string) *Statement {
  546. statement.IsDistinct = true
  547. statement.Cols(columns...)
  548. return statement
  549. }
  550. // ForUpdate generates "SELECT ... FOR UPDATE" statement
  551. func (statement *Statement) ForUpdate() *Statement {
  552. statement.IsForUpdate = true
  553. return statement
  554. }
  555. // Select replace select
  556. func (statement *Statement) Select(str string) *Statement {
  557. statement.selectStr = str
  558. return statement
  559. }
  560. // Cols generate "col1, col2" statement
  561. func (statement *Statement) Cols(columns ...string) *Statement {
  562. cols := col2NewCols(columns...)
  563. for _, nc := range cols {
  564. statement.columnMap[strings.ToLower(nc)] = true
  565. }
  566. newColumns := statement.col2NewColsWithQuote(columns...)
  567. statement.ColumnStr = strings.Join(newColumns, ", ")
  568. statement.ColumnStr = strings.Replace(statement.ColumnStr, statement.Engine.quote("*"), "*", -1)
  569. return statement
  570. }
  571. // AllCols update use only: update all columns
  572. func (statement *Statement) AllCols() *Statement {
  573. statement.useAllCols = true
  574. return statement
  575. }
  576. // MustCols update use only: must update columns
  577. func (statement *Statement) MustCols(columns ...string) *Statement {
  578. newColumns := col2NewCols(columns...)
  579. for _, nc := range newColumns {
  580. statement.mustColumnMap[strings.ToLower(nc)] = true
  581. }
  582. return statement
  583. }
  584. // UseBool indicates that use bool fields as update contents and query contiditions
  585. func (statement *Statement) UseBool(columns ...string) *Statement {
  586. if len(columns) > 0 {
  587. statement.MustCols(columns...)
  588. } else {
  589. statement.allUseBool = true
  590. }
  591. return statement
  592. }
  593. // Omit do not use the columns
  594. func (statement *Statement) Omit(columns ...string) {
  595. newColumns := col2NewCols(columns...)
  596. for _, nc := range newColumns {
  597. statement.columnMap[strings.ToLower(nc)] = false
  598. }
  599. statement.OmitStr = statement.Engine.Quote(strings.Join(newColumns, statement.Engine.Quote(", ")))
  600. }
  601. // Nullable Update use only: update columns to null when value is nullable and zero-value
  602. func (statement *Statement) Nullable(columns ...string) {
  603. newColumns := col2NewCols(columns...)
  604. for _, nc := range newColumns {
  605. statement.nullableMap[strings.ToLower(nc)] = true
  606. }
  607. }
  608. // Top generate LIMIT limit statement
  609. func (statement *Statement) Top(limit int) *Statement {
  610. statement.Limit(limit)
  611. return statement
  612. }
  613. // Limit generate LIMIT start, limit statement
  614. func (statement *Statement) Limit(limit int, start ...int) *Statement {
  615. statement.LimitN = limit
  616. if len(start) > 0 {
  617. statement.Start = start[0]
  618. }
  619. return statement
  620. }
  621. // OrderBy generate "Order By order" statement
  622. func (statement *Statement) OrderBy(order string) *Statement {
  623. if len(statement.OrderStr) > 0 {
  624. statement.OrderStr += ", "
  625. }
  626. statement.OrderStr += order
  627. return statement
  628. }
  629. // Desc generate `ORDER BY xx DESC`
  630. func (statement *Statement) Desc(colNames ...string) *Statement {
  631. var buf bytes.Buffer
  632. fmt.Fprintf(&buf, statement.OrderStr)
  633. if len(statement.OrderStr) > 0 {
  634. fmt.Fprint(&buf, ", ")
  635. }
  636. newColNames := statement.col2NewColsWithQuote(colNames...)
  637. fmt.Fprintf(&buf, "%v DESC", strings.Join(newColNames, " DESC, "))
  638. statement.OrderStr = buf.String()
  639. return statement
  640. }
  641. // Asc provide asc order by query condition, the input parameters are columns.
  642. func (statement *Statement) Asc(colNames ...string) *Statement {
  643. var buf bytes.Buffer
  644. fmt.Fprintf(&buf, statement.OrderStr)
  645. if len(statement.OrderStr) > 0 {
  646. fmt.Fprint(&buf, ", ")
  647. }
  648. newColNames := statement.col2NewColsWithQuote(colNames...)
  649. fmt.Fprintf(&buf, "%v ASC", strings.Join(newColNames, " ASC, "))
  650. statement.OrderStr = buf.String()
  651. return statement
  652. }
  653. // Join The joinOP should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
  654. func (statement *Statement) Join(joinOP string, tablename interface{}, condition string, args ...interface{}) *Statement {
  655. var buf bytes.Buffer
  656. if len(statement.JoinStr) > 0 {
  657. fmt.Fprintf(&buf, "%v %v JOIN ", statement.JoinStr, joinOP)
  658. } else {
  659. fmt.Fprintf(&buf, "%v JOIN ", joinOP)
  660. }
  661. switch tablename.(type) {
  662. case []string:
  663. t := tablename.([]string)
  664. if len(t) > 1 {
  665. fmt.Fprintf(&buf, "%v AS %v", statement.Engine.Quote(t[0]), statement.Engine.Quote(t[1]))
  666. } else if len(t) == 1 {
  667. fmt.Fprintf(&buf, statement.Engine.Quote(t[0]))
  668. }
  669. case []interface{}:
  670. t := tablename.([]interface{})
  671. l := len(t)
  672. var table string
  673. if l > 0 {
  674. f := t[0]
  675. v := rValue(f)
  676. t := v.Type()
  677. if t.Kind() == reflect.String {
  678. table = f.(string)
  679. } else if t.Kind() == reflect.Struct {
  680. table = statement.Engine.tbName(v)
  681. }
  682. }
  683. if l > 1 {
  684. fmt.Fprintf(&buf, "%v AS %v", statement.Engine.Quote(table),
  685. statement.Engine.Quote(fmt.Sprintf("%v", t[1])))
  686. } else if l == 1 {
  687. fmt.Fprintf(&buf, statement.Engine.Quote(table))
  688. }
  689. default:
  690. fmt.Fprintf(&buf, statement.Engine.Quote(fmt.Sprintf("%v", tablename)))
  691. }
  692. fmt.Fprintf(&buf, " ON %v", condition)
  693. statement.JoinStr = buf.String()
  694. statement.joinArgs = append(statement.joinArgs, args...)
  695. return statement
  696. }
  697. // GroupBy generate "Group By keys" statement
  698. func (statement *Statement) GroupBy(keys string) *Statement {
  699. statement.GroupByStr = keys
  700. return statement
  701. }
  702. // Having generate "Having conditions" statement
  703. func (statement *Statement) Having(conditions string) *Statement {
  704. statement.HavingStr = fmt.Sprintf("HAVING %v", conditions)
  705. return statement
  706. }
  707. // Unscoped always disable struct tag "deleted"
  708. func (statement *Statement) Unscoped() *Statement {
  709. statement.unscoped = true
  710. return statement
  711. }
  712. func (statement *Statement) genColumnStr() string {
  713. var buf bytes.Buffer
  714. if statement.RefTable == nil {
  715. return ""
  716. }
  717. columns := statement.RefTable.Columns()
  718. for _, col := range columns {
  719. if statement.OmitStr != "" {
  720. if _, ok := getFlagForColumn(statement.columnMap, col); ok {
  721. continue
  722. }
  723. }
  724. if col.MapType == core.ONLYTODB {
  725. continue
  726. }
  727. if buf.Len() != 0 {
  728. buf.WriteString(", ")
  729. }
  730. if col.IsPrimaryKey && statement.Engine.Dialect().DBType() == "ql" {
  731. buf.WriteString("id() AS ")
  732. }
  733. if statement.JoinStr != "" {
  734. if statement.TableAlias != "" {
  735. buf.WriteString(statement.TableAlias)
  736. } else {
  737. buf.WriteString(statement.TableName())
  738. }
  739. buf.WriteString(".")
  740. }
  741. statement.Engine.QuoteTo(&buf, col.Name)
  742. }
  743. return buf.String()
  744. }
  745. func (statement *Statement) genCreateTableSQL() string {
  746. return statement.Engine.dialect.CreateTableSql(statement.RefTable, statement.TableName(),
  747. statement.StoreEngine, statement.Charset)
  748. }
  749. func (statement *Statement) genIndexSQL() []string {
  750. var sqls []string
  751. tbName := statement.TableName()
  752. quote := statement.Engine.Quote
  753. for idxName, index := range statement.RefTable.Indexes {
  754. if index.Type == core.IndexType {
  755. sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(tbName, idxName)),
  756. quote(tbName), quote(strings.Join(index.Cols, quote(","))))
  757. sqls = append(sqls, sql)
  758. }
  759. }
  760. return sqls
  761. }
  762. func uniqueName(tableName, uqeName string) string {
  763. return fmt.Sprintf("UQE_%v_%v", tableName, uqeName)
  764. }
  765. func (statement *Statement) genUniqueSQL() []string {
  766. var sqls []string
  767. tbName := statement.TableName()
  768. for _, index := range statement.RefTable.Indexes {
  769. if index.Type == core.UniqueType {
  770. sql := statement.Engine.dialect.CreateIndexSql(tbName, index)
  771. sqls = append(sqls, sql)
  772. }
  773. }
  774. return sqls
  775. }
  776. func (statement *Statement) genDelIndexSQL() []string {
  777. var sqls []string
  778. tbName := statement.TableName()
  779. for idxName, index := range statement.RefTable.Indexes {
  780. var rIdxName string
  781. if index.Type == core.UniqueType {
  782. rIdxName = uniqueName(tbName, idxName)
  783. } else if index.Type == core.IndexType {
  784. rIdxName = indexName(tbName, idxName)
  785. }
  786. sql := fmt.Sprintf("DROP INDEX %v", statement.Engine.Quote(rIdxName))
  787. if statement.Engine.dialect.IndexOnTable() {
  788. sql += fmt.Sprintf(" ON %v", statement.Engine.Quote(statement.TableName()))
  789. }
  790. sqls = append(sqls, sql)
  791. }
  792. return sqls
  793. }
  794. func (statement *Statement) genAddColumnStr(col *core.Column) (string, []interface{}) {
  795. quote := statement.Engine.Quote
  796. sql := fmt.Sprintf("ALTER TABLE %v ADD %v;", quote(statement.TableName()),
  797. col.String(statement.Engine.dialect))
  798. return sql, []interface{}{}
  799. }
  800. func (statement *Statement) buildConds(table *core.Table, bean interface{}, includeVersion bool, includeUpdated bool, includeNil bool, includeAutoIncr bool, addedTableName bool) (builder.Cond, error) {
  801. return statement.Engine.buildConds(table, bean, includeVersion, includeUpdated, includeNil, includeAutoIncr, statement.allUseBool, statement.useAllCols,
  802. statement.unscoped, statement.mustColumnMap, statement.TableName(), statement.TableAlias, addedTableName)
  803. }
  804. func (statement *Statement) mergeConds(bean interface{}) error {
  805. if !statement.noAutoCondition {
  806. var addedTableName = (len(statement.JoinStr) > 0)
  807. autoCond, err := statement.buildConds(statement.RefTable, bean, true, true, false, true, addedTableName)
  808. if err != nil {
  809. return err
  810. }
  811. statement.cond = statement.cond.And(autoCond)
  812. }
  813. if err := statement.processIDParam(); err != nil {
  814. return err
  815. }
  816. return nil
  817. }
  818. func (statement *Statement) genConds(bean interface{}) (string, []interface{}, error) {
  819. if err := statement.mergeConds(bean); err != nil {
  820. return "", nil, err
  821. }
  822. return builder.ToSQL(statement.cond)
  823. }
  824. func (statement *Statement) genGetSQL(bean interface{}) (string, []interface{}, error) {
  825. v := rValue(bean)
  826. isStruct := v.Kind() == reflect.Struct
  827. if isStruct {
  828. statement.setRefValue(v)
  829. }
  830. var columnStr = statement.ColumnStr
  831. if len(statement.selectStr) > 0 {
  832. columnStr = statement.selectStr
  833. } else {
  834. // TODO: always generate column names, not use * even if join
  835. if len(statement.JoinStr) == 0 {
  836. if len(columnStr) == 0 {
  837. if len(statement.GroupByStr) > 0 {
  838. columnStr = statement.Engine.Quote(strings.Replace(statement.GroupByStr, ",", statement.Engine.Quote(","), -1))
  839. } else {
  840. columnStr = statement.genColumnStr()
  841. }
  842. }
  843. } else {
  844. if len(columnStr) == 0 {
  845. if len(statement.GroupByStr) > 0 {
  846. columnStr = statement.Engine.Quote(strings.Replace(statement.GroupByStr, ",", statement.Engine.Quote(","), -1))
  847. }
  848. }
  849. }
  850. }
  851. if len(columnStr) == 0 {
  852. columnStr = "*"
  853. }
  854. if isStruct {
  855. if err := statement.mergeConds(bean); err != nil {
  856. return "", nil, err
  857. }
  858. }
  859. condSQL, condArgs, err := builder.ToSQL(statement.cond)
  860. if err != nil {
  861. return "", nil, err
  862. }
  863. sqlStr, err := statement.genSelectSQL(columnStr, condSQL)
  864. if err != nil {
  865. return "", nil, err
  866. }
  867. return sqlStr, append(statement.joinArgs, condArgs...), nil
  868. }
  869. func (statement *Statement) genCountSQL(bean interface{}) (string, []interface{}, error) {
  870. statement.setRefValue(rValue(bean))
  871. condSQL, condArgs, err := statement.genConds(bean)
  872. if err != nil {
  873. return "", nil, err
  874. }
  875. var selectSQL = statement.selectStr
  876. if len(selectSQL) <= 0 {
  877. if statement.IsDistinct {
  878. selectSQL = fmt.Sprintf("count(DISTINCT %s)", statement.ColumnStr)
  879. } else {
  880. selectSQL = "count(*)"
  881. }
  882. }
  883. sqlStr, err := statement.genSelectSQL(selectSQL, condSQL)
  884. if err != nil {
  885. return "", nil, err
  886. }
  887. return sqlStr, append(statement.joinArgs, condArgs...), nil
  888. }
  889. func (statement *Statement) genSumSQL(bean interface{}, columns ...string) (string, []interface{}, error) {
  890. statement.setRefValue(rValue(bean))
  891. var sumStrs = make([]string, 0, len(columns))
  892. for _, colName := range columns {
  893. if !strings.Contains(colName, " ") && !strings.Contains(colName, "(") {
  894. colName = statement.Engine.Quote(colName)
  895. }
  896. sumStrs = append(sumStrs, fmt.Sprintf("COALESCE(sum(%s),0)", colName))
  897. }
  898. sumSelect := strings.Join(sumStrs, ", ")
  899. condSQL, condArgs, err := statement.genConds(bean)
  900. if err != nil {
  901. return "", nil, err
  902. }
  903. sqlStr, err := statement.genSelectSQL(sumSelect, condSQL)
  904. if err != nil {
  905. return "", nil, err
  906. }
  907. return sqlStr, append(statement.joinArgs, condArgs...), nil
  908. }
  909. func (statement *Statement) genSelectSQL(columnStr, condSQL string) (a string, err error) {
  910. var distinct string
  911. if statement.IsDistinct && !strings.HasPrefix(columnStr, "count") {
  912. distinct = "DISTINCT "
  913. }
  914. var dialect = statement.Engine.Dialect()
  915. var quote = statement.Engine.Quote
  916. var top string
  917. var mssqlCondi string
  918. if err := statement.processIDParam(); err != nil {
  919. return "", err
  920. }
  921. var buf bytes.Buffer
  922. if len(condSQL) > 0 {
  923. fmt.Fprintf(&buf, " WHERE %v", condSQL)
  924. }
  925. var whereStr = buf.String()
  926. var fromStr = " FROM "
  927. if dialect.DBType() == core.MSSQL && strings.Contains(statement.TableName(), "..") {
  928. fromStr += statement.TableName()
  929. } else {
  930. fromStr += quote(statement.TableName())
  931. }
  932. if statement.TableAlias != "" {
  933. if dialect.DBType() == core.ORACLE {
  934. fromStr += " " + quote(statement.TableAlias)
  935. } else {
  936. fromStr += " AS " + quote(statement.TableAlias)
  937. }
  938. }
  939. if statement.JoinStr != "" {
  940. fromStr = fmt.Sprintf("%v %v", fromStr, statement.JoinStr)
  941. }
  942. if dialect.DBType() == core.MSSQL {
  943. if statement.LimitN > 0 {
  944. top = fmt.Sprintf(" TOP %d ", statement.LimitN)
  945. }
  946. if statement.Start > 0 {
  947. var column string
  948. if len(statement.RefTable.PKColumns()) == 0 {
  949. for _, index := range statement.RefTable.Indexes {
  950. if len(index.Cols) == 1 {
  951. column = index.Cols[0]
  952. break
  953. }
  954. }
  955. if len(column) == 0 {
  956. column = statement.RefTable.ColumnsSeq()[0]
  957. }
  958. } else {
  959. column = statement.RefTable.PKColumns()[0].Name
  960. }
  961. if statement.needTableName() {
  962. if len(statement.TableAlias) > 0 {
  963. column = statement.TableAlias + "." + column
  964. } else {
  965. column = statement.TableName() + "." + column
  966. }
  967. }
  968. var orderStr string
  969. if len(statement.OrderStr) > 0 {
  970. orderStr = " ORDER BY " + statement.OrderStr
  971. }
  972. var groupStr string
  973. if len(statement.GroupByStr) > 0 {
  974. groupStr = " GROUP BY " + statement.GroupByStr
  975. }
  976. mssqlCondi = fmt.Sprintf("(%s NOT IN (SELECT TOP %d %s%s%s%s%s))",
  977. column, statement.Start, column, fromStr, whereStr, orderStr, groupStr)
  978. }
  979. }
  980. // !nashtsai! REVIEW Sprintf is considered slowest mean of string concatnation, better to work with builder pattern
  981. a = fmt.Sprintf("SELECT %v%v%v%v%v", distinct, top, columnStr, fromStr, whereStr)
  982. if len(mssqlCondi) > 0 {
  983. if len(whereStr) > 0 {
  984. a += " AND " + mssqlCondi
  985. } else {
  986. a += " WHERE " + mssqlCondi
  987. }
  988. }
  989. if statement.GroupByStr != "" {
  990. a = fmt.Sprintf("%v GROUP BY %v", a, statement.GroupByStr)
  991. }
  992. if statement.HavingStr != "" {
  993. a = fmt.Sprintf("%v %v", a, statement.HavingStr)
  994. }
  995. if statement.OrderStr != "" {
  996. a = fmt.Sprintf("%v ORDER BY %v", a, statement.OrderStr)
  997. }
  998. if dialect.DBType() != core.MSSQL && dialect.DBType() != core.ORACLE {
  999. if statement.Start > 0 {
  1000. a = fmt.Sprintf("%v LIMIT %v OFFSET %v", a, statement.LimitN, statement.Start)
  1001. } else if statement.LimitN > 0 {
  1002. a = fmt.Sprintf("%v LIMIT %v", a, statement.LimitN)
  1003. }
  1004. } else if dialect.DBType() == core.ORACLE {
  1005. if statement.Start != 0 || statement.LimitN != 0 {
  1006. a = fmt.Sprintf("SELECT %v FROM (SELECT %v,ROWNUM RN FROM (%v) at WHERE ROWNUM <= %d) aat WHERE RN > %d", columnStr, columnStr, a, statement.Start+statement.LimitN, statement.Start)
  1007. }
  1008. }
  1009. if statement.IsForUpdate {
  1010. a = dialect.ForUpdateSql(a)
  1011. }
  1012. return
  1013. }
  1014. func (statement *Statement) processIDParam() error {
  1015. if statement.idParam == nil {
  1016. return nil
  1017. }
  1018. if len(statement.RefTable.PrimaryKeys) != len(*statement.idParam) {
  1019. return fmt.Errorf("ID condition is error, expect %d primarykeys, there are %d",
  1020. len(statement.RefTable.PrimaryKeys),
  1021. len(*statement.idParam),
  1022. )
  1023. }
  1024. for i, col := range statement.RefTable.PKColumns() {
  1025. var colName = statement.colName(col, statement.TableName())
  1026. statement.cond = statement.cond.And(builder.Eq{colName: (*(statement.idParam))[i]})
  1027. }
  1028. return nil
  1029. }
  1030. func (statement *Statement) joinColumns(cols []*core.Column, includeTableName bool) string {
  1031. var colnames = make([]string, len(cols))
  1032. for i, col := range cols {
  1033. if includeTableName {
  1034. colnames[i] = statement.Engine.Quote(statement.TableName()) +
  1035. "." + statement.Engine.Quote(col.Name)
  1036. } else {
  1037. colnames[i] = statement.Engine.Quote(col.Name)
  1038. }
  1039. }
  1040. return strings.Join(colnames, ", ")
  1041. }
  1042. func (statement *Statement) convertIDSQL(sqlStr string) string {
  1043. if statement.RefTable != nil {
  1044. cols := statement.RefTable.PKColumns()
  1045. if len(cols) == 0 {
  1046. return ""
  1047. }
  1048. colstrs := statement.joinColumns(cols, false)
  1049. sqls := splitNNoCase(sqlStr, " from ", 2)
  1050. if len(sqls) != 2 {
  1051. return ""
  1052. }
  1053. var top string
  1054. if statement.LimitN > 0 && statement.Engine.dialect.DBType() == core.MSSQL {
  1055. top = fmt.Sprintf("TOP %d ", statement.LimitN)
  1056. }
  1057. return fmt.Sprintf("SELECT %s%s FROM %v", top, colstrs, sqls[1])
  1058. }
  1059. return ""
  1060. }
  1061. func (statement *Statement) convertUpdateSQL(sqlStr string) (string, string) {
  1062. if statement.RefTable == nil || len(statement.RefTable.PrimaryKeys) != 1 {
  1063. return "", ""
  1064. }
  1065. colstrs := statement.joinColumns(statement.RefTable.PKColumns(), true)
  1066. sqls := splitNNoCase(sqlStr, "where", 2)
  1067. if len(sqls) != 2 {
  1068. if len(sqls) == 1 {
  1069. return sqls[0], fmt.Sprintf("SELECT %v FROM %v",
  1070. colstrs, statement.Engine.Quote(statement.TableName()))
  1071. }
  1072. return "", ""
  1073. }
  1074. var whereStr = sqls[1]
  1075. //TODO: for postgres only, if any other database?
  1076. var paraStr string
  1077. if statement.Engine.dialect.DBType() == core.POSTGRES {
  1078. paraStr = "$"
  1079. } else if statement.Engine.dialect.DBType() == core.MSSQL {
  1080. paraStr = ":"
  1081. }
  1082. if paraStr != "" {
  1083. if strings.Contains(sqls[1], paraStr) {
  1084. dollers := strings.Split(sqls[1], paraStr)
  1085. whereStr = dollers[0]
  1086. for i, c := range dollers[1:] {
  1087. ccs := strings.SplitN(c, " ", 2)
  1088. whereStr += fmt.Sprintf(paraStr+"%v %v", i+1, ccs[1])
  1089. }
  1090. }
  1091. }
  1092. return sqls[0], fmt.Sprintf("SELECT %v FROM %v WHERE %v",
  1093. colstrs, statement.Engine.Quote(statement.TableName()),
  1094. whereStr)
  1095. }