Advertisement
Guest User

Untitled

a guest
May 28th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. // shoutout to pythoneer!
  2. #[macro_export]
  3. macro_rules! def_model {
  4. (struct $name:ident {
  5. $($field_name:ident: $field_type:ty,)*
  6. }) => {
  7. struct $name {
  8. id: i32,
  9. $($field_name: $field_type,)*
  10. }
  11.  
  12. impl $name {
  13. fn new(id: i32, $($field_name: $field_type,)*) -> $name {
  14. $name {
  15. id: id,
  16. $($field_name: $field_name,)*
  17. }
  18. }
  19.  
  20. fn migrate(conn: rusqlite::Connection) {
  21. let mut query = format!("CREATE TABLE {} ( \n", stringify!($name));
  22. query.push_str("id INTEGER PRIMARY KEY, \n");
  23. $(query.push_str(&format!("{} TEXT NOT NULL, \n",
  24. stringify!($field_name)));)*
  25. query.push_str(")");
  26. println!("{}", query);
  27. conn.execute(&query, &[]);
  28. }
  29.  
  30. fn revert_migration() {
  31. unimplemented!();
  32. }
  33.  
  34. fn insert(&self) {
  35. // How to calculate the number of fields, $field_name here
  36. //let n_of_fields = 0 $(+ 1)* //this is too clever to work
  37.  
  38. let mut query = format!("INSERT INTO {} (", stringify!($name));
  39. $(query.push_str(&format!("{}, ", stringify!($field_name)));)*
  40. query.push_str(") \n");
  41. query.push_str("VALUES (");
  42.  
  43.  
  44. println!("{}", query);
  45.  
  46. }
  47.  
  48. fn get_field_names() -> Vec<&'static str> {
  49. println!("{}", stringify!($name));
  50. vec![$(stringify!($field_name)),*]
  51. }
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement