github.com/gogf/gf@v1.16.9/database/gdb/gdb_core_config.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gdb
     8  
     9  import (
    10  	"fmt"
    11  	"github.com/gogf/gf/os/glog"
    12  	"sync"
    13  	"time"
    14  
    15  	"github.com/gogf/gf/os/gcache"
    16  )
    17  
    18  // Config is the configuration management object.
    19  type Config map[string]ConfigGroup
    20  
    21  // ConfigGroup is a slice of configuration node for specified named group.
    22  type ConfigGroup []ConfigNode
    23  
    24  // ConfigNode is configuration for one node.
    25  type ConfigNode struct {
    26  	Host                 string        `json:"host"`                 // Host of server, ip or domain like: 127.0.0.1, localhost
    27  	Port                 string        `json:"port"`                 // Port, it's commonly 3306.
    28  	User                 string        `json:"user"`                 // Authentication username.
    29  	Pass                 string        `json:"pass"`                 // Authentication password.
    30  	Name                 string        `json:"name"`                 // Default used database name.
    31  	Type                 string        `json:"type"`                 // Database type: mysql, sqlite, mssql, pgsql, oracle.
    32  	Link                 string        `json:"link"`                 // (Optional) Custom link information, when it is used, configuration Host/Port/User/Pass/Name are ignored.
    33  	Role                 string        `json:"role"`                 // (Optional, "master" in default) Node role, used for master-slave mode: master, slave.
    34  	Debug                bool          `json:"debug"`                // (Optional) Debug mode enables debug information logging and output.
    35  	Prefix               string        `json:"prefix"`               // (Optional) Table prefix.
    36  	DryRun               bool          `json:"dryRun"`               // (Optional) Dry run, which does SELECT but no INSERT/UPDATE/DELETE statements.
    37  	Weight               int           `json:"weight"`               // (Optional) Weight for load balance calculating, it's useless if there's just one node.
    38  	Charset              string        `json:"charset"`              // (Optional, "utf8mb4" in default) Custom charset when operating on database.
    39  	Timezone             string        `json:"timezone"`             // (Optional) Sets the time zone for displaying and interpreting time stamps.
    40  	MaxIdleConnCount     int           `json:"maxIdle"`              // (Optional) Max idle connection configuration for underlying connection pool.
    41  	MaxOpenConnCount     int           `json:"maxOpen"`              // (Optional) Max open connection configuration for underlying connection pool.
    42  	MaxConnLifeTime      time.Duration `json:"maxLifeTime"`          // (Optional) Max amount of time a connection may be idle before being closed.
    43  	QueryTimeout         time.Duration `json:"queryTimeout"`         // (Optional) Max query time for per dql.
    44  	ExecTimeout          time.Duration `json:"execTimeout"`          // (Optional) Max exec time for dml.
    45  	TranTimeout          time.Duration `json:"tranTimeout"`          // (Optional) Max exec time time for a transaction.
    46  	PrepareTimeout       time.Duration `json:"prepareTimeout"`       // (Optional) Max exec time time for prepare operation.
    47  	CreatedAt            string        `json:"createdAt"`            // (Optional) The filed name of table for automatic-filled created datetime.
    48  	UpdatedAt            string        `json:"updatedAt"`            // (Optional) The filed name of table for automatic-filled updated datetime.
    49  	DeletedAt            string        `json:"deletedAt"`            // (Optional) The filed name of table for automatic-filled updated datetime.
    50  	TimeMaintainDisabled bool          `json:"timeMaintainDisabled"` // (Optional) Disable the automatic time maintaining feature.
    51  	CtxStrict            bool          `json:"ctxStrict"`            // (Optional) Strictly require context input for all database operations.
    52  }
    53  
    54  const (
    55  	DefaultGroupName = "default" // Default group name.
    56  )
    57  
    58  // configs is internal used configuration object.
    59  var configs struct {
    60  	sync.RWMutex
    61  	config Config // All configurations.
    62  	group  string // Default configuration group.
    63  }
    64  
    65  func init() {
    66  	configs.config = make(Config)
    67  	configs.group = DefaultGroupName
    68  }
    69  
    70  // SetConfig sets the global configuration for package.
    71  // It will overwrite the old configuration of package.
    72  func SetConfig(config Config) {
    73  	defer instances.Clear()
    74  	configs.Lock()
    75  	defer configs.Unlock()
    76  	configs.config = config
    77  }
    78  
    79  // SetConfigGroup sets the configuration for given group.
    80  func SetConfigGroup(group string, nodes ConfigGroup) {
    81  	defer instances.Clear()
    82  	configs.Lock()
    83  	defer configs.Unlock()
    84  	configs.config[group] = nodes
    85  }
    86  
    87  // AddConfigNode adds one node configuration to configuration of given group.
    88  func AddConfigNode(group string, node ConfigNode) {
    89  	defer instances.Clear()
    90  	configs.Lock()
    91  	defer configs.Unlock()
    92  	configs.config[group] = append(configs.config[group], node)
    93  }
    94  
    95  // AddDefaultConfigNode adds one node configuration to configuration of default group.
    96  func AddDefaultConfigNode(node ConfigNode) {
    97  	AddConfigNode(DefaultGroupName, node)
    98  }
    99  
   100  // AddDefaultConfigGroup adds multiple node configurations to configuration of default group.
   101  func AddDefaultConfigGroup(nodes ConfigGroup) {
   102  	SetConfigGroup(DefaultGroupName, nodes)
   103  }
   104  
   105  // GetConfig retrieves and returns the configuration of given group.
   106  func GetConfig(group string) ConfigGroup {
   107  	configs.RLock()
   108  	defer configs.RUnlock()
   109  	return configs.config[group]
   110  }
   111  
   112  // SetDefaultGroup sets the group name for default configuration.
   113  func SetDefaultGroup(name string) {
   114  	defer instances.Clear()
   115  	configs.Lock()
   116  	defer configs.Unlock()
   117  	configs.group = name
   118  }
   119  
   120  // GetDefaultGroup returns the { name of default configuration.
   121  func GetDefaultGroup() string {
   122  	defer instances.Clear()
   123  	configs.RLock()
   124  	defer configs.RUnlock()
   125  	return configs.group
   126  }
   127  
   128  // IsConfigured checks and returns whether the database configured.
   129  // It returns true if any configuration exists.
   130  func IsConfigured() bool {
   131  	configs.RLock()
   132  	defer configs.RUnlock()
   133  	return len(configs.config) > 0
   134  }
   135  
   136  // SetLogger sets the logger for orm.
   137  func (c *Core) SetLogger(logger *glog.Logger) {
   138  	c.logger = logger
   139  }
   140  
   141  // GetLogger returns the (logger) of the orm.
   142  func (c *Core) GetLogger() *glog.Logger {
   143  	return c.logger
   144  }
   145  
   146  // SetMaxIdleConnCount sets the maximum number of connections in the idle
   147  // connection pool.
   148  //
   149  // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
   150  // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
   151  //
   152  // If n <= 0, no idle connections are retained.
   153  //
   154  // The default max idle connections is currently 2. This may change in
   155  // a future release.
   156  func (c *Core) SetMaxIdleConnCount(n int) {
   157  	c.config.MaxIdleConnCount = n
   158  }
   159  
   160  // SetMaxOpenConnCount sets the maximum number of open connections to the database.
   161  //
   162  // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
   163  // MaxIdleConns, then MaxIdleConns will be reduced to match the new
   164  // MaxOpenConns limit.
   165  //
   166  // If n <= 0, then there is no limit on the number of open connections.
   167  // The default is 0 (unlimited).
   168  func (c *Core) SetMaxOpenConnCount(n int) {
   169  	c.config.MaxOpenConnCount = n
   170  }
   171  
   172  // SetMaxConnLifeTime sets the maximum amount of time a connection may be reused.
   173  //
   174  // Expired connections may be closed lazily before reuse.
   175  //
   176  // If d <= 0, connections are not closed due to a connection's age.
   177  func (c *Core) SetMaxConnLifeTime(d time.Duration) {
   178  	c.config.MaxConnLifeTime = d
   179  }
   180  
   181  // String returns the node as string.
   182  func (node *ConfigNode) String() string {
   183  	return fmt.Sprintf(
   184  		`%s@%s:%s,%s,%s,%s,%s,%v,%d-%d-%d#%s`,
   185  		node.User, node.Host, node.Port,
   186  		node.Name, node.Type, node.Role, node.Charset, node.Debug,
   187  		node.MaxIdleConnCount,
   188  		node.MaxOpenConnCount,
   189  		node.MaxConnLifeTime,
   190  		node.Link,
   191  	)
   192  }
   193  
   194  // GetConfig returns the current used node configuration.
   195  func (c *Core) GetConfig() *ConfigNode {
   196  	return c.config
   197  }
   198  
   199  // SetDebug enables/disables the debug mode.
   200  func (c *Core) SetDebug(debug bool) {
   201  	c.debug.Set(debug)
   202  }
   203  
   204  // GetDebug returns the debug value.
   205  func (c *Core) GetDebug() bool {
   206  	return c.debug.Val()
   207  }
   208  
   209  // GetCache returns the internal cache object.
   210  func (c *Core) GetCache() *gcache.Cache {
   211  	return c.cache
   212  }
   213  
   214  // GetGroup returns the group string configured.
   215  func (c *Core) GetGroup() string {
   216  	return c.group
   217  }
   218  
   219  // SetDryRun enables/disables the DryRun feature.
   220  // Deprecated, use GetConfig instead.
   221  func (c *Core) SetDryRun(enabled bool) {
   222  	c.config.DryRun = enabled
   223  }
   224  
   225  // GetDryRun returns the DryRun value.
   226  // Deprecated, use GetConfig instead.
   227  func (c *Core) GetDryRun() bool {
   228  	return c.config.DryRun || allDryRun
   229  }
   230  
   231  // GetPrefix returns the table prefix string configured.
   232  // Deprecated, use GetConfig instead.
   233  func (c *Core) GetPrefix() string {
   234  	return c.config.Prefix
   235  }
   236  
   237  // SetSchema changes the schema for this database connection object.
   238  // Importantly note that when schema configuration changed for the database,
   239  // it affects all operations on the database object in the future.
   240  func (c *Core) SetSchema(schema string) {
   241  	c.schema.Set(schema)
   242  }
   243  
   244  // GetSchema returns the schema configured.
   245  func (c *Core) GetSchema() string {
   246  	return c.schema.Val()
   247  }