_check_orphan.py 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. import pymysql
  2. from collections import defaultdict
  3. M=dict(host='cq-cdb-8fjmemkb.sql.tencentcdb.com',port=27220,user='root',password='Ylrz_1q2w3e4r5t6y',database='ylrz_saas',charset='utf8mb4')
  4. c=pymysql.connect(**M);cur=c.cursor(pymysql.cursors.DictCursor)
  5. cur.execute('SELECT menu_id, parent_id, menu_type FROM tenant_sys_menu')
  6. rows=cur.fetchall()
  7. ids={r['menu_id'] for r in rows}
  8. orph=[r for r in rows if r['parent_id'] not in ids and r['parent_id']!=0]
  9. print('orphans', len(orph))
  10. by=defaultdict(int)
  11. for r in rows: by[r['menu_type']]+=1
  12. print('types', dict(by))
  13. # reachable from roots
  14. roots=[r for r in rows if r['parent_id']==0]
  15. ch=defaultdict(list)
  16. for r in rows: ch[r['parent_id']].append(r)
  17. seen=set()
  18. stack=[r['menu_id'] for r in roots]
  19. while stack:
  20. mid=stack.pop()
  21. if mid in seen: continue
  22. seen.add(mid)
  23. for child in ch.get(mid,[]):
  24. stack.append(child['menu_id'])
  25. print('reachable', len(seen), 'total', len(rows), 'missing', len(rows)-len(seen))
  26. missing=[r for r in rows if r['menu_id'] not in seen]
  27. by2=defaultdict(int)
  28. for r in missing: by2[r['menu_type']]+=1
  29. print('missing by type', dict(by2))
  30. c.close()