summaryrefslogtreecommitdiffstats
path: root/internal/db/posts.go
diff options
context:
space:
mode:
authorivar <i@oiee.no>2026-04-04 16:36:18 +0200
committerivar <i@oiee.no>2026-04-04 16:36:18 +0200
commit0d8f53520a2143b22e2246ab1ec25e0860e90dad (patch)
treeda1798fed5b7f4847538ee7b355a0397f28bbc33 /internal/db/posts.go
parenta6355e7a6530af3335c4cd8af05f1e9c8b978169 (diff)
downloadnebbet.no-0d8f53520a2143b22e2246ab1ec25e0860e90dad.tar.xz
nebbet.no-0d8f53520a2143b22e2246ab1ec25e0860e90dad.zip
fix: make slug rename and content update atomic via RenameAndUpsertPost
Previously RenamePost + UpsertPost were two separate DB calls; a failure between them left the post at the new slug with stale content. The new RenameAndUpsertPost method does both in a single transaction. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Diffstat (limited to 'internal/db/posts.go')
-rw-r--r--internal/db/posts.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/internal/db/posts.go b/internal/db/posts.go
index c1360ab..ab231db 100644
--- a/internal/db/posts.go
+++ b/internal/db/posts.go
@@ -200,3 +200,55 @@ func (m *MetaDB) RenamePost(oldSlug, newSlug string) error {
return tx.Commit()
}
+
+// RenameAndUpsertPost atomically renames a post from oldSlug to p.Slug and
+// updates its content, collapsing any redirect chains and adding a redirect
+// from oldSlug to p.Slug — all in a single transaction.
+func (m *MetaDB) RenameAndUpsertPost(oldSlug string, p PostRecord) error {
+ if oldSlug == p.Slug {
+ return m.UpsertPost(p)
+ }
+ tx, err := m.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ tags, _ := json.Marshal(p.Tags)
+ draftInt := 0
+ if p.Draft {
+ draftInt = 1
+ }
+
+ // Insert new record with updated content
+ if _, err = tx.Exec(`
+ INSERT INTO posts (slug, title, date, tags, draft, blocks, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ p.Slug, p.Title, p.Date, string(tags), draftInt, p.Blocks, p.UpdatedAt,
+ ); err != nil {
+ return err
+ }
+
+ // Delete old record
+ if _, err = tx.Exec(`DELETE FROM posts WHERE slug = ?`, oldSlug); err != nil {
+ return err
+ }
+
+ // Collapse existing redirect chains
+ if _, err = tx.Exec(
+ `UPDATE redirects SET to_slug = ? WHERE to_slug = ?`, p.Slug, oldSlug,
+ ); err != nil {
+ return err
+ }
+
+ // Add redirect from oldSlug to new slug
+ if _, err = tx.Exec(`
+ INSERT INTO redirects (from_slug, to_slug) VALUES (?, ?)
+ ON CONFLICT(from_slug) DO UPDATE SET to_slug = excluded.to_slug`,
+ oldSlug, p.Slug,
+ ); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}