Some values which can be passed into Piccolo queries aren't valid in the database. For example, Enums, Table instances, and dictionaries for JSON columns.
(value: Any, column: Column)
| 12 | |
| 13 | |
| 14 | def convert_to_sql_value(value: Any, column: Column) -> Any: |
| 15 | """ |
| 16 | Some values which can be passed into Piccolo queries aren't valid in the |
| 17 | database. For example, Enums, Table instances, and dictionaries for JSON |
| 18 | columns. |
| 19 | """ |
| 20 | from piccolo.columns.column_types import JSON, JSONB, ForeignKey |
| 21 | from piccolo.table import Table |
| 22 | |
| 23 | if isinstance(value, Table): |
| 24 | if isinstance(column, ForeignKey): |
| 25 | return getattr( |
| 26 | value, |
| 27 | column._foreign_key_meta.resolved_target_column._meta.name, |
| 28 | ) |
| 29 | elif column._meta.primary_key: |
| 30 | return getattr(value, column._meta.name) |
| 31 | else: |
| 32 | raise ValueError( |
| 33 | "Table instance provided, and the column isn't a ForeignKey, " |
| 34 | "or primary key column." |
| 35 | ) |
| 36 | elif isinstance(value, Enum): |
| 37 | return value.value |
| 38 | elif isinstance(column, (JSON, JSONB)) and not isinstance(value, str): |
| 39 | return None if value is None else dump_json(value) |
| 40 | elif isinstance(value, list): |
| 41 | if len(value) > 100: |
| 42 | colored_warning( |
| 43 | "When using large lists, consider bypassing the ORM and " |
| 44 | "using SQL directly for improved performance." |
| 45 | ) |
| 46 | # Attempt to do this as performantly as possible. |
| 47 | func = functools.partial(convert_to_sql_value, column=column) |
| 48 | return list(map(func, value)) |
| 49 | else: |
| 50 | return value |