Files
crawlab/core/mongo/transaction.go
Marvin Zhang dc59599509 refactor: remove db module and update imports to core/mongo
- Deleted the db module, consolidating database-related functionality into the core/mongo package for better organization and maintainability.
- Updated all import paths across the codebase to replace references to the removed db module with core/mongo.
- Cleaned up unused code and dependencies, enhancing overall project clarity and reducing complexity.
- This refactor improves the structure of the codebase by centralizing database operations and simplifying module management.
2024-12-25 10:28:21 +08:00

46 lines
966 B
Go

package mongo
import (
"context"
"github.com/crawlab-team/crawlab/trace"
"go.mongodb.org/mongo-driver/mongo"
)
func RunTransaction(fn func(mongo.SessionContext) error) (err error) {
return RunTransactionWithContext(context.Background(), fn)
}
func RunTransactionWithContext(ctx context.Context, fn func(mongo.SessionContext) error) (err error) {
// default client
c, err := GetMongoClient()
if err != nil {
return err
}
// start session
s, err := c.StartSession()
if err != nil {
return trace.TraceError(err)
}
// start transaction
if err := s.StartTransaction(); err != nil {
return trace.TraceError(err)
}
// perform operation
if err := mongo.WithSession(ctx, s, func(sc mongo.SessionContext) error {
if err := fn(sc); err != nil {
return trace.TraceError(err)
}
if err = s.CommitTransaction(sc); err != nil {
return trace.TraceError(err)
}
return nil
}); err != nil {
return trace.TraceError(err)
}
return nil
}