title: In Persistent (Haskell), how can I insert a record only if it doesn't already exist?
body: <p>I'm a Haskell beginner, so apologies in advance!</p>
  
  <p>I've been following <a href="https://www.yesodweb.com/book/persistent" rel="nofollow noreferrer">the Persistent tutorial here</a>. </p>
  
  <p>I have a data model with a uniqueness constraint: </p>
  
  <pre><code>Book
      gutId Int
      UniqueGutId gutId
      ...
      author [AuthorId]
      ... 
  Author
      gutId Int
      UniqueAuthorGutId gutId
      ...
  </code></pre>
  
  <p>And when I go to <code>insert</code> a record using this: </p>
  
  <pre><code>  runSqlite "test.db" $ do
      runMigration migrateAll
  
      -- FIXME: This won't work if there's an author that's already in the database.
      authorIds &lt;- mapM insert authors
  </code></pre>
  
  <p>It won't work if the record is already in the database. (It'll just return an exception.) I can do this instead: </p>
  
  <pre><code>authorIds &lt;- mapM insertUnique authors
  </code></pre>
  
  <p>But the problem is, I need to use <code>authorIds</code> to update <code>Book</code> records later. So I'm just wondering if anyone knows of an easy way to insert a record if it doesn't exist, and return the new key, or get the record key if it already exists, so that I have an array of keys either way. <a href="https://github.com/JonathanReeve/corpus-db/blob/f3f051ce2a76d803f05fd8d99e1d6989ca9d3206/src/Main.hs" rel="nofollow noreferrer">The full code at this point is up here.</a></p>