Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,20 @@ object MigrationRunner {
"""
)
),
Migration(
name = "pages_backlink_count",
statements = listOf(
"ALTER TABLE pages ADD COLUMN IF NOT EXISTS backlink_count INTEGER NOT NULL DEFAULT 0",
// Backfill existing rows. Runs once on an existing DB; in-memory test DBs are
// empty at migration time so this is a no-op there.
"""
UPDATE pages SET backlink_count = (
SELECT COUNT(*) FROM blocks
WHERE blocks.content LIKE '%[[' || pages.name || ']]%'
)
"""
)
),
)

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,13 @@ class RestrictedDatabaseQueries(private val queries: SteleDatabaseQueries) {
@DirectSqlWrite
fun pragmaWalCheckpointTruncate() = queries.pragmaWalCheckpointTruncate()

@DirectSqlWrite
fun recomputeAllBacklinkCounts(): QueryResult<Long> = queries.recomputeAllBacklinkCounts()

@DirectSqlWrite
fun recomputeBacklinkCountForPage(name: String): QueryResult<Long> =
queries.recomputeBacklinkCountForPage(name)

// ── Git config writes ─────────────────────────────────────────────────────

@DirectSqlWrite
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,8 @@ data class DateRange(
data class SearchedPage(
val page: Page,
val snippet: String? = null,
val bm25Score: Double = 0.0
val bm25Score: Double = 0.0,
val backlinkCount: Int = 0
)

/** A block result with an optional snippet and raw BM25 score from FTS5. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ class SqlDelightBlockRepository(

private val hierarchyTtlMs = 120_000L // 2 minutes

private fun extractWikilinks(content: String): Set<String> =
WIKILINK_REGEX.findAll(content).map { it.groupValues[1].trim() }.toHashSet()

override fun getBlockByUuid(uuid: String): Flow<Either<DomainError, Block?>> =
queries.selectBlockByUuid(uuid)
.asFlow()
Expand Down Expand Up @@ -269,6 +272,7 @@ class SqlDelightBlockRepository(
block.contentHash ?: ContentHasher.sha256ForContent(block.content),
block.blockType
)
extractWikilinks(block.content).forEach { queries.recomputeBacklinkCountForPage(it) }
Unit.right()
} catch (e: CancellationException) {
throw e
Expand All @@ -280,8 +284,12 @@ class SqlDelightBlockRepository(
override suspend fun updateBlockContentOnly(blockUuid: String, content: String): Either<DomainError, Unit> =
withContext(PlatformDispatcher.DB) {
try {
val oldContent = blockCache.get(blockUuid)?.content
?: queries.selectBlockByUuid(blockUuid).executeAsOneOrNull()?.content ?: ""
queries.updateBlockContent(content, Clock.System.now().toEpochMilliseconds(), ContentHasher.sha256ForContent(content), blockUuid)
blockCache.remove(blockUuid)
val changedPages = extractWikilinks(oldContent) + extractWikilinks(content)
changedPages.forEach { queries.recomputeBacklinkCountForPage(it) }
Unit.right()
} catch (e: CancellationException) {
throw e
Expand All @@ -308,13 +316,18 @@ class SqlDelightBlockRepository(
try {
val block = queries.selectBlockByUuid(blockUuid).executeAsOneOrNull()
if (block != null) {
val wikilinkPages = mutableSetOf<String>()
wikilinkPages.addAll(extractWikilinks(block.content))
if (deleteChildren) {
val uuidsToDelete = mutableListOf<String>(block.uuid)
var index = 0
while (index < uuidsToDelete.size) {
val currentUuid = uuidsToDelete[index]
val children = queries.selectBlockChildren(currentUuid, Long.MAX_VALUE, 0L).executeAsList()
children.forEach { uuidsToDelete.add(it.uuid) }
children.forEach { child ->
uuidsToDelete.add(child.uuid)
wikilinkPages.addAll(extractWikilinks(child.content))
}
index++
}

Expand All @@ -334,7 +347,7 @@ class SqlDelightBlockRepository(
}
queries.deleteBlockByUuid(block.uuid)
}

wikilinkPages.forEach { queries.recomputeBacklinkCountForPage(it) }
}
Unit.right()
} catch (e: CancellationException) {
Expand All @@ -346,17 +359,22 @@ class SqlDelightBlockRepository(

override suspend fun deleteBulk(blockUuids: List<String>, deleteChildren: Boolean): Either<DomainError, Unit> = withContext(PlatformDispatcher.DB) {
try {
val wikilinkPages = mutableSetOf<String>()
queries.transaction {
blockUuids.forEach { uuid ->
val block = queries.selectBlockByUuid(uuid).executeAsOneOrNull() ?: return@forEach
wikilinkPages.addAll(extractWikilinks(block.content))
if (deleteChildren) {
// Collect the full subtree
val uuidsToDelete = mutableListOf(block.uuid)
var index = 0
while (index < uuidsToDelete.size) {
val currentUuid = uuidsToDelete[index]
val children = queries.selectBlockChildren(currentUuid, Long.MAX_VALUE, 0L).executeAsList()
children.forEach { uuidsToDelete.add(it.uuid) }
children.forEach { child ->
uuidsToDelete.add(child.uuid)
wikilinkPages.addAll(extractWikilinks(child.content))
}
Comment on lines +374 to +377
index++
}
// Chain repair for the top-level block being deleted
Expand All @@ -374,6 +392,7 @@ class SqlDelightBlockRepository(
queries.deleteBlockByUuid(block.uuid)
}
}
wikilinkPages.forEach { queries.recomputeBacklinkCountForPage(it) }
}
Unit.right()
} catch (e: CancellationException) {
Expand Down Expand Up @@ -1015,4 +1034,8 @@ class SqlDelightBlockRepository(
hierarchyCache.invalidateAll()
ancestorsCache.invalidateAll()
}

companion object {
private val WIKILINK_REGEX = Regex("""\[\[([^\]]+)\]\]""")
}
}
Loading
Loading