sqlcmd

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2021 License: MIT Imports: 16 Imported by: 2

Documentation

Index

Constants

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"
	SQLCMDMAXVARTYPEWIDTH   = "SQLCMDMAXVARTYPEWIDTH"
	SQLCMDMAXFIXEDTYPEWIDTH = "SQLCMDMAXFIXEDTYPEWIDTH"
	SQLCMDEDITOR            = "SQLCMDEDITOR"
	SQLCMDUSEAAD            = "SQLCMDUSEAAD"
)

Built-in scripting variables

View Source
const ErrorPrefix = "Sqlcmd: Error: "

ErrorPrefix is the prefix for all sqlcmd-generated errors

View Source
const SqlcmdEol = "\n"

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

View Source
const WarningPrefix = "Sqlcmd: Warning: "

WarningPrefix is the prefix for all sqlcmd-generated warnings

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")
)
View Source
var Commands = map[string]*Command{
	"QUIT": {
		// contains filtered or unexported fields
	},
	"GO": {
		// contains filtered or unexported fields
	},
	"OUT": {
		// contains filtered or unexported fields
	},
	"ERROR": {
		// contains filtered or unexported fields
	},
}

Commands is the set of Command implementations

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

func InvalidFileError(err error, path string) error

InvalidFileError indicates a file could not be opened

func SetBatchTerminator

func 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

func Setvar

func Setvar(name, value string) error

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

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

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 func() ([]rune, error)) *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

type ConnectSettings

type ConnectSettings struct {
	UseTrustedConnection   bool
	TrustServerCertificate bool
}

ConnectSettings are the settings for connections that can't be inferred from scripting variables

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
	AddRow(*sql.Rows)
	// 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

func NewSQLCmdDefaultFormatter(removeTrailingSpaces bool) 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  ConnectSettings

	Format Formatter
	Query  string
	// 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 New

func New(l rline.IO, workingDirectory string, vars *Variables) *Sqlcmd

New creates a new Sqlcmd instance

func (*Sqlcmd) ConnectDb

func (s *Sqlcmd) ConnectDb(server string, user string, password string, nopw bool) error

ConnectDb opens a connection to the database with the given modifications to the connection

func (*Sqlcmd) ConnectionString

func (s *Sqlcmd) ConnectionString() (connectionString string, err error)

ConnectionString returns the go-mssql connection string to use for queries

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

func (s *Sqlcmd) Prompt() string

Prompt returns the current user prompt message

func (*Sqlcmd) Run

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

Run processes all available batches. When once is true it stops after the first query runs.

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

type VariableError

type VariableError struct {
	Variable      string
	MessageFormat string
}

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 (*VariableError) Error

func (e *VariableError) Error() string

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

func (v Variables) ColumnSeparator() string

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

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

func (v Variables) Password() string

Password returns the password used for connections as specified by SQLCMDPASSWORD variable

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