Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/sqlalchemy/dialects/sqlite/json.py: 33%

30 statements  

« prev     ^ index     » next       coverage.py v7.0.1, created at 2022-12-25 06:11 +0000

1from ... import types as sqltypes 

2 

3 

4class JSON(sqltypes.JSON): 

5 """SQLite JSON type. 

6 

7 SQLite supports JSON as of version 3.9 through its JSON1_ extension. Note 

8 that JSON1_ is a 

9 `loadable extension <https://www.sqlite.org/loadext.html>`_ and as such 

10 may not be available, or may require run-time loading. 

11 

12 :class:`_sqlite.JSON` is used automatically whenever the base 

13 :class:`_types.JSON` datatype is used against a SQLite backend. 

14 

15 .. seealso:: 

16 

17 :class:`_types.JSON` - main documentation for the generic 

18 cross-platform JSON datatype. 

19 

20 The :class:`_sqlite.JSON` type supports persistence of JSON values 

21 as well as the core index operations provided by :class:`_types.JSON` 

22 datatype, by adapting the operations to render the ``JSON_EXTRACT`` 

23 function wrapped in the ``JSON_QUOTE`` function at the database level. 

24 Extracted values are quoted in order to ensure that the results are 

25 always JSON string values. 

26 

27 

28 .. versionadded:: 1.3 

29 

30 

31 .. _JSON1: https://www.sqlite.org/json1.html 

32 

33 """ 

34 

35 

36# Note: these objects currently match exactly those of MySQL, however since 

37# these are not generalizable to all JSON implementations, remain separately 

38# implemented for each dialect. 

39class _FormatTypeMixin(object): 

40 def _format_value(self, value): 

41 raise NotImplementedError() 

42 

43 def bind_processor(self, dialect): 

44 super_proc = self.string_bind_processor(dialect) 

45 

46 def process(value): 

47 value = self._format_value(value) 

48 if super_proc: 

49 value = super_proc(value) 

50 return value 

51 

52 return process 

53 

54 def literal_processor(self, dialect): 

55 super_proc = self.string_literal_processor(dialect) 

56 

57 def process(value): 

58 value = self._format_value(value) 

59 if super_proc: 

60 value = super_proc(value) 

61 return value 

62 

63 return process 

64 

65 

66class JSONIndexType(_FormatTypeMixin, sqltypes.JSON.JSONIndexType): 

67 def _format_value(self, value): 

68 if isinstance(value, int): 

69 value = "$[%s]" % value 

70 else: 

71 value = '$."%s"' % value 

72 return value 

73 

74 

75class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType): 

76 def _format_value(self, value): 

77 return "$%s" % ( 

78 "".join( 

79 [ 

80 "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem 

81 for elem in value 

82 ] 

83 ) 

84 )