Без опису
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package dbs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "git.x2erp.com/qdy/go-svc-mcp/internal/mcp"
  8. )
  9. func init() {
  10. mcp.Register("get_mysql_data", "通过表名称获取MySQL表数据:只能接收表名称和分页查询参数分页参数数据获取数据不能超过10条",
  11. map[string]interface{}{
  12. "type": "object",
  13. "properties": map[string]interface{}{
  14. "table_name": map[string]interface{}{
  15. "type": "string",
  16. "description": "表名称",
  17. },
  18. "schema": map[string]interface{}{
  19. "type": "string",
  20. "description": "数据库名称(默认为当前数据库)",
  21. "default": "",
  22. },
  23. "page": map[string]interface{}{
  24. "type": "integer",
  25. "description": "页码(从1开始)",
  26. "default": 1,
  27. "minimum": 1,
  28. },
  29. "page_size": map[string]interface{}{
  30. "type": "integer",
  31. "description": "每页记录数(最大10条)",
  32. "default": 10,
  33. "minimum": 1,
  34. "maximum": 10,
  35. },
  36. "order_by": map[string]interface{}{
  37. "type": "string",
  38. "description": "排序字段(例如:column1 ASC, column2 DESC)",
  39. "default": "",
  40. },
  41. "where_clause": map[string]interface{}{
  42. "type": "string",
  43. "description": "WHERE条件(例如:status = 'ACTIVE')",
  44. "default": "",
  45. },
  46. "database_key": map[string]interface{}{
  47. "type": "string",
  48. "description": "数据库配置键名(如:business),可选,默认使用主数据库",
  49. "enum": []string{"warehouse", "business"},
  50. "default": "",
  51. },
  52. },
  53. "required": []string{"table_name"},
  54. },
  55. func(input json.RawMessage, deps *mcp.ToolDependencies) (interface{}, error) {
  56. var params struct {
  57. TableName string `json:"table_name"`
  58. Schema string `json:"schema"`
  59. Page int `json:"page"`
  60. PageSize int `json:"page_size"`
  61. OrderBy string `json:"order_by"`
  62. WhereClause string `json:"where_clause"`
  63. DatabaseKey string `json:"database_key"`
  64. }
  65. if len(input) > 0 {
  66. if err := json.Unmarshal(input, &params); err != nil {
  67. return nil, err
  68. }
  69. }
  70. // 设置默认值
  71. if params.Page == 0 {
  72. params.Page = 1
  73. }
  74. if params.PageSize == 0 {
  75. params.PageSize = 10
  76. }
  77. // 确保每页记录数不超过10条
  78. if params.PageSize > 10 {
  79. params.PageSize = 10
  80. }
  81. // 获取数据库工厂
  82. dbFactory, err := GetDBFactory(params.DatabaseKey, deps)
  83. if err != nil {
  84. return nil, err
  85. }
  86. // 获取数据库类型,确保是MySQL
  87. dbType := dbFactory.GetDBType()
  88. if dbType != "mysql" {
  89. return nil, fmt.Errorf("数据库类型为 %s,此工具仅支持MySQL数据库", dbType)
  90. }
  91. // 获取当前数据库名称
  92. currentDatabase := dbFactory.GetDatabaseName()
  93. schema := strings.TrimSpace(params.Schema)
  94. if schema == "" {
  95. schema = currentDatabase
  96. }
  97. tableName := strings.TrimSpace(params.TableName)
  98. if tableName == "" {
  99. return nil, fmt.Errorf("表名称不能为空")
  100. }
  101. // 验证表是否存在
  102. tableExistsQuery := `SELECT COUNT(*) as table_count FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`
  103. tableCheckResults, err := dbFactory.QuerySliceMapWithParams(tableExistsQuery, schema, tableName)
  104. if err != nil {
  105. return nil, fmt.Errorf("检查表是否存在失败: %v", err)
  106. }
  107. tableExists := false
  108. if len(tableCheckResults) > 0 {
  109. if count, ok := tableCheckResults[0]["table_count"].(int64); ok && count > 0 {
  110. tableExists = true
  111. }
  112. }
  113. if !tableExists {
  114. return nil, fmt.Errorf("表 '%s' 不存在于数据库 '%s' 中", tableName, schema)
  115. }
  116. // 构建带数据库前缀的表名
  117. fullTableName := fmt.Sprintf("`%s`.`%s`", schema, tableName)
  118. // 构建WHERE子句
  119. whereClause := ""
  120. if params.WhereClause != "" {
  121. whereClause = fmt.Sprintf("WHERE %s", params.WhereClause)
  122. }
  123. // 构建ORDER BY子句
  124. orderByClause := ""
  125. if params.OrderBy != "" {
  126. orderByClause = fmt.Sprintf("ORDER BY %s", params.OrderBy)
  127. }
  128. // 计算分页偏移量
  129. offset := (params.Page - 1) * params.PageSize
  130. // 先获取总记录数
  131. countQuery := fmt.Sprintf("SELECT COUNT(*) as total_count FROM %s %s", fullTableName, whereClause)
  132. countResults, err := dbFactory.QuerySliceMap(countQuery)
  133. if err != nil {
  134. return nil, fmt.Errorf("查询总记录数失败: %v", err)
  135. }
  136. totalCount := int64(0)
  137. if len(countResults) > 0 {
  138. if count, ok := countResults[0]["total_count"].(int64); ok {
  139. totalCount = count
  140. }
  141. }
  142. // 计算总页数
  143. totalPages := 0
  144. if totalCount > 0 {
  145. totalPages = int((totalCount + int64(params.PageSize) - 1) / int64(params.PageSize))
  146. }
  147. // 如果请求的页码大于总页数,返回空结果
  148. if params.Page > totalPages && totalPages > 0 {
  149. return map[string]interface{}{
  150. "tenant_id": deps.ReqCtx.TenantID,
  151. "user_id": deps.ReqCtx.UserID,
  152. "database_type": dbType,
  153. "database_name": dbFactory.GetDatabaseName(),
  154. "schema": schema,
  155. "table_name": tableName,
  156. "full_table_name": fullTableName,
  157. "page": params.Page,
  158. "page_size": params.PageSize,
  159. "total_count": totalCount,
  160. "total_pages": totalPages,
  161. "where_clause": params.WhereClause,
  162. "order_by": params.OrderBy,
  163. "data": []map[string]interface{}{},
  164. "data_count": 0,
  165. "has_more": false,
  166. "timestamp": time.Now().Format(time.RFC3339),
  167. }, nil
  168. }
  169. // 构建数据查询(MySQL分页查询)
  170. dataQuery := fmt.Sprintf("SELECT * FROM %s %s %s LIMIT %d OFFSET %d",
  171. fullTableName, whereClause, orderByClause, params.PageSize, offset)
  172. // 执行数据查询
  173. dataResults, err := dbFactory.QuerySliceMap(dataQuery)
  174. if err != nil {
  175. return nil, fmt.Errorf("查询表数据失败: %v", err)
  176. }
  177. // 检查是否有更多数据
  178. hasMore := (int64(offset+params.PageSize) < totalCount)
  179. return map[string]interface{}{
  180. "tenant_id": deps.ReqCtx.TenantID,
  181. "user_id": deps.ReqCtx.UserID,
  182. "database_type": dbType,
  183. "database_name": dbFactory.GetDatabaseName(),
  184. "schema": schema,
  185. "table_name": tableName,
  186. "full_table_name": fullTableName,
  187. "page": params.Page,
  188. "page_size": params.PageSize,
  189. "total_count": totalCount,
  190. "total_pages": totalPages,
  191. "where_clause": params.WhereClause,
  192. "order_by": params.OrderBy,
  193. "data": dataResults,
  194. "data_count": len(dataResults),
  195. "has_more": hasMore,
  196. "timestamp": time.Now().Format(time.RFC3339),
  197. "note": "数据获取限制:最多返回10条记录",
  198. }, nil
  199. },
  200. )
  201. }