mirror of
https://github.com/crawlab-team/crawlab.git
synced 2026-01-22 17:31:03 +01:00
- 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.
46 lines
966 B
Go
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
|
|
}
|