statement.go 38 KB

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