database

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package database provides GORM utilities for Clean Architecture backends:

  • Connect: open a database connection (Postgres or SQLite)
  • Register: AutoMigrate domain models at startup
  • Repository[T]: generic CRUD base repository
  • WithTx: run a function inside a transaction with automatic commit/rollback

Usage:

db, err := database.Connect(database.Config{DSN: os.Getenv("DATABASE_URL")})
if err != nil { ... }

database.Register(db, &user.User{}, &order.Order{})

repo := database.NewRepository[user.User](db.DB())

Package database provides GORM utilities for portsmith-based applications.

Connecting

db, err := database.Connect(database.Config{
    DSN: os.Getenv("DATABASE_URL"),
})

For SQLite (tests and local development):

db, err := database.Connect(database.Config{
    Driver: database.DriverSQLite,
    DSN:    ":memory:",
    Silent: true,
})

Auto-migration

Register domain models at application startup:

database.Register(db, &user.User{}, &order.Order{})

This calls gorm.AutoMigrate under the hood. It adds columns and indexes but never removes them (safe migrations).

Generic repository

Use database.Repository[T] to avoid CRUD boilerplate:

type Repository struct {
    base database.Repository[User]
    db   *gorm.DB
}

func NewRepository(db *gorm.DB) *Repository {
    return &Repository{base: database.NewRepository[User](db), db: db}
}

func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) {
    // custom query — only this needs to be written manually
}

Transactions

err := database.WithTx(ctx, db, func(tx *database.DB) error {
    txRepo := NewRepository(tx.DB())
    return txRepo.Create(ctx, entity)
})

The transaction is committed on nil return, rolled back on any error.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Register

func Register(db *DB, models ...any) error

Register runs AutoMigrate for all provided models. Call once at application startup after Connect.

database.Register(db, &user.User{}, &order.Order{})

func WithTx

func WithTx(ctx context.Context, db *DB, fn func(tx *DB) error) error

WithTx runs fn inside a transaction. Commits on success, rolls back on any error returned by fn.

Types

type Config

type Config struct {
	// Driver selects the database engine. Defaults to Postgres.
	Driver Driver

	// DSN is the data source name.
	// Postgres: "host=... user=... dbname=... sslmode=disable"
	// SQLite:   ":memory:" or "/path/to/file.db"
	DSN string

	// Silent disables GORM query logging (useful in tests).
	Silent bool
}

Config holds database connection settings.

type DB

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

DB wraps *gorm.DB to keep the portsmith API decoupled from gorm import paths.

func Connect

func Connect(cfg Config) (*DB, error)

Connect opens a database connection based on Config.

func (*DB) DB

func (d *DB) DB() *gorm.DB

DB returns the underlying *gorm.DB for queries that need it directly.

type Driver

type Driver string

Driver identifies the database engine.

const (
	DriverPostgres Driver = "postgres"
	DriverSQLite   Driver = "sqlite"
)

type Repository

type Repository[T any] struct {
	// contains filtered or unexported fields
}

Repository is a generic base repository for standard CRUD operations. Embed or use directly to avoid per-entity boilerplate.

FindByID returns apperrors.NotFound when no record exists, keeping gorm internals from leaking into the service layer.

func NewRepository

func NewRepository[T any](db *gorm.DB) Repository[T]

NewRepository creates a new generic Repository backed by the given *gorm.DB.

func (Repository[T]) Create

func (r Repository[T]) Create(ctx context.Context, entity *T) error

Create inserts a new record and populates the primary key on the entity.

func (Repository[T]) Delete

func (r Repository[T]) Delete(ctx context.Context, id uint) error

Delete removes a record by primary key.

func (Repository[T]) FindByID

func (r Repository[T]) FindByID(ctx context.Context, id uint) (*T, error)

FindByID retrieves a record by primary key. Returns apperrors.NotFound (code NOT_FOUND) when no record is found.

func (Repository[T]) Update

func (r Repository[T]) Update(ctx context.Context, entity *T) error

Update saves all fields of an existing record.

Jump to

Keyboard shortcuts

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