statement.go 37 KB

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