2023-02-02 10:55:24 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-03-07 23:10:42 +01:00
|
|
|
func NewAgentRepository(ctx context.Context, conf config.DatabaseConfig) (datastore.AgentRepository, error) {
|
|
|
|
driver := string(conf.Driver)
|
|
|
|
dsn := string(conf.DSN)
|
2023-02-02 10:55:24 +01:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2023-10-22 09:50:22 +02:00
|
|
|
agentRepository = sqlite.NewAgentRepository(db, 5)
|
2023-02-02 10:55:24 +01:00
|
|
|
|
|
|
|
default:
|
|
|
|
return nil, errors.Errorf("unsupported database driver '%s'", driver)
|
|
|
|
}
|
|
|
|
|
|
|
|
return agentRepository, nil
|
|
|
|
}
|