mysqlx-connector-python 8.3.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mysqlx/dbdoc.py ADDED
@@ -0,0 +1,120 @@
1
+ # Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved.
2
+ #
3
+ # This program is free software; you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License, version 2.0, as
5
+ # published by the Free Software Foundation.
6
+ #
7
+ # This program is also distributed with certain software (including
8
+ # but not limited to OpenSSL) that is licensed under separate terms,
9
+ # as designated in a particular file or component or in included license
10
+ # documentation. The authors of MySQL hereby grant you an
11
+ # additional permission to link the program and your derivative works
12
+ # with the separately licensed software that they have included with
13
+ # MySQL.
14
+ #
15
+ # Without limiting anything contained in the foregoing, this file,
16
+ # which is part of MySQL Connector/Python, is also subject to the
17
+ # Universal FOSS Exception, version 1.0, a copy of which can be found at
18
+ # http://oss.oracle.com/licenses/universal-foss-exception.
19
+ #
20
+ # This program is distributed in the hope that it will be useful, but
21
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
22
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23
+ # See the GNU General Public License, version 2.0, for more details.
24
+ #
25
+ # You should have received a copy of the GNU General Public License
26
+ # along with this program; if not, write to the Free Software Foundation, Inc.,
27
+ # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28
+
29
+ """Implementation of the DbDoc."""
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+
35
+ from typing import Any, Dict, KeysView, Optional, Union
36
+
37
+ from .errors import ProgrammingError
38
+
39
+
40
+ class ExprJSONEncoder(json.JSONEncoder):
41
+ """A :class:`json.JSONEncoder` subclass, which enables encoding of
42
+ :class:`mysqlx.ExprParser` objects."""
43
+
44
+ def default(self, o: object) -> str:
45
+ if hasattr(o, "expr"):
46
+ return f"{o}"
47
+ # Let the base class default method raise the TypeError
48
+ return json.JSONEncoder.default(self, o)
49
+
50
+
51
+ class DbDoc:
52
+ """Represents a generic document in JSON format.
53
+
54
+ Args:
55
+ value (object): The value can be a JSON string or a dict.
56
+
57
+ Raises:
58
+ ValueError: If ``value`` type is not a basestring or dict.
59
+ """
60
+
61
+ def __init__(self, value: Union[str, Dict[str, Any]]) -> None:
62
+ if isinstance(value, dict):
63
+ self.__dict__ = value
64
+ elif isinstance(value, str):
65
+ self.__dict__ = json.loads(value)
66
+ else:
67
+ raise ValueError(f"Unable to handle type: {type(value)}")
68
+
69
+ def __str__(self) -> str:
70
+ return self.as_str()
71
+
72
+ def __repr__(self) -> str:
73
+ return repr(self.__dict__)
74
+
75
+ def __setitem__(self, index: str, value: Any) -> None:
76
+ if index == "_id":
77
+ raise ProgrammingError("Cannot modify _id")
78
+ self.__dict__[index] = value
79
+
80
+ def __getitem__(self, index: str) -> Any:
81
+ return self.__dict__[index]
82
+
83
+ def __contains__(self, item: str) -> bool:
84
+ return item in self.__dict__
85
+
86
+ def copy(self, doc_id: Optional[str] = None) -> DbDoc:
87
+ """Returns a new copy of a :class:`mysqlx.DbDoc` object containing the
88
+ `doc_id` provided. If `doc_id` is not provided, it will be removed from
89
+ new :class:`mysqlx.DbDoc` object.
90
+
91
+ Args:
92
+ doc_id (Optional[str]): Document ID
93
+
94
+ Returns:
95
+ mysqlx.DbDoc: A new instance of DbDoc containing the _id provided
96
+ """
97
+ new_dict = self.__dict__.copy()
98
+ if doc_id:
99
+ new_dict["_id"] = doc_id
100
+ elif "_id" in new_dict:
101
+ del new_dict["_id"]
102
+ return DbDoc(new_dict)
103
+
104
+ def keys(self) -> KeysView[str]:
105
+ """Returns the keys.
106
+
107
+ Returns:
108
+ `list`: The keys.
109
+ """
110
+ return self.__dict__.keys()
111
+
112
+ def as_str(self) -> str:
113
+ """Serialize :class:`mysqlx.DbDoc` to a JSON formatted ``str``.
114
+
115
+ Returns:
116
+ str: A JSON formatted ``str`` representation of the document.
117
+
118
+ .. versionadded:: 8.0.16
119
+ """
120
+ return json.dumps(self.__dict__, cls=ExprJSONEncoder)