forked from jackskj/carta
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlx_test.go
More file actions
76 lines (62 loc) · 1.55 KB
/
Copy pathsqlx_test.go
File metadata and controls
76 lines (62 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package carta
import (
"testing"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
)
func setupSqlxDB(t *testing.T) *sqlx.DB {
db, err := sqlx.Open("sqlite3", ":memory:")
assert.NoError(t, err)
createAuthorTable := `
CREATE TABLE author (
id INTEGER PRIMARY KEY,
username TEXT
);`
_, err = db.Exec(createAuthorTable)
assert.NoError(t, err)
createBlogTable := `
CREATE TABLE blog (
id INTEGER PRIMARY KEY,
title TEXT,
author_id INTEGER
);`
_, err = db.Exec(createBlogTable)
assert.NoError(t, err)
_, err = db.Exec("INSERT INTO author (id, username) VALUES (?, ?)", 1, "johndoe")
assert.NoError(t, err)
_, err = db.Exec("INSERT INTO blog (id, title, author_id) VALUES (?, ?, ?)", 1, "My First Post", 1)
assert.NoError(t, err)
return db
}
type SqlxAuthor struct {
Id int `db:"id"`
Username string `db:"username"`
}
type SqlxBlog struct {
Id int `db:"id"`
Title string `db:"title"`
Author SqlxAuthor `carta:"author"`
}
func TestMapx(t *testing.T) {
db := setupSqlxDB(t)
defer db.Close()
query := `
SELECT
b.id,
b.title,
a.id AS "author->id",
a.username AS "author->username"
FROM blog b
LEFT JOIN author a ON b.author_id = a.id`
rows, err := db.Queryx(query)
assert.NoError(t, err)
var blogs []*SqlxBlog
err = Mapx(rows, &blogs)
assert.NoError(t, err)
assert.Len(t, blogs, 1)
assert.Equal(t, 1, blogs[0].Id)
assert.Equal(t, "My First Post", blogs[0].Title)
assert.Equal(t, 1, blogs[0].Author.Id)
assert.Equal(t, "johndoe", blogs[0].Author.Username)
}