|
| 1 | +use skytable::{ |
| 2 | + query, |
| 3 | + query::{QList, SQParam}, |
| 4 | + response::{FromResponse, RList, Response, Row, Value}, |
| 5 | +}; |
| 6 | + |
| 7 | +/* |
| 8 | + our model looks like: |
| 9 | +
|
| 10 | + create model myapp.data( |
| 11 | + username: string, |
| 12 | + password: string, |
| 13 | + notes: list { type: string }, |
| 14 | + ) |
| 15 | +*/ |
| 16 | + |
| 17 | +#[derive(Debug, PartialEq)] |
| 18 | +struct BookmarkUser { |
| 19 | + username: String, |
| 20 | + password: String, |
| 21 | + notes: Vec<String>, |
| 22 | +} |
| 23 | + |
| 24 | +impl BookmarkUser { |
| 25 | + fn test_user() -> Self { |
| 26 | + Self { |
| 27 | + username: "sayan".to_owned(), |
| 28 | + password: "pass123".to_owned(), |
| 29 | + notes: vec![ |
| 30 | + "https://example.com".to_owned(), |
| 31 | + "https://skytable.org".to_owned(), |
| 32 | + "https://docs.skytable.org".to_owned(), |
| 33 | + ], |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl<'a> SQParam for &'a BookmarkUser { |
| 39 | + fn append_param(&self, q: &mut Vec<u8>) -> usize { |
| 40 | + self.username.append_param(q) |
| 41 | + + self.password.append_param(q) |
| 42 | + + QList::new(&self.notes).append_param(q) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl FromResponse for BookmarkUser { |
| 47 | + fn from_response(resp: Response) -> skytable::ClientResult<Self> { |
| 48 | + let (username, password, notes) = resp.parse::<(String, String, RList<String>)>()?; |
| 49 | + Ok(Self { |
| 50 | + username, |
| 51 | + password, |
| 52 | + notes: notes.into_values(), |
| 53 | + }) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#[test] |
| 58 | +fn dynlist_q() { |
| 59 | + let bu = BookmarkUser::test_user(); |
| 60 | + let q = query!( |
| 61 | + "insert into myapp.data { username: ?, password: ?, notes: ? }", |
| 62 | + &bu |
| 63 | + ); |
| 64 | + assert_eq!(q.param_cnt(), 3); |
| 65 | +} |
| 66 | + |
| 67 | +#[test] |
| 68 | +fn dynlist_r() { |
| 69 | + // assume that this is the response we got from the server (as a row); this may look messy but in a real-world application, the library does this for you |
| 70 | + // under the hood, so don't worry! you'll never have to write this yourself! |
| 71 | + let resp_from_server = Response::Row(Row::from(vec![ |
| 72 | + Value::String("sayan".to_owned()), |
| 73 | + Value::String("pass123".to_owned()), |
| 74 | + Value::List(vec![ |
| 75 | + Value::String("https://example.com".to_owned()), |
| 76 | + Value::String("https://skytable.org".to_owned()), |
| 77 | + Value::String("https://docs.skytable.org".to_owned()), |
| 78 | + ]), |
| 79 | + ])); |
| 80 | + // now this is our "fetch code" |
| 81 | + let user: BookmarkUser = resp_from_server.parse().unwrap(); |
| 82 | + assert_eq!(user, BookmarkUser::test_user()); |
| 83 | +} |
0 commit comments