protoc-gen-gorm icon indicating copy to clipboard operation
protoc-gen-gorm copied to clipboard

protoc-gen-gorm 1.1.0 produces "unique index" GORM tags that are silently ignored

Open jhberges opened this issue 2 years ago • 0 comments

Hi!

I'm posting this issue mostly to help others that are facing the same issue, as the workaround described below works well.

Example model:

syntax = "proto3";
option go_package = "github.com/jhberges/dummy";
package dummy;
import "options/gorm.proto";


message Parent {
    option (gorm.opts) = { ormable: true };
    string id = 1 [(gorm.field).tag = {type: "uuid"; primary_key: true; default: "uuid_generate_v4()"}];
}

message Child {
    option (gorm.opts) = { ormable: true };
    Parent father = 1 [(gorm.field) = {belongs_to: {foreignkey:"father_fk", foreignkey_tag: {unique_index:"idx_unique_parenthood"}}}]; 
    Parent mother = 2 [(gorm.field) = {belongs_to: {foreignkey:"mother_fk", foreignkey_tag: {unique_index:"idx_unique_parenthood"}}}]; 
}

The plugin will generate the following entity structs from this:

//...
type ParentORM struct {
	Id string `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
}
//...
type ChildORM struct {
	Father   *ParentORM `gorm:"foreignkey:FatherFk;association_foreignkey:Id"`
	FatherFk *string    `gorm:"unique_index:idx_unique_parenthood"`
	Mother   *ParentORM `gorm:"foreignkey:MotherFk;association_foreignkey:Id"`
	MotherFk *string    `gorm:"unique_index:idx_unique_parenthood"`
}
//...

The tag ```gorm:"unique_index:..."is silently ignored as it is expectinguniqueIndex`in the annotation. Thus no index is created.

Workaround Changing the Child to the following works:

message Child {
    option (gorm.opts) = { ormable: true };
    Parent father = 1 [(gorm.field) = {belongs_to: {foreignkey:"father_fk", foreignkey_tag: {index:"idx_unique_parenthood,unique"}}}]; 
    Parent mother = 2 [(gorm.field) = {belongs_to: {foreignkey:"mother_fk", foreignkey_tag: {index:"idx_unique_parenthood,unique"}}}]; 
}

Generating an ORM struct:

type ChildORM struct {
	Father   *ParentORM `gorm:"foreignkey:FatherFk;association_foreignkey:Id"`
	FatherFk *string    `gorm:"index:idx_unique_parenthood,unique"`
	Mother   *ParentORM `gorm:"foreignkey:MotherFk;association_foreignkey:Id"`
	MotherFk *string    `gorm:"index:idx_unique_parenthood,unique"`
}

jhberges avatar Apr 22 '22 11:04 jhberges