Documentation
¶
Index ¶
- Variables
- func AddGlobalHook(modelType string, hookType HookType, callback func(interface{}) error)
- func AddGlobalHookWithPriority(modelType string, hookType HookType, priority int, ...)
- func Begin() (*sql.Tx, error)
- func BeginTransactionOnDatabase(databaseName string, dbType DatabaseType) (*sql.Tx, error)
- func BeginTransactionOnDatabaseWithContext(ctx context.Context, databaseName string, dbType DatabaseType) (*sql.Tx, error)
- func BulkUpdate(modelType interface{}, conditions map[string]interface{}, ...) (int64, error)
- func BulkUpdateWithContext(ctx context.Context, modelType interface{}, conditions map[string]interface{}, ...) (int64, error)
- func ClearGlobalHooks(modelType string, hookType HookType)
- func Close() error
- func Connect(driver, dsn string) (*sql.DB, error)
- func Create(model interface{}) error
- func CreateOnDatabase(databaseName string, model interface{}) error
- func CreateTable(tableName string, callback func(*TableBuilder)) error
- func Delete(model interface{}) error
- func DeleteOnDatabase(databaseName string, model interface{}) error
- func DeleteWithConditions(modelType interface{}, conditions map[string]interface{}) (int64, error)
- func DeleteWithConditionsAndContext(ctx context.Context, modelType interface{}, conditions map[string]interface{}) (int64, error)
- func DropTable(tableName string) error
- func Exec(query string, args ...interface{}) (sql.Result, error)
- func ExecOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) (sql.Result, error)
- func Find(model interface{}, id interface{}) error
- func FindAll(models interface{}) error
- func FindInBatches(modelType interface{}, batchSize int, fn func([]interface{}) error) error
- func FindInBatchesWithContext(ctx context.Context, modelType interface{}, batchSize int, ...) error
- func FindOnDatabase(databaseName string, model interface{}, id interface{}) error
- func FindOrCreate(model interface{}, conditions map[string]interface{}) error
- func FindOrCreateByMap(modelType interface{}, attributes map[string]interface{}) (interface{}, error)
- func FindOrCreateByMapWithContext(ctx context.Context, modelType interface{}, attributes map[string]interface{}) (interface{}, error)
- func FindOrCreateWithContext(ctx context.Context, model interface{}, conditions map[string]interface{}) error
- func GetConnection() *sql.DB
- func GetDriverName() string
- func GetPerformanceStats() map[string]interface{}
- func InnerJoins(models interface{}, joins ...string) error
- func Joins(models interface{}, joins ...string) error
- func LeftJoins(models interface{}, joins ...string) error
- func Log(level LogLevel, message string, fields map[string]interface{})
- func LogDebug(message string, fields map[string]interface{})
- func LogError(message string, fields map[string]interface{})
- func LogFatal(message string, fields map[string]interface{})
- func LogInfo(message string, fields map[string]interface{})
- func LogWarn(message string, fields map[string]interface{})
- func LoggedExec(query string, args ...interface{}) (sql.Result, error)
- func LoggedExecWithContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func LoggedQuery(query string, args ...interface{}) (*sql.Rows, error)
- func LoggedQueryRow(query string, args ...interface{}) *sql.Row
- func LoggedQueryRowWithContext(ctx context.Context, query string, args ...interface{}) *sql.Row
- func LoggedQueryWithContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func Preload(models interface{}, associations ...string) error
- func Query(query string, args ...interface{}) (*sql.Rows, error)
- func QueryOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) (*sql.Rows, error)
- func QueryRow(query string, args ...interface{}) *sql.Row
- func QueryRowOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) *sql.Row
- func ResetPerformanceStats()
- func RunGlobalHooks(model interface{}, hookType HookType) error
- func SetConnection(database *sql.DB, driver string)
- func SetDatabaseManager(dm *DatabaseManager)
- func SetLogger(logger Logger)
- func SetTransactionManager(tm *TransactionManager)
- func Transactional(fn func(*Transaction) error) error
- func TransactionalWithContext(ctx context.Context, fn func(*Transaction) error) error
- func Update(model interface{}) error
- func UpdateOnDatabase(databaseName string, model interface{}) error
- func UpdateWithSQLExpr(model interface{}, expressions map[string]string, args ...interface{}) error
- func UpdateWithSQLExprAndContext(ctx context.Context, model interface{}, expressions map[string]string, ...) error
- func Where(models interface{}, query string, args ...interface{}) error
- func With(models interface{}, associations ...string) error
- type ActiveRecord
- type ActiveRecordModel
- func (m *ActiveRecordModel) BelongsTo(name string, model interface{}, foreignKey string)
- func (m *ActiveRecordModel) Create() error
- func (m *ActiveRecordModel) Delete() error
- func (m *ActiveRecordModel) Destroy() bool
- func (m *ActiveRecordModel) Find(id interface{}) error
- func (m *ActiveRecordModel) GetCreatedAt() time.Time
- func (m *ActiveRecordModel) GetID() interface{}
- func (m *ActiveRecordModel) GetUpdatedAt() time.Time
- func (m *ActiveRecordModel) HasMany(name string, model interface{}, foreignKey string)
- func (m *ActiveRecordModel) HasManyThrough(name string, model interface{}, through string, foreignKey string, ...)
- func (m *ActiveRecordModel) HasOne(name string, model interface{}, foreignKey string)
- func (m *ActiveRecordModel) Include(associationNames ...string) error
- func (m *ActiveRecordModel) IsNewRecord() bool
- func (m *ActiveRecordModel) IsPersisted() bool
- func (m *ActiveRecordModel) Load(associationName string) error
- func (m *ActiveRecordModel) Reload() error
- func (m *ActiveRecordModel) Save() error
- func (m *ActiveRecordModel) SetCreatedAt(t time.Time)
- func (m *ActiveRecordModel) SetID(id interface{})
- func (m *ActiveRecordModel) SetUpdatedAt(t time.Time)
- func (m *ActiveRecordModel) Touch() error
- func (m *ActiveRecordModel) Update() error
- func (m *ActiveRecordModel) Where(query string, args ...interface{}) (interface{}, error)
- type Association
- type AssociationType
- type Associations
- type BaseModel
- func (m *BaseModel) Find(id interface{}) error
- func (m *BaseModel) GetCreatedAt() time.Time
- func (m *BaseModel) GetID() interface{}
- func (m *BaseModel) GetUpdatedAt() time.Time
- func (m *BaseModel) SetCreatedAt(t time.Time)
- func (m *BaseModel) SetID(id interface{})
- func (m *BaseModel) SetUpdatedAt(t time.Time)
- func (m *BaseModel) TableName() string
- func (m *BaseModel) Where(query string, args ...interface{}) (interface{}, error)
- type BatchInsertResult
- func BatchInsert(models []interface{}) (*BatchInsertResult, error)
- func BatchInsertWithContext(ctx context.Context, models []interface{}) (*BatchInsertResult, error)
- func BatchUpsert(models []interface{}, conflictFields []string, updateFields []string) (*BatchInsertResult, error)
- func BatchUpsertWithContext(ctx context.Context, models []interface{}, conflictFields []string, ...) (*BatchInsertResult, error)
- type DatabaseConfig
- type DatabaseConnection
- type DatabaseManager
- func (dm *DatabaseManager) AddDatabase(name string, resolver *DatabaseResolver)
- func (dm *DatabaseManager) Close() error
- func (dm *DatabaseManager) GetConnection(databaseName string, dbType DatabaseType) (*sql.DB, error)
- func (dm *DatabaseManager) GetDatabase(name string) (*DatabaseResolver, error)
- func (dm *DatabaseManager) HealthCheck() map[string]map[string]error
- type DatabaseResolver
- func (dr *DatabaseResolver) AddReadReplica(config *DatabaseConfig) error
- func (dr *DatabaseResolver) AddWriteReplica(config *DatabaseConfig) error
- func (dr *DatabaseResolver) Close() error
- func (dr *DatabaseResolver) GetConnection(dbType DatabaseType) (*sql.DB, error)
- func (dr *DatabaseResolver) GetPrimaryConnection() (*sql.DB, error)
- func (dr *DatabaseResolver) GetReadConnection() (*sql.DB, error)
- func (dr *DatabaseResolver) GetWriteConnection() (*sql.DB, error)
- func (dr *DatabaseResolver) HealthCheck() map[string]error
- func (dr *DatabaseResolver) SetPrimary(config *DatabaseConfig) error
- type DatabaseType
- type DefaultLogger
- type Hook
- type HookType
- type Hookable
- type HookableModel
- func (m *HookableModel) AddHook(hookType HookType, callback func(interface{}) error)
- func (m *HookableModel) AddHookWithPriority(hookType HookType, priority int, callback func(interface{}) error)
- func (m *HookableModel) ClearAllHooks()
- func (m *HookableModel) ClearHooks(hookType HookType)
- func (m *HookableModel) Create() error
- func (m *HookableModel) Delete() error
- func (m *HookableModel) Find(id interface{}) error
- func (m *HookableModel) RunHooks(hookType HookType) error
- func (m *HookableModel) Save() error
- func (m *HookableModel) Update() error
- type LogLevel
- type Logger
- type Migration
- type MigrationInterface
- type MigrationManager
- type MigrationRecord
- type Migrator
- type MigratorStruct
- type Model
- type Modeler
- type PerformanceMetrics
- type QueryBuilder
- func (qb *QueryBuilder) Build() (string, []interface{})
- func (qb *QueryBuilder) Count() (int64, error)
- func (qb *QueryBuilder) Distinct() *QueryBuilder
- func (qb *QueryBuilder) Exclude(fields ...string) *QueryBuilder
- func (qb *QueryBuilder) Execute() (*sql.Rows, error)
- func (qb *QueryBuilder) Exists() (bool, error)
- func (qb *QueryBuilder) Find(models interface{}) error
- func (qb *QueryBuilder) FindInBatches(batchSize int, fn func([]interface{}) error) error
- func (qb *QueryBuilder) First(model interface{}) error
- func (qb *QueryBuilder) GroupBy(fields ...string) *QueryBuilder
- func (qb *QueryBuilder) Having(condition string, args ...interface{}) *QueryBuilder
- func (qb *QueryBuilder) Hint(hint string) *QueryBuilder
- func (qb *QueryBuilder) Include(associations ...string) *QueryBuilder
- func (qb *QueryBuilder) InnerJoin(table, condition string) *QueryBuilder
- func (qb *QueryBuilder) Join(table, condition string) *QueryBuilder
- func (qb *QueryBuilder) LeftJoin(table, condition string) *QueryBuilder
- func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
- func (qb *QueryBuilder) Lock(lock string) *QueryBuilder
- func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
- func (qb *QueryBuilder) OrderBy(field, direction string) *QueryBuilder
- func (qb *QueryBuilder) Pluck(column string, values interface{}) error
- func (qb *QueryBuilder) Preload(associations ...string) *QueryBuilder
- func (qb *QueryBuilder) RightJoin(table, condition string) *QueryBuilder
- func (qb *QueryBuilder) Select(fields ...string) *QueryBuilder
- func (qb *QueryBuilder) SetMode(mode QueryMode) *QueryBuilder
- func (qb *QueryBuilder) Where(condition string, args ...interface{}) *QueryBuilder
- func (qb *QueryBuilder) WhereIn(field string, values []interface{}) *QueryBuilder
- func (qb *QueryBuilder) WhereNotIn(field string, values []interface{}) *QueryBuilder
- func (qb *QueryBuilder) WhereNotNull(field string) *QueryBuilder
- func (qb *QueryBuilder) WhereNull(field string) *QueryBuilder
- func (qb *QueryBuilder) WithContext(ctx context.Context) *QueryBuilder
- type QueryInfo
- type QueryLogger
- func (ql *QueryLogger) LogExec(query string, args []interface{}, start time.Time, result sql.Result, ...)
- func (ql *QueryLogger) LogQuery(query string, args []interface{}, start time.Time, rows *sql.Rows, err error)
- func (ql *QueryLogger) LogQueryRow(query string, args []interface{}, start time.Time, row *sql.Row, err error)
- type QueryMode
- type SchemaMigration
- type StructuredLogger
- type TableBuilder
- type TableNamer
- type Transaction
- func (t *Transaction) AddCallback(callback func() error)
- func (t *Transaction) BeginNested() (*Transaction, error)
- func (t *Transaction) Commit() error
- func (t *Transaction) CreateSavepoint(name string) error
- func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error)
- func (t *Transaction) GetSavepoints() []string
- func (t *Transaction) IsCommitted() bool
- func (t *Transaction) IsRolledBack() bool
- func (t *Transaction) Query(query string, args ...interface{}) (*sql.Rows, error)
- func (t *Transaction) QueryRow(query string, args ...interface{}) *sql.Row
- func (t *Transaction) ReleaseSavepoint(name string) error
- func (t *Transaction) Rollback() error
- func (t *Transaction) RollbackToSavepoint(savepointName string) error
- type TransactionManager
- type Validatable
- type ValidationError
- type ValidationErrors
- type ValidationModel
- func (m *ValidationModel) AddValidation(field, rule string, message string, params ...interface{})
- func (m *ValidationModel) Email(field string)
- func (m *ValidationModel) Errors() ValidationErrors
- func (m *ValidationModel) Format(field string, pattern string)
- func (m *ValidationModel) IsValid(model interface{}) bool
- func (m *ValidationModel) Length(field string, min, max int)
- func (m *ValidationModel) Numericality(field string, min, max float64)
- func (m *ValidationModel) PresenceOf(field string)
- func (m *ValidationModel) Uniqueness(field string)
- func (m *ValidationModel) Validate(model interface{}) ValidationErrors
- type ValidationRule
Constants ¶
This section is empty.
Variables ¶
var (
ErrNotFound = errors.New("record not found")
)
Common errors.
var ErrNotModeler = errors.New("receiver does not implement Modeler")
Functions ¶
func AddGlobalHook ¶
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 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 ¶
ClearGlobalHooks removes all global hooks for a model type
func CreateOnDatabase ¶
CreateOnDatabase creates a record on a specific database
func CreateTable ¶
func CreateTable(tableName string, callback func(*TableBuilder)) error
CreateTable creates a table
func DeleteOnDatabase ¶
DeleteOnDatabase deletes a record on a specific database
func DeleteWithConditions ¶
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 ExecOnDatabase ¶
func ExecOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) (sql.Result, error)
ExecOnDatabase executes a query on a specific database
func FindInBatches ¶
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 ¶
FindOnDatabase finds a record on a specific database
func FindOrCreate ¶
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 GetPerformanceStats ¶
func GetPerformanceStats() map[string]interface{}
GetPerformanceStats returns current performance statistics
func InnerJoins ¶
InnerJoins performs INNER JOIN.
func LoggedExec ¶
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 ¶
LoggedQuery executes a query with logging
func LoggedQueryRow ¶
LoggedQueryRow executes a query row with logging
func LoggedQueryRowWithContext ¶
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 QueryOnDatabase ¶
func QueryOnDatabase(databaseName string, dbType DatabaseType, query string, args ...interface{}) (*sql.Rows, error)
QueryOnDatabase executes a query on a specific database
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 ¶
RunGlobalHooks executes global hooks for a model
func SetConnection ¶
SetConnection sets the global connection.
func SetDatabaseManager ¶
func SetDatabaseManager(dm *DatabaseManager)
SetDatabaseManager sets the global database manager
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 UpdateOnDatabase ¶
UpdateOnDatabase updates a record on a specific database
func UpdateWithSQLExpr ¶
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
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) GetCreatedAt ¶
GetCreatedAt returns the creation time
func (*BaseModel) GetUpdatedAt ¶
GetUpdatedAt returns the update time
func (*BaseModel) SetCreatedAt ¶
SetCreatedAt sets the creation time
func (*BaseModel) SetUpdatedAt ¶
SetUpdatedAt sets the update time
type BatchInsertResult ¶
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 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) Update ¶
func (m *HookableModel) Update() error
Override Update to include hooks
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
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 ¶
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 ¶
MigrationRecord record of a completed migration
type MigratorStruct ¶
type MigratorStruct struct {
// contains filtered or unexported fields
}
Migrator manages migrations
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 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
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 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) PrimaryKey ¶
func (tb *TableBuilder) PrimaryKey(columns ...string)
PrimaryKey adds a primary key
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) 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 ¶
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 ¶
ValidationRule правило validation.