-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathmongo.go
70 lines (62 loc) · 1.47 KB
/
mongo.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package datasource
import (
"context"
"errors"
"net/url"
"strconv"
"strings"
"github.com/k1LoW/tbls/drivers/mongodb"
"github.com/k1LoW/tbls/schema"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
const (
defaultSampleSize = 1000
defaultMultipleFieldType = false
)
// AnalyzeMongodb analyze `mongodb://`
func AnalyzeMongodb(urlstr string) (*schema.Schema, error) {
s := &schema.Schema{}
u, err := url.Parse(urlstr)
if err != nil {
return s, err
}
values := u.Query()
parsedPath := strings.Split(u.Path, "/")
if len(parsedPath) != 2 {
return nil, errors.New("No database name in the connection string")
}
dbName := parsedPath[1]
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(urlstr))
if err != nil {
return s, err
}
err = client.Ping(ctx, readpref.Primary())
if err != nil {
return s, err
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
sampleSize, err := strconv.ParseInt(values.Get("sampleSize"), 10, 0)
if err != nil {
sampleSize = defaultSampleSize
}
multipleFieldType, err := strconv.ParseBool(values.Get("multipleFieldType"))
if err != nil {
multipleFieldType = defaultMultipleFieldType
}
driver, err := mongodb.New(ctx, client, dbName, sampleSize, multipleFieldType)
if err != nil {
return s, err
}
err = driver.Analyze(s)
if err != nil {
return s, err
}
return s, nil
}