schema

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2023 License: Apache-2.0 Imports: 28 Imported by: 1,995

Documentation

Overview

Package schema contains all schema migration logic for SQL dialects.

Index

Constants

View Source
const (
	// ModeReplay computes the current state by replaying the migration directory on the connected database.
	ModeReplay = iota
	// ModeInspect computes the current state by inspecting the connected database.
	ModeInspect
)
View Source
const (
	// TypeTable defines the table name holding the type information.
	TypeTable = "ent_types"

	// MaxTypes defines the max number of types can be created when
	// defining universal ids. The left 16-bits are reserved.
	MaxTypes = math.MaxUint16
)
View Source
const (
	// DefaultStringLen describes the default length for string/varchar types.
	DefaultStringLen int64 = 255
	// Null is the string representation of NULL in SQL.
	Null = "NULL"
	// PrimaryKey is the string representation of PKs in SQL.
	PrimaryKey = "PRI"
	// UniqueKey is the string representation of PKs in SQL.
	UniqueKey = "UNI"
)

Variables

This section is empty.

Functions

func Diff added in v0.11.0

func Diff(ctx context.Context, u, name string, tables []*Table, opts ...MigrateOption) (err error)

Diff compares the state read from a database connection or migration directory with the state defined by the Ent schema. Changes will be written to new migration files.

Types

type Applier added in v0.10.0

type Applier interface {
	// Apply applies the given migrate.Plan on the database.
	Apply(context.Context, dialect.ExecQuerier, *migrate.Plan) error
}

Applier is the interface that wraps the Apply method.

type ApplyFunc added in v0.10.0

type ApplyFunc func(context.Context, dialect.ExecQuerier, *migrate.Plan) error

The ApplyFunc type is an adapter to allow the use of ordinary function as Applier. If f is a function with the appropriate signature, ApplyFunc(f) is an Applier that calls f.

func (ApplyFunc) Apply added in v0.10.0

func (f ApplyFunc) Apply(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error

Apply calls f(ctx, tables...).

type ApplyHook added in v0.10.0

type ApplyHook func(Applier) Applier

ApplyHook defines the "migration applying middleware". A function that gets an Applier and returns an Applier.

type Atlas added in v0.11.0

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

Atlas atlas migration engine.

func NewMigrate

func NewMigrate(drv dialect.Driver, opts ...MigrateOption) (*Atlas, error)

NewMigrate creates a new Atlas form the given dialect.Driver.

func NewMigrateURL added in v0.11.0

func NewMigrateURL(u string, opts ...MigrateOption) (*Atlas, error)

NewMigrateURL create a new Atlas from the given url.

func (*Atlas) Create added in v0.11.0

func (a *Atlas) Create(ctx context.Context, tables ...*Table) (err error)

Create creates all schema resources in the database. It works in an "append-only" mode, which means, it only creates tables, appends columns to tables or modifies column types.

Column can be modified by turning into a NULL from NOT NULL, or having a type conversion not resulting data altering. From example, changing varchar(255) to varchar(120) is invalid, but changing varchar(120) to varchar(255) is valid. For more info, see the convert function below.

func (*Atlas) Diff added in v0.11.0

func (a *Atlas) Diff(ctx context.Context, tables ...*Table) error

Diff compares the state read from the connected database with the state defined by Ent. Changes will be written to migration files by the configured Planner.

func (*Atlas) NamedDiff added in v0.11.0

func (a *Atlas) NamedDiff(ctx context.Context, name string, tables ...*Table) error

NamedDiff compares the state read from the connected database with the state defined by Ent. Changes will be written to migration files by the configured Planner.

func (*Atlas) StateReader added in v0.11.0

func (a *Atlas) StateReader(tables ...*Table) migrate.StateReaderFunc

StateReader returns an atlas migrate.StateReader returning the state as described by the Ent table slice.

func (*Atlas) VerifyTableRange added in v0.11.0

func (a *Atlas) VerifyTableRange(ctx context.Context, tables []*Table) error

VerifyTableRange ensures, that the defined autoincrement starting value is set for each table as defined by the TypTable. This is necessary for MySQL versions < 8.0. In those versions the defined starting value for AUTOINCREMENT columns was stored in memory, and when a server restarts happens and there are no rows yet in a table, the defined starting value is lost, which will result in incorrect behavior when working with global unique ids. Calling this method on service start ensures the information are correct and are set again, if they aren't. For MySQL versions > 8 calling this method is only required once after the upgrade.

type ChangeKind added in v0.10.0

type ChangeKind uint

A ChangeKind denotes the kind of schema change.

const (
	NoChange  ChangeKind = 0
	AddSchema ChangeKind = 1 << (iota - 1)
	ModifySchema
	DropSchema
	AddTable
	ModifyTable
	DropTable
	AddColumn
	ModifyColumn
	DropColumn
	AddIndex
	ModifyIndex
	DropIndex
	AddForeignKey
	ModifyForeignKey
	DropForeignKey
	AddCheck
	ModifyCheck
	DropCheck
)

List of change types.

func (ChangeKind) Is added in v0.10.0

func (k ChangeKind) Is(c ChangeKind) bool

Is reports whether c is match the given change kind.

type Column

type Column struct {
	Name       string            // column name.
	Type       field.Type        // column type.
	SchemaType map[string]string // optional schema type per dialect.
	Attr       string            // extra attributes.
	Size       int64             // max size parameter for string, blob, etc.
	Key        string            // key definition (PRI, UNI or MUL).
	Unique     bool              // column with unique constraint.
	Increment  bool              // auto increment attribute.
	Nullable   bool              // null or not null attribute.
	Default    any               // default value.
	Enums      []string          // enum values.
	Collation  string            // collation type (utf8mb4_unicode_ci, utf8mb4_general_ci)

	Comment string // optional column comment.
	// contains filtered or unexported fields
}

Column schema definition for SQL dialects.

func (*Column) ConvertibleTo

func (c *Column) ConvertibleTo(d *Column) bool

ConvertibleTo reports whether a column can be converted to the new column without altering its data.

func (Column) FloatType

func (c Column) FloatType() bool

FloatType reports of the given type is a float type (float32, float64).

func (Column) IntType

func (c Column) IntType() bool

IntType reports whether the column is an int type (int8 ... int64).

func (*Column) PrimaryKey

func (c *Column) PrimaryKey() bool

PrimaryKey returns boolean indicates if this column is on of the primary key columns. Used by the migration tool when parsing the `DESCRIBE TABLE` output Go objects.

func (*Column) ScanDefault

func (c *Column) ScanDefault(value string) error

ScanDefault scans the default value string to its interface type.

func (Column) UintType

func (c Column) UintType() bool

UintType reports of the given type is a uint type (int8 ... int64).

func (*Column) UniqueKey

func (c *Column) UniqueKey() bool

UniqueKey returns boolean indicates if this column is a unique key. Used by the migration tool when parsing the `DESCRIBE TABLE` output Go objects.

type CreateFunc

type CreateFunc func(context.Context, ...*Table) error

The CreateFunc type is an adapter to allow the use of ordinary function as Creator. If f is a function with the appropriate signature, CreateFunc(f) is a Creator that calls f.

func (CreateFunc) Create

func (f CreateFunc) Create(ctx context.Context, tables ...*Table) error

Create calls f(ctx, tables...).

type Creator

type Creator interface {
	// Create creates the given tables in the database. See Migrate.Create for more details.
	Create(context.Context, ...*Table) error
}

Creator is the interface that wraps the Create method.

type DiffFunc added in v0.10.0

type DiffFunc func(current, desired *schema.Schema) ([]schema.Change, error)

The DiffFunc type is an adapter to allow the use of ordinary function as Differ. If f is a function with the appropriate signature, DiffFunc(f) is a Differ that calls f.

func (DiffFunc) Diff added in v0.10.0

func (f DiffFunc) Diff(current, desired *schema.Schema) ([]schema.Change, error)

Diff calls f(current, desired).

type DiffHook added in v0.10.0

type DiffHook func(Differ) Differ

DiffHook defines the "diff middleware". A function that gets a Differ and returns a Differ.

type Differ added in v0.10.0

type Differ interface {
	// Diff returns a list of changes that construct a migration plan.
	Diff(current, desired *schema.Schema) ([]schema.Change, error)
}

Differ is the interface that wraps the Diff method.

type DirWriter added in v0.11.5

type DirWriter struct {
	Dir       migrate.Dir       // target directory.
	Formatter migrate.Formatter // optional formatter.
	// contains filtered or unexported fields
}

DirWriter implements the io.Writer interface for writing to an Atlas managed directory.

func (*DirWriter) Change added in v0.11.5

func (d *DirWriter) Change(comment string)

Change converts all written statement so far into a migration change with the given comment.

func (*DirWriter) Flush added in v0.11.5

func (d *DirWriter) Flush(name string) error

Flush flushes the written statements to the directory.

func (*DirWriter) FlushChange added in v0.11.5

func (d *DirWriter) FlushChange(name, comment string) error

FlushChange combines Change and Flush.

func (*DirWriter) Write added in v0.11.5

func (d *DirWriter) Write(p []byte) (int, error)

Write implements the io.Writer interface.

type Expr added in v0.11.5

type Expr string

Expr represents a raw expression. It is used to distinguish between literal values and raw expressions when defining default values.

type ForeignKey

type ForeignKey struct {
	Symbol     string          // foreign-key name. Generated if empty.
	Columns    []*Column       // table column
	RefTable   *Table          // referenced table.
	RefColumns []*Column       // referenced columns.
	OnUpdate   ReferenceOption // action on update.
	OnDelete   ReferenceOption // action on delete.
}

ForeignKey definition for creation.

func (ForeignKey) DSL

func (fk ForeignKey) DSL() *sql.ForeignKeyBuilder

DSL returns a default DSL query for a foreign-key.

type Hook

type Hook func(Creator) Creator

Hook defines the "create middleware". A function that gets a Creator and returns a Creator. For example:

hook := func(next schema.Creator) schema.Creator {
	return schema.CreateFunc(func(ctx context.Context, tables ...*schema.Table) error {
		fmt.Println("Tables:", tables)
		return next.Create(ctx, tables...)
	})
}

type Index

type Index struct {
	Name       string                  // index name.
	Unique     bool                    // uniqueness.
	Columns    []*Column               // actual table columns.
	Annotation *entsql.IndexAnnotation // index annotation.
	// contains filtered or unexported fields
}

Index definition for table index.

func (*Index) Builder

func (i *Index) Builder(table string) *sql.IndexBuilder

Builder returns the query builder for index creation. The DSL is identical in all dialects.

func (*Index) DropBuilder

func (i *Index) DropBuilder(table string) *sql.DropIndexBuilder

DropBuilder returns the query builder for the drop index.

type Indexes

type Indexes []*Index

Indexes used for scanning all sql.Rows into a list of indexes, because multiple sql rows can represent the same index (multi-columns indexes).

type InspectOption

type InspectOption func(inspect *Inspector)

InspectOption allows for managing schema configuration using functional options.

func WithSchema

func WithSchema(schema string) InspectOption

WithSchema provides a schema (named-database) for reading the tables from.

type Inspector

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

An Inspector provides methods for inspecting database tables.

func NewInspect

func NewInspect(d dialect.Driver, opts ...InspectOption) (*Inspector, error)

NewInspect returns an inspector for the given SQL driver.

func (*Inspector) Tables

func (i *Inspector) Tables(ctx context.Context) ([]*Table, error)

Tables returns the tables in the schema.

type Migrate deprecated

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

Migrate runs the migration logic for the SQL dialects.

Deprecated: Use the new Atlas struct instead.

func (*Migrate) Create

func (m *Migrate) Create(ctx context.Context, tables ...*Table) error

Create creates all schema resources in the database. It works in an "append-only" mode, which means, it only creates tables, appends columns to tables or modifies column types.

Column can be modified by turning into a NULL from NOT NULL, or having a type conversion not resulting data altering. From example, changing varchar(255) to varchar(120) is invalid, but changing varchar(120) to varchar(255) is valid. For more info, see the convert function below.

Note that SQLite dialect does not support (this moment) the "append-only" mode describe above, since it's used only for testing.

type MigrateOption

type MigrateOption func(*Atlas)

MigrateOption allows configuring Atlas using functional arguments.

func DisableChecksum deprecated added in v0.11.0

func DisableChecksum() MigrateOption

DisableChecksum instructs atlas to skip migration directory integrity sum file generation.

Deprecated: generating the sum file will no longer be optional in future versions.

func WithApplyHook added in v0.10.0

func WithApplyHook(hooks ...ApplyHook) MigrateOption

WithApplyHook adds a list of ApplyHook to the schema migration.

schema.WithApplyHook(func(next schema.Applier) schema.Applier {
	return schema.ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error {
		// Example to hook into the apply process, or implement
		// a custom applier.
		//
		//	for _, c := range plan.Changes {
		//		fmt.Printf("%s: %s", c.Comment, c.Cmd)
		//	}
		//
		return next.Apply(ctx, conn, plan)
	})
})

func WithAtlas deprecated added in v0.10.0

func WithAtlas(b bool) MigrateOption

WithAtlas is an opt-out option for v0.11 indicating the migration should be executed using the deprecated legacy engine. Note, in future versions, this option is going to be removed and the Atlas (https://atlasgo.io) based migration engine should be used.

Deprecated: The legacy engine will be removed.

func WithDialect added in v0.11.0

func WithDialect(d string) MigrateOption

WithDialect configures the Ent dialect to use when migrating for an Atlas supported dialect flavor. As an example, Ent can work with TiDB in MySQL dialect and Atlas can handle TiDB migrations.

func WithDiffHook added in v0.10.0

func WithDiffHook(hooks ...DiffHook) MigrateOption

WithDiffHook adds a list of DiffHook to the schema migration.

schema.WithDiffHook(func(next schema.Differ) schema.Differ {
	return schema.DiffFunc(func(current, desired *atlas.Schema) ([]atlas.Change, error) {
		// Code before standard diff.
		changes, err := next.Diff(current, desired)
		if err != nil {
			return nil, err
		}
		// After diff, you can filter
		// changes or return new ones.
		return changes, nil
	})
})

func WithDir added in v0.10.1

func WithDir(dir migrate.Dir) MigrateOption

WithDir sets the atlas migration directory to use to store migration files.

func WithDropColumn

func WithDropColumn(b bool) MigrateOption

WithDropColumn sets the columns dropping option to the migration. Defaults to false.

func WithDropIndex

func WithDropIndex(b bool) MigrateOption

WithDropIndex sets the indexes dropping option to the migration. Defaults to false.

func WithErrNoPlan added in v0.11.9

func WithErrNoPlan(b bool) MigrateOption

WithErrNoPlan sets Atlas to returns a migrate.ErrNoPlan in case the migration plan is empty. Defaults to false.

func WithFixture deprecated

func WithFixture(b bool) MigrateOption

WithFixture sets the foreign-key renaming option to the migration when upgrading sqlDialect from v0.1.0 (issue-#285). Defaults to false.

Deprecated: This option is no longer needed with the Atlas based migration engine, which now is the default.

func WithForeignKeys

func WithForeignKeys(b bool) MigrateOption

WithForeignKeys enables creating foreign-key in ddl. Defaults to true.

func WithFormatter added in v0.10.1

func WithFormatter(fmt migrate.Formatter) MigrateOption

WithFormatter sets atlas formatter to use to write changes to migration files.

func WithGlobalUniqueID

func WithGlobalUniqueID(b bool) MigrateOption

WithGlobalUniqueID sets the universal ids options to the migration. Defaults to false.

func WithHooks

func WithHooks(hooks ...Hook) MigrateOption

WithHooks adds a list of hooks to the schema migration.

func WithIndent added in v0.11.10

func WithIndent(indent string) MigrateOption

WithIndent sets Atlas to generate SQL statements with indentation. An empty string indicates no indentation.

func WithMigrationMode added in v0.11.0

func WithMigrationMode(mode Mode) MigrateOption

WithMigrationMode instructs atlas how to compute the current state of the schema. This can be done by either replaying (ModeReplay) the migration directory on the connected database, or by inspecting (ModeInspect) the connection. Currently, ModeReplay is opt-in, and ModeInspect is the default. In future versions, ModeReplay will become the default behavior. This option has no effect when using online migrations.

func WithSkipChanges added in v0.10.0

func WithSkipChanges(skip ChangeKind) MigrateOption

WithSkipChanges allows skipping/filtering list of changes returned by the Differ before executing migration planning.

SkipChanges(schema.DropTable|schema.DropColumn)

func WithSumFile deprecated added in v0.11.0

func WithSumFile() MigrateOption

WithSumFile instructs atlas to generate a migration directory integrity sum file.

Deprecated: generating the sum file is now opt-out. This method will be removed in future versions.

type Mode added in v0.11.0

type Mode uint

Mode to compute the current state.

type MySQL

type MySQL struct {
	dialect.Driver
	// contains filtered or unexported fields
}

MySQL is a MySQL migration driver.

type Postgres

type Postgres struct {
	dialect.Driver
	// contains filtered or unexported fields
}

Postgres is a postgres migration driver.

type ReferenceOption

type ReferenceOption string

ReferenceOption for constraint actions.

const (
	NoAction   ReferenceOption = "NO ACTION"
	Restrict   ReferenceOption = "RESTRICT"
	Cascade    ReferenceOption = "CASCADE"
	SetNull    ReferenceOption = "SET NULL"
	SetDefault ReferenceOption = "SET DEFAULT"
)

Reference options.

func (ReferenceOption) ConstName

func (r ReferenceOption) ConstName() string

ConstName returns the constant name of a reference option. It's used by entc for printing the constant name in templates.

type SQLite

type SQLite struct {
	dialect.Driver
	WithForeignKeys bool
}

SQLite is an SQLite migration driver.

func (*SQLite) Tx added in v0.11.3

func (d *SQLite) Tx(ctx context.Context) (dialect.Tx, error)

Tx implements opens a transaction.

type SQLiteTx added in v0.11.3

type SQLiteTx struct {
	dialect.Tx
	// contains filtered or unexported fields
}

SQLiteTx implements dialect.Tx.

func (*SQLiteTx) Commit added in v0.11.3

func (tx *SQLiteTx) Commit() error

Commit ensures foreign keys are toggled back on after commit.

func (*SQLiteTx) Rollback added in v0.11.3

func (tx *SQLiteTx) Rollback() error

Rollback ensures foreign keys are toggled back on after rollback.

type Table

type Table struct {
	Name    string
	Columns []*Column

	Indexes     []*Index
	PrimaryKey  []*Column
	ForeignKeys []*ForeignKey
	Annotation  *entsql.Annotation
	Comment     string
	// contains filtered or unexported fields
}

Table schema definition for SQL dialects.

func CopyTables added in v0.11.0

func CopyTables(tables []*Table) ([]*Table, error)

CopyTables returns a deep-copy of the given tables. This utility function is useful for copying the generated schema tables (i.e. migrate.Tables) before running schema migration when there is a need for execute multiple migrations concurrently. e.g. running parallel unit-tests using the generated enttest package.

func NewTable

func NewTable(name string) *Table

NewTable returns a new table with the given name.

func NewTypesTable added in v0.11.9

func NewTypesTable() *Table

NewTypesTable returns a new table for holding the global-id information.

func (*Table) AddColumn

func (t *Table) AddColumn(c *Column) *Table

AddColumn adds a new column to the table.

func (*Table) AddForeignKey

func (t *Table) AddForeignKey(fk *ForeignKey) *Table

AddForeignKey adds a foreign key to the table.

func (*Table) AddIndex

func (t *Table) AddIndex(name string, unique bool, columns []string) *Table

AddIndex creates and adds a new index to the table from the given options.

func (*Table) AddPrimary

func (t *Table) AddPrimary(c *Column) *Table

AddPrimary adds a new primary key to the table.

func (*Table) Column added in v0.11.0

func (t *Table) Column(name string) (*Column, bool)

Column returns the column with the given name. If exists.

func (*Table) HasColumn added in v0.7.0

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

HasColumn reports if the table contains a column with the given name.

func (*Table) Index added in v0.9.0

func (t *Table) Index(name string) (*Index, bool)

Index returns a table index by its exact name.

func (*Table) SetAnnotation

func (t *Table) SetAnnotation(ant *entsql.Annotation) *Table

SetAnnotation the entsql.Annotation on the table.

func (*Table) SetComment added in v0.11.10

func (t *Table) SetComment(c string) *Table

SetComment sets the table comment.

type WriteDriver

type WriteDriver struct {
	dialect.Driver // optional driver for query calls.
	io.Writer      // target for exec statements.
	FormatFunc     func(string) (string, error)
}

WriteDriver is a driver that writes all driver exec operations to its writer. Note that this driver is used only for printing or writing statements to SQL files, and may require manual changes to the generated SQL statements.

func NewWriteDriver added in v0.11.5

func NewWriteDriver(dialect string, w io.Writer) *WriteDriver

NewWriteDriver creates a dialect.Driver that writes all driver exec statement to its writer.

func (*WriteDriver) Exec

func (w *WriteDriver) Exec(_ context.Context, query string, args, res any) error

Exec implements the dialect.Driver.Exec method.

func (*WriteDriver) Query added in v0.11.5

func (w *WriteDriver) Query(ctx context.Context, query string, args, res any) error

Query implements the dialect.Driver.Query method.

func (*WriteDriver) Tx

Tx writes the transaction start.

Jump to

Keyboard shortcuts

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