2019-06-23 23:22:43 +08:00
|
|
|
// Copyright 2019 The Xorm Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2020-03-22 23:12:55 +08:00
|
|
|
package schemas
|
2016-11-04 06:16:01 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2019-08-27 10:17:23 +08:00
|
|
|
// enumerate all index types
|
2016-11-04 06:16:01 +08:00
|
|
|
const (
|
|
|
|
IndexType = iota + 1
|
|
|
|
UniqueType
|
|
|
|
)
|
|
|
|
|
2019-08-27 10:17:23 +08:00
|
|
|
// Index represents a database index
|
2016-11-04 06:16:01 +08:00
|
|
|
type Index struct {
|
|
|
|
IsRegular bool
|
|
|
|
Name string
|
|
|
|
Type int
|
|
|
|
Cols []string
|
|
|
|
}
|
|
|
|
|
2020-03-22 23:12:55 +08:00
|
|
|
// NewIndex new an index object
|
|
|
|
func NewIndex(name string, indexType int) *Index {
|
|
|
|
return &Index{true, name, indexType, make([]string, 0)}
|
|
|
|
}
|
|
|
|
|
2016-11-04 06:16:01 +08:00
|
|
|
func (index *Index) XName(tableName string) string {
|
|
|
|
if !strings.HasPrefix(index.Name, "UQE_") &&
|
|
|
|
!strings.HasPrefix(index.Name, "IDX_") {
|
2020-01-20 23:45:14 +08:00
|
|
|
tableParts := strings.Split(strings.Replace(tableName, `"`, "", -1), ".")
|
|
|
|
tableName = tableParts[len(tableParts)-1]
|
2016-11-04 06:16:01 +08:00
|
|
|
if index.Type == UniqueType {
|
|
|
|
return fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
|
|
|
|
}
|
|
|
|
return index.Name
|
|
|
|
}
|
|
|
|
|
2019-08-27 10:17:23 +08:00
|
|
|
// AddColumn add columns which will be composite index
|
2016-11-04 06:16:01 +08:00
|
|
|
func (index *Index) AddColumn(cols ...string) {
|
|
|
|
for _, col := range cols {
|
|
|
|
index.Cols = append(index.Cols, col)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (index *Index) Equal(dst *Index) bool {
|
|
|
|
if index.Type != dst.Type {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if len(index.Cols) != len(dst.Cols) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < len(index.Cols); i++ {
|
2019-06-23 23:22:43 +08:00
|
|
|
var found bool
|
|
|
|
for j := 0; j < len(dst.Cols); j++ {
|
|
|
|
if index.Cols[i] == dst.Cols[j] {
|
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !found {
|
2016-11-04 06:16:01 +08:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|