Skip to content

to-one association is generated when 'UNIQUE' set on a composite key(with multiple columns) #77

Closed
@yangyuqian

Description

@yangyuqian

Hi,

It seems a bug to create to-one association when a composite key is unique,

i.e.

When the composite key in user_role(user_id, role_id) is UNIQUE, a to-one association will be generated on both User and UserRole

user(id)
user_role(id, user_id, role_id)
role(id)

And I can fix this by omit the UNIQUE composite keys and still generate to-many associations for them(line number 134):

// bdb/drivers/mysql.go
120 func (m *MySQLDriver) Columns(schema, tableName string) ([]bdb.Column, error) {
121     var columns []bdb.Column
122
123     rows, err := m.dbConn.Query(`
124     select
125     c.column_name,
126     if(c.data_type = 'enum', c.column_type, c.data_type),
127     if(extra = 'auto_increment','auto_increment', c.column_default),
128     c.is_nullable = 'YES',
129         exists (
130             select c.column_name
131             from information_schema.table_constraints tc
132             inner join information_schema.key_column_usage kcu
133                 on tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name and tc.table_schema = kcu.table_schema
+ 134                      and kcu.ORDINAL_POSITION = 1 and kcu.constraint_name = CONCAT('fk_', kcu.table_name, '_', kcu.column_name)
135             where c.column_name = kcu.column_name and tc.table_name = c.table_name and
136                 (tc.constraint_type = 'PRIMARY KEY' or tc.constraint_type = 'UNIQUE')
137         ) as is_unique
138     from information_schema.columns as c
139     where table_name = ? and table_schema = ?;
140     `, tableName, schema)

Do you think this is a feasible fix? I'd like to submit a PR for it

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions