ddl

package
v0.0.0-...-202847b Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2023 License: Apache-2.0 Imports: 22 Imported by: 19

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 (
	// Warning: PrefixView/SuffixView is an anti-pattern I've seen many such
	// systems where at some point a view will become a table.
	PrefixView      = "view_" // If identifier starts with this, it is considered a view.
	SuffixView      = "_view" // If identifier ends with this, it is considered a view.
	MainTable       = "main_table"
	AdditionalTable = "additional_table"
	ScopeTable      = "scope_table"
)

Variables

This section is empty.

Functions

func DisableForeignKeys

func DisableForeignKeys(ctx context.Context, db dml.Execer, callBack func() error) (err error)

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 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`.

func ReverseKeyColumnUsage

func ReverseKeyColumnUsage(kcu map[string]KeyColumnUsageCollection) (kcuRev map[string]KeyColumnUsageCollection)

ReverseKeyColumnUsage 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.

func ShortAlias

func ShortAlias(tableName string) string

ShortAlias 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 (*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) HasEqualType

func (c *Column) HasEqualType(c2 *Column) bool

HasEqualType returns true if the type matches and nullable.

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) IsChar

func (c *Column) IsChar() bool

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

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) 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) IsTime

func (c *Column) IsTime() bool

IsTime returns true if the column is a date, datetime, time or timestamp.

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) Each

func (cs Columns) Each(f func(*Column)) Columns

Each applies function f to all elements.

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.

func (Columns) ViewPrimaryKeys

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

ViewPrimaryKeys 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.

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
	Execer dml.Execer
}

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`

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 (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) Sort

func (cc KeyColumnUsageCollection) Sort()

Sort sorts the collection by constraint name.

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 KeyRelationShips

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

KeyRelationShips contains an internal cache about the database foreign key structure. It can only be created via function GenerateKeyRelationships.

func GenerateKeyRelationships

func GenerateKeyRelationships(ctx context.Context, db dml.Querier, foreignKeys map[string]KeyColumnUsageCollection) (KeyRelationShips, error)

GenerateKeyRelationships 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.

func (KeyRelationShips) Debug

func (krs KeyRelationShips) Debug(w io.Writer)

Debug writes the internal map in a sorted list to w.

func (KeyRelationShips) IsOneToMany

func (krs KeyRelationShips) IsOneToMany(referencedTable, referencedColumn, mainTable, mainColumn string) bool

IsOneToMany returns true for a oneToMany or switching the tables for a ManyToOne relationship

func (KeyRelationShips) IsOneToOne

func (krs KeyRelationShips) IsOneToOne(mainTable, mainColumn, referencedTable, referencedColumn string) bool

IsOneToOne

func (KeyRelationShips) ManyToManyTarget

func (krs KeyRelationShips) ManyToManyTarget(linkTable, linkColumn string) (oppositeTable string, oppositeColumn string)

ManyToManyTarget figures out if a table has M:N relationships and returns the target table and its column or empty strings if not found.

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, []any, 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 Options

type Options struct {
	Execer dml.Execer
	// Wait see https://mariadb.com/kb/en/wait-and-nowait/ The lock wait timeout
	// can be explicitly set in the statement by using either WAIT n (to set the
	// wait in seconds) or NOWAIT, in which case the statement will immediately
	// fail if the lock cannot be obtained. WAIT 0 is equivalent to NOWAIT.
	Wait time.Duration
	// Nowait see https://mariadb.com/kb/en/wait-and-nowait/ or see field Wait.
	// If both are set, Wait wins.
	Nowait bool
	// Comment only supported in the DROP statement. Do not add /* and */ in the
	// comment string. Since MariaDB 5.5.27, the comment before the tablenames
	// (that /*COMMENT TO SAVE*/) is stored in the binary log. That feature can be
	// used by replication tools to send their internal messages.
	Comment string
}

Options allows to set custom options in the database manipulation functions. More fields might be added.

type Table

type Table struct {

	// Always def.
	Catalog string
	// Database name.
	Schema string
	// Table name.
	Name string
	// One of BASE TABLE for a regular table, VIEW for a view, SYSTEM VIEW for
	// Information Schema tables or SYSTEM VERSIONED for system-versioned tables.
	Type string
	// Storage Engine.
	Engine null.String
	// Version number from the table's .frm file
	Version null.Uint64
	// Row format (see InnoDB, Aria and MyISAM row formats).
	RowFormat null.String
	// Number of rows in the table. Some engines, such as XtraDB and InnoDB may
	// store an estimate.
	TableRows null.Uint64
	// Average row length in the table.
	AvgRowLength null.Uint64
	// For InnoDB/XtraDB, the index size, in pages, multiplied by the page size.
	// For Aria and MyISAM, length of the data file, in bytes. For MEMORY, the
	// approximate allocated memory.
	DataLength null.Uint64
	// Maximum length of the data file, ie the total number of bytes that could be
	// stored in the table. Not used in XtraDB and InnoDB.
	MaxDataLength null.Uint64
	// Length of the index file.
	IndexLength null.Uint64
	// Bytes allocated but unused. For InnoDB tables in a shared tablespace, the
	// free space of the shared tablespace with small safety margin. An estimate
	// in the case of partitioned tables - see the PARTITIONS table.
	DataFree null.Uint64
	// Next AUTO_INCREMENT value.
	AutoIncrement null.Uint64
	// Time the table was created.
	CreateTime null.Time
	// Time the table was last updated. On Windows, the timestamp is not updated on
	// update, so MyISAM values will be inaccurate. In InnoDB, if shared
	// tablespaces are used, will be NULL, while buffering can also delay the
	// update, so the value will differ from the actual time of the last UPDATE,
	// INSERT or DELETE.
	UpdateTime null.Time
	// Time the table was last checked. Not kept by all storage engines, in which
	// case will be NULL.
	CheckTime null.Time
	// Character set and collation.
	TableCollation null.String
	// Live checksum value, if any.
	Checksum null.Uint64
	// Extra CREATE TABLE options.
	CreateOptions null.String
	// Table comment provided when MariaDB created the table.
	TableComment   string
	MaxIndexLength null.Uint64
	// Columns all table columns. They do not get used to create or alter a
	// table.
	Columns Columns
	// 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 with minimal information and without a database connection.

func (*Table) Delete

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

Delete creates a new `DELETE FROM table` statement.

func (*Table) DeleteByPK

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

DeleteByPK creates a new `DELETE FROM table WHERE id = ?`

func (*Table) Drop

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

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

func (*Table) HasColumn

func (t *Table) HasColumn(columnName string) bool

HasColumn uses the internal cache to check if a column exists in a table and if so returns true. Case sensitive.

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) IsView

func (t *Table) IsView() bool

IsView determines if a table is a view. Either via system attribute or via its table name.

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 allowlisted by registering them with mysql.RegisterLocalFile(filepath) (recommended) or the allow list 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) Optimize

func (t *Table) Optimize(ctx context.Context, o Options) error

Optimize optimizes a table. https://mariadb.com/kb/en/optimize-table/

func (*Table) Rename

func (t *Table) Rename(ctx context.Context, newTableName string, o Options) 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. https://mariadb.com/kb/en/rename-table/

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(columns ...string) *dml.Select

SelectByPK 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.

func (*Table) Swap

func (t *Table) Swap(ctx context.Context, other string, o Options) 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. 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/

func (*Table) Truncate

func (t *Table) Truncate(ctx context.Context, o Options) 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) Update

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

Update creates a new UPDATE statement without a WHERE clause.

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) WhereByPK

func (t *Table) WhereByPK(op dml.Op) dml.Conditions

WhereByPK puts the primary keys as WHERE clauses into a condition.

type TableLock

type TableLock struct {
	Schema                   string // optional
	Name                     string // required
	Alias                    string // optional
	LockTypeREAD             bool   // Read lock, no writes allowed
	LockTypeREADLOCAL        bool   // Read lock, but allow concurrent inserts
	LockTypeWRITE            bool   // Exclusive write lock. No other connections can read or write to this table
	LockTypeLowPriorityWrite bool   // Exclusive write lock, but allow new read locks on the table until we get the write lock.
	LockTypeWriteConcurrent  bool   // Exclusive write lock, but allow READ LOCAL locks to the table.
}

TableLock defines the tables which are getting locked. Only one of the five lock types can be set. https://mariadb.com/kb/en/lock-tables/

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 but only if a connection has been set beforehand. 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 are getting disabled and at the end re-enabled.

func WithLoadTables

func WithLoadTables(ctx context.Context, db dml.Querier, tableNames ...string) TableOption

WithLoadTables loads all tables and their columns in a database or only the specified tables. Uses INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.TABLES system views.

func WithQueryDBR

func WithQueryDBR(rqb map[string]dml.QueryBuilder) TableOption

WithQueryDBR adds a pre-defined query with its key to the Tables object.

func WithQueryDBRCallBack

func WithQueryDBRCallBack(cbFn func(key string, dbr *dml.DBR)) TableOption

WithQueryDBRCallBack allows to manipulate the generated dml.DBR objects in generated code to fit your needs.

func WithTable

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

WithTable upserts 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 {
	ConnPool *dml.ConnPool // database connection pool
	// 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 maps.

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) Lock

func (tm *Tables) Lock(ctx context.Context, o Options, tables []TableLock, fn func(*dml.Conn) error) (err error)

Lock 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.

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) Optimize

func (tm *Tables) Optimize(ctx context.Context, o Options) error

Optimize optimizes all tables. https://mariadb.com/kb/en/optimize-table/ NO_WRITE_TO_BINLOG is not yet supported.

func (*Tables) Options

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

Options applies options to the Tables service.

func (*Tables) SingleConnection

func (tm *Tables) SingleConnection(ctx context.Context, fns ...func(*dml.Conn) error) (err error)

SingleConnection 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.

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) Transaction

func (tm *Tables) Transaction(ctx context.Context, opts *sql.TxOptions, fn func(*dml.Tx) error) error

Transaction runs all fns within a transaction. On error it calls automatically ROLLBACK and on success (no error) COMMIT.

func (*Tables) Truncate

func (tm *Tables) Truncate(ctx context.Context, o Options) error

Truncate 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.

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, []any, 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