Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // shoutout to pythoneer!
- #[macro_export]
- macro_rules! def_model {
- (struct $name:ident {
- $($field_name:ident: $field_type:ty,)*
- }) => {
- struct $name {
- id: i32,
- $($field_name: $field_type,)*
- }
- impl $name {
- fn new(id: i32, $($field_name: $field_type,)*) -> $name {
- $name {
- id: id,
- $($field_name: $field_name,)*
- }
- }
- fn migrate(conn: rusqlite::Connection) {
- let mut query = format!("CREATE TABLE {} ( \n", stringify!($name));
- query.push_str("id INTEGER PRIMARY KEY, \n");
- $(query.push_str(&format!("{} TEXT NOT NULL, \n",
- stringify!($field_name)));)*
- query.push_str(")");
- println!("{}", query);
- conn.execute(&query, &[]);
- }
- fn revert_migration() {
- unimplemented!();
- }
- fn insert(&self) {
- // How to calculate the number of fields, $field_name here
- //let n_of_fields = 0 $(+ 1)* //this is too clever to work
- let mut query = format!("INSERT INTO {} (", stringify!($name));
- $(query.push_str(&format!("{}, ", stringify!($field_name)));)*
- query.push_str(") \n");
- query.push_str("VALUES (");
- println!("{}", query);
- }
- fn get_field_names() -> Vec<&'static str> {
- println!("{}", stringify!($name));
- vec![$(stringify!($field_name)),*]
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement