insert.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 splitable
  15. import (
  16. "database/sql"
  17. "fmt"
  18. "reflect"
  19. "time"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/util/reflectutils"
  23. "yunion.io/x/pkg/util/timeutils"
  24. "yunion.io/x/sqlchemy"
  25. )
  26. func (t *SSplitTableSpec) getLastTableSpecWithLock(lastDate time.Time) (*sqlchemy.STableSpec, error) {
  27. t.lastTableLock.Lock()
  28. defer t.lastTableLock.Unlock()
  29. now := time.Now()
  30. if t.lastTableSpec != nil && !t.lastTableExpire.IsZero() && t.lastTableExpire.Before(now) {
  31. return t.lastTableSpec, nil
  32. }
  33. lastTableSpec, err := t.getLastTableSpec(lastDate)
  34. if err != nil {
  35. return nil, errors.Wrap(err, "getLastTableSpec")
  36. }
  37. t.lastTableSpec = lastTableSpec
  38. t.lastTableExpire = now.Add(time.Hour * lastTableSpecExpireHours)
  39. return t.lastTableSpec, nil
  40. }
  41. func (t *SSplitTableSpec) getLastTableSpec(lastDate time.Time) (*sqlchemy.STableSpec, error) {
  42. lastMeta, err := t.getTableLastMeta()
  43. if err != nil && errors.Cause(err) != sql.ErrNoRows {
  44. return nil, errors.Wrap(err, "GetTableMeta")
  45. }
  46. var lastRecIndex int64
  47. var lastRecDate time.Time
  48. var lastTableSpec *sqlchemy.STableSpec
  49. newMeta := false
  50. if lastMeta != nil {
  51. if !lastMeta.StartDate.IsZero() && lastDate.Sub(lastMeta.StartDate) > t.maxDuration {
  52. lastTable := t.GetTableSpec(*lastMeta)
  53. ti := lastTable.Instance()
  54. q := ti.Query(sqlchemy.MAX("last_index", ti.Field(t.indexField)), sqlchemy.MAX("last_date", ti.Field(t.dateField)), sqlchemy.COUNT("total"))
  55. r := q.Row()
  56. var lastRecDateStr string
  57. var total uint64
  58. err := r.Scan(&lastRecIndex, &lastRecDateStr, &total)
  59. if err != nil {
  60. return nil, errors.Wrap(err, "scan lastRecIndex and lastRecDate")
  61. }
  62. log.Debugf("lastRecDateStr: %s", lastRecDateStr)
  63. lastRecDate, _ = timeutils.ParseTimeStr(lastRecDateStr)
  64. // seal last meta
  65. _, err = t.metaSpec.Update(lastMeta, func() error {
  66. lastMeta.End = lastRecIndex
  67. lastMeta.EndDate = lastRecDate
  68. lastMeta.Count = total
  69. return nil
  70. })
  71. if err != nil {
  72. return nil, errors.Wrap(err, "Update last meta")
  73. }
  74. newMeta = true
  75. } else {
  76. if lastMeta.StartDate.IsZero() {
  77. indexCol := t.tableSpec.ColumnSpec(t.indexField)
  78. startDate := lastMeta.CreatedAt
  79. if startDate.IsZero() {
  80. startDate = lastDate
  81. }
  82. _, err = t.metaSpec.Update(lastMeta, func() error {
  83. lastMeta.Start = indexCol.AutoIncrementOffset()
  84. lastMeta.StartDate = startDate
  85. return nil
  86. })
  87. if err != nil {
  88. return nil, errors.Wrap(err, "Update last meta")
  89. }
  90. }
  91. lastTableSpec = t.GetTableSpec(*lastMeta)
  92. }
  93. } else {
  94. newMeta = true
  95. }
  96. if newMeta {
  97. lastTableSpec, err = t.newTable(lastRecIndex, lastDate)
  98. if err != nil {
  99. return nil, errors.Wrap(err, "newTable")
  100. }
  101. }
  102. return lastTableSpec, nil
  103. }
  104. func (t *SSplitTableSpec) Insert(dt interface{}) error {
  105. var lastDate time.Time
  106. dataValue := reflect.Indirect(reflect.ValueOf(dt))
  107. vs := reflectutils.FetchAllStructFieldValueSet(dataValue)
  108. if lastDateV, ok := vs.GetValue(t.dateField); !ok {
  109. return errors.Wrap(errors.ErrInvalidStatus, "no dateField found")
  110. } else {
  111. lastDate = lastDateV.Interface().(time.Time)
  112. }
  113. if lastDate.IsZero() {
  114. lastDate = time.Now()
  115. succ := reflectutils.SetStructFieldValue(dataValue, t.dateField, reflect.ValueOf(lastDate))
  116. if !succ {
  117. return errors.Wrap(errors.ErrInvalidStatus, "set dateField failed")
  118. }
  119. }
  120. lastTableSpec, err := t.getLastTableSpecWithLock(lastDate)
  121. if err != nil {
  122. return errors.Wrap(err, "getLastTableSpec")
  123. }
  124. return lastTableSpec.Insert(dt)
  125. }
  126. func (t *SSplitTableSpec) newTable(lastRecIndex int64, lastDate time.Time) (*sqlchemy.STableSpec, error) {
  127. // insert a new metadata
  128. meta := STableMetadata{
  129. Table: fmt.Sprintf("%s_%d", t.tableName, lastDate.Unix()),
  130. }
  131. if lastRecIndex > 0 {
  132. // auto_increment offset should consider HA setup
  133. meta.Start = lastRecIndex + 10000
  134. meta.StartDate = lastDate
  135. }
  136. err := t.metaSpec.Insert(&meta)
  137. if err != nil {
  138. return nil, errors.Wrap(err, "insert new meta")
  139. }
  140. // create new table
  141. newTable := t.GetTableSpec(meta)
  142. err = newTable.Sync()
  143. if err != nil {
  144. return nil, errors.Wrap(err, "sync new table")
  145. }
  146. return newTable, nil
  147. }