diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepository.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepository.kt index b3ed3785d55..56ba670da04 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepository.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepository.kt @@ -229,7 +229,7 @@ internal class ConnectionDataSource( ) insertConversationFromConnection(connection) // should we insert first user before creating conversation ? - userDAO.insertUser(userEntity) + userDAO.upsertUser(userEntity) connectionDAO.insertConnection(connectionMapper.modelToDao(connection)) } }) diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/ConversationGroupRepository.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/ConversationGroupRepository.kt index adbc6fa2021..a1f16094bad 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/ConversationGroupRepository.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/ConversationGroupRepository.kt @@ -99,7 +99,7 @@ internal class ConversationGroupRepositoryImpl( private val selfUserId: UserId, private val teamIdProvider: SelfTeamIdProvider, private val conversationMapper: ConversationMapper = MapperProvider.conversationMapper(selfUserId), - private val eventMapper: EventMapper = MapperProvider.eventMapper(), + private val eventMapper: EventMapper = MapperProvider.eventMapper(selfUserId), private val protocolInfoMapper: ProtocolInfoMapper = MapperProvider.protocolInfoMapper(), ) : ConversationGroupRepository { diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/MLSConversationRepository.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/MLSConversationRepository.kt index d6205b9e3c8..56a74c31064 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/MLSConversationRepository.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/conversation/MLSConversationRepository.kt @@ -332,7 +332,7 @@ internal class MLSConversationDataSource( private suspend fun processCommitBundleEvents(events: List) { events.forEach { eventContentDTO -> - val event = MapperProvider.eventMapper().fromEventContentDTO("", eventContentDTO, true, false) + val event = MapperProvider.eventMapper(selfUserId).fromEventContentDTO("", eventContentDTO, true, false) if (event is Event.Conversation) { commitBundleEventReceiver.onEvent(event) } diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/Event.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/Event.kt index 5e72aa53897..17297a83053 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/Event.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/Event.kt @@ -632,7 +632,7 @@ sealed class Event(open val id: String, open val transient: Boolean, open val li override val id: String, override val transient: Boolean, override val live: Boolean, - val userId: String, + val userId: UserId, val accentId: Int?, val ssoIdDeleted: Boolean?, val name: String?, @@ -645,7 +645,7 @@ sealed class Event(open val id: String, open val transient: Boolean, open val li override fun toLogMap(): Map = mapOf( typeKey to "User.Update", idKey to id.obfuscateId(), - userIdKey to userId.obfuscateId() + userIdKey to userId.toLogString() ) } diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventMapper.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventMapper.kt index 4ad6daf0078..f24e4413b3c 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventMapper.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventMapper.kt @@ -33,6 +33,7 @@ import com.wire.kalium.logic.data.event.Event.UserProperty.TypingIndicatorModeSe import com.wire.kalium.logic.data.featureConfig.FeatureConfigMapper import com.wire.kalium.logic.data.id.SubconversationId import com.wire.kalium.logic.data.id.toModel +import com.wire.kalium.logic.data.user.UserId import com.wire.kalium.logic.data.user.toModel import com.wire.kalium.logic.di.MapperProvider import com.wire.kalium.logic.util.Base64 @@ -51,12 +52,13 @@ import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.SerializationException import kotlinx.serialization.serializer -@Suppress("TooManyFunctions") +@Suppress("TooManyFunctions", "LongParameterList") class EventMapper( private val memberMapper: MemberMapper, private val connectionMapper: ConnectionMapper, private val featureConfigMapper: FeatureConfigMapper, private val roleMapper: ConversationRoleMapper, + private val selfUserId: UserId, private val receiptModeMapper: ReceiptModeMapper = MapperProvider.receiptModeMapper(), private val clientMapper: ClientMapper = MapperProvider.clientMapper() ) { @@ -653,7 +655,7 @@ class EventMapper( live: Boolean ) = Event.User.Update( id = id, - userId = event.userData.nonQualifiedUserId, + userId = UserId(event.userData.nonQualifiedUserId, selfUserId.domain), accentId = event.userData.accentId, ssoIdDeleted = event.userData.ssoIdDeleted, name = event.userData.name, diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventRepository.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventRepository.kt index f94d546a33f..386b2e222ba 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventRepository.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/event/EventRepository.kt @@ -22,6 +22,7 @@ import com.wire.kalium.logic.CoreFailure import com.wire.kalium.logic.NetworkFailure import com.wire.kalium.logic.StorageFailure import com.wire.kalium.logic.data.conversation.ClientId +import com.wire.kalium.logic.data.user.UserId import com.wire.kalium.logic.di.MapperProvider import com.wire.kalium.logic.feature.CurrentClientIdProvider import com.wire.kalium.logic.functional.Either @@ -81,7 +82,8 @@ class EventDataSource( private val notificationApi: NotificationApi, private val metadataDAO: MetadataDAO, private val currentClientId: CurrentClientIdProvider, - private val eventMapper: EventMapper = MapperProvider.eventMapper() + private val selfUserId: UserId, + private val eventMapper: EventMapper = MapperProvider.eventMapper(selfUserId) ) : EventRepository { // TODO(edge-case): handle Missing notification response (notify user that some messages are missing) diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/team/TeamRepository.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/team/TeamRepository.kt index 3f0289b3c27..ebb11a8bb2a 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/team/TeamRepository.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/team/TeamRepository.kt @@ -91,19 +91,16 @@ internal class TeamDataSource( */ if (teamMemberList.hasMore.not()) { teamMemberList.members.map { teamMember -> - userMapper.fromTeamMemberToDaoModel( - teamId = teamId, - nonQualifiedUserId = teamMember.nonQualifiedUserId, - permissionCode = teamMember.permissions?.own, - userDomain = userDomain, - ) + val userId = QualifiedIDEntity(teamMember.nonQualifiedUserId, userDomain) + val userType = userTypeEntityTypeMapper.teamRoleCodeToUserType(teamMember.permissions?.own) + userId to userType } } else { listOf() } }.flatMap { teamMembers -> wrapStorageRequest { - userDAO.upsertTeamMembersTypes(teamMembers) + userDAO.upsertTeamMemberUserTypes(teamMembers.toMap()) } } @@ -123,13 +120,9 @@ internal class TeamDataSource( override suspend fun updateMemberRole(teamId: String, userId: String, permissionCode: Int?): Either { return wrapStorageRequest { - val user = userMapper.fromTeamMemberToDaoModel( - teamId = TeamId(teamId), - nonQualifiedUserId = userId, - userDomain = selfUserId.domain, - permissionCode = permissionCode - ) - userDAO.upsertTeamMembersTypes(listOf(user)) + userDAO.upsertTeamMemberUserTypes(mapOf( + QualifiedIDEntity(userId, selfUserId.domain) to userTypeEntityTypeMapper.teamRoleCodeToUserType(permissionCode) + )) } } @@ -139,7 +132,7 @@ internal class TeamDataSource( teamId = teamId, userId = userId, ) - }.flatMap { _ -> + }.flatMap { _ -> // TODO jacob why dow we fetch team member info if we don't use the response? wrapApiRequest { userDetailsApi.getUserInfo(userId = QualifiedID(userId, selfUserId.domain)) } .flatMap { userProfileDTO -> wrapStorageRequest { @@ -154,7 +147,7 @@ internal class TeamDataSource( isService = userProfileDTO.service != null ) ) - userDAO.insertUser(userEntity) + userDAO.upsertUser(userEntity) } } } diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserMapper.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserMapper.kt index 530b50877ad..c843f1579f1 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserMapper.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserMapper.kt @@ -24,11 +24,9 @@ import com.wire.kalium.logic.data.id.NetworkQualifiedId import com.wire.kalium.logic.data.id.TeamId import com.wire.kalium.logic.data.id.toDao import com.wire.kalium.logic.data.id.toModel -import com.wire.kalium.logic.data.user.type.UserEntityTypeMapper import com.wire.kalium.logic.di.MapperProvider import com.wire.kalium.network.api.base.authenticated.self.UserUpdateRequest import com.wire.kalium.network.api.base.model.AssetSizeDTO -import com.wire.kalium.network.api.base.model.NonQualifiedUserId import com.wire.kalium.network.api.base.model.SelfUserDTO import com.wire.kalium.network.api.base.model.SupportedProtocolDTO import com.wire.kalium.network.api.base.model.UserAssetDTO @@ -38,6 +36,7 @@ import com.wire.kalium.network.api.base.model.getCompleteAssetOrNull import com.wire.kalium.network.api.base.model.getPreviewAssetOrNull import com.wire.kalium.persistence.dao.BotIdEntity import com.wire.kalium.persistence.dao.ConnectionEntity +import com.wire.kalium.persistence.dao.PartialUserEntity import com.wire.kalium.persistence.dao.QualifiedIDEntity import com.wire.kalium.persistence.dao.SupportedProtocolEntity import com.wire.kalium.persistence.dao.UserAvailabilityStatusEntity @@ -68,14 +67,7 @@ interface UserMapper { updateRequest: UserUpdateRequest ): UserEntity - fun fromTeamMemberToDaoModel( - teamId: TeamId, - nonQualifiedUserId: NonQualifiedUserId, - permissionCode: Int?, - userDomain: String, - ): UserEntity - - fun fromUserUpdateEventToUserEntity(event: Event.User.Update, userEntity: UserEntity): UserEntity + fun fromUserUpdateEventToPartialUserEntity(event: Event.User.Update): PartialUserEntity fun fromUserProfileDtoToUserEntity( userProfile: UserProfileDTO, @@ -88,8 +80,7 @@ interface UserMapper { internal class UserMapperImpl( private val idMapper: IdMapper = MapperProvider.idMapper(), private val availabilityStatusMapper: AvailabilityStatusMapper = MapperProvider.availabilityStatusMapper(), - private val connectionStateMapper: ConnectionStateMapper = MapperProvider.connectionStateMapper(), - private val userEntityTypeMapper: UserEntityTypeMapper = MapperProvider.userTypeEntityMapper() + private val connectionStateMapper: ConnectionStateMapper = MapperProvider.connectionStateMapper() ) : UserMapper { override fun fromUserEntityToSelfUser(userEntity: UserEntity) = with(userEntity) { @@ -128,7 +119,7 @@ internal class UserMapperImpl( deleted = false, expiresAt = expiresAt, defederated = false, - supportedProtocols = supportedProtocols?.toDao(), + supportedProtocols = supportedProtocols?.toDao() ?: setOf(SupportedProtocolEntity.PROTEUS), activeOneOnOneConversationId = null ) } @@ -184,39 +175,6 @@ internal class UserMapperImpl( ) ) - /** - * Null and default/hardcoded values will be replaced later when fetching known users. - */ - override fun fromTeamMemberToDaoModel( - teamId: TeamId, - nonQualifiedUserId: NonQualifiedUserId, - permissionCode: Int?, - userDomain: String, - ): UserEntity = - UserEntity( - id = QualifiedIDEntity( - value = nonQualifiedUserId, - domain = userDomain - ), - name = null, - handle = null, - email = null, - phone = null, - accentId = 1, - team = teamId.value, - connectionStatus = ConnectionEntity.State.ACCEPTED, - previewAssetId = null, - completeAssetId = null, - availabilityStatus = UserAvailabilityStatusEntity.NONE, - userType = userEntityTypeMapper.teamRoleCodeToUserType(permissionCode), - botService = null, - deleted = false, - expiresAt = null, - defederated = false, - supportedProtocols = null, - activeOneOnOneConversationId = null - ) - override fun fromUserProfileDtoToUserEntity( userProfile: UserProfileDTO, connectionState: ConnectionEntity.State, @@ -244,21 +202,16 @@ internal class UserMapperImpl( activeOneOnOneConversationId = null ) - override fun fromUserUpdateEventToUserEntity(event: Event.User.Update, userEntity: UserEntity): UserEntity { - return userEntity.let { persistedEntity -> - persistedEntity.copy( - email = event.email ?: persistedEntity.email, - name = event.name ?: persistedEntity.name, - handle = event.handle ?: persistedEntity.handle, - accentId = event.accentId ?: persistedEntity.accentId, - previewAssetId = event.previewAssetId?.let { QualifiedIDEntity(it, persistedEntity.id.domain) } - ?: persistedEntity.previewAssetId, - completeAssetId = event.completeAssetId?.let { QualifiedIDEntity(it, persistedEntity.id.domain) } - ?: persistedEntity.completeAssetId, - supportedProtocols = event.supportedProtocols?.toDao() ?: persistedEntity.supportedProtocols - ) - } - } + override fun fromUserUpdateEventToPartialUserEntity(event: Event.User.Update): PartialUserEntity = + PartialUserEntity( + email = event.email, + name = event.name, + handle = event.handle, + accentId = event.accentId, + previewAssetId = event.previewAssetId?.let { QualifiedIDEntity(it, event.userId.domain) }, + completeAssetId = event.completeAssetId?.let { QualifiedIDEntity(it, event.userId.domain) }, + supportedProtocols = event.supportedProtocols?.toDao() + ) /** * Default values and marked as [UserEntity.hasIncompleteMetadata] = true. diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserRepository.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserRepository.kt index 354b0a8ce22..ea50a8b7188 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserRepository.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/data/user/UserRepository.kt @@ -28,7 +28,6 @@ import com.wire.kalium.logic.data.id.ConversationId import com.wire.kalium.logic.data.id.IdMapper import com.wire.kalium.logic.data.id.NetworkQualifiedId import com.wire.kalium.logic.data.id.QualifiedID -import com.wire.kalium.logic.data.id.QualifiedIdMapper import com.wire.kalium.logic.data.id.toApi import com.wire.kalium.logic.data.id.toDao import com.wire.kalium.logic.data.id.toModel @@ -149,7 +148,6 @@ internal class UserDataSource internal constructor( private val userDetailsApi: UserDetailsApi, private val sessionRepository: SessionRepository, private val selfUserId: UserId, - private val qualifiedIdMapper: QualifiedIdMapper, private val selfTeamIdProvider: SelfTeamIdProvider, private val idMapper: IdMapper = MapperProvider.idMapper(), private val userMapper: UserMapper = MapperProvider.userMapper(), @@ -177,7 +175,7 @@ internal class UserDataSource internal constructor( updateSelfUserProviderAccountInfo(userDTO) .map { userMapper.fromSelfUserDtoToUserEntity(userDTO).copy(connectionStatus = ConnectionEntity.State.ACCEPTED) } .flatMap { userEntity -> - wrapStorageRequest { userDAO.insertUser(userEntity) } + wrapStorageRequest { userDAO.upsertUser(userEntity) } .flatMap { wrapStorageRequest { metadataDAO.insertValue(Json.encodeToString(userEntity.id), SELF_USER_ID_KEY) } } @@ -244,9 +242,7 @@ internal class UserDataSource internal constructor( } private suspend fun persistIncompleteUsers(usersFailed: List) = wrapStorageRequest { - usersFailed.map { userMapper.fromFailedUserToEntity(it) }.forEach { - userDAO.insertUser(it) - } + userDAO.insertOrIgnoreUsers(usersFailed.map { userMapper.fromFailedUserToEntity(it) }) } private suspend fun persistUsers(listUserProfileDTO: List) = wrapStorageRequest { @@ -256,7 +252,7 @@ internal class UserDataSource internal constructor( .filter { userProfileDTO -> isTeamMember(selfUserTeamId, userProfileDTO, selfUserDomain) } val otherUsers = listUserProfileDTO .filter { userProfileDTO -> !isTeamMember(selfUserTeamId, userProfileDTO, selfUserDomain) } - userDAO.upsertTeamMembers( + userDAO.upsertUsers( teamMembers.map { userProfileDTO -> userMapper.fromUserProfileDtoToUserEntity( userProfile = userProfileDTO, @@ -347,7 +343,7 @@ internal class UserDataSource internal constructor( .map { userMapper.fromUpdateRequestToDaoModel(user, updateRequest) } .flatMap { userEntity -> wrapStorageRequest { - userDAO.updateUser(userEntity) + userDAO.upsertUser(userEntity) }.map { userMapper.fromUserEntityToSelfUser(userEntity) } } } @@ -450,10 +446,13 @@ internal class UserDataSource internal constructor( } override suspend fun updateUserFromEvent(event: Event.User.Update): Either = wrapStorageRequest { - val userId = qualifiedIdMapper.fromStringToQualifiedID(event.userId) - val user = - userDAO.getUserByQualifiedID(userId.toDao()).firstOrNull() ?: return Either.Left(StorageFailure.DataNotFound) - userDAO.updateUser(userMapper.fromUserUpdateEventToUserEntity(event, user)) + userDAO.updateUser(event.userId.toDao(), userMapper.fromUserUpdateEventToPartialUserEntity(event)) + }.flatMap { updated -> + if (!updated) { + Either.Left(StorageFailure.DataNotFound) + } else { + Either.Right(Unit) + } } override suspend fun removeUser(userId: UserId): Either { diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/di/MapperProvider.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/di/MapperProvider.kt index a04708ff6eb..789995b4b3d 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/di/MapperProvider.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/di/MapperProvider.kt @@ -106,7 +106,7 @@ internal object MapperProvider { fun availabilityStatusMapper(): AvailabilityStatusMapper = AvailabilityStatusMapperImpl() fun connectionStateMapper(): ConnectionStateMapper = ConnectionStateMapperImpl() fun userMapper(): UserMapper = UserMapperImpl( - idMapper(), availabilityStatusMapper(), connectionStateMapper(), userTypeEntityMapper() + idMapper(), availabilityStatusMapper(), connectionStateMapper() ) fun userTypeMapper(): DomainUserTypeMapper = DomainUserTypeMapperImpl() @@ -135,11 +135,12 @@ internal object MapperProvider { fun sendMessageFailureMapper(): SendMessageFailureMapper = SendMessageFailureMapperImpl() fun assetMapper(): AssetMapper = AssetMapperImpl() fun encryptionAlgorithmMapper(): EncryptionAlgorithmMapper = EncryptionAlgorithmMapper() - fun eventMapper(): EventMapper = EventMapper( + fun eventMapper(selfUserId: UserId): EventMapper = EventMapper( memberMapper(), connectionMapper(), featureConfigMapper(), conversationRoleMapper(), + selfUserId, receiptModeMapper(), ) diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt index 2ea6d272e0e..68afc50fde7 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt @@ -636,7 +636,6 @@ class UserSessionScope internal constructor( authenticatedNetworkContainer.userDetailsApi, globalScope.sessionRepository, userId, - qualifiedIdMapper, selfTeamId ) @@ -1007,7 +1006,7 @@ class UserSessionScope internal constructor( private val eventRepository: EventRepository get() = EventDataSource( - authenticatedNetworkContainer.notificationApi, userStorage.database.metadataDAO, clientIdProvider + authenticatedNetworkContainer.notificationApi, userStorage.database.metadataDAO, clientIdProvider, userId ) private val mlsMigrator: MLSMigrator diff --git a/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/conversation/RenameConversationUseCase.kt b/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/conversation/RenameConversationUseCase.kt index 4ec5e031b19..862cf2277e1 100644 --- a/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/conversation/RenameConversationUseCase.kt +++ b/logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/conversation/RenameConversationUseCase.kt @@ -47,7 +47,7 @@ internal class RenameConversationUseCaseImpl( val persistMessage: PersistMessageUseCase, private val renamedConversationEventHandler: RenamedConversationEventHandler, val selfUserId: UserId, - private val eventMapper: EventMapper = MapperProvider.eventMapper() + private val eventMapper: EventMapper = MapperProvider.eventMapper(selfUserId) ) : RenameConversationUseCase { override suspend fun invoke(conversationId: ConversationId, conversationName: String): RenamingResult { return conversationRepository.changeConversationName(conversationId, conversationName) diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepositoryTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepositoryTest.kt index 053ca9a9614..ec236d12174 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepositoryTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/connection/ConnectionRepositoryTest.kt @@ -137,7 +137,7 @@ class ConnectionRepositoryTest { .wasInvoked(once) verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::insertUser) + .suspendFunction(arrangement.userDAO::upsertUser) .with(any()) .wasInvoked(once) verify(arrangement.userDetailsApi) @@ -206,7 +206,7 @@ class ConnectionRepositoryTest { .with(any()) .wasInvoked(once) verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::insertUser) + .suspendFunction(arrangement.userDAO::upsertUser) .with(any()) .wasInvoked(once) verify(arrangement.conversationRepository) @@ -536,7 +536,7 @@ class ConnectionRepositoryTest { .then { flowOf(stubUserEntity) } given(userDAO) - .suspendFunction(userDAO::insertUser) + .suspendFunction(userDAO::upsertUser) .whenInvokedWith(any()) .then { } diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/event/EventRepositoryTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/event/EventRepositoryTest.kt index 912a1d161e5..8a29d9c3974 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/event/EventRepositoryTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/event/EventRepositoryTest.kt @@ -24,6 +24,7 @@ import com.wire.kalium.logic.data.conversation.ClientId import com.wire.kalium.logic.feature.CurrentClientIdProvider import com.wire.kalium.logic.framework.TestClient import com.wire.kalium.logic.framework.TestConversation +import com.wire.kalium.logic.framework.TestUser import com.wire.kalium.logic.functional.Either import com.wire.kalium.logic.util.shouldFail import com.wire.kalium.logic.util.shouldSucceed @@ -149,7 +150,7 @@ class EventRepositoryTest { @Mock val clientIdProvider = mock(CurrentClientIdProvider::class) - private val eventRepository: EventRepository = EventDataSource(notificationApi, metaDAO, clientIdProvider) + private val eventRepository: EventRepository = EventDataSource(notificationApi, metaDAO, clientIdProvider, TestUser.SELF.id) init { withCurrentClientIdReturning(TestClient.CLIENT_ID) diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/reaction/ReactionRepositoryTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/reaction/ReactionRepositoryTest.kt index 882386a818c..d0677566a5a 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/reaction/ReactionRepositoryTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/reaction/ReactionRepositoryTest.kt @@ -82,7 +82,7 @@ class ReactionRepositoryTest { } suspend fun insertInitialData() { - userDao.insertUser(TEST_SELF_USER_ENTITY) + userDao.upsertUser(TEST_SELF_USER_ENTITY) conversationDao.insertConversation(TEST_CONVERSATION_ENTITY) messageDao.insertOrIgnoreMessage(TEST_MESSAGE_ENTITY) } diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/team/TeamRepositoryTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/team/TeamRepositoryTest.kt index e2dc66188b8..c5b4142d858 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/team/TeamRepositoryTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/team/TeamRepositoryTest.kt @@ -122,7 +122,7 @@ class TeamRepositoryTest { // Verifies that userDAO insertUsers was called with the correct mapped values verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::upsertTeamMembersTypes) + .suspendFunction(arrangement.userDAO::upsertTeamMemberUserTypes) .with(any()) .wasInvoked(exactly = once) @@ -236,7 +236,7 @@ class TeamRepositoryTest { result.shouldSucceed() verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::insertUser) + .suspendFunction(arrangement.userDAO::upsertUser) .with(any()) .wasInvoked(once) } diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserMapperTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserMapperTest.kt index 2221010d26c..4e6ccc95c09 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserMapperTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserMapperTest.kt @@ -18,22 +18,13 @@ package com.wire.kalium.logic.data.user -import com.wire.kalium.logic.data.id.TeamId -import com.wire.kalium.logic.data.team.TeamRole -import com.wire.kalium.logic.framework.TestTeam import com.wire.kalium.logic.framework.TestUser -import com.wire.kalium.network.api.base.authenticated.TeamsApi import com.wire.kalium.persistence.dao.ConnectionEntity -import com.wire.kalium.persistence.dao.QualifiedIDEntity -import com.wire.kalium.persistence.dao.UserAvailabilityStatusEntity -import com.wire.kalium.persistence.dao.UserEntity import com.wire.kalium.persistence.dao.UserTypeEntity -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals -@OptIn(ExperimentalCoroutinesApi::class) class UserMapperTest { @Test @@ -56,48 +47,6 @@ class UserMapperTest { assertEquals(expectedResult, result) } - @Test - fun givenTeamMemberApiModel_whenMappingFromApiResponse_thenDaoModelIsReturned() = runTest { - val apiModel = TestTeam.memberDTO( - nonQualifiedUserId = "teamMember1", - permissions = TeamsApi.Permissions(TeamRole.Member.value, TeamRole.Member.value) - ) - - val expectedResult = UserEntity( - id = QualifiedIDEntity( - value = "teamMember1", - domain = "userDomain" - ), - name = null, - handle = null, - email = null, - phone = null, - accentId = 1, - team = "teamId", - connectionStatus = ConnectionEntity.State.ACCEPTED, - previewAssetId = null, - completeAssetId = null, - availabilityStatus = UserAvailabilityStatusEntity.NONE, - userType = UserTypeEntity.STANDARD, - botService = null, - deleted = false, - expiresAt = null, - defederated = false, - supportedProtocols = null, - activeOneOnOneConversationId = null - ) - val (_, userMapper) = Arrangement().arrange() - - val result = userMapper.fromTeamMemberToDaoModel( - teamId = TeamId("teamId"), - userDomain = "userDomain", - nonQualifiedUserId = "teamMember1", - permissionCode = apiModel.permissions?.own - ) - - assertEquals(expectedResult, result) - } - private class Arrangement { private val userMapper = UserMapperImpl() diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserRepositoryTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserRepositoryTest.kt index 3cf46bf332b..315be690161 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserRepositoryTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/data/user/UserRepositoryTest.kt @@ -35,7 +35,6 @@ import com.wire.kalium.logic.framework.TestUser import com.wire.kalium.logic.framework.TestUser.LIST_USERS_DTO import com.wire.kalium.logic.functional.Either import com.wire.kalium.logic.functional.getOrNull -import com.wire.kalium.logic.sync.receiver.UserEventReceiverTest import com.wire.kalium.logic.test_util.TestNetworkResponseError import com.wire.kalium.logic.util.shouldFail import com.wire.kalium.logic.util.shouldSucceed @@ -63,6 +62,7 @@ import io.mockative.given import io.mockative.matching import io.mockative.mock import io.mockative.once +import io.mockative.twice import io.mockative.verify import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow @@ -128,25 +128,16 @@ class UserRepositoryTest { @Test fun givenAUserEvent_whenPersistingTheUser_thenShouldSucceed() = runTest { val (arrangement, userRepository) = Arrangement() - .withMapperQualifiedUserId() + .withUpdateUserReturning(true) .arrange() - val result = userRepository.updateUserFromEvent(TestEvent.updateUser(userId = UserEventReceiverTest.SELF_USER_ID)) + val result = userRepository.updateUserFromEvent(TestEvent.updateUser(userId = SELF_USER.id)) with(result) { shouldSucceed() - - verify(arrangement.qualifiedIdMapper) - .function(arrangement.qualifiedIdMapper::fromStringToQualifiedID) - .with(any()) - .wasInvoked(exactly = once) - verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::getUserByQualifiedID) - .with(any()) - .wasInvoked(exactly = once) verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::updateUser) - .with(any()) + .with(any(), any()) .wasInvoked(exactly = once) } } @@ -154,27 +145,18 @@ class UserRepositoryTest { @Test fun givenAUserEvent_whenPersistingTheUserAndNotExists_thenShouldFail() = runTest { val (arrangement, userRepository) = Arrangement() - .withMapperQualifiedUserId() - .withUserDaoReturning(null) + .withUpdateUserReturning(false) .arrange() - val result = userRepository.updateUserFromEvent(TestEvent.updateUser(userId = UserEventReceiverTest.SELF_USER_ID)) + val result = userRepository.updateUserFromEvent(TestEvent.updateUser(userId = SELF_USER.id)) with(result) { shouldFail() - verify(arrangement.qualifiedIdMapper) - .function(arrangement.qualifiedIdMapper::fromStringToQualifiedID) - .with(any()) - .wasInvoked(exactly = once) - verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::getUserByQualifiedID) - .with(any()) - .wasInvoked(exactly = once) verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::updateUser) - .with(any()) - .wasNotInvoked() + .with(any(), any()) + .wasInvoked(exactly = once) } } @@ -296,14 +278,10 @@ class UserRepositoryTest { .suspendFunction(arrangement.userDetailsApi::getUserInfo) .with(any()) .wasInvoked(exactly = once) - verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::upsertTeamMembers) - .with(any()) - .wasInvoked(exactly = once) verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::upsertUsers) .with(any()) - .wasInvoked(exactly = once) + .wasInvoked() } } @@ -321,10 +299,6 @@ class UserRepositoryTest { .suspendFunction(arrangement.userDetailsApi::getUserInfo) .with(any()) .wasNotInvoked() - verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::upsertTeamMembers) - .with(any()) - .wasNotInvoked() verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::upsertUsers) .with(any()) @@ -346,14 +320,10 @@ class UserRepositoryTest { .suspendFunction(arrangement.userDetailsApi::getUserInfo) .with(any()) .wasInvoked(exactly = once) - verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::upsertTeamMembers) - .with(any()) - .wasInvoked(exactly = once) verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::upsertUsers) .with(any()) - .wasInvoked(exactly = once) + .wasInvoked(exactly = twice) } val resultSecondTime = userRepository.getKnownUser(TestUser.USER_ID) @@ -362,10 +332,6 @@ class UserRepositoryTest { .suspendFunction(arrangement.userDetailsApi::getUserInfo) .with(any()) .wasNotInvoked() - verify(arrangement.userDAO) - .suspendFunction(arrangement.userDAO::upsertTeamMembers) - .with(any()) - .wasNotInvoked() verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::upsertUsers) .with(any()) @@ -393,7 +359,7 @@ class UserRepositoryTest { verify(arrangement.userDAO) .suspendFunction(arrangement.userDAO::upsertUsers) .with(matching { - it.first().name != null + it.firstOrNull()?.name != null }) .wasInvoked(exactly = once) } @@ -659,7 +625,6 @@ class UserRepositoryTest { userDetailsApi, sessionRepository, selfUserId, - qualifiedIdMapper, selfTeamIdProvider ) } @@ -697,6 +662,13 @@ class UserRepositoryTest { .thenReturn(flowOf(userEntities)) } + fun withUpdateUserReturning(updated: Boolean) = apply { + given(userDAO) + .suspendFunction(userDAO::updateUser) + .whenInvokedWith(any(), any()) + .thenReturn(updated) + } + fun withSuccessfulGetUsersInfo() = apply { given(userDetailsApi) .suspendFunction(userDetailsApi::getUserInfo) @@ -837,6 +809,6 @@ class UserRepositoryTest { } private companion object { - val SELF_USER = TestUser.SELF_USER_DTO + val SELF_USER = TestUser.SELF } } diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/framework/TestEvent.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/framework/TestEvent.kt index f3b4e3091b8..1c85bdef3fc 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/framework/TestEvent.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/framework/TestEvent.kt @@ -94,7 +94,7 @@ object TestEvent { fun userDelete(eventId: String = "eventId", userId: UserId) = Event.User.UserDelete(false, false, eventId, userId) fun updateUser(eventId: String = "eventId", userId: UserId) = Event.User.Update( eventId, - false, false, userId.toString(), null, false, "newName", null, null, null, null, null + false, false, userId, null, false, "newName", null, null, null, null, null ) fun newClient(eventId: String = "eventId", clientId: ClientId = ClientId("client")) = Event.User.NewClient( diff --git a/logic/src/commonTest/kotlin/com/wire/kalium/logic/sync/receiver/conversation/message/ReceiptMessageHandlerTest.kt b/logic/src/commonTest/kotlin/com/wire/kalium/logic/sync/receiver/conversation/message/ReceiptMessageHandlerTest.kt index ee32eb25f12..4d28cba895b 100644 --- a/logic/src/commonTest/kotlin/com/wire/kalium/logic/sync/receiver/conversation/message/ReceiptMessageHandlerTest.kt +++ b/logic/src/commonTest/kotlin/com/wire/kalium/logic/sync/receiver/conversation/message/ReceiptMessageHandlerTest.kt @@ -64,8 +64,8 @@ class ReceiptMessageHandlerTest { private val receiptMessageHandler = ReceiptMessageHandlerImpl(SELF_USER_ID, receiptRepository, messageRepository) private suspend fun insertTestData() { - userDatabase.builder.userDAO.insertUser(TestUser.ENTITY.copy(id = SELF_USER_ID_ENTITY)) - userDatabase.builder.userDAO.insertUser(TestUser.ENTITY.copy(id = OTHER_USER_ID_ENTITY)) + userDatabase.builder.userDAO.upsertUser(TestUser.ENTITY.copy(id = SELF_USER_ID_ENTITY)) + userDatabase.builder.userDAO.upsertUser(TestUser.ENTITY.copy(id = OTHER_USER_ID_ENTITY)) userDatabase.builder.conversationDAO.insertConversation(CONVERSATION_ENTITY) userDatabase.builder.messageDAO.insertOrIgnoreMessage(MESSAGE_ENTITY) } diff --git a/persistence/src/commonMain/db_user/com/wire/kalium/persistence/Users.sq b/persistence/src/commonMain/db_user/com/wire/kalium/persistence/Users.sq index 3fbb7f1171d..3e523ccab45 100644 --- a/persistence/src/commonMain/db_user/com/wire/kalium/persistence/Users.sq +++ b/persistence/src/commonMain/db_user/com/wire/kalium/persistence/Users.sq @@ -46,36 +46,39 @@ email = excluded.email, phone = excluded.phone, accent_id = excluded.accent_id, team = excluded.team, -connection_status = excluded.connection_status, preview_asset_id = excluded.preview_asset_id, complete_asset_id = excluded.complete_asset_id, -user_type = excluded.user_type, bot_service = excluded.bot_service, deleted = excluded.deleted, incomplete_metadata = excluded.incomplete_metadata, expires_at = excluded.expires_at, defederated = 0, -supported_protocols = excluded.supported_protocols, -active_one_on_one_conversation_id = excluded.active_one_on_one_conversation_id; +supported_protocols = excluded.supported_protocols; insertOrIgnoreUser: INSERT OR IGNORE INTO User(qualified_id, name, handle, email, phone, accent_id, team, connection_status, preview_asset_id, complete_asset_id, user_type, bot_service, deleted, incomplete_metadata, expires_at, supported_protocols) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); -updateUser: -UPDATE User -SET name = ?, handle = ?, email = ?, phone = ?, accent_id = ?, team = ?, preview_asset_id = ?, complete_asset_id = ?, user_type = ?, bot_service = ?, incomplete_metadata = ?, expires_at = ? -WHERE qualified_id = ?; - -updateTeamMemberUser: +updateUser { UPDATE User -SET name = ?, handle = ?, email = ?, phone = ?, accent_id = ?, team = ?, preview_asset_id = ?, complete_asset_id = ?, bot_service = ?, incomplete_metadata = 0 +SET +name = :name, name = coalece(:name, name), +handle = :handle, handle = coalece(:handle, handle), +email = :email, email = coalece(:email, email), +accent_id = :accent_id, accent_id = coalece(:accent_id, accent_id), +preview_asset_id = :preview_asset_id, preview_asset_id = coalece(:preview_asset_id, preview_asset_id), +complete_asset_id = :complete_asset_id, complete_asset_id = coalece(:complete_asset_id, complete_asset_id), +supported_protocols = :supported_protocols, supported_protocols = coalece(:supported_protocols, supported_protocols) WHERE qualified_id = ?; +SELECT changes(); +} -updateTeamMemberType: -UPDATE User -SET team = ?, connection_status = ?, user_type = ? -WHERE qualified_id = ?; +upsertTeamMemberUserType: +INSERT INTO User(qualified_id, connection_status, user_type) +VALUES(?, ?, ?) +ON CONFLICT(qualified_id) DO UPDATE SET +connection_status = excluded.connection_status, +user_type = excluded.user_type; markUserAsDeleted: UPDATE User @@ -91,11 +94,6 @@ insertOrIgnoreUserId: INSERT OR IGNORE INTO User(qualified_id, incomplete_metadata) VALUES(?, 1); -updateSelfUser: -UPDATE User -SET name = ?, handle = ?, email = ?, accent_id = ?, preview_asset_id = ?, complete_asset_id = ? -WHERE qualified_id = ?; - insertOrIgnoreUserIdWithConnectionStatus: INSERT OR IGNORE INTO User(qualified_id, connection_status) VALUES(?, ?); diff --git a/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAO.kt b/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAO.kt index fdc4e9a9ccd..ecb050b575d 100644 --- a/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAO.kt +++ b/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAO.kt @@ -94,6 +94,16 @@ data class BotIdEntity( val provider: String ) +data class PartialUserEntity( + val name: String?, + val handle: String?, + val email: String?, + val accentId: Int?, + val previewAssetId: UserAssetIdEntity?, + val completeAssetId: UserAssetIdEntity?, + val supportedProtocols: Set? +) + enum class UserTypeEntity { /**Team member with owner permissions */ @@ -145,50 +155,49 @@ internal typealias UserAssetIdEntity = QualifiedIDEntity @Suppress("TooManyFunctions") interface UserDAO { - /** - * Inserts a new user into the local storage - */ - suspend fun insertUser(user: UserEntity) - /** * Inserts each user into the local storage or ignores if already exists */ suspend fun insertOrIgnoreUsers(users: List) /** - * This will update all columns, except [ConnectionEntity.State] or insert a new record with default value - * [ConnectionEntity.State.NOT_CONNECTED] - * An upsert operation is a one that tries to update a record and if fails (not rows affected by change) inserts instead. - * In this case as the transaction can be executed many times, we need to take care for not deleting old data. + * Perform a partial update of an existing user. Only non-null values will be updated otherwise + * the existing value is kept. + * + * @return true if the user was updated */ - suspend fun upsertUsers(users: List) + suspend fun updateUser(id: UserIDEntity, update: PartialUserEntity): Boolean /** - * This will update [UserEntity.team], [UserEntity.userType], [UserEntity.connectionStatus] to [ConnectionEntity.State.ACCEPTED] - * or insert a new record with default values for other columns. + * This will update all columns (or insert a new record), except: + * - [ConnectionEntity.State] + * - [UserEntity.userType] + * - [UserEntity.activeOneOnOneConversationId] + * * An upsert operation is a one that tries to update a record and if fails (not rows affected by change) inserts instead. - * In this case when trying to insert a member, we could already have the record, so we need to pass only the data needed. + * In this case as the transaction can be executed many times, we need to take care for not deleting old data. */ - suspend fun upsertTeamMembersTypes(users: List) + suspend fun upsertUser(user: UserEntity) /** - * This will update all columns, except [UserEntity.userType] or insert a new record with default values + * This will update all columns (or insert a new record), except: + * - [ConnectionEntity.State] + * - [UserEntity.userType] + * - [UserEntity.activeOneOnOneConversationId] + * * An upsert operation is a one that tries to update a record and if fails (not rows affected by change) inserts instead. * In this case as the transaction can be executed many times, we need to take care for not deleting old data. */ - suspend fun upsertTeamMembers(users: List) + suspend fun upsertUsers(users: List) /** - * This will update a user record corresponding to the User, - * The Fields to update are: - * [UserEntity.name] - * [UserEntity.handle] - * [UserEntity.email] - * [UserEntity.accentId] - * [UserEntity.previewAssetId] - * [UserEntity.completeAssetId] + * This will update [UserEntity.team], [UserEntity.userType], [UserEntity.connectionStatus] to [ConnectionEntity.State.ACCEPTED] + * or insert a new record. + * + * An upsert operation is a one that tries to update a record and if fails (not rows affected by change) inserts instead. + * In this case when trying to insert a member, we could already have the record, so we need to pass only the data needed. */ - suspend fun updateUser(user: UserEntity) + suspend fun upsertTeamMemberUserTypes(users: Map) suspend fun getAllUsers(): Flow> suspend fun observeAllUsersByConnectionStatus(connectionState: ConnectionEntity.State): Flow> suspend fun getUserByQualifiedID(qualifiedID: QualifiedIDEntity): Flow diff --git a/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAOImpl.kt b/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAOImpl.kt index 949db83648b..57490b99df9 100644 --- a/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAOImpl.kt +++ b/persistence/src/commonMain/kotlin/com/wire/kalium/persistence/dao/UserDAOImpl.kt @@ -135,27 +135,8 @@ class UserDAOImpl internal constructor( ) : UserDAO { val mapper = UserMapper() - - override suspend fun insertUser(user: UserEntity) = withContext(queriesContext) { - userQueries.insertUser( - qualified_id = user.id, - name = user.name, - handle = user.handle, - email = user.email, - phone = user.phone, - accent_id = user.accentId, - team = user.team, - preview_asset_id = user.previewAssetId, - complete_asset_id = user.completeAssetId, - user_type = user.userType, - bot_service = user.botService, - incomplete_metadata = user.hasIncompleteMetadata, - expires_at = user.expiresAt, - connection_status = user.connectionStatus, - deleted = user.deleted, - supported_protocols = user.supportedProtocols, - active_one_on_one_conversation_id = user.activeOneOnOneConversationId - ) + override suspend fun upsertUser(user: UserEntity) { + upsertUsers(listOf(user)) } override suspend fun insertOrIgnoreUsers(users: List) = withContext(queriesContext) { @@ -183,130 +164,54 @@ class UserDAOImpl internal constructor( } } - override suspend fun upsertTeamMembers(users: List) = withContext(queriesContext) { - userQueries.transaction { - for (user: UserEntity in users) { - userQueries.updateTeamMemberUser( - qualified_id = user.id, - name = user.name, - handle = user.handle, - email = user.email, - phone = user.phone, - accent_id = user.accentId, - team = user.team, - preview_asset_id = user.previewAssetId, - complete_asset_id = user.completeAssetId, - bot_service = user.botService, - ) - val recordDidNotExist = userQueries.selectChanges().executeAsOne() == 0L - if (recordDidNotExist) { - userQueries.insertUser( - qualified_id = user.id, - name = user.name, - handle = user.handle, - email = user.email, - phone = user.phone, - accent_id = user.accentId, - team = user.team, - preview_asset_id = user.previewAssetId, - complete_asset_id = user.completeAssetId, - user_type = user.userType, - bot_service = user.botService, - incomplete_metadata = user.hasIncompleteMetadata, - expires_at = user.expiresAt, - connection_status = user.connectionStatus, - deleted = user.deleted, - supported_protocols = user.supportedProtocols, - active_one_on_one_conversation_id = user.activeOneOnOneConversationId - ) - } - } - } + override suspend fun updateUser(id: UserIDEntity, update: PartialUserEntity) = withContext(queriesContext) { + userQueries.updateUser( + name = update.name, + handle = update.handle, + email = update.email, + accent_id = update.accentId, + preview_asset_id = update.previewAssetId, + complete_asset_id = update.completeAssetId, + supported_protocols = update.supportedProtocols, + id + ).executeAsOne() > 0 } override suspend fun upsertUsers(users: List) = withContext(queriesContext) { userQueries.transaction { for (user: UserEntity in users) { - userQueries.updateUser( - qualified_id = user.id, - name = user.name, - handle = user.handle, - email = user.email, - phone = user.phone, - accent_id = user.accentId, - team = user.team, - preview_asset_id = user.previewAssetId, - complete_asset_id = user.completeAssetId, - user_type = user.userType, - bot_service = user.botService, - incomplete_metadata = false, - expires_at = user.expiresAt, - ) - val recordDidNotExist = userQueries.selectChanges().executeAsOne() == 0L - if (recordDidNotExist) { - userQueries.insertUser( - qualified_id = user.id, - name = user.name, - handle = user.handle, - email = user.email, - phone = user.phone, - accent_id = user.accentId, - team = user.team, - connection_status = user.connectionStatus, - preview_asset_id = user.previewAssetId, - complete_asset_id = user.completeAssetId, - user_type = user.userType, - bot_service = user.botService, - deleted = user.deleted, - incomplete_metadata = user.hasIncompleteMetadata, - expires_at = user.expiresAt, - supported_protocols = user.supportedProtocols, - active_one_on_one_conversation_id = user.activeOneOnOneConversationId - ) - } + internalInsertUser(user) } } } - override suspend fun upsertTeamMembersTypes(users: List) { + override suspend fun upsertTeamMemberUserTypes(users: Map) { userQueries.transaction { - for (user: UserEntity in users) { - userQueries.updateTeamMemberType(user.team, user.connectionStatus, user.userType, user.id) - val recordDidNotExist = userQueries.selectChanges().executeAsOne() == 0L - if (recordDidNotExist) { - userQueries.insertUser( - qualified_id = user.id, - name = user.name, - handle = user.handle, - email = user.email, - phone = user.phone, - accent_id = user.accentId, - team = user.team, - connection_status = user.connectionStatus, - preview_asset_id = user.previewAssetId, - complete_asset_id = user.completeAssetId, - user_type = user.userType, - bot_service = user.botService, - deleted = user.deleted, - incomplete_metadata = user.hasIncompleteMetadata, - expires_at = user.expiresAt, - supported_protocols = user.supportedProtocols, - active_one_on_one_conversation_id = user.activeOneOnOneConversationId - ) - } + for (user: Map.Entry in users) { + userQueries.upsertTeamMemberUserType(user.key, ConnectionEntity.State.ACCEPTED, user.value) } } } - override suspend fun updateUser(user: UserEntity) = withContext(queriesContext) { - userQueries.updateSelfUser( + private fun internalInsertUser(user: UserEntity) { + userQueries.insertUser( qualified_id = user.id, name = user.name, handle = user.handle, email = user.email, + phone = user.phone, accent_id = user.accentId, + team = user.team, preview_asset_id = user.previewAssetId, complete_asset_id = user.completeAssetId, + user_type = user.userType, + bot_service = user.botService, + incomplete_metadata = user.hasIncompleteMetadata, + expires_at = user.expiresAt, + connection_status = user.connectionStatus, + deleted = user.deleted, + supported_protocols = user.supportedProtocols, + active_one_on_one_conversation_id = user.activeOneOnOneConversationId ) } diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseExporterTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseExporterTest.kt index ab9143dc53d..41aed5a54d7 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseExporterTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseExporterTest.kt @@ -50,9 +50,9 @@ class DatabaseExporterTest : BaseDatabaseTest() { runTest { with(localDB.userDAO) { - insertUser(SELF_USER) - insertUser(OTHER_USER) - insertUser(OTHER_USER_2) + upsertUser(SELF_USER) + upsertUser(OTHER_USER) + upsertUser(OTHER_USER_2) } with(localDB.conversationDAO) { diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseImporterTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseImporterTest.kt index bc2ae29bb0a..dda189d6712 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseImporterTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/DatabaseImporterTest.kt @@ -504,7 +504,7 @@ class DatabaseImporterTest : BaseDatabaseTest() { val uniqueBackupUsers = backupDatabaseDataGenerator.generateAndInsertUsers(uniqueBackupUsersAmount) uniqueBackupUsers.forEach { userEntity -> - backupDatabaseBuilder.userDAO.insertUser(userEntity) + backupDatabaseBuilder.userDAO.upsertUser(userEntity) } // when diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/UserDatabaseDataGenerator.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/UserDatabaseDataGenerator.kt index ff7f5d7ded2..ba3d983aebd 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/UserDatabaseDataGenerator.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/backup/UserDatabaseDataGenerator.kt @@ -66,7 +66,7 @@ class UserDatabaseDataGenerator( for (index in generatedMessagesCount + 1..amount) { val senderUser = generateUser() - userDatabaseBuilder.userDAO.insertUser(senderUser) + userDatabaseBuilder.userDAO.upsertUser(senderUser) val visibility = MessageEntity.Visibility.values()[index % MessageEntity.Visibility.values().size] @@ -111,7 +111,7 @@ class UserDatabaseDataGenerator( for (index in generatedAssetsCount + 1..amount) { val senderUser = generateUser() - userDatabaseBuilder.userDAO.insertUser(senderUser) + userDatabaseBuilder.userDAO.upsertUser(senderUser) val visibility = MessageEntity.Visibility.values()[index % MessageEntity.Visibility.values().size] @@ -209,7 +209,7 @@ class UserDatabaseDataGenerator( for (index in generatedMessagesCount + 1..amount) { val senderUser = generateUser() - userDatabaseBuilder.userDAO.insertUser(senderUser) + userDatabaseBuilder.userDAO.upsertUser(senderUser) val visibility = MessageEntity.Visibility.values()[index % MessageEntity.Visibility.values().size] @@ -338,7 +338,7 @@ class UserDatabaseDataGenerator( val callPrefix = "${databasePrefix}Call${generatedCallsCount}" val userEntity = generateUser() - userDatabaseBuilder.userDAO.insertUser(userEntity) + userDatabaseBuilder.userDAO.upsertUser(userEntity) val conversationType = ConversationEntity.Type.values()[generatedCallsCount % ConversationEntity.Type.values().size] val type = CallEntity.Type.values()[generatedCallsCount % CallEntity.Type.values().size] @@ -549,7 +549,7 @@ class UserDatabaseDataGenerator( for (index in generatedUsersCount + 1..amount) { val user = generateUser() - userDatabaseBuilder.userDAO.insertUser(user) + userDatabaseBuilder.userDAO.upsertUser(user) } return userDatabaseBuilder.userDAO.getAllUsers().first() diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/ConversationDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/ConversationDAOTest.kt index 3d396f0b62f..6826a99a053 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/ConversationDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/ConversationDAOTest.kt @@ -218,7 +218,7 @@ class ConversationDAOTest : BaseDatabaseTest() { fun givenAllMembersAreMlsCapable_WhenGetTeamConversationIdsReadyToBeFinalised_ThenConversationIsReturned() = runTest { val allProtocols = setOf(SupportedProtocolEntity.PROTEUS, SupportedProtocolEntity.MLS) val selfUser = user1.copy(id = selfUserId, supportedProtocols = allProtocols) - userDAO.insertUser(selfUser) + userDAO.upsertUser(selfUser) conversationDAO.insertConversation(conversationEntity6) insertTeamUserAndMember(team, user2.copy(supportedProtocols = allProtocols), conversationEntity6.id) @@ -233,7 +233,7 @@ class ConversationDAOTest : BaseDatabaseTest() { fun givenOnlySomeMembersAreMlsCapable_WhenGetTeamConversationIdsReadyToBeFinalised_ThenConversationIsNotReturned() = runTest { val allProtocols = setOf(SupportedProtocolEntity.PROTEUS, SupportedProtocolEntity.MLS) val selfUser = user1.copy(id = selfUserId, supportedProtocols = allProtocols) - userDAO.insertUser(selfUser) + userDAO.upsertUser(selfUser) conversationDAO.insertConversation(conversationEntity5) insertTeamUserAndMember(team, user2.copy(supportedProtocols = allProtocols), conversationEntity5.id) @@ -488,7 +488,7 @@ class ConversationDAOTest : BaseDatabaseTest() { teamDAO.insertTeam(team) conversationDAO.insertConversation(conversation) - userDAO.insertUser(user1) + userDAO.upsertUser(user1) val messages = buildList { repeat(10) { @@ -703,9 +703,9 @@ class ConversationDAOTest : BaseDatabaseTest() { date = secondRemovalDate, conversationId = conversationEntity1.id ) - userDAO.insertUser(user1) - userDAO.insertUser(user2) - userDAO.insertUser(user3) + userDAO.upsertUser(user1) + userDAO.upsertUser(user2) + userDAO.upsertUser(user3) messageDAO.insertOrIgnoreMessage(message1) messageDAO.insertOrIgnoreMessage(message2) @@ -727,9 +727,9 @@ class ConversationDAOTest : BaseDatabaseTest() { memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member3, conversationEntity1.id) memberDAO.insertMember(mySelfMember, conversationEntity1.id) - userDAO.insertUser(user1) - userDAO.insertUser(user2) - userDAO.insertUser(user3) + userDAO.upsertUser(user1) + userDAO.upsertUser(user2) + userDAO.upsertUser(user3) memberDAO.deleteMemberByQualifiedID(member3.user, conversationEntity1.id) val removalMessage = newSystemMessageEntity( @@ -799,7 +799,7 @@ class ConversationDAOTest : BaseDatabaseTest() { // given conversationDAO.insertConversation(conversationEntity3) teamDAO.insertTeam(team) - userDAO.insertUser(user2) + userDAO.upsertUser(user2) memberDAO.insertMember(MemberEntity(user2.id, MemberEntity.Role.Member), conversationEntity3.id) // when @@ -828,7 +828,7 @@ class ConversationDAOTest : BaseDatabaseTest() { // given conversationDAO.insertConversation(conversationEntity3.copy(creatorId = selfUserId.value)) teamDAO.insertTeam(team) - userDAO.insertUser(user2) + userDAO.upsertUser(user2) insertTeamUserAndMember(team, user2, conversationEntity3.id) // when @@ -892,7 +892,7 @@ class ConversationDAOTest : BaseDatabaseTest() { val instant = Clock.System.now() - userDAO.insertUser(user1) + userDAO.upsertUser(user1) newRegularMessageEntity( id = Random.nextBytes(10).decodeToString(), @@ -902,7 +902,7 @@ class ConversationDAOTest : BaseDatabaseTest() { ).also { messageDAO.insertOrIgnoreMessage(it) } // TODO: insert another message from self user to check if it is not ignored - userDAO.insertUser(user1) + userDAO.upsertUser(user1) newRegularMessageEntity( id = Random.nextBytes(10).decodeToString(), @@ -934,7 +934,7 @@ class ConversationDAOTest : BaseDatabaseTest() { toId = user1.id.value, ) - userDAO.insertUser(user1) + userDAO.upsertUser(user1) conversationDAO.insertConversation(conversation) connectionDAO.insertConnection(connectionEntity) @@ -962,7 +962,7 @@ class ConversationDAOTest : BaseDatabaseTest() { toId = user1.id.value, ) - userDAO.insertUser(user1.copy(name = null)) + userDAO.upsertUser(user1.copy(name = null)) conversationDAO.insertConversation(conversation) connectionDAO.insertConnection(connectionEntity) @@ -977,8 +977,8 @@ class ConversationDAOTest : BaseDatabaseTest() { conversationDAO.insertConversation(conversationEntity1) conversationDAO.insertConversation(conversationEntity2) - userDAO.insertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) // user with metadata - userDAO.insertUser(user2.copy(activeOneOnOneConversationId = conversationEntity2.id, name = null)) // user without metadata + userDAO.upsertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) // user with metadata + userDAO.upsertUser(user2.copy(activeOneOnOneConversationId = conversationEntity2.id, name = null)) // user without metadata memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member2, conversationEntity1.id) @@ -996,8 +996,8 @@ class ConversationDAOTest : BaseDatabaseTest() { conversationDAO.insertConversation(conversationEntity2.copy(archived = true)) conversationDAO.insertConversation(conversationEntity3.copy(archived = false)) - userDAO.insertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) - userDAO.insertUser(user2.copy(activeOneOnOneConversationId = conversationEntity2.id)) + userDAO.upsertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) + userDAO.upsertUser(user2.copy(activeOneOnOneConversationId = conversationEntity2.id)) memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member2, conversationEntity2.id) @@ -1014,8 +1014,8 @@ class ConversationDAOTest : BaseDatabaseTest() { conversationDAO.insertConversation(conversationEntity1.copy(archived = false)) conversationDAO.insertConversation(conversationEntity2.copy(archived = false)) - userDAO.insertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) - userDAO.insertUser(user2.copy(activeOneOnOneConversationId = conversationEntity2.id)) + userDAO.upsertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) + userDAO.upsertUser(user2.copy(activeOneOnOneConversationId = conversationEntity2.id)) memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member2, conversationEntity2.id) @@ -1180,8 +1180,8 @@ class ConversationDAOTest : BaseDatabaseTest() { conversationDAO.insertConversation(conversationEntity1) conversationDAO.insertConversation(conversationEntity2) - userDAO.insertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) // user active one-on-one - userDAO.insertUser(user2.copy(activeOneOnOneConversationId = null)) // user without active one-on-one + userDAO.upsertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) // user active one-on-one + userDAO.upsertUser(user2.copy(activeOneOnOneConversationId = null)) // user without active one-on-one memberDAO.insertMembersWithQualifiedId(listOf(member1, member2), conversationEntity1.id) memberDAO.insertMembersWithQualifiedId(listOf(member1, member2), conversationEntity2.id) @@ -1195,7 +1195,7 @@ class ConversationDAOTest : BaseDatabaseTest() { @Test fun givenOneOnOneConversationNotExisting_whenGettingOneOnOneConversationId_thenShouldReturnEmptyList() = runTest { // given - userDAO.insertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) + userDAO.upsertUser(user1.copy(activeOneOnOneConversationId = conversationEntity1.id)) // then assertTrue(conversationDAO.getOneOnOneConversationIdsWithOtherUser(user1.id, protocol = ConversationEntity.Protocol.PROTEUS).isEmpty()) @@ -1204,7 +1204,7 @@ class ConversationDAOTest : BaseDatabaseTest() { @Test fun givenOneOnOneConversationExisting_whenGettingOneOnOneConversationId_thenShouldRespectProtocol() = runTest { // given - userDAO.insertUser(user1) + userDAO.upsertUser(user1) conversationDAO.insertConversation(conversationEntity1) conversationDAO.insertConversation(conversationEntity2) memberDAO.insertMember(member1, conversationEntity1.id) @@ -1217,7 +1217,7 @@ class ConversationDAOTest : BaseDatabaseTest() { private suspend fun insertTeamUserAndMember(team: TeamEntity, user: UserEntity, conversationId: QualifiedIDEntity) { teamDAO.insertTeam(team) - userDAO.insertUser(user) + userDAO.upsertUser(user) // should be inserted AFTER inserting the conversation!!! memberDAO.insertMembersWithQualifiedId( listOf( diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/LastMessageListTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/LastMessageListTest.kt index 9cf0159b374..a534678d7b8 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/LastMessageListTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/LastMessageListTest.kt @@ -69,7 +69,7 @@ class LastMessageListTest: BaseDatabaseTest() { ) conversationDAO.insertConversation(conversion) - userDAO.insertUser(user) + userDAO.upsertUser(user) messageDAO.insertOrIgnoreMessage(message) messageDAO.observeLastMessages().first().also { diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/MemberDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/MemberDAOTest.kt index c326110bad1..ee84808cac4 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/MemberDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/MemberDAOTest.kt @@ -164,7 +164,7 @@ class MemberDAOTest : BaseDatabaseTest() { val member1 = TestStubs.member1 val user = TestStubs.user1.copy(connectionStatus = ConnectionEntity.State.NOT_CONNECTED) - userDAO.insertUser(user) + userDAO.upsertUser(user) conversationDAO.insertConversation(conversationEntity1) memberDAO.updateOrInsertOneOnOneMemberWithConnectionStatus( member = member1, @@ -205,7 +205,7 @@ class MemberDAOTest : BaseDatabaseTest() { val member1 = TestStubs.member1 conversationDAO.insertConversation(conversationEntity1) - userDAO.insertUser(user1.copy(connectionStatus = ConnectionEntity.State.NOT_CONNECTED)) + userDAO.upsertUser(user1.copy(connectionStatus = ConnectionEntity.State.NOT_CONNECTED)) memberDAO.updateOrInsertOneOnOneMemberWithConnectionStatus( member = member1, @@ -299,9 +299,9 @@ class MemberDAOTest : BaseDatabaseTest() { val member3 = TestStubs.member3 // given conversationDAO.insertConversation(conversationEntity1) - userDAO.insertUser(user1) - userDAO.insertUser(user2) - userDAO.insertUser(user3) + userDAO.upsertUser(user1) + userDAO.upsertUser(user2) + userDAO.upsertUser(user3) memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member2, conversationEntity1.id) memberDAO.insertMember(member3, conversationEntity1.id) @@ -328,9 +328,9 @@ class MemberDAOTest : BaseDatabaseTest() { // given conversationDAO.insertConversation(conversationEntity1) - userDAO.insertUser(user1) - userDAO.insertUser(user2) - userDAO.insertUser(user3) + userDAO.upsertUser(user1) + userDAO.upsertUser(user2) + userDAO.upsertUser(user3) memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member2, conversationEntity1.id) memberDAO.insertMember(member3, conversationEntity1.id) @@ -356,8 +356,8 @@ class MemberDAOTest : BaseDatabaseTest() { conversationDAO.insertConversation(conversationEntity1) conversationDAO.insertConversation(conversationEntity2.copy(hasIncompleteMetadata = true)) - userDAO.insertUser(user1) - userDAO.insertUser(user2) + userDAO.upsertUser(user1) + userDAO.upsertUser(user2) memberDAO.insertMember(member1, conversationEntity1.id) memberDAO.insertMember(member2, conversationEntity1.id) @@ -398,13 +398,13 @@ class MemberDAOTest : BaseDatabaseTest() { // Insert a conversation, user, and a member into the conversation to test the deletion operation val oldMember = MemberEntity(TestStubs.user3.id, MemberEntity.Role.Member) - userDAO.insertUser(TestStubs.user3) + userDAO.upsertUser(TestStubs.user3) conversationDAO.insertConversation(TestStubs.conversationEntity1) memberDAO.insertMember(oldMember, conversationID) // Ensure all new users are inserted before calling updateFullMemberList memberList.forEach { member -> - userDAO.insertUser(TestStubs.user1.copy(id = member.user)) + userDAO.upsertUser(TestStubs.user1.copy(id = member.user)) } // When @@ -435,9 +435,9 @@ class MemberDAOTest : BaseDatabaseTest() { val user2 = TestStubs.user2 val user3 = TestStubs.user3.copy(id = QualifiedIDEntity("3", secondDomain)) - userDAO.insertUser(user1) - userDAO.insertUser(user2) - userDAO.insertUser(user3) + userDAO.upsertUser(user1) + userDAO.upsertUser(user2) + userDAO.upsertUser(user3) conversationDAO.insertConversation(groupConversationEntity) @@ -470,8 +470,8 @@ class MemberDAOTest : BaseDatabaseTest() { val federatedUser = TestStubs.user1.copy(id = QualifiedIDEntity("fedid", federatedDomain)) val otherUser = TestStubs.user1.copy(id = QualifiedIDEntity("other", "other.com")) - userDAO.insertUser(federatedUser) - userDAO.insertUser(otherUser) + userDAO.upsertUser(federatedUser) + userDAO.upsertUser(otherUser) conversationDAO.insertConversation(oneOnOneConversationEntity) conversationDAO.insertConversation(otherOneOnOneConversationEntity) diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserClientDAOIntegrationTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserClientDAOIntegrationTest.kt index 3a871fc1a1b..2690fba36c2 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserClientDAOIntegrationTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserClientDAOIntegrationTest.kt @@ -46,7 +46,7 @@ class UserClientDAOIntegrationTest : BaseDatabaseTest() { @Test fun givenClientsAreInserted_whenDeletingTheUser_thenTheClientsAreDeleted() = runTest { - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertClientParam) userDAO.deleteUserByQualifiedID(user.id) diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserConversationDAOIntegrationTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserConversationDAOIntegrationTest.kt index 4305a9ded2e..8ec25c33c6e 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserConversationDAOIntegrationTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserConversationDAOIntegrationTest.kt @@ -59,7 +59,7 @@ class UserConversationDAOIntegrationTest : BaseDatabaseTest() { @Test fun givenUserExists_whenInsertingMember_thenOriginalUserDetailsAreKept() = runTest(dispatcher) { - userDAO.insertUser(user1) + userDAO.upsertUser(user1) conversationDAO.insertConversation(conversationEntity1) memberDAO.insertMember(member1, conversationEntity1.id) diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserDAOTest.kt index 5219354e83c..e3aa6da96ad 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/UserDAOTest.kt @@ -55,7 +55,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenUser_ThenUserCanBeInserted() = runTest(dispatcher) { - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) val result = db.userDAO.getUserByQualifiedID(user1.id).first() assertEquals(result, user1) } @@ -73,7 +73,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUser_ThenUserCanBeDeleted() = runTest(dispatcher) { - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) db.userDAO.deleteUserByQualifiedID(user1.id) val result = db.userDAO.getUserByQualifiedID(user1.id).first() assertNull(result) @@ -81,7 +81,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUser_ThenUserCanBeUpdated() = runTest(dispatcher) { - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) val updatedUser1 = newUserEntity(user1.id).copy( name = "John Doe", handle = "johndoe", @@ -89,7 +89,7 @@ class UserDAOTest : BaseDatabaseTest() { phone = "phone1", accentId = 1 ) - db.userDAO.updateUser(updatedUser1) + db.userDAO.upsertUser(updatedUser1) val result = db.userDAO.getUserByQualifiedID(user1.id).first() assertEquals(result, updatedUser1) } @@ -98,7 +98,7 @@ class UserDAOTest : BaseDatabaseTest() { fun givenRetrievedUser_ThenUpdatesArePropagatedThroughFlow() = runTest(dispatcher) { val collectedValues = mutableListOf() - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) val updatedUser1 = newUserEntity(user1.id).copy( name = "John Doe", @@ -111,7 +111,7 @@ class UserDAOTest : BaseDatabaseTest() { db.userDAO.getUserByQualifiedID(user1.id).take(2).collect { collectedValues.add(it) if (collectedValues.size == 1) { - db.userDAO.updateUser(updatedUser1) + db.userDAO.upsertUser(updatedUser1) } } assertEquals(user1, collectedValues[0]) @@ -121,7 +121,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUser_WhenUpdateUserHandle_ThenUserHandleIsUpdated() = runTest(dispatcher) { // given - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) val updatedHandle = "new-handle" // when @@ -483,7 +483,7 @@ class UserDAOTest : BaseDatabaseTest() { fun givenAExistingUsers_whenUpdatingTheirValuesAndRecordNotExists_ThenResultsOneUpdatedAnotherInserted() = runTest(dispatcher) { // given val newNameA = "new user naming a" - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) // when val updatedUser1 = user1.copy(name = newNameA) db.userDAO.upsertUsers(listOf(updatedUser1, user2)) @@ -495,30 +495,28 @@ class UserDAOTest : BaseDatabaseTest() { } @Test - fun givenAExistingUsers_whenUpsertingTeamMembers_ThenResultsOneUpdatedAnotherInserted() = runTest(dispatcher) { + fun givenAExistingUsers_whenUpsertingTeamMembersUserTypes_ThenUserTypeIsUpdated() = runTest(dispatcher) { // given - val newTeamId = "new user team id" - db.userDAO.insertUser(user1) + val newUserType = UserTypeEntity.ADMIN + db.userDAO.upsertUser(user1) // when - val updatedUser1 = user1.copy(team = newTeamId) - db.userDAO.upsertTeamMembersTypes(listOf(updatedUser1, user2)) + db.userDAO.upsertTeamMemberUserTypes(mapOf(user1.id to newUserType)) // then - val updated1 = db.userDAO.getUserByQualifiedID(updatedUser1.id) - val inserted2 = db.userDAO.getUserByQualifiedID(user2.id) - assertEquals(newTeamId, updated1.first()?.team) - assertNotNull(inserted2) + val updated = db.userDAO.getUserByQualifiedID(user1.id) + assertEquals(newUserType, updated.first()?.userType) + assertEquals(ConnectionEntity.State.ACCEPTED, updated.first()?.connectionStatus) } @Test - fun givenATeamMember_whenUpsertingTeamMember_ThenUserTypeShouldStayTheSame() = runTest(dispatcher) { + fun givenNotExistingUsers_whenUpsertingTeamMembersUserTypes_ThenUserIsInsertedWithCorrectUserType() = runTest(dispatcher) { // given - val externalMember = user1.copy(userType = UserTypeEntity.EXTERNAL) - db.userDAO.upsertTeamMembersTypes(listOf(externalMember)) + val newUserType = UserTypeEntity.ADMIN // when - db.userDAO.upsertTeamMembers(listOf(user1)) + db.userDAO.upsertTeamMemberUserTypes(mapOf(user1.id to newUserType)) // then - val updated1 = db.userDAO.getUserByQualifiedID(user1.id) - assertEquals(UserTypeEntity.EXTERNAL, updated1.first()?.userType) + val inserted = db.userDAO.getUserByQualifiedID(user1.id) + assertEquals(newUserType, inserted.first()?.userType) + assertEquals(ConnectionEntity.State.ACCEPTED, inserted.first()?.connectionStatus) } @Test @@ -540,7 +538,7 @@ class UserDAOTest : BaseDatabaseTest() { } // when - db.userDAO.upsertTeamMembers(listOf(teamMember)) + db.userDAO.upsertUsers(listOf(teamMember)) // then db.userDAO.getAllUsers().first().also { @@ -556,7 +554,7 @@ class UserDAOTest : BaseDatabaseTest() { fun givenAExistingUsers_whenUpsertingUsers_ThenResultsOneUpdatedAnotherInsertedWithNoConnectionStatusOverride() = runTest(dispatcher) { // given val newTeamId = "new team id" - db.userDAO.insertUser(user1.copy(connectionStatus = ConnectionEntity.State.ACCEPTED)) + db.userDAO.upsertUser(user1.copy(connectionStatus = ConnectionEntity.State.ACCEPTED)) // when val updatedUser1 = user1.copy(team = newTeamId) db.userDAO.upsertUsers(listOf(updatedUser1, user2)) @@ -581,7 +579,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenUser_WhenMarkingAsDeleted_ThenProperValueShouldBeUpdated() = runTest(dispatcher) { val user = user1 - db.userDAO.insertUser(user) + db.userDAO.upsertUser(user) val deletedUser = user1.copy(deleted = true, team = null, userType = UserTypeEntity.NONE) db.userDAO.markUserAsDeleted(user1.id) val result = db.userDAO.getUserByQualifiedID(user1.id).first() @@ -607,7 +605,7 @@ class UserDAOTest : BaseDatabaseTest() { val existingUser = user1 val usersToInsert = listOf(user1.copy(name = "other name to make sure this one wasn't inserted nor edited"), user2) val expected = listOf(user1, user2) - db.userDAO.insertUser(existingUser) + db.userDAO.upsertUser(existingUser) // when db.userDAO.insertOrIgnoreUsers(usersToInsert) // then @@ -619,7 +617,7 @@ class UserDAOTest : BaseDatabaseTest() { fun givenAnExistingUser_whenUpdatingTheDisplayName_thenTheValueShouldBeUpdated() = runTest(dispatcher) { // given val expectedNewDisplayName = "new user display name" - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) // when db.userDAO.updateUserDisplayName(user1.id, expectedNewDisplayName) @@ -632,7 +630,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUserWithoutMetadata_whenQueryingThem_thenShouldReturnUsersWithoutMetadata() = runTest(dispatcher) { // given - db.userDAO.insertUser(user1.copy(name = null, handle = null, hasIncompleteMetadata = true)) + db.userDAO.upsertUser(user1.copy(name = null, handle = null, hasIncompleteMetadata = true)) // when val usersWithoutMetadata = db.userDAO.getUsersWithoutMetadata() @@ -645,7 +643,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUser_WhenRemoveUserAsset_ThenUserAssetIsRemoved() = runTest(dispatcher) { // given - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) val assetId = UserAssetIdEntity("asset1", "domain") val updatedUser1 = user1.copy(previewAssetId = assetId) @@ -677,10 +675,10 @@ class UserDAOTest : BaseDatabaseTest() { val user2 = newUserEntity().copy(id = UserIDEntity("user-2", "domain-2")) val user3 = newUserEntity().copy(id = UserIDEntity("user-3", "domain-1")) - db.userDAO.insertUser(selfUser) - db.userDAO.insertUser(user1) - db.userDAO.insertUser(user2) - db.userDAO.insertUser(user3) + db.userDAO.upsertUser(selfUser) + db.userDAO.upsertUser(user1) + db.userDAO.upsertUser(user2) + db.userDAO.upsertUser(user3) db.userDAO.allOtherUsersId().also { result -> assertFalse { @@ -692,7 +690,7 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUser_ThenUserCanBeDefederated() = runTest(dispatcher) { - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) db.userDAO.markUserAsDefederated(user1.id) val result = db.userDAO.getUserByQualifiedID(user1.id).first() assertNotNull(result) @@ -702,7 +700,7 @@ class UserDAOTest : BaseDatabaseTest() { fun givenAnExistingUser_whenUpdatingTheSupportedProtocols_thenTheValueShouldBeUpdated() = runTest(dispatcher) { // given val expectedNewSupportedProtocols = setOf(SupportedProtocolEntity.PROTEUS, SupportedProtocolEntity.MLS) - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) // when db.userDAO.updateUserSupportedProtocols(user1.id, expectedNewSupportedProtocols) @@ -714,9 +712,9 @@ class UserDAOTest : BaseDatabaseTest() { @Test fun givenExistingUserIsDefederated_ThenUserCanBeRefederatedAfterUpdate() = runTest(dispatcher) { - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) db.userDAO.markUserAsDefederated(user1.id) - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) val result = db.userDAO.getUserByQualifiedID(user1.id).first() assertNotNull(result) assertEquals(false, result.defederated) @@ -726,7 +724,7 @@ class UserDAOTest : BaseDatabaseTest() { fun givenAnExistingUser_WhenUpdatingOneOnOneConversationId_ThenItIsUpdated() = runTest(dispatcher) { // given val expectedNewOneOnOneConversationId = TestStubs.conversationEntity1.id - db.userDAO.insertUser(user1) + db.userDAO.upsertUser(user1) // when db.userDAO.updateActiveOneOnOneConversation(user1.id, expectedNewOneOnOneConversationId) diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/client/ClientDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/client/ClientDAOTest.kt index 7cc22d4078a..c69bfdfad0b 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/client/ClientDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/client/ClientDAOTest.kt @@ -70,7 +70,7 @@ class ClientDAOTest : BaseDatabaseTest() { val insertedClient = insertedClient1.copy(user.id, "id1", deviceType = null, isMLSCapable = true) val expected = client1.copy(user.id, "id1", deviceType = null, isValid = true, isVerified = false, isMLSCapable = true) - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) val result = clientDAO.getClientsOfUserByQualifiedIDFlow(userId).first() @@ -88,7 +88,7 @@ class ClientDAOTest : BaseDatabaseTest() { val insertedClient2 = insertedClient2.copy(user.id, "id2", deviceType = null) val client2 = insertedClient2.toClient() - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClients(listOf(insertedClient, insertedClient2)) val result = clientDAO.getClientsOfUserByQualifiedIDFlow(userId).first() @@ -101,14 +101,14 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenClientsAreInsertedForMultipleUsers_whenFetchingClientsByUserId_thenOnlyTheRelevantClientsAreReturned() = runTest { - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClients(listOf(insertedClient1, insertedClient2)) val unrelatedUserId = QualifiedIDEntity("unrelated", "user") val unrelatedUser = newUserEntity(unrelatedUserId) val unrelatedInsertedClient = insertedClient1.copy(unrelatedUserId, "id1", deviceType = null) - userDAO.insertUser(unrelatedUser) + userDAO.upsertUser(unrelatedUser) clientDAO.insertClient(unrelatedInsertedClient) val result = clientDAO.getClientsOfUserByQualifiedIDFlow(userId).first() @@ -119,7 +119,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenClientIsInserted_whenDeletingItSpecifically_thenItShouldNotBeReturnedAnymoreOnNextFetch() = runTest { - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient1) clientDAO.deleteClient(insertedClient1.userId, insertedClient1.id) @@ -130,7 +130,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenClientsAreInserted_whenDeletingClientsOfUser_thenTheyShouldNotBeReturnedAnymoreOnNextFetch() = runTest { - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClients(listOf(insertedClient1, insertedClient2)) clientDAO.deleteClientsOfUserByQualifiedID(insertedClient1.userId) @@ -146,7 +146,7 @@ class ClientDAOTest : BaseDatabaseTest() { val insertClientWithNullType = insertClientWithType.copy(deviceType = null) - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClients(listOf(insertClientWithType)) clientDAO.getClientsOfUserByQualifiedIDFlow(userId).first().also { resultList -> assertEquals(listOf(clientWithType), resultList) @@ -162,7 +162,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenClientIsInsertedAndRemoveRedundant_whenFetchingClientsByUserId_thenTheRelevantClientsAreReturned() = runTest { - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClientsAndRemoveRedundant(listOf(insertedClient1, insertedClient2)) val result = clientDAO.getClientsOfUserByQualifiedID(userId) @@ -174,7 +174,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenClientIsInsertedAndRemoveRedundant_whenFetchingClientsByUserId_thenTheRedundantClientsAreNotReturned() = runTest { - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClientsAndRemoveRedundant(listOf(insertedClient, insertedClient1)) // this supposes to remove insertedClient1 clientDAO.insertClientsAndRemoveRedundant(listOf(insertedClient, insertedClient2)) @@ -188,7 +188,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenIsMLSCapableIsFalse_whenUpdatingAClient_thenItShouldUpdatedToTrue() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient.copy( isMLSCapable = false )) @@ -201,7 +201,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenIsMLSCapableIsTrue_whenUpdatingAClient_thenItShouldRemainTrue() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient.copy( isMLSCapable = true )) @@ -214,7 +214,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun whenInsertingANewClient_thenIsMustBeMarkedAsValid() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) assertTrue { clientDAO.getClientsOfUserByQualifiedID(userId).first().isValid } } @@ -222,7 +222,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenValidClient_whenMarkingAsInvalid_thenClientInfoIsUpdated() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) clientDAO.tryMarkInvalid(listOf(insertedClient.userId to listOf(insertedClient.id))) assertFalse { clientDAO.getClientsOfUserByQualifiedID(userId).first().isValid } @@ -231,7 +231,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun whenClientIsInsertedTwice_thenIvValidMustNotBeChanged() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) clientDAO.tryMarkInvalid(listOf(insertedClient.userId to listOf(insertedClient.id))) clientDAO.insertClient(insertedClient) @@ -242,7 +242,7 @@ class ClientDAOTest : BaseDatabaseTest() { fun givenInvalidUserClient_whenSelectingConversationRecipients_thenOnlyValidClientAreReturned() = runTest { val user = user val expected: Map> = mapOf(user.id to listOf(client1, client2)) - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) clientDAO.insertClient(insertedClient1) clientDAO.insertClient(insertedClient2) @@ -256,7 +256,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenNewClientAdded_thenItIsMarkedAsNotVerified() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) assertFalse { clientDAO.getClientsOfUserByQualifiedID(userId).first().isVerified } } @@ -264,7 +264,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenClient_whenUpdatingVerificationStatus_thenItIsUpdated() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) clientDAO.updateClientVerificationStatus(user.id, insertedClient.id, true) assertTrue { clientDAO.getClientsOfUserByQualifiedID(userId).first().isVerified } @@ -276,7 +276,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenUserId_whenAClientIsAdded_thenNewListIsEmitted() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.observeClientsByUserId(user.id).test { awaitItem().also { result -> assertEquals(emptyList(), result) } @@ -293,7 +293,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenVerifiedClient_whenInsertingTheSameIdAgain_thenVerificationStatusIsNotChanges() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) assertFalse { clientDAO.getClientsOfUserByQualifiedID(userId).first().isVerified } @@ -308,7 +308,7 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenUserIsPartOfConversation_whenGettingRecipient_thenOnlyValidUserClientsAreReturned() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) conversationDAO.insertConversation(conversationEntity1) memberDAO.insertMember(MemberEntity(user.id, MemberEntity.Role.Admin), conversationEntity1.id) @@ -326,13 +326,13 @@ class ClientDAOTest : BaseDatabaseTest() { @Test fun givenUserIsNotPartOfConversation_whenGettingRecipient_thenTheyAreNotIncludedInTheResult() = runTest { val user = user - userDAO.insertUser(user) + userDAO.upsertUser(user) clientDAO.insertClient(insertedClient) conversationDAO.insertConversation(conversationEntity1) memberDAO.insertMember(MemberEntity(user.id, MemberEntity.Role.Admin), conversationEntity1.id) val user2 = newUserEntity(QualifiedIDEntity("test2", "domain")) - userDAO.insertUser(user2) + userDAO.upsertUser(user2) val insertedClient2 = InsertClientParam( userId = user2.id, id = "id01", diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/CompositeMessageTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/CompositeMessageTest.kt index e11bddaad46..5c7bb4ef7e6 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/CompositeMessageTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/CompositeMessageTest.kt @@ -58,7 +58,7 @@ class CompositeMessageTest : BaseDatabaseTest() { fun givenSuccess_whenInsertingCompositeMessage_thenMessageCanBeRetrieved() = runTest { val conversation = conversationEntity1 conversationDAO.insertConversation(conversation) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val compositeMessage = newRegularMessageEntity().copy( senderUserId = userEntity1.id, @@ -87,7 +87,7 @@ class CompositeMessageTest : BaseDatabaseTest() { fun givenCompositeMessage_whenMarkingButtonAsSelected_thenOnlyOneItIsMarked() = runTest { val conversation = conversationEntity1 conversationDAO.insertConversation(conversation) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val compositeMessage = newRegularMessageEntity().copy( senderUserId = userEntity1.id, @@ -124,7 +124,7 @@ class CompositeMessageTest : BaseDatabaseTest() { fun givenCompositeMessageWithSelection_whenResetSelection_thenSelectionIsFalse() = runTest { val conversation = conversationEntity1 conversationDAO.insertConversation(conversation) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val compositeMessage = newRegularMessageEntity().copy( senderUserId = userEntity1.id, diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOBenchmarkTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOBenchmarkTest.kt index a8b39d9fb85..add186045ef 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOBenchmarkTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOBenchmarkTest.kt @@ -176,8 +176,8 @@ class MessageDAOBenchmarkTest : BaseDatabaseTest() { private suspend fun setupData() { conversationDAO.insertConversations(listOf(conversationEntity1)) - userDAO.insertUser(userEntity1) - userDAO.insertUser(userEntity2) + userDAO.upsertUser(userEntity1) + userDAO.upsertUser(userEntity2) } private companion object { diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOTest.kt index 7f73f441362..05b447f1bb0 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageDAOTest.kt @@ -396,7 +396,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages( listOf( @@ -445,7 +445,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages( listOf( @@ -479,7 +479,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val message = buildList { // add 9 Message before the lastReadDate @@ -515,7 +515,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val readMessagesCount = 3 val unreadMessagesCount = 2 @@ -565,7 +565,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val readMessagesCount = 3 val unreadMessagesCount = 2 @@ -617,7 +617,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages( listOf( @@ -650,7 +650,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val unreadMessagesCount = 2 val message = buildList { @@ -791,7 +791,7 @@ class MessageDAOTest : BaseDatabaseTest() { newConversationEntity(id = conversationId2) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages( listOf( newRegularMessageEntity( @@ -871,7 +871,7 @@ class MessageDAOTest : BaseDatabaseTest() { lastReadDate = "2000-01-01T12:00:00.000Z".toInstant() ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages(listOf(previewAssetMessage)) // when @@ -932,7 +932,7 @@ class MessageDAOTest : BaseDatabaseTest() { lastReadDate = "2000-01-01T12:00:00.000Z".toInstant() ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages(listOf(previewAssetMessage)) // when @@ -992,7 +992,7 @@ class MessageDAOTest : BaseDatabaseTest() { lastReadDate = "2000-01-01T12:00:00.000Z".toInstant() ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessages(listOf(previewAssetMessage)) // when @@ -1082,7 +1082,7 @@ class MessageDAOTest : BaseDatabaseTest() { lastReadDate = "2000-01-01T12:00:00.000Z".toInstant() ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) messageDAO.insertOrIgnoreMessage(initialAssetMessage) // when @@ -1121,7 +1121,7 @@ class MessageDAOTest : BaseDatabaseTest() { lastReadDate = "2000-01-01T12:00:00.000Z".toInstant(), ) ) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val message1 = newRegularMessageEntity( id = messageId, @@ -1155,8 +1155,8 @@ class MessageDAOTest : BaseDatabaseTest() { lastReadDate = "2000-01-01T12:00:00.000Z".toInstant(), ) ) - userDAO.insertUser(userEntity1) - userDAO.insertUser(userEntity2) + userDAO.upsertUser(userEntity1) + userDAO.upsertUser(userEntity2) val messageFromUser1 = newRegularMessageEntity( id = messageId, @@ -1313,7 +1313,7 @@ class MessageDAOTest : BaseDatabaseTest() { val conversationId = QualifiedIDEntity("1", "someDomain") val messageId = "ConversationReceiptModeChanged Message" conversationDAO.insertConversation(newConversationEntity(id = conversationId)) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) // when messageDAO.insertOrIgnoreMessages( @@ -1349,7 +1349,7 @@ class MessageDAOTest : BaseDatabaseTest() { conversationDAO.insertConversation(newConversationEntity(id = conversationId2)) val messageId = "systemMessage" - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) // when messageDAO.persistSystemMessageToAllConversations( @@ -1405,7 +1405,7 @@ class MessageDAOTest : BaseDatabaseTest() { ) ) val messageId = "systemMessage" - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) // when messageDAO.persistSystemMessageToAllConversations( @@ -1511,8 +1511,8 @@ class MessageDAOTest : BaseDatabaseTest() { val conversationId = QualifiedIDEntity("1", "someDomain") val messageId = "Conversation MessageSent With Partial Success" conversationDAO.insertConversation(newConversationEntity(id = conversationId)) - userDAO.insertUser(userEntity1) - userDAO.insertUser(userEntity2) + userDAO.upsertUser(userEntity1) + userDAO.upsertUser(userEntity2) messageDAO.insertOrIgnoreMessages( listOf( diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageInsertExtensionTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageInsertExtensionTest.kt index a585abe557f..ba21ea62245 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageInsertExtensionTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageInsertExtensionTest.kt @@ -63,7 +63,7 @@ class MessageInsertExtensionTest : BaseDatabaseTest() { @Test fun givenDeletedAssetMessage_whenUpdateUploadStatus_thenFail() = runTest { conversationDAO.insertConversation(conversationEntity1) - userDAO.insertUser(userEntity1) + userDAO.upsertUser(userEntity1) val assetMessage = newRegularMessageEntity( id = "messageId", date = Instant.DISTANT_PAST, diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageMetadataDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageMetadataDAOTest.kt index b28f1a38055..71efc8f570b 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageMetadataDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/message/MessageMetadataDAOTest.kt @@ -60,7 +60,7 @@ class MessageMetadataDAOTest : BaseDatabaseTest() { val originalUser = userEntity1 conversationDAO.insertConversation(conversationEntity1) - userDAO.insertUser(originalUser) + userDAO.upsertUser(originalUser) val originalMessage = newRegularMessageEntity( id = messageId, diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/reaction/ReactionDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/reaction/ReactionDAOTest.kt index 86e09b782cf..f86b8e31ff6 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/reaction/ReactionDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/reaction/ReactionDAOTest.kt @@ -193,8 +193,8 @@ class ReactionDAOTest : BaseDatabaseTest() { } private suspend fun insertTestUsers() { - userDAO.insertUser(SELF_USER) - userDAO.insertUser(OTHER_USER) + userDAO.upsertUser(SELF_USER) + userDAO.upsertUser(OTHER_USER) } private companion object { diff --git a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/receipt/ReceiptDAOTest.kt b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/receipt/ReceiptDAOTest.kt index 5b6107f0993..67bc6893d91 100644 --- a/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/receipt/ReceiptDAOTest.kt +++ b/persistence/src/commonTest/kotlin/com/wire/kalium/persistence/dao/receipt/ReceiptDAOTest.kt @@ -169,8 +169,8 @@ class ReceiptDAOTest : BaseDatabaseTest() { } private suspend fun insertTestData() { - userDAO.insertUser(SELF_USER) - userDAO.insertUser(OTHER_USER) + userDAO.upsertUser(SELF_USER) + userDAO.upsertUser(OTHER_USER) conversationDAO.insertConversation(TEST_CONVERSATION) messageDAO.insertOrIgnoreMessage(TEST_MESSAGE) }