/
database.go
84 lines (67 loc) · 1.67 KB
/
database.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gomongo
import (
"bytes"
"encoding/binary"
"github.com/dmliao/gomongo/buffer"
"gopkg.in/mgo.v2/bson"
)
type Database interface {
GetName() string
// GetCollectionNames() []string
GetCollection(string) Collection
// DropCollection(Collection) bool
ExecuteCommand(interface{}, interface{}) error
// DropDatabase() bool
}
type DB struct {
name string
mongo *MongoDB
}
func (d *DB) GetName() string {
return d.name
}
func (d *DB) GetCollection(cName string) Collection {
return &C{
name: cName,
database: d,
cursors: make(map[int64]*cursorObj),
}
}
func (d *DB) run(socket *Connection, command interface{}, result interface{}) error {
commandBytes, err := bson.Marshal(command)
if err != nil {
return err
}
namespace := d.name + ".$cmd"
requestID := d.mongo.nextID()
limit := int32(-1)
skip := int32(0)
responseTo := int32(0)
// flags
flags := int32(0)
fullCollectionBytes := []byte(namespace)
fullCollectionBytes = append(fullCollectionBytes, byte('\x00'))
buf := new(bytes.Buffer)
buffer.WriteToBuf(buf, int32(0), requestID, responseTo, int32(OP_QUERY), flags, fullCollectionBytes,
skip, limit, commandBytes)
input := buf.Bytes()
respSize := make([]byte, 4)
binary.LittleEndian.PutUint32(respSize, uint32(len(input)))
input[0] = respSize[0]
input[1] = respSize[1]
input[2] = respSize[2]
input[3] = respSize[3]
err = socket.send(input)
if err != nil {
return err
}
res, err := socket.receive()
if err != nil {
return err
}
resultBytes := res.Document[0]
return bson.Unmarshal(resultBytes, result)
}
func (d *DB) ExecuteCommand(command interface{}, result interface{}) error {
return d.run(d.mongo.conn, command, result)
}