diff --git a/examples/Cargo.toml b/examples/Cargo.toml deleted file mode 100644 index 9d2ff12..0000000 --- a/examples/Cargo.toml +++ /dev/null @@ -1,2 +0,0 @@ -[workspace] -members = ["basic", "actions", "aio", "custom-queries", "ddl", "custom-types"] diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index 41fe29b..0000000 --- a/examples/README.md +++ /dev/null @@ -1,31 +0,0 @@ -## Examples - -This directory contains multiple examples to help you get started with the Skytable client driver -for Rust. - -Example projects include: - -- The [`actions`](./actions) project provides examples of how you can use actions -- The [`aio`](./aio) project provides an usage of async features -- The [`basic`](./basic) project provides basic usage of the sync API -- The [`custom-queries`](./custom-queries) project provides examples of running custom queries -- The [`ddl`](./ddl) project provides examples of using DDL queries -- The [`custom-types`](./custom-types) project provides an example of using custom types (like `struct`s with the driver) - -## Building - -All the examples are part of a workspace and can be simply built by running `cargo build`. (You may need OpenSSL if you want to use TLS features). - -> **Important note:** You should **change** the version of the dependency **from this**: -> -> ```toml -> skytable = { version="0.7.1", features = ["const-gen"] } -> ``` -> -> **to this**: -> -> ```toml -> skytable = { version="*", features = ["const-gen"] } -> ``` -> -> (or the version you want to use) diff --git a/examples/actions/Cargo.toml b/examples/actions/Cargo.toml deleted file mode 100644 index 5c3a23f..0000000 --- a/examples/actions/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "actions" -version = "0.1.0" -authors = ["Sayan Nandan "] -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -# We use the `const-gen` feature to work with arrays; you can choose to leave it out -skytable = { version = "0.7.1", features = ["const-gen"] } diff --git a/examples/actions/src/main.rs b/examples/actions/src/main.rs deleted file mode 100644 index e53354e..0000000 --- a/examples/actions/src/main.rs +++ /dev/null @@ -1,18 +0,0 @@ -use skytable::{actions::Actions, types::RawString, Connection}; - -fn main() { - let mut con = Connection::new("127.0.0.1", 2003).unwrap(); - con.flushdb().unwrap(); - assert!( - con.mset(vec!["x", "y", "z"], vec!["100", "200", "300"]) - .unwrap() - == 3 - ); - let ret: Vec = con.mget(["x", "y", "z"]).unwrap(); - assert_eq!( - vec!["100".to_owned(), "200".to_owned(), "300".to_owned()], - ret - ); - let mybinarydata = RawString::from(vec![1, 2, 3, 4]); - assert!(con.set("mybindata", &mybinarydata).unwrap()); -} diff --git a/examples/aio/Cargo.toml b/examples/aio/Cargo.toml deleted file mode 100644 index 8788f99..0000000 --- a/examples/aio/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "aio" -version = "0.1.0" -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -skytable = { version = "0.7.1", features = [ - "const-gen", - "aio", -], default-features = false } -tokio = { version = "1.10.0", features = ["full"] } diff --git a/examples/aio/src/main.rs b/examples/aio/src/main.rs deleted file mode 100644 index 05a2bfd..0000000 --- a/examples/aio/src/main.rs +++ /dev/null @@ -1,22 +0,0 @@ -use skytable::actions::AsyncActions; -use skytable::aio::Connection; -use skytable::ConnectionBuilder; - -#[tokio::main] -async fn main() { - let mut con = Connection::new("127.0.0.1", 2003).await.unwrap(); - con.flushdb().await.unwrap(); - con.set("x", "100").await.unwrap(); - // example of getting a custom type - let get: u8 = con.get("x").await.unwrap(); - assert_eq!(get, 100); - - // doing the same thing using a connection builder - let _con = ConnectionBuilder::new() - .set_host("127.0.0.1".to_string()) - .set_port(2003) - .set_entity("default:default".to_owned()) - .get_async_connection() - .await - .unwrap(); -} diff --git a/examples/basic/Cargo.toml b/examples/basic/Cargo.toml deleted file mode 100644 index 8772814..0000000 --- a/examples/basic/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "basic" -version = "0.1.0" -authors = ["Sayan Nandan "] -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -skytable = { version = "0.7.1" } diff --git a/examples/basic/src/main.rs b/examples/basic/src/main.rs deleted file mode 100644 index e0f810e..0000000 --- a/examples/basic/src/main.rs +++ /dev/null @@ -1,19 +0,0 @@ -use skytable::actions::Actions; -use skytable::Connection; -use skytable::ConnectionBuilder; - -fn main() { - // simple example - let mut con = Connection::new("127.0.0.1", 2003).unwrap(); - con.set("sayan", "is writing code").unwrap(); - let get: String = con.get("sayan").unwrap(); - assert_eq!(get, "is writing code".to_owned()); - - // getting a connection using the connection builder - let _con = ConnectionBuilder::new() - .set_host("127.0.0.1".to_string()) - .set_port(2003) - .set_entity("default:default".to_owned()) - .get_connection() - .unwrap(); -} diff --git a/examples/custom-queries/Cargo.toml b/examples/custom-queries/Cargo.toml deleted file mode 100644 index f61668c..0000000 --- a/examples/custom-queries/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "custom-queries" -version = "0.1.0" -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -skytable = { version = "0.7.1" } diff --git a/examples/custom-queries/src/main.rs b/examples/custom-queries/src/main.rs deleted file mode 100644 index bbdaa93..0000000 --- a/examples/custom-queries/src/main.rs +++ /dev/null @@ -1,39 +0,0 @@ -use skytable::types::Array; -use skytable::{Connection, Element, Query}; - -fn main() { - // example of running and handling a custom query - - // initiate the connection - let mut con = Connection::new("127.0.0.1", 2003).unwrap(); - // create your query - let mut query = Query::from("MGET"); - query.push("x"); - query.push("y"); - query.push("z"); - // run it: you will either get a binary array if you declared your table - // to have the `binstr` type for values or you'll get a string array if - // you declared your table to have the `str` type for values - match con.run_query_raw(&query) { - Ok(Element::Array(Array::Bin(binarr))) => { - println!("Got a binary array!"); - for element in binarr { - match element { - Some(item) => println!("Got a blob: {:?}", item), - None => println!("Got null!"), - } - } - } - Ok(Element::Array(Array::Str(strarr))) => { - println!("Got a string array!"); - for element in strarr { - match element { - Some(item) => println!("Got a string: {}", item), - None => println!("Got null!"), - } - } - } - Ok(_) => eprintln!("Oh no, the server returned something bad!"), - Err(e) => eprintln!("Oh no, an error occurred: {}", e), - } -} diff --git a/examples/custom-types/Cargo.toml b/examples/custom-types/Cargo.toml deleted file mode 100644 index c642c50..0000000 --- a/examples/custom-types/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "custom-types" -version = "0.1.0" -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -skytable = { version = "0.7.1", features = ["const-gen"] } -serde_json = "1.0.68" -serde = { version = "1.0.130", features = ["derive"] } diff --git a/examples/custom-types/src/main.rs b/examples/custom-types/src/main.rs deleted file mode 100644 index a00bd46..0000000 --- a/examples/custom-types/src/main.rs +++ /dev/null @@ -1,62 +0,0 @@ -use serde::{Deserialize, Serialize}; -use skytable::actions::Actions; -use skytable::error::Error; -use skytable::sync::Connection; -use skytable::types::FromSkyhashBytes; -use skytable::types::IntoSkyhashBytes; -use skytable::Element; -use skytable::SkyResult; - -/// Our custom user type -#[derive(Serialize, Deserialize, PartialEq, Debug)] -pub struct User { - name: String, - email: String, - verified: bool, -} - -impl User { - pub fn new(name: String, email: String, verified: bool) -> Self { - Self { - name, - email, - verified, - } - } -} - -// Implement this for our type so that we can directly add it to queries -impl IntoSkyhashBytes for &User { - fn as_bytes(&self) -> Vec { - serde_json::to_string(self).unwrap().into_bytes() - } -} - -// Implement this for our type so that we can directly use it with actions/queries -impl FromSkyhashBytes for User { - fn from_element(e: Element) -> SkyResult { - // we want our JSON as a string - let my_value_as_string: String = e.try_element_into()?; - // now let us convert it into our struct - match serde_json::from_str(&my_value_as_string) { - // good, we got it - Ok(v) => Ok(v), - // nah, something bad happened. We'll turn the error into a string - // and return it - Err(e) => Err(Error::ParseError(e.to_string())), - } - } -} - -fn main() { - // let's create our user - let sayan = User::new("Sayan".to_string(), "ohsayan@outlook.com".to_string(), true); - // now connect to the server - let mut con = Connection::new("127.0.0.1", 2003).unwrap(); - // save our user in the database - con.set("sayan", &sayan).unwrap(); - // now get the user - let my_user: User = con.get("sayan").unwrap(); - // it'll be the same as our `sayan` variable! - assert_eq!(my_user, sayan); -} diff --git a/examples/custom_types.rs b/examples/custom_types.rs new file mode 100644 index 0000000..bb9696d --- /dev/null +++ b/examples/custom_types.rs @@ -0,0 +1,75 @@ +use skytable::{ + query, + query::SQParam, + response::{FromResponse, Response}, + ClientResult, Config, +}; + +#[derive(Debug, PartialEq, Clone)] +struct User { + username: String, + password: String, + followers: u64, + email: Option, +} + +impl User { + fn new(username: String, password: String, followers: u64, email: Option) -> Self { + Self { + username, + password, + followers, + email, + } + } +} + +impl SQParam for User { + fn append_param(&self, q: &mut Vec) -> usize { + self.username.append_param(q) + + self.password.append_param(q) + + self.followers.append_param(q) + + self.email.append_param(q) + } +} + +impl FromResponse for User { + fn from_response(resp: Response) -> ClientResult { + let (username, password, followers, email) = FromResponse::from_response(resp)?; + Ok(Self::new(username, password, followers, email)) + } +} + +fn main() { + let mut db = Config::new_default("username", "password") + .connect() + .unwrap(); + + // set up schema + // create space + db.query_parse::<()>(&query!("create space myspace")) + .unwrap(); + // create model + db.query_parse::<()>(&query!( + "create model myspace.mymodel(username: string, password: string, followers: uint64, null email: string" + )) + .unwrap(); + + // insert data + let our_user = User::new("myuser".into(), "pass123".into(), 0, None); + db.query_parse::<()>(&query!( + "insert into myspace.mymodel(?, ?, ?, ?)", + our_user.clone() + )) + .unwrap(); + + // select data + let ret_user: User = db + .query_parse(&query!( + "select * from myspace.mymodel WHERE username = ?", + &our_user.username + )) + .unwrap(); + + assert_eq!(our_user, ret_user); +} diff --git a/examples/ddl/Cargo.toml b/examples/ddl/Cargo.toml deleted file mode 100644 index 672ab51..0000000 --- a/examples/ddl/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "ddl" -version = "0.1.0" -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -skytable = { version = "0.7.1", features = ["const-gen"] } diff --git a/examples/ddl/src/main.rs b/examples/ddl/src/main.rs deleted file mode 100644 index 88329cb..0000000 --- a/examples/ddl/src/main.rs +++ /dev/null @@ -1,21 +0,0 @@ -use skytable::ddl::{Ddl, Keymap, KeymapType}; -use skytable::Connection; - -fn main() { - // initialize a connection - let mut con = Connection::new("127.0.0.1", 2003).unwrap(); - - // let's create the table - // our table is a key/value table has the type (str,binstr) - let mytable = Keymap::new("default:mytbl") - .set_ktype(KeymapType::Str) - .set_vtype(KeymapType::Binstr); - con.create_table(mytable).unwrap(); - - // now let's switch to the table - con.switch("default:mytbl").unwrap(); - // switch back to the default entity because we can't drop an entity while it's in use - con.switch("default:default").unwrap(); - // now let's drop the table - con.drop_table("default:mytbl").unwrap(); -} diff --git a/examples/simple.rs b/examples/simple.rs new file mode 100644 index 0000000..14f8bb6 --- /dev/null +++ b/examples/simple.rs @@ -0,0 +1,62 @@ +use skytable::{query, Config}; + +/// a dummy function to fetch username and password from a request +fn dummy_web_fetch_username_password() -> (String, String) { + ("rickastley".into(), "rick123".into()) +} + +fn dummy_respond_to_request(_followers: u64) {} + +fn main() { + let mut db = Config::new_default("username", "password") + .connect() + .unwrap(); + + // set up schema + // create space + db.query_parse::<()>(&query!("create space myspace")) + .unwrap(); + // create model + db.query_parse::<()>(&query!( + "create model myspace.mymodel(username: string, password: string, followers: uint64" + )) + .unwrap(); + + // manipulate data + + let (form_username, form_pass) = dummy_web_fetch_username_password(); + // insert some data + db.query_parse::<()>(&query!( + "insert into myspace.mymodel(?, ?, ?)", + &form_username, + form_pass, + 100_000_000u64 + )) + .unwrap(); + + // get it back + let (password, followers): (String, u64) = db + .query_parse(&query!( + "select password, followers FROM myspace.mymodel WHERE username = ?", + &form_username + )) + .unwrap(); + assert_eq!(password, "rick123", "password changed!"); + // send to our client + dummy_respond_to_request(followers); + + // update followers to account for huge numbers who were angry after being rickrolled + db.query_parse::<()>(&query!( + "update myspace.mymodel SET followers -= ? WHERE username = ?", + 50_000_000u64, + &form_username + )) + .unwrap(); + + // alright, everyone is tired from being rickrolled so we'll have to ban rick's account + db.query_parse::<()>(&query!( + "delete from myspace.mymodel where username = ?", + &form_username + )) + .unwrap(); +} diff --git a/src/query.rs b/src/query.rs index 1f449b8..1ea7938 100644 --- a/src/query.rs +++ b/src/query.rs @@ -278,6 +278,11 @@ impl<'a> SQParam for &'a str { 1 } } +impl<'a> SQParam for &'a String { + fn append_param(&self, q: &mut Vec) -> usize { + self.as_str().append_param(q) + } +} impl SQParam for String { fn append_param(&self, buf: &mut Vec) -> usize { self.as_str().append_param(buf)