append_server_user_store.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """Append ServerUserStore class to cq2_sdk store.py at the end."""
  2. import io
  3. target = r'D:\传奇\cq2_sdk\src\cq2_sdk\store.py'
  4. addition = '''
  5. # ----- ServerUserStore -----
  6. class ServerUserStore:
  7. """CRUD for the ``server_users`` binding table.
  8. Each (server_id, user_id) pair is unique. ``is_main=1`` flags the
  9. user that the daily 00:00 zone-sync job will use to call
  10. 996box's ``getTodayOpen`` for that server. Application layer
  11. enforces "at most one main per server" (MySQL 5.7 lacks partial
  12. unique indexes).
  13. """
  14. def __init__(self, conn: pymysql.connections.Connection) -> None:
  15. self.conn = conn
  16. def bind(self, server_id: int, user_id: int, server_name: str,
  17. username: str, is_main: int = 0) -> int:
  18. """Bind a user to a server. Idempotent. Returns the row id."""
  19. # 1. 若设主, 先把同 server 其它主清掉
  20. if is_main:
  21. with self.conn.cursor() as cur:
  22. cur.execute(
  23. "UPDATE server_users SET is_main=0 "
  24. "WHERE server_id=%s AND user_id<>%s AND is_main=1",
  25. (server_id, user_id),
  26. )
  27. # 2. upsert
  28. sql = """
  29. INSERT INTO server_users (server_id, user_id, server_name, username, is_main)
  30. VALUES (%s, %s, %s, %s, %s)
  31. ON DUPLICATE KEY UPDATE
  32. server_name = VALUES(server_name),
  33. username = VALUES(username),
  34. is_main = VALUES(is_main)
  35. """
  36. with self.conn.cursor() as cur:
  37. cur.execute(sql, (server_id, user_id, server_name, username, is_main))
  38. cur.execute(
  39. "SELECT id FROM server_users WHERE server_id=%s AND user_id=%s",
  40. (server_id, user_id),
  41. )
  42. row = cur.fetchone()
  43. return row["id"] if row else 0
  44. def get_main(self, server_id: int) -> ServerUser | None:
  45. with self.conn.cursor() as cur:
  46. cur.execute(
  47. "SELECT * FROM server_users WHERE server_id=%s AND is_main=1 LIMIT 1",
  48. (server_id,),
  49. )
  50. row = cur.fetchone()
  51. return ServerUser.from_row(row) if row else None
  52. def list_servers_with_main(self) -> list[ServerUser]:
  53. with self.conn.cursor() as cur:
  54. cur.execute(
  55. "SELECT * FROM server_users WHERE is_main=1 ORDER BY server_id"
  56. )
  57. return [ServerUser.from_row(r) for r in cur.fetchall()]
  58. '''
  59. with open(target, 'a', encoding='utf-8') as f:
  60. f.write(addition)
  61. print('appended ServerUserStore to', target)