| 1 |
package schema |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"reflect" |
| 7 |
"strings" |
| 8 |
"sync" |
| 9 |
|
| 10 |
"github.com/jinzhu/inflection" |
| 11 |
"golang.org/x/text/cases" |
| 12 |
"golang.org/x/text/language" |
| 13 |
|
| 14 |
"gorm.io/gorm/clause" |
| 15 |
) |
| 16 |
|
| 17 |
// RelationshipType relationship type |
| 18 |
type RelationshipType string |
| 19 |
|
| 20 |
const ( |
| 21 |
HasOne RelationshipType = "has_one" // HasOneRel has one relationship |
| 22 |
HasMany RelationshipType = "has_many" // HasManyRel has many relationship |
| 23 |
BelongsTo RelationshipType = "belongs_to" // BelongsToRel belongs to relationship |
| 24 |
Many2Many RelationshipType = "many_to_many" // Many2ManyRel many to many relationship |
| 25 |
has RelationshipType = "has" |
| 26 |
) |
| 27 |
|
| 28 |
type Relationships struct { |
| 29 |
HasOne []*Relationship |
| 30 |
BelongsTo []*Relationship |
| 31 |
HasMany []*Relationship |
| 32 |
Many2Many []*Relationship |
| 33 |
Relations map[string]*Relationship |
| 34 |
|
| 35 |
EmbeddedRelations map[string]*Relationships |
| 36 |
|
| 37 |
Mux sync.RWMutex |
| 38 |
} |
| 39 |
|
| 40 |
type Relationship struct { |
| 41 |
Name string |
| 42 |
Type RelationshipType |
| 43 |
Field *Field |
| 44 |
Polymorphic *Polymorphic |
| 45 |
References []*Reference |
| 46 |
Schema *Schema |
| 47 |
FieldSchema *Schema |
| 48 |
JoinTable *Schema |
| 49 |
foreignKeys, primaryKeys []string |
| 50 |
} |
| 51 |
|
| 52 |
type Polymorphic struct { |
| 53 |
PolymorphicID *Field |
| 54 |
PolymorphicType *Field |
| 55 |
Value string |
| 56 |
} |
| 57 |
|
| 58 |
type Reference struct { |
| 59 |
PrimaryKey *Field |
| 60 |
PrimaryValue string |
| 61 |
ForeignKey *Field |
| 62 |
OwnPrimaryKey bool |
| 63 |
} |
| 64 |
|
| 65 |
func (schema *Schema) parseRelation(field *Field) *Relationship { |
| 66 |
var ( |
| 67 |
err error |
| 68 |
fieldValue = reflect.New(field.IndirectFieldType).Interface() |
| 69 |
relation = &Relationship{ |
| 70 |
Name: field.Name, |
| 71 |
Field: field, |
| 72 |
Schema: schema, |
| 73 |
foreignKeys: toColumns(field.TagSettings["FOREIGNKEY"]), |
| 74 |
primaryKeys: toColumns(field.TagSettings["REFERENCES"]), |
| 75 |
} |
| 76 |
) |
| 77 |
|
| 78 |
if relation.FieldSchema, err = getOrParse(fieldValue, schema.cacheStore, schema.namer); err != nil { |
| 79 |
schema.err = fmt.Errorf("failed to parse field: %s, error: %w", field.Name, err) |
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
if hasPolymorphicRelation(field.TagSettings) { |
| 84 |
schema.buildPolymorphicRelation(relation, field) |
| 85 |
} else if many2many := field.TagSettings["MANY2MANY"]; many2many != "" { |
| 86 |
schema.buildMany2ManyRelation(relation, field, many2many) |
| 87 |
} else if belongsTo := field.TagSettings["BELONGSTO"]; belongsTo != "" { |
| 88 |
schema.guessRelation(relation, field, guessBelongs) |
| 89 |
} else { |
| 90 |
switch field.IndirectFieldType.Kind() { |
| 91 |
case reflect.Struct: |
| 92 |
schema.guessRelation(relation, field, guessGuess) |
| 93 |
case reflect.Slice: |
| 94 |
schema.guessRelation(relation, field, guessHas) |
| 95 |
default: |
| 96 |
schema.err = fmt.Errorf("unsupported data type %v for %v on field %s", relation.FieldSchema, schema, |
| 97 |
field.Name) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
if relation.Type == has { |
| 102 |
if relation.FieldSchema != relation.Schema && relation.Polymorphic == nil && field.OwnerSchema == nil { |
| 103 |
relation.FieldSchema.Relationships.Mux.Lock() |
| 104 |
relation.FieldSchema.Relationships.Relations["_"+relation.Schema.Name+"_"+relation.Name] = relation |
| 105 |
relation.FieldSchema.Relationships.Mux.Unlock() |
| 106 |
} |
| 107 |
|
| 108 |
switch field.IndirectFieldType.Kind() { |
| 109 |
case reflect.Struct: |
| 110 |
relation.Type = HasOne |
| 111 |
case reflect.Slice: |
| 112 |
relation.Type = HasMany |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
if schema.err == nil { |
| 117 |
schema.setRelation(relation) |
| 118 |
switch relation.Type { |
| 119 |
case HasOne: |
| 120 |
schema.Relationships.HasOne = append(schema.Relationships.HasOne, relation) |
| 121 |
case HasMany: |
| 122 |
schema.Relationships.HasMany = append(schema.Relationships.HasMany, relation) |
| 123 |
case BelongsTo: |
| 124 |
schema.Relationships.BelongsTo = append(schema.Relationships.BelongsTo, relation) |
| 125 |
case Many2Many: |
| 126 |
schema.Relationships.Many2Many = append(schema.Relationships.Many2Many, relation) |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
return relation |
| 131 |
} |
| 132 |
|
| 133 |
// hasPolymorphicRelation check if has polymorphic relation |
| 134 |
// 1. `POLYMORPHIC` tag |
| 135 |
// 2. `POLYMORPHICTYPE` and `POLYMORPHICID` tag |
| 136 |
func hasPolymorphicRelation(tagSettings map[string]string) bool { |
| 137 |
if _, ok := tagSettings["POLYMORPHIC"]; ok { |
| 138 |
return true |
| 139 |
} |
| 140 |
|
| 141 |
_, hasType := tagSettings["POLYMORPHICTYPE"] |
| 142 |
_, hasId := tagSettings["POLYMORPHICID"] |
| 143 |
|
| 144 |
return hasType && hasId |
| 145 |
} |
| 146 |
|
| 147 |
func (schema *Schema) setRelation(relation *Relationship) { |
| 148 |
schema.Relationships.Mux.Lock() |
| 149 |
defer schema.Relationships.Mux.Unlock() |
| 150 |
|
| 151 |
// set non-embedded relation |
| 152 |
if rel := schema.Relationships.Relations[relation.Name]; rel != nil { |
| 153 |
if len(rel.Field.BindNames) > 1 { |
| 154 |
schema.Relationships.Relations[relation.Name] = relation |
| 155 |
} |
| 156 |
} else { |
| 157 |
schema.Relationships.Relations[relation.Name] = relation |
| 158 |
} |
| 159 |
|
| 160 |
// set embedded relation |
| 161 |
if len(relation.Field.EmbeddedBindNames) <= 1 { |
| 162 |
return |
| 163 |
} |
| 164 |
relationships := &schema.Relationships |
| 165 |
for i, name := range relation.Field.EmbeddedBindNames { |
| 166 |
if i < len(relation.Field.EmbeddedBindNames)-1 { |
| 167 |
if relationships.EmbeddedRelations == nil { |
| 168 |
relationships.EmbeddedRelations = map[string]*Relationships{} |
| 169 |
} |
| 170 |
if r := relationships.EmbeddedRelations[name]; r == nil { |
| 171 |
relationships.EmbeddedRelations[name] = &Relationships{} |
| 172 |
} |
| 173 |
relationships = relationships.EmbeddedRelations[name] |
| 174 |
} else { |
| 175 |
if relationships.Relations == nil { |
| 176 |
relationships.Relations = map[string]*Relationship{} |
| 177 |
} |
| 178 |
relationships.Relations[relation.Name] = relation |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
// User has many Toys, its `Polymorphic` is `Owner`, Pet has one Toy, its `Polymorphic` is `Owner` |
| 184 |
// |
| 185 |
// type User struct { |
| 186 |
// Toys []Toy `gorm:"polymorphic:Owner;"` |
| 187 |
// } |
| 188 |
// type Pet struct { |
| 189 |
// Toy Toy `gorm:"polymorphic:Owner;"` |
| 190 |
// } |
| 191 |
// type Toy struct { |
| 192 |
// OwnerID int |
| 193 |
// OwnerType string |
| 194 |
// } |
| 195 |
func (schema *Schema) buildPolymorphicRelation(relation *Relationship, field *Field) { |
| 196 |
polymorphic := field.TagSettings["POLYMORPHIC"] |
| 197 |
|
| 198 |
relation.Polymorphic = &Polymorphic{ |
| 199 |
Value: schema.Table, |
| 200 |
} |
| 201 |
|
| 202 |
var ( |
| 203 |
typeName = polymorphic + "Type" |
| 204 |
typeId = polymorphic + "ID" |
| 205 |
) |
| 206 |
|
| 207 |
if value, ok := field.TagSettings["POLYMORPHICTYPE"]; ok { |
| 208 |
typeName = strings.TrimSpace(value) |
| 209 |
} |
| 210 |
|
| 211 |
if value, ok := field.TagSettings["POLYMORPHICID"]; ok { |
| 212 |
typeId = strings.TrimSpace(value) |
| 213 |
} |
| 214 |
|
| 215 |
relation.Polymorphic.PolymorphicType = relation.FieldSchema.FieldsByName[typeName] |
| 216 |
relation.Polymorphic.PolymorphicID = relation.FieldSchema.FieldsByName[typeId] |
| 217 |
|
| 218 |
if value, ok := field.TagSettings["POLYMORPHICVALUE"]; ok { |
| 219 |
relation.Polymorphic.Value = strings.TrimSpace(value) |
| 220 |
} |
| 221 |
|
| 222 |
if relation.Polymorphic.PolymorphicType == nil { |
| 223 |
schema.err = fmt.Errorf("invalid polymorphic type %v for %v on field %s, missing field %s", |
| 224 |
relation.FieldSchema, schema, field.Name, polymorphic+"Type") |
| 225 |
} |
| 226 |
|
| 227 |
if relation.Polymorphic.PolymorphicID == nil { |
| 228 |
schema.err = fmt.Errorf("invalid polymorphic type %v for %v on field %s, missing field %s", |
| 229 |
relation.FieldSchema, schema, field.Name, polymorphic+"ID") |
| 230 |
} |
| 231 |
|
| 232 |
if schema.err == nil { |
| 233 |
relation.References = append(relation.References, &Reference{ |
| 234 |
PrimaryValue: relation.Polymorphic.Value, |
| 235 |
ForeignKey: relation.Polymorphic.PolymorphicType, |
| 236 |
}) |
| 237 |
|
| 238 |
primaryKeyField := schema.PrioritizedPrimaryField |
| 239 |
if len(relation.foreignKeys) > 0 { |
| 240 |
if primaryKeyField = schema.LookUpField(relation.foreignKeys[0]); primaryKeyField == nil || len(relation.foreignKeys) > 1 { |
| 241 |
schema.err = fmt.Errorf("invalid polymorphic foreign keys %+v for %v on field %s", relation.foreignKeys, |
| 242 |
schema, field.Name) |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
if primaryKeyField == nil { |
| 247 |
schema.err = fmt.Errorf("invalid polymorphic type %v for %v on field %s, missing primaryKey field", |
| 248 |
relation.FieldSchema, schema, field.Name) |
| 249 |
return |
| 250 |
} |
| 251 |
|
| 252 |
// use same data type for foreign keys |
| 253 |
if copyableDataType(primaryKeyField.DataType) { |
| 254 |
relation.Polymorphic.PolymorphicID.DataType = primaryKeyField.DataType |
| 255 |
} |
| 256 |
relation.Polymorphic.PolymorphicID.GORMDataType = primaryKeyField.GORMDataType |
| 257 |
if relation.Polymorphic.PolymorphicID.Size == 0 { |
| 258 |
relation.Polymorphic.PolymorphicID.Size = primaryKeyField.Size |
| 259 |
} |
| 260 |
|
| 261 |
relation.References = append(relation.References, &Reference{ |
| 262 |
PrimaryKey: primaryKeyField, |
| 263 |
ForeignKey: relation.Polymorphic.PolymorphicID, |
| 264 |
OwnPrimaryKey: true, |
| 265 |
}) |
| 266 |
} |
| 267 |
|
| 268 |
relation.Type = has |
| 269 |
} |
| 270 |
|
| 271 |
func (schema *Schema) buildMany2ManyRelation(relation *Relationship, field *Field, many2many string) { |
| 272 |
relation.Type = Many2Many |
| 273 |
|
| 274 |
var ( |
| 275 |
err error |
| 276 |
joinTableFields []reflect.StructField |
| 277 |
fieldsMap = map[string]*Field{} |
| 278 |
ownFieldsMap = map[string]*Field{} // fix self join many2many |
| 279 |
referFieldsMap = map[string]*Field{} |
| 280 |
joinForeignKeys = toColumns(field.TagSettings["JOINFOREIGNKEY"]) |
| 281 |
joinReferences = toColumns(field.TagSettings["JOINREFERENCES"]) |
| 282 |
) |
| 283 |
|
| 284 |
ownForeignFields := schema.PrimaryFields |
| 285 |
refForeignFields := relation.FieldSchema.PrimaryFields |
| 286 |
|
| 287 |
if len(relation.foreignKeys) > 0 { |
| 288 |
ownForeignFields = []*Field{} |
| 289 |
for _, foreignKey := range relation.foreignKeys { |
| 290 |
if field := schema.LookUpField(foreignKey); field != nil { |
| 291 |
ownForeignFields = append(ownForeignFields, field) |
| 292 |
} else { |
| 293 |
schema.err = fmt.Errorf("invalid foreign key: %s", foreignKey) |
| 294 |
return |
| 295 |
} |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
if len(relation.primaryKeys) > 0 { |
| 300 |
refForeignFields = []*Field{} |
| 301 |
for _, foreignKey := range relation.primaryKeys { |
| 302 |
if field := relation.FieldSchema.LookUpField(foreignKey); field != nil { |
| 303 |
refForeignFields = append(refForeignFields, field) |
| 304 |
} else { |
| 305 |
schema.err = fmt.Errorf("invalid foreign key: %s", foreignKey) |
| 306 |
return |
| 307 |
} |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
for idx, ownField := range ownForeignFields { |
| 312 |
joinFieldName := cases.Title(language.Und, cases.NoLower).String(schema.Name) + ownField.Name |
| 313 |
if len(joinForeignKeys) > idx { |
| 314 |
joinFieldName = cases.Title(language.Und, cases.NoLower).String(joinForeignKeys[idx]) |
| 315 |
} |
| 316 |
|
| 317 |
ownFieldsMap[joinFieldName] = ownField |
| 318 |
fieldsMap[joinFieldName] = ownField |
| 319 |
joinTableFields = append(joinTableFields, reflect.StructField{ |
| 320 |
Name: joinFieldName, |
| 321 |
PkgPath: ownField.StructField.PkgPath, |
| 322 |
Type: ownField.StructField.Type, |
| 323 |
Tag: removeSettingFromTag(appendSettingFromTag(ownField.StructField.Tag, "primaryKey"), |
| 324 |
"column", "autoincrement", "index", "unique", "uniqueindex"), |
| 325 |
}) |
| 326 |
} |
| 327 |
|
| 328 |
for idx, relField := range refForeignFields { |
| 329 |
joinFieldName := cases.Title(language.Und, cases.NoLower).String(relation.FieldSchema.Name) + relField.Name |
| 330 |
|
| 331 |
if _, ok := ownFieldsMap[joinFieldName]; ok { |
| 332 |
if field.Name != relation.FieldSchema.Name { |
| 333 |
joinFieldName = inflection.Singular(field.Name) + relField.Name |
| 334 |
} else { |
| 335 |
joinFieldName += "Reference" |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
if len(joinReferences) > idx { |
| 340 |
joinFieldName = cases.Title(language.Und, cases.NoLower).String(joinReferences[idx]) |
| 341 |
} |
| 342 |
|
| 343 |
referFieldsMap[joinFieldName] = relField |
| 344 |
|
| 345 |
if _, ok := fieldsMap[joinFieldName]; !ok { |
| 346 |
fieldsMap[joinFieldName] = relField |
| 347 |
joinTableFields = append(joinTableFields, reflect.StructField{ |
| 348 |
Name: joinFieldName, |
| 349 |
PkgPath: relField.StructField.PkgPath, |
| 350 |
Type: relField.StructField.Type, |
| 351 |
Tag: removeSettingFromTag(appendSettingFromTag(relField.StructField.Tag, "primaryKey"), |
| 352 |
"column", "autoincrement", "index", "unique", "uniqueindex"), |
| 353 |
}) |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
joinTableFields = append(joinTableFields, reflect.StructField{ |
| 358 |
Name: cases.Title(language.Und, cases.NoLower).String(schema.Name) + field.Name, |
| 359 |
Type: schema.ModelType, |
| 360 |
Tag: `gorm:"-"`, |
| 361 |
}) |
| 362 |
|
| 363 |
if relation.JoinTable, err = Parse(reflect.New(reflect.StructOf(joinTableFields)).Interface(), schema.cacheStore, |
| 364 |
schema.namer); err != nil { |
| 365 |
schema.err = err |
| 366 |
} |
| 367 |
relation.JoinTable.Name = many2many |
| 368 |
relation.JoinTable.Table = schema.namer.JoinTableName(many2many) |
| 369 |
relation.JoinTable.PrimaryFields = make([]*Field, 0, len(relation.JoinTable.Fields)) |
| 370 |
|
| 371 |
relName := relation.Schema.Name |
| 372 |
relRefName := relation.FieldSchema.Name |
| 373 |
if relName == relRefName { |
| 374 |
relRefName = relation.Field.Name |
| 375 |
} |
| 376 |
|
| 377 |
if _, ok := relation.JoinTable.Relationships.Relations[relName]; !ok { |
| 378 |
relation.JoinTable.Relationships.Relations[relName] = &Relationship{ |
| 379 |
Name: relName, |
| 380 |
Type: BelongsTo, |
| 381 |
Schema: relation.JoinTable, |
| 382 |
FieldSchema: relation.Schema, |
| 383 |
} |
| 384 |
} else { |
| 385 |
relation.JoinTable.Relationships.Relations[relName].References = []*Reference{} |
| 386 |
} |
| 387 |
|
| 388 |
if _, ok := relation.JoinTable.Relationships.Relations[relRefName]; !ok { |
| 389 |
relation.JoinTable.Relationships.Relations[relRefName] = &Relationship{ |
| 390 |
Name: relRefName, |
| 391 |
Type: BelongsTo, |
| 392 |
Schema: relation.JoinTable, |
| 393 |
FieldSchema: relation.FieldSchema, |
| 394 |
} |
| 395 |
} else { |
| 396 |
relation.JoinTable.Relationships.Relations[relRefName].References = []*Reference{} |
| 397 |
} |
| 398 |
|
| 399 |
// build references |
| 400 |
for _, f := range relation.JoinTable.Fields { |
| 401 |
if f.Creatable || f.Readable || f.Updatable { |
| 402 |
// use same data type for foreign keys |
| 403 |
if copyableDataType(fieldsMap[f.Name].DataType) { |
| 404 |
f.DataType = fieldsMap[f.Name].DataType |
| 405 |
} |
| 406 |
f.GORMDataType = fieldsMap[f.Name].GORMDataType |
| 407 |
if f.Size == 0 { |
| 408 |
f.Size = fieldsMap[f.Name].Size |
| 409 |
} |
| 410 |
relation.JoinTable.PrimaryFields = append(relation.JoinTable.PrimaryFields, f) |
| 411 |
|
| 412 |
if of, ok := ownFieldsMap[f.Name]; ok { |
| 413 |
joinRel := relation.JoinTable.Relationships.Relations[relName] |
| 414 |
joinRel.Field = relation.Field |
| 415 |
joinRel.References = append(joinRel.References, &Reference{ |
| 416 |
PrimaryKey: of, |
| 417 |
ForeignKey: f, |
| 418 |
}) |
| 419 |
|
| 420 |
relation.References = append(relation.References, &Reference{ |
| 421 |
PrimaryKey: of, |
| 422 |
ForeignKey: f, |
| 423 |
OwnPrimaryKey: true, |
| 424 |
}) |
| 425 |
} |
| 426 |
|
| 427 |
if rf, ok := referFieldsMap[f.Name]; ok { |
| 428 |
joinRefRel := relation.JoinTable.Relationships.Relations[relRefName] |
| 429 |
if joinRefRel.Field == nil { |
| 430 |
joinRefRel.Field = relation.Field |
| 431 |
} |
| 432 |
joinRefRel.References = append(joinRefRel.References, &Reference{ |
| 433 |
PrimaryKey: rf, |
| 434 |
ForeignKey: f, |
| 435 |
}) |
| 436 |
|
| 437 |
relation.References = append(relation.References, &Reference{ |
| 438 |
PrimaryKey: rf, |
| 439 |
ForeignKey: f, |
| 440 |
}) |
| 441 |
} |
| 442 |
} |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
type guessLevel int |
| 447 |
|
| 448 |
const ( |
| 449 |
guessGuess guessLevel = iota |
| 450 |
guessBelongs |
| 451 |
guessEmbeddedBelongs |
| 452 |
guessHas |
| 453 |
guessEmbeddedHas |
| 454 |
) |
| 455 |
|
| 456 |
func (schema *Schema) guessRelation(relation *Relationship, field *Field, cgl guessLevel) { |
| 457 |
var ( |
| 458 |
primaryFields, foreignFields []*Field |
| 459 |
primarySchema, foreignSchema = schema, relation.FieldSchema |
| 460 |
gl = cgl |
| 461 |
) |
| 462 |
|
| 463 |
if gl == guessGuess { |
| 464 |
if field.Schema == relation.FieldSchema { |
| 465 |
gl = guessBelongs |
| 466 |
} else { |
| 467 |
gl = guessHas |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
reguessOrErr := func() { |
| 472 |
switch cgl { |
| 473 |
case guessGuess: |
| 474 |
schema.guessRelation(relation, field, guessBelongs) |
| 475 |
case guessBelongs: |
| 476 |
schema.guessRelation(relation, field, guessEmbeddedBelongs) |
| 477 |
case guessEmbeddedBelongs: |
| 478 |
schema.guessRelation(relation, field, guessHas) |
| 479 |
case guessHas: |
| 480 |
schema.guessRelation(relation, field, guessEmbeddedHas) |
| 481 |
// case guessEmbeddedHas: |
| 482 |
default: |
| 483 |
schema.err = fmt.Errorf("invalid field found for struct %v's field %s: define a valid foreign key for relations or implement the Valuer/Scanner interface", |
| 484 |
schema, field.Name) |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
switch gl { |
| 489 |
case guessBelongs: |
| 490 |
primarySchema, foreignSchema = relation.FieldSchema, schema |
| 491 |
case guessEmbeddedBelongs: |
| 492 |
if field.OwnerSchema == nil { |
| 493 |
reguessOrErr() |
| 494 |
return |
| 495 |
} |
| 496 |
primarySchema, foreignSchema = relation.FieldSchema, field.OwnerSchema |
| 497 |
case guessHas: |
| 498 |
case guessEmbeddedHas: |
| 499 |
if field.OwnerSchema == nil { |
| 500 |
reguessOrErr() |
| 501 |
return |
| 502 |
} |
| 503 |
primarySchema, foreignSchema = field.OwnerSchema, relation.FieldSchema |
| 504 |
} |
| 505 |
|
| 506 |
if len(relation.foreignKeys) > 0 { |
| 507 |
for _, foreignKey := range relation.foreignKeys { |
| 508 |
f := foreignSchema.LookUpField(foreignKey) |
| 509 |
if f == nil { |
| 510 |
reguessOrErr() |
| 511 |
return |
| 512 |
} |
| 513 |
foreignFields = append(foreignFields, f) |
| 514 |
} |
| 515 |
} else { |
| 516 |
primarySchemaName := primarySchema.Name |
| 517 |
if primarySchemaName == "" { |
| 518 |
primarySchemaName = relation.FieldSchema.Name |
| 519 |
} |
| 520 |
|
| 521 |
if len(relation.primaryKeys) > 0 { |
| 522 |
for _, primaryKey := range relation.primaryKeys { |
| 523 |
if f := primarySchema.LookUpField(primaryKey); f != nil { |
| 524 |
primaryFields = append(primaryFields, f) |
| 525 |
} |
| 526 |
} |
| 527 |
} else { |
| 528 |
primaryFields = primarySchema.PrimaryFields |
| 529 |
} |
| 530 |
|
| 531 |
primaryFieldLoop: |
| 532 |
for _, primaryField := range primaryFields { |
| 533 |
lookUpName := primarySchemaName + primaryField.Name |
| 534 |
if gl == guessBelongs { |
| 535 |
lookUpName = field.Name + primaryField.Name |
| 536 |
} |
| 537 |
|
| 538 |
lookUpNames := []string{lookUpName} |
| 539 |
if len(primaryFields) == 1 { |
| 540 |
lookUpNames = append(lookUpNames, strings.TrimSuffix(lookUpName, primaryField.Name)+"ID", |
| 541 |
strings.TrimSuffix(lookUpName, primaryField.Name)+"Id", schema.namer.ColumnName(foreignSchema.Table, |
| 542 |
strings.TrimSuffix(lookUpName, primaryField.Name)+"ID")) |
| 543 |
} |
| 544 |
|
| 545 |
for _, name := range lookUpNames { |
| 546 |
if f := foreignSchema.LookUpFieldByBindName(field.BindNames, name); f != nil { |
| 547 |
foreignFields = append(foreignFields, f) |
| 548 |
primaryFields = append(primaryFields, primaryField) |
| 549 |
continue primaryFieldLoop |
| 550 |
} |
| 551 |
} |
| 552 |
for _, name := range lookUpNames { |
| 553 |
if f := foreignSchema.LookUpField(name); f != nil { |
| 554 |
foreignFields = append(foreignFields, f) |
| 555 |
primaryFields = append(primaryFields, primaryField) |
| 556 |
continue primaryFieldLoop |
| 557 |
} |
| 558 |
} |
| 559 |
} |
| 560 |
} |
| 561 |
|
| 562 |
switch { |
| 563 |
case len(foreignFields) == 0: |
| 564 |
reguessOrErr() |
| 565 |
return |
| 566 |
case len(relation.primaryKeys) > 0: |
| 567 |
for idx, primaryKey := range relation.primaryKeys { |
| 568 |
if f := primarySchema.LookUpField(primaryKey); f != nil { |
| 569 |
if len(primaryFields) < idx+1 { |
| 570 |
primaryFields = append(primaryFields, f) |
| 571 |
} else if f != primaryFields[idx] { |
| 572 |
reguessOrErr() |
| 573 |
return |
| 574 |
} |
| 575 |
} else { |
| 576 |
reguessOrErr() |
| 577 |
return |
| 578 |
} |
| 579 |
} |
| 580 |
case len(primaryFields) == 0: |
| 581 |
if len(foreignFields) == 1 && primarySchema.PrioritizedPrimaryField != nil { |
| 582 |
primaryFields = append(primaryFields, primarySchema.PrioritizedPrimaryField) |
| 583 |
} else if len(primarySchema.PrimaryFields) == len(foreignFields) { |
| 584 |
primaryFields = append(primaryFields, primarySchema.PrimaryFields...) |
| 585 |
} else { |
| 586 |
reguessOrErr() |
| 587 |
return |
| 588 |
} |
| 589 |
} |
| 590 |
|
| 591 |
// build references |
| 592 |
for idx, foreignField := range foreignFields { |
| 593 |
// use same data type for foreign keys |
| 594 |
schema.Relationships.Mux.Lock() |
| 595 |
if schema != foreignField.Schema { |
| 596 |
foreignField.Schema.Relationships.Mux.Lock() |
| 597 |
} |
| 598 |
if copyableDataType(primaryFields[idx].DataType) { |
| 599 |
foreignField.DataType = primaryFields[idx].DataType |
| 600 |
} |
| 601 |
foreignField.GORMDataType = primaryFields[idx].GORMDataType |
| 602 |
if foreignField.Size == 0 { |
| 603 |
foreignField.Size = primaryFields[idx].Size |
| 604 |
} |
| 605 |
schema.Relationships.Mux.Unlock() |
| 606 |
if schema != foreignField.Schema { |
| 607 |
foreignField.Schema.Relationships.Mux.Unlock() |
| 608 |
} |
| 609 |
|
| 610 |
relation.References = append(relation.References, &Reference{ |
| 611 |
PrimaryKey: primaryFields[idx], |
| 612 |
ForeignKey: foreignField, |
| 613 |
OwnPrimaryKey: (schema == primarySchema && gl == guessHas) || (field.OwnerSchema == primarySchema && gl == guessEmbeddedHas), |
| 614 |
}) |
| 615 |
} |
| 616 |
|
| 617 |
if gl == guessHas || gl == guessEmbeddedHas { |
| 618 |
relation.Type = has |
| 619 |
} else { |
| 620 |
relation.Type = BelongsTo |
| 621 |
} |
| 622 |
} |
| 623 |
|
| 624 |
// Constraint is ForeignKey Constraint |
| 625 |
type Constraint struct { |
| 626 |
Name string |
| 627 |
Field *Field |
| 628 |
Schema *Schema |
| 629 |
ForeignKeys []*Field |
| 630 |
ReferenceSchema *Schema |
| 631 |
References []*Field |
| 632 |
OnDelete string |
| 633 |
OnUpdate string |
| 634 |
} |
| 635 |
|
| 636 |
func (constraint *Constraint) GetName() string { return constraint.Name } |
| 637 |
|
| 638 |
func (constraint *Constraint) Build() (sql string, vars []interface{}) { |
| 639 |
sql = "CONSTRAINT ? FOREIGN KEY ? REFERENCES ??" |
| 640 |
if constraint.OnDelete != "" { |
| 641 |
sql += " ON DELETE " + constraint.OnDelete |
| 642 |
} |
| 643 |
|
| 644 |
if constraint.OnUpdate != "" { |
| 645 |
sql += " ON UPDATE " + constraint.OnUpdate |
| 646 |
} |
| 647 |
|
| 648 |
foreignKeys := make([]interface{}, 0, len(constraint.ForeignKeys)) |
| 649 |
for _, field := range constraint.ForeignKeys { |
| 650 |
foreignKeys = append(foreignKeys, clause.Column{Name: field.DBName}) |
| 651 |
} |
| 652 |
|
| 653 |
references := make([]interface{}, 0, len(constraint.References)) |
| 654 |
for _, field := range constraint.References { |
| 655 |
references = append(references, clause.Column{Name: field.DBName}) |
| 656 |
} |
| 657 |
vars = append(vars, clause.Table{Name: constraint.Name}, foreignKeys, clause.Table{Name: constraint.ReferenceSchema.Table}, references) |
| 658 |
return |
| 659 |
} |
| 660 |
|
| 661 |
func (rel *Relationship) ParseConstraint() *Constraint { |
| 662 |
str := rel.Field.TagSettings["CONSTRAINT"] |
| 663 |
if str == "-" { |
| 664 |
return nil |
| 665 |
} |
| 666 |
|
| 667 |
if rel.Type == BelongsTo { |
| 668 |
for _, r := range rel.FieldSchema.Relationships.Relations { |
| 669 |
if r != rel && r.FieldSchema == rel.Schema && len(rel.References) == len(r.References) { |
| 670 |
matched := true |
| 671 |
for idx, ref := range r.References { |
| 672 |
if !(rel.References[idx].PrimaryKey == ref.PrimaryKey && rel.References[idx].ForeignKey == ref.ForeignKey && |
| 673 |
rel.References[idx].PrimaryValue == ref.PrimaryValue) { |
| 674 |
matched = false |
| 675 |
break |
| 676 |
} |
| 677 |
} |
| 678 |
|
| 679 |
if matched { |
| 680 |
return nil |
| 681 |
} |
| 682 |
} |
| 683 |
} |
| 684 |
} |
| 685 |
|
| 686 |
var ( |
| 687 |
name string |
| 688 |
idx = strings.IndexByte(str, ',') |
| 689 |
settings = ParseTagSetting(str, ",") |
| 690 |
) |
| 691 |
|
| 692 |
// optimize match english letters and midline |
| 693 |
// The following code is basically called in for. |
| 694 |
// In order to avoid the performance problems caused by repeated compilation of regular expressions, |
| 695 |
// it only needs to be done once outside, so optimization is done here. |
| 696 |
if idx != -1 && regEnLetterAndMidline.MatchString(str[0:idx]) { |
| 697 |
name = str[0:idx] |
| 698 |
} else { |
| 699 |
name = rel.Schema.namer.RelationshipFKName(*rel) |
| 700 |
} |
| 701 |
|
| 702 |
constraint := Constraint{ |
| 703 |
Name: name, |
| 704 |
Field: rel.Field, |
| 705 |
OnUpdate: settings["ONUPDATE"], |
| 706 |
OnDelete: settings["ONDELETE"], |
| 707 |
} |
| 708 |
|
| 709 |
for _, ref := range rel.References { |
| 710 |
if ref.PrimaryKey != nil && (rel.JoinTable == nil || ref.OwnPrimaryKey) { |
| 711 |
constraint.ForeignKeys = append(constraint.ForeignKeys, ref.ForeignKey) |
| 712 |
constraint.References = append(constraint.References, ref.PrimaryKey) |
| 713 |
|
| 714 |
if ref.OwnPrimaryKey { |
| 715 |
constraint.Schema = ref.ForeignKey.Schema |
| 716 |
constraint.ReferenceSchema = rel.Schema |
| 717 |
} else { |
| 718 |
constraint.Schema = rel.Schema |
| 719 |
constraint.ReferenceSchema = ref.PrimaryKey.Schema |
| 720 |
} |
| 721 |
} |
| 722 |
} |
| 723 |
|
| 724 |
return &constraint |
| 725 |
} |
| 726 |
|
| 727 |
func (rel *Relationship) ToQueryConditions(ctx context.Context, reflectValue reflect.Value) (conds []clause.Expression) { |
| 728 |
table := rel.FieldSchema.Table |
| 729 |
foreignFields := []*Field{} |
| 730 |
relForeignKeys := []string{} |
| 731 |
|
| 732 |
if rel.JoinTable != nil { |
| 733 |
table = rel.JoinTable.Table |
| 734 |
for _, ref := range rel.References { |
| 735 |
if ref.OwnPrimaryKey { |
| 736 |
foreignFields = append(foreignFields, ref.PrimaryKey) |
| 737 |
relForeignKeys = append(relForeignKeys, ref.ForeignKey.DBName) |
| 738 |
} else if ref.PrimaryValue != "" { |
| 739 |
conds = append(conds, clause.Eq{ |
| 740 |
Column: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName}, |
| 741 |
Value: ref.PrimaryValue, |
| 742 |
}) |
| 743 |
} else { |
| 744 |
conds = append(conds, clause.Eq{ |
| 745 |
Column: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName}, |
| 746 |
Value: clause.Column{Table: rel.FieldSchema.Table, Name: ref.PrimaryKey.DBName}, |
| 747 |
}) |
| 748 |
} |
| 749 |
} |
| 750 |
} else { |
| 751 |
for _, ref := range rel.References { |
| 752 |
if ref.OwnPrimaryKey { |
| 753 |
relForeignKeys = append(relForeignKeys, ref.ForeignKey.DBName) |
| 754 |
foreignFields = append(foreignFields, ref.PrimaryKey) |
| 755 |
} else if ref.PrimaryValue != "" { |
| 756 |
conds = append(conds, clause.Eq{ |
| 757 |
Column: clause.Column{Table: rel.FieldSchema.Table, Name: ref.ForeignKey.DBName}, |
| 758 |
Value: ref.PrimaryValue, |
| 759 |
}) |
| 760 |
} else { |
| 761 |
relForeignKeys = append(relForeignKeys, ref.PrimaryKey.DBName) |
| 762 |
foreignFields = append(foreignFields, ref.ForeignKey) |
| 763 |
} |
| 764 |
} |
| 765 |
} |
| 766 |
|
| 767 |
_, foreignValues := GetIdentityFieldValuesMap(ctx, reflectValue, foreignFields) |
| 768 |
column, values := ToQueryValues(table, relForeignKeys, foreignValues) |
| 769 |
|
| 770 |
conds = append(conds, clause.IN{Column: column, Values: values}) |
| 771 |
return |
| 772 |
} |
| 773 |
|
| 774 |
func copyableDataType(str DataType) bool { |
| 775 |
lowerStr := strings.ToLower(string(str)) |
| 776 |
for _, s := range []string{"auto_increment", "primary key"} { |
| 777 |
if strings.Contains(lowerStr, s) { |
| 778 |
return false |
| 779 |
} |
| 780 |
} |
| 781 |
return true |
| 782 |
} |