Example #1
0
func Init(host, dbname, user, passwd string, count int) {
	if count > mysql_conn_max_num {
		count = mysql_conn_max_num
	} else if count < mysql_conn_min_num {
		count = mysql_conn_min_num
	}

	var settings = db.DataSource{
		Host:     host,
		Database: dbname,
		User:     user,
		Password: passwd,
	}

	dbCh := make(chan *sql.DB, count)

	for i := 0; i < count; i++ {
		sess, err := db.Open("mysql", settings)
		if err != nil {
			panic(err)
		}

		drv := sess.Driver().(*sql.DB)
		if err := drv.Ping(); err != nil {
			panic(err)
		}

		dbCh <- drv
	}

	g_mysql = &MysqlManager{dbCh, count}

	return
}
Example #2
0
func TestAppend(t *testing.T) {

	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

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

	if err == nil {
		t.Errorf("Collection should not exists.")
		//return
	}

	people := sess.ExistentCollection("people")

	people.Truncate()

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

	for i := 0; i < len(names); i++ {
		people.Append(db.Item{"name": names[i]})
	}

	total, _ := people.Count()

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

}
Example #3
0
func TestPopulate(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

	people, _ := sess.Collection("people")
	places, _ := sess.Collection("places")
	children, _ := sess.Collection("children")
	visits, _ := sess.Collection("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 k := 0; k < 3; k++ {
			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 #4
0
func TestDelete(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

	people := sess.ExistentCollection("people")

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

	if err != nil {
		t.Error("Failed to remove.")
	}

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

	if len(result) > 0 {
		t.Error("Could not remove a recently appended item.")
	}
}
Example #5
0
func Database(name string) db.Database {
	if _, ok := sess[name]; ok == false {
		driver, settings := datasource.Config(name)
		sess[name] = db.Open(driver, settings)
		if sess[name] == nil {
			panic(fmt.Sprintf("resource: Cannot open resource %s.", name))
		}
	}
	return sess[name]
}
Example #6
0
func TestOpen(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: "1.1.1.1"})

	if err != nil {
		t.Logf("Got %t, this was intended.", err)
		return
	}

	sess.Close()

	t.Errorf("Reached.")
}
Example #7
0
func TestDrop(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

	sess.Drop()
}
Example #8
0
func TestAuthFail(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname, User: "******", Password: "******"})

	if err != nil {
		t.Logf("Got %t, this was intended.", err)
		return
	}

	sess.Close()

	t.Errorf("Reached.")
}
Example #9
0
File: main.go Project: kdar/db
func main() {

	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 := animals.FindAll()

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

}
Example #10
0
func TestCustom(t *testing.T) {
	sess, err := db.Open("mysql", db.DataSource{Host: host, Database: dbname, User: username, Password: password})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

	_, err = sess.Driver().(*sql.DB).Query("SELECT NOW()")

	if err != nil {
		panic(err)
	}

}
Example #11
0
File: main.go Project: kdar/db
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":  sugar.List{"Puppy", "Pup"},
		"female": "Bitch",
		"male":   "Dog",
		"group":  "Pack",
	})

	items := animals.FindAll()

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

}
Example #12
0
func TestFind(t *testing.T) {

	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

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

	result := people.Find(db.Cond{"name": "José"})

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

}
Example #13
0
func TestUpdate(t *testing.T) {
	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

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

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

	result := people.Find(db.Cond{"name": "Joseph"})

	if len(result) == 0 {
		t.Error("Could not update a recently appended item.")
	}
}
Example #14
0
func TestDelete(t *testing.T) {
	sess, err := db.Open("mysql", db.DataSource{Host: host, Database: dbname, User: username, Password: password})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

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

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

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

	if len(result) > 0 {
		t.Error("Could not remove a recently appended item.")
	}
}
Example #15
0
func TestFind(t *testing.T) {

	sess, err := db.Open("mysql", db.DataSource{Host: host, Database: dbname, User: username, Password: password})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

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

	result := people.Find(db.Cond{"name": "José"})

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

}
Example #16
0
func TestRelation(t *testing.T) {
	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

	people, _ := sess.Collection("people")
	places, _ := sess.Collection("places")
	children, _ := sess.Collection("children")
	visits, _ := sess.Collection("visits")

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

	fmt.Printf("%# v\n", pretty.Formatter(result))
}
Example #17
0
func TestDelete(t *testing.T) {
	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

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

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

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

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

}
Example #18
0
func TestFind(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

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

	result := people.Find(db.Cond{"name": "José"})

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

}
Example #19
0
func TestAppend(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

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

	if col.Exists() == true {
		t.Errorf("Collection should not exists, yet.")
		return
	}

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

	for i := 0; i < len(names); i++ {
		col.Append(db.Item{"name": names[i]})
	}

	if col.Exists() == false {
		t.Errorf("Collection should exists.")
		return
	}

	count, err := col.Count()

	if err != nil {
		t.Error("Failed to count on collection.")
	}

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

}
Example #20
0
func TestRelation(t *testing.T) {
	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

	if err != nil {
		panic(err)
	}

	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("%# v\n", pretty.Formatter(results))
}
Example #21
0
func (l *MysqlLogMgr) Init(config *Config) error {
	if config.MysqlLog == false {
		return errors.New("mysql log server not configure!!!")
	}

	settings := db.DataSource{
		Host:     config.Host,
		Port:     config.Port,
		Database: config.Database,
		User:     config.User,
		Password: config.Password,
		Charset:  config.Charset,
	}

	session, err := db.Open("mysql", settings)
	if err != nil {
		return err
	}
	db := session.Driver().(*sql.DB)
	if err := db.Ping(); err != nil {
		fmt.Println("db.Ping failed:", err)
		return err
	}

	l.init = true
	l.waitGroup = sync_.NewWaitGroup()
	l.logMsgCh = make(chan *LogMsg, getChildLogScaleSize())
	l.logSql = make(chan string, 10)
	l.logLevel = config.MysqlLogLevel
	l.session = session

	for i := 0; i < 10; i++ {
		go l.run()
	}
	go l.writeDB()
	return nil
}
Example #22
0
func TestTruncate(t *testing.T) {

	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

	collections := sess.Collections()

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

		total, _ := col.Count()

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

}
Example #23
0
func TestTruncate(t *testing.T) {

	sess, err := db.Open("mysql", db.DataSource{Host: host, Database: dbname, User: username, Password: password})

	if err != nil {
		panic(err)
	}

	defer sess.Close()

	collections := sess.Collections()

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

		total, _ := col.Count()

		if total != 0 {
			t.Errorf("Could not truncate '%s'.", name)
		}
	}

}
Example #24
0
func TestUpdate(t *testing.T) {
	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

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

	defer sess.Close()

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

	err = people.Update(db.Cond{"name": "José"}, db.Set{"name": "Joseph"})

	if err != nil {
		t.Error("Failed to update collection.")
	}

	result := people.Find(db.Cond{"name": "Joseph"})

	if len(result) == 0 {
		t.Error("Could not update a recently appended item.")
	}
}
Example #25
0
File: main.go Project: kdar/db
func main() {

	var ids []db.Id
	var err error

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

	if err != nil {
		panic(err)
	}

	sess.Drop()

	defer sess.Close()

	peopleIAdmire, _ := sess.Collection("peopleIAdmire")
	worksOfPeopleIAdmire, _ := sess.Collection("worksOfPeopleIAdmire")

	// APPENDING PEOPLE

	// 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

	// 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 := peopleIAdmire.FindAll(
		db.RelateAll{
			"works": db.On{
				worksOfPeopleIAdmire,
				db.Cond{"author_id": "{_id}"},
			},
		},
	)

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

	for _, person := range peopleAndWorks {

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

		for _, work := range person["works"].([]db.Item) {
			fmt.Printf("* %s, %d.\n", work.GetString("name"), work.GetInt("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 #26
0
func TestDataTypes(t *testing.T) {

	sess, err := db.Open("sqlite", db.DataSource{Database: dbpath})

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

	defer sess.Close()

	dataTypes, _ := sess.Collection("data_types")

	dataTypes.Truncate()

	testData := testItem()

	ids, err := dataTypes.Append(testData)

	if err != nil {
		t.Errorf("Could not append test data: %s.", err.Error())
	}

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

	if found == 0 {
		t.Errorf("Cannot find recently inserted item (by ID).")
	}

	// Getting and reinserting.

	item := dataTypes.Find()

	_, err = dataTypes.Append(item)

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

	delete(item, "id")

	_, err = dataTypes.Append(item)

	if err != nil {
		t.Errorf("Could not append second element: %s.", err.Error())
	}

	// Testing rows

	results := dataTypes.FindAll()

	for _, item := range results {

		for key, _ := range item {

			switch key {

			// Signed integers.
			case
				"_int",
				"_int8",
				"_int16",
				"_int32",
				"_int64":
				if item.GetInt(key) != int64(testData["_int"].(int)) {
					t.Errorf("Wrong datatype %v.", key)
				}

			// Unsigned integers.
			case
				"_uint",
				"_uintptr",
				"_uint8",
				"_uint16",
				"_uint32",
				"_uint64",
				"_byte",
				"_rune":
				if item.GetInt(key) != int64(testData["_uint"].(uint)) {
					t.Errorf("Wrong datatype %v.", key)
				}

			// Floating point.
			case "_float32":
			case "_float64":
				if item.GetFloat(key) != testData["_float64"].(float64) {
					t.Errorf("Wrong datatype %v.", key)
				}

			// Boolean
			case "_bool":
				if item.GetBool(key) != testData["_bool"].(bool) {
					t.Errorf("Wrong datatype %v.", key)
				}

			// String
			case "_string":
				if item.GetString(key) != testData["_string"].(string) {
					t.Errorf("Wrong datatype %v.", key)
				}

			/*
				// Map
				case "_map":
					if item.GetTuple(key)["a"] != testData["_map"].(sugar.Tuple)["a"] {
						t.Errorf("Wrong datatype %v.", key)
					}

				// Array
				case "_list":
					if item.GetList(key)[0] != testData["_list"].(sugar.List)[0] {
						t.Errorf("Wrong datatype %v.", key)
					}
			*/

			// Date
			case "_date":
				if item.GetDate(key).Equal(testData["_date"].(time.Time)) == false {
					t.Errorf("Wrong datatype %v.", key)
				}
			}
		}
	}

}