示例#1
0
文件: server.go 项目: picatic/norm
func main() {
	mysqlUri := flag.String("mysql", "mysql://*****:*****@localhost:3306/norm_demo", "provide a database/sql driver uri")
	flag.Parse()
	dbUri, _ := url.Parse(*mysqlUri)
	// configure sql driver and dbr
	var dbUriString = ""

	username := dbUri.User.Username()
	password, hasPassword := dbUri.User.Password()
	if hasPassword {
		dbUriString = fmt.Sprintf("%s:%s@", username, password)
	} else {
		dbUriString = fmt.Sprintf("%s@", username)
	}

	dbUriString = fmt.Sprintf("%s(%s)%s?parseTime=true", dbUriString, dbUri.Host, dbUri.Path)
	log.Printf("uri %s", dbUriString)
	db, err := sql.Open("mysql", dbUriString)
	if err != nil {
		log.Fatal(err)
	}
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}
	normConnection = norm.NewConnection(db, "norm", nil)

	// register some handlers
	http.HandleFunc("/users", usersHandler)
	http.HandleFunc("/users/[0-9]?", usersIdHandler)
	err = http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}
示例#2
0
func ExampleConnection_selectBySql() {

	user := &User{}

	// Mock Database Connection to expect a query and return row data
	db, mock, err := sqlmock.New()
	if err != nil {
		log.Fatal("an error'%s' was not expected while open mock database", err)
	}

	rows := sqlmock.NewRows([]string{"id"}).AddRow("5432")

	mock.ExpectQuery("SELECT 1").WillReturnRows(rows)

	// Create norm Connection and Session for sqlmock
	connection := norm.NewConnection(db, "norm_database", nil)
	session := connection.NewSession(nil)

	// Query and load mocked result into Model
	err = session.SelectBySql("SELECT 1").LoadStruct(user)
	if err != nil {
		log.Fatal(err.Error())
	}

	// Compare query executed versus query provided
	err = mock.ExpectationsWereMet()
	if err != nil {
		fmt.Println(err.Error())
	}

	outputJson(user)
	// Output:
	// {"id":5432,"first_name":"","last_name":"","email":""}

}
示例#3
0
func ExampleNewSelect() {

	cnx := norm.NewConnection(nil, "norm_mysql", nil)
	dbrSess := cnx.NewSession(nil)

	user := &User{}
	user.Id.Scan(1)

	selectBuilder := norm.NewSelect(dbrSess, user, nil)
	selectSql, selectArgs := selectBuilder.ToSql()

	fmt.Println("DML:", selectSql)
	fmt.Println("ARGS:", selectArgs)

	// Output:
	// DML: SELECT `id`, `first_name`, `last_name`, `email` FROM norm_mysql.norm_users
	// ARGS: []

}
示例#4
0
func ExampleNewDelete() {

	cnx := norm.NewConnection(nil, "norm_mysql", nil)
	dbrSess := cnx.NewSession(nil)

	user := &User{}
	user.Id.Scan(5432)

	deleteBuilder := norm.NewDelete(dbrSess, user).Where("id = ?", user.Id.Int64)
	deleteSql, deleteArgs := deleteBuilder.ToSql()

	fmt.Println("DML:", deleteSql)
	fmt.Printf("ARGS: ")
	outputJson(deleteArgs)

	// Output:
	// DML: DELETE FROM `norm_mysql`.`norm_users` WHERE (id = ?)
	// ARGS: [5432]

}
示例#5
0
func ExampleNewInsert() {

	cnx := norm.NewConnection(nil, "norm_mysql", nil)
	dbrSess := cnx.NewSession(nil)

	user := &User{}
	user.FirstName.Scan("Zim")
	user.LastName.Scan("Ham")
	user.Email.Scan("*****@*****.**")

	insertBuilder := norm.NewInsert(dbrSess, user, nil).Record(user)
	insertSql, insertArgs := insertBuilder.ToSql()

	fmt.Println("DML:", insertSql)
	fmt.Printf("ARGS: ")
	outputJson(insertArgs)

	// Output:
	// DML: INSERT INTO `norm_mysql`.`norm_users` (`first_name`,`last_name`,`email`) VALUES (?,?,?)
	// ARGS: ["Zim","Ham","*****@*****.**"]

}
示例#6
0
func ExampleNewUpdate() {

	cnx := norm.NewConnection(nil, "norm_mysql", nil)
	dbrSess := cnx.NewSession(nil)

	user := &User{}
	user.Id.Scan(1)
	user.FirstName.Scan("Zim")
	user.LastName.Scan("Ham")
	user.Email.Scan("*****@*****.**")

	updateBuilder := norm.NewUpdate(dbrSess, user, nil).Where("id = ?", user.Id.Int64)
	updateSql, updateArgs := updateBuilder.ToSql()

	fmt.Println("DML:", updateSql)
	fmt.Printf("ARGS: ")
	outputJson(updateArgs)

	// https://github.com/picatic/norm/issues/4
	// Unstable Field Order Output:
	// DML: UPDATE norm_mysql.norm_users SET `first_name` = ?, `last_name` = ?, `email` = ? WHERE (id = ?)
	// ARGS:["Zim","Ham","*****@*****.**",1]

}
示例#7
0
func ExampleConnection_newSelect() {

	user := &User{}

	// Mock Database Connection to expect a query and return row data
	db, mock, err := sqlmock.New()
	if err != nil {
		log.Fatal("an error'%s' was not expected while open mock database", err)
	}

	rows := sqlmock.NewRows([]string{"id", "email"}).AddRow(5432, "*****@*****.**")

	// ExpectQuery is a regexp, escape regex tokens like `\\(` and `\\)`
	mock.ExpectQuery("SELECT `id`, `email` FROM norm_database.norm_users WHERE \\(id = 5432\\)").WillReturnRows(rows)

	// Create norm Connection and Session for sqlmock
	connection := norm.NewConnection(db, "norm_database", nil)
	session := connection.NewSession(nil)

	// Perform and load mocked result into Model
	err = norm.NewSelect(session, user, field.Names{"id", "email"}).Where("id = ?", 5432).LoadStruct(user)
	if err != nil {
		log.Fatal(err.Error())
	}

	// Compare query executed versus query provided
	err = mock.ExpectationsWereMet()
	if err != nil {
		fmt.Println(err.Error())
	}

	outputJson(user)
	// Output:
	// {"id":5432,"first_name":"","last_name":"","email":"*****@*****.**"}

}