base.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import abc
  2. from typing import List, Dict, Tuple, Union, Optional
  3. import logging.handlers
  4. import logging
  5. from configure import conf
  6. import os
  7. class DBException(Exception):
  8. ...
  9. class DBDoneException(DBException):
  10. ...
  11. class DBCloseException(DBException):
  12. ...
  13. class DBBit:
  14. BIT_0 = b'\x00'
  15. BIT_1 = b'\x01'
  16. class Database(metaclass=abc.ABCMeta):
  17. @abc.abstractmethod
  18. def __init__(self, host: str, name: str, passwd: str, port: str):
  19. self._host = str(host)
  20. self._name = str(name)
  21. self._passwd = str(passwd)
  22. if port is None:
  23. self._port = 3306
  24. else:
  25. self._port = int(port)
  26. self.logger = logging.getLogger("main.database")
  27. self.logger.setLevel(conf["log-level"])
  28. if conf["log-home"] is not None:
  29. handle = logging.handlers.TimedRotatingFileHandler(
  30. os.path.join(conf["log-home"], f"mysql-{os.getpid()}-{name}@{host}.log"))
  31. handle.setFormatter(logging.Formatter(conf["log-format"]))
  32. self.logger.addHandler(handle)
  33. @abc.abstractmethod
  34. def close(self):
  35. """
  36. 关闭数据库, 此代码执行后任何成员函数再被调用其行为是未定义的
  37. :return:
  38. """
  39. ...
  40. @abc.abstractmethod
  41. def is_connect(self) -> bool:
  42. """
  43. :return: 是否处于连接状态
  44. """
  45. ...
  46. @abc.abstractmethod
  47. def get_cursor(self) -> any:
  48. """
  49. :return: 返回数据库游标
  50. """
  51. ...
  52. @abc.abstractmethod
  53. def search(self, columns: List[str], table: str,
  54. where: Union[str, List[str]] = None,
  55. limit: Optional[int] = None,
  56. offset: Optional[int] = None,
  57. order_by: Optional[List[Tuple[str, str]]] = None):
  58. """
  59. 执行 查询 SQL语句
  60. :param columns: 列名称
  61. :param table: 表
  62. :param where: 条件
  63. :param limit: 限制行数
  64. :param offset: 偏移
  65. :param order_by: 排序方式
  66. :return:
  67. """
  68. ...
  69. @abc.abstractmethod
  70. def insert(self, table: str, columns: list, values: Union[str, List[str]]):
  71. """
  72. 执行 插入 SQL语句, 并提交
  73. :param table: 表
  74. :param columns: 列名称
  75. :param values: 数据
  76. :return:
  77. """
  78. ...
  79. @abc.abstractmethod
  80. def delete(self, table: str, where: Union[str, List[str]] = None):
  81. """
  82. 执行 删除 SQL语句, 并提交
  83. :param table: 表
  84. :param where: 条件
  85. :return:
  86. """
  87. ...
  88. @abc.abstractmethod
  89. def update(self, table: str, kw: "Dict[str:str]", where: Union[str, List[str]] = None):
  90. """
  91. 执行 更新 SQL语句, 并提交
  92. :param table: 表
  93. :param kw: 键值对
  94. :param where: 条件
  95. :return:
  96. """
  97. ...