32 lines
796 B
Python
32 lines
796 B
Python
# backend/core/db_utils.py
|
|
|
|
from sqlalchemy import insert as sa_insert
|
|
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
|
from core.db import engine
|
|
|
|
_IS_PG = engine.url.get_backend_name().startswith("postgres")
|
|
|
|
def upsert(
|
|
tbl,
|
|
insert_values: dict,
|
|
conflict_cols: list[str],
|
|
update_values: dict | None = None,
|
|
):
|
|
|
|
if _IS_PG:
|
|
stmt = (
|
|
pg_insert(tbl)
|
|
.values(**insert_values)
|
|
.on_conflict_do_update(
|
|
index_elements=conflict_cols,
|
|
set_=update_values or insert_values,
|
|
)
|
|
)
|
|
else:
|
|
stmt = (
|
|
sa_insert(tbl)
|
|
.values(**insert_values)
|
|
.prefix_with("OR REPLACE") # SQLite
|
|
)
|
|
return stmt
|