Documentation
¶
Overview ¶
Package gorm encapsulates the tRPC plugin in GORM.
Package gorm is a generated GoMock package.
Index ¶
- Variables
- type Client
- func (gc *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (gorm.ConnPool, error)
- func (gc *Client) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (gc *Client) GetDBConn() (*sql.DB, error)
- func (gc *Client) Ping() error
- func (gc *Client) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
- func (gc *Client) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (gc *Client) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
- type ClientCodec
- type ClientTransport
- type Config
- type ConnPool
- type MockLogger
- func (m *MockLogger) Debug(arg0 ...interface{})
- func (m *MockLogger) Debugf(arg0 string, arg1 ...interface{})
- func (m *MockLogger) EXPECT() *MockLoggerMockRecorder
- func (m *MockLogger) Error(arg0 ...interface{})
- func (m *MockLogger) Errorf(arg0 string, arg1 ...interface{})
- func (m *MockLogger) Fatal(arg0 ...interface{})
- func (m *MockLogger) Fatalf(arg0 string, arg1 ...interface{})
- func (m *MockLogger) GetLevel(arg0 string) log.Level
- func (m *MockLogger) Info(arg0 ...interface{})
- func (m *MockLogger) Infof(arg0 string, arg1 ...interface{})
- func (m *MockLogger) SetLevel(arg0 string, arg1 log.Level)
- func (m *MockLogger) Sync() error
- func (m *MockLogger) Trace(arg0 ...interface{})
- func (m *MockLogger) Tracef(arg0 string, arg1 ...interface{})
- func (m *MockLogger) Warn(arg0 ...interface{})
- func (m *MockLogger) Warnf(arg0 string, arg1 ...interface{})
- func (m *MockLogger) With(arg0 ...log.Field) log.Logger
- func (m *MockLogger) WithFields(arg0 ...string) log.Logger
- type MockLoggerMockRecorder
- func (mr *MockLoggerMockRecorder) Debug(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Debugf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Error(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Errorf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Fatal(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Fatalf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) GetLevel(arg0 interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Info(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Infof(arg0 interface{}, arg1 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) SetLevel(arg0, arg1 interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Sync() *gomock.Call
- func (mr *MockLoggerMockRecorder) Trace(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Tracef(arg0 interface{}, arg1 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Warn(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) Warnf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) With(arg0 ...interface{}) *gomock.Call
- func (mr *MockLoggerMockRecorder) WithFields(arg0 ...interface{}) *gomock.Call
- type OpEnum
- type Plugin
- type PoolConfig
- type Request
- type Response
- type TRPCLogger
- func (p *TRPCLogger) Error(ctx context.Context, format string, args ...interface{})
- func (p *TRPCLogger) Info(ctx context.Context, format string, args ...interface{})
- func (p *TRPCLogger) LogMode(level logger.LogLevel) logger.Interface
- func (p *TRPCLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
- func (p *TRPCLogger) Warn(ctx context.Context, format string, args ...interface{})
- type TxClient
- func (txgc *TxClient) Commit() error
- func (txgc *TxClient) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (txgc *TxClient) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
- func (txgc *TxClient) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (txgc *TxClient) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
- func (txgc *TxClient) Rollback() error
Constants ¶
This section is empty.
Variables ¶
var (
DefaultClientCodec = &ClientCodec{}
)
default codec
var DefaultTRPCLogger = NewTRPCLogger(logger.Config{ LogLevel: logger.Warn, IgnoreRecordNotFoundError: true, })
DefaultTRPCLogger is the GORM logger that connects to trpc-log/log.
var NewClientProxy = func(name string, opts ...client.Option) (*gorm.DB, error) { connPool := NewConnPool(name, opts...) splitServiceName := strings.Split(name, ".") if len(splitServiceName) < 2 { return gorm.Open( mysql.New( mysql.Config{ Conn: connPool, }), &gorm.Config{ Logger: getLogger(name), }) } dbEngineType := splitServiceName[1] switch dbEngineType { case "postgres": return gorm.Open( postgres.New( postgres.Config{ PreferSimpleProtocol: true, Conn: connPool, }), &gorm.Config{ Logger: getLogger(name), }) default: return gorm.Open( mysql.New( mysql.Config{ Conn: connPool, }), &gorm.Config{ Logger: getLogger(name), }, ) } }
NewClientProxy generates a gorm.DB that can connect to a specified location and send all requests through tRPC.
var NewConnPool = func(name string, opts ...client.Option) ConnPool { c := &Client{ ServiceName: name, Client: client.DefaultClient, } c.opts = make([]client.Option, 0, len(opts)+3) c.opts = append(c.opts, opts...) c.opts = append(c.opts, client.WithProtocol("gorm"), client.WithDisableServiceRouter(), client.WithTimeout(0), ) return c }
NewConnPool generates a ConnPool that sends all requests through tRPC. This ConnPool can be used as a parameter to generate gorm.DB, making it easier to adjust other configurations of GORM.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct { ServiceName string Client client.Client // contains filtered or unexported fields }
Client encapsulates the tRPC client and implements the ConnPoolBeginner interface.
func (*Client) ExecContext ¶
func (gc *Client) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
ExecContext implements the ConnPool.ExecContext method.
func (*Client) PrepareContext ¶
PrepareContext implements the ConnPool.PrepareContext method.
type ClientCodec ¶
type ClientCodec struct{}
ClientCodec decodes db client requests.
type ClientTransport ¶
type ClientTransport struct { SQLDB map[string]*sql.DB SQLDBLock sync.RWMutex DefaultPoolConfig PoolConfig PoolConfigs map[string]PoolConfig // contains filtered or unexported fields }
ClientTransport is a struct that implements the trpc ClientTransport interface and is responsible for sending requests.
func NewClientTransport ¶
func NewClientTransport(opt ...transport.ClientTransportOption) *ClientTransport
NewClientTransport creates transport.
func (*ClientTransport) GetDB ¶
func (ct *ClientTransport) GetDB(serviceName, dsn string) (*sql.DB, error)
GetDB retrieves the database connection, currently supports mysql/clickhouse, can be extended for other types of databases.
func (*ClientTransport) RoundTrip ¶
func (ct *ClientTransport) RoundTrip(ctx context.Context, reqBuf []byte, callOpts ...transport.RoundTripOption) (rspBuf []byte, err error)
RoundTrip sends a SQL request and handles the SQL response.
type Config ¶
type Config struct { MaxIdle int `yaml:"max_idle"` // Maximum number of idle connections. MaxOpen int `yaml:"max_open"` // Maximum number of connections that can be open at same time. MaxLifetime int `yaml:"max_lifetime"` // The maximum lifetime of each connection, in milliseconds. Logger *loggerConfig `yaml:"logger"` // Logger configuration. Service []struct { // In the case of having multiple database connections, // you can configure the connection pool independently. Name string MaxIdle int `yaml:"max_idle"` // Maximum number of idle connections. MaxOpen int `yaml:"max_open"` // Maximum number of connections that can be open at same time. MaxLifetime int `yaml:"max_lifetime"` // The maximum lifetime of each connection, in milliseconds. // The name of the custom driver used, which is empty by default. DriverName string `yaml:"driver_name"` Logger *loggerConfig `yaml:"logger"` // Logger configuration. } }
Config is the struct for the configuration of the SQL proxy.
type ConnPool ¶
type ConnPool interface { PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row // BeginTx implements ConnPoolBeginner. BeginTx(ctx context.Context, opts *sql.TxOptions) (gorm.ConnPool, error) // Ping implements pinger. Ping() error // GetDBConn implements GetDBConnector. GetDBConn() (*sql.DB, error) }
ConnPool implements the gorm.ConnPool interface as well as transaction and Ping functionality.
type MockLogger ¶
type MockLogger struct {
// contains filtered or unexported fields
}
MockLogger is a mock of Logger interface.
func NewMockLogger ¶
func NewMockLogger(ctrl *gomock.Controller) *MockLogger
NewMockLogger creates a new mock instance.
func (*MockLogger) Debugf ¶
func (m *MockLogger) Debugf(arg0 string, arg1 ...interface{})
Debugf mocks base method.
func (*MockLogger) EXPECT ¶
func (m *MockLogger) EXPECT() *MockLoggerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
func (*MockLogger) Errorf ¶
func (m *MockLogger) Errorf(arg0 string, arg1 ...interface{})
Errorf mocks base method.
func (*MockLogger) Fatalf ¶
func (m *MockLogger) Fatalf(arg0 string, arg1 ...interface{})
Fatalf mocks base method.
func (*MockLogger) GetLevel ¶
func (m *MockLogger) GetLevel(arg0 string) log.Level
GetLevel mocks base method.
func (*MockLogger) Infof ¶
func (m *MockLogger) Infof(arg0 string, arg1 ...interface{})
Infof mocks base method.
func (*MockLogger) SetLevel ¶
func (m *MockLogger) SetLevel(arg0 string, arg1 log.Level)
SetLevel mocks base method.
func (*MockLogger) Tracef ¶
func (m *MockLogger) Tracef(arg0 string, arg1 ...interface{})
Tracef mocks base method.
func (*MockLogger) Warnf ¶
func (m *MockLogger) Warnf(arg0 string, arg1 ...interface{})
Warnf mocks base method.
func (*MockLogger) With ¶
func (m *MockLogger) With(arg0 ...log.Field) log.Logger
With mocks base method.
func (*MockLogger) WithFields ¶
func (m *MockLogger) WithFields(arg0 ...string) log.Logger
WithFields mocks base method.
type MockLoggerMockRecorder ¶
type MockLoggerMockRecorder struct {
// contains filtered or unexported fields
}
MockLoggerMockRecorder is the mock recorder for MockLogger.
func (*MockLoggerMockRecorder) Debug ¶
func (mr *MockLoggerMockRecorder) Debug(arg0 ...interface{}) *gomock.Call
Debug indicates an expected call of Debug.
func (*MockLoggerMockRecorder) Debugf ¶
func (mr *MockLoggerMockRecorder) Debugf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
Debugf indicates an expected call of Debugf.
func (*MockLoggerMockRecorder) Error ¶
func (mr *MockLoggerMockRecorder) Error(arg0 ...interface{}) *gomock.Call
Error indicates an expected call of Error.
func (*MockLoggerMockRecorder) Errorf ¶
func (mr *MockLoggerMockRecorder) Errorf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
Errorf indicates an expected call of Errorf.
func (*MockLoggerMockRecorder) Fatal ¶
func (mr *MockLoggerMockRecorder) Fatal(arg0 ...interface{}) *gomock.Call
Fatal indicates an expected call of Fatal.
func (*MockLoggerMockRecorder) Fatalf ¶
func (mr *MockLoggerMockRecorder) Fatalf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
Fatalf indicates an expected call of Fatalf.
func (*MockLoggerMockRecorder) GetLevel ¶
func (mr *MockLoggerMockRecorder) GetLevel(arg0 interface{}) *gomock.Call
GetLevel indicates an expected call of GetLevel.
func (*MockLoggerMockRecorder) Info ¶
func (mr *MockLoggerMockRecorder) Info(arg0 ...interface{}) *gomock.Call
Info indicates an expected call of Info.
func (*MockLoggerMockRecorder) Infof ¶
func (mr *MockLoggerMockRecorder) Infof(arg0 interface{}, arg1 ...interface{}) *gomock.Call
Infof indicates an expected call of Infof.
func (*MockLoggerMockRecorder) SetLevel ¶
func (mr *MockLoggerMockRecorder) SetLevel(arg0, arg1 interface{}) *gomock.Call
SetLevel indicates an expected call of SetLevel.
func (*MockLoggerMockRecorder) Sync ¶
func (mr *MockLoggerMockRecorder) Sync() *gomock.Call
Sync indicates an expected call of Sync.
func (*MockLoggerMockRecorder) Trace ¶
func (mr *MockLoggerMockRecorder) Trace(arg0 ...interface{}) *gomock.Call
Trace indicates an expected call of Trace.
func (*MockLoggerMockRecorder) Tracef ¶
func (mr *MockLoggerMockRecorder) Tracef(arg0 interface{}, arg1 ...interface{}) *gomock.Call
Tracef indicates an expected call of Tracef.
func (*MockLoggerMockRecorder) Warn ¶
func (mr *MockLoggerMockRecorder) Warn(arg0 ...interface{}) *gomock.Call
Warn indicates an expected call of Warn.
func (*MockLoggerMockRecorder) Warnf ¶
func (mr *MockLoggerMockRecorder) Warnf(arg0 interface{}, arg1 ...interface{}) *gomock.Call
Warnf indicates an expected call of Warnf.
func (*MockLoggerMockRecorder) With ¶
func (mr *MockLoggerMockRecorder) With(arg0 ...interface{}) *gomock.Call
With indicates an expected call of With.
func (*MockLoggerMockRecorder) WithFields ¶
func (mr *MockLoggerMockRecorder) WithFields(arg0 ...interface{}) *gomock.Call
WithFields indicates an expected call of WithFields.
type OpEnum ¶
type OpEnum int
OpEnum is the database operation enumeration type.
type Plugin ¶
type Plugin struct{}
Plugin used to load the configuration of sql.DB connection parameters.
type PoolConfig ¶
PoolConfig is the configuration of the database connection pool.
type Request ¶
type Request struct { // Op is the type of database operation performed. Op OpEnum Query string Args []interface{} Tx *sql.Tx TxOptions *sql.TxOptions }
Request is the request passed to the tRPC framework.
type Response ¶
type Response struct { Result sql.Result Stmt *sql.Stmt Row *sql.Row Rows *sql.Rows Tx *sql.Tx DB *sql.DB }
Response is the result returned by the tRPC framework.
type TRPCLogger ¶
type TRPCLogger struct {
// contains filtered or unexported fields
}
TRPCLogger implements the Gorm logger.Interface.
func NewTRPCLogger ¶
func NewTRPCLogger(config logger.Config) *TRPCLogger
NewTRPCLogger creates a TRPCLogger based on the configuration parameters.
func (*TRPCLogger) Error ¶
func (p *TRPCLogger) Error(ctx context.Context, format string, args ...interface{})
Error prints logs at the Error level.
func (*TRPCLogger) Info ¶
func (p *TRPCLogger) Info(ctx context.Context, format string, args ...interface{})
Info prints logs at the Info level.
func (*TRPCLogger) LogMode ¶
func (p *TRPCLogger) LogMode(level logger.LogLevel) logger.Interface
LogMode changes the log level and returns a new TRPCLogger.
type TxClient ¶
TxClient is the TRPC client with a transaction opened, and it implements the TxCommitter interface. The reason for separating the implementation of Client and TxClient
is that GORM defines two interfaces to support transaction operations: 1. ConnPoolBeginner: including the method for opening transactions using BeginTx, corresponding to the Client object of this plugin. 2. TxCommitter: including the methods for committing and rolling back transactions using Commit and Rollback, corresponding to the TxClient object of this plugin.
These two interfaces correspond to two types of connection pools,
before and after opening transactions, which cannot be mixed.
For example, under the GORM automatic transaction mechanism (SkipDefaultTransaction=false),
for operations such as Create and Delete, if the connection pool has implemented the 'ConnPoolBeginner' interface, it will automatically open a transaction. If the current connection itself has already opened a transaction, it will cause an exception of 'lock wait timeout exceeded' due to the duplicate opening of the transaction, as detailed in the GORM.DB.Begin method.
Therefore, after opening a transaction,
you need to convert the Client object to a connection object that has not implemented the 'ConnPoolBeginner' interface: TxClient.
The calling logic is:
- Use Client before opening a transaction. At this time, the Client implements the ConnPoolBeginner interface and can call BeginTx to open a transaction.
- Call Client.BeginTx to open a transaction and return TxClient.
func (*TxClient) ExecContext ¶
func (txgc *TxClient) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
ExecContext implements the ConnPool.ExecContext method.
func (*TxClient) PrepareContext ¶
PrepareContext implements the ConnPool.PrepareContext method.
func (*TxClient) QueryContext ¶
func (txgc *TxClient) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryContext implements the ConnPool.QueryContext method.