Skip to content

Commit 5a18a04

Browse files
committed
strip pg_dump 17+ meta-commands
1 parent 946e889 commit 5a18a04

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

pkg/dbutil/dbutil.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,22 +57,30 @@ func RunCommand(name string, args ...string) ([]byte, error) {
5757
return stdout.Bytes(), nil
5858
}
5959

60-
// TrimLeadingSQLComments removes sql comments and blank lines from the beginning of text
61-
// generally when performing sql dumps these contain host-specific information such as
62-
// client/server version numbers
60+
// TrimLeadingSQLComments removes sql comments and blank lines from the beginning of text,
61+
// and psql meta-commands (lines starting with \) from anywhere in the text.
62+
// It also collapses 3+ consecutive blank lines to 2 for consistent formatting.
63+
// Generally when performing sql dumps these contain host-specific information such as
64+
// client/server version numbers.
6365
func TrimLeadingSQLComments(data []byte) ([]byte, error) {
6466
// create decent size buffer
6567
out := bytes.NewBuffer(make([]byte, 0, len(data)))
6668

6769
// iterate over sql lines
6870
preamble := true
71+
consecutiveBlankLines := 0
6972
scanner := bufio.NewScanner(bytes.NewReader(data))
7073
for scanner.Scan() {
7174
// we read bytes directly for premature performance optimization
7275
line := scanner.Bytes()
7376

74-
if preamble && (len(line) == 0 || bytes.Equal(line[0:2], []byte("--"))) {
75-
// header section, skip this line in output buffer
77+
// always skip psql meta-commands (e.g., \restrict, \unrestrict from pg_dump 17+)
78+
if len(line) >= 1 && line[0] == '\\' {
79+
continue
80+
}
81+
82+
if preamble && (len(line) == 0 || (len(line) >= 2 && bytes.Equal(line[0:2], []byte("--")))) {
83+
// header section, skip blank lines and SQL comments (--)
7684
continue
7785
}
7886

@@ -82,6 +90,16 @@ func TrimLeadingSQLComments(data []byte) ([]byte, error) {
8290
// trim trailing whitespace
8391
line = bytes.TrimRightFunc(line, unicode.IsSpace)
8492

93+
// track consecutive blank lines and collapse 3+ to 2
94+
if len(line) == 0 {
95+
consecutiveBlankLines++
96+
if consecutiveBlankLines > 2 {
97+
continue
98+
}
99+
} else {
100+
consecutiveBlankLines = 0
101+
}
102+
85103
// copy bytes to output buffer
86104
if _, err := out.Write(line); err != nil {
87105
return nil, err

0 commit comments

Comments
 (0)