From 4dc24357b79f41fad2357570f76d0e9694f2de3d Mon Sep 17 00:00:00 2001 From: Yeagerist0 <180412661+Yeagerist0@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:01:31 +0530 Subject: [PATCH] fix: don't panic on :connect without a server name The command regex yields one empty argument for a bare :connect, so strings.Fields returns nothing and commandArgs[1:] panics. --- pkg/sqlcmd/commands.go | 8 +++++--- pkg/sqlcmd/connect_command_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 pkg/sqlcmd/connect_command_test.go diff --git a/pkg/sqlcmd/commands.go b/pkg/sqlcmd/commands.go index 66dd1dba..f2ae6e16 100644 --- a/pkg/sqlcmd/commands.go +++ b/pkg/sqlcmd/commands.go @@ -466,6 +466,10 @@ func connectCommand(s *Sqlcmd, args []string, line uint) error { } commandArgs := strings.Fields(args[0]) + // A bare ":connect" still yields one empty argument. + if len(commandArgs) == 0 { + return InvalidCommandError("CONNECT", line) + } // Parse flags flags := flag.NewFlagSet("connect", flag.ContinueOnError) @@ -499,9 +503,7 @@ func connectCommand(s *Sqlcmd, args []string, line uint) error { connect.AuthenticationMethod = *authenticationMethod // Set server name as the first positional argument - if len(commandArgs) > 0 { - connect.ServerName, _ = resolveArgumentVariables(s, []rune(commandArgs[0]), false) - } + connect.ServerName, _ = resolveArgumentVariables(s, []rune(commandArgs[0]), false) // If no user name is provided we switch to integrated auth _ = s.ConnectDb(&connect, s.lineIo == nil) diff --git a/pkg/sqlcmd/connect_command_test.go b/pkg/sqlcmd/connect_command_test.go new file mode 100644 index 00000000..2d4c5e89 --- /dev/null +++ b/pkg/sqlcmd/connect_command_test.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package sqlcmd + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestConnectCommandWithoutServerName(t *testing.T) { + for _, line := range []string{":connect", ":CONNECT ", ":connect -- no server"} { + t.Run(line, func(t *testing.T) { + s := New(nil, "", InitializeVariables(false)) + cmd, args := s.Cmd.matchCommand(line) + require.NotNil(t, cmd, "line should match a command") + var err error + assert.NotPanics(t, func() { err = cmd.action(s, args, 1) }) + assert.EqualError(t, err, InvalidCommandError("CONNECT", 1).Error()) + }) + } +}