0

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?

1
  • I wouldn't make "NULL" such a special case, as then you cannot search for this four-character string. Instead, I'd suggest to use std::optional<std::string> to represent nullability and writing a quick wrapper around inja::render() (if it doesn't provide it yet). Commented Jul 24, 2022 at 15:34

1 Answer 1

0

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    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.