The significance of the framework’s database component driver is that the various methods of upper-layer business operations with the database do not change, and you can switch to a new database by simply modifying the database type in the configuration.

We can achieve the design of interfaces in the database component to add third-party database drivers not supported by the framework by default or customize existing drivers. The development of a driver is not about fully developing a database protocol implementation code, but rather using an existing third-party database driver and integrating it with the framework’s database component by implementing its interface, ensuring consistency in upper-layer operations.

Driver Registration

We previously mentioned the Driver interface. After implementing this interface, we can register a custom driver to the gdb module through the following method:

  1. // Register registers custom database driver to gdb.
  2. func Register(name string, driver Driver) error

The driver name name can be an existing driver name, such as mysql, mssql, pgsql, etc. When a driver with the same name is registered, the new driver will overwrite the old one.

Driver Implementation

Developing a custom driver and registering it to the gdb module is very simple. You can refer to the database type code examples already connected in the gdb module source code: https://github.com/gogf/gf/tree/master/contrib/drivers

It should be noted that the most common way to develop or modify a driver is to directly inherit from the existing *Core type, as the Driver interface will pass this type of object, for example:

  1. // DriverMysql is the driver for mysql database.
  2. type DriverMysql struct {
  3. *Core
  4. }
  5. // New creates and returns a database object for mysql.
  6. // It implements the interface of gdb.Driver for extra database driver installation.
  7. func (d *DriverMysql) New(core *Core, node *ConfigNode) (DB, error) {
  8. return &DriverMysql{
  9. Core: core,
  10. }, nil
  11. }

Considerations

A new driver should at least implement the following interface methods:

Interface MethodDescription
OpenUsed to create a database connection.
GetCharsUsed to get the safety/escape symbols of the database.
TablesReturns the list of tables in the current/specified database.
TableFieldsReturns field list information for the specified table.