Author: Alberto Mardegan <mardy@users.sourceforge.net>
Description: ContactWriter: prevent aggregation within the same collection
 .
 We assume that contacts within a collection are all different.
 .
 Fixes: https://gitlab.com/ubports/development/core/qtcontacts-sqlite/-/issues/2

--- a/src/engine/contactwriter.cpp
+++ b/src/engine/contactwriter.cpp
@@ -4040,6 +4040,10 @@
             " SELECT secondId FROM Relationships WHERE firstId = :contactId AND type = 'IsNot'"
             " UNION"
             " SELECT firstId FROM Relationships WHERE secondId = :contactId AND type = 'IsNot'"
+            " UNION"
+            " SELECT firstId FROM Relationships WHERE secondId IN ("
+                " SELECT contactId FROM Contacts WHERE collectionId = :collectionId"
+            " ) AND type = 'Aggregates'"
         " )"));
 
     // Use a simple match algorithm, looking for exact matches on name fields,
@@ -4053,6 +4057,7 @@
     QMap<QString, QVariant> bindings;
     bindings.insert(":lastName", lastName);
     bindings.insert(":contactId", ContactId::databaseId(*contact));
+    bindings.insert(":collectionId", ContactCollectionId::databaseId(contact->collectionId()));
     bindings.insert(":excludeGender", excludeGender);
     if (!m_database.createTemporaryContactIdsTable(possibleAggregatesTable,
                                                    QString(), where, orderBy, bindings)) {
