9
9
"testing"
10
10
"time"
11
11
12
- "github.com/xataio/pgroll/internal/testutils"
13
-
14
12
"github.com/stretchr/testify/require"
13
+
14
+ "github.com/xataio/pgroll/internal/testutils"
15
15
"github.com/xataio/pgroll/pkg/db"
16
16
)
17
17
@@ -37,6 +37,30 @@ func TestExecContext(t *testing.T) {
37
37
})
38
38
}
39
39
40
+ func TestExecContextWhenContextCancelled (t * testing.T ) {
41
+ t .Parallel ()
42
+
43
+ testutils .WithConnectionToContainer (t , func (conn * sql.DB , connStr string ) {
44
+ ctx := context .Background ()
45
+ ctx , cancel := context .WithCancel (ctx )
46
+
47
+ // create a table on which an exclusive lock is held for 2 seconds
48
+ setupTableLock (t , connStr , 2 * time .Second )
49
+
50
+ // set the lock timeout to 100ms
51
+ ensureLockTimeout (t , conn , 100 )
52
+
53
+ // execute a query that should retry until the lock is released
54
+ rdb := & db.RDB {DB : conn }
55
+
56
+ // Cancel the context before the lock times out
57
+ go time .AfterFunc (500 * time .Millisecond , cancel )
58
+
59
+ _ , err := rdb .ExecContext (ctx , "INSERT INTO test(id) VALUES (1)" )
60
+ require .Errorf (t , err , "context canceled" )
61
+ })
62
+ }
63
+
40
64
func TestWithRetryableTransaction (t * testing.T ) {
41
65
t .Parallel ()
42
66
@@ -58,6 +82,32 @@ func TestWithRetryableTransaction(t *testing.T) {
58
82
})
59
83
}
60
84
85
+ func TestWithRetryableTransactionWhenContextCancelled (t * testing.T ) {
86
+ t .Parallel ()
87
+
88
+ testutils .WithConnectionToContainer (t , func (conn * sql.DB , connStr string ) {
89
+ ctx := context .Background ()
90
+ ctx , cancel := context .WithCancel (ctx )
91
+
92
+ // create a table on which an exclusive lock is held for 2 seconds
93
+ setupTableLock (t , connStr , 2 * time .Second )
94
+
95
+ // set the lock timeout to 100ms
96
+ ensureLockTimeout (t , conn , 100 )
97
+
98
+ // run a transaction that should retry until the lock is released
99
+ rdb := & db.RDB {DB : conn }
100
+
101
+ // Cancel the context before the lock times out
102
+ go time .AfterFunc (500 * time .Millisecond , cancel )
103
+
104
+ err := rdb .WithRetryableTransaction (ctx , func (ctx context.Context , tx * sql.Tx ) error {
105
+ return tx .QueryRowContext (ctx , "SELECT 1 FROM test" ).Err ()
106
+ })
107
+ require .Errorf (t , err , "context canceled" )
108
+ })
109
+ }
110
+
61
111
// setupTableLock:
62
112
// * connects to the database
63
113
// * creates a table in the database
0 commit comments