MCPcopy Create free account
hub / github.com/piccolo-orm/piccolo / convert_to_sql_value

Function convert_to_sql_value

piccolo/utils/sql_values.py:14–50  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

12
13
14def 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

Callers 9

querystringMethod · 0.90
get_sql_valuesMethod · 0.90
clean_valueMethod · 0.90
test_convert_jsonMethod · 0.90
test_convert_enumMethod · 0.90
test_otherMethod · 0.90

Calls 2

dump_jsonFunction · 0.90
colored_warningFunction · 0.90

Tested by 6

test_convert_jsonMethod · 0.72
test_convert_enumMethod · 0.72
test_otherMethod · 0.72