mgoにおけるDBRef-データ照会テスト

3240 ワード

午後、データ照会のコードテストを行いました.
  
package main

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"time"
)

var (
	mgoSession   *mgo.Session
	databaseName = "myDB"
	tbl_person   = "persons"
	tbl_log      = "logs"
)

type Person struct {
	Id       string
	Name     string
	Inserted time.Time
}

type Log struct {
	LogId    string
	Log      string
	LogUser  mgo.DBRef
	Inserted time.Time
}

func main() {
	session, err := mgo.Dial("localhost:27017")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	session.DB(databaseName).DropDatabase()

	c := session.DB(databaseName).C(tbl_person)
	d := session.DB(databaseName).C(tbl_log)

	_ = c.Insert(&Person{"111", "ssl1", time.Now()})
	_ = c.Insert(&Person{"222", "ssl1", time.Now()})
	_ = c.Insert(&Person{"333", "ssl1", time.Now()})

	for i := 0; i < 10; i++ {
		_ = d.Insert(&Log{GenerateUUID(), " ", mgo.DBRef{tbl_person, "111", databaseName}, time.Now()})
	}

	for i := 0; i < 10; i++ {
		_ = d.Insert(&Log{GenerateUUID(), " ", mgo.DBRef{tbl_person, "222", databaseName}, time.Now()})
	}

	for i := 0; i < 10; i++ {
		_ = d.Insert(&Log{GenerateUUID(), " ", mgo.DBRef{tbl_person, "333", databaseName}, time.Now()})
	}

	personcount, _ := c.Find(bson.M{}).Count()
	fmt.Println(personcount)

	logcount, _ := d.Find(bson.M{}).Count()
	fmt.Println(logcount)

	// loguser.$db , , : !!!!
	// ,loguser.$db 
	p1logcount, _ := d.Find(bson.M{"loguser.$ref": tbl_person, "loguser.$id": "111", "loguser.$db": "myDB"}).Count()
	fmt.Println(p1logcount)

	result1 := []Log{}
	err = d.Find(bson.M{}).All(&result1)
	fmt.Println(result1)
}

// http://www.ashishbanerjee.com/home/go/go-generate-uuid
func GenerateUUID() string {
	uuid := make([]byte, 16)
	n, err := rand.Read(uuid)
	if n != len(uuid) || err != nil {
		return ""
	}
	uuid[8] = 0x80 // variant bits see page 5
	uuid[4] = 0x40 // version 4 Pseudo Random, see page 7

	return hex.EncodeToString(uuid)
}

  
結果は正しい:
[ `run` | done: 179.164361ms ]
    3
    30
    10

参照先:
  • Database References
  • DB Refs in MongoDB