To add database support for maintaining a history of asset maintenance, you would typically use a relational database system like SQLite, PostgreSQL, or MySQL. For simplicity, we will use SQLite with the rusqlite crate, since it's an embedded database that doesn't require setting up a separate database server, and it's suitable for small to medium-size applications.
First, add the rusqlite crate to your Cargo.toml:
[dependencies]
rusqlite = "0.26.0"
Next, update your src/main.rs file to support basic operations using SQLite. Below, we're adding functions to create a database, add a maintenance record, list maintenance history, and other utilities for asset management. The code includes error handling with Result to manage potential failures during database operations.
use rusqlite::{params, Connection, Result};
use std::time::SystemTime;
// Define the Asset structure
#[derive(Debug, Clone)]
struct Asset {
id: u32,
name: String,
}
// Define the MaintenanceRecord structure
#[derive(Debug, Clone)]
struct MaintenanceRecord {
asset_id: u32,
date: String,
}
// Definitions related to database tables
const CREATE_ASSET_TABLE: &str = "
CREATE TABLE IF NOT EXISTS assets (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE
)";
const CREATE_MAINTENANCE_TABLE: &str = "
CREATE TABLE IF NOT EXISTS maintenances (
id INTEGER PRIMARY KEY AUTOINCREMENT,
asset_id INTEGER NOT NULL,
date TEXT NOT NULL,
FOREIGN KEY (asset_id) REFERENCES assets(id)
)";
fn create_tables(conn: &Connection) -> Result<()> {
conn.execute(CREATE_ASSET_TABLE, [])?;
conn.execute(CREATE_MAINTENANCE_TABLE, [])?;
Ok(())
}
// Database Operations
fn add_asset(conn: &Connection, id: u32, name: &str) -> Result<()> {
conn.execute(
"INSERT INTO assets (id, name) VALUES (?1, ?2)",
params![id, name],
)?;
Ok(())
}
fn add_maintenance_record(conn: &Connection, asset_id: u32, date: &str) -> Result<()> {
conn.execute(
"INSERT INTO maintenances (asset_id, date) VALUES (?1, ?2)",
params![asset_id, date],
)?;
Ok(())
}
fn list_maintenance_history(conn: &Connection, asset_id: u32) -> Result<Vec<MaintenanceRecord>> {
let mut stmt = conn.prepare("SELECT asset_id, date FROM maintenances WHERE asset_id = ?1")?;
let maintenance_iter = stmt.query_map(params![asset_id], |row| {
Ok(MaintenanceRecord {
asset_id: row.get(0)?,
date: row.get(1)?,
})
})?;
let mut history = Vec::new();
for maintenance in maintenance_iter {
history.push(maintenance?);
}
Ok(history)
}
fn current_date_string() -> String {
if let Ok(now) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
let date = chrono::NaiveDateTime::from_timestamp(now.as_secs() as i64, 0);
format!("{}", date.format("%Y-%m-%d %H:%M:%S"))
} else {
"Unknown".to_string()
}
}
fn main() -> Result<()> {
let conn = Connection::open_in_memory()?;
create_tables(&conn)?;
// Example Usage
add_asset(&conn, 1, "Generator")?;
add_asset(&conn, 2, "Vehicle")?;
let date = current_date_string();
add_maintenance_record(&conn, 1, &date)?;
add_maintenance_record(&conn, 2, &date)?;
let history = list_maintenance_history(&conn, 1)?;
println!("Maintenance History for asset 1: {:?}", history);
Ok(())
}
Please note the following in the example above:
- We added a
MaintenanceRecord struct; a history record includes the asset ID and a string for the date.
- The
create_tables function creates the necessary tables in SQLite if they don't exist.
- The
add_asset and add_maintenance_record functions insert new records into the respective tables.
- The
list_maintenance_history function lists all maintenance records for a given asset.
- The
main function demonstrates how you can call these functions to manage assets and maintenance records.
- We've added a utility function
current_date_string to generate a timestamp string in the format "YYYY-MM-DD HH:MM:SS".
Remember to handle errors appropriately based on your application's requirements. Also, this example uses an in-memory SQLite database, which means it will not persist if your application restarts. In a production environment, you would use a file-based SQLite database or a more robust SQL database system, and you'd likely want to organize your code into modules for better maintainability.
Lastly, be aware that for using a real-world application, especially one that contains vital records like an asset maintenance software, using proper data validation, authentication, and authorization mechanisms is crucial for security and data integrity. As your program grows, consider these as important areas to focus on.