Documentation ¶
Index ¶
- Constants
- Variables
- func GetTokenBasedConnection(connstr string, authenticationMethod string) (driver.Connector, error)
- func InvalidFileError(err error, filepath string) error
- func ParseValue(val string) (string, error)
- func ValidIdentifier(name string) error
- type ArgumentError
- type Batch
- type Command
- type CommandError
- type Commands
- type CommonSqlcmdErr
- type ConnectSettings
- type Console
- type ControlCharacterBehavior
- type FileError
- type Formatter
- type Sqlcmd
- func (s *Sqlcmd) ConnectDb(connect *ConnectSettings, nopw bool) error
- func (s *Sqlcmd) GetError() io.Writer
- func (s *Sqlcmd) GetOutput() io.Writer
- func (s *Sqlcmd) IncludeFile(path string, processAll bool) error
- func (s Sqlcmd) Log(_ context.Context, _ msdsn.Log, msg string)
- func (s *Sqlcmd) Prompt() string
- func (s *Sqlcmd) Run(once bool, processAll bool) error
- func (s *Sqlcmd) RunCommand(cmd *Command, args []string) error
- func (s *Sqlcmd) SetError(e io.WriteCloser)
- func (s *Sqlcmd) SetOutput(o io.WriteCloser)
- func (s *Sqlcmd) SetupCloseHandler()
- func (s *Sqlcmd) StopCloseHandler()
- func (s *Sqlcmd) WriteError(stream io.Writer, err error)
- type SqlcmdError
- type SyntaxError
- type VariableError
- type Variables
- func (v Variables) All() map[string]string
- func (v Variables) ColorScheme() string
- func (v Variables) ColumnSeparator() string
- func (v Variables) ErrorLevel() int64
- func (v Variables) Format() string
- func (v Variables) Get(name string) (string, bool)
- func (v Variables) MaxFixedColumnWidth() int64
- func (v Variables) MaxVarColumnWidth() int64
- func (v Variables) QueryTimeoutSeconds() int64
- func (v Variables) RowsBetweenHeaders() int64
- func (v Variables) SQLCmdDatabase() string
- func (v Variables) SQLCmdServer() (serverName string, instance string, port uint64, protocol string, err error)
- func (v Variables) SQLCmdUser() string
- func (v Variables) ScreenWidth() int64
- func (v Variables) Set(name, value string)
- func (variables *Variables) Setvar(name, value string) error
- func (v Variables) StartupScriptFile() string
- func (v Variables) TextEditor() string
- func (v Variables) Unset(name string)
- func (v Variables) UseAad() bool
Constants ¶
const ( NotSpecified = "NotSpecified" SqlPassword = "SqlPassword" )
const ( SQLCMDDBNAME = "SQLCMDDBNAME" SQLCMDINI = "SQLCMDINI" SQLCMDPACKETSIZE = "SQLCMDPACKETSIZE" SQLCMDPASSWORD = "SQLCMDPASSWORD" SQLCMDSERVER = "SQLCMDSERVER" SQLCMDUSER = "SQLCMDUSER" SQLCMDWORKSTATION = "SQLCMDWORKSTATION" SQLCMDLOGINTIMEOUT = "SQLCMDLOGINTIMEOUT" SQLCMDSTATTIMEOUT = "SQLCMDSTATTIMEOUT" SQLCMDHEADERS = "SQLCMDHEADERS" SQLCMDCOLSEP = "SQLCMDCOLSEP" SQLCMDCOLWIDTH = "SQLCMDCOLWIDTH" SQLCMDERRORLEVEL = "SQLCMDERRORLEVEL" SQLCMDFORMAT = "SQLCMDFORMAT" SQLCMDMAXVARTYPEWIDTH = "SQLCMDMAXVARTYPEWIDTH" SQLCMDMAXFIXEDTYPEWIDTH = "SQLCMDMAXFIXEDTYPEWIDTH" SQLCMDEDITOR = "SQLCMDEDITOR" SQLCMDUSEAAD = "SQLCMDUSEAAD" SQLCMDCOLORSCHEME = "SQLCMDCOLORSCHEME" )
Built-in scripting variables
const SqlcmdEol = "\n"
SqlcmdEol is the end-of-line marker for sqlcmd output
Variables ¶
var ( // ErrExitRequested tells the hosting application to exit immediately ErrExitRequested = errors.New("exit") // ErrNeedPassword indicates the user should provide a password to enable the connection ErrNeedPassword = errors.New("need password") // ErrCtrlC indicates execution was ended by ctrl-c or ctrl-break ErrCtrlC = errors.New(WarningPrefix + "The last operation was terminated because the user pressed CTRL+C") // ErrCommandsDisabled indicates system commands and startup script are disabled ErrCommandsDisabled = &CommonSqlcmdErr{ message: ErrCmdDisabled, } )
var ErrCmdDisabled string = localizer.Sprintf("ED and !!<command> commands, startup script, and environment variables are disabled")
Common Sqlcmd error messages
var ErrorPrefix string = localizer.Sprintf("Sqlcmd: Error: ")
ErrorPrefix is the prefix for all sqlcmd-generated errors
var InvalidServerName = ArgumentError{
Parameter: "server",
Rule: "server must be of the form [[np]|[lpc][tcp]]:server[[/instance]|[,port]]",
}
InvalidServerName indicates the SQLCMDSERVER variable has an incorrect format
var WarningPrefix string = localizer.Sprintf("Sqlcmd: Warning: ")
WarningPrefix is the prefix for all sqlcmd-generated warnings
Functions ¶
func GetTokenBasedConnection ¶ added in v0.4.0
func InvalidFileError ¶
InvalidFileError indicates a file could not be opened
func ParseValue ¶ added in v0.1.0
ParseValue returns the string to use as the variable value If the string contains a space or a quote, it must be delimited by quotes and literal quotes within the value must be escaped by another quote "this has a quote "" in it" is valid "this has a quote" in it" is not valid
func ValidIdentifier ¶
ValidIdentifier determines if a given string can be used as a variable name
Types ¶
type ArgumentError ¶
ArgumentError is related to command line switch validation not handled by kong
func (*ArgumentError) Error ¶
func (e *ArgumentError) Error() string
func (*ArgumentError) IsSqlcmdErr ¶ added in v0.11.0
func (e *ArgumentError) IsSqlcmdErr() bool
type Batch ¶
type Batch struct { // Buffer is the current batch text Buffer []rune // Length is the length of the statement Length int // ParseVariables is a function that returns true if Next should parse variables ParseVariables batchParseVariables // contains filtered or unexported fields }
Batch provides the query text to run
func (*Batch) Next ¶
Next processes the next chunk of input and sets the Batch state accordingly. If the input contains a command to run, Next returns the Command and its parameters. Upon exit from Next, the caller can use the State method to determine if it represents a runnable SQL batch text.
type Command ¶
type Command struct {
// contains filtered or unexported fields
}
Command defines a sqlcmd action which can be intermixed with the SQL batch Commands for sqlcmd are defined at https://docs.microsoft.com/sql/tools/sqlcmd-utility#sqlcmd-commands
type CommandError ¶
CommandError indicates syntax errors for specific sqlcmd commands
func InvalidCommandError ¶
func InvalidCommandError(command string, lineNumber uint) *CommandError
InvalidCommandError creates a SQLCmdCommandError
func (*CommandError) Error ¶
func (e *CommandError) Error() string
func (*CommandError) IsSqlcmdErr ¶ added in v0.11.0
func (e *CommandError) IsSqlcmdErr() bool
type Commands ¶
Commands is the set of sqlcmd command implementations
func (Commands) DisableSysCommands ¶ added in v0.10.0
DisableSysCommands disables the ED and :!! commands. When exitOnCall is true, running those commands will exit the process.
func (Commands) SetBatchTerminator ¶ added in v0.1.0
SetBatchTerminator attempts to set the batch terminator to the given value Returns an error if the new value is not usable in the regex
type CommonSqlcmdErr ¶ added in v0.11.0
type CommonSqlcmdErr struct {
// contains filtered or unexported fields
}
func (*CommonSqlcmdErr) Error ¶ added in v0.11.0
func (e *CommonSqlcmdErr) Error() string
func (*CommonSqlcmdErr) IsSqlcmdErr ¶ added in v0.11.0
func (e *CommonSqlcmdErr) IsSqlcmdErr() bool
type ConnectSettings ¶
type ConnectSettings struct { // ServerName is the full name including instance and port ServerName string // UseTrustedConnection indicates integrated auth is used when no user name is provided UseTrustedConnection bool // TrustServerCertificate sets the TrustServerCertificate setting on the connection string TrustServerCertificate bool // AuthenticationMethod defines the authentication method for connecting to Azure SQL Database AuthenticationMethod string // DisableEnvironmentVariables determines if sqlcmd resolves scripting variables from the process environment DisableEnvironmentVariables bool // DisableVariableSubstitution determines if scripting variables should be evaluated DisableVariableSubstitution bool // UserName is the username for the SQL connection UserName string // Password is the password used with SQL authentication or AAD authentications that require a password Password string // Encrypt is the choice of encryption Encrypt string // PacketSize is the size of the packet for TDS communication PacketSize int // LoginTimeoutSeconds specifies the timeout for establishing a connection LoginTimeoutSeconds int // WorkstationName is the string to use to identify the host in server DMVs WorkstationName string // ApplicationIntent can only be empty or "ReadOnly" ApplicationIntent string // LogLevel is the mssql driver log level LogLevel int // ExitOnError specifies whether to exit the app on an error ExitOnError bool // ignore error IgnoreError bool // ErrorSeverityLevel sets the minimum SQL severity level to treat as an error ErrorSeverityLevel uint8 // Database is the name of the database for the connection Database string // ApplicationName is the name of the application to be included in the connection string ApplicationName string // DedicatedAdminConnection forces the connection to occur over tcp on the dedicated admin port. Requires Browser service access DedicatedAdminConnection bool // EnableColumnEncryption enables support for transparent column encryption EnableColumnEncryption bool // ChangePassword is the new password for the user to set during login ChangePassword string }
ConnectSettings specifies the settings for SQL connections and queries
func (ConnectSettings) ConnectionString ¶ added in v0.4.0
func (connect ConnectSettings) ConnectionString() (connectionString string, err error)
ConnectionString returns the go-mssql connection string to use for queries
func (ConnectSettings) RequiresPassword ¶ added in v0.10.0
func (connect ConnectSettings) RequiresPassword() bool
type Console ¶ added in v0.4.0
type Console interface { // Readline returns the next line of input. Readline() (string, error) // Readpassword displays the given prompt and returns a password ReadPassword(prompt string) ([]byte, error) // SetPrompt sets the prompt text shown to input the next line SetPrompt(s string) // Close clears any buffers and closes open file handles Close() }
Console defines methods used for console input and output
type ControlCharacterBehavior ¶
type ControlCharacterBehavior int
ControlCharacterBehavior specifies the text handling required for control characters in the output
const ( // ControlIgnore preserves control characters in the output ControlIgnore ControlCharacterBehavior = iota // ControlReplace replaces control characters with spaces, 1 space per character ControlReplace // ControlRemove removes control characters from the output ControlRemove // ControlReplaceConsecutive replaces multiple consecutive control characters with a single space ControlReplaceConsecutive )
type FileError ¶ added in v0.11.0
type FileError struct {
// contains filtered or unexported fields
}
func (*FileError) IsSqlcmdErr ¶ added in v0.11.0
type Formatter ¶
type Formatter interface { // BeginBatch is called before the query runs BeginBatch(query string, vars *Variables, out io.Writer, err io.Writer) // EndBatch is the last function called during batch execution and signals the end of the batch EndBatch() // BeginResultSet is called when a new result set is encountered BeginResultSet([]*sql.ColumnType) // EndResultSet is called after all rows in a result set have been processed EndResultSet() // AddRow is called for each row in a result set. It returns the value of the first column AddRow(*sql.Rows) string // AddMessage is called for every information message returned by the server during the batch AddMessage(string) // AddError is called for each error encountered during batch execution AddError(err error) // XmlMode enables or disables XML rendering mode XmlMode(enable bool) // IsXmlMode returns whether XML mode is enabled IsXmlMode() bool }
Formatter defines methods to process query output
func NewSQLCmdDefaultFormatter ¶
func NewSQLCmdDefaultFormatter(removeTrailingSpaces bool, ccb ControlCharacterBehavior) Formatter
NewSQLCmdDefaultFormatter returns a Formatter that mimics the original ODBC-based sqlcmd formatter
type Sqlcmd ¶
type Sqlcmd struct { // Exitcode is returned to the operating system when the process exits Exitcode int // Connect controls how Sqlcmd connects to the database Connect *ConnectSettings // Format renders the query output Format Formatter // Query is the TSQL query to run Query string // Cmd provides the implementation of commands like :list and GO Cmd Commands // PrintError allows the host to redirect errors away from the default output. Returns false if the error is not redirected by the host. PrintError func(msg string, severity uint8) bool // UnicodeOutputFile is true when UTF16 file output is needed UnicodeOutputFile bool // EchoInput tells the GO command to print the batch text before running the query EchoInput bool // contains filtered or unexported fields }
Sqlcmd is the core processor for text lines.
It accumulates non-command lines in a buffer and sends command lines to the appropriate command runner. When the batch delimiter is encountered it sends the current batch to the active connection and prints the results to the output writer
func New ¶
New creates a new Sqlcmd instance. The Console instane must be non-nil for Sqlcmd to run in interactive mode. The hosting application is responsible for calling Close() on the Console instance before process exit.
func (*Sqlcmd) ConnectDb ¶
func (s *Sqlcmd) ConnectDb(connect *ConnectSettings, nopw bool) error
ConnectDb opens a connection to the database with the given modifications to the connection nopw == true means don't prompt for a password if the auth type requires it if connect is nil, ConnectDb uses the current connection. If non-nil and the connection succeeds, s.Connect is replaced with the new value.
func (*Sqlcmd) IncludeFile ¶ added in v0.1.0
IncludeFile opens the given file and processes its batches. When processAll is true, text not followed by a go statement is run as a query
func (Sqlcmd) Log ¶ added in v0.4.0
Log attempts to write driver traces to the current output. It ignores errors
func (*Sqlcmd) Run ¶
Run processes all available batches. When once is true it stops after the first query runs. When processAll is true it executes any remaining batch content when reaching EOF The error returned from Run is mainly of informational value. Its Message will have been printed before Run returns.
func (*Sqlcmd) RunCommand ¶
RunCommand performs the given Command
func (*Sqlcmd) SetError ¶
func (s *Sqlcmd) SetError(e io.WriteCloser)
SetError sets the io.WriteCloser to use for errors
func (*Sqlcmd) SetOutput ¶
func (s *Sqlcmd) SetOutput(o io.WriteCloser)
SetOutput sets the io.WriteCloser to use for non-error output
func (*Sqlcmd) SetupCloseHandler ¶ added in v1.0.0
func (s *Sqlcmd) SetupCloseHandler()
SetupCloseHandler subscribes to the os.Signal channel for SIGTERM. When it receives the event due to the user pressing ctrl-c or ctrl-break that isn't handled directly by the Console or hosting application, it will call Close() on the Console and exit the application. Use StopCloseHandler to remove the subscription
func (*Sqlcmd) StopCloseHandler ¶ added in v1.0.0
func (s *Sqlcmd) StopCloseHandler()
StopCloseHandler unsubscribes the Sqlcmd from the SIGTERM signal
type SqlcmdError ¶ added in v0.11.0
type SyntaxError ¶ added in v0.11.0
type SyntaxError struct {
// contains filtered or unexported fields
}
func (*SyntaxError) Error ¶ added in v0.11.0
func (e *SyntaxError) Error() string
func (*SyntaxError) IsSqlcmdErr ¶ added in v0.11.0
func (e *SyntaxError) IsSqlcmdErr() bool
type VariableError ¶
VariableError is an error about scripting variables
func InvalidVariableValue ¶ added in v0.10.0
func InvalidVariableValue(variable string, value string) *VariableError
InvalidVariableValue indicates the variable was set to an invalid value
func ReadOnlyVariable ¶
func ReadOnlyVariable(variable string) *VariableError
ReadOnlyVariable indicates the user tried to set a value to a read-only variable
func UndefinedVariable ¶ added in v0.1.0
func UndefinedVariable(variable string) *VariableError
UndefinedVariable indicates the user tried to reference an undefined variable
func (*VariableError) Error ¶
func (e *VariableError) Error() string
func (*VariableError) IsSqlcmdErr ¶ added in v0.11.0
func (e *VariableError) IsSqlcmdErr() bool
type Variables ¶
Variables provides set and get of sqlcmd scripting variables
func InitializeVariables ¶
InitializeVariables initializes variables with default values. When fromEnvironment is true, then loads from the runtime environment
func (Variables) ColorScheme ¶ added in v0.15.3
ColorScheme is the name of the console output color scheme
func (Variables) ColumnSeparator ¶
ColumnSeparator is the value of SQLCMDCOLSEP variable. It can have 0 or 1 characters
func (Variables) ErrorLevel ¶ added in v0.4.0
ErrorLevel controls the minimum level of errors that are printed
func (Variables) Get ¶ added in v0.1.0
Get returns the value of the named variable To distinguish an empty value from an unset value use the bool return value
func (Variables) MaxFixedColumnWidth ¶
MaxFixedColumnWidth is the value of SQLCMDMAXFIXEDTYPEWIDTH variable. When non-zero, it limits the width of columns for types CHAR, NCHAR, NVARCHAR, VARCHAR, VARBINARY, VARIANT
func (Variables) MaxVarColumnWidth ¶
MaxVarColumnWidth is the value of SQLCMDMAXVARTYPEWIDTH variable. When non-zero, it limits the width of columns for (max) versions of CHAR, NCHAR, VARBINARY. It also limits the width of xml, UDT, text, ntext, and image
func (Variables) QueryTimeoutSeconds ¶ added in v1.4.0
QueryTimeoutSeconds limits the allowed time for a query to complete. Any value <= 0 specifies unlimited
func (Variables) RowsBetweenHeaders ¶
RowsBetweenHeaders is the value of SQLCMDHEADERS variable. When MaxVarColumnWidth() is 0, it returns -1
func (Variables) SQLCmdDatabase ¶
SQLCmdDatabase returns the SQLCMDDBNAME variable value
func (Variables) SQLCmdServer ¶
func (v Variables) SQLCmdServer() (serverName string, instance string, port uint64, protocol string, err error)
SQLCmdServer returns the server connection parameters derived from the SQLCMDSERVER variable value
func (Variables) SQLCmdUser ¶
SQLCmdUser returns the SQLCMDUSER variable value
func (Variables) ScreenWidth ¶
ScreenWidth is the value of SQLCMDCOLWIDTH variable. It tells the formatter how many characters wide to limit all screen output.
func (*Variables) Setvar ¶ added in v0.1.0
Setvar implements the :Setvar command TODO: Add validation functions for the variables.
func (Variables) StartupScriptFile ¶ added in v0.10.0
StartupScriptFile is the path to the file that contains the startup script
func (Variables) TextEditor ¶ added in v0.10.0
TextEditor is the query editor application launched by the :ED command