mssql

package module
v0.0.0-...-242fa5a Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2018 License: BSD-3-Clause Imports: 33 Imported by: 0

README

A pure Go MSSQL driver for Go's database/sql package

GoDoc Build status codecov

Install

Requires Go 1.8 or above.

Install with go get github.com/denisenkom/go-mssqldb .

Connection Parameters and DSN

The recommended connection string uses a URL format: sqlserver://username:password@host/instance?param1=value&param2=value Other supported formats are listed below.

Common parameters:
  • user id - enter the SQL Server Authentication user id or the Windows Authentication user id in the DOMAIN\User format. On Windows, if user id is empty or missing Single-Sign-On is used.
  • password
  • database
  • connection timeout - in seconds (default is 0 for no timeout), set to 0 for no timeout. Recommended to set to 0 and use context to manage query and connection timeouts.
  • dial timeout - in seconds (default is 15), set to 0 for no timeout
  • encrypt
    • disable - Data send between client and server is not encrypted.
    • false - Data sent between client and server is not encrypted beyond the login packet. (Default)
    • true - Data sent between client and server is encrypted.
  • app name - The application name (default is go-mssqldb)
Connection parameters for ODBC and ADO style connection strings:
  • server - host or host\instance (default localhost)
  • port - used only when there is no instance in server (default 1433)
Less common parameters:
  • keepAlive - in seconds; 0 to disable (default is 30)
  • failoverpartner - host or host\instance (default is no partner).
  • failoverport - used only when there is no instance in failoverpartner (default 1433)
  • packet size - in bytes; 512 to 32767 (default is 4096)
  • log - logging flags (default 0/no logging, 63 for full logging)
    • 1 log errors
    • 2 log messages
    • 4 log rows affected
    • 8 trace sql statements
    • 16 log statement parameters
    • 32 log transaction begin/end
  • TrustServerCertificate
    • false - Server certificate is checked. Default is false if encypt is specified.
    • true - Server certificate is not checked. Default is true if encrypt is not specified. If trust server certificate is true, driver accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to man-in-the-middle attacks. This should be used only for testing.
  • certificate - The file that contains the public key certificate of the CA that signed the SQL Server certificate. The specified certificate overrides the go platform specific CA certificates.
  • hostNameInCertificate - Specifies the Common Name (CN) in the server certificate. Default value is the server host.
  • ServerSPN - The kerberos SPN (Service Principal Name) for the server. Default is MSSQLSvc/host:port.
  • Workstation ID - The workstation name (default is the host name)
  • ApplicationIntent - Can be given the value ReadOnly to initiate a read-only connection to an Availability Group listener.
The connection string can be specified in one of three formats:
  1. URL: with sqlserver scheme. username and password appears before the host. Any instance appears as the first segment in the path. All other options are query parameters. Examples:
  • sqlserver://username:password@host/instance?param1=value&param2=value
  • sqlserver://username:password@host:port?param1=value&param2=value
  • sqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30 // `SQLExpress instance.
  • sqlserver://sa:mypass@localhost?database=master&connection+timeout=30 // username=sa, password=mypass.
  • sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30 // port 1234 on localhost.
  • sqlserver://sa:my%7Bpass@somehost?connection+timeout=30 // password is "my{pass"

A string of this format can be constructed using the URL type in the net/url package.

  query := url.Values{}
  query.Add("app name", "MyAppName")

  u := &url.URL{
      Scheme:   "sqlserver",
      User:     url.UserPassword(username, password),
      Host:     fmt.Sprintf("%s:%d", hostname, port),
      // Path:  instance, // if connecting to an instance instead of a port
      RawQuery: query.Encode(),
  }
  db, err := sql.Open("sqlserver", u.String())
  1. ADO: key=value pairs separated by ;. Values may not contain ;, leading and trailing whitespace is ignored. Examples:
  • server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName
  • server=localhost;user id=sa;database=master;app name=MyAppName
  1. ODBC: Prefix with odbc, key=value pairs separated by ;. Allow ; by wrapping values in {}. Examples:
  • odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName
  • odbc:server=localhost;user id=sa;database=master;app name=MyAppName
  • odbc:server=localhost;user id=sa;password={foo;bar} // Value marked with {}, password is "foo;bar"
  • odbc:server=localhost;user id=sa;password={foo{bar} // Value marked with {}, password is "foo{bar"
  • odbc:server=localhost;user id=sa;password={foobar } // Value marked with {}, password is "foobar "
  • odbc:server=localhost;user id=sa;password=foo{bar // Literal {, password is "foo{bar"
  • odbc:server=localhost;user id=sa;password=foo}bar // Literal }, password is "foo}bar"
  • odbc:server=localhost;user id=sa;password={foo{bar} // Literal {, password is "foo{bar"
  • odbc:server=localhost;user id=sa;password={foo}}bar} // Escaped } with }}`, password is "foo}bar"

Executing Stored Procedures

To run a stored procedure, set the query text to the procedure name:

var account = "abc"
_, err := db.ExecContext(ctx, "sp_RunMe",
	sql.Named("ID", 123),
	sql.Named("Account", sql.Out{Dest: &account}),
)

Parameters

The sqlserver driver uses normal MS SQL Server syntax and expects parameters in the sql query to be in the form of either @Name or @p1 to @pN (ordinal position).

db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob")
Parameter Types

To pass specific types to the query parameters, say varchar or date types, you must convert the types to the type before passing in. The following types are supported:

  • string -> nvarchar
  • mssql.VarChar -> varchar
  • time.Time -> datetimeoffset or datetime (TDS version dependent)
  • mssql.DateTime1 -> datetime
  • mssql.DateTimeOffset -> datetimeoffset
  • "cloud.google.com/go/civil".Date -> date
  • "cloud.google.com/go/civil".DateTime -> datetime2
  • "cloud.google.com/go/civil".Time -> time

Important Notes

  • LastInsertId should not be used with this driver (or SQL Server) due to how the TDS protocol works. Please use the OUTPUT Clause or add a select ID = convert(bigint, SCOPE_IDENTITY()); to the end of your query (ref SCOPE_IDENTITY). This will ensure you are getting the correct ID and will prevent a network round trip.
  • NewConnector may be used with OpenDB.
  • Connector.SessionInitSQL may be set to set any driver specific session settings after the session has been reset. If empty the session will still be reset but use the database defaults in Go1.10+.

Features

  • Can be used with SQL Server 2005 or newer
  • Can be used with Microsoft Azure SQL Database
  • Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows)
  • Supports new date/time types: date, time, datetime2, datetimeoffset
  • Supports string parameters longer than 8000 characters
  • Supports encryption using SSL/TLS
  • Supports SQL Server and Windows Authentication
  • Supports Single-Sign-On on Windows
  • Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas.
  • Supports query notifications

Tests

go test is used for testing. A running instance of MSSQL server is required. Environment variables are used to pass login information.

Example:

env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test

Deprecated

These features still exist in the driver, but they are are deprecated.

Query Parameter Token Replace (driver "mssql")

If you use the driver name "mssql" (rather then "sqlserver") the SQL text will be loosly parsed and an attempt to extract identifiers using one of

  • ?
  • ?nnn
  • :nnn
  • $nnn

will be used. This is not recommended with SQL Server. There is at least one existing won't fix issue with the query parsing.

Use the native "@Name" parameters instead with the "sqlserver" driver name.

Known Issues

  • SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled. To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2. To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3. More information: http://support.microsoft.com/kb/2653857

Documentation

Overview

package mssql implements the TDS protocol used to connect to MS SQL Server (sqlserver) database servers.

This package registers the driver:

sqlserver: uses native "@" parameter placeholder names and does no pre-processing.

If the ordinal position is used for query parameters, identifiers will be named "@p1", "@p2", ... "@pN".

Please refer to the README for the format of the DSN. There are multiple DSN formats accepted: ADO style, ODBC style, and URL style. The following is an example of a URL style DSN:

sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CopyIn

func CopyIn(table string, options BulkOptions, columns ...string) string

func SetLogger

func SetLogger(logger Logger)

Types

type Bulk

type Bulk struct {
	Options BulkOptions
	Debug   bool
	// contains filtered or unexported fields
}

func (*Bulk) AddRow

func (b *Bulk) AddRow(row []interface{}) (err error)

AddRow immediately writes the row to the destination table. The arguments are the row values in the order they were specified.

func (*Bulk) Done

func (b *Bulk) Done() (rowcount int64, err error)

type BulkOptions

type BulkOptions struct {
	CheckConstraints  bool
	FireTriggers      bool
	KeepNulls         bool
	KilobytesPerBatch int
	RowsPerBatch      int
	Order             []string
	Tablock           bool
}

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

func (*Conn) Begin

func (c *Conn) Begin() (driver.Tx, error)

func (*Conn) BeginTx

func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)

BeginTx satisfies ConnBeginTx.

func (*Conn) CheckNamedValue

func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error

func (*Conn) Close

func (c *Conn) Close() error

func (*Conn) Commit

func (c *Conn) Commit() error

func (*Conn) CreateBulk

func (cn *Conn) CreateBulk(table string, columns []string) (_ *Bulk)

func (*Conn) CreateBulkContext

func (cn *Conn) CreateBulkContext(ctx context.Context, table string, columns []string) (_ *Bulk)

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context) error

Ping is used to check if the remote server is available and satisfies the Pinger interface.

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (driver.Stmt, error)

func (*Conn) PrepareContext

func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)

func (*Conn) ResetSession

func (c *Conn) ResetSession(ctx context.Context) error

func (*Conn) Rollback

func (c *Conn) Rollback() error

type Connector

type Connector struct {

	// SessionInitSQL is executed after marking a given session to be reset.
	// When not present, the next query will still reset the session to the
	// database defaults.
	//
	// When present the connection will immediately mark the session to
	// be reset, then execute the SessionInitSQL text to setup the session
	// that may be different from the base database defaults.
	//
	// For Example, the application relies on the following defaults
	// but is not allowed to set them at the database system level.
	//
	//    SET XACT_ABORT ON;
	//    SET TEXTSIZE -1;
	//    SET ANSI_NULLS ON;
	//    SET LOCK_TIMEOUT 10000;
	//
	// SessionInitSQL should not attempt to manually call sp_reset_connection.
	// This will happen at the TDS layer.
	//
	// SessionInitSQL is optional. The session will be reset even if
	// SessionInitSQL is empty.
	SessionInitSQL string
	// contains filtered or unexported fields
}

Connector holds the parsed DSN and is ready to make a new connection at any time.

In the future, settings that cannot be passed through a string DSN may be set directly on the connector.

func NewConnector

func NewConnector(dsn string) (*Connector, error)

NewConnector creates a new connector from a DSN. The returned connector may be used with sql.OpenDB.

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context) (driver.Conn, error)

Connect to the server and return a TDS connection.

func (*Connector) Driver

func (c *Connector) Driver() driver.Driver

Driver underlying the Connector.

type DataValue

type DataValue interface{}

type DateTime1

type DateTime1 time.Time

DateTime1 encodes parameters to original DateTime SQL types.

type DateTimeOffset

type DateTimeOffset time.Time

DateTimeOffset encodes parameters to DateTimeOffset, preserving the UTC offset.

type Decimal

type Decimal struct {
	// contains filtered or unexported fields
}

http://msdn.microsoft.com/en-us/library/ee780893.aspx

func Float64ToDecimal

func Float64ToDecimal(f float64) (Decimal, error)

func Float64ToDecimalScale

func Float64ToDecimalScale(f float64, scale uint8) (Decimal, error)

func (Decimal) BigInt

func (d Decimal) BigInt() big.Int

func (Decimal) Bytes

func (d Decimal) Bytes() []byte

func (Decimal) String

func (d Decimal) String() string

func (Decimal) ToFloat64

func (d Decimal) ToFloat64() float64

func (Decimal) UnscaledBytes

func (d Decimal) UnscaledBytes() []byte

type Driver

type Driver struct {
	// contains filtered or unexported fields
}

func (*Driver) Open

func (d *Driver) Open(dsn string) (driver.Conn, error)

func (*Driver) OpenConnection

func (d *Driver) OpenConnection(dsn string) (*Conn, error)

func (*Driver) OpenConnector

func (d *Driver) OpenConnector(dsn string) (*Connector, error)

OpenConnector opens a new connector. Useful to dial with a context.

func (*Driver) SetLogger

func (d *Driver) SetLogger(logger Logger)

type Error

type Error struct {
	Number     int32
	State      uint8
	Class      uint8
	Message    string
	ServerName string
	ProcName   string
	LineNo     int32
}

Error represents an SQL Server error. This type includes methods for reading the contents of the struct, which allows calling programs to check for specific error conditions without having to import this package directly.

func (Error) Error

func (e Error) Error() string

func (Error) SQLErrorClass

func (e Error) SQLErrorClass() uint8

func (Error) SQLErrorLineNo

func (e Error) SQLErrorLineNo() int32

func (Error) SQLErrorMessage

func (e Error) SQLErrorMessage() string

func (Error) SQLErrorNumber

func (e Error) SQLErrorNumber() int32

SQLErrorNumber returns the SQL Server error number.

func (Error) SQLErrorProcName

func (e Error) SQLErrorProcName() string

func (Error) SQLErrorServerName

func (e Error) SQLErrorServerName() string

func (Error) SQLErrorState

func (e Error) SQLErrorState() uint8

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
	Println(v ...interface{})
}

type MssqlBulk

type MssqlBulk = Bulk // Deprecated: users should transition to the new name when possible.

type MssqlBulkOptions

type MssqlBulkOptions = BulkOptions // Deprecated: users should transition to the new name when possible.

type MssqlConn

type MssqlConn = Conn // Deprecated: users should transition to the new name when possible.

type MssqlDriver

type MssqlDriver = Driver // Deprecated: users should transition to the new name when possible.

type MssqlResult

type MssqlResult = Result // Deprecated: users should transition to the new name when possible.

type MssqlRows

type MssqlRows = Rows // Deprecated: users should transition to the new name when possible.

type MssqlStmt

type MssqlStmt = Stmt // Deprecated: users should transition to the new name when possible.

type NVarCharMax

type NVarCharMax string

type Result

type Result struct {
	// contains filtered or unexported fields
}

func (*Result) LastInsertId

func (r *Result) LastInsertId() (int64, error)

func (*Result) RowsAffected

func (r *Result) RowsAffected() (int64, error)

type Rows

type Rows struct {
	// contains filtered or unexported fields
}

func (*Rows) Close

func (rc *Rows) Close() error

func (*Rows) ColumnTypeDatabaseTypeName

func (r *Rows) ColumnTypeDatabaseTypeName(index int) string

RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the database system type name without the length. Type names should be uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", "TIMESTAMP".

func (*Rows) ColumnTypeLength

func (r *Rows) ColumnTypeLength(index int) (int64, bool)

RowsColumnTypeLength may be implemented by Rows. It should return the length of the column type if the column is a variable length type. If the column is not a variable length type ok should return false. If length is not limited other than system limits, it should return math.MaxInt64. The following are examples of returned values for various types:

TEXT          (math.MaxInt64, true)
varchar(10)   (10, true)
nvarchar(10)  (10, true)
decimal       (0, false)
int           (0, false)
bytea(30)     (30, true)

func (*Rows) ColumnTypeNullable

func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool)

The nullable value should be true if it is known the column may be null, or false if the column is known to be not nullable. If the column nullability is unknown, ok should be false.

func (*Rows) ColumnTypePrecisionScale

func (r *Rows) ColumnTypePrecisionScale(index int) (int64, int64, bool)

It should return the precision and scale for decimal types. If not applicable, ok should be false. The following are examples of returned values for various types:

decimal(38, 4)    (38, 4, true)
int               (0, 0, false)
decimal           (math.MaxInt64, math.MaxInt64, true)

func (*Rows) ColumnTypeScanType

func (r *Rows) ColumnTypeScanType(index int) reflect.Type

It should return the value type that can be used to scan types into. For example, the database column type "bigint" this should return "reflect.TypeOf(int64(0))".

func (*Rows) Columns

func (rc *Rows) Columns() (res []string)

func (*Rows) HasNextResultSet

func (rc *Rows) HasNextResultSet() bool

func (*Rows) Next

func (rc *Rows) Next(dest []driver.Value) error

func (*Rows) NextResultSet

func (rc *Rows) NextResultSet() error

type Stmt

type Stmt struct {
	// contains filtered or unexported fields
}

func (*Stmt) Close

func (s *Stmt) Close() error

func (*Stmt) Exec

func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)

func (*Stmt) ExecContext

func (s *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)

func (*Stmt) NumInput

func (s *Stmt) NumInput() int

func (*Stmt) Query

func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)

func (*Stmt) QueryContext

func (s *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)

func (*Stmt) SetQueryNotification

func (s *Stmt) SetQueryNotification(id, options string, timeout time.Duration)

type StreamError

type StreamError struct {
	Message string
}

func (StreamError) Error

func (e StreamError) Error() string

type UniqueIdentifier

type UniqueIdentifier [16]byte

func (*UniqueIdentifier) Scan

func (u *UniqueIdentifier) Scan(v interface{}) error

func (UniqueIdentifier) String

func (u UniqueIdentifier) String() string

func (UniqueIdentifier) Value

func (u UniqueIdentifier) Value() (driver.Value, error)

type VarChar

type VarChar string

VarChar parameter types.

type VarCharMax

type VarCharMax string

Directories

Path Synopsis
bach splits a single script containing multiple batches separated by a keyword into multiple scripts.
bach splits a single script containing multiple batches separated by a keyword into multiple scripts.
examples
internal
cp

Jump to

Keyboard shortcuts

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