repo clean up
This commit is contained in:
parent
1074e1ba19
commit
0f3ea0fe2f
@ -1 +0,0 @@
|
||||
1
|
Binary file not shown.
@ -1 +0,0 @@
|
||||
1
|
Binary file not shown.
@ -1 +0,0 @@
|
||||
1
|
Binary file not shown.
@ -1 +0,0 @@
|
||||
1
|
Binary file not shown.
11
heromodels/Cargo.lock
generated
11
heromodels/Cargo.lock
generated
@ -396,7 +396,6 @@ dependencies = [
|
||||
"r2d2",
|
||||
"r2d2_postgres",
|
||||
"rhai",
|
||||
"rhai_client_macros",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"strum",
|
||||
@ -944,16 +943,6 @@ dependencies = [
|
||||
"thin-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhai_client_macros"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rhai",
|
||||
"syn 2.0.101",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhai_codegen"
|
||||
version = "2.2.0"
|
||||
|
@ -21,7 +21,6 @@ rhai = { version = "1.21.0", features = [
|
||||
"decimal",
|
||||
"internals",
|
||||
] } # Added "decimal" feature, sync for Arc<Mutex<>>
|
||||
rhai_client_macros = { path = "../rhai_client_macros" }
|
||||
strum = "0.26"
|
||||
strum_macros = "0.26"
|
||||
uuid = { version = "1.17.0", features = ["v4"] }
|
||||
@ -56,3 +55,7 @@ path = "examples/flow_example.rs"
|
||||
name = "biz_rhai"
|
||||
path = "examples/biz_rhai/example.rs"
|
||||
required-features = ["rhai"]
|
||||
|
||||
[[example]]
|
||||
name = "postgres_model_example"
|
||||
path = "examples/postgres_example/example.rs"
|
||||
|
@ -1,229 +0,0 @@
|
||||
// Payment Flow Rhai Example
|
||||
// This script demonstrates the complete payment flow for company registration
|
||||
// using the Rhai scripting interface.
|
||||
|
||||
print("=== Payment Flow Rhai Example ===");
|
||||
print("Demonstrating company registration with payment integration");
|
||||
print("");
|
||||
|
||||
// --- Step 1: Create Company with Pending Payment Status ---
|
||||
print("Step 1: Creating company with pending payment status");
|
||||
|
||||
let company_name = "InnovateTech Solutions";
|
||||
let company_reg = "REG-ITS-2024-001";
|
||||
let company_inc_date = 1704067200; // Jan 1, 2024
|
||||
|
||||
// Create company (status defaults to PendingPayment)
|
||||
let company = new_company(company_name, company_reg, company_inc_date)
|
||||
.email("contact@innovatetech.com")
|
||||
.phone("+1-555-0199")
|
||||
.website("https://innovatetech.com")
|
||||
.address("456 Innovation Blvd, Tech Valley, TV 67890")
|
||||
.business_type(BusinessTypeConstants::Starter)
|
||||
.industry("Software Development")
|
||||
.description("Cutting-edge software solutions for modern businesses")
|
||||
.fiscal_year_end("12-31");
|
||||
|
||||
print(` Company: ${company.name}`);
|
||||
print(` Status: ${company.status} (default for new companies)`);
|
||||
print(` Registration: ${company.registration_number}`);
|
||||
print(` Email: ${company.email}`);
|
||||
|
||||
// Save company to database
|
||||
company = set_company(company);
|
||||
print(` Saved with ID: ${company.id}`);
|
||||
print("");
|
||||
|
||||
// --- Step 2: Create Payment Record ---
|
||||
print("Step 2: Creating payment record");
|
||||
|
||||
let payment_intent_id = `pi_rhai_${timestamp()}`;
|
||||
let payment_plan = "yearly";
|
||||
let setup_fee = 750.0;
|
||||
let monthly_fee = 149.0;
|
||||
let total_amount = setup_fee + (monthly_fee * 12.0); // Setup + 12 months
|
||||
|
||||
let payment = new_payment(
|
||||
payment_intent_id,
|
||||
company.id,
|
||||
payment_plan,
|
||||
setup_fee,
|
||||
monthly_fee,
|
||||
total_amount
|
||||
);
|
||||
|
||||
print(` Payment Intent ID: ${payment.payment_intent_id}`);
|
||||
print(` Company ID: ${payment.company_id}`);
|
||||
print(` Payment Plan: ${payment.payment_plan}`);
|
||||
print(` Setup Fee: $${payment.setup_fee}`);
|
||||
print(` Monthly Fee: $${payment.monthly_fee}`);
|
||||
print(` Total Amount: $${payment.total_amount}`);
|
||||
print(` Status: ${payment.status} (default for new payments)`);
|
||||
|
||||
// Save payment to database
|
||||
payment = set_payment(payment);
|
||||
print(` Saved with ID: ${payment.id}`);
|
||||
print("");
|
||||
|
||||
// --- Step 3: Process Payment Successfully ---
|
||||
print("Step 3: Processing payment...");
|
||||
|
||||
// Simulate payment processing
|
||||
print(" Contacting payment processor...");
|
||||
print(" Validating payment details...");
|
||||
print(" Processing transaction...");
|
||||
|
||||
// Complete the payment with Stripe customer ID
|
||||
let stripe_customer_id = `cus_rhai_${timestamp()}`;
|
||||
payment = payment.complete_payment(stripe_customer_id);
|
||||
|
||||
print(" Payment completed successfully!");
|
||||
print(` New Status: ${payment.status}`);
|
||||
print(` Stripe Customer ID: ${payment.stripe_customer_id}`);
|
||||
|
||||
// Save updated payment
|
||||
payment = set_payment(payment);
|
||||
print("");
|
||||
|
||||
// --- Step 4: Update Company Status to Active ---
|
||||
print("Step 4: Updating company status to Active");
|
||||
|
||||
company = company.status(CompanyStatusConstants::Active);
|
||||
print(` Company: ${company.name}`);
|
||||
print(` New Status: ${company.status}`);
|
||||
|
||||
// Save updated company
|
||||
company = set_company(company);
|
||||
print(" Company status updated successfully!");
|
||||
print("");
|
||||
|
||||
// --- Step 5: Verify Payment Status ---
|
||||
print("Step 5: Payment status verification");
|
||||
print(` Is payment completed? ${payment.is_completed()}`);
|
||||
print(` Is payment pending? ${payment.is_pending()}`);
|
||||
print(` Has payment failed? ${payment.has_failed()}`);
|
||||
print(` Is payment refunded? ${payment.is_refunded()}`);
|
||||
print("");
|
||||
|
||||
// --- Step 6: Retrieve Data from Database ---
|
||||
print("Step 6: Verifying data from database");
|
||||
|
||||
let retrieved_company = get_company_by_id(company.id);
|
||||
print(` Retrieved Company: ${retrieved_company.name}`);
|
||||
print(` Status: ${retrieved_company.status}`);
|
||||
|
||||
let retrieved_payment = get_payment_by_id(payment.id);
|
||||
print(` Retrieved Payment: ${retrieved_payment.payment_intent_id}`);
|
||||
print(` Status: ${retrieved_payment.status}`);
|
||||
print(` Total: $${retrieved_payment.total_amount}`);
|
||||
print("");
|
||||
|
||||
// --- Step 7: Demonstrate Failed Payment Scenario ---
|
||||
print("Step 7: Demonstrating failed payment scenario");
|
||||
|
||||
// Create another company for failed payment demo
|
||||
let failed_company = new_company(
|
||||
"FailureDemo Corp",
|
||||
"REG-FDC-2024-002",
|
||||
1704067200
|
||||
)
|
||||
.email("demo@failurecorp.com")
|
||||
.business_type(BusinessTypeConstants::Single)
|
||||
.industry("Consulting");
|
||||
|
||||
failed_company = set_company(failed_company);
|
||||
print(` Created company: ${failed_company.name}`);
|
||||
print(` Status: ${failed_company.status} (pending payment)`);
|
||||
|
||||
// Create payment that will fail
|
||||
let failed_payment_intent = `pi_fail_${timestamp()}`;
|
||||
let failed_payment = new_payment(
|
||||
failed_payment_intent,
|
||||
failed_company.id,
|
||||
"monthly",
|
||||
300.0,
|
||||
59.0,
|
||||
359.0
|
||||
);
|
||||
|
||||
failed_payment = set_payment(failed_payment);
|
||||
|
||||
// Simulate payment failure
|
||||
print(" Simulating payment failure...");
|
||||
failed_payment = failed_payment.fail_payment();
|
||||
failed_payment = set_payment(failed_payment);
|
||||
|
||||
print(` Failed Company: ${failed_company.name}`);
|
||||
print(` Company Status: ${failed_company.status} (remains pending)`);
|
||||
print(` Payment Status: ${failed_payment.status}`);
|
||||
print(` Payment failed: ${failed_payment.has_failed()}`);
|
||||
print("");
|
||||
|
||||
// --- Step 8: Demonstrate Payment Refund ---
|
||||
print("Step 8: Demonstrating payment refund scenario");
|
||||
|
||||
// Create a payment to refund
|
||||
let refund_company = new_company(
|
||||
"RefundDemo Inc",
|
||||
"REG-RDI-2024-003",
|
||||
1704067200
|
||||
)
|
||||
.email("refund@demo.com")
|
||||
.business_type(BusinessTypeConstants::Twin);
|
||||
|
||||
refund_company = set_company(refund_company);
|
||||
|
||||
let refund_payment = new_payment(
|
||||
`pi_refund_${timestamp()}`,
|
||||
refund_company.id,
|
||||
"monthly",
|
||||
200.0,
|
||||
39.0,
|
||||
239.0
|
||||
);
|
||||
|
||||
refund_payment = set_payment(refund_payment);
|
||||
|
||||
// First complete the payment
|
||||
refund_payment = refund_payment.complete_payment(`cus_refund_${timestamp()}`);
|
||||
refund_payment = set_payment(refund_payment);
|
||||
print(` Payment completed: ${refund_payment.is_completed()}`);
|
||||
|
||||
// Then refund it
|
||||
refund_payment = refund_payment.refund_payment();
|
||||
refund_payment = set_payment(refund_payment);
|
||||
|
||||
print(` Payment refunded: ${refund_payment.is_refunded()}`);
|
||||
print(` Refund Status: ${refund_payment.status}`);
|
||||
print("");
|
||||
|
||||
// --- Summary ---
|
||||
print("=== Payment Flow Example Complete ===");
|
||||
print("Summary of demonstrated features:");
|
||||
print("✓ Company creation with PendingPayment status (default)");
|
||||
print("✓ Payment record creation and database persistence");
|
||||
print("✓ Successful payment processing and status updates");
|
||||
print("✓ Company status transition from PendingPayment to Active");
|
||||
print("✓ Payment status verification methods");
|
||||
print("✓ Database retrieval and verification");
|
||||
print("✓ Failed payment scenario handling");
|
||||
print("✓ Payment refund processing");
|
||||
print("");
|
||||
print("Key Payment Statuses:");
|
||||
print("- Pending: Initial state for new payments");
|
||||
print("- Completed: Payment successfully processed");
|
||||
print("- Failed: Payment processing failed");
|
||||
print("- Refunded: Previously completed payment was refunded");
|
||||
print("");
|
||||
print("Key Company Statuses:");
|
||||
print("- PendingPayment: Default for new companies (awaiting payment)");
|
||||
print("- Active: Payment completed, company is operational");
|
||||
print("- Suspended: Company temporarily suspended");
|
||||
print("- Inactive: Company deactivated");
|
||||
|
||||
// Helper function to get current timestamp
|
||||
fn timestamp() {
|
||||
// This would normally return current timestamp
|
||||
// For demo purposes, we'll use a static value
|
||||
1704067200
|
||||
}
|
@ -1,220 +0,0 @@
|
||||
// Payment Flow Rhai Example Runner
|
||||
// This example runs the payment_flow.rhai script to demonstrate
|
||||
// the payment integration using Rhai scripting.
|
||||
|
||||
use heromodels::db::hero::OurDB;
|
||||
use heromodels::models::biz::register_biz_rhai_module;
|
||||
use rhai::Engine;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("=== Payment Flow Rhai Example Runner ===");
|
||||
println!("Running payment flow demonstration using Rhai scripting\n");
|
||||
|
||||
// Initialize database
|
||||
let db = Arc::new(
|
||||
OurDB::new("/tmp/payment_flow_rhai_example", true)
|
||||
.map_err(|e| format!("DB Error: {}", e))?,
|
||||
);
|
||||
|
||||
// Create and configure Rhai engine
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Register the business models module with the engine
|
||||
register_biz_rhai_module(&mut engine, Arc::clone(&db));
|
||||
|
||||
// Add a timestamp function for the Rhai script
|
||||
engine.register_fn("timestamp", || -> i64 { chrono::Utc::now().timestamp() });
|
||||
|
||||
// Read and execute the Rhai script
|
||||
let script_path = "examples/biz_rhai/payment_flow.rhai";
|
||||
|
||||
match std::fs::read_to_string(script_path) {
|
||||
Ok(script_content) => {
|
||||
println!("Executing Rhai script: {}\n", script_path);
|
||||
|
||||
match engine.eval::<()>(&script_content) {
|
||||
Ok(_) => {
|
||||
println!("\n✅ Rhai script executed successfully!");
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("❌ Error executing Rhai script: {}", e);
|
||||
return Err(Box::new(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("❌ Error reading script file {}: {}", script_path, e);
|
||||
println!("Note: Make sure to run this example from the project root directory.");
|
||||
return Err(Box::new(e));
|
||||
}
|
||||
}
|
||||
|
||||
println!("\n=== Example Complete ===");
|
||||
println!("The payment flow has been successfully demonstrated using Rhai scripting.");
|
||||
println!("This shows how the payment integration can be used in scripted environments.");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use heromodels::db::Collection;
|
||||
use heromodels::models::biz::{Company, CompanyStatus, Payment, PaymentStatus};
|
||||
|
||||
#[test]
|
||||
fn test_rhai_payment_integration() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Test that we can create and manipulate payment objects through Rhai
|
||||
let db_config = OurDBConfig {
|
||||
path: "/tmp/test_rhai_payment".to_string(),
|
||||
incremental_mode: true,
|
||||
file_size: None,
|
||||
keysize: None,
|
||||
reset: Some(true),
|
||||
};
|
||||
|
||||
let db = Arc::new(OurDB::new(db_config)?);
|
||||
let mut engine = Engine::new();
|
||||
register_biz_rhai_module(&mut engine, Arc::clone(&db));
|
||||
|
||||
// Test creating a company through Rhai
|
||||
let company_script = r#"
|
||||
let company = new_company("Test Company", "TEST-001", 1704067200)
|
||||
.email("test@example.com")
|
||||
.status(CompanyStatusConstants::PendingPayment);
|
||||
company = set_company(company);
|
||||
company.id
|
||||
"#;
|
||||
|
||||
let company_id: i64 = engine.eval(company_script)?;
|
||||
assert!(company_id > 0);
|
||||
|
||||
// Test creating a payment through Rhai
|
||||
let payment_script = format!(
|
||||
r#"
|
||||
let payment = new_payment("pi_test_123", {}, "monthly", 100.0, 50.0, 150.0);
|
||||
payment = set_payment(payment);
|
||||
payment.id
|
||||
"#,
|
||||
company_id
|
||||
);
|
||||
|
||||
let payment_id: i64 = engine.eval(&payment_script)?;
|
||||
assert!(payment_id > 0);
|
||||
|
||||
// Test completing payment through Rhai
|
||||
let complete_script = format!(
|
||||
r#"
|
||||
let payment = get_payment_by_id({});
|
||||
payment = payment.complete_payment("cus_test_123");
|
||||
payment = set_payment(payment);
|
||||
payment.is_completed()
|
||||
"#,
|
||||
payment_id
|
||||
);
|
||||
|
||||
let is_completed: bool = engine.eval(&complete_script)?;
|
||||
assert!(is_completed);
|
||||
|
||||
// Verify in database
|
||||
let payment: Payment = db.get_by_id(payment_id as u32)?.unwrap();
|
||||
assert_eq!(payment.status, PaymentStatus::Completed);
|
||||
assert_eq!(payment.stripe_customer_id, Some("cus_test_123".to_string()));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_payment_status_constants() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Test that payment status constants are available in Rhai
|
||||
let db_config = OurDBConfig {
|
||||
path: "/tmp/test_payment_constants".to_string(),
|
||||
incremental_mode: true,
|
||||
file_size: None,
|
||||
keysize: None,
|
||||
reset: Some(true),
|
||||
};
|
||||
|
||||
let db = Arc::new(OurDB::new(db_config)?);
|
||||
let mut engine = Engine::new();
|
||||
register_biz_rhai_module(&mut engine, Arc::clone(&db));
|
||||
|
||||
// Test that we can access payment status constants
|
||||
let constants_script = r#"
|
||||
let payment = new_payment("pi_test", 1, "monthly", 100.0, 50.0, 150.0);
|
||||
|
||||
// Test status transitions
|
||||
payment = payment.status(PaymentStatusConstants::Pending);
|
||||
let is_pending = payment.is_pending();
|
||||
|
||||
payment = payment.status(PaymentStatusConstants::Completed);
|
||||
let is_completed = payment.is_completed();
|
||||
|
||||
payment = payment.status(PaymentStatusConstants::Failed);
|
||||
let has_failed = payment.has_failed();
|
||||
|
||||
payment = payment.status(PaymentStatusConstants::Refunded);
|
||||
let is_refunded = payment.is_refunded();
|
||||
|
||||
[is_pending, is_completed, has_failed, is_refunded]
|
||||
"#;
|
||||
|
||||
let results: Vec<bool> = engine.eval(constants_script)?;
|
||||
assert_eq!(results, vec![true, true, true, true]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_company_status_integration() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Test the integration between company and payment status
|
||||
let db_config = OurDBConfig {
|
||||
path: "/tmp/test_status_integration".to_string(),
|
||||
incremental_mode: true,
|
||||
file_size: None,
|
||||
keysize: None,
|
||||
reset: Some(true),
|
||||
};
|
||||
|
||||
let db = Arc::new(OurDB::new(db_config)?);
|
||||
let mut engine = Engine::new();
|
||||
register_biz_rhai_module(&mut engine, Arc::clone(&db));
|
||||
|
||||
let integration_script = r#"
|
||||
// Create company (defaults to PendingPayment)
|
||||
let company = new_company("Integration Test", "INT-001", 1704067200);
|
||||
company = set_company(company);
|
||||
|
||||
// Create payment
|
||||
let payment = new_payment("pi_int_test", company.id, "yearly", 500.0, 99.0, 1688.0);
|
||||
payment = set_payment(payment);
|
||||
|
||||
// Complete payment
|
||||
payment = payment.complete_payment("cus_int_test");
|
||||
payment = set_payment(payment);
|
||||
|
||||
// Update company to active
|
||||
company = company.status(CompanyStatusConstants::Active);
|
||||
company = set_company(company);
|
||||
|
||||
[payment.is_completed(), company.status]
|
||||
"#;
|
||||
|
||||
let results: Vec<rhai::Dynamic> = engine.eval(integration_script)?;
|
||||
|
||||
// Check that payment is completed
|
||||
assert!(results[0].as_bool().unwrap());
|
||||
|
||||
// Check that company status is Active (we can't directly compare enum in Rhai result)
|
||||
// So we'll verify by retrieving from database
|
||||
let companies: Vec<Company> = db.get_all()?;
|
||||
let company = companies
|
||||
.into_iter()
|
||||
.find(|c| c.name == "Integration Test")
|
||||
.unwrap();
|
||||
assert_eq!(company.status, CompanyStatus::Active);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -1,231 +0,0 @@
|
||||
use heromodels::db::postgres::Config;
|
||||
use heromodels::db::{Collection, Db};
|
||||
use heromodels::models::userexample::user::user_index::{is_active, username};
|
||||
use heromodels::models::{Comment, User};
|
||||
use heromodels_core::Model;
|
||||
|
||||
// Helper function to print user details
|
||||
fn print_user_details(user: &User) {
|
||||
println!("\n--- User Details ---");
|
||||
println!("ID: {}", user.get_id());
|
||||
println!("Username: {}", user.username);
|
||||
println!("Email: {}", user.email);
|
||||
println!("Full Name: {}", user.full_name);
|
||||
println!("Active: {}", user.is_active);
|
||||
println!("Created At: {}", user.base_data.created_at);
|
||||
println!("Modified At: {}", user.base_data.modified_at);
|
||||
println!("Comments: {:?}", user.base_data.comments);
|
||||
}
|
||||
|
||||
// Helper function to print comment details
|
||||
fn print_comment_details(comment: &Comment) {
|
||||
println!("\n--- Comment Details ---");
|
||||
println!("ID: {}", comment.get_id());
|
||||
println!("User ID: {}", comment.user_id);
|
||||
println!("Content: {}", comment.content);
|
||||
println!("Created At: {}", comment.base_data.created_at);
|
||||
println!("Modified At: {}", comment.base_data.modified_at);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let db = heromodels::db::postgres::Postgres::new(
|
||||
Config::new()
|
||||
.user(Some("postgres".into()))
|
||||
.password(Some("test123".into()))
|
||||
.host(Some("localhost".into()))
|
||||
.port(Some(5432)),
|
||||
)
|
||||
.expect("Can connect to postgress");
|
||||
|
||||
println!("Hero Models - Basic Usage Example");
|
||||
println!("================================");
|
||||
|
||||
// Create users with auto-generated IDs
|
||||
|
||||
// User 1
|
||||
let user1 = User::new()
|
||||
.username("johndoe")
|
||||
.email("john.doe@example.com")
|
||||
.full_name("John Doe")
|
||||
.is_active(false)
|
||||
.build();
|
||||
|
||||
// User 2
|
||||
let user2 = User::new()
|
||||
.username("janesmith")
|
||||
.email("jane.smith@example.com")
|
||||
.full_name("Jane Smith")
|
||||
.is_active(true)
|
||||
.build();
|
||||
|
||||
// User 3
|
||||
let user3 = User::new()
|
||||
.username("willism")
|
||||
.email("willis.masters@example.com")
|
||||
.full_name("Willis Masters")
|
||||
.is_active(true)
|
||||
.build();
|
||||
|
||||
// User 4
|
||||
let user4 = User::new()
|
||||
.username("carrols")
|
||||
.email("carrol.smith@example.com")
|
||||
.full_name("Carrol Smith")
|
||||
.is_active(false)
|
||||
.build();
|
||||
|
||||
// Save all users to database and get their assigned IDs and updated models
|
||||
let (user1_id, db_user1) = db
|
||||
.collection()
|
||||
.expect("can open user collection")
|
||||
.set(&user1)
|
||||
.expect("can set user");
|
||||
let (user2_id, db_user2) = db
|
||||
.collection()
|
||||
.expect("can open user collection")
|
||||
.set(&user2)
|
||||
.expect("can set user");
|
||||
let (user3_id, db_user3) = db
|
||||
.collection()
|
||||
.expect("can open user collection")
|
||||
.set(&user3)
|
||||
.expect("can set user");
|
||||
let (user4_id, db_user4) = db
|
||||
.collection()
|
||||
.expect("can open user collection")
|
||||
.set(&user4)
|
||||
.expect("can set user");
|
||||
|
||||
println!("User 1 assigned ID: {user1_id}");
|
||||
println!("User 2 assigned ID: {user2_id}");
|
||||
println!("User 3 assigned ID: {user3_id}");
|
||||
println!("User 4 assigned ID: {user4_id}");
|
||||
|
||||
// We already have the updated models from the set method, so we don't need to retrieve them again
|
||||
|
||||
// Print all users retrieved from database
|
||||
println!("\n--- Users Retrieved from Database ---");
|
||||
println!("\n1. First user:");
|
||||
print_user_details(&db_user1);
|
||||
|
||||
println!("\n2. Second user:");
|
||||
print_user_details(&db_user2);
|
||||
|
||||
println!("\n3. Third user:");
|
||||
print_user_details(&db_user3);
|
||||
|
||||
println!("\n4. Fourth user:");
|
||||
print_user_details(&db_user4);
|
||||
|
||||
// Demonstrate different ways to retrieve users from the database
|
||||
|
||||
// 1. Retrieve by username index
|
||||
println!("\n--- Retrieving Users by Different Methods ---");
|
||||
println!("\n1. By Username Index:");
|
||||
let stored_users = db
|
||||
.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.get::<username, _>("johndoe")
|
||||
.expect("can load stored user");
|
||||
|
||||
assert_eq!(stored_users.len(), 1);
|
||||
print_user_details(&stored_users[0]);
|
||||
|
||||
// 2. Retrieve by active status
|
||||
println!("\n2. By Active Status (Active = true):");
|
||||
let active_users = db
|
||||
.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.get::<is_active, _>(&true)
|
||||
.expect("can load stored users");
|
||||
|
||||
assert_eq!(active_users.len(), 2);
|
||||
for active_user in active_users.iter() {
|
||||
print_user_details(active_user);
|
||||
}
|
||||
|
||||
// 3. Delete a user and show the updated results
|
||||
println!("\n3. After Deleting a User:");
|
||||
let user_to_delete_id = active_users[0].get_id();
|
||||
println!("Deleting user with ID: {user_to_delete_id}");
|
||||
db.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.delete_by_id(user_to_delete_id)
|
||||
.expect("can delete existing user");
|
||||
|
||||
// Show remaining active users
|
||||
let active_users = db
|
||||
.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.get::<is_active, _>(&true)
|
||||
.expect("can load stored users");
|
||||
|
||||
println!(" a. Remaining Active Users:");
|
||||
assert_eq!(active_users.len(), 1);
|
||||
for active_user in active_users.iter() {
|
||||
print_user_details(active_user);
|
||||
}
|
||||
|
||||
// Show inactive users
|
||||
let inactive_users = db
|
||||
.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.get::<is_active, _>(&false)
|
||||
.expect("can load stored users");
|
||||
|
||||
println!(" b. Inactive Users:");
|
||||
assert_eq!(inactive_users.len(), 2);
|
||||
for inactive_user in inactive_users.iter() {
|
||||
print_user_details(inactive_user);
|
||||
}
|
||||
|
||||
// Delete a user based on an index for good measure
|
||||
db.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.delete::<username, _>("janesmith")
|
||||
.expect("can delete existing user");
|
||||
|
||||
println!("\n--- User Model Information ---");
|
||||
println!("User DB Prefix: {}", User::db_prefix());
|
||||
|
||||
// Demonstrate comment creation and association with a user
|
||||
println!("\n--- Working with Comments ---");
|
||||
|
||||
// 1. Create and save a comment
|
||||
println!("\n1. Creating a Comment:");
|
||||
let comment = Comment::new()
|
||||
.user_id(db_user1.get_id()) // commenter's user ID
|
||||
.content("This is a comment on the user")
|
||||
.build();
|
||||
|
||||
// Save the comment and get its assigned ID and updated model
|
||||
let (comment_id, db_comment) = db
|
||||
.collection()
|
||||
.expect("can open comment collection")
|
||||
.set(&comment)
|
||||
.expect("can set comment");
|
||||
|
||||
println!("Comment assigned ID: {comment_id}");
|
||||
|
||||
println!(" a. Comment Retrieved from Database:");
|
||||
print_comment_details(&db_comment);
|
||||
|
||||
// 3. Associate the comment with a user
|
||||
println!("\n2. Associating Comment with User:");
|
||||
let mut updated_user = db_user1.clone();
|
||||
updated_user.base_data.add_comment(db_comment.get_id());
|
||||
|
||||
// Save the updated user and get the new version
|
||||
let (_, user_with_comment) = db
|
||||
.collection::<User>()
|
||||
.expect("can open user collection")
|
||||
.set(&updated_user)
|
||||
.expect("can set updated user");
|
||||
|
||||
println!(" a. User with Associated Comment:");
|
||||
print_user_details(&user_with_comment);
|
||||
|
||||
println!("\n--- Model Information ---");
|
||||
println!("User DB Prefix: {}", User::db_prefix());
|
||||
println!("Comment DB Prefix: {}", Comment::db_prefix());
|
||||
}
|
298
rhai_client_example/Cargo.lock
generated
298
rhai_client_example/Cargo.lock
generated
@ -1,298 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"const-random",
|
||||
"getrandom 0.3.3",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "const-random"
|
||||
version = "0.1.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
|
||||
dependencies = [
|
||||
"const-random-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-random-macro"
|
||||
version = "0.1.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
|
||||
dependencies = [
|
||||
"getrandom 0.2.16",
|
||||
"once_cell",
|
||||
"tiny-keccak",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi 0.11.0+wasi-snapshot-preview1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasi 0.14.2+wasi-0.2.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instant"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.172"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.95"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
|
||||
|
||||
[[package]]
|
||||
name = "rhai"
|
||||
version = "1.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce4d759a4729a655ddfdbb3ff6e77fb9eadd902dae12319455557796e435d2a6"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bitflags",
|
||||
"instant",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"rhai_codegen",
|
||||
"smallvec",
|
||||
"smartstring",
|
||||
"thin-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhai_client_example"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rhai",
|
||||
"rhai_client_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhai_client_macros"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rhai",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhai_codegen"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5a11a05ee1ce44058fa3d5961d05194fdbe3ad6b40f904af764d81b86450e6b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9"
|
||||
|
||||
[[package]]
|
||||
name = "smartstring"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3fb72c633efbaa2dd666986505016c32c3044395ceaf881518399d2f4127ee29"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"static_assertions",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "static_assertions"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.101"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thin-vec"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "144f754d318415ac792f9d69fc87abbbfc043ce2ef041c60f16ad828f638717d"
|
||||
|
||||
[[package]]
|
||||
name = "tiny-keccak"
|
||||
version = "2.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
|
||||
dependencies = [
|
||||
"crunchy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.0+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.14.2+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
|
||||
dependencies = [
|
||||
"wit-bindgen-rt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rt"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
@ -1,8 +0,0 @@
|
||||
[package]
|
||||
name = "rhai_client_example"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
rhai = "1.21.0"
|
||||
rhai_client_macros = { path = "../rhai_client_macros" }
|
@ -1,62 +0,0 @@
|
||||
use rhai::Engine;
|
||||
use rhai_client_macros::rhai;
|
||||
|
||||
// Define a Rust function with the #[rhai] attribute
|
||||
#[rhai]
|
||||
fn hello(name: String) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
// Define another function with multiple parameters
|
||||
#[rhai]
|
||||
fn add(a: i32, b: i32) -> i32 {
|
||||
a + b
|
||||
}
|
||||
|
||||
// Define a function with different parameter types
|
||||
#[rhai]
|
||||
fn format_person(name: String, age: i32, is_student: bool) -> String {
|
||||
let student_status = if is_student { "is" } else { "is not" };
|
||||
format!("{} is {} years old and {} a student.", name, age, student_status)
|
||||
}
|
||||
|
||||
// Define adapter functions for Rhai that handle i64 to i32 conversion
|
||||
fn add_rhai(a: i64, b: i64) -> i64 {
|
||||
add(a as i32, b as i32) as i64
|
||||
}
|
||||
|
||||
fn format_person_rhai(name: String, age: i64, is_student: bool) -> String {
|
||||
format_person(name, age as i32, is_student)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Create a Rhai engine
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Register our functions with the Rhai engine
|
||||
// Note: Rhai uses i64 for integers by default
|
||||
engine.register_fn("hello", hello);
|
||||
engine.register_fn("add", add_rhai);
|
||||
engine.register_fn("format_person", format_person_rhai);
|
||||
|
||||
println!("=== Calling Rust functions directly ===");
|
||||
println!("{}", hello("World".to_string()));
|
||||
println!("{}", add(5, 10));
|
||||
println!("{}", format_person("Alice".to_string(), 25, true));
|
||||
|
||||
println!("\n=== Calling functions through Rhai engine ===");
|
||||
let result1: String = engine.eval("hello(\"Rhai World\")").unwrap();
|
||||
println!("{}", result1);
|
||||
|
||||
let result2: i64 = engine.eval("add(20, 30)").unwrap();
|
||||
println!("{}", result2);
|
||||
|
||||
let result3: String = engine.eval("format_person(\"Bob\", 30, false)").unwrap();
|
||||
println!("{}", result3);
|
||||
|
||||
println!("\n=== Calling functions through generated Rhai client functions ===");
|
||||
// Use the generated client functions
|
||||
println!("{}", hello_rhai_client(&engine, "Client World".to_string()));
|
||||
println!("{}", add_rhai_client(&engine, 100, 200));
|
||||
println!("{}", format_person_rhai_client(&engine, "Charlie".to_string(), 35, true));
|
||||
}
|
Loading…
Reference in New Issue
Block a user