migrate_job_to_template.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import re
  2. import pymysql
  3. import time
  4. conn = pymysql.connect(host='cq-cdb-8fjmemkb.sql.tencentcdb.com', port=27220, user='root', password='Ylrz_1q2w3e4r5t6y', database='ylrz_saas')
  5. cur = conn.cursor()
  6. with open(r'F:\project\Saas\ylrz_saas_his_scrm\sql\fs_task_sys_job_seed.sql', 'r', encoding='utf-8') as f:
  7. lines = f.readlines()
  8. col_names = ['job_id', 'job_name', 'job_group', 'invoke_target', 'cron_expression', 'misfire_policy', 'concurrent', 'status', 'create_by', 'create_time', 'update_by', 'update_time', 'remark']
  9. count = 0
  10. skipped = 0
  11. for line in lines:
  12. line = line.strip()
  13. if not line or not line.startswith('INSERT'):
  14. continue
  15. # Extract VALUES part: find the last (...) before the trailing ;
  16. idx = line.rfind('VALUES (')
  17. if idx == -1:
  18. continue
  19. vals_part = line[idx + 8:] # after "VALUES ("
  20. # Remove trailing ); or just )
  21. vals_part = vals_part.rstrip(';').rstrip(')')
  22. # Parse values with state machine (handles quotes and nested parens)
  23. vals = []
  24. current = ''
  25. depth = 0 # nested paren depth
  26. in_quote = False
  27. for ch in vals_part:
  28. if ch == "'" and not in_quote:
  29. in_quote = True
  30. current += ch
  31. elif ch == "'" and in_quote:
  32. # look for escaped quote ''
  33. in_quote = False
  34. current += ch
  35. elif ch == '(' and not in_quote:
  36. depth += 1
  37. current += ch
  38. elif ch == ')' and not in_quote:
  39. depth -= 1
  40. current += ch
  41. elif ch == ',' and not in_quote and depth == 0:
  42. vals.append(current.strip())
  43. current = ''
  44. else:
  45. current += ch
  46. if current.strip():
  47. vals.append(current.strip())
  48. # Build data dict
  49. data = {}
  50. for i, col in enumerate(col_names):
  51. if i < len(vals):
  52. v = vals[i].strip()
  53. if v.startswith("'") and v.endswith("'"):
  54. v = v[1:-1]
  55. if v.upper() == 'NULL':
  56. v = ''
  57. data[col] = v
  58. if 'job_name' not in data or not data.get('invoke_target'):
  59. skipped += 1
  60. continue
  61. target = data.get('invoke_target', '')
  62. # Check if already exists
  63. cur.execute('SELECT COUNT(*) FROM sys_job_template WHERE invoke_target=%s', (target,))
  64. if cur.fetchone()[0] > 0:
  65. print(f' SKIP (exists): {data.get("job_name", "")}')
  66. skipped += 1
  67. continue
  68. # Generate template_code
  69. code = data.get('invoke_target', '').replace('()', '').replace('.', '_')
  70. code = re.sub(r"[\(\)']", '', code)
  71. code = re.sub(r'[^\w]', '_', code)
  72. code = re.sub(r'_+', '_', code).strip('_')
  73. if len(code) > 60:
  74. code = code[:60]
  75. module_tag = data.get('job_group', 'DEFAULT')
  76. cur.execute(
  77. '''INSERT INTO sys_job_template
  78. (template_code, job_name, job_group, invoke_target, cron_expression, misfire_policy, concurrent, scope, module_tag, default_status, status, create_by, create_time, remark)
  79. VALUES (%s,%s,%s,%s,%s,%s,%s,'TENANT',%s,'1',%s,%s,%s,%s)''',
  80. (code,
  81. data.get('job_name', ''),
  82. module_tag,
  83. target,
  84. data.get('cron_expression', ''),
  85. data.get('misfire_policy', '1'),
  86. data.get('concurrent', '1'),
  87. module_tag,
  88. data.get('status', '0'),
  89. data.get('create_by', 'admin'),
  90. data.get('create_time', time.strftime('%Y-%m-%d %H:%M:%S')),
  91. data.get('remark', ''))
  92. )
  93. count += 1
  94. print(f' OK [{code}]: {data.get("job_name", "")}')
  95. conn.commit()
  96. cur.close()
  97. conn.close()
  98. print(f'\nInserted: {count}, Skipped: {skipped}')