| 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 || |
| 673 | rel.References[idx].ForeignKey != ref.ForeignKey || |
| 674 | rel.References[idx].PrimaryValue != ref.PrimaryValue { |
| 675 | matched = false |
| 676 | break |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | if matched { |
| 681 | return nil |
| 682 | } |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | var ( |
| 688 | name string |
| 689 | idx = strings.IndexByte(str, ',') |
| 690 | settings = ParseTagSetting(str, ",") |
| 691 | ) |
| 692 | |
| 693 | // optimize match english letters and midline |
| 694 | // The following code is basically called in for. |
| 695 | // In order to avoid the performance problems caused by repeated compilation of regular expressions, |
| 696 | // it only needs to be done once outside, so optimization is done here. |
| 697 | if idx != -1 && regEnLetterAndMidline.MatchString(str[0:idx]) { |
| 698 | name = str[0:idx] |
| 699 | } else { |
| 700 | name = rel.Schema.namer.RelationshipFKName(*rel) |
| 701 | } |
| 702 | |
| 703 | constraint := Constraint{ |
| 704 | Name: name, |
| 705 | Field: rel.Field, |
| 706 | OnUpdate: settings["ONUPDATE"], |
| 707 | OnDelete: settings["ONDELETE"], |
| 708 | } |
| 709 | |
| 710 | for _, ref := range rel.References { |
| 711 | if ref.PrimaryKey != nil && (rel.JoinTable == nil || ref.OwnPrimaryKey) { |
| 712 | constraint.ForeignKeys = append(constraint.ForeignKeys, ref.ForeignKey) |
| 713 | constraint.References = append(constraint.References, ref.PrimaryKey) |
| 714 | |
| 715 | if ref.OwnPrimaryKey { |
| 716 | constraint.Schema = ref.ForeignKey.Schema |
| 717 | constraint.ReferenceSchema = rel.Schema |
| 718 | } else { |