github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/shared/driver/driver.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  // package driver implements a DB driver that can be used by plugins
     5  // to make SQL queries using RPC. This helps to avoid opening new connections
     6  // for every plugin, and lets everyone use the central connection
     7  // pool in the server.
     8  // The tests for this package are at app/plugin_api_tests/test_db_driver/main.go.
     9  package driver
    10  
    11  import (
    12  	"context"
    13  	"database/sql/driver"
    14  
    15  	"github.com/masterhung0112/hk_server/v5/plugin"
    16  )
    17  
    18  var (
    19  	// Compile-time check to ensure Connector implements the interface.
    20  	_ driver.Connector = &Connector{}
    21  )
    22  
    23  // Connector is the DB connector which is used to
    24  // communicate with the DB API.
    25  type Connector struct {
    26  	api      plugin.Driver
    27  	isMaster bool
    28  }
    29  
    30  // NewConnector returns a DB connector that can be used to return a sql.DB object.
    31  // It takes a plugin.Driver implementation and a boolean flag to indicate whether
    32  // to connect to a master or replica DB instance.
    33  func NewConnector(api plugin.Driver, isMaster bool) *Connector {
    34  	return &Connector{api: api, isMaster: isMaster}
    35  }
    36  
    37  func (c *Connector) Connect(_ context.Context) (driver.Conn, error) {
    38  	connID, err := c.api.Conn(c.isMaster)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  
    43  	return &Conn{id: connID, api: c.api}, nil
    44  }
    45  
    46  func (c *Connector) Driver() driver.Driver {
    47  	return &Driver{c: c}
    48  }
    49  
    50  // Driver is a DB driver implementation.
    51  type Driver struct {
    52  	c *Connector
    53  }
    54  
    55  func (d Driver) Open(name string) (driver.Conn, error) {
    56  	return d.c.Connect(context.Background())
    57  }