MCPcopy
hub / github.com/jackc/pgx / testConnContextCanceledCancelsRunningQueryOnServer

Function testConnContextCanceledCancelsRunningQueryOnServer

pgconn/pgconn_test.go:2890–2946  ·  view source on GitHub ↗
(t *testing.T, connString, dbType string)

Source from the content-addressed store, hash-verified

2888}
2889
2890func testConnContextCanceledCancelsRunningQueryOnServer(t *testing.T, connString, dbType string) {
2891 ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
2892 defer cancel()
2893
2894 pgConn, err := pgconn.Connect(ctx, connString)
2895 require.NoError(t, err)
2896 defer closeConn(t, pgConn)
2897
2898 ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
2899 defer cancel()
2900
2901 // Getting the actual PostgreSQL server process ID (PID) from a query executed through pgbouncer is not straightforward
2902 // because pgbouncer abstracts the underlying database connections, and it doesn't expose the PID of the PostgreSQL
2903 // server process to clients. However, we can check if the query is running by checking the generated query ID.
2904 queryID := fmt.Sprintf("%s testConnContextCanceled %d", dbType, time.Now().UnixNano())
2905
2906 multiResult := pgConn.Exec(ctx, fmt.Sprintf(`
2907 -- %v
2908 select 'Hello, world', pg_sleep(30)
2909 `, queryID))
2910
2911 for multiResult.NextResult() {
2912 }
2913 err = multiResult.Close()
2914 assert.True(t, pgconn.Timeout(err))
2915 assert.True(t, pgConn.IsClosed())
2916 select {
2917 case <-pgConn.CleanupDone():
2918 case <-time.After(5 * time.Second):
2919 t.Fatal("Connection cleanup exceeded maximum time")
2920 }
2921
2922 ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
2923 defer cancel()
2924
2925 otherConn, err := pgconn.Connect(ctx, connString)
2926 require.NoError(t, err)
2927 defer closeConn(t, otherConn)
2928
2929 ctx, cancel = context.WithTimeout(ctx, time.Second*5)
2930 defer cancel()
2931
2932 for {
2933 result := otherConn.ExecParams(ctx,
2934 `select 1 from pg_stat_activity where query like $1`,
2935 [][]byte{[]byte("%" + queryID + "%")},
2936 nil,
2937 nil,
2938 nil,
2939 ).Read()
2940 require.NoError(t, result.Err)
2941
2942 if len(result.Rows) == 0 {
2943 break
2944 }
2945 }
2946}
2947

Calls 10

ConnectFunction · 0.92
TimeoutFunction · 0.92
NextResultMethod · 0.80
CleanupDoneMethod · 0.80
closeConnFunction · 0.70
ExecMethod · 0.65
CloseMethod · 0.65
IsClosedMethod · 0.45
ReadMethod · 0.45
ExecParamsMethod · 0.45

Tested by

no test coverage detected