fix: 调整admin数据库初始化,只用一个初始化创建

This commit is contained in:
npc0-hue
2026-02-27 09:56:46 +08:00
parent bd856e988f
commit 2193013e0f
5 changed files with 107 additions and 207 deletions
+1 -82
View File
@@ -2,10 +2,6 @@ package initialize
import (
"context"
adapter "github.com/casbin/gorm-adapter/v3"
"github.com/flipped-aurora/gin-vue-admin/server/model/example"
"github.com/flipped-aurora/gin-vue-admin/server/model/gaia"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"gorm.io/gorm"
)
@@ -36,48 +32,7 @@ func (e *ensureTables) MigrateTable(ctx context.Context) (context.Context, error
return ctx, system.ErrMissingDBContext
}
tables := []interface{}{
sysModel.SysApi{},
sysModel.SysUser{},
sysModel.SysBaseMenu{},
sysModel.SysAuthority{},
sysModel.JwtBlacklist{},
sysModel.SysDictionary{},
sysModel.SysAutoCodeHistory{},
sysModel.SysOperationRecord{},
sysModel.SysDictionaryDetail{},
sysModel.SysBaseMenuParameter{},
sysModel.SysBaseMenuBtn{},
sysModel.SysAuthorityBtn{},
sysModel.SysAutoCodePackage{},
sysModel.SysExportTemplate{},
sysModel.Condition{},
sysModel.JoinTemplate{},
sysModel.SysParams{},
adapter.CasbinRule{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
// Extend gaia model
gaia.AccountDingTalkExtend{},
gaia.AppRequestTestBatch{},
gaia.AppRequestTest{},
gaia.SystemIntegration{}, // Extend System Integration
gaia.ForwardingExtend{}, // Extend Forwarding Extend
gaia.BatchWorkflow{}, // Extend Batch Workflow
gaia.BatchWorkflowTask{}, // Extend Batch Workflow Task
sysModel.SysUserGlobalCode{}, // Extend Global Code
// Extend gaia model
}
for _, t := range tables {
_ = db.AutoMigrate(&t)
// 视图 authority_menu 会被当成表来创建,引发冲突错误(更新版本的gorm似乎不会)
// 由于 AutoMigrate() 基本无需考虑错误,因此显式忽略
}
RegisterTables(db)
return ctx, nil
}
@@ -86,42 +41,6 @@ func (e *ensureTables) TableCreated(ctx context.Context) bool {
if !ok {
return false
}
tables := []interface{}{
sysModel.SysApi{},
sysModel.SysUser{},
sysModel.SysBaseMenu{},
sysModel.SysAuthority{},
sysModel.JwtBlacklist{},
sysModel.SysDictionary{},
sysModel.SysAutoCodeHistory{},
sysModel.SysOperationRecord{},
sysModel.SysDictionaryDetail{},
sysModel.SysBaseMenuParameter{},
sysModel.SysBaseMenuBtn{},
sysModel.SysAuthorityBtn{},
sysModel.SysAutoCodePackage{},
sysModel.SysExportTemplate{},
sysModel.Condition{},
sysModel.JoinTemplate{},
adapter.CasbinRule{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
// Extend gaia model
gaia.AccountDingTalkExtend{},
gaia.AppRequestTestBatch{},
gaia.AppRequestTest{},
gaia.SystemIntegration{}, // Extend System Integration
gaia.ForwardingExtend{}, // Extend Forwarding Extend
gaia.BatchWorkflow{}, // Extend Batch Workflow
gaia.BatchWorkflowTask{}, // Extend Batch Workflow Task
sysModel.SysUserGlobalCode{}, // Extend Global Code
// Extend gaia model
}
yes := true
for _, t := range tables {
yes = yes && db.Migrator().HasTable(t)
+47 -119
View File
@@ -1,8 +1,7 @@
package initialize
import (
"fmt"
"log"
adapter "github.com/casbin/gorm-adapter/v3"
"os"
"github.com/flipped-aurora/gin-vue-admin/server/global"
@@ -14,6 +13,50 @@ import (
"gorm.io/gorm"
)
var tables = []interface{}{
system.SysApi{},
system.SysIgnoreApi{},
system.SysUser{},
system.SysBaseMenu{},
system.JwtBlacklist{},
system.SysAuthority{},
system.SysDictionary{},
system.SysOperationRecord{},
system.SysAutoCodeHistory{},
system.SysDictionaryDetail{},
system.SysBaseMenuParameter{},
system.SysBaseMenuBtn{},
system.SysAuthorityBtn{},
system.SysAutoCodePackage{},
system.SysExportTemplate{},
system.Condition{},
system.JoinTemplate{},
system.SysParams{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
adapter.CasbinRule{},
// Extend gaia model
gaia.AccountDingTalkExtend{},
gaia.AppRequestTestBatch{},
gaia.AppRequestTest{},
gaia.SystemIntegration{}, // Extend System Integration
gaia.ForwardingExtend{}, // Extend Forwarding Extend
gaia.BatchWorkflow{}, // Extend Batch Workflow
gaia.BatchWorkflowTask{}, // Extend Batch Workflow Task
gaia.AppVersionConfig{}, // 应用版本全局配置(Token
gaia.AppVersionRelease{}, // 应用版本发布
gaia.AppVersionDownload{}, // 应用版本各平台安装包
gaia.ModelProviderConfig{}, // 模型提供商配置
gaia.ModelProxyLog{}, // 模型中转请求日志
system.SysUserGlobalCode{}, // Extend Global Code
// Extend gaia model
}
func Gorm() *gorm.DB {
switch global.GVA_CONFIG.System.DbType {
case "mysql":
@@ -37,50 +80,9 @@ func Gorm() *gorm.DB {
}
}
func RegisterTables() {
db := global.GVA_DB
func RegisterTables(db *gorm.DB) {
err := db.AutoMigrate(
system.SysApi{},
system.SysIgnoreApi{},
system.SysUser{},
system.SysBaseMenu{},
system.JwtBlacklist{},
system.SysAuthority{},
system.SysDictionary{},
system.SysOperationRecord{},
system.SysAutoCodeHistory{},
system.SysDictionaryDetail{},
system.SysBaseMenuParameter{},
system.SysBaseMenuBtn{},
system.SysAuthorityBtn{},
system.SysAutoCodePackage{},
system.SysExportTemplate{},
system.Condition{},
system.JoinTemplate{},
system.SysParams{},
example.ExaFile{},
example.ExaCustomer{},
example.ExaFileChunk{},
example.ExaFileUploadAndDownload{},
// Extend gaia model
gaia.AccountDingTalkExtend{},
gaia.AppRequestTestBatch{},
gaia.AppRequestTest{},
gaia.SystemIntegration{}, // Extend System Integration
gaia.ForwardingExtend{}, // Extend Forwarding Extend
gaia.BatchWorkflow{}, // Extend Batch Workflow
gaia.BatchWorkflowTask{}, // Extend Batch Workflow Task
gaia.AppVersionConfig{}, // 应用版本全局配置(Token
gaia.AppVersionRelease{}, // 应用版本发布
gaia.AppVersionDownload{}, // 应用版本各平台安装包
gaia.ModelProviderConfig{}, // 模型提供商配置
gaia.ModelProxyLog{}, // 模型中转请求日志
system.SysUserGlobalCode{}, // Extend Global Code
// Extend gaia model
)
err := db.AutoMigrate(tables)
if err != nil {
global.GVA_LOG.Error("register table failed", zap.Error(err))
@@ -100,77 +102,3 @@ func RegisterTables() {
}
global.GVA_LOG.Info("register table success")
}
// createPostgreSQLSequences 为PostgreSQL数据库创建必要的序列
func createPostgreSQLSequences(db *gorm.DB) {
// 需要创建序列的表列表
tables := []string{
"sys_users",
"sys_apis",
"sys_base_menus",
"sys_authorities",
"sys_dictionaries",
"sys_operation_records",
"sys_auto_code_histories",
"sys_dictionary_details",
"sys_base_menu_parameters",
"sys_base_menu_btns",
"sys_authority_btns",
"sys_auto_code_packages",
"sys_export_templates",
"conditions",
"join_templates",
"sys_params",
"exa_files",
"exa_customers",
"exa_file_chunks",
"exa_file_upload_and_downloads",
"account_ding_talk_extends",
"app_request_test_batches",
"app_request_tests",
"system_integrations",
"forwarding_extends",
"batch_workflows",
"batch_workflow_tasks",
"app_version_config",
"app_version_releases",
"app_version_downloads",
"sys_user_global_codes",
}
for _, table := range tables {
sequenceName := fmt.Sprintf("%s_id_seq", table)
// 检查序列是否已存在
var exists bool
checkSQL := "SELECT EXISTS (SELECT 1 FROM pg_sequences WHERE sequencename = ?)"
if err := db.Raw(checkSQL, sequenceName).Scan(&exists).Error; err != nil {
log.Printf("检查序列 %s 是否存在时出错: %v", sequenceName, err)
continue
}
if !exists {
// 创建序列
createSQL := fmt.Sprintf("CREATE SEQUENCE IF NOT EXISTS %s START 1 INCREMENT 1", sequenceName)
if err := db.Exec(createSQL).Error; err != nil {
log.Printf("创建序列 %s 时出错: %v", sequenceName, err)
continue
}
// 将序列设置为表的默认值
alterSQL := fmt.Sprintf("ALTER TABLE %s ALTER COLUMN id SET DEFAULT nextval('%s')", table, sequenceName)
if err := db.Exec(alterSQL).Error; err != nil {
log.Printf("设置表 %s 的ID默认值时出错: %v", table, err)
continue
}
// 更新序列的当前值(如果表中已有数据)
updateSQL := fmt.Sprintf("SELECT setval('%s', COALESCE((SELECT MAX(id) FROM %s), 1), true)", sequenceName, table)
if err := db.Exec(updateSQL).Error; err != nil {
log.Printf("更新序列 %s 的当前值时出错: %v", sequenceName, err)
}
log.Printf("成功为表 %s 创建序列 %s", table, sequenceName)
}
}
}
+10 -5
View File
@@ -21,16 +21,21 @@ import (
// @name x-token
// @BasePath /
func main() {
global.GVA_VP = core.Viper() // 初始化Viper
// 初始化Viper
global.GVA_VP = core.Viper()
initialize.OtherInit()
global.GVA_LOG = core.Zap() // 初始化zap日志库
// 初始化zap日志库
global.GVA_LOG = core.Zap()
zap.ReplaceGlobals(global.GVA_LOG)
global.GVA_DB = initialize.Gorm() // gorm连接数据库
// gorm连接数据库
global.GVA_DB = initialize.Gorm()
initialize.Timer()
initialize.DBList()
if global.GVA_DB != nil {
initialize.RegisterTables() // 初始化表
initialize.InitWorkerPool() // 初始化工作池
// 初始化表
initialize.RegisterTables(global.GVA_DB)
// 初始化工作池
initialize.InitWorkerPool()
// 程序结束前关闭数据库链接
db, _ := global.GVA_DB.DB()
defer db.Close()
+1 -1
View File
@@ -274,7 +274,7 @@ func (dashboardService *DashboardService) GetAppQuotaRankingData(info gaiaReq.Ge
Total int64
}{list, total}
if err := dashboardService.cacheResult(cacheKey, result, 1800*time.Second); err != nil {
if err := dashboardService.cacheResult(cacheKey, result, 24*time.Hour); err != nil {
global.GVA_LOG.Error("Failed to cache result", zap.Error(err))
}
@@ -0,0 +1,48 @@
"""add_message_context_extend
Revision ID: 014_message_context_extend
Revises: 013_app_extend
Create Date: 2025-02-27
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.engine.reflection import Inspector
from models import types
# revision identifiers, used by Alembic.
revision = '014_message_context_extend'
down_revision = '013_app_extend'
branch_labels = None
depends_on = None
def upgrade():
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()
if 'message_context_extend' not in tables:
op.create_table('message_context_extend',
sa.Column('id', types.StringUUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('CURRENT_TIMESTAMP(0)'), nullable=False),
sa.Column('conversation_id', sa.String(36), nullable=True),
sa.Column('message_id', sa.String(36), nullable=False),
sa.PrimaryKeyConstraint('id', name='message_context_extend_joins_pkey')
)
with op.batch_alter_table('message_context_extend', schema=None) as batch_op:
batch_op.create_index('message_context_conversation_id_idx', ['conversation_id'], unique=False)
batch_op.create_index('message_context_created_at_idx', ['created_at'], unique=False)
def downgrade():
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()
if 'message_context_extend' in tables:
with op.batch_alter_table('message_context_extend', schema=None) as batch_op:
batch_op.drop_index('message_context_conversation_id_idx')
batch_op.drop_index('message_context_created_at_idx')
op.drop_table('message_context_extend')