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 ForceRegisterSQLDriver(name string, driver driver.Driver)
- func ForceUnregisterSQLDriver(name string)
- func GenerateOrderByExpr(querySource string, dict PropertyDict, options ...OrderByOption) string
- func GetSQLDriver(name string) driver.Driver
- 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 IsPostgreSQLUniqueViolationError(err error) bool
- func IsSQLite(db *gorm.DB) bool
- func IsSQLiteUniqueConstraintError(err error) bool
- func MySQLDefaultDsn(username, password, address, database string) string
- func NewSQLiteDriver(options ...SQLiteDriverOption) *sqlite3.SQLiteDriver
- 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 ILogger
- type LoggerOption
- type LoggerParam
- type LogrusLogger
- type MySQLConfig
- type MySQLExtraConfig
- type OrderByOption
- func WithDefaultExpression(defaultExpression string) 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 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 WithExtensions(extensions []string) SQLiteDriverOption
- func WithFuncRegisterer(name string, impl interface{}, pure bool) SQLiteDriverOption
- func WithPreUpdateHookRegister(callback func(interface{})) SQLiteDriverOption
- func WithRollbackHookRegisterer(callback func()) SQLiteDriverOption
- func WithSQLiteConnectionHooker(hooker func(interface{}) error) SQLiteDriverOption
- func WithUpdateHookRegisterer(callback func(int, string, string, int64)) SQLiteDriverOption
- type SilenceLogger
- type StdLogger
Constants ¶
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" )
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_query" )
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/xgorm package's name. NAME = "ahlib-mx/xgorm" // VERSION represents ahlib-mx/xgorm 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 )
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 ForceRegisterSQLDriver ¶
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 ¶
GetSQLDriver gets registered driver.Driver by given name, returns nil if unregistered.
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 IsPostgreSQLUniqueViolationError ¶
IsPostgreSQLUniqueViolationError checks whether err is PostgreSQL's unique_violation error, whose error code is PostgreSQLUniqueViolationErrno.
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 NewSQLiteDriver ¶
func NewSQLiteDriver(options ...SQLiteDriverOption) *sqlite3.SQLiteDriver
NewSQLiteDriver creates sqlite3.SQLiteDriver with extensions and connect hooks, based on given SQLiteDriverOption-s.
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 *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 ¶
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 ¶
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 ¶
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))