@@ -2,9 +2,16 @@ package migrations
22
33import (
44 "bufio"
5+ "regexp"
56 "strings"
67)
78
9+ // psqlMetaCommand matches a psql meta-command (a line that begins with a
10+ // backslash followed by a command name). pg_dump emits these starting with
11+ // PostgreSQL 17.6 / 16.10 / 15.14 / 14.19 / 13.22 (e.g. `\restrict KEY` and
12+ // `\unrestrict KEY`), and sqlc's SQL parsers cannot handle them.
13+ var psqlMetaCommand = regexp .MustCompile (`^\\[A-Za-z!?;][^\n]*$` )
14+
815// Remove all lines after a rollback comment.
916//
1017// goose: -- +goose Down
@@ -33,6 +40,22 @@ func RemoveRollbackStatements(contents string) string {
3340 return strings .Join (lines , "\n " )
3441}
3542
43+ // RemovePsqlMetaCommands strips psql meta-command lines (e.g. `\restrict KEY`,
44+ // `\unrestrict KEY`, `\connect foo`) from SQL input. These are emitted by
45+ // pg_dump but are not valid SQL, so they must be removed before parsing.
46+ func RemovePsqlMetaCommands (contents string ) string {
47+ s := bufio .NewScanner (strings .NewReader (contents ))
48+ var lines []string
49+ for s .Scan () {
50+ line := s .Text ()
51+ if psqlMetaCommand .MatchString (line ) {
52+ continue
53+ }
54+ lines = append (lines , line )
55+ }
56+ return strings .Join (lines , "\n " )
57+ }
58+
3659func IsDown (filename string ) bool {
3760 // Remove golang-migrate rollback files.
3861 return strings .HasSuffix (filename , ".down.sql" )
0 commit comments