Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor repository/query patterns (#1695)

Leendert de Borst399b94d708ac
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
new file mode 100644
index 000000000..73127d806
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/ItemQueries.kt
@@ -0,0 +1,177 @@
+package net.aliasvault.app.vaultstore.queries
+
+/**
+ * SQL query constants for Item operations.
+ * Centralizes all item-related queries to avoid duplication.
+ * Mirrors the browser extension and React Native implementation.
+ */
+object ItemQueries {
+ /**
+ * Base SELECT for items with common fields.
+ * Includes LEFT JOIN to Logos and subqueries for HasPasskey/HasAttachment/HasTotp.
+ */
+ const val BASE_SELECT = """
+ SELECT DISTINCT
+ i.Id,
+ i.Name,
+ i.ItemType,
+ i.FolderId,
+ l.FileData as Logo,
+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
+ i.CreatedAt,
+ i.UpdatedAt
+ FROM Items i
+ LEFT JOIN Logos l ON i.LogoId = l.Id
+ """
+
+ /**
+ * Get all active items (not deleted, not in trash).
+ */
+ const val GET_ALL_ACTIVE = """
+ $BASE_SELECT
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ ORDER BY i.CreatedAt DESC
+ """
+
+ /**
+ * Get a single item by ID.
+ */
+ const val GET_BY_ID = """
+ $BASE_SELECT
+ WHERE i.Id = ? AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ """
+
+ /**
+ * Get field values for multiple items.
+ * @param itemCount Number of items (for placeholder generation)
+ * @return Query with placeholders
+ */
+ fun getFieldValuesForItems(itemCount: Int): String {
+ val placeholders = Array(itemCount) { "?" }.joinToString(",")
+ return """
+ SELECT
+ fv.ItemId,
+ fv.FieldKey,
+ fv.FieldDefinitionId,
+ fd.Label as CustomLabel,
+ fd.FieldType as CustomFieldType,
+ fd.IsHidden as CustomIsHidden,
+ fd.EnableHistory as CustomEnableHistory,
+ fv.Value,
+ fv.Weight as DisplayOrder
+ FROM FieldValues fv
+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
+ WHERE fv.ItemId IN ($placeholders)
+ AND fv.IsDeleted = 0
+ ORDER BY fv.ItemId, fv.Weight
+ """.trimIndent()
+ }
+
+ /**
+ * Get field values for a single item.
+ */
+ const val GET_FIELD_VALUES_FOR_ITEM = """
+ SELECT
+ fv.FieldKey,
+ fv.FieldDefinitionId,
+ fd.Label as CustomLabel,
+ fd.FieldType as CustomFieldType,
+ fd.IsHidden as CustomIsHidden,
+ fd.EnableHistory as CustomEnableHistory,
+ fv.Value,
+ fv.Weight as DisplayOrder
+ FROM FieldValues fv
+ LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
+ WHERE fv.ItemId = ? AND fv.IsDeleted = 0
+ ORDER BY fv.Weight
+ """
+
+ /**
+ * Get all unique email addresses from field values.
+ */
+ const val GET_ALL_EMAIL_ADDRESSES = """
+ SELECT DISTINCT fv.Value as Email
+ FROM FieldValues fv
+ INNER JOIN Items i ON fv.ItemId = i.Id
+ WHERE fv.FieldKey = ?
+ AND fv.IsDeleted = 0
+ AND i.IsDeleted = 0
+ AND i.DeletedAt IS NULL
+ """
+
+ /**
+ * Get all recently deleted items (in trash).
+ */
+ const val GET_RECENTLY_DELETED = """
+ SELECT DISTINCT
+ i.Id,
+ i.Name,
+ i.ItemType,
+ i.FolderId,
+ l.FileData as Logo,
+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
+ i.CreatedAt,
+ i.UpdatedAt,
+ i.DeletedAt
+ FROM Items i
+ LEFT JOIN Logos l ON i.LogoId = l.Id
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
+ ORDER BY i.DeletedAt DESC
+ """
+
+ /**
+ * Count of recently deleted items.
+ */
+ const val COUNT_RECENTLY_DELETED = """
+ SELECT COUNT(*) as count
+ FROM Items
+ WHERE IsDeleted = 0 AND DeletedAt IS NOT NULL
+ """
+
+ /**
+ * Get the database version from the __EFMigrationsHistory table.
+ */
+ const val GET_DATABASE_VERSION = """
+ SELECT MigrationId FROM __EFMigrationsHistory ORDER BY MigrationId DESC LIMIT 1
+ """
+
+ /**
+ * Move item to trash (set DeletedAt).
+ */
+ const val TRASH_ITEM = """
+ UPDATE Items SET DeletedAt = ?, UpdatedAt = ? WHERE Id = ?
+ """
+
+ /**
+ * Restore item from trash (clear DeletedAt).
+ */
+ const val RESTORE_ITEM = """
+ UPDATE Items SET DeletedAt = NULL, UpdatedAt = ? WHERE Id = ?
+ """
+
+ /**
+ * Convert item to tombstone for permanent deletion.
+ */
+ const val TOMBSTONE_ITEM = """
+ UPDATE Items
+ SET Name = NULL,
+ ItemType = NULL,
+ LogoId = NULL,
+ FolderId = NULL,
+ DeletedAt = NULL,
+ IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?
+ """
+
+ /**
+ * Get folder data for building folder paths.
+ */
+ const val GET_ALL_FOLDERS = """
+ SELECT Id, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0
+ """
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
new file mode 100644
index 000000000..322d5b064
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/queries/PasskeyQueries.kt
@@ -0,0 +1,205 @@
+package net.aliasvault.app.vaultstore.queries
+
+/**
+ * SQL query constants for Passkey operations.
+ * Centralizes all passkey-related queries to avoid duplication.
+ */
+object PasskeyQueries {
+ /**
+ * Base SELECT for passkeys with common fields.
+ */
+ const val BASE_SELECT = """
+ SELECT Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
+ DisplayName, CreatedAt, UpdatedAt, IsDeleted
+ FROM Passkeys
+ """
+
+ /**
+ * Get a passkey by its credential ID.
+ */
+ const val GET_BY_CREDENTIAL_ID = """
+ $BASE_SELECT
+ WHERE Id = ? AND IsDeleted = 0
+ LIMIT 1
+ """
+
+ /**
+ * Get all passkeys for an item.
+ */
+ const val GET_BY_ITEM_ID = """
+ $BASE_SELECT
+ WHERE ItemId = ? AND IsDeleted = 0
+ ORDER BY CreatedAt DESC
+ """
+
+ /**
+ * Get all passkeys for a relying party (rpId).
+ */
+ const val GET_BY_RP_ID = """
+ $BASE_SELECT
+ WHERE RpId = ? AND IsDeleted = 0
+ ORDER BY CreatedAt DESC
+ """
+
+ /**
+ * Get a passkey by its ID.
+ */
+ const val GET_BY_ID = """
+ $BASE_SELECT
+ WHERE Id = ? AND IsDeleted = 0
+ LIMIT 1
+ """
+
+ /**
+ * Insert a new passkey.
+ */
+ const val INSERT = """
+ INSERT INTO Passkeys (Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
+ DisplayName, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """
+
+ /**
+ * Get passkeys with item info for a specific rpId.
+ * Joins with Items and FieldValues to get display info.
+ */
+ val GET_WITH_CREDENTIAL_INFO = """
+ SELECT p.Id, p.ItemId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
+ p.DisplayName, p.CreatedAt, p.UpdatedAt, p.IsDeleted,
+ i.Name,
+ fv_username.Value as Username
+ FROM Passkeys p
+ INNER JOIN Items i ON p.ItemId = i.Id
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ AND fv_username.FieldKey = ?
+ AND fv_username.IsDeleted = 0
+ WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ ORDER BY p.CreatedAt DESC
+ """.trimIndent()
+
+ /**
+ * Get ALL Login items that don't have a passkey yet (no URL filtering).
+ * Used with RustCredentialMatcher for intelligent, cross-platform consistent filtering.
+ */
+ val GET_ALL_ITEMS_WITHOUT_PASSKEY = """
+ SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
+ GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
+ fv_username.Value as Username,
+ fv_password.Value as Password
+ FROM Items i
+ LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
+ AND fv_url.FieldKey = ?
+ AND fv_url.IsDeleted = 0
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ AND fv_username.FieldKey = ?
+ AND fv_username.IsDeleted = 0
+ LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id
+ AND fv_password.FieldKey = ?
+ AND fv_password.IsDeleted = 0
+ WHERE i.IsDeleted = 0
+ AND i.DeletedAt IS NULL
+ AND i.ItemType = 'Login'
+ AND NOT EXISTS (
+ SELECT 1 FROM Passkeys p
+ WHERE p.ItemId = i.Id AND p.IsDeleted = 0
+ )
+ GROUP BY i.Id
+ ORDER BY i.UpdatedAt DESC
+ """.trimIndent()
+
+ /**
+ * Get all passkeys with their associated items in a single query.
+ */
+ val GET_ALL_WITH_ITEMS = """
+ SELECT
+ p.Id, p.ItemId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
+ p.DisplayName, p.CreatedAt as PasskeyCreatedAt, p.UpdatedAt as PasskeyUpdatedAt, p.IsDeleted as PasskeyIsDeleted,
+ i.Id as ItemId, i.Name, i.CreatedAt as ItemCreatedAt, i.UpdatedAt as ItemUpdatedAt,
+ fv_username.Value as Username,
+ fv_email.Value as Email
+ FROM Passkeys p
+ INNER JOIN Items i ON p.ItemId = i.Id
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ AND fv_username.FieldKey = ?
+ AND fv_username.IsDeleted = 0
+ LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
+ AND fv_email.FieldKey = ?
+ AND fv_email.IsDeleted = 0
+ WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ ORDER BY p.CreatedAt DESC
+ """.trimIndent()
+
+ /**
+ * Create an Item record for passkey registration.
+ */
+ const val CREATE_ITEM = """
+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, DeletedAt)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """
+
+ /**
+ * Insert a URL field value.
+ */
+ const val INSERT_FIELD_VALUE = """
+ INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """
+
+ /**
+ * Update item's UpdatedAt timestamp.
+ */
+ const val UPDATE_ITEM_TIMESTAMP = """
+ UPDATE Items SET UpdatedAt = ? WHERE Id = ?
+ """
+
+ /**
+ * Get logo ID from an item.
+ */
+ const val GET_LOGO_ID_FROM_ITEM = """
+ SELECT LogoId FROM Items WHERE Id = ?
+ """
+}
+
+/**
+ * SQL query constants for Logo operations used during passkey/item creation.
+ */
+object LogoQueries {
+ /**
+ * Insert a new logo.
+ */
+ const val INSERT = """
+ INSERT INTO Logos (Id, Source, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ """
+
+ /**
+ * Update logo file data.
+ */
+ const val UPDATE_FILE_DATA = """
+ UPDATE Logos
+ SET FileData = ?,
+ UpdatedAt = ?
+ WHERE Id = ?
+ """
+
+ /**
+ * Get logo by source.
+ */
+ const val GET_BY_SOURCE = """
+ SELECT Id, IsDeleted FROM Logos WHERE Source = ? LIMIT 1
+ """
+
+ /**
+ * Restore a soft-deleted logo.
+ */
+ const val RESTORE = """
+ UPDATE Logos SET IsDeleted = 0, UpdatedAt = ? WHERE Id = ?
+ """
+
+ /**
+ * Update item logo ID.
+ */
+ const val UPDATE_ITEM_LOGO_ID = """
+ UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?
+ """
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
index 8feb3644b..446a57cbf 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/ItemRepository.kt
@@ -7,6 +7,7 @@ import net.aliasvault.app.vaultstore.models.FieldKey
import net.aliasvault.app.vaultstore.models.FieldType
import net.aliasvault.app.vaultstore.models.Item
import net.aliasvault.app.vaultstore.models.ItemField
+import net.aliasvault.app.vaultstore.queries.ItemQueries
import net.aliasvault.app.vaultstore.utils.FolderUtils
import java.util.Calendar
import java.util.Date
@@ -45,8 +46,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
try {
// Get all folders from database
- val folderQuery = "SELECT Id, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0"
- val folderResults = executeQuery(folderQuery, emptyArray())
+ val folderResults = executeQuery(ItemQueries.GET_ALL_FOLDERS, emptyArray())
if (folderResults.isEmpty()) {
return folderPathMap
@@ -88,31 +88,13 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
*/
@Suppress("LongMethod", "NestedBlockDepth", "LoopWithTooManyJumpStatements")
fun getAll(): List<Item> {
- val itemQuery = """
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY i.CreatedAt DESC
- """.trimIndent()
-
val items = mutableListOf<Item>()
val itemIds = mutableListOf<String>()
// Build folder paths
val folderPaths = buildFolderPaths()
- val itemResults = executeQueryWithBlobs(itemQuery, emptyArray())
+ val itemResults = executeQueryWithBlobs(ItemQueries.GET_ALL_ACTIVE, emptyArray())
for (row in itemResults) {
try {
val idString = row["Id"] as? String ?: continue
@@ -157,24 +139,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
}
// Get all field values for these items
- val (placeholders, _) = buildInClause(itemIds)
- val fieldQuery = """
- SELECT
- fv.ItemId,
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId IN ($placeholders)
- AND fv.IsDeleted = 0
- ORDER BY fv.ItemId, fv.Weight
- """.trimIndent()
+ val fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.size)
// Build a map of itemId -> [ItemField]
val fieldsByItemId = mutableMapOf<String, MutableList<ItemField>>()
@@ -239,24 +204,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
* @return Item object or null if not found.
*/
fun getById(itemId: String): Item? {
- val itemQuery = """
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.Id = ? AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- """.trimIndent()
-
- val itemResults = executeQueryWithBlobs(itemQuery, arrayOf(itemId.uppercase()))
+ val itemResults = executeQueryWithBlobs(ItemQueries.GET_BY_ID, arrayOf(itemId.uppercase()))
val row = itemResults.firstOrNull() ?: return null
// Build folder paths
@@ -279,24 +227,8 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
val folderPath = folderUuid?.let { folderPaths[it] }
// Get field values for this item
- val fieldQuery = """
- SELECT
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId = ? AND fv.IsDeleted = 0
- ORDER BY fv.Weight
- """.trimIndent()
-
val fields = mutableListOf<ItemField>()
- val fieldResults = executeQuery(fieldQuery, arrayOf(idString))
+ val fieldResults = executeQuery(ItemQueries.GET_FIELD_VALUES_FOR_ITEM, arrayOf(idString))
for (fieldRow in fieldResults) {
val fieldKey = fieldRow["FieldKey"] as? String
val fieldDefinitionId = fieldRow["FieldDefinitionId"] as? String
@@ -359,18 +291,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
* @return List of email addresses.
*/
fun getAllEmailAddresses(): List<String> {
- val results = executeQuery(
- """
- SELECT DISTINCT fv.Value as Email
- FROM FieldValues fv
- INNER JOIN Items i ON fv.ItemId = i.Id
- WHERE fv.FieldKey = ?
- AND fv.IsDeleted = 0
- AND i.IsDeleted = 0
- AND i.DeletedAt IS NULL
- """.trimIndent(),
- arrayOf(FieldKey.LOGIN_EMAIL),
- )
+ val results = executeQuery(ItemQueries.GET_ALL_EMAIL_ADDRESSES, arrayOf(FieldKey.LOGIN_EMAIL))
return results.mapNotNull { it["Email"] as? String }
}
@@ -382,27 +303,8 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
*/
@Suppress("LongMethod", "LoopWithTooManyJumpStatements")
fun getRecentlyDeleted(): List<Item> {
- val query = """
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.DeletedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
- ORDER BY i.DeletedAt DESC
- """.trimIndent()
-
val items = mutableListOf<Item>()
- val results = executeQueryWithBlobs(query, emptyArray())
+ val results = executeQueryWithBlobs(ItemQueries.GET_RECENTLY_DELETED, emptyArray())
// Build folder paths
val folderPaths = buildFolderPaths()
@@ -454,8 +356,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
* @return Database version string (e.g., "1.0.0").
*/
fun getDatabaseVersion(): String {
- val query = "SELECT MigrationId FROM __EFMigrationsHistory ORDER BY MigrationId DESC LIMIT 1"
- val results = executeQuery(query, emptyArray())
+ val results = executeQuery(ItemQueries.GET_DATABASE_VERSION, emptyArray())
if (results.isEmpty()) {
Log.d(TAG, "No migrations found in database, returning default version")
@@ -484,14 +385,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
* @return Number of items in trash.
*/
fun getRecentlyDeletedCount(): Int {
- val results = executeQuery(
- """
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NOT NULL
- """.trimIndent(),
- emptyArray(),
- )
+ val results = executeQuery(ItemQueries.COUNT_RECENTLY_DELETED, emptyArray())
return (results.firstOrNull()?.get("count") as? Long)?.toInt() ?: 0
}
@@ -506,10 +400,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
fun trash(itemId: String): Int {
return withTransaction {
val now = now()
- executeUpdate(
- "UPDATE Items SET DeletedAt = ?, UpdatedAt = ? WHERE Id = ?",
- arrayOf(now, now, itemId),
- )
+ executeUpdate(ItemQueries.TRASH_ITEM, arrayOf(now, now, itemId))
}
}
@@ -522,10 +413,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
fun restore(itemId: String): Int {
return withTransaction {
val now = now()
- executeUpdate(
- "UPDATE Items SET DeletedAt = NULL, UpdatedAt = ? WHERE Id = ?",
- arrayOf(now, itemId),
- )
+ executeUpdate(ItemQueries.RESTORE_ITEM, arrayOf(now, itemId))
}
}
@@ -556,20 +444,7 @@ class ItemRepository(database: VaultDatabase) : BaseRepository(database) {
}
// Convert item to tombstone
- executeUpdate(
- """
- UPDATE Items
- SET Name = NULL,
- ItemType = NULL,
- LogoId = NULL,
- FolderId = NULL,
- DeletedAt = NULL,
- IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ?
- """.trimIndent(),
- arrayOf(now, itemId),
- )
+ executeUpdate(ItemQueries.TOMBSTONE_ITEM, arrayOf(now, itemId))
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
index f6c9a41b2..3e22a9860 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
@@ -9,6 +9,8 @@ import net.aliasvault.app.vaultstore.models.FieldKey
import net.aliasvault.app.vaultstore.models.Item
import net.aliasvault.app.vaultstore.models.Passkey
import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
+import net.aliasvault.app.vaultstore.queries.LogoQueries
+import net.aliasvault.app.vaultstore.queries.PasskeyQueries
import java.util.Calendar
import java.util.Date
import java.util.TimeZone
@@ -49,13 +51,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
}
val results = executeQuery(
- """
- SELECT Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted
- FROM Passkeys
- WHERE Id = ? AND IsDeleted = 0
- LIMIT 1
- """.trimIndent(),
+ PasskeyQueries.GET_BY_CREDENTIAL_ID,
arrayOf(credentialIdString.uppercase()),
)
@@ -69,13 +65,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
*/
fun getForItem(itemId: UUID): List<Passkey> {
val results = executeQuery(
- """
- SELECT Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted
- FROM Passkeys
- WHERE ItemId = ? AND IsDeleted = 0
- ORDER BY CreatedAt DESC
- """.trimIndent(),
+ PasskeyQueries.GET_BY_ITEM_ID,
arrayOf(itemId.toString().uppercase()),
)
@@ -88,17 +78,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
* @return List of Passkey objects
*/
fun getForRpId(rpId: String): List<Passkey> {
- val results = executeQuery(
- """
- SELECT Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted
- FROM Passkeys
- WHERE RpId = ? AND IsDeleted = 0
- ORDER BY CreatedAt DESC
- """.trimIndent(),
- arrayOf(rpId),
- )
-
+ val results = executeQuery(PasskeyQueries.GET_BY_RP_ID, arrayOf(rpId))
return results.mapNotNull { parsePasskeyRow(it) }
}
@@ -108,17 +88,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
* @return Passkey object or null if not found
*/
fun getById(passkeyId: UUID): Passkey? {
- val results = executeQuery(
- """
- SELECT Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted
- FROM Passkeys
- WHERE Id = ? AND IsDeleted = 0
- LIMIT 1
- """.trimIndent(),
- arrayOf(passkeyId.toString().uppercase()),
- )
-
+ val results = executeQuery(PasskeyQueries.GET_BY_ID, arrayOf(passkeyId.toString().uppercase()))
return results.firstOrNull()?.let { parsePasskeyRow(it) }
}
@@ -134,13 +104,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
val publicKeyString = String(passkey.publicKey, Charsets.UTF_8)
val privateKeyString = String(passkey.privateKey, Charsets.UTF_8)
- val statement = db.compileStatement(
- """
- INSERT INTO Passkeys (Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey,
- DisplayName, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent(),
- )
+ val statement = db.compileStatement(PasskeyQueries.INSERT)
statement.use {
it.bindString(1, passkey.id.toString().uppercase())
it.bindString(2, passkey.parentItemId.toString().uppercase()) // Note: still called parentItemId but references ItemId
@@ -196,10 +160,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// Create the Item
executeUpdate(
- """
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, DeletedAt)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent(),
+ PasskeyQueries.CREATE_ITEM,
arrayOf(
itemId.toString().uppercase(),
displayName,
@@ -216,10 +177,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// Insert URL field value
if (rpId.isNotEmpty()) {
executeUpdate(
- """
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent(),
+ PasskeyQueries.INSERT_FIELD_VALUE,
arrayOf(
generateId(),
itemId.toString().uppercase(),
@@ -237,10 +195,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// Insert username field value if provided
if (userName != null) {
executeUpdate(
- """
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent(),
+ PasskeyQueries.INSERT_FIELD_VALUE,
arrayOf(
generateId(),
itemId.toString().uppercase(),
@@ -301,31 +256,19 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
val itemId = oldPasskey.parentItemId
- // Update the item's name
- executeUpdate(
- "UPDATE Items SET UpdatedAt = ? WHERE Id = ?",
- arrayOf(timestamp, itemId.toString().uppercase()),
- )
+ // Update the item's timestamp
+ executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, itemId.toString().uppercase()))
if (logo != null) {
val source = newPasskey.rpId.lowercase().replace("www.", "")
- val itemResults = executeQuery(
- "SELECT LogoId FROM Items WHERE Id = ?",
- arrayOf(itemId.toString().uppercase()),
- )
+ val itemResults = executeQuery(PasskeyQueries.GET_LOGO_ID_FROM_ITEM, arrayOf(itemId.toString().uppercase()))
val existingLogoId = itemResults.firstOrNull()?.get("LogoId") as? String
if (existingLogoId != null) {
- executeUpdate(
- "UPDATE Logos SET FileData = ?, UpdatedAt = ? WHERE Id = ?",
- arrayOf(logo, timestamp, existingLogoId),
- )
+ executeUpdate(LogoQueries.UPDATE_FILE_DATA, arrayOf(logo, timestamp, existingLogoId))
} else {
val newLogoId = getOrCreateLogo(source, logo, timestamp)
- executeUpdate(
- "UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?",
- arrayOf(newLogoId, timestamp, itemId.toString().uppercase()),
- )
+ executeUpdate(LogoQueries.UPDATE_ITEM_LOGO_ID, arrayOf(newLogoId, timestamp, itemId.toString().uppercase()))
}
}
@@ -367,36 +310,22 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
val source = rpId.lowercase().replace("www.", "")
// Check if item already has a logo
- val itemResults = executeQuery(
- "SELECT LogoId FROM Items WHERE Id = ?",
- arrayOf(itemId.toString().uppercase()),
- )
-
+ val itemResults = executeQuery(PasskeyQueries.GET_LOGO_ID_FROM_ITEM, arrayOf(itemId.toString().uppercase()))
val existingLogoId = itemResults.firstOrNull()?.get("LogoId") as? String
if (existingLogoId != null) {
// Update existing logo
- executeUpdate(
- "UPDATE Logos SET FileData = ?, UpdatedAt = ? WHERE Id = ?",
- arrayOf(logo, timestamp, existingLogoId),
- )
+ executeUpdate(LogoQueries.UPDATE_FILE_DATA, arrayOf(logo, timestamp, existingLogoId))
} else {
// Create or reuse logo with unique source check
val newLogoId = getOrCreateLogo(source, logo, timestamp)
-
// Link logo to item
- executeUpdate(
- "UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?",
- arrayOf(newLogoId, timestamp, itemId.toString().uppercase()),
- )
+ executeUpdate(LogoQueries.UPDATE_ITEM_LOGO_ID, arrayOf(newLogoId, timestamp, itemId.toString().uppercase()))
}
}
// Update item's UpdatedAt timestamp
- executeUpdate(
- "UPDATE Items SET UpdatedAt = ? WHERE Id = ?",
- arrayOf(timestamp, itemId.toString().uppercase()),
- )
+ executeUpdate(PasskeyQueries.UPDATE_ITEM_TIMESTAMP, arrayOf(timestamp, itemId.toString().uppercase()))
// Create the passkey with the existing item ID
val passkeyToInsert = passkey.copy(
@@ -428,22 +357,8 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
): List<PasskeyWithCredentialInfo> {
val db = database.dbConnection ?: return emptyList()
- val query = """
- SELECT p.Id, p.ItemId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
- p.DisplayName, p.CreatedAt, p.UpdatedAt, p.IsDeleted,
- i.Name,
- fv_username.Value as Username
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
- AND fv_username.FieldKey = ?
- AND fv_username.IsDeleted = 0
- WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC
- """.trimIndent()
-
val results = mutableListOf<PasskeyWithCredentialInfo>()
- val cursor = db.query(query, arrayOf(FieldKey.LOGIN_USERNAME, rpId))
+ val cursor = db.query(PasskeyQueries.GET_WITH_CREDENTIAL_INFO, arrayOf(FieldKey.LOGIN_USERNAME, rpId))
cursor.use {
while (it.moveToNext()) {
@@ -484,40 +399,10 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
fun getAllItemsWithoutPasskey(): List<ItemWithCredentialInfo> {
val db = database.dbConnection ?: return emptyList()
- val query = """
- SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
- GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
- fv_username.Value as Username,
- fv_password.Value as Password
- FROM Items i
- LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
- AND fv_url.FieldKey = ?
- AND fv_url.IsDeleted = 0
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
- AND fv_username.FieldKey = ?
- AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id
- AND fv_password.FieldKey = ?
- AND fv_password.IsDeleted = 0
- WHERE i.IsDeleted = 0
- AND i.DeletedAt IS NULL
- AND i.ItemType = 'Login'
- AND NOT EXISTS (
- SELECT 1 FROM Passkeys p
- WHERE p.ItemId = i.Id AND p.IsDeleted = 0
- )
- GROUP BY i.Id
- ORDER BY i.UpdatedAt DESC
- """.trimIndent()
-
val results = mutableListOf<ItemWithCredentialInfo>()
val cursor = db.query(
- query,
- arrayOf(
- FieldKey.LOGIN_URL,
- FieldKey.LOGIN_USERNAME,
- FieldKey.LOGIN_PASSWORD,
- ),
+ PasskeyQueries.GET_ALL_ITEMS_WITHOUT_PASSKEY,
+ arrayOf(FieldKey.LOGIN_URL, FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_PASSWORD),
)
cursor.use {
@@ -594,27 +479,8 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
fun getAllWithItems(): List<PasskeyWithItem> {
val db = database.dbConnection ?: return emptyList()
- val query = """
- SELECT
- p.Id, p.ItemId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey,
- p.DisplayName, p.CreatedAt as PasskeyCreatedAt, p.UpdatedAt as PasskeyUpdatedAt, p.IsDeleted as PasskeyIsDeleted,
- i.Id as ItemId, i.Name, i.CreatedAt as ItemCreatedAt, i.UpdatedAt as ItemUpdatedAt,
- fv_username.Value as Username,
- fv_email.Value as Email
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
- AND fv_username.FieldKey = ?
- AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
- AND fv_email.FieldKey = ?
- AND fv_email.IsDeleted = 0
- WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- ORDER BY p.CreatedAt DESC
- """.trimIndent()
-
val results = mutableListOf<PasskeyWithItem>()
- val cursor = db.query(query, arrayOf(FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL))
+ val cursor = db.query(PasskeyQueries.GET_ALL_WITH_ITEMS, arrayOf(FieldKey.LOGIN_USERNAME, FieldKey.LOGIN_EMAIL))
cursor.use {
while (it.moveToNext()) {
@@ -673,10 +539,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
*/
private fun getOrCreateLogo(source: String, logoData: ByteArray, timestamp: String): String {
// Check if a logo for this source already exists
- val existingLogos = executeQuery(
- "SELECT Id, IsDeleted FROM Logos WHERE Source = ? LIMIT 1",
- arrayOf(source),
- )
+ val existingLogos = executeQuery(LogoQueries.GET_BY_SOURCE, arrayOf(source))
val existingLogo = existingLogos.firstOrNull()
if (existingLogo != null) {
@@ -685,10 +548,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// Sanity check: restore if soft-deleted
if (isDeleted) {
- executeUpdate(
- "UPDATE Logos SET IsDeleted = 0, UpdatedAt = ? WHERE Id = ?",
- arrayOf(timestamp, existingLogoId),
- )
+ executeUpdate(LogoQueries.RESTORE, arrayOf(timestamp, existingLogoId))
}
return existingLogoId
}
@@ -696,20 +556,8 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
// Create new logo entry
val logoId = generateId()
executeUpdate(
- """
- INSERT INTO Logos (Id, Source, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent(),
- arrayOf(
- logoId,
- source,
- logoData,
- "image/png",
- null,
- timestamp,
- timestamp,
- 0,
- ),
+ LogoQueries.INSERT,
+ arrayOf(logoId, source, logoData, "image/png", null, timestamp, timestamp, 0),
)
return logoId
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
index 267f6ba6f..b219524fe 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
@@ -179,4 +179,24 @@ public struct LogoQueries {
UpdatedAt = ?
WHERE Id = ?
"""
+
+ /// Get logo ID by source.
+ public static let getBySource = """
+ SELECT Id, IsDeleted FROM Logos WHERE Source = ? LIMIT 1
+ """
+
+ /// Restore a soft-deleted logo.
+ public static let restore = """
+ UPDATE Logos SET IsDeleted = 0, UpdatedAt = ? WHERE Id = ?
+ """
+
+ /// Get logo ID from an item.
+ public static let getLogoIdFromItem = """
+ SELECT LogoId FROM Items WHERE Id = ?
+ """
+
+ /// Update item logo ID.
+ public static let updateItemLogoId = """
+ UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?
+ """
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
index 03888d856..f0209c370 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
@@ -391,10 +391,7 @@ public class PasskeyRepository: BaseRepository {
now: String
) throws {
// Get current logo ID from item
- let itemResults = try client.executeQuery(
- "SELECT LogoId FROM Items WHERE Id = ?",
- params: [itemId]
- )
+ let itemResults = try client.executeQuery(LogoQueries.getLogoIdFromItem, params: [itemId])
let logoDataParam = "av-base64-to-blob:\(logo.base64EncodedString())"
@@ -411,10 +408,7 @@ public class PasskeyRepository: BaseRepository {
let newLogoId = try getOrCreateLogo(source: source, logoData: logo, now: now)
// Update item with new logo ID
- try client.executeUpdate(
- "UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?",
- params: [newLogoId, now, itemId]
- )
+ try client.executeUpdate(LogoQueries.updateItemLogoId, params: [newLogoId, now, itemId])
}
}
@@ -484,10 +478,7 @@ public class PasskeyRepository: BaseRepository {
/// - Returns: The logo ID (existing or newly created)
private func getOrCreateLogo(source: String, logoData: Data, now: String) throws -> String {
// Check if a logo for this source already exists
- let existingLogos = try client.executeQuery(
- "SELECT Id, IsDeleted FROM Logos WHERE Source = ? LIMIT 1",
- params: [source]
- )
+ let existingLogos = try client.executeQuery(LogoQueries.getBySource, params: [source])
if let existingLogo = existingLogos.first,
let existingLogoId = existingLogo["Id"] as? String {
@@ -495,10 +486,7 @@ public class PasskeyRepository: BaseRepository {
// Sanity check: restore if soft-deleted
if isDeleted {
- try client.executeUpdate(
- "UPDATE Logos SET IsDeleted = 0, UpdatedAt = ? WHERE Id = ?",
- params: [now, existingLogoId]
- )
+ try client.executeUpdate(LogoQueries.restore, params: [now, existingLogoId])
}
return existingLogoId
}
diff --git a/apps/mobile-app/utils/db/queries/ItemQueries.ts b/apps/mobile-app/utils/db/queries/ItemQueries.ts
index 7683873ce..7047bc3dc 100644
--- a/apps/mobile-app/utils/db/queries/ItemQueries.ts
+++ b/apps/mobile-app/utils/db/queries/ItemQueries.ts
@@ -365,3 +365,37 @@ export class FieldHistoryQueries {
SET IsDeleted = 1, UpdatedAt = ?
WHERE Id = ?`;
}
+
+/**
+ * SQL query constants for Tag operations.
+ */
+export class TagQueries {
+ /**
+ * Get tags for multiple items.
+ * @param itemCount - Number of items (for placeholder generation)
+ * @returns Query with placeholders
+ */
+ public static getTagsForItems(itemCount: number): string {
+ const placeholders = Array(itemCount).fill('?').join(',');
+ return `
+ SELECT it.ItemId, t.Id, t.Name, t.Color
+ FROM ItemTags it
+ INNER JOIN Tags t ON it.TagId = t.Id
+ WHERE it.ItemId IN (${placeholders})
+ AND it.IsDeleted = 0
+ AND t.IsDeleted = 0
+ ORDER BY t.DisplayOrder`;
+ }
+
+ /**
+ * Get tags for a single item.
+ */
+ public static readonly GET_TAGS_FOR_ITEM = `
+ SELECT t.Id, t.Name, t.Color
+ FROM ItemTags it
+ INNER JOIN Tags t ON it.TagId = t.Id
+ WHERE it.ItemId = ?
+ AND it.IsDeleted = 0
+ AND t.IsDeleted = 0
+ ORDER BY t.DisplayOrder`;
+}
diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.ts
index 51cf05ec6..cc3976f5a 100644
--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts
+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts
@@ -2,43 +2,11 @@ import type { Item, ItemField, TotpCode, Attachment, FieldHistory } from '@/util
import { FieldKey, MAX_FIELD_HISTORY_RECORDS } from '@/utils/dist/core/models/vault';
import { BaseRepository } from '../BaseRepository';
-import { ItemQueries, FieldValueQueries, FieldDefinitionQueries, FieldHistoryQueries } from '../queries/ItemQueries';
+import { ItemQueries, FieldValueQueries, FieldDefinitionQueries, FieldHistoryQueries, TagQueries } from '../queries/ItemQueries';
import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';
import { ItemMapper, type ItemRow, type TagRow, type ItemWithDeletedAt } from '../mappers/ItemMapper';
import type { LogoRepository } from './LogoRepository';
-/**
- * SQL query constants for Item-related tag operations.
- */
-const TagQueries = {
- /**
- * Get tags for multiple items.
- */
- GET_TAGS_FOR_ITEMS: (itemCount: number): string => {
- const placeholders = Array(itemCount).fill('?').join(',');
- return `
- SELECT it.ItemId, t.Id, t.Name, t.Color
- FROM ItemTags it
- INNER JOIN Tags t ON it.TagId = t.Id
- WHERE it.ItemId IN (${placeholders})
- AND it.IsDeleted = 0
- AND t.IsDeleted = 0
- ORDER BY t.DisplayOrder`;
- },
-
- /**
- * Get tags for a single item.
- */
- GET_TAGS_FOR_ITEM: `
- SELECT t.Id, t.Name, t.Color
- FROM ItemTags it
- INNER JOIN Tags t ON it.TagId = t.Id
- WHERE it.ItemId = ?
- AND it.IsDeleted = 0
- AND t.IsDeleted = 0
- ORDER BY t.DisplayOrder`
-};
-
/**
* Repository for Item CRUD operations.
* Handles fetching, creating, updating, and deleting items with their related data.
@@ -138,7 +106,7 @@ export class ItemRepository extends BaseRepository {
// 4. Fetch tags for all items
let tagsByItem = new Map<string, { Id: string; Name: string; Color?: string }[]>();
if (await this.tableExists('ItemTags')) {
- const tagQuery = TagQueries.GET_TAGS_FOR_ITEMS(itemIds.length);
+ const tagQuery = TagQueries.getTagsForItems(itemIds.length);
const tagRows = await this.client.executeQuery<TagRow>(tagQuery, itemIds);
tagsByItem = ItemMapper.groupTagsByItem(tagRows);
}