feat: implement article version content storage and reconstruction logic; enhance article repository with version management

This commit is contained in:
2026-04-07 22:21:16 +08:00
parent d0f0271346
commit 41f8e0621e
9 changed files with 324 additions and 48 deletions
@@ -30,11 +30,12 @@ type ArticleRepository interface {
}
type articleRepository struct {
q generated.Querier
db generated.DBTX
q generated.Querier
}
func NewArticleRepository(db generated.DBTX) ArticleRepository {
return &articleRepository{q: newQuerier(db)}
return &articleRepository{db: db, q: newQuerier(db)}
}
func (r *articleRepository) CreateArticle(ctx context.Context, input CreateArticleInput) (int64, error) {
@@ -46,15 +47,42 @@ func (r *articleRepository) CreateArticle(ctx context.Context, input CreateArtic
}
func (r *articleRepository) CreateArticleVersion(ctx context.Context, input CreateArticleVersionInput) (int64, error) {
return r.q.CreateArticleVersion(ctx, generated.CreateArticleVersionParams{
ArticleID: input.ArticleID,
VersionNo: int32(input.VersionNo),
Title: pgText(&input.Title),
HtmlContent: pgText(&input.HTMLContent),
MarkdownContent: pgText(&input.MarkdownContent),
WordCount: int32(input.WordCount),
SourceLabel: pgText(&input.SourceLabel),
previous, err := loadLatestArticleVersionContent(ctx, r.db, input.ArticleID)
if err != nil {
return 0, err
}
storedHTML, storedMarkdown := buildArticleVersionDiffStorage(*previous, ArticleVersionContent{
HTMLContent: stringPtr(input.HTMLContent),
MarkdownContent: stringPtr(input.MarkdownContent),
})
var versionID int64
err = r.db.QueryRow(ctx, `
INSERT INTO article_versions (
article_id,
version_no,
title,
html_content,
markdown_content,
word_count,
source_label
)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id
`,
input.ArticleID,
input.VersionNo,
pgText(&input.Title),
pgText(storedHTML),
pgText(storedMarkdown),
input.WordCount,
pgText(&input.SourceLabel),
).Scan(&versionID)
if err != nil {
return 0, err
}
return versionID, nil
}
func (r *articleRepository) UpdateArticleCurrentVersion(ctx context.Context, articleID, tenantID, versionID int64) error {
@@ -0,0 +1,163 @@
package repository
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/sergi/go-diff/diffmatchpatch"
"github.com/geo-platform/tenant-api/internal/tenant/repository/generated"
)
type ArticleVersionContent struct {
HTMLContent *string
MarkdownContent *string
}
type storedArticleVersionContent struct {
VersionNo int
HTMLContent *string
MarkdownContent *string
}
func LoadArticleVersionContent(
ctx context.Context,
db generated.DBTX,
articleID int64,
versionID int64,
) (*ArticleVersionContent, error) {
rows, err := db.Query(ctx, `
SELECT version_no, html_content, markdown_content
FROM article_versions
WHERE article_id = $1
AND version_no <= (
SELECT version_no
FROM article_versions
WHERE id = $2 AND article_id = $1
)
ORDER BY version_no ASC
`, articleID, versionID)
if err != nil {
return nil, err
}
defer rows.Close()
versions, err := collectStoredArticleVersionContents(rows)
if err != nil {
return nil, err
}
if len(versions) == 0 {
return nil, pgx.ErrNoRows
}
return reconstructStoredArticleVersionContents(versions)
}
func loadLatestArticleVersionContent(
ctx context.Context,
db generated.DBTX,
articleID int64,
) (*ArticleVersionContent, error) {
rows, err := db.Query(ctx, `
SELECT version_no, html_content, markdown_content
FROM article_versions
WHERE article_id = $1
ORDER BY version_no ASC
`, articleID)
if err != nil {
return nil, err
}
defer rows.Close()
versions, err := collectStoredArticleVersionContents(rows)
if err != nil {
return nil, err
}
if len(versions) == 0 {
return &ArticleVersionContent{}, nil
}
return reconstructStoredArticleVersionContents(versions)
}
func collectStoredArticleVersionContents(rows pgx.Rows) ([]storedArticleVersionContent, error) {
versions := make([]storedArticleVersionContent, 0)
for rows.Next() {
var version storedArticleVersionContent
if err := rows.Scan(&version.VersionNo, &version.HTMLContent, &version.MarkdownContent); err != nil {
return nil, err
}
versions = append(versions, version)
}
if err := rows.Err(); err != nil {
return nil, err
}
return versions, nil
}
func buildArticleVersionDiffStorage(previous, current ArticleVersionContent) (*string, *string) {
return stringPtr(articleVersionPatchText(textValue(previous.HTMLContent), textValue(current.HTMLContent))),
stringPtr(articleVersionPatchText(textValue(previous.MarkdownContent), textValue(current.MarkdownContent)))
}
func reconstructStoredArticleVersionContents(versions []storedArticleVersionContent) (*ArticleVersionContent, error) {
var html string
var markdown string
for _, version := range versions {
nextHTML, err := applyArticleVersionPatch(html, version.HTMLContent)
if err != nil {
return nil, fmt.Errorf("apply html patch for version %d: %w", version.VersionNo, err)
}
nextMarkdown, err := applyArticleVersionPatch(markdown, version.MarkdownContent)
if err != nil {
return nil, fmt.Errorf("apply markdown patch for version %d: %w", version.VersionNo, err)
}
html = nextHTML
markdown = nextMarkdown
}
result := &ArticleVersionContent{}
result.HTMLContent = stringPtr(html)
result.MarkdownContent = stringPtr(markdown)
return result, nil
}
func articleVersionPatchText(previous, current string) string {
dmp := diffmatchpatch.New()
patches := dmp.PatchMake(previous, current)
return dmp.PatchToText(patches)
}
func applyArticleVersionPatch(base string, patchText *string) (string, error) {
if patchText == nil || *patchText == "" {
return base, nil
}
dmp := diffmatchpatch.New()
patches, err := dmp.PatchFromText(*patchText)
if err != nil {
return "", err
}
next, applied := dmp.PatchApply(patches, base)
for _, ok := range applied {
if !ok {
return "", fmt.Errorf("patch apply failed")
}
}
return next, nil
}
func textValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func stringPtr(value string) *string {
copied := value
return &copied
}
@@ -0,0 +1,67 @@
package repository
import "testing"
func TestBuildArticleVersionDiffStorage_ReconstructsFromEmptyBase(t *testing.T) {
current := ArticleVersionContent{
HTMLContent: stringPtr(""),
MarkdownContent: stringPtr("# First version\n\nHello world"),
}
storedHTML, storedMarkdown := buildArticleVersionDiffStorage(ArticleVersionContent{}, current)
reconstructed, err := reconstructStoredArticleVersionContents([]storedArticleVersionContent{
{
VersionNo: 1,
HTMLContent: storedHTML,
MarkdownContent: storedMarkdown,
},
})
if err != nil {
t.Fatalf("reconstruct stored content: %v", err)
}
if textValue(reconstructed.HTMLContent) != textValue(current.HTMLContent) {
t.Fatalf("unexpected html content: %q", textValue(reconstructed.HTMLContent))
}
if textValue(reconstructed.MarkdownContent) != textValue(current.MarkdownContent) {
t.Fatalf("unexpected markdown content: %q", textValue(reconstructed.MarkdownContent))
}
}
func TestReconstructStoredArticleVersionContents_DiffChain(t *testing.T) {
_, markdownV1 := buildArticleVersionDiffStorage(
ArticleVersionContent{},
ArticleVersionContent{MarkdownContent: stringPtr("alpha")},
)
_, markdownV2 := buildArticleVersionDiffStorage(
ArticleVersionContent{MarkdownContent: stringPtr("alpha")},
ArticleVersionContent{MarkdownContent: stringPtr("alpha beta")},
)
_, markdownV3 := buildArticleVersionDiffStorage(
ArticleVersionContent{MarkdownContent: stringPtr("alpha beta")},
ArticleVersionContent{MarkdownContent: stringPtr("alpha beta gamma")},
)
reconstructed, err := reconstructStoredArticleVersionContents([]storedArticleVersionContent{
{
VersionNo: 1,
MarkdownContent: markdownV1,
},
{
VersionNo: 2,
MarkdownContent: markdownV2,
},
{
VersionNo: 3,
MarkdownContent: markdownV3,
},
})
if err != nil {
t.Fatalf("reconstruct stored content: %v", err)
}
if got := textValue(reconstructed.MarkdownContent); got != "alpha beta gamma" {
t.Fatalf("unexpected markdown content: %q", got)
}
}
@@ -4,9 +4,6 @@ import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
"github.com/geo-platform/tenant-api/internal/shared/contentstats"
"github.com/geo-platform/tenant-api/internal/tenant/repository/generated"
)
@@ -76,7 +73,7 @@ func (r *workspaceRepository) GetRecentArticles(ctx context.Context, tenantID in
GenerationMode: nullableText(row.GenerationMode),
CreatedAt: timeFromTimestamp(row.CreatedAt),
Title: nullableText(row.Title),
WordCount: resolveWorkspaceWordCount(row.MarkdownContent, intFromInt4(row.WordCount)),
WordCount: intFromInt4(row.WordCount),
SourceLabel: nullableText(row.SourceLabel),
TemplateName: nullableText(row.TemplateName),
})
@@ -107,12 +104,3 @@ func (r *workspaceRepository) GetActivePlanForTenant(ctx context.Context, tenant
EndAt: timeFromTimestamp(row.EndAt),
}, nil
}
func resolveWorkspaceWordCount(markdown pgtype.Text, stored int) int {
if markdown.Valid {
if counted := contentstats.CountWords(markdown.String); counted > 0 {
return counted
}
}
return stored
}