use rust_eloquent::{Eloquent, sqlx::FromRow, EloquentModel};
use rust_eloquent::schema::Schema;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserPreferences {
pub theme: String,
pub notifications_enabled: bool,
}
#[derive(Debug, Clone, FromRow, rust_eloquent::Eloquent)]
#[eloquent(table = "users_with_json")]
pub struct User {
pub id: i32,
pub name: String,
#[eloquent(json)]
pub preferences: rust_eloquent::Json<UserPreferences>,
}
#[tokio::main]
async fn main() -> Result<(), rust_eloquent::sqlx::Error> {
let _ = std::fs::remove_file("json_casting.db");
std::fs::File::create("json_casting.db").unwrap();
Eloquent::init("sqlite://json_casting.db").await?;
Schema::create("users_with_json", |table| {
table.id();
table.string("name").not_null();
table.string("preferences").not_null(); }).await?;
let mut user = User {
id: 0,
name: "Louis".to_string(),
preferences: rust_eloquent::Json(UserPreferences {
theme: "dark".to_string(),
notifications_enabled: true,
}),
};
user.save().await?;
println!("Saved User with ID: {}", user.id);
let fetched_user = User::query().where_eq("id", user.id).first().await?.unwrap();
println!("Fetched User Preferences Theme: {}", fetched_user.preferences.theme);
println!("Fetched User Notifications Enabled: {}", fetched_user.preferences.notifications_enabled);
let mut to_update = fetched_user;
to_update.preferences.theme = "light".to_string();
to_update.save().await?;
let updated_user = User::query().where_eq("id", to_update.id).first().await?.unwrap();
println!("Updated User Preferences Theme: {}", updated_user.preferences.theme);
Ok(())
}