From 976bea202c699bf12dbe91788efd2347912bbe26 Mon Sep 17 00:00:00 2001
From: Bruno Muniz Azevedo Filho <bruno@elixxir.io>
Date: Mon, 18 Jul 2022 14:38:45 -0300
Subject: [PATCH] Fixes db issue where my contact wasn't created

---
 Sources/Integration/Session/Session+UD.swift | 20 +++++++-------------
 Sources/Integration/Session/Session.swift    | 20 ++++++++++++++++++++
 2 files changed, 27 insertions(+), 13 deletions(-)

diff --git a/Sources/Integration/Session/Session+UD.swift b/Sources/Integration/Session/Session+UD.swift
index 6dd7472f..21514741 100644
--- a/Sources/Integration/Session/Session+UD.swift
+++ b/Sources/Integration/Session/Session+UD.swift
@@ -41,20 +41,14 @@ extension Session {
 
                 switch $0 {
                 case .success(_):
-                    _ = try? self.dbManager.saveContact(.init(
-                        id: self.client.bindings.myId,
-                        marshaled: self.client.bindings.meMarshalled,
-                        username: value,
-                        email: nil,
-                        phone: nil,
-                        nickname: nil,
-                        photo: nil,
-                        authStatus: .friend,
-                        isRecent: false,
-                        createdAt: Date()
-                    ))
-
                     self.username = value
+                    let query = Contact.Query(id: [self.client.bindings.myId])
+
+                    if var myself = try? self.dbManager.fetchContacts(query).first {
+                        myself.username = value
+                        _ = try? self.dbManager.saveContact(myself)
+                    }
+
                     completion(.success(nil))
                 case .failure(let error):
                     completion(.failure(error))
diff --git a/Sources/Integration/Session/Session.swift b/Sources/Integration/Session/Session.swift
index 51234cab..fc69e656 100644
--- a/Sources/Integration/Session/Session.swift
+++ b/Sources/Integration/Session/Session.swift
@@ -194,6 +194,26 @@ public final class Session: SessionType {
             }
             .store(in: &cancellables)
 
+        /// Create a contact for myself, for foreign key purposes
+        ///
+        if var myself = try? dbManager.fetchContacts(.init(id: [client.bindings.myId])).first {
+            myself.username = username
+            _ = try? dbManager.saveContact(myself)
+        } else {
+            _ = try? dbManager.saveContact(.init(
+                id: client.bindings.myId,
+                marshaled: client.bindings.meMarshalled,
+                username: username,
+                email: email,
+                phone: phone,
+                nickname: nil,
+                photo: nil,
+                authStatus: .friend,
+                isRecent: false,
+                createdAt: Date()
+            ))
+        }
+
         registerUnfinishedUploadTransfers()
         registerUnfinishedDownloadTransfers()
 
-- 
GitLab