Finally figured out how to get sqlx to query an object based on a reflect.Type.
This commit is contained in:
parent
859e3ad0e3
commit
59a71534ae
2 changed files with 45 additions and 2 deletions
|
@ -8,6 +8,7 @@ type Login struct {
|
|||
}
|
||||
|
||||
type User struct {
|
||||
Id int `db:"id" json:"id" validate:"isdefault"`
|
||||
Username string `db:"username" validate:"required,max=30"`
|
||||
Email string `db:"email" validate:"required,email,max=128"`
|
||||
Password string `db:"password" validate:"required,min=8,max=64"`
|
||||
|
|
|
@ -1,15 +1,53 @@
|
|||
package tests
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"testing"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"log"
|
||||
"zedshaw.games/webapp/data"
|
||||
// _ "github.com/mattn/go-sqlite3"
|
||||
// "github.com/jmoiron/sqlx"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
sq "github.com/Masterminds/squirrel"
|
||||
)
|
||||
|
||||
func SelectTable1(table string, theType reflect.Type, err error, sql_query string, args ...interface{}) (error) {
|
||||
db, err := sql.Open("sqlite3", "./db.sqlite3")
|
||||
defer db.Close()
|
||||
|
||||
rows, err := db.Query(sql_query, args...)
|
||||
if err != nil { log.Fatal(err) }
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
data := make([]interface{}, theType.NumField())
|
||||
columns := make([]interface{}, theType.NumField())
|
||||
|
||||
for i := 0; i < len(columns); i++ {
|
||||
columns[i] = &data[i]
|
||||
}
|
||||
|
||||
rows.Scan(columns...)
|
||||
|
||||
fmt.Println(data)
|
||||
}
|
||||
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func SelectTable2(theType reflect.Type, err error, sql_query string, args ...interface{}) (error) {
|
||||
|
||||
the_data := reflect.New(theType)
|
||||
|
||||
err = data.DB.Get(the_data.Interface(), sql_query, args...)
|
||||
|
||||
fmt.Println("select after says", the_data)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func TestAdminIndexPage(t *testing.T) {
|
||||
|
||||
models := data.Models()
|
||||
|
||||
for table, model := range models {
|
||||
|
@ -19,5 +57,9 @@ func TestAdminIndexPage(t *testing.T) {
|
|||
for _, field := range fields {
|
||||
fmt.Println("\t", field.Name, field.Type, field.Tag)
|
||||
}
|
||||
|
||||
sql, args, err := sq.Select("*").From(table).ToSql()
|
||||
err = SelectTable2(model, err, sql, args...)
|
||||
if err != nil { fmt.Println("ERROR", err) }
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue