advsql/db_test.go
Timon Ringwald a39f467b93 QueryOne implemented
Query renamed to QueryMany
Default Decoders refactored
2022-07-11 13:00:36 +02:00

59 lines
1.2 KiB
Go

package advsql
import (
"crypto/sha512"
"encoding/hex"
"fmt"
"testing"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
Name string
Hash []byte
Salt string
}
func UserDecoder(u *User, decode DecodeFunc) error {
return decode(&u.Name, &u.Hash, &u.Salt)
}
func InsertUserEncoder(u *User, encode EncodeFunc) error {
return encode(u.Name, u.Hash, u.Salt)
}
func UpdateUserByNameEncoder(u *User, encode EncodeFunc) error {
return encode(u.Salt, u.Name)
}
func TestDB(t *testing.T) {
db, err := NewMysqlDatabase("ip", 3306, "username", "password", "database")
if err != nil {
t.Fatal(err)
}
defer db.Close()
insertUser := Insert(db, "INSERT INTO users VALUES (?, ?, ?)", InsertUserEncoder)
updateUser := Update(db, "UPDATE users SET salt = ? WHERE name = ?", UpdateUserByNameEncoder)
getUsers := Query(db, "SELECT * FROM users WHERE name = ?", UserDecoder)
pw := sha512.Sum512([]byte("weiter"))
timon := &User{
Name: "timon",
Hash: pw[:],
Salt: "salt",
}
fmt.Println("insert:", insertUser(timon))
timon.Hash = []byte("asd")
fmt.Println("update:", updateUser(timon))
for user := range getUsers("tordarus") {
fmt.Printf("name: \"%s\" | hash: \"%s\" | salt: \"%s\"\n", user.Name, hex.EncodeToString(user.Hash), user.Salt)
}
}