Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add insertUnique_ to PersistUniqueWrite #1469

Merged
merged 4 commits into from
Mar 3, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions persistent-test/src/ReadWriteTest.hs
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,14 @@ specsWith originalRunDb = describe "ReadWriteTest" $ do
mkey1 @== Nothing
mperson <- selectFirst [PersonName ==. name_] []
fmap entityVal mperson @== Just person

let nameLuke = "Luke Seale New"
personLuke = Person nameLuke 31 Nothing
mkey2 <- insertUnique_ personLuke
mkey3 <- insertUnique_ personLuke
mkey3 @== Nothing
mpersonLuke <- selectFirst [PersonName ==. nameLuke] []
fmap entityVal mpersonLuke @== Just personLuke



31 changes: 31 additions & 0 deletions persistent/Database/Persist/Class/PersistUnique.hs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,37 @@ class (PersistUniqueRead backend, PersistStoreWrite backend) =>
Nothing -> Just `liftM` insert datum
Just _ -> return Nothing

-- | Same as 'insertUnique' but doesn't return a @Key@.
--
-- === __Example usage__
--
-- With <#schema-persist-unique-1 schema-1> and <#dataset-persist-unique-1 dataset-1>, we try to insert the following two records:
--
-- > linusId <- insertUnique_ $ User "Linus" 48
-- > spjId <- insertUnique_ $ User "SPJ" 90
--
-- > +-----+------+-----+
-- > |id |name |age |
-- > +-----+------+-----+
-- > |1 |SPJ |40 |
-- > +-----+------+-----+
-- > |2 |Simon |41 |
-- > +-----+------+-----+
-- > |3 |Linus |48 |
-- > +-----+------+-----+
--
-- Linus's record was inserted to <#dataset-persist-unique-1 dataset-1>, while SPJ wasn't because SPJ already exists in <#dataset-persist-unique-1 dataset-1>.
--
-- @since 2.14.4.4
Copy link
Collaborator

@parsonsmatt parsonsmatt Mar 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an addition to a class with a default method, this is a minor version bump - let's bundle this with 2.14.5.0.

insertUnique_
:: forall record m. (MonadIO m, PersistRecordBackend record backend, SafeToInsert record)
=> record -> ReaderT backend m (Maybe ())
insertUnique_ datum = do
conflict <- checkUnique datum
case conflict of
Nothing -> Just `liftM` insert_ datum
Just _ -> return Nothing

-- | Update based on a uniqueness constraint or insert:
--
-- * insert the new record if it does not exist;
Expand Down