qms_add_tenant_id_d4.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # -*- coding: utf-8 -*-
  2. """WP0-D4: add tenant_id to all qms_* tables (idempotent).
  3. 连接参数取自环境变量:MDP_DB_HOST / MDP_DB_PORT / MDP_DB_USER / MDP_DB_PASSWORD / MDP_DB_NAME
  4. """
  5. import os
  6. import pymysql
  7. DEFAULT_TENANT = None # 新环境不再 DEFAULT;存量回填由迁移脚本单独处理
  8. def main():
  9. c = pymysql.connect(
  10. host=os.environ.get("MDP_DB_HOST", "127.0.0.1"),
  11. port=int(os.environ.get("MDP_DB_PORT", "3306")),
  12. user=os.environ.get("MDP_DB_USER", "root"),
  13. password=os.environ.get("MDP_DB_PASSWORD", ""),
  14. database=os.environ.get("MDP_DB_NAME", "aidopdev"),
  15. charset="utf8mb4",
  16. connect_timeout=15,
  17. read_timeout=180,
  18. autocommit=True,
  19. )
  20. cur = c.cursor()
  21. cur.execute(
  22. """
  23. SELECT TABLE_NAME FROM information_schema.TABLES
  24. WHERE TABLE_SCHEMA='aidopdev' AND TABLE_TYPE='BASE TABLE' AND TABLE_NAME LIKE 'qms\\_%'
  25. ORDER BY TABLE_NAME
  26. """
  27. )
  28. tables = [r[0] for r in cur.fetchall()]
  29. added, skipped, errors = [], [], []
  30. for t in tables:
  31. cur.execute(
  32. """
  33. SELECT COUNT(*) FROM information_schema.COLUMNS
  34. WHERE TABLE_SCHEMA='aidopdev' AND TABLE_NAME=%s AND COLUMN_NAME='tenant_id'
  35. """,
  36. (t,),
  37. )
  38. if cur.fetchone()[0] > 0:
  39. skipped.append(t)
  40. continue
  41. cur.execute(
  42. """
  43. SELECT COLUMN_NAME FROM information_schema.COLUMNS
  44. WHERE TABLE_SCHEMA='aidopdev' AND TABLE_NAME=%s
  45. ORDER BY ORDINAL_POSITION LIMIT 1
  46. """,
  47. (t,),
  48. )
  49. first = cur.fetchone()[0]
  50. after = " AFTER `id`" if first.lower() == "id" else ""
  51. sql = (
  52. f"ALTER TABLE `{t}` ADD COLUMN `tenant_id` BIGINT NOT NULL "
  53. f"COMMENT 'tenant_id WP0-D4'{after}"
  54. )
  55. try:
  56. cur.execute(sql)
  57. except Exception as e1:
  58. try:
  59. cur.execute(
  60. f"ALTER TABLE `{t}` ADD COLUMN `tenant_id` BIGINT NOT NULL "
  61. f"COMMENT 'tenant_id WP0-D4'"
  62. )
  63. except Exception as e2:
  64. errors.append((t, str(e2) or str(e1)))
  65. print("ERR", t, e2)
  66. continue
  67. if DEFAULT_TENANT is not None:
  68. cur.execute(
  69. f"UPDATE `{t}` SET tenant_id=%s WHERE tenant_id IS NULL OR tenant_id=0",
  70. (DEFAULT_TENANT,),
  71. )
  72. idx = f"idx_{t}_tenant"[:64]
  73. try:
  74. cur.execute(f"CREATE INDEX `{idx}` ON `{t}` (`tenant_id`)")
  75. except Exception as ie:
  76. if "Duplicate" not in str(ie):
  77. print("IDX warn", t, ie)
  78. added.append(t)
  79. print("OK", t)
  80. cur.execute(
  81. """
  82. SELECT COUNT(*) FROM information_schema.COLUMNS
  83. WHERE TABLE_SCHEMA='aidopdev' AND TABLE_NAME LIKE 'qms\\_%' AND COLUMN_NAME='tenant_id'
  84. """
  85. )
  86. print("done added=", len(added), "skipped=", len(skipped), "errors=", len(errors), "with_tenant=", cur.fetchone()[0])
  87. c.close()
  88. if __name__ == "__main__":
  89. main()