activerecord

package
v0.0.0-...-4221ded Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("record not found")
)

Common errors.

View Source
var ErrNotModeler = errors.New("receiver does not implement Modeler")

Functions

func AddGlobalHook

func AddGlobalHook(modelType string, hookType HookType, callback func(interface{}) error)

AddGlobalHook adds a hook for a specific model type

func AddGlobalHookWithPriority

func AddGlobalHookWithPriority(modelType string, hookType HookType, priority int, callback func(interface{}) error)

AddGlobalHookWithPriority adds a hook with priority for a specific model type

func Begin

func Begin() (*sql.Tx, error)

Begin starts a transaction.

func BeginTransactionOnDatabase

func BeginTransactionOnDatabase(databaseName string, dbType DatabaseType) (*sql.Tx, error)

BeginTransactionOnDatabase begins a transaction on a specific database

func BeginTransactionOnDatabaseWithContext

func BeginTransactionOnDatabaseWithContext(ctx context.Context, databaseName string, dbType DatabaseType) (*sql.Tx, error)

BeginTransactionOnDatabaseWithContext begins a transaction with context on a specific database

func BulkUpdate

func BulkUpdate(modelType interface{}, conditions map[string]interface{}, updates map[string]interface{}) (int64, error)

BulkUpdate performs bulk update operation

func BulkUpdateWithContext

func BulkUpdateWithContext(ctx context.Context, modelType interface{}, conditions map[string]interface{}, updates map[string]interface{}) (int64, error)

BulkUpdateWithContext performs bulk update with context

func ClearGlobalHooks

func ClearGlobalHooks(modelType string, hookType HookType)

ClearGlobalHooks removes all global hooks for a model type

func Close

func Close() error

Close closes the connection to the database.

func Connect

func Connect(driver, dsn string) (*sql.DB, error)

Connect establishes a connection to the database.

func Create

func Create(model interface{}) error

Create creates a new record in the database

func CreateOnDatabase

func CreateOnDatabase(databaseName string, model interface{}) error

CreateOnDatabase creates a record on a specific database

func CreateTable

func CreateTable(tableName string, callback func(*TableBuilder)) error

CreateTable creates a table

func Delete

func Delete(model interface{}) error

Delete deletes a record from the database

func DeleteOnDatabase

func DeleteOnDatabase(databaseName string, model interface{}) error

DeleteOnDatabase deletes a record on a specific database

func DeleteWithConditions

func DeleteWithConditions(modelType interface{}, conditions map[string]interface{}) (int64, error)

DeleteWithConditions deletes records matching conditions

func DeleteWithConditionsAndContext

func DeleteWithConditionsAndContext(ctx context.Context, modelType interface{}, conditions map[string]interface{}) (int64, error)

DeleteWithConditionsAndContext deletes records matching conditions with context

func DropTable

func DropTable(tableName string) error

DropTable deletes a table

func Exec

func Exec(query string, args ...interface{}) (sql.Result, error)

Exec executes an SQL query without returning results.

func ExecOnDatabase

func ExecOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) (sql.Result, error)

ExecOnDatabase executes a query on a specific database

func Find

func Find(model interface{}, id interface{}) error

Find finds a record by ID

func FindAll

func FindAll(models interface{}) error

FindAll finds all records

func FindInBatches

func FindInBatches(modelType interface{}, batchSize int, fn func([]interface{}) error) error

FindInBatches processes records in batches

func FindInBatchesWithContext

func FindInBatchesWithContext(ctx context.Context, modelType interface{}, batchSize int, fn func([]interface{}) error) error

FindInBatchesWithContext processes records in batches with context

func FindOnDatabase

func FindOnDatabase(databaseName string, model interface{}, id interface{}) error

FindOnDatabase finds a record on a specific database

func FindOrCreate

func FindOrCreate(model interface{}, conditions map[string]interface{}) error

FindOrCreate finds a record or creates it if it doesn't exist

func FindOrCreateByMap

func FindOrCreateByMap(modelType interface{}, attributes map[string]interface{}) (interface{}, error)

FindOrCreateByMap finds or creates records based on a map of attributes

func FindOrCreateByMapWithContext

func FindOrCreateByMapWithContext(ctx context.Context, modelType interface{}, attributes map[string]interface{}) (interface{}, error)

FindOrCreateByMapWithContext finds or creates records with context

func FindOrCreateWithContext

func FindOrCreateWithContext(ctx context.Context, model interface{}, conditions map[string]interface{}) error

FindOrCreateWithContext finds a record or creates it with context

func GetConnection

func GetConnection() *sql.DB

GetConnection returns the current connection.

func GetDriverName

func GetDriverName() string

GetDriverName returns the current driver name.

func GetPerformanceStats

func GetPerformanceStats() map[string]interface{}

GetPerformanceStats returns current performance statistics

func InnerJoins

func InnerJoins(models interface{}, joins ...string) error

InnerJoins performs INNER JOIN.

func Joins

func Joins(models interface{}, joins ...string) error

Joins performs JOIN with other tables.

func LeftJoins

func LeftJoins(models interface{}, joins ...string) error

LeftJoins performs LEFT JOIN.

func Log

func Log(level LogLevel, message string, fields map[string]interface{})

Log logs a message using the global logger

func LogDebug

func LogDebug(message string, fields map[string]interface{})

LogDebug logs a debug message

func LogError

func LogError(message string, fields map[string]interface{})

LogError logs an error message

func LogFatal

func LogFatal(message string, fields map[string]interface{})

LogFatal logs a fatal message and exits

func LogInfo

func LogInfo(message string, fields map[string]interface{})

LogInfo logs an info message

func LogWarn

func LogWarn(message string, fields map[string]interface{})

LogWarn logs a warning message

func LoggedExec

func LoggedExec(query string, args ...interface{}) (sql.Result, error)

LoggedExec executes a query with logging

func LoggedExecWithContext

func LoggedExecWithContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

LoggedExecWithContext executes a query with context and logging

func LoggedQuery

func LoggedQuery(query string, args ...interface{}) (*sql.Rows, error)

LoggedQuery executes a query with logging

func LoggedQueryRow

func LoggedQueryRow(query string, args ...interface{}) *sql.Row

LoggedQueryRow executes a query row with logging

func LoggedQueryRowWithContext

func LoggedQueryRowWithContext(ctx context.Context, query string, args ...interface{}) *sql.Row

LoggedQueryRowWithContext executes a query row with context and logging

func LoggedQueryWithContext

func LoggedQueryWithContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

LoggedQueryWithContext executes a query with context and logging

func Preload

func Preload(models interface{}, associations ...string) error

Preload preloads associations.

func Query

func Query(query string, args ...interface{}) (*sql.Rows, error)

Query executes an SQL query and returns results.

func QueryOnDatabase

func QueryOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) (*sql.Rows, error)

QueryOnDatabase executes a query on a specific database

func QueryRow

func QueryRow(query string, args ...interface{}) *sql.Row

QueryRow executes an SQL query and returns a single row.

func QueryRowOnDatabase

func QueryRowOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) *sql.Row

QueryRowOnDatabase executes a query on a specific database and returns a single row

func ResetPerformanceStats

func ResetPerformanceStats()

ResetPerformanceStats resets performance statistics

func RunGlobalHooks

func RunGlobalHooks(model interface{}, hookType HookType) error

RunGlobalHooks executes global hooks for a model

func SetConnection

func SetConnection(database *sql.DB, driver string)

SetConnection sets the global connection.

func SetDatabaseManager

func SetDatabaseManager(dm *DatabaseManager)

SetDatabaseManager sets the global database manager

func SetLogger

func SetLogger(logger Logger)

SetLogger sets the global logger

func SetTransactionManager

func SetTransactionManager(tm *TransactionManager)

SetTransactionManager sets the global transaction manager

func Transactional

func Transactional(fn func(*Transaction) error) error

Transactional executes a function within a transaction

func TransactionalWithContext

func TransactionalWithContext(ctx context.Context, fn func(*Transaction) error) error

TransactionalWithContext executes a function within a transaction with context

func Update

func Update(model interface{}) error

Update updates a record in the database

func UpdateOnDatabase

func UpdateOnDatabase(databaseName string, model interface{}) error

UpdateOnDatabase updates a record on a specific database

func UpdateWithSQLExpr

func UpdateWithSQLExpr(model interface{}, expressions map[string]string, args ...interface{}) error

UpdateWithSQLExpr updates a record using SQL expressions

func UpdateWithSQLExprAndContext

func UpdateWithSQLExprAndContext(ctx context.Context, model interface{}, expressions map[string]string, args ...interface{}) error

UpdateWithSQLExprAndContext updates a record using SQL expressions with context

func Where

func Where(models interface{}, query string, args ...interface{}) error

Where fills the receiver slice with records matching the query.

func With

func With(models interface{}, associations ...string) error

With preloads associations for collection.

Types

type ActiveRecord

type ActiveRecord interface {
	Modeler
	Create() error
	Update() error
	Delete() error
	Save() error
	IsNewRecord() bool
	IsPersisted() bool
	Touch() error
	Reload() error
	Destroy() bool
}

ActiveRecord interface for instance methods of the model.

type ActiveRecordModel

type ActiveRecordModel struct {
	BaseModel
}

ActiveRecordModel base model with Active Record methods.

func (*ActiveRecordModel) BelongsTo

func (m *ActiveRecordModel) BelongsTo(name string, model interface{}, foreignKey string)

BelongsTo defines relationship "belongs to".

func (*ActiveRecordModel) Create

func (m *ActiveRecordModel) Create() error

Create creates a new record in the database.

func (*ActiveRecordModel) Delete

func (m *ActiveRecordModel) Delete() error

Delete deletes a record from the database.

func (*ActiveRecordModel) Destroy

func (m *ActiveRecordModel) Destroy() bool

Destroy deletes a record and returns true if successful.

func (*ActiveRecordModel) Find

func (m *ActiveRecordModel) Find(id interface{}) error

Find fills the receiver by id.

func (*ActiveRecordModel) GetCreatedAt

func (m *ActiveRecordModel) GetCreatedAt() time.Time

func (*ActiveRecordModel) GetID

func (m *ActiveRecordModel) GetID() interface{}

Modeler interface methods.

func (*ActiveRecordModel) GetUpdatedAt

func (m *ActiveRecordModel) GetUpdatedAt() time.Time

func (*ActiveRecordModel) HasMany

func (m *ActiveRecordModel) HasMany(name string, model interface{}, foreignKey string)

HasMany defines relationship "one to many".

func (*ActiveRecordModel) HasManyThrough

func (m *ActiveRecordModel) HasManyThrough(name string, model interface{}, through string,
	foreignKey string, localKey string)

HasManyThrough defines relationship "many to many through".

func (*ActiveRecordModel) HasOne

func (m *ActiveRecordModel) HasOne(name string, model interface{}, foreignKey string)

HasOne defines relationship "one to one".

func (*ActiveRecordModel) Include

func (m *ActiveRecordModel) Include(associationNames ...string) error

Include preloads associations.

func (*ActiveRecordModel) IsNewRecord

func (m *ActiveRecordModel) IsNewRecord() bool

IsNewRecord checks if a record is new.

func (*ActiveRecordModel) IsPersisted

func (m *ActiveRecordModel) IsPersisted() bool

IsPersisted checks if a record is saved in the database.

func (*ActiveRecordModel) Load

func (m *ActiveRecordModel) Load(associationName string) error

Load loads association.

func (*ActiveRecordModel) Reload

func (m *ActiveRecordModel) Reload() error

Reload reloads data from the database.

func (*ActiveRecordModel) Save

func (m *ActiveRecordModel) Save() error

Save saves a record (creates or updates).

func (*ActiveRecordModel) SetCreatedAt

func (m *ActiveRecordModel) SetCreatedAt(t time.Time)

func (*ActiveRecordModel) SetID

func (m *ActiveRecordModel) SetID(id interface{})

func (*ActiveRecordModel) SetUpdatedAt

func (m *ActiveRecordModel) SetUpdatedAt(t time.Time)

func (*ActiveRecordModel) Touch

func (m *ActiveRecordModel) Touch() error

Touch updates timestamps.

func (*ActiveRecordModel) Update

func (m *ActiveRecordModel) Update() error

Update updates a record in the database.

func (*ActiveRecordModel) Where

func (m *ActiveRecordModel) Where(query string, args ...interface{}) (interface{}, error)

Where returns a slice of the receiver's type matching the query.

type Association

type Association struct {
	Type       AssociationType
	Model      interface{}
	ForeignKey string
	LocalKey   string
	Through    string
}

Association definition of association.

type AssociationType

type AssociationType int

AssociationType type of association.

const (
	HasOne AssociationType = iota
	HasMany
	BelongsTo
	HasManyThrough
)

type Associations

type Associations map[string]*Association

Associations map of associations for model.

type BaseModel

type BaseModel struct {
	ID        interface{} `db:"id" json:"id"`
	CreatedAt time.Time   `db:"created_at" json:"created_at"`
	UpdatedAt time.Time   `db:"updated_at" json:"updated_at"`
}

BaseModel base model with common fields

func (*BaseModel) Find

func (m *BaseModel) Find(id interface{}) error

Find fills the receiver by id

func (*BaseModel) GetCreatedAt

func (m *BaseModel) GetCreatedAt() time.Time

GetCreatedAt returns the creation time

func (*BaseModel) GetID

func (m *BaseModel) GetID() interface{}

GetID returns the ID of the model

func (*BaseModel) GetUpdatedAt

func (m *BaseModel) GetUpdatedAt() time.Time

GetUpdatedAt returns the update time

func (*BaseModel) SetCreatedAt

func (m *BaseModel) SetCreatedAt(t time.Time)

SetCreatedAt sets the creation time

func (*BaseModel) SetID

func (m *BaseModel) SetID(id interface{})

SetID sets the ID of the model

func (*BaseModel) SetUpdatedAt

func (m *BaseModel) SetUpdatedAt(t time.Time)

SetUpdatedAt sets the update time

func (*BaseModel) TableName

func (m *BaseModel) TableName() string

TableName returns the default table name

func (*BaseModel) Where

func (m *BaseModel) Where(query string, args ...interface{}) (interface{}, error)

Where returns a slice of the receiver's type matching the query

type BatchInsertResult

type BatchInsertResult struct {
	LastInsertID int64
	RowsAffected int64
	Errors       []error
}

BatchInsertResult represents the result of a batch insert operation

func BatchInsert

func BatchInsert(models []interface{}) (*BatchInsertResult, error)

BatchInsert performs batch insert of multiple records

func BatchInsertWithContext

func BatchInsertWithContext(ctx context.Context, models []interface{}) (*BatchInsertResult, error)

BatchInsertWithContext performs batch insert with context

func BatchUpsert

func BatchUpsert(models []interface{}, conflictFields []string, updateFields []string) (*BatchInsertResult, error)

BatchUpsert performs batch upsert (insert or update) operation

func BatchUpsertWithContext

func BatchUpsertWithContext(ctx context.Context, models []interface{}, conflictFields []string, updateFields []string) (*BatchInsertResult, error)

BatchUpsertWithContext performs batch upsert with context

type DatabaseConfig

type DatabaseConfig struct {
	Driver   string
	DSN      string
	MaxOpen  int
	MaxIdle  int
	Lifetime time.Duration
}

DatabaseConfig represents database configuration

type DatabaseConnection

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

DatabaseConnection represents a database connection

func NewDatabaseConnection

func NewDatabaseConnection(config *DatabaseConfig) (*DatabaseConnection, error)

NewDatabaseConnection creates a new database connection

func (*DatabaseConnection) Close

func (dc *DatabaseConnection) Close() error

Close closes the database connection

func (*DatabaseConnection) GetDB

func (dc *DatabaseConnection) GetDB() *sql.DB

GetDB returns the underlying database connection

func (*DatabaseConnection) HealthCheck

func (dc *DatabaseConnection) HealthCheck() error

HealthCheck performs a health check on the database

type DatabaseManager

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

DatabaseManager manages multiple databases

func GetDatabaseManager

func GetDatabaseManager() *DatabaseManager

GetDatabaseManager returns the global database manager

func NewDatabaseManager

func NewDatabaseManager() *DatabaseManager

NewDatabaseManager creates a new database manager

func (*DatabaseManager) AddDatabase

func (dm *DatabaseManager) AddDatabase(name string, resolver *DatabaseResolver)

AddDatabase adds a database with a name

func (*DatabaseManager) Close

func (dm *DatabaseManager) Close() error

Close closes all database connections

func (*DatabaseManager) GetConnection

func (dm *DatabaseManager) GetConnection(databaseName string, dbType DatabaseType) (*sql.DB, error)

GetConnection returns a connection from a specific database

func (*DatabaseManager) GetDatabase

func (dm *DatabaseManager) GetDatabase(name string) (*DatabaseResolver, error)

GetDatabase returns a database resolver by name

func (*DatabaseManager) HealthCheck

func (dm *DatabaseManager) HealthCheck() map[string]map[string]error

HealthCheck performs health checks on all databases

type DatabaseResolver

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

DatabaseResolver manages multiple database connections

func NewDatabaseResolver

func NewDatabaseResolver() *DatabaseResolver

NewDatabaseResolver creates a new database resolver

func (*DatabaseResolver) AddReadReplica

func (dr *DatabaseResolver) AddReadReplica(config *DatabaseConfig) error

AddReadReplica adds a read replica

func (*DatabaseResolver) AddWriteReplica

func (dr *DatabaseResolver) AddWriteReplica(config *DatabaseConfig) error

AddWriteReplica adds a write replica

func (*DatabaseResolver) Close

func (dr *DatabaseResolver) Close() error

Close closes all database connections

func (*DatabaseResolver) GetConnection

func (dr *DatabaseResolver) GetConnection(dbType DatabaseType) (*sql.DB, error)

GetConnection returns the appropriate database connection based on operation type

func (*DatabaseResolver) GetPrimaryConnection

func (dr *DatabaseResolver) GetPrimaryConnection() (*sql.DB, error)

GetPrimaryConnection returns the primary connection

func (*DatabaseResolver) GetReadConnection

func (dr *DatabaseResolver) GetReadConnection() (*sql.DB, error)

GetReadConnection returns a read connection (read replica or primary)

func (*DatabaseResolver) GetWriteConnection

func (dr *DatabaseResolver) GetWriteConnection() (*sql.DB, error)

GetWriteConnection returns a write connection (write replica or primary)

func (*DatabaseResolver) HealthCheck

func (dr *DatabaseResolver) HealthCheck() map[string]error

HealthCheck performs health checks on all connections

func (*DatabaseResolver) SetPrimary

func (dr *DatabaseResolver) SetPrimary(config *DatabaseConfig) error

SetPrimary sets the primary database connection

type DatabaseType

type DatabaseType int

DatabaseType represents the type of database operation

const (
	Primary DatabaseType = iota
	ReadReplica
	WriteReplica
)

type DefaultLogger

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

DefaultLogger is the default logger implementation

func NewDefaultLogger

func NewDefaultLogger() *DefaultLogger

NewDefaultLogger creates a new default logger

func (*DefaultLogger) GetLevel

func (l *DefaultLogger) GetLevel() LogLevel

GetLevel returns the current logging level

func (*DefaultLogger) Log

func (l *DefaultLogger) Log(level LogLevel, message string, fields map[string]interface{})

Log logs a message with the specified level

func (*DefaultLogger) LogQuery

func (l *DefaultLogger) LogQuery(info *QueryInfo)

LogQuery logs a database query

func (*DefaultLogger) SetLevel

func (l *DefaultLogger) SetLevel(level LogLevel)

SetLevel sets the logging level

type Hook

type Hook struct {
	Type     HookType
	Priority int
	Callback func(interface{}) error
}

Hook represents a hook callback

type HookType

type HookType string

HookType represents the type of hook

const (
	BeforeCreate HookType = "before_create"
	AfterCreate  HookType = "after_create"
	BeforeSave   HookType = "before_save"
	AfterSave    HookType = "after_save"
	BeforeUpdate HookType = "before_update"
	AfterUpdate  HookType = "after_update"
	BeforeDelete HookType = "before_delete"
	AfterDelete  HookType = "after_delete"
	BeforeFind   HookType = "before_find"
	AfterFind    HookType = "after_find"
)

type Hookable

type Hookable interface {
	AddHook(hookType HookType, callback func(interface{}) error)
	AddHookWithPriority(hookType HookType, priority int, callback func(interface{}) error)
	RunHooks(hookType HookType) error
	ClearHooks(hookType HookType)
}

Hookable interface for models that support hooks

type HookableModel

type HookableModel struct {
	ActiveRecordModel
	// contains filtered or unexported fields
}

HookableModel embeds ActiveRecordModel and adds hook functionality

func NewHookableModel

func NewHookableModel() *HookableModel

NewHookableModel creates a new HookableModel

func (*HookableModel) AddHook

func (m *HookableModel) AddHook(hookType HookType, callback func(interface{}) error)

AddHook adds a hook with default priority (0)

func (*HookableModel) AddHookWithPriority

func (m *HookableModel) AddHookWithPriority(hookType HookType, priority int, callback func(interface{}) error)

AddHookWithPriority adds a hook with specified priority

func (*HookableModel) ClearAllHooks

func (m *HookableModel) ClearAllHooks()

ClearAllHooks removes all hooks

func (*HookableModel) ClearHooks

func (m *HookableModel) ClearHooks(hookType HookType)

ClearHooks removes all hooks of the specified type

func (*HookableModel) Create

func (m *HookableModel) Create() error

Override Create to include hooks

func (*HookableModel) Delete

func (m *HookableModel) Delete() error

Override Delete to include hooks

func (*HookableModel) Find

func (m *HookableModel) Find(id interface{}) error

Override Find to include hooks

func (*HookableModel) RunHooks

func (m *HookableModel) RunHooks(hookType HookType) error

RunHooks executes all hooks of the specified type

func (*HookableModel) Save

func (m *HookableModel) Save() error

Override Save to include hooks

func (*HookableModel) Update

func (m *HookableModel) Update() error

Override Update to include hooks

type LogLevel

type LogLevel int

LogLevel represents the logging level

const (
	DebugLevel LogLevel = iota
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
)

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of the log level

type Logger

type Logger interface {
	LogQuery(info *QueryInfo)
	Log(level LogLevel, message string, fields map[string]interface{})
	SetLevel(level LogLevel)
	GetLevel() LogLevel
}

Logger interface for logging

func GetLogger

func GetLogger() Logger

GetLogger returns the global logger

type Migration

type Migration struct {
	ID        int       `db:"id"`
	Version   string    `db:"version"`
	CreatedAt time.Time `db:"created_at"`
}

Migration represents a database migration.

type MigrationInterface

type MigrationInterface interface {
	Up() error
	Down() error
	Version() int64
}

Migration interface for migrations

type MigrationManager

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

MigrationManager manages database migrations.

func NewMigrationManager

func NewMigrationManager() *MigrationManager

NewMigrationManager creates a new migration manager.

func (*MigrationManager) AddMigration

func (mm *MigrationManager) AddMigration(migration Migrator)

AddMigration adds a migration to the manager.

func (*MigrationManager) Migrate

func (mm *MigrationManager) Migrate() error

Migrate runs all pending migrations.

func (*MigrationManager) Rollback

func (mm *MigrationManager) Rollback() error

Rollback rolls back the last migration.

type MigrationRecord

type MigrationRecord struct {
	Version   int64     `db:"version"`
	AppliedAt time.Time `db:"applied_at"`
}

MigrationRecord record of a completed migration

type Migrator

type Migrator interface {
	Up() error
	Down() error
	Version() string
}

Migrator interface for migrations.

type MigratorStruct

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

Migrator manages migrations

func NewMigrator

func NewMigrator() *MigratorStruct

NewMigrator creates a new migrator instance

func (*MigratorStruct) CreateMigrationsTable

func (m *MigratorStruct) CreateMigrationsTable() error

CreateMigrationsTable creates a table for tracking migrations

func (*MigratorStruct) Migrate

func (m *MigratorStruct) Migrate(migrations []MigrationInterface) error

Migrate performs all unapplied migrations

func (*MigratorStruct) Rollback

func (m *MigratorStruct) Rollback(migrations []MigrationInterface) error

Rollback rolls back the last migration

func (*MigratorStruct) Status

func (m *MigratorStruct) Status(migrations []MigrationInterface) error

Status shows the status of migrations

type Model

type Model struct{}

Model base structure for all Active Record models

type Modeler

type Modeler interface {
	TableName() string
	GetID() interface{}
	SetID(interface{})
	GetCreatedAt() time.Time
	SetCreatedAt(time.Time)
	GetUpdatedAt() time.Time
	SetUpdatedAt(time.Time)
	Find(id interface{}) error
	Where(query string, args ...interface{}) (interface{}, error)
}

Modeler interface for working with models

type PerformanceMetrics

type PerformanceMetrics struct {
	TotalQueries       int64
	TotalDuration      time.Duration
	SlowQueries        int64
	SlowQueryThreshold time.Duration
	// contains filtered or unexported fields
}

PerformanceMetrics tracks performance metrics

func GetMetrics

func GetMetrics() *PerformanceMetrics

GetMetrics returns the global performance metrics

func NewPerformanceMetrics

func NewPerformanceMetrics(slowQueryThreshold time.Duration) *PerformanceMetrics

NewPerformanceMetrics creates new performance metrics

func (*PerformanceMetrics) GetStats

func (pm *PerformanceMetrics) GetStats() map[string]interface{}

GetStats returns current statistics

func (*PerformanceMetrics) RecordQuery

func (pm *PerformanceMetrics) RecordQuery(duration time.Duration)

RecordQuery records a query for metrics

func (*PerformanceMetrics) Reset

func (pm *PerformanceMetrics) Reset()

Reset resets the metrics

type QueryBuilder

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

QueryBuilder represents a query builder

func NewQueryBuilder

func NewQueryBuilder(tableName string) *QueryBuilder

NewQueryBuilder creates a new query builder

func (*QueryBuilder) Build

func (qb *QueryBuilder) Build() (string, []interface{})

Build builds the SQL query

func (*QueryBuilder) Count

func (qb *QueryBuilder) Count() (int64, error)

Count executes a count query

func (*QueryBuilder) Distinct

func (qb *QueryBuilder) Distinct() *QueryBuilder

Distinct sets distinct flag

func (*QueryBuilder) Exclude

func (qb *QueryBuilder) Exclude(fields ...string) *QueryBuilder

Exclude adds exclude fields

func (*QueryBuilder) Execute

func (qb *QueryBuilder) Execute() (*sql.Rows, error)

Execute executes the query and returns rows

func (*QueryBuilder) Exists

func (qb *QueryBuilder) Exists() (bool, error)

Exists checks if any records exist

func (*QueryBuilder) Find

func (qb *QueryBuilder) Find(models interface{}) error

Find executes the query and scans results into the provided slice

func (*QueryBuilder) FindInBatches

func (qb *QueryBuilder) FindInBatches(batchSize int, fn func([]interface{}) error) error

FindInBatches processes records in batches

func (*QueryBuilder) First

func (qb *QueryBuilder) First(model interface{}) error

First executes the query and returns the first result

func (*QueryBuilder) GroupBy

func (qb *QueryBuilder) GroupBy(fields ...string) *QueryBuilder

GroupBy adds a group by clause

func (*QueryBuilder) Having

func (qb *QueryBuilder) Having(condition string, args ...interface{}) *QueryBuilder

Having adds a having clause

func (*QueryBuilder) Hint

func (qb *QueryBuilder) Hint(hint string) *QueryBuilder

Hint adds a hint

func (*QueryBuilder) Include

func (qb *QueryBuilder) Include(associations ...string) *QueryBuilder

Include adds include associations

func (*QueryBuilder) InnerJoin

func (qb *QueryBuilder) InnerJoin(table, condition string) *QueryBuilder

InnerJoin adds an inner join clause

func (*QueryBuilder) Join

func (qb *QueryBuilder) Join(table, condition string) *QueryBuilder

Join adds a join clause

func (*QueryBuilder) LeftJoin

func (qb *QueryBuilder) LeftJoin(table, condition string) *QueryBuilder

LeftJoin adds a left join clause

func (*QueryBuilder) Limit

func (qb *QueryBuilder) Limit(limit int) *QueryBuilder

Limit sets the limit

func (*QueryBuilder) Lock

func (qb *QueryBuilder) Lock(lock string) *QueryBuilder

Lock adds a lock clause

func (*QueryBuilder) Offset

func (qb *QueryBuilder) Offset(offset int) *QueryBuilder

Offset sets the offset

func (*QueryBuilder) OrderBy

func (qb *QueryBuilder) OrderBy(field, direction string) *QueryBuilder

OrderBy adds an order by clause

func (*QueryBuilder) Pluck

func (qb *QueryBuilder) Pluck(column string, values interface{}) error

Pluck executes the query and returns a slice of values from a single column

func (*QueryBuilder) Preload

func (qb *QueryBuilder) Preload(associations ...string) *QueryBuilder

Preload adds preload associations

func (*QueryBuilder) RightJoin

func (qb *QueryBuilder) RightJoin(table, condition string) *QueryBuilder

RightJoin adds a right join clause

func (*QueryBuilder) Select

func (qb *QueryBuilder) Select(fields ...string) *QueryBuilder

Select sets the fields to select

func (*QueryBuilder) SetMode

func (qb *QueryBuilder) SetMode(mode QueryMode) *QueryBuilder

SetMode sets the query mode

func (*QueryBuilder) Where

func (qb *QueryBuilder) Where(condition string, args ...interface{}) *QueryBuilder

Where adds a where clause

func (*QueryBuilder) WhereIn

func (qb *QueryBuilder) WhereIn(field string, values []interface{}) *QueryBuilder

WhereIn adds a where in clause

func (*QueryBuilder) WhereNotIn

func (qb *QueryBuilder) WhereNotIn(field string, values []interface{}) *QueryBuilder

WhereNotIn adds a where not in clause

func (*QueryBuilder) WhereNotNull

func (qb *QueryBuilder) WhereNotNull(field string) *QueryBuilder

WhereNotNull adds a where not null clause

func (*QueryBuilder) WhereNull

func (qb *QueryBuilder) WhereNull(field string) *QueryBuilder

WhereNull adds a where null clause

func (*QueryBuilder) WithContext

func (qb *QueryBuilder) WithContext(ctx context.Context) *QueryBuilder

WithContext sets the context

type QueryInfo

type QueryInfo struct {
	Query     string
	Args      []interface{}
	Duration  time.Duration
	Error     error
	Database  string
	Operation string
	Timestamp time.Time
}

QueryInfo represents information about a database query

type QueryLogger

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

QueryLogger wraps database operations with logging

func GetQueryLogger

func GetQueryLogger() *QueryLogger

GetQueryLogger returns the global query logger

func NewQueryLogger

func NewQueryLogger(logger Logger) *QueryLogger

NewQueryLogger creates a new query logger

func (*QueryLogger) LogExec

func (ql *QueryLogger) LogExec(query string, args []interface{}, start time.Time, result sql.Result, err error)

LogExec logs an Exec operation

func (*QueryLogger) LogQuery

func (ql *QueryLogger) LogQuery(query string, args []interface{}, start time.Time, rows *sql.Rows, err error)

LogQuery logs a Query operation

func (*QueryLogger) LogQueryRow

func (ql *QueryLogger) LogQueryRow(query string, args []interface{}, start time.Time, row *sql.Row, err error)

LogQueryRow logs a QueryRow operation

type QueryMode

type QueryMode int

QueryMode represents the mode of query execution

const (
	NormalMode QueryMode = iota
	PreparedStatementMode
	DryRunMode
)

type SchemaMigration

type SchemaMigration struct {
	ActiveRecordModel
}

SchemaMigration manages schema migrations

func (*SchemaMigration) TableName

func (sm *SchemaMigration) TableName() string

TableName returns the name of the migrations table

type StructuredLogger

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

StructuredLogger is a structured logger implementation

func NewStructuredLogger

func NewStructuredLogger() *StructuredLogger

NewStructuredLogger creates a new structured logger

func (*StructuredLogger) GetLevel

func (sl *StructuredLogger) GetLevel() LogLevel

GetLevel returns the current logging level

func (*StructuredLogger) Log

func (sl *StructuredLogger) Log(level LogLevel, message string, fields map[string]interface{})

Log logs a message in structured format

func (*StructuredLogger) LogQuery

func (sl *StructuredLogger) LogQuery(info *QueryInfo)

LogQuery logs a database query in structured format

func (*StructuredLogger) SetLevel

func (sl *StructuredLogger) SetLevel(level LogLevel)

SetLevel sets the logging level

type TableBuilder

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

TableBuilder table builder

func (*TableBuilder) Build

func (tb *TableBuilder) Build() (string, []string)

Build builds an SQL query

func (*TableBuilder) Column

func (tb *TableBuilder) Column(name, dataType string, options ...string)

Column adds a column

func (*TableBuilder) Index

func (tb *TableBuilder) Index(columns ...string)

Index adds an index

func (*TableBuilder) PrimaryKey

func (tb *TableBuilder) PrimaryKey(columns ...string)

PrimaryKey adds a primary key

func (*TableBuilder) Timestamps

func (tb *TableBuilder) Timestamps()

Timestamps adds timestamps

type TableNamer

type TableNamer interface {
	TableName() string
}

TableNamer interface for getting table name

type Transaction

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

Transaction represents a database transaction

func (*Transaction) AddCallback

func (t *Transaction) AddCallback(callback func() error)

AddCallback adds a callback to be executed before commit

func (*Transaction) BeginNested

func (t *Transaction) BeginNested() (*Transaction, error)

BeginNested starts a nested transaction (savepoint)

func (*Transaction) Commit

func (t *Transaction) Commit() error

Commit commits the transaction

func (*Transaction) CreateSavepoint

func (t *Transaction) CreateSavepoint(name string) error

CreateSavepoint creates a named savepoint

func (*Transaction) Exec

func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error)

Exec executes a query within the transaction

func (*Transaction) GetSavepoints

func (t *Transaction) GetSavepoints() []string

GetSavepoints returns the list of savepoints

func (*Transaction) IsCommitted

func (t *Transaction) IsCommitted() bool

IsCommitted returns true if the transaction is committed

func (*Transaction) IsRolledBack

func (t *Transaction) IsRolledBack() bool

IsRolledBack returns true if the transaction is rolled back

func (*Transaction) Query

func (t *Transaction) Query(query string, args ...interface{}) (*sql.Rows, error)

Query executes a query and returns rows

func (*Transaction) QueryRow

func (t *Transaction) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow executes a query and returns a single row

func (*Transaction) ReleaseSavepoint

func (t *Transaction) ReleaseSavepoint(name string) error

ReleaseSavepoint releases a named savepoint

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback rolls back the transaction

func (*Transaction) RollbackToSavepoint

func (t *Transaction) RollbackToSavepoint(savepointName string) error

RollbackToSavepoint rolls back to a specific savepoint

type TransactionManager

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

TransactionManager manages transactions

func GetTransactionManager

func GetTransactionManager() *TransactionManager

GetTransactionManager returns the global transaction manager

func NewTransactionManager

func NewTransactionManager(db *sql.DB) *TransactionManager

NewTransactionManager creates a new transaction manager

func (*TransactionManager) Begin

func (tm *TransactionManager) Begin() (*Transaction, error)

Begin starts a new transaction

func (*TransactionManager) BeginWithContext

func (tm *TransactionManager) BeginWithContext(ctx context.Context) (*Transaction, error)

BeginWithContext starts a new transaction with context

type Validatable

type Validatable interface {
	Validate() ValidationErrors
	IsValid() bool
	Errors() ValidationErrors
}

Validatable интерфейс для валидируемых моделей.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError ошибка validation.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors коллекция ошибок validation.

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

type ValidationModel

type ValidationModel struct {
	ActiveRecordModel
	// contains filtered or unexported fields
}

ValidationModel базовая модель с validation.

func (*ValidationModel) AddValidation

func (m *ValidationModel) AddValidation(field, rule string, message string, params ...interface{})

AddValidation добавляет правило validation.

func (*ValidationModel) Email

func (m *ValidationModel) Email(field string)

Email проверяет формат email.

func (*ValidationModel) Errors

func (m *ValidationModel) Errors() ValidationErrors

Errors возвращает ошибки validation.

func (*ValidationModel) Format

func (m *ValidationModel) Format(field string, pattern string)

Format проверяет формат по регулярному выражению.

func (*ValidationModel) IsValid

func (m *ValidationModel) IsValid(model interface{}) bool

IsValid проверяет, валидна ли модель.

func (*ValidationModel) Length

func (m *ValidationModel) Length(field string, min, max int)

Length проверяет длину строки.

func (*ValidationModel) Numericality

func (m *ValidationModel) Numericality(field string, min, max float64)

Numericality проверяет числовое значение.

func (*ValidationModel) PresenceOf

func (m *ValidationModel) PresenceOf(field string)

PresenceOf проверяет наличие значения.

func (*ValidationModel) Uniqueness

func (m *ValidationModel) Uniqueness(field string)

Uniqueness проверяет уникальность.

func (*ValidationModel) Validate

func (m *ValidationModel) Validate(model interface{}) ValidationErrors

Validate выполняет validation модели.

type ValidationRule

type ValidationRule struct {
	Field   string
	Rule    string
	Message string
	Params  []interface{}
}

ValidationRule правило validation.

Jump to

Keyboard shortcuts

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