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

get_sqlserver_data.go 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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_sqlserver_data", "通过表名称获取SQL Server表数据:只能接收表名称和分页查询参数分页参数数据获取数据不能超过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": "模式名称(默认为dbo)",
  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": "warehouse",
  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. // 获取数据库类型,确保是SQL Server
  87. dbType := dbFactory.GetDBType()
  88. if dbType != "sqlserver" {
  89. return nil, fmt.Errorf("当前数据库类型为 %s,此工具仅支持SQL Server数据库", dbType)
  90. }
  91. // 设置默认模式
  92. schema := strings.TrimSpace(params.Schema)
  93. if schema == "" {
  94. schema = "dbo"
  95. }
  96. tableName := strings.TrimSpace(params.TableName)
  97. if tableName == "" {
  98. return nil, fmt.Errorf("表名称不能为空")
  99. }
  100. // 验证表是否存在
  101. tableExistsQuery := `SELECT COUNT(*) as table_count FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @p1 AND TABLE_NAME = @p2`
  102. tableCheckResults, err := dbFactory.QuerySliceMapWithParams(tableExistsQuery, schema, tableName)
  103. if err != nil {
  104. return nil, fmt.Errorf("检查表是否存在失败: %v", err)
  105. }
  106. tableExists := false
  107. if len(tableCheckResults) > 0 {
  108. if count, ok := tableCheckResults[0]["table_count"].(int64); ok && count > 0 {
  109. tableExists = true
  110. }
  111. }
  112. if !tableExists {
  113. return nil, fmt.Errorf("表 '%s' 不存在于模式 '%s' 中", tableName, schema)
  114. }
  115. // 构建带模式前缀的表名
  116. fullTableName := fmt.Sprintf("[%s].[%s]", schema, tableName)
  117. // 构建WHERE子句
  118. whereClause := ""
  119. if params.WhereClause != "" {
  120. whereClause = fmt.Sprintf("WHERE %s", params.WhereClause)
  121. }
  122. // 构建ORDER BY子句
  123. orderByClause := ""
  124. if params.OrderBy != "" {
  125. orderByClause = fmt.Sprintf("ORDER BY %s", params.OrderBy)
  126. }
  127. // 计算分页偏移量
  128. offset := (params.Page - 1) * params.PageSize
  129. // 先获取总记录数
  130. countQuery := fmt.Sprintf("SELECT COUNT(*) as total_count FROM %s %s", fullTableName, whereClause)
  131. countResults, err := dbFactory.QuerySliceMap(countQuery)
  132. if err != nil {
  133. return nil, fmt.Errorf("查询总记录数失败: %v", err)
  134. }
  135. totalCount := int64(0)
  136. if len(countResults) > 0 {
  137. if count, ok := countResults[0]["total_count"].(int64); ok {
  138. totalCount = count
  139. }
  140. }
  141. // 计算总页数
  142. totalPages := 0
  143. if totalCount > 0 {
  144. totalPages = int((totalCount + int64(params.PageSize) - 1) / int64(params.PageSize))
  145. }
  146. // 如果请求的页码大于总页数,返回空结果
  147. if params.Page > totalPages && totalPages > 0 {
  148. return map[string]interface{}{
  149. "tenant_id": deps.ReqCtx.TenantID,
  150. "user_id": deps.ReqCtx.UserID,
  151. "database_type": dbType,
  152. "database_name": dbFactory.GetDatabaseName(),
  153. "schema": schema,
  154. "table_name": tableName,
  155. "full_table_name": fullTableName,
  156. "page": params.Page,
  157. "page_size": params.PageSize,
  158. "total_count": totalCount,
  159. "total_pages": totalPages,
  160. "where_clause": params.WhereClause,
  161. "order_by": params.OrderBy,
  162. "data": []map[string]interface{}{},
  163. "data_count": 0,
  164. "has_more": false,
  165. "timestamp": time.Now().Format(time.RFC3339),
  166. }, nil
  167. }
  168. // 构建数据查询(SQL Server分页查询 - 使用OFFSET FETCH,需要SQL Server 2012+)
  169. dataQuery := ""
  170. if orderByClause == "" {
  171. // 如果没有指定ORDER BY,需要指定一个默认排序
  172. orderByClause = "ORDER BY (SELECT NULL)"
  173. }
  174. dataQuery = fmt.Sprintf(`
  175. SELECT * FROM %s
  176. %s
  177. %s
  178. OFFSET %d ROWS
  179. FETCH NEXT %d ROWS ONLY`,
  180. fullTableName, whereClause, orderByClause, offset, params.PageSize)
  181. // 执行数据查询
  182. dataResults, err := dbFactory.QuerySliceMap(dataQuery)
  183. if err != nil {
  184. // 如果OFFSET FETCH失败,可能是旧版本SQL Server,使用ROW_NUMBER作为备选方案
  185. fallbackQuery := fmt.Sprintf(`
  186. SELECT * FROM (
  187. SELECT *, ROW_NUMBER() OVER (%s) as row_num
  188. FROM %s
  189. %s
  190. ) as numbered
  191. WHERE row_num > %d AND row_num <= %d`,
  192. orderByClause, fullTableName, whereClause, offset, offset+params.PageSize)
  193. dataResults, err = dbFactory.QuerySliceMap(fallbackQuery)
  194. if err != nil {
  195. return nil, fmt.Errorf("查询表数据失败: %v", err)
  196. }
  197. // 移除row_num字段
  198. for i := range dataResults {
  199. delete(dataResults[i], "row_num")
  200. }
  201. }
  202. // 检查是否有更多数据
  203. hasMore := (int64(offset+params.PageSize) < totalCount)
  204. return map[string]interface{}{
  205. "tenant_id": deps.ReqCtx.TenantID,
  206. "user_id": deps.ReqCtx.UserID,
  207. "database_type": dbType,
  208. "database_name": dbFactory.GetDatabaseName(),
  209. "schema": schema,
  210. "table_name": tableName,
  211. "full_table_name": fullTableName,
  212. "page": params.Page,
  213. "page_size": params.PageSize,
  214. "total_count": totalCount,
  215. "total_pages": totalPages,
  216. "where_clause": params.WhereClause,
  217. "order_by": params.OrderBy,
  218. "data": dataResults,
  219. "data_count": len(dataResults),
  220. "has_more": hasMore,
  221. "timestamp": time.Now().Format(time.RFC3339),
  222. "note": "数据获取限制:最多返回10条记录",
  223. }, nil
  224. },
  225. )
  226. }