-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathanalyze.go
More file actions
369 lines (319 loc) · 8.95 KB
/
analyze.go
File metadata and controls
369 lines (319 loc) · 8.95 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
package analyzer
import (
"context"
"fmt"
"strings"
"sync"
"github.com/ncruces/go-sqlite3"
_ "github.com/ncruces/go-sqlite3/embed"
core "github.com/sqlc-dev/sqlc/internal/analysis"
"github.com/sqlc-dev/sqlc/internal/config"
"github.com/sqlc-dev/sqlc/internal/opts"
"github.com/sqlc-dev/sqlc/internal/shfmt"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/catalog"
"github.com/sqlc-dev/sqlc/internal/sql/named"
"github.com/sqlc-dev/sqlc/internal/sql/sqlerr"
)
type Analyzer struct {
db config.Database
conn *sqlite3.Conn
dbg opts.Debug
replacer *shfmt.Replacer
mu sync.Mutex
}
func New(db config.Database) *Analyzer {
return &Analyzer{
db: db,
dbg: opts.DebugFromEnv(),
replacer: shfmt.NewReplacer(nil),
}
}
func (a *Analyzer) Analyze(ctx context.Context, n ast.Node, query string, migrations []string, ps *named.ParamSet) (*core.Analysis, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn == nil {
var uri string
applyMigrations := a.db.Managed
if a.db.Managed {
// For managed databases, create an in-memory database
uri = ":memory:"
} else if a.dbg.OnlyManagedDatabases {
return nil, fmt.Errorf("database: connections disabled via SQLCDEBUG=databases=managed")
} else {
uri = a.replacer.Replace(a.db.URI)
// For in-memory databases, we need to apply migrations since the database starts empty
if isInMemoryDatabase(uri) {
applyMigrations = true
}
}
conn, err := sqlite3.Open(uri)
if err != nil {
return nil, fmt.Errorf("failed to open sqlite database: %w", err)
}
a.conn = conn
// Apply migrations for managed or in-memory databases
if applyMigrations {
for _, m := range migrations {
if len(strings.TrimSpace(m)) == 0 {
continue
}
if err := a.conn.Exec(m); err != nil {
a.conn.Close()
a.conn = nil
return nil, fmt.Errorf("migration failed: %s: %w", m, err)
}
}
}
}
// Prepare the statement to get column and parameter information
stmt, _, err := a.conn.Prepare(query)
if err != nil {
return nil, a.extractSqlErr(n, err)
}
defer stmt.Close()
var result core.Analysis
// Get column information
colCount := stmt.ColumnCount()
for i := range colCount {
name := stmt.ColumnName(i)
declType := stmt.ColumnDeclType(i)
tableName := stmt.ColumnTableName(i)
originName := stmt.ColumnOriginName(i)
dbName := stmt.ColumnDatabaseName(i)
// Normalize the data type
dataType := normalizeType(declType)
// Determine if column is NOT NULL
// SQLite doesn't provide this info directly from prepared statements,
// so we default to nullable (false)
notNull := false
col := &core.Column{
Name: name,
OriginalName: originName,
DataType: dataType,
NotNull: notNull,
}
if tableName != "" {
col.Table = &core.Identifier{
Schema: dbName,
Name: tableName,
}
}
result.Columns = append(result.Columns, col)
}
// Get parameter information
bindCount := stmt.BindCount()
for i := 1; i <= bindCount; i++ {
paramName := stmt.BindName(i)
// SQLite doesn't provide parameter types from prepared statements
// We use "any" as the default type
name := ""
if paramName != "" {
// Remove the prefix (?, :, @, $) from parameter names
name = strings.TrimLeft(paramName, "?:@$")
}
if ps != nil {
if n, ok := ps.NameFor(i); ok {
name = n
}
}
result.Params = append(result.Params, &core.Parameter{
Number: int32(i),
Column: &core.Column{
Name: name,
DataType: "any",
NotNull: false,
},
})
}
return &result, nil
}
func (a *Analyzer) extractSqlErr(n ast.Node, err error) error {
if err == nil {
return nil
}
// Try to extract SQLite error details
var sqliteErr *sqlite3.Error
if e, ok := err.(*sqlite3.Error); ok {
sqliteErr = e
}
if sqliteErr != nil {
return &sqlerr.Error{
Code: fmt.Sprintf("%d", sqliteErr.Code()),
Message: sqliteErr.Error(),
Location: n.Pos(),
}
}
return &sqlerr.Error{
Message: err.Error(),
Location: n.Pos(),
}
}
func (a *Analyzer) Close(_ context.Context) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn != nil {
err := a.conn.Close()
a.conn = nil
return err
}
return nil
}
// EnsureConn initializes the database connection if not already done.
// This is useful for database-only mode where we need to connect before analyzing queries.
func (a *Analyzer) EnsureConn(ctx context.Context, migrations []string) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn != nil {
return nil
}
var uri string
applyMigrations := a.db.Managed
if a.db.Managed {
// For managed databases, create an in-memory database
uri = ":memory:"
} else if a.dbg.OnlyManagedDatabases {
return fmt.Errorf("database: connections disabled via SQLCDEBUG=databases=managed")
} else {
uri = a.replacer.Replace(a.db.URI)
// For in-memory databases, we need to apply migrations since the database starts empty
if isInMemoryDatabase(uri) {
applyMigrations = true
}
}
conn, err := sqlite3.Open(uri)
if err != nil {
return fmt.Errorf("failed to open sqlite database: %w", err)
}
a.conn = conn
// Apply migrations for managed or in-memory databases
if applyMigrations {
for _, m := range migrations {
if len(strings.TrimSpace(m)) == 0 {
continue
}
if err := a.conn.Exec(m); err != nil {
a.conn.Close()
a.conn = nil
return fmt.Errorf("migration failed: %s: %w", m, err)
}
}
}
return nil
}
// GetColumnNames implements the expander.ColumnGetter interface.
// It prepares a query and returns the column names from the result set description.
func (a *Analyzer) GetColumnNames(ctx context.Context, query string) ([]string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn == nil {
return nil, fmt.Errorf("database connection not initialized")
}
stmt, _, err := a.conn.Prepare(query)
if err != nil {
return nil, err
}
defer stmt.Close()
colCount := stmt.ColumnCount()
columns := make([]string, colCount)
for i := range colCount {
columns[i] = stmt.ColumnName(i)
}
return columns, nil
}
// IntrospectSchema queries the database to build a catalog containing
// tables and columns for the database.
func (a *Analyzer) IntrospectSchema(ctx context.Context, schemas []string) (*catalog.Catalog, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn == nil {
return nil, fmt.Errorf("database connection not initialized")
}
// Build catalog
cat := &catalog.Catalog{
DefaultSchema: "main",
}
// Create default schema
mainSchema := &catalog.Schema{Name: "main"}
cat.Schemas = append(cat.Schemas, mainSchema)
// Query tables from sqlite_master
stmt, _, err := a.conn.Prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
if err != nil {
return nil, fmt.Errorf("introspect tables: %w", err)
}
tableNames := []string{}
for stmt.Step() {
tableName := stmt.ColumnText(0)
tableNames = append(tableNames, tableName)
}
stmt.Close()
// For each table, get column information using PRAGMA table_info
for _, tableName := range tableNames {
tbl := &catalog.Table{
Rel: &ast.TableName{
Name: tableName,
},
}
pragmaStmt, _, err := a.conn.Prepare(fmt.Sprintf("PRAGMA table_info('%s')", tableName))
if err != nil {
return nil, fmt.Errorf("pragma table_info for %s: %w", tableName, err)
}
for pragmaStmt.Step() {
// PRAGMA table_info returns: cid, name, type, notnull, dflt_value, pk
colName := pragmaStmt.ColumnText(1)
colType := pragmaStmt.ColumnText(2)
notNull := pragmaStmt.ColumnInt(3) != 0
tbl.Columns = append(tbl.Columns, &catalog.Column{
Name: colName,
Type: ast.TypeName{Name: normalizeType(colType)},
IsNotNull: notNull,
})
}
pragmaStmt.Close()
mainSchema.Tables = append(mainSchema.Tables, tbl)
}
return cat, nil
}
// isInMemoryDatabase checks if a SQLite URI refers to an in-memory database
func isInMemoryDatabase(uri string) bool {
if uri == ":memory:" || uri == "" {
return true
}
// Check for file URI with mode=memory parameter
// e.g., "file:test?mode=memory&cache=shared"
if strings.Contains(uri, "mode=memory") {
return true
}
return false
}
// normalizeType converts SQLite type declarations to standard type names
func normalizeType(declType string) string {
if declType == "" {
return "any"
}
// Convert to lowercase for comparison
lower := strings.ToLower(declType)
// SQLite type affinity rules (https://www.sqlite.org/datatype3.html)
switch {
case strings.Contains(lower, "int"):
return "integer"
case strings.Contains(lower, "char"),
strings.Contains(lower, "clob"),
strings.Contains(lower, "text"):
return "text"
case strings.Contains(lower, "blob"):
return "blob"
case strings.Contains(lower, "real"),
strings.Contains(lower, "floa"),
strings.Contains(lower, "doub"):
return "real"
case strings.Contains(lower, "bool"):
return "boolean"
case strings.Contains(lower, "date"),
strings.Contains(lower, "time"):
return "datetime"
default:
// Return as-is for numeric or other types
return lower
}
}