dorm

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 14 Imported by: 0

README

dorm

Policy-driven PostgreSQL ORM for Go. Automatically enforce data access policies to eliminate forgotten tenant filters, while providing deterministic migrations, schema drift detection, built-in seeding, and first-class OpenTelemetry support.

Why dorm?

Multi-tenant applications often contain queries like:

db.Where("company_id = ?", companyID).
    Find(&products)

This works... until someone forgets the filter.

// Missing company filter
db.Find(&products)

A single missing condition can expose data belonging to another company or tenant.

dorm is designed to prevent this class of bugs.

Instead of manually writing access filters everywhere, developers write business queries while dorm automatically injects the required access policies from context.Context.

db.Find(ctx, &products)

Automatically becomes:

SELECT *
FROM products
WHERE company_id = $1
  AND deleted_at IS NULL

No boilerplate.

No forgotten filters.

Secure by default.


Features

Policy-Driven Access Engine

The primary feature of dorm.

Automatically applies:

  • Company isolation
  • Row-level access policies
  • Soft delete filtering
  • Context-aware security

Supports multiple policy levels:

  • Default
  • IgnoreCompany
  • IgnoreRLS
  • System

Designed for:

  • SaaS platforms
  • ERP
  • WMS
  • CRM
  • Multi-tenant systems

PostgreSQL First

Built specifically for PostgreSQL.

Rather than supporting every SQL dialect from day one, dorm focuses on delivering the best possible PostgreSQL experience.


Deterministic Migrations

Model-driven migration generation.

go install github.com/dionisius77/dorm/cmd/orm

orm migrate generate

No automatic schema mutation.

Developers review generated migrations before execution.

orm migrate run

If no schema changes exist, no migration is generated.


Schema Drift Detection

Detect differences between:

  • Go models
  • PostgreSQL schema

before they become production issues.


Seed Engine

Built-in, idempotent seed synchronization.

seed.Sync(
    []Role{
        {
            Code: "ADMIN",
            Name: "Administrator",
        },
    },
    seed.Key("Code"),
)

Running the same seed repeatedly always produces the same final database state.


OpenTelemetry

First-class observability.

Automatically traces:

  • Queries
  • Transactions
  • Migrations
  • Seeds
  • Schema inspection

SQL visibility is configurable:

  • Disabled
  • Metadata
  • Statement
  • StatementWithArgs

Raw SQL Escape Hatch

dorm also supports explicit native SQL for cases where the high-level API is not the best fit.

Raw SQL never bypasses access policy implicitly.

Developers must explicitly opt out:

db.Raw(
    ctx,
    `
    SELECT *
    FROM users
    WHERE email = ?
    `,
    email,
).
    WithoutPolicy().
    Scan(&users)

Notes:

  • WithoutPolicy() is required before Scan() or Exec()
  • ? placeholders are rebound by the active dialect
  • Raw SQL participates in the current transaction automatically
  • The ORM does not parse or rewrite SQL beyond placeholder conversion

Composable Models

Choose only the capabilities your model requires.

Full entity:

type User struct {
    model.Entity

    ID   uuid.UUID
    Name string
}

Company only:

type Product struct {
    model.Company

    ID   uuid.UUID
    Name string
}

Optimistic locking:

type User struct {
    model.Company
    model.Version

    ID   uuid.UUID
    Name string
}

model.Version enables safe concurrent updates with automatic version checks.

Raw model:

type Country struct {
    ID   int
    Name string
}

Installation

go get github.com/dionisius77/dorm

Quick Start

Connect

driver := postgres.New(postgres.Config{
    Host:     "localhost",
    Port:     5432,
    Database: "app",
    Username: "postgres",
    Password: "secret",
})

db, err := dorm.Open(ctx, driver)
if err != nil {
    panic(err)
}

defer db.Close()

Create a model

type Product struct {
    model.Entity

    ID    uuid.UUID
    Name  string
    Price decimal.Decimal
}

CRUD

err := db.Create(ctx, &product)

err = db.Find(ctx, &products)

err = db.Update(ctx, &product)

err = db.Delete(ctx, &product)

Query Composition

Query modifiers are passed as QueryOptions and composed in SQL order by the ORM.

err := db.WithContext(ctx).Find(
    &users,
    orm.Select("users.id, users.name"),
    orm.LeftJoin("roles r", "r.id = users.role_id"),
    orm.Where("users.status = ?", status),
    orm.OrderBy("users.created_at DESC"),
    orm.Limit(20),
    orm.Offset(40),
)

Access Policy

Access policies are automatically resolved from context.Context.

Normal application code:

db.Find(ctx, &products)

No manual company filtering is required.

Override policies when needed.

Default:

db.WithPolicy(access.Default())

Ignore company isolation:

db.WithPolicy(access.IgnoreCompany())

Ignore row-level isolation:

db.WithPolicy(access.IgnoreRLS())

System mode:

db.WithPolicy(access.System())

Policy changes are explicit and observable.


Migrations

Generate:

orm migrate generate

Run:

orm migrate run

Rollback:

orm migrate rollback

Schema verification:

orm schema check

Seeds

Register seeders:

seed.Register(
    RoleSeeder{},
    PermissionSeeder{},
    AdminSeeder{},
)

Run:

orm seed run

Tracing

dorm integrates with OpenTelemetry out of the box.

Database operations automatically generate traces for:

  • Query execution
  • Transactions
  • Migrations
  • Schema inspection
  • Seed synchronization

SQL trace visibility is configurable depending on the environment.


CLI

All database tooling is included.

go install github.com/dionisius77/dorm/cmd/orm

orm --help

orm migrate generate

orm migrate run

orm migrate rollback

orm schema check

orm seed run

orm analyze --sql "SELECT * FROM users WHERE email = $1"

The CLI reuses the same Driver configuration as the application, ensuring a single source of truth for database access.


Example Applications

Explore complete examples:

examples/
├── basic/
├── todo/
└── multi-tenant/

Philosophy

dorm is built around a small set of principles:

  • Policy-driven data access
  • Secure by default
  • Explicit over magic
  • Deterministic schema management
  • PostgreSQL first
  • Production-ready observability
  • Idiomatic Go APIs

Documentation

docs/
├── adr/
├── architecture/
├── guides/
└── examples/

Roadmap

Current priorities:

  • Production hardening
  • Performance optimization
  • Relationship API
  • Plugin ecosystem
  • Additional SQL dialects

Contributing

Contributions are welcome.

Before opening a Pull Request:

  • Run unit tests
  • Run integration tests
  • Run benchmarks
  • Ensure examples compile
  • Follow the project's architectural decisions (ADR)

License

MIT License.

Documentation

Overview

Package dorm provides the stable public entry points for opening database connections.

Index

Constants

View Source
const (
	ExecutionStatusSkipped             = orm.ExecutionStatusSkipped
	AccessPolicyEventInjectedPredicate = orm.AccessPolicyEventInjectedPredicate
	AccessPolicyEventInjectedField     = orm.AccessPolicyEventInjectedField
	AccessPolicyEventInheritedPolicy   = orm.AccessPolicyEventInheritedPolicy
	AccessPolicyEventPolicyOverride    = orm.AccessPolicyEventPolicyOverride
	AccessPolicyEventSoftDelete        = orm.AccessPolicyEventSoftDelete
)
View Source
const (
	// VersionMajor is the major release component for the current public API.
	VersionMajor = 0
	// VersionMinor is the minor release component for the current public API.
	VersionMinor = 4
	// VersionPatch is the patch release component for the current public API.
	VersionPatch = 3
)
View Source
const (
	// MinimumSupportedGoVersion is the minimum Go toolchain version supported by this release line.
	MinimumSupportedGoVersion = "1.26"
)

Variables

View Source
var (
	// SupportedOS lists the platform targets considered supported by the framework.
	SupportedOS = []string{"linux", "darwin", "windows"}
	// SupportedArch lists the CPU architectures considered supported by the framework.
	SupportedArch = []string{"amd64", "arm64"}
	// SupportedPostgresMajorVersions lists the PostgreSQL major versions validated by this release line.
	SupportedPostgresMajorVersions = []int{13, 14, 15, 16, 17}
)
View Source
var (
	ErrNotFound             = dormerrors.ErrNotFound
	ErrAlreadyExists        = dormerrors.ErrAlreadyExists
	ErrConflict             = dormerrors.ErrConflict
	ErrInvalidModel         = dormerrors.ErrInvalidModel
	ErrInvalidRelationship  = dormerrors.ErrInvalidRelationship
	ErrMigrationRequired    = dormerrors.ErrMigrationRequired
	ErrSchemaDrift          = dormerrors.ErrSchemaDrift
	ErrInvalidContext       = dormerrors.ErrInvalidContext
	ErrMissingCompany       = dormerrors.ErrMissingCompany
	ErrPolicyDenied         = dormerrors.ErrPolicyDenied
	ErrSeedConflict         = dormerrors.ErrSeedConflict
	ErrDriverNotRegistered  = dormerrors.ErrDriverNotRegistered
	ErrUnsupportedDialect   = dormerrors.ErrUnsupportedDialect
	ErrTransactionClosed    = dormerrors.ErrTransactionClosed
	ErrCommitFailed         = dormerrors.ErrCommitFailed
	ErrRollbackFailed       = dormerrors.ErrRollbackFailed
	ErrOptimisticLockFailed = dormerrors.ErrOptimisticLockFailed
	ErrRawSQLPolicyRequired = dormerrors.ErrRawSQLPolicyRequired
)

Functions

func RegisterDriver

func RegisterDriver(d driver.Driver)

func RegisteredDriver

func RegisteredDriver() driver.Driver

func Version

func Version() string

Version returns the current module version in semantic version format.

Types

type APIContract

type APIContract struct {
	Name            string
	Lifecycle       APILifecycle
	DeprecatedSince string
	Replacement     string
}

APIContract describes the lifecycle state of a public symbol or package.

func DeprecatedAPI

func DeprecatedAPI(name, since, replacement string) APIContract

DeprecatedAPI creates a deprecated API contract record.

func ExperimentalAPI

func ExperimentalAPI(name string) APIContract

ExperimentalAPI creates an experimental API contract record.

func StableAPI

func StableAPI(name string) APIContract

StableAPI creates a stable API contract record.

func (APIContract) IsDeprecated

func (c APIContract) IsDeprecated() bool

IsDeprecated reports whether the contract is deprecated.

func (APIContract) IsStable

func (c APIContract) IsStable() bool

IsStable reports whether the contract is stable.

type APILifecycle

type APILifecycle string

APILifecycle describes the lifecycle of a public symbol.

const (
	// APILifecycleExperimental marks a symbol that may change without notice.
	APILifecycleExperimental APILifecycle = "experimental"
	// APILifecycleStable marks a supported public symbol.
	APILifecycleStable APILifecycle = "stable"
	// APILifecycleDeprecated marks a public symbol that should not be used for new code.
	APILifecycleDeprecated APILifecycle = "deprecated"
	// APILifecycleRemoved marks a symbol that has been removed from the public API.
	APILifecycleRemoved APILifecycle = "removed"
)

type AccessPolicyEvent added in v0.4.0

type AccessPolicyEvent = orm.AccessPolicyEvent

type AccessPolicyEventKind added in v0.4.0

type AccessPolicyEventKind = orm.AccessPolicyEventKind

type AuditAction added in v0.4.0

type AuditAction = orm.AuditAction

type CompatibilityPolicy

type CompatibilityPolicy struct {
	MinimumGoVersion string
	OperatingSystems []string
	Architectures    []string
	PostgresMajors   []int
}

CompatibilityPolicy describes supported runtime and database environments.

func DefaultCompatibilityPolicy

func DefaultCompatibilityPolicy() CompatibilityPolicy

DefaultCompatibilityPolicy returns the framework compatibility policy for this release line.

func (CompatibilityPolicy) Summary

func (p CompatibilityPolicy) Summary() string

Summary returns a stable human-readable summary of the compatibility policy.

func (CompatibilityPolicy) SupportsPostgreSQLMajor

func (p CompatibilityPolicy) SupportsPostgreSQLMajor(major int) bool

SupportsPostgreSQLMajor reports whether the provided PostgreSQL major version is supported.

func (CompatibilityPolicy) ValidateRuntime

func (p CompatibilityPolicy) ValidateRuntime() error

ValidateRuntime checks whether the current Go runtime and platform are supported.

type DB

type DB = orm.DB

func Open

func Open(ctx context.Context, drv driver.Driver, opts ...OpenOption) (*DB, error)

type DryRunSession added in v0.4.0

type DryRunSession = orm.DryRunSession

type ExecutionReport added in v0.4.0

type ExecutionReport = orm.ExecutionReport

type ExecutionStatement added in v0.4.0

type ExecutionStatement = orm.ExecutionStatement

type ExecutionStatus added in v0.4.0

type ExecutionStatus = orm.ExecutionStatus

type LifecycleHookEvent added in v0.4.0

type LifecycleHookEvent = orm.LifecycleHookEvent

type OpenOption added in v0.1.11

type OpenOption func(*openConfig)

func WithObservability added in v0.1.11

func WithObservability(cfg orm.ObservabilityConfig) OpenOption

type OptimisticLockingInfo added in v0.4.1

type OptimisticLockingInfo = orm.OptimisticLockingInfo

type QueryAdvisor added in v0.4.0

type QueryAdvisor = orm.QueryAdvisor

type QueryAdvisorFinding added in v0.4.0

type QueryAdvisorFinding = orm.QueryAdvisorFinding

type QueryAdvisorInput added in v0.4.0

type QueryAdvisorInput = orm.QueryAdvisorInput

type QueryAdvisorReport added in v0.4.0

type QueryAdvisorReport = orm.QueryAdvisorReport

type RoadmapModule

type RoadmapModule struct {
	Name        string
	Description string
	Contract    APIContract
}

RoadmapModule describes a stable core capability or a planned future module.

func ExperimentalRoadmap

func ExperimentalRoadmap() []RoadmapModule

ExperimentalRoadmap returns the planned future modules only.

func Roadmap

func Roadmap() []RoadmapModule

Roadmap returns the stable core and the likely future modules for the framework.

func StableCore

func StableCore() []RoadmapModule

StableCore returns the stable core roadmap items only.

Directories

Path Synopsis
Package access applies context-scoped policies and row-level access controls.
Package access applies context-scoped policies and row-level access controls.
benchmark
cmd
orm command
Package dialect defines SQL rendering contracts for database-specific implementations.
Package dialect defines SQL rendering contracts for database-specific implementations.
Package driver defines database driver integration for opening connections and exposing dialects.
Package driver defines database driver integration for opening connections and exposing dialects.
Package errkind defines typed error categories used throughout the framework.
Package errkind defines typed error categories used throughout the framework.
examples
basic command
multi-tenant command
todo command
internal
Package migrate generates, writes, and applies database migrations.
Package migrate generates, writes, and applies database migrations.
Package orm provides the runtime ORM for querying and mutating application models.
Package orm provides the runtime ORM for querying and mutating application models.
Package schema parses, inspects, and compares database schema definitions.
Package schema parses, inspects, and compares database schema definitions.

Jump to

Keyboard shortcuts

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