Skip to content

Instantly share code, notes, and snippets.

@mersinvald
Last active August 19, 2016 23:43
Show Gist options
  • Select an option

  • Save mersinvald/0640eecfa824b13faadbf547ce638fcd to your computer and use it in GitHub Desktop.

Select an option

Save mersinvald/0640eecfa824b13faadbf547ce638fcd to your computer and use it in GitHub Desktop.
Insert query generator macro
#![feature(inclusive_range_syntax)]
macro_rules! new_model {
($struct_name:ident {
$( $arg:ident : $arg_type:ty ),*
}, table: $table:expr) => (
#[derive(Clone, Debug)]
pub struct $struct_name {
pub id: i32,
$ (
pub $arg: $arg_type,
)*
}
impl $struct_name {
pub fn new($($arg: $arg_type,)*) -> $struct_name {
$struct_name {
id: 0,
$(
$arg : $arg,
)*
}
}
pub fn insert_query() -> String {
let cnt = count!($($arg)*);
concat!("INSERT INTO ", $table, "(").to_owned()
+ &{ let mut s = String::new();
let mut i = 0;
$(
s.push_str(
&format!("{}{}", stringify!($arg), {
i += 1; if i < cnt { ", " } else { "" }
})
);
)*
s
} + ")"
+ " VALUES("
+ &{ let mut s = String::new();
for i in 1...cnt { s += &format!("${}{}", i, {
if i < cnt { ", " } else { "" }
});}
s
} + ")"
}
pub fn batch_insert_query(object: Self) -> String {
let cnt = count!($($arg)*);
concat!("INSERT INTO ", $table, "(").to_owned()
+ &{ let mut s = String::new();
let mut i = 0;
$(
s.push_str(
&format!("{}{}", stringify!($arg), {
i += 1; if i < cnt { ", " } else { "" }
})
);
)*
s
} + ")"
+ " VALUES("
+ &{ let mut s = String::new();
let mut i = 0;
$(
s.push_str(
&format!("{}{}", object.$arg, {
i += 1; if i < cnt { ", " } else { "" }
})
);
)*
s
} + ");"
}
}
)
}
macro_rules! count {
() => (0usize);
( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
}
new_model!(Args {
flag_flat: bool,
flag_all: bool,
cmd_new: bool,
cmd_done: bool,
cmd_del: bool,
cmd_clear: bool,
arg_list: String,
arg_task: String,
arg_description: String,
arg_num: i32
}, table: "args");
fn main() {
println!("{}", Args::insert_query());
// output:
// INSERT INTO args(flag_flat, flag_all, cmd_new, cmd_done, cmd_del, cmd_clear, arg_list, arg_task, arg_description, arg_num)
// VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment