123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- from pathlib import Path
- def schema_convert(base_dir: str):
- base_dir = Path(base_dir).absolute()
- schema_file = base_dir / "schema.ini"
- with open(schema_file, "r", encoding="latin-1") as frh:
- schema = frh.read()
- # schema = schema.replace('\n\n', '\n').replace('\n\n', '\n')
- tables = dict([convert_table_info(t) for t in schema[1:].split("\n[")])
- tables_with_columns = {}
- for table, details in tables.items():
- table_file = base_dir / table
- if "schema.ini" in table or not table_file.exists():
- continue
- col_names = [c.split(" ")[0] for c in details["columns"].values()]
- tables_with_columns[table] = col_names
- create_format_xml_files(base_dir, tables_with_columns)
- def convert_table_info(table_info):
- info = table_info.split("]\n")
- if len(info) < 2:
- return ("", "")
- details = {}
- details["columns"] = {}
- for key, value in [row.split("=") for row in info[1].split("\n") if "=" in row]:
- if key.lower() != "colnameheader" and key.lower()[:3] == "col":
- details["columns"][key[3:]] = value
- return (info[0], details)
- def create_format_xml_files(base_dir, tables_with_columns: dict[str, list[str]]):
- for table, columns in tables_with_columns.items():
- format_file = base_dir / (table + ".xml")
- record = []
- row = []
- for i, col_name in enumerate(columns, 1):
- record.append(
- f' <FIELD ID="{i}" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="255" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>'
- )
- row.append(f' <COLUMN SOURCE="{i}" NAME="{col_name}" xsi:type="SQLVARYCHAR"/>')
- record[-1] = record[-1].replace(";", "\\r\\n")
- with open(format_file, "w") as fwh:
- fwh.write(
- '<?xml version="1.0"?>\n<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" '
- )
- fwh.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n <RECORD>\n')
- fwh.write("\n".join(record))
- fwh.write("\n </RECORD>\n <ROW>\n")
- fwh.write("\n".join(row))
- fwh.write("\n </ROW>\n</BCPFORMAT>")
- if __name__ == "__main__":
- schema_convert("C:\\GlobalCube_LOCOSOFT\\GCStruct_SKR51\\Kontenrahmen")
|