statement.go 37 KB

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