diff --git a/batch_test.go b/batch_test.go index 44abbd8e..8d38f466 100644 --- a/batch_test.go +++ b/batch_test.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "testing" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" @@ -17,7 +18,10 @@ import ( func TestConnSendBatch(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server serial type is incompatible with test") sql := `create temporary table ledger( @@ -36,7 +40,7 @@ func TestConnSendBatch(t *testing.T) { batch.Queue("select * from ledger where false") batch.Queue("select sum(amount) from ledger") - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) ct, err := br.Exec() if err != nil { @@ -152,7 +156,10 @@ func TestConnSendBatch(t *testing.T) { func TestConnSendBatchQueuedQuery(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server serial type is incompatible with test") sql := `create temporary table ledger( @@ -237,7 +244,7 @@ func TestConnSendBatchQueuedQuery(t *testing.T) { return nil }) - err := conn.SendBatch(context.Background(), batch).Close() + err := conn.SendBatch(ctx, batch).Close() assert.NoError(t, err) }) } @@ -245,7 +252,10 @@ func TestConnSendBatchQueuedQuery(t *testing.T) { func TestConnSendBatchMany(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { sql := `create temporary table ledger( id serial primary key, description varchar not null, @@ -262,7 +272,7 @@ func TestConnSendBatchMany(t *testing.T) { } batch.Queue("select count(*) from ledger") - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) for i := 0; i < numInserts; i++ { ct, err := br.Exec() @@ -290,9 +300,12 @@ func TestConnSendBatchWithPreparedStatement(t *testing.T) { pgx.QueryExecModeExec, // Don't test simple mode with prepared statements. } - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, modes, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, modes, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server issues incorrect ParameterDescription (https://github.com/cockroachdb/cockroach/issues/60907)") - _, err := conn.Prepare(context.Background(), "ps1", "select n from generate_series(0,$1::int) n") + _, err := conn.Prepare(ctx, "ps1", "select n from generate_series(0,$1::int) n") if err != nil { t.Fatal(err) } @@ -304,7 +317,7 @@ func TestConnSendBatchWithPreparedStatement(t *testing.T) { batch.Queue("ps1", 5) } - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) for i := 0; i < queryCount; i++ { rows, err := br.Query() @@ -337,13 +350,16 @@ func TestConnSendBatchWithPreparedStatement(t *testing.T) { func TestConnSendBatchWithQueryRewriter(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { batch := &pgx.Batch{} batch.Queue("something to be replaced", &testQueryRewriter{sql: "select $1::int", args: []any{1}}) batch.Queue("something else to be replaced", &testQueryRewriter{sql: "select $1::text", args: []any{"hello"}}) batch.Queue("more to be replaced", &testQueryRewriter{sql: "select $1::int", args: []any{3}}) - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) var n int32 err := br.QueryRow().Scan(&n) @@ -368,6 +384,9 @@ func TestConnSendBatchWithQueryRewriter(t *testing.T) { func TestConnSendBatchWithPreparedStatementAndStatementCacheDisabled(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgx.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -380,7 +399,7 @@ func TestConnSendBatchWithPreparedStatementAndStatementCacheDisabled(t *testing. pgxtest.SkipCockroachDB(t, conn, "Server issues incorrect ParameterDescription (https://github.com/cockroachdb/cockroach/issues/60907)") - _, err = conn.Prepare(context.Background(), "ps1", "select n from generate_series(0,$1::int) n") + _, err = conn.Prepare(ctx, "ps1", "select n from generate_series(0,$1::int) n") if err != nil { t.Fatal(err) } @@ -392,7 +411,7 @@ func TestConnSendBatchWithPreparedStatementAndStatementCacheDisabled(t *testing. batch.Queue("ps1", 5) } - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) for i := 0; i < queryCount; i++ { rows, err := br.Query() @@ -426,13 +445,16 @@ func TestConnSendBatchWithPreparedStatementAndStatementCacheDisabled(t *testing. func TestConnSendBatchCloseRowsPartiallyRead(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { batch := &pgx.Batch{} batch.Queue("select n from generate_series(0,5) n") batch.Queue("select n from generate_series(0,5) n") - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) rows, err := br.Query() if err != nil { @@ -485,13 +507,16 @@ func TestConnSendBatchCloseRowsPartiallyRead(t *testing.T) { func TestConnSendBatchQueryError(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { batch := &pgx.Batch{} batch.Queue("select n from generate_series(0,5) n where 100/(5-n) > 0") batch.Queue("select n from generate_series(0,5) n") - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) rows, err := br.Query() if err != nil { @@ -523,12 +548,15 @@ func TestConnSendBatchQueryError(t *testing.T) { func TestConnSendBatchQuerySyntaxError(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { batch := &pgx.Batch{} batch.Queue("select 1 1") - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) var n int32 err := br.QueryRow().Scan(&n) @@ -547,7 +575,10 @@ func TestConnSendBatchQuerySyntaxError(t *testing.T) { func TestConnSendBatchQueryRowInsert(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { sql := `create temporary table ledger( id serial primary key, @@ -560,7 +591,7 @@ func TestConnSendBatchQueryRowInsert(t *testing.T) { batch.Queue("select 1") batch.Queue("insert into ledger(description, amount) values($1, $2),($1, $2)", "q1", 1) - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) var value int err := br.QueryRow().Scan(&value) @@ -584,7 +615,10 @@ func TestConnSendBatchQueryRowInsert(t *testing.T) { func TestConnSendBatchQueryPartialReadInsert(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { sql := `create temporary table ledger( id serial primary key, @@ -597,7 +631,7 @@ func TestConnSendBatchQueryPartialReadInsert(t *testing.T) { batch.Queue("select 1 union all select 2 union all select 3") batch.Queue("insert into ledger(description, amount) values($1, $2),($1, $2)", "q1", 1) - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) rows, err := br.Query() if err != nil { @@ -621,7 +655,10 @@ func TestConnSendBatchQueryPartialReadInsert(t *testing.T) { func TestTxSendBatch(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { sql := `create temporary table ledger1( id serial primary key, @@ -635,7 +672,7 @@ func TestTxSendBatch(t *testing.T) { );` mustExec(t, conn, sql) - tx, _ := conn.Begin(context.Background()) + tx, _ := conn.Begin(ctx) batch := &pgx.Batch{} batch.Queue("insert into ledger1(description) values($1) returning id", "q1") @@ -652,7 +689,7 @@ func TestTxSendBatch(t *testing.T) { batch.Queue("insert into ledger2(id,amount) values($1, $2)", id, 2) batch.Queue("select amount from ledger2 where id = $1", id) - br = tx.SendBatch(context.Background(), batch) + br = tx.SendBatch(ctx, batch) ct, err := br.Exec() if err != nil { @@ -669,10 +706,10 @@ func TestTxSendBatch(t *testing.T) { } br.Close() - tx.Commit(context.Background()) + tx.Commit(ctx) var count int - conn.QueryRow(context.Background(), "select count(1) from ledger1 where id = $1", id).Scan(&count) + conn.QueryRow(ctx, "select count(1) from ledger1 where id = $1", id).Scan(&count) if count != 1 { t.Errorf("count => %v, want %v", count, 1) } @@ -688,7 +725,10 @@ func TestTxSendBatch(t *testing.T) { func TestTxSendBatchRollback(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { sql := `create temporary table ledger1( id serial primary key, @@ -696,11 +736,11 @@ func TestTxSendBatchRollback(t *testing.T) { );` mustExec(t, conn, sql) - tx, _ := conn.Begin(context.Background()) + tx, _ := conn.Begin(ctx) batch := &pgx.Batch{} batch.Queue("insert into ledger1(description) values($1) returning id", "q1") - br := tx.SendBatch(context.Background(), batch) + br := tx.SendBatch(ctx, batch) var id int err := br.QueryRow().Scan(&id) @@ -708,9 +748,9 @@ func TestTxSendBatchRollback(t *testing.T) { t.Error(err) } br.Close() - tx.Rollback(context.Background()) + tx.Rollback(ctx) - row := conn.QueryRow(context.Background(), "select count(1) from ledger1 where id = $1", id) + row := conn.QueryRow(ctx, "select count(1) from ledger1 where id = $1", id) var count int row.Scan(&count) if count != 0 { @@ -724,7 +764,10 @@ func TestTxSendBatchRollback(t *testing.T) { func TestSendBatchErrorWhileReadingResultsWithoutCallback(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { batch := &pgx.Batch{} batch.Queue("select 4 / $1::int", 0) @@ -745,7 +788,10 @@ func TestSendBatchErrorWhileReadingResultsWithoutCallback(t *testing.T) { func TestSendBatchErrorWhileReadingResultsWithExecWhereSomeRowsAreReturned(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { batch := &pgx.Batch{} batch.Queue("select 4 / n from generate_series(-2, 2) n") @@ -766,7 +812,10 @@ func TestSendBatchErrorWhileReadingResultsWithExecWhereSomeRowsAreReturned(t *te func TestConnBeginBatchDeferredError(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does not support deferred constraint (https://github.com/cockroachdb/cockroach/issues/31632)") @@ -782,7 +831,7 @@ func TestConnBeginBatchDeferredError(t *testing.T) { batch.Queue(`update t set n=n+1 where id='b' returning *`) - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) rows, err := br.Query() if err != nil { @@ -811,6 +860,9 @@ func TestConnBeginBatchDeferredError(t *testing.T) { } func TestConnSendBatchNoStatementCache(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE")) config.DefaultQueryExecMode = pgx.QueryExecModeDescribeExec config.StatementCacheCapacity = 0 @@ -819,10 +871,13 @@ func TestConnSendBatchNoStatementCache(t *testing.T) { conn := mustConnect(t, config) defer closeConn(t, conn) - testConnSendBatch(t, conn, 3) + testConnSendBatch(t, ctx, conn, 3) } func TestConnSendBatchPrepareStatementCache(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE")) config.DefaultQueryExecMode = pgx.QueryExecModeCacheStatement config.StatementCacheCapacity = 32 @@ -830,10 +885,13 @@ func TestConnSendBatchPrepareStatementCache(t *testing.T) { conn := mustConnect(t, config) defer closeConn(t, conn) - testConnSendBatch(t, conn, 3) + testConnSendBatch(t, ctx, conn, 3) } func TestConnSendBatchDescribeStatementCache(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE")) config.DefaultQueryExecMode = pgx.QueryExecModeCacheDescribe config.DescriptionCacheCapacity = 32 @@ -841,16 +899,16 @@ func TestConnSendBatchDescribeStatementCache(t *testing.T) { conn := mustConnect(t, config) defer closeConn(t, conn) - testConnSendBatch(t, conn, 3) + testConnSendBatch(t, ctx, conn, 3) } -func testConnSendBatch(t *testing.T, conn *pgx.Conn, queryCount int) { +func testConnSendBatch(t *testing.T, ctx context.Context, conn *pgx.Conn, queryCount int) { batch := &pgx.Batch{} for j := 0; j < queryCount; j++ { batch.Queue("select n from generate_series(0,5) n") } - br := conn.SendBatch(context.Background(), batch) + br := conn.SendBatch(ctx, batch) for j := 0; j < queryCount; j++ { rows, err := br.Query() @@ -873,12 +931,12 @@ func testConnSendBatch(t *testing.T, conn *pgx.Conn, queryCount int) { func TestSendBatchSimpleProtocol(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE")) config.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - conn := mustConnect(t, config) defer closeConn(t, conn) @@ -912,7 +970,10 @@ func TestSendBatchSimpleProtocol(t *testing.T) { } func ExampleConn_SendBatch() { - conn, err := pgx.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + conn, err := pgx.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) if err != nil { fmt.Printf("Unable to establish connection: %v", err) return @@ -955,7 +1016,7 @@ func ExampleConn_SendBatch() { return err }) - err = conn.SendBatch(context.Background(), batch).Close() + err = conn.SendBatch(ctx, batch).Close() if err != nil { fmt.Printf("SendBatch error: %v", err) return diff --git a/conn_test.go b/conn_test.go index e0b55e81..14bfd7e8 100644 --- a/conn_test.go +++ b/conn_test.go @@ -215,7 +215,10 @@ func TestParseConfigErrors(t *testing.T) { func TestExec(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { if results := mustExec(t, conn, "create temporary table foo(id integer primary key);"); results.String() != "CREATE TABLE" { t.Error("Unexpected results from Exec") } @@ -258,7 +261,10 @@ func (qr *testQueryRewriter) RewriteQuery(ctx context.Context, conn *pgx.Conn, s func TestExecWithQueryRewriter(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { qr := testQueryRewriter{sql: "select $1::int", args: []any{42}} _, err := conn.Exec(ctx, "should be replaced", &qr) require.NoError(t, err) @@ -268,7 +274,10 @@ func TestExecWithQueryRewriter(t *testing.T) { func TestExecFailure(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { if _, err := conn.Exec(context.Background(), "selct;"); err == nil { t.Fatal("Expected SQL syntax error") } @@ -284,7 +293,10 @@ func TestExecFailure(t *testing.T) { func TestExecFailureWithArguments(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { _, err := conn.Exec(context.Background(), "selct $1;", 1) if err == nil { t.Fatal("Expected SQL syntax error") @@ -299,7 +311,10 @@ func TestExecFailureWithArguments(t *testing.T) { func TestExecContextWithoutCancelation(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { ctx, cancelFunc := context.WithCancel(context.Background()) defer cancelFunc() @@ -317,7 +332,10 @@ func TestExecContextWithoutCancelation(t *testing.T) { func TestExecContextFailureWithoutCancelation(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { ctx, cancelFunc := context.WithCancel(context.Background()) defer cancelFunc() @@ -339,7 +357,10 @@ func TestExecContextFailureWithoutCancelation(t *testing.T) { func TestExecContextFailureWithoutCancelationWithArguments(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { ctx, cancelFunc := context.WithCancel(context.Background()) defer cancelFunc() @@ -491,7 +512,10 @@ func TestPrepareIdempotency(t *testing.T) { func TestPrepareStatementCacheModes(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { _, err := conn.Prepare(context.Background(), "test", "select $1::text") require.NoError(t, err) @@ -731,7 +755,10 @@ func TestFatalTxError(t *testing.T) { func TestInsertBoolArray(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { if results := mustExec(t, conn, "create temporary table foo(spice bool[]);"); results.String() != "CREATE TABLE" { t.Error("Unexpected results from Exec") } @@ -746,7 +773,10 @@ func TestInsertBoolArray(t *testing.T) { func TestInsertTimestampArray(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { if results := mustExec(t, conn, "create temporary table foo(spice timestamp[]);"); results.String() != "CREATE TABLE" { t.Error("Unexpected results from Exec") } @@ -828,7 +858,10 @@ func TestConnInitTypeMap(t *testing.T) { } func TestUnregisteredTypeUsableAsStringArgumentAndBaseResult(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does support domain types (https://github.com/cockroachdb/cockroach/issues/27796)") var n uint64 @@ -844,7 +877,10 @@ func TestUnregisteredTypeUsableAsStringArgumentAndBaseResult(t *testing.T) { } func TestDomainType(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does support domain types (https://github.com/cockroachdb/cockroach/issues/27796)") // Domain type uint64 is a PostgreSQL domain of underlying type numeric. @@ -878,7 +914,10 @@ func TestDomainType(t *testing.T) { } func TestLoadTypeSameNameInDifferentSchemas(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does support composite types (https://github.com/cockroachdb/cockroach/issues/27792)") tx, err := conn.Begin(ctx) @@ -920,7 +959,10 @@ create type pgx_b.point as (c text); } func TestLoadCompositeType(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does support composite types (https://github.com/cockroachdb/cockroach/issues/27792)") tx, err := conn.Begin(ctx) @@ -939,7 +981,10 @@ func TestLoadCompositeType(t *testing.T) { } func TestLoadRangeType(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does support range types") tx, err := conn.Begin(ctx) @@ -970,7 +1015,10 @@ func TestLoadRangeType(t *testing.T) { } func TestLoadMultiRangeType(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server does support range types") pgxtest.SkipPostgreSQLVersionLessThan(t, conn, 14) // multirange data type was added in 14 postgresql @@ -1157,7 +1205,10 @@ func TestStmtCacheInvalidationTx(t *testing.T) { } func TestInsertDurationInterval(t *testing.T) { - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { _, err := conn.Exec(context.Background(), "create temporary table t(duration INTERVAL(0) NOT NULL)") require.NoError(t, err) diff --git a/copy_from_test.go b/copy_from_test.go index 1342c14c..85c0ac2c 100644 --- a/copy_from_test.go +++ b/copy_from_test.go @@ -19,6 +19,9 @@ func TestConnCopyWithAllQueryExecModes(t *testing.T) { t.Run(mode.String(), func(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cfg := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE")) cfg.DefaultQueryExecMode = mode conn := mustConnect(t, cfg) @@ -39,7 +42,7 @@ func TestConnCopyWithAllQueryExecModes(t *testing.T) { {nil, nil, nil, nil, nil}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e"}, pgx.CopyFromRows(inputRows)) if err != nil { t.Errorf("Unexpected error for CopyFrom: %v", err) } @@ -47,7 +50,7 @@ func TestConnCopyWithAllQueryExecModes(t *testing.T) { t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -80,6 +83,9 @@ func TestConnCopyWithKnownOIDQueryExecModes(t *testing.T) { t.Run(mode.String(), func(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cfg := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE")) cfg.DefaultQueryExecMode = mode conn := mustConnect(t, cfg) @@ -102,7 +108,7 @@ func TestConnCopyWithKnownOIDQueryExecModes(t *testing.T) { {nil, nil, nil, nil, nil, nil, nil}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, pgx.CopyFromRows(inputRows)) if err != nil { t.Errorf("Unexpected error for CopyFrom: %v", err) } @@ -110,7 +116,7 @@ func TestConnCopyWithKnownOIDQueryExecModes(t *testing.T) { t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -140,6 +146,9 @@ func TestConnCopyWithKnownOIDQueryExecModes(t *testing.T) { func TestConnCopyFromSmall(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -160,7 +169,7 @@ func TestConnCopyFromSmall(t *testing.T) { {nil, nil, nil, nil, nil, nil, nil}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, pgx.CopyFromRows(inputRows)) if err != nil { t.Errorf("Unexpected error for CopyFrom: %v", err) } @@ -168,7 +177,7 @@ func TestConnCopyFromSmall(t *testing.T) { t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -196,6 +205,9 @@ func TestConnCopyFromSmall(t *testing.T) { func TestConnCopyFromSliceSmall(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -216,7 +228,7 @@ func TestConnCopyFromSliceSmall(t *testing.T) { {nil, nil, nil, nil, nil, nil, nil}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, pgx.CopyFromSlice(len(inputRows), func(i int) ([]any, error) { return inputRows[i], nil })) @@ -227,7 +239,7 @@ func TestConnCopyFromSliceSmall(t *testing.T) { t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -255,6 +267,9 @@ func TestConnCopyFromSliceSmall(t *testing.T) { func TestConnCopyFromLarge(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -279,7 +294,7 @@ func TestConnCopyFromLarge(t *testing.T) { inputRows = append(inputRows, []any{int16(0), int32(1), int64(2), "abc", "efg", time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), tzedTime, []byte{111, 111, 111, 111}}) } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g", "h"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g", "h"}, pgx.CopyFromRows(inputRows)) if err != nil { t.Errorf("Unexpected error for CopyFrom: %v", err) } @@ -287,7 +302,7 @@ func TestConnCopyFromLarge(t *testing.T) { t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -315,10 +330,12 @@ func TestConnCopyFromLarge(t *testing.T) { func TestConnCopyFromEnum(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) - ctx := context.Background() tx, err := conn.Begin(ctx) require.NoError(t, err) defer tx.Rollback(ctx) @@ -384,6 +401,9 @@ func TestConnCopyFromEnum(t *testing.T) { func TestConnCopyFromJSON(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -403,7 +423,7 @@ func TestConnCopyFromJSON(t *testing.T) { {nil, nil}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b"}, pgx.CopyFromRows(inputRows)) if err != nil { t.Errorf("Unexpected error for CopyFrom: %v", err) } @@ -411,7 +431,7 @@ func TestConnCopyFromJSON(t *testing.T) { t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -461,6 +481,9 @@ func (cfs *clientFailSource) Err() error { func TestConnCopyFromFailServerSideMidway(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -475,7 +498,7 @@ func TestConnCopyFromFailServerSideMidway(t *testing.T) { {int32(3), "def"}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b"}, pgx.CopyFromRows(inputRows)) if err == nil { t.Errorf("Expected CopyFrom return error, but it did not") } @@ -486,7 +509,7 @@ func TestConnCopyFromFailServerSideMidway(t *testing.T) { t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -537,6 +560,9 @@ func (fs *failSource) Err() error { func TestConnCopyFromFailServerSideMidwayAbortsWithoutWaiting(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -548,7 +574,7 @@ func TestConnCopyFromFailServerSideMidwayAbortsWithoutWaiting(t *testing.T) { startTime := time.Now() - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, &failSource{}) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a"}, &failSource{}) if err == nil { t.Errorf("Expected CopyFrom return error, but it did not") } @@ -565,7 +591,7 @@ func TestConnCopyFromFailServerSideMidwayAbortsWithoutWaiting(t *testing.T) { t.Errorf("Failing CopyFrom shouldn't have taken so long: %v", copyTime) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -614,6 +640,9 @@ func (fs *slowFailRaceSource) Err() error { func TestConnCopyFromSlowFailRace(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -622,7 +651,7 @@ func TestConnCopyFromSlowFailRace(t *testing.T) { b bytea not null )`) - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b"}, &slowFailRaceSource{}) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b"}, &slowFailRaceSource{}) if err == nil { t.Errorf("Expected CopyFrom return error, but it did not") } @@ -639,6 +668,9 @@ func TestConnCopyFromSlowFailRace(t *testing.T) { func TestConnCopyFromCopyFromSourceErrorMidway(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -646,7 +678,7 @@ func TestConnCopyFromCopyFromSourceErrorMidway(t *testing.T) { a bytea not null )`) - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, &clientFailSource{}) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a"}, &clientFailSource{}) if err == nil { t.Errorf("Expected CopyFrom return error, but it did not") } @@ -654,7 +686,7 @@ func TestConnCopyFromCopyFromSourceErrorMidway(t *testing.T) { t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -699,6 +731,9 @@ func (cfs *clientFinalErrSource) Err() error { func TestConnCopyFromCopyFromSourceErrorEnd(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -706,7 +741,7 @@ func TestConnCopyFromCopyFromSourceErrorEnd(t *testing.T) { a bytea not null )`) - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, &clientFinalErrSource{}) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a"}, &clientFinalErrSource{}) if err == nil { t.Errorf("Expected CopyFrom return error, but it did not") } @@ -714,7 +749,7 @@ func TestConnCopyFromCopyFromSourceErrorEnd(t *testing.T) { t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount) } - rows, err := conn.Query(context.Background(), "select * from foo") + rows, err := conn.Query(ctx, "select * from foo") if err != nil { t.Errorf("Unexpected error for Query: %v", err) } @@ -742,6 +777,9 @@ func TestConnCopyFromCopyFromSourceErrorEnd(t *testing.T) { func TestConnCopyFromAutomaticStringConversion(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE")) defer closeConn(t, conn) @@ -755,11 +793,11 @@ func TestConnCopyFromAutomaticStringConversion(t *testing.T) { {8}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a"}, pgx.CopyFromRows(inputRows)) require.NoError(t, err) require.EqualValues(t, len(inputRows), copyCount) - rows, _ := conn.Query(context.Background(), "select * from foo") + rows, _ := conn.Query(ctx, "select * from foo") nums, err := pgx.CollectRows(rows, pgx.RowTo[int64]) require.NoError(t, err) diff --git a/pgconn/pgconn_test.go b/pgconn/pgconn_test.go index 86e6f068..2f040378 100644 --- a/pgconn/pgconn_test.go +++ b/pgconn/pgconn_test.go @@ -42,12 +42,15 @@ func TestConnect(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv(tt.env) if connString == "" { t.Skipf("Skipping due to missing environment variable %v", tt.env) } - conn, err := pgconn.Connect(context.Background(), connString) + conn, err := pgconn.Connect(ctx, connString) require.NoError(t, err) closeConn(t, conn) @@ -70,13 +73,16 @@ func TestConnectWithOptions(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv(tt.env) if connString == "" { t.Skipf("Skipping due to missing environment variable %v", tt.env) } var sslOptions pgconn.ParseConfigOptions sslOptions.GetSSLPassword = GetSSLPassword - conn, err := pgconn.ConnectWithOptions(context.Background(), connString, sslOptions) + conn, err := pgconn.ConnectWithOptions(ctx, connString, sslOptions) require.NoError(t, err) closeConn(t, conn) @@ -89,15 +95,18 @@ func TestConnectWithOptions(t *testing.T) { func TestConnectTLS(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_TLS_CONN_STRING") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TLS_CONN_STRING") } - conn, err := pgconn.Connect(context.Background(), connString) + conn, err := pgconn.Connect(ctx, connString) require.NoError(t, err) - result := conn.ExecParams(context.Background(), `select ssl from pg_stat_ssl where pg_backend_pid() = pid;`, nil, nil, nil, nil).Read() + result := conn.ExecParams(ctx, `select ssl from pg_stat_ssl where pg_backend_pid() = pid;`, nil, nil, nil, nil).Read() require.NoError(t, result.Err) require.Len(t, result.Rows, 1) require.Len(t, result.Rows[0], 1) @@ -109,6 +118,9 @@ func TestConnectTLS(t *testing.T) { func TestConnectTLSPasswordProtectedClientCertWithSSLPassword(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_TLS_CLIENT_CONN_STRING") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TLS_CLIENT_CONN_STRING") @@ -119,10 +131,10 @@ func TestConnectTLSPasswordProtectedClientCertWithSSLPassword(t *testing.T) { connString += " sslpassword=" + os.Getenv("PGX_SSL_PASSWORD") - conn, err := pgconn.Connect(context.Background(), connString) + conn, err := pgconn.Connect(ctx, connString) require.NoError(t, err) - result := conn.ExecParams(context.Background(), `select ssl from pg_stat_ssl where pg_backend_pid() = pid;`, nil, nil, nil, nil).Read() + result := conn.ExecParams(ctx, `select ssl from pg_stat_ssl where pg_backend_pid() = pid;`, nil, nil, nil, nil).Read() require.NoError(t, result.Err) require.Len(t, result.Rows, 1) require.Len(t, result.Rows[0], 1) @@ -134,6 +146,9 @@ func TestConnectTLSPasswordProtectedClientCertWithSSLPassword(t *testing.T) { func TestConnectTLSPasswordProtectedClientCertWithGetSSLPasswordConfigOption(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_TLS_CLIENT_CONN_STRING") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TLS_CLIENT_CONN_STRING") @@ -147,10 +162,10 @@ func TestConnectTLSPasswordProtectedClientCertWithGetSSLPasswordConfigOption(t * config, err := pgconn.ParseConfigWithOptions(connString, sslOptions) require.Nil(t, err) - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) - result := conn.ExecParams(context.Background(), `select ssl from pg_stat_ssl where pg_backend_pid() = pid;`, nil, nil, nil, nil).Read() + result := conn.ExecParams(ctx, `select ssl from pg_stat_ssl where pg_backend_pid() = pid;`, nil, nil, nil, nil).Read() require.NoError(t, result.Err) require.Len(t, result.Rows, 1) require.Len(t, result.Rows[0], 1) @@ -327,6 +342,9 @@ func TestConnectTimeoutStuckOnTLSHandshake(t *testing.T) { func TestConnectInvalidUser(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_TCP_CONN_STRING") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TCP_CONN_STRING") @@ -337,7 +355,7 @@ func TestConnectInvalidUser(t *testing.T) { config.User = "pgxinvalidusertest" - _, err = pgconn.ConnectConfig(context.Background(), config) + _, err = pgconn.ConnectConfig(ctx, config) require.Error(t, err) pgErr, ok := errors.Unwrap(err).(*pgconn.PgError) if !ok { @@ -351,10 +369,13 @@ func TestConnectInvalidUser(t *testing.T) { func TestConnectWithConnectionRefused(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + // Presumably nothing is listening on 127.0.0.1:1 - conn, err := pgconn.Connect(context.Background(), "host=127.0.0.1 port=1") + conn, err := pgconn.Connect(ctx, "host=127.0.0.1 port=1") if err == nil { - conn.Close(context.Background()) + conn.Close(ctx) t.Fatal("Expected error establishing connection to bad port") } } @@ -362,6 +383,9 @@ func TestConnectWithConnectionRefused(t *testing.T) { func TestConnectCustomDialer(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -371,7 +395,7 @@ func TestConnectCustomDialer(t *testing.T) { return net.Dial(network, address) } - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) require.True(t, dialed) closeConn(t, conn) @@ -380,6 +404,9 @@ func TestConnectCustomDialer(t *testing.T) { func TestConnectCustomLookup(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_TCP_CONN_STRING") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TCP_CONN_STRING") @@ -394,7 +421,7 @@ func TestConnectCustomLookup(t *testing.T) { return net.LookupHost(host) } - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) require.True(t, looked) closeConn(t, conn) @@ -403,6 +430,9 @@ func TestConnectCustomLookup(t *testing.T) { func TestConnectCustomLookupWithPort(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_TCP_CONN_STRING") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TCP_CONN_STRING") @@ -428,7 +458,7 @@ func TestConnectCustomLookupWithPort(t *testing.T) { return addrs, nil } - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) require.True(t, looked) closeConn(t, conn) @@ -437,6 +467,9 @@ func TestConnectCustomLookupWithPort(t *testing.T) { func TestConnectWithRuntimeParams(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -445,16 +478,16 @@ func TestConnectWithRuntimeParams(t *testing.T) { "search_path": "myschema", } - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, conn) - result := conn.ExecParams(context.Background(), "show application_name", nil, nil, nil, nil).Read() + result := conn.ExecParams(ctx, "show application_name", nil, nil, nil, nil).Read() require.Nil(t, result.Err) assert.Equal(t, 1, len(result.Rows)) assert.Equal(t, "pgxtest", string(result.Rows[0][0])) - result = conn.ExecParams(context.Background(), "show search_path", nil, nil, nil, nil).Read() + result = conn.ExecParams(ctx, "show search_path", nil, nil, nil, nil).Read() require.Nil(t, result.Err) assert.Equal(t, 1, len(result.Rows)) assert.Equal(t, "myschema", string(result.Rows[0][0])) @@ -463,6 +496,9 @@ func TestConnectWithRuntimeParams(t *testing.T) { func TestConnectWithFallback(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -488,7 +524,7 @@ func TestConnectWithFallback(t *testing.T) { }, }, config.Fallbacks...) - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) closeConn(t, conn) } @@ -496,6 +532,9 @@ func TestConnectWithFallback(t *testing.T) { func TestConnectWithValidateConnect(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -524,7 +563,7 @@ func TestConnectWithValidateConnect(t *testing.T) { // Repeat fallbacks config.Fallbacks = append(config.Fallbacks, config.Fallbacks...) - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) closeConn(t, conn) @@ -535,15 +574,15 @@ func TestConnectWithValidateConnect(t *testing.T) { func TestConnectWithValidateConnectTargetSessionAttrsReadWrite(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) config.ValidateConnect = pgconn.ValidateConnectTargetSessionAttrsReadWrite config.RuntimeParams["default_transaction_read_only"] = "on" - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - conn, err := pgconn.ConnectConfig(ctx, config) if !assert.NotNil(t, err) { conn.Close(ctx) @@ -553,6 +592,9 @@ func TestConnectWithValidateConnectTargetSessionAttrsReadWrite(t *testing.T) { func TestConnectWithAfterConnect(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -561,10 +603,10 @@ func TestConnectWithAfterConnect(t *testing.T) { return err } - conn, err := pgconn.ConnectConfig(context.Background(), config) + conn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) - results, err := conn.Exec(context.Background(), "show search_path;").ReadAll() + results, err := conn.Exec(ctx, "show search_path;").ReadAll() require.NoError(t, err) defer closeConn(t, conn) @@ -574,19 +616,25 @@ func TestConnectWithAfterConnect(t *testing.T) { func TestConnectConfigRequiresConfigFromParseConfig(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config := &pgconn.Config{} - require.PanicsWithValue(t, "config must be created by ParseConfig", func() { pgconn.ConnectConfig(context.Background(), config) }) + require.PanicsWithValue(t, "config must be created by ParseConfig", func() { pgconn.ConnectConfig(ctx, config) }) } func TestConnPrepareSyntaxError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - psd, err := pgConn.Prepare(context.Background(), "ps1", "SYNTAX ERROR", nil) + psd, err := pgConn.Prepare(ctx, "ps1", "SYNTAX ERROR", nil) require.Nil(t, psd) require.NotNil(t, err) @@ -596,12 +644,15 @@ func TestConnPrepareSyntaxError(t *testing.T) { func TestConnPrepareContextPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - ctx, cancel := context.WithCancel(context.Background()) cancel() + psd, err := pgConn.Prepare(ctx, "ps1", "select 1", nil) assert.Nil(t, psd) assert.Error(t, err) @@ -614,11 +665,14 @@ func TestConnPrepareContextPrecanceled(t *testing.T) { func TestConnExec(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - results, err := pgConn.Exec(context.Background(), "select 'Hello, world'").ReadAll() + results, err := pgConn.Exec(ctx, "select 'Hello, world'").ReadAll() assert.NoError(t, err) assert.Len(t, results, 1) @@ -633,11 +687,14 @@ func TestConnExec(t *testing.T) { func TestConnExecEmpty(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - multiResult := pgConn.Exec(context.Background(), ";") + multiResult := pgConn.Exec(ctx, ";") resultCount := 0 for multiResult.NextResult() { @@ -654,11 +711,14 @@ func TestConnExecEmpty(t *testing.T) { func TestConnExecMultipleQueries(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - results, err := pgConn.Exec(context.Background(), "select 'Hello, world'; select 1").ReadAll() + results, err := pgConn.Exec(ctx, "select 'Hello, world'; select 1").ReadAll() assert.NoError(t, err) assert.Len(t, results, 2) @@ -679,11 +739,14 @@ func TestConnExecMultipleQueries(t *testing.T) { func TestConnExecMultipleQueriesEagerFieldDescriptions(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - mrr := pgConn.Exec(context.Background(), "select 'Hello, world' as msg; select 1 as num") + mrr := pgConn.Exec(ctx, "select 'Hello, world' as msg; select 1 as num") require.True(t, mrr.NextResult()) require.Len(t, mrr.ResultReader().FieldDescriptions(), 1) @@ -707,11 +770,14 @@ func TestConnExecMultipleQueriesEagerFieldDescriptions(t *testing.T) { func TestConnExecMultipleQueriesError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - results, err := pgConn.Exec(context.Background(), "select 1; select 1/0; select 1").ReadAll() + results, err := pgConn.Exec(ctx, "select 1; select 1/0; select 1").ReadAll() require.NotNil(t, err) if pgErr, ok := err.(*pgconn.PgError); ok { assert.Equal(t, "22012", pgErr.Code) @@ -738,7 +804,10 @@ func TestConnExecMultipleQueriesError(t *testing.T) { func TestConnExecDeferredError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -754,10 +823,10 @@ func TestConnExecDeferredError(t *testing.T) { insert into t (id, n) values ('a', 1), ('b', 2), ('c', 3);` - _, err = pgConn.Exec(context.Background(), setupSQL).ReadAll() + _, err = pgConn.Exec(ctx, setupSQL).ReadAll() assert.NoError(t, err) - _, err = pgConn.Exec(context.Background(), `update t set n=n+1 where id='b' returning *`).ReadAll() + _, err = pgConn.Exec(ctx, `update t set n=n+1 where id='b' returning *`).ReadAll() require.NotNil(t, err) var pgErr *pgconn.PgError @@ -770,11 +839,15 @@ func TestConnExecDeferredError(t *testing.T) { func TestConnExecContextCanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) + cancel() - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() multiResult := pgConn.Exec(ctx, "select 'Hello, world', pg_sleep(1)") @@ -794,11 +867,13 @@ func TestConnExecContextCanceled(t *testing.T) { func TestConnExecContextPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - ctx, cancel := context.WithCancel(context.Background()) cancel() _, err = pgConn.Exec(ctx, "select 'Hello, world'").ReadAll() assert.Error(t, err) @@ -811,11 +886,14 @@ func TestConnExecContextPrecanceled(t *testing.T) { func TestConnExecParams(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - result := pgConn.ExecParams(context.Background(), "select $1::text as msg", [][]byte{[]byte("Hello, world")}, nil, nil, nil) + result := pgConn.ExecParams(ctx, "select $1::text as msg", [][]byte{[]byte("Hello, world")}, nil, nil, nil) require.Len(t, result.FieldDescriptions(), 1) assert.Equal(t, "msg", result.FieldDescriptions()[0].Name) @@ -835,7 +913,10 @@ func TestConnExecParams(t *testing.T) { func TestConnExecParamsDeferredError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -851,10 +932,10 @@ func TestConnExecParamsDeferredError(t *testing.T) { insert into t (id, n) values ('a', 1), ('b', 2), ('c', 3);` - _, err = pgConn.Exec(context.Background(), setupSQL).ReadAll() + _, err = pgConn.Exec(ctx, setupSQL).ReadAll() assert.NoError(t, err) - result := pgConn.ExecParams(context.Background(), `update t set n=n+1 where id='b' returning *`, nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, `update t set n=n+1 where id='b' returning *`, nil, nil, nil, nil).Read() require.NotNil(t, result.Err) var pgErr *pgconn.PgError require.True(t, errors.As(result.Err, &pgErr)) @@ -866,7 +947,10 @@ func TestConnExecParamsDeferredError(t *testing.T) { func TestConnExecParamsMaxNumberOfParams(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -879,7 +963,7 @@ func TestConnExecParamsMaxNumberOfParams(t *testing.T) { } sql := "values" + strings.Join(params, ", ") - result := pgConn.ExecParams(context.Background(), sql, args, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, sql, args, nil, nil, nil).Read() require.NoError(t, result.Err) require.Len(t, result.Rows, paramCount) @@ -889,7 +973,10 @@ func TestConnExecParamsMaxNumberOfParams(t *testing.T) { func TestConnExecParamsTooManyParams(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -902,7 +989,7 @@ func TestConnExecParamsTooManyParams(t *testing.T) { } sql := "values" + strings.Join(params, ", ") - result := pgConn.ExecParams(context.Background(), sql, args, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, sql, args, nil, nil, nil).Read() require.Error(t, result.Err) require.Equal(t, "extended protocol limited to 65535 parameters", result.Err.Error()) @@ -912,11 +999,14 @@ func TestConnExecParamsTooManyParams(t *testing.T) { func TestConnExecParamsCanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() result := pgConn.ExecParams(ctx, "select current_database(), pg_sleep(1)", nil, nil, nil, nil) rowCount := 0 @@ -940,11 +1030,13 @@ func TestConnExecParamsCanceled(t *testing.T) { func TestConnExecParamsPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - ctx, cancel := context.WithCancel(context.Background()) cancel() result := pgConn.ExecParams(ctx, "select $1::text", [][]byte{[]byte("Hello, world")}, nil, nil, nil).Read() require.Error(t, result.Err) @@ -957,7 +1049,7 @@ func TestConnExecParamsPrecanceled(t *testing.T) { func TestConnExecParamsEmptySQL(t *testing.T) { t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) @@ -976,11 +1068,14 @@ func TestConnExecParamsEmptySQL(t *testing.T) { func TestResultReaderValuesHaveSameCapacityAsLength(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - result := pgConn.ExecParams(context.Background(), "select $1::text as msg", [][]byte{[]byte("Hello, world")}, nil, nil, nil) + result := pgConn.ExecParams(ctx, "select $1::text as msg", [][]byte{[]byte("Hello, world")}, nil, nil, nil) require.Len(t, result.FieldDescriptions(), 1) assert.Equal(t, "msg", result.FieldDescriptions()[0].Name) @@ -1001,17 +1096,20 @@ func TestResultReaderValuesHaveSameCapacityAsLength(t *testing.T) { func TestConnExecPrepared(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - psd, err := pgConn.Prepare(context.Background(), "ps1", "select $1::text as msg", nil) + psd, err := pgConn.Prepare(ctx, "ps1", "select $1::text as msg", nil) require.NoError(t, err) require.NotNil(t, psd) assert.Len(t, psd.ParamOIDs, 1) assert.Len(t, psd.Fields, 1) - result := pgConn.ExecPrepared(context.Background(), "ps1", [][]byte{[]byte("Hello, world")}, nil, nil) + result := pgConn.ExecPrepared(ctx, "ps1", [][]byte{[]byte("Hello, world")}, nil, nil) require.Len(t, result.FieldDescriptions(), 1) assert.Equal(t, "msg", result.FieldDescriptions()[0].Name) @@ -1031,7 +1129,10 @@ func TestConnExecPrepared(t *testing.T) { func TestConnExecPreparedMaxNumberOfParams(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1044,13 +1145,13 @@ func TestConnExecPreparedMaxNumberOfParams(t *testing.T) { } sql := "values" + strings.Join(params, ", ") - psd, err := pgConn.Prepare(context.Background(), "ps1", sql, nil) + psd, err := pgConn.Prepare(ctx, "ps1", sql, nil) require.NoError(t, err) require.NotNil(t, psd) assert.Len(t, psd.ParamOIDs, paramCount) assert.Len(t, psd.Fields, 1) - result := pgConn.ExecPrepared(context.Background(), "ps1", args, nil, nil).Read() + result := pgConn.ExecPrepared(ctx, "ps1", args, nil, nil).Read() require.NoError(t, result.Err) require.Len(t, result.Rows, paramCount) @@ -1060,7 +1161,10 @@ func TestConnExecPreparedMaxNumberOfParams(t *testing.T) { func TestConnExecPreparedTooManyParams(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1073,7 +1177,7 @@ func TestConnExecPreparedTooManyParams(t *testing.T) { } sql := "values" + strings.Join(params, ", ") - psd, err := pgConn.Prepare(context.Background(), "ps1", sql, nil) + psd, err := pgConn.Prepare(ctx, "ps1", sql, nil) if pgConn.ParameterStatus("crdb_version") != "" { // CockroachDB rejects preparing a statement with more than 65535 parameters. require.EqualError(t, err, "ERROR: more than 65535 arguments to prepared statement: 65536 (SQLSTATE 08P01)") @@ -1084,7 +1188,7 @@ func TestConnExecPreparedTooManyParams(t *testing.T) { assert.Len(t, psd.ParamOIDs, paramCount) assert.Len(t, psd.Fields, 1) - result := pgConn.ExecPrepared(context.Background(), "ps1", args, nil, nil).Read() + result := pgConn.ExecPrepared(ctx, "ps1", args, nil, nil).Read() require.EqualError(t, result.Err, "extended protocol limited to 65535 parameters") } @@ -1094,14 +1198,17 @@ func TestConnExecPreparedTooManyParams(t *testing.T) { func TestConnExecPreparedCanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Prepare(context.Background(), "ps1", "select current_database(), pg_sleep(1)", nil) + _, err = pgConn.Prepare(ctx, "ps1", "select current_database(), pg_sleep(1)", nil) require.NoError(t, err) - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() result := pgConn.ExecPrepared(ctx, "ps1", nil, nil, nil) rowCount := 0 @@ -1123,14 +1230,16 @@ func TestConnExecPreparedCanceled(t *testing.T) { func TestConnExecPreparedPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Prepare(context.Background(), "ps1", "select current_database(), pg_sleep(1)", nil) + _, err = pgConn.Prepare(ctx, "ps1", "select current_database(), pg_sleep(1)", nil) require.NoError(t, err) - ctx, cancel := context.WithCancel(context.Background()) cancel() result := pgConn.ExecPrepared(ctx, "ps1", nil, nil, nil).Read() require.Error(t, result.Err) @@ -1143,7 +1252,7 @@ func TestConnExecPreparedPrecanceled(t *testing.T) { func TestConnExecPreparedEmptySQL(t *testing.T) { t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) @@ -1164,11 +1273,14 @@ func TestConnExecPreparedEmptySQL(t *testing.T) { func TestConnExecBatch(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Prepare(context.Background(), "ps1", "select $1::text", nil) + _, err = pgConn.Prepare(ctx, "ps1", "select $1::text", nil) require.NoError(t, err) batch := &pgconn.Batch{} @@ -1176,7 +1288,7 @@ func TestConnExecBatch(t *testing.T) { batch.ExecParams("select $1::text", [][]byte{[]byte("ExecParams 1")}, nil, nil, nil) batch.ExecPrepared("ps1", [][]byte{[]byte("ExecPrepared 1")}, nil, nil) batch.ExecParams("select $1::text", [][]byte{[]byte("ExecParams 2")}, nil, nil, nil) - results, err := pgConn.ExecBatch(context.Background(), batch).ReadAll() + results, err := pgConn.ExecBatch(ctx, batch).ReadAll() require.NoError(t, err) require.Len(t, results, 3) @@ -1196,7 +1308,10 @@ func TestConnExecBatch(t *testing.T) { func TestConnExecBatchDeferredError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1212,13 +1327,13 @@ func TestConnExecBatchDeferredError(t *testing.T) { insert into t (id, n) values ('a', 1), ('b', 2), ('c', 3);` - _, err = pgConn.Exec(context.Background(), setupSQL).ReadAll() + _, err = pgConn.Exec(ctx, setupSQL).ReadAll() require.NoError(t, err) batch := &pgconn.Batch{} batch.ExecParams(`update t set n=n+1 where id='b' returning *`, nil, nil, nil, nil) - _, err = pgConn.ExecBatch(context.Background(), batch).ReadAll() + _, err = pgConn.ExecBatch(ctx, batch).ReadAll() require.NotNil(t, err) var pgErr *pgconn.PgError require.True(t, errors.As(err, &pgErr)) @@ -1230,11 +1345,14 @@ func TestConnExecBatchDeferredError(t *testing.T) { func TestConnExecBatchPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Prepare(context.Background(), "ps1", "select $1::text", nil) + _, err = pgConn.Prepare(ctx, "ps1", "select $1::text", nil) require.NoError(t, err) batch := &pgconn.Batch{} @@ -1243,7 +1361,6 @@ func TestConnExecBatchPrecanceled(t *testing.T) { batch.ExecPrepared("ps1", [][]byte{[]byte("ExecPrepared 1")}, nil, nil) batch.ExecParams("select $1::text", [][]byte{[]byte("ExecParams 2")}, nil, nil, nil) - ctx, cancel := context.WithCancel(context.Background()) cancel() _, err = pgConn.ExecBatch(ctx, batch).ReadAll() require.Error(t, err) @@ -1263,7 +1380,10 @@ func TestConnExecBatchHuge(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1277,7 +1397,7 @@ func TestConnExecBatchHuge(t *testing.T) { batch.ExecParams("select $1::text", [][]byte{[]byte(args[i])}, nil, nil, nil) } - results, err := pgConn.ExecBatch(context.Background(), batch).ReadAll() + results, err := pgConn.ExecBatch(ctx, batch).ReadAll() require.NoError(t, err) require.Len(t, results, queryCount) @@ -1291,7 +1411,10 @@ func TestConnExecBatchHuge(t *testing.T) { func TestConnExecBatchImplicitTransaction(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1299,7 +1422,7 @@ func TestConnExecBatchImplicitTransaction(t *testing.T) { t.Skip("Skipping due to known server issue: (https://github.com/cockroachdb/cockroach/issues/44803)") } - _, err = pgConn.Exec(context.Background(), "create temporary table t(id int)").ReadAll() + _, err = pgConn.Exec(ctx, "create temporary table t(id int)").ReadAll() require.NoError(t, err) batch := &pgconn.Batch{} @@ -1308,22 +1431,25 @@ func TestConnExecBatchImplicitTransaction(t *testing.T) { batch.ExecParams("insert into t(id) values(2)", nil, nil, nil, nil) batch.ExecParams("insert into t(id) values(3)", nil, nil, nil, nil) batch.ExecParams("select 1/0", nil, nil, nil, nil) - _, err = pgConn.ExecBatch(context.Background(), batch).ReadAll() + _, err = pgConn.ExecBatch(ctx, batch).ReadAll() require.Error(t, err) - result := pgConn.ExecParams(context.Background(), "select count(*) from t", nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, "select count(*) from t", nil, nil, nil, nil).Read() require.Equal(t, "0", string(result.Rows[0][0])) } func TestConnLocking(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - mrr := pgConn.Exec(context.Background(), "select 'Hello, world'") - _, err = pgConn.Exec(context.Background(), "select 'Hello, world'").ReadAll() + mrr := pgConn.Exec(ctx, "select 'Hello, world'") + _, err = pgConn.Exec(ctx, "select 'Hello, world'").ReadAll() assert.Error(t, err) assert.Equal(t, "conn busy", err.Error()) assert.True(t, pgconn.SafeToRetry(err)) @@ -1342,6 +1468,9 @@ func TestConnLocking(t *testing.T) { func TestConnOnNotice(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -1351,7 +1480,7 @@ func TestConnOnNotice(t *testing.T) { } config.RuntimeParams["client_min_messages"] = "notice" // Ensure we only get the message we expect. - pgConn, err := pgconn.ConnectConfig(context.Background(), config) + pgConn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1359,7 +1488,7 @@ func TestConnOnNotice(t *testing.T) { t.Skip("Server does not support PL/PGSQL (https://github.com/cockroachdb/cockroach/issues/17511)") } - multiResult := pgConn.Exec(context.Background(), `do $$ + multiResult := pgConn.Exec(ctx, `do $$ begin raise notice 'hello, world'; end$$;`) @@ -1373,6 +1502,9 @@ end$$;`) func TestConnOnNotification(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -1381,7 +1513,7 @@ func TestConnOnNotification(t *testing.T) { msg = n.Payload } - pgConn, err := pgconn.ConnectConfig(context.Background(), config) + pgConn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1389,16 +1521,16 @@ func TestConnOnNotification(t *testing.T) { t.Skip("Server does not support LISTEN / NOTIFY (https://github.com/cockroachdb/cockroach/issues/41522)") } - _, err = pgConn.Exec(context.Background(), "listen foo").ReadAll() + _, err = pgConn.Exec(ctx, "listen foo").ReadAll() require.NoError(t, err) - notifier, err := pgconn.ConnectConfig(context.Background(), config) + notifier, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, notifier) - _, err = notifier.Exec(context.Background(), "notify foo, 'bar'").ReadAll() + _, err = notifier.Exec(ctx, "notify foo, 'bar'").ReadAll() require.NoError(t, err) - _, err = pgConn.Exec(context.Background(), "select 1").ReadAll() + _, err = pgConn.Exec(ctx, "select 1").ReadAll() require.NoError(t, err) assert.Equal(t, "bar", msg) @@ -1409,6 +1541,9 @@ func TestConnOnNotification(t *testing.T) { func TestConnWaitForNotification(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) @@ -1417,7 +1552,7 @@ func TestConnWaitForNotification(t *testing.T) { msg = n.Payload } - pgConn, err := pgconn.ConnectConfig(context.Background(), config) + pgConn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1425,16 +1560,16 @@ func TestConnWaitForNotification(t *testing.T) { t.Skip("Server does not support LISTEN / NOTIFY (https://github.com/cockroachdb/cockroach/issues/41522)") } - _, err = pgConn.Exec(context.Background(), "listen foo").ReadAll() + _, err = pgConn.Exec(ctx, "listen foo").ReadAll() require.NoError(t, err) - notifier, err := pgconn.ConnectConfig(context.Background(), config) + notifier, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, notifier) - _, err = notifier.Exec(context.Background(), "notify foo, 'bar'").ReadAll() + _, err = notifier.Exec(ctx, "notify foo, 'bar'").ReadAll() require.NoError(t, err) - err = pgConn.WaitForNotification(context.Background()) + err = pgConn.WaitForNotification(ctx) require.NoError(t, err) assert.Equal(t, "bar", msg) @@ -1445,14 +1580,16 @@ func TestConnWaitForNotification(t *testing.T) { func TestConnWaitForNotificationPrecanceled(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) - pgConn, err := pgconn.ConnectConfig(context.Background(), config) + pgConn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, pgConn) - ctx, cancel := context.WithCancel(context.Background()) cancel() err = pgConn.WaitForNotification(ctx) require.ErrorIs(t, err, context.Canceled) @@ -1463,14 +1600,17 @@ func TestConnWaitForNotificationPrecanceled(t *testing.T) { func TestConnWaitForNotificationTimeout(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + config, err := pgconn.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) - pgConn, err := pgconn.ConnectConfig(context.Background(), config) + pgConn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) defer closeConn(t, pgConn) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond) + ctx, cancel = context.WithTimeout(ctx, 5*time.Millisecond) err = pgConn.WaitForNotification(ctx) cancel() assert.True(t, pgconn.Timeout(err)) @@ -1482,7 +1622,10 @@ func TestConnWaitForNotificationTimeout(t *testing.T) { func TestConnCopyToSmall(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1490,7 +1633,7 @@ func TestConnCopyToSmall(t *testing.T) { t.Skip("Server does support COPY TO") } - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int2, b int4, c int8, @@ -1501,10 +1644,10 @@ func TestConnCopyToSmall(t *testing.T) { )`).ReadAll() require.NoError(t, err) - _, err = pgConn.Exec(context.Background(), `insert into foo values (0, 1, 2, 'abc', 'efg', '2000-01-01', '{"abc":"def","foo":"bar"}')`).ReadAll() + _, err = pgConn.Exec(ctx, `insert into foo values (0, 1, 2, 'abc', 'efg', '2000-01-01', '{"abc":"def","foo":"bar"}')`).ReadAll() require.NoError(t, err) - _, err = pgConn.Exec(context.Background(), `insert into foo values (null, null, null, null, null, null, null)`).ReadAll() + _, err = pgConn.Exec(ctx, `insert into foo values (null, null, null, null, null, null, null)`).ReadAll() require.NoError(t, err) inputBytes := []byte("0\t1\t2\tabc\tefg\t2000-01-01\t{\"abc\":\"def\",\"foo\":\"bar\"}\n" + @@ -1512,7 +1655,7 @@ func TestConnCopyToSmall(t *testing.T) { outputWriter := bytes.NewBuffer(make([]byte, 0, len(inputBytes))) - res, err := pgConn.CopyTo(context.Background(), outputWriter, "copy foo to stdout") + res, err := pgConn.CopyTo(ctx, outputWriter, "copy foo to stdout") require.NoError(t, err) assert.Equal(t, int64(2), res.RowsAffected()) @@ -1524,7 +1667,10 @@ func TestConnCopyToSmall(t *testing.T) { func TestConnCopyToLarge(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1532,7 +1678,7 @@ func TestConnCopyToLarge(t *testing.T) { t.Skip("Server does support COPY TO") } - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int2, b int4, c int8, @@ -1547,14 +1693,14 @@ func TestConnCopyToLarge(t *testing.T) { inputBytes := make([]byte, 0) for i := 0; i < 1000; i++ { - _, err = pgConn.Exec(context.Background(), `insert into foo values (0, 1, 2, 'abc', 'efg', '2000-01-01', '{"abc":"def","foo":"bar"}', 'oooo')`).ReadAll() + _, err = pgConn.Exec(ctx, `insert into foo values (0, 1, 2, 'abc', 'efg', '2000-01-01', '{"abc":"def","foo":"bar"}', 'oooo')`).ReadAll() require.NoError(t, err) inputBytes = append(inputBytes, "0\t1\t2\tabc\tefg\t2000-01-01\t{\"abc\":\"def\",\"foo\":\"bar\"}\t\\\\x6f6f6f6f\n"...) } outputWriter := bytes.NewBuffer(make([]byte, 0, len(inputBytes))) - res, err := pgConn.CopyTo(context.Background(), outputWriter, "copy foo to stdout") + res, err := pgConn.CopyTo(ctx, outputWriter, "copy foo to stdout") require.NoError(t, err) assert.Equal(t, int64(1000), res.RowsAffected()) @@ -1566,13 +1712,16 @@ func TestConnCopyToLarge(t *testing.T) { func TestConnCopyToQueryError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) outputWriter := bytes.NewBuffer(make([]byte, 0)) - res, err := pgConn.CopyTo(context.Background(), outputWriter, "cropy foo to stdout") + res, err := pgConn.CopyTo(ctx, outputWriter, "cropy foo to stdout") require.Error(t, err) assert.IsType(t, &pgconn.PgError{}, err) assert.Equal(t, int64(0), res.RowsAffected()) @@ -1583,7 +1732,10 @@ func TestConnCopyToQueryError(t *testing.T) { func TestConnCopyToCanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1593,7 +1745,7 @@ func TestConnCopyToCanceled(t *testing.T) { outputWriter := &bytes.Buffer{} - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() res, err := pgConn.CopyTo(ctx, outputWriter, "copy (select *, pg_sleep(0.01) from generate_series(1,1000)) to stdout") assert.Error(t, err) @@ -1610,13 +1762,15 @@ func TestConnCopyToCanceled(t *testing.T) { func TestConnCopyToPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) outputWriter := &bytes.Buffer{} - ctx, cancel := context.WithCancel(context.Background()) cancel() res, err := pgConn.CopyTo(ctx, outputWriter, "copy (select * from generate_series(1,1000)) to stdout") require.Error(t, err) @@ -1630,11 +1784,14 @@ func TestConnCopyToPrecanceled(t *testing.T) { func TestConnCopyFrom(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int4, b varchar )`).ReadAll() @@ -1655,11 +1812,11 @@ func TestConnCopyFrom(t *testing.T) { if pgConn.ParameterStatus("crdb_version") != "" { copySql = "COPY foo FROM STDIN WITH CSV" } - ct, err := pgConn.CopyFrom(context.Background(), srcBuf, copySql) + ct, err := pgConn.CopyFrom(ctx, srcBuf, copySql) require.NoError(t, err) assert.Equal(t, int64(len(inputRows)), ct.RowsAffected()) - result := pgConn.ExecParams(context.Background(), "select * from foo", nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, "select * from foo", nil, nil, nil, nil).Read() require.NoError(t, result.Err) assert.Equal(t, inputRows, result.Rows) @@ -1670,11 +1827,14 @@ func TestConnCopyFrom(t *testing.T) { func TestConnCopyFromBinary(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int4, b varchar )`).ReadAll() @@ -1708,11 +1868,11 @@ func TestConnCopyFromBinary(t *testing.T) { srcBuf := &bytes.Buffer{} srcBuf.Write(buf) - ct, err := pgConn.CopyFrom(context.Background(), srcBuf, "COPY foo (a, b) FROM STDIN BINARY;") + ct, err := pgConn.CopyFrom(ctx, srcBuf, "COPY foo (a, b) FROM STDIN BINARY;") require.NoError(t, err) assert.Equal(t, int64(len(inputRows)), ct.RowsAffected()) - result := pgConn.ExecParams(context.Background(), "select * from foo", nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, "select * from foo", nil, nil, nil, nil).Read() require.NoError(t, result.Err) assert.Equal(t, inputRows, result.Rows) @@ -1723,11 +1883,14 @@ func TestConnCopyFromBinary(t *testing.T) { func TestConnCopyFromCanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int4, b varchar )`).ReadAll() @@ -1746,7 +1909,7 @@ func TestConnCopyFromCanceled(t *testing.T) { } }() - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond) copySql := "COPY foo FROM STDIN WITH (FORMAT csv)" if pgConn.ParameterStatus("crdb_version") != "" { copySql = "COPY foo FROM STDIN WITH CSV" @@ -1767,11 +1930,14 @@ func TestConnCopyFromCanceled(t *testing.T) { func TestConnCopyFromPrecanceled(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int4, b varchar )`).ReadAll() @@ -1790,7 +1956,7 @@ func TestConnCopyFromPrecanceled(t *testing.T) { } }() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel = context.WithCancel(ctx) cancel() ct, err := pgConn.CopyFrom(ctx, r, "COPY foo FROM STDIN WITH (FORMAT csv)") require.Error(t, err) @@ -1804,7 +1970,10 @@ func TestConnCopyFromPrecanceled(t *testing.T) { func TestConnCopyFromGzipReader(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1812,7 +1981,7 @@ func TestConnCopyFromGzipReader(t *testing.T) { t.Skip("Server does not fully support COPY FROM (https://www.cockroachlabs.com/docs/v20.2/copy-from.html)") } - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int4, b varchar )`).ReadAll() @@ -1845,7 +2014,7 @@ func TestConnCopyFromGzipReader(t *testing.T) { if pgConn.ParameterStatus("crdb_version") != "" { copySql = "COPY foo FROM STDIN WITH CSV" } - ct, err := pgConn.CopyFrom(context.Background(), gr, copySql) + ct, err := pgConn.CopyFrom(ctx, gr, copySql) require.NoError(t, err) assert.Equal(t, int64(len(inputRows)), ct.RowsAffected()) @@ -1858,7 +2027,7 @@ func TestConnCopyFromGzipReader(t *testing.T) { err = os.Remove(f.Name()) require.NoError(t, err) - result := pgConn.ExecParams(context.Background(), "select * from foo", nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, "select * from foo", nil, nil, nil, nil).Read() require.NoError(t, result.Err) assert.Equal(t, inputRows, result.Rows) @@ -1869,11 +2038,14 @@ func TestConnCopyFromGzipReader(t *testing.T) { func TestConnCopyFromQuerySyntaxError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Exec(context.Background(), `create temporary table foo( + _, err = pgConn.Exec(ctx, `create temporary table foo( a int4, b varchar )`).ReadAll() @@ -1892,7 +2064,7 @@ func TestConnCopyFromQuerySyntaxError(t *testing.T) { require.NoError(t, err) } - res, err := pgConn.CopyFrom(context.Background(), srcBuf, "cropy foo FROM STDIN WITH (FORMAT csv)") + res, err := pgConn.CopyFrom(ctx, srcBuf, "cropy foo FROM STDIN WITH (FORMAT csv)") require.Error(t, err) assert.IsType(t, &pgconn.PgError{}, err) assert.Equal(t, int64(0), res.RowsAffected()) @@ -1903,13 +2075,16 @@ func TestConnCopyFromQuerySyntaxError(t *testing.T) { func TestConnCopyFromQueryNoTableError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) srcBuf := &bytes.Buffer{} - res, err := pgConn.CopyFrom(context.Background(), srcBuf, "copy foo to stdout") + res, err := pgConn.CopyFrom(ctx, srcBuf, "copy foo to stdout") require.Error(t, err) assert.IsType(t, &pgconn.PgError{}, err) assert.Equal(t, int64(0), res.RowsAffected()) @@ -1921,7 +2096,9 @@ func TestConnCopyFromQueryNoTableError(t *testing.T) { func TestConnCopyFromNoticeResponseReceivedMidStream(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -1973,6 +2150,9 @@ func (d delayedReader) Read(p []byte) (int, error) { // https://github.com/jackc/pgconn/issues/128 func TestConnCopyFromDataWriteAfterErrorAndReturn(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connString := os.Getenv("PGX_TEST_DATABASE") if connString == "" { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_DATABASE") @@ -1981,7 +2161,7 @@ func TestConnCopyFromDataWriteAfterErrorAndReturn(t *testing.T) { config, err := pgconn.ParseConfig(connString) require.NoError(t, err) - pgConn, err := pgconn.ConnectConfig(context.Background(), config) + pgConn, err := pgconn.ConnectConfig(ctx, config) require.NoError(t, err) if pgConn.ParameterStatus("crdb_version") != "" { @@ -1993,23 +2173,26 @@ func TestConnCopyFromDataWriteAfterErrorAndReturn(t *testing.T) { n int not null );` - _, err = pgConn.Exec(context.Background(), setupSQL).ReadAll() + _, err = pgConn.Exec(ctx, setupSQL).ReadAll() assert.NoError(t, err) r1 := delayedReader{r: strings.NewReader(`id 0\n`)} // Generate an error with a bogus COPY command - _, err = pgConn.CopyFrom(context.Background(), r1, "COPY nosuchtable FROM STDIN ") + _, err = pgConn.CopyFrom(ctx, r1, "COPY nosuchtable FROM STDIN ") assert.Error(t, err) r2 := delayedReader{r: strings.NewReader(`id 0\n`)} - _, err = pgConn.CopyFrom(context.Background(), r2, "COPY t FROM STDIN") + _, err = pgConn.CopyFrom(ctx, r2, "COPY t FROM STDIN") assert.NoError(t, err) } func TestConnEscapeString(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -2037,7 +2220,10 @@ func TestConnEscapeString(t *testing.T) { func TestConnCancelRequest(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) @@ -2045,14 +2231,14 @@ func TestConnCancelRequest(t *testing.T) { t.Skip("Server does not support query cancellation (https://github.com/cockroachdb/cockroach/issues/41335)") } - multiResult := pgConn.Exec(context.Background(), "select 'Hello, world', pg_sleep(2)") + multiResult := pgConn.Exec(ctx, "select 'Hello, world', pg_sleep(2)") go func() { // The query is actually sent when multiResult.NextResult() is called. So wait to ensure it is sent. // Once Flush is available this could use that instead. time.Sleep(500 * time.Millisecond) - err := pgConn.CancelRequest(context.Background()) + err := pgConn.CancelRequest(ctx) require.NoError(t, err) }() @@ -2070,13 +2256,16 @@ func TestConnCancelRequest(t *testing.T) { func TestConnContextCanceledCancelsRunningQueryOnServer(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) pid := pgConn.PID() - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() multiResult := pgConn.Exec(ctx, "select 'Hello, world', pg_sleep(30)") @@ -2091,11 +2280,14 @@ func TestConnContextCanceledCancelsRunningQueryOnServer(t *testing.T) { t.Fatal("Connection cleanup exceeded maximum time") } - otherConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + otherConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, otherConn) - ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) + ctx, cancel = context.WithTimeout(ctx, time.Second*5) defer cancel() for { @@ -2117,13 +2309,16 @@ func TestConnContextCanceledCancelsRunningQueryOnServer(t *testing.T) { func TestHijackAndConstruct(t *testing.T) { t.Parallel() - origConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + origConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) hc, err := origConn.Hijack() require.NoError(t, err) - _, err = origConn.Exec(context.Background(), "select 'Hello, world'").ReadAll() + _, err = origConn.Exec(ctx, "select 'Hello, world'").ReadAll() require.Error(t, err) newConn, err := pgconn.Construct(hc) @@ -2131,7 +2326,7 @@ func TestHijackAndConstruct(t *testing.T) { defer closeConn(t, newConn) - results, err := newConn.Exec(context.Background(), "select 'Hello, world'").ReadAll() + results, err := newConn.Exec(ctx, "select 'Hello, world'").ReadAll() assert.NoError(t, err) assert.Len(t, results, 1) @@ -2146,13 +2341,15 @@ func TestHijackAndConstruct(t *testing.T) { func TestConnCloseWhileCancellableQueryInProgress(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) - ctx, _ := context.WithCancel(context.Background()) pgConn.Exec(ctx, "select n from generate_series(1,10) n") - closeCtx, _ := context.WithCancel(context.Background()) + closeCtx, _ := context.WithCancel(ctx) pgConn.Close(closeCtx) select { case <-pgConn.CleanupDone(): @@ -2165,6 +2362,9 @@ func TestConnCloseWhileCancellableQueryInProgress(t *testing.T) { func TestFatalErrorReceivedAfterCommandComplete(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + steps := pgmock.AcceptUnauthenticatedConnRequestSteps() steps = append(steps, pgmock.ExpectAnyMessage(&pgproto3.Parse{})) steps = append(steps, pgmock.ExpectAnyMessage(&pgproto3.Bind{})) @@ -2212,7 +2412,7 @@ func TestFatalErrorReceivedAfterCommandComplete(t *testing.T) { port := parts[1] connStr := fmt.Sprintf("sslmode=disable host=%s port=%s", host, port) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel = context.WithTimeout(ctx, 5*time.Second) defer cancel() conn, err := pgconn.Connect(ctx, connStr) require.NoError(t, err) @@ -2230,11 +2430,14 @@ func TestFatalErrorReceivedAfterCommandComplete(t *testing.T) { func TestConnLargeResponseWhileWritingDoesNotDeadlock(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - _, err = pgConn.Exec(context.Background(), "set client_min_messages = debug5").ReadAll() + _, err = pgConn.Exec(ctx, "set client_min_messages = debug5").ReadAll() require.NoError(t, err) // The actual contents of this test aren't important. What's important is a large amount of data to be written and @@ -2249,7 +2452,7 @@ func TestConnLargeResponseWhileWritingDoesNotDeadlock(t *testing.T) { } sql := "values" + strings.Join(params, ", ") - result := pgConn.ExecParams(context.Background(), sql, args, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, sql, args, nil, nil, nil).Read() require.NoError(t, result.Err) require.Len(t, result.Rows, paramCount) @@ -2259,6 +2462,9 @@ func TestConnLargeResponseWhileWritingDoesNotDeadlock(t *testing.T) { func TestConnCheckConn(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + // Intentionally using TCP connection for more predictable close behavior. (Not sure if Unix domain sockets would behave subtlely different.) connString := os.Getenv("PGX_TEST_TCP_CONN_STRING") @@ -2266,9 +2472,9 @@ func TestConnCheckConn(t *testing.T) { t.Skipf("Skipping due to missing environment variable %v", "PGX_TEST_TCP_CONN_STRING") } - c1, err := pgconn.Connect(context.Background(), connString) + c1, err := pgconn.Connect(ctx, connString) require.NoError(t, err) - defer c1.Close(context.Background()) + defer c1.Close(ctx) if c1.ParameterStatus("crdb_version") != "" { t.Skip("Server does not support pg_terminate_backend() (https://github.com/cockroachdb/cockroach/issues/35897)") @@ -2277,11 +2483,11 @@ func TestConnCheckConn(t *testing.T) { err = c1.CheckConn() require.NoError(t, err) - c2, err := pgconn.Connect(context.Background(), connString) + c2, err := pgconn.Connect(ctx, connString) require.NoError(t, err) - defer c2.Close(context.Background()) + defer c2.Close(ctx) - _, err = c2.Exec(context.Background(), fmt.Sprintf("select pg_terminate_backend(%d)", c1.PID())).ReadAll() + _, err = c2.Exec(ctx, fmt.Sprintf("select pg_terminate_backend(%d)", c1.PID())).ReadAll() require.NoError(t, err) // Give a little time for the signal to actually kill the backend. @@ -2294,14 +2500,17 @@ func TestConnCheckConn(t *testing.T) { func TestPipelinePrepare(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - result := pgConn.ExecParams(context.Background(), `create temporary table t (id text primary key)`, nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, `create temporary table t (id text primary key)`, nil, nil, nil, nil).Read() require.NoError(t, result.Err) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendPrepare("selectInt", "select $1::bigint as a", nil) pipeline.SendPrepare("selectText", "select $1::text as b", nil) pipeline.SendPrepare("selectNoParams", "select 42 as c", nil) @@ -2366,11 +2575,14 @@ func TestPipelinePrepare(t *testing.T) { func TestPipelinePrepareError(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendPrepare("selectInt", "select $1::bigint as a", nil) pipeline.SendPrepare("selectError", "bad", nil) pipeline.SendPrepare("selectText", "select $1::text as b", nil) @@ -2408,11 +2620,14 @@ func TestPipelinePrepareError(t *testing.T) { func TestPipelinePrepareAndDeallocate(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendPrepare("selectInt", "select $1::bigint as a", nil) pipeline.SendDeallocate("selectInt") err = pipeline.Sync() @@ -2449,11 +2664,14 @@ func TestPipelinePrepareAndDeallocate(t *testing.T) { func TestPipelineQuery(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendQueryParams(`select 1`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 2`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 3`, nil, nil, nil, nil) @@ -2538,11 +2756,14 @@ func TestPipelineQuery(t *testing.T) { func TestPipelinePrepareQuery(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendPrepare("ps", "select $1::text as msg", nil) pipeline.SendQueryPrepared(`ps`, [][]byte{[]byte("hello")}, nil, nil) pipeline.SendQueryPrepared(`ps`, [][]byte{[]byte("goodbye")}, nil, nil) @@ -2595,11 +2816,14 @@ func TestPipelinePrepareQuery(t *testing.T) { func TestPipelineQueryErrorBetweenSyncs(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendQueryParams(`select 1`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 2`, nil, nil, nil, nil) err = pipeline.Sync() @@ -2699,11 +2923,14 @@ func TestPipelineQueryErrorBetweenSyncs(t *testing.T) { func TestPipelineCloseReadsUnreadResults(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendQueryParams(`select 1`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 2`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 3`, nil, nil, nil, nil) @@ -2734,11 +2961,14 @@ func TestPipelineCloseReadsUnreadResults(t *testing.T) { func TestPipelineCloseDetectsUnsyncedRequests(t *testing.T) { t.Parallel() - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) require.NoError(t, err) defer closeConn(t, pgConn) - pipeline := pgConn.StartPipeline(context.Background()) + pipeline := pgConn.StartPipeline(ctx) pipeline.SendQueryParams(`select 1`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 2`, nil, nil, nil, nil) pipeline.SendQueryParams(`select 3`, nil, nil, nil, nil) @@ -2763,13 +2993,16 @@ func TestPipelineCloseDetectsUnsyncedRequests(t *testing.T) { } func Example() { - pgConn, err := pgconn.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + pgConn, err := pgconn.Connect(ctx, os.Getenv("PGX_TEST_DATABASE")) if err != nil { log.Fatalln(err) } - defer pgConn.Close(context.Background()) + defer pgConn.Close(ctx) - result := pgConn.ExecParams(context.Background(), "select generate_series(1,3)", nil, nil, nil, nil).Read() + result := pgConn.ExecParams(ctx, "select generate_series(1,3)", nil, nil, nil, nil).Read() if result.Err != nil { log.Fatalln(result.Err) } @@ -2872,6 +3105,9 @@ func TestSNISupport(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + ln, err := net.Listen("tcp", "127.0.0.1:") require.NoError(t, err) defer ln.Close() @@ -2945,7 +3181,7 @@ func TestSNISupport(t *testing.T) { port := strings.Split(ln.Addr().String(), ":")[1] connStr := fmt.Sprintf("sslmode=require host=localhost port=%s %s", port, tt.sni_param) - _, err = pgconn.Connect(context.Background(), connStr) + _, err = pgconn.Connect(ctx, connStr) select { case sniHost := <-serverSNINameChan: diff --git a/pgtype/hstore_test.go b/pgtype/hstore_test.go index 3d3e722e..aa6881c5 100644 --- a/pgtype/hstore_test.go +++ b/pgtype/hstore_test.go @@ -4,6 +4,7 @@ import ( "context" "reflect" "testing" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" @@ -215,7 +216,10 @@ func TestHstoreCodec(t *testing.T) { pgxtest.RunValueRoundTripTests(context.Background(), t, ctrWithoutCodec, pgxtest.AllQueryExecModes, "hstore", tests) // scan empty and NULL: should be different in all query modes - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, pgxtest.AllQueryExecModes, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, pgxtest.AllQueryExecModes, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { h := pgtype.Hstore{"should_be_erased": nil} err := conn.QueryRow(ctx, `select cast(null as hstore)`).Scan(&h) if err != nil { diff --git a/query_test.go b/query_test.go index d2aa0f63..bbb59a99 100644 --- a/query_test.go +++ b/query_test.go @@ -220,7 +220,10 @@ func TestConnQueryValuesWithUnregisteredOID(t *testing.T) { func TestConnQueryArgsAndScanWithUnregisteredOID(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tx, err := conn.Begin(ctx) require.NoError(t, err) defer tx.Rollback(ctx) @@ -1943,7 +1946,10 @@ func TestQueryErrorWithDisabledStatementCache(t *testing.T) { func TestQueryWithQueryRewriter(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { qr := testQueryRewriter{sql: "select $1::int", args: []any{42}} rows, err := conn.Query(ctx, "should be replaced", &qr) require.NoError(t, err) diff --git a/rows_test.go b/rows_test.go index e85bacec..3bc587a7 100644 --- a/rows_test.go +++ b/rows_test.go @@ -39,7 +39,10 @@ func TestRowScanner(t *testing.T) { func TestForEachRow(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { var actualResults []any rows, _ := conn.Query( @@ -67,7 +70,10 @@ func TestForEachRow(t *testing.T) { func TestForEachRowScanError(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { var actualResults []any rows, _ := conn.Query( @@ -88,7 +94,10 @@ func TestForEachRowScanError(t *testing.T) { func TestForEachRowAbort(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { rows, _ := conn.Query( context.Background(), "select n, n * 2 from generate_series(1, $1) n", diff --git a/tracelog/tracelog_test.go b/tracelog/tracelog_test.go index 5458eaea..9ea08a08 100644 --- a/tracelog/tracelog_test.go +++ b/tracelog/tracelog_test.go @@ -7,6 +7,7 @@ import ( "os" "strings" "testing" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxtest" @@ -71,7 +72,10 @@ func TestContextGetsPassedToLogMethod(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { logger.Clear() // Clear any logs written when establishing connection ctx = context.WithValue(context.Background(), "ctxdata", "foo") @@ -133,7 +137,10 @@ func TestLogQuery(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { logger.Clear() // Clear any logs written when establishing connection _, err := conn.Exec(ctx, `select $1::text`, "testing") @@ -172,7 +179,10 @@ func TestLogQueryArgsHandlesUTF8(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { logger.Clear() // Clear any logs written when establishing connection var s string @@ -217,7 +227,10 @@ func TestLogCopyFrom(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, pgxtest.KnownOIDQueryExecModes, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, pgxtest.KnownOIDQueryExecModes, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { _, err := conn.Exec(context.Background(), `create temporary table foo(a int4)`) require.NoError(t, err) @@ -302,7 +315,10 @@ func TestLogBatchStatementsOnExec(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { logger.Clear() // Clear any logs written when establishing connection batch := &pgx.Batch{} @@ -346,7 +362,10 @@ func TestLogBatchStatementsOnBatchResultClose(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { logger.Clear() // Clear any logs written when establishing connection batch := &pgx.Batch{} @@ -382,7 +401,10 @@ func TestLogPrepare(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, []pgx.QueryExecMode{ + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, []pgx.QueryExecMode{ pgx.QueryExecModeCacheStatement, pgx.QueryExecModeCacheDescribe, pgx.QueryExecModeDescribeExec, @@ -406,7 +428,10 @@ func TestLogPrepare(t *testing.T) { require.Equal(t, err, logs[0].data["err"]) }) - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { logger.Clear() // Clear any logs written when establishing connection _, err := conn.Prepare(ctx, "test_query_1", `select $1::int`) diff --git a/tracer_test.go b/tracer_test.go index 86375b34..409e6410 100644 --- a/tracer_test.go +++ b/tracer_test.go @@ -3,6 +3,7 @@ package pgx_test import ( "context" "testing" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxtest" @@ -106,7 +107,10 @@ func TestTraceExec(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { traceQueryStartCalled := false tracer.traceQueryStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context { traceQueryStartCalled = true @@ -143,7 +147,10 @@ func TestTraceQuery(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { traceQueryStartCalled := false tracer.traceQueryStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context { traceQueryStartCalled = true @@ -182,7 +189,10 @@ func TestTraceBatchNormal(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { traceBatchStartCalled := false tracer.traceBatchStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceBatchStartData) context.Context { traceBatchStartCalled = true @@ -242,7 +252,10 @@ func TestTraceBatchClose(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { traceBatchStartCalled := false tracer.traceBatchStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceBatchStartData) context.Context { traceBatchStartCalled = true @@ -290,7 +303,10 @@ func TestTraceBatchErrorWhileReadingResults(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, []pgx.QueryExecMode{pgx.QueryExecModeSimpleProtocol}, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, []pgx.QueryExecMode{pgx.QueryExecModeSimpleProtocol}, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { traceBatchStartCalled := false tracer.traceBatchStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceBatchStartData) context.Context { traceBatchStartCalled = true @@ -356,7 +372,10 @@ func TestTraceBatchErrorWhileReadingResultsWhileClosing(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, []pgx.QueryExecMode{pgx.QueryExecModeSimpleProtocol}, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, []pgx.QueryExecMode{pgx.QueryExecModeSimpleProtocol}, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { traceBatchStartCalled := false tracer.traceBatchStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceBatchStartData) context.Context { traceBatchStartCalled = true @@ -409,7 +428,13 @@ func TestTraceCopyFrom(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + traceCopyFromStartCalled := false tracer.traceCopyFromStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TraceCopyFromStartData) context.Context { traceCopyFromStartCalled = true @@ -426,7 +451,7 @@ func TestTraceCopyFrom(t *testing.T) { require.NoError(t, data.Err) } - _, err := conn.Exec(context.Background(), `create temporary table foo(a int4)`) + _, err := conn.Exec(ctx, `create temporary table foo(a int4)`) require.NoError(t, err) inputRows := [][]any{ @@ -434,7 +459,7 @@ func TestTraceCopyFrom(t *testing.T) { {nil}, } - copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, pgx.CopyFromRows(inputRows)) + copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a"}, pgx.CopyFromRows(inputRows)) require.NoError(t, err) require.EqualValues(t, len(inputRows), copyCount) require.True(t, traceCopyFromStartCalled) @@ -454,7 +479,10 @@ func TestTracePrepare(t *testing.T) { return config } - pgxtest.RunWithQueryExecModes(context.Background(), t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, ctr, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tracePrepareStartCalled := false tracer.tracePrepareStart = func(ctx context.Context, conn *pgx.Conn, data pgx.TracePrepareStartData) context.Context { tracePrepareStartCalled = true diff --git a/values_test.go b/values_test.go index 854fe279..5df47f63 100644 --- a/values_test.go +++ b/values_test.go @@ -19,7 +19,10 @@ import ( func TestDateTranscode(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { dates := []time.Time{ time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(1000, 1, 1, 0, 0, 0, 0, time.UTC), @@ -58,7 +61,10 @@ func TestDateTranscode(t *testing.T) { func TestTimestampTzTranscode(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { inputTime := time.Date(2013, 1, 2, 3, 4, 5, 6000, time.Local) var outputTime time.Time @@ -78,7 +84,10 @@ func TestTimestampTzTranscode(t *testing.T) { func TestJSONAndJSONBTranscode(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { for _, typename := range []string{"json", "jsonb"} { if _, ok := conn.TypeMap().TypeForName(typename); !ok { continue // No JSON/JSONB type -- must be running against old PostgreSQL @@ -246,7 +255,10 @@ func mustParseCIDR(t testing.TB, s string) *net.IPNet { func TestInetCIDRTranscodeIPNet(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tests := []struct { sql string value *net.IPNet @@ -297,7 +309,10 @@ func TestInetCIDRTranscodeIPNet(t *testing.T) { func TestInetCIDRTranscodeIP(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tests := []struct { sql string value net.IP @@ -361,7 +376,10 @@ func TestInetCIDRTranscodeIP(t *testing.T) { func TestInetCIDRArrayTranscodeIPNet(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tests := []struct { sql string value []*net.IPNet @@ -424,7 +442,10 @@ func TestInetCIDRArrayTranscodeIPNet(t *testing.T) { func TestInetCIDRArrayTranscodeIP(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tests := []struct { sql string value []net.IP @@ -510,7 +531,10 @@ func TestInetCIDRArrayTranscodeIP(t *testing.T) { func TestInetCIDRTranscodeWithJustIP(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tests := []struct { sql string value string @@ -556,7 +580,10 @@ func TestInetCIDRTranscodeWithJustIP(t *testing.T) { func TestArrayDecoding(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { tests := []struct { sql string query any @@ -672,7 +699,10 @@ func TestArrayDecoding(t *testing.T) { func TestEmptyArrayDecoding(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { var val []string err := conn.QueryRow(context.Background(), "select array[]::text[]").Scan(&val) @@ -717,7 +747,10 @@ func TestEmptyArrayDecoding(t *testing.T) { func TestPointerPointer(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { pgxtest.SkipCockroachDB(t, conn, "Server auto converts ints to bigint and test relies on exact types") type allTypes struct { @@ -803,7 +836,10 @@ func TestPointerPointer(t *testing.T) { func TestPointerPointerNonZero(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { f := "foo" dest := &f @@ -820,7 +856,10 @@ func TestPointerPointerNonZero(t *testing.T) { func TestEncodeTypeRename(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { type _int int inInt := _int(1) var outInt _int @@ -989,7 +1028,10 @@ func TestEncodeTypeRename(t *testing.T) { func TestRowsScanNilThenScanValue(t *testing.T) { t.Parallel() - pgxtest.RunWithQueryExecModes(context.Background(), t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + pgxtest.RunWithQueryExecModes(ctx, t, defaultConnTestRunner, nil, func(ctx context.Context, t testing.TB, conn *pgx.Conn) { sql := `select null as a, null as b union select 1, 2