...

Source file src/github.com/jackc/pgx/v5/conn_internal_test.go

Documentation: github.com/jackc/pgx/v5

     1  package pgx
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func mustParseConfig(t testing.TB, connString string) *ConnConfig {
    14  	config, err := ParseConfig(connString)
    15  	require.Nil(t, err)
    16  	return config
    17  }
    18  
    19  func mustConnect(t testing.TB, config *ConnConfig) *Conn {
    20  	conn, err := ConnectConfig(context.Background(), config)
    21  	if err != nil {
    22  		t.Fatalf("Unable to establish connection: %v", err)
    23  	}
    24  	return conn
    25  }
    26  
    27  // Ensures the connection limits the size of its cached objects.
    28  // This test examines the internals of *Conn so must be in the same package.
    29  func TestStmtCacheSizeLimit(t *testing.T) {
    30  	const cacheLimit = 16
    31  
    32  	connConfig := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE"))
    33  	connConfig.StatementCacheCapacity = cacheLimit
    34  	conn := mustConnect(t, connConfig)
    35  	defer func() {
    36  		err := conn.Close(context.Background())
    37  		if err != nil {
    38  			t.Fatal(err)
    39  		}
    40  	}()
    41  
    42  	// run a set of unique queries that should overflow the cache
    43  	ctx := context.Background()
    44  	for i := 0; i < cacheLimit*2; i++ {
    45  		uniqueString := fmt.Sprintf("unique %d", i)
    46  		uniqueSQL := fmt.Sprintf("select '%s'", uniqueString)
    47  		var output string
    48  		err := conn.QueryRow(ctx, uniqueSQL).Scan(&output)
    49  		require.NoError(t, err)
    50  		require.Equal(t, uniqueString, output)
    51  	}
    52  	// preparedStatements contains cacheLimit+1 because deallocation happens before the query
    53  	assert.Len(t, conn.preparedStatements, cacheLimit+1)
    54  	assert.Equal(t, cacheLimit, conn.statementCache.Len())
    55  }
    56  

View as plain text