Example #1
0
// Trying to open an empty datasource, must fail.
func TestOpenFailed(t *testing.T) {
	_, err := db.Open(wrapperName, db.DataSource{})

	if err == nil {
		t.Errorf("Could not open database.")
	}
}
Example #2
0
// Contributed by wei2912
// See: https://github.com/gosexy/db/issues/20#issuecomment-20167939
// Applying the BEGIN and END transaction optimizations.
func BenchmarkAppendDbItem_Transaction(b *testing.B) {
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		b.Fatalf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")
	people.Truncate()

	err = sess.Begin()
	if err != nil {
		b.Fatalf(err.Error())
	}

	for i := 0; i < b.N; i++ {
		_, err = people.Append(db.Item{"name": "john"})
		if err != nil {
			b.Fatalf(err.Error())
		}
	}

	err = sess.End()
	if err != nil {
		b.Fatalf(err.Error())
	}
}
Example #3
0
// Tries to update rows.
func TestUpdate(t *testing.T) {
	var found int

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")

	// Update with map.
	people.Update(db.Cond{"name": "José"}, db.Set{"name": "Joseph"})

	found, _ = people.Count(db.Cond{"name": "Joseph"})

	if found != 1 {
		t.Fatalf("Could not update a recently appended item.")
	}

	// Update with struct.
	people.Update(db.Cond{"name": "Joseph"}, struct{ Name string }{"José"})

	found, _ = people.Count(db.Cond{"name": "José"})

	if found != 1 {
		t.Fatalf("Could not update a recently appended item.")
	}
}
Example #4
0
// Truncates all collections/tables, one by one.
func TestTruncate(t *testing.T) {

	var err error

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	collections := sess.Collections()

	for _, name := range collections {
		col := sess.ExistentCollection(name)
		col.Truncate()

		total, err := col.Count()

		if err != nil {
			t.Fatalf(err.Error())
		}

		if total != 0 {
			t.Errorf("Could not truncate.")
		}
	}

}
Example #5
0
// Tries to add test data and relations.
func TestPopulate(t *testing.T) {

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Errorf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")
	places := sess.ExistentCollection("places")
	children := sess.ExistentCollection("children")
	visits := sess.ExistentCollection("visits")

	values := []string{"Alaska", "Nebraska", "Alaska", "Acapulco", "Rome", "Singapore", "Alabama", "Cancún"}

	for i, value := range values {
		places.Append(db.Item{
			"code_id": i,
			"name":    value,
		})
	}

	results, _ := people.FindAll(
		db.Fields{"id", "name"},
		db.Sort{"name": "ASC", "id": -1},
	)

	for _, person := range results {

		// Has 5 children.

		for j := 0; j < 5; j++ {
			children.Append(db.Item{
				"name":      fmt.Sprintf("%s's child %d", person["name"], j+1),
				"parent_id": person["id"],
			})
		}

		// Lives in
		people.Update(
			db.Cond{"id": person["id"]},
			db.Set{"place_code_id": int(rand.Float32() * float32(len(results)))},
		)

		// Has visited
		for j := 0; j < 3; j++ {
			place, _ := places.Find(db.Cond{
				"code_id": int(rand.Float32() * float32(len(results))),
			})
			visits.Append(db.Item{
				"place_id":  place["id"],
				"person_id": person["id"],
			})
		}
	}

}
Example #6
0
func main() {

	sess, err := db.Open("postgresql", settings)

	if err != nil {
		panic(err)
	}

	defer sess.Close()

	animals, err := sess.Collection("animals")

	if err != nil {
		fmt.Printf("Please create the `animals` table: %s", err.Error())
		return
	}

	animals.Truncate()

	animals.Append(db.Item{
		"animal": "Bird",
		"young":  "Chick",
		"female": "Hen",
		"male":   "C**k",
		"group":  "flock",
	})

	animals.Append(db.Item{
		"animal": "Bovidae",
		"young":  "Calf",
		"female": "Cow",
		"male":   "Bull",
		"group":  "Herd",
	})

	animals.Append(db.Item{
		"animal": "Canidae",
		"young":  "Puppy, Pup",
		"female": "Bitch",
		"male":   "Dog",
		"group":  "Pack",
	})

	items, err := animals.FindAll()

	if err != nil {
		panic(err.Error())
	}

	for _, item := range items {
		fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
	}

}
Example #7
0
// Tests relations between collections.
func TestRelation(t *testing.T) {
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Errorf(err.Error())
	}

	defer sess.Close()

	people, _ := sess.Collection("people")

	results, _ := people.FindAll(
		db.Relate{
			"lives_in": db.On{
				sess.ExistentCollection("places"),
				db.Cond{"code_id": "{place_code_id}"},
			},
		},
		db.RelateAll{
			"has_children": db.On{
				sess.ExistentCollection("children"),
				db.Cond{"parent_id": "{id}"},
			},
			"has_visited": db.On{
				sess.ExistentCollection("visits"),
				db.Cond{"person_id": "{id}"},
				db.Relate{
					"place": db.On{
						sess.ExistentCollection("places"),
						db.Cond{"id": "{place_id}"},
					},
				},
			},
		},
	)

	fmt.Printf("relations (1) %# v\n", pretty.Formatter(results))

	var testv string

	testv = dig.String(&results, 0, "lives_in", "name")

	if testv == "" {
		t.Fatalf("Test failed, expected some value.")
	}

	testv = dig.String(&results, 1, "has_children", 2, "name")

	if testv == "" {
		t.Fatalf("Test failed, expected some value.")
	}
}
Example #8
0
func main() {

	sess, err := db.Open("mongo", settings)

	if err != nil {
		panic(err)
	}

	defer sess.Close()

	animals, _ := sess.Collection("animals")

	animals.Truncate()

	animals.Append(db.Item{
		"animal": "Bird",
		"young":  "Chick",
		"female": "Hen",
		"male":   "C**k",
		"group":  "flock",
	})

	animals.Append(db.Item{
		"animal": "Bovidae",
		"young":  "Calf",
		"female": "Cow",
		"male":   "Bull",
		"group":  "Herd",
	})

	animals.Append(db.Item{
		"animal": "Canidae",
		"young":  []string{"Puppy", "Pup"},
		"female": "Bitch",
		"male":   "Dog",
		"group":  "Pack",
	})

	items, err := animals.FindAll()

	if err != nil {
		panic(err.Error())
	}

	for _, item := range items {
		fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
	}

}
Example #9
0
func BenchmarkAppendStruct(b *testing.B) {
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		b.Fatalf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")
	people.Truncate()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err = people.Append(struct{ Name string }{"john"})
		if err != nil {
			b.Fatalf(err.Error())
		}
	}
}
Example #10
0
// Tests limit and offset.
func TestLimitOffset(t *testing.T) {
	var err error

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	people, _ := sess.Collection("people")

	items, _ := people.FindAll(db.Limit(2), db.Offset(1))

	if len(items) != 2 {
		t.Fatalf("Test failed")
	}

}
Example #11
0
// Tries to delete rows.
func TestDelete(t *testing.T) {
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")

	people.Remove(db.Cond{"name": "Juan"})

	result, _ := people.Find(db.Cond{"name": "Juan"})

	if len(result) > 0 {
		t.Fatalf("Could not remove a recently appended item.")
	}

}
Example #12
0
func BenchmarkAppendRaw(b *testing.B) {
	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		b.Fatalf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")
	people.Truncate()

	driver := sess.Driver().(*sql.DB)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err := driver.Exec(`INSERT INTO people (name) VALUES("john")`)
		if err != nil {
			b.Fatalf(err.Error())
		}
	}
}
Example #13
0
func main() {

	var ids []db.Id
	var err error

	mysqlSess, err := db.Open("mysql", mysqlSettings)

	if err != nil {
		panic(err)
	}

	defer mysqlSess.Close()

	postgresqlSess, err := db.Open("postgresql", postgresqlSettings)

	if err != nil {
		panic(err)
	}

	defer postgresqlSess.Close()

	peopleIAdmire := postgresqlSess.ExistentCollection("peopleIAdmire")
	worksOfPeopleIAdmire := mysqlSess.ExistentCollection("worksOfPeopleIAdmire")

	// APPENDING PEOPLE
	peopleIAdmire.Truncate()

	// Hayao Miyazaki
	ids, err = peopleIAdmire.Append(db.Item{
		"name": "Hayao Miyazaki",
		"born": 1941,
	})

	if err != nil {
		panic(err)
	}

	miyazakiId := ids[0]

	// Edgar Allan Poe
	ids, err = peopleIAdmire.Append(db.Item{
		"name": "Edgar Allan Poe",
		"born": 1809,
	})

	if err != nil {
		panic(err)
	}

	poeId := ids[0]

	// Gabriel García Márquez
	ids, err = peopleIAdmire.Append(db.Item{
		"name": "Gabriel García Márquez",
		"born": 1927,
	})

	if err != nil {
		panic(err)
	}

	gaboId := ids[0]

	// APPENDING WORKS
	worksOfPeopleIAdmire.Truncate()

	// Mizayaki
	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "Nausicaä of the Valley of the Wind",
		"year":      1984,
		"author_id": miyazakiId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "Princes Mononoke",
		"year":      1997,
		"author_id": miyazakiId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "Howl's Moving Castle",
		"year":      2004,
		"author_id": miyazakiId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "My Neighbor Totoro",
		"year":      1988,
		"author_id": miyazakiId,
	})

	// Poe
	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "The Black Cat",
		"year":      1843,
		"author_id": poeId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "The Facts in the Case of M. Valdemar",
		"year":      1845,
		"author_id": poeId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "The Gold Bug",
		"year":      1843,
		"author_id": poeId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "The Murders in the Rue Morge",
		"year":      1841,
		"author_id": poeId,
	})

	// Gabo
	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "Memoria de mis putas tristes",
		"year":      2004,
		"author_id": gaboId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "El amor en los tiempos del cólera",
		"year":      1985,
		"author_id": gaboId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "Del amor y otros demonios",
		"year":      1994,
		"author_id": gaboId,
	})

	worksOfPeopleIAdmire.Append(db.Item{
		"name":      "Cien años de soledad",
		"year":      1967,
		"author_id": gaboId,
	})

	// TESTING RELATION

	peopleAndWorks, err := peopleIAdmire.FindAll(
		db.RelateAll{
			"works": db.On{
				worksOfPeopleIAdmire,
				db.Cond{"author_id": "{id}"},
			},
		},
	)

	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("People I Admire:\n\n")

	for _, person := range peopleAndWorks {

		fmt.Printf("%s. Born %d.\n\n", person["name"], person["born"])
		fmt.Printf("Some of his works are:\n")

		for _, work := range person["works"].([]db.Item) {
			fmt.Printf("* %s, %d.\n", work["name"], work["year"])
		}

		fmt.Printf("---\n\n")
	}

	/*
		People I Admire:

		Hayao Miyazaki. Born 1941.

		Some of his works are:
		* Nausicaä of the Valley of the Wind, 1984.
		* Princes Mononoke, 1997.
		* Howl's Moving Castle, 2004.
		* My Neighbor Totoro, 1988.
		---

		Edgar Allan Poe. Born 1809.

		Some of his works are:
		* The Black Cat, 1843.
		* The Facts in the Case of M. Valdemar, 1845.
		* The Gold Bug, 1843.
		* The Murders in the Rue Morge, 1841.
		---

		Gabriel García Márquez. Born 1927.

		Some of his works are:
		* Memoria de mis putas tristes, 2004.
		* El amor en los tiempos del cólera, 1985.
		* Del amor y otros demonios, 1994.
		* Cien años de soledad, 1967.
		---
	*/

}
Example #14
0
func main() {

	sess, err := db.Open("mysql", settings)

	if err != nil {
		panic(err)
	}

	defer sess.Close()

	animals, err := sess.Collection("animals")

	if err != nil {
		fmt.Printf("Please create the `animals` table.: %s", err.Error())
		return
	}

	animals.Truncate()

	animals.Append(db.Item{
		"animal": "Bird",
		"young":  "Chick",
		"female": "Hen",
		"male":   "C**k",
		"group":  "flock",
	})

	animals.Append(db.Item{
		"animal": "Bovidae",
		"young":  "Calf",
		"female": "Cow",
		"male":   "Bull",
		"group":  "Herd",
	})

	animals.Append(db.Item{
		"animal": "Canidae",
		"young":  "Puppy, Pup",
		"female": "Bitch",
		"male":   "Dog",
		"group":  "Pack",
	})

	items, err := animals.FindAll()

	if err != nil {
		panic(err.Error())
	}

	for _, item := range items {
		fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
	}

	// Custom SQL
	drv := sess.Driver().(*sql.DB)

	rows, err := drv.Query("SELECT * from animals")

	items = []db.Item{}

	// Empty virtual table
	vtable := &sqlutil.T{}
	vtable.FetchRows(&items, rows)

	for _, item := range items {
		fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
	}

}
Example #15
0
// Tests datatype conversions.
func TestDataTypes(t *testing.T) {
	var res db.Result
	var items []db.Item

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	dataTypes := sess.ExistentCollection("data_types")

	dataTypes.Truncate()

	ids, err := dataTypes.Append(testValues)

	if err != nil {
		t.Fatalf(err.Error())
	}

	found, err := dataTypes.Count(db.Cond{"id": db.Id(ids[0])})

	if err != nil {
		t.Fatalf(err.Error())
	}

	if found == 0 {
		t.Errorf("Expecting an item.")
	}

	// Getting and reinserting (a db.Item).
	item, _ := dataTypes.Find()

	_, err = dataTypes.Append(item)

	if err == nil {
		t.Fatalf("Expecting duplicated-key error.")
	}

	delete(item, "id")

	_, err = dataTypes.Append(item)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Testing date ranges
	items, err = dataTypes.FindAll(db.Cond{
		"_date": time.Now(),
	})

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(items) > 0 {
		t.Fatalf("Expecting no results.")
	}

	items, err = dataTypes.FindAll(db.Cond{
		"_date <=": time.Now(),
	})

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(items) != 2 {
		t.Fatalf("Expecting some results.")
	}

	// Testing struct
	sresults := []testValuesStruct{}

	res, err = dataTypes.Query()

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&sresults)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Testing struct equality
	for _, item := range sresults {
		if reflect.DeepEqual(item, testValues) == false {
			t.Errorf("Struct is different.")
		}
	}

	// Testing maps
	results, _ := dataTypes.FindAll()

	for _, item := range results {

		for key, _ := range item {

			switch key {

			// Signed integers.
			case
				"_int",
				"_int8",
				"_int16",
				"_int32",
				"_int64":
				if to.Int64(item[key]) != testValues.Int64 {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Unsigned integers.
			case
				"_uint",
				"_uint8",
				"_uint16",
				"_uint32",
				"_uint64":
				if to.Uint64(item[key]) != testValues.Uint64 {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Floating point.
			case "_float32":
			case "_float64":
				if to.Float64(item[key]) != testValues.Float64 {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Boolean
			case "_bool":
				if to.Bool(item[key]) != testValues.Bool {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// String
			case "_string":
				if to.String(item[key]) != testValues.String {
					t.Fatalf("Wrong datatype %v.", key)
				}

			// Date
			case "_date":
				if to.Time(item[key]).Equal(testValues.Date) == false {
					t.Fatalf("Wrong datatype %v.", key)
				}
			}
		}
	}

}
Example #16
0
// Tests relations between collections using structs.
func TestRelationStruct(t *testing.T) {
	var err error
	var res db.Result

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Errorf(err.Error())
	}

	defer sess.Close()

	people := sess.ExistentCollection("people")

	results := []struct {
		Id          int
		Name        string
		PlaceCodeId int
		LivesIn     struct {
			Name string
		}
		HasChildren []struct {
			Name string
		}
		HasVisited []struct {
			PlaceId int
			Place   struct {
				Name string
			}
		}
	}{}

	res, err = people.Query(
		db.Relate{
			"LivesIn": db.On{
				sess.ExistentCollection("places"),
				db.Cond{"code_id": "{PlaceCodeId}"},
			},
		},
		db.RelateAll{
			"HasChildren": db.On{
				sess.ExistentCollection("children"),
				db.Cond{"parent_id": "{Id}"},
			},
			"HasVisited": db.On{
				sess.ExistentCollection("visits"),
				db.Cond{"person_id": "{Id}"},
				db.Relate{
					"Place": db.On{
						sess.ExistentCollection("places"),
						db.Cond{"id": "{PlaceId}"},
					},
				},
			},
		},
	)

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&results)

	if err != nil {
		t.Fatalf(err.Error())
	}

	fmt.Printf("relations (2) %# v\n", pretty.Formatter(results))
}
Example #17
0
// Appends maps and structs.
func TestAppend(t *testing.T) {

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	_, err = sess.Collection("doesnotexists")

	if err == nil {
		t.Fatalf("Collection should not exists.")
	}

	people := sess.ExistentCollection("people")

	// To be inserted
	names := []string{
		"Juan",
		"José",
		"Pedro",
		"María",
		"Roberto",
		"Manuel",
		"Miguel",
	}

	var total int

	// Append db.Item
	people.Truncate()

	for _, name := range names {
		people.Append(db.Item{"name": name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

	// Append map[string]string
	people.Truncate()

	for _, name := range names {
		people.Append(map[string]string{"name": name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

	// Append map[string]interface{}
	people.Truncate()

	for _, name := range names {
		people.Append(map[string]interface{}{"name": name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

	// Append struct
	people.Truncate()

	for _, name := range names {
		people.Append(struct {
			ignoreMe string
			LastName string `ignorenil:"true"`
			// Must ignore OtherName and use "name" as column.
			OtherName string `field:"name",ignorenil:"true"`
			// Should not get inserted.
			nothing string
		}{"nuff said", "", name, "nothing"})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

}
Example #18
0
// Tries to find and fetch rows.
func TestFind(t *testing.T) {

	var err error
	var res db.Result

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	/*
		// Testing simultaneous connection.
		sess2, err := db.Open(wrapperName, db.DataSource {
			Database: "mysql",
			Socket: socket,
			User: "******",
		})

		if err != nil {
			t.Fatalf(err.Error())
		}

		defer sess2.Close()
	*/

	people, _ := sess.Collection("people")

	// Testing Find()
	item, _ := people.Find(db.Cond{"name": "José"})

	if item["name"] != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Fetch into map slice.
	dst := []map[string]string{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&dst)

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(dst) != 1 {
		t.Fatalf("Could not find a recently appended item.")
	}

	if dst[0]["name"] != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Fetch into struct slice.
	dst2 := []struct {
		foo        string
		PersonName string `field:"name"`
		none       string
	}{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&dst2)

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(dst2) != 1 {
		t.Fatalf("Could not find a recently appended item.")
	}

	if dst2[0].PersonName != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Fetch into map.
	dst3 := map[string]interface{}{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.One(&dst3)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Fetch into struct.
	dst4 := struct{ Name string }{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.One(&dst4)

	if err != nil {
		t.Fatalf(err.Error())
	}

	if dst4.Name != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Makes a query and stores the result
	res, err = people.Query(nil)

	if err != nil {
		t.Fatalf(err.Error())
	}

	dst5 := struct {
		PersonName string `field:"name"`
	}{}
	found := false

	for {
		err = res.Next(&dst5)
		if err == nil {
			if dst5.PersonName == "José" {
				found = true
			}
		} else if err == db.ErrNoMoreRows {
			break
		} else {
			t.Fatalf(err.Error())
		}
	}

	res.Close()

	if found == false {
		t.Fatalf("José was not found.")
	}

}
Example #19
0
func main() {

	sqlite.DateFormat = "2006-01-02"

	sess, err := db.Open("sqlite", settings)

	if err != nil {
		fmt.Println("Please create the `animals.db` sqlite3 database.")
		return
	}

	defer sess.Close()

	animals, err := sess.Collection("animals")

	if err != nil {
		fmt.Println("Please create the `animals` table and make sure the `animals.db` sqlite3 database exists.")
		return
	}

	animals.Truncate()

	animals.Append(db.Item{
		"animal": "Bird",
		"young":  "Chick",
		"female": "Hen",
		"male":   "C**k",
		"group":  "flock",
	})

	animals.Append(db.Item{
		"animal": "Bovidae",
		"young":  "Calf",
		"female": "Cow",
		"male":   "Bull",
		"group":  "Herd",
	})

	animals.Append(db.Item{
		"animal": "Canidae",
		"young":  "Puppy, Pup",
		"female": "Bitch",
		"male":   "Dog",
		"group":  "Pack",
	})

	items, err := animals.FindAll()

	if err != nil {
		panic(err.Error())
	}

	for _, item := range items {
		fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
	}

	birthdays, err := sess.Collection("birthdays")

	if err != nil {
		fmt.Println("Please create the `birthdays` table and make sure the `animals.db` sqlite3 database exists.")
		return
	}

	birthdays.Append(db.Item{
		"name": "Joseph",
		"born": time.Date(1987, time.July, 28, 0, 0, 0, 0, time.UTC),
		"age":  26,
	})

	items, err = birthdays.FindAll()

	if err != nil {
		panic(err.Error())
	}

	for _, item := range items {
		fmt.Printf("name: %s, born: %s, age: %d\n", item["name"], item["born"], item["age"])
	}

}
Example #20
0
// Tries to find and fetch rows.
func TestFind(t *testing.T) {

	var err error
	var res db.Result

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	people, _ := sess.Collection("people")

	// Testing Find()
	item, _ := people.Find(db.Cond{"name": "José"})

	if item["name"] != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Fetch into map slice.
	dst := []map[string]string{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&dst)

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(dst) != 1 {
		t.Fatalf("Could not find a recently appended item.")
	}

	if dst[0]["name"] != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Fetch into struct slice.
	dst2 := []struct{ Name string }{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.All(&dst2)

	if err != nil {
		t.Fatalf(err.Error())
	}

	if len(dst2) != 1 {
		t.Fatalf("Could not find a recently appended item.")
	}

	if dst2[0].Name != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Fetch into map.
	dst3 := map[string]interface{}{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.One(&dst3)

	if err != nil {
		t.Fatalf(err.Error())
	}

	// Fetch into struct.
	dst4 := struct{ Name string }{}

	res, err = people.Query(db.Cond{"name": "José"})

	if err != nil {
		t.Fatalf(err.Error())
	}

	err = res.One(&dst4)

	if err != nil {
		t.Fatalf(err.Error())
	}

	if dst4.Name != "José" {
		t.Fatalf("Could not find a recently appended item.")
	}

	// Makes a query and stores the result
	res, err = people.Query(nil)

	if err != nil {
		t.Fatalf(err.Error())
	}

	dst5 := struct{ Name string }{}
	found := false

	for {
		err = res.Next(&dst5)
		if err != nil {
			break
		}
		if dst5.Name == "José" {
			found = true
		}
	}

	res.Close()

	if found == false {
		t.Fatalf("José was not found.")
	}

}
Example #21
0
// Appends maps and structs.
func TestAppend(t *testing.T) {

	sess, err := db.Open(wrapperName, settings)

	if err != nil {
		t.Fatalf(err.Error())
	}

	defer sess.Close()

	_, err = sess.Collection("doesnotexists")

	if err == nil {
		t.Fatalf("Collection should not exists.")
	}

	people := sess.ExistentCollection("people")

	// To be inserted
	names := []string{
		"Juan",
		"José",
		"Pedro",
		"María",
		"Roberto",
		"Manuel",
		"Miguel",
	}

	var total int

	// Append db.Item
	people.Truncate()

	for _, name := range names {
		people.Append(db.Item{"name": name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

	// Append map[string]string
	people.Truncate()

	for _, name := range names {
		people.Append(map[string]string{"name": name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

	// Append map[string]interface{}
	people.Truncate()

	for _, name := range names {
		people.Append(map[string]interface{}{"name": name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

	// Append struct
	people.Truncate()

	for _, name := range names {
		people.Append(struct{ Name string }{name})
	}

	total, _ = people.Count()

	if total != len(names) {
		t.Fatalf("Could not append all items.")
	}

}