Skip to content

Commit 14a6e24

Browse files
committed
feat: add note tagging through the desktop notes.sqlite
Read, filter, and assign QOwnNotes desktop tags from the note folder's notes.sqlite over WebDAV. A new notefolder-sqlite module validates and writes private copies of the file. Room mirrors tags with pending operations applied, and a trigger relinks tags when a note's confirmed name changes. Changes are replayed on the newest server file and uploaded with If-Match, so concurrent desktop edits are never overwritten. Tagging stays off when the file is missing. See ADR 0006.
1 parent 4bf7a9c commit 14a6e24

30 files changed

Lines changed: 3859 additions & 35 deletions

File tree

‎AGENTS.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,16 @@ The Gradle modules are declared in [`settings.gradle.kts`](settings.gradle.kts):
3434
| `data` | Room entities, DAOs, repositories, migrations, pull application, and push result application | `QOwnNotesDatabase.kt`, `Entities.kt`, `RoomNoteRepository.kt`, `RoomAccountRepository.kt`, `RoomPushStore.kt` |
3535
| `backend-nextcloud` | Nextcloud SSO integration, capability negotiation, Notes API transport, DTOs, and HTTP error classification | `NextcloudBackend.kt` |
3636
| `markdown-android` | Markwon rendering/editing, Android text widgets, safe images and links, syntax highlighting, selection, search highlights, and edit history | `MarkdownRenderer.kt`, `MarkdownEditor.kt`, `SelectableLinkMovementMethod.kt`, `TextEditHistory.kt` |
37+
| `notefolder-sqlite` | Validated reading and conservative writing of the QOwnNotes desktop `notes.sqlite` tag tables | `NoteFolderTagDatabase.kt` |
3738

3839
Keep these boundaries intact:
3940

4041
- UI code observes repositories and calls application-level operations. It must not call Room DAOs,
4142
Retrofit APIs, SSO APIs, or document providers directly.
4243
- `core` must not depend on Android or backend-specific types. Put reusable policy there.
4344
- Keep Room details in `data`, Nextcloud protocol details in `backend-nextcloud`, and Android text
44-
behavior in `markdown-android`.
45+
behavior in `markdown-android`. Only `notefolder-sqlite` opens desktop `notes.sqlite` files, and
46+
only as private copies.
4547
- Prefer constructor injection and the existing `ApplicationComponent`; do not add a DI framework
4648
without a concrete need.
4749

@@ -202,6 +204,7 @@ Test changes at the boundary they affect:
202204
- `data/src/androidTest`: Room repositories, transactions, and migrations.
203205
- `markdown-android/src/test`: pure Markdown/editor helpers.
204206
- `markdown-android/src/androidTest`: Android rendering and editor widgets.
207+
- `notefolder-sqlite/src/androidTest`: `notes.sqlite` validation and desktop-compatible writes.
205208
- `app/src/androidTest`: Compose navigation and end-to-end user flows using
206209
`TestQOwnNotesApplication` and `FakePullBackend`.
207210

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- Note tags shared with QOwnNotes desktop through the `notes.sqlite` file in the Nextcloud notes
13+
folder. The note list shows each note's tags and can filter by one or more tags. A note's
14+
"Tags" menu adds and removes existing or new tags, including offline. Changes are merged into
15+
the newest server version of the file and never overwrite concurrent desktop changes. Tagging
16+
stays off, with an explanation, when the notes folder has no `notes.sqlite`.
17+
1018
## [0.10.0] - 2026-09-28
1119

1220
### Added

‎app/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ dependencies {
9595
implementation(project(":data"))
9696
implementation(project(":backend-nextcloud"))
9797
implementation(project(":markdown-android"))
98+
implementation(project(":notefolder-sqlite"))
9899
implementation(platform(libs.androidx.compose.bom))
99100
implementation(libs.androidx.activity.compose)
100101
implementation(libs.androidx.appcompat)
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
package org.qownnotes.mobile
2+
3+
import android.database.sqlite.SQLiteDatabase
4+
import androidx.room.Room
5+
import androidx.test.core.app.ApplicationProvider
6+
import androidx.test.ext.junit.runners.AndroidJUnit4
7+
import java.io.File
8+
import kotlinx.coroutines.flow.first
9+
import kotlinx.coroutines.runBlocking
10+
import org.junit.After
11+
import org.junit.Assert.assertEquals
12+
import org.junit.Assert.assertNull
13+
import org.junit.Assert.assertTrue
14+
import org.junit.Before
15+
import org.junit.Test
16+
import org.junit.runner.RunWith
17+
import org.qownnotes.mobile.core.Account
18+
import org.qownnotes.mobile.core.NoteTag
19+
import org.qownnotes.mobile.core.NoteTagAvailability
20+
import org.qownnotes.mobile.core.NoteTagKey
21+
import org.qownnotes.mobile.core.NoteTagLink
22+
import org.qownnotes.mobile.data.QOwnNotesDatabase
23+
import org.qownnotes.mobile.data.RoomAccountRepository
24+
import org.qownnotes.mobile.data.RoomNoteTagRepository
25+
import org.qownnotes.mobile.notefolder.NoteFolderTagDatabase
26+
27+
@RunWith(AndroidJUnit4::class)
28+
class NoteTagSynchronizerTest {
29+
private val account = Account("account", "Account", "https://cloud.example", "sso", "user")
30+
private val key = NoteTagKey("Meeting", "Work")
31+
private lateinit var database: QOwnNotesDatabase
32+
private lateinit var directory: File
33+
private lateinit var tags: RoomNoteTagRepository
34+
private lateinit var server: FakeTagFileBackend
35+
private lateinit var synchronizer: NoteTagSynchronizer
36+
37+
@Before
38+
fun setUp() = runBlocking {
39+
val context = ApplicationProvider.getApplicationContext<android.content.Context>()
40+
database = Room.inMemoryDatabaseBuilder(context, QOwnNotesDatabase::class.java)
41+
.addCallback(QOwnNotesDatabase.CALLBACK)
42+
.build()
43+
RoomAccountRepository(database.accountDao()).save(account)
44+
directory = File(context.cacheDir, "tag-sync-${System.nanoTime()}").apply { mkdirs() }
45+
tags = RoomNoteTagRepository(database)
46+
server = FakeTagFileBackend(File(directory, "server"))
47+
synchronizer = NoteTagSynchronizer(tags, server, File(directory, "cache"))
48+
}
49+
50+
@After
51+
fun tearDown() {
52+
database.close()
53+
directory.deleteRecursively()
54+
}
55+
56+
@Test
57+
fun missingFileDisablesTagging() = runBlocking {
58+
synchronizer.synchronize(account)
59+
60+
val state = tags.observe(account.id).first()
61+
assertEquals(NoteTagAvailability.MISSING, state.availability)
62+
assertTrue(state.message!!.contains("notes.sqlite"))
63+
}
64+
65+
@Test
66+
fun downloadsOnlyWhenTheFileChanged() = runBlocking {
67+
server.create()
68+
synchronizer.synchronize(account)
69+
assertEquals(listOf(null), server.downloadEtags)
70+
assertEquals(
71+
listOf("Work"),
72+
tags.observe(account.id).first().tagsOf(key).map(NoteTag::name)
73+
)
74+
75+
synchronizer.synchronize(account)
76+
assertEquals(listOf(null, "\"1\""), server.downloadEtags)
77+
78+
server.edit("INSERT INTO tag (id, name) VALUES (5, 'Desktop')")
79+
server.edit(
80+
"INSERT INTO noteTagLink (tag_id, note_file_name, note_sub_folder_path) " +
81+
"VALUES (5, 'Meeting', 'Work')"
82+
)
83+
synchronizer.synchronize(account)
84+
assertEquals(
85+
listOf("Desktop", "Work"),
86+
tags.observe(account.id).first().tagsOf(key).map(NoteTag::name)
87+
)
88+
assertTrue(server.uploads.isEmpty())
89+
}
90+
91+
@Test
92+
fun uploadsPendingChangesWithIfMatch() = runBlocking {
93+
server.create()
94+
synchronizer.synchronize(account)
95+
tags.link(account.id, key, listOf("Mobile"))
96+
tags.unlink(account.id, key, listOf("Work"))
97+
98+
synchronizer.synchronize(account)
99+
100+
assertEquals(listOf("\"1\""), server.uploads)
101+
val remote = server.read()
102+
val mobile = remote.tags.single { it.name == "Mobile" }
103+
assertEquals(setOf(NoteTagLink(mobile.id, key)), remote.links)
104+
assertTrue(tags.pendingOperations(account.id).isEmpty())
105+
assertEquals("\"2\"", tags.fileState(account.id)!!.etag)
106+
assertEquals(mobile.id, tags.observe(account.id).first().tagsOf(key).single().id)
107+
}
108+
109+
@Test
110+
fun concurrentDesktopChangeIsKeptAndTheUploadRetried() = runBlocking {
111+
server.create()
112+
synchronizer.synchronize(account)
113+
tags.link(account.id, key, listOf("Mobile"))
114+
server.beforeUpload = {
115+
server.beforeUpload = null
116+
server.edit(
117+
"INSERT INTO noteTagLink (tag_id, note_file_name, note_sub_folder_path) " +
118+
"VALUES (1, 'Desktop note', '')"
119+
)
120+
}
121+
122+
synchronizer.synchronize(account)
123+
124+
assertEquals(listOf("\"1\"", "\"2\""), server.uploads)
125+
val remote = server.read()
126+
assertTrue(NoteTagLink(1, NoteTagKey("Desktop note", "")) in remote.links)
127+
assertTrue(remote.links.any { it.key == key && it.tagId != 1L })
128+
assertTrue(tags.pendingOperations(account.id).isEmpty())
129+
}
130+
131+
@Test
132+
fun operationsThatAreAlreadyAppliedAreNotUploaded() = runBlocking {
133+
server.create()
134+
synchronizer.synchronize(account)
135+
tags.link(account.id, key, listOf("Mobile"))
136+
server.edit("INSERT INTO tag (id, name) VALUES (9, 'mobile')")
137+
server.edit(
138+
"INSERT INTO noteTagLink (tag_id, note_file_name, note_sub_folder_path) " +
139+
"VALUES (9, 'Meeting', 'Work')"
140+
)
141+
142+
synchronizer.synchronize(account)
143+
144+
assertTrue(server.uploads.isEmpty())
145+
assertTrue(tags.pendingOperations(account.id).isEmpty())
146+
assertEquals(
147+
setOf(1L, 9L),
148+
tags.observe(account.id).first().tagIdsByNote[key]
149+
)
150+
}
151+
152+
@Test
153+
fun incompatibleFileIsNeverWritten() = runBlocking {
154+
server.create()
155+
synchronizer.synchronize(account)
156+
tags.link(account.id, key, listOf("Mobile"))
157+
server.edit("UPDATE appData SET value = '99'")
158+
159+
synchronizer.synchronize(account)
160+
161+
assertTrue(server.uploads.isEmpty())
162+
val state = tags.observe(account.id).first()
163+
assertEquals(NoteTagAvailability.AVAILABLE, state.availability)
164+
assertEquals(false, state.writable)
165+
assertEquals(1, tags.pendingOperations(account.id).size)
166+
167+
server.file.writeText("garbage")
168+
server.etag++
169+
synchronizer.synchronize(account)
170+
assertEquals(
171+
NoteTagAvailability.INCOMPATIBLE,
172+
tags.observe(account.id).first().availability
173+
)
174+
assertNull(tags.fileState(account.id)!!.etag)
175+
}
176+
177+
private class FakeTagFileBackend(val file: File) :
178+
org.qownnotes.mobile.core.NoteTagFileBackend {
179+
var etag = 0
180+
val downloadEtags = mutableListOf<String?>()
181+
val uploads = mutableListOf<String>()
182+
var beforeUpload: (() -> Unit)? = null
183+
184+
fun create() {
185+
file.parentFile!!.mkdirs()
186+
val params = SQLiteDatabase.OpenParams.Builder()
187+
.setOpenFlags(
188+
SQLiteDatabase.CREATE_IF_NECESSARY or SQLiteDatabase.NO_LOCALIZED_COLLATORS
189+
)
190+
.setJournalMode("DELETE")
191+
.build()
192+
SQLiteDatabase.openDatabase(file, params).use { database ->
193+
DESKTOP_SCHEMA.forEach(database::execSQL)
194+
}
195+
etag = 1
196+
}
197+
198+
fun edit(sql: String) {
199+
SQLiteDatabase.openDatabase(
200+
file,
201+
SQLiteDatabase.OpenParams.Builder()
202+
.setOpenFlags(SQLiteDatabase.NO_LOCALIZED_COLLATORS)
203+
.setJournalMode("DELETE")
204+
.build()
205+
).use { it.execSQL(sql) }
206+
etag++
207+
}
208+
209+
fun read() = NoteFolderTagDatabase.read(file).snapshot
210+
211+
override suspend fun downloadTagFile(
212+
account: Account,
213+
etag: String?
214+
): org.qownnotes.mobile.core.NoteTagFileDownload {
215+
downloadEtags += etag
216+
return when {
217+
!file.exists() -> org.qownnotes.mobile.core.NoteTagFileDownload.Missing
218+
etag == "\"${this.etag}\"" ->
219+
org.qownnotes.mobile.core.NoteTagFileDownload.NotModified
220+
else -> org.qownnotes.mobile.core.NoteTagFileDownload.Downloaded(
221+
file.readBytes(),
222+
"\"${this.etag}\""
223+
)
224+
}
225+
}
226+
227+
override suspend fun uploadTagFile(
228+
account: Account,
229+
content: ByteArray,
230+
etag: String
231+
): String {
232+
uploads += etag
233+
beforeUpload?.invoke()
234+
if (etag != "\"${this.etag}\"") {
235+
throw org.qownnotes.mobile.core.BackendException.Conflict()
236+
}
237+
file.writeBytes(content)
238+
this.etag++
239+
return "\"${this.etag}\""
240+
}
241+
}
242+
243+
private companion object {
244+
val DESKTOP_SCHEMA = listOf(
245+
"CREATE TABLE appData (name VARCHAR(255) PRIMARY KEY, value VARCHAR(255))",
246+
"""CREATE TABLE tag (id INTEGER PRIMARY KEY, name VARCHAR(255) COLLATE NOCASE,
247+
priority INTEGER DEFAULT 0, created DATETIME DEFAULT current_timestamp,
248+
parent_id INTEGER DEFAULT 0, color VARCHAR(20), dark_color VARCHAR(20),
249+
updated DATETIME DEFAULT current_timestamp)""",
250+
"CREATE UNIQUE INDEX idxUniqueTag ON tag (name, parent_id)",
251+
"""CREATE TABLE noteTagLink (id INTEGER PRIMARY KEY, tag_id INTEGER,
252+
note_file_name VARCHAR(255) DEFAULT '', note_sub_folder_path TEXT DEFAULT '',
253+
created DATETIME DEFAULT current_timestamp, stale_date DATETIME DEFAULT NULL)""",
254+
"""CREATE UNIQUE INDEX idxUniqueTagNoteLink
255+
ON noteTagLink (tag_id, note_file_name, note_sub_folder_path)""",
256+
"INSERT INTO appData (name, value) VALUES ('database_version', '16')",
257+
"INSERT INTO tag (id, name) VALUES (1, 'Work')",
258+
"""INSERT INTO noteTagLink (tag_id, note_file_name, note_sub_folder_path)
259+
VALUES (1, 'Meeting', 'Work')"""
260+
)
261+
}
262+
}

0 commit comments

Comments
 (0)