_analyze_tables.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env python3
  2. """
  3. Parse ROHS SQL file to extract all table definitions (table name, columns, types),
  4. then connect to 安监 database to compare.
  5. """
  6. import re
  7. import json
  8. def parse_sql_file(filepath):
  9. """Parse the ROHS SQL file and extract table definitions."""
  10. with open(filepath, 'r', encoding='utf-8') as f:
  11. content = f.read()
  12. # Split by CREATE TABLE statements
  13. tables = {}
  14. # Find all CREATE TABLE blocks
  15. pattern = r'CREATE TABLE "SLAJ_ROHS"\."(\w+)"\s*\((.*?)\);'
  16. matches = re.finditer(pattern, content, re.DOTALL)
  17. for match in matches:
  18. table_name = match.group(1)
  19. columns_text = match.group(2)
  20. columns = []
  21. # Parse each column line
  22. for line in columns_text.strip().split('\n'):
  23. line = line.strip().rstrip(',')
  24. if not line or line.startswith('CONSTRAINT') or line.startswith('PRIMARY KEY') or line.startswith('UNIQUE') or line.startswith('CHECK') or line.startswith('USING'):
  25. continue
  26. # Extract column name and type
  27. # Pattern: "COLUMN_NAME" TYPE ... or COLUMN_NAME TYPE ...
  28. col_match = re.match(r'"?(\w+)"?\s+([\w\(\)\s,]+?)(?:\s+DEFAULT|\s+NOT\s+NULL|\s+NULL|\s*$|,)', line)
  29. if col_match:
  30. col_name = col_match.group(1).upper()
  31. col_type = col_match.group(2).strip().upper()
  32. columns.append({'name': col_name, 'type': col_type})
  33. tables[table_name] = columns
  34. return tables
  35. def extract_all_table_names(content):
  36. """Extract all table names from CREATE TABLE statements."""
  37. pattern = r'CREATE TABLE "SLAJ_ROHS"\."(\w+)"'
  38. return re.findall(pattern, content)
  39. if __name__ == '__main__':
  40. filepath = r'd:\Workspaces\slaj\docs\slaj-rohs_tbl-all_without-data_hg.sql'
  41. with open(filepath, 'r', encoding='utf-8') as f:
  42. content = f.read()
  43. tables = parse_sql_file(filepath)
  44. print(f"Total ROHS tables: {len(tables)}")
  45. print()
  46. # Categorize tables
  47. skip_tables = {t for t in tables if t.startswith('MLOG$_') or t.endswith('_BAK') or t.endswith('BAK') or
  48. '_BAK' in t or t.endswith('_20250407') or t.endswith('_0326') or t.endswith('_1125') or
  49. t.endswith('_BAK25') or t.endswith('_0731') or 'BAK2025' in t or '20250113' in t or
  50. '20250110' in t or '_MW' in t or '_MW_' in t or t.endswith('_MW')}
  51. real_tables = {k: v for k, v in tables.items() if k not in skip_tables}
  52. skipped = sorted({t for t in tables if t in skip_tables})
  53. print(f"Real tables (excluding backups/logs/materialized views): {len(real_tables)}")
  54. print(f"Skipped tables (backups/logs/MV): {len(skipped)}")
  55. print()
  56. print("=== REAL TABLES ===")
  57. for tname in sorted(real_tables.keys()):
  58. cols = real_tables[tname]
  59. print(f"\n{tname} ({len(cols)} columns):")
  60. for c in cols:
  61. print(f" {c['name']}: {c['type']}")
  62. print("\n=== SKIPPED TABLES ===")
  63. for t in skipped:
  64. print(f" {t} ({len(tables[t])} columns)")
  65. # Save as JSON for programmatic comparison
  66. with open(r'd:\Workspaces\slaj\_rohs_tables.json', 'w', encoding='utf-8') as f:
  67. json.dump(real_tables, f, indent=2, ensure_ascii=False)
  68. print(f"\nSaved ROHS tables to _rohs_tables.json")