File size: 1,337 Bytes
1c4c66b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | package adapter
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/openmeterio/openmeter/openmeter/billing/worker/subscriptionsync"
entdb "github.com/openmeterio/openmeter/openmeter/ent/db"
"github.com/openmeterio/openmeter/pkg/framework/entutils"
"github.com/openmeterio/openmeter/pkg/framework/transaction"
)
type Config struct {
Client *entdb.Client
}
func (c Config) Validate() error {
var errs []error
if c.Client == nil {
errs = append(errs, errors.New("client is required"))
}
return errors.Join(errs...)
}
type adapter struct {
db *entdb.Client
}
func New(config Config) (subscriptionsync.Adapter, error) {
if err := config.Validate(); err != nil {
return nil, err
}
return &adapter{
db: config.Client,
}, nil
}
func (a *adapter) Tx(ctx context.Context) (context.Context, transaction.Driver, error) {
txCtx, rawConfig, eDriver, err := a.db.HijackTx(ctx, &sql.TxOptions{
ReadOnly: false,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to hijack transaction: %w", err)
}
return txCtx, entutils.NewTxDriver(eDriver, rawConfig), nil
}
func (a *adapter) WithTx(ctx context.Context, tx *entutils.TxDriver) *adapter {
txDb := entdb.NewTxClientFromRawConfig(ctx, *tx.GetConfig())
return &adapter{
db: txDb.Client(),
}
}
func (a *adapter) Self() *adapter {
return a
}
|