mysql

package
v1.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MySql

type MySql struct {
	// MySql server connection properties
	UserName string
	Password string

	Host     string
	Port     int
	Database string

	Charset        string // utf8, utf8mb4
	Collation      string // utf8mb4_general_ci, utf8_general_ci
	ConnectTimeout string // must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
	ReadTimeout    string // must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
	WriteTimeout   string // must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
	RejectReadOnly bool

	MaxOpenConns    int
	MaxIdleConns    int
	MaxConnIdleTime time.Duration
	// contains filtered or unexported fields
}

MySql struct encapsulates the MySql server database access functionality by wrapping Sqlx package with top level methods

   	Charset = utf8, utf8mb4 (< Default)
		Collation = utf8mb4_general_ci (< Default), utf8_general_ci
   	...Timeout = must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"

		MaxOpenConns = maximum open and idle connections for the connection pool, default is 0, which is unlimited (db *sqlx.DB internally is a connection pool object)
		MaxIdleConns = maximum number of idle connections to keep in the connection pool, default is 0 which is unlimited, this number should be equal or less than MaxOpenConns
		MaxConnIdleTime = maximum duration that an idle connection be kept in the connection pool, default is 0 which has no time limit, suggest 5 - 10 minutes if set

func (*MySql) Begin

func (svr *MySql) Begin() (*MySqlTransaction, error)

Begin starts a mysql transaction, and stores the transaction object into txMap until commit or rollback. ensure that transaction related actions are executed from the MySqlTransaction object.

func (*MySql) Close

func (svr *MySql) Close() error

Close will close the database connection and set db to nil

func (*MySql) ExecByNamedMapParam

func (svr *MySql) ExecByNamedMapParam(actionQuery string, args map[string]interface{}) MySqlResult

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 ?, 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. MySqlResult = represents the sql action result received (including error info if applicable)

func (*MySql) ExecByOrdinalParams

func (svr *MySql) ExecByOrdinalParams(actionQuery string, args ...interface{}) MySqlResult

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 ?1, ?2 .. ?N, 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. MySqlResult = represents the sql action result received (including error info if applicable)

func (*MySql) ExecByStructParam

func (svr *MySql) ExecByStructParam(actionQuery string, args interface{}) MySqlResult

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 ?, 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. MySqlResult = represents the sql action result received (including error info if applicable)

func (*MySql) GetDsn

func (svr *MySql) GetDsn() (string, error)

GetDsn serializes MySql server dsn to connection string, for use in database connectivity

func (*MySql) GetRowsByNamedMapParam

func (svr *MySql) 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 ?, 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 { if !rows.Next() { break } rows.Scan(&x, &y, etc) }
  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 (*MySql) GetRowsByOrdinalParams

func (svr *MySql) 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 ?, 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 { if !rows.Next() { break } rows.Scan(&x, &y, etc) }
  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 (*MySql) GetRowsByStructParam

func (svr *MySql) 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 ?, 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 { if !rows.Next() { break } rows.Scan(&x, &y, etc) }
  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 (*MySql) GetScalarNullString

func (svr *MySql) 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 ?, 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 (*MySql) GetScalarString

func (svr *MySql) 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 ?, 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 (*MySql) GetSingleRow

func (svr *MySql) 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 ?, 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 (*MySql) GetStruct

func (svr *MySql) 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 ?, 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 (*MySql) GetStructSlice

func (svr *MySql) 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 ?, 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 (*MySql) Open

func (svr *MySql) Open(parentSegment ...*xray.XRayParentSegment) error

Open will open a database either as normal or with xray tracing, Open uses the dsn properties defined in the struct fields

func (*MySql) Ping

func (svr *MySql) Ping() (err error)

Ping tests if current database connection is still active and ready

func (*MySql) ScanColumnsByRow

func (svr *MySql) 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 (*MySql) ScanSlice

func (svr *MySql) 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 (rows will be closed automatically)
  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 (*MySql) ScanSliceByRow

func (svr *MySql) 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 (*MySql) ScanStruct

func (svr *MySql) 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 (rows will be closed automatically)
  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 (*MySql) ScanStructByRow

func (svr *MySql) 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)

type MySqlResult

type MySqlResult struct {
	RowsAffected    int64
	NewlyInsertedID int64 // ONLY FOR INSERT, ONLY IF AUTO_INCREMENT PRIMARY KEY (Custom PK ID Will Have This Field as 0 Always)
	Err             error
}

MySqlResult defines sql action query result info [ Notes ]

  1. NewlyInsertedID = ONLY FOR INSERT, ONLY IF AUTO_INCREMENT PRIMARY KEY (Custom PK ID Will Have This Field as 0 Always)

type MySqlTransaction added in v1.1.8

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

MySqlTransaction represents an instance of the sqlx.Tx. Since sqlx.DB is actually a connection pool container, it may initiate multiple sql transactions, therefore, independent sqlx.Tx must be managed individually throughout its lifecycle.

each mysql transaction created will also register with MySql struct, so that during Close/Cleanup, all the related outstanding Transactions can rollback

func (*MySqlTransaction) Commit added in v1.1.8

func (t *MySqlTransaction) Commit() (err error)

Commit will commit the current mysql transaction and close off from further uses (if commit was successful). on commit error, transaction will not close off

func (*MySqlTransaction) ExecByNamedMapParam added in v1.1.8

func (t *MySqlTransaction) ExecByNamedMapParam(actionQuery string, args map[string]interface{}) MySqlResult

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 ?, 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. MySqlResult = represents the sql action result received (including error info if applicable)

func (*MySqlTransaction) ExecByOrdinalParams added in v1.1.8

func (t *MySqlTransaction) ExecByOrdinalParams(actionQuery string, args ...interface{}) MySqlResult

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 ?1, ?2 .. ?N, 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. MySqlResult = represents the sql action result received (including error info if applicable)

func (*MySqlTransaction) ExecByStructParam added in v1.1.8

func (t *MySqlTransaction) ExecByStructParam(actionQuery string, args interface{}) MySqlResult

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 ?, 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. MySqlResult = represents the sql action result received (including error info if applicable)

func (*MySqlTransaction) GetRowsByNamedMapParam added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 { if !rows.Next() { break } rows.Scan(&x, &y, etc) }
  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 (*MySqlTransaction) GetRowsByOrdinalParams added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 { if !rows.Next() { break } rows.Scan(&x, &y, etc) }
  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 (*MySqlTransaction) GetRowsByStructParam added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 { if !rows.Next() { break } rows.Scan(&x, &y, etc) }
  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 (*MySqlTransaction) GetScalarNullString added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 (*MySqlTransaction) GetScalarString added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 (*MySqlTransaction) GetSingleRow added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 (*MySqlTransaction) GetStruct added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 (*MySqlTransaction) GetStructSlice added in v1.1.8

func (t *MySqlTransaction) 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 ?, 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 (*MySqlTransaction) Rollback added in v1.1.8

func (t *MySqlTransaction) Rollback() (err error)

Rollback will rollback the current mysql transaction and close off from further uses (whether rollback succeeds or failures)

type QueryBuilder

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

QueryBuilder struct to help build sql queries (use named parameters instead of ordinal)

func (*QueryBuilder) Build

func (q *QueryBuilder) Build()

Build will create the output query string based on the bytes buffer appends

func (*QueryBuilder) ClearAll

func (q *QueryBuilder) ClearAll()

ClearAll will reset the query builder internal fields to init status

func (*QueryBuilder) ClearParams

func (q *QueryBuilder) ClearParams()

ClearParams will clear the parameters map in reset state

func (*QueryBuilder) ClearSQL

func (q *QueryBuilder) ClearSQL()

ClearSQL will clear the sql buffer and output only, leaving named map params intact

func (*QueryBuilder) Named

func (q *QueryBuilder) Named(paramName string, paramValue interface{})

Named will add or update a named parameter and its value into named params map

func (*QueryBuilder) Ordinal

func (q *QueryBuilder) Ordinal(ordinalParamValue interface{})

Ordinal will add an ordinal parameter value into ordinal params slice

func (*QueryBuilder) ParamsMap

func (q *QueryBuilder) ParamsMap() map[string]interface{}

ParamsMap returns the parameters map for use as input argument to the appropriate mysql query or exec actions

func (*QueryBuilder) ParamsSlice

func (q *QueryBuilder) ParamsSlice() []interface{}

ParamsSlice returns parameters slice for use as input argument to appropriate mysql, sqlite, sqlserver as its ordinal parameters

func (*QueryBuilder) SQL

func (q *QueryBuilder) SQL() string

SQL will return the built query string

func (*QueryBuilder) Set

func (q *QueryBuilder) Set(sqlPart string)

Set will append a sqlPart to the query builder buffer [ notes ]

  1. Ordinal Params a) MySql, SQLite Params = ? b) SQLServer Params = @p1, @p2, ...@pN
  2. Named Params a) MySql, SQLite, SQLServer Params = :xyz1, :xyz2, ...:xyzN

Jump to

Keyboard shortcuts

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