sqlcmd

package
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 5, 2024 License: MIT Imports: 31 Imported by: 2

Documentation

Index

Constants

View Source
const (
	NotSpecified = "NotSpecified"
	SqlPassword  = "SqlPassword"
)
View Source
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

View Source
const SqlcmdEol = "\n"

SqlcmdEol is the end-of-line marker for sqlcmd output

Variables

View Source
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,
	}
)
View Source
var ErrCmdDisabled string = localizer.Sprintf("ED and !!<command> commands, startup script, and environment variables are disabled")

Common Sqlcmd error messages

View Source
var ErrorPrefix string = localizer.Sprintf("Sqlcmd: Error: ")

ErrorPrefix is the prefix for all sqlcmd-generated errors

View Source
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

View Source
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 GetTokenBasedConnection(connstr string, authenticationMethod string) (driver.Connector, error)

func InvalidFileError

func InvalidFileError(err error, filepath string) error

InvalidFileError indicates a file could not be opened

func ParseValue added in v0.1.0

func ParseValue(val string) (string, error)

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

func ValidIdentifier(name string) error

ValidIdentifier determines if a given string can be used as a variable name

Types

type ArgumentError

type ArgumentError struct {
	Parameter string
	Rule      string
}

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
	// contains filtered or unexported fields
}

Batch provides the query text to run

func NewBatch

func NewBatch(reader batchScan, cmd Commands) *Batch

NewBatch creates a Batch which converts runes provided by reader into SQL batches

func (*Batch) Next

func (b *Batch) Next() (*Command, []string, error)

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.

func (*Batch) Reset

func (b *Batch) Reset(r []rune)

Reset clears the current batch text and replaces it with new runes

func (*Batch) State

func (b *Batch) State() string

State returns a string representing the state of statement parsing. * Is in the middle of a multi-line comment - Has a non-empty batch ready to run = Is empty ' " Is in the middle of a multi-line quoted string

func (*Batch) String

func (b *Batch) String() string

String returns the current 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

type CommandError struct {
	Command    string
	LineNumber uint
}

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

type Commands map[string]*Command

Commands is the set of sqlcmd command implementations

func (Commands) DisableSysCommands added in v0.10.0

func (c Commands) DisableSysCommands(exitOnCall bool)

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

func (c Commands) SetBatchTerminator(terminator string) error

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) Error added in v0.11.0

func (e *FileError) Error() string

func (*FileError) IsSqlcmdErr added in v0.11.0

func (e *FileError) IsSqlcmdErr() bool

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

func New(l Console, workingDirectory string, vars *Variables) *Sqlcmd

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) GetError

func (s *Sqlcmd) GetError() io.Writer

GetError returns the io.Writer to use for errors

func (*Sqlcmd) GetOutput

func (s *Sqlcmd) GetOutput() io.Writer

GetOutput returns the io.Writer to use for non-error output

func (*Sqlcmd) IncludeFile added in v0.1.0

func (s *Sqlcmd) IncludeFile(path string, processAll bool) error

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

func (s Sqlcmd) Log(_ context.Context, _ msdsn.Log, msg string)

Log attempts to write driver traces to the current output. It ignores errors

func (*Sqlcmd) Prompt

func (s *Sqlcmd) Prompt() string

Prompt returns the current user prompt message

func (*Sqlcmd) Run

func (s *Sqlcmd) Run(once bool, processAll bool) error

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

func (s *Sqlcmd) RunCommand(cmd *Command, args []string) error

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

func (*Sqlcmd) WriteError added in v0.10.0

func (s *Sqlcmd) WriteError(stream io.Writer, err error)

WriteError writes the error on specified stream

type SqlcmdError added in v0.11.0

type SqlcmdError interface {
	error
	IsSqlcmdErr() bool
}

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

type VariableError struct {
	Variable      string
	MessageFormat string
}

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

type Variables map[string]string

Variables provides set and get of sqlcmd scripting variables

func InitializeVariables

func InitializeVariables(fromEnvironment bool) *Variables

InitializeVariables initializes variables with default values. When fromEnvironment is true, then loads from the runtime environment

func (Variables) All

func (v Variables) All() map[string]string

All returns a copy of the current variables

func (Variables) ColorScheme added in v0.15.3

func (v Variables) ColorScheme() string

ColorScheme is the name of the console output color scheme

func (Variables) ColumnSeparator

func (v Variables) ColumnSeparator() string

ColumnSeparator is the value of SQLCMDCOLSEP variable. It can have 0 or 1 characters

func (Variables) ErrorLevel added in v0.4.0

func (v Variables) ErrorLevel() int64

ErrorLevel controls the minimum level of errors that are printed

func (Variables) Format added in v0.5.0

func (v Variables) Format() string

Format is the name of the results format

func (Variables) Get added in v0.1.0

func (v Variables) Get(name string) (string, bool)

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

func (v Variables) MaxFixedColumnWidth() int64

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

func (v Variables) MaxVarColumnWidth() int64

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

func (v Variables) QueryTimeoutSeconds() int64

QueryTimeoutSeconds limits the allowed time for a query to complete. Any value <= 0 specifies unlimited

func (Variables) RowsBetweenHeaders

func (v Variables) RowsBetweenHeaders() int64

RowsBetweenHeaders is the value of SQLCMDHEADERS variable. When MaxVarColumnWidth() is 0, it returns -1

func (Variables) SQLCmdDatabase

func (v Variables) SQLCmdDatabase() string

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

func (v Variables) SQLCmdUser() string

SQLCmdUser returns the SQLCMDUSER variable value

func (Variables) ScreenWidth

func (v Variables) ScreenWidth() int64

ScreenWidth is the value of SQLCMDCOLWIDTH variable. It tells the formatter how many characters wide to limit all screen output.

func (Variables) Set

func (v Variables) Set(name, value string)

Set sets or adds the value in the map.

func (*Variables) Setvar added in v0.1.0

func (variables *Variables) Setvar(name, value string) error

Setvar implements the :Setvar command TODO: Add validation functions for the variables.

func (Variables) StartupScriptFile added in v0.10.0

func (v Variables) StartupScriptFile() string

StartupScriptFile is the path to the file that contains the startup script

func (Variables) TextEditor added in v0.10.0

func (v Variables) TextEditor() string

TextEditor is the query editor application launched by the :ED command

func (Variables) Unset

func (v Variables) Unset(name string)

Unset removes the value from the map

func (Variables) UseAad

func (v Variables) UseAad() bool

UseAad returns whether the SQLCMDUSEAAD variable value is set to "true"

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL