garbage.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import time
  2. from db import DB, DBBit, DBDataException, DBDoneException
  3. from tool.type_ import *
  4. from tool.time_ import HGSTime, mysql_time, time_from_mysql
  5. from core.garbage import GarbageBag, GarbageType
  6. class GarbageDBException(DBDataException):
  7. ...
  8. def update_garbage_type(where: str, type_: int, db: DB) -> int:
  9. if len(where) == 0:
  10. return -1
  11. cur = db.done(f"UPDATE garbage SET GarbageType={type_} WHERE {where};")
  12. if cur is None:
  13. return -1
  14. return cur.rowcount
  15. def update_garbage_check(where: str, check_: bool, db: DB) -> int:
  16. if len(where) == 0:
  17. return -1
  18. i = 1 if check_ else 0
  19. cur = db.done(f"UPDATE garbage SET CheckResult={i} WHERE {where};")
  20. if cur is None:
  21. return -1
  22. return cur.rowcount
  23. def __get_time(time_str: str) -> float:
  24. if time_str == 'now':
  25. return time.time()
  26. if time_str.startswith("Date:") and len(time_str) >= 5:
  27. return time_from_mysql(time_str[5:])
  28. return float(time_str)
  29. def __get_time_diff(time_str: str) -> float:
  30. if time_str.endswith("s") and len(time_str) >= 2:
  31. return float(time_str[:-1])
  32. elif time_str.endswith("ms") and len(time_str) >= 3:
  33. return float(time_str[:-1]) / 1000
  34. elif time_str.endswith("min") and len(time_str) >= 4:
  35. return float(time_str[:-1]) * 60
  36. elif time_str.endswith("h") and len(time_str) >= 2:
  37. return float(time_str[:-1]) * 60 * 60
  38. elif time_str.endswith("d") and len(time_str) >= 2:
  39. return float(time_str[:-1]) * 24 * 60 * 60
  40. return float(time_str)
  41. def __search_fields_time(time_: str, time_name: str) -> str:
  42. if time_ == '<=now':
  43. return f"{time_name}<={mysql_time()} AND"
  44. sp = time_.split(',')
  45. if len(sp) == 2:
  46. try:
  47. time_list = __get_time(sp[0]), __get_time(sp[1])
  48. a = min(time_list)
  49. b = max(time_list)
  50. except (TypeError, ValueError):
  51. return ""
  52. else:
  53. return f"({time_name} BETWEEN {mysql_time(a)} AND {mysql_time(b)}) AND"
  54. sp = time_.split(';')
  55. if len(sp) == 2:
  56. try:
  57. time_list = __get_time(sp[0]), __get_time_diff(sp[1])
  58. a = time_list[0] - time_list[1]
  59. b = time_list[0] + time_list[1]
  60. except (TypeError, ValueError):
  61. return ""
  62. else:
  63. return f"({time_name} BETWEEN {mysql_time(a)} AND {mysql_time(b)}) AND"
  64. try:
  65. t = __get_time(time_)
  66. except (TypeError, ValueError):
  67. return ""
  68. else:
  69. return f"({time_name}={mysql_time(t)} AND"
  70. def search_garbage_by_fields(columns, gid, uid, cuid, create_time, use_time, loc, type_, check, db: DB):
  71. where = ""
  72. if gid is not None:
  73. where += f"GarbageID={gid} AND "
  74. if uid is not None:
  75. where += f"UserID=‘{uid}’ AND "
  76. if cuid is not None:
  77. where += f"CheckerID='{cuid}' AND "
  78. if loc is not None:
  79. where += f"Location='{loc}' AND "
  80. if check is not None:
  81. if check == "False":
  82. where += f"CheckResult=0 AND "
  83. else:
  84. where += f"CheckResult=1 AND "
  85. if type_ is not None and type_ in GarbageType.GarbageTypeStrList:
  86. res = GarbageType.GarbageTypeStrList.index(type_)
  87. where += f"Phone={res} AND "
  88. if create_time is not None:
  89. where += __search_fields_time(create_time, "CreateTime")
  90. if use_time is not None:
  91. where += __search_fields_time(use_time, "UseTime")
  92. if len(where) != 0:
  93. where = where[0:-4] # 去除末尾的AND
  94. return search_from_garbage_view(columns, where, db)
  95. def search_from_garbage_view(columns, where: str, db: DB):
  96. if len(where) > 0:
  97. where = f"WHERE {where} "
  98. column = ", ".join(columns)
  99. cur = db.search(f"SELECT {column} FROM garbage {where};")
  100. if cur is None:
  101. return None
  102. res = cur.fetchall()
  103. return res
  104. def count_garbage_by_time(uid: uid_t, db: DB):
  105. ti: time_t = time.time()
  106. start = ti - 3.5 * 24 * 60 * 60 # 前后3.5天
  107. end = ti + 3.5 * 24 * 60 * 60
  108. cur = db.search(f"SELECT GarbageID "
  109. f"FROM garbage_time "
  110. f"WHERE UserID = '{uid}' AND UseTime BETWEEN {mysql_time(start)} AND {mysql_time(end)};")
  111. if cur is None:
  112. return -1
  113. return cur.rowcount
  114. def __find_garbage(sql: str, res_len, db: DB):
  115. cur = db.search(sql)
  116. if cur is None or cur.rowcount == 0:
  117. return [None, tuple()]
  118. assert cur.rowcount == 1
  119. res = cur.fetchone()
  120. assert len(res) == res_len
  121. return GarbageBag(str(res[0])), res
  122. def find_not_use_garbage(gid: gid_t, db: DB) -> Union[GarbageBag, None]:
  123. return __find_garbage(f"SELECT GarbageID FROM garbage_n WHERE GarbageID = {gid};", 1, db)[0]
  124. def find_wait_garbage(gid: gid_t, db: DB) -> Union[GarbageBag, None]:
  125. res: Tuple[int, bytes, str, str, str]
  126. gb: GarbageBag
  127. gb, res = __find_garbage(f"SELECT GarbageID, GarbageType, UseTime, UserID, Location "
  128. f"FROM garbage_c "
  129. f"WHERE GarbageID = {gid};", 5, db)
  130. if gb is None:
  131. return None
  132. garbage_type: enum = int(res[1].decode())
  133. use_time: time_t = time_from_mysql(res[2])
  134. uid: uid_t = res[3]
  135. loc: location_t = res[4]
  136. gb.config_use(garbage_type, use_time, uid, loc)
  137. return gb
  138. def find_use_garbage(gid: gid_t, db: DB) -> Union[GarbageBag, None]:
  139. res: Tuple[int, bytes, str, str, str, bytes]
  140. gb: GarbageBag
  141. gb, res = __find_garbage(f"SELECT GarbageID, GarbageType, UseTime, UserID, Location, CheckResult, CheckerID "
  142. f"FROM garbage_u "
  143. f"WHERE GarbageID = {gid};", 7, db)
  144. if gb is None:
  145. return None
  146. garbage_type: enum = int(res[1].decode())
  147. use_time: time_t = time_from_mysql(res[2])
  148. uid: uid_t = res[3]
  149. loc: location_t = res[4]
  150. check: bool = res[5] == DBBit.BIT_1
  151. check_uid: uid_t = res[6]
  152. gb.config_use(garbage_type, use_time, uid, loc)
  153. gb.config_check(check, check_uid)
  154. return gb
  155. def find_garbage(gid: gid_t, db: DB) -> Union[GarbageBag, None]:
  156. res: Tuple[bool, int] = is_garbage_exists(gid, db)
  157. if not res[0]:
  158. return None
  159. elif res[1] == 0:
  160. re = find_not_use_garbage(gid, db)
  161. elif res[1] == 1:
  162. re = find_wait_garbage(gid, db)
  163. elif res[1] == 2:
  164. re = find_use_garbage(gid, db)
  165. else:
  166. re = None
  167. assert re is not None
  168. return re
  169. def is_garbage_exists(gid: gid_t, db: DB) -> Tuple[bool, int]:
  170. cur = db.search(f"SELECT GarbageID, Flat FROM garbage WHERE GarbageID = {gid};")
  171. if cur is None or cur.rowcount == 0:
  172. return False, 0
  173. assert cur.rowcount == 1
  174. res: Tuple[int, int] = cur.fetchone()
  175. return True, res[1]
  176. def update_garbage(garbage: GarbageBag, db: DB) -> bool:
  177. re = find_garbage(garbage.get_gid(), db)
  178. if re is None:
  179. return False
  180. if re.is_use() and not garbage.is_use() or re.is_check()[0] and not garbage.is_check():
  181. return False
  182. if not garbage.is_use() and not garbage.is_check()[0]:
  183. return True # 不做任何修改
  184. gid = garbage.get_gid()
  185. info = garbage.get_info()
  186. try:
  187. if garbage.is_check()[0]:
  188. db.done_(f"UPDATE garbage SET "
  189. f"Flat = 2,"
  190. f"UserID = '{info['user']}',"
  191. f"UseTime = {time_from_mysql(info['use_time'])},"
  192. f"GarbageType = {info['type']},"
  193. f"Location = '{info['loc']}',"
  194. f"CheckResult = {info['check']},"
  195. f"CheckerID = '{info['checker']}',"
  196. f"WHERE GarbageID = {gid};")
  197. elif garbage.is_use():
  198. db.done_(f"UPDATE garbage SET "
  199. f"Flat = 1,"
  200. f"UserID = '{info['user']}',"
  201. f"UseTime = {time_from_mysql(info['use_time'])},"
  202. f"GarbageType = {info['type']},"
  203. f"Location = '{info['loc']}',"
  204. f"CheckResult = NULL,"
  205. f"CheckerID = NULL,"
  206. f"WHERE GarbageID = {gid};")
  207. else:
  208. db.done_(f"UPDATE garbage SET "
  209. f"Flat = 0,"
  210. f"UserID = NULL,"
  211. f"UseTime = NULL,"
  212. f"GarbageType = NULL,"
  213. f"Location = NULL,"
  214. f"CheckResult = NULL,"
  215. f"CheckerID = NULL,"
  216. f"WHERE GarbageID = {gid};")
  217. except DBDoneException:
  218. return False
  219. finally:
  220. db.done_commit()
  221. return True
  222. def create_new_garbage(db: DB) -> Optional[GarbageBag]:
  223. cur = db.done(f"INSERT INTO garbage(CreateTime, Flat) VALUES ({mysql_time()}, 0);")
  224. if cur is None:
  225. return None
  226. assert cur.rowcount == 1
  227. gid = cur.lastrowid
  228. return GarbageBag(str(gid))
  229. def del_garbage_not_use(gid: gid_t, db: DB) -> bool:
  230. cur = db.done(f"DELETE FROM garbage_n WHERE GarbageID = {gid};")
  231. if cur is None or cur.rowcount == 0:
  232. return False
  233. assert cur.rowcount == 1
  234. return True
  235. def del_garbage_wait_check(gid: gid_t, db: DB) -> bool:
  236. cur = db.done(f"DELETE FROM garbage_c WHERE GarbageID = {gid};")
  237. if cur is None or cur.rowcount == 0:
  238. return False
  239. assert cur.rowcount == 1
  240. return True
  241. def del_garbage_has_check(gid: gid_t, db: DB) -> bool:
  242. cur = db.done(f"DELETE FROM garbage_u WHERE GarbageID = {gid};")
  243. if cur is None or cur.rowcount == 0:
  244. return False
  245. assert cur.rowcount == 1
  246. return True
  247. def del_garbage(gid, db: DB):
  248. cur = db.done(f"DELETE FROM garbage WHERE GarbageID = {gid};")
  249. if cur is None or cur.rowcount == 0:
  250. return False
  251. assert cur.rowcount == 1
  252. return True
  253. def del_garbage_where_not_use(where, db: DB) -> int:
  254. cur = db.done_(f"DELETE FROM garbage_n WHERE {where};")
  255. if cur is None:
  256. return -1
  257. return cur.rowcount
  258. def del_garbage_where_wait_check(where, db: DB) -> int:
  259. cur = db.done_(f"DELETE FROM garbage_c WHERE {where};")
  260. if cur is None:
  261. return -1
  262. return cur.rowcount
  263. def del_garbage_where_has_check(where, db: DB) -> int:
  264. cur = db.done_(f"DELETE FROM garbage_u WHERE {where};")
  265. if cur is None:
  266. return -1
  267. return cur.rowcount
  268. def del_garbage_where_scan_not_use(where, db: DB) -> int:
  269. cur = db.done(f"SELECT GarbageID FROM garbage_n WHERE {where};")
  270. if cur is None:
  271. return -1
  272. return cur.rowcount
  273. def del_garbage_where_scan_wait_check(where, db: DB) -> int:
  274. cur = db.done(f"SELECT GarbageID FROM garbage_c WHERE {where};")
  275. if cur is None:
  276. return -1
  277. return cur.rowcount
  278. def del_garbage_where_scan_has_check(where, db: DB) -> int:
  279. cur = db.done(f"SELECT GarbageID FROM garbage_u WHERE {where};")
  280. if cur is None:
  281. return -1
  282. return cur.rowcount
  283. def del_all_garbage(db: DB) -> int:
  284. cur = db.done(f"DELETE FROM garbage WHERE 1;")
  285. if cur is None:
  286. return -1
  287. return cur.rowcount
  288. def del_all_garbage_scan(db: DB) -> int:
  289. cur = db.done(f"SELECT GarbageID FROM garbage WHERE 1;")
  290. if cur is None:
  291. return -1
  292. return cur.rowcount
  293. if __name__ == '__main__':
  294. mysql_db = DB()
  295. bag = create_new_garbage(mysql_db)
  296. print(bag)
  297. bag.config_use(GarbageType.recyclable, HGSTime(), "1e1d30a1f9b78c8fa852d19b4cfaee79", "HuaDu")
  298. update_garbage(bag, mysql_db)
  299. print(bag)
  300. bag = find_garbage(bag.get_gid(), mysql_db)
  301. print(bag)
  302. bag.config_check(True, "048529ca5c6accf594b74e6f73ee1bf0")
  303. update_garbage(bag, mysql_db)
  304. print(bag)
  305. bag = find_garbage(bag.get_gid(), mysql_db)
  306. print(bag)
  307. print(count_garbage_by_time("1e1d30a1f9b78c8fa852d19b4cfaee79", mysql_db))