89 lines
2.1 KiB
Go
89 lines
2.1 KiB
Go
|
|
package stardb
|
||
|
|
|
||
|
|
import (
|
||
|
|
"testing"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
type User struct {
|
||
|
|
ID int64 `db:"id"`
|
||
|
|
Name string `db:"name"`
|
||
|
|
Email string `db:"email"`
|
||
|
|
Age int `db:"age"`
|
||
|
|
Balance float64 `db:"balance"`
|
||
|
|
Active bool `db:"active"`
|
||
|
|
CreatedAt time.Time `db:"created_at"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type Profile struct {
|
||
|
|
UserID int `db:"user_id"`
|
||
|
|
Bio string `db:"bio"`
|
||
|
|
Avatar string `db:"avatar"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type NestedUser struct {
|
||
|
|
ID int64 `db:"id"`
|
||
|
|
Name string `db:"name"`
|
||
|
|
Profile `db:"---"`
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestBuildInsertSQL(t *testing.T) {
|
||
|
|
user := User{
|
||
|
|
ID: 1,
|
||
|
|
Name: "Test",
|
||
|
|
Email: "test@example.com",
|
||
|
|
Age: 30,
|
||
|
|
Balance: 100.0,
|
||
|
|
Active: true,
|
||
|
|
CreatedAt: time.Now(),
|
||
|
|
}
|
||
|
|
|
||
|
|
query, params, err := buildInsertSQL(&user, "users", "id")
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("buildInsertSQL failed: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
expectedQuery := "INSERT INTO users (name, email, age, balance, active, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
||
|
|
if query != expectedQuery {
|
||
|
|
t.Errorf("Expected query:\n%s\nGot:\n%s", expectedQuery, query)
|
||
|
|
}
|
||
|
|
|
||
|
|
expectedParams := []string{":name", ":email", ":age", ":balance", ":active", ":created_at"}
|
||
|
|
if len(params) != len(expectedParams) {
|
||
|
|
t.Errorf("Expected %d params, got %d", len(expectedParams), len(params))
|
||
|
|
}
|
||
|
|
|
||
|
|
for i, param := range params {
|
||
|
|
if param != expectedParams[i] {
|
||
|
|
t.Errorf("Expected param %s, got %s", expectedParams[i], param)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestBuildUpdateSQL(t *testing.T) {
|
||
|
|
user := User{
|
||
|
|
ID: 1,
|
||
|
|
Name: "Test",
|
||
|
|
Email: "test@example.com",
|
||
|
|
Age: 30,
|
||
|
|
Balance: 100.0,
|
||
|
|
Active: true,
|
||
|
|
CreatedAt: time.Now(),
|
||
|
|
}
|
||
|
|
|
||
|
|
query, params, err := buildUpdateSQL(&user, "users", "id")
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("buildUpdateSQL failed: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
expectedQuery := "UPDATE users SET id = ?, name = ?, email = ?, age = ?, balance = ?, active = ?, created_at = ? WHERE id = ?"
|
||
|
|
if query != expectedQuery {
|
||
|
|
t.Errorf("Expected query:\n%s\nGot:\n%s", expectedQuery, query)
|
||
|
|
}
|
||
|
|
|
||
|
|
expectedParamCount := 8 // 7 fields + 1 primary key
|
||
|
|
if len(params) != expectedParamCount {
|
||
|
|
t.Errorf("Expected %d params, got %d", expectedParamCount, len(params))
|
||
|
|
}
|
||
|
|
}
|