parse.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 mysql
  15. import (
  16. "regexp"
  17. "yunion.io/x/sqlchemy"
  18. )
  19. const (
  20. indexPattern = `(?P<unique>UNIQUE\s+)?KEY ` + "`" + `(?P<name>\w+)` + "`" + ` \((?P<cols>` + "`" + `\w+` + "`" + `(\(\d+\))?(,\s*` + "`" + `\w+` + "`" + `(\(\d+\))?)*)\)`
  21. constraintPattern = `CONSTRAINT ` + "`" + `(?P<name>\w+)` + "`" + ` FOREIGN KEY \((?P<cols>` + "`" + `\w+` + "`" + `(,\s*` + "`" + `\w+` + "`" + `)*)\) REFERENCES ` + "`" + `(?P<table>\w+)` + "`" + ` \((?P<fcols>` + "`" + `\w+` + "`" + `(,\s*` + "`" + `\w+` + "`" + `)*)\)`
  22. )
  23. var (
  24. indexRegexp = regexp.MustCompile(indexPattern)
  25. constraintRegexp = regexp.MustCompile(constraintPattern)
  26. )
  27. func fetchColumns(match string) []string {
  28. return sqlchemy.FetchColumns(match)
  29. }
  30. func parseConstraints(defStr string) []sqlchemy.STableConstraint {
  31. matches := constraintRegexp.FindAllStringSubmatch(defStr, -1)
  32. tcs := make([]sqlchemy.STableConstraint, len(matches))
  33. for i := range matches {
  34. tcs[i] = sqlchemy.NewTableConstraint(
  35. matches[i][1],
  36. fetchColumns(matches[i][2]),
  37. matches[i][4],
  38. fetchColumns(matches[i][5]),
  39. )
  40. }
  41. return tcs
  42. }
  43. func parseIndexes(ts sqlchemy.ITableSpec, defStr string) []sqlchemy.STableIndex {
  44. matches := indexRegexp.FindAllStringSubmatch(defStr, -1)
  45. tcs := make([]sqlchemy.STableIndex, len(matches))
  46. for i := range matches {
  47. tcs[i] = sqlchemy.NewTableIndex(
  48. ts,
  49. matches[i][2],
  50. fetchColumns(matches[i][3]),
  51. len(matches[i][1]) > 0,
  52. )
  53. }
  54. return tcs
  55. }