title: Insert into a table if a condition is met with sqlite3
body: <p>if I have two tables: <code>files(id, owner)</code> and <code>share(file_id, user)</code>, where owner and user would be primary IDs from a theoretical user table, how can I insert an entry into <code>share</code> only if the user doing the sharing owns that file?</p>
  
  <p>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:</p>
  
  <pre>
  files:
  id: 1, owner: 1
  </pre>
  
  <p>and user 2 wants to see file 1, I would use this query:</p>
  
  <pre><code>insert into share values (1, 2)
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>and they are all syntax errors. I'm doing this from Python, so after this query, I would just check the <code>Cursor.rowcount</code> to see if it is 1 or 0, and if it's 0, then the user didn't have permission to complete the operation.</p>
  
  <p>How can I properly write this query?</p>