From b80aaa172778f8ebe1eb2f5dd6347cfa7d090b35 Mon Sep 17 00:00:00 2001 From: Nathan Wallace Date: Sun, 16 Nov 2025 14:11:56 -0500 Subject: [PATCH] Fix #4704: Preserve newlines in getPipedStdinData (#4878) * Add test for #4704: getPipedStdinData should preserve newlines * Fix #4704: Preserve newlines in getPipedStdinData --- cmd/query.go | 13 ++++++------ cmd/query_test.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 cmd/query_test.go diff --git a/cmd/query.go b/cmd/query.go index 81423a7cb..758fcbe93 100644 --- a/cmd/query.go +++ b/cmd/query.go @@ -1,9 +1,9 @@ package cmd import ( - "bufio" "context" "fmt" + "io" "os" "slices" "strings" @@ -185,12 +185,13 @@ func getPipedStdinData() string { error_helpers.ShowWarning("could not fetch information about STDIN") return "" } - stdinData := "" if (fi.Mode()&os.ModeCharDevice) == 0 && fi.Size() > 0 { - scanner := bufio.NewScanner(os.Stdin) - for scanner.Scan() { - stdinData = fmt.Sprintf("%s%s", stdinData, scanner.Text()) + data, err := io.ReadAll(os.Stdin) + if err != nil { + error_helpers.ShowWarning("could not read from STDIN") + return "" } + return string(data) } - return stdinData + return "" } diff --git a/cmd/query_test.go b/cmd/query_test.go new file mode 100644 index 000000000..9284c46a3 --- /dev/null +++ b/cmd/query_test.go @@ -0,0 +1,54 @@ +package cmd + +import ( + "os" + "strings" + "testing" +) + +func TestGetPipedStdinData_PreservesNewlines(t *testing.T) { + // Save original stdin + oldStdin := os.Stdin + defer func() { os.Stdin = oldStdin }() + + // Create a temporary file to simulate piped input + tmpFile, err := os.CreateTemp("", "stdin-test-*") + if err != nil { + t.Fatalf("Failed to create temp file: %v", err) + } + defer os.Remove(tmpFile.Name()) + + // Test input with multiple lines - matching the bug report example + testInput := "SELECT * FROM aws_account\nWHERE account_id = '123'\nAND region = 'us-east-1';" + + // Write test input to the temp file + if _, err := tmpFile.WriteString(testInput); err != nil { + t.Fatalf("Failed to write to temp file: %v", err) + } + + // Seek back to the beginning + if _, err := tmpFile.Seek(0, 0); err != nil { + t.Fatalf("Failed to seek temp file: %v", err) + } + + // Replace stdin with our temp file + os.Stdin = tmpFile + + // Call the function + result := getPipedStdinData() + + // Clean up + tmpFile.Close() + + // Verify that newlines are preserved + if result != testInput { + t.Errorf("getPipedStdinData() did not preserve newlines\nExpected: %q\nGot: %q", testInput, result) + + // Show the difference more clearly + expectedLines := strings.Split(testInput, "\n") + resultLines := strings.Split(result, "\n") + t.Logf("Expected %d lines, got %d lines", len(expectedLines), len(resultLines)) + t.Logf("Expected lines: %v", expectedLines) + t.Logf("Got lines: %v", resultLines) + } +}