ddl

package
v0.0.0-...-b553abb Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2019 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package ddl implements MySQL data definition language functions.

Functions for tables, columns, statements, replication, validation and DB variables.

https://launchbylunch.com/posts/2014/Feb/16/sql-naming-conventions/

Index

Examples

Constants

View Source
const (
	// PrefixView  is an anti-pattern I've seen many such systems where at some point a view will become a table.
	// deprecated
	PrefixView      = "view_" // If identifier starts with this, it is considered a view.
	MainTable       = "main_table"
	AdditionalTable = "additional_table"
	ScopeTable      = "scope_table"
)

Variables

This section is empty.

Functions

func ForeignKeyName

func ForeignKeyName(priTableName, priColumnName, refTableName, refColumnName string) string

ForeignKeyName creates a new foreign key name. The returned string represents a valid identifier within MySQL.

func IndexName

func IndexName(indexType, tableName string, fields ...string) string

IndexName creates a new valid index name. IndexType can only be one of the three following enums: `index`, `unique` or `fulltext`. If empty or mismatch it falls back to `index`. The returned string represents a valid identifier within MySQL.

func LoadColumns

func LoadColumns(ctx context.Context, db dml.Querier, tables ...string) (map[string]Columns, error)

LoadColumns returns all columns from a list of table names in the current database. Map key contains the table name. Returns a NotFound error if the table is not available. All columns from all tables gets selected when you don't provide the argument `tables`.

func LoadKeyColumnUsage

func LoadKeyColumnUsage(ctx context.Context, db dml.Querier, tables ...string) (tc map[string]KeyColumnUsageCollection, err error)

LoadKeyColumnUsage returns all foreign key columns from a list of table names in the current database. Map key contains REFERENCED_TABLE_NAME.REFERENCED_COLUMN_NAME. All columns from all tables gets selected when you don't provide the argument `tables`.

func Shorten

func Shorten(tableName string) string

Shorten creates a short alias name from a table name using the first two characters.

catalog_category_entity_datetime => cacaenda
catalog_category_entity_decimal => cacaende

func TableName

func TableName(prefix, name string, suffixes ...string) string

TableName generates a table name, shortens it, if necessary, and removes all invalid characters. First round of shortening goes by replacing common words with their abbreviations and in the second round creating a MD5 hash of the table name.

func TriggerName

func TriggerName(tableName, time, event string) string

TriggerName creates a new trigger name. The returned string represents a valid identifier within MySQL. Argument time should be either `before` or `after`. Event should be one of the following types: `insert`, `update` or `delete`

Types

type Column

type Column struct {
	Field   string      // `COLUMN_NAME` varchar(64) NOT NULL DEFAULT ”,
	Pos     uint64      // `ORDINAL_POSITION` bigint(21) unsigned NOT NULL DEFAULT '0',
	Default null.String // `COLUMN_DEFAULT` longtext,
	Null    string      // `IS_NULLABLE` varchar(3) NOT NULL DEFAULT ”,
	// DataType contains the basic type of a column like smallint, int, mediumblob,
	// float, double, etc... but always transformed to lower case.
	DataType      string     // `DATA_TYPE` varchar(64) NOT NULL DEFAULT ”,
	CharMaxLength null.Int64 // `CHARACTER_MAXIMUM_LENGTH` bigint(21) unsigned DEFAULT NULL,
	Precision     null.Int64 // `NUMERIC_PRECISION` bigint(21) unsigned DEFAULT NULL,
	Scale         null.Int64 // `NUMERIC_SCALE` bigint(21) unsigned DEFAULT NULL,
	// ColumnType full SQL string of the column type
	ColumnType string // `COLUMN_TYPE` longtext NOT NULL,
	// Key primary or unique or ...
	Key                  string      // `COLUMN_KEY` varchar(3) NOT NULL DEFAULT ”,
	Extra                string      // `EXTRA` varchar(30) NOT NULL DEFAULT ”,
	Comment              string      // `COLUMN_COMMENT` varchar(1024) NOT NULL DEFAULT ”,
	Generated            string      // `IS_GENERATED` varchar(6) NOT NULL DEFAULT ”, MariaDB only https://mariadb.com/kb/en/library/information-schema-columns-table/
	GenerationExpression null.String // `GENERATION_EXPRESSION` longtext DEFAULT NULL, MariaDB only https://mariadb.com/kb/en/library/information-schema-columns-table/
	// Aliases specifies different names used for this column. Mainly used when
	// generating code for interface dml.ColumnMapper. For example
	// customer_entity.entity_id can also be sales_order.customer_id. The alias
	// would be just: entity_id:[]string{"customer_id"}.
	Aliases []string
	// Uniquified used when generating code to uniquify the values in a
	// collection when the column is not a primary or unique key. The values get
	// returned in its own primitive slice.
	Uniquified bool
	// StructTag  used in code generation and applies a custom struct tag.
	StructTag string
}

Column contains information about one database table column retrieved from information_schema.COLUMNS

func NewColumn

func NewColumn(rc *dml.ColumnMap) (c *Column, tableName string, err error)

NewColumn creates a new column pointer and maps it from a raw database row its bytes into the type Column.

func (*Column) GoComment

func (c *Column) GoComment() string

GoComment creates a comment from a database column to be used in Go code

func (*Column) GoString

func (c *Column) GoString() string

GoString returns the Go types representation. See interface fmt.GoStringer

func (*Column) IsAutoIncrement

func (c *Column) IsAutoIncrement() bool

IsAutoIncrement checks if column has an auto increment property

func (*Column) IsBlobDataType

func (c *Column) IsBlobDataType() bool

IsBlobDataType returns true if the columns data type is neither blob, text, binary nor json. It doesn't matter if tiny, long or small has been prefixed.

func (*Column) IsBool

func (c *Column) IsBool() (ok bool)

IsBool returns true if column is of type `int` and its name starts with a special string like: `used_`, `is_`, `has_`.

func (*Column) IsCurrentTimestamp

func (c *Column) IsCurrentTimestamp() bool

IsCurrentTimestamp checks if the Default field is a current timestamp

func (*Column) IsFloat

func (c *Column) IsFloat() bool

IsFloat returns true if a column is of one of the types: decimal, double or float.

func (*Column) IsGenerated

func (c *Column) IsGenerated() bool

IsGenerated returns true if the column is a virtual generated column.

func (*Column) IsMoney

func (c *Column) IsMoney() bool

IsMoney checks if a column contains a MySQL decimal or float type and if the column name has a special naming. This function needs a lot of care ...

func (*Column) IsNull

func (c *Column) IsNull() bool

IsNull checks if column can have null values

func (*Column) IsPK

func (c *Column) IsPK() bool

IsPK checks if column is a primary key

func (*Column) IsString

func (c *Column) IsString() bool

IsString returns true if the column can contain a string or byte values.

func (*Column) IsSystemVersioned

func (c *Column) IsSystemVersioned() bool

IsSystemVersioned returns true if the column gets used for system versioning. https://mariadb.com/kb/en/library/system-versioned-tables/

func (*Column) IsUnique

func (c *Column) IsUnique() bool

IsUnique checks if column is a unique key

func (*Column) IsUnsigned

func (c *Column) IsUnsigned() bool

IsUnsigned checks if field TypeRaw contains the word unsigned.

type Columns

type Columns []*Column

Columns contains a slice of column types

func (Columns) ByField

func (cs Columns) ByField(fieldName string) *Column

ByField finds a column by its field name. Case sensitive. Guaranteed to return a non-nil return value.

func (Columns) Contains

func (cs Columns) Contains(fieldName string) bool

Contains returns true if fieldName is contained in slice Columns.

func (Columns) FieldNames

func (cs Columns) FieldNames(fn ...string) []string

FieldNames returns all column names and appends it to `fn`, if provided.

func (Columns) Filter

func (cs Columns) Filter(f func(*Column) bool, cols ...*Column) Columns

Filter filters the columns by predicate f and appends the column pointers to the optional argument `cols`.

func (Columns) First

func (cs Columns) First() *Column

First returns the first column from the slice. Guaranteed to a non-nil return value.

func (Columns) GoString

func (cs Columns) GoString() string

GoString returns the Go types representation. See interface fmt.GoStringer

func (Columns) JoinFields

func (cs Columns) JoinFields(sep string) string

JoinFields joins the field names into a string, separated by the provided separator.

func (Columns) Len

func (cs Columns) Len() int

Len returns the length

func (Columns) Less

func (cs Columns) Less(i, j int) bool

Less compares via the Pos field.

func (Columns) NonPrimaryColumns

func (cs Columns) NonPrimaryColumns() Columns

NonPrimaryColumns returns all non primary key and non-unique key columns.

func (Columns) PrimaryKeys

func (cs Columns) PrimaryKeys(cols ...*Column) Columns

PrimaryKeys returns all primary key columns. It may append the columns to the provided argument slice.

func (Columns) String

func (cs Columns) String() string

String same as GoString()

func (Columns) Swap

func (cs Columns) Swap(i, j int)

Swap changes the position

func (Columns) UniqueColumns

func (cs Columns) UniqueColumns(cols ...*Column) Columns

UniqueColumns returns all columns which are either a single primary key or a single unique key. If a PK or UK consists of more than one column, then they won't be included in the returned Columns slice. The result might be appended to argument `cols`, if provided.

func (Columns) UniqueKeys

func (cs Columns) UniqueKeys(cols ...*Column) Columns

UniqueKeys returns all unique key columns. It may append the columns to the provided argument slice.

func (Columns) UniquifiedColumns

func (cs Columns) UniquifiedColumns(cols ...*Column) Columns

UniquifiedColumns returns all columns which have the flag Uniquified set to true. The result might be appended to argument `cols`, if provided.

type InfileOptions

type InfileOptions struct {
	// IsNotLocal disables LOCAL load file. If LOCAL is specified, the file is read
	// by the client program on the client host and sent to the server. If LOCAL
	// is not specified, the file must be located on the server host and is read
	// directly by the server.
	// See security issues in https://dev.mysql.com/doc/refman/5.7/en/load-data-local.html
	IsNotLocal bool
	// Replace, input rows replace existing rows. In other words, rows that have
	// the same value for a primary key or unique index as an existing row.
	Replace bool
	// Ignore, rows that duplicate an existing row on a unique key value are
	// discarded.
	Ignore bool
	// FieldsOptionallyEnclosedBy set true if not all columns are enclosed.
	FieldsOptionallyEnclosedBy bool
	FieldsEnclosedBy           rune
	FieldsEscapedBy            rune
	LinesTerminatedBy          string
	FieldsTerminatedBy         string
	// LinesStartingBy: If all the lines you want to read in have a common
	// prefix that you want to ignore, you can use LINES STARTING BY
	// 'prefix_string' to skip over the prefix, and anything before it. If a
	// line does not include the prefix, the entire line is skipped.
	LinesStartingBy string
	// IgnoreLinesAtStart can be used to ignore lines at the start of the file.
	// For example, you can use IGNORE 1 LINES to skip over an initial header
	// line containing column names.
	IgnoreLinesAtStart int
	// Set must be a balanced key,value slice. The column list (field Columns)
	// can contain either column names or user variables. With user variables,
	// the SET clause enables you to perform transformations on their values
	// before assigning the result to columns. The SET clause can be used to
	// supply values not derived from the input file. e.g. SET column3 =
	// CURRENT_TIMESTAMP For more details please read
	// https://dev.mysql.com/doc/refman/5.7/en/load-data.html
	Set []string
	// Columns optional custom columns if the default columns of the table
	// differs from the CSV file. Column names do NOT get automatically quoted.
	Columns []string
	// Log optional logger for debugging purposes
	Log log.Logger
}

InfileOptions provides options for the function LoadDataInfile. Some columns are self-describing.

type KeyColumnUsage

type KeyColumnUsage struct {
	ConstraintCatalog          string      // CONSTRAINT_CATALOG varchar(512) NOT NULL  DEFAULT ””  ""
	ConstraintSchema           string      // CONSTRAINT_SCHEMA varchar(64) NOT NULL  DEFAULT ””  ""
	ConstraintName             string      // CONSTRAINT_NAME varchar(64) NOT NULL  DEFAULT ””  ""
	TableCatalog               string      // TABLE_CATALOG varchar(512) NOT NULL  DEFAULT ””  ""
	TableSchema                string      // TABLE_SCHEMA varchar(64) NOT NULL  DEFAULT ””  ""
	TableName                  string      // TABLE_NAME varchar(64) NOT NULL  DEFAULT ””  ""
	ColumnName                 string      // COLUMN_NAME varchar(64) NOT NULL  DEFAULT ””  ""
	OrdinalPosition            int64       // ORDINAL_POSITION bigint(10) NOT NULL  DEFAULT '0'  ""
	PositionInUniqueConstraint null.Int64  // POSITION_IN_UNIQUE_CONSTRAINT bigint(10) NULL  DEFAULT 'NULL'  ""
	ReferencedTableSchema      null.String // REFERENCED_TABLE_SCHEMA varchar(64) NULL  DEFAULT 'NULL'  ""
	ReferencedTableName        null.String // REFERENCED_TABLE_NAME varchar(64) NULL  DEFAULT 'NULL'  ""
	ReferencedColumnName       null.String // REFERENCED_COLUMN_NAME varchar(64) NULL  DEFAULT 'NULL'  ""
}

KeyColumnUsage represents a single row for DB table `KEY_COLUMN_USAGE` Generated via dmlgen.

func NewKeyColumnUsage

func NewKeyColumnUsage() *KeyColumnUsage

NewKeyColumnUsage creates a new pointer with pre-initialized fields.

func (*KeyColumnUsage) MapColumns

func (e *KeyColumnUsage) MapColumns(cm *dml.ColumnMap) error

MapColumns implements interface ColumnMapper only partially.

func (*KeyColumnUsage) Reset

func (e *KeyColumnUsage) Reset() *KeyColumnUsage

Reset resets the struct to its empty fields.

type KeyColumnUsageCollection

type KeyColumnUsageCollection struct {
	Data             []*KeyColumnUsage
	BeforeMapColumns func(uint64, *KeyColumnUsage) error
	AfterMapColumns  func(uint64, *KeyColumnUsage) error
}

KeyColumnUsageCollection represents a collection type for DB table KEY_COLUMN_USAGE Not thread safe. Generated via dmlgen.

func MakeKeyColumnUsageCollection

func MakeKeyColumnUsageCollection() KeyColumnUsageCollection

MakeKeyColumnUsageCollection creates a new initialized collection.

func (KeyColumnUsageCollection) ColumnNames

func (cc KeyColumnUsageCollection) ColumnNames(ret ...string) []string

ColumnNames belongs to the column `COLUMN_NAME` and returns a slice or appends to a slice only unique values of that column. The values will be filtered internally in a Go map. No DB query gets executed.

func (KeyColumnUsageCollection) MapColumns

func (cc KeyColumnUsageCollection) MapColumns(cm *dml.ColumnMap) error

MapColumns implements dml.ColumnMapper interface

func (KeyColumnUsageCollection) TableNames

func (cc KeyColumnUsageCollection) TableNames(ret ...string) []string

TableNames belongs to the column `TABLE_NAME` and returns a slice or appends to a slice only unique values of that column. The values will be filtered internally in a Go map. No DB query gets executed.

type MasterStatus

type MasterStatus struct {
	File           string
	Position       uint
	BinlogDoDB     string
	BinlogIgnoreDB string
	// ExecutedGTIDSet: When global transaction IDs are in use, ExecutedGTIDSet
	// shows the set of GTIDs for transactions that have been executed on the
	// master. This is the same as the value for the gtid_executed system variable
	// on this server, as well as the value for ExecutedGTIDSet in the output of
	// SHOW SLAVE STATUS on this server.
	ExecutedGTIDSet string
}

MasterStatus provides status information about the binary log files of the master. It requires either the SUPER or REPLICATION CLIENT privilege. Once a MasterStatus pointer variable has been created it can be reused multiple times.

func (MasterStatus) Compare

func (ms MasterStatus) Compare(other MasterStatus) int

Compare compares with another MasterStatus. Returns 1 if left hand side is bigger, 0 if both are equal and -1 if right hand side is bigger.

func (*MasterStatus) FromString

func (ms *MasterStatus) FromString(str string) error

FromString parses as string in the format: mysql-bin.000002;236423 means filename;position.

func (*MasterStatus) MapColumns

func (ms *MasterStatus) MapColumns(rc *dml.ColumnMap) error

MapColumns implements dml.ColumnMapper interface to scan a row returned from a database query.

Example
package main

import ()

func main() {

}
Output:

func (MasterStatus) String

func (ms MasterStatus) String() string

String converts the file name and the position to a string, separated by a semi-colon.

func (MasterStatus) ToSQL

func (ms MasterStatus) ToSQL() (string, []interface{}, error)

ToSQL implements dml.QueryBuilder interface to assemble a SQL string and its arguments for query execution.

func (MasterStatus) WriteTo

func (ms MasterStatus) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo and writes the current position and file name to w.

type Table

type Table struct {

	// Schema represents the name of the database. Might be empty.
	Schema string
	// Name of the table
	Name string
	// Columns all table columns. They do not get used to create or alter a
	// table.
	Columns Columns
	// IsView set to true to mark if the table is a view.
	IsView bool
	// contains filtered or unexported fields
}

Table represents a table from a specific database with a bound default connection pool. Its fields are not secure to use in concurrent context and hence might cause a race condition if used not properly.

func NewTable

func NewTable(tableName string, cs ...*Column) *Table

NewTable initializes a new table structure

func (*Table) DeleteByPK

func (t *Table) DeleteByPK() *dml.Delete

DeleteByPK creates a new `DELETE FROM table WHERE id IN (?)`

func (*Table) Drop

func (t *Table) Drop(ctx context.Context) error

Drop drops, if exists, the table or the view. To use a custom connection, call WithDB before.

func (*Table) Insert

func (t *Table) Insert() *dml.Insert

Insert creates a new INSERT statement with all non primary key columns. If OnDuplicateKey() gets called, the INSERT can be used as an update or create statement. Adding multiple VALUES section is allowed. Using this statement to prepare a query, a call to `BuildValues()` triggers building the VALUES clause, otherwise a SQL parse error will occur.

func (*Table) LoadDataInfile

func (t *Table) LoadDataInfile(ctx context.Context, filePath string, o InfileOptions) error

LoadDataInfile loads a local CSV file into a MySQL table. For more details please read https://dev.mysql.com/doc/refman/5.7/en/load-data.html Files must be whitelisted by registering them with mysql.RegisterLocalFile(filepath) (recommended) or the Whitelist check must be deactivated by using the DSN parameter allowAllFiles=true (Might be insecure!). For more details https://godoc.org/github.com/go-sql-driver/mysql#RegisterLocalFile. To ignore foreign key constraints during the load operation, issue a SET foreign_key_checks = 0 statement before executing LOAD DATA.

func (*Table) Rename

func (t *Table) Rename(ctx context.Context, new string) error

Rename renames the current table to the new table name. Renaming is an atomic operation in the database. As long as two databases are on the same file system, you can use RENAME TABLE to move a table from one database to another. RENAME TABLE also works for views, as long as you do not try to rename a view into a different database. To use a custom connection, call WithDB before.

func (*Table) Select

func (t *Table) Select(columns ...string) *dml.Select

Select creates a new SELECT statement. If "*" gets set as an argument, then all columns will be added to to list of columns.

func (*Table) SelectByPK

func (t *Table) SelectByPK() *dml.Select

SelectByPK creates a new `SELECT columns FROM table WHERE id IN (?)`

func (*Table) Swap

func (t *Table) Swap(ctx context.Context, other string) error

Swap swaps the current table with the other table of the same structure. Renaming is an atomic operation in the database. Note: indexes won't get swapped! As long as two databases are on the same file system, you can use RENAME TABLE to move a table from one database to another. To use a custom connection, call WithDB before.

func (*Table) Truncate

func (t *Table) Truncate(ctx context.Context) error

Truncate truncates the table. Removes all rows and sets the auto increment to zero. Just like a CREATE TABLE statement. To use a custom connection, call WithDB before.

func (*Table) UpdateByPK

func (t *Table) UpdateByPK() *dml.Update

UpdateByPK creates a new `UPDATE table SET ... WHERE id = ?`. The SET clause contains all non primary columns.

func (*Table) WithDB

func (t *Table) WithDB(db dml.QueryExecPreparer) *Table

WithDB creates a shallow clone of the current Table object and uses argument `db` as the current connection. `db` can be a connection pool, a single connection or a transaction. This method might cause a race condition if use not properly. One shall not modify the slices in the returned *Table.

type TableOption

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

TableOption applies options and helper functions when creating a new table. For example loading column definitions.

func WithConnPool

func WithConnPool(db *dml.ConnPool) TableOption

WithConnPool sets the connection pool to the Tables and each of it Table type. This function has precedence over WithDB.

func WithCreateTable

func WithCreateTable(ctx context.Context, identifierCreateSyntax ...string) TableOption

WithCreateTable upserts tables to the current `Tables` object. Either it adds a new table/view or overwrites existing entries. Argument `identifierCreateSyntax` must be balanced slice where index i is the table/view name and i+1 can be either empty or contain the SQL CREATE statement. In case a SQL CREATE statement has been supplied, it gets executed otherwise ignored. After table initialization the create syntax and the column specifications are getting loaded. Write the SQL CREATE statement in upper case.

WithCreateTable(
	"sales_order_history", "CREATE TABLE `sales_order_history` ( ... )", // table created if not exists
	"sales_order_stat", "CREATE VIEW `sales_order_stat` AS SELECT ...", // table created if not exists
	"sales_order", "", // table/view already exists and gets loaded, NOT dropped.
)

func WithCreateTableFromFile

func WithCreateTableFromFile(ctx context.Context, globPattern string, tableNames ...string) TableOption

WithCreateTableFromFile creates the defined tables from the loaded *.sql files.

func WithDB

func WithDB(db *sql.DB, opts ...dml.ConnPoolOption) TableOption

WithDB sets the DB object to the Tables and all sub Table types to handle the database connections. It must be set if other options get used to access the DB.

func WithDropTable

func WithDropTable(ctx context.Context, option string, tableViewNames ...string) TableOption

WithDropTable drops the tables or views listed in argument `tableViewNames`. If argument `option` contains the string "DISABLE_FOREIGN_KEY_CHECKS", then foreign keys get disabled and at the end re-enabled.

func WithTable

func WithTable(tableName string, cols ...*Column) TableOption

WithTable inserts a new table to the Tables struct. You can optionally specify the columns. Without columns the call to load the columns from the INFORMATION_SCHEMA must be added.

type Tables

type Tables struct {

	// Schema represents the name of the database. Might be empty.
	Schema string
	// contains filtered or unexported fields
}

Tables handles all the tables defined for a package. Thread safe.

func MustNewTables

func MustNewTables(opts ...TableOption) *Tables

MustNewTables same as NewTableService but panics on error.

func NewTables

func NewTables(opts ...TableOption) (*Tables, error)

NewTables creates a new TableService satisfying interface Manager.

func (*Tables) DeleteAllFromCache

func (tm *Tables) DeleteAllFromCache()

DeleteAllFromCache clears the internal table cache and resets the map.

func (*Tables) DeleteFromCache

func (tm *Tables) DeleteFromCache(tableNames ...string)

DeleteFromCache removes tables by their given indexes. If no index has been passed then all entries get removed and the map reinitialized.

func (*Tables) Len

func (tm *Tables) Len() int

Len returns the number of all tables.

func (*Tables) MustTable

func (tm *Tables) MustTable(name string) *Table

MustTable same as Table function but panics when the table cannot be found or any other error occurs.

func (*Tables) Options

func (tm *Tables) Options(opts ...TableOption) error

Options applies options to the Tables service.

func (*Tables) Table

func (tm *Tables) Table(name string) (*Table, error)

Table returns the structure from a map m by a giving index i. What is the reason to use int as the table index and not a name? Because table names between M1 and M2 get renamed and in a Go SQL code generator script of the CoreStore project, we can guarantee that the generated index constant will always stay the same but the name of the table differs.

func (*Tables) Tables

func (tm *Tables) Tables(ret ...string) []string

Tables returns a random list of all available table names. It can append the names to the argument slice.

func (*Tables) Upsert

func (tm *Tables) Upsert(tNew *Table) error

Upsert adds or updates a new table into the internal cache. If a table already exists, then the new table gets applied. The ListenerBuckets gets merged from the existing table to the new table, they will be appended to the new table buckets. Empty columns in the new table gets updated from the existing table.

func (*Tables) Validate

func (tm *Tables) Validate(ctx context.Context) error

Validate validates the table names and their column against the current database schema. The context is used to maybe cancel the "Load Columns" query.

type Variables

type Variables struct {
	Data map[string]string
	Show *dml.Show
}

Variables contains multiple MySQL configuration variables. Not threadsafe.

func NewVariables

func NewVariables(names ...string) *Variables

NewVariables creates a new variable collection. If the argument names gets passed, the SQL query will load the all variables matching the names. Empty argument loads all variables.

func (*Variables) Bool

func (vs *Variables) Bool(key string) (val bool, ok bool)

Bool returns for a given key its bool value. If the key does not exists or string parsing into bool fails, it returns false. Only allowed bool values are YES, NO, ON, OFF and yes, no, on, off.

func (*Variables) Contains

func (vs *Variables) Contains(key, subStr string) bool

Contains check case sensitive if subStr is contained in the value retrieved by key.

func (*Variables) Equal

func (vs *Variables) Equal(key, expected string) bool

Equal compares case sensitive the value of key with the `expected`.

func (*Variables) EqualFold

func (vs *Variables) EqualFold(key, expected string) bool

EqualFold reports whether the value of key and `expected`, interpreted as UTF-8 strings, are equal under Unicode case-folding.

func (*Variables) Float64

func (vs *Variables) Float64(key string) (val float64, ok bool)

Float64 returns for a given key its float64 value. If the key does not exists or string parsing into float fails, it returns false.

func (*Variables) Int64

func (vs *Variables) Int64(key string) (val int64, ok bool)

Int64 returns for a given key its int64 value. If the key does not exists or string parsing into int fails, it returns false.

func (*Variables) Keys

func (vs *Variables) Keys(keys ...string) []string

Keys if argument keys has been provided the map keys will be appended to the slice otherwise a new slice gets returned. The returned slice has a random order. The keys argument is not for filtering.

func (*Variables) MapColumns

func (vs *Variables) MapColumns(rc *dml.ColumnMap) error

MapColumns implements dml.ColumnMapper interface and scans a single row from the database query result.

func (*Variables) String

func (vs *Variables) String(key string) (val string, ok bool)

String returns for a given key its string value. If the key does not exists, it returns false.

func (*Variables) ToSQL

func (vs *Variables) ToSQL() (string, []interface{}, error)

ToSQL implements dml.QueryBuilder interface to assemble a SQL string and its arguments for query execution.

func (*Variables) Uint64

func (vs *Variables) Uint64(key string) (val uint64, ok bool)

Uint64 returns for a given key its uint64 value. If the key does not exists or string parsing into uint fails, it returns false.

Jump to

Keyboard shortcuts

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