schema_ini_convert.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from pathlib import Path
  2. def schema_convert(base_dir: str):
  3. base_dir = Path(base_dir).absolute()
  4. schema_file = base_dir / "schema.ini"
  5. with open(schema_file, "r", encoding="latin-1") as frh:
  6. schema = frh.read()
  7. # schema = schema.replace('\n\n', '\n').replace('\n\n', '\n')
  8. tables = dict([convert_table_info(t) for t in schema[1:].split("\n[")])
  9. tables_with_columns = {}
  10. for table, details in tables.items():
  11. table_file = base_dir / table
  12. if "schema.ini" in table or not table_file.exists():
  13. continue
  14. col_names = [c.split(" ")[0] for c in details["columns"].values()]
  15. tables_with_columns[table] = col_names
  16. create_format_xml_files(base_dir, tables_with_columns)
  17. def convert_table_info(table_info):
  18. info = table_info.split("]\n")
  19. if len(info) < 2:
  20. return ("", "")
  21. details = {}
  22. details["columns"] = {}
  23. for key, value in [row.split("=") for row in info[1].split("\n") if "=" in row]:
  24. if key.lower() != "colnameheader" and key.lower()[:3] == "col":
  25. details["columns"][key[3:]] = value
  26. return (info[0], details)
  27. def create_format_xml_files(base_dir, tables_with_columns: dict[str, list[str]]):
  28. for table, columns in tables_with_columns.items():
  29. format_file = base_dir / (table + ".xml")
  30. record = []
  31. row = []
  32. for i, col_name in enumerate(columns, 1):
  33. record.append(
  34. f' <FIELD ID="{i}" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="255" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>'
  35. )
  36. row.append(f' <COLUMN SOURCE="{i}" NAME="{col_name}" xsi:type="SQLVARYCHAR"/>')
  37. record[-1] = record[-1].replace(";", "\\r\\n")
  38. with open(format_file, "w") as fwh:
  39. fwh.write(
  40. '<?xml version="1.0"?>\n<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" '
  41. )
  42. fwh.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n <RECORD>\n')
  43. fwh.write("\n".join(record))
  44. fwh.write("\n </RECORD>\n <ROW>\n")
  45. fwh.write("\n".join(row))
  46. fwh.write("\n </ROW>\n</BCPFORMAT>")
  47. if __name__ == "__main__":
  48. schema_convert("C:\\GlobalCube_LOCOSOFT\\GCStruct_SKR51\\Kontenrahmen")