advsql/db_test.go
2022-07-12 17:56:06 +02:00

56 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 ScanFunc) error {
return decode(&u.Name, &u.Hash, &u.Salt)
}
func InsertUserEncoder(u *User, encode ScanFunc) error {
return encode(u.Name, u.Hash, u.Salt)
}
func UpdateUserByNameEncoder(u *User, encode ScanFunc) error {
return encode(u.Salt, u.Name)
}
func TestDB(t *testing.T) {
db := NewMysqlDatabase("ip", 3306, "username", "password", "database")
defer db.Close()
insertUser := Insert(db, "INSERT INTO users VALUES (?, ?, ?)", InsertUserEncoder)
updateUser := Update(db, "UPDATE users SET salt = ? WHERE name = ?", UpdateUserByNameEncoder)
getUsers := QueryMany(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)
}
}