Coverage for databases/tests/types/raw_queries/test_json.py: 100%
32 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
3import pytest
4from pydantic import BaseModel
6from prisma import Json, Prisma
7from prisma.models import Types
9from ...._types import DatabaseMapping, SupportedDatabase
10from ...._compat import LiteralString
13class Queries(BaseModel):
14 select: LiteralString
17_postgresql_queries = Queries(
18 select='SELECT * FROM "Types" WHERE json_obj = $1',
19)
21RAW_QUERIES: DatabaseMapping[Queries] = {
22 'mysql': Queries(
23 select='SELECT * FROM Types WHERE json_obj->"$.foo" = ?',
24 ),
25 'mariadb': Queries(
26 select="SELECT * FROM Types WHERE JSON_CONTAINS(json_obj, '\"bar\"', '$.foo')",
27 ),
28 'sqlite': Queries(
29 select='SELECT * FROM Types WHERE json_obj = ?',
30 ),
31 'postgresql': _postgresql_queries,
32 'cockroachdb': _postgresql_queries,
33}
36@pytest.mark.asyncio
37async def test_query_first(
38 client: Prisma,
39 database: SupportedDatabase,
40) -> None:
41 """Standard usage of json_obj in raw SELECT queries"""
42 queries = RAW_QUERIES[database]
44 record = await client.types.create(
45 {
46 'json_obj': Json.keys(
47 foo='bar',
48 is_foo=True,
49 )
50 }
51 )
53 raw = {
54 'foo': 'bar',
55 'is_foo': True,
56 }
58 if database == 'mysql':
59 # filtering by the full JSON object does not work for MySQL
60 args = ['bar']
61 elif database == 'mariadb':
62 # I couldn't figure out the right syntax for passing query
63 # parameters for this case in MariaDB
64 args = []
65 else:
66 args = [raw]
68 found = await client.query_first(queries.select, *args)
69 assert found['id'] == record.id
71 if database == 'mariadb':
72 # MariaDB will return JSON fields as a raw string
73 obj = json.loads(found['json_obj'])
74 else:
75 obj = found['json_obj']
77 assert obj == raw
78 assert obj['is_foo'] is True
80 model = await client.query_first(queries.select, *args, model=Types)
81 assert model is not None
82 assert model.id == record.id
83 assert model.json_obj is not None
84 assert model.json_obj == raw
85 assert model.json_obj['is_foo'] is True