Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added get_subquery() and add_imported_fields, fixed soft-delete and join demos #31

Merged
merged 5 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ async fn test_abc() {
async fn main() -> Result<()> {
create_bootstrap_db().await?;

panic!("oho");
println!("In this example, we will be interracting with the records and testing conditions");
let products = Product::table();

Expand All @@ -38,18 +37,40 @@ async fn main() -> Result<()> {

println!("");
println!("Adding a single new product");
let id = products
let nuclear_sandwich_id = products
.insert(Product {
name: "Nuclear Sandwich".to_string(),
calories: 100,
bakery_id: 1,
price: 110,
})
.await?;
.await?
.unwrap();

println!(
"After adding \"Nuclear Sandwich\" (id={}) we are left with {} products",
id.unwrap(),
&nuclear_sandwich_id,
products.count().get_one_untyped().await?
);

// So far we didn't know about the soft delete field, but lets add it now
let product_sd = products
.clone()
.with_extension(SoftDelete::new("is_deleted"));

// Next we are going to delete a nuclear sandwitch with "sd"
product_sd
.clone()
.with_id(nuclear_sandwich_id)
.delete()
.await?;

println!(
"After soft-deleting \"Nuclear Sandwich\" we are left with {} SD (soft delete) products",
product_sd.count().get_one_untyped().await?
);
println!(
"However as per our old set (no SD) we still have {} products",
products.count().get_one_untyped().await?
);

Expand Down
74 changes: 74 additions & 0 deletions bakery_model/examples/2-joined-tables.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use anyhow::Result;
use dorm::{dataset::WritableDataSet, prelude::*};

use bakery_model::*;
use serde::{Deserialize, Serialize};

async fn create_bootstrap_db() -> Result<()> {
// Connect to postgress and store client statically
bakery_model::connect_postgres().await?;

// Get the postgres client for batch execution
let dorm_client = bakery_model::postgres();
let client = dorm_client.client();

// Read the schema from the file and execute it
let schema = tokio::fs::read_to_string("bakery_model/schema-pg.sql").await?;
client.batch_execute(&schema).await?;

Ok(())
}

#[tokio::test]
async fn test_abc() {
panic!("aoeu");
}

#[tokio::main]
async fn main() -> Result<()> {
create_bootstrap_db().await?;

println!("In this example, we will interract with 'product' and 'inventory' tables, which are joinable");

let products = Product::table();
for rec in products.get().await? {
println!("{:?}", rec);
}

// Inventory does not have a table, so we will just create one
#[derive(Clone, Serialize, Deserialize, Debug)]
struct Inventory {
stock: i64,
}
impl Entity for Inventory {}
let inventory: Table<Postgres, Inventory> = Table::new_with_entity("inventory", postgres())
.with_id_field("product_id")
.with_field("stock");

for rec in inventory.get().await? {
println!("{:?}", rec);
}

println!(
"Records are separate now and do not make any sense! But lets create a new joined table"
);

#[derive(Clone, Serialize, Deserialize, Debug)]
struct ProductInventory {
name: String,
calories: i64,
price: i64,
i_stock: i64,
}
impl Entity for ProductInventory {}

let product_inventory = products
.clone()
.with_join::<ProductInventory, _>(inventory.clone(), "id");

for rec in product_inventory.get().await? {
println!("{:?}", rec);
}

Ok(())
}
5 changes: 3 additions & 2 deletions bakery_model/examples/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::anyhow;
use anyhow::Result;
use dorm::{dataset::WritableDataSet, prelude::*};

Expand Down Expand Up @@ -108,7 +109,7 @@ async fn main() -> Result<()> {
for row in orders.get().await.unwrap().into_iter() {
println!(
"id: {}, client: {} (id: {}) total(calculated): {}",
row.id, row.client, row.client_id, row.total
row.id, row.client_name, row.client_id, row.total
);
}
}
Expand All @@ -124,7 +125,7 @@ async fn main() -> Result<()> {
let row: Order = serde_json::from_value(row_untyped)?;
println!(
"id: {}, client: {:<13} (id: {}) total: {}",
row.id, row.client, row.client_id, row.total
row.id, row.client_name, row.client_id, row.total
);
}

Expand Down
3 changes: 2 additions & 1 deletion bakery_model/schema-pg.sql
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ CREATE TABLE product (
name varchar(255) NOT NULL,
calories int NOT NULL,
bakery_id int NOT NULL,
price int NOT NULL
price int NOT NULL,
is_deleted boolean DEFAULT false
);

-- Insert data into tables
Expand Down
18 changes: 8 additions & 10 deletions bakery_model/src/bakery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ impl Bakery {
.with_id_field("id")
.with_field("name")
.with_field("profit_margin")
.has_many("clients", "bakery_id", || Box::new(Client::table()))
.has_many("products", "bakery_id", || Box::new(Product::table()))
.with_many("clients", "bakery_id", || Box::new(Client::table()))
.with_many("products", "bakery_id", || Box::new(Product::table()))
})
}
pub fn table() -> Table<Postgres, Bakery> {
Expand All @@ -29,10 +29,6 @@ impl Bakery {
}

pub trait BakeryTable: AnyTable {
fn as_table(&self) -> &Table<Postgres, Bakery> {
self.as_any_ref().downcast_ref().unwrap()
}

// fields
fn id(&self) -> Arc<Field> {
self.get_field("id").unwrap()
Expand All @@ -44,12 +40,14 @@ pub trait BakeryTable: AnyTable {
self.get_field("profit_margin").unwrap()
}

// references
fn ref_clients(&self) -> Table<Postgres, Client>;
fn ref_products(&self) -> Table<Postgres, Product>;
}
impl BakeryTable for Table<Postgres, Bakery> {
fn ref_clients(&self) -> Table<Postgres, Client> {
self.as_table().get_ref_as("clients").unwrap()
self.get_ref_as("clients").unwrap()
}
fn ref_products(&self) -> Table<Postgres, Product> {
self.as_table().get_ref_as("products").unwrap()
self.get_ref_as("products").unwrap()
}
}
impl BakeryTable for Table<Postgres, Bakery> {}
29 changes: 0 additions & 29 deletions bakery_model/src/cakes_bakers.rs

This file was deleted.

28 changes: 8 additions & 20 deletions bakery_model/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,8 @@ impl Client {
.with_field("name")
.with_field("contact_details")
.with_field("bakery_id")
.has_one("bakery", "bakery_id", || Box::new(Bakery::table()))
.has_many("orders", "client_id", || Box::new(Order::table()))
// .has_many("baked_cakes", "baker_id", || {
// // add baker_id field into Cake through a left join
// CakeSet::new().with_join(
// Table::new("cakes_bakers", postgres())
// .with_id_field("cake_id")
// .with_field("baker_id"),
// "id",
// )
// })
.with_one("bakery", "bakery_id", || Box::new(Bakery::table()))
.with_many("orders", "client_id", || Box::new(Order::table()))
})
}
pub fn table() -> Table<Postgres, Client> {
Expand All @@ -41,9 +32,6 @@ impl Client {
}

pub trait ClientTable: AnyTable {
fn as_table(&self) -> &Table<Postgres, Client> {
self.as_any_ref().downcast_ref().unwrap()
}
fn name(&self) -> Arc<Field> {
self.get_field("name").unwrap()
}
Expand All @@ -54,14 +42,14 @@ pub trait ClientTable: AnyTable {
self.get_field("bakery_id").unwrap()
}

fn ref_bakery(&self) -> Table<Postgres, Bakery>;
fn ref_orders(&self) -> Table<Postgres, Order>;
}
impl ClientTable for Table<Postgres, Client> {
fn ref_bakery(&self) -> Table<Postgres, Bakery> {
self.as_table().get_ref_as("bakery").unwrap()
self.get_ref_as("bakery").unwrap()
}
fn ref_orders(&self) -> Table<Postgres, Order> {
self.as_table().get_ref_as("orders").unwrap()
self.get_ref_as("orders").unwrap()
}
// fn ref_cakes(&self) -> Table<Postgres, Cake> {
// self.as_table().get_ref_as("cakes").unwrap()
// }
}
impl ClientTable for Table<Postgres, Client> {}
38 changes: 0 additions & 38 deletions bakery_model/src/customer.rs

This file was deleted.

4 changes: 2 additions & 2 deletions bakery_model/src/lineitem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ impl LineItem {
product.add_condition(product.id().eq(&t.product_id()));
product.field_query(product.price()).render_chunk()
})
.has_one("order", "order_id", || Box::new(Order::table()))
.has_one("product", "product_id", || Box::new(Product::table()))
.with_one("order", "order_id", || Box::new(Order::table()))
.with_one("product", "product_id", || Box::new(Product::table()))
})
}
pub fn table() -> Table<Postgres, LineItem> {
Expand Down
25 changes: 7 additions & 18 deletions bakery_model/src/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ use serde::{Deserialize, Serialize};

use crate::{
lineitem::{LineItem, LineItemTable},
postgres, Client, ClientTable,
postgres, Client,
};

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
pub struct Order {
pub id: i64,
pub client_id: i64,
pub client: String,
pub client_name: String,
pub total: i64,
}
impl Entity for Order {}
Expand All @@ -26,20 +26,13 @@ impl Order {
.with_id_field("id")
.with_field("client_id")
.with_extension(SoftDelete::new("is_deleted"))
.with_one("client", "client_id", || Box::new(Client::table()))
.with_many("line_items", "order_id", || Box::new(LineItem::table()))
.with_expression("total", |t| {
let mut item = LineItem::table();
item.add_condition(item.order_id().eq(&t.id()));
item.get_empty_query()
.with_column_arc("total".to_string(), Arc::new(item.total()))
.render_chunk()
let item = t.get_subquery_as::<LineItem>("line_items").unwrap();
item.sum(item.total()).render_chunk()
})
.with_expression("client", |t| {
let mut client = Client::table();
client.add_condition(client.id().eq(&t.client_id()));
client.field_query(client.name()).render_chunk()
})
.has_one("client", "client_id", || Box::new(Client::table()))
.has_many("line_items", "order_id", || Box::new(LineItem::table()))
.with_imported_fields("client", &["name"])
})
}
pub fn table() -> Table<Postgres, Order> {
Expand All @@ -48,10 +41,6 @@ impl Order {
}

pub trait OrderTable: AnyTable {
// fn as_table(&self) -> &Table<Postgres, Order> {
// self.as_any_ref().downcast_ref().unwrap()
// }

fn client_id(&self) -> Arc<Field> {
Order::table().get_field("client_id").unwrap()
}
Expand Down
Loading
Loading