MCPcopy Create free account
hub / github.com/bytebase/bytebase / executeQuery

Method executeQuery

backend/api/mcp/tool_query.go:180–255  ·  view source on GitHub ↗

executeQuery executes a SQL query against the resolved database.

(ctx context.Context, resolved *resolvedDatabase, statement string, limit int)

Source from the content-addressed store, hash-verified

178
179// executeQuery executes a SQL query against the resolved database.
180func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, statement string, limit int) (*QueryOutput, error) {
181 body := map[string]any{
182 "name": resolved.resourceName,
183 "dataSourceId": resolved.dataSourceID,
184 "statement": statement,
185 }
186 resp, err := s.apiRequest(ctx, "/bytebase.v1.SQLService/Query", body)
187 if err != nil {
188 return nil, &toolError{
189 Code: "QUERY_ERROR",
190 Message: fmt.Sprintf("query request failed: %s", err.Error()),
191 Suggestion: "check network connectivity and try again",
192 }
193 }
194 if resp.Status >= 400 {
195 errMsg := parseError(resp.Body)
196 if errMsg == "" {
197 errMsg = fmt.Sprintf("HTTP %d", resp.Status)
198 }
199 suggestion := "check your SQL syntax and try again"
200 if resp.Status == http.StatusForbidden || resp.Status == http.StatusUnauthorized {
201 suggestion = "you may not have permission to query this database — request the SQL Editor role on the project"
202 }
203 return nil, &toolError{
204 Code: "QUERY_ERROR",
205 Message: errMsg,
206 Suggestion: suggestion,
207 }
208 }
209
210 var qr queryResponse
211 if err := json.Unmarshal(resp.Body, &qr); err != nil {
212 return nil, errors.Wrap(err, "failed to parse query response")
213 }
214 if len(qr.Results) == 0 {
215 return &QueryOutput{
216 Columns: []string{},
217 ColumnTypes: []string{},
218 Rows: [][]any{},
219 }, nil
220 }
221
222 result := qr.Results[0]
223 if result.Error != "" {
224 return nil, &toolError{
225 Code: "QUERY_ERROR",
226 Message: result.Error,
227 Suggestion: "check your SQL syntax and try again",
228 }
229 }
230
231 // Flatten rows.
232 rows := make([][]any, 0, len(result.Rows))
233 for _, row := range result.Rows {
234 flat := make([]any, 0, len(row.Values))
235 for _, v := range row.Values {
236 flat = append(flat, flattenRowValue(v))
237 }

Callers 2

handleQueryDatabaseMethod · 0.95

Calls 6

apiRequestMethod · 0.95
parseErrorFunction · 0.85
flattenRowValueFunction · 0.85
parseLatencyMsFunction · 0.85
UnmarshalMethod · 0.80
ErrorMethod · 0.45

Tested by 1