Skip to content

condition for quoting SQL NULL #251

@pedro-vicente

Description

@pedro-vicente

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 values like 'my_value'

std::string insert_template =
"INSERT INTO [my_table] (col1) VALUES ( '{{my_value}}' )";
nlohmann::json js;
to_json(js, my structure to convert to JSON);
std::string sql = inja::render(insert_template, js);

calling the template with a

std::string my_null = "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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions