You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2019 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package schemas
  5. import (
  6. "fmt"
  7. "strings"
  8. )
  9. // enumerate all index types
  10. const (
  11. IndexType = iota + 1
  12. UniqueType
  13. )
  14. // Index represents a database index
  15. type Index struct {
  16. IsRegular bool
  17. Name string
  18. Type int
  19. Cols []string
  20. }
  21. // NewIndex new an index object
  22. func NewIndex(name string, indexType int) *Index {
  23. return &Index{true, name, indexType, make([]string, 0)}
  24. }
  25. func (index *Index) XName(tableName string) string {
  26. if !strings.HasPrefix(index.Name, "UQE_") &&
  27. !strings.HasPrefix(index.Name, "IDX_") {
  28. tableParts := strings.Split(strings.Replace(tableName, `"`, "", -1), ".")
  29. tableName = tableParts[len(tableParts)-1]
  30. if index.Type == UniqueType {
  31. return fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
  32. }
  33. return fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
  34. }
  35. return index.Name
  36. }
  37. // AddColumn add columns which will be composite index
  38. func (index *Index) AddColumn(cols ...string) {
  39. for _, col := range cols {
  40. index.Cols = append(index.Cols, col)
  41. }
  42. }
  43. func (index *Index) Equal(dst *Index) bool {
  44. if index.Type != dst.Type {
  45. return false
  46. }
  47. if len(index.Cols) != len(dst.Cols) {
  48. return false
  49. }
  50. for i := 0; i < len(index.Cols); i++ {
  51. var found bool
  52. for j := 0; j < len(dst.Cols); j++ {
  53. if index.Cols[i] == dst.Cols[j] {
  54. found = true
  55. break
  56. }
  57. }
  58. if !found {
  59. return false
  60. }
  61. }
  62. return true
  63. }