fix: 修改apikey长度为1024

This commit is contained in:
tbphp
2025-07-25 13:02:06 +08:00
parent dd43bb8a9e
commit adb5397473
3 changed files with 57 additions and 3 deletions

View File

@@ -6,5 +6,12 @@ import (
func MigrateDatabase(db *gorm.DB) error {
// v1.0.13 修复请求日志数据
return V1_0_13_FixRequestLogs(db)
if err := V1_0_13_FixRequestLogs(db); err != nil {
return err
}
// v1.0.16 增加 key_value 字段长度
if err := V1_0_16_IncreaseKeyValueLength(db); err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,47 @@
package db
import (
"fmt"
"gorm.io/gorm"
)
// V1_0_16_IncreaseKeyValueLength migrates the key_value column length.
func V1_0_16_IncreaseKeyValueLength(db *gorm.DB) error {
if err := alterColumnType(db, "api_keys", "key_value", "varchar(1024)"); err != nil {
return fmt.Errorf("failed to migrate api_keys table: %w", err)
}
if err := alterColumnType(db, "request_logs", "key_value", "varchar(1024)"); err != nil {
return fmt.Errorf("failed to migrate request_logs table: %w", err)
}
return nil
}
func alterColumnType(db *gorm.DB, tableName, columnName, newType string) error {
var currentType string
switch db.Dialector.Name() {
case "sqlite":
return nil
case "mysql":
err := db.Raw("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?",
db.Migrator().CurrentDatabase(), tableName, columnName).Scan(&currentType).Error
if err != nil {
return err
}
if currentType == newType {
return nil
}
return db.Exec(fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s %s", tableName, columnName, newType)).Error
case "postgres":
err := db.Raw("SELECT data_type FROM information_schema.columns WHERE table_name = ? AND column_name = ?",
tableName, columnName).Scan(&currentType).Error
if err != nil {
return err
}
return db.Exec(fmt.Sprintf("ALTER TABLE %s ALTER COLUMN %s TYPE %s", tableName, columnName, newType)).Error
default:
return nil
}
}

View File

@@ -62,7 +62,7 @@ type Group struct {
// APIKey 对应 api_keys 表
type APIKey struct {
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
KeyValue string `gorm:"type:varchar(512);not null;uniqueIndex:idx_group_key" json:"key_value"`
KeyValue string `gorm:"type:varchar(1024);not null;uniqueIndex:idx_group_key" json:"key_value"`
GroupID uint `gorm:"not null;uniqueIndex:idx_group_key" json:"group_id"`
Status string `gorm:"type:varchar(50);not null;default:'active'" json:"status"`
RequestCount int64 `gorm:"not null;default:0" json:"request_count"`
@@ -78,7 +78,7 @@ type RequestLog struct {
Timestamp time.Time `gorm:"not null;index" json:"timestamp"`
GroupID uint `gorm:"not null;index" json:"group_id"`
GroupName string `gorm:"type:varchar(255);index" json:"group_name"`
KeyValue string `gorm:"type:varchar(512)" json:"key_value"`
KeyValue string `gorm:"type:varchar(1024)" json:"key_value"`
IsSuccess bool `gorm:"not null" json:"is_success"`
SourceIP string `gorm:"type:varchar(45)" json:"source_ip"`
StatusCode int `gorm:"not null" json:"status_code"`