Documentation ¶
Index ¶
- Constants
- Variables
- func GetTokenBasedConnection(connstr string, authenticationMethod string) (driver.Connector, error)
- func InvalidFileError(err error, path string) error
- func ParseValue(val string) (string, error)
- func ValidIdentifier(name string) error
- type ArgumentError
- type Batch
- type Command
- type CommandError
- type Commands
- type ConnectSettings
- type Console
- type ControlCharacterBehavior
- 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)
- type VariableError
- type Variables
- func (v Variables) All() map[string]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) RowsBetweenHeaders() int64
- func (v Variables) SQLCmdDatabase() string
- func (v Variables) SQLCmdServer() (serverName string, instance string, port uint64, 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) 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" )
Built-in scripting variables
const ErrorPrefix = "Sqlcmd: Error: "
ErrorPrefix is the prefix for all sqlcmd-generated errors
const SqlcmdEol = "\n"
SqlcmdEol is the end-of-line marker for sqlcmd output
const WarningPrefix = "Sqlcmd: Warning: "
WarningPrefix is the prefix for all sqlcmd-generated warnings
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") )
var InvalidServerName = ArgumentError{
Parameter: "server",
Rule: "server must be of the form [tcp]:server[[/instance]|[,port]]",
}
InvalidServerName indicates the SQLCMDSERVER variable has an incorrect format
Functions ¶
func GetTokenBasedConnection ¶
func InvalidFileError ¶
InvalidFileError indicates a file could not be opened
func ParseValue ¶
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
type Batch ¶
type Batch struct { // Buffer is the current batch text Buffer []rune // Length is the length of the statement Length int // 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
type Commands ¶
Commands is the set of sqlcmd command implementations
func (Commands) SetBatchTerminator ¶
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 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 // 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 }
ConnectSettings specifies the settings for connections
func (ConnectSettings) ConnectionString ¶
func (connect ConnectSettings) ConnectionString() (connectionString string, err error)
ConnectionString returns the go-mssql connection string to use for queries
type Console ¶
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 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) }
Formatter defines methods to process query output
func NewSQLCmdDefaultFormatter ¶
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 ConnectSettings Format Formatter Query string 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 bool // contains filtered or unexported fields }
Sqlcmd is the core processor for text lines.
It accumulates non-command lines in a buffer and 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 (*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 ¶
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) 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
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
type VariableError ¶
VariableError is an error about scripting variables
func ReadOnlyVariable ¶
func ReadOnlyVariable(variable string) *VariableError
ReadOnlyVariable indicates the user tried to set a value to a read-only variable
func UndefinedVariable ¶
func UndefinedVariable(variable string) *VariableError
UndefinedVariable indicates the user tried to reference an undefined variable
func (*VariableError) Error ¶
func (e *VariableError) Error() string
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) ColumnSeparator ¶
ColumnSeparator is the value of SQLCMDCOLSEP variable. It can have 0 or 1 characters
func (Variables) ErrorLevel ¶
ErrorLevel controls the minimum level of errors that are printed
func (Variables) Get ¶
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) 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 ¶
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.