From 06e5e30ebe1d9b95d5cbebb3e04513e33ab607e2 Mon Sep 17 00:00:00 2001 From: Marc Scholten Date: Sat, 22 Jun 2024 16:08:20 -0700 Subject: [PATCH] Add copyRecord --- IHP/ModelSupport.hs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/IHP/ModelSupport.hs b/IHP/ModelSupport.hs index 0f973a7ad..38e23ba8b 100644 --- a/IHP/ModelSupport.hs +++ b/IHP/ModelSupport.hs @@ -1125,4 +1125,23 @@ onlyWhereReferencesMaybe field referenced records = filter (\record -> get field -- > |> isValid -- isValid :: forall record. (HasField "meta" record MetaBag) => record -> Bool -isValid record = isEmpty record.meta.annotations \ No newline at end of file +isValid record = isEmpty record.meta.annotations + +-- | Copies all the fields (except the 'id' field) into a new record +-- +-- Example: Duplicate a database record (except the primary key of course) +-- +-- > project <- fetch projectId +-- > duplicatedProject <- createRecord (copyRecord project) +-- +copyRecord :: forall record id. (Table record, SetField "id" record id, Default id, SetField "meta" record MetaBag) => record -> record +copyRecord existingRecord = + let + fieldsExceptId = (columnNames @record) |> filter (\field -> field /= "id") + + meta :: MetaBag + meta = def { touchedFields = map (IHP.NameSupport.columnNameToFieldName . cs) fieldsExceptId } + in + existingRecord + |> set #id def + |> set #meta meta \ No newline at end of file