本文整理汇总了Golang中upper/io/db.Collection.Append方法的典型用法代码示例。如果您正苦于以下问题:Golang Collection.Append方法的具体用法?Golang Collection.Append怎么用?Golang Collection.Append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类upper/io/db.Collection
的用法示例。
在下文中一共展示了Collection.Append方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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)
}
}
}
示例2: 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.`)
}
}
示例3: 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.`)
}
}
示例4: 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.")
}
}
示例5: 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.`)
}
}
示例6: main
func main() {
var (
col db.Collection
user User
)
col = SetupCollection()
//START CODE OMIT
col.Append(User{Id: 1, FirstName: "John", LastName: "Doe"})
PrintTable(col)
col.Find(db.Cond{"id": 1}).One(&user)
user.FirstName = "James"
col.Find(user.Id).Update(user)
PrintTable(col)
col.Find(db.Cond{"id": user.Id}).Remove()
PrintTable(col)
//END CODE OMIT
}
示例7: BenchmarkAppendTxUpperMap
// Benchmarking Append() with map.
func BenchmarkAppendTxUpperMap(b *testing.B) {
var sess db.Database
var err error
if sess, err = db.Open(Adapter, settings); err != nil {
b.Fatal(err)
}
defer sess.Close()
var tx db.Tx
if tx, err = sess.Transaction(); err != nil {
b.Fatal(err)
}
var artist db.Collection
if artist, err = tx.Collection("artist"); err != nil {
b.Fatal(err)
}
if err = artist.Truncate(); err != nil {
b.Fatal(err)
}
item := map[string]string{"name": "Hayao Miyazaki"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err = artist.Append(item); err != nil {
b.Fatal(err)
}
}
if err = tx.Commit(); err != nil {
b.Fatal(err)
}
}
示例8: main
func main() {
var (
col db.Collection
)
col = SetupCollection()
//START SETUP OMIT
col.Append(User{
Id: 1,
FirstName: "John",
LastName: "Doe",
Age: 24,
})
col.Append(User{
Id: 2,
FirstName: "Jane",
LastName: "Doe",
Age: 52,
})
col.Append(User{
Id: 3,
FirstName: "Joe",
LastName: "Shmoe",
Age: 10,
})
//END SETUP OMIT
//START CODE OMIT
var users []User
col.Find(db.Or{
db.Cond{"last_name": "Doe"},
db.Cond{"age <": "12"},
}).
Limit(2).
Sort("-age").
All(&users)
fmt.Printf("%+v\n", users)
//END CODE OMIT
}
示例9: createDefault
func createDefault(sexes db.Collection) {
sexes.Append(models.Sex{
Name: "man_sex",
Caption: "мужчина",
TypeName: "sex",
})
sexes.Append(models.Sex{
Name: "woman_sex",
Caption: "женщина",
TypeName: "sex",
})
sexes.Append(models.Sex{
Name: "trans_sex",
Caption: "транс",
TypeName: "sex",
})
}
示例10: TestTransactionsAndRollback
// Attempts to test database transactions.
func TestTransactionsAndRollback(t *testing.T) {
var sess db.Database
var err error
type artistType struct {
ID int64 `db:"id,omitempty"`
Name string `db:"name"`
}
if sess, err = db.Open(Adapter, settings); err != nil {
t.Fatal(err)
}
defer sess.Close()
// Simple transaction that should not fail.
var tx db.Tx
if tx, err = sess.Transaction(); err != nil {
t.Fatal(err)
}
var artist db.Collection
if artist, err = tx.Collection("artist"); err != nil {
t.Fatal(err)
}
if err = artist.Truncate(); err != nil {
t.Fatal(err)
}
// Simple transaction
if _, err = artist.Append(artistType{1, "First"}); err != nil {
t.Fatal(err)
}
if err = tx.Commit(); err != nil {
t.Fatal(err)
}
// Attempt to use the same transaction should fail.
if _, err = tx.Collection("artist"); err == nil {
t.Fatalf("Illegal, transaction has already been commited.")
}
// Use another transaction.
if tx, err = sess.Transaction(); err != nil {
t.Fatal(err)
}
if artist, err = tx.Collection("artist"); err != nil {
t.Fatal(err)
}
// Won't fail.
if _, err = artist.Append(artistType{2, "Second"}); err != nil {
t.Fatal(err)
}
// Won't fail.
if _, err = artist.Append(artistType{3, "Third"}); err != nil {
t.Fatal(err)
}
// Will fail.
if _, err = artist.Append(artistType{1, "Duplicated"}); err == nil {
t.Fatal("Should have failed, as we have already inserted ID 1.")
}
if err = tx.Rollback(); err != nil {
t.Fatal(err)
}
if err = tx.Commit(); err == nil {
t.Fatalf("Should have failed, as we've already rolled back.")
}
// Let's verify we still have one element.
if artist, err = sess.Collection("artist"); err != nil {
t.Fatal(err)
}
var count uint64
if count, err = artist.Find().Count(); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatalf("Expecting only one element.")
}
// Attempt to add some rows.
if tx, err = sess.Transaction(); err != nil {
t.Fatal(err)
}
if artist, err = tx.Collection("artist"); err != nil {
t.Fatal(err)
}
//.........这里部分代码省略.........
示例11: 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.")
}
//.........这里部分代码省略.........
示例12: 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:"-"`
//.........这里部分代码省略.........
示例13: TestFibonacci
func TestFibonacci(t *testing.T) {
var err error
var res db.Result
var total uint64
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("fibonacci")
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 uint64
for i = 0; i < 10; i++ {
item := fibonacci{Input: i, Output: fib(i)}
_, err = col.Append(item)
if err != nil {
t.Fatalf(`Could not append item with wrapper %s: %q`, wrapper, err)
}
}
// Testing sorting by function.
res = col.Find(
// 5, 6, 7, 3
db.Or{
db.And{
db.Cond{"input >=": 5},
db.Cond{"input <=": 7},
},
db.Cond{"input": 3},
},
)
// Testing sort by function.
switch wrapper {
case `postgresql`:
res = res.Sort(db.Raw{`RANDOM()`})
case `sqlite`:
res = res.Sort(db.Raw{`RANDOM()`})
case `mysql`:
res = res.Sort(db.Raw{`RAND()`})
}
total, err = res.Count()
if err != nil {
t.Fatalf(`%s: %q`, wrapper, err)
}
if total != 4 {
t.Fatalf("%s: Expecting a count of 4, got %d.", wrapper, total)
}
// Find() with IN/$in
var whereIn db.Cond
switch wrapper {
case `mongo`:
whereIn = db.Cond{"input": db.Func{"$in", []int{3, 5, 6, 7}}}
default:
whereIn = db.Cond{"input": db.Func{"IN", []int{3, 5, 6, 7}}}
}
res = col.Find(whereIn).Sort("input")
total, err = res.Count()
if err != nil {
t.Fatalf(`%s: %q`, wrapper, err)
}
if total != 4 {
t.Fatalf(`Expecting a count of 4.`)
}
res = res.Skip(1).Limit(2)
for {
var item fibonacci
err = res.Next(&item)
if err == nil {
switch item.Input {
case 5:
//.........这里部分代码省略.........
示例14: 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.
item_m := map[string]string{
"name": "Ozzie",
}
if id, err = artist.Append(item_m); err != nil {
t.Fatal(err)
}
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Attempt to append a struct.
item_s := struct {
Name string `db:"name"`
}{
"Flea",
}
if id, err = artist.Append(item_s); err != nil {
t.Fatal(err)
}
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Append to append a tagged struct.
item_t := struct {
ArtistName string `db:"name"`
}{
"Slash",
}
if id, err = artist.Append(item_t); err != nil {
t.Fatal(err)
}
if to.Int64(id) == 0 {
t.Fatalf("Expecting an ID.")
}
// Counting elements, must be exactly 3 elements.
if total, err = artist.Find().Count(); err != nil {
t.Fatal(err)
}
if total != 3 {
t.Fatalf("Expecting exactly 3 rows.")
}
}
示例15: 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.")
}
}