本文整理汇总了Golang中upper/io/db.Database.Collection方法的典型用法代码示例。如果您正苦于以下问题:Golang Database.Collection方法的具体用法?Golang Database.Collection怎么用?Golang Database.Collection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类upper/io/db.Database
的用法示例。
在下文中一共展示了Database.Collection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestResultCount
// Attempts to count all rows in our newly defined set.
func TestResultCount(t *testing.T) {
var err error
var res db.Result
var sess db.Database
var artist db.Collection
var total uint64
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
// We should close the database when it's no longer in use.
if artist, err = sess.Collection("artist"); err != nil {
t.Fatal(err)
}
// Defining a set with no conditions.
res = artist.Find()
// Counting all the matching rows.
if total, err = res.Count(); err != nil {
t.Fatal(err)
}
if total == 0 {
t.Fatalf("Counter should not be zero, we've just added some rows!")
}
}
示例2: BenchmarkAppendUpper
// Benchmarking Append().
//
// Contributed by wei2912
// See: https://github.com/gosexy/db/issues/20#issuecomment-20097801
func BenchmarkAppendUpper(b *testing.B) {
var sess db.Database
var artist db.Collection
var err error
if sess, err = db.Open(Adapter, settings); err != nil {
b.Fatal(err)
}
defer sess.Close()
if artist, err = sess.Collection("artist"); err != nil {
b.Fatal(err)
}
artist.Truncate()
item := struct {
Name string `db:"name"`
}{"Hayao Miyazaki"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err = artist.Append(item); err != nil {
b.Fatal(err)
}
}
}
示例3: SetupCollection
func SetupCollection() (col db.Collection) {
var (
err error
sess db.Database
settings db.Settings
)
settings = db.Settings{
Database: `:memory:`,
}
if sess, err = db.Open("sqlite", settings); err != nil {
panic(err)
}
if _, err = sess.Driver().(*sql.DB).Exec(`CREATE TABLE users (
id INTEGER,
first_name VARCHAR(80),
last_name VARCHAR(80),
age INTEGER
);
`); err != nil {
panic(err)
}
if col, err = sess.Collection("users"); err != nil {
panic(err)
}
return col
}
示例4: TestSetterAndConstrainer
// MongoDB: Does not support schemas so it can't has composite keys. We're
// testing db.Constrainer and db.IDSetter interface.
func TestSetterAndConstrainer(t *testing.T) {
var err error
var id interface{}
var sess db.Database
var compositeKeys db.Collection
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
if compositeKeys, err = sess.Collection("composite_keys"); err != nil {
if err != db.ErrCollectionDoesNotExist {
t.Fatal(err)
}
}
//n := rand.Intn(100000)
item := itemWithKey{
// "ABCDEF",
// strconv.Itoa(n),
SomeVal: "Some value",
}
if id, err = compositeKeys.Append(&item); err != nil {
t.Fatal(err)
}
// ids := id.([]interface{})
// if ids[0].(string) != item.Code {
// t.Fatal(`Keys must match.`)
// }
//
// if ids[1].(string) != item.UserID {
// t.Fatal(`Keys must match.`)
// }
// Using constraint interface.
res := compositeKeys.Find(itemWithKey{ID: id.(bson.ObjectId)})
var item2 itemWithKey
if item2.SomeVal == item.SomeVal {
t.Fatal(`Values must be different before query.`)
}
if err := res.One(&item2); err != nil {
t.Fatal(err)
}
if item2.SomeVal != item.SomeVal {
t.Fatal(`Values must be equal after query.`)
}
}
示例5: TestGroup
func TestGroup(t *testing.T) {
var err error
var sess db.Database
var stats db.Collection
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
type statsType struct {
Numeric int `db:"numeric"`
Value int `db:"value"`
}
defer sess.Close()
if stats, err = sess.Collection("stats_test"); err != nil {
t.Fatal(err)
}
// Truncating table.
if err = stats.Truncate(); err != nil {
t.Fatal(err)
}
// Adding row append.
for i := 0; i < 1000; i++ {
numeric, value := rand.Intn(10), rand.Intn(100)
if _, err = stats.Append(statsType{numeric, value}); err != nil {
t.Fatal(err)
}
}
// db.Func{"COUNT", 1},
// db.Func{"SUM", `value`},
// Testing GROUP BY
res := stats.Find().Select(
`numeric`,
db.Raw{`COUNT(1) AS counter`},
db.Raw{`SUM(value) AS total`},
).Group(`numeric`)
var results []map[string]interface{}
if err = res.All(&results); err != nil {
t.Fatal(err)
}
if len(results) != 10 {
t.Fatalf(`Expecting exactly 10 results, this could fail, but it's very unlikely to happen.`)
}
}
示例6: TestFunction
// Attempts to use functions within database queries.
func TestFunction(t *testing.T) {
var err error
var res db.Result
var sess db.Database
var artist db.Collection
var total uint64
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
if artist, err = sess.Collection("artist"); err != nil {
t.Fatal(err)
}
row_s := struct {
Id uint64
Name string
}{}
res = artist.Find(db.Cond{"id NOT IN": []int{0, -1}})
if err = res.One(&row_s); err != nil {
t.Fatal(err)
}
if total, err = res.Count(); err != nil {
t.Fatal(err)
}
if total != 3 {
t.Fatalf("Expecting 3 items.")
}
res = artist.Find(db.Cond{"id": db.Func{"NOT IN", []int{0, -1}}})
if err = res.One(&row_s); err != nil {
t.Fatal(err)
}
if total, err = res.Count(); err != nil {
t.Fatal(err)
}
if total != 3 {
t.Fatalf("Expecting 3 items.")
}
res.Close()
}
示例7: TestDataTypes
// Attempts to add many different datatypes to a single row in a collection,
// then it tries to get the stored datatypes and check if the stored and the
// original values match.
func TestDataTypes(t *testing.T) {
var res db.Result
var sess db.Database
var dataTypes db.Collection
var err error
var id interface{}
var exists uint64
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
// Getting a pointer to the "data_types" collection.
if dataTypes, err = sess.Collection("data_types"); err != nil {
t.Fatal(err)
}
// Removing all data.
if err = dataTypes.Truncate(); err != nil {
t.Fatal(err)
}
// Appending our test subject.
if id, err = dataTypes.Append(testValues); err != nil {
t.Fatal(err)
}
// Defining our set.
res = dataTypes.Find(db.Cond{"id": id})
if exists, err = res.Count(); err != nil {
t.Fatal(err)
}
if exists == 0 {
t.Fatalf("Expecting an item.")
}
// Trying to dump the subject into an empty structure of the same type.
var item testValuesStruct
res.One(&item)
// The original value and the test subject must match.
if reflect.DeepEqual(item, testValues) == false {
t.Fatalf("Struct is different.")
}
}
示例8: TestCompositeKeys
// Attempts to test composite keys.
func TestCompositeKeys(t *testing.T) {
var err error
var sess db.Database
var compositeKeys db.Collection
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
if compositeKeys, err = sess.Collection("composite_keys"); err != nil {
t.Fatal(err)
}
n := rand.Intn(100000)
item := itemWithKey{
"ABCDEF",
strconv.Itoa(n),
"Some value",
}
if _, err = compositeKeys.Append(&item); err != nil {
t.Fatal(err)
}
// Using constraint interface.
var item2 itemWithKey
if item2.SomeVal == item.SomeVal {
t.Fatal(`Values must be different before query.`)
}
res := compositeKeys.Find(item)
if err := res.One(&item2); err != nil {
t.Fatal(err)
}
if item2.SomeVal != item.SomeVal {
t.Fatal(`Values must be equal after query.`)
}
}
示例9: TestTruncate
// Attempts to get all collections and truncate each one of them.
func TestTruncate(t *testing.T) {
var err error
var sess db.Database
var collections []string
var col db.Collection
// Opening database.
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
// We should close the database when it's no longer in use.
defer sess.Close()
// Getting a list of all collections in this database.
if collections, err = sess.Collections(); err != nil {
t.Fatal(err)
}
if len(collections) == 0 {
t.Fatalf("Expecting some collections.")
}
// Walking over collections.
for _, name := range collections {
// Getting a collection.
if col, err = sess.Collection(name); err != nil {
t.Fatal(err)
}
// Table must exists before we can use it.
if col.Exists() == true {
// Truncating the table.
if err = col.Truncate(); err != nil {
t.Fatal(err)
}
}
}
}
示例10: TestRemove
// Attempts to delete previously added rows.
func TestRemove(t *testing.T) {
var err error
var res db.Result
var sess db.Database
var artist db.Collection
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
if artist, err = sess.Collection("artist"); err != nil {
t.Fatal(err)
}
// Getting the artist with id = 1
res = artist.Find(db.Cond{"id": 1})
// Trying to remove the row.
if err = res.Remove(); err != nil {
t.Fatal(err)
}
}
示例11: TestNullableFields
// Attempts to test nullable fields.
func TestNullableFields(t *testing.T) {
var err error
var sess db.Database
var col db.Collection
var id interface{}
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
type testType struct {
ID int64 `db:"id,omitempty"`
NullStringTest sql.NullString `db:"_string"`
NullInt64Test sql.NullInt64 `db:"_int64"`
NullFloat64Test sql.NullFloat64 `db:"_float64"`
NullBoolTest sql.NullBool `db:"_bool"`
}
var test testType
if col, err = sess.Collection(`data_types`); err != nil {
t.Fatal(err)
}
if err = col.Truncate(); err != nil {
t.Fatal(err)
}
// Testing insertion of invalid nulls.
test = testType{
NullStringTest: sql.NullString{"", false},
NullInt64Test: sql.NullInt64{0, false},
NullFloat64Test: sql.NullFloat64{0.0, false},
NullBoolTest: sql.NullBool{false, false},
}
if id, err = col.Append(testType{}); err != nil {
t.Fatal(err)
}
// Testing fetching of invalid nulls.
if err = col.Find(db.Cond{"id": id}).One(&test); err != nil {
t.Fatal(err)
}
if test.NullInt64Test.Valid {
t.Fatalf(`Expecting invalid null.`)
}
if test.NullFloat64Test.Valid {
t.Fatalf(`Expecting invalid null.`)
}
if test.NullBoolTest.Valid {
t.Fatalf(`Expecting invalid null.`)
}
if test.NullStringTest.Valid {
t.Fatalf(`Expecting invalid null.`)
}
// Testing insertion of valid nulls.
test = testType{
NullStringTest: sql.NullString{"", true},
NullInt64Test: sql.NullInt64{0, true},
NullFloat64Test: sql.NullFloat64{0.0, true},
NullBoolTest: sql.NullBool{false, true},
}
if id, err = col.Append(test); err != nil {
t.Fatal(err)
}
// Testing fetching of valid nulls.
if err = col.Find(db.Cond{"id": id}).One(&test); err != nil {
t.Fatal(err)
}
if test.NullInt64Test.Valid == false {
t.Fatalf(`Expecting valid value.`)
}
if test.NullFloat64Test.Valid == false {
t.Fatalf(`Expecting valid value.`)
}
if test.NullBoolTest.Valid == false {
t.Fatalf(`Expecting valid value.`)
}
if test.NullStringTest.Valid == false {
t.Fatalf(`Expecting valid value.`)
}
}
示例12: TestAppend
// Attempts to append some data into the "artist" table.
func TestAppend(t *testing.T) {
var err error
var id interface{}
var sess db.Database
var artist db.Collection
var total uint64
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
if artist, err = sess.Collection("artist"); err != nil {
t.Fatal(err)
}
// Attempt to append a map.
itemMap := map[string]string{
"name": "Ozzie",
}
if id, err = artist.Append(itemMap); err != nil {
t.Fatal(err)
}
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Attempt to append a struct.
itemStruct := struct {
Name string `db:"name"`
}{
"Flea",
}
if id, err = artist.Append(itemStruct); err != nil {
t.Fatal(err)
}
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Attempt to append a tagged struct.
itemStruct2 := struct {
ArtistName string `db:"name"`
}{
"Slash",
}
if id, err = artist.Append(itemStruct2); err != nil {
t.Fatal(err)
}
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Attempt to append and update a private key
itemStruct3 := artistWithInt64Key{
Name: "Janus",
}
if _, err = artist.Append(&itemStruct3); err != nil {
t.Fatal(err)
}
if itemStruct3.id == 0 {
t.Fatalf("Expecting an ID.")
}
// Counting elements, must be exactly 4 elements.
if total, err = artist.Find().Count(); err != nil {
t.Fatal(err)
}
if total != 4 {
t.Fatalf("Expecting exactly 4 rows.")
}
}
示例13: TestUpdate
// Attempts to modify previously added rows.
func TestUpdate(t *testing.T) {
var err error
var sess db.Database
var artist db.Collection
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
if artist, err = sess.Collection("artist"); err != nil {
t.Fatal(err)
}
// Defining destination struct
value := struct {
ID uint64
Name string
}{}
// Getting the first artist.
res := artist.Find(db.Cond{"id !=": 0}).Limit(1)
if err = res.One(&value); err != nil {
t.Fatal(err)
}
// Updating set with a map
rowMap := map[string]interface{}{
"name": strings.ToUpper(value.Name),
}
if err = res.Update(rowMap); err != nil {
t.Fatal(err)
}
// Pulling it again.
if err = res.One(&value); err != nil {
t.Fatal(err)
}
// Verifying.
if value.Name != rowMap["name"] {
t.Fatalf("Expecting a modification.")
}
// Updating set with a struct
rowStruct := struct {
Name string
}{strings.ToLower(value.Name)}
if err = res.Update(rowStruct); err != nil {
t.Fatal(err)
}
// Pulling it again.
if err = res.One(&value); err != nil {
t.Fatal(err)
}
// Verifying
if value.Name != rowStruct.Name {
t.Fatalf("Expecting a modification.")
}
// Updating set with a tagged struct
rowStruct2 := struct {
Value1 string `db:"name"`
}{strings.Replace(value.Name, "z", "Z", -1)}
if err = res.Update(rowStruct2); err != nil {
t.Fatal(err)
}
// Pulling it again.
if err = res.One(&value); err != nil {
t.Fatal(err)
}
// Verifying
if value.Name != rowStruct2.Value1 {
t.Fatalf("Expecting a modification.")
}
}
示例14: TestExplicitAndDefaultMapping
func TestExplicitAndDefaultMapping(t *testing.T) {
var err error
var col db.Collection
var sess db.Database
var res db.Result
var testE mapE
var testN mapN
for _, wrapper := range wrappers {
if settings[wrapper] == nil {
t.Fatalf(`No such settings entry for wrapper %s.`, wrapper)
} else {
if sess, err = db.Open(wrapper, *settings[wrapper]); err != nil {
t.Fatalf(`Test for wrapper %s failed: %q`, wrapper, err)
}
defer sess.Close()
col, err = sess.Collection("Case_Test")
if col, err = sess.Collection("CaSe_TesT"); err != nil {
if wrapper == `mongo` && err == db.ErrCollectionDoesNotExist {
// Nothing, it's expected.
} else {
t.Fatal(err)
}
}
if err = col.Truncate(); err != nil {
if wrapper == `mongo` {
// Nothing, it's expected.
} else {
t.Fatal(err)
}
}
// Testing explicit mapping.
testE = mapE{
CaseTest: "Hello!",
}
if _, err = col.Append(testE); err != nil {
t.Fatal(err)
}
res = col.Find(db.Cond{"Case_Test": "Hello!"})
if wrapper == `ql` {
res = res.Select(`id() as ID`, `Case_Test`)
}
if err = res.One(&testE); err != nil {
t.Fatal(err)
}
if wrapper == `mongo` {
if testE.MongoID.Valid() == false {
t.Fatalf("Expecting an ID.")
}
} else {
if testE.ID == 0 {
t.Fatalf("Expecting an ID.")
}
}
// Testing default mapping.
testN = mapN{
Casetest: "World!",
}
if _, err = col.Append(testN); err != nil {
t.Fatal(err)
}
if wrapper == `mongo` {
// We don't have this kind of control with mongodb.
res = col.Find(db.Cond{"casetest": "World!"})
} else {
res = col.Find(db.Cond{"Case_Test": "World!"})
}
if wrapper == `ql` {
res = res.Select(`id() as ID`, `Case_Test`)
}
if err = res.One(&testN); err != nil {
t.Fatal(err)
}
if wrapper == `mongo` {
if testN.MongoID.Valid() == false {
t.Fatalf("Expecting an ID.")
}
} else {
if testN.ID == 0 {
t.Fatalf("Expecting an ID.")
}
//.........这里部分代码省略.........
示例15: TestEven
func TestEven(t *testing.T) {
var err error
for _, wrapper := range wrappers {
if settings[wrapper] == nil {
t.Fatalf(`No such settings entry for wrapper %s.`, wrapper)
} else {
var sess db.Database
sess, err = db.Open(wrapper, *settings[wrapper])
if err != nil {
t.Fatalf(`Test for wrapper %s failed: %q`, wrapper, err)
}
defer sess.Close()
var col db.Collection
col, err = sess.Collection("is_even")
if err != nil {
if wrapper == `mongo` && err == db.ErrCollectionDoesNotExist {
// Expected error with mongodb.
} else {
t.Fatalf(`Could not use collection with wrapper %s: %q`, wrapper, err)
}
}
// Adding some items.
var i int
for i = 1; i < 100; i++ {
item := oddEven{Input: i, IsEven: even(i)}
_, err = col.Append(item)
if err != nil {
t.Fatalf(`Could not append item with wrapper %s: %q`, wrapper, err)
}
}
// Retrieving items
res := col.Find(db.Cond{"is_even": true})
for {
var item oddEven
err = res.Next(&item)
if err != nil {
if err == db.ErrNoMoreRows {
break
} else {
t.Fatalf(`%s: %v`, wrapper, err)
}
}
if item.Input%2 != 0 {
t.Fatalf("Expecting even numbers with wrapper %s. Got: %v\n", wrapper, item)
}
}
if err = res.Remove(); err != nil {
t.Fatalf(`Could not remove with wrapper %s: %q`, wrapper, err)
}
res = col.Find()
for {
// Testing named inputs (using tags).
var item struct {
Value uint `db:"input" bson:"input"` // The "bson" tag is required by mgo.
}
err = res.Next(&item)
if err != nil {
if err == db.ErrNoMoreRows {
break
} else {
t.Fatalf(`%s: %v`, wrapper, err)
}
}
if item.Value%2 == 0 {
t.Fatalf("Expecting odd numbers only with wrapper %s. Got: %v\n", wrapper, item)
}
}
for {
// Testing inline tag.
var item struct {
oddEven `db:",inline" bson:",inline"`
}
err = res.Next(&item)
if err != nil {
if err == db.ErrNoMoreRows {
break
} else {
t.Fatalf(`%s: %v`, wrapper, err)
}
}
if item.Input%2 == 0 {
t.Fatalf("Expecting odd numbers only with wrapper %s. Got: %v\n", wrapper, item)
}
}
// Testing omision tag.
for {
var item struct {
Value uint `db:"-"`
//.........这里部分代码省略.........