You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
874 B
36 lines
874 B
5 years ago
|
package database
|
||
5 years ago
|
|
||
|
import (
|
||
|
"context"
|
||
|
"math/rand"
|
||
|
"strconv"
|
||
|
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
|
||
5 years ago
|
"github.com/mainnika/mongox-go-driver/v2/mongox"
|
||
|
"github.com/mainnika/mongox-go-driver/v2/mongox/database"
|
||
5 years ago
|
)
|
||
|
|
||
5 years ago
|
// EphemeralDatabase is a temporary database connection that will be destroyed after close
|
||
|
type EphemeralDatabase struct {
|
||
5 years ago
|
mongox.Database
|
||
|
}
|
||
|
|
||
5 years ago
|
// NewEphemeral creates new mongo connection
|
||
|
func NewEphemeral(URI string) (db *EphemeralDatabase, err error) {
|
||
5 years ago
|
|
||
|
name := strconv.Itoa(rand.Int())
|
||
|
opts := options.Client().ApplyURI(URI)
|
||
|
client, err := mongo.Connect(context.Background(), opts)
|
||
|
|
||
5 years ago
|
db = &EphemeralDatabase{Database: database.NewDatabase(client, name)}
|
||
5 years ago
|
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// Close the connection and drop database
|
||
5 years ago
|
func (e *EphemeralDatabase) Close() error {
|
||
|
return e.Client().Database(e.Name()).Drop(e.Context())
|
||
5 years ago
|
}
|