70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package setup
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"net/url"
|
|
"sync"
|
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/config"
|
|
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
|
|
"forge.cadoles.com/Cadoles/emissary/internal/datastore/sqlite"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/pkg/errors"
|
|
"gitlab.com/wpetit/goweb/logger"
|
|
)
|
|
|
|
var (
|
|
postgresPoolOnce sync.Once
|
|
postgresPoolErr error
|
|
postgresPool *pgxpool.Pool
|
|
)
|
|
|
|
func openPostgresPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
|
postgresPoolOnce.Do(func() {
|
|
postgresPool, postgresPoolErr = pgxpool.New(ctx, dsn)
|
|
})
|
|
if postgresPoolErr != nil {
|
|
return nil, errors.WithStack(postgresPoolErr)
|
|
}
|
|
|
|
return postgresPool, nil
|
|
}
|
|
|
|
func NewAgentRepository(ctx context.Context, conf *config.Config) (datastore.AgentRepository, error) {
|
|
driver := string(conf.Database.Driver)
|
|
dsn := string(conf.Database.DSN)
|
|
|
|
var agentRepository datastore.AgentRepository
|
|
|
|
logger.Debug(ctx, "initializing agent repository", logger.F("driver", driver), logger.F("dsn", dsn))
|
|
|
|
switch driver {
|
|
case config.DatabaseDriverPostgres:
|
|
// TODO
|
|
// pool, err := openPostgresPool(ctx, dsn)
|
|
// if err != nil {
|
|
// return nil, errors.WithStack(err)
|
|
// }
|
|
|
|
// entryRepository = postgres.NewEntryRepository(pool)
|
|
case config.DatabaseDriverSQLite:
|
|
url, err := url.Parse(dsn)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
db, err := sql.Open(driver, url.Host+url.Path)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
agentRepository = sqlite.NewAgentRepository(db)
|
|
|
|
default:
|
|
return nil, errors.Errorf("unsupported database driver '%s'", driver)
|
|
}
|
|
|
|
return agentRepository, nil
|
|
}
|