Coverage for databases/sync_tests/types/raw_queries/test_json.py: 100%
30 statements
« prev ^ index » next coverage.py v7.2.7, created at 2024-08-27 18:25 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2024-08-27 18:25 +0000
1import json
3from pydantic import BaseModel
5from prisma import Json, Prisma
6from prisma.models import Types
8from ...._types import DatabaseMapping, SupportedDatabase
9from ...._compat import LiteralString
12class Queries(BaseModel):
13 select: LiteralString
16_postgresql_queries = Queries(
17 select='SELECT * FROM "Types" WHERE json_obj = $1',
18)
20RAW_QUERIES: DatabaseMapping[Queries] = {
21 'mysql': Queries(
22 select='SELECT * FROM Types WHERE json_obj->"$.foo" = ?',
23 ),
24 'mariadb': Queries(
25 select="SELECT * FROM Types WHERE JSON_CONTAINS(json_obj, '\"bar\"', '$.foo')",
26 ),
27 'sqlite': Queries(
28 select='SELECT * FROM Types WHERE json_obj = ?',
29 ),
30 'postgresql': _postgresql_queries,
31 'cockroachdb': _postgresql_queries,
32}
35def test_query_first(
36 client: Prisma,
37 database: SupportedDatabase,
38) -> None:
39 """Standard usage of json_obj in raw SELECT queries"""
40 queries = RAW_QUERIES[database]
42 record = client.types.create(
43 {
44 'json_obj': Json.keys(
45 foo='bar',
46 is_foo=True,
47 )
48 }
49 )
51 raw = {
52 'foo': 'bar',
53 'is_foo': True,
54 }
56 if database == 'mysql':
57 # filtering by the full JSON object does not work for MySQL
58 args = ['bar']
59 elif database == 'mariadb':
60 # I couldn't figure out the right syntax for passing query
61 # parameters for this case in MariaDB
62 args = []
63 else:
64 args = [raw]
66 found = client.query_first(queries.select, *args)
67 assert found['id'] == record.id
69 if database == 'mariadb':
70 # MariaDB will return JSON fields as a raw string
71 obj = json.loads(found['json_obj'])
72 else:
73 obj = found['json_obj']
75 assert obj == raw
76 assert obj['is_foo'] is True
78 model = client.query_first(queries.select, *args, model=Types)
79 assert model is not None
80 assert model.id == record.id
81 assert model.json_obj is not None
82 assert model.json_obj == raw
83 assert model.json_obj['is_foo'] is True