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?
this construct in the template chooses the quoted version or not depending on the value being "NULL"
nlohmann::json json4;
json4["name"] = "NULL";
std::string template5 = "INSERT INTO [my_table] (col1) VALUES ( \
{%if name == \"NULL\"%}\
{{name}}\
{%else%}\
'{{name}}'\
{%endif%}\
)";
std::string rendered5 = inja::render(template5, json4);
std::cout << rendered5 << std::endl;
rendered string is
INSERT INTO [my_table] (col1) VALUES ( NULL )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.