statement.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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. tableName string
  54. RawSQL string
  55. RawParams []interface{}
  56. UseCascade bool
  57. UseAutoJoin bool
  58. StoreEngine string
  59. Charset string
  60. BeanArgs []interface{}
  61. UseCache bool
  62. UseAutoTime bool
  63. noAutoCondition bool
  64. IsDistinct bool
  65. IsForUpdate bool
  66. TableAlias string
  67. allUseBool bool
  68. checkVersion bool
  69. unscoped bool
  70. mustColumnMap map[string]bool
  71. nullableMap map[string]bool
  72. inColumns map[string]*inParam
  73. incrColumns map[string]incrParam
  74. decrColumns map[string]decrParam
  75. exprColumns map[string]exprParam
  76. }
  77. // Init reset all the statment's fields
  78. func (statement *Statement) Init() {
  79. statement.RefTable = nil
  80. statement.Start = 0
  81. statement.LimitN = 0
  82. statement.WhereStr = ""
  83. statement.Params = make([]interface{}, 0)
  84. statement.OrderStr = ""
  85. statement.UseCascade = true
  86. statement.JoinStr = ""
  87. statement.joinArgs = make([]interface{}, 0)
  88. statement.GroupByStr = ""
  89. statement.HavingStr = ""
  90. statement.ColumnStr = ""
  91. statement.OmitStr = ""
  92. statement.columnMap = make(map[string]bool)
  93. statement.ConditionStr = ""
  94. statement.AltTableName = ""
  95. statement.tableName = ""
  96. statement.IdParam = nil
  97. statement.RawSQL = ""
  98. statement.RawParams = make([]interface{}, 0)
  99. statement.BeanArgs = make([]interface{}, 0)
  100. statement.UseCache = true
  101. statement.UseAutoTime = true
  102. statement.noAutoCondition = false
  103. statement.IsDistinct = false
  104. statement.IsForUpdate = false
  105. statement.TableAlias = ""
  106. statement.selectStr = ""
  107. statement.allUseBool = false
  108. statement.useAllCols = false
  109. statement.mustColumnMap = make(map[string]bool)
  110. statement.nullableMap = make(map[string]bool)
  111. statement.checkVersion = true
  112. statement.unscoped = false
  113. statement.inColumns = make(map[string]*inParam)
  114. statement.incrColumns = make(map[string]incrParam)
  115. statement.decrColumns = make(map[string]decrParam)
  116. statement.exprColumns = make(map[string]exprParam)
  117. }
  118. // NoAutoCondition if you do not want convert bean's field as query condition, then use this function
  119. func (statement *Statement) NoAutoCondition(no ...bool) *Statement {
  120. statement.noAutoCondition = true
  121. if len(no) > 0 {
  122. statement.noAutoCondition = no[0]
  123. }
  124. return statement
  125. }
  126. // Sql add the raw sql statement
  127. func (statement *Statement) Sql(querystring string, args ...interface{}) *Statement {
  128. statement.RawSQL = querystring
  129. statement.RawParams = args
  130. return statement
  131. }
  132. // Alias set the table alias
  133. func (statement *Statement) Alias(alias string) *Statement {
  134. statement.TableAlias = alias
  135. return statement
  136. }
  137. // Where add Where statment
  138. func (statement *Statement) Where(querystring string, args ...interface{}) *Statement {
  139. // The second where will be triggered as And
  140. if len(statement.WhereStr) > 0 {
  141. return statement.And(querystring, args...)
  142. }
  143. if !strings.Contains(querystring, statement.Engine.dialect.EqStr()) {
  144. querystring = strings.Replace(querystring, "=", statement.Engine.dialect.EqStr(), -1)
  145. }
  146. statement.WhereStr = querystring
  147. statement.Params = args
  148. return statement
  149. }
  150. // And add Where & and statment
  151. func (statement *Statement) And(querystring string, args ...interface{}) *Statement {
  152. if len(statement.WhereStr) > 0 {
  153. var buf bytes.Buffer
  154. fmt.Fprintf(&buf, "(%v) %s (%v)", statement.WhereStr,
  155. statement.Engine.dialect.AndStr(), querystring)
  156. statement.WhereStr = buf.String()
  157. } else {
  158. statement.WhereStr = querystring
  159. }
  160. statement.Params = append(statement.Params, args...)
  161. return statement
  162. }
  163. // Or add Where & Or statment
  164. func (statement *Statement) Or(querystring string, args ...interface{}) *Statement {
  165. if len(statement.WhereStr) > 0 {
  166. var buf bytes.Buffer
  167. fmt.Fprintf(&buf, "(%v) %s (%v)", statement.WhereStr,
  168. statement.Engine.dialect.OrStr(), querystring)
  169. statement.WhereStr = buf.String()
  170. } else {
  171. statement.WhereStr = querystring
  172. }
  173. statement.Params = append(statement.Params, args...)
  174. return statement
  175. }
  176. func (statement *Statement) setRefValue(v reflect.Value) {
  177. statement.RefTable = statement.Engine.autoMapType(v)
  178. statement.tableName = statement.Engine.tbName(v)
  179. }
  180. // Table tempororily set table name, the parameter could be a string or a pointer of struct
  181. func (statement *Statement) Table(tableNameOrBean interface{}) *Statement {
  182. v := rValue(tableNameOrBean)
  183. t := v.Type()
  184. if t.Kind() == reflect.String {
  185. statement.AltTableName = tableNameOrBean.(string)
  186. } else if t.Kind() == reflect.Struct {
  187. statement.RefTable = statement.Engine.autoMapType(v)
  188. statement.AltTableName = statement.Engine.tbName(v)
  189. }
  190. return statement
  191. }
  192. // Auto generating update columnes and values according a struct
  193. func buildUpdates(engine *Engine, table *core.Table, bean interface{},
  194. includeVersion bool, includeUpdated bool, includeNil bool,
  195. includeAutoIncr bool, allUseBool bool, useAllCols bool,
  196. mustColumnMap map[string]bool, nullableMap map[string]bool,
  197. columnMap map[string]bool, update, unscoped bool) ([]string, []interface{}) {
  198. var colNames = make([]string, 0)
  199. var args = make([]interface{}, 0)
  200. for _, col := range table.Columns() {
  201. if !includeVersion && col.IsVersion {
  202. continue
  203. }
  204. if col.IsCreated {
  205. continue
  206. }
  207. if !includeUpdated && col.IsUpdated {
  208. continue
  209. }
  210. if !includeAutoIncr && col.IsAutoIncrement {
  211. continue
  212. }
  213. if col.IsDeleted && !unscoped {
  214. continue
  215. }
  216. if use, ok := columnMap[col.Name]; ok && !use {
  217. continue
  218. }
  219. fieldValuePtr, err := col.ValueOf(bean)
  220. if err != nil {
  221. engine.logger.Error(err)
  222. continue
  223. }
  224. fieldValue := *fieldValuePtr
  225. fieldType := reflect.TypeOf(fieldValue.Interface())
  226. requiredField := useAllCols
  227. includeNil := useAllCols
  228. lColName := strings.ToLower(col.Name)
  229. if b, ok := mustColumnMap[lColName]; ok {
  230. if b {
  231. requiredField = true
  232. } else {
  233. continue
  234. }
  235. }
  236. // !evalphobia! set fieldValue as nil when column is nullable and zero-value
  237. if b, ok := nullableMap[lColName]; ok {
  238. if b && col.Nullable && isZero(fieldValue.Interface()) {
  239. var nilValue *int
  240. fieldValue = reflect.ValueOf(nilValue)
  241. fieldType = reflect.TypeOf(fieldValue.Interface())
  242. includeNil = true
  243. }
  244. }
  245. var val interface{}
  246. if fieldValue.CanAddr() {
  247. if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  248. data, err := structConvert.ToDB()
  249. if err != nil {
  250. engine.logger.Error(err)
  251. } else {
  252. val = data
  253. }
  254. goto APPEND
  255. }
  256. }
  257. if structConvert, ok := fieldValue.Interface().(core.Conversion); ok {
  258. data, err := structConvert.ToDB()
  259. if err != nil {
  260. engine.logger.Error(err)
  261. } else {
  262. val = data
  263. }
  264. goto APPEND
  265. }
  266. if fieldType.Kind() == reflect.Ptr {
  267. if fieldValue.IsNil() {
  268. if includeNil {
  269. args = append(args, nil)
  270. colNames = append(colNames, fmt.Sprintf("%v=?", engine.Quote(col.Name)))
  271. }
  272. continue
  273. } else if !fieldValue.IsValid() {
  274. continue
  275. } else {
  276. // dereference ptr type to instance type
  277. fieldValue = fieldValue.Elem()
  278. fieldType = reflect.TypeOf(fieldValue.Interface())
  279. requiredField = true
  280. }
  281. }
  282. switch fieldType.Kind() {
  283. case reflect.Bool:
  284. if allUseBool || requiredField {
  285. val = fieldValue.Interface()
  286. } else {
  287. // if a bool in a struct, it will not be as a condition because it default is false,
  288. // please use Where() instead
  289. continue
  290. }
  291. case reflect.String:
  292. if !requiredField && fieldValue.String() == "" {
  293. continue
  294. }
  295. // for MyString, should convert to string or panic
  296. if fieldType.String() != reflect.String.String() {
  297. val = fieldValue.String()
  298. } else {
  299. val = fieldValue.Interface()
  300. }
  301. case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64:
  302. if !requiredField && fieldValue.Int() == 0 {
  303. continue
  304. }
  305. val = fieldValue.Interface()
  306. case reflect.Float32, reflect.Float64:
  307. if !requiredField && fieldValue.Float() == 0.0 {
  308. continue
  309. }
  310. val = fieldValue.Interface()
  311. case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
  312. if !requiredField && fieldValue.Uint() == 0 {
  313. continue
  314. }
  315. t := int64(fieldValue.Uint())
  316. val = reflect.ValueOf(&t).Interface()
  317. case reflect.Struct:
  318. if fieldType.ConvertibleTo(core.TimeType) {
  319. t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
  320. if !requiredField && (t.IsZero() || !fieldValue.IsValid()) {
  321. continue
  322. }
  323. val = engine.FormatTime(col.SQLType.Name, t)
  324. } else if nulType, ok := fieldValue.Interface().(driver.Valuer); ok {
  325. val, _ = nulType.Value()
  326. } else {
  327. if !col.SQLType.IsJson() {
  328. engine.autoMapType(fieldValue)
  329. if table, ok := engine.Tables[fieldValue.Type()]; ok {
  330. if len(table.PrimaryKeys) == 1 {
  331. pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName)
  332. // fix non-int pk issues
  333. if pkField.IsValid() && (!requiredField && !isZero(pkField.Interface())) {
  334. val = pkField.Interface()
  335. } else {
  336. continue
  337. }
  338. } else {
  339. //TODO: how to handler?
  340. panic("not supported")
  341. }
  342. } else {
  343. val = fieldValue.Interface()
  344. }
  345. } else {
  346. // Blank struct could not be as update data
  347. if requiredField || !isStructZero(fieldValue) {
  348. bytes, err := json.Marshal(fieldValue.Interface())
  349. if err != nil {
  350. panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface()))
  351. }
  352. if col.SQLType.IsText() {
  353. val = string(bytes)
  354. } else if col.SQLType.IsBlob() {
  355. val = bytes
  356. }
  357. } else {
  358. continue
  359. }
  360. }
  361. }
  362. case reflect.Array, reflect.Slice, reflect.Map:
  363. if !requiredField {
  364. if fieldValue == reflect.Zero(fieldType) {
  365. continue
  366. }
  367. if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 {
  368. continue
  369. }
  370. }
  371. if col.SQLType.IsText() {
  372. bytes, err := json.Marshal(fieldValue.Interface())
  373. if err != nil {
  374. engine.logger.Error(err)
  375. continue
  376. }
  377. val = string(bytes)
  378. } else if col.SQLType.IsBlob() {
  379. var bytes []byte
  380. var err error
  381. if (fieldType.Kind() == reflect.Array || fieldType.Kind() == reflect.Slice) &&
  382. fieldType.Elem().Kind() == reflect.Uint8 {
  383. if fieldValue.Len() > 0 {
  384. val = fieldValue.Bytes()
  385. } else {
  386. continue
  387. }
  388. } else {
  389. bytes, err = json.Marshal(fieldValue.Interface())
  390. if err != nil {
  391. engine.logger.Error(err)
  392. continue
  393. }
  394. val = bytes
  395. }
  396. } else {
  397. continue
  398. }
  399. default:
  400. val = fieldValue.Interface()
  401. }
  402. APPEND:
  403. //fmt.Println("==", col.Name, "==", fmt.Sprintf("%v", val))
  404. args = append(args, val)
  405. if col.IsPrimaryKey && engine.dialect.DBType() == "ql" {
  406. continue
  407. }
  408. colNames = append(colNames, fmt.Sprintf("%v = ?", engine.Quote(col.Name)))
  409. }
  410. return colNames, args
  411. }
  412. func (statement *Statement) needTableName() bool {
  413. return len(statement.JoinStr) > 0
  414. }
  415. func (statement *Statement) colName(col *core.Column, tableName string) string {
  416. if statement.needTableName() {
  417. var nm = tableName
  418. if len(statement.TableAlias) > 0 {
  419. nm = statement.TableAlias
  420. }
  421. return statement.Engine.Quote(nm) + "." + statement.Engine.Quote(col.Name)
  422. }
  423. return statement.Engine.Quote(col.Name)
  424. }
  425. // Auto generating conditions according a struct
  426. func buildConditions(engine *Engine, table *core.Table, bean interface{},
  427. includeVersion bool, includeUpdated bool, includeNil bool,
  428. includeAutoIncr bool, allUseBool bool, useAllCols bool, unscoped bool,
  429. mustColumnMap map[string]bool, tableName, aliasName string, addedTableName bool) ([]string, []interface{}) {
  430. var colNames []string
  431. var args = make([]interface{}, 0)
  432. for _, col := range table.Columns() {
  433. if !includeVersion && col.IsVersion {
  434. continue
  435. }
  436. if !includeUpdated && col.IsUpdated {
  437. continue
  438. }
  439. if !includeAutoIncr && col.IsAutoIncrement {
  440. continue
  441. }
  442. if engine.dialect.DBType() == core.MSSQL && col.SQLType.Name == core.Text {
  443. continue
  444. }
  445. if col.SQLType.IsJson() {
  446. continue
  447. }
  448. var colName string
  449. if addedTableName {
  450. var nm = tableName
  451. if len(aliasName) > 0 {
  452. nm = aliasName
  453. }
  454. colName = engine.Quote(nm) + "." + engine.Quote(col.Name)
  455. } else {
  456. colName = engine.Quote(col.Name)
  457. }
  458. fieldValuePtr, err := col.ValueOf(bean)
  459. if err != nil {
  460. engine.logger.Error(err)
  461. continue
  462. }
  463. if col.IsDeleted && !unscoped { // tag "deleted" is enabled
  464. colNames = append(colNames, fmt.Sprintf("(%v IS NULL OR %v = '0001-01-01 00:00:00')",
  465. colName, colName))
  466. }
  467. fieldValue := *fieldValuePtr
  468. if fieldValue.Interface() == nil {
  469. continue
  470. }
  471. fieldType := reflect.TypeOf(fieldValue.Interface())
  472. requiredField := useAllCols
  473. if b, ok := mustColumnMap[strings.ToLower(col.Name)]; ok {
  474. if b {
  475. requiredField = true
  476. } else {
  477. continue
  478. }
  479. }
  480. if fieldType.Kind() == reflect.Ptr {
  481. if fieldValue.IsNil() {
  482. if includeNil {
  483. args = append(args, nil)
  484. colNames = append(colNames, fmt.Sprintf("%v %s ?", colName, engine.dialect.EqStr()))
  485. }
  486. continue
  487. } else if !fieldValue.IsValid() {
  488. continue
  489. } else {
  490. // dereference ptr type to instance type
  491. fieldValue = fieldValue.Elem()
  492. fieldType = reflect.TypeOf(fieldValue.Interface())
  493. requiredField = true
  494. }
  495. }
  496. var val interface{}
  497. switch fieldType.Kind() {
  498. case reflect.Bool:
  499. if allUseBool || requiredField {
  500. val = fieldValue.Interface()
  501. } else {
  502. // if a bool in a struct, it will not be as a condition because it default is false,
  503. // please use Where() instead
  504. continue
  505. }
  506. case reflect.String:
  507. if !requiredField && fieldValue.String() == "" {
  508. continue
  509. }
  510. // for MyString, should convert to string or panic
  511. if fieldType.String() != reflect.String.String() {
  512. val = fieldValue.String()
  513. } else {
  514. val = fieldValue.Interface()
  515. }
  516. case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64:
  517. if !requiredField && fieldValue.Int() == 0 {
  518. continue
  519. }
  520. val = fieldValue.Interface()
  521. case reflect.Float32, reflect.Float64:
  522. if !requiredField && fieldValue.Float() == 0.0 {
  523. continue
  524. }
  525. val = fieldValue.Interface()
  526. case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
  527. if !requiredField && fieldValue.Uint() == 0 {
  528. continue
  529. }
  530. t := int64(fieldValue.Uint())
  531. val = reflect.ValueOf(&t).Interface()
  532. case reflect.Struct:
  533. if fieldType.ConvertibleTo(core.TimeType) {
  534. t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
  535. if !requiredField && (t.IsZero() || !fieldValue.IsValid()) {
  536. continue
  537. }
  538. val = engine.FormatTime(col.SQLType.Name, t)
  539. } else if _, ok := reflect.New(fieldType).Interface().(core.Conversion); ok {
  540. continue
  541. } else if valNul, ok := fieldValue.Interface().(driver.Valuer); ok {
  542. val, _ = valNul.Value()
  543. if val == nil {
  544. continue
  545. }
  546. } else {
  547. if col.SQLType.IsJson() {
  548. if col.SQLType.IsText() {
  549. bytes, err := json.Marshal(fieldValue.Interface())
  550. if err != nil {
  551. engine.logger.Error(err)
  552. continue
  553. }
  554. val = string(bytes)
  555. } else if col.SQLType.IsBlob() {
  556. var bytes []byte
  557. var err error
  558. bytes, err = json.Marshal(fieldValue.Interface())
  559. if err != nil {
  560. engine.logger.Error(err)
  561. continue
  562. }
  563. val = bytes
  564. }
  565. } else {
  566. engine.autoMapType(fieldValue)
  567. if table, ok := engine.Tables[fieldValue.Type()]; ok {
  568. if len(table.PrimaryKeys) == 1 {
  569. pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName)
  570. // fix non-int pk issues
  571. //if pkField.Int() != 0 {
  572. if pkField.IsValid() && !isZero(pkField.Interface()) {
  573. val = pkField.Interface()
  574. } else {
  575. continue
  576. }
  577. } else {
  578. //TODO: how to handler?
  579. panic(fmt.Sprintln("not supported", fieldValue.Interface(), "as", table.PrimaryKeys))
  580. }
  581. } else {
  582. val = fieldValue.Interface()
  583. }
  584. }
  585. }
  586. case reflect.Array, reflect.Slice, reflect.Map:
  587. if fieldValue == reflect.Zero(fieldType) {
  588. continue
  589. }
  590. if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 {
  591. continue
  592. }
  593. if col.SQLType.IsText() {
  594. bytes, err := json.Marshal(fieldValue.Interface())
  595. if err != nil {
  596. engine.logger.Error(err)
  597. continue
  598. }
  599. val = string(bytes)
  600. } else if col.SQLType.IsBlob() {
  601. var bytes []byte
  602. var err error
  603. if (fieldType.Kind() == reflect.Array || fieldType.Kind() == reflect.Slice) &&
  604. fieldType.Elem().Kind() == reflect.Uint8 {
  605. if fieldValue.Len() > 0 {
  606. val = fieldValue.Bytes()
  607. } else {
  608. continue
  609. }
  610. } else {
  611. bytes, err = json.Marshal(fieldValue.Interface())
  612. if err != nil {
  613. engine.logger.Error(err)
  614. continue
  615. }
  616. val = bytes
  617. }
  618. } else {
  619. continue
  620. }
  621. default:
  622. val = fieldValue.Interface()
  623. }
  624. args = append(args, val)
  625. var condi string
  626. if col.IsPrimaryKey && engine.dialect.DBType() == "ql" {
  627. condi = "id() == ?"
  628. } else {
  629. condi = fmt.Sprintf("%v %s ?", colName, engine.dialect.EqStr())
  630. }
  631. colNames = append(colNames, condi)
  632. }
  633. return colNames, args
  634. }
  635. // TableName return current tableName
  636. func (statement *Statement) TableName() string {
  637. if statement.AltTableName != "" {
  638. return statement.AltTableName
  639. }
  640. return statement.tableName
  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. table = statement.Engine.tbName(v)
  919. }
  920. }
  921. if l > 1 {
  922. fmt.Fprintf(&buf, "%v AS %v", statement.Engine.Quote(table),
  923. statement.Engine.Quote(fmt.Sprintf("%v", t[1])))
  924. } else if l == 1 {
  925. fmt.Fprintf(&buf, statement.Engine.Quote(table))
  926. }
  927. default:
  928. fmt.Fprintf(&buf, statement.Engine.Quote(fmt.Sprintf("%v", tablename)))
  929. }
  930. fmt.Fprintf(&buf, " ON %v", condition)
  931. statement.JoinStr = buf.String()
  932. statement.joinArgs = append(statement.joinArgs, args...)
  933. return statement
  934. }
  935. // GroupBy generate "Group By keys" statement
  936. func (statement *Statement) GroupBy(keys string) *Statement {
  937. statement.GroupByStr = keys
  938. return statement
  939. }
  940. // Having generate "Having conditions" statement
  941. func (statement *Statement) Having(conditions string) *Statement {
  942. statement.HavingStr = fmt.Sprintf("HAVING %v", conditions)
  943. return statement
  944. }
  945. // Unscoped always disable struct tag "deleted"
  946. func (statement *Statement) Unscoped() *Statement {
  947. statement.unscoped = true
  948. return statement
  949. }
  950. func (statement *Statement) genColumnStr() string {
  951. table := statement.RefTable
  952. var colNames []string
  953. for _, col := range table.Columns() {
  954. if statement.OmitStr != "" {
  955. if _, ok := statement.columnMap[strings.ToLower(col.Name)]; ok {
  956. continue
  957. }
  958. }
  959. if col.MapType == core.ONLYTODB {
  960. continue
  961. }
  962. if statement.JoinStr != "" {
  963. var name string
  964. if statement.TableAlias != "" {
  965. name = statement.Engine.Quote(statement.TableAlias)
  966. } else {
  967. name = statement.Engine.Quote(statement.TableName())
  968. }
  969. name += "." + statement.Engine.Quote(col.Name)
  970. if col.IsPrimaryKey && statement.Engine.Dialect().DBType() == "ql" {
  971. colNames = append(colNames, "id() AS "+name)
  972. } else {
  973. colNames = append(colNames, name)
  974. }
  975. } else {
  976. name := statement.Engine.Quote(col.Name)
  977. if col.IsPrimaryKey && statement.Engine.Dialect().DBType() == "ql" {
  978. colNames = append(colNames, "id() AS "+name)
  979. } else {
  980. colNames = append(colNames, name)
  981. }
  982. }
  983. }
  984. return strings.Join(colNames, ", ")
  985. }
  986. func (statement *Statement) genCreateTableSQL() string {
  987. return statement.Engine.dialect.CreateTableSql(statement.RefTable, statement.TableName(),
  988. statement.StoreEngine, statement.Charset)
  989. }
  990. func (s *Statement) genIndexSQL() []string {
  991. var sqls []string
  992. tbName := s.TableName()
  993. quote := s.Engine.Quote
  994. for idxName, index := range s.RefTable.Indexes {
  995. if index.Type == core.IndexType {
  996. sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(tbName, idxName)),
  997. quote(tbName), quote(strings.Join(index.Cols, quote(","))))
  998. sqls = append(sqls, sql)
  999. }
  1000. }
  1001. return sqls
  1002. }
  1003. func uniqueName(tableName, uqeName string) string {
  1004. return fmt.Sprintf("UQE_%v_%v", tableName, uqeName)
  1005. }
  1006. func (s *Statement) genUniqueSQL() []string {
  1007. var sqls []string
  1008. tbName := s.TableName()
  1009. for _, index := range s.RefTable.Indexes {
  1010. if index.Type == core.UniqueType {
  1011. sql := s.Engine.dialect.CreateIndexSql(tbName, index)
  1012. sqls = append(sqls, sql)
  1013. }
  1014. }
  1015. return sqls
  1016. }
  1017. func (s *Statement) genDelIndexSQL() []string {
  1018. var sqls []string
  1019. tbName := s.TableName()
  1020. for idxName, index := range s.RefTable.Indexes {
  1021. var rIdxName string
  1022. if index.Type == core.UniqueType {
  1023. rIdxName = uniqueName(tbName, idxName)
  1024. } else if index.Type == core.IndexType {
  1025. rIdxName = indexName(tbName, idxName)
  1026. }
  1027. sql := fmt.Sprintf("DROP INDEX %v", s.Engine.Quote(rIdxName))
  1028. if s.Engine.dialect.IndexOnTable() {
  1029. sql += fmt.Sprintf(" ON %v", s.Engine.Quote(s.TableName()))
  1030. }
  1031. sqls = append(sqls, sql)
  1032. }
  1033. return sqls
  1034. }
  1035. func (statement *Statement) genGetSql(bean interface{}) (string, []interface{}) {
  1036. statement.setRefValue(rValue(bean))
  1037. var table = statement.RefTable
  1038. var addedTableName = (len(statement.JoinStr) > 0)
  1039. if !statement.noAutoCondition {
  1040. colNames, args := statement.buildConditions(table, bean, true, true, false, true, addedTableName)
  1041. statement.ConditionStr = strings.Join(colNames, " "+statement.Engine.dialect.AndStr()+" ")
  1042. statement.BeanArgs = args
  1043. }
  1044. var columnStr = statement.ColumnStr
  1045. if len(statement.selectStr) > 0 {
  1046. columnStr = statement.selectStr
  1047. } else {
  1048. // TODO: always generate column names, not use * even if join
  1049. if len(statement.JoinStr) == 0 {
  1050. if len(columnStr) == 0 {
  1051. if len(statement.GroupByStr) > 0 {
  1052. columnStr = statement.Engine.Quote(strings.Replace(statement.GroupByStr, ",", statement.Engine.Quote(","), -1))
  1053. } else {
  1054. columnStr = statement.genColumnStr()
  1055. }
  1056. }
  1057. } else {
  1058. if len(columnStr) == 0 {
  1059. if len(statement.GroupByStr) > 0 {
  1060. columnStr = statement.Engine.Quote(strings.Replace(statement.GroupByStr, ",", statement.Engine.Quote(","), -1))
  1061. } else {
  1062. columnStr = "*"
  1063. }
  1064. }
  1065. }
  1066. }
  1067. statement.attachInSql() // !admpub! fix bug:Iterate func missing "... IN (...)"
  1068. return statement.genSelectSQL(columnStr), append(append(statement.joinArgs, statement.Params...), statement.BeanArgs...)
  1069. }
  1070. func (s *Statement) genAddColumnStr(col *core.Column) (string, []interface{}) {
  1071. quote := s.Engine.Quote
  1072. sql := fmt.Sprintf("ALTER TABLE %v ADD %v;", quote(s.TableName()),
  1073. col.String(s.Engine.dialect))
  1074. return sql, []interface{}{}
  1075. }
  1076. /*func (s *Statement) genAddIndexStr(idxName string, cols []string) (string, []interface{}) {
  1077. quote := s.Engine.Quote
  1078. colstr := quote(strings.Join(cols, quote(", ")))
  1079. sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(idxName), quote(s.TableName()), colstr)
  1080. return sql, []interface{}{}
  1081. }
  1082. func (s *Statement) genAddUniqueStr(uqeName string, cols []string) (string, []interface{}) {
  1083. quote := s.Engine.Quote
  1084. colstr := quote(strings.Join(cols, quote(", ")))
  1085. sql := fmt.Sprintf("CREATE UNIQUE INDEX %v ON %v (%v);", quote(uqeName), quote(s.TableName()), colstr)
  1086. return sql, []interface{}{}
  1087. }*/
  1088. func (statement *Statement) buildConditions(table *core.Table, bean interface{}, includeVersion bool, includeUpdated bool, includeNil bool, includeAutoIncr bool, addedTableName bool) ([]string, []interface{}) {
  1089. return buildConditions(statement.Engine, table, bean, includeVersion, includeUpdated, includeNil, includeAutoIncr, statement.allUseBool, statement.useAllCols,
  1090. statement.unscoped, statement.mustColumnMap, statement.TableName(), statement.TableAlias, addedTableName)
  1091. }
  1092. func (statement *Statement) genCountSql(bean interface{}) (string, []interface{}) {
  1093. statement.setRefValue(rValue(bean))
  1094. var addedTableName = (len(statement.JoinStr) > 0)
  1095. if !statement.noAutoCondition {
  1096. colNames, args := statement.buildConditions(statement.RefTable, bean, true, true, false, true, addedTableName)
  1097. statement.ConditionStr = strings.Join(colNames, " "+statement.Engine.Dialect().AndStr()+" ")
  1098. statement.BeanArgs = args
  1099. }
  1100. // count(index fieldname) > count(0) > count(*)
  1101. var id = "*"
  1102. if statement.Engine.Dialect().DBType() == "ql" {
  1103. id = ""
  1104. }
  1105. statement.attachInSql()
  1106. return statement.genSelectSQL(fmt.Sprintf("count(%v)", id)), append(append(statement.joinArgs, statement.Params...), statement.BeanArgs...)
  1107. }
  1108. func (statement *Statement) genSumSql(bean interface{}, columns ...string) (string, []interface{}) {
  1109. statement.setRefValue(rValue(bean))
  1110. var addedTableName = (len(statement.JoinStr) > 0)
  1111. if !statement.noAutoCondition {
  1112. colNames, args := statement.buildConditions(statement.RefTable, bean, true, true, false, true, addedTableName)
  1113. statement.ConditionStr = strings.Join(colNames, " "+statement.Engine.Dialect().AndStr()+" ")
  1114. statement.BeanArgs = args
  1115. }
  1116. statement.attachInSql()
  1117. var sumStrs = make([]string, 0, len(columns))
  1118. for _, colName := range columns {
  1119. sumStrs = append(sumStrs, fmt.Sprintf("sum(%s)", colName))
  1120. }
  1121. return statement.genSelectSQL(strings.Join(sumStrs, ", ")), append(append(statement.joinArgs, statement.Params...), statement.BeanArgs...)
  1122. }
  1123. func (statement *Statement) genSelectSQL(columnStr string) (a string) {
  1124. var distinct string
  1125. if statement.IsDistinct {
  1126. distinct = "DISTINCT "
  1127. }
  1128. var dialect = statement.Engine.Dialect()
  1129. var quote = statement.Engine.Quote
  1130. var top string
  1131. var mssqlCondi string
  1132. statement.processIdParam()
  1133. var buf bytes.Buffer
  1134. if len(statement.WhereStr) > 0 {
  1135. if len(statement.ConditionStr) > 0 {
  1136. fmt.Fprintf(&buf, " WHERE (%v)", statement.WhereStr)
  1137. } else {
  1138. fmt.Fprintf(&buf, " WHERE %v", statement.WhereStr)
  1139. }
  1140. if statement.ConditionStr != "" {
  1141. fmt.Fprintf(&buf, " %s (%v)", dialect.AndStr(), statement.ConditionStr)
  1142. }
  1143. } else if len(statement.ConditionStr) > 0 {
  1144. fmt.Fprintf(&buf, " WHERE %v", statement.ConditionStr)
  1145. }
  1146. var whereStr = buf.String()
  1147. var fromStr = " FROM " + quote(statement.TableName())
  1148. if statement.TableAlias != "" {
  1149. if dialect.DBType() == core.ORACLE {
  1150. fromStr += " " + quote(statement.TableAlias)
  1151. } else {
  1152. fromStr += " AS " + quote(statement.TableAlias)
  1153. }
  1154. }
  1155. if statement.JoinStr != "" {
  1156. fromStr = fmt.Sprintf("%v %v", fromStr, statement.JoinStr)
  1157. }
  1158. if dialect.DBType() == core.MSSQL {
  1159. if statement.LimitN > 0 {
  1160. top = fmt.Sprintf(" TOP %d ", statement.LimitN)
  1161. }
  1162. if statement.Start > 0 {
  1163. var column = "(id)"
  1164. if len(statement.RefTable.PKColumns()) == 0 {
  1165. for _, index := range statement.RefTable.Indexes {
  1166. if len(index.Cols) == 1 {
  1167. column = index.Cols[0]
  1168. break
  1169. }
  1170. }
  1171. if len(column) == 0 {
  1172. column = statement.RefTable.ColumnsSeq()[0]
  1173. }
  1174. }
  1175. var orderStr string
  1176. if len(statement.OrderStr) > 0 {
  1177. orderStr = " ORDER BY " + statement.OrderStr
  1178. }
  1179. var groupStr string
  1180. if len(statement.GroupByStr) > 0 {
  1181. groupStr = " GROUP BY " + statement.GroupByStr
  1182. }
  1183. mssqlCondi = fmt.Sprintf("(%s NOT IN (SELECT TOP %d %s%s%s%s%s))",
  1184. column, statement.Start, column, fromStr, whereStr, orderStr, groupStr)
  1185. }
  1186. }
  1187. // !nashtsai! REVIEW Sprintf is considered slowest mean of string concatnation, better to work with builder pattern
  1188. a = fmt.Sprintf("SELECT %v%v%v%v%v", top, distinct, columnStr, fromStr, whereStr)
  1189. if len(mssqlCondi) > 0 {
  1190. if len(whereStr) > 0 {
  1191. a += " AND " + mssqlCondi
  1192. } else {
  1193. a += " WHERE " + mssqlCondi
  1194. }
  1195. }
  1196. if statement.GroupByStr != "" {
  1197. a = fmt.Sprintf("%v GROUP BY %v", a, statement.GroupByStr)
  1198. }
  1199. if statement.HavingStr != "" {
  1200. a = fmt.Sprintf("%v %v", a, statement.HavingStr)
  1201. }
  1202. if statement.OrderStr != "" {
  1203. a = fmt.Sprintf("%v ORDER BY %v", a, statement.OrderStr)
  1204. }
  1205. if dialect.DBType() != core.MSSQL && dialect.DBType() != core.ORACLE {
  1206. if statement.Start > 0 {
  1207. a = fmt.Sprintf("%v LIMIT %v OFFSET %v", a, statement.LimitN, statement.Start)
  1208. } else if statement.LimitN > 0 {
  1209. a = fmt.Sprintf("%v LIMIT %v", a, statement.LimitN)
  1210. }
  1211. } else if dialect.DBType() == core.ORACLE {
  1212. if statement.Start != 0 || statement.LimitN != 0 {
  1213. 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)
  1214. }
  1215. }
  1216. if statement.IsForUpdate {
  1217. a = dialect.ForUpdateSql(a)
  1218. }
  1219. return
  1220. }
  1221. func (statement *Statement) processIdParam() {
  1222. if statement.IdParam != nil {
  1223. if statement.Engine.dialect.DBType() != "ql" {
  1224. for i, col := range statement.RefTable.PKColumns() {
  1225. var colName = statement.colName(col, statement.TableName())
  1226. if i < len(*(statement.IdParam)) {
  1227. statement.And(fmt.Sprintf("%v %s ?", colName,
  1228. statement.Engine.dialect.EqStr()), (*(statement.IdParam))[i])
  1229. } else {
  1230. statement.And(fmt.Sprintf("%v %s ?", colName,
  1231. statement.Engine.dialect.EqStr()), "")
  1232. }
  1233. }
  1234. } else {
  1235. if len(*(statement.IdParam)) <= 1 {
  1236. statement.And("id() == ?", (*(statement.IdParam))[0])
  1237. }
  1238. }
  1239. }
  1240. }
  1241. func (statement *Statement) JoinColumns(cols []*core.Column, includeTableName bool) string {
  1242. var colnames = make([]string, len(cols))
  1243. for i, col := range cols {
  1244. if includeTableName {
  1245. colnames[i] = statement.Engine.Quote(statement.TableName()) +
  1246. "." + statement.Engine.Quote(col.Name)
  1247. } else {
  1248. colnames[i] = statement.Engine.Quote(col.Name)
  1249. }
  1250. }
  1251. return strings.Join(colnames, ", ")
  1252. }
  1253. func (statement *Statement) convertIdSql(sqlStr string) string {
  1254. if statement.RefTable != nil {
  1255. cols := statement.RefTable.PKColumns()
  1256. if len(cols) == 0 {
  1257. return ""
  1258. }
  1259. colstrs := statement.JoinColumns(cols, false)
  1260. sqls := splitNNoCase(sqlStr, " from ", 2)
  1261. if len(sqls) != 2 {
  1262. return ""
  1263. }
  1264. if statement.Engine.dialect.DBType() == "ql" {
  1265. return fmt.Sprintf("SELECT id() FROM %v", sqls[1])
  1266. }
  1267. return fmt.Sprintf("SELECT %s FROM %v", colstrs, sqls[1])
  1268. }
  1269. return ""
  1270. }
  1271. func (statement *Statement) convertUpdateSQL(sqlStr string) (string, string) {
  1272. if statement.RefTable == nil || len(statement.RefTable.PrimaryKeys) != 1 {
  1273. return "", ""
  1274. }
  1275. colstrs := statement.JoinColumns(statement.RefTable.PKColumns(), true)
  1276. sqls := splitNNoCase(sqlStr, "where", 2)
  1277. if len(sqls) != 2 {
  1278. if len(sqls) == 1 {
  1279. return sqls[0], fmt.Sprintf("SELECT %v FROM %v",
  1280. colstrs, statement.Engine.Quote(statement.TableName()))
  1281. }
  1282. return "", ""
  1283. }
  1284. var whereStr = sqls[1]
  1285. //TODO: for postgres only, if any other database?
  1286. var paraStr string
  1287. if statement.Engine.dialect.DBType() == core.POSTGRES {
  1288. paraStr = "$"
  1289. } else if statement.Engine.dialect.DBType() == core.MSSQL {
  1290. paraStr = ":"
  1291. }
  1292. if paraStr != "" {
  1293. if strings.Contains(sqls[1], paraStr) {
  1294. dollers := strings.Split(sqls[1], paraStr)
  1295. whereStr = dollers[0]
  1296. for i, c := range dollers[1:] {
  1297. ccs := strings.SplitN(c, " ", 2)
  1298. whereStr += fmt.Sprintf(paraStr+"%v %v", i+1, ccs[1])
  1299. }
  1300. }
  1301. }
  1302. return sqls[0], fmt.Sprintf("SELECT %v FROM %v WHERE %v",
  1303. colstrs, statement.Engine.Quote(statement.TableName()),
  1304. whereStr)
  1305. }