fix(postgres): create the stats upsert indexes and partition audit_log

The hourly and daily aggregation upserts name a unique expression index that AutoMigrate does not create, so every aggregation failed on PostgreSQL. AutoMigrate also created audit_log as a plain table, so the partition step failed on every start. The partition manager now creates the two indexes and replaces an empty plain audit_log with a partitioned one.
This commit is contained in:
2026-11-23 02:23:35 +00:00
parent ea00fac0fe
commit d38eb34e06
2 changed files with 142 additions and 4 deletions
+43 -4
View File
@@ -36,6 +36,10 @@ func (pm *PartitionManager) EnsurePartitions() error {
log.Info().Msg("Ensuring partitions exist")
if err := pm.ensureStatsUpsertIndexes(); err != nil {
return err
}
// Create partitions for download_events
if err := pm.ensureDownloadEventPartitions(); err != nil {
return err
@@ -157,16 +161,51 @@ func (pm *PartitionManager) createDownloadEventPartition(month time.Time) error
return nil
}
// statsUpsertIndexes are the unique indexes that the ON CONFLICT clauses in
// aggregation_worker.go name; AutoMigrate cannot express the COALESCE.
var statsUpsertIndexes = []string{
"CREATE UNIQUE INDEX IF NOT EXISTS idx_stats_hourly_upsert ON download_stats_hourly (registry_id, COALESCE(package_id, 0), time_bucket)",
"CREATE UNIQUE INDEX IF NOT EXISTS idx_stats_daily_upsert ON download_stats_daily (registry_id, COALESCE(package_id, 0), time_bucket)",
}
func (pm *PartitionManager) ensureStatsUpsertIndexes() error {
for _, stmt := range statsUpsertIndexes {
if err := pm.db.Exec(stmt).Error; err != nil {
return fmt.Errorf("failed to create stats upsert index: %w", err)
}
}
return nil
}
// ensureAuditLogPartitions creates audit_log partitions
func (pm *PartitionManager) ensureAuditLogPartitions() error {
// Check if table exists
var exists bool
err := pm.db.Raw("SELECT EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'audit_log')").Scan(&exists).Error
var partitioned bool
err := pm.db.Raw("SELECT EXISTS (SELECT 1 FROM pg_partitioned_table WHERE partrelid = to_regclass('audit_log'))").Scan(&partitioned).Error
if err != nil {
return err
}
if !exists {
if !partitioned {
// AutoMigrate creates audit_log as a plain table. An empty one can be
// replaced; one that holds rows stays as it is.
var exists bool
if err := pm.db.Raw("SELECT to_regclass('audit_log') IS NOT NULL").Scan(&exists).Error; err != nil {
return err
}
if exists {
var rows int64
if err := pm.db.Raw("SELECT COUNT(*) FROM audit_log").Scan(&rows).Error; err != nil {
return err
}
if rows > 0 {
log.Warn().Int64("rows", rows).Msg("audit_log holds rows and is not partitioned, leaving it as is")
return nil
}
if err := pm.db.Exec("DROP TABLE audit_log").Error; err != nil {
return fmt.Errorf("failed to replace empty audit_log: %w", err)
}
}
// Create partitioned table
createTableSQL := `
CREATE TABLE IF NOT EXISTS audit_log (
@@ -0,0 +1,99 @@
//go:build pgintegration
package gormstore
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
)
func newPostgresStore(t *testing.T) (*GORMStoreV2, string) {
t.Helper()
ctx := context.Background()
container, err := postgres.Run(ctx, "postgres:16-alpine",
postgres.WithDatabase("testdb"),
postgres.WithUsername("testuser"),
postgres.WithPassword("testpass"),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(90*time.Second),
),
)
require.NoError(t, err)
t.Cleanup(func() { _ = container.Terminate(ctx) })
connStr, err := container.ConnectionString(ctx, "sslmode=disable")
require.NoError(t, err)
store, err := NewV2(Config{Driver: "postgres", DSN: connStr, LogLevel: "silent"})
require.NoError(t, err)
t.Cleanup(func() { _ = store.Close() })
return store, connStr
}
func TestPostgresPartitionsBothTables(t *testing.T) {
store, connStr := newPostgresStore(t)
second, err := NewV2(Config{Driver: "postgres", DSN: connStr, LogLevel: "silent"})
require.NoError(t, err, "a second start must accept the converted tables")
defer func() { _ = second.Close() }()
for _, table := range []string{"download_events", "audit_log"} {
var partitioned bool
require.NoError(t, store.db.Raw(
"SELECT EXISTS (SELECT 1 FROM pg_partitioned_table WHERE partrelid = ?::regclass)", table,
).Scan(&partitioned).Error)
require.True(t, partitioned, table)
var parts int64
require.NoError(t, store.db.Raw(
"SELECT COUNT(*) FROM pg_inherits WHERE inhparent = ?::regclass", table,
).Scan(&parts).Error)
require.Positive(t, parts, table)
}
}
func TestPostgresHourlyAggregationUpserts(t *testing.T) {
store, _ := newPostgresStore(t)
old := time.Now().UTC().Add(-3 * time.Hour)
for i := 0; i < 2; i++ {
require.NoError(t, store.db.Exec(
"INSERT INTO download_events (package_id, registry_id, downloaded_at, ip_address, authenticated) VALUES (1, 1, ?, '10.0.0.1', false)",
old,
).Error)
}
require.NoError(t, store.aggregationWorker.AggregateHourly())
var count int64
require.NoError(t, store.db.Raw("SELECT COALESCE(SUM(download_count), 0) FROM download_stats_hourly WHERE package_id = 1").Scan(&count).Error)
require.Equal(t, int64(2), count)
var registryTotal int64
require.NoError(t, store.db.Raw("SELECT COALESCE(SUM(download_count), 0) FROM download_stats_hourly WHERE package_id IS NULL").Scan(&registryTotal).Error)
require.Equal(t, int64(2), registryTotal)
}
func TestPostgresDailyAggregationUpserts(t *testing.T) {
store, _ := newPostgresStore(t)
bucket := time.Now().UTC().Truncate(24 * time.Hour).Add(-24 * time.Hour)
require.NoError(t, store.db.Exec(
"INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at) VALUES (1, NULL, ?, 5, 2, 0, NOW(), NOW())",
bucket,
).Error)
require.NoError(t, store.aggregationWorker.AggregateDaily())
var count int64
require.NoError(t, store.db.Raw("SELECT COALESCE(SUM(download_count), 0) FROM download_stats_daily").Scan(&count).Error)
require.Equal(t, int64(5), count)
}