Files
Inventory/scripts/normalize-dump.py

81 lines
1.7 KiB
Python

#!/usr/bin/env python3
import sys
TABLE_NAME_MAP = {
"ModelType": "model_types",
}
def normalize_identifiers(sql: str) -> str:
out = []
i = 0
in_single = False
length = len(sql)
while i < length:
ch = sql[i]
if in_single:
if ch == "'":
if i + 1 < length and sql[i + 1] == "'":
out.append("''")
i += 2
continue
in_single = False
out.append(ch)
i += 1
continue
if ch == "'":
in_single = True
out.append(ch)
i += 1
continue
if ch == '"':
i += 1
ident = []
while i < length:
if sql[i] == '"':
break
ident.append(sql[i])
i += 1
ident_str = ''.join(ident)
mapped = TABLE_NAME_MAP.get(ident_str)
if mapped is not None:
out.append(mapped)
else:
out.append(ident_str.lower())
if i < length and sql[i] == '"':
i += 1
continue
out.append(ch)
i += 1
return ''.join(out)
def main() -> int:
if len(sys.argv) != 3:
print("Usage: scripts/normalize-dump.py <input.sql> <output.sql>", file=sys.stderr)
return 1
src = sys.argv[1]
dst = sys.argv[2]
with open(src, "r", encoding="utf-8") as f:
data = f.read()
normalized = normalize_identifiers(data)
with open(dst, "w", encoding="utf-8") as f:
f.write(normalized)
return 0
if __name__ == "__main__":
raise SystemExit(main())