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
|
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0
package oblast_test
import (
"database/sql"
"testing"
"go.xyrillian.de/oblast"
"go.xyrillian.de/oblast/internal/testhelpers/assert"
"go.xyrillian.de/oblast/internal/testhelpers/mock"
"go.xyrillian.de/oblast/internal/testhelpers/must"
)
func TestRuntimeIndex(t *testing.T) {
ctx := t.Context()
md := mock.NewDriver()
db := oblast.Wrap(sql.OpenDB(md))
type basicRecord struct {
ID int64 `db:"id"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
commonSetup := func() {
md.ForQuery(`SELECT "id", "name" FROM "basic_records" WHERE id > 0`).
ExpectQueryWithArgs().
AndReturnColumns("id", "name").
WithRow(1, "foo").
WithRow(2, "bar").
WithRow(3, "baz")
}
t.Run("Index", func(t *testing.T) {
byName := oblast.NewRuntimeIndex(func(r basicRecord) string { return r.Name })
// test success path
commonSetup()
result := must.Return(byName.IndexFrom(store.SelectWhere(ctx, db, `id > 0`)))(t)
assert.DeepEqual(t, result, map[string]basicRecord{
"foo": {1, "foo"},
"bar": {2, "bar"},
"baz": {3, "baz"},
})
// test error path
_, err := byName.IndexFrom(store.SelectWhere(ctx, db, `id = 1`))
assert.ErrEqual(t, err, `during Query(): unexpected query: SELECT "id", "name" FROM "basic_records" WHERE id = 1`)
})
t.Run("Partition", func(t *testing.T) {
byFirstLetter := oblast.NewRuntimeIndex(func(r basicRecord) string { return r.Name[0:1] })
// test success path
commonSetup()
result := must.Return(byFirstLetter.PartitionFrom(store.SelectWhere(ctx, db, `id > 0`)))(t)
assert.DeepEqual(t, result, map[string][]basicRecord{
"f": {{1, "foo"}},
"b": {{2, "bar"}, {3, "baz"}},
})
// test error path
_, err := byFirstLetter.PartitionFrom(store.SelectWhere(ctx, db, `id = 1`))
assert.ErrEqual(t, err, `during Query(): unexpected query: SELECT "id", "name" FROM "basic_records" WHERE id = 1`)
})
}
|