Jelajahi Sumber

fix(storage): align entry ID query sorting and visibility

Join categories in ID-only queries and resolve supported sort columns to
qualified identifiers without fetching full entry data. Preserve search
ranking, pagination limits, and compatibility query behavior.

Add a final same-direction ID tiebreak to native entry queries after
search ranking. This overlaps with the native API portion of PR #4559;
UI and Google Reader handlers remain unchanged.

Cover sorting, visibility, filtered counts, stable pagination, direction
normalization, and compatibility queries, and run storage integration
tests from the integration-test target.
AiraNadih 1 bulan lalu
induk
melakukan
3ffed17141

+ 2 - 0
Makefile

@@ -133,6 +133,8 @@ integration-test:
 		sleep 1; \
 	done
 
+	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/storage
+
 	TEST_MINIFLUX_BASE_URL=http://127.0.0.1:8080 \
 	TEST_MINIFLUX_ADMIN_USERNAME=admin \
 	TEST_MINIFLUX_ADMIN_PASSWORD=test123 \

+ 4 - 0
internal/api/entry_handlers.go

@@ -194,6 +194,10 @@ func (h *handler) findEntries(w http.ResponseWriter, r *http.Request, feedID int
 	}
 
 	builder = configureFilters(builder, r)
+	// Keep the unique tiebreak after any search ranking expression.
+	if order != "id" {
+		builder.WithSorting("id", direction)
+	}
 
 	entries, count, err := builder.GetEntriesWithCount()
 	if err != nil {

+ 96 - 0
internal/api/entry_pagination_integration_test.go

@@ -0,0 +1,96 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package api
+
+import (
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"slices"
+	"strings"
+	"testing"
+
+	miniflux "miniflux.app/v2/client"
+)
+
+func TestGetEntriesStablePaginationWithIdenticalPublishedDates(t *testing.T) {
+	t.Parallel()
+
+	testConfig := newIntegrationTestConfig()
+	if !testConfig.isConfigured() {
+		t.Skip(skipIntegrationTestsMessage)
+	}
+
+	const (
+		entryCount = 120
+		pageSize   = 25
+	)
+
+	var feed strings.Builder
+	feed.WriteString(`<?xml version="1.0"?><rss version="2.0"><channel><title>Pagination</title><link>https://example.org</link><description>Pagination test</description>`)
+	for i := range entryCount {
+		fmt.Fprintf(&feed, `<item><guid>pagination-%d</guid><title>Shared pagination title</title><link>https://example.org/%d</link><pubDate>Wed, 01 Jan 2025 00:00:00 GMT</pubDate><description>Shared pagination content</description></item>`, i, i)
+	}
+	feed.WriteString(`</channel></rss>`)
+	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/rss+xml")
+		fmt.Fprint(w, feed.String())
+	}))
+	defer server.Close()
+
+	adminClient := miniflux.NewClient(testConfig.testBaseURL, testConfig.testAdminUsername, testConfig.testAdminPassword)
+	user, err := adminClient.CreateUser(testConfig.genRandomUsername(), testConfig.testRegularPassword, false)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer adminClient.DeleteUser(user.ID)
+
+	client := miniflux.NewClient(testConfig.testBaseURL, user.Username, testConfig.testRegularPassword)
+	if _, err := client.CreateFeed(&miniflux.FeedCreationRequest{FeedURL: server.URL}); err != nil {
+		t.Fatal(err)
+	}
+
+	all, err := client.EntryIDs(nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if all.Total != entryCount || len(all.EntryIDs) != entryCount {
+		t.Fatalf("Got %d IDs and total %d, want %d", len(all.EntryIDs), all.Total, entryCount)
+	}
+
+	for _, direction := range []string{"asc", "desc"} {
+		want := slices.Clone(all.EntryIDs)
+		slices.Sort(want)
+		if direction == "desc" {
+			slices.Reverse(want)
+		}
+
+		for _, search := range []string{"", "pagination"} {
+			t.Run(direction+"/search="+search, func(t *testing.T) {
+				var got []int64
+				for offset := 0; offset < len(want); offset += pageSize {
+					page, err := client.Entries(&miniflux.Filter{
+						Order:     "published_at",
+						Direction: direction,
+						Search:    search,
+						Limit:     pageSize,
+						Offset:    offset,
+					})
+					if err != nil {
+						t.Fatal(err)
+					}
+					if page.Total != len(want) {
+						t.Fatalf("Got total %d, want %d", page.Total, len(want))
+					}
+					for _, entry := range page.Entries {
+						got = append(got, entry.ID)
+					}
+				}
+				if !slices.Equal(got, want) {
+					t.Fatalf("Got IDs %v, want %v", got, want)
+				}
+			})
+		}
+	}
+}

+ 57 - 13
internal/storage/entry_query_builder.go

@@ -21,13 +21,19 @@ type EntryQueryBuilder struct {
 	store           *Storage
 	args            []any
 	conditions      []string
-	sortExpressions []string
+	sortExpressions []entrySortExpression
 	limit           int
 	offset          int
 	fetchEnclosures bool
 	excludeContent  bool
 }
 
+type entrySortExpression struct {
+	column     string
+	direction  string
+	expression string
+}
+
 // WithEnclosures fetches enclosures for each entry.
 func (e *EntryQueryBuilder) WithEnclosures() *EntryQueryBuilder {
 	e.fetchEnclosures = true
@@ -51,9 +57,9 @@ func (e *EntryQueryBuilder) WithSearchQuery(query string) *EntryQueryBuilder {
 
 		// 0.0000001 = 0.1 / (seconds_in_a_day)
 
-		e.sortExpressions = append(e.sortExpressions,
-			fmt.Sprintf("ts_rank(document_vectors, websearch_to_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001 DESC", nArgs),
-		)
+		e.sortExpressions = append(e.sortExpressions, entrySortExpression{
+			expression: fmt.Sprintf("ts_rank(document_vectors, websearch_to_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001 DESC", nArgs),
+		})
 	}
 	return e
 }
@@ -191,11 +197,14 @@ func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
 func (e *EntryQueryBuilder) WithSorting(column, direction string) *EntryQueryBuilder {
 	switch {
 	case strings.EqualFold(direction, "ASC"):
-		e.sortExpressions = append(e.sortExpressions, pq.QuoteIdentifier(column)+" ASC")
+		direction = "ASC"
 	case strings.EqualFold(direction, "DESC"):
-		e.sortExpressions = append(e.sortExpressions, pq.QuoteIdentifier(column)+" DESC")
+		direction = "DESC"
+	default:
+		return e
 	}
 
+	e.sortExpressions = append(e.sortExpressions, entrySortExpression{column: column, direction: direction})
 	return e
 }
 
@@ -295,6 +304,11 @@ func (e *EntryQueryBuilder) GetEntriesWithCount() (model.Entries, int, error) {
 // When withCount is true, count(*) OVER() is included in the SELECT and the total
 // count of matching rows is returned; otherwise the returned count is 0.
 func (e *EntryQueryBuilder) fetchEntries(withCount bool) (model.Entries, int, error) {
+	sorting, err := e.buildSorting(false)
+	if err != nil {
+		return nil, 0, err
+	}
+
 	countColumn := ""
 	if withCount {
 		countColumn = "count(*) OVER(),"
@@ -353,7 +367,7 @@ func (e *EntryQueryBuilder) fetchEntries(withCount bool) (model.Entries, int, er
 			icons i ON i.id=fi.icon_id
 		INNER JOIN
 			users u ON u.id=e.user_id
-		WHERE ` + e.buildCondition() + " " + e.buildSorting()
+		WHERE ` + e.buildCondition() + " " + sorting
 
 	rows, err := e.store.db.Query(query, e.args...)
 	if err != nil {
@@ -466,6 +480,11 @@ func (e *EntryQueryBuilder) fetchEntries(withCount bool) (model.Entries, int, er
 
 // GetEntryIDs returns a list of entry IDs that match the condition.
 func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
+	sorting, err := e.buildSorting(true)
+	if err != nil {
+		return nil, err
+	}
+
 	query := `
 		SELECT
 			e.id
@@ -475,7 +494,9 @@ func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
 			feeds f
 		ON
 			f.id=e.feed_id
-		WHERE ` + e.buildCondition() + " " + e.buildSorting()
+		LEFT JOIN
+			categories c ON c.id=f.category_id
+		WHERE ` + e.buildCondition() + " " + sorting
 
 	rows, err := e.store.db.Query(query, e.args...)
 	if err != nil {
@@ -523,11 +544,34 @@ func (e *EntryQueryBuilder) buildCondition() string {
 	return strings.Join(e.conditions, " AND ")
 }
 
-func (e *EntryQueryBuilder) buildSorting() string {
-	var parts string
+func (e *EntryQueryBuilder) buildSorting(entryIDsOnly bool) (string, error) {
+	sortExpressions := make([]string, 0, len(e.sortExpressions))
+	for _, sorting := range e.sortExpressions {
+		if sorting.expression != "" {
+			sortExpressions = append(sortExpressions, sorting.expression)
+			continue
+		}
 
-	if len(e.sortExpressions) > 0 {
-		parts += " ORDER BY " + strings.Join(e.sortExpressions, ", ")
+		column := pq.QuoteIdentifier(sorting.column)
+		if entryIDsOnly {
+			// ID-only queries cannot rely on the SELECT aliases used by GetEntries.
+			switch sorting.column {
+			case "id", "status", "changed_at", "published_at", "created_at", "title", "author":
+				column = `"e".` + column
+			case "category_title":
+				column = `"c"."title"`
+			case "category_id":
+				column = `"f".` + column
+			default:
+				return "", fmt.Errorf("store: invalid entry ID sorting column: %q", sorting.column)
+			}
+		}
+		sortExpressions = append(sortExpressions, column+" "+sorting.direction)
+	}
+
+	var parts string
+	if len(sortExpressions) > 0 {
+		parts += " ORDER BY " + strings.Join(sortExpressions, ", ")
 	}
 
 	if e.limit > 0 {
@@ -538,7 +582,7 @@ func (e *EntryQueryBuilder) buildSorting() string {
 		parts += " OFFSET " + strconv.Itoa(e.offset)
 	}
 
-	return parts
+	return parts, nil
 }
 
 // NewEntryQueryBuilder returns a new EntryQueryBuilder.

+ 320 - 0
internal/storage/entry_query_builder_integration_test.go

@@ -0,0 +1,320 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package storage
+
+import (
+	"database/sql"
+	"os"
+	"slices"
+	"testing"
+	"time"
+
+	"miniflux.app/v2/internal/model"
+)
+
+func newEntryQueryTestStorage(t *testing.T) *Storage {
+	t.Helper()
+
+	databaseURL := os.Getenv("TEST_DATABASE_URL")
+	if databaseURL == "" {
+		t.Skip("Set TEST_DATABASE_URL to a migrated PostgreSQL database to run storage integration tests")
+	}
+
+	db, err := sql.Open("postgres", databaseURL)
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { db.Close() })
+
+	// Keep temporary tables on the same connection and leave the database unchanged.
+	db.SetMaxOpenConns(1)
+	_, err = db.Exec(`
+		SET TIME ZONE 'UTC';
+		CREATE TEMP TABLE users (LIKE users INCLUDING DEFAULTS);
+		CREATE TEMP TABLE categories (LIKE categories INCLUDING DEFAULTS);
+		CREATE TEMP TABLE feeds (LIKE feeds INCLUDING DEFAULTS);
+		CREATE TEMP TABLE entries (LIKE entries INCLUDING DEFAULTS);
+		CREATE TEMP TABLE feed_icons (LIKE feed_icons INCLUDING DEFAULTS);
+		CREATE TEMP TABLE icons (LIKE icons INCLUDING DEFAULTS);
+
+		INSERT INTO users (id, username) VALUES (1, 'entry-query-user'), (2, 'entry-query-other');
+		INSERT INTO categories (id, user_id, title, hide_globally) VALUES
+			(10, 1, 'Zulu category', false),
+			(20, 1, 'Alpha category', false),
+			(30, 1, 'Hidden category', true),
+			(40, 2, 'Other category', false);
+		INSERT INTO feeds (id, user_id, category_id, title, feed_url, site_url, hide_globally) VALUES
+			(11, 1, 10, 'Alpha feed', 'https://example.org/11', 'https://example.org', false),
+			(12, 1, 20, 'Zulu feed', 'https://example.org/12', 'https://example.org', false),
+			(13, 1, 10, 'Hidden feed', 'https://example.org/13', 'https://example.org', true),
+			(14, 1, 30, 'Visible feed in hidden category', 'https://example.org/14', 'https://example.org', false),
+			(15, 1, 30, 'Hidden feed in hidden category', 'https://example.org/15', 'https://example.org', true),
+			(16, 2, 40, 'Other feed', 'https://example.org/16', 'https://example.org', false);
+		INSERT INTO entries (id, user_id, feed_id, hash, title, url, author, content, status, starred,
+			published_at, created_at, changed_at, document_vectors, tags) VALUES
+			(1, 1, 11, '1', 'Zulu entry', 'https://example.org/1', 'Bravo', 'shared content', 'unread', false,
+				'2025-01-03', '2025-01-02', '2025-01-04', to_tsvector('shared'), ARRAY['one', 'two']),
+			(2, 1, 12, '2', 'Alpha entry', 'https://example.org/2', 'Charlie', 'shared content', 'read', true,
+				'2025-01-01', '2025-01-03', '2025-01-02', to_tsvector('shared'), ARRAY['one']),
+			(3, 1, 11, '3', 'Alpha entry', 'https://example.org/3', 'Alpha', 'shared content', 'unread', false,
+				'2025-01-02', '2025-01-01', '2025-01-03', to_tsvector('shared'), ARRAY['one', 'two']),
+			(4, 1, 13, '4', 'Hidden feed entry', 'https://example.org/4', '', '', 'unread', true,
+				'2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('hidden'), ARRAY[]::text[]),
+			(5, 1, 14, '5', 'Hidden category entry', 'https://example.org/5', '', '', 'read', false,
+				'2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('hidden'), ARRAY[]::text[]),
+			(6, 1, 15, '6', 'Both hidden entry', 'https://example.org/6', '', '', 'unread', false,
+				'2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('hidden'), ARRAY[]::text[]),
+			(7, 2, 16, '7', 'Other user entry', 'https://example.org/7', '', '', 'unread', true,
+				'2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('shared'), ARRAY['one', 'two']);
+	`)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	return NewStorage(db)
+}
+
+func TestGetEntryIDsSorting(t *testing.T) {
+	store := newEntryQueryTestStorage(t)
+
+	for _, test := range []struct {
+		order string
+		ids   []int64
+	}{
+		{"id", []int64{1, 2, 3}},
+		{"status", []int64{1, 3, 2}},
+		{"changed_at", []int64{2, 3, 1}},
+		{"published_at", []int64{2, 3, 1}},
+		{"created_at", []int64{3, 1, 2}},
+		{"category_title", []int64{2, 1, 3}},
+		{"category_id", []int64{1, 3, 2}},
+		{"title", []int64{2, 3, 1}},
+		{"author", []int64{3, 1, 2}},
+	} {
+		for _, direction := range []string{"asc", "desc"} {
+			t.Run(test.order+"/"+direction, func(t *testing.T) {
+				want := slices.Clone(test.ids)
+				if direction == "desc" {
+					slices.Reverse(want)
+				}
+
+				builder := store.NewEntryQueryBuilder(1).
+					WithEntryIDs(1, 2, 3).
+					WithSorting(test.order, direction).
+					WithSorting("id", direction)
+				ids, err := builder.GetEntryIDs()
+				if err != nil {
+					t.Fatal(err)
+				}
+				if !slices.Equal(ids, want) {
+					t.Fatalf("Got IDs %v, want %v", ids, want)
+				}
+
+				entries, err := builder.GetEntries()
+				if err != nil {
+					t.Fatal(err)
+				}
+				if len(entries) != len(ids) {
+					t.Fatalf("Got %d entries, want %d", len(entries), len(ids))
+				}
+				for i, entry := range entries {
+					if entry.ID != ids[i] {
+						t.Fatalf("Entry %d has ID %d, want %d", i, entry.ID, ids[i])
+					}
+				}
+			})
+		}
+	}
+}
+
+func TestGetEntryIDsFiltersAndCount(t *testing.T) {
+	store := newEntryQueryTestStorage(t)
+
+	for _, test := range []struct {
+		name      string
+		configure func(*EntryQueryBuilder) *EntryQueryBuilder
+		ids       []int64
+	}{
+		{"all including hidden", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b }, []int64{1, 2, 3, 4, 5, 6}},
+		{"globally visible", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithGloballyVisible() }, []int64{1, 2, 3}},
+		{"hidden feed", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithFeedID(13).WithGloballyVisible() }, nil},
+		{"hidden category", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithCategoryID(30).WithGloballyVisible() }, nil},
+		{"matching scope", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithFeedID(11).WithCategoryID(10) }, []int64{1, 3}},
+		{"mismatched scope", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithFeedID(11).WithCategoryID(20) }, nil},
+		{"unread", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithStatuses(model.EntryStatusUnread) }, []int64{1, 3, 4, 6}},
+		{"read", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithStatuses(model.EntryStatusRead) }, []int64{2, 5}},
+		{"both statuses", func(b *EntryQueryBuilder) *EntryQueryBuilder {
+			return b.WithStatuses(model.EntryStatusRead, model.EntryStatusUnread)
+		}, []int64{1, 2, 3, 4, 5, 6}},
+		{"starred", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithStarred(true) }, []int64{2, 4}},
+		{"not starred", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithStarred(false) }, []int64{1, 3, 5, 6}},
+		{"combined", func(b *EntryQueryBuilder) *EntryQueryBuilder {
+			return b.WithGloballyVisible().WithStatuses(model.EntryStatusUnread).WithTags("ONE", "two").WithSearchQuery("shared")
+		}, []int64{1, 3}},
+		{"strict ID boundaries", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.AfterEntryID(1).BeforeEntryID(3) }, []int64{2}},
+		{"strict time boundaries", func(b *EntryQueryBuilder) *EntryQueryBuilder {
+			return b.AfterPublishedDate(time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)).
+				BeforePublishedDate(time.Date(2025, 1, 3, 0, 0, 0, 0, time.UTC))
+		}, []int64{3}},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			builder := test.configure(store.NewEntryQueryBuilder(1).WithSorting("id", "asc"))
+			ids, total, err := builder.GetEntryIDsWithCount()
+			if err != nil {
+				t.Fatal(err)
+			}
+			if !slices.Equal(ids, test.ids) || total != len(test.ids) {
+				t.Fatalf("Got IDs %v and total %d, want %v and %d", ids, total, test.ids, len(test.ids))
+			}
+
+			for offset := 0; offset <= len(test.ids); offset++ {
+				builder.WithLimitAndMaximum(1, model.MaxEntryIDsLimit).WithOffset(offset)
+				ids, total, err := builder.GetEntryIDsWithCount()
+				if err != nil {
+					t.Fatal(err)
+				}
+				want := test.ids[offset:min(offset+1, len(test.ids))]
+				if !slices.Equal(ids, want) || total != len(test.ids) {
+					t.Fatalf("Offset %d: got IDs %v and total %d, want %v and %d", offset, ids, total, want, len(test.ids))
+				}
+			}
+		})
+	}
+}
+
+func TestGetEntryIDsStablePagination(t *testing.T) {
+	const pageSize = 25
+
+	store := newEntryQueryTestStorage(t)
+	_, err := store.db.Exec(`
+		DELETE FROM entries;
+		INSERT INTO entries (id, user_id, feed_id, hash, title, url, author, content,
+			published_at, created_at, changed_at, document_vectors)
+		SELECT n, 1, 11, n::text, 'Shared title', 'https://example.org/' || n, 'Shared author', '',
+			'2025-01-01', '2025-01-01', '2025-01-01', to_tsvector('shared')
+		FROM generate_series(1, 120) AS n;
+	`)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	for _, order := range []string{"id", "status", "changed_at", "published_at", "created_at", "category_title", "category_id", "title", "author"} {
+		for _, direction := range []string{"asc", "desc"} {
+			want := make([]int64, 120)
+			for i := range want {
+				want[i] = int64(i + 1)
+			}
+			if direction == "desc" {
+				slices.Reverse(want)
+			}
+
+			for _, search := range []string{"", "shared"} {
+				t.Run(order+"/"+direction+"/search="+search, func(t *testing.T) {
+					var got []int64
+					for offset := 0; offset < len(want); offset += pageSize {
+						ids, total, err := store.NewEntryQueryBuilder(1).
+							WithSorting(order, direction).
+							WithSearchQuery(search).
+							WithSorting("id", direction).
+							WithLimit(pageSize).
+							WithOffset(offset).
+							GetEntryIDsWithCount()
+						if err != nil {
+							t.Fatal(err)
+						}
+						if total != len(want) {
+							t.Fatalf("Got total %d, want %d", total, len(want))
+						}
+						got = append(got, ids...)
+					}
+					if !slices.Equal(got, want) {
+						t.Fatalf("Got IDs %v, want %v", got, want)
+					}
+				})
+			}
+		}
+	}
+}
+
+func TestGetEntryIDsSearchSorting(t *testing.T) {
+	store := newEntryQueryTestStorage(t)
+
+	for _, test := range []struct {
+		direction string
+		ids       []int64
+	}{
+		{"asc", []int64{3, 2, 1}},
+		{"desc", []int64{1, 3, 2}},
+	} {
+		t.Run(test.direction, func(t *testing.T) {
+			ids, err := store.NewEntryQueryBuilder(1).
+				WithSorting("title", test.direction).
+				WithSearchQuery("shared").
+				WithSorting("id", test.direction).
+				GetEntryIDs()
+			if err != nil {
+				t.Fatal(err)
+			}
+			if !slices.Equal(ids, test.ids) {
+				t.Fatalf("Got IDs %v, want %v", ids, test.ids)
+			}
+		})
+	}
+}
+
+func TestGetEntryIDsWithoutEntryData(t *testing.T) {
+	store := newEntryQueryTestStorage(t)
+	if _, err := store.db.Exec(`ALTER TABLE entries DROP COLUMN content`); err != nil {
+		t.Fatal(err)
+	}
+
+	ids, err := store.NewEntryQueryBuilder(1).
+		WithEntryIDs(1, 2, 3).
+		WithSorting("category_title", "asc").
+		WithSorting("id", "asc").
+		WithEnclosures().
+		GetEntryIDs()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !slices.Equal(ids, []int64{2, 1, 3}) {
+		t.Fatalf("Got IDs %v, want [2 1 3]", ids)
+	}
+}
+
+func TestGetEntryIDsCompatibilityQueries(t *testing.T) {
+	store := newEntryQueryTestStorage(t)
+
+	// Fever fetches unread and starred IDs without sorting or pagination.
+	for _, test := range []struct {
+		builder *EntryQueryBuilder
+		ids     []int64
+	}{
+		{store.NewEntryQueryBuilder(1).WithStatuses(model.EntryStatusUnread), []int64{1, 3, 4, 6}},
+		{store.NewEntryQueryBuilder(1).WithStarred(true), []int64{2, 4}},
+	} {
+		ids, err := test.builder.GetEntryIDs()
+		if err != nil {
+			t.Fatal(err)
+		}
+		slices.Sort(ids)
+		if !slices.Equal(ids, test.ids) {
+			t.Fatalf("Got IDs %v, want %v", ids, test.ids)
+		}
+	}
+
+	// Google Reader sorts IDs by publication date and uses limit/offset.
+	ids, err := store.NewEntryQueryBuilder(1).
+		WithFeedID(11).
+		WithSorting(model.DefaultSortingOrder, "desc").
+		WithLimitAndMaximum(1, model.MaxEntryIDsLimit).
+		WithOffset(1).
+		GetEntryIDs()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !slices.Equal(ids, []int64{3}) {
+		t.Fatalf("Got IDs %v, want [3]", ids)
+	}
+}

+ 168 - 0
internal/storage/entry_query_builder_test.go

@@ -0,0 +1,168 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package storage
+
+import (
+	"strings"
+	"testing"
+
+	"miniflux.app/v2/internal/model"
+)
+
+func TestEntryQuerySortingColumns(t *testing.T) {
+	for _, test := range []struct {
+		column          string
+		qualifiedColumn string
+	}{
+		{"id", `"e"."id"`},
+		{"status", `"e"."status"`},
+		{"changed_at", `"e"."changed_at"`},
+		{"published_at", `"e"."published_at"`},
+		{"created_at", `"e"."created_at"`},
+		{"category_title", `"c"."title"`},
+		{"category_id", `"f"."category_id"`},
+		{"title", `"e"."title"`},
+		{"author", `"e"."author"`},
+	} {
+		for _, direction := range []string{"asc", "DESC"} {
+			t.Run(test.column+"/"+direction, func(t *testing.T) {
+				builder := new(Storage).NewEntryQueryBuilder(1).WithSorting(test.column, direction)
+				for _, idsOnly := range []bool{true, false} {
+					got, err := builder.buildSorting(idsOnly)
+					if err != nil {
+						t.Fatal(err)
+					}
+					column := test.qualifiedColumn
+					if !idsOnly {
+						column = `"` + test.column + `"`
+					}
+					want := " ORDER BY " + column + " " + strings.ToUpper(direction)
+					if got != want {
+						t.Fatalf("IDs only=%t: got %q, want %q", idsOnly, got, want)
+					}
+				}
+			})
+		}
+	}
+}
+
+func TestEntryQuerySortingDirections(t *testing.T) {
+	for _, test := range []struct {
+		name          string
+		direction     string
+		wantDirection string
+	}{
+		{"ascending", "ASC", "ASC"},
+		{"lowercase ascending", "asc", "ASC"},
+		{"mixed-case ascending", "aSc", "ASC"},
+		{"descending", "DESC", "DESC"},
+		{"lowercase descending", "desc", "DESC"},
+		{"mixed-case descending", "dEsC", "DESC"},
+		{"Unicode ascending", "aſc", "ASC"},
+		{"Unicode descending", "deſc", "DESC"},
+		{"empty", "", ""},
+		{"unsupported", "invalid", ""},
+		{"leading whitespace", " asc", ""},
+		{"trailing whitespace", "desc ", ""},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			builder := new(Storage).NewEntryQueryBuilder(1).WithSorting("id", "asc")
+			if builder.WithSorting("title", test.direction) != builder {
+				t.Fatal("Expected WithSorting to return the same builder")
+			}
+
+			got, err := builder.buildSorting(false)
+			if err != nil {
+				t.Fatal(err)
+			}
+			want := ` ORDER BY "id" ASC`
+			if test.wantDirection != "" {
+				want += `, "title" ` + test.wantDirection
+			}
+			if got != want {
+				t.Fatalf("Got %q, want %q", got, want)
+			}
+		})
+	}
+}
+
+func TestEntryQueryIDSortingRejectsUnknownColumns(t *testing.T) {
+	for _, column := range []string{"", "unknown", "feed_title", "e.title", `title" DESC; DROP TABLE entries; --`, "title\x00"} {
+		t.Run(column, func(t *testing.T) {
+			builder := new(Storage).NewEntryQueryBuilder(1).WithSorting(column, "asc")
+			if _, err := builder.buildSorting(true); err == nil {
+				t.Fatal("Expected an error for an unsupported ID sorting column")
+			}
+		})
+	}
+}
+
+func TestEntryQuerySortingPreservesSearchPriority(t *testing.T) {
+	for _, direction := range []string{"asc", "desc"} {
+		t.Run(direction, func(t *testing.T) {
+			builder := new(Storage).NewEntryQueryBuilder(1).
+				WithSorting("title", direction).
+				WithSearchQuery("shared").
+				WithSorting("id", direction).
+				WithLimit(25).
+				WithOffset(50)
+			rank := "ts_rank(document_vectors, websearch_to_tsquery($2)) - extract (epoch from now() - published_at)::float * 0.0000001 DESC"
+			sqlDirection := strings.ToUpper(direction)
+			for _, idsOnly := range []bool{false, true, false} {
+				got, err := builder.buildSorting(idsOnly)
+				if err != nil {
+					t.Fatal(err)
+				}
+				prefix := ""
+				if idsOnly {
+					prefix = `"e".`
+				}
+				want := " ORDER BY " + strings.Join([]string{
+					prefix + `"title" ` + sqlDirection,
+					rank,
+					prefix + `"id" ` + sqlDirection,
+				}, ", ") + " LIMIT 25 OFFSET 50"
+				if got != want {
+					t.Fatalf("IDs only=%t: got %q, want %q", idsOnly, got, want)
+				}
+			}
+			if len(builder.args) != 2 || builder.args[1] != "shared" {
+				t.Fatalf("Unexpected search arguments: %v", builder.args)
+			}
+		})
+	}
+}
+
+func TestEntryQuerySortingCompatibility(t *testing.T) {
+	for _, test := range []struct {
+		name      string
+		configure func(*EntryQueryBuilder) *EntryQueryBuilder
+		want      string
+	}{
+		{"no implicit sorting", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b }, ""},
+		{"empty search", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithSearchQuery("") }, ""},
+		{"invalid direction", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithSorting("id", "invalid") }, ""},
+		{"negative offset", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithOffset(-1) }, ""},
+		{"IDs pagination", func(b *EntryQueryBuilder) *EntryQueryBuilder {
+			return b.WithLimitAndMaximum(0, model.MaxEntryIDsLimit).WithOffset(1)
+		}, " LIMIT 10000 OFFSET 1"},
+		{"IDs maximum", func(b *EntryQueryBuilder) *EntryQueryBuilder {
+			return b.WithLimitAndMaximum(10001, model.MaxEntryIDsLimit)
+		}, " LIMIT 10000"},
+		{"entries maximum", func(b *EntryQueryBuilder) *EntryQueryBuilder { return b.WithLimit(10001) }, " LIMIT 1000"},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			builder := test.configure(new(Storage).NewEntryQueryBuilder(1))
+			for _, idsOnly := range []bool{false, true} {
+				got, err := builder.buildSorting(idsOnly)
+				if err != nil {
+					t.Fatal(err)
+				}
+				if got != test.want {
+					t.Fatalf("IDs only=%t: got %q, want %q", idsOnly, got, test.want)
+				}
+			}
+		})
+	}
+}