Skip to content

Instantly share code, notes, and snippets.

@amodig
Created March 9, 2022 10:33
Show Gist options
  • Save amodig/890df0ec1af7ccdfef5c285f56818c43 to your computer and use it in GitHub Desktop.
Save amodig/890df0ec1af7ccdfef5c285f56818c43 to your computer and use it in GitHub Desktop.
Postgres upsert template
from jinja2 import Template
_POSTGRES_UPSERT_TEMPLATE = Template(
"""
--beginsql
INSERT INTO {{ target_table }}
{{ select_statement }}
ON CONFLICT ({{ primary_keys|join(', ') }}) DO UPDATE SET
{%- for col in target_cols %}
{%- if loop.first %}
{{ col }} = EXCLUDED.{{ col }}
{%- else %}
, {{ col }} = EXCLUDED.{{ col }}
{%- endif -%}
{%- endfor %}
--endsql
"""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment