mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
This change introduces PostgreSQL compatibility, by implementing the following changes: * Use `JSONB` instead of `JSON` for PostgreSQL databases. This is achieved by creating a custom `CustomJSON` type that uses `JSONB` on PostgreSQL and `JSON` on other databases, leveraging the variant mechanism of SQLAlchemy. * Add `is_postgresql` function to check if the current database is PostgreSQL. Commonly used for migrations, but can be used to determine how to build queries based on the database engine. * Add `json_array_contains_value` function to check if a JSON array includes a specific value. This function is needed as it's engine-specific. Support for PostgreSQL is on a best-effort basis, and it relies on the community for continued support and testing. The project's main database is MariaDB. Closes #667.
26 lines
811 B
Python
26 lines
811 B
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):
|
|
return sa.type_coerce(column, sa_pg.JSONB()).has_key(value)
|
|
return func.json_contains(column, value)
|