dbparity

package
v0.1.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EnvTestPostgresDSN      = "LIP_TEST_POSTGRES_DSN"
	EnvTestPostgresAdminDSN = "LIP_TEST_POSTGRES_ADMIN_DSN"
	EnvManagedPostgresDSN   = "LIP_MANAGED_POSTGRES_DSN"
	EnvRequirePostgres      = "LIP_REQUIRE_POSTGRES"
)

Environment variable names for PostgreSQL DSNs and mandatory parity enforcement.

Variables

This section is empty.

Functions

func AssertMigrationFilesApplied

func AssertMigrationFilesApplied(discovered []MigrationFile, recorded map[string]bool) error

AssertMigrationFilesApplied verifies that every discovered migration file is recorded in the applied migration history map.

func AssertMigrationHistory

func AssertMigrationHistory(discovered []string, applied []string) error

AssertMigrationHistory verifies that every discovered migration ID is present in the applied migration history slice.

func AssertMigrationHistoryIDs

func AssertMigrationHistoryIDs(discovered []string, recorded map[string]bool) error

AssertMigrationHistoryIDs verifies that every discovered migration ID is recorded in the applied migration history map. It returns an error naming all missing migration IDs in sorted order if any are missing.

func DiscoverMigrationIDs

func DiscoverMigrationIDs(root string) ([]string, error)

DiscoverMigrationIDs discovers and returns the sorted unique list of migration IDs in the specified root directory.

func EffectivePostgresDSN

func EffectivePostgresDSN(env []string) string

EffectivePostgresDSN returns the effective PostgreSQL DSN from env using precedence: 1. LIP_TEST_POSTGRES_DSN (direct test DSN) 2. LIP_MANAGED_POSTGRES_DSN (legacy managed DSN) 3. LIP_TEST_POSTGRES_ADMIN_DSN (admin DSN fallback) Returns empty string if none is configured.

func FormatList

func FormatList(cat Catalog) string

FormatList formats the catalog components and test packages as human-readable text.

func FormatListJSON

func FormatListJSON(cat Catalog) (string, error)

FormatListJSON formats the catalog components and test packages as formatted JSON.

func IsMissingRow

func IsMissingRow(err error) bool

IsMissingRow reports whether err is or wraps sql.ErrNoRows.

func MapExitStatus

func MapExitStatus(err error) int

MapExitStatus determines the process exit status code for a given error. - Returns 0 if err is nil. - Returns 130 if err is or wraps context.Canceled (standard SIGINT exit code 128+2). - Returns the process exit code if err is or wraps an ExitCoder (e.g. *exec.ExitError). - Returns 1 for any other non-nil error.

func MigrationIDs

func MigrationIDs(files []MigrationFile) []string

MigrationIDs extracts the slice of migration IDs from a slice of MigrationFiles.

func ParseFlagWords

func ParseFlagWords(s string) ([]string, error)

ParseFlagWords parses a flag string (such as GO_TEST_FLAGS or a CLI -flags argument) into individual argument words using a deliberately minimal, predictable word format.

Format rules:

  • Whitespace (spaces, tabs, newlines) outside quotes separates words.
  • Single ('...') and double ("...") quotes group characters into words and are stripped.
  • Adjacent quoted and unquoted segments concatenate into a single word (e.g., -run="^$" -> -run=^$, -literal=a'b' -> -literal=ab, prefix"mid"suffix -> prefixmidsuffix).
  • Backslashes ('\') are ALWAYS literal characters (inside and outside quotes), preserving UNC paths (\\server\share), drive roots (C:\), trailing separators (C:\path\), and regular expression escapes (\d+, \s+) without escaping or stripping.
  • Quote characters cannot be escaped inside their own quote type; users switch quote types to embed the other quote delimiter (e.g., 'he said "hello"' or "it's fine").
  • Unmatched (unclosed) single or double quotes are rejected with an error.

func PreflightPostgresDirect

func PreflightPostgresDirect(baseEnv []string) error

PreflightPostgresDirect checks whether a direct PostgreSQL DSN is configured in baseEnv. If baseEnv is nil, os.Environ() is used. Returns an actionable error naming the accepted environment variables if no direct DSN exists.

func PtrBool

func PtrBool(b bool) *bool

PtrBool is a convenience helper returning a pointer to a bool value.

func RedactDSN

func RedactDSN(s string) string

RedactDSN scrubs sensitive credentials (passwords in URLs and key-value strings) from output.

func ReorderCLIArgs

func ReorderCLIArgs(args []string) ([]string, error)

ReorderCLIArgs reorders CLI arguments so that all flag options (including trailing flags specified after a positional mode argument) precede any positional arguments.

It validates that all flags are recognized documented flags, verifies that value flags are supplied with an argument, supports both -flag and --flag variants as well as equals forms (-flag=value and --flag=value), and respects the double-dash (--) delimiter.

If an unknown flag or missing flag value is encountered, an actionable error is returned.

func Run

func Run(ctx context.Context, mode RunnerMode, opts PlanOptions, stdout, stderr io.Writer) error

Run executes the dbparity runner for the specified mode, routing output to stdout and stderr.

func VerifyPostgresSchema

func VerifyPostgresSchema(ctx context.Context, database *bun.DB, spec LogicalSchemaSpec) error

VerifyPostgresSchema verifies the logical schema spec against a PostgreSQL database using information_schema, pg_indexes, pg_constraint, and pg_trigger metadata introspection.

func VerifySQLiteSchema

func VerifySQLiteSchema(ctx context.Context, database *bun.DB, spec LogicalSchemaSpec) error

VerifySQLiteSchema verifies the logical schema spec against a SQLite database using sqlite_master and PRAGMA table_info / index_list metadata introspection.

func VerifySchema

func VerifySchema(ctx context.Context, database *bun.DB, spec LogicalSchemaSpec) error

VerifySchema verifies that the database matches the declared logical schema spec, dispatching to engine-native metadata probes based on the database dialect.

Types

type BackendClass

type BackendClass string

BackendClass classifies a persistence capability's backend and topology posture.

const (
	Common              BackendClass = "common"
	SQLiteSpecific      BackendClass = "sqlite"
	PostgresDirect      BackendClass = "postgres-direct"
	PostgresDistributed BackendClass = "postgres-distributed"
	PostgresPooler      BackendClass = "postgres-pooler"
)

func ValidBackendClasses

func ValidBackendClasses() []BackendClass

ValidBackendClasses returns the recognized backend classes.

func (BackendClass) IsValid

func (b BackendClass) IsValid() bool

IsValid reports whether the backend class is recognized.

type Capability

type Capability struct {
	ID        string       `json:"id"`
	Class     BackendClass `json:"class"`
	Evidence  string       `json:"evidence"`
	Rationale string       `json:"rationale,omitempty"` // Required for non-common capabilities
}

Capability describes an individual persistence capability and its evidence posture.

type Catalog

type Catalog struct {
	Components  []Component `json:"components"`
	SharedInfra []string    `json:"shared_infra"`
}

Catalog captures all dual-dialect persistence components and shared infrastructure.

func DefaultCatalog

func DefaultCatalog() Catalog

DefaultCatalog returns the frozen canonical catalog of all 9 production persistence families and shared database infrastructure, audited against current repository state.

func (Catalog) AllMigrationRoots

func (c Catalog) AllMigrationRoots() []string

AllMigrationRoots returns the unique, deterministically sorted list of all migration roots.

func (Catalog) AllSourceRoots

func (c Catalog) AllSourceRoots() []string

AllSourceRoots returns the unique, deterministically sorted list of all source roots.

func (Catalog) AllTestPackages

func (c Catalog) AllTestPackages() []string

AllTestPackages returns the unique, deterministically sorted list of all test packages.

func (Catalog) CommonCapabilities

func (c Catalog) CommonCapabilities(componentID string) []Capability

CommonCapabilities returns the list of Common capabilities for the given component ID.

func (Catalog) ComponentByID

func (c Catalog) ComponentByID(id string) (Component, bool)

ComponentByID returns the component with the given ID, or false if not found.

func (Catalog) ComponentIDs

func (c Catalog) ComponentIDs() []string

ComponentIDs returns the ordered list of component IDs in the catalog.

func (Catalog) NonCommonCapabilities

func (c Catalog) NonCommonCapabilities(componentID string) []Capability

NonCommonCapabilities returns the list of non-Common capabilities for the given component ID.

func (Catalog) Validate

func (c Catalog) Validate() error

Validate verifies that the catalog satisfies all structural invariants: - no empty component list - no duplicate or blank component IDs - deterministic alphabetical sorting of components by ID - non-empty source roots, test packages, migration roots, store contracts, capabilities - no duplicate or blank paths/contracts within components - no duplicate source root or migration root ownership across components - shared infrastructure roots are disjoint from component source/migration roots - non-common capabilities have non-empty rationale and non-empty evidence - common capabilities have non-empty evidence - all capability classes are valid - at least one Common capability per component

func (Catalog) ValidatePaths

func (c Catalog) ValidatePaths(repoRoot string) error

ValidatePaths verifies that all referenced paths (source roots, test packages, migration roots, shared infra, and capability evidence anchors) exist on the filesystem.

type CheckConstraintSpec

type CheckConstraintSpec struct {
	Name       string `json:"name,omitempty"`
	Expression string `json:"expression"` // Substring/fragment expected in check definition
}

CheckConstraintSpec describes expected check constraints.

type ColumnSpec

type ColumnSpec struct {
	Name            string       `json:"name"`
	Type            SemanticType `json:"type,omitempty"`             // Optional semantic type category
	Nullable        *bool        `json:"nullable,omitempty"`         // Optional nullability expectation
	PrimaryKey      bool         `json:"primary_key,omitempty"`      // Part of primary key
	Default         string       `json:"default,omitempty"`          // Expected default fragment ("" means no assertion)
	DefaultValue    string       `json:"default_value,omitempty"`    // Deprecated alias / backwards compatibility for Default
	DefaultPostgres string       `json:"default_postgres,omitempty"` // Optional engine-specific default override for PostgreSQL
}

ColumnSpec describes expected column-level invariants.

type CommandPlan

type CommandPlan struct {
	ComponentID string   `json:"component_id"`
	Package     string   `json:"package"`
	Backend     string   `json:"backend"`
	Args        []string `json:"args"`
	Env         []string `json:"env,omitempty"`
}

CommandPlan describes a single executable test command planned by the runner.

func Plan

func Plan(mode RunnerMode, opts PlanOptions) ([]CommandPlan, error)

Plan constructs the sequence of CommandPlans for the requested runner mode.

func (CommandPlan) Cmd

func (p CommandPlan) Cmd(ctx context.Context, baseEnv []string) *exec.Cmd

Cmd creates an *exec.Cmd configured for this plan with normalized child environment variables.

type Component

type Component struct {
	ID             string       `json:"id"`
	SourceRoots    []string     `json:"source_roots"`
	TestPackages   []string     `json:"test_packages"`
	StoreContracts []string     `json:"store_contracts"`
	MigrationRoots []string     `json:"migration_roots"`
	Capabilities   []Capability `json:"capabilities"`
}

Component records the authoritative source, test, migration, and contract metadata for a production persistence component supporting SQLite and PostgreSQL.

type ComponentListEntry

type ComponentListEntry struct {
	ID           string   `json:"id"`
	TestPackages []string `json:"test_packages"`
}

ComponentListEntry is a serializable representation of a component's test scope.

type ExitCoder

type ExitCoder interface {
	ExitCode() int
}

ExitCoder is implemented by error types that provide a process exit status code (e.g. *exec.ExitError).

type ForeignKeySpec

type ForeignKeySpec struct {
	Name       string   `json:"name,omitempty"`
	Columns    []string `json:"columns"`
	RefTable   string   `json:"ref_table"`
	RefColumns []string `json:"ref_columns,omitempty"`
}

ForeignKeySpec describes expected foreign key constraints.

type ImmutabilityProtection

type ImmutabilityProtection struct {
	Name         string `json:"name"`                     // Descriptive name
	Table        string `json:"table"`                    // Target table
	TriggerName  string `json:"trigger_name,omitempty"`   // Required trigger name in DB (if DB-enforced)
	AppLevelOnly bool   `json:"app_level_only,omitempty"` // If true, documented as app-level enforced (absent-by-design in DB)
	Description  string `json:"description,omitempty"`
}

ImmutabilityProtection describes expected immutability protections (triggers or documented app-level enforcement).

type IndexSpec

type IndexSpec struct {
	Name      string   `json:"name,omitempty"`      // Optional if unique signature is matched
	Table     string   `json:"table"`               // Table on which index resides
	Columns   []string `json:"columns,omitempty"`   // Column list (ordered)
	Unique    bool     `json:"unique,omitempty"`    // Whether the index is unique
	Predicate string   `json:"predicate,omitempty"` // WHERE clause fragment for partial indexes
}

IndexSpec describes expected index invariants.

type Inventory

type Inventory = Catalog

Inventory is a type alias for Catalog to preserve backward compatibility.

func DefaultInventory

func DefaultInventory() Inventory

DefaultInventory returns the inventory for backward compatibility.

type LogicalSchemaSpec

type LogicalSchemaSpec struct {
	ComponentID string                   `json:"component_id,omitempty"`
	Tables      []TableSpec              `json:"tables,omitempty"`
	Indexes     []IndexSpec              `json:"indexes,omitempty"`
	Protections []ImmutabilityProtection `json:"protections,omitempty"`
	Retired     RetiredArtifacts         `json:"retired,omitempty"`
}

LogicalSchemaSpec represents declared logical schema invariants for a component.

type MigrationFile

type MigrationFile struct {
	ID       string `json:"id"`       // 14-digit timestamp string (e.g. "20260812000000")
	Name     string `json:"name"`     // Descriptive name after timestamp prefix (e.g. "billing_baseline")
	Filename string `json:"filename"` // Base filename (e.g. "20260812000000_billing_baseline.go")
	Path     string `json:"path"`     // Full or relative path to the migration file
}

MigrationFile represents a discovered versioned database migration file.

func DiscoverComponentMigrations

func DiscoverComponentMigrations(repoRoot string, comp Component) ([]MigrationFile, error)

DiscoverComponentMigrations discovers all versioned migration files across all migration roots of a component. Discovered migrations are returned sorted chronologically by timestamp ID. If two migration files across roots share the same 14-digit timestamp ID, an error is returned naming the component, the duplicate ID, and both file paths.

func DiscoverMigrations

func DiscoverMigrations(root string) ([]MigrationFile, error)

DiscoverMigrations discovers versioned migration files in the specified directory root. It extracts 14-digit timestamp IDs from filenames matching ^\d{14}_.+\.go$, excluding _test.go files. Discovered migrations are returned sorted chronologically by timestamp ID. If two eligible migration files share the same 14-digit timestamp ID, an error is returned naming the duplicate ID and both filenames.

type PlanOptions

type PlanOptions struct {
	Catalog     Catalog                   // Parity catalog to use (defaults to DefaultCatalog() if empty)
	GoTestFlags []string                  // Additional flags for `go test` (e.g. -timeout=10m, -parallel=8)
	ComponentID string                    // Optional filter by component ID
	BaseEnv     []string                  // Base environment for DSN/env inspection (defaults to os.Environ() if nil)
	GoBinary    string                    // Optional go binary path (defaults to "go")
	CmdRunner   func(cmd *exec.Cmd) error // Optional test hook to override cmd.Run() execution (defaults to cmd.Run if nil)
}

PlanOptions contains options for planning and executing the dbparity runner.

type RetiredArtifacts

type RetiredArtifacts struct {
	Tables   []string        `json:"tables,omitempty"`
	Columns  []RetiredColumn `json:"columns,omitempty"`
	Indexes  []string        `json:"indexes,omitempty"`
	Triggers []string        `json:"triggers,omitempty"`
}

RetiredArtifacts records tables, columns, indexes, and triggers that must NOT exist.

type RetiredColumn

type RetiredColumn struct {
	Table  string `json:"table"`
	Column string `json:"column"` // Exact name or prefix pattern (e.g. "reserved%nano" or glob)
}

RetiredColumn represents a column on a table that must not exist.

type RunStepError

type RunStepError struct {
	Component string `json:"component"`
	Package   string `json:"package"`
	Backend   string `json:"backend"`
	Err       error  `json:"-"`
}

RunStepError represents a failure encountered when executing a test step in the runner. It wraps the underlying cause (such as *exec.ExitError or context.Canceled) to allow callers to inspect the exit code or error type while preserving contextual information (component, package, backend).

func (*RunStepError) Error

func (e *RunStepError) Error() string

Error formats a human-readable and redacted error description.

func (*RunStepError) ExitCode

func (e *RunStepError) ExitCode() int

ExitCode returns the exit code of the underlying error.

func (*RunStepError) Unwrap

func (e *RunStepError) Unwrap() error

Unwrap returns the underlying error cause (e.g. *exec.ExitError, context.Canceled).

type RunnerMode

type RunnerMode string

RunnerMode defines the execution mode of the dbparity runner.

const (
	// ModeList outputs the catalog-derived component and package inventory without executing tests.
	ModeList RunnerMode = "list"
	// ModeSQLite executes the canonical SQLite parity wrappers.
	ModeSQLite RunnerMode = "sqlite"
	// ModePostgresDirect executes the canonical PostgreSQL-direct parity wrappers in fail-closed mode.
	ModePostgresDirect RunnerMode = "postgres-direct"
	// ModeAll executes SQLite parity wrappers followed by PostgreSQL-direct parity wrappers.
	ModeAll RunnerMode = "all"
)

func ParseRunnerMode

func ParseRunnerMode(s string) (RunnerMode, error)

ParseRunnerMode parses a string into a RunnerMode or returns an actionable error.

func ValidRunnerModes

func ValidRunnerModes() []RunnerMode

ValidRunnerModes returns all recognized runner modes.

func (RunnerMode) IsValid

func (m RunnerMode) IsValid() bool

IsValid reports whether the runner mode is recognized.

type SemanticType

type SemanticType string

SemanticType represents an engine-agnostic data type category.

const (
	TypeText      SemanticType = "text"
	TypeInteger   SemanticType = "integer"
	TypeBoolean   SemanticType = "boolean"
	TypeTimestamp SemanticType = "timestamp"
	TypeBlob      SemanticType = "blob"
	TypeJSON      SemanticType = "json"
	TypeNumeric   SemanticType = "numeric"
)

type TableSpec

type TableSpec struct {
	Name              string                 `json:"name"`
	Columns           []ColumnSpec           `json:"columns,omitempty"`
	PrimaryKey        []string               `json:"primary_key,omitempty"` // Compound/single PK column order
	ForeignKeys       []ForeignKeySpec       `json:"foreign_keys,omitempty"`
	UniqueConstraints []UniqueConstraintSpec `json:"unique_constraints,omitempty"`
	CheckConstraints  []CheckConstraintSpec  `json:"check_constraints,omitempty"`
}

TableSpec describes expected table-level logical schema invariants.

type UniqueConstraintSpec

type UniqueConstraintSpec struct {
	Name    string   `json:"name,omitempty"`
	Columns []string `json:"columns"`
}

UniqueConstraintSpec describes expected unique constraints.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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