insert_batch.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. "strings"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/gotypes"
  23. "yunion.io/x/pkg/util/reflectutils"
  24. "yunion.io/x/pkg/util/timeutils"
  25. )
  26. const (
  27. sqlLineLimit = 100
  28. )
  29. func (t *STableSpec) InsertBatch(dataList []interface{}) error {
  30. qChar := t.Database().backend.QuoteChar()
  31. var sql string
  32. var fieldCount int
  33. {
  34. buffer := new(bytes.Buffer)
  35. buffer.WriteString("INSERT INTO ")
  36. buffer.WriteString(qChar)
  37. buffer.WriteString(t.Name())
  38. buffer.WriteString(qChar)
  39. buffer.WriteString(" (")
  40. headers := make([]string, 0)
  41. format := make([]string, 0)
  42. for _, col := range t.Columns() {
  43. if col.IsAutoIncrement() {
  44. continue
  45. }
  46. name := col.Name()
  47. headers = append(headers, fmt.Sprintf("%s%s%s", qChar, name, qChar))
  48. if col.IsCreatedAt() || col.IsUpdatedAt() {
  49. if t.Database().backend.SupportMixedInsertVariables() {
  50. format = append(format, t.Database().backend.CurrentUTCTimeStampString())
  51. } else {
  52. format = append(format, "?")
  53. fieldCount++
  54. }
  55. continue
  56. }
  57. format = append(format, "?")
  58. fieldCount++
  59. }
  60. buffer.WriteString(strings.Join(headers, ","))
  61. buffer.WriteString(") VALUES ")
  62. buffer.WriteString("(")
  63. buffer.WriteString(strings.Join(format, ","))
  64. buffer.WriteString(")")
  65. sql = buffer.String()
  66. if DEBUG_SQLCHEMY {
  67. log.Debugf("batchInsert SQL: %s", buffer.String())
  68. }
  69. }
  70. batchParams := make([][]interface{}, 0)
  71. now := timeutils.UtcNow()
  72. errs := make([]error, 0)
  73. for i := range dataList {
  74. v := dataList[i]
  75. var params []interface{}
  76. modelValue := reflect.Indirect(reflect.ValueOf(v))
  77. beforeInsert(modelValue)
  78. dataFields := reflectutils.FetchStructFieldValueSet(modelValue)
  79. for _, col := range t.Columns() {
  80. if col.IsAutoIncrement() {
  81. continue
  82. }
  83. if col.IsCreatedAt() || col.IsUpdatedAt() {
  84. if !t.Database().backend.SupportMixedInsertVariables() {
  85. params = append(params, now)
  86. }
  87. continue
  88. }
  89. ov, find := dataFields.GetInterface(col.Name())
  90. if !find || gotypes.IsNil(ov) || col.IsZero(ov) {
  91. // empty column
  92. if col.IsSupportDefault() && (len(col.Default()) > 0 || col.IsString()) {
  93. params = append(params, col.ConvertFromString(col.Default()))
  94. } else {
  95. params = append(params, nil)
  96. }
  97. } else {
  98. // validate text width
  99. if col.IsString() && col.GetWidth() > 0 {
  100. newStr, ok := ov.(string)
  101. if ok && len(newStr) > col.GetWidth() {
  102. ov = newStr[:col.GetWidth()]
  103. }
  104. }
  105. params = append(params, col.ConvertFromValue(ov))
  106. }
  107. }
  108. if len(params) != fieldCount {
  109. log.Errorf("expect %d got %d(%#v)", fieldCount, len(params), params)
  110. }
  111. batchParams = append(batchParams, params)
  112. if len(batchParams) >= sqlLineLimit || (i+1) == len(dataList) {
  113. results, err := t.Database().TxBatchExec(sql, batchParams)
  114. if err != nil {
  115. return errors.Wrap(err, "TxBatchExec")
  116. }
  117. for _, result := range results {
  118. if result.Error != nil {
  119. errs = append(errs, result.Error)
  120. }
  121. }
  122. if len(errs) != 0 {
  123. return errors.NewAggregate(errs)
  124. }
  125. batchParams = make([][]interface{}, 0)
  126. }
  127. }
  128. return nil
  129. }