field_update.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sqlchemy
  15. import (
  16. "bytes"
  17. "fmt"
  18. "reflect"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/gotypes"
  22. "yunion.io/x/pkg/util/reflectutils"
  23. )
  24. // UpdateFields update a record with the values provided by fields stringmap
  25. // params dt: model struct, fileds: {struct-field-name-string: update-value}
  26. func (ts *STableSpec) UpdateFields(dt interface{}, fields map[string]interface{}) error {
  27. return ts.updateFields(dt, fields, false)
  28. }
  29. // params dt: model struct, fileds: {struct-field-name-string: update-value}
  30. // find primary key and index key
  31. // find fields correlatively columns
  32. // joint sql and executed
  33. func (ts *STableSpec) updateFieldSql(dt interface{}, fields map[string]interface{}, debug bool) (*SUpdateSQLResult, error) {
  34. dataValue := reflect.Indirect(reflect.ValueOf(dt))
  35. cv := make(map[string]interface{})
  36. // use field to store field order
  37. cnames := make([]string, 0)
  38. fullFields := reflectutils.FetchStructFieldValueSet(dataValue)
  39. versionFields := make([]string, 0)
  40. updatedFields := make([]string, 0)
  41. primaryCols := make([]sPrimaryKeyValue, 0)
  42. for _, col := range ts.Columns() {
  43. name := col.Name()
  44. colValue, ok := fullFields.GetInterface(name)
  45. if !ok {
  46. continue
  47. }
  48. if col.IsPrimary() {
  49. if !gotypes.IsNil(colValue) && !col.IsZero(colValue) {
  50. primaryCols = append(primaryCols, sPrimaryKeyValue{
  51. key: name,
  52. value: colValue,
  53. })
  54. } else if col.IsText() {
  55. primaryCols = append(primaryCols, sPrimaryKeyValue{
  56. key: name,
  57. value: "",
  58. })
  59. } else {
  60. return nil, ErrEmptyPrimaryKey
  61. }
  62. continue
  63. }
  64. if col.IsAutoVersion() {
  65. versionFields = append(versionFields, name)
  66. continue
  67. }
  68. if col.IsUpdatedAt() {
  69. updatedFields = append(updatedFields, name)
  70. continue
  71. }
  72. if _, exist := fields[name]; exist {
  73. cv[name] = col.ConvertFromValue(fields[name])
  74. cnames = append(cnames, name)
  75. }
  76. }
  77. if len(primaryCols) == 0 {
  78. return nil, ErrEmptyPrimaryKey
  79. }
  80. qChar := ts.Database().backend.QuoteChar()
  81. vars := make([]interface{}, 0)
  82. var buf bytes.Buffer
  83. buf.WriteString(fmt.Sprintf("UPDATE %s%s%s SET ", qChar, ts.name, qChar))
  84. for i, k := range cnames {
  85. v := cv[k]
  86. if i > 0 {
  87. buf.WriteString(", ")
  88. }
  89. buf.WriteString(fmt.Sprintf("%s%s%s = ?", qChar, k, qChar))
  90. vars = append(vars, v)
  91. }
  92. for _, versionField := range versionFields {
  93. buf.WriteString(fmt.Sprintf(", %s%s%s = %s%s%s + 1", qChar, versionField, qChar, qChar, versionField, qChar))
  94. }
  95. for _, updatedField := range updatedFields {
  96. buf.WriteString(fmt.Sprintf(", %s%s%s = %s", qChar, updatedField, qChar, ts.Database().backend.CurrentUTCTimeStampString()))
  97. }
  98. buf.WriteString(" WHERE ")
  99. for i, pkv := range primaryCols {
  100. if i > 0 {
  101. buf.WriteString(" AND ")
  102. }
  103. buf.WriteString(fmt.Sprintf("%s%s%s = ?", qChar, pkv.key, qChar))
  104. vars = append(vars, pkv.value)
  105. }
  106. if DEBUG_SQLCHEMY || debug {
  107. log.Infof("Update: %s", buf.String())
  108. }
  109. return &SUpdateSQLResult{
  110. Sql: buf.String(),
  111. Vars: vars,
  112. primaries: primaryCols,
  113. }, nil
  114. }
  115. func (ts *STableSpec) updateFields(dt interface{}, fields map[string]interface{}, debug bool) error {
  116. results, err := ts.updateFieldSql(dt, fields, debug)
  117. if err != nil {
  118. return errors.Wrap(err, "updateFieldSql")
  119. }
  120. err = ts.execUpdateSql(dt, results)
  121. if err != nil {
  122. return errors.Wrap(err, "execUpdateSql")
  123. }
  124. return nil
  125. }