mssql

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2023 License: BSD-3-Clause Imports: 34 Imported by: 0

README

ondrejsika/fork-go-mssqldb-32bit-for-slu

!! Fork of microsoft/go-mssqldb with reverted 32bit support !!

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

Examples

Constants

View Source
const (
	// FedAuthLibraryLiveIDCompactToken specifies the Microsoft Live ID Compact Token authentication scheme
	FedAuthLibraryLiveIDCompactToken = 0x00

	// FedAuthLibrarySecurityToken specifies a token-based authentication where the token is available
	// without additional information provided during the login sequence.
	FedAuthLibrarySecurityToken = 0x01

	// FedAuthLibraryADAL specifies a token-based authentication where a token is obtained during the
	// login sequence using the server SPN and STS URL provided by the server during login.
	FedAuthLibraryADAL = 0x02

	// FedAuthLibraryReserved is used to indicate that no federated authentication scheme applies.
	FedAuthLibraryReserved = 0x7F
)

Federated authentication library affects the login data structure and message sequence.

View Source
const (
	// FedAuthADALWorkflowPassword uses a username/password to obtain a token from Active Directory
	FedAuthADALWorkflowPassword = 0x01

	// fedAuthADALWorkflowPassword uses the Windows identity to obtain a token from Active Directory
	FedAuthADALWorkflowIntegrated = 0x02

	// FedAuthADALWorkflowMSI uses the managed identity service to obtain a token
	FedAuthADALWorkflowMSI = 0x03

	// FedAuthADALWorkflowNone does not need to obtain token
	FedAuthADALWorkflowNone = 0x04
)

Federated authentication ADAL workflow affects the mechanism used to authenticate.

Variables

View Source
var (
	ErrorEmptyTVPTypeName = errors.New("TypeName must not be empty")
	ErrorTypeSlice        = errors.New("TVP must be slice type")
	ErrorTypeSliceIsEmpty = errors.New("TVP mustn't be null value")
	ErrorSkip             = errors.New("all fields mustn't skip")
	ErrorObjectName       = errors.New("wrong tvp name")
	ErrorWrongTyping      = errors.New("the number of elements in columnStr and tvpFieldIndexes do not align")
)

Functions

func CopyIn

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

This example shows how to perform bulk imports

//go:build go1.10
// +build go1.10

package main

import (
	"database/sql"
	"log"
	"strings"
	"unicode/utf8"

	mssql "github.com/microsoft/go-mssqldb"
)

const (
	createTestTable = `CREATE TABLE test_table(
		id int IDENTITY(1,1) NOT NULL,
		test_nvarchar nvarchar(50) NULL,
		test_varchar varchar(50) NULL,
		test_float float NULL,
		test_datetime2_3 datetime2(3) NULL,
		test_bitn bit NULL,
		test_bigint bigint NOT NULL,
		test_geom geometry NULL,
	CONSTRAINT PK_table_test_id PRIMARY KEY CLUSTERED
	(
		id ASC
	) ON [PRIMARY]);`
	dropTestTable = "IF OBJECT_ID('test_table', 'U') IS NOT NULL DROP TABLE test_table;"
)

// This example shows how to perform bulk imports
func main() {

	connString := makeConnURL().String()

	db, err := sql.Open("sqlserver", connString)
	if err != nil {
		log.Fatal("Open connection failed:", err.Error())
	}
	defer db.Close()

	txn, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}

	// Create table
	_, err = db.Exec(createTestTable)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Exec(dropTestTable)

	// mssqldb.CopyIn creates string to be consumed by Prepare
	stmt, err := txn.Prepare(mssql.CopyIn("test_table", mssql.BulkOptions{}, "test_varchar", "test_nvarchar", "test_float", "test_bigint"))
	if err != nil {
		log.Fatal(err.Error())
	}

	for i := 0; i < 10; i++ {
		_, err = stmt.Exec(generateString(0, 30), generateStringUnicode(0, 30), i, i)
		if err != nil {
			log.Fatal(err.Error())
		}
	}

	result, err := stmt.Exec()
	if err != nil {
		log.Fatal(err)
	}

	err = stmt.Close()
	if err != nil {
		log.Fatal(err)
	}

	err = txn.Commit()
	if err != nil {
		log.Fatal(err)
	}
	rowCount, _ := result.RowsAffected()
	log.Printf("%d row copied\n", rowCount)
	log.Printf("bye\n")
}

func generateString(x int, n int) string {
	letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	b := make([]byte, n)
	for i := range b {
		b[i] = letters[(x+i)%len(letters)]
	}
	return string(b)
}
func generateStringUnicode(x int, n int) string {
	letters := []byte("ab©💾é?ghïjklmnopqЯ☀tuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	b := &strings.Builder{}
	for i := 0; i < n; i++ {
		r, sz := utf8.DecodeRune(letters[x%len(letters):])
		x += sz
		b.WriteRune(r)
	}
	return b.String()
}
Output:

func IsSkipField

func IsSkipField(tvpTagValue string, isTvpValue bool, jsonTagValue string, isJsonTagValue bool) bool

func NewAccessTokenConnector

func NewAccessTokenConnector(dsn string, tokenProvider func() (string, error)) (driver.Connector, error)

NewAccessTokenConnector creates a new connector from a DSN and a token provider. The token provider func will be called when a new connection is requested and should return a valid access token. The returned connector may be used with sql.OpenDB.

func SetContextLogger

func SetContextLogger(ctxLogger ContextLogger)

SetContextLogger sets a ContextLogger for both driver instances ("mssql" and "sqlserver"). Use this to get callbacks from go-mssqldb with additional information and extra details that you can log in the format of your choice. You can set either a ContextLogger or a Logger, but not both. Calling SetContextLogger will overwrite any Logger you set with SetLogger.

func SetLogger

func SetLogger(logger Logger)

SetLogger sets a Logger for both driver instances ("mssql" and "sqlserver"). Use this to have go-msqldb log additional information in a format it picks. You can set either a Logger or a ContextLogger, but not both. Calling SetLogger will overwrite any ContextLogger you set with SetContextLogger.

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

func (c *Conn) IsValid() bool

IsValid satisfies the driver.Validator interface.

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

	// Dialer sets a custom dialer for all network operations.
	// If Dialer is not set, normal net dialers are used.
	Dialer Dialer
	// 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.

Example

This example shows the usage of Connector type

//go:build go1.10
// +build go1.10

package main

import (
	"context"
	"database/sql"
	"flag"
	"fmt"
	"log"
	"net/url"
	"strconv"

	mssql "github.com/microsoft/go-mssqldb"
)

var (
	debug         = flag.Bool("debug", false, "enable debugging")
	password      = flag.String("password", "", "the database password")
	port     *int = flag.Int("port", 1433, "the database port")
	server        = flag.String("server", ".", "the database server")
	user          = flag.String("user", "", "the database user")
)

const (
	createTableSql      = "CREATE TABLE TestAnsiNull (bitcol bit, charcol char(1));"
	dropTableSql        = "IF OBJECT_ID('TestAnsiNull', 'U') IS NOT NULL DROP TABLE TestAnsiNull;"
	insertQuery1        = "INSERT INTO TestAnsiNull VALUES (0, NULL);"
	insertQuery2        = "INSERT INTO TestAnsiNull VALUES (1, 'a');"
	selectNullFilter    = "SELECT bitcol FROM TestAnsiNull WHERE charcol = NULL;"
	selectNotNullFilter = "SELECT bitcol FROM TestAnsiNull WHERE charcol <> NULL;"
)

func makeConnURL() *url.URL {
	flag.Parse()
	if *debug {
		fmt.Printf(" password:%s\n", *password)
		fmt.Printf(" port:%d\n", *port)
		fmt.Printf(" server:%s\n", *server)
		fmt.Printf(" user:%s\n", *user)
	}

	params, err := mssql.GetConnParams()
	if err == nil && params != nil {
		return params.URL()
	}
	var userInfo *url.Userinfo
	if *user != "" {
		userInfo = url.UserPassword(*user, *password)
	}
	return &url.URL{
		Scheme: "sqlserver",
		Host:   *server + ":" + strconv.Itoa(*port),
		User:   userInfo,
	}
}

// This example shows the usage of Connector type
func main() {

	connString := makeConnURL().String()
	if *debug {
		fmt.Printf(" connString:%s\n", connString)
	}

	// Create a new connector object by calling NewConnector
	connector, err := mssql.NewConnector(connString)
	if err != nil {
		log.Println(err)
		return
	}

	// Use SessionInitSql to set any options that cannot be set with the dsn string
	// With ANSI_NULLS set to ON, compare NULL data with = NULL or <> NULL will return 0 rows
	connector.SessionInitSQL = "SET ANSI_NULLS ON"

	// Pass connector to sql.OpenDB to get a sql.DB object
	db := sql.OpenDB(connector)
	defer db.Close()

	// Create and populate table
	_, err = db.Exec(createTableSql)
	if err != nil {
		log.Println(err)
		return
	}
	defer db.Exec(dropTableSql)
	_, err = db.Exec(insertQuery1)
	if err != nil {
		log.Println(err)
		return
	}
	_, err = db.Exec(insertQuery2)
	if err != nil {
		log.Println(err)
		return
	}

	var bitval bool
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// (*Row) Scan should return ErrNoRows since ANSI_NULLS is set to ON
	err = db.QueryRowContext(ctx, selectNullFilter).Scan(&bitval)
	if err != nil {
		if err.Error() != "sql: no rows in result set" {
			log.Println(err)
			return
		}
	} else {
		log.Println("Expects an ErrNoRows error. No error is returned")
		return
	}

	// (*Row) Scan should return ErrNoRows since ANSI_NULLS is set to ON
	err = db.QueryRowContext(ctx, selectNotNullFilter).Scan(&bitval)
	if err != nil {
		if err.Error() != "sql: no rows in result set" {
			log.Println(err)
			return
		}
	} else {
		log.Println("Expects an ErrNoRows error. No error is returned")
		return
	}

	// Set ANSI_NULLS to OFF
	connector.SessionInitSQL = "SET ANSI_NULLS OFF"

	// (*Row) Scan should copy data to bitval
	err = db.QueryRowContext(ctx, selectNullFilter).Scan(&bitval)
	if err != nil {
		log.Println(err)
		return
	}
	if bitval != false {
		log.Println("Incorrect value retrieved.")
		return
	}

	// (*Row) Scan should copy data to bitval
	err = db.QueryRowContext(ctx, selectNotNullFilter).Scan(&bitval)
	if err != nil {
		log.Println(err)
		return
	}
	if bitval != true {
		log.Println("Incorrect value retrieved.")
		return
	}
}
Output:

func NewActiveDirectoryTokenConnector

func NewActiveDirectoryTokenConnector(config msdsn.Config, adalWorkflow byte, tokenProvider func(ctx context.Context, serverSPN, stsURL string) (string, error)) (*Connector, error)

newADALTokenConnector creates a new connector from a Config and a Active Directory token provider. Token provider implementations are called during federated authentication login sequences where the server provides a service principal name and security token service endpoint that should be used to obtain the token. Implementations should contact the security token service specified and obtain the appropriate token, or return an error to indicate why a token is not available.

The returned connector may be used with sql.OpenDB.

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 NewConnectorConfig

func NewConnectorConfig(config msdsn.Config) *Connector

NewConnectorConfig creates a new Connector for a DSN Config struct. The returned connector may be used with sql.OpenDB.

func NewConnectorWithAccessTokenProvider

func NewConnectorWithAccessTokenProvider(dsn string, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error)

NewConnectorWithAccessTokenProvider creates a new connector from a DSN using the given access token provider. The returned connector may be used with sql.OpenDB.

func NewSecurityTokenConnector

func NewSecurityTokenConnector(config msdsn.Config, tokenProvider func(ctx context.Context) (string, error)) (*Connector, error)

newSecurityTokenConnector creates a new connector from a Config and a token provider. When invoked, token provider implementations should contact the security token service specified and obtain the appropriate token, or return an error to indicate why a token is not available. 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 ContextLogger

type ContextLogger interface {
	Log(ctx context.Context, category msdsn.Log, msg string)
}

ContextLogger is an interface that provides more information than Logger and lets you log messages yourself. This gives you more information to log (e.g. trace IDs in the context), more control over the logging activity (e.g. log it, trace it, or log and trace it, depending on the class of message), and lets you log in exactly the format you want.

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.

Example

This example shows how to insert and retrieve date and time types data

//go:build go1.10
// +build go1.10

package main

import (
	"database/sql"
	"fmt"
	"log"
	"time"

	"github.com/golang-sql/civil"
	mssql "github.com/microsoft/go-mssqldb"
)

// This example shows how to insert and retrieve date and time types data
func main() {

	connString := makeConnURL().String()

	db, err := sql.Open("sqlserver", connString)
	if err != nil {
		log.Fatal("Open connection failed:", err.Error())
	}
	defer db.Close()

	insertDateTime(db)
	retrieveDateTime(db)
	retrieveDateTimeOutParam(db)
}

func insertDateTime(db *sql.DB) {
	_, err := db.Exec("CREATE TABLE datetimeTable (timeCol TIME, dateCol DATE, smalldatetimeCol SMALLDATETIME, datetimeCol DATETIME, datetime2Col DATETIME2, datetimeoffsetCol DATETIMEOFFSET)")
	if err != nil {
		log.Fatal(err)
	}
	stmt, err := db.Prepare("INSERT INTO datetimeTable VALUES(@p1, @p2, @p3, @p4, @p5, @p6)")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	tin, err := time.Parse(time.RFC3339, "2006-01-02T22:04:05.787-07:00")
	if err != nil {
		log.Fatal(err)
	}
	var timeCol civil.Time = civil.TimeOf(tin)
	var dateCol civil.Date = civil.DateOf(tin)
	var smalldatetimeCol string = "2006-01-02 22:04:00"
	var datetimeCol mssql.DateTime1 = mssql.DateTime1(tin)
	var datetime2Col civil.DateTime = civil.DateTimeOf(tin)
	var datetimeoffsetCol mssql.DateTimeOffset = mssql.DateTimeOffset(tin)
	_, err = stmt.Exec(timeCol, dateCol, smalldatetimeCol, datetimeCol, datetime2Col, datetimeoffsetCol)
	if err != nil {
		log.Fatal(err)
	}
}

func retrieveDateTime(db *sql.DB) {
	rows, err := db.Query("SELECT timeCol, dateCol, smalldatetimeCol, datetimeCol, datetime2Col, datetimeoffsetCol FROM datetimeTable")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	var c1, c2, c3, c4, c5, c6 time.Time
	for rows.Next() {
		err = rows.Scan(&c1, &c2, &c3, &c4, &c5, &c6)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("c1: %+v; c2: %+v; c3: %+v; c4: %+v; c5: %+v; c6: %+v;\n", c1, c2, c3, c4, c5, c6)
	}
}

func retrieveDateTimeOutParam(db *sql.DB) {
	CreateProcSql := `
	CREATE PROCEDURE OutDatetimeProc
		@timeOutParam TIME OUTPUT,
		@dateOutParam DATE OUTPUT,
		@smalldatetimeOutParam SMALLDATETIME OUTPUT,
		@datetimeOutParam DATETIME OUTPUT,
		@datetime2OutParam DATETIME2 OUTPUT,
		@datetimeoffsetOutParam DATETIMEOFFSET OUTPUT
	AS
		SET NOCOUNT ON
		SET @timeOutParam = '22:04:05.7870015'
		SET @dateOutParam = '2006-01-02'
		SET @smalldatetimeOutParam = '2006-01-02 22:04:00'
		SET @datetimeOutParam = '2006-01-02 22:04:05.787'
		SET @datetime2OutParam = '2006-01-02 22:04:05.7870015'
		SET @datetimeoffsetOutParam = '2006-01-02 22:04:05.7870015 -07:00'`
	_, err := db.Exec(CreateProcSql)
	if err != nil {
		log.Fatal(err)
	}
	var (
		timeOutParam, datetime2OutParam, datetimeoffsetOutParam mssql.DateTimeOffset
		dateOutParam, datetimeOutParam                          mssql.DateTime1
		smalldatetimeOutParam                                   string
	)
	_, err = db.Exec("OutDatetimeProc",
		sql.Named("timeOutParam", sql.Out{Dest: &timeOutParam}),
		sql.Named("dateOutParam", sql.Out{Dest: &dateOutParam}),
		sql.Named("smalldatetimeOutParam", sql.Out{Dest: &smalldatetimeOutParam}),
		sql.Named("datetimeOutParam", sql.Out{Dest: &datetimeOutParam}),
		sql.Named("datetime2OutParam", sql.Out{Dest: &datetime2OutParam}),
		sql.Named("datetimeoffsetOutParam", sql.Out{Dest: &datetimeoffsetOutParam}))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("timeOutParam: %+v; dateOutParam: %+v; smalldatetimeOutParam: %s; datetimeOutParam: %+v; datetime2OutParam: %+v; datetimeoffsetOutParam: %+v;\n", time.Time(timeOutParam), time.Time(dateOutParam), smalldatetimeOutParam, time.Time(datetimeOutParam), time.Time(datetime2OutParam), time.Time(datetimeoffsetOutParam))
}
Output:

type Dialer

type Dialer interface {
	DialContext(ctx context.Context, network string, addr string) (net.Conn, error)
}

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

func (d *Driver) SetContextLogger(ctxLogger ContextLogger)

SetContextLogger sets a ContextLogger for the driver instance on which you call it. Use this to get callbacks from go-mssqldb with additional information and extra details that you can log in the format of your choice. You can set either a ContextLogger or a Logger, but not both. Calling SetContextLogger will overwrite any Logger you set with SetLogger.

func (*Driver) SetLogger

func (d *Driver) SetLogger(logger Logger)

SetLogger sets a Logger for the driver instance on which you call it. Use this to have go-msqldb log additional information in a format it picks. You can set either a Logger or a ContextLogger, but not both. Calling SetLogger will overwrite any ContextLogger you set with SetContextLogger.

type Error

type Error struct {
	Number     int32
	State      uint8
	Class      uint8
	Message    string
	ServerName string
	ProcName   string
	LineNo     int32
	// All lists all errors that were received from first to last.
	// This includes the last one, which is described in the other members.
	All []Error
}

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
Example
package main

import (
	"fmt"
)

func main() {
	// call a function that might return a mssql error
	err := callUsingMSSQL()

	type SQLError interface {
		SQLErrorNumber() int32
		SQLErrorMessage() string
	}

	if sqlError, ok := err.(SQLError); ok {
		if sqlError.SQLErrorNumber() == 1205 {
			fmt.Println("deadlock error", sqlError.SQLErrorMessage())
		}
	}
}

func callUsingMSSQL() error {
	return nil
}
Output:

func (Error) SQLErrorNumber

func (e Error) SQLErrorNumber() int32

SQLErrorNumber returns the SQL Server error number.

Example
package main

import (
	"fmt"
)

func main() {
	// call a function that might return a mssql error
	err := callUsingMSSQL()

	type ErrorWithNumber interface {
		SQLErrorNumber() int32
	}

	if errorWithNumber, ok := err.(ErrorWithNumber); ok {
		if errorWithNumber.SQLErrorNumber() == 1205 {
			fmt.Println("deadlock error")
		}
	}
}

func callUsingMSSQL() error {
	return nil
}
Output:

func (Error) SQLErrorProcName

func (e Error) SQLErrorProcName() string

func (Error) SQLErrorServerName

func (e Error) SQLErrorServerName() string

func (Error) SQLErrorState

func (e Error) SQLErrorState() uint8

func (Error) String

func (e Error) String() string

type Logger

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

Logger is an interface you can implement to have the go-msqldb driver automatically log detailed information on your behalf

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 MssqlProtocolDialer

type MssqlProtocolDialer interface {
	// DialSqlConnection creates a net.Conn from a Connector based on the Config
	DialSqlConnection(ctx context.Context, c *Connector, p *msdsn.Config) (conn net.Conn, err error)
}

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 RetryableError

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

RetryableError is returned when an error was caused by a bad connection at the start of a query and can be safely retried using database/sql's automatic retry logic.

In many cases database/sql's retry logic will transparently handle this error, the retried call will return successfully, and you won't even see this error. However, you may see this error if the retry logic cannot successfully handle the error. In that case you can get the underlying error by calling this error's UnWrap function.

func (RetryableError) Error

func (r RetryableError) Error() string

func (RetryableError) Is

func (r RetryableError) Is(err error) bool

func (RetryableError) Unwrap

func (r RetryableError) Unwrap() error

type ReturnStatus

type ReturnStatus int32

ReturnStatus may be used to return the return value from a proc.

var rs mssql.ReturnStatus
_, err := db.Exec("theproc", &rs)
log.Printf("return status = %d", rs)

type Rows

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

Rows represents the non-experimental data/sql model for Query and QueryContext

Example (Usingmessages)

This example shows the usage of sqlexp/Messages

//go:build go1.10
// +build go1.10

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"

	"github.com/golang-sql/sqlexp"
	mssql "github.com/microsoft/go-mssqldb"
)

const (
	msgQuery = `select 'name' as Name
PRINT N'This is a message'
select 199
RAISERROR (N'Testing!' , 11, 1)
select 300
`
)

// This example shows the usage of sqlexp/Messages
func main() {

	connString := makeConnURL().String()

	// Create a new connector object by calling NewConnector
	connector, err := mssql.NewConnector(connString)
	if err != nil {
		log.Println(err)
		return
	}

	// Pass connector to sql.OpenDB to get a sql.DB object
	db := sql.OpenDB(connector)
	defer db.Close()
	retmsg := &sqlexp.ReturnMessage{}
	ctx := context.Background()
	rows, err := db.QueryContext(ctx, msgQuery, retmsg)
	if err != nil {
		log.Fatalf("QueryContext failed: %v", err)
	}
	active := true
	for active {
		msg := retmsg.Message(ctx)
		switch m := msg.(type) {
		case sqlexp.MsgNotice:
			fmt.Println(m.Message)
		case sqlexp.MsgNext:
			inresult := true
			for inresult {
				inresult = rows.Next()
				if inresult {
					cols, err := rows.Columns()
					if err != nil {
						log.Fatalf("Columns failed: %v", err)
					}
					fmt.Println(cols)
					var d interface{}
					if err = rows.Scan(&d); err == nil {
						fmt.Println(d)
					}
				}
			}
		case sqlexp.MsgNextResultSet:
			active = rows.NextResultSet()
		case sqlexp.MsgError:
			fmt.Println("Error:", m.Error)
		case sqlexp.MsgRowsAffected:
			fmt.Println("Rows affected:", m.Count)
		}
	}
}
Output:

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 Rowsq

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

Rowsq implements the sqlexp messages model for Query and QueryContext Theory: We could also implement the non-experimental model this way

func (*Rowsq) Close

func (rc *Rowsq) Close() error

func (*Rowsq) ColumnTypeDatabaseTypeName

func (r *Rowsq) 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 (*Rowsq) ColumnTypeLength

func (r *Rowsq) 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 (*Rowsq) ColumnTypeNullable

func (r *Rowsq) 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 (*Rowsq) ColumnTypePrecisionScale

func (r *Rowsq) 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 (*Rowsq) ColumnTypeScanType

func (r *Rowsq) 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 (*Rowsq) Columns

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

ProcessSingleResponse queues MsgNext for every columns token. data/sql calls Columns during the app's call to Next.

func (*Rowsq) HasNextResultSet

func (rc *Rowsq) HasNextResultSet() bool

In Message Queue mode, we always claim another resultset could be on the way to avoid Rows being closed prematurely

func (*Rowsq) Next

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

func (*Rowsq) NextResultSet

func (rc *Rowsq) NextResultSet() error

Scans to the end of the current statement being processed Note that the caller may not have read all the rows in the prior set

type ServerError

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

ServerError is returned when the server got a fatal error that aborts the process and severs the connection.

To get the errors returned before the process was aborted, unwrap this error or call errors.As with a pointer to an mssql.Error variable.

func (ServerError) Error

func (e ServerError) Error() string

func (ServerError) Unwrap

func (e ServerError) Unwrap() 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 {
	InnerError error
}

func (StreamError) Error

func (e StreamError) Error() string

type TVP

type TVP struct {
	//TypeName mustn't be default value
	TypeName string
	//Value must be the slice, mustn't be nil
	Value interface{}
}

TVP is driver type, which allows supporting Table Valued Parameters (TVP) in SQL Server

Example

This example shows how to use tvp type

const (
	createTable = "CREATE TABLE Location (Name VARCHAR(50), CostRate INT, Availability BIT, ModifiedDate DATETIME2)"

	createTVP = `CREATE TYPE LocationTableType AS TABLE
		(LocationName VARCHAR(50),
		CostRate INT)`

	dropTVP = "IF type_id('LocationTableType') IS NOT NULL DROP TYPE LocationTableType"

	createProc = `CREATE PROCEDURE dbo.usp_InsertProductionLocation
		@TVP LocationTableType READONLY
		AS
		SET NOCOUNT ON
		INSERT INTO Location
		(
			Name,
			CostRate,
			Availability,
			ModifiedDate)
			SELECT *, 0,GETDATE()
			FROM @TVP`

	dropProc = "IF OBJECT_ID('dbo.usp_InsertProductionLocation', 'P') IS NOT NULL DROP PROCEDURE dbo.usp_InsertProductionLocation"

	execTvp = "exec dbo.usp_InsertProductionLocation @TVP;"
)
type LocationTableTvp struct {
	LocationName    string
	LocationCountry string `tvp:"-"`
	CostRate        int64
	Currency        string `json:"-"`
}

connString := makeConnURL().String()

db, err := sql.Open("sqlserver", connString)
if err != nil {
	log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()

_, err = db.Exec(createTable)
if err != nil {
	log.Fatal(err)
}
_, err = db.Exec(createTVP)
if err != nil {
	log.Fatal(err)
}
defer db.Exec(dropTVP)
_, err = db.Exec(createProc)
if err != nil {
	log.Fatal(err)
}
defer db.Exec(dropProc)

locationTableTypeData := []LocationTableTvp{
	{
		LocationName:    "Alberta",
		LocationCountry: "Canada",
		CostRate:        0,
		Currency:        "CAD",
	},
	{
		LocationName:    "British Columbia",
		LocationCountry: "Canada",
		CostRate:        1,
		Currency:        "CAD",
	},
}

tvpType := mssql.TVP{
	TypeName: "LocationTableType",
	Value:    locationTableTypeData,
}

_, err = db.Exec(execTvp, sql.Named("TVP", tvpType))
if err != nil {
	log.Fatal(err)
} else {
	for _, locationData := range locationTableTypeData {
		fmt.Printf("Data for location %s, %s has been inserted.\n", locationData.LocationName, locationData.LocationCountry)
	}
}
Output:

type UniqueIdentifier

type UniqueIdentifier [16]byte

func (UniqueIdentifier) MarshalText

func (u UniqueIdentifier) MarshalText() []byte

MarshalText converts Uniqueidentifier to bytes corresponding to the stringified hexadecimal representation of the Uniqueidentifier e.g., "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" -> [65 65 65 65 65 65 65 65 45 65 65 65 65 45 65 65 65 65 45 65 65 65 65 65 65 65 65 65 65 65 65]

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
tvp
internal
cp
np
querytext
Package querytext is the old query parser and parameter substitute process.
Package querytext is the old query parser and parameter substitute process.

Jump to

Keyboard shortcuts

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