orm

package
v0.12.12 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 20 Imported by: 3

README

ORM Package

The orm package provides database abstraction and utilities built on top of GORM.

Features

  • Multi-Database Support: MySQL, PostgreSQL, SQLite, SQL Server, ODBC
  • Auto Migration: Automatic table and view creation
  • Database Health Check: Health monitoring endpoints
  • Query Utilities: Paging, common query patterns
  • Database Logging: Integrated GORM logging with Zap
  • Entity Registration: Dynamic entity registration for migration

Main Components

Database Initialization
  • InitDefaultDB(): Initialize default database connection
  • InitDB(sub, logger): Initialize named database connection
  • InitDBWithPrefix(sub, prefix): Initialize with table prefix
Connection Management
  • DialectorMap: Map of database driver dialects
  • Connections: Map of active database connections
  • Support for multiple database connections
Utilities
  • QueryBase: Base struct for paging queries
  • PagingResult[T]: Generic paging result with total count
  • AppendEntity(): Register entities for auto-migration
  • MigrateTableAndView(): Migrate tables and database views
Database Drivers
  • MySQL (primary)
  • PostgreSQL
  • SQLite
  • SQL Server
  • ODBC (legacy)

Configuration

Configure via Viper:

  • type: Database type (mysql, postgres, etc.)
  • connection: Connection string
  • maxLifetime: Connection max lifetime
  • max: Max open connections
  • idel: Max idle connections
  • tablePrefix: Table name prefix
  • initDB: Enable auto migration

Usage

// Register entity for migration
orm.AppendEntity(&MyModel{})

// Use default DB connection
db := core.GetService[*gorm.DB]()

// Query with paging
var result orm.PagingResult[MyModel]
result.Trigger(db, queryBase)

Dependencies

  • GORM
  • Zap logging
  • Viper configuration
  • GinShared for integration

Documentation

Index

Constants

View Source
const (
	KeyInitDB      = ginshared.KeyInitDB
	KeyTablePrefix = "database.tablePrefix"
)
View Source
const (
	HealthURIKey   = "healthz"
	HealthURIValue = "/healthz"
)
View Source
const ViewMysqlTmp = "CREATE OR REPLACE ALGORITHM = UNDEFINED VIEW %s%s AS %s"

Variables

View Source
var (
	DialectorMap = make(map[string]OrmDialector)
	Connections  = make(map[string]*gorm.DB)
)
View Source
var ReplaceTablePrefix = core.ReplaceTablePrefix
View Source
var ViewMap = make(map[string]GetViewSql)

Functions

func AppendEntity added in v0.4.11

func AppendEntity(entity ...interface{})

func ApplyMigrate added in v0.5.0

func ApplyMigrate() error

func CleanViews added in v0.12.10

func CleanViews(tx *gorm.DB, logger *zap.Logger, viewsToClean []string) error

func DefaulViewSql added in v0.4.8

func DefaulViewSql(tablePrefix, view, query string) string

func DeleteDuplicatesKeepLastMultiFields added in v0.11.8

func DeleteDuplicatesKeepLastMultiFields[T any](db *gorm.DB, uniqueFields ...string) error

DeleteDuplicatesKeepLastMultiFields 删除重复记录,保留最后一条, 可以指定多个字段

func DisableGormLogger added in v0.10.14

func DisableGormLogger() gormlogger.Interface

func InitDB

func InitDB(sub string, logger *zap.Logger) *gorm.DB

func InitDBWithPrefix added in v0.10.0

func InitDBWithPrefix(sub string, prefix string) *gorm.DB

func InitDefaultDB added in v0.1.3

func InitDefaultDB(logger *zap.Logger) *gorm.DB

func InitMysqlViews added in v0.1.7

func InitMysqlViews(tx *gorm.DB, logger *zap.Logger) error

func MigrateTableAndView added in v0.4.11

func MigrateTableAndView(db *gorm.DB, logger *zap.Logger, bus EventBus.Bus, cleanViews ...string)

func NewGormLogger added in v0.10.14

func NewGormLogger(slowThreshold time.Duration, logLeveal string) gormlogger.Interface

func SessionWithConfig added in v0.4.6

func SessionWithConfig(slowThreshold time.Duration, ignoredNotFound bool) *gorm.Session

Types

type GetViewSql added in v0.4.8

type GetViewSql func(tablePrefix, view, query string) string

type GormLogger added in v0.10.14

type GormLogger struct {
	ZapLogger *zap.Logger
	Config    gormlogger.Config
}

func (*GormLogger) Error added in v0.10.14

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

func (*GormLogger) Info added in v0.10.14

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

func (*GormLogger) LogMode added in v0.10.14

func (*GormLogger) Trace added in v0.10.14

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

func (*GormLogger) Warn added in v0.10.14

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

type HealthController

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

func (*HealthController) Ping

func (h *HealthController) Ping(c *gin.Context)

type OrmDialector added in v0.0.5

type OrmDialector func(dsn string) gorm.Dialector

type PagingResult added in v0.11.10

type PagingResult[T any] struct {
	Page      int
	PageSize  int
	TotalPage int64
	Total     int64
	Error     error
	Data      []T
}

func (*PagingResult[T]) Trigger added in v0.11.10

func (p *PagingResult[T]) Trigger(tx *gorm.DB, req QueryBase) error

type QueryBase added in v0.11.10

type QueryBase struct {
	OwnerID   uint
	OwnerName string
	Page      int    `form:"page"`
	PageSize  int    `form:"pageSize"`
	Q         string `form:"q"`
	OrderBy   string `form:"orderBy"`
}

Jump to

Keyboard shortcuts

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