2021-10-27 18:49:33 +03:00
|
|
|
package wrapper
|
|
|
|
|
|
|
|
import (
|
2023-01-06 23:24:39 +03:00
|
|
|
"context"
|
2021-10-27 18:49:33 +03:00
|
|
|
"database/sql/driver"
|
2023-01-06 23:24:39 +03:00
|
|
|
"time"
|
2021-10-27 18:49:33 +03:00
|
|
|
|
2023-06-10 13:09:25 +03:00
|
|
|
"go.unistack.org/micro/v4/tracer"
|
2021-10-27 18:49:33 +03:00
|
|
|
)
|
|
|
|
|
2023-06-10 13:09:25 +03:00
|
|
|
var _ driver.Tx = (*wrapperTx)(nil)
|
2023-01-16 23:26:58 +03:00
|
|
|
|
2021-10-27 18:49:33 +03:00
|
|
|
// wrapperTx defines a wrapper for driver.Tx
|
|
|
|
type wrapperTx struct {
|
|
|
|
tx driver.Tx
|
|
|
|
span tracer.Span
|
|
|
|
opts Options
|
2023-01-16 23:26:58 +03:00
|
|
|
ctx context.Context
|
2021-10-27 18:49:33 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Commit implements driver.Tx Commit
|
|
|
|
func (w *wrapperTx) Commit() error {
|
2023-01-06 23:24:39 +03:00
|
|
|
ts := time.Now()
|
2023-01-05 16:03:21 +03:00
|
|
|
err := w.tx.Commit()
|
2023-01-06 23:24:39 +03:00
|
|
|
td := time.Since(ts)
|
|
|
|
|
2023-06-10 13:09:25 +03:00
|
|
|
if w.span != nil {
|
|
|
|
if err != nil {
|
2023-09-01 00:21:08 +03:00
|
|
|
w.span.SetStatus(tracer.SpanStatusError, err.Error())
|
2023-06-10 13:09:25 +03:00
|
|
|
}
|
|
|
|
w.span.Finish()
|
2023-01-16 15:19:30 +03:00
|
|
|
}
|
|
|
|
|
2023-06-10 13:09:25 +03:00
|
|
|
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
|
2023-09-01 00:21:08 +03:00
|
|
|
w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Commit", getCallerName(), td, err)).Log(w.ctx, w.opts.LoggerLevel)
|
2023-01-06 23:24:39 +03:00
|
|
|
}
|
|
|
|
|
2023-01-16 23:26:58 +03:00
|
|
|
w.ctx = nil
|
|
|
|
|
2023-01-05 16:03:21 +03:00
|
|
|
return err
|
2021-10-27 18:49:33 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Rollback implements driver.Tx Rollback
|
|
|
|
func (w *wrapperTx) Rollback() error {
|
2023-01-06 23:24:39 +03:00
|
|
|
ts := time.Now()
|
2023-01-05 16:03:21 +03:00
|
|
|
err := w.tx.Rollback()
|
2023-01-06 23:24:39 +03:00
|
|
|
td := time.Since(ts)
|
|
|
|
|
2023-06-10 13:09:25 +03:00
|
|
|
if w.span != nil {
|
|
|
|
if err != nil {
|
2023-09-01 00:21:08 +03:00
|
|
|
w.span.SetStatus(tracer.SpanStatusError, err.Error())
|
2023-06-10 13:09:25 +03:00
|
|
|
}
|
|
|
|
w.span.Finish()
|
2023-01-16 15:19:30 +03:00
|
|
|
}
|
|
|
|
|
2023-06-10 13:09:25 +03:00
|
|
|
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
|
2023-09-01 00:21:08 +03:00
|
|
|
w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Rollback", getCallerName(), td, err)).Log(w.ctx, w.opts.LoggerLevel)
|
2023-01-06 23:24:39 +03:00
|
|
|
}
|
|
|
|
|
2023-01-16 23:26:58 +03:00
|
|
|
w.ctx = nil
|
|
|
|
|
2023-01-05 16:03:21 +03:00
|
|
|
return err
|
2021-10-27 18:49:33 +03:00
|
|
|
}
|