sqlserver

package
v1.3.7 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2023 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type SQLResult

type SQLResult struct {
	RowsAffected    int64
	NewlyInsertedID int64
	Err             error
}

SQLResult defines sql action query result info

type SQLServer

type SQLServer struct {
	// SQLServer connection properties
	Host      string
	Port      int
	Instance  string
	Database  string
	UserName  string
	Password  string
	Timeout   int
	Encrypted bool
	AppName   string
	// contains filtered or unexported fields
}

SQLServer struct encapsulates the SQLServer database access functionality (using sqlx package)

func (*SQLServer) Begin

func (svr *SQLServer) Begin() error

Begin starts a database transaction, and stores the transaction object until commit or rollback

func (*SQLServer) Close

func (svr *SQLServer) Close() error

Close will close the database connection and set db to nil

func (*SQLServer) Commit

func (svr *SQLServer) Commit() error

Commit finalizes a database transaction, and commits changes to database

func (*SQLServer) ExecByNamedMapParam

func (svr *SQLServer) ExecByNamedMapParam(query string, args map[string]interface{}) SQLResult

ExecByNamedMapParam executes action query string with named map containing parameters to return result, if error, returns error object within result [ Syntax ]

  1. in sql = instead of defining ordinal parameters @p1..@pN, each parameter in sql does not need to be ordinal, rather define with :xyz (must have : in front of param name), where xyz is name of parameter, such as :customerID
  2. in go = setup a map variable: var p = make(map[string]interface{})
  3. in go = to set values into map variable: p["xyz"] = abc where xyz is the parameter name matching the sql :xyz (do not include : in go map "xyz") where abc is the value of the parameter value, whether string or other data types note: in using map, just add additional map elements using the p["xyz"] = abc syntax note: if parameter value can be a null, such as nullint, nullstring, use util.ToNullTime(), ToNullInt(), ToNullString(), etc.
  4. in go = when calling this function passing the map variable, simply pass the map variable p into the args parameter

[ Parameters ]

actionQuery = sql action query, with named parameters using :xyz syntax
args = required, the map variable of the named parameters

[ Return Values ]

  1. SQLResult = represents the sql action result received (including error info if applicable)

func (*SQLServer) ExecByOrdinalParams

func (svr *SQLServer) ExecByOrdinalParams(query string, args ...interface{}) SQLResult

ExecByOrdinalParams executes action query string and parameters to return result, if error, returns error object within result [ Parameters ]

actionQuery = sql action query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. SQLResult = represents the sql action result received (including error info if applicable)

func (*SQLServer) ExecByStructParam

func (svr *SQLServer) ExecByStructParam(query string, args interface{}) SQLResult

ExecByStructParam executes action query string with struct containing parameters to return result, if error, returns error object within result, the struct fields' struct tags must match the parameter names, such as: struct tag `db:"customerID"` must match parameter name in sql as ":customerID" [ Syntax ]

  1. in sql = instead of defining ordinal parameters @p1..@pN, each parameter in sql does not need to be ordinal, rather define with :xyz (must have : in front of param name), where xyz is name of parameter, such as :customerID
  2. in go = using a struct to contain fields to match parameters, make sure struct tags match to the sql parameter names, such as struct tag `db:"customerID"` must match parameter name in sql as ":customerID" (the : is not part of the match)

[ Parameters ]

actionQuery = sql action query, with named parameters using :xyz syntax
args = required, the struct variable, whose fields having struct tags matching sql parameter names

[ Return Values ]

  1. SQLResult = represents the sql action result received (including error info if applicable)

func (*SQLServer) GetDsnADO

func (svr *SQLServer) GetDsnADO() (string, error)

GetDsnADO serialize SQLServer dsn to ado style connection string, for use in database connectivity (dsn.Port is ignored)

func (*SQLServer) GetDsnURL

func (svr *SQLServer) GetDsnURL() (string, error)

GetDsnURL serialize sql server dsn to url style connection string, for use in database connectivity

func (*SQLServer) GetRowsByNamedMapParam

func (svr *SQLServer) GetRowsByNamedMapParam(query string, args map[string]interface{}) (*sqlx.Rows, error)

GetRowsByNamedMapParam performs query with named map containing parameters to get ROWS of result, and returns *sqlx.Rows [ Syntax ]

  1. in sql = instead of defining ordinal parameters @p1..@pN, each parameter in sql does not need to be ordinal, rather define with :xyz (must have : in front of param name), where xyz is name of parameter, such as :customerID
  2. in go = setup a map variable: var p = make(map[string]interface{})
  3. in go = to set values into map variable: p["xyz"] = abc where xyz is the parameter name matching the sql :xyz (do not include : in go map "xyz") where abc is the value of the parameter value, whether string or other data types note: in using map, just add additional map elements using the p["xyz"] = abc syntax note: if parameter value can be a null, such as nullint, nullstring, use util.ToNullTime(), ToNullInt(), ToNullString(), etc.
  4. in go = when calling this function passing the map variable, simply pass the map variable p into the args parameter

[ Parameters ]

query = sql query, optionally having parameters marked as :xyz for each parameter name, where each represents a named parameter
args = required, the map variable of the named parameters

[ Return Values ]

  1. *sqlx.Rows = pointer to sqlx.Rows; or nil if no rows yielded
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and sqlx.Rows is returned as nil)

[ Ranged Loop & Scan ]

  1. to loop, use: for _, r := range rows
  2. to scan, use: r.Scan(&x, &y, ...), where r is the row struct in loop, where &x &y etc are the scanned output value (scan in order of select columns sequence)

[ Continuous Loop & Scan ]

  1. Continuous loop until endOfRows = true is yielded from ScanSlice() or ScanStruct()
  2. ScanSlice(): accepts *sqlx.Rows, scans rows result into target pointer slice (if no error, endOfRows = true is returned)
  3. ScanStruct(): accepts *sqlx.Rows, scans current single row result into target pointer struct, returns endOfRows as true of false; if endOfRows = true, loop should stop

func (*SQLServer) GetRowsByOrdinalParams

func (svr *SQLServer) GetRowsByOrdinalParams(query string, args ...interface{}) (*sqlx.Rows, error)

GetRowsByOrdinalParams performs query with optional variadic parameters to get ROWS of result, and returns *sqlx.Rows [ Parameters ]

query = sql query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. *sqlx.Rows = pointer to sqlx.Rows; or nil if no rows yielded
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and sqlx.Rows is returned as nil)

[ Ranged Loop & Scan ]

  1. to loop, use: for _, r := range rows
  2. to scan, use: r.Scan(&x, &y, ...), where r is the row struct in loop, where &x &y etc are the scanned output value (scan in order of select columns sequence)

[ Continuous Loop & Scan ]

  1. Continuous loop until endOfRows = true is yielded from ScanSlice() or ScanStruct()
  2. ScanSlice(): accepts *sqlx.Rows, scans rows result into target pointer slice (if no error, endOfRows = true is returned)
  3. ScanStruct(): accepts *sqlx.Rows, scans current single row result into target pointer struct, returns endOfRows as true of false; if endOfRows = true, loop should stop

func (*SQLServer) GetRowsByStructParam

func (svr *SQLServer) GetRowsByStructParam(query string, args interface{}) (*sqlx.Rows, error)

GetRowsByStructParam performs query with a struct as parameter input to get ROWS of result, and returns *sqlx.Rows [ Syntax ]

  1. in sql = instead of defining ordinal parameters @p1..@pN, each parameter in sql does not need to be ordinal, rather define with :xyz (must have : in front of param name), where xyz is name of parameter, such as :customerID
  2. in sql = important: the :xyz defined where xyz portion of parameter name must batch the struct tag's `db:"xyz"`
  3. in go = a struct containing struct tags that matches the named parameters will be set with values, and passed into this function's args parameter input
  4. in go = when calling this function passing the struct variable, simply pass the struct variable into the args parameter

[ Parameters ]

query = sql query, optionally having parameters marked as :xyz for each parameter name, where each represents a named parameter
args = required, the struct variable where struct fields' struct tags match to the named parameters

[ Return Values ]

  1. *sqlx.Rows = pointer to sqlx.Rows; or nil if no rows yielded
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and sqlx.Rows is returned as nil)

[ Ranged Loop & Scan ]

  1. to loop, use: for _, r := range rows
  2. to scan, use: r.Scan(&x, &y, ...), where r is the row struct in loop, where &x &y etc are the scanned output value (scan in order of select columns sequence)

[ Continuous Loop & Scan ]

  1. Continuous loop until endOfRows = true is yielded from ScanSlice() or ScanStruct()
  2. ScanSlice(): accepts *sqlx.Rows, scans rows result into target pointer slice (if no error, endOfRows = true is returned)
  3. ScanStruct(): accepts *sqlx.Rows, scans current single row result into target pointer struct, returns endOfRows as true of false; if endOfRows = true, loop should stop

func (*SQLServer) GetScalarNullString

func (svr *SQLServer) GetScalarNullString(query string, args ...interface{}) (retVal sql.NullString, retNotFound bool, retErr error)

GetScalarNullString performs query with optional variadic parameters, and returns the first row and first column value in sql.NullString{} data type [ Parameters ]

query = sql query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. retVal = string value of scalar result, if no value, sql.NullString{} is returned
  2. retNotFound = now row found
  3. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and retVal is returned as sql.NullString{})

func (*SQLServer) GetScalarString

func (svr *SQLServer) GetScalarString(query string, args ...interface{}) (retVal string, retNotFound bool, retErr error)

GetScalarString performs query with optional variadic parameters, and returns the first row and first column value in string data type [ Parameters ]

query = sql query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. retVal = string value of scalar result, if no value, blank is returned
  2. retNotFound = now row found
  3. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and retVal is returned as blank)

func (*SQLServer) GetSingleRow

func (svr *SQLServer) GetSingleRow(query string, args ...interface{}) (*sqlx.Row, error)

GetSingleRow performs query with optional variadic parameters to get a single ROW of result, and returns *sqlx.Row (This function returns SINGLE ROW) [ Parameters ]

query = sql query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. *sqlx.Row = pointer to sqlx.Row; or nil if no row yielded
  2. if error != nil, then error is encountered (if error = sql.ErrNoRows, then error is treated as nil, and sqlx.Row is returned as nil)

[ Scan Values ]

  1. Use row.Scan() and pass in pointer or address of variable to receive scanned value outputs (Scan is in the order of column sequences in select statement)

[ WARNING !!! ]

WHEN USING Scan(), MUST CHECK Scan Result Error for sql.ErrNoRow status
SUGGESTED TO USE ScanColumnsByRow() Instead of Scan()

func (*SQLServer) GetStruct

func (svr *SQLServer) GetStruct(dest interface{}, query string, args ...interface{}) (notFound bool, retErr error)

GetStruct performs query with optional variadic parameters, and unmarshal single result row into single target struct, such as: Customer struct where one row of data represent a customer [ Parameters ]

dest = pointer to struct or address of struct, this is the result of row to be marshaled into this struct
query = sql query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. notFound = indicates no rows found in query (aka sql.ErrNoRows), if error is detected, notFound is always false
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is nil)

func (*SQLServer) GetStructSlice

func (svr *SQLServer) GetStructSlice(dest interface{}, query string, args ...interface{}) (notFound bool, retErr error)

GetStructSlice performs query with optional variadic parameters, and unmarshal result rows into target struct slice, in essence, each row of data is marshaled into the given struct, and multiple struct form the slice, such as: []Customer where each row represent a customer, and multiple customers being part of the slice [ Parameters ]

dest = pointer to the struct slice or address of struct slice, this is the result of rows to be marshaled into struct slice
query = sql query, optionally having parameters marked as @p1, @p2, ... @pN, where each represents a parameter position
args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters

[ Return Values ]

  1. notFound = indicates no rows found in query (aka sql.ErrNoRows), if error is detected, notFound is always false
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is nil)

[ Notes ]

  1. if error == nil, and len(dest struct slice) == 0 then zero struct slice result

func (*SQLServer) Open

func (svr *SQLServer) Open(useADOConnectString ...bool) error

Open a database by connecting to it, using the dsn properties defined in the struct fields

useADOConnectString = if ignored, default is true, to use URL connect string format, set parameter value to false explicitly

func (*SQLServer) Ping

func (svr *SQLServer) Ping() error

Ping tests if current database connection is still active and ready

func (*SQLServer) Rollback

func (svr *SQLServer) Rollback() error

Rollback cancels pending database changes for the current transaction and clears out transaction object

func (*SQLServer) ScanColumnsByRow

func (svr *SQLServer) ScanColumnsByRow(row *sqlx.Row, dest ...interface{}) (notFound bool, err error)

ScanColumnsByRow accepts a *sqlx row, and scans specific columns into dest outputs, this is different than ScanSliceByRow or ScanStructByRow because this function allows specific extraction of column values into target fields, (note: this function must extra all row column values to dest variadic parameters as present in the row parameter) [ Parameters ]

row = *sqlx.Row representing the row containing columns to extract, note that this function MUST extract all columns from this row
dest = MUST BE pointer (or &variable) to target variable to receive the column value, data type must match column data type value, and sequence of dest must be in the order of columns sequence

[ Return Values ]

  1. notFound = true if no row is found in current scan
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is set as nil and notFound is true)

[ Example ]

  1. assuming: Select CustomerID, CustomerName, Address FROM Customer Where CustomerPhone='123';
  2. assuming: row // *sqlx.Row derived from GetSingleRow() or specific row from GetRowsByOrdinalParams() / GetRowsByNamedMapParam() / GetRowsByStructParam()
  3. assuming: var CustomerID int64 var CustomerName string var Address string
  4. notFound, err := svr.ScanColumnsByRow(row, &CustomerID, &CustomerName, &Address)

func (*SQLServer) ScanSlice

func (svr *SQLServer) ScanSlice(rows *sqlx.Rows, dest []interface{}) (endOfRows bool, err error)

ScanSlice takes in *sqlx.Rows as parameter, will invoke the rows.Next() to advance to next row position, and marshals current row's column values into a pointer reference to a slice, this enables us to quickly retrieve a slice of current row column values without knowing how many columns or names or columns (columns appear in select columns sequence), to loop thru all rows, use range, and loop until endOfRows = true; the dest is nil if no columns found; the dest is pointer of slice when columns exists [ Parameters ]

rows = *sqlx.Rows
dest = pointer or address to slice, such as: variable to "*[]string", or variable to "&cList for declaration cList []string"

[ Return Values ]

  1. endOfRows = true if this action call yielded end of rows, meaning stop further processing of current loop
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is set as nil)

func (*SQLServer) ScanSliceByRow

func (svr *SQLServer) ScanSliceByRow(row *sqlx.Row, dest []interface{}) (notFound bool, err error)

ScanSliceByRow takes in *sqlx.Row as parameter, and marshals current row's column values into a pointer reference to a slice, this enables us to quickly retrieve a slice of current row column values without knowing how many columns or names or columns (columns appear in select columns sequence) [ Parameters ]

row = *sqlx.Row
dest = pointer or address to slice, such as: variable to "*[]string", or variable to "&cList for declaration cList []string"

[ Return Values ]

  1. notFound = true if no row is found in current scan
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is set as nil and notFound is true)

func (*SQLServer) ScanStruct

func (svr *SQLServer) ScanStruct(rows *sqlx.Rows, dest interface{}) (endOfRows bool, err error)

ScanStruct takes in *sqlx.Rows, will invoke the rows.Next() to advance to next row position, and marshals current row's column values into a pointer reference to a struct, the struct fields and row columns must match for both name and sequence position, this enables us to quickly convert the row's columns into a defined struct automatically, to loop thru all rows, use range, and loop until endOfRows = true; the dest is nil if no columns found; the dest is pointer of struct when mapping is complete [ Parameters ]

rows = *sqlx.Rows
dest = pointer or address to struct, such as: variable to "*Customer", or variable to "&c for declaration c Customer"

[ Return Values ]

  1. endOfRows = true if this action call yielded end of rows, meaning stop further processing of current loop
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is set as nil)

func (*SQLServer) ScanStructByRow

func (svr *SQLServer) ScanStructByRow(row *sqlx.Row, dest interface{}) (notFound bool, err error)

ScanStructByRow takes in *sqlx.Row, and marshals current row's column values into a pointer reference to a struct, the struct fields and row columns must match for both name and sequence position, this enables us to quickly convert the row's columns into a defined struct automatically, the dest is nil if no columns found; the dest is pointer of struct when mapping is complete [ Parameters ]

row = *sqlx.Row
dest = pointer or address to struct, such as: variable to "*Customer", or variable to "&c for declaration c Customer"

[ Return Values ]

  1. notFound = true if no row is found in current scan
  2. if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is set as nil and notFound is true)

Jump to

Keyboard shortcuts

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