Skip to content

Commit b7ed26a

Browse files
committed
Update example and README.md
1 parent 4cf59f9 commit b7ed26a

3 files changed

Lines changed: 66 additions & 37 deletions

File tree

go/pgx/README.md

Lines changed: 51 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,33 @@
1-
# Aurora DSQL pgx code examples
1+
# PGX with Aurora DSQL
22

33
## Overview
44

5-
The code examples in this topic show you how to use DSQL with Go pgx.
5+
This code example demonstrates how to use the `pgx` driver with Amazon Aurora DSQL. The example shows you how to connect to an Aurora DSQL cluster and perform database operations using IAM authentication.
66

7-
## Features
7+
Aurora DSQL is a distributed SQL database service that provides high availability and scalability for your PostgreSQL-compatible applications. `pgx` is a pure Go driver and toolkit for PostgreSQL that offers robust features including automatic connection pool management and authentication token refresh.
88

9-
- Uses `dsql.NewFromConfig` to create DSQL clients from AWS configuration
10-
- Supports automatic token refresh to maintain database connectivity
11-
- Implements connection pooling with pgx
12-
- Thread-safe token refresh mechanism
13-
- Demonstrates that connections before and after refresh are different
9+
10+
## About the code example
11+
12+
The example demonstrates a flexible connection approach using IAM authentication:
13+
14+
- Implements automatic token refresh mechanism to maintain continuous database connectivity
15+
- Handles secure IAM-based authentication token generation
16+
- Provides connection pooling and management
17+
- Demonstrates best practices for Aurora DSQL connectivity in Go applications
18+
19+
## ⚠️ Important
20+
21+
- Running this code might result in charges to your AWS account.
22+
- We recommend that you grant your code least privilege. At most, grant only the
23+
minimum permissions required to perform the task. For more information, see
24+
Grant least privilege in the AWS IAM User Guide.
25+
- This code is not tested in every AWS Region. For more information, see
26+
AWS Regional Services.
1427

1528
## Configuration
1629

17-
The following environment variables can be used to configure the connection:
30+
The following environment variables can be used to configure the connection parameter in this example:
1831

1932
- `CLUSTER_ENDPOINT`: Your Aurora cluster endpoint (required)
2033
- `REGION`: AWS region where your cluster is located (required)
@@ -31,21 +44,40 @@ The following environment variables can be used to configure the connection:
3144

3245
### Prerequisites
3346

34-
* Go version >= 1.21
35-
* AWS credentials file is configured
47+
- You must have an AWS account, and have your default credentials and AWS Region
48+
configured as described in the
49+
[Globally configuring AWS SDKs and tools](https://docs.aws.amazon.com/credref/latest/refdocs/creds-config-files.html)
50+
guide.
51+
-You must have an Aurora DSQL cluster. For information about creating an Aurora DSQL cluster, see the
52+
[Getting started with Aurora DSQL](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/getting-started.html)
53+
guide.
54+
- If connecting as a non-admin user, ensure the user is linked to an IAM role and is granted access to the `myschema`
55+
schema. See the
56+
[Using database roles with IAM roles](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/using-database-and-iam-roles.html)
57+
guide.
58+
- Go version >= 1.21
3659

3760
### Setup test running environment
3861

3962
Ensure you are authenticated with AWS credentials. No other setup is needed besides having Go installed.
4063

64+
### Environment Variables
65+
Set the following required environment variables:
66+
67+
```shell
68+
# Your cluster endpoint (e.g., "cluster-name.cluster-xxx.region.rds.amazonaws.com")
69+
export CLUSTER_ENDPOINT="<your cluster endpoint>"
70+
71+
# Your AWS region (e.g., "us-east-1")
72+
export REGION="<your cluster region>"
73+
```
74+
4175
### Run the example tests
4276

4377
In a terminal run the following commands:
4478

4579
```sh
4680
# Use the account credentials dedicated for golang
47-
export CLUSTER_ENDPOINT="<your cluster endpoint>"
48-
export REGION="<your cluster region>"
4981
go env -w GOPROXY=direct
5082
go test
5183

@@ -56,31 +88,19 @@ go build
5688

5789
## Token Refresh
5890

91+
Token Refresh
5992
The implementation includes an automatic token refresh mechanism that:
6093

6194
1. Creates a new token before the current one expires (default: every 15 minutes)
62-
2. Updates the connection pool with the new token
63-
3. Ensures all new connections use the refreshed token
64-
4. Handles the refresh process in a thread-safe manner
65-
66-
You can disable token refresh by setting the environment variable `DB_REFRESH_TOKEN=false`.
67-
68-
### Connection Refresh Verification
6995

70-
The code now includes functionality to verify that connections before and after token refresh are different:
96+
1. Ensures continuous database connectivity
7197

72-
1. The `TestTokenRefresh` test captures connection IDs before and after refresh and verifies they are different
73-
2. The `TestMultipleConnectionsRefresh` test checks multiple connections to ensure all are replaced
74-
3. The `TestComprehensiveConnectionRefresh` test provides detailed statistics about the connection pool before and after refresh
75-
4. The example application includes a demonstration of connection refresh that shows the connection IDs changing
98+
1. Handles token generation and rotation securelye fresh connections with valid authentication tokens.
7699

77-
When the token is refreshed, the following happens:
78-
- The old connection pool is reset
79-
- A new connection pool is created with the new token
80-
- All existing connections are closed and replaced with new connections
81-
- The new connections have different process IDs on the database server
100+
## Additional resources
82101

83-
This ensures that all database operations after a token refresh use fresh connections with valid authentication tokens.
102+
- [Amazon Aurora DSQL Documentation](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/what-is-aurora-dsql.html)
103+
- [AWS SDK for Go Documentation](https://docs.aws.amazon.com/sdk-for-go/)
84104

85105
---
86106

go/pgx/example.go

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,23 @@ func NewDSQLClient(ctx context.Context, region string) (*dsql.Client, error) {
6363
return dsqlClient, nil
6464
}
6565

66-
// GenerateDbConnectAdminAuthToken generates an authentication token for database connection
67-
func GenerateDbConnectAdminAuthToken(ctx context.Context, clusterEndpoint, region string) (string, error) {
66+
// GenerateDbConnectAuthToken generates an authentication token for database connection
67+
func GenerateDbConnectAuthToken(ctx context.Context, clusterEndpoint, region, user string) (string, error) {
6868
cfg, err := config.LoadDefaultConfig(ctx)
6969
if err != nil {
7070
return "", err
7171
}
7272

73-
token, err := auth.GenerateDBConnectAdminAuthToken(ctx, clusterEndpoint, region, cfg.Credentials)
73+
if user == "admin" {
74+
token, err := auth.GenerateDBConnectAdminAuthToken(ctx, clusterEndpoint, region, cfg.Credentials)
75+
if err != nil {
76+
return "", err
77+
}
78+
79+
return token, nil
80+
}
81+
82+
token, err := auth.GenerateDbConnectAuthToken(ctx, clusterEndpoint, region, cfg.Credentials)
7483
if err != nil {
7584
return "", err
7685
}
@@ -122,7 +131,7 @@ func NewPool(ctx context.Context, clusterEndpoint string, region string) (*Pool,
122131
}
123132

124133
// Generate initial token
125-
token, err := GenerateDbConnectAdminAuthToken(poolCtx, clusterEndpoint, region)
134+
token, err := GenerateDbConnectAuthToken(poolCtx, clusterEndpoint, region, dbConfig.User)
126135
if err != nil {
127136
cancel()
128137
return nil, fmt.Errorf("failed to generate auth token: %v", err)
@@ -205,7 +214,7 @@ func (p *Pool) refreshToken() error {
205214
defer p.mu.Unlock()
206215

207216
// Generate new token
208-
token, err := GenerateDbConnectAdminAuthToken(p.ctx, p.clusterEndpoint, p.config.Region)
217+
token, err := GenerateDbConnectAuthToken(p.ctx, p.clusterEndpoint, p.config.Region, p.config.User)
209218
if err != nil {
210219
return fmt.Errorf("failed to refresh auth token: %v", err)
211220
}

go/pgx/example_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func TestGenerateDbConnectAdminAuthToken(t *testing.T) {
4040
ctx := context.Background()
4141

4242
// Test token generation
43-
token, err := GenerateDbConnectAdminAuthToken(ctx, clusterEndpoint, region)
43+
token, err := GenerateDbConnectAuthToken(ctx, clusterEndpoint, region, "admin")
4444
if err != nil {
4545
t.Errorf("Error generating auth token: %v\n", err)
4646
}

0 commit comments

Comments
 (0)