Нет описания
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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_postgresql_columns", "根据表名称获取PostgreSQL表的所有字段相关信息",
  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": "模式名称(默认为public)",
  21. "default": "",
  22. },
  23. "include_comments": map[string]interface{}{
  24. "type": "boolean",
  25. "description": "是否包含字段注释",
  26. "default": true,
  27. },
  28. "database_key": map[string]interface{}{
  29. "type": "string",
  30. "description": "数据库配置键名(如:business),可选,默认使用主数据库",
  31. "enum": []string{"warehouse", "business"},
  32. "default": "warehouse",
  33. },
  34. },
  35. "required": []string{"table_name"},
  36. },
  37. func(input json.RawMessage, deps *mcp.ToolDependencies) (interface{}, error) {
  38. var params struct {
  39. TableName string `json:"table_name"`
  40. Schema string `json:"schema"`
  41. IncludeComments bool `json:"include_comments"`
  42. DatabaseKey string `json:"database_key"`
  43. }
  44. if len(input) > 0 {
  45. if err := json.Unmarshal(input, &params); err != nil {
  46. return nil, err
  47. }
  48. }
  49. // 获取数据库工厂
  50. dbFactory, err := GetDBFactory(params.DatabaseKey, deps)
  51. if err != nil {
  52. return nil, err
  53. }
  54. // 获取数据库类型,确保是PostgreSQL
  55. dbType := dbFactory.GetDBType()
  56. if dbType != "postgresql" {
  57. return nil, fmt.Errorf("当前数据库类型为 %s,此工具仅支持PostgreSQL数据库", dbType)
  58. }
  59. // 设置默认模式
  60. schema := strings.TrimSpace(params.Schema)
  61. if schema == "" {
  62. schema = "public"
  63. }
  64. tableName := strings.TrimSpace(params.TableName)
  65. if tableName == "" {
  66. return nil, fmt.Errorf("表名称不能为空")
  67. }
  68. // 构建查询SQL
  69. var query string
  70. if params.IncludeComments {
  71. query = `
  72. SELECT
  73. c.ordinal_position as column_id,
  74. c.column_name,
  75. c.data_type,
  76. c.is_nullable,
  77. c.column_default,
  78. pgd.description as column_comment,
  79. c.character_maximum_length,
  80. c.numeric_precision,
  81. c.numeric_scale,
  82. c.udt_name as user_defined_type,
  83. CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_primary_key
  84. FROM information_schema.columns c
  85. LEFT JOIN pg_catalog.pg_description pgd
  86. ON pgd.objsubid = c.ordinal_position
  87. AND pgd.objoid = (SELECT oid FROM pg_catalog.pg_class WHERE relname = $2 AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1))
  88. LEFT JOIN (
  89. SELECT
  90. ku.column_name,
  91. tc.table_schema,
  92. tc.table_name
  93. FROM information_schema.table_constraints tc
  94. JOIN information_schema.key_column_usage ku
  95. ON tc.constraint_name = ku.constraint_name
  96. AND tc.table_schema = ku.table_schema
  97. WHERE tc.constraint_type = 'PRIMARY KEY'
  98. ) pk ON c.table_schema = pk.table_schema AND c.table_name = pk.table_name AND c.column_name = pk.column_name
  99. WHERE c.table_schema = $1
  100. AND c.table_name = $2
  101. ORDER BY c.ordinal_position`
  102. } else {
  103. query = `
  104. SELECT
  105. c.ordinal_position as column_id,
  106. c.column_name,
  107. c.data_type,
  108. c.is_nullable,
  109. c.column_default,
  110. c.character_maximum_length,
  111. c.numeric_precision,
  112. c.numeric_scale,
  113. c.udt_name as user_defined_type,
  114. CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_primary_key
  115. FROM information_schema.columns c
  116. LEFT JOIN (
  117. SELECT
  118. ku.column_name,
  119. tc.table_schema,
  120. tc.table_name
  121. FROM information_schema.table_constraints tc
  122. JOIN information_schema.key_column_usage ku
  123. ON tc.constraint_name = ku.constraint_name
  124. AND tc.table_schema = ku.table_schema
  125. WHERE tc.constraint_type = 'PRIMARY KEY'
  126. ) pk ON c.table_schema = pk.table_schema AND c.table_name = pk.table_name AND c.column_name = pk.column_name
  127. WHERE c.table_schema = $1
  128. AND c.table_name = $2
  129. ORDER BY c.ordinal_position`
  130. }
  131. // 执行查询
  132. results, err := dbFactory.QuerySliceMapWithParams(query, schema, tableName)
  133. if err != nil {
  134. return nil, fmt.Errorf("查询表字段信息失败: %v", err)
  135. }
  136. if len(results) == 0 {
  137. // 尝试查询表是否存在
  138. tableExistsQuery := `SELECT COUNT(*) as table_count FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2`
  139. tableCheckResults, err := dbFactory.QuerySliceMapWithParams(tableExistsQuery, schema, tableName)
  140. if err == nil && len(tableCheckResults) > 0 {
  141. if count, ok := tableCheckResults[0]["table_count"].(int64); ok && count == 0 {
  142. return nil, fmt.Errorf("表 '%s' 不存在于模式 '%s' 中", tableName, schema)
  143. }
  144. }
  145. return nil, fmt.Errorf("表 '%s' 存在但没有字段信息或表为空", tableName)
  146. }
  147. // 处理字段信息
  148. for i := range results {
  149. // 处理nullable字段
  150. if nullable, ok := results[i]["is_nullable"].(string); ok {
  151. results[i]["is_nullable"] = nullable == "YES"
  152. }
  153. // 处理注释字段
  154. if params.IncludeComments {
  155. if comment, ok := results[i]["column_comment"]; ok && comment == nil {
  156. results[i]["column_comment"] = ""
  157. }
  158. }
  159. // 处理默认值
  160. if defaultValue, ok := results[i]["column_default"]; ok && defaultValue == nil {
  161. results[i]["column_default"] = ""
  162. }
  163. // 构建完整数据类型
  164. if dataType, ok := results[i]["data_type"].(string); ok {
  165. fullType := dataType
  166. if length, ok := results[i]["character_maximum_length"].(int64); ok && length > 0 {
  167. fullType = fmt.Sprintf("%s(%d)", dataType, length)
  168. } else if precision, ok := results[i]["numeric_precision"].(int64); ok && precision > 0 {
  169. if scale, ok := results[i]["numeric_scale"].(int64); ok && scale > 0 {
  170. fullType = fmt.Sprintf("%s(%d,%d)", dataType, precision, scale)
  171. } else {
  172. fullType = fmt.Sprintf("%s(%d)", dataType, precision)
  173. }
  174. }
  175. results[i]["full_data_type"] = fullType
  176. }
  177. }
  178. // 获取表注释
  179. tableCommentQuery := `
  180. SELECT obj_description(pgc.oid, 'pg_class') as table_comment
  181. FROM pg_catalog.pg_class pgc
  182. JOIN pg_catalog.pg_namespace pgn ON pgn.oid = pgc.relnamespace
  183. WHERE pgc.relname = $2 AND pgn.nspname = $1`
  184. commentResults, err := dbFactory.QuerySliceMapWithParams(tableCommentQuery, schema, tableName)
  185. tableComment := ""
  186. if err == nil && len(commentResults) > 0 {
  187. if comment, ok := commentResults[0]["table_comment"].(string); ok {
  188. tableComment = comment
  189. }
  190. }
  191. return map[string]interface{}{
  192. "tenant_id": deps.ReqCtx.TenantID,
  193. "user_id": deps.ReqCtx.UserID,
  194. "database_type": dbType,
  195. "database_name": dbFactory.GetDatabaseName(),
  196. "schema": schema,
  197. "table_name": tableName,
  198. "table_comment": tableComment,
  199. "include_comments": params.IncludeComments,
  200. "columns": results,
  201. "total_columns": len(results),
  202. "timestamp": time.Now().Format(time.RFC3339),
  203. }, nil
  204. },
  205. )
  206. }