-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.go
More file actions
194 lines (177 loc) · 5.31 KB
/
Copy pathsql.go
File metadata and controls
194 lines (177 loc) · 5.31 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
package tools
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"gophermind/internal/safety"
_ "modernc.org/sqlite"
)
// sqlMaxRows caps how many result rows the tool returns.
const sqlMaxRows = 100
// readOnlyVerbs are the statement kinds allowed by the read-only SQL tool.
var readOnlyVerbs = map[string]bool{"SELECT": true, "WITH": true, "PRAGMA": true, "EXPLAIN": true}
// SQLQuery returns a read-only, parameterized SQLite query tool. The database is
// opened read-only (mode=ro) AND the statement must begin with a read-only verb
// (SELECT/WITH/PRAGMA/EXPLAIN), so it can reason over real data without any risk
// of mutation. The db path is contained to the repository root.
func SQLQuery(root string) Tool {
return Tool{
Name: "sql_query",
Description: "Run a READ-ONLY, parameterized SQL query against a SQLite database file and return the rows. Only SELECT/WITH/PRAGMA/EXPLAIN are allowed.",
Schema: object(map[string]any{
"db": str("Path to the SQLite database file, relative to the repo root."),
"query": str("The SQL query (SELECT/WITH/PRAGMA/EXPLAIN only)."),
"params": map[string]any{"type": "array", "description": "Positional parameters bound to ? placeholders.", "items": map[string]any{}},
}, "db", "query"),
Run: func(ctx context.Context, raw json.RawMessage) (string, error) {
var a struct {
DB string `json:"db"`
Query string `json:"query"`
Params []any `json:"params"`
}
if err := json.Unmarshal(raw, &a); err != nil {
return "", fmt.Errorf("invalid arguments: %w", err)
}
if verb := firstVerb(a.Query); !readOnlyVerbs[verb] {
return "", fmt.Errorf("only read-only queries are allowed (got %q)", verb)
}
full, err := safety.SafeJoin(root, a.DB)
if err != nil {
return "", err
}
info, err := os.Stat(full)
if err != nil {
return "", fmt.Errorf("database %q not found", a.DB)
}
// Optional result cache keyed by (db-mtime, query, params) so repeat
// queries during analysis are instant.
cacheDir := sqlCacheDir()
var key string
if cacheDir != "" {
key = sqlCacheKey(full, info.ModTime().UnixNano(), a.Query, a.Params)
if cached, ok := cacheGetKey(cacheDir, key); ok {
return cached, nil
}
}
db, err := sql.Open("sqlite", "file:"+full+"?mode=ro")
if err != nil {
return "", fmt.Errorf("open db: %w", err)
}
defer db.Close()
rows, err := db.QueryContext(ctx, a.Query, a.Params...)
if err != nil {
return "", fmt.Errorf("query: %w", err)
}
defer rows.Close()
out, err := formatRows(rows)
if err != nil {
return "", err
}
if cacheDir != "" {
cachePutKey(cacheDir, key, out)
}
return out, nil
},
}
}
// firstVerb returns the upper-cased first SQL keyword of a query (ignoring
// leading whitespace and a leading comment line).
func firstVerb(q string) string {
q = strings.TrimSpace(q)
// Skip a leading -- comment line.
for strings.HasPrefix(q, "--") {
if i := strings.IndexByte(q, '\n'); i >= 0 {
q = strings.TrimSpace(q[i+1:])
} else {
return ""
}
}
fields := strings.Fields(q)
if len(fields) == 0 {
return ""
}
return strings.ToUpper(fields[0])
}
// formatRows renders result rows as a compact header + pipe-separated table,
// capped at sqlMaxRows.
func formatRows(rows *sql.Rows) (string, error) {
cols, err := rows.Columns()
if err != nil {
return "", err
}
var b strings.Builder
b.WriteString(strings.Join(cols, " | ") + "\n")
n := 0
for rows.Next() {
if n >= sqlMaxRows {
fmt.Fprintf(&b, "… [capped at %d rows]\n", sqlMaxRows)
break
}
vals := make([]any, len(cols))
ptrs := make([]any, len(cols))
for i := range vals {
ptrs[i] = &vals[i]
}
if err := rows.Scan(ptrs...); err != nil {
return "", err
}
cells := make([]string, len(cols))
for i, v := range vals {
cells[i] = cellString(v)
}
b.WriteString(strings.Join(cells, " | ") + "\n")
n++
}
if err := rows.Err(); err != nil {
return "", err
}
if n == 0 {
b.WriteString("(no rows)\n")
}
return truncate(b.String()), nil
}
// sqlCacheDir returns the configured SQL result-cache directory, or "" when
// caching is disabled (the default).
func sqlCacheDir() string {
return os.Getenv("GOPHERMIND_SQL_CACHE_DIR")
}
// sqlCacheKey derives a stable cache key from the db path, its mtime, and the
// query + params, so a modified database (new mtime) invalidates the entry.
func sqlCacheKey(dbPath string, mtimeNano int64, query string, params []any) string {
h := sha256.New()
fmt.Fprintf(h, "%s\x00%d\x00%s\x00", dbPath, mtimeNano, query)
pb, _ := json.Marshal(params)
h.Write(pb)
return hex.EncodeToString(h.Sum(nil))
}
// cacheGetKey returns a cached result for a precomputed key, if present.
func cacheGetKey(dir, key string) (string, bool) {
data, err := os.ReadFile(filepath.Join(dir, key+".txt"))
if err != nil {
return "", false
}
return string(data), true
}
// cachePutKey stores a result under a precomputed key, best-effort.
func cachePutKey(dir, key, content string) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return
}
_ = os.WriteFile(filepath.Join(dir, key+".txt"), []byte(content), 0o644)
}
func cellString(v any) string {
switch t := v.(type) {
case nil:
return "NULL"
case []byte:
return string(t)
default:
return fmt.Sprintf("%v", t)
}
}