Documentation
¶
Overview ¶
Package orm opens the application's database, MySQL or PostgreSQL, from the database configuration, and holds the dialect-aware query helpers (CSV-column filters, escaped LIKE searches, date buckets, batched deletes) that repositories need to run the same queries on both drivers. The default connection parameters pin the session time zone, which stored times and per-day statistics are in.
Index ¶
- Constants
- func CommaSeparatedContains(field string, values []string) func(db *gorm.DB) *gorm.DB
- func CommaSeparatedContainsCondition(db *gorm.DB, field string, values []string) (string, []any)
- func ConnectDatabase(m Mysql) (*gorm.DB, error)
- func ConnectMysql(m Mysql) (*gorm.DB, error)
- func ContainsLike(fields []string, value string) func(db *gorm.DB) *gorm.DB
- func DateBucketExpr(db *gorm.DB, column, bucket string) string
- func DefaultMySQLQuery(location string) string
- func DefaultPostgresQuery(location string) string
- func DeleteBefore(ctx context.Context, rows BatchDeleter, before time.Time, batchSize int) (int64, error)
- func LikeContainsPattern(value string) string
- func LikeEscape(value string) string
- func LikeEscapeClause() string
- func LikePrefixPattern(value string) string
- func NormalizeDriver(driver string) string
- func PrefixLike(fields []string, value string) func(db *gorm.DB) *gorm.DB
- type BatchDeleter
- type Config
- type Mysql
Constants ¶
const ( // DriverMySQL and DriverPostgres are the drivers NormalizeDriver // returns; DriverPostgres2 is the other spelling it accepts for // PostgreSQL, the scheme of postgresql:// DSNs. DriverMySQL = "mysql" DriverPostgres = "postgres" DriverPostgres2 = "postgresql" // DefaultLocation is the time zone the default connection parameters // use when the caller names none. DefaultLocation = "Asia/Shanghai" // DefaultMySQLConfig is the default MySQL connection parameters for // DefaultLocation, the value DefaultMySQLQuery returns for it. DefaultMySQLConfig = "charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai&interpolateParams=true" // DefaultSlowThresholdMs, DefaultConnMaxLifetimeSeconds and // DefaultConnMaxIdleTimeSeconds are the slow-query and pool settings of // a configuration built in code, the same as Config's default tags. DefaultSlowThresholdMs = 1000 DefaultConnMaxLifetimeSeconds = 1800 DefaultConnMaxIdleTimeSeconds = 300 )
const DefaultPostgresSSLMode = "prefer"
DefaultPostgresSSLMode is the sslmode of the default PostgreSQL parameters: the connection is encrypted when the server offers TLS and falls back to plaintext when it does not, so a server without a certificate still works. It does not verify the server; deployments that reach the database over a network should set sslmode=verify-full in the parameters. Configurations written before this default keep their sslmode=disable.
Variables ¶
This section is empty.
Functions ¶
func CommaSeparatedContains ¶ added in v1.2.13
CommaSeparatedContains filters comma-separated string columns, such as "1,2,3".
func CommaSeparatedContainsCondition ¶ added in v1.19.0
CommaSeparatedContainsCondition returns the dialect-aware SQL fragment used when multiple CSV predicates must be combined in one surrounding OR query.
func ConnectDatabase ¶ added in v1.2.12
ConnectDatabase opens the connection pool m describes, with the application's GORM configuration.
func ContainsLike ¶ added in v1.2.13
ContainsLike is a GORM scope keeping the rows where one of fields contains value; a blank value keeps every row.
func DateBucketExpr ¶ added in v1.15.3
DateBucketExpr renders the dialect-specific SQL that buckets a timestamp column by day or by month ("YYYY-MM-DD" / "YYYY-MM"), for GROUP BY statistics queries.
func DefaultMySQLQuery ¶ added in v1.21.0
DefaultMySQLQuery returns the default MySQL connection parameters, reading DATETIME values in location (DefaultLocation when empty).
func DefaultPostgresQuery ¶ added in v1.21.0
DefaultPostgresQuery returns the default PostgreSQL connection parameters, with the session time zone set to location (DefaultLocation when empty). The zone's slashes stay visible; see encodePostgresParams.
func DeleteBefore ¶ added in v1.21.0
func DeleteBefore(ctx context.Context, rows BatchDeleter, before time.Time, batchSize int) (int64, error)
DeleteBefore deletes the rows older than before batch by batch, so a large backlog never runs as one long statement holding its locks, and returns how many rows it deleted, including those of the batches before a failure. batchSize must be positive.
func LikeContainsPattern ¶ added in v1.2.13
LikeContainsPattern returns the escaped LIKE pattern matching values that contain value, or "" for a blank value.
func LikeEscape ¶ added in v1.21.0
LikeEscape escapes value for use inside a LIKE pattern paired with LikeEscapeClause.
func LikeEscapeClause ¶ added in v1.2.15
func LikeEscapeClause() string
LikeEscapeClause is the ESCAPE clause of the patterns built here. They escape with '=' rather than the backslash, which MySQL and PostgreSQL quote differently in a string literal.
func LikePrefixPattern ¶ added in v1.2.13
LikePrefixPattern returns the escaped LIKE pattern matching values that start with value, or "" for a blank value.
func NormalizeDriver ¶ added in v1.2.12
NormalizeDriver maps the driver names a configuration or DSN may use onto DriverMySQL (the default, for an empty name) or DriverPostgres; an unknown name is returned lowercased, for the caller to reject.
Types ¶
type BatchDeleter ¶ added in v1.21.0
type BatchDeleter interface {
DeleteBeforeBatch(ctx context.Context, before time.Time, limit int) (int64, error)
}
BatchDeleter deletes up to limit rows older than before per call and reports how many it deleted.
type Config ¶
type Config struct {
Driver string `yaml:"Driver" default:"mysql"`
Addr string `yaml:"Addr"`
Username string `yaml:"Username"`
Password string `yaml:"Password"`
Dbname string `yaml:"Dbname"`
Config string `yaml:"Config" default:"charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai&interpolateParams=true"`
MaxIdleConns int `yaml:"MaxIdleConns" default:"10"`
MaxOpenConns int `yaml:"MaxOpenConns" default:"10"`
ConnMaxLifetime int64 `yaml:"ConnMaxLifetime" default:"1800"`
ConnMaxIdleTime int64 `yaml:"ConnMaxIdleTime" default:"300"`
SlowThreshold int64 `yaml:"SlowThreshold" default:"1000"`
}
Config is the database configuration (the Database section).
func ParseDSN ¶
ParseDSN parses a MySQL or URL-form DSN with the default parameters for DefaultLocation; it is ParseDSNIn(dsn, "").
func ParseDSNIn ¶ added in v1.21.0
ParseDSNIn parses a MySQL or URL-form DSN. A DSN without parameters gets the default ones for location (DefaultLocation when empty). It returns nil for a DSN it cannot parse.
type Mysql ¶
type Mysql struct {
Config Config
// Location is the IANA time zone of the default connection parameters,
// used when Config.Config is empty or, for PostgreSQL, still a MySQL
// default, and the session zone of PostgreSQL parameters that name none.
// Empty keeps DefaultLocation.
Location string
}
Mysql is a database connection to open, of either driver despite its name.
func (Mysql) Dsn ¶
Dsn returns the DSN the driver connects with, with the default parameters filled in.
func (*Mysql) GetSlowThreshold ¶
GetSlowThreshold returns the duration from which a query is logged as slow.
func (Mysql) MigrationDsn ¶ added in v1.2.12
MigrationDsn returns the DSN the schema migrations connect with. For MySQL the user name and password are URL-escaped: golang-migrate's mysql driver unescapes both (a compatibility remnant of when it parsed the DSN with net/url), so a password with %, + or @ handed over as is would be altered. The PostgreSQL DSN is a URL already, with escaped credentials.
func (Mysql) SessionLocation ¶ added in v1.21.0
SessionLocation reports the time zone the connection stores and reads timestamps in: the loc parameter for MySQL (the driver's UTC when custom parameters name none, the process zone's name for "Local"), the TimeZone parameter for PostgreSQL (Location's zone when custom parameters name none, since postgresDsn adds it), and the default parameters' zone otherwise. It is "" only for parameters that do not parse. Stored times and per-day statistics are in this zone.