-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathanalyze.go
More file actions
233 lines (206 loc) · 5.4 KB
/
analyze.go
File metadata and controls
233 lines (206 loc) · 5.4 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
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/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 := 0; i < colCount; i++ {
name := stmt.ColumnName(i)
declType := stmt.ColumnDeclType(i)
dbName := stmt.ColumnDatabaseName(i)
tableName := stmt.ColumnTableName(i)
originName := stmt.ColumnOriginName(i)
// Determine if column is NOT NULL
var notNull bool
var dataType string
if originName != "" {
declType, _, notNull, _, _, _ = a.conn.TableColumnMetadata(
dbName, tableName, originName)
}
// Normalize the data type
dataType = normalizeType(declType)
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
}
// 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
}
}