### Install Tern using go install Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Installs the latest version of the Tern migration tool globally using the go install command. ```bash go install github.com/jackc/tern/v2@latest ``` -------------------------------- ### Example Migration Output Logging Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate This example demonstrates how migration progress is logged during an 'OnStartMigrationProgressLogging' event. ```go Output: Migrating up: create a table ``` -------------------------------- ### Example Migration Progress Logging Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 This example demonstrates logging migration progress. It shows the output when a migration is applied. ```go Output: Migrating up: create a table ``` -------------------------------- ### Install a Code Package with Tern Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Installs a code package from a specified directory into the database. Requires a configuration file. ```bash tern code install path/to/code --config path/to/tern.conf ``` -------------------------------- ### Tern Configuration File Example Source: https://pkg.go.dev/github.com/jackc/tern/v2 An example 'tern.conf' file demonstrating database connection settings and data variable interpolation. Supports standard PostgreSQL environment variables and Go's text/template package with Sprig functions. ```ini [database] # host supports TCP addresses and Unix domain sockets # host = /private/tmp host = 127.0.0.1 # port = 5432 database = tern_test user = jack password = {{env "MIGRATOR_PASSWORD"}} # version_table = public.schema_version # # sslmode generally matches the behavior described in: # http://www.postgresql.org/docs/9.4/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION # # There are only two modes that most users should use: # prefer - on trusted networks where security is not required # verify-full - require SSL connection # sslmode = prefer # # "conn_string" accepts two formats; URI or DSN as described in: # https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING # # This property is lenient i.e., it does not throw error # if values for both "conn_string" and "host/port/.." are # provided. In this case, the individual properties will # override the correspoding part in the "conn_string". # # URI format: # conn_string = postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp # DSN format: # conn_string = host=localhost port=5432 dbname=mydb connect_timeout=10 # Proxy the above database connection via SSH # [ssh-tunnel] # host = # port = 22 # user defaults to OS user # user = # password is not required if using SSH agent authentication # password = # keyfile is the path to a SSH key file # keyfile = # passphrase for the SSH key file given above or one of the default SSH key files in ~/.ssh # passphrase = [data] prefix = foo app_user = joe ``` -------------------------------- ### Tern configuration file example (tern.conf) Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 An example of a tern.conf file demonstrating database connection settings and data variables for interpolation into migrations. Supports INI format with 'database' and 'data' sections. ```ini [database] # host supports TCP addresses and Unix domain sockets # host = /private/tmp host = 127.0.0.1 # port = 5432 database = tern_test user = jack password = {{env "MIGRATOR_PASSWORD"}} # version_table = public.schema_version # # sslmode generally matches the behavior described in: # http://www.postgresql.org/docs/9.4/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION # # There are only two modes that most users should use: # prefer - on trusted networks where security is not required # verify-full - require SSL connection # sslmode = prefer # # "conn_string" accepts two formats; URI or DSN as described in: # https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING # # This property is lenient i.e., it does not throw error # if values for both "conn_string" and "host/port/.." are # provided. In this case, the individual properties will # override the correspoding part in the "conn_string". # # URI format: # conn_string = postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp # DSN format: # conn_string = host=localhost port=5432 dbname=mydb connect_timeout=10 # Proxy the above database connection via SSH # [ssh-tunnel] # host = # port = 22 # user defaults to OS user # user = # password is not required if using SSH agent authentication # password = # keyfile is the path to a SSH key file # keyfile = # passphrase for the SSH key file given above or one of the default SSH key files in ~/.ssh # passphrase = [data] prefix = foo app_user = joe ``` -------------------------------- ### Install Tern CLI Source: https://pkg.go.dev/github.com/jackc/tern/v2 Installs the latest version of the Tern command-line interface using go install. Ensure Go is installed and configured correctly. ```bash go install github.com/jackc/tern/v2@latest ``` -------------------------------- ### Function: InstallCodePackage Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Installs a code package into the database. It requires a context, a database connection, merge data, and the code package itself. Returns an error if the installation fails. ```go func InstallCodePackage(ctx context.Context, conn *pgx.Conn, mergeData map[string]interface{}, codePackage *CodePackage) (err error) ``` -------------------------------- ### InstallCodePackage Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Installs a code package into the database. ```APIDOC ## InstallCodePackage ### Description Installs a code package into the database. ### Signature ```go func InstallCodePackage(ctx context.Context, conn *pgx.Conn, mergeData map[string]interface{}, codePackage *CodePackage) (err error) ``` ``` -------------------------------- ### Basic Migration SQL Structure Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Migrations use a simple format with up and down SQL statements separated by a magic comment. This example shows a basic create and drop table. ```sql create table t1( id serial primary key ); ---- create above / drop below ---- drop table t1; ``` -------------------------------- ### Renumber Migrations - Start Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Initiate the renumbering process on the branch containing migrations that should retain lower numbers. ```bash $ git switch master Switched to branch 'master' $ ls 001_create_users.sql 002_add_last_login_to_users.sql $ git switch feature Switched to branch 'feature' $ ls 001_create_users.sql 002_create_todos.sql # Both branches have a migration number 2. # Run tern renumber start on the branch with the migrations that should come first. $ git switch master Switched to branch 'master' $ tern renumber start ``` -------------------------------- ### InstallCodePackage Function Signature Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Signature for the InstallCodePackage function, used to install a code package with merge data. ```go func InstallCodePackage(ctx context.Context, conn *pgx.Conn, mergeData map[string]interface{}, codePackage *CodePackage) (err error) ``` -------------------------------- ### Generate SQL Migration Script with gengen Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Use the `gengen` command to create a SQL script that generates a migration SQL script. This is useful for applications or plugins that need to perform migrations but do not have Tern installed. ```bash $ tern gengen > generate-migrations.sql $ psql --no-psqlrc --tuples-only --quiet --no-align -f generate-migrations.sql mydb > migrations.sql ``` -------------------------------- ### Migrator.GetCurrentVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Gets the current migration version from the database. ```APIDOC ## (*Migrator) GetCurrentVersion ### Description Gets the current migration version from the database. ### Signature ```go func (m *Migrator) GetCurrentVersion(ctx context.Context) (v int32, err error) ``` ``` -------------------------------- ### Renumber Conflicting Migrations Source: https://pkg.go.dev/github.com/jackc/tern/v2 Automatically renumbers migrations when merging branches to resolve conflicts. Run `renumber start` on the branch to keep, merge, then run `renumber finish`. ```bash $ git switch master Switched to branch 'master' $ ls 001_create_users.sql 002_add_last_login_to_users.sql $ git switch feature Switched to branch 'feature' $ ls 001_create_users.sql 002_create_todos.sql # Both branches have a migration number 2. # Run tern renumber start on the branch with the migrations that should come first. $ git switch master Switched to branch 'master' $ tern renumber start # Then go to the branch with migrations that should come later and merge or rebase. $ git switch feature $ git rebase master Successfully rebased and updated refs/heads/feature. $ ls 001_create_users.sql 002_add_last_login_to_users.sql 002_create_todos.sql # There are now two migrations with the same migration number. $ tern renumber finish $ ls 001_create_users.sql 002_add_last_login_to_users.sql 003_create_todos.sql # The migrations are now renumbered in the correct order. ``` -------------------------------- ### Initialize Tern Project Source: https://pkg.go.dev/github.com/jackc/tern/v2 Creates a new Tern project in the current directory. Alternatively, specify a path to create the project elsewhere. ```bash tern init ``` ```bash tern init path/to/project ``` -------------------------------- ### Migrator.Migrate Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Applies all pending migrations to the database. Calls m.OnStart before each migration. ```go func (m *Migrator) Migrate(ctx context.Context) error ``` -------------------------------- ### Initialize a new Tern project Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Creates a new Tern project in the current directory. Alternatively, specify a path to create the project elsewhere. ```bash tern init ``` ```bash tern init path/to/project ``` -------------------------------- ### Migrator.Migrate Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Runs pending migrations. It calls m.OnStart when it begins a migration. ```APIDOC ## Migrator.Migrate ### Description Runs pending migrations. It calls m.OnStart when it begins a migration. ### Method Signature ```go func (m *Migrator) Migrate(ctx context.Context) error ``` ### Parameters - **ctx** (context.Context) - The context for the operation. ### Returns - **err** (error) - An error if the migration fails. ``` -------------------------------- ### Embedding Tern Migrations in Go Applications Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Demonstrates setting up a `migrate.Migrator` to perform migrations using Go functions and SQL. Requires environment variables for database connection. ```go // Note: requires the right mix of environment variables to be set: PGHOST, PGPORT, PGDATABASE, // PGUSER, PGPASSWORD. conn, _ := pgx.Connect(ctx, "") m, _ := migrate.NewMigrator(context.Background(), conn, "my_schema_version") m.Migrations = []*migrate.Migration{ // Migration that uses Go functions. { Sequence: 1, Name: "1", UpFunc: func(ctx context.Context, conn *pgx.Conn) error { _, err := conn.Exec(ctx, "CREATE TABLE tmp (id INT);") return err }, DownFunc: func(ctx context.Context, conn *pgx.Conn) error { _, err := conn.Exec(ctx, "DROP TABLE tmp;") return err }, }, // Migration that uses SQL. { Sequence: 2, Name: "2", UpSQL: `CREATE TABLE tmp2 (id INT);`, DownSQL: `DROP TABLE tmp2;`, }, // Migration that uses both Go function and SQL. { Sequence: 3, Name: "3", UpFunc: func(ctx context.Context, conn *pgx.Conn) error { _, err := conn.Exec(ctx, "CREATE TABLE tmp3 (id INT);") return err }, DownSQL: `DROP TABLE tmp3;`, }, } _ = m.Migrate(ctx) ``` -------------------------------- ### Method: CodePackage.Eval Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Evaluates the CodePackage with provided data. It returns the evaluated result as a string and an error if evaluation fails. ```go func (cp *CodePackage) Eval(data map[string]interface{}) (string, error) ``` -------------------------------- ### Migrate to Latest Version Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Run this command to apply all pending migrations up to the latest version, using the default config and migration directory. ```bash tern migrate ``` -------------------------------- ### Use a Different Config File Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Specify a custom configuration file path using the `--config` flag. ```bash tern migrate --config path/to/tern.json ``` -------------------------------- ### Run Tern Tests with Connection Strings Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Configure and run Tern's tests by setting environment variables for database connection strings. Two databases are required: one for main Tern program tests and another for migrate library tests. ```bash TERN_TEST_CONN_STRING="host=/private/tmp database=tern_test" MIGRATE_TEST_CONN_STRING="host=/private/tmp database=tern_migrate_test" MIGRATE_TEST_DATABASE=tern_migrate_test go test ./... ``` -------------------------------- ### Include Shared SQL Files in Migrations Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Use the `template` command to include SQL files from subdirectories. A trailing dot is necessary if the shared file needs access to custom data values. ```go // Include the file shared/v1_001.sql. Note the trailing dot. // It is necessary if the shared file needs access to custom data values. {{ template "shared/v1_001.sql" . }} ); ``` -------------------------------- ### Dynamic Schema Creation using Environment Variables Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Dynamically creates or drops a schema based on the 'CODE_SCHEMA' environment variable. Useful for blue/green deployments. ```sql drop schema if exists {{ env "CODE_SCHEMA" }} cascade; create schema {{ env "CODE_SCHEMA" }}; ``` -------------------------------- ### Function: LoadCodePackage Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Loads a CodePackage from a given file system. It takes an fs.FS and returns a pointer to a CodePackage and an error if loading fails. ```go func LoadCodePackage(fsys fs.FS) (*CodePackage, error) ``` -------------------------------- ### Create a Migration from a Code Package Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Generates a single migration file from the current state of a code package. Specify the output migrations directory. ```bash tern code snapshot path/to/code --migrations path/to/migrations ``` -------------------------------- ### Apply Migrations Source: https://pkg.go.dev/github.com/jackc/tern/v2 Run migrations to the latest version, a specific version, or a relative number of versions up or down. Specify config and migration directories if they differ from defaults. ```bash tern migrate ``` ```bash tern migrate --destination 42 ``` ```bash tern migrate --destination +3 ``` ```bash tern migrate --destination -3 ``` ```bash tern migrate --destination -+3 ``` ```bash tern migrate --config path/to/tern.json ``` ```bash tern migrate --migrations path/to/migrations ``` -------------------------------- ### Migrate Down and Rerun Previous Versions Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Use `-+` with `--destination` to migrate down and then rerun the specified number of previous versions. ```bash tern migrate --destination -+3 ``` -------------------------------- ### Migrate Up N Versions Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Specify a positive number with `--destination` to migrate up a relative number of versions. ```bash tern migrate --destination +3 ``` -------------------------------- ### Migrator.LoadMigrations Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Loads migrations from a given file system. ```go func (m *Migrator) LoadMigrations(fsys fs.FS) error ``` -------------------------------- ### Migrator.MigrateTo Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Applies migrations to bring the database schema to a specific target version. ```go func (m *Migrator) MigrateTo(ctx context.Context, targetVersion int32) (err error) ``` -------------------------------- ### Migrate Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Runs all pending migrations. ```APIDOC ## Migrate ### Description Runs pending migrations. It calls m.OnStart when it begins a migration. ### Method ```go func (m *Migrator) Migrate(ctx context.Context) error ``` ### Parameters * **ctx** (context.Context) - The context for the operation. ``` -------------------------------- ### NewMigratorEx Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Initializes a new Migrator with options. It is highly recommended that versionTable be schema qualified. ```APIDOC ## NewMigratorEx ### Description Initializes a new Migrator with options. It is highly recommended that versionTable be schema qualified. ### Function Signature ```go func NewMigratorEx(ctx context.Context, conn *pgx.Conn, versionTable string, opts *MigratorOptions) (m *Migrator, err error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - The context for the operation. - **conn** (*pgx.Conn) - The database connection. - **versionTable** (string) - The name of the version table, recommended to be schema qualified. - **opts** (*MigratorOptions) - Options for the migrator. ``` -------------------------------- ### Use a Different Migrations Directory Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Specify a custom directory for migration files using the `--migrations` flag. ```bash tern migrate --migrations path/to/migrations ``` -------------------------------- ### LoadMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Loads migrations from a given file system. ```APIDOC ## LoadMigrations ### Description Loads migrations from a given file system. ### Method ```go func (m *Migrator) LoadMigrations(fsys fs.FS) error ``` ### Parameters * **fsys** (fs.FS) - The file system to load migrations from. ``` -------------------------------- ### Migrate to a Specific Version Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Use the `--destination` flag to migrate up or down to a specific version number. ```bash tern migrate --destination 42 ``` -------------------------------- ### Migrate Down N Versions Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Specify a negative number with `--destination` to migrate down a relative number of versions. ```bash tern migrate --destination -3 ``` -------------------------------- ### Migrator.LoadMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Loads migrations from a file system. ```APIDOC ## Migrator.LoadMigrations ### Description Loads migrations from a file system. ### Method Signature ```go func (m *Migrator) LoadMigrations(fsys fs.FS) error ``` ### Parameters - **fsys** (fs.FS) - The file system to load migrations from. ``` -------------------------------- ### CodePackage Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents a package of code for migration. ```APIDOC ## CodePackage ### Description Represents a package of code for migration. ### Type Definition ```go type CodePackage struct { // contains filtered or unexported fields } ``` ``` -------------------------------- ### NewMigratorEx Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Initializes a new Migrator with optional configurations. It is recommended that versionTable be schema qualified. ```APIDOC ## NewMigratorEx ### Description Initializes a new Migrator with optional configurations. It is highly recommended that versionTable be schema qualified. ### Function Signature ```go func NewMigratorEx(ctx context.Context, conn *pgx.Conn, versionTable string, opts *MigratorOptions) (m *Migrator, err error) ``` ### Parameters * **ctx** (context.Context) - The context for the operation. * **conn** (*pgx.Conn) - The database connection. * **versionTable** (string) - The name of the version table, preferably schema qualified. * **opts** (*MigratorOptions) - Optional configuration for the Migrator. ``` -------------------------------- ### Migrator.LoadMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Loads migrations from the provided file system. ```APIDOC ## (*Migrator) LoadMigrations ### Description Loads migrations from the provided file system. ### Signature ```go func (m *Migrator) LoadMigrations(fsys fs.FS) error ``` ``` -------------------------------- ### MigrateTo Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Migrates the database schema to a specific target version. ```APIDOC ## MigrateTo ### Description Migrates to targetVersion. ### Method ```go func (m *Migrator) MigrateTo(ctx context.Context, targetVersion int32) (err error) ``` ### Parameters * **ctx** (context.Context) - The context for the operation. * **targetVersion** (int32) - The target migration version to migrate to. ``` -------------------------------- ### Create a New Migration with Tern Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Use this command to generate a new migration file. The `-e` flag can be used to automatically open the new file in your editor. ```bash tern new name_of_migration ``` -------------------------------- ### Function: FindMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Finds all migration files within a given file system. It takes an fs.FS as input and returns a slice of strings representing migration file names and an error if any occurs. ```go func FindMigrations(fsys fs.FS) ([]string, error) ``` -------------------------------- ### LoadCodePackage Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Loads a code package from the file system. ```APIDOC ## LoadCodePackage ### Description Loads a code package from the file system. ### Signature ```go func LoadCodePackage(fsys fs.FS) (*CodePackage, error) ``` ``` -------------------------------- ### Migration File Structure Source: https://pkg.go.dev/github.com/jackc/tern/v2 Migration files contain up and down SQL statements separated by a magic comment. For irreversible migrations, omit the magic comment. ```sql ---- create above / drop below ---- ``` ```sql create table t1( id serial primary key ); ---- create above / drop below ---- drop table t1; ``` ```sql drop table widgets; ``` -------------------------------- ### Migrator.LoadMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Loads migrations from the specified file system. ```APIDOC ## (*Migrator) LoadMigrations ### Description Loads migrations from the specified file system. ### Signature ```go func (m *Migrator) LoadMigrations(fsys fs.FS) error ``` ``` -------------------------------- ### NewMigratorEx Function Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Initializes a new Migrator instance with optional configuration. It is recommended to use a schema-qualified versionTable name. ```go func NewMigratorEx(ctx context.Context, conn *pgx.Conn, versionTable string, opts *MigratorOptions) (m *Migrator, err error) ``` -------------------------------- ### Type: CodePackage Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents a package of code, likely for database operations or scripts. It contains filtered or unexported fields. ```go type CodePackage struct { // contains filtered or unexported fields } ``` -------------------------------- ### NewMigrator Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Initializes a new Migrator. It is highly recommended that versionTable be schema qualified. ```APIDOC ## NewMigrator ### Description Initializes a new Migrator. It is highly recommended that versionTable be schema qualified. ### Function Signature ```go func NewMigrator(ctx context.Context, conn *pgx.Conn, versionTable string) (m *Migrator, err error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - The context for the operation. - **conn** (*pgx.Conn) - The database connection. - **versionTable** (string) - The name of the version table, recommended to be schema qualified. ``` -------------------------------- ### MigrationPgError.Unwrap Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Unwraps the embedded pgconn.PgError. ```go func (e MigrationPgError) Unwrap() error ``` -------------------------------- ### NewMigrator Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Initializes a new Migrator. It is recommended that versionTable be schema qualified. ```APIDOC ## NewMigrator ### Description Initializes a new Migrator. It is highly recommended that versionTable be schema qualified. ### Function Signature ```go func NewMigrator(ctx context.Context, conn *pgx.Conn, versionTable string) (m *Migrator, err error) ``` ### Parameters * **ctx** (context.Context) - The context for the operation. * **conn** (*pgx.Conn) - The database connection. * **versionTable** (string) - The name of the version table, preferably schema qualified. ``` -------------------------------- ### FindMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 FindMigrations finds all migration files in the provided file system. ```APIDOC ## FindMigrations ### Description Finds all migration files in fsys. ### Signature ```go func FindMigrations(fsys fs.FS) ([]string, error) ``` ``` -------------------------------- ### FindMigrations Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate FindMigrations finds all migration files in the provided file system. ```APIDOC ## FindMigrations ### Description FindMigrations finds all migration files in fsys. ### Signature ```go func FindMigrations(fsys fs.FS) ([]string, error) ``` ``` -------------------------------- ### Migrator.MigrateTo Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Applies migrations up to the specified target version. ```APIDOC ## (*Migrator) MigrateTo ### Description Applies migrations up to the specified target version. ### Signature ```go func (m *Migrator) MigrateTo(ctx context.Context, targetVersion int32) (err error) ``` ``` -------------------------------- ### Migrator.Migrate Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Applies all available migrations. ```APIDOC ## (*Migrator) Migrate ### Description Applies all available migrations. ### Signature ```go func (m *Migrator) Migrate(ctx context.Context) error ``` ``` -------------------------------- ### CodePackage Type Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Defines the CodePackage struct, which likely holds information about a code package for migration. ```go type CodePackage struct { // contains filtered or unexported fields } ``` -------------------------------- ### NewMigrator Function Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Initializes a new Migrator instance. It is recommended to use a schema-qualified versionTable name. ```go func NewMigrator(ctx context.Context, conn *pgx.Conn, versionTable string) (m *Migrator, err error) ``` -------------------------------- ### Migrator.MigrateTo Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Migrates the database schema to a specific target version. ```APIDOC ## Migrator.MigrateTo ### Description Migrates the database schema to a specific target version. ### Method Signature ```go func (m *Migrator) MigrateTo(ctx context.Context, targetVersion int32) (err error) ``` ### Parameters - **ctx** (context.Context) - The context for the operation. - **targetVersion** (int32) - The target schema version to migrate to. ### Returns - **err** (error) - An error if the migration fails. ``` -------------------------------- ### Migrator.MigrateTo Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Applies migrations up to a specific target version. ```APIDOC ## (*Migrator) MigrateTo ### Description Applies migrations up to a specific target version. ### Signature ```go func (m *Migrator) MigrateTo(ctx context.Context, targetVersion int32) (err error) ``` ``` -------------------------------- ### CodePackage.Eval Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Evaluates the code package with provided data. ```APIDOC ## (*CodePackage) Eval ### Description Evaluates the code package with provided data. ### Signature ```go func (cp *CodePackage) Eval(data map[string]interface{}) (string, error) ``` ``` -------------------------------- ### MigrationPgError.Error Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Implements the error interface for MigrationPgError. ```go func (e MigrationPgError) Error() string ``` -------------------------------- ### Interpolate Custom Data in Migrations Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Prefix a config file variable name with a dot and surround it with double curly braces to interpolate its value into your SQL statements. ```sql create table {{.prefix}}config( id serial primary key ); ``` -------------------------------- ### Templating in Migrations Source: https://pkg.go.dev/github.com/jackc/tern/v2 Custom data values from the config file can be interpolated using double curly braces, prefixed with a dot. Go text/template syntax is supported. ```go-template create table {{.prefix}}config( id serial primary key ); ``` ```go-template // Include the file shared/v1_001.sql. Note the trailing dot. // It is necessary if the shared file needs access to custom data values. {{ template "shared/v1_001.sql" . }} ); ``` -------------------------------- ### NoMigrationsFoundError.Error Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Implements the error interface for NoMigrationsFoundError. ```go func (e NoMigrationsFoundError) Error() string ``` -------------------------------- ### Using Sprig for Template Merging Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Merges a dictionary with view parameters into the template context for creating views. Requires Sprig library. ```sql {{ template "_view_partial.sql" (merge (dict "view_name" "some_name" "where_clause" "some_extra_condition=true") . ) }} ``` -------------------------------- ### Method: BadVersionError.Error Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Returns the string representation of the BadVersionError. This method satisfies the error interface. ```go func (e BadVersionError) Error() string ``` -------------------------------- ### NewMigratorEx Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Creates a new Migrator instance with extended options. ```APIDOC ## NewMigratorEx ### Description Creates a new Migrator instance with extended options. ### Signature ```go func NewMigratorEx(ctx context.Context, conn *pgx.Conn, versionTable string, ...) (m *Migrator, err error) ``` ``` -------------------------------- ### Method: IrreversibleMigrationError.Error Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Returns the string representation of the IrreversibleMigrationError. This method satisfies the error interface. ```go func (e IrreversibleMigrationError) Error() string ``` -------------------------------- ### Migrator.Migrate Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Applies all available migrations up to the latest version. ```APIDOC ## (*Migrator) Migrate ### Description Applies all available migrations up to the latest version. ### Signature ```go func (m *Migrator) Migrate(ctx context.Context) error ``` ``` -------------------------------- ### Variable: ErrNoFwMigration Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 This variable represents an error indicating that there is no SQL in the forward migration step. It is a predefined error value. ```go var ErrNoFwMigration = errors.New("no sql in forward migration step") ``` -------------------------------- ### LoadCodePackage Function Signature Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Signature for the LoadCodePackage function, which loads a code package from a file system. ```go func LoadCodePackage(fsys fs.FS) (*CodePackage, error) ``` -------------------------------- ### Type: BadVersionError Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents an error indicating an invalid version. It is defined as a string type. ```go type BadVersionError string ``` -------------------------------- ### Migrator.GetCurrentVersion Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Retrieves the current applied migration version from the database. ```go func (m *Migrator) GetCurrentVersion(ctx context.Context) (v int32, err error) ``` -------------------------------- ### NewMigrator Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Creates a new Migrator instance. ```APIDOC ## NewMigrator ### Description Creates a new Migrator instance. ### Signature ```go func NewMigrator(ctx context.Context, conn *pgx.Conn, versionTable string) (m *Migrator, err error) ``` ``` -------------------------------- ### Find Migrations Function Signature Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Signature for the FindMigrations function, which locates all migration files within a given file system. ```go func FindMigrations(fsys fs.FS) ([]string, error) ``` -------------------------------- ### Migration Struct Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Defines a database schema migration with SQL or Go function definitions for up and down directions. Supports disabling transactions for specific statements. ```go type Migration struct { // Sequence is a state identifier for the database schema after the up direction of the // [Migration] has been applied. Sequence int32 // Name is a human-readable name or description of the [Migration]. Name string // UpSQL declares SQL statements that brings the database up from its prior [Migration] // state. The [Migrator] will run the statements in a transaction unless the SQL contains // [disableTxPattern]. Cannot be used together with [UpFunc]. UpSQL string // DownSQL declares SQL statements that brings the database back down to its prior // [Migration] state. The [Migrator] will run the statements in a transaction unless the SQL // contains [disableTxPattern]. Cannot be used together with [DownFunc]. DownSQL string // DisableFuncTx, when true, tells the [Migrator] to not start a new transaction before // calling [UpFunc] (or [DownFunc]). Some SQL statements such as `create index concurrently` // cannot run within a transaction. DisableFuncTx bool // UpFunc is a Go function that brings the database up from its prior state [Migration] // state. Cannot be used together with [UpSQL]. UpFunc MigrationFunc // DownFunc is a Go function that brings the database back down to its prior [Migration] // state. Cannot be used together with [DownSQL]. DownFunc MigrationFunc } ``` -------------------------------- ### Function: LockExecTx Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Executes a SQL statement within a transaction after acquiring a lock. It requires a context, a database connection, and the SQL string. Returns an error if the lock or execution fails. ```go func LockExecTx(ctx context.Context, conn *pgx.Conn, sql string) (err error) ``` -------------------------------- ### BadVersionError Error Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Implements the Error method for the BadVersionError type, providing a string representation of the error. ```go func (e BadVersionError) Error() string ``` -------------------------------- ### Migrator.GetCurrentVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Retrieves the current database schema version. ```APIDOC ## Migrator.GetCurrentVersion ### Description Retrieves the current database schema version. ### Method Signature ```go func (m *Migrator) GetCurrentVersion(ctx context.Context) (v int32, err error) ``` ### Parameters - **ctx** (context.Context) - The context for the operation. ### Returns - **v** (int32) - The current schema version. - **err** (error) - An error if the operation fails. ``` -------------------------------- ### Split Function Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate/internal/sqlsplit The Split function takes a single string containing SQL and returns a slice of strings, where each string is a complete SQL statement. ```APIDOC ## func Split ### Description Split splits sql into into a slice of strings each containing one SQL statement. ### Signature ```go func Split(sql string) []string ``` ### Parameters #### Path Parameters - **sql** (string) - The input string containing SQL statements. ### Returns - **[]string** - A slice of strings, where each element is a single SQL statement. ``` -------------------------------- ### GetCurrentVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Retrieves the current applied migration version from the database. ```APIDOC ## GetCurrentVersion ### Description Retrieves the current applied migration version from the database. ### Method ```go func (m *Migrator) GetCurrentVersion(ctx context.Context) (v int32, err error) ``` ### Parameters * **ctx** (context.Context) - The context for the operation. ### Returns * **v** (int32) - The current migration version. * **err** (error) - An error if retrieval fails. ``` -------------------------------- ### Migrator.AppendMigration Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Appends a new migration to the Migrator's list of migrations. ```go func (m *Migrator) AppendMigration(name, upSQL, downSQL string) ``` -------------------------------- ### Migrator.SetVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Sets the current database version. ```APIDOC ## (*Migrator) SetVersion ### Description Sets the current database version. ### Signature ```go func (m *Migrator) SetVersion(ctx context.Context, version int32) (err error) ``` ``` -------------------------------- ### Migrator.GetCurrentVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Retrieves the current database version from the version table. ```APIDOC ## (*Migrator) GetCurrentVersion ### Description Retrieves the current database version from the version table. ### Signature ```go func (m *Migrator) GetCurrentVersion(ctx context.Context) (v int32, err error) ``` ``` -------------------------------- ### Migrator Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Manages database migrations. ```APIDOC ## Migrator ### Description Manages database migrations. ### NewMigrator ```go func NewMigrator(ctx context.Context, conn *pgx.Conn, versionTable string) (m *Migrator, err error) ``` ### NewMigratorEx ```go func NewMigratorEx(ctx context.Context, conn *pgx.Conn, versionTable string, ...) (m *Migrator, err error) ``` ``` -------------------------------- ### BadVersionError Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents an error indicating an invalid version. ```APIDOC ## BadVersionError ### Description Represents an error indicating an invalid version. ### Type Definition ```go type BadVersionError string ``` ### Error Method ```go func (e BadVersionError) Error() string ``` ``` -------------------------------- ### Migrator.AppendMigration Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Appends a new migration to the migrator. ```APIDOC ## (*Migrator) AppendMigration ### Description Appends a new migration to the migrator. ### Signature ```go func (m *Migrator) AppendMigration(name, upSQL, downSQL string) ``` ``` -------------------------------- ### Migrator.AppendMigration Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Appends a new migration to the migrator. ```APIDOC ## Migrator.AppendMigration ### Description Appends a new migration to the migrator. ### Method Signature ```go func (m *Migrator) AppendMigration(name, upSQL, downSQL string) ``` ### Parameters - **name** (string) - The name of the migration. - **upSQL** (string) - The SQL statements to apply for the migration. - **downSQL** (string) - The SQL statements to revert the migration. ``` -------------------------------- ### Declare Error Variable for No Forward Migration Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Declares a package-level error variable used when no SQL is found in a forward migration step. ```go var ErrNoFwMigration = errors.New("no sql in forward migration step") ``` -------------------------------- ### SetVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Sets the current migration version without running any migrations. Useful for baselining an existing database. ```APIDOC ## SetVersion ### Description Sets the current migration version without running any migrations. This is useful for baselining an existing database when adopting tern. ### Method ```go func (m *Migrator) SetVersion(ctx context.Context, version int32) (err error) ``` ### Parameters * **ctx** (context.Context) - The context for the operation. * **version** (int32) - The version to set. ``` -------------------------------- ### IrreversibleMigrationError Error Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Implements the Error method for the IrreversibleMigrationError type, providing a string representation of the error. ```go func (e IrreversibleMigrationError) Error() string ``` -------------------------------- ### MigratorOptions Struct Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Options for configuring the Migrator, such as disabling transactions for all migrations. ```go type MigratorOptions struct { // DisableTx causes the Migrator not to run migrations in a transaction. DisableTx bool } ``` -------------------------------- ### Migrator.SetVersion Method Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Sets the current migration version without executing any migration scripts. Useful for baselining existing databases. ```go func (m *Migrator) SetVersion(ctx context.Context, version int32) (err error) ``` -------------------------------- ### LockExecTx Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Executes a SQL statement within a transaction, ensuring exclusive lock. ```APIDOC ## LockExecTx ### Description Executes a SQL statement within a transaction, ensuring exclusive lock. ### Signature ```go func LockExecTx(ctx context.Context, conn *pgx.Conn, sql string) (err error) ``` ``` -------------------------------- ### Split SQL String Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate/internal/sqlsplit Use this function to split a single string containing multiple SQL statements into a slice of individual statements. It handles standard SQL syntax for statement separation. ```go func Split(sql string) []string ``` -------------------------------- ### NoMigrationsFoundError Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents an error when no migrations are found. ```APIDOC ## NoMigrationsFoundError ### Description Represents an error when no migrations are found. ### Type Definition ```go type NoMigrationsFoundError string ``` ### Error Method ```go func (e NoMigrationsFoundError) Error() string ``` ``` -------------------------------- ### LockExecTx Function Signature Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Signature for the LockExecTx function, which executes SQL within a transaction lock. ```go func LockExecTx(ctx context.Context, conn *pgx.Conn, sql string) (err error) ``` -------------------------------- ### IrreversibleMigrationError Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents an error for an irreversible migration. ```APIDOC ## IrreversibleMigrationError ### Description Represents an error for an irreversible migration. ### Type Definition ```go type IrreversibleMigrationError struct { // contains filtered or unexported fields } ``` ### Error Method ```go func (e IrreversibleMigrationError) Error() string ``` ``` -------------------------------- ### Migrator.SetVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Sets the current migration version in the database. ```APIDOC ## (*Migrator) SetVersion ### Description Sets the current migration version in the database. ### Signature ```go func (m *Migrator) SetVersion(ctx context.Context, version int32) (err error) ``` ``` -------------------------------- ### Override Database Version Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Use `tern override-version` to set the migration version in the version table without running migrations. This is useful when adopting Tern on an existing database. ```bash tern override-version 1 ``` -------------------------------- ### Renumber Migrations - Finish Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Complete the renumbering process after merging branches. This command automatically adjusts migration numbers to resolve conflicts and maintain order. ```bash # Then go to the branch with migrations that should come later and merge or rebase. $ git switch feature $ git rebase master Successfully rebased and updated refs/heads/feature. $ ls 001_create_users.sql 002_add_last_login_to_users.sql 002_create_todos.sql # There are now two migrations with the same migration number. $ tern renumber finish $ ls 001_create_users.sql 002_add_last_login_to_users.sql 003_create_todos.sql # The migrations are now renumbered in the correct order. ``` -------------------------------- ### BadVersionError Type Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Defines the BadVersionError type, used to indicate issues with migration versions. ```go type BadVersionError string ``` -------------------------------- ### CodePackage Eval Method Signature Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Signature for the Eval method of the CodePackage type, used to evaluate the code package with provided data. ```go func (cp *CodePackage) Eval(data map[string]interface{}) (string, error) ``` -------------------------------- ### Type: IrreversibleMigrationError Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Represents an error for migrations that cannot be reversed. It contains filtered or unexported fields. ```go type IrreversibleMigrationError struct { // contains filtered or unexported fields } ``` -------------------------------- ### MigrationPgError Struct Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Represents a PostgreSQL error that occurred during a migration. It embeds pgconn.PgError for detailed error information. ```go type MigrationPgError struct { MigrationName string Sql string *pgconn.PgError } ``` -------------------------------- ### AppendMigration Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Appends a new migration to the Migrator's list of migrations. ```APIDOC ## AppendMigration ### Description Appends a new migration to the Migrator's list of migrations. ### Method ```go func (m *Migrator) AppendMigration(name, upSQL, downSQL string) ``` ### Parameters * **name** (string) - The name of the migration. * **upSQL** (string) - The SQL statements to apply for the up migration. * **downSQL** (string) - The SQL statements to apply for the down migration. ``` -------------------------------- ### Irreversible Migration SQL Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 For irreversible migrations, such as dropping a table, simply omit the magic comment that separates up and down statements. ```sql drop table widgets; ``` -------------------------------- ### Disable Transaction for Migrations Source: https://pkg.go.dev/github.com/jackc/tern/v2%40v2.4.1 Include this magic comment to disable the default transaction wrapping for migrations. This is necessary for statements like `create index concurrently`. ```sql ---- tern: disable-tx ---- ``` -------------------------------- ### Migrator.SetVersion Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Sets the current migration version without running any migrations. This is useful for baselining an existing database when adopting tern. ```APIDOC ## Migrator.SetVersion ### Description Sets the current migration version without running any migrations. This is useful for baselining an existing database when adopting tern. ### Method Signature ```go func (m *Migrator) SetVersion(ctx context.Context, version int32) (err error) ``` ### Parameters - **ctx** (context.Context) - The context for the operation. - **version** (int32) - The version to set. ### Returns - **err** (error) - An error if setting the version fails. ``` -------------------------------- ### NoMigrationsFoundError Struct Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate An empty struct type used to indicate that no migrations were found. ```go type NoMigrationsFoundError struct{} ``` -------------------------------- ### MigrationFunc Type Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Defines a function signature for custom migration logic in Go. The Migrator will manage transactions unless Migration.DisableFuncTx is set. ```go type MigrationFunc func(context.Context, *pgx.Conn) error ``` -------------------------------- ### Migrator Struct Definition Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Manages a collection of migrations and provides methods to apply them to a database. Supports custom callbacks and data for migrations. ```go type Migrator struct { Migrations []*Migration OnStart func(int32, string, string, string) // OnStart is called when a migration is run with the sequence, name, direction, and SQL Data map[string]interface{} // Data available to use in migrations // contains filtered or unexported fields } ``` -------------------------------- ### Function: ExtractErrorLine Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Extracts line number, column number, and text from a source string at a given character position. The first character is position 1. Returns an ErrorLineExtract and an error if extraction fails. ```go func ExtractErrorLine(source string, position int) (ErrorLineExtract, error) ``` -------------------------------- ### ExtractErrorLine Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Extracts line number, column number, and text from a source string at a given position. ```APIDOC ## ExtractErrorLine ### Description Extracts line number, column number, and text from a source string at a given position. The first character is position 1. ### Signature ```go func ExtractErrorLine(source string, position int) (ErrorLineExtract, error) ``` ``` -------------------------------- ### ExtractErrorLine Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate Extracts line number, column number, and text from a source string at a given position. ```APIDOC ## ExtractErrorLine ### Description ExtractErrorLine takes source and character position extracts the line number, column number, and the line of text. The first character is position 1. ### Signature ```go func ExtractErrorLine(source string, position int) (ErrorLineExtract, error) ``` ### Returns - **ErrorLineExtract**: Contains LineNum, ColumnNum, and Text. ``` -------------------------------- ### Type: ErrorLineExtract Source: https://pkg.go.dev/github.com/jackc/tern/v2/migrate%40v2.4.1 Structure to hold extracted error line information, including line number, column number, and the text of the line. ```go type ErrorLineExtract struct { LineNum int // Line number starting with 1 ColumnNum int // Column number starting with 1 Text string // Text of the line without a new line character. } ```