update_batch.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "fmt"
  17. "strings"
  18. "yunion.io/x/log"
  19. )
  20. func (ts *STableSpec) UpdateBatch(data map[string]interface{}, filter map[string]interface{}) error {
  21. if len(data) <= 0 {
  22. return nil
  23. }
  24. qChar := ts.Database().backend.QuoteChar()
  25. params := make([]interface{}, 0, len(data))
  26. setter := make([]string, 0, len(data))
  27. for k, v := range data {
  28. col := ts.ColumnSpec(k)
  29. if col == nil {
  30. log.Warningf("UpdateBatch: column %s not found", k)
  31. continue
  32. }
  33. setter = append(setter, fmt.Sprintf("%s%s%s = ?", qChar, k, qChar))
  34. params = append(params, col.ConvertFromValue(v))
  35. }
  36. conds, condparams := ts.getSQLFilters(filter, qChar)
  37. params = append(params, condparams...)
  38. buf := strings.Builder{}
  39. buf.WriteString("UPDATE ")
  40. buf.WriteString(qChar)
  41. buf.WriteString(ts.Name())
  42. buf.WriteString(qChar)
  43. buf.WriteString(" SET ")
  44. buf.WriteString(strings.Join(setter, ", "))
  45. if len(conds) > 0 {
  46. buf.WriteString(" WHERE ")
  47. buf.WriteString(strings.Join(conds, " AND "))
  48. }
  49. if DEBUG_SQLCHEMY {
  50. log.Infof("UpdateBATCH: %s %s", buf.String(), params)
  51. }
  52. _, err := ts.Database().Exec(buf.String(), params...)
  53. return err
  54. }