executeQuery executes a SQL query against the resolved database.
(ctx context.Context, resolved *resolvedDatabase, statement string, limit int)
| 178 | |
| 179 | // executeQuery executes a SQL query against the resolved database. |
| 180 | func (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 | } |