storm

package
v0.0.50 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Version      = "1.0.0-alpha"
	APIVersion   = "v1"
	MinGoVersion = "1.24"
)

Version information

Variables

View Source
var (
	ErrClosed            = errors.New("storm: connection closed")
	ErrNoConnection      = errors.New("storm: no database connection")
	ErrInvalidConfig     = errors.New("storm: invalid configuration")
	ErrMigrationFailed   = errors.New("storm: migration failed")
	ErrSchemaInvalid     = errors.New("storm: invalid schema")
	ErrNotImplemented    = errors.New("storm: not implemented")
	ErrMigrationExists   = errors.New("storm: migration already exists")
	ErrMigrationNotFound = errors.New("storm: migration not found")
	ErrDestructiveChange = errors.New("storm: destructive change detected")
)

Common errors

View Source
var (
	MigratorFactory        func(db *sqlx.DB, config *Config, logger Logger) Migrator
	ORMFactory             func(config *Config, logger Logger) ORMGenerator
	SchemaInspectorFactory func(db *sqlx.DB, config *Config, logger Logger) SchemaInspector
)

Factory functions for implementations

View Source
var BuildInfo = struct {
	Version    string
	APIVersion string
	GitCommit  string
	BuildDate  string
	GoVersion  string
}{
	Version:    Version,
	APIVersion: APIVersion,
	GoVersion:  runtime.Version(),
}

BuildInfo contains build information

Functions

func FullVersionInfo

func FullVersionInfo() string

FullVersionInfo returns detailed version information

func IsVersionCompatible

func IsVersionCompatible(required string) bool

IsVersionCompatible checks if the current version is compatible with the minimum required version

func SetBuildInfo

func SetBuildInfo(commit, date, goVersion string)

SetBuildInfo is called by the build process

func VersionInfo

func VersionInfo() string

VersionInfo returns formatted version information

Types

type AutoMigrateOptions added in v0.0.49

type AutoMigrateOptions struct {
	AllowDestructive    bool
	DryRun              bool
	CreateDBIfNotExists bool
	LockTimeout         time.Duration
}

AutoMigrateOptions configures automatic schema migration

type Column

type Column struct {
	Name         string
	Type         string
	Nullable     bool
	Default      string
	Length       int
	Precision    int
	Scale        int
	IsPrimaryKey bool
	IsForeignKey bool
}

Column represents a table column

type ColumnDiff

type ColumnDiff struct {
	TypeChanged     bool
	OldType         string
	NewType         string
	NullableChanged bool
	OldNullable     bool
	NewNullable     bool
	DefaultChanged  bool
	OldDefault      string
	NewDefault      string
}

ColumnDiff represents differences between column schemas

func (*ColumnDiff) IsEmpty

func (cd *ColumnDiff) IsEmpty() bool

IsEmpty returns true if the column diff has no changes

type Config

type Config struct {
	// Database settings
	Driver          string        `yaml:"driver" env:"STORM_DRIVER"`
	DatabaseURL     string        `yaml:"database_url" env:"STORM_DATABASE_URL"`
	MaxOpenConns    int           `yaml:"max_open_conns" env:"STORM_MAX_OPEN_CONNS"`
	MaxIdleConns    int           `yaml:"max_idle_conns" env:"STORM_MAX_IDLE_CONNS"`
	ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" env:"STORM_CONN_MAX_LIFETIME"`

	// Models settings
	ModelsPackage string `yaml:"models_package" env:"STORM_MODELS_PACKAGE"`

	// Migration settings
	MigrationsDir   string             `yaml:"migrations_dir" env:"STORM_MIGRATIONS_DIR"`
	MigrationsTable string             `yaml:"migrations_table" env:"STORM_MIGRATIONS_TABLE"`
	AutoMigrate     bool               `yaml:"auto_migrate" env:"STORM_AUTO_MIGRATE"`
	AutoMigrateOpts AutoMigrateOptions `yaml:"-"`

	// ORM settings
	GenerateHooks bool `yaml:"generate_hooks" env:"STORM_GENERATE_HOOKS"`
	GenerateTests bool `yaml:"generate_tests" env:"STORM_GENERATE_TESTS"`
	GenerateMocks bool `yaml:"generate_mocks" env:"STORM_GENERATE_MOCKS"`

	// Schema settings
	StrictMode       bool   `yaml:"strict_mode" env:"STORM_STRICT_MODE"`
	NamingConvention string `yaml:"naming_convention" env:"STORM_NAMING_CONVENTION"`

	// Runtime settings
	Logger Logger `yaml:"-"`
	Debug  bool   `yaml:"debug" env:"STORM_DEBUG"`
}

Config holds all Storm configuration

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig loads configuration from file and environment

func NewConfig

func NewConfig() *Config

NewConfig creates a config with sensible defaults

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a deep copy of the configuration

func (*Config) LoadEnv

func (c *Config) LoadEnv()

LoadEnv loads configuration from environment variables

func (*Config) LoadFile

func (c *Config) LoadFile(path string) error

LoadFile loads configuration from a YAML file

func (*Config) SaveFile

func (c *Config) SaveFile(path string) error

SaveFile saves the configuration to a YAML file

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid

type Constraint

type Constraint struct {
	Name       string
	Table      string
	Type       string
	Definition string
}

Constraint represents a database constraint

type Enum

type Enum struct {
	Name   string
	Values []string
}

Enum represents a database enum type

type Error

type Error struct {
	Type    ErrorType
	Op      string
	Err     error
	Details map[string]interface{}
}

Error represents a Storm error with context

func NewConfigError

func NewConfigError(op string, err error) *Error

NewConfigError creates a configuration error

func NewConnectionError

func NewConnectionError(op string, err error) *Error

NewConnectionError creates a connection error

func NewError

func NewError(errType ErrorType, op string, err error) *Error

NewError creates a new Storm error

func NewGenerationError

func NewGenerationError(op string, err error) *Error

NewGenerationError creates a generation error

func NewMigrationError

func NewMigrationError(op string, err error) *Error

NewMigrationError creates a migration error

func NewORMError

func NewORMError(op string, err error) *Error

NewORMError creates an ORM error

func NewSchemaError

func NewSchemaError(op string, err error) *Error

NewSchemaError creates a schema error

func NewValidationError

func NewValidationError(op string, err error) *Error

NewValidationError creates a validation error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) Is

func (e *Error) Is(target error) bool

Is implements errors.Is

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap implements errors.Unwrap

func (*Error) WithDetails

func (e *Error) WithDetails(key string, value interface{}) *Error

WithDetails adds details to the error

type ErrorType

type ErrorType string

ErrorType represents the type of error

const (
	ErrorTypeConnection ErrorType = "connection"
	ErrorTypeConfig     ErrorType = "config"
	ErrorTypeMigration  ErrorType = "migration"
	ErrorTypeSchema     ErrorType = "schema"
	ErrorTypeORM        ErrorType = "orm"
	ErrorTypeGeneration ErrorType = "generation"
	ErrorTypeValidation ErrorType = "validation"
	ErrorTypeUnknown    ErrorType = "unknown"
)

type ForeignKey

type ForeignKey struct {
	Name           string
	Columns        []string
	ForeignTable   string
	ForeignColumns []string
}

ForeignKey represents a foreign key constraint

type Function

type Function struct {
	Name       string
	Schema     string
	Definition string
}

Function represents a database function

type GenerateOptions

type GenerateOptions struct {
	PackagePath  string
	OutputDir    string
	IncludeHooks bool
	IncludeTests bool
	IncludeMocks bool
}

GenerateOptions configures ORM code generation

type Index

type Index struct {
	Name    string
	Table   string
	Columns []string
	Unique  bool
}

Index represents a database index

type Logger

type Logger interface {
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
}

Logger defines logging interface

func NewDefaultLogger

func NewDefaultLogger() Logger

DefaultLogger creates a simple default logger

type MigrateOptions

type MigrateOptions struct {
	Name                string
	PackagePath         string
	OutputDir           string
	DryRun              bool
	AllowDestructive    bool
	SkipPrompt          bool
	CreateDBIfNotExists bool
}

MigrateOptions configures migration generation

type Migration

type Migration struct {
	ID          string
	Name        string
	Version     string
	Description string
	UpSQL       string
	DownSQL     string
	Checksum    string
	CreatedAt   time.Time
}

Migration represents a database migration

type MigrationRecord

type MigrationRecord struct {
	ID        string
	Version   string
	AppliedAt time.Time
	AppliedBy string
	Duration  time.Duration
	Success   bool
	Error     string
}

MigrationRecord represents an applied migration

type MigrationStatus

type MigrationStatus struct {
	Current   string
	Available int
	Pending   int
	Applied   int
}

MigrationStatus represents current migration state

type Migrator

type Migrator interface {
	// Generate creates a new migration by comparing models with database
	Generate(ctx context.Context, opts MigrateOptions) (*Migration, error)

	// Apply executes a migration
	Apply(ctx context.Context, migration *Migration) error

	// Rollback reverses a migration
	Rollback(ctx context.Context, migration *Migration) error

	// Status returns the current migration status
	Status(ctx context.Context) (*MigrationStatus, error)

	// History returns all applied migrations
	History(ctx context.Context) ([]*MigrationRecord, error)

	// Pending returns all pending migrations
	Pending(ctx context.Context) ([]*Migration, error)

	// AutoMigrate reads Go structs and applies schema changes directly to the database
	AutoMigrate(ctx context.Context, opts AutoMigrateOptions) error
}

Migrator handles database migrations

type ORM

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

func (*ORM) Generate

func (o *ORM) Generate(ctx context.Context, opts GenerateOptions) error

type ORMGenerator

type ORMGenerator interface {
	Generate(ctx context.Context, opts GenerateOptions) error
}

type Option

type Option func(*Config) error

Option configures Storm

func WithAutoMigrate

func WithAutoMigrate(enabled bool) Option

WithAutoMigrate enables automatic migrations

func WithAutoMigrateOptions added in v0.0.49

func WithAutoMigrateOptions(opts AutoMigrateOptions) Option

WithAutoMigrateOptions configures automatic migration behavior

func WithConfig

func WithConfig(other *Config) Option

WithConfig merges another config

func WithConfigFile

func WithConfigFile(path string) Option

WithConfigFile loads configuration from file

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) Option

WithConnMaxLifetime sets connection lifetime

func WithDebug

func WithDebug(enabled bool) Option

WithDebug enables debug mode

func WithDriver

func WithDriver(driver string) Option

WithDriver sets the database driver

func WithGenerateHooks

func WithGenerateHooks(enabled bool) Option

WithGenerateHooks enables hook generation

func WithGenerateMocks

func WithGenerateMocks(enabled bool) Option

WithGenerateMocks enables mock generation

func WithGenerateTests

func WithGenerateTests(enabled bool) Option

WithGenerateTests enables test generation

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets a custom logger

func WithMaxConnections

func WithMaxConnections(max int) Option

WithMaxConnections sets connection pool size

func WithMaxIdleConnections

func WithMaxIdleConnections(max int) Option

WithMaxIdleConnections sets max idle connections

func WithMigrationsDir

func WithMigrationsDir(dir string) Option

WithMigrationsDir sets the migrations directory

func WithMigrationsTable

func WithMigrationsTable(table string) Option

WithMigrationsTable sets the migrations table name

func WithModelsPackage

func WithModelsPackage(path string) Option

WithModelsPackage sets the models package path

func WithNamingConvention

func WithNamingConvention(convention string) Option

WithNamingConvention sets the naming convention

func WithStrictMode

func WithStrictMode(enabled bool) Option

WithStrictMode enables strict mode

type PrimaryKey

type PrimaryKey struct {
	Name    string
	Columns []string
}

PrimaryKey represents a primary key constraint

type Schema

type Schema struct {
	Tables      map[string]*Table
	Views       []*View
	Functions   []*Function
	Indexes     []*Index
	Constraints []*Constraint
	Enums       []*Enum
}

Schema represents a database schema

type SchemaDiff

type SchemaDiff struct {
	AddedTables    map[string]*Table
	DroppedTables  map[string]*Table
	ModifiedTables map[string]*TableDiff
}

SchemaDiff represents differences between schemas

type SchemaInspector

type SchemaInspector interface {
	// Inspect returns the current database schema
	Inspect(ctx context.Context) (*Schema, error)

	// Compare compares two schemas
	Compare(ctx context.Context, from, to *Schema) (*SchemaDiff, error)

	// ExportSQL exports schema as SQL
	ExportSQL(ctx context.Context) (string, error)

	// ExportGo exports schema as Go structs
	ExportGo(ctx context.Context) (string, error)
}

SchemaInspector analyzes database schema

type Storm

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

Storm is the main entry point for all database operations

func New

func New(databaseURL string, opts ...Option) (*Storm, error)

New creates a new Storm instance with the given database URL

func NewWithConfig

func NewWithConfig(config *Config) (*Storm, error)

NewWithConfig creates a new Storm instance with explicit configuration

func (*Storm) AutoMigrate added in v0.0.49

func (s *Storm) AutoMigrate(ctx context.Context, opts ...AutoMigrateOptions) error

AutoMigrate reads Go structs and applies schema changes directly to the database

func (*Storm) Close

func (s *Storm) Close() error

Close closes all connections and cleans up resources

func (*Storm) Config

func (s *Storm) Config() *Config

Config returns the current configuration

func (*Storm) DB

func (s *Storm) DB() *sqlx.DB

DB returns the underlying database connection

func (*Storm) Generate

func (s *Storm) Generate(ctx context.Context, opts ...GenerateOptions) error

Generate creates ORM code from models

func (*Storm) Introspect

func (s *Storm) Introspect(ctx context.Context) (*Schema, error)

Introspect analyzes the database schema

func (*Storm) Logger

func (s *Storm) Logger() Logger

Logger returns the current logger

func (*Storm) Migrate

func (s *Storm) Migrate(ctx context.Context, opts ...MigrateOptions) error

Migrate generates and optionally applies migrations

func (*Storm) Migrator

func (s *Storm) Migrator() Migrator

Migrator returns the migration interface

func (*Storm) ORM

func (s *Storm) ORM() *ORM

ORM returns the ORM interface

func (*Storm) Ping

func (s *Storm) Ping(ctx context.Context) error

Ping verifies the database connection

func (*Storm) Schema

func (s *Storm) Schema() SchemaInspector

Schema returns the schema inspector

func (*Storm) Status

func (s *Storm) Status(ctx context.Context) (*MigrationStatus, error)

Status returns the current migration status

type Table

type Table struct {
	Name        string
	Schema      string
	Columns     map[string]*Column
	PrimaryKey  *PrimaryKey
	ForeignKeys []*ForeignKey
	Indexes     []*Index
	Constraints []*Constraint
}

Table represents a database table

type TableDiff

type TableDiff struct {
	AddedColumns    map[string]*Column
	DroppedColumns  map[string]*Column
	ModifiedColumns map[string]*ColumnDiff
}

TableDiff represents differences between table schemas

func (*TableDiff) IsEmpty

func (td *TableDiff) IsEmpty() bool

IsEmpty returns true if the table diff has no changes

type View

type View struct {
	Name       string
	Schema     string
	Definition string
}

View represents a database view

Jump to

Keyboard shortcuts

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