to options mode

This commit is contained in:
yanghao05
2023-04-27 18:30:39 +08:00
parent 8ae3d19aa9
commit 574736a878
20 changed files with 180 additions and 50 deletions

View File

@@ -4,6 +4,8 @@ import (
"fmt"
)
const DefaultPrefix = "MySQL"
// MySQL database config
type Config struct {
Host string

View File

@@ -4,15 +4,20 @@ import (
"database/sql"
"github.com/rogeecn/atom/container"
"github.com/rogeecn/atom/providers"
"github.com/rogeecn/atom/providers/log"
"go.uber.org/dig"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
func Provide(conf *Config, opts ...dig.ProvideOption) error {
func Provide(o *providers.Options) error {
var conf Config
if err := o.UnmarshalConfig(&conf); err != nil {
return err
}
return container.Container.Provide(func() (*gorm.DB, error) {
if err := createMySQLDatabase(conf.EmptyDsn(), "mysql", conf.CreateDatabaseSql()); err != nil {
return nil, err
@@ -53,7 +58,7 @@ func Provide(conf *Config, opts ...dig.ProvideOption) error {
sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
return db, err
}, opts...)
}, o.DiOptions()...)
}
// createDatabase 创建数据库

View File

@@ -4,6 +4,8 @@ import (
"fmt"
)
const DefaultPrefix = "Postgres"
type Config struct {
Username string
Password string

View File

@@ -4,14 +4,19 @@ import (
"log"
"github.com/rogeecn/atom/container"
"go.uber.org/dig"
"github.com/rogeecn/atom/providers"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
func Provide(conf *Config, opts ...dig.ProvideOption) error {
func Provide(o *providers.Options) error {
var conf Config
if err := o.UnmarshalConfig(&conf); err != nil {
return err
}
return container.Container.Provide(func() (*gorm.DB, error) {
dbConfig := postgres.Config{
DSN: conf.DSN(), // DSN data source name
@@ -36,5 +41,5 @@ func Provide(conf *Config, opts ...dig.ProvideOption) error {
sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
return db, err
}, opts...)
}, o.DiOptions()...)
}

View File

@@ -1,5 +1,7 @@
package sqlite
const DefaultPrefix = "SQLite"
type Config struct {
File string
}

View File

@@ -2,14 +2,19 @@ package sqlite
import (
"github.com/rogeecn/atom/container"
"go.uber.org/dig"
"github.com/rogeecn/atom/providers"
// "gorm.io/driver/sqlite"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func Provide(conf *Config, opts ...dig.ProvideOption) error {
func Provide(o *providers.Options) error {
var conf Config
if err := o.UnmarshalConfig(&conf); err != nil {
return err
}
return container.Container.Provide(func() (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open(conf.File), &gorm.Config{})
if err != nil {
@@ -17,5 +22,5 @@ func Provide(conf *Config, opts ...dig.ProvideOption) error {
}
return db, err
}, opts...)
}, o.DiOptions()...)
}