{"modulePath":"github.com/windhooked/pkg","version":"v0.0.0-20210530195812-02de94908f4f","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package dml\n\nPackage dml handles the SQL DML for super fast performance, type safety and convenience.\n\nAim: Allow a developer to easily modify a SQL query without type assertion of parts of the query. No reflection magic has been used so we must achieve type safety with code generation.\n\nThis package works only with MySQL and its derivates like MariaDB or Percona.\n\n### Abbreviations {#hdr-Abbreviations}\n\nDML ([https://en.wikipedia.org/wiki/Data\\_manipulation\\_language](https://en.wikipedia.org/wiki/Data_manipulation_language)) Select, Insert, Update and Delete.\n\nDDL ([https://en.wikipedia.org/wiki/Data\\_definition\\_language](https://en.wikipedia.org/wiki/Data_definition_language)) Create, Drop, Alter, and Rename.\n\nDCL ([https://en.wikipedia.org/wiki/Data\\_control\\_language](https://en.wikipedia.org/wiki/Data_control_language)) Grant and Revoke.\n\nCRUD ([https://en.wikipedia.org/wiki/Create,\\_read,\\_update\\_and\\_delete](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete)) Create, Read, Update and Delete.\n\n[https://mariadb.com/kb/en/mariadb/documentation/](https://mariadb.com/kb/en/mariadb/documentation/)\n\nPractical Guide to SQL Transaction Isolation: [https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html](https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html)\n\nNetSPI SQL Injection Wiki: [https://sqlwiki.netspi.com/](https://sqlwiki.netspi.com/)\n\nTODO(CyS) think about named locks: [https://news.ycombinator.com/item?id=14907679](https://news.ycombinator.com/item?id=14907679) [https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function\\_get-lock](https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock) Database locks should not be used by the average developer. Understand optimistic concurrency and use serializable isolation.\n\nTODO(CyS) refactor some parts of the code once Go implements generics ;-)\n\nTODO(CyS) implement usage of window functions:\n\n  - [https://mariadb.com/kb/en/library/window-functions/](https://mariadb.com/kb/en/library/window-functions/)\n  - [https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html](https://dev.mysql.com/doc/refman/8.0/en/window-functions-usage.html)\n  - [https://blog.statsbot.co/sql-window-functions-tutorial-b5075b87d129](https://blog.statsbot.co/sql-window-functions-tutorial-b5075b87d129)\n\n## Constants\n\n```go\nconst (\n\tColumnMapEntityReadAll     columnMapMode = 'a'\n\tColumnMapEntityReadSet     columnMapMode = 'r'\n\tColumnMapCollectionReadSet columnMapMode = 'R'\n\tColumnMapScan              columnMapMode = 'S' // can be used for both\n)\n```\nThose four constants represents the modes for ColumnMap.Mode. An upper case letter defines a collection and a lower case letter an entity.\n\n```go\nconst EnvDSN string = \"CS_DSN\"\n```\nEnvDSN is the name of the environment variable\n\n```go\nconst MaxIdentifierLength = 64\n```\nMaxIdentifierLength see [http://dev.mysql.com/doc/refman/5.7/en/identifiers.html](http://dev.mysql.com/doc/refman/5.7/en/identifiers.html)\n\n## Variables\n\n```go\nvar Now = nowSentinel{}\n```\nNow is a value that serializes to the current time. Should only be used to testing purposes. This exported variable can be removed at any time.\n\n```go\nvar Quoter = MysqlQuoter{\n\t// contains filtered or unexported fields\n}\n```\nQuoter at the quoter to use for quoting text; use Mysql quoting by default.\n\n## Functions\n\n```go\nfunc ExecValidateOneAffectedRow(res sql.Result, err error) error\n```\nExecValidateOneAffectedRow checks the sql.Result.RowsAffected if it returns one. If not returns an error of type NotValid. This function is useful for ExecContext function.\n\n```go\nfunc Interpolate(sql string) *ip\n```\nInterpolate takes a SQL byte slice with placeholders and a list of arguments to replace them with. It returns a blank string or an error if the number of placeholders does not match the number of arguments. Implements the ExpandPlaceHolders function.\n\n```go\nfunc IsValidIdentifier(objectName string) (err error)\n```\nIsValidIdentifier checks the permissible syntax for identifiers. Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers. ASCII: \\[0-9,a-z,A-Z$\\_] (basic Latin letters, digits 0-9, dollar, underscore) Max length 63 characters. It is recommended that you do not use names that begin with Me or MeN, where M and N are integers. For example, avoid using 1e as an identifier, because an expression such as 1e+3 is ambiguous. Depending on context, it might be interpreted as the expression 1e + 3 or as the number 1e+3.\n\nReturns 0 if the identifier is valid.\n\n[http://dev.mysql.com/doc/refman/5.7/en/identifiers.html](http://dev.mysql.com/doc/refman/5.7/en/identifiers.html)\n\n```go\nfunc MakeIdentifier(name string) id\n```\nMakeIdentifier creates a new quoted name with an optional alias \\`a\\`, which can be empty.\n\n```go\nfunc MySQLMessageFromError(err error) string\n```\nMySQLMessageFromError returns the textual message of the MySQL error. The error has been generated by the driver go-sql-driver/mysql. Returns an empty string if the type of error is not \\*mysql.MySQLError.\n\n```go\nfunc MySQLNumberFromError(err error) uint16\n```\nMySQLNumberFromError returns the error code number from an error. The error has been generated by the driver go-sql-driver/mysql. A list of error codes can be accessed here: [https://mariadb.com/kb/en/mariadb-error-codes/](https://mariadb.com/kb/en/mariadb-error-codes/) Returns 0 if the type of error is not \\*mysql.MySQLError.\n\n```go\nfunc WithContextQueryOptions(ctx context.Context, qo QueryOptions) context.Context\n```\nWithContextQueryOptions adds options for executing queries, mostly in generated code.\n\n## Types\n\n```go\ntype BuilderBase struct {\n\tTable id\n\t// IsUnsafe if set to true the functions AddColumn* will turn any\n\t// non valid identifier (not `{a-z}[a-z0-9$_]+`i) into an expression.\n\tIsUnsafe bool\n\t// contains filtered or unexported fields\n}\n```\nBuilderBase contains fields which all SQL query builder have in common, the same base. Exported for documentation reasons.\n\n```go\nfunc (bb BuilderBase) Clone() BuilderBase\n```\nClone creates a clone of the current object.\n\n```go\ntype BuilderConditional struct {\n\tJoins    Joins\n\tWheres   Conditions\n\tOrderBys ids\n\t// OrderByRandColumnName defines the column name of the single primary key\n\t// in a table to build the optimized ORDER BY RAND() JOIN clause.\n\tOrderByRandColumnName string\n\tLimitCount            uint64\n\tLimitValid            bool\n}\n```\nBuilderConditional defines base fields used in statements which can have conditional constraints like WHERE, JOIN, ORDER, etc. Exported for documentation reasons.\n\n```go\nfunc (b BuilderConditional) Clone() BuilderConditional\n```\nClone creates a new clone of the current object.\n\n```go\ntype ColumnMap struct {\n\n\t// CheckValidUTF8 if enabled checks if strings contains valid UTF-8 characters.\n\tCheckValidUTF8 bool\n\t// HasRows set to true if at least one row has been found.\n\tHasRows bool\n\t// Count increments on call to Scan.\n\tCount uint64\n\t// contains filtered or unexported fields\n}\n```\nColumnMap takes care that the table/view/identifiers are getting properly mapped to ColumnMapper interface. ColumnMap has two run modes either collect arguments from a type for running a SQL query OR to convert the sql.RawBytes into the desired final type. ColumnMap scans a \\*sql.Rows into a \\*sql.RawBytes slice without having a big memory overhead and not a single use of reflection. The conversion into the desired final type can happen without allocating of memory. It does not support streaming because neither database/sql does :-(  The method receiver functions have the same names as in type ColumnMap.\n\n```go\nfunc NewColumnMap(cap int, columns ...string) *ColumnMap\n```\nNewColumnMap exported for testing reasons.\n\n```go\nfunc (b *ColumnMap) Binary(enc interface {\n\tencoding.BinaryMarshaler\n\tencoding.BinaryUnmarshaler\n}) *ColumnMap\n```\nBinary allows to encode an object to its binary representation when arguments are requested and to decode a byte slice into its object when data is retrieved from the server. Use this function for GOB, Protocol Buffers, etc formats.\n\n```go\nfunc (b *ColumnMap) Bool(ptr *bool) *ColumnMap\n```\nBool reads a bool value and appends it to the arguments slice or assigns the bool value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Byte(ptr *[]byte) *ColumnMap\n```\nByte reads a \\[]byte value and appends it to the arguments slice or assigns the \\[]byte value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Column() string\n```\nColumn returns the current column name after calling \\`Next\\`.\n\n```go\nfunc (b *ColumnMap) Debug(w ioWriter) (err error)\n```\nDebug writes the column names with their values into \\`w\\`. The output format might change.\n\n```go\nfunc (b *ColumnMap) Decimal(ptr *null.Decimal) *ColumnMap\n```\nDecimal reads a Decimal value and appends it to the arguments slice or assigns the numeric value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Err() error\n```\nErr returns the delayed error from one of the scans and parsings. Function is idempotent.\n\n```go\nfunc (b *ColumnMap) Float64(ptr *float64) *ColumnMap\n```\nFloat64 reads a float64 value and appends it to the arguments slice or assigns the float64 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Int(ptr *int) *ColumnMap\n```\nInt reads an int value and appends it to the arguments slice or assigns the int value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Int16(ptr *int16) *ColumnMap\n```\nInt16 reads a int16 value and appends it to the arguments slice or assigns the int16 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Int16s(values ...int16) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Int32(ptr *int32) *ColumnMap\n```\nInt32 reads a int32 value and appends it to the arguments slice or assigns the int32 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Int32s(values ...int32) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Int64(ptr *int64) *ColumnMap\n```\nInt64 reads a int64 value and appends it to the arguments slice or assigns the int64 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Int64s(values ...int64) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Int8(ptr *int8) *ColumnMap\n```\nInt8 reads a int8 value and appends it to the arguments slice or assigns the int8 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Int8s(values ...int8) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Mode() (m columnMapMode)\n```\nMode returns a status byte of four different states. These states are getting used in the implementation of ColumnMapper. Each state represents a different action while scanning from the query or collecting arguments. ColumnMapper can be implemented by either a single type or a slice/map type. Slice or not slice requires different states. A primitive type must only handle mode ColumnMapEntityReadAll to return all requested fields. A slice type must handle additionally the cases ColumnMapEntityReadSet, ColumnMapCollectionReadSet and ColumnMapScan. See the examples. Documentation needs to be written better.\n\n```go\nfunc (b *ColumnMap) Next(fieldCount int) bool\n```\nNext moves the internal index to the next position. It may return false if during RawBytes scanning an error has occurred.\n\n```go\nfunc (b *ColumnMap) NullBool(ptr *null.Bool) *ColumnMap\n```\nNullBool reads a bool value and appends it to the arguments slice or assigns the bool value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullFloat64(ptr *null.Float64) *ColumnMap\n```\nNullFloat64 reads a float64 value and appends it to the arguments slice or assigns the float64 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullInt16(ptr *null.Int16) *ColumnMap\n```\nNullInt16 reads an int16 value and appends it to the arguments slice or assigns the int16 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullInt32(ptr *null.Int32) *ColumnMap\n```\nNullInt32 reads an int32 value and appends it to the arguments slice or assigns the int32 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullInt64(ptr *null.Int64) *ColumnMap\n```\nNullInt64 reads an int64 value and appends it to the arguments slice or assigns the int64 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullInt8(ptr *null.Int8) *ColumnMap\n```\nNullInt8 reads an int8 value and appends it to the arguments slice or assigns the int8 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullString(ptr *null.String) *ColumnMap\n```\nNullString reads a string value and appends it to the arguments slice or assigns the string value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullStrings(values ...null.String) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) NullTime(ptr *null.Time) *ColumnMap\n```\nNullTime reads a time value and appends it to the arguments slice or assigns the NullTime value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullUint16(ptr *null.Uint16) *ColumnMap\n```\nNullInt16 reads an int16 value and appends it to the arguments slice or assigns the int16 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullUint32(ptr *null.Uint32) *ColumnMap\n```\nNullInt32 reads an int32 value and appends it to the arguments slice or assigns the int32 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullUint64(ptr *null.Uint64) *ColumnMap\n```\nNullInt64 reads an int64 value and appends it to the arguments slice or assigns the int64 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) NullUint8(ptr *null.Uint8) *ColumnMap\n```\nNullInt8 reads an int8 value and appends it to the arguments slice or assigns the int8 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Scan(r *sql.Rows) error\n```\nScan calls rows.Scan and builds an internal stack of sql.RawBytes for further processing and type conversion.\n\nEach function for a specific type converts the underlying byte slice at the current applied index (see function Index) to the appropriate type. You can call as many times as you want the specific functions. The underlying byte slice value is valid until the next call to rows.Next, rows.Scan or rows.Close. See the example for further usages.\n\n```go\nfunc (b *ColumnMap) String(ptr *string) *ColumnMap\n```\nString reads a string value and appends it to the arguments slice or assigns the string value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Strings(values ...string) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Text(enc interface {\n\tencoding.TextMarshaler\n\tencoding.TextUnmarshaler\n}) *ColumnMap\n```\nText allows to encode an object to its text representation when arguments are requested and to decode a byte slice into its object when data is retrieved from the server. Use this function for JSON, XML, YAML, etc formats. This function can check for valid UTF8 characters, see field CheckValidUTF8.\n\n```go\nfunc (b *ColumnMap) Time(ptr *time.Time) *ColumnMap\n```\nTime reads a time.Time value and appends it to the arguments slice or assigns the time.Time value stored in sql.RawBytes to the pointer. See the documentation for function Scan. It supports all MySQL/MariaDB date/time types.\n\n```go\nfunc (b *ColumnMap) Times(values ...time.Time) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Uint(ptr *uint) *ColumnMap\n```\nUint reads an uint value and appends it to the arguments slice or assigns the uint value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Uint16(ptr *uint16) *ColumnMap\n```\nUint16 reads an uint16 value and appends it to the arguments slice or assigns the uint16 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Uint16s(values ...uint16) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Uint32(ptr *uint32) *ColumnMap\n```\nUint32 reads an uint32 value and appends it to the arguments slice or assigns the uint32 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Uint32s(values ...uint32) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Uint64(ptr *uint64) *ColumnMap\n```\nUint64 reads an uint64 value and appends it to the arguments slice or assigns the uint64 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Uint64s(values ...uint64) *ColumnMap\n```\n\n```go\nfunc (b *ColumnMap) Uint8(ptr *uint8) *ColumnMap\n```\nUint8 reads an uint8 value and appends it to the arguments slice or assigns the uint8 value stored in sql.RawBytes to the pointer. See the documentation for function Scan.\n\n```go\nfunc (b *ColumnMap) Uint8s(values ...uint8) *ColumnMap\n```\n\n```go\ntype ColumnMapper interface {\n\t// RowScan implementation must use function `Scan` to scan the values of the\n\t// query into its own type. See database/sql package for examples.\n\tMapColumns(rc *ColumnMap) error\n}\n```\nColumnMapper allows a type to load data from database query into its fields or return the fields values as arguments for a query. It's used in the rows.Next() for-loop. A ColumnMapper is usually a single record/row or in case of a slice a complete query result.\n\n```go\ntype Condition struct {\n\tAliased string\n\t// Left can contain either a valid identifier or an expression. Set field\n\t// `IsLeftExpression` to true to avoid quoting of the this field. Left can also\n\t// contain a string in the format `qualifier.identifier`.\n\tLeft string\n\t// Right defines the right hand side for an assignment which can be either a\n\t// single argument, multiple arguments in case of an expression, a sub\n\t// select or a name of a column.\n\tRight struct {\n\t\t// Column defines a column name to compare to. The column, with an\n\t\t// optional qualifier, gets quoted, in case IsExpression is false.\n\t\tColumn string\n\t\t// PlaceHolder can be a :named or the MySQL/MariaDB place holder\n\t\t// character `?`. If set, the current condition just acts as a place\n\t\t// holder for a prepared statement or an interpolation. In case of a\n\t\t// :named place holder for a prepared statement, the :named string gets\n\t\t// replaced with the `?`. The allowed characters are unicode letters and\n\t\t// digits.\n\t\tPlaceHolder string\n\n\t\t// Select adds a sub-select to the where statement. Column must be\n\t\t// either a column name or anything else which can handle the result of\n\t\t// a sub-select.\n\t\tSub *Select\n\t\t// IsExpression if true field `Column` gets treated as an expression.\n\t\t// Additionally the field Right.args will be read to extract any\n\t\t// given args.\n\t\tIsExpression bool\n\t\t// contains filtered or unexported fields\n\t}\n\t// Operator contains the comparison logic like LIKE, IN, GREATER, etc ...\n\t// defaults to EQUAL.\n\tOperator Op\n\t// IsLeftExpression if set to true, the field Left won't get quoted and\n\t// treated as an expression. Additionally the field Right.args will be\n\t// read to extract any given args.\n\tIsLeftExpression bool\n\t// Logical states how multiple WHERE statements will be connected.\n\t// Default to AND. Possible values are a=AND, o=OR, x=XOR, n=NOT\n\tLogical byte\n\t// Columns is a list of column names which get quoted during SQL statement\n\t// creation in the JOIN part for the USING syntax. Additionally used in ON\n\t// DUPLICATE KEY.\n\tColumns []string\n\t// contains filtered or unexported fields\n}\n```\nCondition implements a single condition often used in WHERE, ON, SET and ON DUPLICATE KEY UPDATE. Please use the helper functions instead of using this type directly.\n\n```go\nfunc Column(columnName string) *Condition\n```\nColumn adds a new condition.\n\n```go\nfunc Columns(columns ...string) *Condition\n```\nColumns add syntactic sugar to a JOIN or ON DUPLICATE KEY statement: In case of JOIN: The USING(column\\_list) clause names a list of columns that must exist in both tables. If tables a and b both contain columns c1, c2, and c3, the following join compares corresponding columns from the two tables:\n\n\ta LEFT JOIN b USING (c1, c2, c3)\n\nThe columns list gets quoted while writing the query string. In case of ON DUPLICATE KEY each column gets written like: \\`column\\`=VALUES(\\`column\\`). Any other field in \\*Condition gets ignored once field Columns has been set.\n\n```go\nfunc Expr(expression string) *Condition\n```\nExpr adds an unquoted SQL expression to a column, WHERE, HAVING, SET or ON DUPLICATE KEY statement. Each item of an expression gets written into the buffer without a separator.\n\n```go\nfunc ParenthesisClose() *Condition\n```\nParenthesisClose sets a closing parenthesis \")\". Mostly used for OR conditions in combination with AND conditions.\n\n```go\nfunc ParenthesisOpen() *Condition\n```\nParenthesisOpen sets an open parenthesis \"(\". Mostly used for OR conditions in combination with AND conditions.\n\n```go\nfunc SQLCase(value, defaultValue string, compareResult ...string) *Condition\n```\nSQLCase generates a CASE ... WHEN ... THEN ... ELSE ... END statement. \\`value\\` argument can be empty. defaultValue used in the ELSE part can also be empty and then won't get written. \\`compareResult\\` must be a balanced sliced where index \\`i\\` represents the case part and index \\`i+1\\` the result. If the slice is imbalanced the function assumes that the last item of compareResult should be printed as an alias. [https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator\\_case](https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case)\n\n```go\nfunc SQLIf(expression, true, false string) *Condition\n```\nSQLIf writes a SQL IF() expression.\n\n\tIF(expr1,expr2,expr3)\n\nIf expr1 is TRUE (expr1 \\\u003c\u003e 0 and expr1 \\\u003c\u003e NULL) then IF() returns expr2; otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used. Returns a \\[]string.\n\n```go\nfunc SQLIfNull(expression ...string) *Condition\n```\nSQLIfNull creates an IFNULL expression. Argument count can be either 1, 2 or 4. A single expression can contain a qualified or unqualified identifier. See the examples.\n\nIFNULL(expr1,expr2) If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.\n\n```go\nfunc (c *Condition) Alias(a string) *Condition\n```\nAlias assigns an alias name to the condition.\n\n```go\nfunc (c *Condition) And() *Condition\n```\nAnd sets the logical AND operator\n\n```go\nfunc (c *Condition) Between() *Condition\n```\n\n```go\nfunc (c *Condition) Bool(b bool) *Condition\n```\n\n```go\nfunc (c *Condition) Bools(b ...bool) *Condition\n```\n\n```go\nfunc (c *Condition) Bytes(p []byte) *Condition\n```\nBytes uses a byte slice for comparison. Providing a nil value returns a NULL type. Detects between valid UTF-8 strings and binary data. Later gets hex encoded.\n\n```go\nfunc (c *Condition) BytesSlice(p ...[]byte) *Condition\n```\n\n```go\nfunc (c *Condition) Clone() *Condition\n```\nClone creates a new clone of the current object. It resets the internal error field.\n\n```go\nfunc (c *Condition) Coalesce() *Condition\n```\n\n```go\nfunc (c *Condition) Column(col string) *Condition\n```\nColumn compares the left hand side with this column name.\n\n```go\nfunc (c *Condition) Decimal(d null.Decimal) *Condition\n```\n\n```go\nfunc (c *Condition) DriverValue(dv ...driver.Valuer) *Condition\n```\nDriverValue adds multiple of the same underlying values to the argument slice. When using different values, the last applied value wins and gets added to the argument slice. For example driver.Values of type \\`int\\` will result in \\[]int.\n\n```go\nfunc (c *Condition) DriverValues(dv ...driver.Valuer) *Condition\n```\nDriverValues adds each driver.Value as its own argument to the argument slice. It panics if the underlying type is not one of the allowed of interface driver.Valuer.\n\n```go\nfunc (c *Condition) Equal() *Condition\n```\n\n```go\nfunc (c *Condition) Exists() *Condition\n```\n\n```go\nfunc (c *Condition) Expr(expression string) *Condition\n```\nExpr compares the left hand side with the expression of the right hand side.\n\n```go\nfunc (c *Condition) Float64(f float64) *Condition\n```\n\n```go\nfunc (c *Condition) Float64s(f ...float64) *Condition\n```\n\n```go\nfunc (c *Condition) Greater() *Condition\n```\n\n```go\nfunc (c *Condition) GreaterOrEqual() *Condition\n```\n\n```go\nfunc (c *Condition) Greatest() *Condition\n```\n\n```go\nfunc (c *Condition) In() *Condition\n```\n\n```go\nfunc (c *Condition) Int(i int) *Condition\n```\n\n```go\nfunc (c *Condition) Int64(i int64) *Condition\n```\n\n```go\nfunc (c *Condition) Int64s(i ...int64) *Condition\n```\n\n```go\nfunc (c *Condition) Ints(i ...int) *Condition\n```\n\n```go\nfunc (c *Condition) Least() *Condition\n```\n\n```go\nfunc (c *Condition) Less() *Condition\n```\n\n```go\nfunc (c *Condition) LessOrEqual() *Condition\n```\n\n```go\nfunc (c *Condition) Like() *Condition\n```\n\n```go\nfunc (c *Condition) NamedArg(n string) *Condition\n```\nNamedArg treats a condition as a place holder. If set the MySQL/MariaDB placeholder \\`?\\` will be used and the provided name gets replaced. Records which implement ColumnMapper must also use this name. A dot in the name (for e.g. setting a qualifier) is not allowed.\n\n```go\nfunc (c *Condition) NotBetween() *Condition\n```\n\n```go\nfunc (c *Condition) NotEqual() *Condition\n```\n\n```go\nfunc (c *Condition) NotExists() *Condition\n```\n\n```go\nfunc (c *Condition) NotIn() *Condition\n```\n\n```go\nfunc (c *Condition) NotLike() *Condition\n```\n\n```go\nfunc (c *Condition) NotNull() *Condition\n```\n\n```go\nfunc (c *Condition) NotRegexp() *Condition\n```\n\n```go\nfunc (c *Condition) Null() *Condition\n```\n\n```go\nfunc (c *Condition) NullBool(nv null.Bool) *Condition\n```\n\n```go\nfunc (c *Condition) NullBools(nv ...null.Bool) *Condition\n```\n\n```go\nfunc (c *Condition) NullFloat64(nv null.Float64) *Condition\n```\n\n```go\nfunc (c *Condition) NullFloat64s(nv ...null.Float64) *Condition\n```\n\n```go\nfunc (c *Condition) NullInt64(nv null.Int64) *Condition\n```\n\n```go\nfunc (c *Condition) NullInt64s(nv ...null.Int64) *Condition\n```\n\n```go\nfunc (c *Condition) NullString(nv null.String) *Condition\n```\n\n```go\nfunc (c *Condition) NullStrings(nv ...null.String) *Condition\n```\n\n```go\nfunc (c *Condition) NullTime(nv null.Time) *Condition\n```\n\n```go\nfunc (c *Condition) NullTimes(nv ...null.Time) *Condition\n```\n\n```go\nfunc (c *Condition) Op(o Op) *Condition\n```\nOp sets a custom operator\n\n```go\nfunc (c *Condition) Or() *Condition\n```\nOr sets the logical OR operator\n\n```go\nfunc (c *Condition) PlaceHolder() *Condition\n```\nPlaceHolder treats a condition as a placeholder. Sets the database specific placeholder character \"?\". Mostly used in prepared statements and for interpolation.\n\n```go\nfunc (c *Condition) PlaceHolders(count int) *Condition\n```\nPlaceHolders treats a condition as a string with multiple placeholders. Sets the database specific placeholder character \"?\" as many times as specified in variable count. Mostly used in prepared statements and for interpolation and when using the IN clause.\n\n```go\nfunc (c *Condition) Regexp() *Condition\n```\n\n```go\nfunc (c *Condition) SQLCase(value, defaultValue string, compareResult ...string) *Condition\n```\nSQLCase see description at function SQLCase.\n\n```go\nfunc (c *Condition) SQLIfNull(expression ...string) *Condition\n```\nSQLIfNull see description at function SQLIfNull.\n\n```go\nfunc (c *Condition) SpaceShip() *Condition\n```\n\n```go\nfunc (c *Condition) Str(s string) *Condition\n```\n\n```go\nfunc (c *Condition) Strs(s ...string) *Condition\n```\n\n```go\nfunc (c *Condition) Sub(sub *Select) *Condition\n```\nSub compares the left hand side with the SELECT of the right hand side. Choose the appropriate comparison operator, default is IN.\n\n```go\nfunc (c *Condition) Time(t time.Time) *Condition\n```\n\n```go\nfunc (c *Condition) Times(t ...time.Time) *Condition\n```\n\n```go\nfunc (c *Condition) Tuples() *Condition\n```\nTuples allows to build a query string for tuple comparison.\n\n\tSELECT * FROM catalog_product_index_decimal_idx WHERE\n\t(entity_id,attribute_id,store_id,source_id) IN (\n\t\t(4,4,4,4), (3,3,3,3), (dynamical values)\n\t);\n\nSee test ... TBC\n\n```go\nfunc (c *Condition) Uint64(i uint64) *Condition\n```\n\n```go\nfunc (c *Condition) Uint64s(i ...uint64) *Condition\n```\n\n```go\nfunc (c *Condition) Values() *Condition\n```\nValues only usable in case for ON DUPLICATE KEY to generate a statement like:\n\n\tcolumn=VALUES(column)\n\n```go\nfunc (c *Condition) Xor() *Condition\n```\n\n```go\ntype Conditions []*Condition\n```\nConditions provides a list where the left hand side gets an assignment from the right hand side. Mostly used in\n\n```go\nfunc (cs Conditions) Clone() Conditions\n```\nClone creates a clone of the current object.\n\n```go\nfunc (cs *Conditions) Reset() Conditions\n```\nReset resets the slice to length zero and retains the allocated memory.\n\n```go\ntype Conn struct {\n\tDB *sql.Conn\n\t// contains filtered or unexported fields\n}\n```\nConn represents a single database session rather a pool of database sessions. Prefer running queries from DB unless there is a specific need for a continuous single database session.\n\nA Conn must call Close to return the connection to the database pool and may do so concurrently with a running query.\n\nAfter a call to Close, all operations on the connection fail with ErrConnDone.\n\n```go\nfunc (c *Conn) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)\n```\nBeginTx starts a transaction.\n\nThe provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.\n\nThe provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.\n\n```go\nfunc (c *Conn) CacheKeyExists(cacheKey string) bool\n```\nCacheKeyExists returns true if a given key already exists.\n\n```go\nfunc (c *Conn) Close() error\n```\nClose returns the connection to the connection pool. All operations after a Close will return with ErrConnDone. Close is safe to call concurrently with other operations and will block until all other operations finish. It may be useful to first cancel any used context and then call close directly after. It logs the time taken, if a logger has been set with Info logging enabled.\n\n```go\nfunc (c *Conn) Transaction(ctx context.Context, opts *sql.TxOptions, f func(*Tx) error) error\n```\nTransaction is a helper method that will automatically BEGIN a transaction and COMMIT or ROLLBACK once the supplied functions are done executing.\n\n\t     if err := con.Transaction(\n\t\t\t\tfunc(tx *dml.Tx) error {\n\t         \t// SQL\n\t\t\t        return nil\n\t     \t},\n\t\t\t); err != nil{\n\t          panic(err.Error()) // you could gracefully handle the error also\n\t     }\n\nIt logs the time taken, if a logger has been set with Debug logging enabled. The provided context gets used only for starting the transaction.\n\n```go\nfunc (c *Conn) WithCacheKey(cacheKey string, opts ...DBRFunc) *DBR\n```\nWithCacheKey creates a DBR object from a cached query.\n\n```go\nfunc (c *Conn) WithPrepare(ctx context.Context, qb QueryBuilder, opts ...DBRFunc) *DBR\n```\nWithPrepare adds the query to the cache and returns a prepared statement which must be closed after its use.\n\n```go\nfunc (c *Conn) WithPrepareCacheKey(ctx context.Context, cacheKey string, opts ...DBRFunc) *DBR\n```\nWithPrepareCacheKey creates a DBR object from a prepared cached query. The statement must be closed after its use.\n\n```go\nfunc (c *Conn) WithQueryBuilder(qb QueryBuilder, opts ...DBRFunc) *DBR\n```\nWithQueryBuilder creates a new DBR for handling the arguments with the assigned connection and builds the SQL string. The returned arguments and errors of the QueryBuilder will be forwarded to the DBR type. It generates a unique cache key based on the SQL string. The cache key can be retrieved via DBR object.\n\n```go\ntype ConnPool struct {\n\n\t// DB must be set using one of the ConnPoolOption function.\n\tDB *sql.DB\n\t// contains filtered or unexported fields\n}\n```\nConnPool at a connection to the database with an EventReceiver to send events, errors, and timings to\n\n```go\nfunc MustConnectAndVerify(opts ...ConnPoolOption) *ConnPool\n```\nMustConnectAndVerify at like NewConnPool but it verifies the connection and panics on errors.\n\n```go\nfunc NewConnPool(opts ...ConnPoolOption) (*ConnPool, error)\n```\nNewConnPool instantiates a ConnPool for a given database/sql connection and event receiver. An invalid driver name causes a NotImplemented error to be returned. You can either apply a DSN or a pre configured \\*sql.DB type. For full UTF-8 support you must set the charset in the SQL driver to utf8mb4.\n\nQuote: [http://techblog.en.klab-blogs.com/archives/31093990.html](http://techblog.en.klab-blogs.com/archives/31093990.html) Recommended sql.DB Settings:\n\nDefinitely set SetMaxOpenConns(). You need this in order to stop opening new connections and sending queries when the load is high and server response slows. If possible, it’s good to do a load test and set the minimum number of connections to ensure maximum throughput, but even if you can’t do that, you should decide on a reasonably appropriate number based on max\\_connection and the number of cores.\n\nConfigure SetMaxIdleConns() to be equal to or higher than SetMaxOpenConns(). Let SetConnMaxLifetime handle closing idle connections.\n\nSet SetConnMaxLifetime() to be the maximum number of connections x 1 second. In most environments, a load of one connection per second won’t be a problem. When you want to set it for longer than an hour, discuss that with an infrastructure/network engineer.\n\n```go\nfunc (c *ConnPool) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)\n```\nBeginTx starts a transaction.\n\nThe provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.\n\nThe provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.\n\nPractical Guide to SQL Transaction Isolation: [https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html](https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html)\n\n```go\nfunc (c *ConnPool) CacheKeyExists(cacheKey string) bool\n```\nCacheKeyExists returns true if a given key already exists.\n\n```go\nfunc (c *ConnPool) CachedQueries() map[string]string\n```\n\n```go\nfunc (c *ConnPool) Close() (err error)\n```\nClose closes the database, releasing any open resources.\n\nIt is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines. It logs the time taken, if a logger has been set with Info logging enabled. It runs the ConnPoolOption, marked for running before close.\n\n```go\nfunc (c *ConnPool) Conn(ctx context.Context) (*Conn, error)\n```\nConn returns a single connection by either opening a new connection or returning an existing connection from the connection pool. Conn will block until either a connection is returned or ctx is canceled. Queries run on the same Conn will be run in the same database session.\n\nEvery Conn must be returned to the database pool after use by calling Conn.Close.\n\n```go\nfunc (c *ConnPool) DSN() string\n```\nDSN returns the formatted DSN. Will leak the password.\n\n```go\nfunc (c *ConnPool) DeregisterByCacheKey(cacheKey string) error\n```\n\n```go\nfunc (c *ConnPool) RegisterByQueryBuilder(cacheKeyQB map[string]QueryBuilder) error\n```\nRegisterByQueryBuilder adds the SQL queries to the local internal cache. The cacheKeyQB map gets iterated in alphabetical order.\n\n```go\nfunc (c *ConnPool) Schema() string\n```\nSchema returns the database name as provided in the DSN. Returns an empty string if no DSN has been set.\n\n```go\nfunc (c *ConnPool) Transaction(ctx context.Context, opts *sql.TxOptions, fn func(*Tx) error) (err error)\n```\nTransaction is a helper method that will automatically BEGIN a transaction and COMMIT or ROLLBACK once the supplied functions are done executing.\n\n\t     if err := con.Transaction(\n\t\t\t\tfunc(tx *dml.Tx) error {\n\t         \t// SQL\n\t\t\t        return nil\n\t     \t}\n\t\t\t); err != nil{\n\t          panic(err.Error()) // you could gracefully handle the error also\n\t     }\n\nIt logs the time taken, if a logger has been set with Debug logging enabled. The provided context gets used only for starting the transaction.\n\n```go\nfunc (c *ConnPool) WithCacheKey(cacheKey string, opts ...DBRFunc) *DBR\n```\nWithCacheKey creates a DBR object from a cached query.\n\n```go\nfunc (c *ConnPool) WithDisabledForeignKeyChecks(ctx context.Context, callBack func(*Conn) error) (err error)\n```\nWithDisabledForeignKeyChecks runs the callBack with disabled foreign key checks in a dedicated connection session. Foreign key checks are getting automatically re-enabled. The context is used to disable and enable the FK check.\n\n```go\nfunc (c *ConnPool) WithPrepare(ctx context.Context, qb QueryBuilder, opts ...DBRFunc) *DBR\n```\nPrepare executes the statement represented by the Select to create a prepared statement. It returns a custom statement type or an error if there was one. Provided arguments or records in the Select are getting ignored. The provided context is used for the preparation of the statement, not for the execution of the statement. The returned DBR is not safe for concurrent use, despite the underlying \\*sql.Stmt is. It generates a unique cache key based on the SQL string. The cache key can be retrieved via DBR object.\n\n```go\nfunc (c *ConnPool) WithPrepareCacheKey(ctx context.Context, cacheKey string, opts ...DBRFunc) *DBR\n```\nWithPrepareCacheKey creates a DBR object from a prepared cached query.\n\n```go\nfunc (c *ConnPool) WithQueryBuilder(qb QueryBuilder, opts ...DBRFunc) *DBR\n```\nWithQueryBuilder creates a new DBR for handling the arguments with the assigned connection and builds the SQL string. The returned arguments and errors of the QueryBuilder will be forwarded to the DBR type. It generates a unique cache key based on the SQL string. The cache key can be retrieved via DBR object.\n\n```go\ntype ConnPoolOption struct {\n\n\t// WithUniqueIDFn applies a unique ID generator function without an applied\n\t// logger as in WithLogger. For more details see WithLogger function.\n\t// Sort Order 8.\n\tUniqueIDFn func() string\n\t// TableNameMapper maps the old name in the DML query to a new name. E.g.\n\t// for adding a prefix and/or a suffix.\n\tTableNameMapper func(oldName string) (newName string)\n\t// OptimisticLock is enabled all queries with Exec will have a `version` field.\n\t// UPDATE user SET ..., version = version + 1 WHERE id = ? AND version = ?\n\t// TODO implement OptimisticLock\n\tOptimisticLock bool\n\t// OptimisticLockFieldName custom global column name, defaults to `version\n\t// uint64`.\n\t// TODO implement OptimisticLock\n\tOptimisticLockColumnName string\n\t// contains filtered or unexported fields\n}\n```\nConnPoolOption can be used at an argument in NewConnPool to configure a connection.\n\n```go\nfunc WithCreateDatabase(ctx context.Context, databaseName string) ConnPoolOption\n```\nWithCreateDatabase creates the database and sets the utf8mb4 option. It does not drop the database. If databaseName is empty, the DB name gets derived from the DSN.\n\n```go\nfunc WithDB(db *sql.DB) ConnPoolOption\n```\nWithDB sets the DB value to an existing connection. Mainly used for testing. Does not support DriverCallBack.\n\n```go\nfunc WithDSN(dsn string) ConnPoolOption\n```\nWithDSN sets the data source name for a connection. Second argument DriverCallBack adds a low level call back function on MySQL driver level to create a a new instrumented driver. No need to call \\`sql.Register\\`! If the DSN contains as database name the word \"random\", then the name will be \"test\\_\\[unixtimestamp\\_nano]\", especially useful in tests. The environment variable SKIP\\_CLEANUP=1 skips dropping the test database.\n\n\t$ SKIP_CLEANUP=1 go test -v -run=TestX\n\n```go\nfunc WithDSNFromEnv(dsnEnvName string) ConnPoolOption\n```\nWithDSNFromEnv loads the DSN string from an environment variable named by \\`dsnEnvName\\`. If \\`dsnEnvName\\` is empty, then it falls back to the environment variable name of constant \\`EnvDSN\\`.\n\n```go\nfunc WithDriverCallBack(cb DriverCallBack) ConnPoolOption\n```\nWithDriverCallBack allows low level query logging and argument inspection.\n\n```go\nfunc WithExecSQLOnConnClose(ctx context.Context, sqlQuery ...string) ConnPoolOption\n```\nWithExecSQLOnConnClose runs the sqlQuery arguments before closing a DB connection. More than one queries are running in a transaction, a single query not.\n\n```go\nfunc WithExecSQLOnConnOpen(ctx context.Context, sqlQuery ...string) ConnPoolOption\n```\nWithExecSQLOnConnOpen runs the sqlQuery arguments after successful opening a DB connection. More than one queries are running in a transaction, a single query not.\n\n```go\nfunc WithLogger(l log.Logger, uniqueIDFn func() string) ConnPoolOption\n```\nWithLogger sets the customer logger to be used across the package. The logger gets inherited to type Conn and Tx and also to all statement types. Each heredity creates new fields as a prefix. Argument \\`uniqueID\\` generates for each heredity a new unique ID for tracing in Info logging. Those IDs will be assigned to a new connection or a new statement. The function signature is equal to fmt.Stringer so one can use for example:\n\n\tuuid.NewV4().String\n\nThe returned unique ID from \\`uniqueIDFn\\` gets used in logging and inserted as a comment into the SQL string for tracing in server log files and PROCESS LIST. The returned string must not contain the comment-end-termination pattern: \\`\\*/\\`. The \\`uniqueIDFn\\` must be thread safe.\n\n```go\nfunc WithSetNamesUTF8MB4() ConnPoolOption\n```\nWithSetNamesUTF8MB4 sets the utf8mb4 charset and collation.\n\n```go\nfunc WithVerifyConnection(ctx context.Context, pingRetry time.Duration) ConnPoolOption\n```\nWithVerifyConnection checks if the connection to the server is valid and can be established.\n\n```go\ntype DBR struct {\n\n\t// DB can be either a *sql.DB (connection pool), a *sql.Conn (a single\n\t// dedicated database session) or a *sql.Tx (an in-progress database\n\t// transaction).\n\tDB QueryExecPreparer\n\n\t// Options like enable interpolation or expanding placeholders.\n\tOptions uint\n\n\t// ResultCheckFn custom function to check for affected rows or last insert ID.\n\t// Only used in generated code.\n\tResultCheckFn func(tableName string, expectedAffectedRows int, res sql.Result, err error) error\n\n\t// QualifiedColumnsAliases allows to overwrite the internal qualified\n\t// columns slice with custom names. Only in the use case when records are\n\t// applied. The list of column names in `QualifiedColumnsAliases` gets\n\t// passed to the ColumnMapper and back to the provided object. The\n\t// `QualifiedColumnsAliases` slice must have the same length as the\n\t// qualified columns slice. The order of the alias names must be in the same\n\t// order as the qualified columns or as the placeholders occur.\n\tQualifiedColumnsAliases []string\n\tOrderBys                ids\n\tLimitValid              bool\n\tOffsetValid             bool\n\tLimitCount              uint64\n\tOffsetCount             uint64\n\t// contains filtered or unexported fields\n}\n```\nDBR is a DataBaseRunner which prepares the SQL string from a DML type, collects and build a list of arguments for later sending and execution in the database server. Arguments are collections of primitive types or slices of primitive types. An DBR type acts like a prepared statement. In fact it can contain under the hood different connection types. DBR is optimized for reuse and allow saving memory allocations. It can't be used in concurrent context.\n\n```go\nfunc (bc *DBR) CacheKey() string\n```\nCacheKey returns the cache key used when registering a SQL statement with the ConnPool.\n\n```go\nfunc (a *DBR) Close() error\n```\nClose tries to close the underlying DB connection. Useful in cases of prepared statements. If the underlying DB connection does not implement io.Closer, nothing will happen.\n\n```go\nfunc (a *DBR) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)\n```\nExecContext executes the statement represented by the Update/Insert object. It returns the raw database/sql Result or an error if there was one. Regarding LastInsertID(): If you insert multiple rows using a single INSERT statement, LAST\\_INSERT\\_ID() returns the value generated for the first inserted row only. The reason for this at to make it possible to reproduce easily the same INSERT statement against some other server. If a record resp. and object implements the interface LastInsertIDAssigner then the LastInsertID gets assigned incrementally to the objects. Pro tip: you can use function ExecValidateOneAffectedRow to check if the underlying SQL statement has affected only one row.\n\n```go\nfunc (a *DBR) ExpandPlaceHolders() *DBR\n```\nExpandPlaceHolders repeats the place holders with the provided argument count. If the amount of arguments does not match the number of place holders, a mismatch error gets returned.\n\n\tExpandPlaceHolders(\"SELECT * FROM table WHERE id IN (?) AND status IN (?)\", Int(myIntSlice...), String(myStrSlice...))\n\nGets converted to:\n\n\tSELECT * FROM table WHERE id IN (?,?) AND status IN (?,?,?)\n\nThe place holders are of course depending on the values in the Arg\\* functions. This function should be generally used when dealing with prepared statements or interpolation.\n\n```go\nfunc (a *DBR) Interpolate() *DBR\n```\nInterpolate if set stringyfies the arguments into the SQL string and returns pre-processed SQL command when calling the function ToSQL. Not suitable for prepared statements. ToSQLs second argument \\`args\\` will then be nil.\n\n```go\nfunc (a *DBR) IterateParallel(ctx context.Context, concurrencyLevel int, callBack func(*ColumnMap) error, args ...interface{}) (err error)\n```\nIterateParallel starts a number of workers as defined by variable concurrencyLevel and executes the query. Each database row gets evenly distributed to the workers. The callback function gets called within a worker. concurrencyLevel should be the number of CPUs. You should use this function when you expect to process large amount of rows returned from a query.\n\n```go\nfunc (a *DBR) IterateSerial(ctx context.Context, callBack func(*ColumnMap) error, args ...interface{}) (err error)\n```\nIterateSerial iterates in serial order over the result set by loading one row each iteration and then discarding it. Handles records one by one. The context gets only used in the Query function.\n\n```go\nfunc (a *DBR) Limit(offset, limit uint64) *DBR\n```\nLimit sets a LIMIT clause for the statement; overrides any existing LIMIT. This LIMIT clause gets appended to the current internal cached SQL string independently if the SQL statement supports it or not or if there exists already a LIMIT clause.\n\n```go\nfunc (a *DBR) Load(ctx context.Context, s ColumnMapper, args ...interface{}) (rowCount uint64, err error)\n```\nLoad loads data from a query into an object. Load can load a single row or multiple-rows. It checks on top if ColumnMapper \\`s\\` implements io.Closer, to call the custom close function. This is useful for e.g. unlocking a mutex.\n\n```go\nfunc (a *DBR) LoadDecimal(ctx context.Context, args ...interface{}) (nv null.Decimal, found bool, err error)\n```\nLoadDecimal executes the query and returns the first row parsed into the current type. \\`Found\\` might be false if there are no matching rows.\n\n```go\nfunc (a *DBR) LoadFloat64s(ctx context.Context, dest []float64, args ...interface{}) (_ []float64, err error)\n```\nLoadFloat64s executes the query and returns the values appended to slice dest. It ignores and skips NULL values.\n\n```go\nfunc (a *DBR) LoadInt64s(ctx context.Context, dest []int64, args ...interface{}) (_ []int64, err error)\n```\nLoadInt64s executes the query and returns the values appended to slice dest. It ignores and skips NULL values.\n\n```go\nfunc (a *DBR) LoadNullFloat64(ctx context.Context, args ...interface{}) (nv null.Float64, found bool, err error)\n```\nLoadNullFloat64 executes the query and returns the first row parsed into the current type. \\`Found\\` might be false if there are no matching rows.\n\n```go\nfunc (a *DBR) LoadNullInt64(ctx context.Context, args ...interface{}) (nv null.Int64, found bool, err error)\n```\nLoadNullInt64 executes the query and returns the first row parsed into the current type. \\`Found\\` might be false if there are no matching rows.\n\n```go\nfunc (a *DBR) LoadNullString(ctx context.Context, args ...interface{}) (nv null.String, found bool, err error)\n```\nLoadNullString executes the query and returns the first row parsed into the current type. \\`Found\\` might be false if there are no matching rows.\n\n```go\nfunc (a *DBR) LoadNullTime(ctx context.Context, args ...interface{}) (nv null.Time, found bool, err error)\n```\nLoadNullTime executes the query and returns the first row parsed into the current type. \\`Found\\` might be false if there are no matching rows.\n\n```go\nfunc (a *DBR) LoadNullUint64(ctx context.Context, args ...interface{}) (nv null.Uint64, found bool, err error)\n```\nLoadNullUint64 executes the query and returns the first row parsed into the current type. \\`Found\\` might be false if there are no matching rows. This function with ptr type uint64 comes in handy when performing a COUNT(\\*) query. See function \\`Select.Count\\`.\n\n```go\nfunc (a *DBR) LoadStrings(ctx context.Context, dest []string, args ...interface{}) (_ []string, err error)\n```\nLoadStrings executes the query and returns the values appended to slice dest. It ignores and skips NULL values.\n\n```go\nfunc (a *DBR) LoadUint64s(ctx context.Context, dest []uint64, args ...interface{}) (_ []uint64, err error)\n```\nLoadUint64s executes the query and returns the values appended to slice dest. It ignores and skips NULL values.\n\n```go\nfunc (a *DBR) OrderBy(columns ...string) *DBR\n```\nOrderBy appends columns to the ORDER BY statement for ascending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. This ORDER BY clause gets appended to the current internal cached SQL string independently if the SQL statement supports it or not or if there exists already an ORDER BY clause. A column name can also contain the suffix words \" ASC\" or \" DESC\" to indicate the sorting. This avoids using the method OrderByDesc when sorting certain columns descending.\n\n```go\nfunc (a *DBR) OrderByDesc(columns ...string) *DBR\n```\nOrderByDesc appends columns to the ORDER BY statement for descending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. This ORDER BY clause gets appended to the current internal cached SQL string independently if the SQL statement supports it or not or if there exists already an ORDER BY clause.\n\n```go\nfunc (a *DBR) Paginate(page, perPage uint64) *DBR\n```\nPaginate sets LIMIT/OFFSET for the statement based on the given page/perPage Assumes page/perPage are valid. Page and perPage must be \u003e= 1\n\n```go\nfunc (a *DBR) Prepare(ctx context.Context) (*DBR, error)\n```\nPrepare generates a prepared statement from the underlying SQL and assigns the \\*sql.Stmt to the DB field. It fails if it contains an already prepared statement.\n\n```go\nfunc (a *DBR) PreviousError() error\n```\nPreviousError returns the previous error. Mostly used for testing.\n\n```go\nfunc (a *DBR) QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error)\n```\nQueryContext traditional way of the databasel/sql package.\n\n```go\nfunc (a *DBR) QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row\n```\nQueryRowContext traditional way of the databasel/sql package.\n\n```go\nfunc (a *DBR) Reset() *DBR\n```\nReset resets the internal slices for new usage retaining the already allocated memory. Reset gets called automatically in many Load\\* functions. In case of an INSERT statement, Reset triggers a new build of the VALUES part. This function must be called when the number of argument changes for an INSERT query.\n\n```go\nfunc (a *DBR) TestWithArgs(args ...interface{}) QueryBuilder\n```\nTestWithArgs returns a QueryBuilder with resolved arguments. Mostly used for testing and in examples to skip the calls to ExecContext or QueryContext. Every 2nd call arguments are getting interpolated.\n\n```go\nfunc (a *DBR) ToSQL() (string, []interface{}, error)\n```\nToSQL generates the SQL string.\n\n```go\nfunc (a *DBR) TupleCount(tuples, rows uint) *DBR\n```\nTupleCount sets the amount of tuples and its rows. Only needed in case of a prepared statement with tuples. WHERE clause contains:\n\n\tdml.Columns(\"entity_id\", \"attribute_id\", \"store_id\", \"source_id\").In().Tuples(),\n\nand set to 4,2 because 4 columns with two rows = 8 arguments.\n\n\tTupleCount(4,2)\n\nresults into\n\n\tWHERE ((`entity_id`, `attribute_id`, `store_id`, `source_id`) IN ((?,?,?,?),(?,?,?,?)))\n\n```go\nfunc (bc *DBR) WithCacheKey(cacheKey string) *DBR\n```\nWithCacheKey allows to set a custom cache key in generated code to change the underlying SQL query.\n\n```go\nfunc (a *DBR) WithDB(db QueryExecPreparer) *DBR\n```\nWithDB sets the database query object.\n\n```go\nfunc (a *DBR) WithPreparedStmt(stmt *sql.Stmt) *DBR\n```\nWithPreparedStmt uses a SQL statement as DB connection.\n\n```go\nfunc (a *DBR) WithQualifiedColumnsAliases(aliases ...string) *DBR\n```\nWithQualifiedColumnsAliases for documentation please see: DBR.QualifiedColumnsAliases.\n\n```go\nfunc (a *DBR) WithTx(tx *Tx) *DBR\n```\nWithTx sets the transaction query executor and the logger to run this query within a transaction.\n\n```go\ntype DBRFunc func(*DBR)\n```\nDBRFunc defines a call back function used in other packages to allow modifications to the DBR object.\n\n```go\nfunc DBRValidateMinAffectedRow(minExpectedRows int64) DBRFunc\n```\nDBRValidateMinOneAffectedRow is an option argument to provide a basic helper function to check that at least one row has been deleted.\n\n```go\nfunc DBRWithTx(tx *Tx, opts []DBRFunc) []DBRFunc\n```\n\n```go\ntype Delete struct {\n\tBuilderBase\n\tBuilderConditional\n\t// MultiTables specifies the additional tables to delete from. Use function\n\t// `FromTables` to conveniently set it.\n\tMultiTables ids\n\t// Returning allows from MariaDB 10.0.5, it is possible to return a\n\t// resultset of the deleted rows for a single table to the client by using\n\t// the syntax DELETE ... RETURNING select_expr [, select_expr2 ...]] Any of\n\t// SQL expression that can be calculated from a single row fields is\n\t// allowed. Subqueries are allowed. The AS keyword is allowed, so it is\n\t// possible to use aliases. The use of aggregate functions is not allowed.\n\t// RETURNING cannot be used in multi-table DELETEs.\n\tReturning *Select\n}\n```\nDelete contains the clauses for a DELETE statement.\n\nInnoDB Tables: If you are deleting many rows from a large table, you may exceed the lock table size for an InnoDB table. To avoid this problem, or simply to minimize the time that the table remains locked, the following strategy (which does not use DELETE at all) might be helpful:\n\nSelect the rows not to be deleted into an empty table that has the same structure as the original table:\n\n\tINSERT INTO t_copy SELECT * FROM t WHERE ... ;\n\nUse RENAME TABLE to atomically move the original table out of the way and rename the copy to the original name:\n\n\tRENAME TABLE t TO t_old, t_copy TO t;\n\nDrop the original table:\n\n\tDROP TABLE t_old;\n\nNo other sessions can access the tables involved while RENAME TABLE executes, so the rename operation is not subject to concurrency problems.\n\n```go\nfunc NewDelete(from string) *Delete\n```\nNewDelete creates a new Delete object.\n\n```go\nfunc (b *Delete) Alias(alias string) *Delete\n```\nAlias sets an alias for the table name.\n\n```go\nfunc (b *Delete) Clone() *Delete\n```\nClone creates a clone of the current object, leaving fields DB and Log untouched.\n\n```go\nfunc (b *Delete) CrossJoin(table id, onConditions ...*Condition) *Delete\n```\nCrossJoin creates a CROSS join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Delete) FromTables(tables ...string) *Delete\n```\nFromTables specifies additional tables to delete from besides the default table.\n\n```go\nfunc (b *Delete) Join(table id, onConditions ...*Condition) *Delete\n```\nJoin creates an INNER join construct. By default, the onConditions are glued together with AND. Same Source and Target Table: Until MariaDB 10.3.1, deleting from a table with the same source and target was not possible. From MariaDB 10.3.1, this is now possible. For example:\n\n\tDELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0);\n\n```go\nfunc (b *Delete) LeftJoin(table id, onConditions ...*Condition) *Delete\n```\nLeftJoin creates a LEFT join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Delete) Limit(limit uint64) *Delete\n```\nLimit sets a LIMIT clause for the statement; overrides any existing LIMIT\n\n```go\nfunc (b *Delete) OrderBy(columns ...string) *Delete\n```\nOrderBy appends columns to the ORDER BY statement for ascending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a DELETE, the server sorts arguments using only the initial number of bytes indicated by the max\\_sort\\_length system variable. A column name can also contain the suffix words \" ASC\" or \" DESC\" to indicate the sorting. This avoids using the method OrderByDesc when sorting certain columns descending.\n\n```go\nfunc (b *Delete) OrderByDesc(columns ...string) *Delete\n```\nOrderByDesc appends columns to the ORDER BY statement for descending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a DELETE, the server sorts arguments using only the initial number of bytes indicated by the max\\_sort\\_length system variable.\n\n```go\nfunc (b *Delete) OuterJoin(table id, onConditions ...*Condition) *Delete\n```\nOuterJoin creates an OUTER join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Delete) RightJoin(table id, onConditions ...*Condition) *Delete\n```\nRightJoin creates a RIGHT join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Delete) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (b *Delete) ToSQL() (string, []interface{}, error)\n```\nToSQL generates the SQL string and might caches it internally, if not disabled. The returned interface slice is always nil.\n\n```go\nfunc (b *Delete) Unsafe() *Delete\n```\nUnsafe see BuilderBase.IsUnsafe which weakens security when building the SQL string. This function must be called before calling any other function.\n\n```go\nfunc (b *Delete) Where(wf ...*Condition) *Delete\n```\nWhere appends a WHERE clause to the statement whereSQLOrMap can be a string or map. If it'ab a string, args wil replaces any places holders.\n\n```go\nfunc (b *Delete) WithDBR(db QueryExecPreparer) *DBR\n```\n\n```go\ntype DriverCallBack func(fnName string) func(err error, query string, args []driver.NamedValue) error\n```\nDriverCallBack defines the call back signature used in every driver function. The returned function gets called in a defer. \\`fnName\\` states the name of the parent function like PrepareContext or Query, etc. The call to the first function can be used to e.g. start a timer. The call to second function can log the query and its args and also measure the time spend. The error as first argument in the returned function comes from the parent called function and should be returned or wrapped into a new one. \\`namedArgs\\` contains the, sometimes, named arguments. It can also be nil. context.Context can be added later.\n\n```go\ntype EventFlag uint8\n```\nEventFlag describes where and when an event might get dispatched.\n\n```go\nconst (\n\tEventFlagUndefined EventFlag = iota\n\tEventFlagBeforeSelect\n\tEventFlagAfterSelect\n\tEventFlagBeforeInsert\n\tEventFlagAfterInsert\n\tEventFlagBeforeUpdate\n\tEventFlagAfterUpdate\n\tEventFlagBeforeUpsert\n\tEventFlagAfterUpsert\n\tEventFlagBeforeDelete\n\tEventFlagAfterDelete\n\tEventFlagMax // indicates maximum events available. Might change without notice.\n)\n```\nEventFlag constants define the concrete locations of dispatched events.\n\n```go\ntype Execer interface {\n\t// ExecContext executes a query that doesn't return rows.\n\tExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)\n}\n```\nExecer can execute a non-returning query. The underlying type can be either a \\*sql.DB (connection pool), a \\*sql.Conn (a single dedicated database session) or a \\*sql.Tx (an in-progress database transaction).\n\n```go\ntype Insert struct {\n\tBuilderBase\n\tInto    string\n\tColumns []string\n\t// RowCount defines the number of expected rows.\n\tRowCount int // See SetRowCount()\n\t// RecordPlaceHolderCount defines the number of place holders for each set\n\t// within the brackets. Must only be set when Records have been applied\n\t// and `Columns` field has been omitted.\n\tRecordPlaceHolderCount int\n\t// Select used to create an \"INSERT INTO `table` SELECT ...\" statement.\n\tSelect *Select\n\tPairs  Conditions\n\t// OnDuplicateKeys updates the referenced columns. See documentation for\n\t// type `Conditions`. For more details\n\t// https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html\n\t// Conditions contains the column/argument association for either the SET\n\t// clause in an UPDATE statement or to be used in an INSERT ... ON DUPLICATE\n\t// KEY statement. For each column there must be one argument which can\n\t// either be nil or has an actual value.\n\t//\n\t// When using the ON DUPLICATE KEY feature in the Insert builder:\n\t//\n\t// The function dml.ExpressionValue is supported and allows SQL\n\t// constructs like (ib == InsertBuilder builds INSERT statements):\n\t// \t\t`columnA`=VALUES(`columnB`)+2\n\t// by writing the Go code:\n\t//\t\tib.AddOnDuplicateKey(\"columnA\", ExpressionValue(\"VALUES(`columnB`)+?\", Int(2)))\n\t// Omitting the argument and using the keyword nil will turn this Go code:\n\t//\t\tib.AddOnDuplicateKey(\"columnA\", nil)\n\t// into that SQL:\n\t// \t\t`columnA`=VALUES(`columnA`)\n\t// Same applies as when the columns gets only assigned without any arguments:\n\t//\t\tib.OnDuplicateKeys.Columns = []string{\"name\",\"sku\"}\n\t// will turn into:\n\t// \t\t`name`=VALUES(`name`), `sku`=VALUES(`sku`)\n\t// Type `Conditions` gets used in type `Update` with field\n\t// `SetClauses` and in type `Insert` with field OnDuplicateKeys.\n\tOnDuplicateKeys Conditions\n\t// OnDuplicateKeyExclude excludes the mentioned columns to the ON DUPLICATE\n\t// KEY UPDATE section. Otherwise all columns in the field `Columns` will be\n\t// added to the ON DUPLICATE KEY UPDATE expression. Usually the slice\n\t// `OnDuplicateKeyExclude` contains the primary key columns. Case-sensitive\n\t// comparison.\n\tOnDuplicateKeyExclude []string\n\t// IsOnDuplicateKey if enabled adds all columns to the ON DUPLICATE KEY\n\t// claus. Takes the OnDuplicateKeyExclude field into consideration.\n\tIsOnDuplicateKey bool\n\t// IsReplace uses the REPLACE syntax. See function Replace().\n\tIsReplace bool\n\t// IsIgnore ignores error. See function Ignore().\n\tIsIgnore bool\n\t// IsBuildValues if true the VALUES part gets build when calling ToSQL.\n\t// VALUES do not need to get build by default because mostly WithDBR gets\n\t// called to build the VALUES part dynamically.\n\tIsBuildValues bool\n}\n```\nInsert contains the clauses for an INSERT statement\n\n```go\nfunc NewInsert(into string) *Insert\n```\nNewInsert creates a new Insert object.\n\n```go\nfunc (b *Insert) AddColumns(columns ...string) *Insert\n```\nAddColumns appends columns and increases the \\`RecordPlaceHolderCount\\` variable.\n\n```go\nfunc (b *Insert) AddOnDuplicateKey(c ...*Condition) *Insert\n```\nAddOnDuplicateKey has some hidden features for best flexibility. You can only set the Columns itself to allow the following SQL construct:\n\n\t`columnA`=VALUES(`columnA`)\n\nMeans columnA gets automatically mapped to the VALUES column name.\n\n```go\nfunc (b *Insert) AddOnDuplicateKeyExclude(columns ...string) *Insert\n```\nAddOnDuplicateKeyExclude adds a column to the exclude list. As soon as a column gets set with this function the ON DUPLICATE KEY clause gets generated. Usually the slice \\`OnDuplicateKeyExclude\\` contains the primary/unique key columns. Case-sensitive comparison.\n\n```go\nfunc (b *Insert) BuildValues() *Insert\n```\nBuildValues see IsBuildValues.\n\n```go\nfunc (b *Insert) Clone() *Insert\n```\nClone creates a clone of the current object, leaving fields DB and Log untouched.\n\n```go\nfunc (b *Insert) FromSelect(s *Select) *Insert\n```\nFromSelect creates an \"INSERT INTO \\`table\\` SELECT ...\" statement from a previously created SELECT statement.\n\n```go\nfunc (b *Insert) Ignore() *Insert\n```\nIgnore modifier enables errors that occur while executing the INSERT statement are getting ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors generate warnings instead. [https://dev.mysql.com/doc/refman/5.7/en/insert.html](https://dev.mysql.com/doc/refman/5.7/en/insert.html)\n\n```go\nfunc (b *Insert) OnDuplicateKey() *Insert\n```\nOnDuplicateKey enables for all columns to be written into the ON DUPLICATE KEY claus. Takes the field OnDuplicateKeyExclude into consideration.\n\n```go\nfunc (b *Insert) Replace() *Insert\n```\nReplace instead of INSERT to overwrite old rows. REPLACE is the counterpart to INSERT IGNORE in the treatment of new rows that contain unique key values that duplicate old rows: The new rows are used to replace the old rows rather than being discarded. [https://dev.mysql.com/doc/refman/5.7/en/replace.html](https://dev.mysql.com/doc/refman/5.7/en/replace.html)\n\n```go\nfunc (b *Insert) SetRecordPlaceHolderCount(valueCount int) *Insert\n```\nSetRecordPlaceHolderCount number of expected place holders within each set. Only needed in case the SQL string gets build without any arguments.\n\n\tINSERT INTO tableX (?,?,?)\n\nSetRecordPlaceHolderCount would now be 3 because of the three place holders.\n\n```go\nfunc (b *Insert) SetRowCount(rows int) *Insert\n```\nSetRowCount defines the number of expected rows. Each set of place holders within the brackets defines a row. This setting defaults to one. It gets applied when fields \\`args\\` and \\`Records\\` have been left empty. For each defined column the QueryBuilder creates a place holder. Use when creating a prepared statement. See the example for more details.\n\n\tRowCount = 2 ==\u003e (?,?,?),(?,?,?)\n\tRowCount = 3 ==\u003e (?,?,?),(?,?,?),(?,?,?)\n\n```go\nfunc (b *Insert) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (b *Insert) ToSQL() (string, []interface{}, error)\n```\nToSQL serialized the Insert to a SQL string It returns the string with placeholders and a slice of query arguments.\n\n```go\nfunc (b *Insert) WithDBR(db QueryExecPreparer) *DBR\n```\n\n```go\nfunc (b *Insert) WithPairs(cvs ...*Condition) *Insert\n```\nWithPairs appends a column/value pair to the statement. Calling this function multiple times with the same column name will trigger an error. Slice values and right/left side expressions are not supported and ignored. You must call WithDBR afterwards to activate the \\`Pairs\\`.\n\n```go\ntype Joins []*join\n```\nJoins defines multiple join conditions.\n\n```go\nfunc (js Joins) Clone() Joins\n```\nClone creates a new clone of the current object.\n\n```go\ntype LastInsertIDAssigner interface {\n\tAssignLastInsertID(int64)\n}\n```\nLastInsertIDAssigner assigns the last insert ID of an auto increment column back to the objects.\n\n```go\ntype MysqlQuoter struct {\n\t// contains filtered or unexported fields\n}\n```\nMysqlQuoter implements Mysql-specific quoting\n\n```go\nfunc (mq MysqlQuoter) ColumnsWithQualifier(t string, cols ...string) []string\n```\nColumnsWithQualifier prefixes all columns in the slice \\`cols\\` with a qualifier and applies backticks. If a column name has already been prefixed with a qualifier or an alias it will be ignored. This functions modifies the argument slice \\`cols\\`.\n\n```go\nfunc (mq MysqlQuoter) Name(n string) string\n```\nName quotes securely a name.\n\n\tName(\"tableName\") =\u003e `tableName`\n\tName(\"table`Name\") =\u003e `tableName`\n\n[https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html](https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html)\n\n```go\nfunc (mq MysqlQuoter) NameAlias(name, alias string) string\n```\nNameAlias quotes with back ticks and splits at a dot into the qualified or unqualified identifier. First argument table and/or column name (separated by a dot) and second argument can be an alias. Both parts will get quoted.\n\n\tNameAlias(\"f\", \"g\") \t\t\t// \"`f` AS `g`\"\n\tNameAlias(\"e.entity_id\", \"ee\") \t// `e`.`entity_id` AS `ee`\n\tNameAlias(\"e.entity_id\", \"\") \t// `e`.`entity_id`\n\n```go\nfunc (mq MysqlQuoter) QualifierName(q, n string) string\n```\nQualifierName quotes securely a qualifier and its name.\n\n\tQualifierName(\"dbName\", \"tableName\") =\u003e `dbName`.`tableName`\n\tQualifierName(\"db`Name\", \"`tableName`\") =\u003e `dbName`.`tableName`\n\n[https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html](https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html)\n\n```go\nfunc (mq MysqlQuoter) WriteIdentifier(w *bytes.Buffer, name string)\n```\nWriteIdentifier quotes with back ticks and splits at a dot into the qualified or unqualified identifier. First argument table and/or column name (separated by a dot). It quotes always and each part. If a string contains quotes, they won't get stripped.\n\n\tWriteIdentifier(\u0026buf,\"tableName.ColumnName\") -\u003e `tableName`.`ColumnName`\n\n```go\nfunc (mq MysqlQuoter) WriteQualifierName(w *bytes.Buffer, qualifier, name string)\n```\nWriteQualifierName same as function QualifierName but writes into w.\n\n```go\ntype Op rune\n```\nOp the Operator, defines comparison and operator functions used in any conditions. The upper case letter always negates. [https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html](https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html) [https://mariadb.com/kb/en/mariadb/comparison-operators/](https://mariadb.com/kb/en/mariadb/comparison-operators/)\n\n```go\nconst (\n\tNull           Op = 'n'          // IS NULL\n\tNotNull        Op = 'N'          // IS NOT NULL\n\tIn             Op = '∈'          // IN ?\n\tNotIn          Op = '∉'          // NOT IN ?\n\tBetween        Op = 'b'          // BETWEEN ? AND ?\n\tNotBetween     Op = 'B'          // NOT BETWEEN ? AND ?\n\tLike           Op = 'l'          // LIKE ?\n\tNotLike        Op = 'L'          // NOT LIKE ?\n\tGreatest       Op = '≫'          // GREATEST(?,?,?) returns NULL if any value is NULL.\n\tLeast          Op = '≪'          // LEAST(?,?,?) If any value is NULL, the result is NULL.\n\tEqual          Op = '='          // = ?\n\tNotEqual       Op = '≠'          // != ?\n\tExists         Op = '∃'          // EXISTS(subquery)\n\tNotExists      Op = '∄'          // NOT EXISTS(subquery)\n\tLess           Op = '\u003c'          // \u003c\n\tGreater        Op = '\u003e'          // \u003e\n\tLessOrEqual    Op = '≤'          // \u003c=\n\tGreaterOrEqual Op = '≥'          // \u003e=\n\tRegexp         Op = 'r'          // REGEXP ?\n\tNotRegexp      Op = 'R'          // NOT REGEXP ?\n\tXor            Op = '⊻'          // XOR ?\n\tSpaceShip      Op = '\\U0001f680' // a \u003c=\u003e b is equivalent to a = b OR (a IS NULL AND b IS NULL) NULL-safe equal to operator\n\tCoalesce       Op = 'c'          // Returns the first non-NULL value in the list, or NULL if there are no non-NULL arguments.\n)\n```\nComparison functions and operators describe all available possibilities.\n\n```go\nfunc (o Op) String() string\n```\nString transforms the rune into a string.\n\n```go\ntype Preparer interface {\n\t// PrepareContext - the provided context is used for the preparation of the\n\t// statement, not for the execution of the statement.\n\t// PrepareContext creates a prepared statement for later queries or\n\t// executions. Multiple queries or executions may be run concurrently from\n\t// the returned statement. The caller must call the statement's Close method\n\t// when the statement is no longer needed.\n\tPrepareContext(ctx context.Context, query string) (*sql.Stmt, error)\n}\n```\nPreparer prepares a query in the server. The underlying type can be either a \\*sql.DB (connection pool), a \\*sql.Conn (a single dedicated database session) or a \\*sql.Tx (an in-progress database transaction).\n\n```go\ntype QualifiedRecord struct {\n\t// Qualifier is the name of the table or view or procedure or can be their\n\t// alias. It must be a valid MySQL/MariaDB identifier.\n\t//\n\t// If empty, the main table or its alias of a query will be used. We call it\n\t// the default qualifier. Each query can only contain one default qualifier.\n\t// If you provide multiple default qualifier, the last one wins and\n\t// overwrites the previous.\n\tQualifier string\n\tRecord    ColumnMapper\n}\n```\nQualifiedRecord is a ColumnMapper with a qualifier. A QualifiedRecord gets used as arguments to ExecRecord or WithRecords in the SQL statement. If you use an alias for the main table/view you must set the alias as the qualifier.\n\n```go\nfunc Qualify(q string, record ColumnMapper) QualifiedRecord\n```\nQualify provides a more concise way to create QualifiedRecord values.\n\n```go\ntype Querier interface {\n\t// QueryContext executes a query that returns rows, typically a SELECT. The\n\t// args are for any placeholder parameters in the query.\n\tQueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)\n}\n```\nQuerier can execute a returning query. The underlying type can be either a \\*sql.DB (connection pool), a \\*sql.Conn (a single dedicated database session) or a \\*sql.Tx (an in-progress database transaction).\n\n```go\ntype QueryBuilder interface {\n\tToSQL() (string, []interface{}, error)\n}\n```\nQueryBuilder assembles a query and returns the raw SQL without parameter substitution and the arguments. The input arguments might be modified and returned as plain primitive types.\n\n```go\ntype QueryExecPreparer interface {\n\tPreparer\n\tQuerier\n\tExecer\n\tQueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row\n}\n```\nQueryExecPreparer can execute a returning query and prepare a returning query. The underlying type can be either a \\*sql.DB (connection pool), a \\*sql.Conn (a single dedicated database session) or a \\*sql.Tx (an in-progress database transaction). ExecPreparer a composite interface which can execute and prepare a query. The underlying type can be either a \\*sql.DB (connection pool), a \\*sql.Conn (a single dedicated database session) or a \\*sql.Tx (an in-progress database transaction).\n\n```go\ntype QueryOptions struct {\n\tSkipEvents     bool // skips above defined EventFlag\n\tSkipTimestamps bool // skips generating timestamps (TODO)\n\tSkipRelations  bool // skips executing relation based SQL code\n}\n```\nQueryOptions provides different options while executing code for SQL queries.\n\n```go\nfunc FromContextQueryOptions(ctx context.Context) QueryOptions\n```\nFromContextQueryOptions returns the options from the context.\n\n```go\ntype QuerySQL string\n```\nQuerySQL simple type to satisfy the QueryBuilder interface.\n\n```go\nfunc (qs QuerySQL) ToSQL() (string, []interface{}, error)\n```\nToSQL satisfies interface QueryBuilder and returns always nil arguments and nil error.\n\n```go\ntype QuerySQLFn func() (string, []interface{}, error)\n```\nQuerySQL a helper type to transform a string into a QueryBuilder compatible type.\n\n```go\nfunc (fn QuerySQLFn) ToSQL() (string, []interface{}, error)\n```\nToSQL satisfies interface QueryBuilder and returns always nil arguments and nil error.\n\n```go\ntype Select struct {\n\tBuilderBase\n\tBuilderConditional\n\n\t// Columns represents a slice of names and its optional identifiers. Wildcard\n\t// `SELECT *` statements are not really supported:\n\t// http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful\n\tColumns ids\n\n\tGroupBys             ids\n\tHavings              Conditions\n\tIsStar               bool // IsStar generates a SELECT * FROM query\n\tIsCountStar          bool // IsCountStar retains the column names but executes a COUNT(*) query.\n\tIsDistinct           bool // See Distinct()\n\tIsStraightJoin       bool // See StraightJoin()\n\tIsSQLNoCache         bool // See SQLNoCache()\n\tIsForUpdate          bool // See ForUpdate()\n\tIsLockInShareMode    bool // See LockInShareMode()\n\tIsOrderByDeactivated bool // See OrderByDeactivated()\n\tIsOrderByRand        bool // enables the original slow ORDER BY RAND() clause\n\tOffsetCount          uint64\n}\n```\nSelect contains the clauses for a SELECT statement. Wildcard \\`SELECT \\*\\` statements are not really supported. [http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful](http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful)\n\n```go\nfunc NewSelect(columns ...string) *Select\n```\nNewSelect creates a new Select object.\n\n```go\nfunc NewSelectWithDerivedTable(subSelect *Select, aliasName string) *Select\n```\nNewSelectWithDerivedTable creates a new derived table (Subquery in the FROM Clause) using the provided sub-select in the FROM part together with an alias name. Appends the arguments of the sub-select to the parent \\*Select pointer arguments list. SQL result may look like:\n\n\tSELECT a,b FROM (SELECT x,y FROM `product` AS `p`) AS `t`\n\n[https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html](https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html)\n\n```go\nfunc (b *Select) AddColumns(cols ...string) *Select\n```\nAddColumns appends more columns to the Columns slice. If a column name is not valid identifier that column gets switched into an expression.\n\n\tAddColumns(\"a\",\"b\") \t\t// `a`,`b`\n\tAddColumns(\"a,b\",\"z\",\"c,d\")\t// a,b,`z`,c,d\n\tAddColumns(\"t1.name\",\"t1.sku\",\"price\") // `t1`.`name`, `t1`.`sku`,`price`\n\n```go\nfunc (b *Select) AddColumnsAliases(columnAliases ...string) *Select\n```\nAddColumnsAliases expects a balanced slice of \"Column1, Alias1, Column2, Alias2\" and adds both to the Columns slice. An imbalanced slice will cause a panic. If a column name is not valid identifier that column gets switched into an expression.\n\n\tAddColumnsAliases(\"t1.name\",\"t1Name\",\"t1.sku\",\"t1SKU\") // `t1`.`name` AS `t1Name`, `t1`.`sku` AS `t1SKU`\n\tAddColumnsAliases(\"(e.price*x.tax*t.weee)\", \"final_price\") // error: `(e.price*x.tax*t.weee)` AS `final_price`\n\n```go\nfunc (b *Select) AddColumnsConditions(expressions ...*Condition) *Select\n```\nAddColumnsConditions adds a condition as a column to the statement. The operator field gets ignored. DBR in the condition gets applied to the RawArguments field to maintain the correct order of arguments.\n\n\tAddColumnsConditions(Expr(\"(e.price*x.tax*t.weee)\").Alias(\"final_price\")) // (e.price*x.tax*t.weee) AS `final_price`\n\n```go\nfunc (b *Select) Clone() *Select\n```\nClone creates a clone of the current object, leaving fields DB and Log untouched.\n\n```go\nfunc (b *Select) Count() *Select\n```\nCount executes a COUNT(\\*) as \\`counted\\` query without touching or changing the currently set columns.\n\n```go\nfunc (b *Select) CrossJoin(table id, onConditions ...*Condition) *Select\n```\nCrossJoin creates a CROSS join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Select) Distinct() *Select\n```\nDistinct marks the statement at a DISTINCT SELECT. It specifies removal of duplicate rows from the result set.\n\n```go\nfunc (b *Select) ForUpdate() *Select\n```\nForUpdate sets for index records the search encounters, locks the rows and any associated index entries, the same as if you issued an UPDATE statement for those rows. Other transactions are blocked from updating those rows, from doing SELECT ... LOCK IN SHARE MODE, or from reading the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view. (Old versions of a record cannot be locked; they are reconstructed by applying undo logs on an in-memory copy of the record.) Note: Locking of rows for update using SELECT FOR UPDATE only applies when autocommit is disabled (either by beginning transaction with START TRANSACTION or by setting autocommit to 0. If autocommit is enabled, the rows matching the specification are not locked. [https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html](https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html)\n\n```go\nfunc (b *Select) From(from string) *Select\n```\nFrom sets the table for the SELECT FROM part.\n\n```go\nfunc (b *Select) FromAlias(from, alias string) *Select\n```\nFromAlias sets the table and its alias name for a \\`SELECT ... FROM table AS alias\\` query.\n\n```go\nfunc (b *Select) GroupBy(columns ...string) *Select\n```\nGroupBy appends columns to group the statement. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. MySQL does not sort the results set. To avoid the overhead of sorting that GROUP BY produces this function should add an ORDER BY NULL with function \\`OrderByDeactivated\\`.\n\n```go\nfunc (b *Select) GroupByAsc(columns ...string) *Select\n```\nGroupByAsc sorts the groups in ascending order. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. No need to add an ORDER BY clause. When you use ORDER BY or GROUP BY to sort a column in a SELECT, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable.\n\n```go\nfunc (b *Select) GroupByDesc(columns ...string) *Select\n```\nGroupByDesc sorts the groups in descending order. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. No need to add an ORDER BY clause. When you use ORDER BY or GROUP BY to sort a column in a SELECT, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable.\n\n```go\nfunc (b *Select) Having(wf ...*Condition) *Select\n```\nHaving appends a HAVING clause to the statement\n\n```go\nfunc (b *Select) Join(table id, onConditions ...*Condition) *Select\n```\nJoin creates an INNER join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Select) LeftJoin(table id, onConditions ...*Condition) *Select\n```\nLeftJoin creates a LEFT join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Select) Limit(offset uint64, limit uint64) *Select\n```\nLimit sets a limit for the statement; overrides any existing LIMIT. Don't build a pagination with offset or you go straight to hell.\n\n```go\nfunc (b *Select) LockInShareMode() *Select\n```\nLockInShareMode sets a shared mode lock on any rows that are read. Other sessions can read the rows, but cannot modify them until your transaction commits. If any of these rows were changed by another transaction that has not yet committed, your query waits until that transaction ends and then uses the latest values. [https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html](https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html)\n\n```go\nfunc (b *Select) OrderBy(columns ...string) *Select\n```\nOrderBy appends columns to the ORDER BY statement for ascending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a SELECT, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable. A column name can also contain the suffix words \" ASC\" or \" DESC\" to indicate the sorting. This avoids using the method OrderByDesc when sorting certain columns descending.\n\n```go\nfunc (b *Select) OrderByDeactivated() *Select\n```\nOrderByDeactivated deactivates ordering of the result set by applying ORDER BY NULL to the SELECT statement. Very useful for GROUP BY queries.\n\n```go\nfunc (b *Select) OrderByDesc(columns ...string) *Select\n```\nOrderByDesc appends columns to the ORDER BY statement for descending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a SELECT, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable.\n\n```go\nfunc (b *Select) OrderByRandom(idColumnName string, limit uint64) *Select\n```\nOrderByRandom sorts the table randomly by not using ORDER BY RAND() rather using a JOIN with the single primary key column. This function overwrites previously set ORDER BY statements and the field LimitCount. The generated SQL by this function is about 3-4 times faster than ORDER BY RAND(). The generated SQL does not work for all queries. The underlying SQL statement might change without notice.\n\n```go\nfunc (b *Select) OuterJoin(table id, onConditions ...*Condition) *Select\n```\nOuterJoin creates an OUTER join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Select) Paginate(page, perPage uint64) *Select\n```\nPaginate sets LIMIT/OFFSET for the statement based on the given page/perPage Assumes page/perPage are valid. Page and perPage must be \u003e= 1. Deprecated see a talk from Marcus Wienand - Modern SQL\n\n```go\nfunc (b *Select) RightJoin(table id, onConditions ...*Condition) *Select\n```\nRightJoin creates a RIGHT join construct. By default, the onConditions are glued together with AND.\n\n```go\nfunc (b *Select) SQLNoCache() *Select\n```\nSQLNoCache tells the server that it does not use the query cache. It neither checks the query cache to see whether the result is already cached, nor does it cache the query result.\n\n```go\nfunc (b *Select) Star() *Select\n```\nStar creates a SELECT \\* FROM query. Such queries are discouraged from using.\n\n```go\nfunc (b *Select) StraightJoin() *Select\n```\nStraightJoin forces the optimizer to join the tables in the order in which they are listed in the FROM clause. You can use this to speed up a query if the optimizer joins the tables in nonoptimal order.\n\n```go\nfunc (b *Select) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (b *Select) ToSQL() (string, []interface{}, error)\n```\nToSQL generates the SQL string and might caches it internally, if not disabled.\n\n```go\nfunc (b *Select) Unless(test bool, fn func(*Select), defaultFn func(*Select)) *Select\n```\nUnless applies the function \\`fn\\` query changes if the given \"test\" is false. Providing the optional second function, uses it as the default value, if test is false. \\`defaultFn\\` can be nil.\n\n```go\nfunc (b *Select) Unsafe() *Select\n```\nUnsafe see BuilderBase.IsUnsafe which weakens security when building the SQL string. This function must be called before calling any other function.\n\n```go\nfunc (b *Select) When(test bool, fn func(*Select), defaultFn func(*Select)) *Select\n```\nWhen applies the function \\`fn\\` query changes if the given \"test\" is true. Providing the optional second function, uses it as the default value, if test is false. \\`defaultFn\\` can be nil.\n\n```go\nfunc (b *Select) Where(wf ...*Condition) *Select\n```\nWhere appends a WHERE clause to the statement for the given string and args or map of column/value pairs.\n\n```go\nfunc (b *Select) WithDBR(db QueryExecPreparer) *DBR\n```\nWithDBR sets the database query object and creates a database runner.\n\n```go\ntype Show struct {\n\tBuilderBase\n\t// Type bitwise flag containing the type of the SHOW statement.\n\tType uint\n\t// LikeCondition supports only one argument. Either `LikeCondition` or\n\t// `WhereFragments` can be set.\n\tLikeCondition  bool\n\tWhereFragments Conditions\n}\n```\nShow represents the SHOW syntax\n\n```go\nfunc NewShow() *Show\n```\nNewShow creates a new Truman SHOW.\n\n```go\nfunc (b *Show) BinaryLog() *Show\n```\nBinaryLog lists the binary log files on the server.\n\n```go\nfunc (b *Show) Global() *Show\n```\nGlobal displays with a GLOBAL modifier, the statement displays global system variable values. These are the values used to initialize the corresponding session variables for new connections to MySQL. If a variable has no global value, no value is displayed.\n\n```go\nfunc (b *Show) Like() *Show\n```\nLike sets the comparisons LIKE condition. Either WHERE or LIKE can be used. Only the first argument supported.\n\n```go\nfunc (b *Show) MasterStatus() *Show\n```\nMasterStatus provides status information about the binary log files of the master. It requires either the SUPER or REPLICATION CLIENT privilege.\n\n```go\nfunc (b *Show) Session() *Show\n```\nSession displays with a SESSION modifier, the statement displays the system variable values that are in effect for the current connection. If a variable has no session value, the global value is displayed. LOCAL is a synonym for SESSION. If no modifier is present, the default is SESSION.\n\n```go\nfunc (b *Show) Status() *Show\n```\nStatus provides server status information. This statement does not require any privilege. It requires only the ability to connect to the server.\n\n```go\nfunc (b *Show) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (b *Show) TableStatus() *Show\n```\nTableStatus works likes SHOW TABLES, but provides a lot of information about each non-TEMPORARY table. The LIKE clause, if present, indicates which table names to match. The WHERE clause can be given to select rows using more general conditions. This statement also displays information about views.\n\n```go\nfunc (b *Show) ToSQL() (string, []interface{}, error)\n```\nToSQL converts the select statement into a string and returns its arguments.\n\n```go\nfunc (b *Show) Variable() *Show\n```\nVariable shows the values of MySQL|MariaDB system variables (“Server System Variables”). This statement does not require any privilege. It requires only the ability to connect to the server.\n\n```go\nfunc (b *Show) Where(wf ...*Condition) *Show\n```\nWhere appends a WHERE clause to the statement for the given string and args or map of column/value pairs. Either WHERE or LIKE can be used.\n\n```go\nfunc (b *Show) WithDBR(db QueryExecPreparer) *DBR\n```\n\n```go\ntype StaticSQLResult struct {\n\tLID  int64\n\tRows int64\n\tErr  error\n}\n```\nStaticSQLResult implements sql.Result for mocking reasons.\n\n```go\nfunc (r StaticSQLResult) LastInsertId() (int64, error)\n```\n\n```go\nfunc (r StaticSQLResult) RowsAffected() (int64, error)\n```\n\n```go\ntype Stmt struct {\n\tStmt *sql.Stmt\n}\n```\nStmt wraps a \\*sql.Stmt (a prepared statement) with a specific SQL query. To create a Stmt call the Prepare function of a specific DML type. Stmt is not yet safe for concurrent use, despite the underlying \\*sql.Stmt is. Don't forget to call Close!\n\n```go\nfunc (st *Stmt) Close() error\n```\nClose closes the statement in the database and frees its resources.\n\n```go\ntype StmtExecer interface {\n\t// ExecContext executes a query that doesn't return rows.\n\tExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)\n}\n```\nStmtExecer executes a prepared statement.\n\n```go\ntype StmtQuerier interface {\n\t// QueryContext executes a query that returns rows, typically a SELECT. The\n\t// args are for any placeholder parameters in the query.\n\tQueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error)\n}\n```\nStmtQuerier executes a prepared statement query.\n\n```go\ntype Tx struct {\n\tDB *sql.Tx\n\t// contains filtered or unexported fields\n}\n```\nTx is an in-progress database transaction.\n\nA transaction must end with a call to Commit or Rollback.\n\nAfter a call to Commit or Rollback, all operations on the transaction fail with ErrTxDone.\n\nThe statements prepared for a transaction by calling the transaction's Prepare or Stmt methods are closed by the call to Commit or Rollback. Practical Guide to SQL Transaction Isolation: [https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html](https://begriffs.com/posts/2017-08-01-practical-guide-sql-isolation.html)\n\n```go\nfunc (tx *Tx) CacheKeyExists(cacheKey string) bool\n```\nCacheKeyExists returns true if a given key already exists.\n\n```go\nfunc (tx *Tx) Commit() error\n```\nCommit finishes the transaction. It logs the time taken, if a logger has been set with Info logging enabled.\n\n```go\nfunc (tx *Tx) Rollback() error\n```\nRollback cancels the transaction. It logs the time taken, if a logger has been set with Info logging enabled.\n\n```go\nfunc (tx *Tx) WithCacheKey(cacheKey string, opts ...DBRFunc) *DBR\n```\nWithCacheKey creates a DBR object from a cached query.\n\n```go\nfunc (tx *Tx) WithPrepare(ctx context.Context, qb QueryBuilder, opts ...DBRFunc) *DBR\n```\nWithPrepare executes the statement represented by the Select to create a prepared statement. It returns a custom statement type or an error if there was one. Provided arguments or records in the Select are getting ignored. The provided context is used for the preparation of the statement, not for the execution of the statement. The returned Stmter is not safe for concurrent use, despite the underlying \\*sql.Stmt is. You must close DBR after its use. It generates a unique cache key based on the SQL string. The cache key can be retrieved via DBR object.\n\n```go\nfunc (tx *Tx) WithPrepareCacheKey(ctx context.Context, cacheKey string, opts ...DBRFunc) *DBR\n```\nWithPrepareCacheKey creates a DBR object from a prepared cached query. After use the query statement must be closed.\n\n```go\nfunc (tx *Tx) WithQueryBuilder(qb QueryBuilder, opts ...DBRFunc) *DBR\n```\nWithQueryBuilder creates a new DBR for handling the arguments with the assigned connection and builds the SQL string. The returned arguments and errors of the QueryBuilder will be forwarded to the DBR type. It generates a unique cache key based on the SQL string. The cache key can be retrieved via DBR object.\n\n```go\ntype Union struct {\n\tBuilderBase\n\tSelects     []*Select\n\tOrderBys    ids\n\tIsAll       bool // IsAll enables UNION ALL\n\tIsIntersect bool // See Intersect()\n\tIsExcept    bool // See Except()\n\t// contains filtered or unexported fields\n}\n```\nUnion represents a UNION SQL statement. UNION is used to combine the result from multiple SELECT statements into a single result set. With template usage enabled, it builds multiple select statements joined by UNION and all based on a common template.\n\n```go\nfunc NewUnion(selects ...*Select) *Union\n```\nNewUnion creates a new Union object. If using as a template, only one \\*Select object can be provided.\n\n```go\nfunc (u *Union) All() *Union\n```\nAll returns all rows. The default behavior for UNION is that duplicate rows are removed from the result. Enabling ALL returns all rows.\n\n```go\nfunc (u *Union) Append(selects ...*Select) *Union\n```\nAppend adds more \\*Select objects to the Union object. When using Union as a template only one \\*Select object can be provided.\n\n```go\nfunc (u *Union) Clone() *Union\n```\nClone creates a clone of the current object, leaving fields DB and Log untouched. Additionally the fields for replacing strings also won't get copied.\n\n```go\nfunc (u *Union) Except() *Union\n```\nExcept switches the query from UNION to EXCEPT. The result of EXCEPT is all records of the left SELECT result except records which are in right SELECT result set, i.e. it is subtraction of two result sets. EXCEPT and UNION have the same operation precedence. Only supported in MariaDB \u003e=10.3\n\n```go\nfunc (u *Union) Intersect() *Union\n```\nIntersect switches the query type from UNION to INTERSECT. The result of an intersect is the intersection of right and left SELECT results, i.e. only records that are present in both result sets will be included in the result of the operation. INTERSECT has higher precedence than UNION and EXCEPT. If possible it will be executed linearly but if not it will be translated to a subquery in the FROM clause. Only supported in MariaDB \u003e=10.3\n\n```go\nfunc (u *Union) OrderBy(columns ...string) *Union\n```\nOrderBy appends a column to ORDER the statement ascending. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. MySQL might order the result set in a temporary table, which is slow. Under different conditions sorting can skip the temporary table. [https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-3.html](https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-3.html) A column name can also contain the suffix words \" ASC\" or \" DESC\" to indicate the sorting. This avoids using the method OrderByDesc when sorting certain columns descending.\n\n```go\nfunc (u *Union) OrderByDesc(columns ...string) *Union\n```\nOrderByDesc appends columns to the ORDER BY statement for descending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a DELETE, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable.\n\n```go\nfunc (u *Union) PreserveResultSet() *Union\n```\nPreserveResultSet enables the correct ordering of the result set from the Select statements. UNION by default produces an unordered set of rows. To cause rows in a UNION result to consist of the sets of rows retrieved by each SELECT one after the other, select an additional column in each SELECT to use as a sort column and add an ORDER BY following the last SELECT.\n\n```go\nfunc (u *Union) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (u *Union) StringReplace(key string, values ...string) *Union\n```\nStringReplace is only applicable when using \\*Union as a template. StringReplace replaces the \\`key\\` with one of the \\`values\\`. Each value defines a generated SELECT query. Repeating calls of StringReplace must provide the same amount of \\`values\\` as the first  or an index of bound stack trace happens. This function is just a simple string replacement. Make sure that your key does not match other parts of the SQL query.\n\n```go\nfunc (u *Union) ToSQL() (string, []interface{}, error)\n```\nToSQL converts the statements into a string and returns its arguments.\n\n```go\nfunc (u *Union) Unsafe() *Union\n```\nUnsafe see BuilderBase.IsUnsafe which weakens security when building the SQL string. This function must be called before calling any other function.\n\n```go\nfunc (b *Union) WithDBR(db QueryExecPreparer) *DBR\n```\n\n```go\ntype Update struct {\n\tBuilderBase\n\tBuilderConditional\n\t// SetClauses contains the column/argument association. For each column\n\t// there must be one argument.\n\tSetClauses Conditions\n}\n```\nUpdate contains the logic for an UPDATE statement. TODO: add UPDATE JOINS\n\n```go\nfunc NewUpdate(table string) *Update\n```\nNewUpdate creates a new Update object.\n\n```go\nfunc (b *Update) AddClauses(c ...*Condition) *Update\n```\nAddClauses appends a column/value pair for the statement.\n\n```go\nfunc (b *Update) AddColumns(columnNames ...string) *Update\n```\nAddColumns adds columns whose values gets later derived from a ColumnMapper. Those columns will get passed to the ColumnMapper implementation.\n\n```go\nfunc (b *Update) Alias(alias string) *Update\n```\nAlias sets an alias for the table name.\n\n```go\nfunc (b *Update) Clone() *Update\n```\nClone creates a clone of the current object, leaving fields DB and Log untouched.\n\n```go\nfunc (b *Update) Limit(limit uint64) *Update\n```\nLimit sets a limit for the statement; overrides any existing LIMIT\n\n```go\nfunc (b *Update) OrderBy(columns ...string) *Update\n```\nOrderBy appends columns to the ORDER BY statement for ascending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a UPDATE, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable. A column name can also contain the suffix words \" ASC\" or \" DESC\" to indicate the sorting. This avoids using the method OrderByDesc when sorting certain columns descending.\n\n```go\nfunc (b *Update) OrderByDesc(columns ...string) *Update\n```\nOrderByDesc appends columns to the ORDER BY statement for descending sorting. A column gets always quoted if it is a valid identifier otherwise it will be treated as an expression. When you use ORDER BY or GROUP BY to sort a column in a UPDATE, the server sorts values using only the initial number of bytes indicated by the max\\_sort\\_length system variable.\n\n```go\nfunc (b *Update) SetColumns(columnNames ...string) *Update\n```\nSetColumns resets the SetClauses slice and adds the columns. Same behaviour as AddColumns.\n\n```go\nfunc (b *Update) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (b *Update) ToSQL() (string, []interface{}, error)\n```\nToSQL converts the select statement into a string and returns its arguments.\n\n```go\nfunc (b *Update) Unsafe() *Update\n```\nUnsafe see BuilderBase.IsUnsafe which weakens security when building the SQL string. This function must be called before calling any other function.\n\n```go\nfunc (b *Update) Where(wf ...*Condition) *Update\n```\nWhere appends a WHERE clause to the statement\n\n```go\nfunc (b *Update) WithDBR(db QueryExecPreparer) *DBR\n```\n\n```go\ntype With struct {\n\tBuilderBase\n\tSubclauses []WithCTE\n\t// TopLevel a union type which allows only one of the fields to be set.\n\tTopLevel struct {\n\t\tSelect *Select\n\t\tUnion  *Union\n\t\tUpdate *Update\n\t\tDelete *Delete\n\t}\n\tIsRecursive bool // See Recursive()\n}\n```\nWith represents a common table expression. Common Table Expressions (CTEs) are a standard SQL feature, and are essentially temporary named result sets. Non-recursive CTES are basically 'query-local VIEWs'. One CTE can refer to another. The syntax is more readable than nested FROM (SELECT ...). One can refer to a CTE from multiple places. They are better than copy-pasting FROM(SELECT ...)\n\nCommon Table Expression versus Derived Table: Better readability; Can be referenced multiple times; Can refer to other CTEs; Improved performance.\n\n[https://dev.mysql.com/doc/refman/8.0/en/with.html](https://dev.mysql.com/doc/refman/8.0/en/with.html)\n\n[https://mariadb.com/kb/en/mariadb/non-recursive-common-table-expressions-overview/](https://mariadb.com/kb/en/mariadb/non-recursive-common-table-expressions-overview/)\n\n[http://mysqlserverteam.com/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes/](http://mysqlserverteam.com/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes/)\n\n[http://dankleiman.com/2018/02/06/3-ways-to-level-up-your-sql-as-a-software-engineer/](http://dankleiman.com/2018/02/06/3-ways-to-level-up-your-sql-as-a-software-engineer/)\n\nSupported in: MySQL \u003e=8.0.1 and MariaDb \u003e=10.2\n\n```go\nfunc NewWith(expressions ...WithCTE) *With\n```\nNewWith creates a new WITH statement with multiple common table expressions (CTE).\n\n```go\nfunc (b *With) Clone() *With\n```\nClone creates a clone of the current object, leaving fields DB and Log untouched.\n\n```go\nfunc (b *With) Delete(topLevel *Delete) *With\n```\nDelete gets used in the top level statement.\n\n```go\nfunc (b *With) Recursive() *With\n```\nRecursive common table expressions are one having a subquery that refers to its own name. The WITH clause must begin with WITH RECURSIVE if any CTE in the WITH clause refers to itself. (If no CTE refers to itself, RECURSIVE is permitted but not required.) Common applications of recursive CTEs include series generation and traversal of hierarchical or tree-structured data. It is simpler, when experimenting with WITH RECURSIVE, to put this at the start of your session: \\`SET max\\_execution\\_time = 10000;\\` so that the runaway query aborts automatically after 10 seconds, if the WHERE clause wasn’t correct.\n\n```go\nfunc (b *With) Select(topLevel *Select) *With\n```\nSelect gets used in the top level statement.\n\n```go\nfunc (b *With) String() string\n```\nString returns a string representing a preprocessed, interpolated, query. On error, the error gets printed. Fulfills interface fmt.Stringer.\n\n```go\nfunc (b *With) ToSQL() (string, []interface{}, error)\n```\nToSQL converts the select statement into a string and returns its arguments.\n\n```go\nfunc (b *With) Union(topLevel *Union) *With\n```\nUnion gets used in the top level statement.\n\n```go\nfunc (b *With) Update(topLevel *Update) *With\n```\nUpdate gets used in the top level statement.\n\n```go\nfunc (b *With) WithDBR(db QueryExecPreparer) *DBR\n```\n\n```go\ntype WithCTE struct {\n\tName string\n\t// Columns, optionally, the number of names in the list must be the same as\n\t// the number of columns in the result set.\n\tColumns []string\n\t// Select clause as a common table expression. Has precedence over the Union field.\n\tSelect *Select\n\t// Union clause as a common table expression. Select field pointer must be\n\t// nil to trigger SQL generation of this field.\n\tUnion *Union\n}\n```\nWithCTE defines a common table expression used in the type \\`With\\`.\n\n```go\nfunc (cte WithCTE) Clone() WithCTE\n```\nClone creates a cloned object of the current one.\n\n","path":"github.com/windhooked/pkg/sql/dml","name":"dml","synopsis":"Package dml handles the SQL DML for super fast performance, type safety and convenience.","isRedistributable":true}
