Skip to content

Commit 7b5b4c7

Browse files
committed
feat: add traces on migrations
1 parent 1119816 commit 7b5b4c7

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

migrations/migrator.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import (
44
"context"
55
"errors"
66
"fmt"
7+
"go.opentelemetry.io/otel/attribute"
8+
"go.opentelemetry.io/otel/trace"
9+
"go.opentelemetry.io/otel/trace/noop"
710
"math"
811
"strconv"
912
"strings"
@@ -42,6 +45,7 @@ type Migrator struct {
4245
schema string
4346
tableName string
4447
rootDB bun.IDB
48+
tracer trace.Tracer
4549
}
4650

4751
func (m *Migrator) GetSchema() string {
@@ -160,6 +164,11 @@ func (m *Migrator) GetLastVersion(ctx context.Context) (int, error) {
160164
}
161165

162166
func (m *Migrator) Up(ctx context.Context) error {
167+
ctx, span := m.tracer.Start(ctx, "migrations.Up")
168+
defer span.End()
169+
170+
span.SetAttributes(attribute.String("schema", m.GetSchema()))
171+
163172
for {
164173
err := m.UpByOne(ctx)
165174
if err != nil {
@@ -414,15 +423,26 @@ func (m *Migrator) upByOne(ctx context.Context, db bun.IDB) error {
414423
}
415424

416425
func (m *Migrator) UpByOne(ctx context.Context) error {
417-
return m.upByOne(ctx, m.rootDB)
426+
ctx, span := m.tracer.Start(ctx, "migrations.UpByOne")
427+
defer span.End()
428+
429+
span.SetAttributes(attribute.String("schema", m.GetSchema()))
430+
431+
err := m.upByOne(ctx, m.rootDB)
432+
if err != nil && !errors.Is(err, ErrAlreadyUpToDate) {
433+
span.RecordError(err)
434+
return err
435+
}
436+
437+
return err
418438
}
419439

420440
func NewMigrator(db bun.IDB, opts ...Option) *Migrator {
421441
ret := &Migrator{
422442
rootDB: db,
423443
tableName: migrationTable,
424444
}
425-
for _, opt := range opts {
445+
for _, opt := range append(defaultOptions, opts...) {
426446
opt(ret)
427447
}
428448
return ret
@@ -441,3 +461,13 @@ func WithTableName(name string) Option {
441461
m.tableName = name
442462
}
443463
}
464+
465+
func WithTracer(tracer trace.Tracer) Option {
466+
return func(m *Migrator) {
467+
m.tracer = tracer
468+
}
469+
}
470+
471+
var defaultOptions = []Option{
472+
WithTracer(noop.Tracer{}),
473+
}

0 commit comments

Comments
 (0)