Allow making m2m relation of a table to itself
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 2.2k
- Forks
- 172
- Avg merge
- 9m
- Merged PRs (30d)
- 1
Description
I am building a database, in which one of the tables has a many-to-many relationship to itself. As far as I can see, this is not (yet) possible using .m2m() in sqlite-utils. This may be a bit of a niche use case, so feel free to close this issue if you feel it would introduce too much complexity compared to the benefits.
Example: suppose I have a table of people, and I want to store the information that John and Mary have two children, Michael and Suzy. It would be neat if I could do something like this:
from sqlite_utils import Database
db = Database(memory=True)
db["people"].insert({"name": "John"}, pk="name").m2m(
"people", [{"name": "Michael"}, {"name": "Suzy"}], m2m_table="parent_child", pk="name"
)
db["people"].insert({"name": "Mary"}, pk="name").m2m(
"people", [{"name": "Michael"}, {"name": "Suzy"}], m2m_table="parent_child", pk="name"
)
But if I do that, the many-to-many table parent_child has only one column:
CREATE TABLE [parent_child] (
[people_id] TEXT REFERENCES [people]([name]),
PRIMARY KEY ([people_id], [people_id])
)
This could be solved by adding one or two keyword_arguments to .m2m(), e.g. .m2m(..., left_name=None, right_name=None) or .m2m(..., names=(None, None)).
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing the Python .m2m() implementation and the schema it creates for the provided self-referential people example. Determine how the two sides of the relationship can receive distinct columns, then verify that both parent-child calls create the intended links in SQLite without collapsing the foreign keys.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, sqlite
- Domain
- databases
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100