delete_batch.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "reflect"
  18. "strings"
  19. "yunion.io/x/log"
  20. )
  21. func (ts *STableSpec) getSQLFilters(filter map[string]interface{}, qChar string) ([]string, []interface{}) {
  22. conds := make([]string, 0, len(filter))
  23. params := make([]interface{}, 0, len(filter))
  24. for k, v := range filter {
  25. col := ts.ColumnSpec(k)
  26. if col == nil {
  27. log.Warningf("getSQLFilters: column %s not found", k)
  28. continue
  29. }
  30. if reflect.TypeOf(v).Kind() == reflect.Slice || reflect.TypeOf(v).Kind() == reflect.Array {
  31. value := reflect.ValueOf(v)
  32. if value.Len() == 0 {
  33. continue
  34. }
  35. arr := make([]string, value.Len())
  36. for i := 0; i < value.Len(); i++ {
  37. arr[i] = "?"
  38. params = append(params, col.ConvertFromValue(value.Index(i).Interface()))
  39. }
  40. conds = append(conds, fmt.Sprintf("%s%s%s in (%s)", qChar, k, qChar, strings.Join(arr, ", ")))
  41. } else {
  42. conds = append(conds, fmt.Sprintf("%s%s%s = ?", qChar, k, qChar))
  43. params = append(params, col.ConvertFromValue(v))
  44. }
  45. }
  46. return conds, params
  47. }
  48. func (ts *STableSpec) DeleteFrom(filters map[string]interface{}) error {
  49. buf := strings.Builder{}
  50. qChar := ts.Database().backend.QuoteChar()
  51. buf.WriteString("DELETE FROM ")
  52. buf.WriteString(qChar)
  53. buf.WriteString(ts.Name())
  54. buf.WriteString(qChar)
  55. conds, params := ts.getSQLFilters(filters, qChar)
  56. if len(conds) > 0 {
  57. buf.WriteString(" WHERE ")
  58. buf.WriteString(strings.Join(conds, " AND "))
  59. }
  60. if DEBUG_SQLCHEMY {
  61. log.Infof("Update: %s %s", buf.String(), params)
  62. }
  63. _, err := ts.Database().TxExec(buf.String(), params...)
  64. return err
  65. }