SAL PostgreSQL Client (sal-postgresclient
)
The SAL PostgreSQL Client (sal-postgresclient
) is an independent package that provides a simple and efficient way to interact with PostgreSQL databases in Rust. It offers connection management, query execution, a builder pattern for flexible configuration, and PostgreSQL installer functionality using nerdctl.
Installation
Add this to your Cargo.toml
:
[]
= "0.1.0"
Features
- Connection Management: Automatic connection handling and reconnection
- Query Execution: Simple API for executing queries and fetching results
- Builder Pattern: Flexible configuration with authentication support
- Environment Variable Support: Easy configuration through environment variables
- Thread Safety: Safe to use in multi-threaded applications
- PostgreSQL Installer: Install and configure PostgreSQL using nerdctl containers
- Rhai Integration: Scripting support for PostgreSQL operations
Usage
Basic Usage
use ;
// Execute a query
let create_table_query = "CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)";
execute.expect;
// Insert data
let insert_query = "INSERT INTO users (name) VALUES ($1) RETURNING id";
let rows = query.expect;
let id: i32 = rows.get;
// Query data
let select_query = "SELECT id, name FROM users WHERE id = $1";
let row = query_one.expect;
let name: String = row.get;
println!;
Connection Management
The module manages connections automatically, but you can also reset the connection if needed:
use reset;
// Reset the PostgreSQL client connection
reset.expect;
Builder Pattern
The module provides a builder pattern for flexible configuration:
use ;
// Create a configuration builder
let config = new
.host
.port
.user
.password
.database
.application_name
.connect_timeout
.ssl_mode;
// Connect with the configuration
let client = with_config.expect;
PostgreSQL Installer
The package includes a PostgreSQL installer that can set up PostgreSQL using nerdctl containers:
use ;
// Create installer configuration
let config = new
.container_name
.version
.port
.username
.password
.data_dir
.persistent;
// Install PostgreSQL
let container = install_postgres.expect;
Rhai Integration
The package provides Rhai scripting support for PostgreSQL operations:
use register_postgresclient_module;
use Engine;
let mut engine = new;
register_postgresclient_module.expect;
// Now you can use PostgreSQL functions in Rhai scripts
let script = r#"
// Connect to PostgreSQL
let connected = pg_connect();
// Execute a query
let rows_affected = pg_execute("CREATE TABLE test (id SERIAL PRIMARY KEY, name TEXT)");
// Query data
let results = pg_query("SELECT * FROM test");
"#;
engine..expect;
Configuration
Environment Variables
The module uses the following environment variables for configuration:
POSTGRES_HOST
: PostgreSQL server host (default: localhost)POSTGRES_PORT
: PostgreSQL server port (default: 5432)POSTGRES_USER
: PostgreSQL username (default: postgres)POSTGRES_PASSWORD
: PostgreSQL passwordPOSTGRES_DB
: PostgreSQL database name (default: postgres)
Connection String
The connection string is built from the configuration options:
host=localhost port=5432 user=postgres dbname=postgres
With authentication:
host=localhost port=5432 user=postgres password=secret dbname=postgres
With additional options:
host=localhost port=5432 user=postgres dbname=postgres application_name=my-app connect_timeout=30 sslmode=require
API Reference
Connection Functions
get_postgres_client() -> Result<Arc<PostgresClientWrapper>, PostgresError>
: Get the PostgreSQL client instancereset() -> Result<(), PostgresError>
: Reset the PostgreSQL client connection
Query Functions
execute(query: &str, params: &[&(dyn postgres::types::ToSql + Sync)]) -> Result<u64, PostgresError>
: Execute a query and return the number of affected rowsquery(query: &str, params: &[&(dyn postgres::types::ToSql + Sync)]) -> Result<Vec<Row>, PostgresError>
: Execute a query and return the results as a vector of rowsquery_one(query: &str, params: &[&(dyn postgres::types::ToSql + Sync)]) -> Result<Row, PostgresError>
: Execute a query and return a single rowquery_opt(query: &str, params: &[&(dyn postgres::types::ToSql + Sync)]) -> Result<Option<Row>, PostgresError>
: Execute a query and return an optional row
Configuration Functions
PostgresConfigBuilder::new() -> PostgresConfigBuilder
: Create a new PostgreSQL configuration builderwith_config(config: PostgresConfigBuilder) -> Result<Client, PostgresError>
: Create a new PostgreSQL client with custom configuration
Error Handling
The module uses the postgres::Error
type for error handling:
use ;
// Handle errors
match query
// Using query_one with no results
match query_one
Thread Safety
The PostgreSQL client module is designed to be thread-safe. It uses Arc
and Mutex
to ensure safe concurrent access to the client instance.
Examples
Basic CRUD Operations
use ;
// Create
let create_query = "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id";
let rows = query.expect;
let id: i32 = rows.get;
// Read
let read_query = "SELECT id, name, email FROM users WHERE id = $1";
let row = query_one.expect;
let name: String = row.get;
let email: String = row.get;
// Update
let update_query = "UPDATE users SET email = $1 WHERE id = $2";
let affected = execute.expect;
// Delete
let delete_query = "DELETE FROM users WHERE id = $1";
let affected = execute.expect;
Transactions
Transactions are not directly supported by the module, but you can use the PostgreSQL client to implement them:
use ;
// Start a transaction
execute.expect;
// Perform operations
let insert_query = "INSERT INTO accounts (user_id, balance) VALUES ($1, $2)";
execute.expect;
let update_query = "UPDATE users SET has_account = TRUE WHERE id = $1";
execute.expect;
// Commit the transaction
execute.expect;
// Or rollback in case of an error
// execute("ROLLBACK", &[]).expect("Failed to rollback transaction");
Testing
The module includes comprehensive tests for both unit and integration testing:
// Unit tests
// Integration tests