if I have two tables: files(id, owner)
and share(file_id, user)
, where owner and user would be primary IDs from a theoretical user table, how can I insert an entry into share
only if the user doing the sharing owns that file?
This is a stripped down example, so I'll just use a literal for the one doing the share operation -- normally this value would come from a session. So if I had:
files: id: 1, owner: 1
and user 2 wants to see file 1, I would use this query:
insert into share values (1, 2)
but that isn't allowed -- user 2 doesn't own file 1, user 1 does. I am trying to do this in one query, but I can't figure it out. I have tried:
case when (select owner from files where id=1) is 2
then (insert into share values (1, 2));
case (select owner from files where id=1) is 2
then (insert into share values (1, 2));
insert into share values (1, 2)
where 2 not in (select owner from files where id=1)
and they are all syntax errors. I'm doing this from Python, so after this query, I would just check the Cursor.rowcount
to see if it is 1 or 0, and if it's 0, then the user didn't have permission to complete the operation.
How can I properly write this query?