Skip to content

Commit 6ad1dd9

Browse files
authored
Validate metadata from comment string (#117)
1 parent ff349b0 commit 6ad1dd9

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

internal/dinosql/parser.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,18 @@ func parseMetadata(t string) (string, string, error) {
291291
continue
292292
}
293293
part := strings.Split(line, " ")
294+
if len(part) == 2 {
295+
return "", "", fmt.Errorf("missing query type [':one', ':many', ':exec', ':execrows']: %s", line)
296+
}
297+
if len(part) != 4 {
298+
return "", "", fmt.Errorf("invalid query comment: %s", line)
299+
}
300+
queryType := strings.TrimSpace(part[3])
301+
switch queryType {
302+
case ":one", ":many", ":exec", ":execrows":
303+
default:
304+
return "", "", fmt.Errorf("invalid query type: %s", queryType)
305+
}
294306
return part[2], strings.TrimSpace(part[3]), nil
295307
}
296308
return "", "", nil

internal/dinosql/query_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,3 +781,39 @@ func TestStarWalker(t *testing.T) {
781781
})
782782
}
783783
}
784+
785+
func TestInvalidQueries(t *testing.T) {
786+
for i, tc := range []struct {
787+
stmt string
788+
}{
789+
{
790+
`
791+
CREATE TABLE foo (id text not null);
792+
-- name: ListFoos
793+
SELECT id FROM foo;
794+
`,
795+
},
796+
{
797+
`
798+
CREATE TABLE foo (id text not null);
799+
-- name: ListFoos :one :many
800+
SELECT id FROM foo;
801+
`,
802+
},
803+
{
804+
`
805+
CREATE TABLE foo (id text not null);
806+
-- name: ListFoos :two
807+
SELECT id FROM foo;
808+
`,
809+
},
810+
} {
811+
test := tc
812+
t.Run(strconv.Itoa(i), func(t *testing.T) {
813+
_, err := parseSQL(test.stmt)
814+
if err == nil {
815+
t.Errorf("expected err, got nil")
816+
}
817+
})
818+
}
819+
}

0 commit comments

Comments
 (0)