index.go 1.5 KB

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 core
  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. func (index *Index) XName(tableName string) string {
  22. if !strings.HasPrefix(index.Name, "UQE_") &&
  23. !strings.HasPrefix(index.Name, "IDX_") {
  24. tableName = strings.Replace(tableName, `"`, "", -1)
  25. tableName = strings.Replace(tableName, `.`, "_", -1)
  26. if index.Type == UniqueType {
  27. return fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
  28. }
  29. return fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
  30. }
  31. return index.Name
  32. }
  33. // AddColumn add columns which will be composite index
  34. func (index *Index) AddColumn(cols ...string) {
  35. for _, col := range cols {
  36. index.Cols = append(index.Cols, col)
  37. }
  38. }
  39. func (index *Index) Equal(dst *Index) bool {
  40. if index.Type != dst.Type {
  41. return false
  42. }
  43. if len(index.Cols) != len(dst.Cols) {
  44. return false
  45. }
  46. for i := 0; i < len(index.Cols); i++ {
  47. var found bool
  48. for j := 0; j < len(dst.Cols); j++ {
  49. if index.Cols[i] == dst.Cols[j] {
  50. found = true
  51. break
  52. }
  53. }
  54. if !found {
  55. return false
  56. }
  57. }
  58. return true
  59. }
  60. // NewIndex new an index object
  61. func NewIndex(name string, indexType int) *Index {
  62. return &Index{true, name, indexType, make([]string, 0)}
  63. }