Documentation ¶
Overview ¶
Package migration contains the elements for writing and running database migration operations.
Index ¶
Constants ¶
const ( NoAction refOption = "NO ACTION" SetNull refOption = "SET NULL" SetDefault refOption = "SET DEFAULT" Cascade refOption = "CASCADE" Restrict refOption = "RESTRICT" )
const MySQL = "mysql"
MySQL is the constant name of the MySQL dialect translator.
const PostgreSQL = "postgresql"
PostgreSQL is the constant name of the PostgreSQL dialect translator.
const SQLite = "sqlite"
SQLite is the constant name of the SQLite dialect translator.
Variables ¶
var ( // PrimaryKey declares the column as the table's primary key. Only 1 primary // key is allowed per table. For multi-column primary keys, use table constraints // instead. PrimaryKey = &pk{} // ForeignKey declares the column as a foreign key referencing the given table. ForeignKey = fkFn // NotNull adds a 'not null' constraint to the column. NotNull = ¬Null{} // AutoIncr adds an auto-increment to the column. Only works on columns with // type TinyInt, SmallInt, Integer & BigInt. AutoIncr = &autoIncr{} // Unique adds a 'unique' constraint to the column. To place a 'unique' // constraint on multiple columns, use table constraints instead. Unique = &unique{} // Default adds a default value to the column. The value should be given as // parameter of the constraint (ex: Default(0)). Default = defaultFn )
The different types of column constraints usable in a CREATE TABLE statement.
var ( // MultiPrimaryKey adds a primary-key constraint to the given columns. MultiPrimaryKey = pkFn // MultiUnique adds a 'unique' constraint to the given columns. MultiUnique = uniqueFn // MultiIndex creates an index on the given columns. MultiIndex = indexFn // Check add a check constraint to the table. Check = checkFn )
The different types of table constraints usable in a CREATE TABLE statement.
var ( Boolean = sqlType{/* contains filtered or unexported fields */} TinyInt = sqlType{/* contains filtered or unexported fields */} SmallInt = sqlType{/* contains filtered or unexported fields */} Integer = sqlType{/* contains filtered or unexported fields */} BigInt = sqlType{/* contains filtered or unexported fields */} Float = sqlType{/* contains filtered or unexported fields */} Double = sqlType{/* contains filtered or unexported fields */} Varchar = func(s uint64) sqlType { return sqlType{code: varchar, size: s} } Text = sqlType{/* contains filtered or unexported fields */} Date = sqlType{/* contains filtered or unexported fields */} DateTime = sqlType{/* contains filtered or unexported fields */} Timestamp = sqlType{/* contains filtered or unexported fields */} Timestampz = sqlType{/* contains filtered or unexported fields */} Binary = func(s uint64) sqlType { return sqlType{code: binary, size: s} } Blob = sqlType{/* contains filtered or unexported fields */} )
The SQL types supported by the migration engine. These values should be used when declaring a column or when adding a row to a table. If a database RDBMS does not support a specific type, it will be converted to the closest supported equivalent.
var CurrentTimestamp = &curTimestamp{}
var ErrUnknownDialect = errors.New("unknown SQL dialect")
Functions ¶
This section is empty.
Types ¶
type Actions ¶
type Actions interface { // Query executes a query that returns rows, typically a SELECT. // Query uses '?' as placeholder for arguments, no matter the database backend. Query(query string, args ...any) (*sql.Rows, error) // QueryRow executes a query that is expected to return at most one row. // QueryRow always returns a non-nil value. Errors are deferred until // Row's Scan method is called. // If the query selects no rows, the *Row's Scan will return ErrNoRows. // Otherwise, the *Row's Scan scans the first selected row and discards // the rest. // QueryRow uses '?' as placeholder for arguments, no matter the database backend. QueryRow(query string, args ...any) *sql.Row // Exec executes a prepared statement with the given arguments. The statement // should not return anything. If it does, use Query or QueryRow instead. // Exec uses '?' as placeholder for arguments, no matter the database backend. Exec(query string, args ...any) error // GetDialect returns the database's dialect. GetDialect() string // FormatValue takes a Go value and returns the corresponding SQL value in // the given SQL type. If the given value cannot be formatted in the given // type, an error is returned. FormatValue(val any) (string, error) // CreateTable creates a new table with the given definitions. A definition // can be either Column or a TableConstraint. CreateTable(name string, defs ...Definition) error // AddColumn adds a new column to the table with the given type and constraints. // It is up to the migration script to then fill that column if necessary. AddColumn(table, column string, dataType sqlType, constraints ...Constraint) error // AddRow inserts a new row into the given table. // Deprecated: simply use Exec with an 'INSERT INTO' command. AddRow(table string, values Values) error // RenameTable changes the name of the given table to a new one. This is a // destructive (non retro-compatible) operation. RenameTable(oldName, newName string) error // DropTable drops the given table. This is a destructive (non // retro-compatible) operation. DropTable(name string) error // RenameColumn changes the name of the given column. This is a destructive // (non retro-compatible) operation. RenameColumn(table, oldName, newName string) error // ChangeColumnType changes the type of the given column. This is a // destructive (non retro-compatible) operation. ChangeColumnType(table, col string, to sqlType) error // SwapColumns swaps all the values of col1 and col2 for the rows fulfilling // the given conditions. The columns' types MUST be compatible for this // operation to work. SwapColumns(table, col1, col2, cond string, condArgs ...any) error // DropColumn drops the given column. This is a destructive (non // retro-compatible) operation. DropColumn(table, name string) error // CreateIndex adds an index (unique or not) on the given columns of the given // table. CreateIndex(isUnique bool, table, indexName string, cols ...string) error // DropIndex drops the index (unique or not) on the given columns of the given // table if it exists. DropIndex(isUnique bool, table, indexName string) error }
Actions is an interface regrouping all the database actions available inside a migration script.
type Column ¶
type Column struct { Name string Type sqlType Constraints []Constraint }
Column is a type representing a column declaration in a CREATE TABLE statement. It contains the column's name, type and its constraints (if it has some).
func Col ¶
func Col(name string, typ sqlType, constraints ...Constraint) Column
Col is a shortcut function for instantiating a column without having to declare the attributes' names.
type Constraint ¶
type Constraint any
Constraint represents a single SQL column constraint to be used when declaring a column. Valid constraints are: PrimaryKey, ForeignKey, NotNull, AutoIncr, Unique and Default.
type Definition ¶
type Definition any
Definition represents one part of a column definition. It can be a column or a table constraint.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is an object which can execute a series of script, using the Up and Down functions. It requires an *sql.DB and an SQL dialect to initiate.
func NewEngine ¶
NewEngine returns a new Engine for the given sql.DB, using the given SQL dialect. Errors and requests will be logged on the given Logger.
If the io.Writer argument is not nil, the commands (except for queries) will be written to it instead of being sent to the database. This can be useful if one wishes to execute the migration directly, instead of leaving it to the engine itself.
func (*Engine) Downgrade ¶
Downgrade takes a slice of migrations, and "reverts" them by calling all their Down functions in reverse order, starting from the last one. All the migrations are run inside a single transaction, and if any of them fails, the whole transaction will be canceled.
type Logger ¶
type Logger interface { Trace(msg string, args ...any) Debug(msg string, args ...any) Info(msg string, args ...any) Warning(msg string, args ...any) Error(msg string, args ...any) Critical(msg string, args ...any) Alert(msg string, args ...any) }
Logger is the interface which must be implemented by loggers.
type Migration ¶
type Migration []Script
A Migration is a list of Script which can be executed by the Engine.
type Script ¶
type Script struct { // A short description of what the script does. Description string // Up applies the migration. Up func(db Actions) error // Down undoes migration. Down func(db Actions) error }
Script represents a collection of database changes. It is recommended to keep scripts short, and not to run many operation in a single script.
type TableConstraint ¶
type TableConstraint any
TableConstraint represents a constraint put on an SQL table when declaring said table. Valid table constraints are: MultiPrimaryKey, MultiUnique and Check.