postgres

package
v0.0.0-...-276d082 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2025 License: MIT Imports: 16 Imported by: 0

README

postgres

postgres://user:password@host:port/dbname?query (postgresql:// works, too)

URL Query WithInstance Config Description
x-migrations-table MigrationsTable Name of the migrations table
x-migrations-table-quoted MigrationsTableQuoted By default, migrate quotes the migration table for SQL injection safety reasons. This option disable quoting and naively checks that you have quoted the migration table name. e.g. "my_schema"."schema_migrations"
x-statement-timeout StatementTimeout Abort any statement that takes more than the specified number of milliseconds
x-multi-statement MultiStatementEnabled Enable multi-statement execution (default: false)
x-multi-statement-max-size MultiStatementMaxSize Maximum size of single statement in bytes (default: 10MB)
dbname DatabaseName The name of the database to connect to
search_path This variable specifies the order in which schemas are searched when an object is referenced by a simple name with no schema specified.
user The user to sign in as
password The user's password
host The host to connect to. Values that start with / are for unix domain sockets. (default is localhost)
port The port to bind to. (default is 5432)
fallback_application_name An application_name to fall back to if one isn't provided.
connect_timeout Maximum wait for connection, in seconds. Zero or not specified means wait indefinitely.
sslcert Cert file location. The file must contain PEM encoded data.
sslkey Key file location. The file must contain PEM encoded data.
sslrootcert The location of the root certificate file. The file must contain PEM encoded data.
sslmode Whether or not to use SSL (disable|require|verify-ca|verify-full)

Upgrading from v1

  1. Write down the current migration version from schema_migrations
  2. DROP TABLE schema_migrations
  3. Wrap your existing migrations in transactions (BEGIN/COMMIT) if you use multiple statements within one migration.
  4. Download and install the latest migrate version.
  5. Force the current migration version with migrate force <current_version>.

Multi-statement mode

In PostgreSQL running multiple SQL statements in one Exec executes them inside a transaction. Sometimes this behavior is not desirable because some statements can be only run outside of transaction (e.g. CREATE INDEX CONCURRENTLY). If you want to use CREATE INDEX CONCURRENTLY without activating multi-statement mode you have to put such statements in a separate migration files.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultMigrationsTable       = "schema_migrations"
	DefaultMultiStatementMaxSize = 10 * 1 << 20 // 10 MB
)
View Source
var (
	ErrNilConfig      = fmt.Errorf("no config")
	ErrNoDatabaseName = fmt.Errorf("no database name")
	ErrNoSchema       = fmt.Errorf("no schema")
	ErrDatabaseDirty  = fmt.Errorf("database is dirty")
)

Functions

func WithInstance

func WithInstance(instance *sql.DB, config *Config) (database.Driver, error)

Types

type Config

type Config struct {
	MigrationsTable       string
	MigrationsTableQuoted bool
	MultiStatementEnabled bool
	DatabaseName          string
	SchemaName            string

	StatementTimeout      time.Duration
	MultiStatementMaxSize int
	// contains filtered or unexported fields
}

type Postgres

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

func (*Postgres) Close

func (p *Postgres) Close() error

func (*Postgres) Drop

func (p *Postgres) Drop() (err error)

func (*Postgres) IsDatabaseDirty

func (p *Postgres) IsDatabaseDirty() (int, bool, error)

IsDatabaseDirty checks if the database's migrations table contains any "dirty" (in-progress or failed) migrations. It queries the migrations table for any entry where the dirty flag is set to true. If a dirty migration is found, it returns its migration_timestamp and true. If no dirty migrations are found, or if the migrations table itself doesn't exist (e.g., first run), it returns 0 and false. Any other database errors are wrapped and returned.

func (*Postgres) Open

func (p *Postgres) Open(url string) (database.Driver, error)

func (*Postgres) Run

func (p *Postgres) Run(migration io.Reader) error

func (*Postgres) SetVersion

func (p *Postgres) SetVersion(version int, dirty bool) error

func (*Postgres) Unlock

func (p *Postgres) Unlock() error

func (*Postgres) Version

func (p *Postgres) Version() (version int, dirty bool, err error)

type PostgresExtras

type PostgresExtras struct {
	*Postgres
}

func WithConnection

func WithConnection(ctx context.Context, conn *sql.Conn, config *Config) (*PostgresExtras, error)

WithConnection initializes a new PostgresExtras instance using an existing, active sql.Conn and a Config struct. It ensures the connection is valid and, if not explicitly provided in the config, it automatically fetches the current database name and schema name from the connection. It also sets default values for the migrations table if none are specified and correctly parses quoted table names. Finally, it verifies the existence and readiness of the migrations version table in the database before returning the initialized PostgresExtras object.

func (*PostgresExtras) AddDirtyMigration

func (p *PostgresExtras) AddDirtyMigration(version uint) error

AddDirtyMigration marks a specific migration version as "dirty" or "in-progress" in the database's migrations table. It does this by inserting a new record with the provided version into the table within a database transaction. If the insertion fails or the transaction cannot be committed, it attempts to roll back the transaction and returns a detailed error.

func (*PostgresExtras) GetAllAppliedMigrations

func (p *PostgresExtras) GetAllAppliedMigrations() ([]int, error)

GetAllAppliedMigrations retrieves a list of all applied migration timestamps from the migrations table in the database. It constructs a SQL query to select migration_timestamp values, orders them in descending order, and executes the query against the database. The function then scans the results into a slice of integers and handles any potential database errors, including proper closing of the result rows.

func (*PostgresExtras) IsMigrationApplied

func (p *PostgresExtras) IsMigrationApplied(version uint) (bool, error)

IsMigrationApplied checks if a specific migration version has already been applied by querying the migrations table. It returns true if the migration is found, false if not found or if the table doesn't exist. It wraps other unexpected errors in a custom database.Error.

func (*PostgresExtras) RemoveMigration

func (p *PostgresExtras) RemoveMigration(version uint) error

RemoveMigration deletes a specific migration version from the database's migrations table. It constructs and executes a SQL DELETE statement based on the provided version within a database transaction. The function includes comprehensive error handling for transaction management, ensuring that any failures during the deletion process are properly rolled back and reported.

func (*PostgresExtras) UpdateMigrationDirtyFlag

func (p *PostgresExtras) UpdateMigrationDirtyFlag(version uint, dirty bool) error

UpdateMigrationDirtyFlag updates the dirty status and applied_at timestamp for a specific migration version in the database's migrations table. It sets the dirty flag to true or false based on the provided boolean value and records the current timestamp. The operation is performed within a database transaction, with robust error handling for transaction start, execution, and commit/rollback.

Jump to

Keyboard shortcuts

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