Skip to main content
The database package provides database connection management and migration functionality using PostgreSQL with sqlx.

Database Type

The Database type represents a database connection with migration capabilities.

Constructor

(*Database, error)
Creates a new Database instance with the given PostgreSQL connection string.Parameters:
  • connection (string): PostgreSQL connection string
Connection string format:
Example:

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 identifier
  • repository (any): Repository instance

Migrate

error
Runs all pending migrations for registered repositories. Migrations are tracked in a migrations table and only run once.Process:
  1. Creates the migrations tracking table if it doesn’t exist
  2. Retrieves completed migrations
  3. Parses migrations from all registered repositories
  4. 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 .sql extension
  • Contain a -- +migrate Up marker followed by SQL statements
  • Optionally contain a -- +migrate Down marker 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 the Migrations() method:

Complete Example

Repository with Migrations

user_repository.go:
001_create_users_table.sql:

Application Setup

main.go:

Migration Tracking

Platforma automatically tracks applied migrations in a migrations table:
Each migration is tracked by repository name and migration ID, ensuring migrations are only applied once.