├── .gitignore ├── CODE_OF_CONDUCT.md ├── .github ├── ISSUE_TEMPLATE │ ├── question.md │ ├── feature_request.md │ └── bug_report.md └── FUNDING.yml ├── .cargo-husky └── hooks │ └── pre-commit ├── Makefile ├── src ├── types │ ├── mod.rs │ ├── error.rs │ ├── response.rs │ ├── http.rs │ └── query.rs ├── lib.rs ├── client.rs └── http.rs ├── examples ├── async_deal_with_error_entity.rs ├── async_tx_log.rs ├── evict.rs ├── deal_with_errors_entity_tx.rs ├── entity_tx.rs ├── async_tx_logs.rs ├── tx_log.rs ├── tx_logs.rs ├── match_no_continue_tx.rs ├── async_entity_tx_timed.rs ├── complex_query.rs ├── match_continue_tx.rs ├── async_query.rs ├── limit_offset_query.rs ├── async_entity_timed.rs ├── entity.rs ├── entity_history.rs ├── simple_query.rs └── async_entity_history_timed.rs ├── .circleci └── config.yml ├── Cargo.toml ├── LICENSE ├── tests └── lib.rs └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | datomic-pro-*.jar 4 | .DS_Store -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Same as the Rust Code of Conduct 2 | 3 | The Code of Conduct for this repository [can be found online](https://www.rust-lang.org/conduct.html). -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: 'Any other topic different than bug or feature report. ' 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | 2 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 3 | patreon: naomijub 4 | custom: ["https://github.com/sponsors/naomijub", "https://patreon.com/naomijub"] 5 | -------------------------------------------------------------------------------- /.cargo-husky/hooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cargo fmt -- --check 4 | 5 | exit_code=$? 6 | 7 | if [ $exit_code == "1" ]; then 8 | echo "There was a problem formatting, to fix run \`cargo fmt\`" 9 | exit 1 10 | fi 11 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | crux: 2 | docker run -d -p 3000:3000 --name CruxDB juxt/crux-standalone:20.09-1.11.0 3 | 4 | int: 5 | cargo test --test lib --no-fail-fast --features "mock" 6 | 7 | unit: 8 | cargo test --locked --no-fail-fast --lib 9 | 10 | examples-sync: 11 | cargo test --examples 12 | 13 | examples-async: 14 | cargo test --examples --features "async" 15 | 16 | test: unit int examples-sync examples-async -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem or issue? Please describe or annex.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | ** Purpose the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | 29 | **Additional context** 30 | Add any other context about the problem here. 31 | -------------------------------------------------------------------------------- /src/types/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod error; 2 | pub mod http; 3 | pub mod query; 4 | pub mod response; 5 | 6 | use edn_rs::{Deserialize, Edn, EdnError, Serialize}; 7 | 8 | /// Id to use as reference in Crux, similar to `ids` with `Uuid`. This id is supposed to be a KEYWORD, `Edn::Key`. 9 | #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)] 10 | pub struct CruxId(String); 11 | 12 | impl Serialize for CruxId { 13 | fn serialize(mut self) -> String { 14 | self.0.insert(0, ':'); 15 | 16 | format!("{}", self.0.replace(" ", "-")) 17 | } 18 | } 19 | 20 | impl Deserialize for CruxId { 21 | fn deserialize(edn: &Edn) -> Result { 22 | match edn { 23 | Edn::Key(k) => Ok(Self::new(k)), 24 | Edn::Str(s) => Ok(Self::new(s)), 25 | _ => Err(EdnError::Deserialize(format!( 26 | "couldn't convert {} into CruxId", 27 | edn 28 | ))), 29 | } 30 | } 31 | } 32 | 33 | impl CruxId { 34 | /// `CruxId::new` receives a regular string and parses it to the `Edn::Key` format. 35 | /// `CruxId::new("Jorge da Silva") -> Edn::Key(":Jorge-da-Silva")` 36 | pub fn new(id: &str) -> Self { 37 | let clean_id = id.replace(":", ""); 38 | Self { 39 | 0: clean_id.to_string(), 40 | } 41 | } 42 | } 43 | 44 | pub use http::{Actions, Order}; 45 | -------------------------------------------------------------------------------- /examples/async_deal_with_error_entity.rs: -------------------------------------------------------------------------------- 1 | use chrono::prelude::*; 2 | use transistor::client::Crux; 3 | use transistor::types::error::CruxError; 4 | use transistor::types::CruxId; 5 | 6 | async fn entity_timed() -> Result { 7 | let client = Crux::new("localhost", "3000").http_client(); 8 | let timed = "2014-11-28T21:00:09-09:00" 9 | .parse::>() 10 | .unwrap(); 11 | 12 | let edn_body = client 13 | .entity_timed(CruxId::new("unknown-id"), None, Some(timed)) 14 | .await; 15 | 16 | return edn_body; 17 | } 18 | 19 | #[tokio::main] 20 | async fn main() { 21 | let edn_body = entity_timed().await; 22 | 23 | println!("\n Edn Body = {:#?}", edn_body); 24 | // Edn Body = Err( 25 | // BadResponse( 26 | // "entity responded with 404 for id \":unknown-id\" ", 27 | // ), 28 | // ) 29 | } 30 | 31 | #[tokio::test] 32 | async fn test_entity_timed() { 33 | let entity = entity_timed().await; 34 | 35 | match entity { 36 | Ok(_) => assert!(false), 37 | Err(e) => assert_eq!( 38 | format!("{:?}", e), 39 | format!( 40 | "{:?}", 41 | CruxError::BadResponse( 42 | "entity responded with 404 for id \":unknown-id\" ".to_string() 43 | ) 44 | ) 45 | ), 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /examples/async_tx_log.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::response::TxLogResponse; 4 | use transistor::types::Actions; 5 | use transistor::types::CruxId; 6 | 7 | async fn tx_log() -> TxLogResponse { 8 | let person1 = Person { 9 | crux__db___id: CruxId::new("jorge-3"), 10 | first_name: "Michael".to_string(), 11 | last_name: "Jorge".to_string(), 12 | }; 13 | 14 | let person2 = Person { 15 | crux__db___id: CruxId::new("manuel-1"), 16 | first_name: "Diego".to_string(), 17 | last_name: "Manuel".to_string(), 18 | }; 19 | 20 | let actions = Actions::new().append_put(person1).append_put(person2); 21 | 22 | let body = Crux::new("localhost", "3000") 23 | .http_client() 24 | .tx_log(actions) 25 | .await 26 | .unwrap(); 27 | 28 | return body; 29 | } 30 | 31 | #[tokio::main] 32 | async fn main() { 33 | let tx_log = tx_log().await; 34 | println!("body = {:?}", tx_log); 35 | // Body = "{:crux.tx/tx-id 7, :crux.tx/tx-time #inst \"2020-07-16T21:50:39.309-00:00\"}" 36 | } 37 | 38 | #[tokio::test] 39 | async fn test_tx_log() { 40 | let tx_log = tx_log().await; 41 | assert!(tx_log.tx___tx_id > 0); 42 | } 43 | 44 | #[derive(Debug, Clone, Serialize)] 45 | #[allow(non_snake_case)] 46 | pub struct Person { 47 | crux__db___id: CruxId, 48 | first_name: String, 49 | last_name: String, 50 | } 51 | -------------------------------------------------------------------------------- /examples/evict.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::response::TxLogResponse; 4 | use transistor::types::Actions; 5 | use transistor::types::CruxId; 6 | 7 | #[cfg(not(feature = "async"))] 8 | fn evict() -> TxLogResponse { 9 | let person = Person { 10 | crux__db___id: CruxId::new("hello-evict"), 11 | first_name: "Hello".to_string(), 12 | last_name: "World".to_string(), 13 | }; 14 | // { :crux.db/id :hello-evict, :first-name \"Hello\", :last-name \"World\", } 15 | 16 | let client = Crux::new("localhost", "3000").http_client(); 17 | 18 | let actions = Actions::new().append_put(person.clone()); 19 | // [[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }]]" 20 | 21 | let _ = client.tx_log(actions).unwrap(); 22 | // {:crux.tx/tx-id 7, :crux.tx/tx-time #inst \"2020-07-16T21:50:39.309-00:00\"} 23 | 24 | let actions = Actions::new().append_evict(person.crux__db___id); 25 | let evict_body = client.tx_log(actions).unwrap(); 26 | return evict_body; 27 | } 28 | 29 | #[cfg(not(feature = "async"))] 30 | fn main() { 31 | let evict_body = evict(); 32 | println!("\n Evict Body = {:?}", evict_body); 33 | } 34 | 35 | #[test] 36 | #[cfg(not(feature = "async"))] 37 | fn test_evict() { 38 | let evict = evict(); 39 | assert!(evict.tx___tx_id > 0); 40 | } 41 | 42 | #[derive(Debug, Clone, Serialize)] 43 | #[allow(non_snake_case)] 44 | pub struct Person { 45 | crux__db___id: CruxId, 46 | first_name: String, 47 | last_name: String, 48 | } 49 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | jobs: 4 | lint: 5 | docker: 6 | - image: rust 7 | steps: 8 | - checkout 9 | - run: 10 | name: Install cargo fmt 11 | command: rustup component add rustfmt 12 | - run: 13 | name: Run lint 14 | command: cargo fmt -- --check 15 | 16 | clippy: 17 | docker: 18 | - image: rust 19 | steps: 20 | - checkout 21 | - run: 22 | name: Install cargo clippy 23 | command: rustup component add clippy 24 | - run: 25 | name: Run Clippy 26 | command: cargo clippy -- -W clippy::pedantic 27 | build: 28 | parameters: 29 | toolchain: 30 | description: rust toolchain 31 | type: string 32 | 33 | docker: 34 | - image: buildpack-deps:trusty 35 | - image: juxt/crux-standalone:20.09-1.11.0 36 | 37 | steps: 38 | - checkout 39 | - run: > 40 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | 41 | sh -s -- -v -y --profile minimal --default-toolchain <> 42 | - run: $HOME/.cargo/bin/cargo build 43 | - run: $HOME/.cargo/bin/cargo test --examples 44 | - run: $HOME/.cargo/bin/cargo test --examples --features "async" 45 | - run: $HOME/.cargo/bin/cargo test --locked --no-fail-fast --lib 46 | - run: $HOME/.cargo/bin/cargo test --test lib --no-fail-fast --features "mock" 47 | 48 | workflows: 49 | version: 2.1 50 | 51 | build_and_test: 52 | jobs: 53 | - lint 54 | - clippy 55 | - build: 56 | matrix: 57 | parameters: 58 | toolchain: ["stable", "beta", "nightly"] 59 | -------------------------------------------------------------------------------- /examples/deal_with_errors_entity_tx.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::error::CruxError; 4 | use transistor::types::response::EntityTxResponse; 5 | use transistor::types::CruxId; 6 | 7 | #[cfg(not(feature = "async"))] 8 | fn entity_tx() -> Result { 9 | let person = Person { 10 | crux__db___id: CruxId::new("error-id"), 11 | first_name: "Hello".to_string(), 12 | last_name: "World".to_string(), 13 | }; 14 | // { :crux.db/id :hello-entity, :first-name \"Hello\", :last-name \"World\", } 15 | 16 | let client = Crux::new("localhost", "3000").http_client(); 17 | 18 | let tx_body = client.entity_tx(person.crux__db___id); 19 | return tx_body; 20 | } 21 | 22 | #[cfg(not(feature = "async"))] 23 | fn main() { 24 | let entity_tx = entity_tx(); 25 | println!("Tx Body = {:#?}", entity_tx); 26 | // Tx Body = Err( 27 | // BadResponse( 28 | // "entity-tx responded with 404 for id :error-id", 29 | // ), 30 | // ) 31 | } 32 | 33 | #[test] 34 | #[cfg(not(feature = "async"))] 35 | fn test_entity_tx() { 36 | let entity_tx = entity_tx(); 37 | 38 | match entity_tx { 39 | Ok(_) => assert!(false), 40 | Err(e) => assert_eq!( 41 | format!("{:?}", e), 42 | format!( 43 | "{:?}", 44 | CruxError::BadResponse( 45 | "entity-tx responded with 404 for id \":error-id\" ".to_string() 46 | ) 47 | ) 48 | ), 49 | } 50 | } 51 | 52 | #[derive(Debug, Clone, Serialize)] 53 | #[allow(non_snake_case)] 54 | pub struct Person { 55 | crux__db___id: CruxId, 56 | first_name: String, 57 | last_name: String, 58 | } 59 | -------------------------------------------------------------------------------- /examples/entity_tx.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::response::EntityTxResponse; 4 | use transistor::types::Actions; 5 | use transistor::types::CruxId; 6 | 7 | #[cfg(not(feature = "async"))] 8 | fn entity_tx() -> EntityTxResponse { 9 | let person = Person { 10 | crux__db___id: CruxId::new("hello-entity"), 11 | first_name: "Hello".to_string(), 12 | last_name: "World".to_string(), 13 | }; 14 | // { :crux.db/id :hello-entity, :first-name \"Hello\", :last-name \"World\", } 15 | 16 | let client = Crux::new("localhost", "3000").http_client(); 17 | let put_person = Actions::new().append_put(person.clone()); 18 | 19 | let _ = client.tx_log(put_person).unwrap(); 20 | // {:crux.tx/tx-id 7, :crux.tx/tx-time #inst \"2020-07-16T21:50:39.309-00:00\"} 21 | 22 | let tx_body = client.entity_tx(person.crux__db___id).unwrap(); 23 | return tx_body; 24 | } 25 | 26 | #[cfg(not(feature = "async"))] 27 | fn main() { 28 | let entity_tx = entity_tx(); 29 | println!("Tx Body = {:#?}", entity_tx); 30 | // Tx Body = EntityTxResponse { 31 | // db___id: "d72ccae848ce3a371bd313865cedc3d20b1478ca", 32 | // db___content_hash: "1828ebf4466f98ea3f5252a58734208cd0414376", 33 | // db___valid_time: "2020-07-20T20:38:27.515-00:00", 34 | // tx___tx_id: 31, 35 | // tx___tx_time: "2020-07-20T20:38:27.515-00:00", 36 | // } 37 | } 38 | 39 | #[test] 40 | #[cfg(not(feature = "async"))] 41 | fn test_entity_tx() { 42 | let entity_tx = entity_tx(); 43 | 44 | assert!(entity_tx.tx___tx_id > 0); 45 | } 46 | 47 | #[derive(Debug, Clone, Serialize)] 48 | #[allow(non_snake_case)] 49 | pub struct Person { 50 | crux__db___id: CruxId, 51 | first_name: String, 52 | last_name: String, 53 | } 54 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "transistor" 3 | version = "2.1.2" 4 | authors = ["Julia Naomi ", "Otavio Pace "] 5 | description = "Crux Datalog DB Client" 6 | readme = "README.md" 7 | documentation = "https://docs.rs/transistor/" 8 | repository = "https://github.com/naomijub/transistor" 9 | keywords = ["CRUX", "Client", "EDN", "Database", "Datalog"] 10 | license = "LGPL-3.0" 11 | edition = "2018" 12 | 13 | [features] 14 | mock = ["mockito"] 15 | time_as_str = [] 16 | async = ["tokio", "futures"] 17 | 18 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 19 | 20 | [dependencies] 21 | reqwest = { version = "0.10.6", features = ["blocking"] } 22 | edn-rs = { version = "0.16.11", features = ["async"]} 23 | edn-derive = "0.5.0" 24 | mockito = {version = "0.26", optional = true } 25 | chrono = "0.4" 26 | futures = {version = "0.3.5", optional = true } 27 | tokio = {version = "0.2.22", optional = true, features = ["macros"] } 28 | 29 | [dev-dependencies] 30 | mockito = "0.26" 31 | trybuild = { version = "1.0", features = ["diff"] } 32 | criterion = "0.3" 33 | 34 | [dev-dependencies.cargo-husky] 35 | version = "1" 36 | default-features = false 37 | features = ["user-hooks"] 38 | 39 | [[example]] 40 | name = "async_tx_log" 41 | required-features = ["async"] 42 | 43 | [[example]] 44 | name = "async_tx_logs" 45 | required-features = ["async"] 46 | 47 | [[example]] 48 | name = "async_entity_timed" 49 | required-features = ["async"] 50 | 51 | [[example]] 52 | name = "async_entity_tx_timed" 53 | required-features = ["async"] 54 | 55 | [[example]] 56 | name = "async_entity_history_timed" 57 | required-features = ["async"] 58 | 59 | [[example]] 60 | name = "async_query" 61 | required-features = ["async"] 62 | 63 | [[example]] 64 | name = "async_deal_with_error_entity" 65 | required-features = ["async"] 66 | -------------------------------------------------------------------------------- /examples/async_tx_logs.rs: -------------------------------------------------------------------------------- 1 | use transistor::client::Crux; 2 | use transistor::types::response::TxLogsResponse; 3 | 4 | async fn tx_logs() -> TxLogsResponse { 5 | let body = Crux::new("localhost", "3000") 6 | .http_client() 7 | .tx_logs() 8 | .await 9 | .unwrap(); 10 | return body; 11 | } 12 | 13 | #[tokio::main] 14 | async fn main() { 15 | let tx_logs = tx_logs().await; 16 | println!("Body = {:#?}", tx_logs); 17 | // Body = TxLogsResponse { 18 | // tx_events: [ 19 | // TxLogResponse { 20 | // tx___tx_id: 0, 21 | // tx___tx_time: "2020-07-09T23:38:06.465-00:00", 22 | // tx__event___tx_events: Some( 23 | // [ 24 | // [ 25 | // ":crux.tx/put", 26 | // "a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e", 27 | // "125d29eb3bed1bf51d64194601ad4ff93defe0e2", 28 | // ], 29 | // ], 30 | // ), 31 | // }, 32 | // TxLogResponse { 33 | // tx___tx_id: 1, 34 | // tx___tx_time: "2020-07-09T23:39:33.815-00:00", 35 | // tx__event___tx_events: Some( 36 | // [ 37 | // [ 38 | // ":crux.tx/put", 39 | // "a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e", 40 | // "1b42e0d5137e3833423f7bb958622bee29f91eee", 41 | // ], 42 | // ], 43 | // ), 44 | // }, 45 | // ... 46 | // ] 47 | // } 48 | } 49 | 50 | #[tokio::test] 51 | async fn test_tx_logs() { 52 | let tx_logs = tx_logs().await; 53 | assert!(tx_logs.tx_events.len() > 0) 54 | } 55 | -------------------------------------------------------------------------------- /examples/tx_log.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::response::TxLogResponse; 4 | use transistor::types::Actions; 5 | use transistor::types::CruxId; 6 | 7 | #[cfg(not(feature = "async"))] 8 | fn tx_log() -> TxLogResponse { 9 | let person1 = Person { 10 | crux__db___id: CruxId::new("jorge-3"), 11 | first_name: "Michael".to_string(), 12 | last_name: "Jorge".to_string(), 13 | }; 14 | // edn_rs::to_string(person1) { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", } 15 | 16 | let person2 = Person { 17 | crux__db___id: CruxId::new("manuel-1"), 18 | first_name: "Diego".to_string(), 19 | last_name: "Manuel".to_string(), 20 | }; 21 | // edn_rs::to_string(person2): { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", } 22 | 23 | let actions = Actions::new().append_put(person1).append_put(person2); 24 | // "[[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }], 25 | // [:crux.tx/put { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", }]]" 26 | 27 | let body = Crux::new("localhost", "3000") 28 | .http_client() 29 | .tx_log(actions) 30 | .unwrap(); 31 | 32 | return body; 33 | } 34 | 35 | #[test] 36 | #[cfg(not(feature = "async"))] 37 | fn test_tx_log() { 38 | let tx_log = tx_log(); 39 | assert!(tx_log.tx___tx_id > 0) 40 | } 41 | 42 | #[cfg(not(feature = "async"))] 43 | fn main() { 44 | let body = tx_log(); 45 | println!("Body = {:?}", body); 46 | // Body = "{:crux.tx/tx-id 7, :crux.tx/tx-time #inst \"2020-07-16T21:50:39.309-00:00\"}" 47 | } 48 | 49 | #[derive(Debug, Clone, Serialize)] 50 | #[allow(non_snake_case)] 51 | pub struct Person { 52 | crux__db___id: CruxId, 53 | first_name: String, 54 | last_name: String, 55 | } 56 | -------------------------------------------------------------------------------- /examples/tx_logs.rs: -------------------------------------------------------------------------------- 1 | use transistor::client::Crux; 2 | use transistor::types::response::TxLogsResponse; 3 | 4 | #[cfg(not(feature = "async"))] 5 | fn tx_logs() -> TxLogsResponse { 6 | let body = Crux::new("localhost", "3000") 7 | .http_client() 8 | .tx_logs() 9 | .unwrap(); 10 | 11 | return body; 12 | } 13 | 14 | #[test] 15 | #[cfg(not(feature = "async"))] 16 | fn test_tx_logs() { 17 | let logs = tx_logs(); 18 | assert!(logs.tx_events.len() > 0); 19 | } 20 | 21 | #[cfg(not(feature = "async"))] 22 | fn main() { 23 | let body = tx_logs(); 24 | println!("Body = {:#?}", body); 25 | // Body = TxLogsResponse { 26 | // tx_events: [ 27 | // TxLogResponse { 28 | // tx___tx_id: 0, 29 | // tx___tx_time: "2020-07-09T23:38:06.465-00:00", 30 | // tx__event___tx_events: Some( 31 | // [ 32 | // [ 33 | // ":crux.tx/put", 34 | // "a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e", 35 | // "125d29eb3bed1bf51d64194601ad4ff93defe0e2", 36 | // ], 37 | // ], 38 | // ), 39 | // }, 40 | // TxLogResponse { 41 | // tx___tx_id: 1, 42 | // tx___tx_time: "2020-07-09T23:39:33.815-00:00", 43 | // tx__event___tx_events: Some( 44 | // [ 45 | // [ 46 | // ":crux.tx/put", 47 | // "a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e", 48 | // "1b42e0d5137e3833423f7bb958622bee29f91eee", 49 | // ], 50 | // ], 51 | // ), 52 | // }, 53 | // ... 54 | // ] 55 | // } 56 | } 57 | -------------------------------------------------------------------------------- /examples/match_no_continue_tx.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::Actions; 4 | use transistor::types::{ 5 | error::CruxError, 6 | {query::Query, CruxId}, 7 | }; 8 | 9 | #[cfg(not(feature = "async"))] 10 | fn match_break() -> Result<(), CruxError> { 11 | let mut crux = Database { 12 | crux__db___id: CruxId::new("crux"), 13 | name: "Crux Datalog".to_string(), 14 | is_sql: false, 15 | }; 16 | 17 | let client = Crux::new("localhost", "3000").http_client(); 18 | let actions = Actions::new().append_put(crux.clone()); 19 | 20 | let _ = client.tx_log(actions)?; 21 | 22 | let query = Query::find(vec!["?d"])? 23 | .where_clause(vec!["?d :is-sql false"])? 24 | .build()?; 25 | 26 | let query_response = client.query(query)?; 27 | 28 | let id = CruxId::new(&query_response.iter().next().unwrap()[0]); 29 | let _ = client.entity(id).unwrap(); 30 | // Map(Map({":crux.db/id": Key(":crux"), ":is-sql": Bool(false), ":name": Str("Crux Datalog")})) 31 | 32 | crux.name = "banana".to_string(); 33 | let actions = Actions::new() 34 | .append_match_doc(CruxId::new(":crux"), crux.clone()) 35 | .append_put(crux.clone()); 36 | 37 | let _ = client.tx_log(actions)?; 38 | // TxLogResponse { tx___tx_id: 54, tx___tx_time: "2020-08-09T03:54:20.730-00:00", tx__event___tx_events: None } 39 | 40 | let query = Query::find(vec!["?d"])? 41 | .where_clause(vec!["?d :is-sql false"])? 42 | .build()?; 43 | 44 | let query_response = client.query(query)?; 45 | 46 | let id = CruxId::new(&query_response.iter().next().unwrap()[0]); 47 | let _ = client.entity(id).unwrap(); 48 | // Map(Map({":crux.db/id": Key(":crux"), ":is-sql": Bool(false), ":name": Str("Crux Datalog")})) 49 | 50 | Ok(()) 51 | } 52 | 53 | #[cfg(not(feature = "async"))] 54 | fn main() { 55 | let _ = match_break(); 56 | } 57 | 58 | #[test] 59 | #[cfg(not(feature = "async"))] 60 | fn test_match_break() { 61 | match_break().unwrap(); 62 | } 63 | 64 | #[derive(Debug, Clone, Serialize)] 65 | #[allow(non_snake_case)] 66 | pub struct Database { 67 | crux__db___id: CruxId, 68 | name: String, 69 | is_sql: bool, 70 | } 71 | -------------------------------------------------------------------------------- /examples/async_entity_tx_timed.rs: -------------------------------------------------------------------------------- 1 | use chrono::prelude::*; 2 | use edn_derive::Serialize; 3 | use transistor::client::Crux; 4 | use transistor::edn_rs::EdnError; 5 | use transistor::types::response::EntityTxResponse; 6 | use transistor::types::Actions; 7 | use transistor::types::CruxId; 8 | 9 | async fn entity_tx_timed() -> EntityTxResponse { 10 | let person1 = Person { 11 | crux__db___id: CruxId::new("calor-jorge-3"), 12 | first_name: "Calors Michael".to_string(), 13 | last_name: "Jorge".to_string(), 14 | }; 15 | 16 | let person2 = Person { 17 | crux__db___id: CruxId::new("silva-manuel-1"), 18 | first_name: "Silva Diego".to_string(), 19 | last_name: "Manuel".to_string(), 20 | }; 21 | 22 | let client = Crux::new("localhost", "3000").http_client(); 23 | let timed = "2014-11-28T21:00:09-09:00" 24 | .parse::>() 25 | .unwrap(); 26 | 27 | let actions = Actions::new() 28 | .append_put_timed(person1.clone(), timed.clone()) 29 | .append_put_timed(person2, timed.clone()); 30 | 31 | let _ = Crux::new("localhost", "3000") 32 | .http_client() 33 | .tx_log(actions) 34 | .await 35 | .unwrap(); 36 | 37 | let entity_tx_body = client 38 | .entity_tx_timed(person1.crux__db___id, None, Some(timed)) 39 | .await 40 | .unwrap(); 41 | 42 | return entity_tx_body; 43 | } 44 | 45 | #[tokio::main] 46 | async fn main() { 47 | let entity = entity_tx_timed().await; 48 | println!("\n Edn Body = {:#?}", entity); 49 | // Edn Body = EntityTxResponse { 50 | // db___id: "f936408359776345394b07809bf1fd9bf0f70046", 51 | // db___content_hash: "621f30a89898d2c55bc81b0b1e0db0be2878486c", 52 | // db___valid_time: 2014-11-29T06:00:09+00:00, 53 | // tx___tx_id: 111, 54 | // tx___tx_time: 2020-09-30T13:22:02.795+00:00, 55 | // } 56 | } 57 | 58 | #[tokio::test] 59 | async fn test_entity_tx_timed() { 60 | let entity = entity_tx_timed().await; 61 | 62 | assert!(entity.tx___tx_id > 0); 63 | } 64 | 65 | #[derive(Debug, Clone, Serialize)] 66 | #[allow(non_snake_case)] 67 | pub struct Person { 68 | crux__db___id: CruxId, 69 | first_name: String, 70 | last_name: String, 71 | } 72 | -------------------------------------------------------------------------------- /examples/complex_query.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::Actions; 4 | use transistor::types::{ 5 | error::CruxError, 6 | {query::Query, CruxId}, 7 | }; 8 | 9 | #[cfg(not(feature = "async"))] 10 | fn query() -> Result<(), CruxError> { 11 | let crux = Database { 12 | crux__db___id: CruxId::new("crux"), 13 | name: "Crux Datalog".to_string(), 14 | is_sql: false, 15 | }; 16 | 17 | let psql = Database { 18 | crux__db___id: CruxId::new("postgres"), 19 | name: "Postgres".to_string(), 20 | is_sql: true, 21 | }; 22 | 23 | let mysql = Database { 24 | crux__db___id: CruxId::new("mysql"), 25 | name: "MySQL".to_string(), 26 | is_sql: true, 27 | }; 28 | 29 | let cassandra = Database { 30 | crux__db___id: CruxId::new("cassandra"), 31 | name: "Cassandra".to_string(), 32 | is_sql: false, 33 | }; 34 | 35 | let sqlserver = Database { 36 | crux__db___id: CruxId::new("sqlserver"), 37 | name: "Sql Server".to_string(), 38 | is_sql: true, 39 | }; 40 | 41 | let client = Crux::new("localhost", "3000").http_client(); 42 | let actions = Actions::new() 43 | .append_put(crux) 44 | .append_put(psql) 45 | .append_put(mysql) 46 | .append_put(cassandra) 47 | .append_put(sqlserver); 48 | 49 | let _ = client.tx_log(actions)?; 50 | 51 | let query_is_sql = Query::find(vec!["?p1", "?n"])? 52 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?sql"])? 53 | .order_by(vec!["?n :asc"])? 54 | .args(vec!["?sql true"])? 55 | .build(); 56 | // {:query\n {:find [?p1 ?n]\n:where [[?p1 :name ?n]\n[?p1 :is-sql ?sql]]\n:args [{?sql true}]\n:order-by [[?n :asc]]\n}} 57 | 58 | let _ = client.query(query_is_sql?)?; 59 | // {[":mysql", "MySQL"], [":postgres", "Postgres"], [":sqlserver", "Sql Server"]} 60 | 61 | Ok(()) 62 | } 63 | 64 | #[cfg(not(feature = "async"))] 65 | fn main() { 66 | let _ = query(); 67 | } 68 | 69 | #[test] 70 | #[cfg(not(feature = "async"))] 71 | fn test_query() { 72 | query().unwrap(); 73 | } 74 | 75 | #[derive(Debug, Clone, Serialize)] 76 | #[allow(non_snake_case)] 77 | pub struct Database { 78 | crux__db___id: CruxId, 79 | name: String, 80 | is_sql: bool, 81 | } 82 | -------------------------------------------------------------------------------- /examples/match_continue_tx.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::Actions; 4 | use transistor::types::{ 5 | error::CruxError, 6 | {query::Query, CruxId}, 7 | }; 8 | 9 | #[cfg(not(feature = "async"))] 10 | fn match_continue() -> Result<(), CruxError> { 11 | let crux = Database { 12 | crux__db___id: CruxId::new("crux"), 13 | name: "Crux Datalog".to_string(), 14 | is_sql: false, 15 | }; 16 | 17 | let client = Crux::new("localhost", "3000").http_client(); 18 | let actions = Actions::new().append_put(crux.clone()); 19 | 20 | let _ = client.tx_log(actions)?; 21 | 22 | let query = Query::find(vec!["?d"])? 23 | .where_clause(vec!["?d :is-sql false"])? 24 | .build()?; 25 | 26 | let query_response = client.query(query)?; 27 | 28 | let id = CruxId::new(&query_response.iter().next().unwrap()[0]); 29 | let _ = client.entity(id).unwrap(); 30 | // Map(Map({":crux.db/id": Key(":crux"), ":is-sql": Bool(false), ":name": Str("Crux Datalog")})) 31 | 32 | let actions = Actions::new() 33 | .append_match_doc(CruxId::new(":crux"), crux.clone()) 34 | .append_put(crux.rename("banana")); 35 | 36 | let _ = client.tx_log(actions)?; 37 | // TxLogResponse { tx___tx_id: 54, tx___tx_time: "2020-08-09T03:54:20.730-00:00", tx__event___tx_events: None } 38 | 39 | let query = Query::find(vec!["?d"])? 40 | .where_clause(vec!["?d :is-sql false"])? 41 | .build()?; 42 | 43 | let query_response = client.query(query)?; 44 | 45 | let id = CruxId::new(&query_response.iter().next().unwrap()[0]); 46 | let _ = client.entity(id).unwrap(); 47 | // Map(Map({":crux.db/id": Key(":crux"), ":is-sql": Bool(false), ":name": Str("banana")})) 48 | 49 | Ok(()) 50 | } 51 | 52 | #[cfg(not(feature = "async"))] 53 | fn main() { 54 | let _ = match_continue(); 55 | } 56 | 57 | #[test] 58 | #[cfg(not(feature = "async"))] 59 | fn test_match_continue() { 60 | match_continue().unwrap(); 61 | } 62 | 63 | #[derive(Debug, Clone, Serialize)] 64 | #[allow(non_snake_case)] 65 | pub struct Database { 66 | crux__db___id: CruxId, 67 | name: String, 68 | is_sql: bool, 69 | } 70 | 71 | impl Database { 72 | fn rename(mut self, name: &str) -> Self { 73 | self.name = name.to_string(); 74 | self 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /examples/async_query.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::error::CruxError; 4 | use transistor::types::Actions; 5 | use transistor::types::{query::Query, CruxId}; 6 | 7 | async fn query() -> Result<(), CruxError> { 8 | let crux = Database { 9 | crux__db___id: CruxId::new("crux"), 10 | name: "Crux Datalog".to_string(), 11 | is_sql: false, 12 | }; 13 | 14 | let psql = Database { 15 | crux__db___id: CruxId::new("postgres"), 16 | name: "Postgres".to_string(), 17 | is_sql: true, 18 | }; 19 | 20 | let mysql = Database { 21 | crux__db___id: CruxId::new("mysql"), 22 | name: "MySQL".to_string(), 23 | is_sql: true, 24 | }; 25 | 26 | let client = Crux::new("localhost", "3000").http_client(); 27 | let actions = Actions::new() 28 | .append_put(crux) 29 | .append_put(psql) 30 | .append_put(mysql); 31 | 32 | let _ = client.tx_log(actions).await.unwrap(); 33 | 34 | let query_is_sql = Query::find(vec!["?p1", "?n"]) 35 | .unwrap() 36 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql true"]) 37 | .unwrap() 38 | .build(); 39 | 40 | let is_sql = client.query(query_is_sql.unwrap()).await.unwrap(); 41 | // QueryAsyncResponse({[":mysql", "MySQL"], [":postgres", "Postgres"]}) BTreeSet 42 | 43 | let query_is_no_sql = Query::find(vec!["?p1", "?n", "?s"]) 44 | .unwrap() 45 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql false"]) 46 | .unwrap() 47 | .with_full_results() 48 | .build() 49 | .unwrap(); 50 | 51 | let is_no_sql = client.query(query_is_no_sql).await.unwrap(); 52 | // {["{:crux.db/id: Key(\":cassandra\"), :is-sql: Bool(false), :name: Str(\"Cassandra\"), }", "Cassandra", "false"], 53 | // ["{:crux.db/id: Key(\":crux\"), :is-sql: Bool(false), :name: Str(\"Crux Datalog\"), }", "Crux Datalog", "false"]} 54 | 55 | Ok(()) 56 | } 57 | 58 | #[tokio::main] 59 | async fn main() { 60 | let _ = query().await.unwrap(); 61 | } 62 | 63 | #[tokio::test] 64 | async fn test_query() { 65 | let _ = query().await.unwrap(); 66 | } 67 | 68 | #[derive(Debug, Clone, Serialize)] 69 | #[allow(non_snake_case)] 70 | pub struct Database { 71 | crux__db___id: CruxId, 72 | name: String, 73 | is_sql: bool, 74 | } 75 | -------------------------------------------------------------------------------- /examples/limit_offset_query.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::Actions; 4 | use transistor::types::{ 5 | error::CruxError, 6 | {query::Query, CruxId}, 7 | }; 8 | 9 | #[cfg(not(feature = "async"))] 10 | fn limit_offset() -> Result<(), CruxError> { 11 | let crux = Database { 12 | crux__db___id: CruxId::new("crux"), 13 | name: "Crux Datalog".to_string(), 14 | is_sql: false, 15 | }; 16 | 17 | let psql = Database { 18 | crux__db___id: CruxId::new("postgres"), 19 | name: "Postgres".to_string(), 20 | is_sql: true, 21 | }; 22 | 23 | let mysql = Database { 24 | crux__db___id: CruxId::new("mysql"), 25 | name: "MySQL".to_string(), 26 | is_sql: true, 27 | }; 28 | 29 | let cassandra = Database { 30 | crux__db___id: CruxId::new("cassandra"), 31 | name: "Cassandra".to_string(), 32 | is_sql: false, 33 | }; 34 | 35 | let sqlserver = Database { 36 | crux__db___id: CruxId::new("sqlserver"), 37 | name: "Sql Server".to_string(), 38 | is_sql: true, 39 | }; 40 | 41 | let client = Crux::new("localhost", "3000").http_client(); 42 | let actions = Actions::new() 43 | .append_put(crux) 44 | .append_put(psql) 45 | .append_put(mysql) 46 | .append_put(cassandra) 47 | .append_put(sqlserver); 48 | // [[:crux.tx/put { :crux.db/id :crux, :name \"Crux Datalog\", :is-sql false, }], 49 | // [:crux.tx/put { :crux.db/id :mysql, :name \"MySQL\", :is-sql true, }], 50 | // [:crux.tx/put { :crux.db/id :postgres, :name \"Postgres\", :is-sql true, }]] 51 | 52 | let _ = client.tx_log(actions)?; 53 | 54 | let query_is_sql = Query::find(vec!["?p1", "?n"])? 55 | .where_clause(vec!["?p1 :name ?n"])? 56 | .order_by(vec!["?n :desc"])? 57 | .limit(3) 58 | .offset(1) 59 | .build(); 60 | // "{:query\n {:find [?p1 ?n]\n:where [[?p1 :name ?n]]\n:order-by [[?n :desc]]\n:limit 3\n:offset 1\n}}" 61 | 62 | let _ = client.query(query_is_sql?)?; 63 | // {[":crux", "Crux Datalog"], [":mysql", "MySQL"], [":postgres", "Postgres"]} 64 | 65 | Ok(()) 66 | } 67 | 68 | #[cfg(not(feature = "async"))] 69 | fn main() { 70 | let _ = limit_offset(); 71 | } 72 | 73 | #[test] 74 | #[cfg(not(feature = "async"))] 75 | fn test_limit_offset() { 76 | limit_offset().unwrap(); 77 | } 78 | 79 | #[derive(Debug, Clone, Serialize)] 80 | #[allow(non_snake_case)] 81 | pub struct Database { 82 | crux__db___id: CruxId, 83 | name: String, 84 | is_sql: bool, 85 | } 86 | -------------------------------------------------------------------------------- /examples/async_entity_timed.rs: -------------------------------------------------------------------------------- 1 | use chrono::prelude::*; 2 | use edn_derive::{Deserialize, Serialize}; 3 | use transistor::client::Crux; 4 | use transistor::types::Actions; 5 | use transistor::types::CruxId; 6 | 7 | async fn entity_timed() -> edn_rs::Edn { 8 | let person1 = Person { 9 | crux__db___id: CruxId::new("jorge-3"), 10 | first_name: "Michael".to_string(), 11 | last_name: "Jorge".to_string(), 12 | }; 13 | 14 | let person2 = Person { 15 | crux__db___id: CruxId::new("manuel-1"), 16 | first_name: "Diego".to_string(), 17 | last_name: "Manuel".to_string(), 18 | }; 19 | 20 | let client = Crux::new("localhost", "3000").http_client(); 21 | let timed = "2014-11-28T21:00:09-09:00" 22 | .parse::>() 23 | .unwrap(); 24 | 25 | let actions = Actions::new() 26 | .append_put_timed(person1.clone(), timed) 27 | .append_put_timed(person2, timed); 28 | 29 | let _ = Crux::new("localhost", "3000") 30 | .http_client() 31 | .tx_log(actions) 32 | .await 33 | .unwrap(); 34 | 35 | let edn_body = client 36 | .entity_timed(person1.crux__db___id, None, Some(timed)) 37 | .await 38 | .unwrap(); 39 | 40 | return edn_body; 41 | } 42 | 43 | #[tokio::main] 44 | async fn main() { 45 | let edn_body = entity_timed().await; 46 | 47 | println!("\n Edn Body = {:#?}", edn_body); 48 | // Edn Body = Map( 49 | // Map( 50 | // { 51 | // ":crux.db/id": Key( 52 | // ":hello-entity", 53 | // ), 54 | // ":first-name": Str( 55 | // "Hello", 56 | // ), 57 | // ":last-name": Str( 58 | // "World", 59 | // ), 60 | // }, 61 | // ), 62 | // ) 63 | 64 | println!( 65 | "\n Person Parsed Response = {:#?}", 66 | edn_rs::from_edn::(&edn_body) 67 | ); 68 | // Person Parsed Response = Person { 69 | // crux__db___id: CruxId( 70 | // ":hello-entity", 71 | // ), 72 | // first_name: "Hello", 73 | // last_name: "World", 74 | // } 75 | } 76 | 77 | #[tokio::test] 78 | async fn test_entity_timed() { 79 | let edn_body = entity_timed().await; 80 | let entity = edn_rs::from_edn::(&edn_body).unwrap(); 81 | let expected = Person { 82 | crux__db___id: CruxId::new("jorge-3"), 83 | first_name: "Michael".to_string(), 84 | last_name: "Jorge".to_string(), 85 | }; 86 | 87 | assert_eq!(entity, expected); 88 | } 89 | 90 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 91 | #[allow(non_snake_case)] 92 | pub struct Person { 93 | crux__db___id: CruxId, 94 | first_name: String, 95 | last_name: String, 96 | } 97 | -------------------------------------------------------------------------------- /examples/entity.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::edn_rs::{Deserialize, EdnError}; 4 | use transistor::types::Actions; 5 | use transistor::types::CruxId; 6 | 7 | #[cfg(not(feature = "async"))] 8 | fn entity() -> edn_rs::Edn { 9 | let person = Person { 10 | crux__db___id: CruxId::new("hello-entity"), 11 | first_name: "Hello".to_string(), 12 | last_name: "World".to_string(), 13 | }; 14 | // { :crux.db/id :hello-entity, :first-name \"Hello\", :last-name \"World\", } 15 | 16 | let client = Crux::new("localhost", "3000").http_client(); 17 | let put_person = Actions::new().append_put(person.clone()); 18 | 19 | let _ = client.tx_log(put_person).unwrap(); 20 | // {:crux.tx/tx-id 7, :crux.tx/tx-time #inst \"2020-07-16T21:50:39.309-00:00\"} 21 | 22 | let edn_body = client.entity(person.crux__db___id).unwrap(); 23 | 24 | return edn_body; 25 | } 26 | 27 | #[test] 28 | #[cfg(not(feature = "async"))] 29 | fn test_entity() { 30 | let edn_body = entity(); 31 | let person = edn_rs::from_edn::(&edn_body); 32 | let expected = Person { 33 | crux__db___id: CruxId::new("hello-entity"), 34 | first_name: "Hello".to_string(), 35 | last_name: "World".to_string(), 36 | }; 37 | 38 | assert_eq!(person.unwrap(), expected); 39 | } 40 | 41 | #[cfg(not(feature = "async"))] 42 | fn main() { 43 | let edn_body = entity(); 44 | println!("\n Edn Body = {:#?}", edn_body.clone()); 45 | // Edn Body = Map( 46 | // Map( 47 | // { 48 | // ":crux.db/id": Key( 49 | // ":hello-entity", 50 | // ), 51 | // ":first-name": Str( 52 | // "Hello", 53 | // ), 54 | // ":last-name": Str( 55 | // "World", 56 | // ), 57 | // }, 58 | // ), 59 | // ) 60 | 61 | println!( 62 | "\n Person Parsed Response = {:#?}", 63 | edn_rs::from_edn::(&edn_body) 64 | ); 65 | // Person Parsed Response = Person { 66 | // crux__db___id: CruxId( 67 | // ":hello-entity", 68 | // ), 69 | // first_name: "Hello", 70 | // last_name: "World", 71 | // } 72 | } 73 | 74 | #[derive(Debug, PartialEq, Clone, Serialize)] 75 | #[allow(non_snake_case)] 76 | pub struct Person { 77 | crux__db___id: CruxId, 78 | first_name: String, 79 | last_name: String, 80 | } 81 | 82 | impl Deserialize for Person { 83 | fn deserialize(edn: &edn_rs::Edn) -> Result { 84 | Ok(Self { 85 | crux__db___id: edn_rs::from_edn(&edn[":crux.db/id"])?, 86 | first_name: edn_rs::from_edn(&edn[":first-name"])?, 87 | last_name: edn_rs::from_edn(&edn[":last-name"])?, 88 | }) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /examples/entity_history.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::http::{Actions, Order}; 4 | use transistor::types::response::EntityTxResponse; 5 | use transistor::types::CruxId; 6 | 7 | #[cfg(not(feature = "async"))] 8 | fn entity_tx() -> EntityTxResponse { 9 | let person = Person { 10 | crux__db___id: CruxId::new("hello-history"), 11 | first_name: "Hello".to_string(), 12 | last_name: "World".to_string(), 13 | }; 14 | 15 | let put_person = Actions::new().append_put(person.clone()); 16 | 17 | let client = Crux::new("localhost", "3000").http_client(); 18 | let _ = client.tx_log(put_person).unwrap(); 19 | 20 | let tx_body = client.entity_tx(person.crux__db___id).unwrap(); 21 | return tx_body; 22 | } 23 | 24 | #[test] 25 | #[cfg(not(feature = "async"))] 26 | fn test_entity_history_with_docs() { 27 | let client = Crux::new("localhost", "3000").http_client(); 28 | let tx_body = entity_tx(); 29 | let docs = client 30 | .entity_history(tx_body.db___id.clone(), Order::Asc, true) 31 | .unwrap(); 32 | assert!(docs.history[0].db__doc.is_some()) 33 | } 34 | 35 | #[test] 36 | #[cfg(not(feature = "async"))] 37 | fn test_entity_history_without_docs() { 38 | let client = Crux::new("localhost", "3000").http_client(); 39 | let tx_body = entity_tx(); 40 | let docs = client 41 | .entity_history(tx_body.db___id.clone(), Order::Asc, false) 42 | .unwrap(); 43 | assert!(docs.history[0].db__doc.is_none()) 44 | } 45 | 46 | #[cfg(not(feature = "async"))] 47 | fn main() { 48 | let client = Crux::new("localhost", "3000").http_client(); 49 | let tx_body = entity_tx(); 50 | let _ = client.entity_history(tx_body.db___id.clone(), Order::Asc, true); 51 | // EntityHistoryResponse { history: [ 52 | // EntityHistoryElement { 53 | // db___valid_time: "2020-08-05T03:00:06.476-00:00", 54 | // tx___tx_id: 37, tx___tx_time: "2020-08-05T03:00:06.476-00:00", 55 | // db___content_hash: "2da097a2dffbb9828cd4377f1461a59e8454674b", 56 | // db__doc: Some(Map(Map({":crux.db/id": Key(":hello-history"), ":first-name": Str("Hello"), ":last-name": Str("World")}))) 57 | // } 58 | // ]} 59 | 60 | let _ = client.entity_history(tx_body.db___id, Order::Asc, false); 61 | // EntityHistoryResponse { 62 | // history: [ 63 | // EntityHistoryElement { 64 | // db___valid_time: "2020-08-05T03:00:06.476-00:00", 65 | // tx___tx_id: 37, 66 | // tx___tx_time: "2020-08-05T03:00:06.476-00:00", 67 | // db___content_hash: "2da097a2dffbb9828cd4377f1461a59e8454674b", 68 | // db__doc: None 69 | // } 70 | // } 71 | // ]} 72 | } 73 | 74 | #[derive(Debug, Clone, Serialize)] 75 | #[allow(non_snake_case)] 76 | pub struct Person { 77 | crux__db___id: CruxId, 78 | first_name: String, 79 | last_name: String, 80 | } 81 | -------------------------------------------------------------------------------- /examples/simple_query.rs: -------------------------------------------------------------------------------- 1 | use edn_derive::Serialize; 2 | use transistor::client::Crux; 3 | use transistor::types::Actions; 4 | use transistor::types::{ 5 | error::CruxError, 6 | {query::Query, CruxId}, 7 | }; 8 | 9 | #[cfg(not(feature = "async"))] 10 | fn query() -> Result<(), CruxError> { 11 | let crux = Database { 12 | crux__db___id: CruxId::new("crux"), 13 | name: "Crux Datalog".to_string(), 14 | is_sql: false, 15 | }; 16 | // edn_rs::to_string(crux) { :crux.db/id :crux, :name \"Crux Datalog\", :is-sql false, } 17 | 18 | let psql = Database { 19 | crux__db___id: CruxId::new("postgres"), 20 | name: "Postgres".to_string(), 21 | is_sql: true, 22 | }; 23 | // edn_rs::to_string(psql) { :crux.db/id :postgres, :name \"Postgres\", :is-sql true, } 24 | 25 | let mysql = Database { 26 | crux__db___id: CruxId::new("mysql"), 27 | name: "MySQL".to_string(), 28 | is_sql: true, 29 | }; 30 | // edn_rs::to_string(mysql) { :crux.db/id :mysql, :name \"MySQL\", :is-sql true, } 31 | 32 | let client = Crux::new("localhost", "3000").http_client(); 33 | let actions = Actions::new() 34 | .append_put(crux) 35 | .append_put(psql) 36 | .append_put(mysql); 37 | // [[:crux.tx/put { :crux.db/id :crux, :name \"Crux Datalog\", :is-sql false, }], 38 | // [:crux.tx/put { :crux.db/id :mysql, :name \"MySQL\", :is-sql true, }], 39 | // [:crux.tx/put { :crux.db/id :postgres, :name \"Postgres\", :is-sql true, }]] 40 | 41 | let _ = client.tx_log(actions)?; 42 | 43 | let query_is_sql = Query::find(vec!["?p1", "?n"])? 44 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql true"])? 45 | .build(); 46 | // Query: 47 | // {:query 48 | // {:find [?p1 ?n] 49 | // :where [[?p1 :name ?n] 50 | // [?p1 :is-sql true]]}} 51 | 52 | let _ = client.query(query_is_sql?)?; 53 | // BTreeSet{[":mysql", "MySQL"], [":postgres", "Postgres"]} 54 | 55 | let query_is_no_sql = Query::find(vec!["?p1", "?n", "?s"])? 56 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql false"])? 57 | .with_full_results() 58 | .build(); 59 | // Query: 60 | // {:query 61 | // {:find [?p1] 62 | // :where [[?p1 :name ?n] 63 | // [?p1 :is-sql ?s] 64 | // [?p1 :is-sql false]]}} 65 | 66 | let _ = client.query(query_is_no_sql?)?; 67 | // BTreeSet{ 68 | // ["{:crux.db/id: Key(\":cassandra\"), :is-sql: Bool(false), :name: Str(\"Cassandra\"), }", "Cassandra", "false"], 69 | // ["{:crux.db/id: Key(\":crux\"), :is-sql: Bool(false), :name: Str(\"Crux Datalog\"), }", "Crux Datalog", "false"]} 70 | 71 | Ok(()) 72 | } 73 | 74 | #[cfg(not(feature = "async"))] 75 | fn main() { 76 | let _ = query(); 77 | } 78 | 79 | #[test] 80 | #[cfg(not(feature = "async"))] 81 | fn test_query() { 82 | query().unwrap() 83 | } 84 | 85 | #[derive(Debug, Clone, Serialize)] 86 | #[allow(non_snake_case)] 87 | pub struct Database { 88 | crux__db___id: CruxId, 89 | name: String, 90 | is_sql: bool, 91 | } 92 | -------------------------------------------------------------------------------- /src/types/error.rs: -------------------------------------------------------------------------------- 1 | use edn_rs::EdnError; 2 | use reqwest::Error; 3 | 4 | /// Main error type for transistor crate 5 | #[derive(Debug)] 6 | pub enum CruxError { 7 | /// Error originated by `edn_rs` crate. The provided EDN did not match schema. 8 | ParseEdnError(String), 9 | /// Error originated by `edn_rs` crate. There was an error on deserializing an Edn to a struct. 10 | DeserializeError(String), 11 | /// Error originated by `edn_rs` crate. There was an error on iterating over an Edn structure. 12 | IterError(String), 13 | /// Error originated by `reqwest` crate. Failed to make HTTP request. 14 | RequestError(Error), 15 | /// Error originated by `reqwest` crate. Failed to make HTTP request. 16 | BadResponse(String), 17 | /// Error originated by undefined behavior when parsing Crux response. 18 | ResponseFailed(String), 19 | /// Query response error, most likely a Clojure stacktrace from Crux response. 20 | QueryError(String), 21 | /// Provided Query struct did not match schema. 22 | QueryFormatError(String), 23 | /// Provided Actions cannot be empty. 24 | TxLogActionError(String), 25 | } 26 | 27 | impl std::error::Error for CruxError { 28 | fn description(&self) -> &str { 29 | match self { 30 | CruxError::ParseEdnError(s) => &s, 31 | CruxError::DeserializeError(s) => &s, 32 | CruxError::RequestError(_) => "HTTP request to Crux failed", 33 | CruxError::BadResponse(s) => &s, 34 | CruxError::ResponseFailed(s) => &s, 35 | CruxError::QueryError(s) => &s, 36 | CruxError::QueryFormatError(s) => &s, 37 | CruxError::IterError(s) => &s, 38 | CruxError::TxLogActionError(s) => &s, 39 | } 40 | } 41 | 42 | fn cause(&self) -> Option<&dyn std::error::Error> { 43 | Some(self) 44 | } 45 | } 46 | 47 | impl std::fmt::Display for CruxError { 48 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 49 | match self { 50 | CruxError::ParseEdnError(s) => write!(f, "{}", &s), 51 | CruxError::DeserializeError(s) => write!(f, "{}", &s), 52 | CruxError::RequestError(e) => write!(f, "{:?}", &e), 53 | CruxError::BadResponse(e) => write!(f, "{}", &e), 54 | CruxError::ResponseFailed(e) => write!(f, "{}", &e), 55 | CruxError::QueryError(s) => write!(f, "{}", &s), 56 | CruxError::QueryFormatError(s) => write!(f, "{}", &s), 57 | CruxError::IterError(s) => write!(f, "{}", &s), 58 | CruxError::TxLogActionError(s) => write!(f, "{}", &s), 59 | } 60 | } 61 | } 62 | 63 | impl From for CruxError { 64 | fn from(err: EdnError) -> Self { 65 | match err { 66 | EdnError::ParseEdn(s) => CruxError::ParseEdnError(s), 67 | EdnError::Deserialize(s) => CruxError::DeserializeError(s), 68 | EdnError::Iter(s) => CruxError::IterError(s), 69 | } 70 | } 71 | } 72 | 73 | impl From for CruxError { 74 | fn from(err: Error) -> Self { 75 | CruxError::RequestError(err) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub use edn_rs; 2 | 3 | /// Generic Request/Response Types for Crux. 4 | /// Availables types are: 5 | /// * `CruxId` is the field that receives a String and serielizes it to a EDN Keyword. 6 | /// 7 | /// Availables types for responses in module `types::response` are: 8 | /// * `StateResponse` response for Crux REST API at endpoint `/state`. 9 | /// * `TxLogResponse` response for Crux REST API at endpoint `/tx-log`. For `POSTs`, `tx__event___tx_events (:crux-tx.event/tx_events)` comes with `None`. 10 | /// * `TxLogsResponse` response is the wrapper for a `GET` at endpoint `/tx-logs`, it is a `Vector` of type `TxLogResponse`. 11 | /// * `EntityTxResponse` response for Crux REST API at `/entity-tx` endpoint. 12 | /// * `EntityHistoryResponse` response for Crux REST API at `/entity-history`. 13 | /// * `QueryAsyncResponse` is a Future response for a query on Crux REST Api at `/query`, feature `async` is required. 14 | /// 15 | /// Available auxiliary Enums for HTTP in module `types::http`: 16 | /// * Enum [`Action`](../types/http/enum.Action.html) is available in this module. 17 | /// * Enum [`Order`](../types/http/enum.Order.html) is available in this module to be used with `entity_history`. 18 | /// * Enum [`TimeHistory`](../types/http/enum.TimeHistory.html) is available in this module to be used with `entity_history_timed`. 19 | /// 20 | /// It is possible to use `chrono` for time related responses (`TxLogResponse`, `EntityTxResponse`, `EntityHistoryElement`). to use it you need to enable feature `"time". 21 | pub mod types; 22 | 23 | /// Http Client module. It contains the [`HttpClient`](../http/struct.HttpClient.html#impl) for Docker and Standalone HTTP Server. 24 | /// 25 | /// `HttpClient` Contains the following functions: 26 | /// * `tx_log` requests endpoint `/tx-log` via `POST`. A Vector of `types::http::Action` is expected as argument. 27 | /// * `tx_logs` requests endpoint `/tx-log` via `GET`. No args. 28 | /// * `entity` requests endpoint `/entity` via `POST`. A serialized `CruxId`, serialized `Edn::Key` or a String containing a [`keyword`](https://github.com/edn-format/edn#keywords) must be passed as argument. 29 | /// * `entity_timed` similar to `entity`, but receives as arguments `transaction_time: Option>` and `valid_time: Option>,`. 30 | /// * `entity_tx` requests endpoint `/entity-tx` via `POST`. A serialized `CruxId`, serialized `Edn::Key` or a String containing a [`keyword`](https://github.com/edn-format/edn#keywords) must be passed as argument. 31 | /// * `entity_tx_timed` similar to `entity_tx`, but receives as arguments `transaction_time: Option>` and `valid_time: Option>,`. 32 | /// * `entity_history` requests endpoint `/entity-history` via `GET`. Arguments are the `crux.db/id` as a `String`, an ordering argument defined by the enum `types::http::Order` (`Asc` or `Desc`) and a boolean for the `with-docs?` flag (this returns values for the field `:crux.db/doc`). 33 | /// * `entity_history_timed` similar to `entity_history`, but receives one more argument that is a `Vec` to define `valid-time` and `transaction-time` 34 | /// * `query` requests endpoint `/query` via `POST`. Argument is a `query` of the type `Query`. Retrives a Set containing a vector of the values defined by the function `Query::find`. 35 | /// * All endpoints support async calls when `--feature "async"` is enabled, check [`async_<...>` examples](https://github.com/naomijub/transistor/tree/master/examples) for usage. [Tokio runtime](https://docs.rs/tokio/0.2.22/tokio/) is required. 36 | /// 37 | /// Examples can be found in the [examples directory](https://github.com/naomijub/transistor/tree/master/examples). 38 | pub mod http; 39 | 40 | /// This module contains the basic client, struct `Crux`, which configures `host:port` and `authorization`, and returns the needed `client`. 41 | pub mod client; 42 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use reqwest::header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE}; 2 | 3 | use crate::http::HttpClient; 4 | 5 | /// Struct to define parameters to connect to Crux 6 | /// `host` and `port` are required. 7 | /// `authorization` in `HeaderMap` is optional. 8 | pub struct Crux { 9 | host: String, 10 | port: String, 11 | headers: HeaderMap, 12 | } 13 | 14 | impl Crux { 15 | /// Define Crux instance with `host:port` 16 | pub fn new(host: &str, port: &str) -> Self { 17 | let mut headers = HeaderMap::new(); 18 | headers.insert(CONTENT_TYPE, "application/edn".parse().unwrap()); 19 | 20 | Self { 21 | host: host.to_string(), 22 | port: port.to_string(), 23 | headers, 24 | } 25 | } 26 | 27 | /// Function to add `AUTHORIZATION` token to the Crux Client 28 | pub fn with_authorization(mut self, authorization: &str) -> Self { 29 | self.headers 30 | .insert(AUTHORIZATION, authorization.parse().unwrap()); 31 | self 32 | } 33 | 34 | #[cfg(not(test))] 35 | fn uri(&self) -> String { 36 | format!("http://{}:{}", self.host, self.port) 37 | } 38 | 39 | #[cfg(test)] 40 | fn uri(&self) -> String { 41 | use mockito::server_url; 42 | server_url() 43 | } 44 | 45 | /// To query database on Docker/standalone via http it is necessary to use `HttpClient` 46 | #[cfg(not(feature = "async"))] 47 | pub fn http_client(&mut self) -> HttpClient { 48 | HttpClient { 49 | client: reqwest::blocking::Client::new(), 50 | uri: self.uri().clone(), 51 | headers: self.headers.clone(), 52 | } 53 | } 54 | 55 | #[cfg(feature = "async")] 56 | pub fn http_client(&mut self) -> HttpClient { 57 | HttpClient { 58 | client: reqwest::Client::new(), 59 | uri: self.uri().clone(), 60 | headers: self.headers.clone(), 61 | } 62 | } 63 | 64 | /// A mock of `HttpClient` using `mockito = "0.26"`. 65 | #[cfg(feature = "mock")] 66 | pub fn http_mock(&mut self) -> HttpClient { 67 | use mockito::server_url; 68 | 69 | self.headers 70 | .insert(CONTENT_TYPE, "application/edn".parse().unwrap()); 71 | HttpClient { 72 | client: reqwest::blocking::Client::new(), 73 | uri: server_url(), 74 | headers: self.headers.clone(), 75 | } 76 | } 77 | } 78 | 79 | #[cfg(test)] 80 | mod test { 81 | use super::*; 82 | 83 | #[test] 84 | fn new() { 85 | let actual = Crux::new("host", "port"); 86 | let mut headers = HeaderMap::new(); 87 | headers.insert(CONTENT_TYPE, "application/edn".parse().unwrap()); 88 | 89 | let expected = Crux { 90 | host: String::from("host"), 91 | port: String::from("port"), 92 | headers, 93 | }; 94 | 95 | assert_eq!(actual.host, expected.host); 96 | assert_eq!(actual.port, expected.port); 97 | assert_eq!(actual.headers, expected.headers); 98 | } 99 | 100 | #[test] 101 | fn authorization() { 102 | let crux = Crux::new("host", "port").with_authorization("auth"); 103 | let mut headers = HeaderMap::new(); 104 | headers.insert(AUTHORIZATION, "auth".parse().unwrap()); 105 | headers.insert(CONTENT_TYPE, "application/edn".parse().unwrap()); 106 | 107 | assert_eq!(crux.headers, headers); 108 | } 109 | 110 | #[test] 111 | fn uri() { 112 | let crux = Crux::new("localhost", "1234"); 113 | 114 | assert_eq!(crux.uri(), "http://127.0.0.1:1234") 115 | } 116 | 117 | #[test] 118 | fn http_client() { 119 | let mut headers = HeaderMap::new(); 120 | headers.insert(AUTHORIZATION, "auth".parse().unwrap()); 121 | headers.insert(CONTENT_TYPE, "application/edn".parse().unwrap()); 122 | 123 | let actual = Crux::new("127.0.0.1", "1234") 124 | .with_authorization("auth") 125 | .http_client(); 126 | let expected = HttpClient { 127 | client: reqwest::blocking::Client::new(), 128 | uri: "http://127.0.0.1:1234".to_string(), 129 | headers: headers, 130 | }; 131 | 132 | assert_eq!(actual.uri, expected.uri); 133 | assert_eq!(actual.headers, expected.headers); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /examples/async_entity_history_timed.rs: -------------------------------------------------------------------------------- 1 | use chrono::prelude::*; 2 | use edn_derive::Serialize; 3 | use transistor::client::Crux; 4 | use transistor::types::http::{Actions, Order, TimeHistory}; 5 | use transistor::types::response::EntityHistoryResponse; 6 | use transistor::types::CruxId; 7 | 8 | async fn entity_history_timed() -> EntityHistoryResponse { 9 | let person1 = Person { 10 | crux__db___id: CruxId::new("jorge-3"), 11 | first_name: "Michael".to_string(), 12 | last_name: "Jorge".to_string(), 13 | }; 14 | 15 | let person2 = Person { 16 | crux__db___id: CruxId::new("manuel-1"), 17 | first_name: "Diego".to_string(), 18 | last_name: "Manuel".to_string(), 19 | }; 20 | 21 | let client = Crux::new("localhost", "3000").http_client(); 22 | let timed = "2014-11-28T21:00:09-09:00" 23 | .parse::>() 24 | .unwrap(); 25 | 26 | let start_timed = "2013-11-28T21:00:09-09:00" 27 | .parse::>() 28 | .unwrap(); 29 | let end_timed = "2015-11-28T21:00:09-09:00" 30 | .parse::>() 31 | .unwrap(); 32 | let time_history = TimeHistory::ValidTime(Some(start_timed), Some(end_timed)); 33 | 34 | let actions = Actions::new() 35 | .append_put_timed(person1.clone(), timed) 36 | .append_put_timed(person2, timed); 37 | 38 | let _ = Crux::new("localhost", "3000") 39 | .http_client() 40 | .tx_log(actions) 41 | .await 42 | .unwrap(); 43 | 44 | let tx_body = client.entity_tx(person1.crux__db___id).await.unwrap(); 45 | 46 | let entity_history = client 47 | .entity_history_timed( 48 | tx_body.db___id.clone(), 49 | Order::Asc, 50 | true, 51 | vec![time_history], 52 | ) 53 | .await 54 | .unwrap(); 55 | 56 | return entity_history; 57 | } 58 | 59 | #[tokio::main] 60 | async fn main() { 61 | let entity_history = entity_history_timed().await; 62 | println!("{:#?}", entity_history); 63 | // EntityHistoryResponse { 64 | // history: [ 65 | // EntityHistoryElement { 66 | // db___valid_time: 2014-11-28T12:00:09+00:00, 67 | // tx___tx_id: 6, 68 | // tx___tx_time: 2020-08-17T15:21:53.682+00:00, 69 | // db___content_hash: "9d2c7102d6408d465f85b0b35dfb209b34daadd1", 70 | // db__doc: Some( 71 | // Map( 72 | // Map( 73 | // { 74 | // ":crux.db/id": Key( 75 | // ":jorge-3", 76 | // ), 77 | // ":first-name": Str( 78 | // "Michael", 79 | // ), 80 | // ":last-name": Str( 81 | // "Jorge", 82 | // ), 83 | // }, 84 | // ), 85 | // ), 86 | // ), 87 | // }, 88 | // EntityHistoryElement { 89 | // db___valid_time: 2014-11-29T06:00:09+00:00, 90 | // tx___tx_id: 12, 91 | // tx___tx_time: 2020-08-17T18:57:00.044+00:00, 92 | // db___content_hash: "9d2c7102d6408d465f85b0b35dfb209b34daadd1", 93 | // db__doc: Some( 94 | // Map( 95 | // Map( 96 | // { 97 | // ":crux.db/id": Key( 98 | // ":jorge-3", 99 | // ), 100 | // ":first-name": Str( 101 | // "Michael", 102 | // ), 103 | // ":last-name": Str( 104 | // "Jorge", 105 | // ), 106 | // }, 107 | // ), 108 | // ), 109 | // ), 110 | // }, 111 | // ], 112 | // } 113 | } 114 | 115 | #[tokio::test] 116 | async fn test_entity_history() { 117 | let entity = entity_history_timed().await; 118 | assert!(entity.history.len() > 0); 119 | } 120 | 121 | #[derive(Debug, Clone, Serialize)] 122 | #[allow(non_snake_case)] 123 | pub struct Person { 124 | crux__db___id: CruxId, 125 | first_name: String, 126 | last_name: String, 127 | } 128 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/] 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "mock")] 2 | mod integration { 3 | use chrono::prelude::*; 4 | use edn_derive::Serialize; 5 | use mockito::mock; 6 | use transistor::client::Crux; 7 | use transistor::types::http::TimeHistory; 8 | use transistor::types::http::{ActionMock, Actions, Order}; 9 | use transistor::types::CruxId; 10 | 11 | #[test] 12 | fn mock_client() { 13 | let _m = mock("POST", "/tx-log") 14 | .with_status(200) 15 | .match_body("[[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }], [:crux.tx/put { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", }]]") 16 | .with_header("content-type", "text/plain") 17 | .with_body("{:crux.tx/tx-id 8, :crux.tx/tx-time #inst \"2020-07-16T21:53:14.628-00:00\"}") 18 | .create(); 19 | 20 | let body = Crux::new("localhost", "3000") 21 | .http_mock() 22 | .tx_log(actions()) 23 | .unwrap(); 24 | 25 | assert_eq!( 26 | format!("{:?}", body), 27 | String::from("TxLogResponse { tx___tx_id: 8, tx___tx_time: 2020-07-16T21:53:14.628+00:00, tx__event___tx_events: None }") 28 | ); 29 | } 30 | 31 | #[test] 32 | fn chrono() { 33 | let _m = mock("POST", "/tx-log") 34 | .with_status(200) 35 | .match_body("[[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }], [:crux.tx/put { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", }]]") 36 | .with_header("content-type", "text/plain") 37 | .with_body("{:crux.tx/tx-id 8, :crux.tx/tx-time #inst \"2020-07-16T21:53:14.628-00:00\"}") 38 | .create(); 39 | 40 | let body = Crux::new("localhost", "3000") 41 | .http_mock() 42 | .tx_log(actions()) 43 | .unwrap(); 44 | 45 | assert_eq!( 46 | body.tx___tx_time, 47 | "2020-07-16T21:53:14.628-00:00" 48 | .parse::>() 49 | .unwrap() 50 | ); 51 | } 52 | 53 | #[test] 54 | fn entity_history() { 55 | let expected_body = "({:crux.tx/tx-time \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28, :crux.db/valid-time \"2020-07-19T04:12:13.788-00:00\", :crux.db/content-hash \"1828ebf4466f98ea3f5252a58734208cd0414376\"})"; 56 | let _m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false") 57 | .with_status(200) 58 | .with_header("content-type", "application/edn") 59 | .with_body(expected_body) 60 | .create(); 61 | 62 | let body = Crux::new("localhost", "3000") 63 | .http_mock() 64 | .entity_history( 65 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 66 | Order::Asc, 67 | false, 68 | ) 69 | .unwrap(); 70 | 71 | let actual = format!("{:?}", body); 72 | let expected = "EntityHistoryResponse { history: [EntityHistoryElement { db___valid_time: 2020-07-19T04:12:13.788+00:00, tx___tx_id: 28, tx___tx_time: 2020-07-19T04:12:13.788+00:00, db___content_hash: \"1828ebf4466f98ea3f5252a58734208cd0414376\", db__doc: None }] }"; 73 | assert_eq!(actual, expected); 74 | } 75 | 76 | #[test] 77 | fn entity_tx() { 78 | let expected_body = "{:crux.db/id \"d72ccae848ce3a371bd313865cedc3d20b1478ca\", :crux.db/content-hash \"1828ebf4466f98ea3f5252a58734208cd0414376\", :crux.db/valid-time #inst \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-time #inst \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28}"; 79 | let _m = mock("POST", "/entity-tx") 80 | .with_status(200) 81 | .match_body("{:eid :ivan}") 82 | .with_header("content-type", "application/edn") 83 | .with_body(expected_body) 84 | .create(); 85 | 86 | let id = CruxId::new(":ivan"); 87 | let body = Crux::new("localhost", "3000") 88 | .http_mock() 89 | .entity_tx(id) 90 | .unwrap(); 91 | 92 | let actual = format!("{:?}", body); 93 | let expected = "EntityTxResponse { db___id: \"d72ccae848ce3a371bd313865cedc3d20b1478ca\", db___content_hash: \"1828ebf4466f98ea3f5252a58734208cd0414376\", db___valid_time: 2020-07-19T04:12:13.788+00:00, tx___tx_id: 28, tx___tx_time: 2020-07-19T04:12:13.788+00:00 }"; 94 | 95 | assert_eq!(actual, expected); 96 | } 97 | 98 | #[test] 99 | fn match_tx_date_times() { 100 | let date = "2014-11-28T21:00:09+09:00" 101 | .parse::>() 102 | .unwrap(); 103 | let m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false&start-transaction-time=2014-11-28T12:00:09&end-transaction-time=2014-11-28T12:00:09") 104 | .create(); 105 | 106 | let _ = Crux::new("localhost", "3000") 107 | .http_mock() 108 | .entity_history_timed( 109 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 110 | Order::Asc, 111 | false, 112 | vec![TimeHistory::TransactionTime(Some(date), Some(date))], 113 | ); 114 | 115 | m.assert(); 116 | } 117 | 118 | #[test] 119 | fn match_tx_end_date() { 120 | let date = "2014-11-28T21:00:09+09:00" 121 | .parse::>() 122 | .unwrap(); 123 | let m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false&end-transaction-time=2014-11-28T12:00:09") 124 | .create(); 125 | 126 | let _ = Crux::new("localhost", "3000") 127 | .http_mock() 128 | .entity_history_timed( 129 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 130 | Order::Asc, 131 | false, 132 | vec![TimeHistory::TransactionTime(None, Some(date))], 133 | ); 134 | 135 | m.assert(); 136 | } 137 | 138 | #[test] 139 | fn match_valid_start_date() { 140 | let date = "2014-11-28T21:00:09+09:00" 141 | .parse::>() 142 | .unwrap(); 143 | let m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false&start-valid-time=2014-11-28T12:00:09") 144 | .create(); 145 | 146 | let _ = Crux::new("localhost", "3000") 147 | .http_mock() 148 | .entity_history_timed( 149 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 150 | Order::Asc, 151 | false, 152 | vec![TimeHistory::ValidTime(Some(date), None)], 153 | ); 154 | 155 | m.assert(); 156 | } 157 | 158 | #[test] 159 | fn match_none_date() { 160 | let m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false") 161 | .create(); 162 | 163 | let _ = Crux::new("localhost", "3000") 164 | .http_mock() 165 | .entity_history_timed( 166 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 167 | Order::Asc, 168 | false, 169 | vec![TimeHistory::ValidTime(None, None)], 170 | ); 171 | 172 | m.assert(); 173 | } 174 | 175 | #[test] 176 | fn test_actions_eq_actions_mock() { 177 | let actions = test_actions(); 178 | let mock = test_action_mock(); 179 | 180 | assert_eq!(actions, mock); 181 | } 182 | 183 | fn test_action_mock() -> Vec { 184 | let person1 = Person { 185 | crux__db___id: CruxId::new("jorge-3"), 186 | first_name: "Michael".to_string(), 187 | last_name: "Jorge".to_string(), 188 | }; 189 | 190 | let person2 = Person { 191 | crux__db___id: CruxId::new("manuel-1"), 192 | first_name: "Diego".to_string(), 193 | last_name: "Manuel".to_string(), 194 | }; 195 | 196 | vec![ 197 | ActionMock::Put(edn_rs::to_string(person1.clone()), None), 198 | ActionMock::Put(edn_rs::to_string(person2), None), 199 | ActionMock::Delete(edn_rs::to_string(person1.crux__db___id), None), 200 | ] 201 | } 202 | 203 | fn test_actions() -> Actions { 204 | let person1 = Person { 205 | crux__db___id: CruxId::new("jorge-3"), 206 | first_name: "Michael".to_string(), 207 | last_name: "Jorge".to_string(), 208 | }; 209 | actions().append_delete(person1.crux__db___id) 210 | } 211 | 212 | fn actions() -> Actions { 213 | let person1 = Person { 214 | crux__db___id: CruxId::new("jorge-3"), 215 | first_name: "Michael".to_string(), 216 | last_name: "Jorge".to_string(), 217 | }; 218 | 219 | let person2 = Person { 220 | crux__db___id: CruxId::new("manuel-1"), 221 | first_name: "Diego".to_string(), 222 | last_name: "Manuel".to_string(), 223 | }; 224 | 225 | Actions::new().append_put(person1).append_put(person2) 226 | } 227 | 228 | #[derive(Debug, Clone, Serialize)] 229 | #[allow(non_snake_case)] 230 | pub struct Person { 231 | crux__db___id: CruxId, 232 | first_name: String, 233 | last_name: String, 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/types/response.rs: -------------------------------------------------------------------------------- 1 | use crate::types::error::CruxError; 2 | use chrono::prelude::*; 3 | use edn_rs::{Deserialize, Edn, EdnError}; 4 | use std::collections::BTreeSet; 5 | use std::str::FromStr; 6 | 7 | #[derive(Debug, PartialEq, Clone)] 8 | #[allow(non_snake_case)] 9 | /// Definition for the response of a `POST` at `tx-log` endpoint 10 | pub struct TxLogResponse { 11 | pub tx___tx_id: usize, 12 | #[cfg(feature = "time_as_str")] 13 | pub tx___tx_time: String, 14 | #[cfg(not(feature = "time_as_str"))] 15 | pub tx___tx_time: DateTime, 16 | pub tx__event___tx_events: Option>>, 17 | } 18 | 19 | impl Deserialize for TxLogResponse { 20 | fn deserialize(edn: &Edn) -> Result { 21 | #[cfg(not(feature = "time_as_str"))] 22 | let tx_time: String = edn_rs::from_edn(&edn[":crux.tx/tx-time"])?; 23 | 24 | Ok(Self { 25 | tx___tx_id: edn_rs::from_edn(&edn[":crux.tx/tx-id"]).unwrap_or(0usize), 26 | #[cfg(feature = "time_as_str")] 27 | tx___tx_time: edn_rs::from_edn(&edn[":crux.tx/tx-time"])?, 28 | #[cfg(not(feature = "time_as_str"))] 29 | tx___tx_time: tx_time 30 | .parse::>() 31 | .map_err(|_| EdnError::Deserialize("Unable to deserialize `:crux.tx/tx-time`, verify if the transaction time you're sending is correct".to_string()))?, 32 | tx__event___tx_events: edn_rs::from_edn(&edn[":crux.tx.event/tx-events"])?, 33 | }) 34 | } 35 | } 36 | 37 | impl TxLogResponse { 38 | #[cfg(test)] 39 | pub fn default() -> Self { 40 | Self { 41 | tx___tx_id: 8usize, 42 | tx___tx_time: "2020-07-16T21:53:14.628-00:00" 43 | .parse::>() 44 | .unwrap(), 45 | tx__event___tx_events: None, 46 | } 47 | } 48 | } 49 | 50 | #[derive(Debug, PartialEq, Clone)] 51 | #[allow(non_snake_case)] 52 | /// Definition for the response of a `GET` at `tx-log` endpoint 53 | pub struct TxLogsResponse { 54 | pub tx_events: Vec, 55 | } 56 | 57 | impl FromStr for TxLogsResponse { 58 | type Err = CruxError; 59 | fn from_str(resp: &str) -> Result { 60 | let clean_edn = resp.replace("#crux/id", "").replace("#inst", ""); 61 | edn_rs::from_str(&clean_edn).map_err(|e| e.into()) 62 | } 63 | } 64 | 65 | impl Deserialize for TxLogsResponse { 66 | fn deserialize(edn: &Edn) -> Result { 67 | Ok(Self { 68 | tx_events: edn 69 | .iter() 70 | .ok_or(EdnError::Deserialize(format!( 71 | "The following Edn cannot be deserialized to TxLogs: {:?}", 72 | edn 73 | )))? 74 | .map(edn_rs::from_edn) 75 | .collect::, EdnError>>()?, 76 | }) 77 | } 78 | } 79 | 80 | #[derive(Debug, PartialEq, Clone)] 81 | #[allow(non_snake_case)] 82 | /// Definition for the response of a `POST` at `/entity-tx` endpoint 83 | pub struct EntityTxResponse { 84 | pub db___id: String, 85 | pub db___content_hash: String, 86 | #[cfg(feature = "time_as_str")] 87 | pub db___valid_time: String, 88 | #[cfg(not(feature = "time_as_str"))] 89 | pub db___valid_time: DateTime, 90 | pub tx___tx_id: usize, 91 | #[cfg(feature = "time_as_str")] 92 | pub tx___tx_time: String, 93 | #[cfg(not(feature = "time_as_str"))] 94 | pub tx___tx_time: DateTime, 95 | } 96 | 97 | impl FromStr for EntityTxResponse { 98 | type Err = CruxError; 99 | fn from_str(resp: &str) -> Result { 100 | let clean_edn = resp.replace("#crux/id", ""); 101 | edn_rs::from_str(&clean_edn).map_err(|e| e.into()) 102 | } 103 | } 104 | 105 | impl EntityTxResponse { 106 | #[cfg(test)] 107 | pub fn default() -> Self { 108 | Self { 109 | db___id: "d72ccae848ce3a371bd313865cedc3d20b1478ca".to_string(), 110 | db___content_hash: "1828ebf4466f98ea3f5252a58734208cd0414376".to_string(), 111 | db___valid_time: "2020-07-19T04:12:13.788-00:00" 112 | .parse::>() 113 | .unwrap(), 114 | tx___tx_id: 28usize, 115 | tx___tx_time: "2020-07-19T04:12:13.788-00:00" 116 | .parse::>() 117 | .unwrap(), 118 | } 119 | } 120 | } 121 | 122 | impl Deserialize for EntityTxResponse { 123 | fn deserialize(edn: &Edn) -> Result { 124 | #[cfg(not(feature = "time_as_str"))] 125 | let valid_time: String = edn_rs::from_edn(&edn[":crux.db/valid-time"])?; 126 | #[cfg(not(feature = "time_as_str"))] 127 | let tx_time: String = edn_rs::from_edn(&edn[":crux.tx/tx-time"])?; 128 | 129 | Ok(Self { 130 | db___id: edn_rs::from_edn(&edn[":crux.db/id"])?, 131 | db___content_hash: edn_rs::from_edn(&edn[":crux.db/content-hash"])?, 132 | #[cfg(feature = "time_as_str")] 133 | db___valid_time: edn_rs::from_edn(&edn[":crux.db/valid-time"]), 134 | #[cfg(not(feature = "time_as_str"))] 135 | db___valid_time: valid_time.parse::>().unwrap(), 136 | tx___tx_id: edn_rs::from_edn(&edn[":crux.tx/tx-id"]).unwrap_or(0usize), 137 | #[cfg(feature = "time_as_str")] 138 | tx___tx_time: edn_rs::from_edn(&edn[":crux.tx/tx-time"]), 139 | #[cfg(not(feature = "time_as_str"))] 140 | tx___tx_time: tx_time.parse::>().unwrap(), 141 | }) 142 | } 143 | } 144 | 145 | #[doc(hidden)] 146 | #[cfg(not(feature = "async"))] 147 | pub(crate) struct QueryResponse(pub(crate) BTreeSet>); 148 | 149 | #[cfg(not(feature = "async"))] 150 | impl Deserialize for QueryResponse { 151 | fn deserialize(edn: &Edn) -> Result { 152 | if edn.set_iter().is_some() { 153 | Ok(Self( 154 | edn.set_iter() 155 | .ok_or(EdnError::Deserialize(format!( 156 | "The following Edn cannot be deserialized to BTreeSet: {:?}", 157 | edn 158 | )))? 159 | .map(|e| { 160 | e.to_vec().ok_or(EdnError::Deserialize(format!( 161 | "The following Edn cannot be deserialized to Vec: {:?}", 162 | edn 163 | ))) 164 | }) 165 | .collect::>, EdnError>>()?, 166 | )) 167 | } else { 168 | Ok(Self( 169 | edn.iter() 170 | .ok_or(EdnError::Deserialize(format!( 171 | "The following Edn cannot be deserialized to BTreeSet: {:?}", 172 | edn 173 | )))? 174 | .map(|e| { 175 | e.to_vec().ok_or(EdnError::Deserialize(format!( 176 | "The following Edn cannot be deserialized to Vec: {:?}", 177 | edn 178 | ))) 179 | }) 180 | .collect::>, EdnError>>()?, 181 | )) 182 | } 183 | } 184 | } 185 | 186 | #[cfg(feature = "async")] 187 | #[derive(Clone, Debug, PartialEq)] 188 | /// When feature `async` is enabled this is the response type for endpoint `/query`. 189 | pub struct QueryAsyncResponse(pub(crate) BTreeSet>); 190 | 191 | #[cfg(feature = "async")] 192 | impl Deserialize for QueryAsyncResponse { 193 | fn deserialize(edn: &Edn) -> Result { 194 | if edn.set_iter().is_some() { 195 | Ok(Self { 196 | 0: edn 197 | .set_iter() 198 | .ok_or(EdnError::Deserialize(format!( 199 | "The following Edn cannot be deserialize to BTreeSet: {:?}", 200 | edn 201 | )))? 202 | .map(|e| { 203 | e.to_vec().ok_or(EdnError::Deserialize(format!( 204 | "The following Edn cannot be deserialized to Vec: {:?}", 205 | edn 206 | ))) 207 | }) 208 | .collect::>, EdnError>>()?, 209 | }) 210 | } else { 211 | Ok(Self { 212 | 0: edn 213 | .iter() 214 | .ok_or(EdnError::Deserialize(format!( 215 | "The following Edn cannot be deserialize to BTreeSet: {:?}", 216 | edn 217 | )))? 218 | .map(|e| { 219 | e.to_vec().ok_or(EdnError::Deserialize(format!( 220 | "The following Edn cannot be deserialized to Vec: {:?}", 221 | edn 222 | ))) 223 | }) 224 | .collect::>, EdnError>>()?, 225 | }) 226 | } 227 | } 228 | } 229 | 230 | #[derive(Debug, PartialEq, Clone)] 231 | #[allow(non_snake_case)] 232 | pub struct EntityHistoryElement { 233 | #[cfg(feature = "time_as_str")] 234 | pub db___valid_time: String, 235 | #[cfg(not(feature = "time_as_str"))] 236 | pub db___valid_time: DateTime, 237 | pub tx___tx_id: usize, 238 | #[cfg(feature = "time_as_str")] 239 | pub tx___tx_time: String, 240 | #[cfg(not(feature = "time_as_str"))] 241 | pub tx___tx_time: DateTime, 242 | pub db___content_hash: String, 243 | pub db__doc: Option, 244 | } 245 | 246 | impl Deserialize for EntityHistoryElement { 247 | fn deserialize(edn: &Edn) -> Result { 248 | #[cfg(not(feature = "time_as_str"))] 249 | let valid_time: String = edn_rs::from_edn(&edn[":crux.db/valid-time"])?; 250 | #[cfg(not(feature = "time_as_str"))] 251 | let tx_time: String = edn_rs::from_edn(&edn[":crux.tx/tx-time"])?; 252 | 253 | Ok(Self { 254 | db___content_hash: edn_rs::from_edn(&edn[":crux.db/content-hash"])?, 255 | #[cfg(feature = "time_as_str")] 256 | db___valid_time: edn_rs::from_edn(&edn[":crux.db/valid-time"])?, 257 | #[cfg(not(feature = "time_as_str"))] 258 | db___valid_time: valid_time.parse::>().unwrap(), 259 | tx___tx_id: edn_rs::from_edn(&edn[":crux.tx/tx-id"]).unwrap_or(0usize), 260 | #[cfg(feature = "time_as_str")] 261 | tx___tx_time: edn_rs::from_edn(&edn[":crux.tx/tx-time"])?, 262 | #[cfg(not(feature = "time_as_str"))] 263 | tx___tx_time: tx_time.parse::>().unwrap(), 264 | db__doc: edn.get(":crux.db/doc").map(|d| d.to_owned()), 265 | }) 266 | } 267 | } 268 | 269 | #[cfg(test)] 270 | impl EntityHistoryElement { 271 | pub fn default() -> Self { 272 | Self { 273 | db___content_hash: "1828ebf4466f98ea3f5252a58734208cd0414376".to_string(), 274 | db___valid_time: "2020-07-19T04:12:13.788-00:00" 275 | .parse::>() 276 | .unwrap(), 277 | tx___tx_id: 28usize, 278 | tx___tx_time: "2020-07-19T04:12:13.788-00:00" 279 | .parse::>() 280 | .unwrap(), 281 | db__doc: None, 282 | } 283 | } 284 | 285 | pub fn default_docs() -> Self { 286 | Self { 287 | db___content_hash: "1828ebf4466f98ea3f5252a58734208cd0414376".to_string(), 288 | db___valid_time: "2020-07-19T04:12:13.788-00:00" 289 | .parse::>() 290 | .unwrap(), 291 | tx___tx_id: 28usize, 292 | tx___tx_time: "2020-07-19T04:12:13.788-00:00" 293 | .parse::>() 294 | .unwrap(), 295 | db__doc: Some(Edn::Key(":docs".to_string())), 296 | } 297 | } 298 | } 299 | 300 | /// Definition for the response of a `GET` at `/entity-history` endpoint. This returns a Vec of `EntityHistoryElement`. 301 | #[derive(Debug, PartialEq, Clone)] 302 | pub struct EntityHistoryResponse { 303 | pub history: Vec, 304 | } 305 | 306 | impl FromStr for EntityHistoryResponse { 307 | type Err = CruxError; 308 | fn from_str(resp: &str) -> Result { 309 | let clean_edn = resp.replace("#crux/id", "").replace("#inst", ""); 310 | edn_rs::from_str(&clean_edn).map_err(|e| e.into()) 311 | } 312 | } 313 | 314 | impl Deserialize for EntityHistoryResponse { 315 | fn deserialize(edn: &Edn) -> Result { 316 | Ok(Self { 317 | history: edn 318 | .iter() 319 | .ok_or(EdnError::Deserialize(format!( 320 | "The following Edn cannot be deserialize to entity-history: {:?}", 321 | edn 322 | )))? 323 | .map(edn_rs::from_edn) 324 | .collect::, EdnError>>()?, 325 | }) 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /src/types/http.rs: -------------------------------------------------------------------------------- 1 | use crate::types::CruxId; 2 | use chrono::prelude::*; 3 | use edn_rs::Serialize; 4 | 5 | static ACTION_DATE_FORMAT: &'static str = "%Y-%m-%dT%H:%M:%S%Z"; 6 | static DATETIME_FORMAT: &'static str = "%Y-%m-%dT%H:%M:%S"; 7 | 8 | #[derive(Debug, PartialEq, Clone)] 9 | pub(crate) enum Action { 10 | Put(String, Option>), 11 | Delete(String, Option>), 12 | Evict(String), 13 | Match(String, String, Option>), 14 | } 15 | 16 | /// Test enum to test and debug `Actions`. Implements `PartialEq` with `Actions` 17 | #[cfg(feature = "mock")] 18 | #[derive(Debug, PartialEq)] 19 | pub enum ActionMock { 20 | Put(String, Option>), 21 | Delete(String, Option>), 22 | Evict(String), 23 | Match(String, String, Option>), 24 | } 25 | 26 | /// Actions to perform in Crux. It is a builder struct to help you create a `Vec` for `tx_log`. 27 | /// 28 | /// Allowed actions: 29 | /// * `PUT` - Write a version of a document. Functions are `append_put` and `append_put_timed`. 30 | /// * `Delete` - Deletes the specific document at a given valid time. Functions are `append_delete` and `append_delete_timed`. 31 | /// * `Evict` - Evicts a document entirely, including all historical versions (receives only the ID to evict). Function is `append_evict`. 32 | /// * `Match` - Matches the current state of an entity, if the state doesn't match the provided document, the transaction will not continue. Functions are `append_match` and `append_match_timed`. 33 | #[derive(Debug, PartialEq, Clone)] 34 | pub struct Actions { 35 | actions: Vec, 36 | } 37 | 38 | impl Actions { 39 | pub fn new() -> Self { 40 | Self { 41 | actions: Vec::new(), 42 | } 43 | } 44 | 45 | pub(crate) fn is_empty(&self) -> bool { 46 | self.actions.is_empty() 47 | } 48 | 49 | /// Appends an `Action::Put` enforcing types for `action` field to be a `T: Serialize` 50 | pub fn append_put(mut self, action: T) -> Self { 51 | self.actions.push(Action::put(action)); 52 | self 53 | } 54 | 55 | /// Appends an `Action::Put` that includes `date` enforcing types for `action` field to be a `T: Serialize` and `date` to be `DateTime`. 56 | pub fn append_put_timed( 57 | mut self, 58 | action: T, 59 | date: DateTime, 60 | ) -> Self { 61 | self.actions.push(Action::put(action).with_valid_date(date)); 62 | self 63 | } 64 | 65 | /// Appends an `Action::Delete` enforcing types for `id` field to be a `CruxId` 66 | pub fn append_delete(mut self, id: CruxId) -> Self { 67 | self.actions.push(Action::delete(id)); 68 | self 69 | } 70 | 71 | /// Appends an `Action::Delete` that includes `date` enforcing types for `id` field to be a `CruxId` and `date` to be `DateTime`. 72 | pub fn append_delete_timed(mut self, id: CruxId, date: DateTime) -> Self { 73 | self.actions.push(Action::delete(id).with_valid_date(date)); 74 | self 75 | } 76 | 77 | /// Appends an `Action::Evict` enforcing types for `id` field to be a `CruxId` 78 | pub fn append_evict(mut self, id: CruxId) -> Self { 79 | self.actions.push(Action::evict(id)); 80 | self 81 | } 82 | 83 | /// Appends an `Action::Match` enforcing types for `id` field to be a `CruxId` and `action` field to be a `T: Serialize` 84 | pub fn append_match_doc(mut self, id: CruxId, action: T) -> Self { 85 | self.actions.push(Action::match_doc(id, action)); 86 | self 87 | } 88 | 89 | /// Appends an `Action::Match` that includes `date` enforcing types for `id` field to be a `CruxId`, `action` field to be a `T: Serialize` and `date` to be `DateTime`. 90 | pub fn append_match_doc_timed( 91 | mut self, 92 | id: CruxId, 93 | action: T, 94 | date: DateTime, 95 | ) -> Self { 96 | self.actions 97 | .push(Action::match_doc(id, action).with_valid_date(date)); 98 | self 99 | } 100 | 101 | pub(crate) fn build(self) -> String { 102 | edn_rs::to_string(self.actions) 103 | } 104 | } 105 | 106 | impl Action { 107 | fn put(action: T) -> Action { 108 | Action::Put(edn_rs::to_string(action), None) 109 | } 110 | 111 | fn with_valid_date(self, date: DateTime) -> Action { 112 | match self { 113 | Action::Put(action, _) => Action::Put(action, Some(date)), 114 | Action::Delete(action, _) => Action::Delete(action, Some(date)), 115 | Action::Match(id, action, _) => Action::Match(id, action, Some(date)), 116 | action => action, 117 | } 118 | } 119 | 120 | fn delete(id: CruxId) -> Action { 121 | Action::Delete(edn_rs::to_string(id), None) 122 | } 123 | 124 | fn evict(id: CruxId) -> Action { 125 | Action::Evict(edn_rs::to_string(id)) 126 | } 127 | 128 | fn match_doc(id: CruxId, action: T) -> Action { 129 | Action::Match(edn_rs::to_string(id), edn_rs::to_string(action), None) 130 | } 131 | } 132 | 133 | impl Serialize for Action { 134 | fn serialize(self) -> String { 135 | match self { 136 | Action::Put(edn, None) => format!("[:crux.tx/put {}]", edn), 137 | Action::Put(edn, Some(date)) => format!( 138 | "[:crux.tx/put {} #inst \"{}\"]", 139 | edn, 140 | date.format(ACTION_DATE_FORMAT).to_string() 141 | ), 142 | Action::Delete(id, None) => format!("[:crux.tx/delete {}]", id), 143 | Action::Delete(id, Some(date)) => format!( 144 | "[:crux.tx/delete {} #inst \"{}\"]", 145 | id, 146 | date.format(ACTION_DATE_FORMAT).to_string() 147 | ), 148 | Action::Evict(id) => { 149 | if id.starts_with(":") { 150 | format!("[:crux.tx/evict {}]", id) 151 | } else { 152 | "".to_string() 153 | } 154 | } 155 | Action::Match(id, edn, None) => format!("[:crux.tx/match {} {}]", id, edn), 156 | Action::Match(id, edn, Some(date)) => format!( 157 | "[:crux.tx/match {} {} #inst \"{}\"]", 158 | id, 159 | edn, 160 | date.format(ACTION_DATE_FORMAT).to_string() 161 | ), 162 | } 163 | } 164 | } 165 | 166 | /// `Order` enum to define how the `entity_history` response will be ordered. Options are `Asc` and `Desc`. 167 | #[derive(Debug, PartialEq)] 168 | pub enum Order { 169 | Asc, 170 | Desc, 171 | } 172 | 173 | impl Serialize for Order { 174 | fn serialize(self) -> String { 175 | match self { 176 | Order::Asc => String::from("asc"), 177 | Order::Desc => String::from("desc"), 178 | } 179 | } 180 | } 181 | 182 | /// enum `TimeHistory` is used as an argument in the function `entity_history_timed`. It is responsible for defining `valid-time` and `transaction-times` ranges for the query. 183 | /// The possible options are `ValidTime` and `TransactionTime`, both of them receive two `Option>`. The first parameter will transform into an start time and the second into and end-time, and they will be formated as `%Y-%m-%dT%H:%M:%S`. 184 | /// The query params will become: 185 | /// * ValidTime(Some(start), Some(end)) => "&start-valid-time={}&end-valid-time={}" 186 | /// * ValidTime(None, Some(end)) => "&end-valid-time={}" 187 | /// * ValidTime(Some(start), None) => "&start-valid-time={}" 188 | /// * ValidTime(None, None) => "", 189 | /// * TransactionTime(Some(start), Some(end)) => "&start-transaction-time={}&end-transaction-time={}" 190 | /// * TransactionTime(None, Some(end)) => "&end-transaction-time={}" 191 | /// * TransactionTime(Some(start), None) => "&start-transaction-time={}" 192 | /// * TransactionTime(None, None) => "", 193 | #[derive(Debug, PartialEq)] 194 | pub enum TimeHistory { 195 | ValidTime(Option>, Option>), 196 | TransactionTime(Option>, Option>), 197 | } 198 | 199 | impl Serialize for TimeHistory { 200 | fn serialize(self) -> String { 201 | use crate::types::http::TimeHistory::TransactionTime; 202 | use crate::types::http::TimeHistory::ValidTime; 203 | 204 | match self { 205 | ValidTime(Some(start), Some(end)) => format!( 206 | "&start-valid-time={}&end-valid-time={}", 207 | start.format(DATETIME_FORMAT).to_string(), 208 | end.format(DATETIME_FORMAT).to_string() 209 | ), 210 | ValidTime(None, Some(end)) => format!( 211 | "&end-valid-time={}", 212 | end.format(DATETIME_FORMAT).to_string() 213 | ), 214 | ValidTime(Some(start), None) => format!( 215 | "&start-valid-time={}", 216 | start.format(DATETIME_FORMAT).to_string() 217 | ), 218 | ValidTime(None, None) => format!(""), 219 | 220 | TransactionTime(Some(start), Some(end)) => format!( 221 | "&start-transaction-time={}&end-transaction-time={}", 222 | start.format(DATETIME_FORMAT).to_string(), 223 | end.format(DATETIME_FORMAT).to_string() 224 | ), 225 | TransactionTime(None, Some(end)) => format!( 226 | "&end-transaction-time={}", 227 | end.format(DATETIME_FORMAT).to_string() 228 | ), 229 | TransactionTime(Some(start), None) => format!( 230 | "&start-transaction-time={}", 231 | start.format(DATETIME_FORMAT).to_string() 232 | ), 233 | TransactionTime(None, None) => format!(""), 234 | } 235 | } 236 | } 237 | 238 | #[doc(hidden)] 239 | pub trait VecSer { 240 | fn serialize(self) -> String; 241 | } 242 | #[doc(hidden)] 243 | impl VecSer for Vec { 244 | fn serialize(self) -> String { 245 | if self.len() > 2 || self.len() == 0 { 246 | String::new() 247 | } else { 248 | self.into_iter() 249 | .map(edn_rs::to_string) 250 | .collect::>() 251 | .join("") 252 | } 253 | } 254 | } 255 | 256 | #[cfg(feature = "mock")] 257 | impl std::cmp::PartialEq> for Actions { 258 | fn eq(&self, other: &Vec) -> bool { 259 | self.actions 260 | .iter() 261 | .zip(other.iter()) 262 | .map(|(acs, acm)| match (acs, acm) { 263 | (Action::Put(ap, tp), ActionMock::Put(am, tm)) if ap == am && tp == tm => true, 264 | (Action::Evict(id), ActionMock::Evict(idm)) if id == idm => true, 265 | (Action::Delete(id, tp), ActionMock::Delete(idm, tm)) if id == idm && tp == tm => { 266 | true 267 | } 268 | (Action::Match(id, a, tp), ActionMock::Match(idm, am, tm)) 269 | if id == idm && a == am && tp == tm => 270 | { 271 | true 272 | } 273 | _ => false, 274 | }) 275 | .fold(true, |acc, e| acc && e) 276 | } 277 | } 278 | 279 | #[cfg(test)] 280 | mod tests { 281 | use super::*; 282 | use crate::types::CruxId; 283 | use edn_derive::Serialize; 284 | 285 | #[test] 286 | fn actions() { 287 | let person1 = Person { 288 | crux__db___id: CruxId::new("jorge-3"), 289 | first_name: "Michael".to_string(), 290 | last_name: "Jorge".to_string(), 291 | }; 292 | 293 | let person2 = Person { 294 | crux__db___id: CruxId::new("manuel-1"), 295 | first_name: "Diego".to_string(), 296 | last_name: "Manuel".to_string(), 297 | }; 298 | 299 | let person3 = Person { 300 | crux__db___id: CruxId::new("manuel-1"), 301 | first_name: "Diego".to_string(), 302 | last_name: "Manuel".to_string(), 303 | }; 304 | 305 | let timed = "2014-11-28T21:00:09-09:00" 306 | .parse::>() 307 | .unwrap(); 308 | 309 | let actions = Actions::new() 310 | .append_put_timed(person1.clone(), timed) 311 | .append_put(person2.clone()) 312 | .append_evict(person1.crux__db___id) 313 | .append_delete(person2.crux__db___id) 314 | .append_match_doc(person3.clone().crux__db___id, person3); 315 | 316 | assert_eq!(actions.clone(), expected_actions()); 317 | } 318 | 319 | fn expected_actions() -> Actions { 320 | let person1 = Person { 321 | crux__db___id: CruxId::new("jorge-3"), 322 | first_name: "Michael".to_string(), 323 | last_name: "Jorge".to_string(), 324 | }; 325 | 326 | let person2 = Person { 327 | crux__db___id: CruxId::new("manuel-1"), 328 | first_name: "Diego".to_string(), 329 | last_name: "Manuel".to_string(), 330 | }; 331 | 332 | let person3 = Person { 333 | crux__db___id: CruxId::new("manuel-1"), 334 | first_name: "Diego".to_string(), 335 | last_name: "Manuel".to_string(), 336 | }; 337 | 338 | Actions { 339 | actions: vec![ 340 | Action::Put( 341 | person1.clone().serialize(), 342 | Some( 343 | "2014-11-28T21:00:09-09:00" 344 | .parse::>() 345 | .unwrap(), 346 | ), 347 | ), 348 | Action::Put(person2.clone().serialize(), None), 349 | Action::Evict(person1.crux__db___id.serialize()), 350 | Action::Delete(person2.crux__db___id.serialize(), None), 351 | Action::Match( 352 | person3.clone().crux__db___id.serialize(), 353 | person3.serialize(), 354 | None, 355 | ), 356 | ], 357 | } 358 | } 359 | 360 | #[derive(Debug, Clone, Serialize)] 361 | #[allow(non_snake_case)] 362 | pub struct Person { 363 | crux__db___id: CruxId, 364 | first_name: String, 365 | last_name: String, 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Transistor 2 | 3 | 4 | A Rust Crux Client crate/lib. For now, this crate intends to support 2 ways to interact with Crux: 5 | 6 | - [x] Via `Docker` with a [`crux-standalone`](https://opencrux.com/reference/building.html#_docker) version [docker-hub](https://hub.docker.com/r/juxt/crux-standalone). Current Docker image `juxt/crux-standalone:20.09-1.11.0`. 7 | - [x] Via [`HTTP`](https://opencrux.com/reference/http.html#start-http-server) using the [`HTTP API`](https://opencrux.com/reference/http.html#http-api). 8 | - [x] Async support. 9 | 10 | * [**Crux Getting Started**](https://opencrux.com/reference/get-started.html) 11 | * [**Crux FAQs**](https://opencrux.com/about/faq.html) 12 | * For examples on usage, please refer to [examples directory](https://github.com/naomijub/transistor/tree/master/examples) or to the [`ATM Crux`](https://github.com/naomijub/atm-crux) for more complete and interactive example. 13 | * supported version is currently at `20.09-1.11.0`. Docker standalone newer versions are required to upgrade the code. 14 | 15 | ## Bitemporal Crux 16 | 17 | Crux is optimised for efficient and globally consistent point-in-time queries using a pair of transaction-time and valid-time timestamps. 18 | 19 | Ad-hoc systems for bitemporal recordkeeping typically rely on explicitly tracking either valid-from and valid-to timestamps or range types directly within relations. The bitemporal document model that Crux provides is very simple to reason about and it is universal across the entire database, therefore it does not require you to consider which historical information is worth storing in special "bitemporal tables" upfront. 20 | 21 | One or more documents may be inserted into Crux via a put transaction at a specific valid-time, defaulting to the transaction time (i.e. now), and each document remains valid until explicitly updated with a new version via put or deleted via delete. 22 | 23 | ### Why? 24 | 25 | | Time | Purpose | 26 | |- |- | 27 | | transaction-time | Used for audit purposes, technical requirements such as event sourcing. | 28 | | valid-time | Used for querying data across time, historical analysis. | 29 | 30 | `transaction-time` represents the point at which data arrives into the database. This gives us an audit trail and we can see what the state of the database was at a particular point in time. You cannot write a new transaction with a transaction-time that is in the past. 31 | 32 | `valid-time` is an arbitrary time that can originate from an upstream system, or by default is set to transaction-time. Valid time is what users will typically use for query purposes. 33 | 34 | Reference [crux bitemporality](https://opencrux.com/about/bitemporality.html) and [value of bitemporality](https://juxt.pro/blog/posts/value-of-bitemporality.html) 35 | 36 | ## Usage 37 | 38 | To add this crate to your project you should add one of the following line to your `dependencies` field in `Cargo.toml`: 39 | > 40 | > ``` 41 | > [dependencies] 42 | > transistor = "2.1.2" 43 | > ``` 44 | 45 | ## Creating a Crux Client 46 | All operations with Transistor start in the module `client` with `Crux::new("localhost", "3000")`. The struct `Crux` is responsabile for defining request `HeadersMap` and the request `URL`. The `URL` definition is required and it is done by the static function `new`, which receives as argument a `host` and a `port` and returns a `Crux` instance. To change `HeadersMap` info so that you can add `AUTHORIZATION` you can use the function `with_authorization` that receives as argument the authorization token and mutates the `Crux` instance. 47 | * `HeaderMap` already contains the header `Content-Type: application/edn`. 48 | 49 | Finally, to create a Crux Client the function `_client` should be called, for example `http_client`. This function returns a struct that contains all possible implementarions to query Crux Docker and Standalone HTTP Server. 50 | ```rust 51 | use transistor::client::Crux; 52 | 53 | // HttpClient with AUTHORIZATION 54 | let auth_client = Crux::new("127.0.0.1","3000").with_authorization("my-auth-token").http_client(); 55 | 56 | // HttpClient without AUTHORIZATION 57 | let client = Crux::new("127.0.0.1","3000").http_client(); 58 | ``` 59 | 60 | ## Http Client 61 | Once you have called `http_client` you will have an instance of the `HttpClient` struct which has a bunch of functions to query Crux on Docker and Standalone HTTP Server: 62 | 63 | * [`state`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.state) queries endpoint [`/`](https://opencrux.com/reference/http.html#home) with a `GET`. No args. Returns various details about the state of the database. 64 | ```rust 65 | let body = client.state().unwrap(); 66 | 67 | // StateResponse { 68 | // index___index_version: 5, 69 | // doc_log___consumer_state: None, 70 | // tx_log___consumer_state: None, 71 | // kv___kv_store: "crux.kv.rocksdb.RocksKv", 72 | // kv___estimate_num_keys: 56, 73 | // kv___size: 2271042 74 | // } 75 | ``` 76 | 77 | * [`tx_log`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.tx_log) requests endpoint [`/tx-log`](https://opencrux.com/reference/http.html#tx-log-post) via `POST`. `Actions` is expected as argument. The "write" endpoint, to post transactions. 78 | ```rust 79 | use transistor::http::{Actions}; 80 | use transistor::client::Crux; 81 | use transistor::types::{CruxId}; 82 | 83 | let person1 = Person { 84 | crux__db___id: CruxId::new("jorge-3"), 85 | .. 86 | }; 87 | 88 | let person2 = Person { 89 | crux__db___id: CruxId::new("manuel-1"), 90 | .. 91 | }; 92 | 93 | let actions = Actions::new() 94 | .append_put(person1) 95 | .append_put(person2); 96 | 97 | let body = client.tx_log(actions).unwrap(); 98 | // {:crux.tx/tx-id 7, :crux.tx/tx-time #inst \"2020-07-16T21:50:39.309-00:00\"} 99 | ``` 100 | 101 | * [`tx_logs`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.tx_logs) requests endpoint [`/tx-log`](https://opencrux.com/reference/http.html#tx-log) via `GET`. No args. Returns a list of all transactions. 102 | ```rust 103 | use transistor::client::Crux; 104 | 105 | let body = client.tx_logs().unwrap(); 106 | 107 | // TxLogsResponse { 108 | // tx_events: [ 109 | // TxLogResponse { 110 | // tx___tx_id: 0, 111 | // tx___tx_time: 2020-07-09T23:38:06.465-00:00, 112 | // tx__event___tx_events: Some( 113 | // [ 114 | // [ 115 | // ":crux.tx/put", 116 | // "a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e", 117 | // "125d29eb3bed1bf51d64194601ad4ff93defe0e2", 118 | // ], 119 | // ], 120 | // ), 121 | // }, 122 | // TxLogResponse { 123 | // tx___tx_id: 1, 124 | // tx___tx_time: 2020-07-09T23:39:33.815-00:00, 125 | // tx__event___tx_events: Some( 126 | // [ 127 | // [ 128 | // ":crux.tx/put", 129 | // "a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e", 130 | // "1b42e0d5137e3833423f7bb958622bee29f91eee", 131 | // ], 132 | // ], 133 | // ), 134 | // }, 135 | // ... 136 | // ] 137 | // } 138 | ``` 139 | 140 | * [`entity`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.entity) requests endpoint [`/entity`](https://opencrux.com/reference/http.html#entity) via `POST`. A serialized `CruxId`, serialized `Edn::Key` or a String containing a [`keyword`](https://github.com/edn-format/edn#keywords) must be passed as argument. Returns an entity for a given ID and optional valid-time/transaction-time co-ordinates. 141 | ```rust 142 | let person = Person { 143 | crux__db___id: CruxId::new("hello-entity"), 144 | ... 145 | }; 146 | 147 | let client = Crux::new("localhost", "3000").http_client(); 148 | 149 | // entity expects a CruxId 150 | let edn_body = client.entity(person.crux__db___id).unwrap(); 151 | // Map( 152 | // Map( 153 | // { 154 | // ":crux.db/id": Key( 155 | // ":hello-entity", 156 | // ), 157 | // ":first-name": Str( 158 | // "Hello", 159 | // ), 160 | // ":last-name": Str( 161 | // "World", 162 | // ), 163 | // }, 164 | // ), 165 | // ) 166 | ``` 167 | 168 | * [`entity_timed`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.entity_timed) is similar to `entity` as it requests the same endpoint, the difference is that it can send `transaction-time` and `valid-time` as query-params. This is done by the extra arguments `transaction_time: Option>` and `valid_time: Option>`. 169 | 170 | * [`entity_tx`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.entity_tx) requests endpoint [`/entity-tx`](https://opencrux.com/reference/http.html#entity-tx) via `POST`. A serialized `CruxId`, serialized `Edn::Key` or a String containing a [`keyword`](https://github.com/edn-format/edn#keywords) must be passed as argument. Returns the transaction that most recently set a key. 171 | ```rust 172 | use transistor::http::{Action}; 173 | use transistor::client::Crux; 174 | use transistor::types::{CruxId}; 175 | 176 | let person = Person { 177 | crux__db___id: CruxId::new("hello-entity"), 178 | ... 179 | }; 180 | 181 | let client = Crux::new("localhost", "3000").http_client(); 182 | 183 | let tx_body = client.entity_tx(edn_rs::to_string(person.crux__db___id)).unwrap(); 184 | // EntityTxResponse { 185 | // db___id: "d72ccae848ce3a371bd313865cedc3d20b1478ca", 186 | // db___content_hash: "1828ebf4466f98ea3f5252a58734208cd0414376", 187 | // db___valid_time: 2020-07-20T20:38:27.515-00:00, 188 | // tx___tx_id: 31, 189 | // tx___tx_time: 2020-07-20T20:38:27.515-00:00, 190 | // } 191 | ``` 192 | 193 | * [`entity_tx_timed`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.entity_tx_timed) is similar to `entity_tx` as it requests the same endpoint, the difference is that it can send `transaction-time` and `valid-time` as query-params. This is done by the extra arguments `transaction_time: Option>` and `valid_time: Option>`. 194 | 195 | * [`entity_history`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.entity_history) requests endpoint [`/entity-history`](https://opencrux.com/reference/http.html#entity-history) via `GET`. Arguments are the `crux.db/id` as a `String`, an ordering argument defined by the enum `http::Order` (`Asc` or `Desc`) and a boolean for the `with-docs?` flag. The response is a Vector containing `EntityHistoryElement`. If `with-docs?` is `true`, thank the field `db__doc`, `:crux.db/doc`, witll return an `Option` containing the inserted struct. 196 | ```rust 197 | use transistor::client::Crux; 198 | use transistor::http::Order; 199 | use transistor::types::CruxId; 200 | 201 | let person = Person { 202 | crux__db___id: CruxId::new("hello-history"), 203 | ... 204 | 205 | let client = Crux::new("localhost", "3000").http_client(); 206 | 207 | let tx_body = client.entity_tx(person.crux__db___id).unwrap(); 208 | 209 | let entity_history = client.entity_history(tx_body.db___id.clone(), Order::Asc, true); 210 | // EntityHistoryResponse { history: [ 211 | // EntityHistoryElement { 212 | // db___valid_time: 2020-08-05T03:00:06.476-00:00, 213 | // tx___tx_id: 37, tx___tx_time: 2020-08-05T03:00:06.476-00:00, 214 | // db___content_hash: "2da097a2dffbb9828cd4377f1461a59e8454674b", 215 | // db__doc: Some(Map(Map( 216 | // {":crux.db/id": Key(":hello-history"), 217 | // ":first-name": Str("Hello"), 218 | // ":last-name": Str("World")} 219 | // ))) 220 | // } 221 | // ]} 222 | 223 | let entity_history_without_docs = client.entity_history(tx_body.db___id, Order::Asc, false); 224 | // EntityHistoryResponse { 225 | // history: [ 226 | // EntityHistoryElement { 227 | // db___valid_time: 2020-08-05T03:00:06.476-00:00, 228 | // tx___tx_id: 37, 229 | // tx___tx_time: 2020-08-05T03:00:06.476-00:00, 230 | // db___content_hash: "2da097a2dffbb9828cd4377f1461a59e8454674b", 231 | // db__doc: None 232 | // } 233 | // } 234 | // ]} 235 | ``` 236 | 237 | * [`entity_history_timed`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.entity_history_timed) is similar to `entity_histoty` as it requests the same endpoint, the difference is that it can send `start-transaction-time`, `end-transaction-time`, `start-valid-time` and `end-valid-time` as query-params. This is done by adding a `Vec` containing one `TimeHistory::TransactionTime` and/or one `TimeHistory::ValidTime`, both of them receive two `Option>`. The first `DateTime` is the `start--time` and the second is the `end--time`. 238 | 239 | 240 | * [`query`](https://docs.rs/transistor/2.1.2/transistor/http/struct.HttpClient.html#method.query) requests endpoint [`/query`](https://opencrux.com/reference/http.html#query) via `POST`. Argument is a `query` of the type `Query`. Retrives a Set containing a vector of the values defined by the function `Query::find`. 241 | Available functions are `find`, `find_by_aggregates`, `where_clause`, `args`, `order_by`, `limit`, `offset`, examples [`complex_query`](https://github.com/naomijub/transistor/blob/master/examples/complex_query.rs) and [`limit_offset_query`](https://github.com/naomijub/transistor/blob/master/examples/limit_offset_query.rs) have examples on how to use them. 242 | 243 | **Simple find** 244 | ```rust 245 | use transistor::client::Crux; 246 | use transistor::types::{query::Query}; 247 | 248 | let client = Crux::new("localhost", "3000").http_client(); 249 | 250 | let query_is_sql = Query::find(vec!["?p1", "?n"]) 251 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql true"]) 252 | .build(); 253 | // Query: 254 | // {:query 255 | // {:find [?p1 ?n] 256 | // :where [[?p1 :name ?n] 257 | // [?p1 :is-sql true]]}} 258 | 259 | let is_sql = client.query(query_is_sql.unwrap()).unwrap(); 260 | // {[":mysql", "MySQL"], [":postgres", "Postgres"]} BTreeSet 261 | ``` 262 | 263 | **Find by aggregates** 264 | * Available aggregates at [`Aggregate`]([`Query`](https://docs.rs/transistor/2.1.2/transistor/types/query/enum.Aggregate.html) ) 265 | ```rust 266 | use transistor::client::Crux; 267 | use transistor::types::{query::Query}; 268 | 269 | let client = Crux::new("localhost", "3000").http_client(); 270 | 271 | let q = Query::find_by_aggregates(vec![ 272 | Aggregate::Min("?e".to_string()), Aggregate::Max("?e".to_string()), Aggregate::Count("?e".to_string()), 273 | Aggregate::MinN(5, "?e".to_string()), Aggregate::CountDistinct("?e".to_string()) 274 | ])? 275 | .where_clause(vec!["?e :type :burger"])? 276 | .build()?; 277 | // Query: 278 | // {:query 279 | // {:find [(min ?e) (max ?e) (count ?e) (min 5 ?e) (count-distinct ?e)] 280 | // :where [[?e :type :burger]] 281 | // }} 282 | 283 | let _ = client.query(q)?; 284 | ``` 285 | 286 | ### Transisitor's Structs and Enums 287 | 288 | [`Actions`](https://docs.rs/transistor/2.1.2/transistor/http/enum.Actions.html) is a builder struct to help you create a `Vec` for `tx_log`. Available functions are: 289 | * `new` static method to instantiate struct `Actions`. 290 | * `append_put(action: T)` appends a [`Put`](https://opencrux.com/reference/transactions.html#put) to `Actions` with no `valid-time`. `Put` writes a document. 291 | * `append_put_timed(action: T, date: DateTime)` appends a [`Put`](https://opencrux.com/reference/transactions.html#put) to `Actions` with `valid-time`. 292 | * `append_delete(id: CruxId)` appends a [`Delete`](https://opencrux.com/reference/transactions.html#delete) to `Actions` with no `valid-time`. Deletes the specific document at last `valid-time`. 293 | * `append_delete_timed(id: CruxId, date: DateTime)` appends a [`Delete`](https://opencrux.com/reference/transactions.html#delete) to `Actions` with `valid-time`. Deletes the specific document at the given `valid-time`. 294 | * `append_evict(id: CruxId)` appends an [`Evict`](https://opencrux.com/reference/transactions.html#evict) to `Actions`. Evicts a document entirely, including all historical versions (receives only the ID to evict). 295 | * `append_match_doc(id: CruxId, action: T)` appends a [`Match`](https://opencrux.com/reference/transactions.html#match) to `Actions` with no `valid-time`. Matches the current state of an entity, if the state doesn't match the provided document, the transaction will not continue. 296 | * `append_match_doc_timed(id: CruxId, action: T, date: DateTime)` appends a [`Match`](https://opencrux.com/reference/transactions.html#match) to `Actions` with `valid-time`. 297 | * `build` generates the `Vec` from `Actions` 298 | 299 | ```rust 300 | use transistor::client::Crux; 301 | use transistor::types::Actions; 302 | 303 | fn main() -> Result<(), CruxError> { 304 | let crux = Database { 305 | // ... 306 | }; 307 | 308 | let psql = Database { 309 | // ... 310 | }; 311 | 312 | let mysql = Database { 313 | // ... 314 | }; 315 | 316 | let cassandra = Database { 317 | // ... 318 | }; 319 | 320 | let sqlserver = Database { 321 | // ... 322 | }; 323 | 324 | let client = Crux::new("localhost", "3000").http_client(); 325 | let timed = "2014-11-28T21:00:09-09:00" 326 | .parse::>() 327 | .unwrap(); 328 | 329 | let actions: Vec = Actions::new() 330 | .append_put(crux) 331 | .append_put(psql) 332 | .append_put(mysql) 333 | .append_put_timed(cassandra, timed) 334 | .append_put(sqlserver) 335 | .build(); 336 | 337 | let _ = client.tx_log(actions)?; 338 | } 339 | ``` 340 | 341 | [`Query`](https://docs.rs/transistor/2.1.2/transistor/types/query/struct.Query.html) is a struct responsible for creating the fields and serializing them into the correct `query` format. It has a function for each field and a `build` function to help check if it is correctyly formatted. 342 | * `find` is a static builder function to define the elements inside the `:find` clause. 343 | * `where_clause` is a builder function that defines the vector os elements inside the `:where []` array. 344 | * `order_by` is a builder function to define the elements inside the `:order-by` clause. 345 | * `args` is a builder function to define the elements inside the `:args` clause. 346 | * `limit` is a builder function to define the elements inside the `:limit` clause. 347 | * `offset` is a builder function to define the elements inside the `:offset` clause. 348 | * `with_full_results` is a builder function to define the flag `full-results?` as true. This allows your `query` response to return the whole document instead of only the searched keys. The result of the Query `{:query {:find [?user ?a] :where [[?user :first-name ?a]] :full-results? true}}` will be a `BTreeSet>` like `([{:crux.db/id :fafilda, :first-name "Jorge", :last-name "Klaus"} "Jorge"])`, so the document will need further EDN parsing to become the document's struct. 349 | 350 | Errors are defined in the [`CruxError`](https://docs.rs/transistor/2.1.2/transistor/types/error/enum.CruxError.html) enum. 351 | * `EdnError` is a wrapper over `edn_rs::EdnError`. 352 | * `RequestError` is originated by `reqwest` crate. Failed to make HTTP request. 353 | * `QueryFormatError` is originated when the provided Query struct did not match schema. 354 | * `QueryError` is responsible for encapsulation the Stacktrace error from Crux response: 355 | 356 | ```rust 357 | use transistor::client::Crux; 358 | use transistor::types::{query::Query}; 359 | 360 | let _client = Crux::new("localhost", "3000").http_client(); 361 | 362 | // field `n` doesn't exist 363 | let _query_error_response = Query::find(vec!["?p1", "?n"]) 364 | .where_clause(vec!["?p1 :name ?g", "?p1 :is-sql true"]) 365 | .build(); 366 | 367 | let error = client.query(query_error_response?)?; 368 | println!("Stacktrace \n{:?}", error); 369 | 370 | // Stacktrace 371 | // QueryError("{:via 372 | // [{:type java.lang.IllegalArgumentException, 373 | // :message \"Find refers to unknown variable: n\", 374 | // :at [crux.query$q invokeStatic \"query.clj\" 1152]}], 375 | // :trace 376 | // [[crux.query$q invokeStatic \"query.clj\" 1152] 377 | // [crux.query$q invoke \"query.clj\" 1099] 378 | // [crux.query$q$fn__10850 invoke \"query.clj\" 1107] 379 | // [clojure.core$binding_conveyor_fn$fn__5754 invoke \"core.clj\" 2030] 380 | // [clojure.lang.AFn call \"AFn.java\" 18] 381 | // [java.util.concurrent.FutureTask run \"FutureTask.java\" 264] 382 | // [java.util.concurrent.ThreadPoolExecutor 383 | // runWorker 384 | // \"ThreadPoolExecutor.java\" 385 | // 1128] 386 | // [java.util.concurrent.ThreadPoolExecutor$Worker 387 | // run 388 | // \"ThreadPoolExecutor.java\" 389 | // 628] 390 | // [java.lang.Thread run \"Thread.java\" 834]], 391 | // :cause \"Find refers to unknown variable: n\"} 392 | // ") 393 | ``` 394 | 395 | ### Testing the Crux Client 396 | 397 | For testing purpose there is a `feature` called `mock` that enables the `http_mock` function that is a replacement for the `http_client` function. To use it run your commands with the the flag `--features "mock"` as in `cargo test --test lib --no-fail-fast --features "mock"`. The mocking feature uses the crate `mockito = "0.26"` as a Cargo dependency. An example usage with this feature enabled: 398 | 399 | ```rust 400 | use transistor::client::Crux; 401 | use transistor::http::Action; 402 | use edn_derive::Serialize; 403 | use transistor::types::{CruxId}; 404 | use mockito::mock; 405 | 406 | #[test] 407 | #[cfg(feature = "mock")] 408 | fn mock_client() { 409 | let _m = mock("POST", "/tx-log") 410 | .with_status(200) 411 | .match_body("[[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }], [:crux.tx/put { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", }]]") 412 | .with_header("content-type", "text/plain") 413 | .with_body("{:crux.tx/tx-id 8, :crux.tx/tx-time #inst \"2020-07-16T21:53:14.628-00:00\"}") 414 | .create(); 415 | 416 | let person1 = Person { 417 | // ... 418 | }; 419 | 420 | let person2 = Person { 421 | /// ... 422 | }; 423 | 424 | let actions = vec![Action::put(person1), Action::put(person2)]; 425 | 426 | let body = Crux::new("localhost", "3000") 427 | .http_mock() 428 | .tx_log(actions) 429 | .unwrap(); 430 | 431 | assert_eq!( 432 | format!("{:?}", body), 433 | String::from("TxLogResponse { tx___tx_id: 8, tx___tx_time: 2020-07-16T21:53:14.628-00:00, tx__event___tx_events: None }") 434 | ); 435 | } 436 | 437 | #[derive(Debug, Clone, Serialize)] 438 | #[allow(non_snake_case)] 439 | pub struct Person { 440 | crux__db___id: CruxId, 441 | // ... 442 | } 443 | 444 | ``` 445 | 446 | Also, struct `Actions` can be tested with feature `mock` by using enum `ActionMock` due to the implementation of `impl PartialEq> for Actions`. A demo example can be: 447 | 448 | ```rust 449 | use transistor::types::http::{Actions, ActionMock}; 450 | 451 | fn test_actions_eq_actions_mock() { 452 | let actions = test_actions(); 453 | let mock = test_action_mock(); 454 | 455 | assert_eq!(actions, mock); 456 | } 457 | 458 | fn test_action_mock() -> Vec { 459 | let person1 = Person { 460 | crux__db___id: CruxId::new("jorge-3"), 461 | first_name: "Michael".to_string(), 462 | last_name: "Jorge".to_string(), 463 | }; 464 | 465 | let person2 = Person { 466 | crux__db___id: CruxId::new("manuel-1"), 467 | first_name: "Diego".to_string(), 468 | last_name: "Manuel".to_string(), 469 | }; 470 | 471 | vec![ 472 | ActionMock::Put(edn_rs::to_string(person1.clone()), None), 473 | ActionMock::Put(edn_rs::to_string(person2), None), 474 | ActionMock::Delete(edn_rs::to_string(person1.crux__db___id), None), 475 | ] 476 | } 477 | 478 | fn test_actions() -> Actions { 479 | let person1 = Person { 480 | crux__db___id: CruxId::new("jorge-3"), 481 | first_name: "Michael".to_string(), 482 | last_name: "Jorge".to_string(), 483 | }; 484 | 485 | let person2 = Person { 486 | crux__db___id: CruxId::new("manuel-1"), 487 | first_name: "Diego".to_string(), 488 | last_name: "Manuel".to_string(), 489 | }; 490 | Actions::new().append_put(person1.clone()).append_put(person2).append_delete(person1.crux__db___id) 491 | } 492 | ``` 493 | 494 | ### Async support 495 | 496 | **Async feature is still in BETA** as it depends heavily on `unwraps`. 497 | 498 | It is possible to use `async/await` http client, for that it is necessary to enable feature `async` in transistor, `transistor = { version = "2.1.2", features = ["async"] }`. With this feature enabled the `HttpClient` will use `reqwest::Client` instead of `reqwest::blocking::Client`. The default async runtime for `reqwest::Client` is `tokio`, so it is good to have `tokio` with feature `macros`, as well as `futures`, in your `Cargo.toml`: 499 | 500 | ```toml 501 | futures = {version = "0.3.5" } 502 | tokio = {version = "0.2.22", features = ["macros"] } 503 | ``` 504 | 505 | An async query example can be found below: 506 | 507 | ```rust 508 | use tokio::prelude::*; 509 | use transistor::client::Crux; 510 | use edn_derive::Serialize; 511 | use transistor::types::http::Action; 512 | use transistor::types::{ 513 | error::CruxError, 514 | {query::Query, CruxId}, 515 | }; 516 | 517 | #[tokio::main] 518 | async fn main() { 519 | let crux = Database { 520 | crux__db___id: CruxId::new("crux"), 521 | name: "Crux Datalog".to_string(), 522 | is_sql: false, 523 | }; 524 | 525 | let psql = Database { 526 | crux__db___id: CruxId::new("postgres"), 527 | name: "Postgres".to_string(), 528 | is_sql: true, 529 | }; 530 | 531 | let mysql = Database { 532 | crux__db___id: CruxId::new("mysql"), 533 | name: "MySQL".to_string(), 534 | is_sql: true, 535 | }; 536 | 537 | let client = Crux::new("localhost", "3000").http_client(); 538 | let action1 = Action::put(crux, None); 539 | let action2 = Action::put(psql, None); 540 | let action3 = Action::put(mysql, None); 541 | 542 | let _ = client.tx_log(vec![action1, action2, action3]).await; 543 | 544 | let query_is_sql = Query::find(vec!["?p1", "?n"]) 545 | .unwrap() 546 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql true"]) 547 | .unwrap() 548 | .build(); 549 | 550 | let is_sql = client.query(query_is_sql.unwrap()).await; 551 | 552 | let query_is_no_sql = Query::find(vec!["?p1", "?n", "?s"]) 553 | .unwrap() 554 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql false"]) 555 | .unwrap() 556 | .with_full_results() 557 | .build(); 558 | 559 | let is_no_sql = client.query(query_is_no_sql.unwrap()).await; 560 | } 561 | 562 | #[derive(Debug, Clone, Serialize)] 563 | #[allow(non_snake_case)] 564 | pub struct Database { 565 | crux__db___id: CruxId, 566 | name: String, 567 | is_sql: bool 568 | } 569 | 570 | ``` 571 | 572 | Note `use tokio::prelude::*;` and `#[tokio::main] \n async fn main()`. 573 | 574 | ## Enabling feature `time_as_str` 575 | It is possible to use receive the responses (`TxLogResponse`, `EntityTxResponse`, `EntityHistoryElement`) time dates as Strings, to do so you have to enable feature `time_as_str`: 576 | 577 | ```toml 578 | transistor = { version = "2.1.2", features = ["time_as_str"] } 579 | ``` 580 | 581 | ## Possible Features 582 | ``` 583 | mock = ["mockito"] -> http_mock() 584 | time_as_str = [] -> DataTime types become Strings 585 | async = ["tokio", "futures"] -> async/await 586 | ``` 587 | 588 | ## Dependencies 589 | A strong dependency of this crate is the [edn-rs](https://crates.io/crates/edn-rs) crate, as many of the return types are in the [Edn format](https://github.com/edn-format/edn), also the [edn-derive](https://crates.io/crates/edn-derive). The sync http client is `reqwest` with `blocking` feature enabled. `Chrono` for time values that can be `DateTime`, for inserts, and `DateTime`, for reads, and `mockito` for feature `mock`. 590 | 591 | ## Licensing 592 | This project is licensed under LGPP-3.0 (GNU Lesser General Public License v3.0). 593 | -------------------------------------------------------------------------------- /src/types/query.rs: -------------------------------------------------------------------------------- 1 | use crate::types::error::CruxError; 2 | use edn_rs::Serialize; 3 | use std::collections::BTreeSet; 4 | use std::convert::TryFrom; 5 | 6 | /// A [`Query`](https://opencrux.com/reference/queries.html) is a special kind of body that we submit to the `query` function. It has the following fields: 7 | /// * `find` is responsible for defining which elements of the query you want shown in the response, it is **required**. Argument is a vector with elements to be queried, `vec!["a", "b", "c"]`. It is parsed as `:find [a b c]`, qhere `a, b, c` are the elements defined in `where` clause. 8 | /// * `where_clause` is responsible for defining which rules will be applied to filter elements, it is **required**. Argument is a vector with the strings containing the filtering function, `vec!["a :db-key1 b", "a :db-key2 c", "a :db-key3 "]`. It is parsed as `:where [ [a :db-key1 b] [a :db-key2 c] [a :db-key3 ] ]`. 9 | /// * `args` is responsible for defining arguments to be replaced in `where_clause`, **optional**. Argument is a vector with strings containing the matches `vec!["?n \"Ivan\" ?l \"Ivanov\"", "?n \"Petr\" ?l \"Petrov\""]`. 10 | /// * `order_by` is responsible for defining the order in which the response will be represented, **optional**. Argument is a vector with strings containing the element and how to order (`:asc` or `:desc`) `vec!["time :desc", "device-id :asc"]`. 11 | /// * `limit` is responsible for defining the limit size of the response, **optional**. Argument is a usize. 12 | /// * `offset` is responsible for defining the offset of the response, **optional**. Argument is a usize. 13 | #[derive(Clone, Debug)] 14 | pub struct Query { 15 | find: Find, 16 | aggregates: Option>, 17 | where_: Option, 18 | args: Option, 19 | order_by: Option, 20 | limit: Option, 21 | offset: Option, 22 | full_results: bool, 23 | } 24 | #[derive(Clone, Debug)] 25 | struct Find(Vec); 26 | #[derive(Clone, Debug)] 27 | struct Where(Vec); 28 | #[derive(Clone, Debug)] 29 | struct Args(Vec); 30 | #[derive(Clone, Debug)] 31 | struct OrderBy(Vec); 32 | #[derive(Clone, Debug)] 33 | struct Limit(usize); 34 | #[derive(Clone, Debug)] 35 | struct Offset(usize); 36 | 37 | /// `Aggregate` is an enum of possible aggregation to use with `find_by_aggregates` clause. 38 | #[derive(Clone)] 39 | pub enum Aggregate { 40 | /// Accumulates as single value via the Clojure + function 41 | Sum(String), 42 | /// Return the single minimal value via the Clojure compare function which may operates on many types (integers, strings, collections etc.) 43 | Min(String), 44 | /// Return the single maximal value via the Clojure compare function which may operates on many types (integers, strings, collections etc.) 45 | Max(String), 46 | /// Returns a sorted set of the N minimum items. N must be a positive integer and cannot be referenced via an additional logic-var. 47 | MinN(usize, String), 48 | /// Returns a sorted set of the N maximum items. N must be a positive integer and cannot be referenced via an additional logic-var. 49 | MaxN(usize, String), 50 | /// Returns a single count of all values including any duplicates 51 | Count(String), 52 | /// Returns a single count of all unique values 53 | CountDistinct(String), 54 | /// Returns a single value equivalent to `sum / count` 55 | Avg(String), 56 | /// Return single value corresponding to the statistical definition of median 57 | Median(String), 58 | /// Return single value corresponding to the statistical definition of variance 59 | Variance(String), 60 | /// Return single value corresponding to the statistical definition of stddev 61 | Stddev(String), 62 | /// Returns a vector of exactly N values, where some values may be duplicates if N is larger than the range 63 | Rand(usize, String), 64 | /// Returns a vector of at-most N distinct values 65 | Sample(usize, String), 66 | /// Returns a set of distinct values 67 | Distinct(String), 68 | /// Adds a simple element without function calls 69 | NonAggregative(String), 70 | } 71 | 72 | impl Aggregate { 73 | fn string_value(&self) -> String { 74 | match self { 75 | Aggregate::Sum(s) => s.to_string(), 76 | Aggregate::Min(s) => s.to_string(), 77 | Aggregate::Max(s) => s.to_string(), 78 | Aggregate::MinN(_, s) => s.to_string(), 79 | Aggregate::MaxN(_, s) => s.to_string(), 80 | Aggregate::Count(s) => s.to_string(), 81 | Aggregate::CountDistinct(s) => s.to_string(), 82 | Aggregate::Avg(s) => s.to_string(), 83 | Aggregate::Median(s) => s.to_string(), 84 | Aggregate::Variance(s) => s.to_string(), 85 | Aggregate::Stddev(s) => s.to_string(), 86 | Aggregate::Rand(_, s) => s.to_string(), 87 | Aggregate::Sample(_, s) => s.to_string(), 88 | Aggregate::Distinct(s) => s.to_string(), 89 | Aggregate::NonAggregative(s) => s.to_string(), 90 | } 91 | } 92 | } 93 | 94 | impl std::fmt::Display for Aggregate { 95 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 96 | match self { 97 | Aggregate::Sum(s) => write!(f, "(sum {})", &s), 98 | Aggregate::Min(s) => write!(f, "(min {})", &s), 99 | Aggregate::Max(s) => write!(f, "(max {})", &s), 100 | Aggregate::MinN(n, s) => write!(f, "(min {} {})", n, &s), 101 | Aggregate::MaxN(n, s) => write!(f, "(max {} {})", n, &s), 102 | Aggregate::Count(s) => write!(f, "(count {})", &s), 103 | Aggregate::CountDistinct(s) => write!(f, "(count-distinct {})", &s), 104 | Aggregate::Avg(s) => write!(f, "(avg {})", &s), 105 | Aggregate::Median(s) => write!(f, "(median {})", &s), 106 | Aggregate::Variance(s) => write!(f, "(variance {})", &s), 107 | Aggregate::Stddev(s) => write!(f, "(stddev {})", &s), 108 | Aggregate::Rand(n, s) => write!(f, "(rand {} {})", n, &s), 109 | Aggregate::Sample(n, s) => write!(f, "(sample {} {})", n, &s), 110 | Aggregate::Distinct(s) => write!(f, "(distinct {})", &s), 111 | Aggregate::NonAggregative(s) => write!(f, "{}", &s), 112 | } 113 | } 114 | } 115 | 116 | impl Query { 117 | /// `find` is the function responsible for defining the `:find` key in the query. 118 | /// Input should be the elements to be queried by the `where_clause`. 119 | /// Ex: `vec!["time", "device-id", "temperature", "humidity"]`. 120 | /// Becomes: `:find [time, device-id, temperature, humidity]`. 121 | /// 122 | /// Error cases: 123 | /// * All elements should start with `?`, example `vec!["?p1", "?n", "?g"]`. If theey do not start the CruxError::QueryFormatError containing `All elements of find clause should start with '?', element '{}' doesn't conform` is thrown. 124 | pub fn find(find: Vec<&str>) -> Result { 125 | if find.iter().any(|e| !e.starts_with("?")) { 126 | let error = find.iter().find(|e| !e.starts_with("?")).unwrap(); 127 | return Err(CruxError::QueryFormatError(format!( 128 | "All elements of find clause should start with '?', element '{}' doesn't conform", 129 | error 130 | ))); 131 | } 132 | 133 | Ok(Self { 134 | find: Find { 135 | 0: find.into_iter().map(String::from).collect::>(), 136 | }, 137 | aggregates: None, 138 | where_: None, 139 | args: None, 140 | order_by: None, 141 | limit: None, 142 | offset: None, 143 | full_results: false, 144 | }) 145 | } 146 | 147 | /// `find_by_aggregates` is the function responsible for defining the `:find` key in the query similar to `find`. 148 | /// However, it supports sending aggregates to `:find` keys. 149 | /// Input should be the elements to be queried by the `where_clause`. 150 | /// Ex: `vec![(Sum("?heads"), Min("?heads"), Max("?heads"), Count("?heads"), CountDistinct("?heads")]`. 151 | /// Becomes: `:find [(sum ?heads) (min ?heads) (max ?heads) (count ?heads) (count-distinct ?heads)]`. 152 | /// 153 | /// Error cases: 154 | /// * All elements should start with `?`, example `vec!["(min ?heads)"]`. If theey do not start the CruxError::QueryFormatError containing `All elements of find clause should start with '?', element '{}' doesn't conform` is thrown. 155 | pub fn find_by_aggregates(find: Vec) -> Result { 156 | // if find.iter() 157 | // .any(|e| !e.starts_with("?")) { 158 | // let error = find.iter().find(|e| !e.starts_with("?")).unwrap(); 159 | // return Err(CruxError::QueryFormatError(format!( 160 | // "All elements of find clause should start with '?', element '{}' doesn't conform", 161 | // error 162 | // ))); 163 | // } 164 | if find 165 | .iter() 166 | .map(|a| a.string_value()) 167 | .any(|e| !e.starts_with("?")) 168 | { 169 | let error = find 170 | .iter() 171 | .filter(|e| !e.string_value().starts_with("?")) 172 | .take(1) 173 | .next() 174 | .unwrap(); 175 | return Err(CruxError::QueryFormatError(format!( 176 | "All elements of find clause should start with '?', element '{}' doesn't conform", 177 | error 178 | ))); 179 | } 180 | let aggregates = Some( 181 | find.iter() 182 | .map(|a| a.string_value()) 183 | .collect::>(), 184 | ); 185 | 186 | Ok(Self { 187 | find: Find { 188 | 0: find 189 | .into_iter() 190 | .map(|a| a.to_string()) 191 | .collect::>(), 192 | }, 193 | aggregates: aggregates, 194 | where_: None, 195 | args: None, 196 | order_by: None, 197 | limit: None, 198 | offset: None, 199 | full_results: false, 200 | }) 201 | } 202 | 203 | /// `where_clause` is the function responsible for defining the required `:where` key in the query. 204 | /// Input should be `element1 :key element2`, `element2` may have a modifier like `#inst`. The order matters. 205 | /// Ex: `vec!["c :condition/time time", "c :condition/device-id device-id", "c :condition/temperature temperature", "c :condition/humidity humidity"]`. 206 | /// Becomes: 207 | /// `:where [[c :condition/time time] [c :condition/device-id device-id] [c :condition/temperature temperature] [c :condition/humidity humidity]]`. 208 | /// 209 | /// Error cases: 210 | /// * All elements present in find clause should be present in where clause. If your find clause is `"?p", "?n", "?s"`, and your where clause is `"?p1 :alpha ?n", "?p1 :beta true"` an error `Not all element of find, `"?p", "?n", "?s"`, are present in the where clause, ?s is missing` is thrown. 211 | pub fn where_clause(mut self, where_: Vec<&str>) -> Result { 212 | if self.aggregates.is_none() && self.find.0.iter().any(|e| !where_.join(" ").contains(e)) { 213 | let error = self 214 | .find 215 | .0 216 | .iter() 217 | .find(|e| !where_.join(" ").contains(*e)) 218 | .unwrap(); 219 | return Err(CruxError::QueryFormatError(format!( 220 | "Not all element of find, {}, are present in the where clause, {} is missing", 221 | self.find.0.join(", "), 222 | error 223 | ))); 224 | } 225 | 226 | if self.clone().aggregates.is_some() 227 | && self 228 | .aggregates 229 | .clone() 230 | .unwrap_or(std::collections::HashSet::new()) 231 | .iter() 232 | .any(|e| !where_.join(" ").contains(e)) 233 | { 234 | return Err(CruxError::QueryFormatError(format!( 235 | "Not all element of find, {}, are present in the where clause", 236 | self.find.0.join(", "), 237 | ))); 238 | } 239 | 240 | let w = where_ 241 | .iter() 242 | .map(|s| s.replace("[", "").replace("]", "")) 243 | .collect::>(); 244 | self.where_ = Some(Where { 0: w }); 245 | Ok(self) 246 | } 247 | 248 | /// `args` is the function responsible for defining the optional `:args` key in the query. 249 | /// Input are elements you want to replace in the `where_clause`, a good practice is to name them with `?` before. 250 | /// Ex: `vec!["?n \"Ivan\" ?l \"Ivanov\"", "?n \"Petr\" ?l \"Petrov\""]`. 251 | /// Becomes: `:args [{?n "Ivan" ?l "Ivanov"} {?n "Petr" ?l "Petrov"}]`. 252 | /// 253 | /// Error cases: 254 | /// * The first element of the argument key-value tuple should start with `?`. An input `vec!["n true"]` will return an error `All elements should start with '?'`. 255 | /// * All arguments key should be present in the where clause. If the where clause `?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"` and an args clause `vec!["?s true ?x 1243"]` will return an error `All elements should be present in where clause`. 256 | pub fn args(mut self, args: Vec<&str>) -> Result { 257 | let where_ = self.where_.clone().unwrap().0.join(" "); 258 | self.args = Some(Args::try_from((args, where_))?); 259 | Ok(self) 260 | } 261 | 262 | /// `order_by` is the function responsible for defining the optional `:order-by` key in the query. 263 | /// Input is the elements to be ordered by, the first element is the first order, the second is the further orthers. Allowed keys are `:Asc`and `:desc`. 264 | /// Ex: `vec!["time :desc", "device-id :asc"]`. 265 | /// Becomes: `:order-by [[time :desc] [device-id :asc]]`. 266 | /// 267 | /// Error cases: 268 | /// * The second element of each order clause should be `:asc` or `:desc`, if different, like `:eq` in `"?p1 :asc", "?n :desc", "?s :eq"`, error `Order element should be ':asc' or ':desc'` is thrown. 269 | /// * The first element of each order clause should be present in the find clause. If the order clause is `"?p1 :asc", "?n :desc", "?g :asc"` and the find clause is `"?p1", "?n"` the error `All elements to be ordered should be present in find clause, ?g not present` is thrown. 270 | pub fn order_by(mut self, order_by: Vec<&str>) -> Result { 271 | let f = self.find.0.join(" "); 272 | if !order_by 273 | .iter() 274 | .map(|e| e.split(" ").collect::>()) 275 | .map(|e| e[1]) 276 | .all(|e| e.to_lowercase() == ":asc" || e.to_lowercase() == ":desc") 277 | { 278 | return Err(CruxError::QueryFormatError( 279 | "Order element should be ':asc' or ':desc'".to_string(), 280 | )); 281 | } 282 | if !order_by 283 | .iter() 284 | .map(|e| e.split(" ").collect::>()) 285 | .map(|e| e[0]) 286 | .all(|e| f.contains(e)) 287 | { 288 | let error = order_by 289 | .iter() 290 | .map(|e| e.split(" ").collect::>()) 291 | .map(|e| e[0]) 292 | .find(|e| !f.contains(e)) 293 | .unwrap(); 294 | return Err(CruxError::QueryFormatError(format!( 295 | "All elements to be ordered should be present in find clause, {} not present", 296 | error 297 | ))); 298 | } 299 | 300 | let o = order_by 301 | .iter() 302 | .map(|s| s.replace("[", "").replace("]", "")) 303 | .collect::>(); 304 | self.order_by = Some(OrderBy { 0: o }); 305 | Ok(self) 306 | } 307 | 308 | /// `limit` is the function responsible for defining the optional `:limit` key in the query. 309 | /// Input is a usize with the query limit size. 310 | /// `.limit(5usize)` Becomes: `:limit 5`. 311 | pub fn limit(mut self, limit: usize) -> Self { 312 | self.limit = Some(Limit { 0: limit }); 313 | self 314 | } 315 | 316 | /// `offset` is the function responsible for defining the optional `:offset` key in the query. 317 | /// Input is a usize with the query offset. 318 | /// `.offset(5usize)` Becomes: `:offset 5`. 319 | pub fn offset(mut self, offset: usize) -> Self { 320 | self.offset = Some(Offset { 0: offset }); 321 | self 322 | } 323 | 324 | /// `with_full_results` adds `:full-results? true` to the query map to easily retrieve the source documents relating to the entities in the result set. 325 | pub fn with_full_results(mut self) -> Self { 326 | self.full_results = true; 327 | self 328 | } 329 | 330 | /// `build` function helps you assert that required fields were implemented. 331 | pub fn build(self) -> Result { 332 | if self.where_.is_none() { 333 | Err(CruxError::QueryFormatError(String::from( 334 | "Where clause is required", 335 | ))) 336 | } else { 337 | Ok(self) 338 | } 339 | } 340 | } 341 | 342 | impl Serialize for Query { 343 | fn serialize(self) -> String { 344 | let mut q = String::from("{:query\n {"); 345 | q.push_str(&edn_rs::to_string(self.find)); 346 | q.push_str(&edn_rs::to_string(self.where_.unwrap())); 347 | if self.args.is_some() { 348 | q.push_str(&edn_rs::to_string(self.args.unwrap())); 349 | } 350 | if self.order_by.is_some() { 351 | q.push_str(&edn_rs::to_string(self.order_by.unwrap())); 352 | } 353 | if self.limit.is_some() { 354 | q.push_str(&edn_rs::to_string(self.limit.unwrap())); 355 | } 356 | if self.offset.is_some() { 357 | q.push_str(&edn_rs::to_string(self.offset.unwrap())); 358 | } 359 | if self.full_results == true { 360 | q.push_str(" :full-results? true\n") 361 | } 362 | q.push_str("}}"); 363 | q 364 | } 365 | } 366 | 367 | impl Serialize for Find { 368 | fn serialize(self) -> String { 369 | let mut q = String::from(":find ["); 370 | q.push_str(&self.0.join(" ")); 371 | q.push_str("]\n"); 372 | q 373 | } 374 | } 375 | 376 | impl Serialize for Where { 377 | fn serialize(self) -> String { 378 | let mut q = String::from(":where [["); 379 | q.push_str(&self.0.join("]\n[")); 380 | q.push_str("]]\n"); 381 | q 382 | } 383 | } 384 | 385 | impl Serialize for Args { 386 | fn serialize(self) -> String { 387 | let mut q = String::from(":args [{"); 388 | q.push_str(&self.0.join("}\n{")); 389 | q.push_str("}]\n"); 390 | q 391 | } 392 | } 393 | 394 | impl Serialize for OrderBy { 395 | fn serialize(self) -> String { 396 | let mut q = String::from(":order-by [["); 397 | q.push_str(&self.0.join("]\n[")); 398 | q.push_str("]]\n"); 399 | q 400 | } 401 | } 402 | 403 | impl Serialize for Limit { 404 | fn serialize(self) -> String { 405 | let mut q = String::from(":limit "); 406 | q.push_str(&self.0.to_string()); 407 | q.push_str("\n"); 408 | q 409 | } 410 | } 411 | 412 | impl Serialize for Offset { 413 | fn serialize(self) -> String { 414 | let mut q = String::from(":offset "); 415 | q.push_str(&self.0.to_string()); 416 | q.push_str("\n"); 417 | q 418 | } 419 | } 420 | 421 | type RawArgsWithWhere<'a> = (Vec<&'a str>, String); 422 | 423 | impl TryFrom> for Args { 424 | type Error = CruxError; 425 | 426 | fn try_from(value: RawArgsWithWhere) -> Result { 427 | let (args, where_) = value; 428 | 429 | let args_key_set = args_key_bset(&args); 430 | 431 | let all_elements_in_where = args_key_set.iter().any(|e| !where_.contains(e)); 432 | let has_question = args_key_set.iter().any(|e| !e.starts_with("?")); 433 | 434 | match (all_elements_in_where, has_question) { 435 | (true, false) => Err(CruxError::QueryFormatError("All elements should be present in where clause".to_string())), 436 | (false, true) => Err(CruxError::QueryFormatError("All elements should start with '?'".to_string())), 437 | (true, true) => Err(CruxError::QueryFormatError("All elements should be present in where clause and all elements should start with '?'".to_string())), 438 | (false, false) => Ok(Args{0: args.iter().map(|s| s.replace("{", "").replace("}", "")).collect::>()}), 439 | } 440 | } 441 | } 442 | 443 | fn args_key_bset(args: &Vec<&str>) -> BTreeSet { 444 | let args_without_inst = args.join(" ").replace("#inst", ""); 445 | args_without_inst 446 | .split(" ") 447 | .filter(|i| !i.is_empty()) 448 | .enumerate() 449 | .filter(|(i, _)| i % 2 == 0) 450 | .map(|(_, s)| s.to_owned()) 451 | .collect::>() 452 | } 453 | 454 | #[cfg(test)] 455 | mod test { 456 | use super::{Aggregate, Query}; 457 | use crate::client::Crux; 458 | 459 | #[test] 460 | fn query_with_find_and_where() { 461 | let expected = 462 | "{:query\n {:find [?p1]\n:where [[?p1 :first-name n]\n[?p1 :last-name \"Jorge\"]]\n}}"; 463 | let q = Query::find(vec!["?p1"]) 464 | .unwrap() 465 | .where_clause(vec!["?p1 :first-name n", "?p1 :last-name \"Jorge\""]) 466 | .unwrap() 467 | .build(); 468 | 469 | assert_eq!(edn_rs::to_string(q.unwrap()), expected); 470 | } 471 | 472 | #[test] 473 | #[should_panic(expected = "Where clause is required")] 474 | fn expect_query_format_error() { 475 | let client = Crux::new("", "").http_client(); 476 | let query_where_is_none = Query::find(vec!["?p1", "?n"]).unwrap().build().unwrap(); 477 | 478 | let _ = client.query(query_where_is_none).unwrap(); 479 | } 480 | 481 | #[test] 482 | fn query_with_order() { 483 | let expected = 484 | "{:query\n {:find [?p1]\n:where [[?p1 :first-name n]\n[?p1 :last-name \"Jorge\"]]\n:order-by [[?p1 :asc]]\n}}"; 485 | let q = Query::find(vec!["?p1"]) 486 | .unwrap() 487 | .where_clause(vec!["?p1 :first-name n", "?p1 :last-name \"Jorge\""]) 488 | .unwrap() 489 | .order_by(vec!["?p1 :asc"]) 490 | .unwrap() 491 | .build(); 492 | 493 | assert_eq!(edn_rs::to_string(q.unwrap()), expected); 494 | } 495 | 496 | #[test] 497 | fn query_with_args() { 498 | let expected = 499 | "{:query\n {:find [?p1]\n:where [[?p1 :first-name n]\n[?p1 :last-name ?n]]\n:args [{?n \"Jorge\"}]\n}}"; 500 | let q = Query::find(vec!["?p1"]) 501 | .unwrap() 502 | .where_clause(vec!["?p1 :first-name n", "?p1 :last-name ?n"]) 503 | .unwrap() 504 | .args(vec!["?n \"Jorge\""]) 505 | .unwrap() 506 | .build(); 507 | 508 | assert_eq!(edn_rs::to_string(q.unwrap()), expected); 509 | } 510 | 511 | #[test] 512 | fn query_with_limit_and_offset() { 513 | let expected = 514 | "{:query\n {:find [?p1]\n:where [[?p1 :first-name n]\n[?p1 :last-name n]]\n:limit 5\n:offset 10\n}}"; 515 | let q = Query::find(vec!["?p1"]) 516 | .unwrap() 517 | .where_clause(vec!["?p1 :first-name n", "?p1 :last-name n"]) 518 | .unwrap() 519 | .limit(5) 520 | .offset(10) 521 | .build(); 522 | 523 | assert_eq!(edn_rs::to_string(q.unwrap()), expected); 524 | } 525 | 526 | #[test] 527 | fn full_query() { 528 | let expected = 529 | "{:query\n {:find [?p1]\n:where [[?p1 :first-name n]\n[?p1 :last-name ?n]]\n:args [{?n \"Jorge\"}]\n:order-by [[?p1 :Asc]]\n:limit 5\n:offset 10\n}}"; 530 | let q = Query::find(vec!["?p1"]) 531 | .unwrap() 532 | .where_clause(vec!["?p1 :first-name n", "?p1 :last-name ?n"]) 533 | .unwrap() 534 | .args(vec!["?n \"Jorge\""]) 535 | .unwrap() 536 | .order_by(vec!["?p1 :Asc"]) 537 | .unwrap() 538 | .limit(5) 539 | .offset(10) 540 | .build(); 541 | 542 | assert_eq!(edn_rs::to_string(q.unwrap()), expected); 543 | } 544 | 545 | #[test] 546 | #[should_panic( 547 | expected = "Not all element of find, ?p1, ?n, ?s, are present in the where clause, ?n is missing" 548 | )] 549 | fn where_query_format_error() { 550 | let _query = Query::find(vec!["?p1", "?n", "?s"]) 551 | .unwrap() 552 | .where_clause(vec!["?p1 :name ?g", "?p1 :is-sql ?s", "?p1 :is-sql true"]) 553 | .unwrap() 554 | .build(); 555 | } 556 | 557 | #[test] 558 | #[should_panic(expected = "Order element should be \\\':asc\\\' or \\\':desc\\\'")] 559 | fn order_should_panic_for_unknow_order_element() { 560 | let _query = Query::find(vec!["?p1", "?n", "?s"]) 561 | .unwrap() 562 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"]) 563 | .unwrap() 564 | .order_by(vec!["?p1 :asc", "?n :desc", "?s :eq"]) 565 | .unwrap() 566 | .build(); 567 | } 568 | 569 | #[test] 570 | #[should_panic( 571 | expected = "All elements to be ordered should be present in find clause, ?g not present" 572 | )] 573 | fn order_element_should_be_present_in_find_clause() { 574 | let _query = Query::find(vec!["?p1", "?n", "?s"]) 575 | .unwrap() 576 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"]) 577 | .unwrap() 578 | .order_by(vec!["?p1 :asc", "?n :desc", "?g :asc"]) 579 | .unwrap() 580 | .build(); 581 | } 582 | 583 | #[test] 584 | #[should_panic(expected = "All elements should be present in where clause")] 585 | fn all_args_present_in_where() { 586 | let _query = Query::find(vec!["?p1", "?n"]) 587 | .unwrap() 588 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"]) 589 | .unwrap() 590 | .args(vec!["?s true ?x 1243"]) 591 | .unwrap() 592 | .build(); 593 | } 594 | 595 | #[test] 596 | #[should_panic(expected = "All elements should start with \\\'?\\\'")] 597 | fn all_args_should_start_with_question() { 598 | let _query = Query::find(vec!["?p1", "?n"]) 599 | .unwrap() 600 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql s", "?p1 :is-sql true"]) 601 | .unwrap() 602 | .args(vec!["s true"]) 603 | .unwrap() 604 | .build(); 605 | } 606 | 607 | #[test] 608 | fn query_with_full_results() { 609 | let expected = 610 | "{:query\n {:find [?p1]\n:where [[?p1 :first-name n]\n[?p1 :last-name \"Jorge\"]]\n :full-results? true\n}}"; 611 | let q = Query::find(vec!["?p1"]) 612 | .unwrap() 613 | .where_clause(vec!["?p1 :first-name n", "?p1 :last-name \"Jorge\""]) 614 | .unwrap() 615 | .with_full_results() 616 | .build(); 617 | 618 | assert_eq!(edn_rs::to_string(q.unwrap()), expected); 619 | } 620 | 621 | #[test] 622 | fn query_with_aggregates() { 623 | let expected = "{:query\n {:find [(min ?e) (max ?e) (count ?e) (min 5 ?e) (count-distinct ?e) ?e]\n:where [[?e :type :burger]]\n}}"; 624 | let q = Query::find_by_aggregates(vec![ 625 | Aggregate::Min("?e".to_string()), 626 | Aggregate::Max("?e".to_string()), 627 | Aggregate::Count("?e".to_string()), 628 | Aggregate::MinN(5, "?e".to_string()), 629 | Aggregate::CountDistinct("?e".to_string()), 630 | Aggregate::NonAggregative("?e".to_string()), 631 | ]) 632 | .unwrap() 633 | .where_clause(vec!["?e :type :burger"]) 634 | .unwrap() 635 | .build() 636 | .unwrap(); 637 | 638 | assert_eq!(edn_rs::to_string(q), expected); 639 | } 640 | 641 | #[test] 642 | #[should_panic( 643 | expected = "All elements of find clause should start with \\\'?\\\', element \\\'(min e)\\\' doesn\\\'t conform" 644 | )] 645 | fn query_with_aggregates_error() { 646 | let _ = Query::find_by_aggregates(vec![ 647 | Aggregate::Min("e".to_string()), 648 | Aggregate::Max("?e".to_string()), 649 | Aggregate::Count("?e".to_string()), 650 | Aggregate::MinN(5, "?e".to_string()), 651 | Aggregate::CountDistinct("?e".to_string()), 652 | ]) 653 | .unwrap() 654 | .where_clause(vec!["?e :type :burger"]) 655 | .unwrap() 656 | .build(); 657 | } 658 | } 659 | -------------------------------------------------------------------------------- /src/http.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "async")] 2 | use crate::types::response::QueryAsyncResponse; 3 | #[cfg(not(feature = "async"))] 4 | use crate::types::response::QueryResponse; 5 | use crate::types::{ 6 | error::CruxError, 7 | http::{Actions, Order}, 8 | query::Query, 9 | response::{EntityHistoryResponse, EntityTxResponse, TxLogResponse, TxLogsResponse}, 10 | CruxId, 11 | }; 12 | use chrono::prelude::*; 13 | use edn_rs::Edn; 14 | #[cfg(not(feature = "async"))] 15 | use reqwest::blocking; 16 | use reqwest::header::HeaderMap; 17 | use std::collections::BTreeSet; 18 | use std::str::FromStr; 19 | 20 | static DATE_FORMAT: &'static str = "%Y-%m-%dT%H:%M:%S%Z"; 21 | 22 | /// `HttpClient` has the `reqwest::blocking::Client`, the `uri` to query and the `HeaderMap` with 23 | /// all the possible headers. Default header is `Content-Type: "application/edn"`. Synchronous request. 24 | pub struct HttpClient { 25 | #[cfg(not(feature = "async"))] 26 | pub(crate) client: blocking::Client, 27 | #[cfg(feature = "async")] 28 | pub(crate) client: reqwest::Client, 29 | pub(crate) uri: String, 30 | pub(crate) headers: HeaderMap, 31 | } 32 | 33 | #[cfg(not(feature = "async"))] 34 | impl HttpClient { 35 | /// Function `tx_log` requests endpoint `/tx-log` via `POST` which allow you to send actions `Action` 36 | /// to CruxDB. 37 | /// The "write" endpoint, to post transactions. 38 | pub fn tx_log(&self, actions: Actions) -> Result { 39 | if actions.is_empty() { 40 | return Err(CruxError::TxLogActionError( 41 | "Actions cannot be empty.".to_string(), 42 | )); 43 | } 44 | let body = actions.build(); 45 | 46 | let resp = self 47 | .client 48 | .post(&format!("{}/tx-log", self.uri)) 49 | .headers(self.headers.clone()) 50 | .body(body) 51 | .send()?; 52 | if resp.status().as_u16() < 300 { 53 | let resp_body = resp.text()?.replace("#inst", ""); 54 | edn_rs::from_str(&resp_body).map_err(|e| e.into()) 55 | } else { 56 | Err(CruxError::BadResponse(format!( 57 | "tx_log responded with {}", 58 | resp.status().as_u16(), 59 | ))) 60 | } 61 | } 62 | 63 | /// Function `tx_logs` requests endpoint `/tx-log` via `GET` and returns a list of all transactions 64 | pub fn tx_logs(&self) -> Result { 65 | let resp = self 66 | .client 67 | .get(&format!("{}/tx-log", self.uri)) 68 | .headers(self.headers.clone()) 69 | .send()?; 70 | 71 | if resp.status().as_u16() < 300 { 72 | let resp_body = resp.text()?; 73 | TxLogsResponse::from_str(&resp_body) 74 | } else { 75 | Err(CruxError::BadResponse(format!( 76 | "tx_logs responded with {}", 77 | resp.status().as_u16(), 78 | ))) 79 | } 80 | } 81 | 82 | /// Function `entity` requests endpoint `/entity` via `POST` which retrieves the last document 83 | /// in CruxDB. 84 | /// Field with `CruxId` is required. 85 | /// Response is a `reqwest::Result` with the last Entity with that ID. 86 | pub fn entity(&self, id: CruxId) -> Result { 87 | let crux_id = edn_rs::to_string(id); 88 | 89 | let mut s = String::new(); 90 | s.push_str("{:eid "); 91 | s.push_str(&crux_id); 92 | s.push_str("}"); 93 | 94 | let resp = self 95 | .client 96 | .post(&format!("{}/entity", self.uri)) 97 | .headers(self.headers.clone()) 98 | .body(s) 99 | .send()?; 100 | 101 | if resp.status().as_u16() < 300 { 102 | let resp_body = resp.text()?; 103 | let edn_resp = Edn::from_str(&resp_body.replace("#inst", "")); 104 | edn_resp.or_else(|_| { 105 | Err(CruxError::ResponseFailed(format!( 106 | "entity responded with {} for id \"{}\" ", 107 | 500, crux_id 108 | ))) 109 | }) 110 | } else { 111 | Err(CruxError::BadResponse(format!( 112 | "entity responded with {} for id \"{}\" ", 113 | resp.status().as_u16(), 114 | crux_id 115 | ))) 116 | } 117 | } 118 | 119 | /// Function `entity_timed` is like `entity` but with two optional fields `transaction_time` and `valid_time` that are of type `Option>`. 120 | pub fn entity_timed( 121 | &self, 122 | id: CruxId, 123 | transaction_time: Option>, 124 | valid_time: Option>, 125 | ) -> Result { 126 | let crux_id = edn_rs::to_string(id); 127 | 128 | let mut s = String::new(); 129 | s.push_str("{:eid "); 130 | s.push_str(&crux_id); 131 | s.push_str("}"); 132 | 133 | let url = build_timed_url(self.uri.clone(), "entity", transaction_time, valid_time); 134 | 135 | let resp = self 136 | .client 137 | .post(&url) 138 | .headers(self.headers.clone()) 139 | .body(s) 140 | .send()?; 141 | 142 | if resp.status().as_u16() < 300 { 143 | let resp_body = resp.text()?; 144 | let edn_resp = Edn::from_str(&resp_body.replace("#inst", "")); 145 | edn_resp.or_else(|_| { 146 | Err(CruxError::ResponseFailed(format!( 147 | "entity-timed responded with {} for id \"{}\" ", 148 | 500, crux_id 149 | ))) 150 | }) 151 | } else { 152 | Err(CruxError::BadResponse(format!( 153 | "entity-timed responded with {} for id \"{}\" ", 154 | resp.status().as_u16(), 155 | crux_id 156 | ))) 157 | } 158 | } 159 | 160 | /// Function `entity_tx` requests endpoint `/entity-tx` via `POST` which retrieves the docs and tx infos 161 | /// for the last document for that ID saved in CruxDB. 162 | pub fn entity_tx(&self, id: CruxId) -> Result { 163 | let crux_id = edn_rs::to_string(id); 164 | 165 | let mut s = String::new(); 166 | s.push_str("{:eid "); 167 | s.push_str(&crux_id); 168 | s.push_str("}"); 169 | 170 | let resp = self 171 | .client 172 | .post(&format!("{}/entity-tx", self.uri)) 173 | .headers(self.headers.clone()) 174 | .body(s) 175 | .send()?; 176 | 177 | if resp.status().as_u16() < 300 { 178 | let resp_body = resp.text()?; 179 | EntityTxResponse::from_str(&resp_body.replace("#inst", "")) 180 | } else { 181 | Err(CruxError::BadResponse(format!( 182 | "entity-tx responded with {} for id \"{}\" ", 183 | resp.status().as_u16(), 184 | crux_id 185 | ))) 186 | } 187 | } 188 | 189 | /// Function `entity_tx_timed` is like `entity_tx` but with two optional fields `transaction_time` and `valid_time` that are of type `Option>`. 190 | pub fn entity_tx_timed( 191 | &self, 192 | id: CruxId, 193 | transaction_time: Option>, 194 | valid_time: Option>, 195 | ) -> Result { 196 | let crux_id = edn_rs::to_string(id); 197 | 198 | let mut s = String::new(); 199 | s.push_str("{:eid "); 200 | s.push_str(&crux_id); 201 | s.push_str("}"); 202 | 203 | let url = build_timed_url(self.uri.clone(), "entity-tx", transaction_time, valid_time); 204 | 205 | let resp = self 206 | .client 207 | .post(&url) 208 | .headers(self.headers.clone()) 209 | .body(s) 210 | .send()?; 211 | 212 | if resp.status().as_u16() < 300 { 213 | let resp_body = resp.text()?; 214 | EntityTxResponse::from_str(&resp_body.replace("#inst", "")) 215 | } else { 216 | Err(CruxError::BadResponse(format!( 217 | "entity-tx-timed responded with {} for id \"{}\" ", 218 | resp.status().as_u16(), 219 | crux_id 220 | ))) 221 | } 222 | } 223 | 224 | /// Function `entity_history` requests endpoint `/entity-history` via `GET` which returns a list with all entity's transaction history. 225 | /// It is possible to order it with [`Order`](../types/http/enum.Order.html) , `types::http::Order::Asc` and `types::http::Order:Desc`, (second argument) and to include the document for each transaction with the boolean flag `with_docs` (third argument). 226 | pub fn entity_history( 227 | &self, 228 | hash: String, 229 | order: Order, 230 | with_docs: bool, 231 | ) -> Result { 232 | let url = format!( 233 | "{}/entity-history/{}?sort-order={}&with-docs={}", 234 | self.uri, 235 | hash, 236 | edn_rs::to_string(order), 237 | with_docs 238 | ); 239 | let resp = self.client.get(&url).headers(self.headers.clone()).send()?; 240 | 241 | if resp.status().as_u16() < 300 { 242 | let resp_body = resp.text()?; 243 | EntityHistoryResponse::from_str(&resp_body.replace("#inst", "")) 244 | } else { 245 | Err(CruxError::BadResponse(format!( 246 | "entity-history responded with {} for hash \"{}\" ", 247 | resp.status().as_u16(), 248 | hash 249 | ))) 250 | } 251 | } 252 | 253 | /// Function `entity_history_timed` is an txtension of the function `entity_history`. 254 | /// This function receives as the last argument a vector containing [`TimeHistory`](../types/http/enum.TimeHistory.html) elements. 255 | /// `TimeHistory` can be `ValidTime` or `TransactionTime` and both have optional `DateTime` params corresponding to the start-time and end-time to be queried. 256 | pub fn entity_history_timed( 257 | &self, 258 | hash: String, 259 | order: Order, 260 | with_docs: bool, 261 | time: Vec, 262 | ) -> Result { 263 | let url = format!( 264 | "{}/entity-history/{}?sort-order={}&with-docs={}{}", 265 | self.uri, 266 | hash, 267 | edn_rs::to_string(order), 268 | with_docs, 269 | edn_rs::to_string(time).replace("[", "").replace("]", ""), 270 | ); 271 | 272 | let resp = self.client.get(&url).headers(self.headers.clone()).send()?; 273 | 274 | if resp.status().as_u16() < 300 { 275 | let resp_body = resp.text()?; 276 | EntityHistoryResponse::from_str(&resp_body.replace("#inst", "")) 277 | } else { 278 | Err(CruxError::BadResponse(format!( 279 | "entity-hisotry-timed responded with {} for hash \"{}\" ", 280 | resp.status().as_u16(), 281 | hash 282 | ))) 283 | } 284 | } 285 | 286 | /// Function `query` requests endpoint `/query` via `POST` which retrives a Set containing a vector of the values defined by the function [`Query::find` - github example](https://github.com/naomijub/transistor/blob/master/examples/simple_query.rs#L53). 287 | /// Argument is a `query` of the type `Query`. 288 | pub fn query(&self, query: Query) -> Result>, CruxError> { 289 | let resp = self 290 | .client 291 | .post(&format!("{}/query", self.uri)) 292 | .headers(self.headers.clone()) 293 | .body(edn_rs::to_string(query)) 294 | .send()?; 295 | 296 | if resp.status().as_u16() < 300 { 297 | let resp_body = resp.text()?; 298 | let query_response: QueryResponse = edn_rs::from_str(&resp_body)?; 299 | 300 | Ok(query_response.0) 301 | } else { 302 | Err(CruxError::BadResponse(format!( 303 | "query responded with {}", 304 | resp.status().as_u16(), 305 | ))) 306 | } 307 | } 308 | } 309 | 310 | #[cfg(feature = "async")] 311 | impl HttpClient { 312 | pub async fn tx_log(&self, actions: Actions) -> Result { 313 | if actions.is_empty() { 314 | return Err(CruxError::TxLogActionError( 315 | "Actions cannot be empty.".to_string(), 316 | )); 317 | } 318 | 319 | let body = actions.build(); 320 | 321 | let resp = self 322 | .client 323 | .post(&format!("{}/tx-log", self.uri)) 324 | .headers(self.headers.clone()) 325 | .body(body) 326 | .send() 327 | .await? 328 | .text() 329 | .await?; 330 | 331 | edn_rs::from_str(&resp).map_err(|e| e.into()) 332 | } 333 | 334 | pub async fn tx_logs(&self) -> Result { 335 | let resp = self 336 | .client 337 | .get(&format!("{}/tx-log", self.uri)) 338 | .headers(self.headers.clone()) 339 | .send() 340 | .await? 341 | .text() 342 | .await?; 343 | 344 | TxLogsResponse::from_str(&resp) 345 | } 346 | 347 | pub async fn entity(&self, id: CruxId) -> Result { 348 | let crux_id = edn_rs::to_string(id); 349 | 350 | let mut s = String::new(); 351 | s.push_str("{:eid "); 352 | s.push_str(&crux_id); 353 | s.push_str("}"); 354 | 355 | let resp = self 356 | .client 357 | .post(&format!("{}/entity", self.uri)) 358 | .headers(self.headers.clone()) 359 | .body(s) 360 | .send() 361 | .await?; 362 | 363 | if resp.status().as_u16() < 300 { 364 | let resp_body = resp.text().await?; 365 | let edn_resp = Edn::from_str(&resp_body.replace("#inst", "")); 366 | edn_resp.or_else(|_| { 367 | Err(CruxError::ResponseFailed(format!( 368 | "entity responded with {} for id \"{}\" ", 369 | 500, crux_id 370 | ))) 371 | }) 372 | } else { 373 | Err(CruxError::BadResponse(format!( 374 | "entity responded with {} for id \"{}\" ", 375 | resp.status().as_u16(), 376 | crux_id 377 | ))) 378 | } 379 | } 380 | 381 | pub async fn entity_timed( 382 | &self, 383 | id: CruxId, 384 | transaction_time: Option>, 385 | valid_time: Option>, 386 | ) -> Result { 387 | let crux_id = edn_rs::to_string(id); 388 | 389 | let mut s = String::new(); 390 | s.push_str("{:eid "); 391 | s.push_str(&crux_id); 392 | s.push_str("}"); 393 | 394 | let url = build_timed_url(self.uri.clone(), "entity", transaction_time, valid_time); 395 | let resp = self 396 | .client 397 | .post(&url) 398 | .headers(self.headers.clone()) 399 | .body(s) 400 | .send() 401 | .await?; 402 | 403 | if resp.status().as_u16() < 300 { 404 | let resp_body = resp.text().await?; 405 | let edn_resp = Edn::from_str(&resp_body.replace("#inst", "")); 406 | edn_resp.or_else(|_| { 407 | Err(CruxError::ResponseFailed(format!( 408 | "entity responded with {} for id \"{}\" ", 409 | 500, crux_id 410 | ))) 411 | }) 412 | } else { 413 | Err(CruxError::BadResponse(format!( 414 | "entity responded with {} for id \"{}\" ", 415 | resp.status().as_u16(), 416 | crux_id 417 | ))) 418 | } 419 | } 420 | 421 | pub async fn entity_tx(&self, id: CruxId) -> Result { 422 | let crux_id = edn_rs::to_string(id); 423 | let mut s = String::new(); 424 | s.push_str("{:eid "); 425 | s.push_str(&crux_id); 426 | s.push_str("}"); 427 | 428 | let resp = self 429 | .client 430 | .post(&format!("{}/entity-tx", self.uri)) 431 | .headers(self.headers.clone()) 432 | .body(s) 433 | .send() 434 | .await?; 435 | 436 | if resp.status().as_u16() < 300 { 437 | let resp_body = resp.text().await?; 438 | EntityTxResponse::from_str(&resp_body.replace("#inst", "")) 439 | } else { 440 | Err(CruxError::BadResponse(format!( 441 | "entity-tx responded with {} for id \"{}\" ", 442 | resp.status().as_u16(), 443 | crux_id 444 | ))) 445 | } 446 | } 447 | 448 | pub async fn entity_tx_timed( 449 | &self, 450 | id: CruxId, 451 | transaction_time: Option>, 452 | valid_time: Option>, 453 | ) -> Result { 454 | let crux_id = edn_rs::to_string(id); 455 | let mut s = String::new(); 456 | s.push_str("{:eid "); 457 | s.push_str(&crux_id); 458 | s.push_str("}"); 459 | 460 | let url = build_timed_url(self.uri.clone(), "entity-tx", transaction_time, valid_time); 461 | 462 | let resp = self 463 | .client 464 | .post(&url) 465 | .headers(self.headers.clone()) 466 | .body(s) 467 | .send() 468 | .await?; 469 | 470 | if resp.status().as_u16() < 300 { 471 | let resp_body = resp.text().await?; 472 | EntityTxResponse::from_str(&resp_body.replace("#inst", "")) 473 | } else { 474 | Err(CruxError::BadResponse(format!( 475 | "entity-tx-timed responded with {} for id \"{}\" ", 476 | resp.status().as_u16(), 477 | crux_id 478 | ))) 479 | } 480 | } 481 | 482 | pub async fn entity_history( 483 | &self, 484 | hash: String, 485 | order: Order, 486 | with_docs: bool, 487 | ) -> Result { 488 | let url = format!( 489 | "{}/entity-history/{}?sort-order={}&with-docs={}", 490 | self.uri, 491 | hash.clone(), 492 | edn_rs::to_string(order), 493 | with_docs 494 | ); 495 | let resp = self 496 | .client 497 | .get(&url) 498 | .headers(self.headers.clone()) 499 | .send() 500 | .await?; 501 | 502 | if resp.status().as_u16() < 300 { 503 | let resp_body = resp.text().await?; 504 | EntityHistoryResponse::from_str(&resp_body.replace("#inst", "")) 505 | } else { 506 | Err(CruxError::BadResponse(format!( 507 | "entity-history responded with {} for hash \"{}\" ", 508 | resp.status().as_u16(), 509 | hash 510 | ))) 511 | } 512 | } 513 | 514 | pub async fn entity_history_timed( 515 | &self, 516 | hash: String, 517 | order: Order, 518 | with_docs: bool, 519 | time: Vec, 520 | ) -> Result { 521 | let url = format!( 522 | "{}/entity-history/{}?sort-order={}&with-docs={}{}", 523 | self.uri, 524 | hash.clone(), 525 | edn_rs::to_string(order), 526 | with_docs, 527 | edn_rs::to_string(time).replace("[", "").replace("]", ""), 528 | ); 529 | 530 | let resp = self 531 | .client 532 | .get(&url) 533 | .headers(self.headers.clone()) 534 | .send() 535 | .await?; 536 | 537 | if resp.status().as_u16() < 300 { 538 | let resp_body = resp.text().await?; 539 | EntityHistoryResponse::from_str(&resp_body.replace("#inst", "")) 540 | } else { 541 | Err(CruxError::BadResponse(format!( 542 | "entity-history-timed responded with {} for hash \"{}\" ", 543 | resp.status().as_u16(), 544 | hash 545 | ))) 546 | } 547 | } 548 | 549 | pub async fn query(&self, query: Query) -> Result>, CruxError> { 550 | let resp = self 551 | .client 552 | .post(&format!("{}/query", self.uri)) 553 | .headers(self.headers.clone()) 554 | .body(edn_rs::to_string(query)) 555 | .send() 556 | .await?; 557 | 558 | if resp.status().as_u16() < 300 { 559 | let resp_body = resp.text().await?; 560 | let query_response: QueryAsyncResponse = edn_rs::from_str(&resp_body)?; 561 | 562 | Ok(query_response.0) 563 | } else { 564 | Err(CruxError::BadResponse(format!( 565 | "query responded with {}", 566 | resp.status().as_u16(), 567 | ))) 568 | } 569 | } 570 | } 571 | 572 | fn build_timed_url( 573 | url: String, 574 | endpoint: &str, 575 | transaction_time: Option>, 576 | valid_time: Option>, 577 | ) -> String { 578 | match (transaction_time, valid_time) { 579 | (None, None) => format!("{}/{}", url, endpoint), 580 | (Some(tx), None) => format!( 581 | "{}/{}?transaction-time={}", 582 | url, 583 | endpoint, 584 | tx.format(DATE_FORMAT).to_string() 585 | ), 586 | (None, Some(valid)) => format!( 587 | "{}/{}?valid-time={}", 588 | url, 589 | endpoint, 590 | valid.format(DATE_FORMAT).to_string() 591 | ), 592 | (Some(tx), Some(valid)) => format!( 593 | "{}/{}?transaction-time={}&valid-time={}", 594 | url, 595 | endpoint, 596 | tx.format(DATE_FORMAT).to_string(), 597 | valid.format(DATE_FORMAT).to_string() 598 | ), 599 | } 600 | .replace("+", "%2B") 601 | } 602 | 603 | #[cfg(test)] 604 | mod http { 605 | use crate::client::Crux; 606 | use crate::types::http::Actions; 607 | use crate::types::http::Order; 608 | use crate::types::{ 609 | query::Query, 610 | response::{EntityHistoryElement, EntityHistoryResponse, EntityTxResponse, TxLogResponse}, 611 | CruxId, 612 | }; 613 | use edn_derive::Serialize; 614 | use mockito::mock; 615 | 616 | #[derive(Debug, Clone, Serialize)] 617 | #[allow(non_snake_case)] 618 | pub struct Person { 619 | crux__db___id: CruxId, 620 | first_name: String, 621 | last_name: String, 622 | } 623 | 624 | #[test] 625 | fn tx_log() { 626 | let _m = mock("POST", "/tx-log") 627 | .with_status(200) 628 | .match_body("[[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }], [:crux.tx/put { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", }]]") 629 | .with_header("content-type", "text/plain") 630 | .with_body("{:crux.tx/tx-id 8, :crux.tx/tx-time #inst \"2020-07-16T21:53:14.628-00:00\"}") 631 | .create(); 632 | 633 | let person1 = Person { 634 | crux__db___id: CruxId::new("jorge-3"), 635 | first_name: "Michael".to_string(), 636 | last_name: "Jorge".to_string(), 637 | }; 638 | 639 | let person2 = Person { 640 | crux__db___id: CruxId::new("manuel-1"), 641 | first_name: "Diego".to_string(), 642 | last_name: "Manuel".to_string(), 643 | }; 644 | 645 | let actions = Actions::new().append_put(person1).append_put(person2); 646 | 647 | let response = Crux::new("localhost", "4000").http_client().tx_log(actions); 648 | 649 | assert_eq!(response.unwrap(), TxLogResponse::default()) 650 | } 651 | 652 | #[test] 653 | #[should_panic(expected = "TxLogActionError(\"Actions cannot be empty.\")")] 654 | fn empty_actions_on_tx_log() { 655 | let actions = Actions::new(); 656 | 657 | let err = Crux::new("localhost", "4000").http_client().tx_log(actions); 658 | err.unwrap(); 659 | } 660 | 661 | #[test] 662 | fn tx_logs() { 663 | let _m = mock("GET", "/tx-log") 664 | .with_status(200) 665 | .with_header("content-type", "application/edn") 666 | .with_body("({:crux.tx/tx-id 0, :crux.tx/tx-time #inst \"2020-07-09T23:38:06.465-00:00\", :crux.tx.event/tx-events [[:crux.tx/put \"a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e\" \"125d29eb3bed1bf51d64194601ad4ff93defe0e2\"]]}{:crux.tx/tx-id 1, :crux.tx/tx-time #inst \"2020-07-09T23:39:33.815-00:00\", :crux.tx.event/tx-events [[:crux.tx/put \"a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e\" \"1b42e0d5137e3833423f7bb958622bee29f91eee\"]]})") 667 | .create(); 668 | 669 | let response = Crux::new("localhost", "4000").http_client().tx_logs(); 670 | 671 | assert_eq!(response.unwrap().tx_events.len(), 2); 672 | } 673 | 674 | #[test] 675 | #[should_panic( 676 | expected = "DeserializeError(\"The following Edn cannot be deserialized to TxLogs: Symbol(\\\"Holy\\\")\")" 677 | )] 678 | fn tx_log_error() { 679 | let _m = mock("GET", "/tx-log") 680 | .with_status(200) 681 | .with_header("content-type", "application/edn") 682 | .with_body("Holy errors!") 683 | .create(); 684 | 685 | let _error = Crux::new("localhost", "4000") 686 | .http_client() 687 | .tx_logs() 688 | .unwrap(); 689 | } 690 | 691 | #[test] 692 | fn entity() { 693 | let expected_body = "Map(Map({\":crux.db/id\": Key(\":hello-entity\"), \":first-name\": Str(\"Hello\"), \":last-name\": Str(\"World\")}))"; 694 | let _m = mock("POST", "/entity") 695 | .with_status(200) 696 | .match_body("{:eid :ivan}") 697 | .with_header("content-type", "application/edn") 698 | .with_body("{:crux.db/id :hello-entity :first-name \"Hello\", :last-name \"World\"}") 699 | .create(); 700 | 701 | let id = CruxId::new(":ivan"); 702 | let edn_body = Crux::new("localhost", "3000") 703 | .http_client() 704 | .entity(id) 705 | .unwrap(); 706 | 707 | let resp = format!("{:?}", edn_body); 708 | assert_eq!(resp, expected_body); 709 | } 710 | 711 | #[test] 712 | fn entity_tx() { 713 | let expected_body = "{:crux.db/id \"d72ccae848ce3a371bd313865cedc3d20b1478ca\", :crux.db/content-hash \"1828ebf4466f98ea3f5252a58734208cd0414376\", :crux.db/valid-time #inst \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-time #inst \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28}"; 714 | let _m = mock("POST", "/entity-tx") 715 | .with_status(200) 716 | .match_body("{:eid :ivan}") 717 | .with_header("content-type", "application/edn") 718 | .with_body(expected_body) 719 | .create(); 720 | 721 | let id = CruxId::new(":ivan"); 722 | let body = Crux::new("localhost", "3000") 723 | .http_client() 724 | .entity_tx(id) 725 | .unwrap(); 726 | 727 | assert_eq!(body, EntityTxResponse::default()); 728 | } 729 | 730 | #[test] 731 | fn simple_query() { 732 | let expected_body = "#{[:postgres \"Postgres\" true] [:mysql \"MySQL\" true]}"; 733 | let _m = mock("POST", "/query") 734 | .with_status(200) 735 | .with_header("content-type", "application/edn") 736 | .with_body(expected_body) 737 | .create(); 738 | 739 | let query = Query::find(vec!["?p1", "?n", "?s"]) 740 | .unwrap() 741 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"]) 742 | .unwrap() 743 | .build(); 744 | let body = Crux::new("localhost", "3000") 745 | .http_client() 746 | .query(query.unwrap()) 747 | .unwrap(); 748 | 749 | let response = format!("{:?}", body); 750 | assert_eq!( 751 | response, 752 | "{[\":mysql\", \"MySQL\", \"true\"], [\":postgres\", \"Postgres\", \"true\"]}" 753 | ); 754 | } 755 | 756 | #[test] 757 | fn simple_query_error() { 758 | let _m = mock("POST", "/query") 759 | .with_status(400) 760 | .with_header("content-type", "application/edn") 761 | .create(); 762 | 763 | let query = Query::find(vec!["?p1", "?n", "?s"]) 764 | .unwrap() 765 | .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"]) 766 | .unwrap() 767 | .build(); 768 | let body = Crux::new("localhost", "3000") 769 | .http_client() 770 | .query(query.unwrap()); 771 | 772 | assert!(body.is_err()) 773 | } 774 | 775 | #[test] 776 | fn entity_history() { 777 | let expected_body = "({:crux.tx/tx-time \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28, :crux.db/valid-time \"2020-07-19T04:12:13.788-00:00\", :crux.db/content-hash \"1828ebf4466f98ea3f5252a58734208cd0414376\"})"; 778 | let _m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false") 779 | .with_status(200) 780 | .with_header("content-type", "application/edn") 781 | .with_body(expected_body) 782 | .create(); 783 | 784 | let edn_body = Crux::new("localhost", "3000") 785 | .http_client() 786 | .entity_history( 787 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 788 | Order::Asc, 789 | false, 790 | ) 791 | .unwrap(); 792 | 793 | let expected = EntityHistoryResponse { 794 | history: vec![EntityHistoryElement::default()], 795 | }; 796 | 797 | assert_eq!(edn_body, expected); 798 | } 799 | 800 | #[test] 801 | fn entity_history_docs() { 802 | let expected_body = "({:crux.tx/tx-time \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28, :crux.db/valid-time \"2020-07-19T04:12:13.788-00:00\", :crux.db/content-hash \"1828ebf4466f98ea3f5252a58734208cd0414376\", :crux.db/doc :docs})"; 803 | let _m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=true") 804 | .with_status(200) 805 | .with_header("content-type", "application/edn") 806 | .with_body(expected_body) 807 | .create(); 808 | 809 | let edn_body = Crux::new("localhost", "3000") 810 | .http_client() 811 | .entity_history( 812 | "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(), 813 | Order::Asc, 814 | true, 815 | ) 816 | .unwrap(); 817 | 818 | let expected = EntityHistoryResponse { 819 | history: vec![EntityHistoryElement::default_docs()], 820 | }; 821 | 822 | assert_eq!(edn_body, expected); 823 | } 824 | } 825 | 826 | #[cfg(test)] 827 | mod build_url { 828 | use super::build_timed_url; 829 | use chrono::prelude::*; 830 | 831 | #[test] 832 | fn both_times_are_none() { 833 | let url = build_timed_url("localhost:3000".to_string(), "entity", None, None); 834 | 835 | assert_eq!(url, "localhost:3000/entity"); 836 | } 837 | 838 | #[test] 839 | fn both_times_are_some() { 840 | let url = build_timed_url( 841 | "localhost:3000".to_string(), 842 | "entity", 843 | Some( 844 | "2020-08-09T18:05:29.301-03:00" 845 | .parse::>() 846 | .unwrap(), 847 | ), 848 | Some( 849 | "2020-11-09T18:05:29.301-03:00" 850 | .parse::>() 851 | .unwrap(), 852 | ), 853 | ); 854 | 855 | assert_eq!(url, "localhost:3000/entity?transaction-time=2020-08-09T18:05:29-03:00&valid-time=2020-11-09T18:05:29-03:00"); 856 | } 857 | 858 | #[test] 859 | fn only_tx_time_is_some() { 860 | let url = build_timed_url( 861 | "localhost:3000".to_string(), 862 | "entity", 863 | Some( 864 | "2020-08-09T18:05:29.301-03:00" 865 | .parse::>() 866 | .unwrap(), 867 | ), 868 | None, 869 | ); 870 | 871 | assert_eq!( 872 | url, 873 | "localhost:3000/entity?transaction-time=2020-08-09T18:05:29-03:00" 874 | ); 875 | } 876 | 877 | #[test] 878 | fn only_valid_time_is_some() { 879 | let url = build_timed_url( 880 | "localhost:3000".to_string(), 881 | "entity", 882 | None, 883 | Some( 884 | "2020-08-09T18:05:29.301+03:00" 885 | .parse::>() 886 | .unwrap(), 887 | ), 888 | ); 889 | 890 | assert_eq!( 891 | url, 892 | "localhost:3000/entity?valid-time=2020-08-09T18:05:29%2B03:00" 893 | ); 894 | } 895 | } 896 | --------------------------------------------------------------------------------