index.go 1.4 KB

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