lmrc-postgres
Part of the LMRC Stack - Infrastructure-as-Code toolkit for building production-ready Rust applications
A comprehensive Rust library for managing PostgreSQL installations on remote servers via SSH.
Features
- 🔨 Builder Pattern API: Fluent, type-safe configuration
- ♻️ Idempotent Operations: Safe to run multiple times
- 🔍 Diff Detection: Track and apply configuration changes
- 🔄 Full Lifecycle: Install, configure, update, and uninstall
- 🔐 SSH-based: Secure remote operations via
ssh-manager - ⚠️ Error Handling: Comprehensive error types with context
- 📝 Well Documented: Extensive documentation and examples
- ✅ Tested: Comprehensive unit and integration tests
Installation
Add this to your Cargo.toml:
[]
= "0.1"
= "0.1"
= { = "1.0", = ["full"] }
Quick Start
use ;
async
Usage Examples
Install with Custom Configuration
use ;
async
Detect and Apply Configuration Changes
use ;
async
Configuration Validation and Auto-Tuning
The library provides comprehensive validation and intelligent auto-tuning:
use ;
async
Validation Features:
- Memory size format validation (e.g., "256MB", "1GB")
- CIDR notation validation for network addresses
- Conflicting settings detection
- Resource limits validation
- PostgreSQL version format validation
Auto-Tuning Workload Types:
WorkloadType::Web- Web applications (moderate connections, OLTP + read-heavy)WorkloadType::Mixed- Mixed workload (OLTP + analytics)WorkloadType::DataWarehouse- Complex queries, fewer connectionsWorkloadType::Oltp- High-throughput OLTP (many connections, simple queries)
Step-by-Step Installation
use ;
async
Backup, Rollback, and Dry-Run
The library provides comprehensive safety features for configuration changes:
use ;
async
Safety Features:
- Dry-run mode: Preview changes before applying them
- Automatic backups: Configuration is backed up before changes
- Automatic rollback: If changes fail, automatically restore previous configuration
- Manual rollback: Quickly revert to any previous backup
- Backup management: List, restore, and cleanup old backups
- pg_hba.conf support: Read, parse, and diff authentication rules
User & Database Management
Comprehensive user and database lifecycle management with granular permission control:
use ;
async
User & Database Operations:
- List operations:
list_users(),list_databases()- Query all users/databases with metadata - Create operations:
create_database_with_options(),create_user_with_options()- Advanced creation with owner, encoding, capabilities - Drop operations:
drop_database(),drop_user()- Safely remove users and databases - Password management:
update_user_password()- Change user passwords - Existence checks:
user_exists(),database_exists()- Check if user/database exists - Granular privileges:
grant_privileges(),revoke_privileges()- 12+ privilege types (SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, USAGE, ALL) - Role management:
create_role(),grant_role(),revoke_role()- Create and assign roles for organized permissions
Uninstall PostgreSQL
use ;
async
API Overview
PostgresConfig Builder
let config = builder
.version // PostgreSQL version
.database_name // Database name
.username // Database user
.password // Database password
.listen_addresses // CIDR notation
.port // Port number
.max_connections // Max connections
.shared_buffers // Shared buffers
.effective_cache_size // Cache size
.work_mem // Work memory
.maintenance_work_mem // Maintenance memory
.wal_buffers // WAL buffers
.checkpoint_completion_target // Checkpoint target
.ssl // Enable SSL
.add_config // Custom config
.build?;
PostgresManager Builder
let manager = builder
.config // PostgresConfig instance
.server_ip // Server IP address
.ssh_user // SSH username
.ssh_port // SSH port
.private_ip // Private IP (optional)
.build?;
Core Operations
All operations are idempotent and can be safely run multiple times:
Installation & Setup:
is_installed()- Check if PostgreSQL is installedget_installed_version()- Get installed versioninstall()- Install PostgreSQLuninstall(purge)- Uninstall PostgreSQLconfigure_database()- Configure database and userconfigure_server()- Configure server settingsconfigure()- Configure both database and serversetup()- Complete installation and configurationtest_connection()- Test database connection
Configuration Management:
diff()- Detect configuration changesapply_diff(diff)- Apply configuration changesdry_run_configure()- Preview changes without applyingapply_diff_safe(diff)- Apply with automatic rollback on failure
Backup & Restore:
backup_config()- Create configuration backuplist_backups()- List all backupsrestore_backup(backup)- Restore specific backuprollback_config()- Quick rollback to most recentcleanup_old_backups(keep)- Manage backup historyread_pg_hba()- Read pg_hba.conf authentication rules
User Management:
list_users()- List all PostgreSQL userscreate_user_with_options()- Create user with advanced optionsdrop_user(username)- Remove userupdate_user_password(username, password)- Change passworduser_exists(username)- Check if user exists
Database Management:
list_databases()- List all databasescreate_database_with_options()- Create database with advanced optionsdrop_database(database)- Remove databasedatabase_exists(database)- Check if database exists
Permission Management:
grant_privileges(db, user, privileges)- Grant granular privilegesrevoke_privileges(db, user, privileges)- Revoke privilegescreate_role(role, can_login, is_superuser)- Create rolegrant_role(role, user)- Grant role to userrevoke_role(role, user)- Revoke role from user
Configuration Options
Required
version- PostgreSQL version (e.g., "15", "14", "13")database_name- Database name to createusername- Database usernamepassword- Database password
Optional
listen_addresses- CIDR notation (default: "0.0.0.0/0")port- PostgreSQL port (default: 5432)max_connections- Maximum concurrent connectionsshared_buffers- Shared memory buffers (e.g., "256MB")effective_cache_size- Query optimizer cache sizework_mem- Memory for sorts and queriesmaintenance_work_mem- Memory for maintenance operationswal_buffers- Write-ahead log bufferscheckpoint_completion_target- Checkpoint spread (0.0-1.0)ssl- Enable SSL (default: false)extra_config- Additional custom parameters
Error Handling
The library provides comprehensive error types:
use ;
match manager.install.await
Idempotency
All operations are designed to be idempotent:
- Install: Skips if already installed with the correct version
- Configure: Creates database/user if they don't exist, updates if they do
- Setup: Combines install and configure safely
- Uninstall: Succeeds even if not installed
This makes it safe to run operations multiple times without errors.
Testing
Run the test suite:
# Unit tests
# Integration tests (requires SSH access to a test server)
# All tests with logging
RUST_LOG=debug
Examples
See the examples/ directory for more usage examples:
basic_install.rs- Basic installationcustom_config.rs- Custom configurationdiff_detection.rs- Detect and apply changesuninstall.rs- Uninstall PostgreSQL
Run an example:
Platform Support
Currently supports:
- Debian-based Linux distributions (Debian, Ubuntu)
- PostgreSQL versions 12-16
Planned support:
- RedHat-based distributions (RHEL, CentOS, Fedora)
- Alpine Linux
- Other PostgreSQL versions
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
Part of the LMRC Stack project. Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Security
If you discover a security vulnerability, please email security@example.com instead of using the issue tracker.
Acknowledgments
- Built on top of ssh-manager
- Inspired by infrastructure-as-code tools like Ansible and Terraform