-
Notifications
You must be signed in to change notification settings - Fork 3
/
driver.go
54 lines (46 loc) · 1.25 KB
/
driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package mongo
import (
"context"
"log"
"github.com/roneli/fastgql/pkg/execution/builders"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo"
)
// Driver is a dialect.Driver implementation for SQL based databases.
type Driver struct {
client *mongo.Client
builder Builder
dialect string
}
// NewDriver creates a new Driver with the given Conn and dialect.
func NewDriver(dialect string, cfg *builders.Config, uri string) *Driver {
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(uri))
if err != nil {
log.Fatal(err)
}
return &Driver{dialect: dialect, builder: NewBuilder(cfg), client: client}
}
func (d Driver) Scan(ctx context.Context, model interface{}) error {
field := builders.CollectFields(ctx, d.builder.Schema)
table := field.Table()
db := d.client.Database(table.Schema)
collection := db.Collection(table.Name)
pipeline, err := d.builder.Query(field)
if err != nil {
return err
}
cur, err := collection.Aggregate(ctx, pipeline)
if err != nil {
log.Fatal(err)
}
defer func() {
_ = cur.Close(ctx)
}()
return cur.All(ctx, model)
}
func (d Driver) Close() error {
return d.client.Disconnect(context.Background())
}
func (d Driver) Dialect() string {
return d.dialect
}