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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
|
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0
package oblast_test
import (
"database/sql"
"strconv"
"testing"
"time"
"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 TestInsertBasic(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `oblast:"id,auto"`
Name string `oblast:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.StructTagKeyIs("oblast"), // this test also randomly provides coverage for this option
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
for _, batchSize := range []int{1, oblast.PrepareThreshold - 1, oblast.PrepareThreshold + 1} {
t.Run("N="+strconv.Itoa(batchSize), func(t *testing.T) {
records := make([]*basicRecord, batchSize)
for idx := range batchSize {
records[idx] = &basicRecord{Name: "new"}
md.ForQuery(`INSERT INTO "basic_records" ("name") VALUES (?) RETURNING "id"`).
ExpectQueryWithArgs("new").
AndReturnColumns("id").
WithRow(int64(42 + idx))
}
must.Succeed(t, store.Insert(db, records...))
for idx, r := range records {
assert.Equal(t, r.ID, int64(42+idx))
}
})
}
}
func TestUpdateBasic(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
for _, batchSize := range []int{1, oblast.PrepareThreshold - 1, oblast.PrepareThreshold + 1} {
t.Run("N="+strconv.Itoa(batchSize), func(t *testing.T) {
records := make([]basicRecord, batchSize)
for idx := range batchSize {
r := basicRecord{ID: int64(42 + idx), Name: "updated"}
records[idx] = r
md.ForQuery(`UPDATE "basic_records" SET "name" = ? WHERE "id" = ?`).
ExpectExecWithArgs(r.Name, r.ID).
AndReturnRowsAffected(1)
}
must.Succeed(t, store.Update(db, records...))
})
}
}
func TestDeleteBasic(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
for _, batchSize := range []int{1, oblast.PrepareThreshold - 1, oblast.PrepareThreshold + 1} {
t.Run("N="+strconv.Itoa(batchSize), func(t *testing.T) {
records := make([]basicRecord, batchSize)
for idx := range batchSize {
r := basicRecord{ID: int64(42 + idx), Name: "removed"}
records[idx] = r
md.ForQuery(`DELETE FROM "basic_records" WHERE "id" = ?`).
ExpectExecWithArgs(r.ID).
AndReturnRowsAffected(1)
}
must.Succeed(t, store.Delete(db, records...))
})
}
}
func TestUpsertBasicWithAutoColumn(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
md.ForQuery(`INSERT INTO "basic_records" ("name") VALUES (?) RETURNING "id"`).
ExpectQueryWithArgs("first needs insert").
AndReturnColumns("id").
WithRow(int64(1))
md.ForQuery(`UPDATE "basic_records" SET "name" = ? WHERE "id" = ?`).
ExpectExecWithArgs("second needs update", 2).
AndReturnRowsAffected(1)
md.ForQuery(`INSERT INTO "basic_records" ("name") VALUES (?) RETURNING "id"`).
ExpectQueryWithArgs("third needs insert").
AndReturnColumns("id").
WithRow(int64(3))
md.ForQuery(`UPDATE "basic_records" SET "name" = ? WHERE "id" = ?`).
ExpectExecWithArgs("fourth needs update", 4).
AndReturnRowsAffected(1)
records := []*basicRecord{
{Name: "first needs insert"},
{ID: 2, Name: "second needs update"},
{Name: "third needs insert"},
{ID: 4, Name: "fourth needs update"},
}
must.Succeed(t, store.Upsert(db, records...))
assert.SliceDeepEqual(t, records,
&basicRecord{ID: 1, Name: "first needs insert"},
&basicRecord{ID: 2, Name: "second needs update"},
&basicRecord{ID: 3, Name: "third needs insert"},
&basicRecord{ID: 4, Name: "fourth needs update"},
)
}
func TestWriteQueriesNotPossible(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
// no TableNameIs() or PrimaryKeyIs() given
)
r := basicRecord{Name: "foo"}
err := store.Insert(db, &r)
assert.ErrEqual(t, err, "cannot execute Insert() because query could not be autogenerated")
err = store.Upsert(db, &r)
assert.ErrEqual(t, err, "cannot execute Insert() because query could not be autogenerated")
r.ID = 42
err = store.Update(db, r)
assert.ErrEqual(t, err, "cannot execute Update() because query could not be autogenerated")
err = store.Delete(db, r)
assert.ErrEqual(t, err, "cannot execute Delete() because query could not be autogenerated")
}
func TestWriteQueriesFailDuringPrepare(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
for _, batchSize := range []int{1, oblast.PrepareThreshold - 1, oblast.PrepareThreshold + 1} {
records := make([]basicRecord, batchSize)
recordsForInsert := make([]*basicRecord, batchSize)
for idx := range batchSize {
records[idx] = basicRecord{ID: int64(42 + idx), Name: "foo"}
recordsForInsert[idx] = &basicRecord{Name: "foo"}
}
err := store.Insert(db, recordsForInsert...)
baseError := `unexpected query: INSERT INTO "basic_records" ("name") VALUES (?) RETURNING "id"`
if batchSize < oblast.PrepareThreshold {
assert.ErrEqual(t, err, "while inserting record with idx = 0: "+baseError)
} else {
assert.ErrEqual(t, err, "during Prepare(): "+baseError)
}
err = store.Update(db, records...)
baseError = `unexpected query: UPDATE "basic_records" SET "name" = ? WHERE "id" = ?`
if batchSize < oblast.PrepareThreshold {
assert.ErrEqual(t, err, "while updating record with idx = 0: "+baseError)
} else {
assert.ErrEqual(t, err, "during Prepare(): "+baseError)
}
err = store.Delete(db, records...)
baseError = `unexpected query: DELETE FROM "basic_records" WHERE "id" = ?`
if batchSize < oblast.PrepareThreshold {
assert.ErrEqual(t, err, "while deleting record with idx = 0: "+baseError)
} else {
assert.ErrEqual(t, err, "during Prepare(): "+baseError)
}
}
}
func TestUpdateOrUpsertFailsOnMissingRecord(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
// test Update()
md.ForQuery(`UPDATE "basic_records" SET "name" = ? WHERE "id" = ?`).
ExpectExecWithArgs("changed", 42).
AndReturnRowsAffected(0)
err := store.Update(db, basicRecord{ID: 42, Name: "changed"})
assert.ErrEqual(t, err, "could not UPDATE record that does not exist in the database: id = 42")
_, hasCorrectType := err.(oblast.MissingRecordError[basicRecord]) //nolint:errorlint // we explicitly do not want a wrapped error
assert.Equal(t, hasCorrectType, true)
// test Upsert() -> this will not try inserting because the strategy
// is chosen based on the fill state of the "auto" field
md.ForQuery(`UPDATE "basic_records" SET "name" = ? WHERE "id" = ?`).
ExpectExecWithArgs("changed", 42).
AndReturnRowsAffected(0)
err = store.Upsert(db, &basicRecord{ID: 42, Name: "changed"})
assert.ErrEqual(t, err, "could not UPDATE record that does not exist in the database: id = 42")
_, hasCorrectType = err.(oblast.MissingRecordError[basicRecord]) //nolint:errorlint // we explicitly do not want a wrapped error
assert.Equal(t, hasCorrectType, true)
}
func TestInsertFailsOnFilledAutoField(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type basicRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
}
store := oblast.MustNewStore[basicRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("basic_records"),
oblast.PrimaryKeyIs("id"),
)
md.ForQuery(`INSERT INTO "basic_records" ("name") VALUES (?) RETURNING "id"`).
ExpectQueryWithArgs("existing").
AndReturnColumns("id").
WithRow(42)
err := store.Insert(db, &basicRecord{ID: 23, Name: "third"})
assert.ErrEqual(t, err, `refusing to INSERT record with idx = 0 that already has non-zero values in its "auto" columns`)
}
func TestInsertAndUpsertWithNoAutoColumns(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type relation struct {
FooID int64 `db:"foo_id"`
BarID int64 `db:"bar_id"`
}
store := oblast.MustNewStore[relation](
oblast.SqliteDialect(),
oblast.TableNameIs("foo_bar_relations"),
oblast.PrimaryKeyIs("foo_id", "bar_id"),
)
// test Insert()
md.ForQuery(`INSERT INTO "foo_bar_relations" ("foo_id", "bar_id") VALUES (?, ?)`).
ExpectExecWithArgs(23, 42).
AndReturnRowsAffected(1)
must.Succeed(t, store.Insert(db, &relation{23, 42}))
// test Upsert()
md.ForQuery(`INSERT INTO "foo_bar_relations" ("foo_id", "bar_id") VALUES (?, ?) ON CONFLICT ("foo_id", "bar_id") DO NOTHING`).
ExpectExecWithArgs(1, 2).
AndReturnRowsAffected(1)
md.ForQuery(`INSERT INTO "foo_bar_relations" ("foo_id", "bar_id") VALUES (?, ?) ON CONFLICT ("foo_id", "bar_id") DO NOTHING`).
ExpectExecWithArgs(3, 4).
AndReturnRowsAffected(1)
must.Succeed(t, store.Upsert(db, &relation{1, 2}, &relation{3, 4}))
}
func TestUpsertFailsOnMixedAutoFieldState(t *testing.T) {
md := mock.NewDriver()
db := sql.OpenDB(md)
type complexRecord struct {
ID int64 `db:"id,auto"`
Name string `db:"name"`
CreatedAt time.Time `db:"created_at,auto"`
}
store := oblast.MustNewStore[complexRecord](
oblast.SqliteDialect(),
oblast.TableNameIs("complex_records"),
oblast.PrimaryKeyIs("id"),
)
brokenRecord := complexRecord{
ID: 42, // this looks like we need to UPDATE
Name: "foo",
CreatedAt: time.Time{}, // this looks like we need to INSERT
}
err := store.Upsert(db, &brokenRecord)
assert.ErrEqual(t, err, `cannot decide whether to INSERT or UPDATE record with idx = 0: some "auto" columns are zero, others are not`)
}
|