Kononnable / typeorm-model-generator

Generates models for TypeORM from existing database.
MIT License
1.51k stars 281 forks source link

Tree entities detecton #234

Open boenrobot opened 4 years ago

boenrobot commented 4 years ago

It would be useful (and just really cool...) if the generator could detect tree structures and add the appropriate decorators and options

Models like materialized path and nested set can't be reliably detected, but adjacency lists and closure tables sure can be.

If a table has a nullable single foreign key that refers to a primary/unique column(s) in the same table, it's definitely an adjacency list, with the fk being the parent pointer, and the inverse side is the children.

If a table has exactly two foreign keys that refer to the same primary/unique columns in the same other table, and all columns in both fks form a unique/primary index, that table is definetly a closure table for the table referenced by the fks... exactly which fk is parents and which is children is trickier though... by convention, the first one in the table is the parents, but this isn't necessarily true, and complex fks could cross their positions within the table. If the first such column determines the parent, I think that covers most schemas in the wild.

Either way, the naming strategy of the entity should be able to adjust or opt out of these options on per entity basis. This loophole should also enable users to mark manually known nested sets and materialized paths, as they can't be detected automatically that easily.

boenrobot commented 4 years ago

After some investigation into TypeORM's support, it seems they must first provide a way to configure a closure table (see typeorm/typeorm#5288) and also, adjacency lists are not supported in the tree API (see typeorm/typeorm#2540), despite their remains as an option in the tree decorator.

IMHO, adjacency lists support should be added rather than dropped, perhaps with some exceptions for operations impossible in that model.

avin-kavish commented 4 years ago

I agree that adjacency lists should be added. I don't think they limited as the documentation makes them out to be. It is possible to retrieve a full tree using recursive queries. (in postgres at least)