Files
romm/backend/utils/database.py
Michael Manganiello 7825bce7b8 fix: Use proper JSON contains function for PostgreSQL
Fix `json_array_contains_value` function to use the `@>` operator for
checking if a JSON array contains a value in PostgreSQL. This is
necessary because the `has_key` function only works for string values.

Also, remove `get_rom_collections` method, as it was doing the same
thing as `get_collections_by_rom_id`.

Fixes #1441.
2025-01-08 21:07:01 -03:00

32 lines
1.1 KiB
Python

from typing import Any
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as sa_pg
from sqlalchemy.orm import Session
from sqlalchemy.sql import ColumnElement, func
def CustomJSON(**kwargs: Any) -> sa.JSON:
"""Custom SQLAlchemy JSON type that uses JSONB on PostgreSQL."""
return sa.JSON(**kwargs).with_variant(sa_pg.JSONB(**kwargs), "postgresql")
def is_postgresql(conn: sa.Connection) -> bool:
return conn.engine.name == "postgresql"
def json_array_contains_value(
column: sa.Column, value: Any, *, session: Session
) -> ColumnElement:
"""Check if a JSON array column contains a single value."""
conn = session.get_bind()
if is_postgresql(conn):
# In PostgreSQL, string values can be checked for containment using the `?` operator.
# For other types, we use the `@>` operator.
if isinstance(value, str):
return sa.type_coerce(column, sa_pg.JSONB).has_key(value)
return sa.type_coerce(column, sa_pg.JSONB).contains(
func.cast(value, sa_pg.JSONB)
)
return func.json_contains(column, value)