63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
|
package simplesql_test
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"embed"
|
||
|
"testing"
|
||
|
|
||
|
ssql "git.simplesystems.tech/bjj-gym-management/simplesql"
|
||
|
"github.com/jmoiron/sqlx"
|
||
|
_ "github.com/mattn/go-sqlite3"
|
||
|
)
|
||
|
|
||
|
//go:embed sqlq
|
||
|
var sqlQueries embed.FS
|
||
|
|
||
|
type user struct {
|
||
|
Username string `db:"username"`
|
||
|
}
|
||
|
|
||
|
func TestNew(t *testing.T) {
|
||
|
// Create in-memory db for test
|
||
|
db, err := sqlx.Open("sqlite3", "file:temp.db?mode=memory")
|
||
|
if err != nil {
|
||
|
t.Fatalf("opening db: %v", err)
|
||
|
}
|
||
|
defer db.Close()
|
||
|
|
||
|
// Create table
|
||
|
if _, err := db.Exec("CREATE TABLE users(id INT, username VARCHAR)"); err != nil {
|
||
|
t.Fatalf("creating table: %v", err)
|
||
|
}
|
||
|
|
||
|
// Add users
|
||
|
if _, err := db.Exec("INSERT INTO users (id, username) VALUES (1, 'u1'), (2, 'u2')"); err != nil {
|
||
|
t.Fatalf("adding users: %v", err)
|
||
|
}
|
||
|
|
||
|
// Prepare statements
|
||
|
stmts, err := ssql.Prepare(context.TODO(), db, sqlQueries)
|
||
|
if err != nil {
|
||
|
t.Fatalf("preparing statements: %v", err)
|
||
|
}
|
||
|
defer stmts.Close()
|
||
|
|
||
|
if len(stmts) != 1 {
|
||
|
t.Errorf("expecting 1 statement, but got %d", len(stmts))
|
||
|
}
|
||
|
|
||
|
if _, ok := stmts["get_user"]; !ok {
|
||
|
t.Error("expecting get_user to be in stmts, but it is not")
|
||
|
}
|
||
|
|
||
|
// Get a user from the table, using the prepared statement
|
||
|
var res user
|
||
|
if err := stmts["get_user"].Get(&res, map[string]interface{}{"user_id": "2"}); err != nil {
|
||
|
t.Fatalf("getting users: %v", err)
|
||
|
}
|
||
|
|
||
|
if res.Username != "u2" {
|
||
|
t.Errorf("expecting u2, but got %s", res.Username)
|
||
|
}
|
||
|
}
|