use microrm::prelude::*; use test_log::test; mod common; struct CR; impl Relation for CR { type Domain = Customer; type Range = Receipt; const NAME: &'static str = "CR"; } #[derive(Entity)] struct Customer { name: String, receipts: microrm::RelationDomain, } #[derive(Entity)] struct Receipt { value: usize, customers: microrm::RelationRange, } #[derive(Default, Schema)] struct ReceiptDB { customers: microrm::IDMap, receipts: microrm::IDMap, } #[test] fn check_schema_creation() { let (_pool, _db): (_, ReceiptDB) = common::open_test_db!(); } #[test] fn simple_operations() { let (pool, db): (_, ReceiptDB) = common::open_test_db!(); let mut lease = pool.acquire().unwrap(); let ca = db .customers .insert( &mut lease, Customer { name: "customer A".to_string(), receipts: Default::default(), }, ) .expect("couldn't insert customer record"); let ra = db .receipts .insert( &mut lease, Receipt { value: 32usize, customers: Default::default(), }, ) .expect("couldn't insert receipt record"); let rb = db .receipts .insert( &mut lease, Receipt { value: 64usize, customers: Default::default(), }, ) .expect("couldn't insert receipt record"); let e_ca = db .customers .by_id(&mut lease, ca) .expect("couldn't retrieve customer record") .expect("no customer record"); log::trace!( "connecting customer a (ID {:?}) to receipt a (ID {:?})", ca, ra ); e_ca.receipts .connect_to(&mut lease, ra) .expect("couldn't relationiate customer with receipt a"); log::trace!( "connecting customer a (ID {:?}) to receipt b (ID {:?})", ca, rb ); e_ca.receipts .connect_to(&mut lease, rb) .expect("couldn't relationiate customer with receipt b"); log::trace!("connected!"); // technically this can fail if sqlite gives ra and rb back in the opposite order, which is // valid behaviour assert_eq!( e_ca.receipts .get(&mut lease) .expect("couldn't get receipts related with customer") .into_iter() .map(|x| x.id()) .collect::>(), vec![ra, rb] ); // check that the reverse direction was also added let e_ra = db .receipts .by_id(&mut lease, ra) .expect("couldn't retreieve receipt record") .expect("no receipt record"); assert_eq!( e_ra.customers .get(&mut lease) .expect("couldn't get related customers") .into_iter() .map(|x| x.id()) .collect::>(), vec![ca] ); }