piccolo-orm / piccolo

A fast, user friendly ORM and query builder which supports asyncio.
https://piccolo-orm.com/
MIT License
1.32k stars 86 forks source link

Improve `LazyTableReference` #1039

Closed dantownsend closed 4 days ago

dantownsend commented 4 days ago

LazyTableReference is needed when a foreign key has to reference a table lower down in the file:

class Band(Table):
    manager = ForeignKey(
        LazyTableReference("Manager", module_path=__name__)
    )
    name = Varchar()

class Manager(Table):
    name = Varchar()

The challenge is making sure that LazyTableReference is converted to a real reference at the correct time - too soon, and you get circular import errors. Too late, and the foreign key won't work properly.

In the Table metaclass we're calling the copy method on ForeignKey which seems to be causing some issues (triggering the conversion to a real reference too soon). We need to improve this.