Ejemplo n.º 1
0
func Example() {
	type User struct {
		ID           int64      `sql:"column:id"`
		Name         string     `sql:"column:name"`
		DateCreation *time.Time `sql:"column:date_creation"`
	}
	db, _ := sql.Open("sqlite3", ":memory:")
	defer db.Close()
	for _, statement := range []string{
		`CREATE TABLE users(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                date_creation TIMESTAMP NOT NULL DEFAULT(DATETIME('now'))
            );`,
		"INSERT INTO users(name) values('john doe'),('jane doe');",
	} {
		db.Exec(statement)
	}

	rows, _ := db.Query("SELECT * FROM users;")
	users := []*User{}
	err := mapper.MapRowsToSliceOfStruct(rows, &users, false)
	fmt.Println(err)
	fmt.Println(len(users))
	fmt.Println(users[0].Name)
	// Output:
	// <nil>
	// 2
	// john doe

}
Ejemplo n.º 2
0
func TestMapRowsToSliceOfStruct(t *testing.T) {
	type User struct {
		ID           int64
		Name         string
		DateCreation *time.Time
	}
	db, err := sql.Open("sqlite3", ":memory:")
	defer db.Close()
	ex.Expect(t, err, nil, "sql.Open")
	for _, statement := range []string{
		`CREATE TABLE users(
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			name TEXT NOT NULL,
			date_creation TIMESTAMP NOT NULL DEFAULT(DATETIME('now'))
		);`,
		"INSERT INTO users(name) values('john doe');",
		"INSERT INTO users(name) values('jane doe');",
	} {
		_, err := db.Exec(statement)
		ex.Expect(t, err, nil, "db.Exec("+statement+")")
	}
	t.Run("Simple Row/Struct Mapping", func(t *testing.T) {
		rows, err := db.Query("SELECT id as ID,name as Name,date_creation as DateCreation FROM users;")
		ex.Expect(t, err, nil, "db.Query")
		users := []*User{}
		err = mapper.MapRowsToSliceOfStruct(rows, &users, false)
		ex.Expect(t, err, nil, "map rows to slice of structs")
		ex.Expect(t, len(users), 2, "len(users)")
	})
}