Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

index: add composite id #5269

Merged
merged 3 commits into from Apr 25, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 23 additions & 3 deletions schema/index.go
@@ -1,6 +1,7 @@
package schema

import (
"fmt"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -31,7 +32,12 @@ func (schema *Schema) ParseIndexes() map[string]Index {

for _, field := range schema.Fields {
if field.TagSettings["INDEX"] != "" || field.TagSettings["UNIQUEINDEX"] != "" {
for _, index := range parseFieldIndexes(field) {
fieldIndexes, err := parseFieldIndexes(field)
if err != nil {
schema.err = err
break
}
for _, index := range fieldIndexes {
idx := indexes[index.Name]
idx.Name = index.Name
if idx.Class == "" {
Expand Down Expand Up @@ -82,7 +88,7 @@ func (schema *Schema) LookIndex(name string) *Index {
return nil
}

func parseFieldIndexes(field *Field) (indexes []Index) {
func parseFieldIndexes(field *Field) (indexes []Index, err error) {
for _, value := range strings.Split(field.Tag.Get("gorm"), ";") {
if value != "" {
v := strings.Split(value, ":")
Expand All @@ -106,7 +112,20 @@ func parseFieldIndexes(field *Field) (indexes []Index) {
}

if name == "" {
name = field.Schema.namer.IndexName(field.Schema.Table, field.Name)
subName := field.Name
const key = "COMPOSITE"
if composite, found := settings[key]; found {
if len(composite) == 0 || composite == key {
err = fmt.Errorf(
"The composite tag of %s.%s cannot be empty",
field.Schema.Name,
field.Name)
return
}
subName = composite
}
name = field.Schema.namer.IndexName(
field.Schema.Table, subName)
}

if (k == "UNIQUEINDEX") || settings["UNIQUE"] != "" {
Expand Down Expand Up @@ -138,5 +157,6 @@ func parseFieldIndexes(field *Field) (indexes []Index) {
}
}

err = nil
return
}