Skip to main content

Database Plugin

Go-Lynx provides a database connection plugin, allowing us to connect to databases without worrying about writing the code for database connections. Simply provide the corresponding database configuration file, and the plugin will automatically initialize the database connection. Some configuration parameters are not yet complete (such as SSL encrypted communication, multiple data source configuration), and development is ongoing. Stay tuned for more updates.

Database Configuration

To specify a database, you need to configure it in the configuration file, which should look like this:

lynx:
db:
driver: mysql
source: root:123@tcp(127.0.0.1:3306)/demo?parseTime=True
min_conn: 50
max_conn: 50
max_idle_time: 30s

The lynx.db section contains the database configuration information. By default, it uses ent for database connections, but support for more ORM frameworks, such as gorm, will be added in the future.

After the configuration is complete, the application will load the database based on the plugin order upon startup.

How to obtain the Driver information for the database connection?

import (
"github.com/go-lynx/lynx/plugin/db"
)

var ProviderSet = wire.NewSet(
NewData,
db.GetDriver
)

type Data struct {
db *ent.Client
}

func NewData(dri *sql.Driver, logger log.Logger) (*Data, error) {
client := ent.NewClient(ent.Driver(dri), ent.Debug())

// Schema creation
if err := client.Schema.Create(context.Background()); err != nil {
dfLog := log.NewHelper(logger)
dfLog.Errorf("failed creating database schema resources: %v", err)
return nil, err
}

d := &Data{
db: client
}
return d, nil
}

We provide the db.GetDriver method, which retrieves the connection object information from the plugin. Combined with the wire framework to help generate method calls, you can fully utilize the database plugin as shown above.