暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

init_table.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package routes
  2. import (
  3. "database/sql"
  4. "log"
  5. "git.x2erp.com/qdy/go-base/types"
  6. "git.x2erp.com/qdy/go-db/factory"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // 定义表结构
  10. type tableDDL struct {
  11. TableName string
  12. SQL string
  13. }
  14. // 最简单的使用方式 - 直接在代码中维护
  15. func ExecuteDDLHandler(db *sql.DB) func(c *gin.Context) {
  16. return func(c *gin.Context) {
  17. tables := getTableDDLs()
  18. success := []string{}
  19. failures := map[string]string{}
  20. // 直接遍历 tables 切片
  21. for _, table := range tables {
  22. if err := factory.ExecuteDDL(db, table.SQL); err != nil {
  23. failures[table.TableName] = err.Error()
  24. log.Printf("[%s] 失败: %v", table.TableName, err)
  25. } else {
  26. success = append(success, table.TableName)
  27. log.Printf("[%s] 成功", table.TableName)
  28. }
  29. }
  30. successState := true
  31. if len(failures) > 0 {
  32. successState = false // 这里用 = 赋值,不是 :=
  33. }
  34. c.JSON(200, types.QueryResult{
  35. Success: successState,
  36. Data: gin.H{
  37. "success": success,
  38. "failures": failures,
  39. },
  40. })
  41. }
  42. }
  43. // 获取所有表定义
  44. func getTableDDLs() []tableDDL {
  45. return []tableDDL{
  46. {
  47. TableName: "etl_service",
  48. SQL: `
  49. CREATE TABLE IF NOT EXISTS etl_service (
  50. etl_service_name VARCHAR(255) PRIMARY KEY,
  51. etl_ip VARCHAR(50) NOT NULL,
  52. etl_port INTEGER NOT NULL,
  53. create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  54. );
  55. `,
  56. },
  57. {
  58. TableName: "etl_agent",
  59. SQL: `
  60. CREATE TABLE IF NOT EXISTS etl_agent (
  61. agent_id VARCHAR(50) PRIMARY KEY,
  62. agent_name VARCHAR(100) NOT NULL,
  63. agent_url VARCHAR(512) NOT NULL,
  64. agent_token VARCHAR(512) NOT NULL,
  65. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  66. );
  67. `,
  68. },
  69. // 添加新表在这里插入新的 TableDDL
  70. }
  71. }