orm

package module
v0.0.0-...-78ddb44 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 24 Imported by: 18

Documentation

Index

Constants

View Source
const (
	DefaultConnection = "default"
)

Variables

View Source
var (
	ErrorDatabaseNotDefined = errors.New("database is required but not defined")
)

Functions

func BuildPostgresConnectionString

func BuildPostgresConnectionString(config PostgresConfig) string

func Close

func Close(c context.Context) error

func CreateTestContext

func CreateTestContext(c context.Context, modelsToMigration ...interface{}) context.Context

func DB

func DB(ctx context.Context) *gorm.DB

RetrieveDB retrieves the database connection from the context.

func FileWithLineNum

func FileWithLineNum() string

FileWithLineNum returns the file name and line number of the most recent caller outside specific libraries or test files, optimized for production use.

func FromContext

func FromContext(ctx context.Context) *gorm.DB

func GlobalConnection

func GlobalConnection() *gorm.DB

func MigrationDown

func MigrationDown(db *gorm.DB, args []string) error

MigrationDown reverts a specific migration by version number.

func MigrationGenerate

func MigrationGenerate(db *gorm.DB, args []string) error

MigrationGenerate creates new migration files with up and down SQL templates.

func MigrationInit

func MigrationInit(db *gorm.DB, args []string) error

MigrationInit initializes the migration folder and creates the schema migrations table.

func MigrationPerform

func MigrationPerform(db *gorm.DB, args []string) error

MigrationPerform applies all missing migrations to bring the database up to date.

func MigrationSeed

func MigrationSeed(db *gorm.DB, args []string) error

MigrationSeed runs a seed script located in the seed.go file.

func MigrationVersion

func MigrationVersion(db *gorm.DB, args []string) error

MigrationVersion prints the current database version and lists any missing migrations.

func NewDB

func NewDB(c context.Context) *gorm.DB

func NewInMemoryConnection

func NewInMemoryConnection(fileName string, modelToMigrate ...interface{}) *gorm.DB

this is used for testing makes things easier. NewInMemoryConnection creates a new database connection and migrates any passed in model

func NewPostgresConnection

func NewPostgresConnection(config PostgresConfig) (*gorm.DB, error)

func NewSQLiteConnection

func NewSQLiteConnection(config SQLiteConfig, modelToMigrate ...interface{}) (*gorm.DB, error)

this is used for testing makes things easier. NewInMemoryConnection creates a new database connection and migrates any passed in model

func ToContext

func ToContext(parent context.Context, db *gorm.DB) context.Context

Types

type AfterFunc

type AfterFunc func(db *gorm.DB) error

type Config

type Config struct {
	Driver Driver

	Host     string
	User     string
	Database string
	Password string
	Port     int

	SSL bool
}

type ConfigFunc

type ConfigFunc[T any] func(a *golly.Application) (T, error)

type CustomDialector

type CustomDialector struct {
	DB        *sql.DB
	Dialector gorm.Dialector
}

CustomDialector wraps the stdlib DB and dynamically generates IAM tokens per connection.

func (*CustomDialector) BindVarTo

func (dialect *CustomDialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{})

func (*CustomDialector) DataTypeOf

func (dialect *CustomDialector) DataTypeOf(field *schema.Field) string

func (*CustomDialector) DefaultValueOf

func (dialect *CustomDialector) DefaultValueOf(field *schema.Field) clause.Expression

func (*CustomDialector) Explain

func (dialect *CustomDialector) Explain(sql string, vars ...interface{}) string

func (*CustomDialector) Initialize

func (dialect *CustomDialector) Initialize(db *gorm.DB) error

func (*CustomDialector) Migrator

func (dialect *CustomDialector) Migrator(db *gorm.DB) gorm.Migrator

func (*CustomDialector) Name

func (dialect *CustomDialector) Name() string

func (*CustomDialector) QuoteTo

func (dialect *CustomDialector) QuoteTo(writer clause.Writer, s string)

type Driver

type Driver string
const (
	InMemoryDriver Driver = "in-memory"
	SQLiteDriver   Driver = "sqlite"
	PostgresDriver Driver = "postgres"
)

type Logger

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

func NewLogger

func NewLogger(driver string, disableLogger bool) *Logger

func (Logger) Error

func (l Logger) Error(ctx context.Context, msg string, data ...interface{})

Error print error messages

func (Logger) Info

func (l Logger) Info(ctx context.Context, msg string, data ...interface{})

Info print info

func (*Logger) LogMode

func (l *Logger) LogMode(level logger.LogLevel) logger.Interface

LogMode log mode

func (Logger) Trace

func (l Logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

Trace print sql message

func (Logger) Warn

func (l Logger) Warn(ctx context.Context, msg string, data ...interface{})

Warn print warn messages

func (Logger) WithSourceFields

func (l Logger) WithSourceFields() *golly.Entry

type Model

type Model struct {
	ID        uint           `json:"id" gorm:"primaryKey" faker:"-"`
	CreatedAt time.Time      `json:"createdAt,omitempty" faker:"-"`
	UpdatedAt time.Time      `json:"updatedAt,omitempty" faker:"-"`
	DeletedAt gorm.DeletedAt `json:"deletedAt,omitempty" faker:"-"`
}

Model default model struct (Can add additional functionality here)

type ModelUUID

type ModelUUID struct {
	ID        uuid.UUID      `gorm:"type:uuid;" json:"id" fake:"-"`
	CreatedAt time.Time      `json:"createdAt" faker:"-"`
	UpdatedAt time.Time      `json:"updatedAt" faker:"-"`
	DeletedAt gorm.DeletedAt `json:"deletedAt,omitempty" faker:"-"`
}

ModelUUID is a UUID version of model

func NewModelUUID

func NewModelUUID() ModelUUID

func TestModelUUID

func TestModelUUID() ModelUUID

type OrmPlugin

type OrmPlugin[T any] struct {
	UseGormMigrations bool

	Database T // Generic configuration, specific to the database driver
	// contains filtered or unexported fields
}

OrmConfig provides a generic configuration wrapper for the ORM plugin.

func NewOrmPlugin

func NewOrmPlugin[T any](config ConfigFunc[T]) *OrmPlugin[T]

NewOrmPlugin creates a new instance of OrmPlugin with default values.

func (*OrmPlugin[T]) After

func (p *OrmPlugin[T]) After(handlers ...AfterFunc) *OrmPlugin[T]

After allows you to hook on to after the connection is estabilished to enable any gorm specific stuff you want like CTEs etc

func (*OrmPlugin[T]) AfterDeinitialize

func (p *OrmPlugin[T]) AfterDeinitialize(app *golly.Application) error

AfterDeinitialize closes the global database connection.

func (*OrmPlugin[T]) Commands

func (p *OrmPlugin[T]) Commands() []*cobra.Command

Commands returns CLI commands for migration and database tasks.

func (*OrmPlugin[T]) Deinitialize

func (p *OrmPlugin[T]) Deinitialize(app *golly.Application) error

func (*OrmPlugin[T]) Initialize

func (p *OrmPlugin[T]) Initialize(app *golly.Application) error

Initialize sets up the database connection and middleware.

func (*OrmPlugin[T]) Name

func (*OrmPlugin[T]) Name() string

type PostgresConfig

type PostgresConfig struct {
	ConnectionString string
	ApplicationName  string

	Host     string
	Port     int
	User     string
	Password string
	Database string
	SSL      bool
	URL      string // Optional: Use a full database URL if provided.
	Logger   bool   // Disable logger if false.

	MaxIdleConns    int
	MaxOpenConns    int
	ConnMaxLifetime time.Duration
	MaxIdleTime     time.Duration

	ConnectionTimeout time.Duration

	AuthToken        string
	AuthTokenFnc     func() (string, error)
	BeforeConnectFnc func(ctx context.Context, config *pgx.ConnConfig) error
}

PostgresConfig defines the configuration required to connect to a PostgreSQL database.

type SQLiteConfig

type SQLiteConfig struct {
	Logger           bool
	InMemory         bool
	Database         string
	Path             string
	ConnectionString string
}

type SchemaMigration

type SchemaMigration struct {
	Version string `gorm:"primaryKey;autoIncrement:false"`
	File    string
}

Jump to

Keyboard shortcuts

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