simonw / sqlite-utils

Python CLI utility and library for manipulating SQLite databases
https://sqlite-utils.datasette.io
Apache License 2.0
1.67k stars 111 forks source link

add ability to configure "on delete" and "on update" attributes of foreign keys: #530

Open fgregg opened 1 year ago

fgregg commented 1 year ago

sqlite supports these, and it would be quite nice to be able to add them with sqlite-utils.

https://www.sqlite.org/foreignkeys.html#fk_actions

simonw commented 1 year ago

Wow, this is a neat feature I didn't know about. Looks like there are a bunch of options:

simonw commented 1 year ago

I think the natural place to add these in the Python library API would be https://sqlite-utils.datasette.io/en/stable/python-api.html#adding-foreign-key-constraints - maybe something like this:

db["books"].add_foreign_key("author_id", "authors", "id", on_delete=RESTRICT)

Then for the CLI tool could be added to https://sqlite-utils.datasette.io/en/stable/cli-reference.html#add-foreign-key

sqlite-utils add-foreign-key my.db books author_id authors id --on-update SET_NULL

I wouldn't support these for the other methods of adding foreign keys - foreign_keys(...) for the various .insert() etc methods and the add_foreign_keys(...) bulk menthod.