xgorm

package module
v0.0.0-...-488c756 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: MIT Imports: 23 Imported by: 0

README

xgorm

Dependencies

  • github.com/Aoi-hosizora/ahlib
  • github.com/Aoi-hosizora/ahlib-mx/xdbutils
  • github.com/jinzhu/gorm
  • github.com/go-sql-driver/mysql
  • github.com/VividCortex/mysqlerr
  • github.com/mattn/go-sqlite3 (cgo)
  • github.com/lib/pq
  • github.com/sirupsen/logrus

Documents

Types
  • type SQLiteDriverOptions struct
  • type MySQLConfig struct
  • type MySQLExtraConfig struct
  • type SQLiteConfig struct
  • type PostgreSQLConfig struct
  • type PropertyValue struct
  • type PropertyDict map
  • type OrderByOption func
  • type GormTime struct
  • type GormTime2 struct
  • type LoggerOption func
  • type ILogger interface
  • type SilenceLogger struct
  • type LogrusLogger struct
  • type StdLogger struct
  • type LoggerParam struct
Variables
  • var FormatLoggerFunc func
  • var FieldifyLoggerFunc func
Constants
  • const MySQL string
  • const SQLite string
  • const Postgres string
  • const MySQLDuplicateEntryErrno uint16
  • const SQLiteUniqueConstraintErrno int
  • const PostgreSQLUniqueViolationErrno string
  • const DefaultDeletedAtTimestamp string
  • const CreateCallbackName string
  • const UpdateCallbackName string
  • const DeleteCallbackName string
  • const QueryCallbackName string
  • const RowQueryCallbackName string
Functions
  • func IsMySQL(db *gorm.DB) bool
  • func IsSQLite(db *gorm.DB) bool
  • func IsPostgreSQL(db *gorm.DB) bool
  • func MySQLDefaultDsn(username, password, address, database string) string
  • func SQLiteDefaultDsn(file string) string
  • func PostgreSQLDefaultDsn(username, password, host string, port int, database string) string
  • func IsMySQLDuplicateEntryError(err error) bool
  • func IsSQLiteUniqueConstraintError(err error) bool
  • func IsPostgreSQLUniqueViolationError(err error) bool
  • func QueryErr(rdb *gorm.DB) (xstatus.DbStatus, error)
  • func CreateErr(rdb *gorm.DB) (xstatus.DbStatus, error)
  • func UpdateErr(rdb *gorm.DB) (xstatus.DbStatus, error)
  • func DeleteErr(rdb *gorm.DB) (xstatus.DbStatus, error)
  • func NewPropertyValue(reverse bool, destinations ...string) *PropertyValue
  • func WithOrderBySourceSeparator(separator string) OrderByOption
  • func WithOrderByTargetSeparator(separator string) OrderByOption
  • func WithOrderBySourceProcessor(processor func(source string) (field string, asc bool)) OrderByOption
  • func WithOrderByTargetProcessor(processor func(destination string, asc bool) (target string)) OrderByOption
  • func WithDefaultExpression(defaultExpression string) OrderByOption
  • func GenerateOrderByExpr(querySource string, dict PropertyDict, options ...OrderByOption) string
  • func GetSQLDriver(name string) driver.Driver
  • func ForceRegisterSQLDriver(name string, driver driver.Driver)
  • func ForceUnregisterSQLDriver(name string)
  • func WithExtensions(extensions []string) SQLiteDriverOption
  • func WithAggregatorRegisterer(name string, impl interface{}, pure bool) SQLiteDriverOption
  • func WithAuthorizerRegisterer(callback func(int, string, string, string) int) SQLiteDriverOption
  • func WithCollationRegisterer(name string, cmp func(string, string) int) SQLiteDriverOption
  • func WithCommitHookRegisterer(callback func() int) SQLiteDriverOption
  • func WithFuncRegisterer(name string, impl interface{}, pure bool) SQLiteDriverOption
  • func WithPreUpdateHookRegister(callback func(interface{})) SQLiteDriverOption
  • func WithRollbackHookRegisterer(callback func()) SQLiteDriverOption
  • func WithUpdateHookRegisterer(callback func(int, string, string, int64)) SQLiteDriverOption
  • func WithSQLiteConnectionHooker(hooker func(interface{}) error) SQLiteDriverOption
  • func NewSqliteDriver(extensions []string, connectHook func(*sqlite3.SQLiteConn) error) *sqlite3.SQLiteDriver
  • func HookDeletedAt(db *gorm.DB, defaultTimestamp string)
  • func WithLogInfo(log bool) LoggerOption
  • func WithLogSQL(log bool) LoggerOption
  • func WithLogOther(log bool) LoggerOption
  • func WithSlowThreshold(threshold time.Duration) LoggerOption
  • func EnableLogger()
  • func DisableLogger()
  • func NewSilenceLogger() *SilenceLogger
  • func NewLogrusLogger(logger *logrus.Logger, options ...LoggerOption) *LogrusLogger
  • func NewStdLogger(logger logrus.StdLogger, options ...LoggerOption) *StdLogger
Methods
  • func (p *PropertyValue) Destinations() []string
  • func (p *PropertyValue) Reverse() bool
  • func (s *SilenceLogger) Print(...interface{})
  • func (l *LogrusLogger) Print(v ...interface{})
  • func (l *StdLogger) Print(v ...interface{})

Documentation

Index

Constants

View Source
const (
	// MySQL represents the "mysql" dialect for gorm. Remember to import github.com/jinzhu/gorm/dialects/mysql or github.com/go-sql-driver/mysql to initial package.
	MySQL = "mysql"

	// SQLite represents the "sqlite3" dialect for gorm. Remember to import github.com/jinzhu/gorm/dialects/sqlite or github.com/mattn/go-sqlite3 to initial package.
	SQLite = "sqlite3"

	// Postgres represents the "postgres" dialect for gorm. Remember to import github.com/jinzhu/gorm/dialects/postgres or github.com/lib/pq to initial package.
	Postgres = "postgres"
)
View Source
const (
	// MySQLDuplicateEntryErrno is MySQL's DUP_ENTRY errno, referred from https://github.com/VividCortex/mysqlerr/blob/69f897f9a2/mysqlerr.go and
	// https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.htm.
	MySQLDuplicateEntryErrno = uint16(mysqlerr.ER_DUP_ENTRY) // 1062, DUP_ENTRY

	// SQLiteUniqueConstraintErrno is SQLite's CONSTRAINT_UNIQUE extended errno, referred from https://github.com/mattn/go-sqlite3/blob/85a15a7254/error.go
	// and http://www.sqlite.org/c3ref/c_abort_rollback.html.
	SQLiteUniqueConstraintErrno = int(xdbutils_sqlite.ErrConstraintUnique) // 19 | 8<<8, sqlite3.ErrConstraintUnique

	// PostgreSQLUniqueViolationErrno is PostgreSQL's unique_violation errno, referred from https://github.com/lib/pq/blob/89fee89644/error.go and
	// https://www.postgresql.org/docs/10/errcodes-appendix.html
	PostgreSQLUniqueViolationErrno = "23505" // pq.errorCodeNames unique_violation
)
View Source
const (
	CreateCallbackName   = "gorm:create"
	UpdateCallbackName   = "gorm:update"
	DeleteCallbackName   = "gorm:delete"
	QueryCallbackName    = "gorm:query"
	RowQueryCallbackName = "gorm:row_query"
)

Gorm's callback names. See gorm.Callback or visit https://github.com/jinzhu/gorm/blob/5c235b72a4/callback.go for more details.

View Source
const (
	// NAME represents ahlib-mx/xgorm package's name.
	NAME = "ahlib-mx/xgorm"

	// VERSION represents ahlib-mx/xgorm package's current version.
	VERSION = "1.6.0"
)
View Source
const (
	// DefaultDeletedAtTimestamp represents the default value in `gorm` tag of GormTime.DeletedAt.
	DefaultDeletedAtTimestamp = "1970-01-01 00:00:01"
)

Variables

View Source
var (
	// FormatLoggerFunc is a custom LoggerParam's format function for LogrusLogger and StdLogger.
	FormatLoggerFunc func(p *LoggerParam) string

	// FieldifyLoggerFunc is a custom LoggerParam's fieldify function for LogrusLogger.
	FieldifyLoggerFunc func(p *LoggerParam) logrus.Fields
)

Functions

func CreateErr

func CreateErr(rdb *gorm.DB) (xstatus.DbStatus, error)

CreateErr checks gorm.DB after create operated, will only return xstatus.DbSuccess, xstatus.DbExisted and xstatus.DbFailed.

func DeleteErr

func DeleteErr(rdb *gorm.DB) (xstatus.DbStatus, error)

DeleteErr checks gorm.DB after delete operated, will only return xstatus.DbSuccess, xstatus.DbNotFound and xstatus.DbFailed.

func DisableLogger

func DisableLogger()

DisableLogger disables LogrusLogger and StdLogger.

func EnableLogger

func EnableLogger()

EnableLogger enables LogrusLogger and StdLogger to do any log.

func ForceRegisterSQLDriver

func ForceRegisterSQLDriver(name string, driver driver.Driver)

ForceRegisterSQLDriver registers given driver.Driver just like sql.Register, but will replace the same-name-registered driver.Driver.

func ForceUnregisterSQLDriver

func ForceUnregisterSQLDriver(name string)

ForceUnregisterSQLDriver unregisters driver.Driver with given name.

func GenerateOrderByExpr

func GenerateOrderByExpr(querySource string, dict PropertyDict, options ...OrderByOption) string

GenerateOrderByExpr returns a generated order-by expression by given order-by query source string (such as "name desc, age asc") and PropertyDict, with some OrderByOption-s. The generated expression will be in mysql-sql (such as "xxx ASC") or neo4j-cypher style (such as "xxx.yyy DESC").

Example:

dict := PropertyDict{
	"uid":  NewPropertyValue(false, "uid"),
	"name": NewPropertyValue(false, "firstname", "lastname"),
	"age":  NewPropertyValue(true, "birthday"),
}
_ = GenerateOrderByExpr(`uid, age desc`, dict) // => uid ASC, birthday ASC
_ = GenerateOrderByExpr(`age, username desc`, dict) // => birthday DESC, firstname DESC, lastname DESC

func GetSQLDriver

func GetSQLDriver(name string) driver.Driver

GetSQLDriver gets registered driver.Driver by given name, returns nil if unregistered.

func HookDeletedAt

func HookDeletedAt(db *gorm.DB, defaultTimestamp string)

HookDeletedAt hooks gorm.DB's callbacks to make soft deleting to use the new default deletedAt timestamp, such as DefaultDeletedAtTimestamp.

func IsMySQL

func IsMySQL(db *gorm.DB) bool

IsMySQL checks whether the dialect of given gorm.DB is "mysql".

func IsMySQLDuplicateEntryError

func IsMySQLDuplicateEntryError(err error) bool

IsMySQLDuplicateEntryError checks whether err is MySQL's ER_DUP_ENTRY error, whose error code is MySQLDuplicateEntryErrno.

func IsPostgreSQL

func IsPostgreSQL(db *gorm.DB) bool

IsPostgreSQL checks whether the dialect of given gorm.DB is "postgres".

func IsPostgreSQLUniqueViolationError

func IsPostgreSQLUniqueViolationError(err error) bool

IsPostgreSQLUniqueViolationError checks whether err is PostgreSQL's unique_violation error, whose error code is PostgreSQLUniqueViolationErrno.

func IsSQLite

func IsSQLite(db *gorm.DB) bool

IsSQLite checks whether the dialect of given gorm.DB is "sqlite3".

func IsSQLiteUniqueConstraintError

func IsSQLiteUniqueConstraintError(err error) bool

IsSQLiteUniqueConstraintError checks whether err is SQLite's ErrConstraintUnique error, whose extended code is SQLiteUniqueConstraintErrno.

func MySQLDefaultDsn

func MySQLDefaultDsn(username, password, address, database string) string

MySQLDefaultDsn returns the MySQL dsn from given parameters with "utf8mb4" charset and "local" location.

Please visit the follow links for more information: - https://github.com/go-sql-driver/mysql#dsn-data-source-name - https://dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html

func NewSQLiteDriver

func NewSQLiteDriver(options ...SQLiteDriverOption) *sqlite3.SQLiteDriver

NewSQLiteDriver creates sqlite3.SQLiteDriver with extensions and connect hooks, based on given SQLiteDriverOption-s.

func PostgreSQLDefaultDsn

func PostgreSQLDefaultDsn(username, password, host string, port int, database string) string

PostgreSQLDefaultDsn returns the PostgreSQL dsn from given parameters.

Please visit the follow links for more information: - https://pkg.go.dev/github.com/lib/pq#hdr-Connection_String_Parameters - https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING - https://www.postgresql.org/docs/current/runtime-config-client.html

func QueryErr

func QueryErr(rdb *gorm.DB) (xstatus.DbStatus, error)

QueryErr checks gorm.DB after query operated, will only return xstatus.DbSuccess, xstatus.DbNotFound and xstatus.DbFailed.

func SQLiteDefaultDsn

func SQLiteDefaultDsn(file string) string

SQLiteDefaultDsn returns the SQLite dsn from given parameter (database filename or ":memory:" or empty string).

Please visit the follow links for more information: - https://github.com/mattn/go-sqlite3#connection-string - https://www.sqlite.org/c3ref/open.html

func UpdateErr

func UpdateErr(rdb *gorm.DB) (xstatus.DbStatus, error)

UpdateErr checks gorm.DB after update operated, will only return xstatus.DbSuccess, xstatus.DbNotFound, xstatus.DbExisted and xstatus.DbFailed.

Types

type GormTime

type GormTime struct {
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *time.Time `sql:"index" gorm:"default:'1970-01-01 00:00:01'"`
}

GormTime represents a structure of CreatedAt, UpdatedAt, DeletedAt (defaults to DefaultDeletedAtTimestamp), is a replacement of gorm.Model.

type GormTime2

type GormTime2 struct {
	CreatedAt time.Time
	UpdatedAt time.Time
}

GormTime2 represents a structure of CreatedAt, UpdatedAt, which allow you to customize the DeletedAt field, is a replacement of gorm.Model.

type ILogger

type ILogger interface {
	Print(v ...interface{})
}

ILogger abstracts gorm's internal logger to an interface, equals to gorm.logger interface.

type LoggerOption

type LoggerOption func(*loggerOptions)

LoggerOption represents an option type for LogrusLogger and StdLogger's option, can be created by WithXXX functions.

func WithLogInfo

func WithLogInfo(log bool) LoggerOption

WithLogInfo creates a LoggerOption to decide whether to do log for [info] or not, defaults to true.

func WithLogOther

func WithLogOther(log bool) LoggerOption

WithLogOther creates a LoggerOption to decide whether to do log for other type (such as log) or not, defaults to true.

func WithLogSQL

func WithLogSQL(log bool) LoggerOption

WithLogSQL creates a LoggerOption to decide whether to do log for [sql] or not, defaults to true.

func WithSlowThreshold

func WithSlowThreshold(threshold time.Duration) LoggerOption

WithSlowThreshold creates a LoggerOption to specify a slow operation's duration used to highlight loggers, defaults to 0ms, means no highlight.

type LoggerParam

type LoggerParam struct {
	Type     string
	Message  string
	SQL      string
	Rows     int64
	Duration time.Duration
	Slow     bool
	Source   string
}

LoggerParam stores some logger parameters and is used by LogrusLogger and StdLogger.

type LogrusLogger

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

LogrusLogger represents a gorm's logger, used to log gorm's executing message to logrus.Logger.

func NewLogrusLogger

func NewLogrusLogger(logger *logrus.Logger, options ...LoggerOption) *LogrusLogger

NewLogrusLogger creates a new LogrusLogger using given logrus.Logger and LoggerOption-s.

Example:

db, err := gorm.Open("mysql", dsn)
db.LogMode(true) // must be true
l := logrus.New()
l.SetFormatter(&logrus.TextFormatter{})
db.SetLogger(xgorm.NewLogrusLogger(l))

func (*LogrusLogger) Print

func (l *LogrusLogger) Print(v ...interface{})

Print implements gorm.logger interface, it logs gorm's message to logrus.Logger.

type MySQLConfig

type MySQLConfig = mysql.Config

MySQLConfig is a configuration for MySQL, can be used to generate DSN by FormatDSN method.

type MySQLExtraConfig

type MySQLExtraConfig = xdbutils_mysql.MySQLExtraConfig

MySQLExtraConfig is an extra configuration for MySQL, can be used to generate extends given param by ToParams method.

type OrderByOption

type OrderByOption = xdbutils_orderby.OrderByOption

OrderByOption represents an option type for GenerateOrderByExpr's option, can be created by WithXXX functions.

func WithDefaultExpression

func WithDefaultExpression(defaultExpression string) OrderByOption

WithDefaultExpression creates an OrderByOption to specify the default order expression when generated result is empty, defaults to empty.

func WithOrderBySourceProcessor

func WithOrderBySourceProcessor(processor func(source string) (field string, asc bool)) OrderByOption

WithOrderBySourceProcessor creates an OrderByOption to specify the source processor for extracting field name and ascending flag from given source, defaults to use the "field asc" or "field desc" format (case-insensitive) to extract information.

func WithOrderBySourceSeparator

func WithOrderBySourceSeparator(separator string) OrderByOption

WithOrderBySourceSeparator creates an OrderByOption to specify the source order-by expression fields separator, defaults to ",".

func WithOrderByTargetProcessor

func WithOrderByTargetProcessor(processor func(destination string, asc bool) (target string)) OrderByOption

WithOrderByTargetProcessor creates an OrderByOption to specify the target processor for combining field name and ascending flag to target expression, defaults to generate the target with "destination ASC" or "destination DESC" format.

func WithOrderByTargetSeparator

func WithOrderByTargetSeparator(separator string) OrderByOption

WithOrderByTargetSeparator creates an OrderByOption to specify the target order-by expression fields separator, defaults to ", ".

type PostgreSQLConfig

type PostgreSQLConfig = xdbutils_postgres.PostgreSQLConfig

PostgreSQLConfig is a configuration for PostgreSQL, can be used to generate DSN by FormatDSN method.

type PropertyDict

type PropertyDict = xdbutils_orderby.PropertyDict

PropertyDict is used to store PropertyValue-s for data transfer object (dto) to entity's property mapping rule, is used in GenerateOrderByExpr.

type PropertyValue

type PropertyValue = xdbutils_orderby.PropertyValue

PropertyValue represents database single entity's property mapping rule, is used in GenerateOrderByExpr.

func NewPropertyValue

func NewPropertyValue(reverse bool, destinations ...string) *PropertyValue

NewPropertyValue creates a PropertyValue by given reverse and destinations, is used to describe database single entity's property mapping rule.

Here: 1. `destinations` represents mapping property destination list, use `property_name` directly for sql, use `returned_name.property_name` for cypher. 2. `reverse` represents the flag whether you need to revert the order or not.

type SQLiteConfig

type SQLiteConfig = xdbutils_sqlite.SQLiteConfig

SQLiteConfig is a configuration for SQLite, can be used to generate DSN by FormatDSN method.

type SQLiteDriverOption

type SQLiteDriverOption = xdbutils_sqlite.SQLiteDriverOption

SQLiteDriverOption represents an option type for NewSQLiteDriver's option, can be created by WithXXX functions.

func WithAggregatorRegisterer

func WithAggregatorRegisterer(name string, impl interface{}, pure bool) SQLiteDriverOption

WithAggregatorRegisterer creates an SQLiteDriverOption to specify the aggregator registerer for sqlite driver.

func WithAuthorizerRegisterer

func WithAuthorizerRegisterer(callback func(int, string, string, string) int) SQLiteDriverOption

WithAuthorizerRegisterer creates an SQLiteDriverOption to specify the authorizer registerer for sqlite driver.

func WithCollationRegisterer

func WithCollationRegisterer(name string, cmp func(string, string) int) SQLiteDriverOption

WithCollationRegisterer creates an SQLiteDriverOption to specify the collation registerer for sqlite driver.

func WithCommitHookRegisterer

func WithCommitHookRegisterer(callback func() int) SQLiteDriverOption

WithCommitHookRegisterer creates an SQLiteDriverOption to specify the commit hook registerer for sqlite driver.

func WithExtensions

func WithExtensions(extensions []string) SQLiteDriverOption

WithExtensions creates an SQLiteDriverOption to specify the extensions for sqlite driver.

func WithFuncRegisterer

func WithFuncRegisterer(name string, impl interface{}, pure bool) SQLiteDriverOption

WithFuncRegisterer creates an SQLiteDriverOption to specify the func registerer for sqlite driver.

func WithPreUpdateHookRegister

func WithPreUpdateHookRegister(callback func(interface{})) SQLiteDriverOption

WithPreUpdateHookRegister creates an SQLiteDriverOption to specify the pre-update hook registerer for sqlite driver.

func WithRollbackHookRegisterer

func WithRollbackHookRegisterer(callback func()) SQLiteDriverOption

WithRollbackHookRegisterer creates an SQLiteDriverOption to specify the rollback hook registerer for sqlite driver.

func WithSQLiteConnectionHooker

func WithSQLiteConnectionHooker(hooker func(interface{}) error) SQLiteDriverOption

WithSQLiteConnectionHooker creates an SQLiteDriverOption to specify the sqlite connection hooker for sqlite driver.

func WithUpdateHookRegisterer

func WithUpdateHookRegisterer(callback func(int, string, string, int64)) SQLiteDriverOption

WithUpdateHookRegisterer creates an SQLiteDriverOption to specify the update hook registerer for sqlite driver.

type SilenceLogger

type SilenceLogger struct{}

SilenceLogger represents a gorm's logger, used to hide all logs, including [info], [sql] and so on. Note that `gorm.DB.LogMode(false)` will only hide [sql] message.

func NewSilenceLogger

func NewSilenceLogger() *SilenceLogger

NewSilenceLogger creates a new SilenceLogger.

Example:

db, err := gorm.Open("mysql", dsn)
db.LogMode(false) // both true and false are ok
db.SetLogger(xgorm.NewSilenceLogger())

func (*SilenceLogger) Print

func (s *SilenceLogger) Print(...interface{})

Print implements gorm.logger interface, it does nothing for logging.

type StdLogger

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

StdLogger represents a gorm's logger, used to log gorm's executing message to logrus.StdLogger.

func NewStdLogger

func NewStdLogger(logger logrus.StdLogger, options ...LoggerOption) *StdLogger

NewStdLogger creates a new StdLogger using given logrus.StdLogger and LoggerOption-s.

Example:

db, err := gorm.Open("mysql", dsn)
db.LogMode(true) // must be true
l := log.Default()
db.SetLogger(xgorm.NewStdLogger(l))

func (*StdLogger) Print

func (l *StdLogger) Print(v ...interface{})

Print implements gorm.logger interface, it logs gorm's message to logrus.StdLogger.

Jump to

Keyboard shortcuts

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