-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
418 lines (370 loc) · 10.5 KB
/
main.go
File metadata and controls
418 lines (370 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package main
import (
"database/sql"
"encoding/json"
"fmt"
"strings"
"sync"
_ "github.com/databricks/databricks-sql-go"
"github.com/mlund01/squadron-sdk"
)
var tools = map[string]*squadron.ToolInfo{
"execute_sql": {
Name: "execute_sql",
Description: "Execute a SQL query against Databricks and return results as JSON. Use for SELECT queries, DDL, or DML statements.",
Schema: squadron.Schema{
Type: squadron.TypeObject,
Properties: squadron.PropertyMap{
"query": {
Type: squadron.TypeString,
Description: "The SQL query to execute",
},
"catalog": {
Type: squadron.TypeString,
Description: "The catalog to set before running the query (optional if using fully qualified names)",
},
"schema": {
Type: squadron.TypeString,
Description: "The schema to set before running the query (optional if using fully qualified names)",
},
"max_rows": {
Type: squadron.TypeInteger,
Description: "Maximum number of rows to return (default: 1000, max: 10000)",
},
},
Required: []string{"query"},
},
},
"list_schemas": {
Name: "list_schemas",
Description: "List all schemas in a catalog",
Schema: squadron.Schema{
Type: squadron.TypeObject,
Properties: squadron.PropertyMap{
"catalog": {
Type: squadron.TypeString,
Description: "The catalog to list schemas from (optional)",
},
},
},
},
"list_tables": {
Name: "list_tables",
Description: "List all tables in a schema",
Schema: squadron.Schema{
Type: squadron.TypeObject,
Properties: squadron.PropertyMap{
"catalog": {
Type: squadron.TypeString,
Description: "The catalog containing the schema (optional)",
},
"schema": {
Type: squadron.TypeString,
Description: "The schema name to list tables from (required)",
},
},
Required: []string{"schema"},
},
},
"describe_table": {
Name: "describe_table",
Description: "Get the column names, types, and comments for a table",
Schema: squadron.Schema{
Type: squadron.TypeObject,
Properties: squadron.PropertyMap{
"table": {
Type: squadron.TypeString,
Description: "The table name (can be catalog.schema.table, schema.table, or just table)",
},
},
Required: []string{"table"},
},
},
}
type DatabricksPlugin struct {
mu sync.Mutex
db *sql.DB
}
func (p *DatabricksPlugin) Configure(settings map[string]string) error {
host := settings["host"]
token := settings["token"]
httpPath := settings["http_path"]
if host == "" {
return fmt.Errorf("'host' setting is required")
}
if token == "" {
return fmt.Errorf("'token' setting is required")
}
if httpPath == "" {
return fmt.Errorf("'http_path' setting is required")
}
dsn := fmt.Sprintf("token:%s@%s:443%s", token, host, httpPath)
db, err := sql.Open("databricks", dsn)
if err != nil {
return fmt.Errorf("failed to open databricks connection: %w", err)
}
if err := db.Ping(); err != nil {
db.Close()
return fmt.Errorf("failed to connect to databricks: %w", err)
}
p.mu.Lock()
defer p.mu.Unlock()
p.db = db
return nil
}
func (p *DatabricksPlugin) Call(toolName string, payload string) (string, error) {
p.mu.Lock()
db := p.db
p.mu.Unlock()
if db == nil {
return "", fmt.Errorf("plugin not configured — call Configure first")
}
switch toolName {
case "execute_sql":
return p.executeSQL(db, payload)
case "list_schemas":
return p.listSchemas(db, payload)
case "list_tables":
return p.listTables(db, payload)
case "describe_table":
return p.describeTable(db, payload)
default:
return "", fmt.Errorf("unknown tool: %s", toolName)
}
}
func (p *DatabricksPlugin) GetToolInfo(toolName string) (*squadron.ToolInfo, error) {
info, ok := tools[toolName]
if !ok {
return nil, fmt.Errorf("unknown tool: %s", toolName)
}
return info, nil
}
func (p *DatabricksPlugin) ListTools() ([]*squadron.ToolInfo, error) {
result := make([]*squadron.ToolInfo, 0, len(tools))
for _, info := range tools {
result = append(result, info)
}
return result, nil
}
// useCatalogSchema runs USE CATALOG and USE SCHEMA if provided, scoped to a single call
func (p *DatabricksPlugin) useCatalogSchema(db *sql.DB, catalog, schema string) error {
if catalog != "" {
if _, err := db.Exec("USE CATALOG " + catalog); err != nil {
return fmt.Errorf("failed to set catalog: %w", err)
}
}
if schema != "" {
if _, err := db.Exec("USE SCHEMA " + schema); err != nil {
return fmt.Errorf("failed to set schema: %w", err)
}
}
return nil
}
// executeSQL runs a SQL query and returns results as JSON
func (p *DatabricksPlugin) executeSQL(db *sql.DB, payload string) (string, error) {
var params struct {
Query string `json:"query"`
Catalog string `json:"catalog"`
Schema string `json:"schema"`
MaxRows int `json:"max_rows"`
}
if err := json.Unmarshal([]byte(payload), ¶ms); err != nil {
return "", fmt.Errorf("invalid payload: %w", err)
}
if params.Query == "" {
return "", fmt.Errorf("'query' is required")
}
if params.MaxRows <= 0 {
params.MaxRows = 1000
}
if params.MaxRows > 10000 {
params.MaxRows = 10000
}
if err := p.useCatalogSchema(db, params.Catalog, params.Schema); err != nil {
return "", err
}
// Detect if this is a non-SELECT statement
trimmed := strings.TrimSpace(strings.ToUpper(params.Query))
isSelect := strings.HasPrefix(trimmed, "SELECT") || strings.HasPrefix(trimmed, "SHOW") || strings.HasPrefix(trimmed, "DESCRIBE") || strings.HasPrefix(trimmed, "EXPLAIN") || strings.HasPrefix(trimmed, "WITH")
if !isSelect {
result, err := db.Exec(params.Query)
if err != nil {
return "", fmt.Errorf("query execution failed: %w", err)
}
rowsAffected, _ := result.RowsAffected()
return fmt.Sprintf(`{"status": "ok", "rows_affected": %d}`, rowsAffected), nil
}
rows, err := db.Query(params.Query)
if err != nil {
return "", fmt.Errorf("query execution failed: %w", err)
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return "", fmt.Errorf("failed to get columns: %w", err)
}
var results []map[string]any
count := 0
for rows.Next() && count < params.MaxRows {
values := make([]any, len(columns))
valuePtrs := make([]any, len(columns))
for i := range values {
valuePtrs[i] = &values[i]
}
if err := rows.Scan(valuePtrs...); err != nil {
return "", fmt.Errorf("failed to scan row: %w", err)
}
row := make(map[string]any)
for i, col := range columns {
val := values[i]
if b, ok := val.([]byte); ok {
row[col] = string(b)
} else {
row[col] = val
}
}
results = append(results, row)
count++
}
if err := rows.Err(); err != nil {
return "", fmt.Errorf("row iteration error: %w", err)
}
output := map[string]any{
"columns": columns,
"rows": results,
"row_count": len(results),
}
if len(results) == params.MaxRows {
output["truncated"] = true
}
b, err := json.Marshal(output)
if err != nil {
return "", fmt.Errorf("failed to marshal results: %w", err)
}
return string(b), nil
}
// listSchemas returns all schemas in a catalog
func (p *DatabricksPlugin) listSchemas(db *sql.DB, payload string) (string, error) {
var params struct {
Catalog string `json:"catalog"`
}
if payload != "" && payload != "{}" {
json.Unmarshal([]byte(payload), ¶ms)
}
query := "SHOW SCHEMAS"
if params.Catalog != "" {
query += " IN " + params.Catalog
}
rows, err := db.Query(query)
if err != nil {
return "", fmt.Errorf("failed to list schemas: %w", err)
}
defer rows.Close()
var schemas []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return "", fmt.Errorf("failed to scan schema: %w", err)
}
schemas = append(schemas, name)
}
b, err := json.Marshal(map[string]any{"schemas": schemas})
if err != nil {
return "", fmt.Errorf("failed to marshal schemas: %w", err)
}
return string(b), nil
}
// listTables returns all tables in a schema
func (p *DatabricksPlugin) listTables(db *sql.DB, payload string) (string, error) {
var params struct {
Catalog string `json:"catalog"`
Schema string `json:"schema"`
}
if err := json.Unmarshal([]byte(payload), ¶ms); err != nil {
return "", fmt.Errorf("invalid payload: %w", err)
}
if params.Schema == "" {
return "", fmt.Errorf("'schema' is required")
}
qualifier := params.Schema
if params.Catalog != "" {
qualifier = params.Catalog + "." + params.Schema
}
rows, err := db.Query("SHOW TABLES IN " + qualifier)
if err != nil {
return "", fmt.Errorf("failed to list tables: %w", err)
}
defer rows.Close()
columns, _ := rows.Columns()
var tables []map[string]any
for rows.Next() {
values := make([]any, len(columns))
valuePtrs := make([]any, len(columns))
for i := range values {
valuePtrs[i] = &values[i]
}
if err := rows.Scan(valuePtrs...); err != nil {
return "", fmt.Errorf("failed to scan table: %w", err)
}
row := make(map[string]any)
for i, col := range columns {
if b, ok := values[i].([]byte); ok {
row[col] = string(b)
} else {
row[col] = values[i]
}
}
tables = append(tables, row)
}
b, err := json.Marshal(map[string]any{"tables": tables})
if err != nil {
return "", fmt.Errorf("failed to marshal tables: %w", err)
}
return string(b), nil
}
// describeTable returns column info for a table
func (p *DatabricksPlugin) describeTable(db *sql.DB, payload string) (string, error) {
var params struct {
Table string `json:"table"`
}
if err := json.Unmarshal([]byte(payload), ¶ms); err != nil {
return "", fmt.Errorf("invalid payload: %w", err)
}
if params.Table == "" {
return "", fmt.Errorf("'table' is required")
}
rows, err := db.Query("DESCRIBE TABLE " + params.Table)
if err != nil {
return "", fmt.Errorf("failed to describe table: %w", err)
}
defer rows.Close()
columns, _ := rows.Columns()
var columnInfos []map[string]any
for rows.Next() {
values := make([]any, len(columns))
valuePtrs := make([]any, len(columns))
for i := range values {
valuePtrs[i] = &values[i]
}
if err := rows.Scan(valuePtrs...); err != nil {
return "", fmt.Errorf("failed to scan column info: %w", err)
}
row := make(map[string]any)
for i, col := range columns {
if b, ok := values[i].([]byte); ok {
row[col] = string(b)
} else {
row[col] = values[i]
}
}
columnInfos = append(columnInfos, row)
}
b, err := json.Marshal(map[string]any{"table": params.Table, "columns": columnInfos})
if err != nil {
return "", fmt.Errorf("failed to marshal column info: %w", err)
}
return string(b), nil
}
func main() {
squadron.Serve(&DatabricksPlugin{})
}