Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
57 changes: 41 additions & 16 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"os/user"
Expand Down Expand Up @@ -81,26 +82,37 @@ func NewRootCmd(ctx context.Context, cliCtx *CliContext) *cobra.Command {
if err := cliCtx.App.Start(ctx); err != nil {
return err
}
cliCtx.Printer.Println("Thanks for using Pgxcli.")
cliCtx.Printer.Println("see you next time.")
return nil
},

PersistentPostRunE: func(_ *cobra.Command, _ []string) error {
if cliCtx.App != nil {
if err := cliCtx.App.Close(); err != nil {
return err
}
}
if cliCtx.Client != nil {
if err := cliCtx.Client.Close(ctx); err != nil {
return err
}
PersistentPostRunE: func(cmd *cobra.Command, _ []string) error {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thank you, Daniel. One more thing I noticed is that when closing resources such as the DB, logger, etc, the current implementation exits the function as soon as an error occurs while closing a resource and prints the close error.

To make it more robust, how about collecting any errors that occur while closing the resources and returning them all at the end, if there are any? In that case, the output would be something like:

go run .
Thanks for using Pgxcli.
See you next time.
[error: failed to close the database connection]

We have to decide whether farewell message should be printed or not, if close error occurs. You can address this in another PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 584a3e9. Cleanup now attempts to close the application, database client, and logger even if an earlier close fails, then returns all close errors with errors.Join. For the farewell behavior, I chose to preserve #110’s intent: if any cleanup step fails, no farewell is printed. Added tests for cleanup order, error aggregation, and farewell behavior.

cleanupErr := closeResources(
func() error {
if cliCtx.App == nil {
return nil
}
return cliCtx.App.Close()
},
func() error {
if cliCtx.Client == nil {
return nil
}
return cliCtx.Client.Close(ctx)
},
func() error {
if cliCtx.Logger == nil {
return nil
}
return cliCtx.Logger.Close()
},
)
if cleanupErr != nil {
return cleanupErr
}
if cliCtx.Logger != nil {
if err := cliCtx.Logger.Close(); err != nil {
return err
}
// Keep future non-interactive subcommand output free of the interactive farewell.
if cmd == cmd.Root() {
cliCtx.Printer.Println("Thanks for using Pgxcli.")
cliCtx.Printer.Println("see you next time.")
}
return nil
},
Expand All @@ -125,6 +137,19 @@ func NewRootCmd(ctx context.Context, cliCtx *CliContext) *cobra.Command {
return rootCmd
}

// Close every resource so failures do not prevent later cleanup.
func closeResources(closers ...func() error) error {
var errs []error

for _, close := range closers {
if err := close(); err != nil {
errs = append(errs, err)
}
}

return errors.Join(errs...)
}

type connectionParams struct {
database string
user string
Expand Down
91 changes: 91 additions & 0 deletions internal/cli/root_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package cli

import (
"bytes"
"context"
"errors"
"io"
"os"
"strings"
"testing"

"github.com/balajz/pgxcli/internal/cliio"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -19,6 +25,91 @@ type dbAndUserTestCase struct {
expectedUser string
}

type testApp struct {
closeErr error
closeCalled bool
}

func (a *testApp) Start(context.Context) error { return nil }

func (a *testApp) Close() error {
a.closeCalled = true
return a.closeErr
}

func TestCloseResourcesClosesEverythingAndJoinsErrors(t *testing.T) {
t.Parallel()

appErr := errors.New("app close failed")
loggerErr := errors.New("logger close failed")
var calls []string

err := closeResources(
func() error {
calls = append(calls, "app")
return appErr
},
func() error {
calls = append(calls, "client")
return nil
},
func() error {
calls = append(calls, "logger")
return loggerErr
},
)

assert.Equal(t, []string{"app", "client", "logger"}, calls)
assert.ErrorIs(t, err, appErr)
assert.ErrorIs(t, err, loggerErr)
}

func TestPersistentPostRunCleanupAndFarewell(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
childCommand bool
cleanupFails bool
wantFarewell bool
}{
{name: "root success", wantFarewell: true},
{name: "root failure", cleanupFails: true},
{name: "child success", childCommand: true},
{name: "child failure", childCommand: true, cleanupFails: true},
}

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var output bytes.Buffer
var closeErr error
if testCase.cleanupFails {
closeErr = errors.New("history save failed")
}
testApplication := &testApp{closeErr: closeErr}
cliCtx := &CliContext{
App: testApplication,
Printer: cliio.NewPgxPrinter(&output, io.Discard),
}
rootCmd := NewRootCmd(context.Background(), cliCtx)
cmd := rootCmd
if testCase.childCommand {
cmd = &cobra.Command{Use: "export"}
rootCmd.AddCommand(cmd)
}

err := rootCmd.PersistentPostRunE(cmd, nil)
if closeErr != nil {
require.ErrorIs(t, err, closeErr)
} else {
require.NoError(t, err)
}
assert.True(t, testApplication.closeCalled)
assert.Equal(t, testCase.wantFarewell, strings.Contains(output.String(), "Thanks for using Pgxcli."))
})
}
}

func TestPromptPasswordFallsBackToFullLineInput(t *testing.T) {
oldStdin := os.Stdin
stdin, writer, err := os.Pipe()
Expand Down
Loading