README
¶
PostgreSQL DataStore Example
This example demonstrates how to use the PostgreSQL DataStore client with the Agent SDK.
Features Demonstrated
- Self-contained setup: Automatically creates and drops the test table
- Creating a PostgreSQL client
- Creating tables with indexes
- Inserting documents
- Retrieving documents by ID
- Updating documents
- Querying documents with filters
- Querying with limit and ordering
- Using transactions for atomic operations
- Multi-tenancy with organization ID isolation
- Cleaning up resources
Prerequisites
- PostgreSQL server running and accessible
- A database created with appropriate permissions
- No manual table setup required - the example creates and drops the table automatically
What the Example Does
The example automatically:
- Creates the
userstable with proper schema and indexes - Runs all CRUD and query operations
- Drops the
userstable at the end for clean up
This makes it completely self-contained and safe to run multiple times without manual cleanup.
Configuration
Set the PostgreSQL connection string as an environment variable:
# Local development (SSL disabled)
export POSTGRES_URL="postgres://username:password@localhost:5432/dbname?sslmode=disable"
# Production (SSL enabled)
export POSTGRES_URL="postgres://username:password@host:5432/dbname?sslmode=require"
Replace the connection string with your actual PostgreSQL credentials:
username: Your PostgreSQL usernamepassword: Your PostgreSQL passwordlocalhost:5432: Your PostgreSQL host and portdbname: Your database namesslmode=disable: SSL mode (see SSL Configuration below)
SSL Configuration
If you get an error like "SSL is not enabled on the server", add ?sslmode=disable to your connection string:
export POSTGRES_URL="postgres://user:password@localhost:5432/dbname?sslmode=disable"
Available SSL modes:
disable- No SSL (local development, trusted networks)require- Require SSL but don't verify certificateverify-ca- Require SSL and verify CA certificateverify-full- Require SSL and verify CA + hostname (recommended for production)
Running the Example
cd examples/datastore/postgres
go run main.go
Expected Output
The example will:
- Drop any existing
userstable (clean slate) - Create the
userstable with indexes - Insert a new user document
- Retrieve the document by ID
- Update the document
- Retrieve the updated document
- Insert multiple user documents
- Query active users
- Query with limit and ordering
- Perform a transaction with multiple operations
- Delete all created documents
- Drop the
userstable
Example Output
PostgreSQL DataStore Example
============================
Setting up database...
1. Cleaning up any existing tables...
Cleaned up successfully
2. Creating users table...
Table created successfully
3. Inserting a document...
Inserted user with ID: 123e4567-e89b-12d3-a456-426614174000
4. Retrieving the document...
Retrieved user: map[age:28 created_at:2024-01-15T10:30:00Z email:alice@example.com id:123e4567-e89b-12d3-a456-426614174000 name:Alice Johnson org_id:demo-org-123 status:active]
5. Updating the document...
Document updated successfully
6. Retrieving updated document...
Updated user: map[age:29 created_at:2024-01-15T10:30:00Z email:alice@example.com id:123e4567-e89b-12d3-a456-426614174000 name:Alice Johnson org_id:demo-org-123 status:verified updated_at:2024-01-15T10:30:15Z]
7. Inserting multiple documents...
Inserted user: Bob Smith with ID: 223e4567-e89b-12d3-a456-426614174001
Inserted user: Carol White with ID: 323e4567-e89b-12d3-a456-426614174002
Inserted user: David Brown with ID: 423e4567-e89b-12d3-a456-426614174003
8. Querying active users...
Found 3 active users
- Alice Johnson (alice@example.com)
- Bob Smith (bob@example.com)
- Carol White (carol@example.com)
9. Querying with limit and ordering...
Retrieved top 2 active users (ordered by name):
- Alice Johnson
- Bob Smith
10. Using transactions...
Transaction completed successfully
11. Cleaning up - deleting all created documents...
Deleted user with ID: 123e4567-e89b-12d3-a456-426614174000
Deleted user with ID: 223e4567-e89b-12d3-a456-426614174001
Deleted user with ID: 323e4567-e89b-12d3-a456-426614174002
Deleted user with ID: 423e4567-e89b-12d3-a456-426614174003
Deleted user with ID: 523e4567-e89b-12d3-a456-426614174004
12. Dropping users table...
Table dropped successfully
Example completed successfully!
Key Concepts
Self-Contained Example
This example is completely self-contained and:
- Creates its own table with the proper schema and indexes
- Runs all operations on the created table
- Cleans up after itself by dropping the table at the end
- Can be run multiple times without conflicts
- Requires no manual database setup beyond creating the database itself
Multi-Tenancy
All operations are automatically scoped to an organization ID:
ctx := multitenancy.WithOrgID(context.Background(), "demo-org-123")
This ensures data isolation between different organizations.
Automatic Fields
The client automatically manages these fields:
id: Generated UUID if not providedorg_id: Set from contextcreated_at: Set on insertupdated_at: Set on update
Transactions
Transactions ensure atomicity of multiple operations:
err := client.Transaction(ctx, func(tx interfaces.Transaction) error {
collection := tx.Collection("users")
// Multiple operations...
// If any fails, all are rolled back
return nil // or return error to rollback
})
Query Options
Available query options:
interfaces.QueryWithLimit(n): Limit resultsinterfaces.QueryWithOffset(n): Skip resultsinterfaces.QueryWithOrderBy(field, direction): Order results
Error Handling
The example includes basic error handling. In production, you should:
- Check for specific error types
- Implement retry logic for transient failures
- Log errors appropriately
- Handle database connection issues
Next Steps
- Explore more complex queries
- Implement pagination for large datasets
- Add indexes for better performance
- Use connection pooling for production workloads
- Implement proper error handling and logging
Related Examples
/examples/datastore/supabase- Supabase DataStore example/examples/memory- Memory storage example
Documentation
Documentation
¶
There is no documentation for this package.