From afb470e405cd5fba4c1b70467ef5f505f32a3878 Mon Sep 17 00:00:00 2001 From: YuPeng Wu <44936809+realRoc@users.noreply.github.com> Date: Sat, 30 May 2026 19:54:02 +0800 Subject: [PATCH] fix(model): correct idx_created_at_id index column order to (created_at, id) (#5191) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The idx_created_at_id composite index on the logs table was defined as (id, created_at) because the GORM `priority` values on Id and CreatedAt were swapped. Since `id` is the auto-increment primary key, a secondary composite index leading with `id` is redundant with the PK and cannot accelerate `created_at` range scans (a range column must sit at the index prefix). This defeats the common log-listing queries (`WHERE created_at BETWEEN ? AND ? ORDER BY id DESC LIMIT n` in GetAllLogs/GetUserLogs) that the index name implies it should serve — the optimizer falls back to scanning the primary key, degrading to near full-table scans on large logs tables. Swap the priorities so the column order becomes (created_at, id), matching the index name and its intended purpose. idx_user_id_id and idx_created_at_type are unaffected. Note: GORM AutoMigrate does not change the column order of an already-existing index with the same name, so existing deployments must rebuild the index manually (see PR description for per-database DDL). Co-authored-by: wuyupeng Co-authored-by: Claude Opus 4.8 (1M context) --- model/log.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/model/log.go b/model/log.go index 3db19f7e..0f6af51f 100644 --- a/model/log.go +++ b/model/log.go @@ -32,9 +32,9 @@ func applyExplicitLogTextFilter(tx *gorm.DB, column string, value string) (*gorm } type Log struct { - Id int `json:"id" gorm:"index:idx_created_at_id,priority:1;index:idx_user_id_id,priority:2"` + Id int `json:"id" gorm:"index:idx_created_at_id,priority:2;index:idx_user_id_id,priority:2"` UserId int `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"` - CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"` + CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:1;index:idx_created_at_type"` Type int `json:"type" gorm:"index:idx_created_at_type"` Content string `json:"content"` Username string `json:"username" gorm:"index;index:index_username_model_name,priority:2;default:''"`