|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | +import abc |
| 4 | +import collections |
| 5 | +import json |
| 6 | + |
| 7 | + |
| 8 | +class BaseMySqlRow(abc.ABC): |
| 9 | + |
| 10 | + @classmethod |
| 11 | + @abc.abstractmethod |
| 12 | + def from_json(cls, json_data: str) -> 'BaseMySqlRow': |
| 13 | + raise NotImplementedError |
| 14 | + |
| 15 | + @classmethod |
| 16 | + @abc.abstractmethod |
| 17 | + def from_dict(cls, dct: dict) -> 'BaseMySqlRow': |
| 18 | + raise NotImplementedError |
| 19 | + |
| 20 | + @abc.abstractmethod |
| 21 | + def __getitem__(self, key): |
| 22 | + raise NotImplementedError |
| 23 | + |
| 24 | + @abc.abstractmethod |
| 25 | + def __setitem__(self, key, value): |
| 26 | + raise NotImplementedError |
| 27 | + |
| 28 | + @abc.abstractmethod |
| 29 | + def to_json(self) -> str: |
| 30 | + raise NotImplementedError |
| 31 | + |
| 32 | + |
| 33 | +class BaseMySqlRowList(abc.ABC): |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +class MySqlRow(BaseMySqlRow, collections.UserDict): |
| 38 | + """A MySql Row. |
| 39 | +
|
| 40 | + MySqlRow objects are ''UserDict'' subclasses and behave like dicts. |
| 41 | + """ |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def from_json(cls, json_data: str) -> 'BaseMySqlRow': |
| 45 | + """Create a MySqlRow from a JSON string.""" |
| 46 | + return cls.from_dict(json.loads(json_data)) |
| 47 | + |
| 48 | + @classmethod |
| 49 | + def from_dict(cls, dct: dict) -> 'BaseMySqlRow': |
| 50 | + """Create a MySqlRow from a dict object""" |
| 51 | + return cls({k: v for k, v in dct.items()}) |
| 52 | + |
| 53 | + def to_json(self) -> str: |
| 54 | + """Return the JSON representation of the MySqlRow""" |
| 55 | + return json.dumps(dict(self)) |
| 56 | + |
| 57 | + def __getitem__(self, key): |
| 58 | + return collections.UserDict.__getitem__(self, key) |
| 59 | + |
| 60 | + def __setitem__(self, key, value): |
| 61 | + return collections.UserDict.__setitem__(self, key, value) |
| 62 | + |
| 63 | + def __repr__(self) -> str: |
| 64 | + return ( |
| 65 | + f'<MySqlRow at 0x{id(self):0x}>' |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +class MySqlRowList(BaseMySqlRowList, collections.UserList): |
| 70 | + "A ''UserList'' subclass containing a list of :class:'~MySqlRow' objects" |
| 71 | + pass |
0 commit comments