statement.go 35 KB

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