emissary/internal/setup/repository.go

107 lines
2.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.DatabaseConfig) (datastore.AgentRepository, error) {
driver := string(conf.Driver)
dsn := string(conf.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, 5)
default:
return nil, errors.Errorf("unsupported database driver '%s'", driver)
}
return agentRepository, nil
}
func NewTenantRepository(ctx context.Context, conf config.DatabaseConfig) (datastore.TenantRepository, error) {
driver := string(conf.Driver)
dsn := string(conf.DSN)
var tenantRepository datastore.TenantRepository
logger.Debug(ctx, "initializing tenant 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)
}
tenantRepository = sqlite.NewTenantRepository(db, 5)
default:
return nil, errors.Errorf("unsupported database driver '%s'", driver)
}
return tenantRepository, nil
}