statement.go 35 KB

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