{"modulePath":"github.com/weiwolves/pkg","version":"v0.0.0-20200322065615-581c8d33cff6","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package ddl\n\nPackage ddl implements MySQL data definition language functions.\n\nFunctions for tables, columns, statements, replication, validation and DB variables.\n\n[https://launchbylunch.com/posts/2014/Feb/16/sql-naming-conventions/](https://launchbylunch.com/posts/2014/Feb/16/sql-naming-conventions/)\n\n## Constants\n\n```go\nconst (\n\t// Warning: PrefixView/SuffixView is an anti-pattern I've seen many such\n\t// systems where at some point a view will become a table.\n\tPrefixView      = \"view_\" // If identifier starts with this, it is considered a view.\n\tSuffixView      = \"_view\" // If identifier ends with this, it is considered a view.\n\tMainTable       = \"main_table\"\n\tAdditionalTable = \"additional_table\"\n\tScopeTable      = \"scope_table\"\n)\n```\n\n## Functions\n\n```go\nfunc DisableForeignKeys(ctx context.Context, db dml.Execer, callBack func() error) (err error)\n```\n\n```go\nfunc ForeignKeyName(priTableName, priColumnName, refTableName, refColumnName string) string\n```\nForeignKeyName creates a new foreign key name. The returned string represents a valid identifier within MySQL.\n\n```go\nfunc IndexName(indexType, tableName string, fields ...string) string\n```\nIndexName 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.\n\n```go\nfunc LoadColumns(ctx context.Context, db dml.Querier, tables ...string) (map[string]Columns, error)\n```\nLoadColumns 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\\`.\n\n```go\nfunc LoadKeyColumnUsage(ctx context.Context, db dml.Querier, tables ...string) (tc map[string]KeyColumnUsageCollection, err error)\n```\nLoadKeyColumnUsage returns all foreign key columns from a list of table names in the current database. Map key contains TABLE\\_NAME and value contains all of the table foreign keys. All columns from all tables gets selected when you don't provide the argument \\`tables\\`.\n\n```go\nfunc ReverseKeyColumnUsage(kcu map[string]KeyColumnUsageCollection) (kcuRev map[string]KeyColumnUsageCollection)\n```\nReverseKeyColumnUsage reverses the argument to a new key column usage collection. E.g. customer\\_entity, catalog\\_product\\_entity and other tables have a foreign key to table store.store\\_id which is a OneToOne relationship. When reversed the table store, as map key, points to customer\\_entity and catalog\\_product\\_entity which becomes then a OneToMany relationship. If that makes sense is another topic.\n\n```go\nfunc ShortAlias(tableName string) string\n```\nShortAlias creates a short alias name from a table name using the first two characters.\n\n\tcatalog_category_entity_datetime =\u003e cacaenda\n\tcatalog_category_entity_decimal =\u003e cacaende\n\n```go\nfunc TableName(prefix, name string, suffixes ...string) string\n```\nTableName 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.\n\n```go\nfunc TriggerName(tableName, time, event string) string\n```\nTriggerName 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\\`\n\n## Types\n\n```go\ntype Column struct {\n\tField   string      // `COLUMN_NAME` varchar(64) NOT NULL DEFAULT '',\n\tPos     uint64      // `ORDINAL_POSITION` bigint(21) unsigned NOT NULL DEFAULT '0',\n\tDefault null.String // `COLUMN_DEFAULT` longtext,\n\tNull    string      // `IS_NULLABLE` varchar(3) NOT NULL DEFAULT '',\n\t// DataType contains the basic type of a column like smallint, int, mediumblob,\n\t// float, double, etc... but always transformed to lower case.\n\tDataType      string     // `DATA_TYPE` varchar(64) NOT NULL DEFAULT '',\n\tCharMaxLength null.Int64 // `CHARACTER_MAXIMUM_LENGTH` bigint(21) unsigned DEFAULT NULL,\n\tPrecision     null.Int64 // `NUMERIC_PRECISION` bigint(21) unsigned DEFAULT NULL,\n\tScale         null.Int64 // `NUMERIC_SCALE` bigint(21) unsigned DEFAULT NULL,\n\t// ColumnType full SQL string of the column type\n\tColumnType string // `COLUMN_TYPE` longtext NOT NULL,\n\t// Key primary or unique or ...\n\tKey                  string      // `COLUMN_KEY` varchar(3) NOT NULL DEFAULT '',\n\tExtra                string      // `EXTRA` varchar(30) NOT NULL DEFAULT '',\n\tComment              string      // `COLUMN_COMMENT` varchar(1024) NOT NULL DEFAULT '',\n\tGenerated            string      // `IS_GENERATED` varchar(6) NOT NULL DEFAULT '', MariaDB only https://mariadb.com/kb/en/library/information-schema-columns-table/\n\tGenerationExpression null.String // `GENERATION_EXPRESSION` longtext DEFAULT NULL, MariaDB only https://mariadb.com/kb/en/library/information-schema-columns-table/\n\t// Aliases specifies different names used for this column. Mainly used when\n\t// generating code for interface dml.ColumnMapper. For example\n\t// customer_entity.entity_id can also be sales_order.customer_id. The alias\n\t// would be just: entity_id:[]string{\"customer_id\"}.\n\tAliases []string\n\t// Uniquified used when generating code to uniquify the values in a\n\t// collection when the column is not a primary or unique key. The values get\n\t// returned in its own primitive slice.\n\tUniquified bool\n\t// StructTag  used in code generation and applies a custom struct tag.\n\tStructTag string\n}\n```\nColumn contains information about one database table column retrieved from information\\_schema.COLUMNS\n\n```go\nfunc (c *Column) GoComment() string\n```\nGoComment creates a comment from a database column to be used in Go code\n\n```go\nfunc (c *Column) GoString() string\n```\nGoString returns the Go types representation. See interface fmt.GoStringer\n\n```go\nfunc (c *Column) IsAutoIncrement() bool\n```\nIsAutoIncrement checks if column has an auto increment property\n\n```go\nfunc (c *Column) IsBlobDataType() bool\n```\nIsBlobDataType 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.\n\n```go\nfunc (c *Column) IsBool() (ok bool)\n```\nIsBool returns true if column is of type \\`int\\` and its name starts with a special string like: \\`used\\_\\`, \\`is\\_\\`, \\`has\\_\\`.\n\n```go\nfunc (c *Column) IsChar() bool\n```\nIsChar returns true if the column can contain a string or byte values.\n\n```go\nfunc (c *Column) IsCurrentTimestamp() bool\n```\nIsCurrentTimestamp checks if the Default field is a current timestamp\n\n```go\nfunc (c *Column) IsFloat() bool\n```\nIsFloat returns true if a column is of one of the types: decimal, double or float.\n\n```go\nfunc (c *Column) IsGenerated() bool\n```\nIsGenerated returns true if the column is a virtual generated column.\n\n```go\nfunc (c *Column) IsMoney() bool\n```\nIsMoney 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 ...\n\n```go\nfunc (c *Column) IsNull() bool\n```\nIsNull checks if column can have null values\n\n```go\nfunc (c *Column) IsPK() bool\n```\nIsPK checks if column is a primary key\n\n```go\nfunc (c *Column) IsSystemVersioned() bool\n```\nIsSystemVersioned returns true if the column gets used for system versioning. [https://mariadb.com/kb/en/library/system-versioned-tables/](https://mariadb.com/kb/en/library/system-versioned-tables/)\n\n```go\nfunc (c *Column) IsTime() bool\n```\nIsTime returns true if the column is a date, datetime, time or timestamp.\n\n```go\nfunc (c *Column) IsUnique() bool\n```\nIsUnique checks if column is a unique key\n\n```go\nfunc (c *Column) IsUnsigned() bool\n```\nIsUnsigned checks if field TypeRaw contains the word unsigned.\n\n```go\ntype Columns []*Column\n```\nColumns contains a slice of column types\n\n```go\nfunc (cs Columns) ByField(fieldName string) *Column\n```\nByField finds a column by its field name. Case sensitive. Guaranteed to return a non-nil return value.\n\n```go\nfunc (cs Columns) Contains(fieldName string) bool\n```\nContains returns true if fieldName is contained in slice Columns.\n\n```go\nfunc (cs Columns) Each(f func(*Column)) Columns\n```\nEach applies function f to all elements.\n\n```go\nfunc (cs Columns) FieldNames(fn ...string) []string\n```\nFieldNames returns all column names and appends it to \\`fn\\`, if provided.\n\n```go\nfunc (cs Columns) Filter(f func(*Column) bool, cols ...*Column) Columns\n```\nFilter filters the columns by predicate f and appends the column pointers to the optional argument \\`cols\\`.\n\n```go\nfunc (cs Columns) First() *Column\n```\nFirst returns the first column from the slice. Guaranteed to a non-nil return value.\n\n```go\nfunc (cs Columns) GoString() string\n```\nGoString returns the Go types representation. See interface fmt.GoStringer\n\n```go\nfunc (cs Columns) JoinFields(sep string) string\n```\nJoinFields joins the field names into a string, separated by the provided separator.\n\n```go\nfunc (cs Columns) Len() int\n```\nLen returns the length\n\n```go\nfunc (cs Columns) Less(i, j int) bool\n```\nLess compares via the Pos field.\n\n```go\nfunc (cs Columns) NonPrimaryColumns() Columns\n```\nNonPrimaryColumns returns all non primary key and non-unique key columns.\n\n```go\nfunc (cs Columns) PrimaryKeys(cols ...*Column) Columns\n```\nPrimaryKeys returns all primary key columns. It may append the columns to the provided argument slice.\n\n```go\nfunc (cs Columns) String() string\n```\nString same as GoString()\n\n```go\nfunc (cs Columns) Swap(i, j int)\n```\nSwap changes the position\n\n```go\nfunc (cs Columns) UniqueColumns(cols ...*Column) Columns\n```\nUniqueColumns 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.\n\n```go\nfunc (cs Columns) UniqueKeys(cols ...*Column) Columns\n```\nUniqueKeys returns all unique key columns. It may append the columns to the provided argument slice.\n\n```go\nfunc (cs Columns) UniquifiedColumns(cols ...*Column) Columns\n```\nUniquifiedColumns returns all columns which have the flag Uniquified set to true. The result might be appended to argument \\`cols\\`, if provided.\n\n```go\nfunc (cs Columns) ViewPrimaryKeys(cols ...*Column) Columns\n```\nViewPrimaryKeys is a special function for views which might be able to figure out the primary key columns. Neither MySQL nor MariaDB do not report which columns are primary keys in a view. Current implementation checks if a column name ends with \\`\\_id\\` or is \\`id\\` to consider it as a primary key.\n\n```go\ntype InfileOptions struct {\n\t// IsNotLocal disables LOCAL load file. If LOCAL is specified, the file is read\n\t// by the client program on the client host and sent to the server. If LOCAL\n\t// is not specified, the file must be located on the server host and is read\n\t// directly by the server.\n\t// See security issues in https://dev.mysql.com/doc/refman/5.7/en/load-data-local.html\n\tIsNotLocal bool\n\t// Replace, input rows replace existing rows. In other words, rows that have\n\t// the same value for a primary key or unique index as an existing row.\n\tReplace bool\n\t// Ignore, rows that duplicate an existing row on a unique key value are\n\t// discarded.\n\tIgnore bool\n\t// FieldsOptionallyEnclosedBy set true if not all columns are enclosed.\n\tFieldsOptionallyEnclosedBy bool\n\tFieldsEnclosedBy           rune\n\tFieldsEscapedBy            rune\n\tLinesTerminatedBy          string\n\tFieldsTerminatedBy         string\n\t// LinesStartingBy: If all the lines you want to read in have a common\n\t// prefix that you want to ignore, you can use LINES STARTING BY\n\t// 'prefix_string' to skip over the prefix, and anything before it. If a\n\t// line does not include the prefix, the entire line is skipped.\n\tLinesStartingBy string\n\t// IgnoreLinesAtStart can be used to ignore lines at the start of the file.\n\t// For example, you can use IGNORE 1 LINES to skip over an initial header\n\t// line containing column names.\n\tIgnoreLinesAtStart int\n\t// Set must be a balanced key,value slice. The column list (field Columns)\n\t// can contain either column names or user variables. With user variables,\n\t// the SET clause enables you to perform transformations on their values\n\t// before assigning the result to columns. The SET clause can be used to\n\t// supply values not derived from the input file. e.g. SET column3 =\n\t// CURRENT_TIMESTAMP For more details please read\n\t// https://dev.mysql.com/doc/refman/5.7/en/load-data.html\n\tSet []string\n\t// Columns optional custom columns if the default columns of the table\n\t// differs from the CSV file. Column names do NOT get automatically quoted.\n\tColumns []string\n\t// Log optional logger for debugging purposes\n\tLog    log.Logger\n\tExecer dml.Execer\n}\n```\nInfileOptions provides options for the function LoadDataInfile. Some columns are self-describing.\n\n```go\ntype KeyColumnUsage struct {\n\tConstraintCatalog          string      // CONSTRAINT_CATALOG varchar(512) NOT NULL  DEFAULT ''''  \"\"\n\tConstraintSchema           string      // CONSTRAINT_SCHEMA varchar(64) NOT NULL  DEFAULT ''''  \"\"\n\tConstraintName             string      // CONSTRAINT_NAME varchar(64) NOT NULL  DEFAULT ''''  \"\"\n\tTableCatalog               string      // TABLE_CATALOG varchar(512) NOT NULL  DEFAULT ''''  \"\"\n\tTableSchema                string      // TABLE_SCHEMA varchar(64) NOT NULL  DEFAULT ''''  \"\"\n\tTableName                  string      // TABLE_NAME varchar(64) NOT NULL  DEFAULT ''''  \"\"\n\tColumnName                 string      // COLUMN_NAME varchar(64) NOT NULL  DEFAULT ''''  \"\"\n\tOrdinalPosition            int64       // ORDINAL_POSITION bigint(10) NOT NULL  DEFAULT '0'  \"\"\n\tPositionInUniqueConstraint null.Int64  // POSITION_IN_UNIQUE_CONSTRAINT bigint(10) NULL  DEFAULT 'NULL'  \"\"\n\tReferencedTableSchema      null.String // REFERENCED_TABLE_SCHEMA varchar(64) NULL  DEFAULT 'NULL'  \"\"\n\tReferencedTableName        null.String // REFERENCED_TABLE_NAME varchar(64) NULL  DEFAULT 'NULL'  \"\"\n\tReferencedColumnName       null.String // REFERENCED_COLUMN_NAME varchar(64) NULL  DEFAULT 'NULL'  \"\"\n}\n```\nKeyColumnUsage represents a single row for DB table \\`KEY\\_COLUMN\\_USAGE\\`\n\n```go\nfunc (e *KeyColumnUsage) MapColumns(cm *dml.ColumnMap) error\n```\nMapColumns implements interface ColumnMapper only partially.\n\n```go\nfunc (e *KeyColumnUsage) Reset() *KeyColumnUsage\n```\nReset resets the struct to its empty fields.\n\n```go\ntype KeyColumnUsageCollection struct {\n\tData             []*KeyColumnUsage\n\tBeforeMapColumns func(uint64, *KeyColumnUsage) error\n\tAfterMapColumns  func(uint64, *KeyColumnUsage) error\n}\n```\nKeyColumnUsageCollection represents a collection type for DB table KEY\\_COLUMN\\_USAGE Not thread safe. Generated via dmlgen.\n\n```go\nfunc (cc KeyColumnUsageCollection) ColumnNames(ret ...string) []string\n```\nColumnNames 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.\n\n```go\nfunc (cc KeyColumnUsageCollection) MapColumns(cm *dml.ColumnMap) error\n```\nMapColumns implements dml.ColumnMapper interface\n\n```go\nfunc (cc KeyColumnUsageCollection) Sort()\n```\nSort sorts the collection by constraint name.\n\n```go\nfunc (cc KeyColumnUsageCollection) TableNames(ret ...string) []string\n```\nTableNames 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.\n\n```go\ntype KeyRelationShips struct {\n\t// contains filtered or unexported fields\n}\n```\nKeyRelationShips contains an internal cache about the database foreign key structure. It can only be created via function GenerateKeyRelationships.\n\n```go\nfunc GenerateKeyRelationships(ctx context.Context, db dml.Querier, foreignKeys map[string]KeyColumnUsageCollection) (KeyRelationShips, error)\n```\nGenerateKeyRelationships loads the foreign key relationships between a list of given tables or all tables in a database. Might not yet work across several databases on the same file system.\n\n```go\nfunc (krs KeyRelationShips) Debug(w io.Writer)\n```\nDebug writes the internal map in a sorted list to w.\n\n```go\nfunc (krs KeyRelationShips) IsOneToMany(referencedTable, referencedColumn, mainTable, mainColumn string) bool\n```\nIsOneToMany returns true for a oneToMany or switching the tables for a ManyToOne relationship\n\n```go\nfunc (krs KeyRelationShips) IsOneToOne(mainTable, mainColumn, referencedTable, referencedColumn string) bool\n```\nIsOneToOne\n\n```go\nfunc (krs KeyRelationShips) ManyToManyTarget(linkTable, linkColumn string) (oppositeTable string, oppositeColumn string)\n```\nManyToManyTarget figures out if a table has M:N relationships and returns the target table and its column or empty strings if not found.\n\n```go\ntype MasterStatus struct {\n\tFile           string\n\tPosition       uint\n\tBinlogDoDB     string\n\tBinlogIgnoreDB string\n\t// ExecutedGTIDSet: When global transaction IDs are in use, ExecutedGTIDSet\n\t// shows the set of GTIDs for transactions that have been executed on the\n\t// master. This is the same as the value for the gtid_executed system variable\n\t// on this server, as well as the value for ExecutedGTIDSet in the output of\n\t// SHOW SLAVE STATUS on this server.\n\tExecutedGTIDSet string\n}\n```\nMasterStatus 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.\n\n```go\nfunc (ms MasterStatus) Compare(other MasterStatus) int\n```\nCompare 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.\n\n```go\nfunc (ms *MasterStatus) FromString(str string) error\n```\nFromString parses as string in the format: mysql-bin.000002;236423 means filename;position.\n\n```go\nfunc (ms *MasterStatus) MapColumns(rc *dml.ColumnMap) error\n```\nMapColumns implements dml.ColumnMapper interface to scan a row returned from a database query.\n\n```go\nfunc (ms MasterStatus) String() string\n```\nString converts the file name and the position to a string, separated by a semi-colon.\n\n```go\nfunc (ms MasterStatus) ToSQL() (string, []interface{}, error)\n```\nToSQL implements dml.QueryBuilder interface to assemble a SQL string and its arguments for query execution.\n\n```go\nfunc (ms MasterStatus) WriteTo(w io.Writer) (n int64, err error)\n```\nWriteTo implements io.WriterTo and writes the current position and file name to w.\n\n```go\ntype Options struct {\n\tExecer dml.Execer\n\t// Wait see https://mariadb.com/kb/en/wait-and-nowait/ The lock wait timeout\n\t// can be explicitly set in the statement by using either WAIT n (to set the\n\t// wait in seconds) or NOWAIT, in which case the statement will immediately\n\t// fail if the lock cannot be obtained. WAIT 0 is equivalent to NOWAIT.\n\tWait time.Duration\n\t// Nowait see https://mariadb.com/kb/en/wait-and-nowait/ or see field Wait.\n\t// If both are set, Wait wins.\n\tNowait bool\n\t// Comment only supported in the DROP statement. Do not add /* and */ in the\n\t// comment string. Since MariaDB 5.5.27, the comment before the tablenames\n\t// (that /*COMMENT TO SAVE*/) is stored in the binary log. That feature can be\n\t// used by replication tools to send their internal messages.\n\tComment string\n}\n```\nOptions allows to set custom options in the database manipulation functions. More fields might be added.\n\n```go\ntype Table struct {\n\n\t// Always def.\n\tCatalog string\n\t// Database name.\n\tSchema string\n\t// Table name.\n\tName string\n\t// One of BASE TABLE for a regular table, VIEW for a view, SYSTEM VIEW for\n\t// Information Schema tables or SYSTEM VERSIONED for system-versioned tables.\n\tType string\n\t// Storage Engine.\n\tEngine null.String\n\t// Version number from the table's .frm file\n\tVersion null.Uint64\n\t// Row format (see InnoDB, Aria and MyISAM row formats).\n\tRowFormat null.String\n\t// Number of rows in the table. Some engines, such as XtraDB and InnoDB may\n\t// store an estimate.\n\tTableRows null.Uint64\n\t// Average row length in the table.\n\tAvgRowLength null.Uint64\n\t// For InnoDB/XtraDB, the index size, in pages, multiplied by the page size.\n\t// For Aria and MyISAM, length of the data file, in bytes. For MEMORY, the\n\t// approximate allocated memory.\n\tDataLength null.Uint64\n\t// Maximum length of the data file, ie the total number of bytes that could be\n\t// stored in the table. Not used in XtraDB and InnoDB.\n\tMaxDataLength null.Uint64\n\t// Length of the index file.\n\tIndexLength null.Uint64\n\t// Bytes allocated but unused. For InnoDB tables in a shared tablespace, the\n\t// free space of the shared tablespace with small safety margin. An estimate\n\t// in the case of partitioned tables - see the PARTITIONS table.\n\tDataFree null.Uint64\n\t// Next AUTO_INCREMENT value.\n\tAutoIncrement null.Uint64\n\t// Time the table was created.\n\tCreateTime null.Time\n\t// Time the table was last updated. On Windows, the timestamp is not updated on\n\t// update, so MyISAM values will be inaccurate. In InnoDB, if shared\n\t// tablespaces are used, will be NULL, while buffering can also delay the\n\t// update, so the value will differ from the actual time of the last UPDATE,\n\t// INSERT or DELETE.\n\tUpdateTime null.Time\n\t// Time the table was last checked. Not kept by all storage engines, in which\n\t// case will be NULL.\n\tCheckTime null.Time\n\t// Character set and collation.\n\tTableCollation null.String\n\t// Live checksum value, if any.\n\tChecksum null.Uint64\n\t// Extra CREATE TABLE options.\n\tCreateOptions null.String\n\t// Table comment provided when MariaDB created the table.\n\tTableComment   string\n\tMaxIndexLength null.Uint64\n\t// Columns all table columns. They do not get used to create or alter a\n\t// table.\n\tColumns Columns\n\t// contains filtered or unexported fields\n}\n```\nTable 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.\n\n```go\nfunc NewTable(tableName string, cs ...*Column) *Table\n```\nNewTable initializes a new table structure with minimal information and without a database connection.\n\n```go\nfunc (t *Table) Delete() *dml.Delete\n```\nDelete creates a new \\`DELETE FROM table\\` statement.\n\n```go\nfunc (t *Table) DeleteByPK() *dml.Delete\n```\nDeleteByPK creates a new \\`DELETE FROM table WHERE id = ?\\`\n\n```go\nfunc (t *Table) Drop(ctx context.Context, o Options) error\n```\nDrop drops, if exists, the table or the view. To use a custom connection, call WithDB before.\n\n```go\nfunc (t *Table) HasColumn(columnName string) bool\n```\nHasColumn uses the internal cache to check if a column exists in a table and if so returns true. Case sensitive.\n\n```go\nfunc (t *Table) Insert() *dml.Insert\n```\nInsert 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.\n\n```go\nfunc (t *Table) IsView() bool\n```\nIsView determines if a table is a view. Either via system attribute or via its table name.\n\n```go\nfunc (t *Table) LoadDataInfile(ctx context.Context, filePath string, o InfileOptions) error\n```\nLoadDataInfile 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](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](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.\n\n```go\nfunc (t *Table) Optimize(ctx context.Context, o Options) error\n```\nOptimize optimizes a table. [https://mariadb.com/kb/en/optimize-table/](https://mariadb.com/kb/en/optimize-table/)\n\n```go\nfunc (t *Table) Rename(ctx context.Context, newTableName string, o Options) error\n```\nRename 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. [https://mariadb.com/kb/en/rename-table/](https://mariadb.com/kb/en/rename-table/)\n\n```go\nfunc (t *Table) Select(columns ...string) *dml.Select\n```\nSelect creates a new SELECT statement. If \"\\*\" gets set as an argument, then all columns will be added to to list of columns.\n\n```go\nfunc (t *Table) SelectByPK(columns ...string) *dml.Select\n```\nSelectByPK creates a new \\`SELECT columns FROM table WHERE id = ?\\`. If \"\\*\" gets set as an argument, then all columns will be added to to list of columns.\n\n```go\nfunc (t *Table) Swap(ctx context.Context, other string, o Options) error\n```\nSwap 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. RENAME TABLE has to wait for existing queries on the table to finish until it can be executed. That would be fine, but it also locks out other queries while waiting for RENAME to happen! This can cause a serious locking up of your database tables. [https://mariadb.com/kb/en/rename-table/](https://mariadb.com/kb/en/rename-table/)\n\n```go\nfunc (t *Table) Truncate(ctx context.Context, o Options) error\n```\nTruncate 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.\n\n```go\nfunc (t *Table) Update() *dml.Update\n```\nUpdate creates a new UPDATE statement without a WHERE clause.\n\n```go\nfunc (t *Table) UpdateByPK() *dml.Update\n```\nUpdateByPK creates a new \\`UPDATE table SET ... WHERE id = ?\\`. The SET clause contains all non primary columns.\n\n```go\nfunc (t *Table) WhereByPK(op dml.Op) dml.Conditions\n```\nWhereByPK puts the primary keys as WHERE clauses into a condition.\n\n```go\ntype TableLock struct {\n\tSchema                   string // optional\n\tName                     string // required\n\tAlias                    string // optional\n\tLockTypeREAD             bool   // Read lock, no writes allowed\n\tLockTypeREADLOCAL        bool   // Read lock, but allow concurrent inserts\n\tLockTypeWRITE            bool   // Exclusive write lock. No other connections can read or write to this table\n\tLockTypeLowPriorityWrite bool   // Exclusive write lock, but allow new read locks on the table until we get the write lock.\n\tLockTypeWriteConcurrent  bool   // Exclusive write lock, but allow READ LOCAL locks to the table.\n}\n```\nTableLock defines the tables which are getting locked. Only one of the five lock types can be set. [https://mariadb.com/kb/en/lock-tables/](https://mariadb.com/kb/en/lock-tables/)\n\n```go\ntype TableOption struct {\n\t// contains filtered or unexported fields\n}\n```\nTableOption applies options and helper functions when creating a new table. For example loading column definitions.\n\n```go\nfunc WithConnPool(db *dml.ConnPool) TableOption\n```\nWithConnPool sets the connection pool to the Tables and each of it Table type. This function has precedence over WithDB.\n\n```go\nfunc WithCreateTable(ctx context.Context, identifierCreateSyntax ...string) TableOption\n```\nWithCreateTable 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 but only if a connection has been set beforehand. Write the SQL CREATE statement in upper case.\n\n\tWithCreateTable(\n\t\t\"sales_order_history\", \"CREATE TABLE `sales_order_history` ( ... )\", // table created if not exists\n\t\t\"sales_order_stat\", \"CREATE VIEW `sales_order_stat` AS SELECT ...\", // table created if not exists\n\t\t\"sales_order\", \"\", // table/view already exists and gets loaded, NOT dropped.\n\t)\n\n```go\nfunc WithCreateTableFromFile(ctx context.Context, globPattern string, tableNames ...string) TableOption\n```\nWithCreateTableFromFile creates the defined tables from the loaded \\*.sql files.\n\n```go\nfunc WithDB(db *sql.DB, opts ...dml.ConnPoolOption) TableOption\n```\nWithDB 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.\n\n```go\nfunc WithDropTable(ctx context.Context, option string, tableViewNames ...string) TableOption\n```\nWithDropTable drops the tables or views listed in argument \\`tableViewNames\\`. If argument \\`option\\` contains the string \"DISABLE\\_FOREIGN\\_KEY\\_CHECKS\", then foreign keys are getting disabled and at the end re-enabled.\n\n```go\nfunc WithLoadTables(ctx context.Context, db dml.Querier, tableNames ...string) TableOption\n```\nWithLoadTables loads all tables and their columns in a database or only the specified tables. Uses INFORMATION\\_SCHEMA.COLUMNS and INFORMATION\\_SCHEMA.TABLES system views.\n\n```go\nfunc WithQueryDBR(key string, dbr *dml.DBR) TableOption\n```\nWithQueryDBR adds a pre-defined query with its key to the Tables object.\n\n```go\nfunc WithQueryDBRCallBack(cbFn func(key string, dbr *dml.DBR)) TableOption\n```\nWithQueryDBRCallBack allows to manipulate the generated dml.DBR objects in generated code to fit your needs.\n\n```go\nfunc WithTable(tableName string, cols ...*Column) TableOption\n```\nWithTable 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.\n\n```go\ntype Tables struct {\n\n\t// Schema represents the name of the database. Might be empty.\n\tSchema string\n\t// contains filtered or unexported fields\n}\n```\nTables handles all the tables defined for a package. Thread safe.\n\n```go\nfunc MustNewTables(opts ...TableOption) *Tables\n```\nMustNewTables same as NewTableService but panics on error.\n\n```go\nfunc NewTables(opts ...TableOption) (*Tables, error)\n```\nNewTables creates a new TableService satisfying interface Manager.\n\n```go\nfunc (tm *Tables) CachedQueries() map[string]string\n```\nCachedQueries returns a copy of the cached SQL queries. cache key =\u003e SQL string.\n\n```go\nfunc (tm *Tables) CachedQuery(key string) *dml.DBR\n```\nCachedQuery returns a SQL query string by its cache key. If a cache key does not exists, it panics. Do not share the returned pointer by multiple goroutines. This function must only be used by generated code.\n\n```go\nfunc (tm *Tables) DeleteAllFromCache()\n```\nDeleteAllFromCache clears the internal table cache and resets the maps.\n\n```go\nfunc (tm *Tables) DeleteFromCache(tableNames ...string)\n```\nDeleteFromCache removes tables by their given indexes. If no index has been passed then all entries get removed and the map reinitialized.\n\n```go\nfunc (tm *Tables) Len() int\n```\nLen returns the number of all tables.\n\n```go\nfunc (tm *Tables) Lock(ctx context.Context, o Options, tables []TableLock, fns ...func(*dml.Conn) error) (err error)\n```\nLock runs the functions within the acquired table locks. On error or success the lock gets automatically released. The Options do not support the Execer field. All queries run in a single database connection (\\*sql.Conn). Locks may be used to emulate transactions or to get more speed when updating tables.\n\n```go\nfunc (tm *Tables) MustTable(name string) *Table\n```\nMustTable same as Table function but panics when the table cannot be found or any other error occurs.\n\n```go\nfunc (tm *Tables) Optimize(ctx context.Context, o Options) error\n```\nOptimize optimizes all tables. [https://mariadb.com/kb/en/optimize-table/](https://mariadb.com/kb/en/optimize-table/) NO\\_WRITE\\_TO\\_BINLOG is not yet supported.\n\n```go\nfunc (tm *Tables) Options(opts ...TableOption) error\n```\nOptions applies options to the Tables service.\n\n```go\nfunc (tm *Tables) SingleConnection(ctx context.Context, fns ...func(*dml.Conn) error) (err error)\n```\nSingleConnection runs all fns in a single connection and guarantees no change to the connection. Single session. If more than one \\`fns\\` gets added, the last function of the fns slice runs in a defer statement before the connection close.\n\n```go\nfunc (tm *Tables) Table(name string) (*Table, error)\n```\nTable 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.\n\n```go\nfunc (tm *Tables) Tables(ret ...string) []string\n```\nTables returns a random list of all available table names. It can append the names to the argument slice.\n\n```go\nfunc (tm *Tables) Transaction(ctx context.Context, opts *sql.TxOptions, fns ...func(*dml.Tx) error) error\n```\nTransaction runs all fns within a transaction. On error it calls automatically ROLLBACK and on success (no error) COMMIT.\n\n```go\nfunc (tm *Tables) Truncate(ctx context.Context, o Options) error\n```\nTruncate force truncates all tables by also disabling foreign keys. Does not guarantee to run all commands over the same connection but you can set a custom dml.Execer.\n\n```go\nfunc (tm *Tables) Upsert(tNew *Table) error\n```\nUpsert 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.\n\n```go\nfunc (tm *Tables) Validate(ctx context.Context) error\n```\nValidate validates the table names and their column against the current database schema. The context is used to maybe cancel the \"Load Columns\" query.\n\n```go\nfunc (tm *Tables) WithRawSQL(query string) *dml.DBR\n```\nWithRawSQL creates a database runner with a raw SQL string.\n\n```go\ntype Variables struct {\n\tData map[string]string\n\tShow *dml.Show\n}\n```\nVariables contains multiple MySQL configuration variables. Not threadsafe.\n\n```go\nfunc NewVariables(names ...string) *Variables\n```\nNewVariables 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.\n\n```go\nfunc (vs *Variables) Bool(key string) (val bool, ok bool)\n```\nBool 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.\n\n```go\nfunc (vs *Variables) Contains(key, subStr string) bool\n```\nContains check case sensitive if subStr is contained in the value retrieved by key.\n\n```go\nfunc (vs *Variables) Equal(key, expected string) bool\n```\nEqual compares case sensitive the value of key with the \\`expected\\`.\n\n```go\nfunc (vs *Variables) EqualFold(key, expected string) bool\n```\nEqualFold reports whether the value of key and \\`expected\\`, interpreted as UTF-8 strings, are equal under Unicode case-folding.\n\n```go\nfunc (vs *Variables) Float64(key string) (val float64, ok bool)\n```\nFloat64 returns for a given key its float64 value. If the key does not exists or string parsing into float fails, it returns false.\n\n```go\nfunc (vs *Variables) Int64(key string) (val int64, ok bool)\n```\nInt64 returns for a given key its int64 value. If the key does not exists or string parsing into int fails, it returns false.\n\n```go\nfunc (vs *Variables) Keys(keys ...string) []string\n```\nKeys 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.\n\n```go\nfunc (vs *Variables) MapColumns(rc *dml.ColumnMap) error\n```\nMapColumns implements dml.ColumnMapper interface and scans a single row from the database query result.\n\n```go\nfunc (vs *Variables) String(key string) (val string, ok bool)\n```\nString returns for a given key its string value. If the key does not exists, it returns false.\n\n```go\nfunc (vs *Variables) ToSQL() (string, []interface{}, error)\n```\nToSQL implements dml.QueryBuilder interface to assemble a SQL string and its arguments for query execution.\n\n```go\nfunc (vs *Variables) Uint64(key string) (val uint64, ok bool)\n```\nUint64 returns for a given key its uint64 value. If the key does not exists or string parsing into uint fails, it returns false.\n\n","path":"github.com/weiwolves/pkg/sql/ddl","name":"ddl","synopsis":"Package ddl implements MySQL data definition language functions.","isRedistributable":true}
