statement.go 36 KB

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