// Attempts to open an empty datasource.
func TestOpenWithWrongData(t *testing.T) {
	var err error
	var rightSettings, wrongSettings db.Settings

	// Attempt to open with safe settings.
	rightSettings = db.Settings{
		Database: database,
		Host:     *host,
		User:     username,
		Password: password,
	}

	// Attempt to open an empty database.
	if _, err = db.Open(Adapter, rightSettings); err != nil {
		// Must fail.
		t.Fatal(err)
	}

	// Attempt to open with wrong password.
	wrongSettings = db.Settings{
		Database: database,
		Host:     *host,
		User:     username,
		Password: "******",
	}

	if _, err = db.Open(Adapter, wrongSettings); err == nil {
		t.Fatalf("Expecting an error.")
	}

	// Attempt to open with wrong database.
	wrongSettings = db.Settings{
		Database: "fail",
		Host:     *host,
		User:     username,
		Password: password,
	}

	if _, err = db.Open(Adapter, wrongSettings); err == nil {
		t.Fatalf("Expecting an error.")
	}

	// Attempt to open with wrong username.
	wrongSettings = db.Settings{
		Database: database,
		Host:     *host,
		User:     "******",
		Password: password,
	}

	if _, err = db.Open(Adapter, wrongSettings); err == nil {
		t.Fatalf("Expecting an error.")
	}
}
Example #2
0
func init() {
	var err error

	host := os.Getenv("MONGO_HOST")

	if host == "" {
		host = defaultHost
	}

	settings = db.Settings{
		Host:     host,
		Database: defaultDatabase,
	}

	if sess, err = db.Open("mongo", settings); err != nil {
		log.Fatal("db.Open: ", err)
	}

	log.Printf("Connected to mongo://%s/%s.\n", host, defaultDatabase)

	scores, err = sess.Collection("scores")
	if err != nil {
		if err != db.ErrCollectionDoesNotExists {
			log.Fatal("db.Collection: ", err)
		}
	}
}
Example #3
0
// Benchmarking raw database/sql.
func BenchmarkAppendRawSQL(b *testing.B) {
	var err error
	var sess db.Database

	if sess, err = db.Open(Adapter, settings); err != nil {
		b.Fatal(err)
	}

	defer sess.Close()

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

	if _, err = driver.Exec(`DELETE FROM "artist"`); err != nil {
		b.Fatal(err)
	}

	b.ResetTimer()
	stmt, err := driver.Prepare(
		`INSERT INTO "artist" ("name") VALUES('Hayao Miyazaki')`)
	if err != nil {
		b.Fatal(err)
	}
	for i := 0; i < b.N; i++ {
		if _, err = stmt.Exec(); err != nil {
			b.Fatal(err)
		}
	}
}
// Benchmarking raw database/sql.
func BenchmarkAppendTxRawSQL(b *testing.B) {
	var err error
	var sess db.Database
	var tx *sql.Tx

	if sess, err = db.Open(Adapter, settings); err != nil {
		b.Fatal(err)
	}

	defer sess.Close()

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

	if tx, err = driver.Begin(); err != nil {
		b.Fatal(err)
	}

	if _, err = tx.Exec("TRUNCATE TABLE `artist`"); err != nil {
		b.Fatal(err)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if _, err = tx.Exec("INSERT INTO `artist` (`name`) VALUES('Hayao Miyazaki')"); err != nil {
			b.Fatal(err)
		}
	}

	if err = tx.Commit(); err != nil {
		b.Fatal(err)
	}
}
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
}
Example #6
0
// Trying to open an empty datasource, it must succeed (mongo).
func TestOpenFailed(t *testing.T) {
	_, err := db.Open(wrapperName, db.Settings{})

	if err != nil {
		t.Errorf(err.Error())
	}
}
Example #7
0
// Trying to open an empty datasource, it must fail.
func TestOpenFailed(t *testing.T) {
	_, err := db.Open(wrapperName, db.Settings{})

	if err == nil {
		t.Errorf("Expecting an error.")
	}
}
Example #8
0
// This test tries to remove some previously added rows.
func TestRemove(t *testing.T) {

	var err error

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

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

	// We should close the database when it's no longer in use.
	defer sess.Close()

	// Getting a pointer to the "artist" collection.
	artist, err := sess.Collection("artist")

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

	// Getting the artist with id = 1
	res := artist.Find(db.Cond{"id": 1})

	// Trying to remove the row.
	err = res.Remove()

	if err != nil {
		t.Fatalf(err.Error())
	}
}
Example #9
0
func TestSetup(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)
			}

			if setupFn[wrapper] == nil {
				t.Fatalf(`Missing setup function for wrapper %s.`, wrapper)
			} else {
				if err = setupFn[wrapper](sess.Driver()); err != nil {
					t.Fatalf(`Failed to setup wrapper %s: %q`, wrapper, err)
				}
			}

			err = sess.Close()
			if err != nil {
				t.Fatalf(`Could not close %s: %q`, wrapper, err)
			}

		}
	}
}
Example #10
0
// Benchmarking raw mgo queries.
func BenchmarkAppendRaw(b *testing.B) {
	sess, err := db.Open(Adapter, settings)

	if err != nil {
		b.Fatal(err)
	}

	defer sess.Close()

	artist, err := sess.Collection("artist")
	artist.Truncate()

	driver := sess.Driver().(*mgo.Session)

	mgodb := driver.DB(database)
	col := mgodb.C("artist")

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		err := col.Insert(map[string]string{"name": "Hayao Miyazaki"})
		if err != nil {
			b.Fatal(err)
		}
	}
}
Example #11
0
// This test tries to use an empty filter and count how many elements were
// added into the artist collection.
func TestResultCount(t *testing.T) {

	var err error
	var res db.Result

	// Opening database.
	sess, err := db.Open(Adapter, settings)

	if err != nil {
		t.Fatal(err)
	}

	defer sess.Close()

	// We should close the database when it's no longer in use.
	artist, _ := sess.Collection("artist")

	res = artist.Find()

	// Counting all the matching rows.
	total, err := res.Count()

	if err != nil {
		t.Fatal(err)
	}

	if total == 0 {
		t.Fatalf("Should not be empty, we've just added some rows!")
	}

}
Example #12
0
func main() {
	log.SetFlags(log.Lshortfile | log.Ldate | log.Ltime)

	go signalCatcher()
	go signalReload()

	var settings = db.Settings{
		Host:     "localhost", // MySQL server IP or name.
		Database: "Paoge",     // Database name.
		User:     "******",      // Optional user name.
		Password: "******",      // Optional user password.
	}
	session, err := db.Open("mysql", settings)
	defer session.Close()
	if err != nil {
		fmt.Println("DB Connection Error")
	}
	serviceCollection, err := session.Collection("service_results")
	if err != nil {
		fmt.Println("DB Table Connection Error")
	}
	serviceCollection.Append(data.ServiceResults{})

	http.HandleFunc("/nster/receive", receiveChecks).Name()
	log.Fatal(http.ListenAndServe(":9000", nil))
	select {}
}
Example #13
0
// Benchmarking Append() with transactions.
//
// 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()

	artist, err := sess.Collection("artist")
	artist.Truncate()

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

	for i := 0; i < b.N; i++ {
		_, err = artist.Append(map[string]string{"name": "Isaac Asimov"})
		if err != nil {
			b.Fatalf(err.Error())
		}
	}

	err = sess.End()
	if err != nil {
		b.Fatalf(err.Error())
	}
}
Example #14
0
File: main.go Project: pzduniak/db
func main() {

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

	if err != nil {
		fmt.Println("Unable to connect:", err.Error())
		return
	}

	defer sess.Close()

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

	if err != nil {
		if err != db.ErrCollectionDoesNotExists {
			fmt.Println("Could not use collection:", err.Error())
			return
		}
	} else {
		err = birthdayCollection.Truncate()

		if err != nil {
			fmt.Println(err.Error())
			return
		}
	}

	birthdayCollection.Append(Birthday{
		Name: "Hayao Miyazaki",
		Born: time.Date(1941, time.January, 5, 0, 0, 0, 0, time.UTC),
	})

	birthdayCollection.Append(Birthday{
		Name: "Nobuo Uematsu",
		Born: time.Date(1959, time.March, 21, 0, 0, 0, 0, time.UTC),
	})

	birthdayCollection.Append(Birthday{
		Name: "Hironobu Sakaguchi",
		Born: time.Date(1962, time.November, 25, 0, 0, 0, 0, time.UTC),
	})

	var res db.Result

	res = birthdayCollection.Find()

	var birthdays []Birthday

	err = res.All(&birthdays)

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

	for _, birthday := range birthdays {
		fmt.Printf("%s was born in %s.\n", birthday.Name, birthday.Born.Format("January 2, 2006"))
	}

}
Example #15
0
// 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!")
	}
}
Example #16
0
// 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)
		}
	}
}
Example #17
0
// 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.`)
	}

}
Example #18
0
File: main.go Project: pzduniak/db
func main() {

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

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

	defer sess.Close()

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

	if err != nil {
		fmt.Println(err.Error())
		return
	}

	err = birthdayCollection.Truncate()

	if err != nil {
		fmt.Println(err.Error())
		return
	}

	birthdayCollection.Append(Birthday{
		Name: "Hayao Miyazaki",
		Born: time.Date(1941, time.January, 5, 0, 0, 0, 0, time.UTC),
	})

	birthdayCollection.Append(Birthday{
		Name: "Nobuo Uematsu",
		Born: time.Date(1959, time.March, 21, 0, 0, 0, 0, time.UTC),
	})

	birthdayCollection.Append(Birthday{
		Name: "Hironobu Sakaguchi",
		Born: time.Date(1962, time.November, 25, 0, 0, 0, 0, time.UTC),
	})

	var res db.Result

	res = birthdayCollection.Find()

	var birthdays []Birthday

	err = res.All(&birthdays)

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

	for _, birthday := range birthdays {
		fmt.Printf("%s was born in %s.\n", birthday.Name, birthday.Born.Format("January 2, 2006"))
	}

}
Example #19
0
File: upperio.go Project: gourd/kit
// Open implements store.Source
func (src *Source) Open() (s store.Conn, err error) {
	database, err := db.Open(src.adapter, src.connURL)
	if err != nil {
		return
	}

	s = &Conn{db: database}
	return
}
Example #20
0
func main() {

	r := gin.Default()
	settings := mongo.ConnectionURL{
		Address:  db.Host("ds031763.mongolab.com:31763"), // MongoDB hostname.
		Database: "dirty-chat",                           // Database name.
		User:     "******",                              // Optional user name.
		Password: "******",
	}

	var err error

	Mng, err = db.Open(mongo.Adapter, settings)
	if err != nil {
		fmt.Println(err.Error())
	}

	defer Mng.Close()

	Store = sessions.NewCookieStore([]byte("nebdr84"))
	r.Use(sessions.Middleware("my_session", Store))
	r.Use(csrf.Middleware(csrf.Options{Secret: "nebdr84", IgnoreMethods: []string{"GET"}}))
	r.Use(static.Serve("/", static.LocalFile("assets", false)))
	r.Use(AuthInspector())
	r.Use(GlobalResources())
	rnd = render.New(render.Options{
		Directory:       "templates",                 // Specify what path to load the templates from.
		Layout:          "layout",                    // Specify a layout template. Layouts can call {{ yield }} to render the current template or {{ block "css" }} to render a block from the current template
		Extensions:      []string{".tmpl", ".html"},  // Specify extensions to load for templates.
		Delims:          render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings.
		Charset:         "UTF-8",                     // Sets encoding for json and html content-types. Default is "UTF-8".
		IndentJSON:      true,                        // Output human readable JSON.
		IndentXML:       false,
		PrefixJSON:      []byte(")]}',\n"), // Prefixes JSON responses with the given bytes.
		HTMLContentType: "text/html",       // Output XHTML content type instead of default "text/html".
		IsDevelopment:   true,              // Render will now recompile the templates on every HTML response.
		UnEscapeHTML:    true,              // Replace ensure '&<>' are output correctly (JSON only).
		StreamingJSON:   true,              // Streams the JSON response via json.Encoder.
	})

	r.LoadHTMLGlob("templates/*.html")

	r.Any("/", indexHandler)
	r.GET("/login", ShowLogin)
	r.POST("/login", Login)
	// r.GET("user/:name", controllers.ShowUser)
	//r.POST("user/:name", controllers.EditUser)

	r.GET("/sex", controllers.IndexSex)
	r.GET("/sex/:name/:edit", controllers.EditSex)
	r.DELETE("/sex/:name", controllers.DeleteSex)
	r.POST("/sex", controllers.CreateSex)
	r.POST("/sex/:name", controllers.UpdateSex)
	r.GET("/sex.json", controllers.IndexSexJson)

	r.Run(":3000")
}
Example #21
0
// Attempts to open an empty datasource.
func TestOpenFailed(t *testing.T) {
	var err error

	// Attempt to open an empty database.
	if _, err = db.Open(Adapter, db.Settings{}); err == nil {
		// Must fail.
		t.Fatalf("Expecting an error.")
	}
}
Example #22
0
// dbsetup sets up the database.
func dbsetup() error {
	var err error
	var databaseName string

	if *flagDatabase == "" {
		// Let's find an unused database file.
		for i := 0; ; i++ {
			databaseName = fmt.Sprintf(defaultDatabase, i)
			if _, err := os.Stat(databaseName); err != nil {
				// File does not exists (yet).
				// And that's OK.
				break
			}
		}
	} else {
		// Use the provided database name.
		databaseName = *flagDatabase
	}

	// Attempting to open database.
	if sess, err = db.Open(sqlite.Adapter, sqlite.ConnectionURL{Database: databaseName}); err != nil {
		log.Fatalf(ErrDatabaseConnection.Error(), err)
	}

	// Collection lookup.
	col, err = sess.Collection(defaultCaptureCollection)

	if err == nil {
		// Collection exists! Nothing else to do.
		log.Printf("Using database %s.", databaseName)
		return nil
	}

	log.Printf("Initializing database %s...", databaseName)

	if err != db.ErrCollectionDoesNotExist {
		// This error is different to a missing collection error.
		log.Fatalf(ErrDatabaseConnection.Error(), err)
	}

	// Collection does not exists, let's create it.
	if drv, ok := sess.Driver().(*sql.DB); ok {
		// Execute CREATE TABLE.
		if _, err = drv.Exec(collectionCreateSQL); err != nil {
			log.Fatalf(ErrDatabaseConnection.Error(), err)
		}
		// Try pulling collection again.
		if col, err = sess.Collection(defaultCaptureCollection); err != nil {
			log.Fatalf(ErrDatabaseConnection.Error(), err)
		}
	}

	return nil
}
Example #23
0
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.`)
	}
}
Example #24
0
// This test appends some data into the "artist" table.
func TestAppend(t *testing.T) {

	var err error
	var id interface{}

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

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

	// We should close the database when it's no longer in use.
	defer sess.Close()

	// Getting a pointer to the "artist" collection.
	artist, err := sess.Collection("artist")

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

	// Appending a map.
	id, err = artist.Append(map[string]string{
		"name": "Ozzie",
	})

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Appending a struct.
	id, err = artist.Append(struct {
		Name string `field:name`
	}{
		"Flea",
	})

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

	// Appending a struct (using tags to specify the field name).
	id, err = artist.Append(struct {
		ArtistName string `field:"name"`
	}{
		"Slash",
	})

	if to.Int64(id) == 0 {
		t.Fatalf("Expecting an ID.")
	}

}
Example #25
0
// 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()
}
Example #26
0
func Open(adapter string, url db.ConnectionURL) (Session, error) {
	conn, err := db.Open(adapter, url)
	if err != nil {
		return nil, err
	}

	sess := &session{
		Database: conn,
		stores:   make(map[string]*store),
	}

	return sess, nil
}
func openPostgresql(constr string) (Database, error) {
	settings, err := postgresql.ParseURL(constr)
	if err != nil {
		return Database{nil}, err
	}

	d, err := db.Open(postgresql.Adapter, settings)
	if err != nil {
		return Database{nil}, err
	}

	return Database{d}, nil
}
Example #28
0
// 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.")
	}
}
Example #29
0
// This test tries 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

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

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

	// We should close the database when it's no longer in use.
	defer sess.Close()

	// Getting a pointer to the "data_types" collection.
	dataTypes, err := sess.Collection("data_types")
	dataTypes.Truncate()

	// Appending our test subject.
	id, err := dataTypes.Append(testValues)

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

	// Trying to get the same subject we added.
	res, err = dataTypes.Find(db.Cond{"id": id})

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

	exists, err := res.Count()

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

	if exists == 0 {
		t.Errorf("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.Errorf("Struct is different.")
	}
}
Example #30
0
// dbsetup sets up the database.
func dbsetup() error {
	var err error
	// Attemping to establish a connection to the database.
	sess, err = db.Open(mongo.Adapter, settings)
	fmt.Println(sess)

	if err != nil {
		log.Fatalf("db.Open(): %q\n", err)
	}

	// Pointing to the "http_info" table.
	col, err = sess.Collection("http_info")

	return nil
}