Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 49 additions & 4 deletions docs/howto/vet.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
Rules are defined in the `sqlc` [configuration](../reference/config) file. They consist
of a name, message, and a [Common Expression Language (CEL)](https://github.com/google/cel-spec)
expression. Expressions are evaluated using [cel-go](https://github.com/google/cel-go).
If an expression evaluates to `true`, an error is reported using the given message.
If an expression evaluates to `true`, `sqlc vet` will report an error using the given message.

Each expression has access to variables from your sqlc configuration and queries,
defined in the following struct:
## Defining lint rules

Each lint rule's CEL expression has access to variables from your sqlc configuration and queries,
defined in the following struct.

```proto
message Config
Expand Down Expand Up @@ -109,4 +111,47 @@ example](https://github.com/kyleconroy/sqlc/blob/main/examples/authors/sqlc.yaml

Please note that `sqlc` does not manage or migrate your database. Use your
migration tool of choice to create the necessary database tables and objects
before running `sqlc vet`.
before running `sqlc vet` with the `sqlc/db-prepare` rule.

## Running lint rules

When you add the name of a defined rule to the rules list
for a [sql package](https://docs.sqlc.dev/en/stable/reference/config.html#sql),
`sqlc vet` will evaluate that rule against every query in the package.

In the example below, two rules are defined but only one is enabled.

```yaml
version: 2
sql:
- schema: "query.sql"
queries: "query.sql"
engine: "postgresql"
gen:
go:
package: "authors"
out: "db"
rules:
- no-delete
rules:
- name: no-pg
message: "invalid engine: postgresql"
rule: |
config.engine == "postgresql"
- name: no-delete
message: "don't use delete statements"
rule: |
query.sql.contains("DELETE")
```

### Opting-out of lint rules

For any query, you can tell `sqlc vet` not to evaluate lint rules using the
`@sqlc-vet-disable` query annotation.

```sql
/* name: GetAuthor :one */
/* @sqlc-vet-disable */
SELECT * FROM authors
WHERE id = ? LIMIT 1;
```
1 change: 1 addition & 0 deletions examples/authors/mysql/query.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* name: GetAuthor :one */
/* @sqlc-vet-disable */
SELECT * FROM authors
WHERE id = ? LIMIT 1;

Expand Down
6 changes: 5 additions & 1 deletion internal/cmd/vet.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
var ErrFailedChecks = errors.New("failed checks")

const RuleDbPrepare = "sqlc/db-prepare"
const QueryFlagSqlcVetDisable = "@sqlc-vet-disable"

func NewCmdVet() *cobra.Command {
return &cobra.Command{
Expand Down Expand Up @@ -249,7 +250,6 @@ func (c *checker) checkSQL(ctx context.Context, s config.SQL) error {
return ErrFailedChecks
}

// TODO: Add MySQL support
var prep preparer
if s.Database != nil {
if c.NoDatabase {
Expand Down Expand Up @@ -299,6 +299,10 @@ func (c *checker) checkSQL(ctx context.Context, s config.SQL) error {
req := codeGenRequest(result, combo)
cfg := vetConfig(req)
for i, query := range req.Queries {
if result.Queries[i].Flags[QueryFlagSqlcVetDisable] {
fmt.Printf("Skipping vet rules for query %s", query.Name)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think printing to stderr is fine and more correct than printing to stdout. Can we change the format to match error output? Also, if you want to suppress the output by default, you can check to see if debug.Active is true and only print it then.

fmt.Fprintf(c.Stderr, "%s: %s: %s: skipping\n", query.Filename, q.Name, name)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem with printing to stderr I think is that's where "normal" vet rule errors are reported, so skipping a rule would trigger a vet fail every time right?

The debug.Active check would suppress that except in cases where someone explicitly opted-in, but I'm still not sure it's the right thing to do.

continue
}
q := vetQuery(query)
for _, name := range s.Rules {
// Built-in rule
Expand Down
2 changes: 1 addition & 1 deletion internal/compiler/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (c *Compiler) parseQuery(stmt ast.Node, src string, o opts.Parser) (*Query,
return nil, err
}

flags, err := metadata.ParseQueryFlags(comments)
flags, comments, err := metadata.ParseQueryFlags(comments)
if err != nil {
return nil, err
}
Expand Down
7 changes: 5 additions & 2 deletions internal/metadata/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,9 @@ func ParseQueryNameAndType(t string, commentStyle CommentSyntax) (string, string
return "", "", nil
}

func ParseQueryFlags(comments []string) (map[string]bool, error) {
func ParseQueryFlags(comments []string) (map[string]bool, []string, error) {
flags := make(map[string]bool)
remainingComments := make([]string, 0, len(comments))
for _, line := range comments {
cleanLine := strings.TrimPrefix(line, "--")
cleanLine = strings.TrimPrefix(cleanLine, "/*")
Expand All @@ -115,7 +116,9 @@ func ParseQueryFlags(comments []string) (map[string]bool, error) {
if strings.HasPrefix(cleanLine, "@") {
flagName := strings.SplitN(cleanLine, " ", 2)[0]
flags[flagName] = true
continue
}
remainingComments = append(remainingComments, line)
}
return flags, nil
return flags, remainingComments, nil
}
2 changes: 1 addition & 1 deletion internal/metadata/meta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestParseQueryFlags(t *testing.T) {
"-- @flag-foo",
},
} {
flags, err := ParseQueryFlags(comments)
flags, _, err := ParseQueryFlags(comments)
if err != nil {
t.Errorf("expected query flags to parse, got error: %s", err)
}
Expand Down