| 86 | |
| 87 | |
| 88 | def import_sql_dump(conn, sql_path: Path) -> None: |
| 89 | with conn.cursor() as cursor: |
| 90 | statement_lines = [] |
| 91 | with sql_path.open(encoding="utf-8") as sql_file: |
| 92 | while True: |
| 93 | line = sql_file.readline() |
| 94 | if line == "": |
| 95 | break |
| 96 | stripped = line.strip() |
| 97 | if not stripped or stripped.startswith("--"): |
| 98 | continue |
| 99 | statement_lines.append(line) |
| 100 | if not stripped.endswith(";"): |
| 101 | continue |
| 102 | |
| 103 | statement = "".join(statement_lines) |
| 104 | statement_lines.clear() |
| 105 | if statement.lstrip().upper().startswith("COPY ") and " FROM stdin;" in statement: |
| 106 | with cursor.copy(statement) as copy: |
| 107 | while True: |
| 108 | copy_line = sql_file.readline() |
| 109 | if copy_line == "": |
| 110 | raise RuntimeError(f"Unterminated COPY block in {sql_path}") |
| 111 | if copy_line.strip() == r"\.": |
| 112 | break |
| 113 | copy.write(copy_line) |
| 114 | else: |
| 115 | cursor.execute(statement) |
| 116 | |
| 117 | if statement_lines: |
| 118 | cursor.execute("".join(statement_lines)) |
| 119 | conn.commit() |
| 120 | |
| 121 | |
| 122 | def main() -> int: |