sync.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 dameng
  15. import (
  16. "fmt"
  17. "sort"
  18. "strings"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/utils"
  21. "yunion.io/x/sqlchemy"
  22. )
  23. func (mysql *SDamengBackend) CommitTableChangeSQL(ts sqlchemy.ITableSpec, changes sqlchemy.STableChanges) []string {
  24. ret := make([]string, 0)
  25. for _, idx := range changes.RemoveIndexes {
  26. sql := fmt.Sprintf(`DROP INDEX "%s"`, idx.Name())
  27. ret = append(ret, sql)
  28. log.Infof("%s;", sql)
  29. }
  30. alters := make([]string, 0)
  31. // first check if primary key is modifed
  32. changePrimary := false
  33. for _, col := range changes.RemoveColumns {
  34. if col.IsPrimary() {
  35. changePrimary = true
  36. break
  37. }
  38. }
  39. if !changePrimary {
  40. for _, cols := range changes.UpdatedColumns {
  41. if cols.OldCol.IsPrimary() != cols.NewCol.IsPrimary() {
  42. changePrimary = true
  43. break
  44. }
  45. }
  46. }
  47. if !changePrimary {
  48. for _, col := range changes.AddColumns {
  49. if col.IsPrimary() {
  50. changePrimary = true
  51. break
  52. }
  53. }
  54. }
  55. // in case of a primary key change, we first need to drop primary key.
  56. // BUT if a mysql table has no primary key at all,
  57. // exec drop primary key will cause error
  58. if changePrimary {
  59. oldHasPrimary := false
  60. for _, col := range changes.OldColumns {
  61. if col.IsPrimary() {
  62. oldHasPrimary = true
  63. break
  64. }
  65. }
  66. if oldHasPrimary {
  67. alters = append(alters, fmt.Sprintf(`ALTER TABLE "%s" DROP PRIMARY KEY;`, ts.Name()))
  68. }
  69. }
  70. /* IGNORE DROP STATEMENT */
  71. for _, col := range changes.RemoveColumns {
  72. sql := fmt.Sprintf(`ALTER TABLE "%s" DROP COLUMN "%s";`, ts.Name(), col.Name())
  73. log.Debugf("skip %s", sql)
  74. // alters = append(alters, sql)
  75. // ignore drop statement
  76. // if the column is auto_increment integer column,
  77. // then need to drop auto_increment attribute
  78. if col.IsAutoIncrement() {
  79. // make sure the column is nullable
  80. col.SetNullable(true)
  81. log.Errorf("column %s is IDENTITY, drop IDENTITY attribute", col.Name())
  82. col.SetAutoIncrement(false)
  83. sql := fmt.Sprintf(`ALTER TABLE "%s" DROP IDENTITY;`, ts.Name())
  84. alters = append(alters, sql)
  85. sql = fmt.Sprintf(`ALTER TABLE "%s" MODIFY (%s);`, ts.Name(), col.DefinitionString())
  86. alters = append(alters, sql)
  87. }
  88. // if the column is not nullable but no default
  89. // then need to drop the not-nullable attribute
  90. if !col.IsNullable() && col.Default() == "" {
  91. col.SetNullable(true)
  92. sql := fmt.Sprintf(`ALTER TABLE "%s" MODIFY (%s);`, ts.Name(), col.DefinitionString())
  93. alters = append(alters, sql)
  94. log.Errorf("column %s is not nullable but no default, drop not nullable attribute", col.Name())
  95. }
  96. }
  97. for _, cols := range changes.UpdatedColumns {
  98. if cols.OldCol.Name() != cols.NewCol.Name() {
  99. // rename
  100. sql := fmt.Sprintf(`ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s";`, ts.Name(), cols.OldCol.Name(), cols.NewCol.Name())
  101. alters = append(alters, sql)
  102. } else if (strings.HasPrefix(cols.OldCol.ColType(), "VARCHAR") && cols.NewCol.ColType() == "TEXT") || (strings.HasPrefix(cols.NewCol.ColType(), "VARCHAR") && cols.OldCol.ColType() == "TEXT") {
  103. // change varchar to text
  104. oldTmpName := fmt.Sprintf("%s_%s", cols.OldCol.Name(), utils.GenRequestId(6))
  105. alters = append(alters,
  106. // rename oldcol
  107. fmt.Sprintf(`ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s";`, ts.Name(), cols.OldCol.Name(), oldTmpName),
  108. // add a new col
  109. fmt.Sprintf(`ALTER TABLE "%s" ADD %s;`, ts.Name(), cols.NewCol.DefinitionString()),
  110. // copy data
  111. fmt.Sprintf(`UPDATE "%s" SET "%s"=TRIM("%s");`, ts.Name(), cols.NewCol.Name(), oldTmpName),
  112. // drop old col
  113. fmt.Sprintf(`ALTER TABLE "%s" DROP COLUMN "%s";`, ts.Name(), oldTmpName),
  114. )
  115. } else {
  116. if cols.OldCol.IsAutoIncrement() {
  117. sql := fmt.Sprintf(`ALTER TABLE "%s" DROP IDENTITY;`, ts.Name())
  118. alters = append(alters, sql)
  119. }
  120. if cols.NewCol.IsAutoIncrement() {
  121. sql := fmt.Sprintf(`ALTER TABLE "%s" ADD COLUMN "%s" IDENTITY(%d, 1);`, ts.Name(), cols.NewCol.Name(), cols.NewCol.AutoIncrementOffset())
  122. alters = append(alters, sql)
  123. } else {
  124. sql := fmt.Sprintf(`ALTER TABLE "%s" MODIFY (%s)`, ts.Name(), cols.NewCol.DefinitionString())
  125. alters = append(alters, sql)
  126. }
  127. if hasDefault(cols.NewCol) && cols.OldCol.Default() != cols.NewCol.Default() {
  128. defStr := cols.NewCol.Default()
  129. defStr = sqlchemy.GetStringValue(cols.NewCol.ConvertFromString(defStr))
  130. if cols.NewCol.IsText() {
  131. defStr = "'" + defStr + "'"
  132. }
  133. sql := fmt.Sprintf(`ALTER TABLE "%s" ALTER COLUMN "%s" SET DEFAULT %s`, ts.Name(), cols.NewCol.Name(), defStr)
  134. alters = append(alters, sql)
  135. } else if !hasDefault(cols.NewCol) && hasDefault(cols.OldCol) {
  136. sql := fmt.Sprintf(`ALTER TABLE "%s" ALTER COLUMN "%s" DROP DEFAULT`, ts.Name(), cols.NewCol.Name())
  137. alters = append(alters, sql)
  138. }
  139. if cols.NewCol.IsNullable() != cols.OldCol.IsNullable() {
  140. if cols.NewCol.IsNullable() {
  141. sql := fmt.Sprintf(`ALTER TABLE "%s" MODIFY "%s" NULL`, ts.Name(), cols.NewCol.Name())
  142. alters = append(alters, sql)
  143. } else {
  144. sql := fmt.Sprintf(`ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL`, ts.Name(), cols.NewCol.Name())
  145. alters = append(alters, sql)
  146. }
  147. }
  148. }
  149. }
  150. for _, col := range changes.AddColumns {
  151. sql := fmt.Sprintf(`ALTER TABLE "%s" ADD %s`, ts.Name(), col.DefinitionString())
  152. alters = append(alters, sql)
  153. }
  154. if changePrimary {
  155. primaries := make([]string, 0)
  156. primariesQuote := make([]string, 0)
  157. for _, c := range ts.Columns() {
  158. if c.IsPrimary() {
  159. primaries = append(primaries, c.Name())
  160. primariesQuote = append(primariesQuote, fmt.Sprintf(`"%s"`, c.Name()))
  161. }
  162. }
  163. if len(primaries) > 0 {
  164. sort.Strings(primaries)
  165. pkName := fmt.Sprintf("pk_%s_%s", ts.Name(), strings.Join(primaries, "_"))
  166. sql := fmt.Sprintf(`ALTER TABLE "%s" ADD CONSTRAINT %s PRIMARY KEY(%s)`, ts.Name(), pkName, strings.Join(primariesQuote, ", "))
  167. alters = append(alters, sql)
  168. }
  169. }
  170. if len(alters) > 0 {
  171. ret = append(ret, alters...)
  172. log.Infof("%s", strings.Join(alters, "\n"))
  173. }
  174. for _, idx := range changes.AddIndexes {
  175. sql := createIndexSQL(ts, idx)
  176. ret = append(ret, sql)
  177. log.Infof("%s", sql)
  178. }
  179. return ret
  180. }
  181. func createIndexSQL(ts sqlchemy.ITableSpec, idx sqlchemy.STableIndex) string {
  182. return fmt.Sprintf(`CREATE INDEX "%s" ON "%s" (%s);`, idx.Name(), ts.Name(), strings.Join(idx.QuotedColumns(`"`), ","))
  183. }