forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_test.go
365 lines (302 loc) · 9.53 KB
/
state_test.go
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright 2024 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package domain
import (
"context"
"database/sql"
"fmt"
"sync/atomic"
"time"
"github.com/canonical/sqlair"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
schematesting "github.com/juju/juju/domain/schema/testing"
"github.com/juju/juju/internal/testing"
)
type stateSuite struct {
schematesting.ControllerSuite
}
var _ = gc.Suite(&stateSuite{})
func (s *stateSuite) TestStateBaseGetDB(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
}
func (s *stateSuite) TestStateBaseGetDBNilFactory(c *gc.C) {
base := NewStateBase(nil)
_, err := base.DB()
c.Assert(err, gc.ErrorMatches, `nil getDB`)
}
func (s *stateSuite) TestStateBasePrepare(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Prepare new query.
stmt1, err := base.Prepare("SELECT name AS &M.* FROM sqlite_schema", sqlair.M{})
c.Assert(err, jc.ErrorIsNil)
// Validate prepared statement works as expected.
var name any
err = db.Txn(context.Background(), func(ctx context.Context, tx *sqlair.TX) error {
results := sqlair.M{}
err := tx.Query(ctx, stmt1).Get(results)
if err != nil {
return err
}
name = results["name"]
return nil
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(name, gc.Equals, "schema")
// Retrieve previous statement.
stmt2, err := base.Prepare("SELECT name AS &M.* FROM sqlite_schema", sqlair.M{})
c.Assert(err, jc.ErrorIsNil)
c.Assert(stmt1, gc.Equals, stmt2)
}
func (s *stateSuite) TestStateBasePrepareKeyClash(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Check(db, gc.NotNil)
// Prepare statement with TestType.
{
type TestType struct {
WrongName string `db:"type"`
}
_, err := base.Prepare("SELECT &TestType.* FROM sqlite_schema", TestType{})
c.Assert(err, jc.ErrorIsNil)
}
// Prepare statement with a different type of the same name, this will
// retrieve the previously prepared statement which used the shadowed type.
type TestType struct {
Name string `db:"name"`
}
stmt, err := base.Prepare("SELECT &TestType.* FROM sqlite_schema", TestType{})
c.Assert(err, jc.ErrorIsNil)
// Try and run a query.
err = db.Txn(context.Background(), func(ctx context.Context, tx *sqlair.TX) error {
var results TestType
return tx.Query(ctx, stmt).Get(&results)
})
c.Assert(err, gc.ErrorMatches, `cannot get result: parameter with type "domain.TestType" missing, have type with same name: "domain.TestType"`)
}
func (s *stateSuite) TestStateBaseRunAtomicTransactionExists(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the transaction is sent via the AtomicContext.
var tx *sqlair.TX
err = base.RunAtomic(context.Background(), func(c AtomicContext) error {
tx = c.(*atomicContext).tx
return err
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(tx, gc.NotNil)
}
func (s *stateSuite) TestStateBaseRunAtomicPreventAtomicContextStoring(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// If the AtomicContext is stored outside of the transaction, it should
// not be possible to use it to perform state changes, as the sqlair.TX
// should be removed upon completion of the transaction.
var txCtx AtomicContext
err = base.RunAtomic(context.Background(), func(c AtomicContext) error {
txCtx = c
return err
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(txCtx, gc.NotNil)
// Convert the AtomicContext to the underlying type.
c.Check(txCtx.(*atomicContext).tx, gc.IsNil)
}
func (s *stateSuite) TestStateBaseRunAtomicContextValue(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the context is passed through to the AtomicContext.
type contextKey string
var key contextKey = "key"
ctx := context.WithValue(context.Background(), key, "hello")
var dbCtx AtomicContext
err = base.RunAtomic(ctx, func(c AtomicContext) error {
dbCtx = c
return err
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(dbCtx, gc.NotNil)
c.Check(dbCtx.Context().Value(key), gc.Equals, "hello")
}
func (s *stateSuite) TestStateBaseRunAtomicCancel(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Make sure that the context symantics are respected in terms of
// cancellation.
ctx, cancel := context.WithCancel(context.Background())
cancel()
err = base.RunAtomic(ctx, func(dbCtx AtomicContext) error {
c.Fatalf("should not be called")
return err
})
c.Assert(err, jc.ErrorIs, context.Canceled)
}
func (s *stateSuite) TestStateBaseRunAtomicWithRun(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the Run method is called.
var called bool
err = base.RunAtomic(context.Background(), func(txCtx AtomicContext) error {
return Run(txCtx, func(ctx context.Context, tx *sqlair.TX) error {
called = true
return nil
})
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
}
func (s *stateSuite) TestStateBaseRunAtomicWithRunMultipleTimes(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the Run method is called.
var called int
err = base.RunAtomic(context.Background(), func(txCtx AtomicContext) error {
for i := 0; i < 10; i++ {
if err := Run(txCtx, func(ctx context.Context, tx *sqlair.TX) error {
called++
return nil
}); err != nil {
return err
}
}
return nil
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, gc.Equals, 10)
}
func (s *stateSuite) TestStateBaseRunAtomicWithRunFailsConcurrently(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the run methods are correctly sequenced. Although there
// is no guarantee on the order of execution after the first run. This
// is undefined behaviour.
var called int64
err = base.RunAtomic(context.Background(), func(txCtx AtomicContext) error {
firstErr := make(chan error)
secondErr := make(chan error)
start := make(chan struct{})
go func() {
err := Run(txCtx, func(ctx context.Context, tx *sqlair.TX) error {
atomic.AddInt64(&called, 1)
defer atomic.AddInt64(&called, 1)
close(start)
<-time.After(time.Millisecond * 100)
return nil
})
firstErr <- err
}()
go func() {
select {
case <-start:
case <-time.After(testing.LongWait):
secondErr <- fmt.Errorf("failed to start in time")
return
}
err := Run(txCtx, func(ctx context.Context, tx *sqlair.TX) error {
// If the first goroutine run is still running, the called
// value will be 1. If it has completed, the called value
// will be 2. This isn't exact, but it should be good enough
// to ensure that the first run has completed.
if atomic.LoadInt64(&called) != 2 {
return fmt.Errorf("called before first run completed")
}
atomic.AddInt64(&called, 1)
return nil
})
secondErr <- err
}()
select {
case err := <-firstErr:
if err != nil {
return err
}
case <-time.After(testing.LongWait):
return fmt.Errorf("failed to complete first run in time")
}
select {
case err := <-secondErr:
return err
case <-time.After(testing.LongWait):
return fmt.Errorf("failed to complete second run in time")
}
})
c.Assert(err, jc.ErrorIsNil)
// Ensure that this is 3. 0 implies that it was never run, 1 implies that
// the first run was never completed, 2 shows that the first run was
// completed. Lastly 3 states that everything was run.
c.Assert(called, gc.Equals, int64(3))
}
func (s *stateSuite) TestStateBaseRunAtomicWithRunPreparedStatements(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the Run method can use sqlair prepared statements.
type N struct {
Name string `db:"name"`
}
stmt, err := base.Prepare("SELECT &N.* FROM sqlite_schema WHERE name='schema'", N{})
c.Assert(err, jc.ErrorIsNil)
var result []N
err = base.RunAtomic(context.Background(), func(txCtx AtomicContext) error {
return Run(txCtx, func(ctx context.Context, tx *sqlair.TX) error {
return tx.Query(ctx, stmt).GetAll(&result)
})
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(result, gc.HasLen, 1)
c.Check(result[0].Name, gc.Equals, "schema")
}
func (s *stateSuite) TestStateBaseRunAtomicWithRunDoesNotLeakError(c *gc.C) {
f := s.TxnRunnerFactory()
base := NewStateBase(f)
db, err := base.DB()
c.Assert(err, jc.ErrorIsNil)
c.Assert(db, gc.NotNil)
// Ensure that the Run method does not leak sql.ErrNoRows.
type N struct {
Name string `db:"name"`
}
stmt, err := base.Prepare("SELECT &N.* FROM sqlite_schema WHERE name='something something something'", N{})
c.Assert(err, jc.ErrorIsNil)
var result N
err = base.RunAtomic(context.Background(), func(txCtx AtomicContext) error {
return Run(txCtx, func(ctx context.Context, tx *sqlair.TX) error {
return tx.Query(ctx, stmt).Get(&result)
})
})
c.Assert(err, gc.Not(jc.ErrorIs), sql.ErrNoRows)
c.Assert(err, gc.Not(jc.ErrorIs), sqlair.ErrNoRows)
}