{# Commonly used macros related to basic SQL syntax formatting #}-- noqa:disable=JJ01

{%- macro comma_delineate(loop) -%}
{%- if not loop.last -%}
, 
{%- endif -%}
{%- endmacro -%}

{%- macro period_delineate(loop) -%}
{%- if not loop.last -%}
.
{%- endif -%}
{%- endmacro -%}

{%- macro union_delineate(loop) -%}
{%- if not loop.last -%}
UNION
{%- endif -%}
{%- endmacro -%}

{%- macro union_all_delineate(loop) -%}
{%- if not loop.last -%}
UNION ALL
{%- endif -%}
{%- endmacro -%}

{# Note that the following two delineations are meant to be at the front of the string
in a loop - this is to enable formatting in a WHERE statement like this:
---
WHERE
    b.bar = a.foo
    AND b.baz != a.foo
---
This is slightly easier to work with when debugging queries (and also
conforms better to the mozilla style guide)
#}
{%- macro and_delineate(loop) -%}
{%- if not loop.first -%}AND {% endif -%}
{%- endmacro -%}

{%- macro or_delineate(loop) -%}
{%- if not loop.first -%}OR {% endif -%}
{%- endmacro -%}

{#- The intent of this macro is to convert sql wildcard format to regex syntax.
 So for example, a value of macro_string like:

https://fhir.cerner.com/%/codeSet/71

will be converted into a regex-escaped pattern with a regex match anything pattern:

https:\/\/fhir\.cerner\.com\/(.*)\/codeSet\/71 

See https://trino.io/docs/current/functions/regexp.html for more information. We
are applying a limited ruleset currently, since this is based on common patterns
in coding system fields, where this is currently used; if needed this could be
made more robust.
-#}
{%- macro wildcard_to_regex(match_string) -%}
{{ match_string.replace("\'", "\\\''").replace(".", "\\.").replace("%", ".*") }}
{%- endmacro -%}


{#- This macro provides a SQL LIKE-esque interface to abstract away having to
worry about the slightly more performant regex based matching we want to use
in most cases.
-#}
{%- macro like(field, match_string) -%}
REGEXP_LIKE({{ field }}, '^{{ wildcard_to_regex(match_string) }}$')
{%- endmacro -%}

{%- macro ilike(field, match_string) -%}
REGEXP_LIKE({{ field }}, '^(?i:{{ wildcard_to_regex(match_string) }})$')
{%- endmacro -%}

{#- Checks for NULL, empty, whitespace-only, and '\u0000' strings
(We've seen Cerner give back strings with just a single NUL char.) -#}
{% macro is_string_valid(field) -%}
(
    {{ field }} IS NOT NULL
    AND TRIM({{ field }}) <> ''
    AND {{ field }} <> CHR(0)
)
{%- endmacro %}

{#- converts a string to be safe for use in table/column names -#}
{% macro sql_safe_string(field) -%}
{{ field|lower|replace('.', '_') }}
{%- endmacro%}
