Skip to content

Commit

Permalink
Merge pull request #1523 from jamiecounsell/fix/mysql-json-contains
Browse files Browse the repository at this point in the history
Fix MySQL json_contains Error by Converting Non-String Values to JSON Strings
  • Loading branch information
zurdi15 authored Feb 1, 2025
2 parents 9117f6b + 72a0d2b commit 881a1d1
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions backend/utils/database.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from typing import Any

import sqlalchemy as sa
Expand All @@ -15,6 +16,10 @@ def is_postgresql(conn: sa.Connection) -> bool:
return conn.engine.name == "postgresql"


def is_mysql(conn: sa.Connection) -> bool:
return conn.engine.name == "mysql"


def json_array_contains_value(
column: sa.Column, value: Any, *, session: Session
) -> ColumnElement:
Expand All @@ -28,6 +33,9 @@ def json_array_contains_value(
return sa.type_coerce(column, sa_pg.JSONB).contains(
func.cast(value, sa_pg.JSONB)
)
elif is_mysql(conn):
# In MySQL, JSON.contains() requires a JSON-formatted string (even if it's an int)
return func.json_contains(column, json.dumps(value))
return func.json_contains(column, value)


Expand Down

0 comments on commit 881a1d1

Please sign in to comment.