Add primary key to the query log table #585 (#609)

This commit is contained in:
Dimitri Herzog 2022-07-28 23:08:37 +02:00 committed by GitHub
parent 88991379cf
commit e4445f05f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 31 additions and 1 deletions

View File

@ -2,6 +2,7 @@ package querylog
import (
"fmt"
"reflect"
"strings"
"sync"
"time"
@ -70,7 +71,7 @@ func newDatabaseWriter(target gorm.Dialector, logRetentionDays uint64,
}
// Migrate the schema
if err := db.AutoMigrate(&logEntry{}); err != nil {
if err := databaseMigration(db); err != nil {
return nil, fmt.Errorf("can't perform auto migration: %w", err)
}
@ -84,6 +85,35 @@ func newDatabaseWriter(target gorm.Dialector, logRetentionDays uint64,
return w, nil
}
func databaseMigration(db *gorm.DB) error {
if err := db.AutoMigrate(&logEntry{}); err != nil {
return err
}
tableName := db.NamingStrategy.TableName(reflect.TypeOf(logEntry{}).Name())
// create unmapped primary key
switch db.Config.Name() {
case "mysql":
tx := db.Exec("ALTER TABLE `" + tableName + "` ADD `id` INT PRIMARY KEY AUTO_INCREMENT")
if tx.Error != nil {
// mysql doesn't support "add column if not exist"
if strings.Contains(tx.Error.Error(), "1060") {
// error 1060: duplicate column name
// ignore it
return nil
}
return tx.Error
}
case "postgres":
return db.Exec("ALTER TABLE " + tableName + " ADD column if not exists id serial primary key").Error
}
return nil
}
func (d *DatabaseWriter) periodicFlush() {
ticker := time.NewTicker(d.dbFlushPeriod)
defer ticker.Stop()