database package provides database connection management and migration functionality using PostgreSQL with sqlx.
Database Type
TheDatabase type represents a database connection with migration capabilities.
Constructor
(*Database, error)
Creates a new Database instance with the given PostgreSQL connection string.Parameters:Example:
connection(string): PostgreSQL connection string
Methods
Connection
*sqlx.DB
Returns the underlying sqlx database connection for direct database operations.
RegisterRepository
void
Registers a repository with the database. If the repository implements the migrator interface, its migrations will be applied when
Migrate() is called.Parameters:name(string): Repository identifierrepository(any): Repository instance
Migrate
error
Runs all pending migrations for registered repositories. Migrations are tracked in a
migrations table and only run once.Process:- Creates the migrations tracking table if it doesn’t exist
- Retrieves completed migrations
- Parses migrations from all registered repositories
- Applies only pending migrations in order
Migration Type
Represents a database migration with up and down SQL statements.string
Unique identifier for the migration, derived from the filename (without .sql extension) or overridden with
-- +migrate ID: marker.string
SQL statements to apply the migration.
string
SQL statements to revert the migration (optional).
Migration File Format
Migration files must:- Have a
.sqlextension - Contain a
-- +migrate Upmarker followed by SQL statements - Optionally contain a
-- +migrate Downmarker for rollback SQL - Be named in a sortable format (e.g.,
001_create_users.sql,002_add_email.sql)
Basic Migration Example
Custom Migration ID
You can override the migration ID using the-- +migrate ID: marker (must be the first marker):
Implementing Migrations in Repositories
To enable migrations for a repository, implement theMigrations() method:
Complete Example
Repository with Migrations
user_repository.go:Application Setup
main.go:Migration Tracking
Platforma automatically tracks applied migrations in amigrations table: