package routes import ( "database/sql" "log" "git.x2erp.com/qdy/go-base/types" "git.x2erp.com/qdy/go-db/factory" "github.com/gin-gonic/gin" ) // 定义表结构 type tableDDL struct { TableName string SQL string } // 最简单的使用方式 - 直接在代码中维护 func ExecuteDDLHandler(db *sql.DB) func(c *gin.Context) { return func(c *gin.Context) { tables := getTableDDLs() success := []string{} failures := map[string]string{} // 直接遍历 tables 切片 for _, table := range tables { if err := factory.ExecuteDDL(db, table.SQL); err != nil { failures[table.TableName] = err.Error() log.Printf("[%s] 失败: %v", table.TableName, err) } else { success = append(success, table.TableName) log.Printf("[%s] 成功", table.TableName) } } successState := true if len(failures) > 0 { successState = false // 这里用 = 赋值,不是 := } c.JSON(200, types.QueryResult{ Success: successState, Data: gin.H{ "success": success, "failures": failures, }, }) } } // 获取所有表定义 func getTableDDLs() []tableDDL { return []tableDDL{ { TableName: "etl_service", SQL: ` CREATE TABLE IF NOT EXISTS etl_service ( etl_service_name VARCHAR(255) PRIMARY KEY, etl_ip VARCHAR(50) NOT NULL, etl_port INTEGER NOT NULL, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); `, }, { TableName: "etl_agent", SQL: ` CREATE TABLE IF NOT EXISTS etl_agent ( agent_id VARCHAR(50) PRIMARY KEY, agent_name VARCHAR(100) NOT NULL, agent_url VARCHAR(512) NOT NULL, agent_token VARCHAR(512) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); `, }, // 添加新表在这里插入新的 TableDDL } }