I'm currently working on a library project for creating SQL-Queries and encountered a stack overflow when running a test with my InsertQuery struct.
The struct is defined as follows:
pub struct InsertQuery<'a> {
into: &'a str,
pub values: BTreeMap<&'a str, Value<'a>>,
}
'Value' is just an Enum that represents some basic MySQL data types (Value::Varchar(&'a str)...)
The struct has a method that returns a string representing the struct as a Query for use with databases called 'as_string' which is defined like this:
pub fn as_string(&self) -> String {
let mut res = String::new();
let (mut vals, mut vals_list) = (String::new(), String::new());
res = format!("INSERT INTO {}", self.into);
if !self.values.is_empty() {
let mut keys = self.values.keys();
let key = keys.next().unwrap();
vals = format!("{}", key);
vals_list = format!("{}", self.values[key]);
for k in keys {
vals = format!("{}, {}", vals, k);
vals_list = format!("{}, {}", vals_list, self.values[k]);
}
}
format!("{}({}) VALUES({})", res, vals, vals_list)
}
and the struct's constructor looks like this:
pub fn into(table: &'a str) -> InsertQuery<'a> {
InsertQuery {
into: table,
values: BTreeMap::new(),
}
}
And when running my test function
#[test]
fn insert_simple() {
let mut q = InsertQuery::into("users");
q.values.insert("name", Value::Varchar("greg"));
assert_eq!(q.as_string(), "INSERT INTO users(name) VALUES('greg')")
}
with 'cargo test' I end up with this error:
thread 'tests::insert_simple' has overflowed its stack fatal runtime error: stack overflow
error: process didn't exit successfully: `/home/elliot/Rust/libs/query_builder/target/debug /deps/query_builder-0ad36dfbc570aadb` (signal: 6, SIGABRT: process abort signal)
However, I already got an older implementation that works similar (also using BTreeMap<&'a str, Value<'a>>) which did not end up like this. The only differences are, that the older implementation had an internal String that was updated on every other call to the struct (the field 'values' was private and data was added via an extra method that just called the insert function on the map followed a call to update the string)
I do not understand why this one does overflow while the other one did not. Please help me to understand and fix this problem.
Thank you in advance