advsql/db_test.go

56 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-07-05 12:38:39 +02:00
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)
2022-07-05 12:38:39 +02:00
}
func InsertUserEncoder(u *User, encode EncodeFunc) error {
return encode(u.Name, u.Hash, u.Salt)
2022-07-05 12:38:39 +02:00
}
func UpdateUserByNameEncoder(u *User, encode EncodeFunc) error {
return encode(u.Salt, u.Name)
2022-07-05 12:38:39 +02:00
}
func TestDB(t *testing.T) {
2022-07-11 13:28:07 +02:00
db := NewMysqlDatabase("ip", 3306, "username", "password", "database")
2022-07-05 12:38:39 +02:00
defer db.Close()
insertUser := Insert(db, "INSERT INTO users VALUES (?, ?, ?)", InsertUserEncoder)
2022-07-05 12:38:39 +02:00
updateUser := Update(db, "UPDATE users SET salt = ? WHERE name = ?", UpdateUserByNameEncoder)
2022-07-05 12:38:39 +02:00
2022-07-11 13:28:07 +02:00
getUsers := QueryMany(db, "SELECT * FROM users WHERE name = ?", UserDecoder)
2022-07-05 12:38:39 +02:00
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)
}
}