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

1import json 

2 

3from pydantic import BaseModel 

4 

5from prisma import Json, Prisma 

6from prisma.models import Types 

7 

8from ...._types import DatabaseMapping, SupportedDatabase 

9from ...._compat import LiteralString 

10 

11 

12class Queries(BaseModel): 

13 select: LiteralString 

14 

15 

16_postgresql_queries = Queries( 

17 select='SELECT * FROM "Types" WHERE json_obj = $1', 

18) 

19 

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} 

33 

34 

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] 

41 

42 record = client.types.create( 

43 { 

44 'json_obj': Json.keys( 

45 foo='bar', 

46 is_foo=True, 

47 ) 

48 } 

49 ) 

50 

51 raw = { 

52 'foo': 'bar', 

53 'is_foo': True, 

54 } 

55 

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] 

65 

66 found = client.query_first(queries.select, *args) 

67 assert found['id'] == record.id 

68 

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'] 

74 

75 assert obj == raw 

76 assert obj['is_foo'] is True 

77 

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