fix: Fix the issue of postgres database not being synchronized

This commit is contained in:
ssongliu 2025-11-17 15:23:31 +08:00
parent 4209ee4486
commit 3e0381b7f8
21 changed files with 55 additions and 24 deletions

View file

@ -281,14 +281,15 @@ type DatabaseItem struct {
}
type DatabaseCreate struct {
Name string `json:"name" validate:"required,max=256"`
Type string `json:"type" validate:"required"`
From string `json:"from" validate:"required,oneof=local remote"`
Version string `json:"version" validate:"required"`
Address string `json:"address"`
Port uint `json:"port"`
Username string `json:"username" validate:"required"`
Password string `json:"password"`
Name string `json:"name" validate:"required,max=256"`
Type string `json:"type" validate:"required"`
From string `json:"from" validate:"required,oneof=local remote"`
Version string `json:"version" validate:"required"`
Address string `json:"address"`
Port uint `json:"port"`
InitialDB string `json:"initialDB"`
Username string `json:"username" validate:"required"`
Password string `json:"password"`
SSL bool `json:"ssl"`
RootCert string `json:"rootCert"`

View file

@ -9,6 +9,7 @@ type Database struct {
From string `json:"from" gorm:"not null"`
Address string `json:"address" gorm:"not null"`
Port uint `json:"port" gorm:"not null"`
InitialDB string `json:"initialDB"`
Username string `json:"username"`
Password string `json:"password"`

View file

@ -122,12 +122,13 @@ func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool {
switch req.Type {
case constant.AppPostgresql:
_, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote",
Address: req.Address,
Port: req.Port,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
From: "remote",
Address: req.Address,
Port: req.Port,
InitialDB: req.InitialDB,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
})
return err == nil
case constant.AppRedis:

View file

@ -52,6 +52,7 @@ func InitAgentDB() {
migrations.UpdateCronJob,
migrations.UpdateTensorrtLLM,
migrations.AddIptablesFilterRuleTable,
migrations.UpdateDatabase,
})
if err := m.Migrate(); err != nil {
global.LOG.Error(err)

View file

@ -705,3 +705,10 @@ var UpdateTensorrtLLM = &gormigrate.Migration{
return tx.AutoMigrate(&model.TensorRTLLM{})
},
}
var UpdateDatabase = &gormigrate.Migration{
ID: "20251117-update-database",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&model.Database{})
},
}

View file

@ -33,7 +33,10 @@ func NewPostgresqlClient(conn client.DBInfo) (PostgresqlClient, error) {
}
escapedUsername := url.QueryEscape(conn.Username)
escapedPassword := url.QueryEscape(conn.Password)
connArgs := fmt.Sprintf("postgres://%s:%s@%s:%d/postgres?sslmode=disable", escapedUsername, escapedPassword, conn.Address, conn.Port)
if len(conn.InitialDB) == 0 {
conn.InitialDB = escapedUsername
}
connArgs := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", escapedUsername, escapedPassword, conn.Address, conn.Port, conn.InitialDB)
db, err := sql.Open("pgx", connArgs)
if err != nil {
return nil, err

View file

@ -5,13 +5,14 @@ import (
)
type DBInfo struct {
From string `json:"from"`
Database string `json:"database"`
Address string `json:"address"`
Port uint `json:"port"`
Username string `json:"userName"`
Password string `json:"password"`
AppKey string `json:"appKey"`
From string `json:"from"`
Database string `json:"database"`
Address string `json:"address"`
Port uint `json:"port"`
InitialDB string `json:"initialDB"`
Username string `json:"userName"`
Password string `json:"password"`
AppKey string `json:"appKey"`
Timeout uint `json:"timeout"` // second
}

View file

@ -199,7 +199,7 @@ func (r *Local) SyncDB() ([]SyncDBInfo, error) {
}
for _, line := range lines {
itemLine := strings.TrimLeft(line, " ")
if len(itemLine) == 0 || itemLine == "postgres" || itemLine == "template1" || itemLine == "template0" || itemLine == r.Username {
if len(itemLine) == 0 || itemLine == "template1" || itemLine == "template0" || itemLine == r.Username {
continue
}
datas = append(datas, SyncDBInfo{Name: itemLine, From: "local", PostgresqlName: r.Database})

View file

@ -215,7 +215,7 @@ func (r *Remote) SyncDB() ([]SyncDBInfo, error) {
if err := rows.Scan(&dbName); err != nil {
continue
}
if len(dbName) == 0 || dbName == "postgres" || dbName == "template1" || dbName == "template0" || dbName == r.User {
if len(dbName) == 0 || dbName == "template1" || dbName == "template0" || dbName == r.User {
continue
}
datas = append(datas, SyncDBInfo{Name: dbName, From: r.From, PostgresqlName: r.Database})

View file

@ -274,6 +274,7 @@ export namespace Database {
from: string;
address: string;
port: number;
initialDB: string;
username: string;
password: string;

View file

@ -537,6 +537,7 @@ const message = {
caCert: 'CA certificate',
hasCA: 'Has CA certificate',
skipVerify: 'Ignore certificate validity check',
initialDB: 'Initial Database',
formatHelper:
'The current database character set is {0}, the character set inconsistency may cause recovery failure',

View file

@ -541,6 +541,8 @@ const message = {
caCert: 'Certificado CA',
hasCA: 'Posee certificado CA',
skipVerify: 'Omitir la verificación de validez del certificado',
initialDB: 'Base de Datos Inicial',
formatHelper:
'El conjunto de caracteres actual de la base de datos es {0}, la inconsistencia de conjuntos puede causar errores al recuperar',
dropHelper: 'Puede arrastrar y soltar el archivo aquí o',

View file

@ -525,6 +525,7 @@ const message = {
caCert: '証明書として',
hasCA: 'CA証明書があります',
skipVerify: '証明書の有効性チェックを無視します',
initialDB: '初期データベース',
formatHelper: '現在のデータベース文字セットは{0}です文字セットの矛盾は回復の故障を引き起こす可能性があります',
dropHelper: 'ここでアップロードされたファイルをドラッグアンドドロップするか',

View file

@ -523,6 +523,7 @@ const message = {
caCert: 'CA 인증서',
hasCA: 'CA 인증서 있음',
skipVerify: '인증서 유효성 검사 무시',
initialDB: '초기 데이터베이스',
formatHelper: '현재 데이터베이스 문자셋은 {0} 입니다. 문자셋 불일치로 인해 복구에 실패할 있습니다.',
dropHelper: '여기에 업로드한 파일을 드래그 드롭하거나',

View file

@ -536,6 +536,7 @@ const message = {
caCert: 'Sijil CA',
hasCA: 'Mempunyai sijil CA',
skipVerify: 'Abaikan pemeriksaan kesahihan sijil',
initialDB: 'Pangkalan Data Awal',
formatHelper:
'Set aksara pangkalan data semasa adalah {0}, ketidakkonsistenan set aksara mungkin menyebabkan kegagalan pemulihan.',

View file

@ -534,6 +534,7 @@ const message = {
caCert: 'Certificado CA',
hasCA: 'Possui certificado CA',
skipVerify: 'Ignorar verificação de validade do certificado',
initialDB: 'Banco de Dados Inicial',
formatHelper:
'O conjunto de caracteres atual do banco de dados é {0}, a inconsistência no conjunto de caracteres pode causar falha na recuperação',

View file

@ -528,6 +528,7 @@ const message = {
caCert: 'Сертификат CA',
hasCA: 'Есть сертификат CA',
skipVerify: 'Игнорировать проверку действительности сертификата',
initialDB: 'Исходная База Данных',
formatHelper:
'Текущая кодировка базы данных - {0}, несоответствие кодировок может привести к ошибке восстановления',

View file

@ -543,6 +543,8 @@ const message = {
caCert: 'CA sertifikası',
hasCA: 'CA sertifikası var',
skipVerify: 'Sertifika geçerlilik kontrolünü yoksay',
initialDB: 'Başlangıç Veritabanı',
formatHelper:
'Mevcut veritabanı karakter seti {0}, karakter seti tutarsızlığı kurtarma işleminin başarısız olmasına neden olabilir',
dropHelper: 'Yüklenen dosyayı buraya sürükleyip bırakabilir veya',

View file

@ -516,6 +516,7 @@ const message = {
hasCA: '擁有 CA 證書',
caCert: 'CA 證書',
skipVerify: '忽略校驗證書可用性檢測',
initialDB: '初始資料庫',
formatHelper: '目前資料庫字元集為 {0}字元集不一致可能導致復原失敗',
dropHelper: '將上傳文件拖曳到此處或者',

View file

@ -517,6 +517,7 @@ const message = {
hasCA: '拥有 CA 证书',
caCert: 'CA 证书',
skipVerify: '忽略校验证书可用性检测',
initialDB: '初始数据库',
formatHelper: '当前数据库字符集为 {0}字符集不一致可能导致恢复失败',
dropHelper: '将上传文件拖拽到此处或者',

View file

@ -25,6 +25,9 @@
<el-form-item :label="$t('commons.table.port')" prop="port">
<el-input @change="isOK = false" clearable v-model.number="dialogData.rowData!.port" />
</el-form-item>
<el-form-item :label="$t('database.initialDB')" prop="initialDB">
<el-input @change="isOK = false" clearable v-model.trim="dialogData.rowData!.initialDB" />
</el-form-item>
<el-form-item :label="$t('commons.login.username')" prop="username">
<el-input @change="isOK = false" clearable v-model.trim="dialogData.rowData!.username" />
<span class="input-help">{{ $t('database.pgUserHelper') }}</span>