Documentation
¶
Index ¶
- Constants
- Variables
- func CreateErr(rdb *gorm.DB) (xstatus.DbStatus, error)
- func DeleteErr(rdb *gorm.DB) (xstatus.DbStatus, error)
- func DisableLogger()
- func EnableLogger()
- func GenerateOrderByExpr(querySource string, dict PropertyDict, options ...OrderByOption) string
- func HookDeletedAt(db *gorm.DB, defaultTimestamp string)
- func IsMySQL(db *gorm.DB) bool
- func IsMySQLDuplicateEntryError(err error) bool
- func IsPostgreSQL(db *gorm.DB) bool
- func IsRecordNotFound(err error) bool
- func IsSQLite(db *gorm.DB) bool
- func IsSQLiteUniqueConstraintError(err error) bool
- func MySQLDefaultDsn(username, password, address, database string) string
- func PostgreSQLDefaultDsn(username, password, host string, port int, database string) string
- func QueryErr(rdb *gorm.DB) (xstatus.DbStatus, error)
- func SQLiteDefaultDsn(file string) string
- func UpdateErr(rdb *gorm.DB) (xstatus.DbStatus, error)
- type GormTime
- type GormTime2
- type LoggerOption
- type LoggerParam
- type LogrusLogger
- func (l *LogrusLogger) Error(_ context.Context, msg string, data ...interface{})
- func (l *LogrusLogger) Info(_ context.Context, msg string, data ...interface{})
- func (l *LogrusLogger) LogMode(logger.LogLevel) logger.Interface
- func (l *LogrusLogger) Trace(_ context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), ...)
- func (l *LogrusLogger) Warn(_ context.Context, msg string, data ...interface{})
- type MySQLConfig
- type MySQLExtraConfig
- type OrderByOption
- func WithOrderBySourceProcessor(processor func(source string) (field string, asc bool)) OrderByOption
- func WithOrderBySourceSeparator(separator string) OrderByOption
- func WithOrderByTargetProcessor(processor func(destination string, asc bool) (target string)) OrderByOption
- func WithOrderByTargetSeparator(separator string) OrderByOption
- type PostgreSQLConfig
- type PropertyDict
- type PropertyValue
- type SQLiteConfig
- type SilenceLogger
- func (*SilenceLogger) Error(context.Context, string, ...interface{})
- func (*SilenceLogger) Info(context.Context, string, ...interface{})
- func (s *SilenceLogger) LogMode(logger.LogLevel) logger.Interface
- func (*SilenceLogger) Trace(context.Context, time.Time, func() (string, int64), error)
- func (*SilenceLogger) Warn(context.Context, string, ...interface{})
- type StdLogger
- func (l *StdLogger) Error(_ context.Context, msg string, data ...interface{})
- func (l *StdLogger) Info(_ context.Context, msg string, data ...interface{})
- func (l *StdLogger) LogMode(logger.LogLevel) logger.Interface
- func (l *StdLogger) Trace(_ context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), ...)
- func (l *StdLogger) Warn(_ context.Context, msg string, data ...interface{})
Constants ¶
const ( // MySQL represents the "mysql" dialect for gorm. Remember to use github.com/go-gorm/mysql to open a gorm.DB for MySQL. MySQL = "mysql" // SQLite represents the "sqlite" dialect for gorm. Remember to use github.com/go-gorm/sqlite to open a gorm.DB SQLite. SQLite = "sqlite" // Postgres represents the "postgres" dialect for gorm. Remember to use github.com/go-gorm/postgres to open a gorm.DB for PostgreSQL. Postgres = "postgres" )
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 )
const ( CreateCallbackName = "gorm:create" UpdateCallbackName = "gorm:update" DeleteCallbackName = "gorm:delete" QueryCallbackName = "gorm:query" RowQueryCallbackName = "gorm:row" )
Gorm's callback names. See gorm.Callback or visit https://github.com/jinzhu/gorm/blob/5c235b72a4/callback.go for more details.
const ( // NAME represents ahlib-mx/xgormv2 package's name. NAME = "ahlib-mx/xgormv2" // VERSION represents ahlib-mx/xgormv2 package's current version. VERSION = "1.6.0" )
const (
// DefaultDeletedAtTimestamp represents the default value in `gorm` tag of GormTime.DeletedAt.
DefaultDeletedAtTimestamp = "1970-01-01 00:00:01"
)
Variables ¶
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 )
var IsPostgreSQLUniqueViolationError func(err error) bool
IsPostgreSQLUniqueViolationError is a variable that used to check whether err is PostgreSQL's unique_violation error, whose error code is PostgreSQLUniqueViolationErrno.
You have to import "github.com/jackc/pgconn" and set this variable manually in order to make it be usable in CreateErr and UpdateErr.
xgormv2.IsPostgreSQLUniqueViolationError = func(err error) bool { perr, ok := err.(*pgconn.PgError) return ok && perr.Code == xgormv2.PostgreSQLUniqueViolationErrno }
Functions ¶
func CreateErr ¶
CreateErr checks gorm.DB after create operated, will only return xstatus.DbSuccess, xstatus.DbExisted and xstatus.DbFailed.
func DeleteErr ¶
DeleteErr checks gorm.DB after delete operated, will only return xstatus.DbSuccess, xstatus.DbNotFound and xstatus.DbFailed.
func EnableLogger ¶
func EnableLogger()
EnableLogger enables LogrusLogger and StdLogger to do any log.
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 HookDeletedAt ¶
HookDeletedAt hooks gorm.DB's callbacks to make soft deleting to use the new default deletedAt timestamp, such as DefaultDeletedAtTimestamp.
func IsMySQLDuplicateEntryError ¶
IsMySQLDuplicateEntryError checks whether err is MySQL's ER_DUP_ENTRY error, whose error code is MySQLDuplicateEntryErrno.
func IsPostgreSQL ¶
IsPostgreSQL checks whether the dialect of given gorm.DB is "postgres".
func IsRecordNotFound ¶
IsRecordNotFound checks whether given error from gorm.DB is gorm.ErrRecordNotFound.
func IsSQLiteUniqueConstraintError ¶
IsSQLiteUniqueConstraintError checks whether err is SQLite's ErrConstraintUnique error, whose extended code is SQLiteUniqueConstraintErrno.
func MySQLDefaultDsn ¶
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 PostgreSQLDefaultDsn ¶
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 ¶
QueryErr checks gorm.DB after query operated, will only return xstatus.DbSuccess, xstatus.DbNotFound and xstatus.DbFailed.
func SQLiteDefaultDsn ¶
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
Types ¶
type GormTime ¶
type GormTime struct { CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index; not null; 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 ¶
GormTime2 represents a structure of CreatedAt, UpdatedAt, which allow you to customize the DeletedAt field, is a replacement of gorm.Model.
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 [warn] and [erro]) 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:
l := logrus.New() l.SetFormatter(&logrus.TextFormatter{}) gorm.Open(..., &gorm.Config{ Logger: NewLogrusLogger(l), })
func (*LogrusLogger) Error ¶
func (l *LogrusLogger) Error(_ context.Context, msg string, data ...interface{})
Error implements logger.Interface for LogrusLogger.
func (*LogrusLogger) Info ¶
func (l *LogrusLogger) Info(_ context.Context, msg string, data ...interface{})
Info implements logger.Interface for LogrusLogger.
func (*LogrusLogger) LogMode ¶
func (l *LogrusLogger) LogMode(logger.LogLevel) logger.Interface
LogMode implements logger.Interface for LogrusLogger.
type MySQLConfig ¶
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 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 SilenceLogger ¶
type SilenceLogger struct{}
SilenceLogger represents a gorm's logger, used to hide all logs, including [info], [warn], [erro], [sql].
func NewSilenceLogger ¶
func NewSilenceLogger() *SilenceLogger
NewSilenceLogger creates a new SilenceLogger.
Example:
gorm.Open(..., &gorm.Config{ Logger: NewSilenceLogger(), })
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:
l := log.Default() gorm.Open(..., &gorm.Config{ Logger: NewStdLogger(l), })