statement.go 38 KB

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