using the C++ template engine library
https://github.com/pantor/inja
In SQL I can INSERT a row in a database with a VARCHAR SQL type column named 'col1' with
std::string my_template = "INSERT INTO [my_table] (col1) VALUES ('my_value');"
To note that the SQL VARCHAR type requires to single quote
'my_value'
To insert a SQL NULL value, the single quotes are not specified
"INSERT INTO [my_table] (col1) VALUES (NULL);"
I have a template where the value is single quoted, and it allows to insert string values like
std::string insert_template =
"INSERT INTO [my_table] (col1) VALUES ( '{{my_value}}' )";
nlohmann::json json;
json["my_value"] = "some_value";
std::string sql = inja::render(insert_template, json);
calling the template with a tentative insertion of SQL NULL as
nlohmann::json json;
json["my_value"] = "NULL";
is incorrect because the string is single quoted resulting in a SQL insertion of 'NULL' as a 4 character string and not an SQL NULL value
question
how can I make a condition to detect if the argument '{{my_value}}' )
should be single quoted or not in the case the value is "NULL" ?
defining the template as (not single quoted)
std::string insert_template =
"INSERT INTO [my_table] (col1) VALUES ( {{my_value}} )";
would work for a NULL value but not a string
so, I would want something like (in pseudo INJA syntax)
std::string insert_template =
"INSERT INTO [my_table] (col1) VALUES (
{% if my_value == NULL %}
{{my_value}}
{% else %}
'{{my_value}}'
{% endif %}
)";
Is this possible to achieve somehow?
"NULL"such a special case, as then you cannot search for this four-character string. Instead, I'd suggest to usestd::optional<std::string>to represent nullability and writing a quick wrapper aroundinja::render()(if it doesn't provide it yet).