-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathcompile.go
More file actions
271 lines (245 loc) · 6.86 KB
/
compile.go
File metadata and controls
271 lines (245 loc) · 6.86 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
package compiler
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/sqlc-dev/sqlc/internal/metadata"
"github.com/sqlc-dev/sqlc/internal/migrations"
"github.com/sqlc-dev/sqlc/internal/multierr"
"github.com/sqlc-dev/sqlc/internal/opts"
"github.com/sqlc-dev/sqlc/internal/rpc"
"github.com/sqlc-dev/sqlc/internal/source"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/named"
"github.com/sqlc-dev/sqlc/internal/sql/sqlerr"
"github.com/sqlc-dev/sqlc/internal/sql/sqlfile"
"github.com/sqlc-dev/sqlc/internal/sql/sqlpath"
)
// TODO: Rename this interface Engine
type Parser interface {
Parse(io.Reader) ([]ast.Statement, error)
CommentSyntax() source.CommentSyntax
IsReservedKeyword(string) bool
}
func (c *Compiler) parseCatalog(schemas []string) error {
files, err := sqlpath.Glob(schemas)
if err != nil {
return err
}
// Check if we're in skip_parser mode
skipParser := c.conf.Analyzer.SkipParser != nil && *c.conf.Analyzer.SkipParser
// If skip_parser is enabled, just read schema files without parsing
if skipParser {
for _, filename := range files {
blob, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("reading schema file %s: %w", filename, err)
}
contents := migrations.RemoveRollbackStatements(string(blob))
c.schema = append(c.schema, contents)
}
return nil
}
// Normal path: parse and update catalog
merr := multierr.New()
for _, filename := range files {
blob, err := os.ReadFile(filename)
if err != nil {
merr.Add(filename, "", 0, err)
continue
}
contents := migrations.RemoveRollbackStatements(string(blob))
c.schema = append(c.schema, contents)
stmts, err := c.parser.Parse(strings.NewReader(contents))
if err != nil {
merr.Add(filename, contents, 0, err)
continue
}
for i := range stmts {
if err := c.catalog.Update(stmts[i], c); err != nil {
merr.Add(filename, contents, stmts[i].Pos(), err)
continue
}
}
}
if len(merr.Errs()) > 0 {
return merr
}
return nil
}
func (c *Compiler) parseQueries(o opts.Parser) (*Result, error) {
var q []*Query
merr := multierr.New()
set := map[string]struct{}{}
files, err := sqlpath.Glob(c.conf.Queries)
if err != nil {
return nil, err
}
for _, filename := range files {
blob, err := os.ReadFile(filename)
if err != nil {
merr.Add(filename, "", 0, err)
continue
}
src := string(blob)
stmts, err := c.parser.Parse(strings.NewReader(src))
if err != nil {
merr.Add(filename, src, 0, err)
continue
}
for _, stmt := range stmts {
query, err := c.parseQuery(stmt.Raw, src, o)
if err != nil {
var e *sqlerr.Error
loc := stmt.Raw.Pos()
if errors.As(err, &e) && e.Location != 0 {
loc = e.Location
}
merr.Add(filename, src, loc, err)
// If this rpc unauthenticated error bubbles up, then all future parsing/analysis will fail
if errors.Is(err, rpc.ErrUnauthenticated) {
return nil, merr
}
continue
}
if query == nil {
continue
}
query.Metadata.Filename = filepath.Base(filename)
queryName := query.Metadata.Name
if queryName != "" {
if _, exists := set[queryName]; exists {
merr.Add(filename, src, stmt.Raw.Pos(), fmt.Errorf("duplicate query name: %s", queryName))
continue
}
set[queryName] = struct{}{}
}
q = append(q, query)
}
}
if len(merr.Errs()) > 0 {
return nil, merr
}
if len(q) == 0 {
return nil, fmt.Errorf("no queries contained in paths %s", strings.Join(c.conf.Queries, ","))
}
return &Result{
Catalog: c.catalog,
Queries: q,
}, nil
}
// parseQueriesWithAnalyzer parses queries using only the database analyzer,
// skipping the parser and catalog entirely. Uses sqlfile.Split to extract
// individual queries from .sql files.
func (c *Compiler) parseQueriesWithAnalyzer(o opts.Parser) (*Result, error) {
ctx := context.Background()
var q []*Query
merr := multierr.New()
set := map[string]struct{}{}
files, err := sqlpath.Glob(c.conf.Queries)
if err != nil {
return nil, err
}
if c.analyzer == nil {
return nil, fmt.Errorf("database analyzer is required when skip_parser is enabled")
}
for _, filename := range files {
blob, err := os.ReadFile(filename)
if err != nil {
merr.Add(filename, "", 0, err)
continue
}
src := string(blob)
// Use sqlfile.Split to extract individual queries
queries, err := sqlfile.Split(ctx, strings.NewReader(src))
if err != nil {
merr.Add(filename, src, 0, err)
continue
}
for _, queryText := range queries {
// Extract metadata from comments
name, cmd, err := metadata.ParseQueryNameAndType(queryText, metadata.CommentSyntax{Dash: true})
if err != nil {
merr.Add(filename, queryText, 0, err)
continue
}
// Skip queries without names (not marked with sqlc comments)
if name == "" {
continue
}
// Check for duplicate query names
if _, exists := set[name]; exists {
merr.Add(filename, queryText, 0, fmt.Errorf("duplicate query name: %s", name))
continue
}
set[name] = struct{}{}
// Extract additional metadata from comments
cleanedComments, err := source.CleanedComments(queryText, source.CommentSyntax{Dash: true})
if err != nil {
merr.Add(filename, queryText, 0, err)
continue
}
md := metadata.Metadata{
Name: name,
Cmd: cmd,
Filename: filepath.Base(filename),
}
md.Params, md.Flags, md.RuleSkiplist, err = metadata.ParseCommentFlags(cleanedComments)
if err != nil {
merr.Add(filename, queryText, 0, err)
continue
}
// Use the database analyzer to analyze the query
// We pass an empty AST node since we're not using the parser
result, err := c.analyzer.Analyze(ctx, nil, queryText, c.schema, &named.ParamSet{})
if err != nil {
merr.Add(filename, queryText, 0, err)
// If this rpc unauthenticated error bubbles up, then all future parsing/analysis will fail
if errors.Is(err, rpc.ErrUnauthenticated) {
return nil, merr
}
continue
}
// Convert analyzer results to Query format
var cols []*Column
for _, col := range result.Columns {
cols = append(cols, convertColumn(col))
}
var params []Parameter
for _, p := range result.Params {
params = append(params, Parameter{
Number: int(p.Number),
Column: convertColumn(p.Column),
})
}
// Strip comments from the final SQL
trimmed, comments, err := source.StripComments(queryText)
if err != nil {
merr.Add(filename, queryText, 0, err)
continue
}
md.Comments = comments
query := &Query{
SQL: trimmed,
Metadata: md,
Columns: cols,
Params: params,
}
q = append(q, query)
}
}
if len(merr.Errs()) > 0 {
return nil, merr
}
if len(q) == 0 {
return nil, fmt.Errorf("no queries contained in paths %s", strings.Join(c.conf.Queries, ","))
}
return &Result{
Catalog: nil, // No catalog when skip_parser is enabled
Queries: q,
}, nil
}