|
| 1 | +package mongo |
| 2 | + |
| 3 | +import ( |
| 4 | +"context" |
| 5 | +"errors" |
| 6 | +"strconv" |
| 7 | +"strings" |
| 8 | + |
| 9 | +"go.mongodb.org/mongo-driver/bson" |
| 10 | +"go.mongodb.org/mongo-driver/mongo" |
| 11 | +"go.mongodb.org/mongo-driver/mongo/options" |
| 12 | +"go.mongodb.org/mongo-driver/x/bsonx" |
| 13 | + |
| 14 | +"github.com/qa-dev/jsonwire-grid/config" |
| 15 | +"github.com/qa-dev/jsonwire-grid/pool" |
| 16 | +) |
| 17 | + |
| 18 | +type Factory struct { |
| 19 | +} |
| 20 | + |
| 21 | +func (f *Factory) Create(cfg config.Config) (pool.StorageInterface, error) { |
| 22 | +ctx := context.Background() |
| 23 | +client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.DB.Connection)) |
| 24 | +if err != nil { |
| 25 | +panic("Database connection error: " + err.Error()) |
| 26 | +} |
| 27 | + |
| 28 | +err = client.Ping(ctx, nil) |
| 29 | +if err != nil { |
| 30 | +err = errors.New("Database connection not established: " + err.Error()) |
| 31 | +return nil, err |
| 32 | +} |
| 33 | + |
| 34 | +db := client.Database(cfg.DB.DbName) |
| 35 | +err = checkServerVersion(ctx, client) |
| 36 | +if err != nil { |
| 37 | +err = errors.New("version check error: " + err.Error()) |
| 38 | +return nil, err |
| 39 | +} |
| 40 | + |
| 41 | +s := NewMongoStorage(db) |
| 42 | +mod := mongo.IndexModel{ |
| 43 | +Keys: bson.M{ |
| 44 | +"key": 1, |
| 45 | +"address": 1, |
| 46 | +}, |
| 47 | +Options: options.Index().SetUnique(true).SetName("key_address_unique"), |
| 48 | +} |
| 49 | + |
| 50 | +_, err = s.collection.Indexes().CreateOne(ctx, mod) |
| 51 | +if err != nil { |
| 52 | +err = errors.New("Create index error: " + err.Error()) |
| 53 | +return nil, err |
| 54 | +} |
| 55 | + |
| 56 | +return s, nil |
| 57 | +} |
| 58 | + |
| 59 | +func checkServerVersion(ctx context.Context, client *mongo.Client) error { |
| 60 | +serverStatus, err := client.Database("admin").RunCommand( |
| 61 | +ctx, |
| 62 | +bsonx.Doc{bsonx.Elem{Key: "serverStatus", Value: bsonx.Int32(1)}}, |
| 63 | +).DecodeBytes() |
| 64 | +if err != nil { |
| 65 | +return err |
| 66 | +} |
| 67 | + |
| 68 | +version, err := serverStatus.LookupErr("version") |
| 69 | +if err != nil { |
| 70 | +return err |
| 71 | +} |
| 72 | + |
| 73 | +majorVersion, _ := strconv.Atoi(strings.Split(version.StringValue(), ".")[0]) |
| 74 | +if majorVersion < 4 { |
| 75 | +return errors.New("mongodb version not supported: " + version.StringValue()) |
| 76 | +} |
| 77 | +return nil |
| 78 | +} |
0 commit comments