ponyorm / pony

Pony Object Relational Mapper
Apache License 2.0
3.58k stars 242 forks source link

Parameter 'fk_name' doesn't work #692

Open AlvaDamian opened 9 months ago

AlvaDamian commented 9 months ago

I am trying to create the same table names and relations structure in different schemas. This leads to the same FK name. Dont't pay attention to our use case, we can work with different table names, but I wanted to report that when trying to set the FK names to something else using the fk_name parameter, it doesn't work.

class ReferencedEntity(db.Entity):
    one_entities = Set('OneEntity', reverse='referenced')
    another_entities = Set('AnotherEntity', reverse='referenced')

class OneEntity(db.Entity):
    _table_ = ('public', 'entity')
    referenced = Required('ReferencedEntity', reverse='one_entities', fk_name='fk_oneentity_referenced_id')

class AnotherEntity(db.Entity):
    _table_ = ('another', 'entity')
    referenced = Required('ReferencedEntity', reverse='another_entities', fk_name='fk_anotherentity_referenced_id')

Creating this schema with the method generate_mapping(check_tables=False, create_tables=True) throws an exception:

File ".../venv/lib/python3.10/site-packages/pony/orm/core.py", line 1127, in generate_mapping
    table.add_foreign_key(attr.reverse.fk_name, child_columns, parent_table, parent_columns, attr.index,
  File ".../venv/lib/python3.10/site-packages/pony/orm/dbschema.py", line 205, in add_foreign_key
    return table.schema.fk_class(fk_name, table, child_columns, parent_table, parent_columns, index_name, on_delete,
  File ".../venv/lib/python3.10/site-packages/pony/orm/dbschema.py", line 361, in __init__
    throw(DBSchemaError, 'Foreign key %s cannot be created, name is already in use' % name)
  File ".../venv/lib/python3.10/site-packages/pony/utils/utils.py", line 99, in throw
    raise exc
pony.orm.core.DBSchemaError: Foreign key fk_entity__referenced cannot be created, name is already in use

I am not seeing anything wrong in my code according to the documentation for the fk_name parameter