Repository navigation
Expand file tree
/
Copy pathsplit_dump.py
More file actions
504 lines (425 loc) · 19.4 KB
/
Copy pathsplit_dump.py
File metadata and controls
504 lines (425 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#!/usr/bin/env python3
"""
split_dump.py - split a huge mysqldump file into per-table (and per-chunk)
pieces, then import them one at a time with resume-on-failure.
# 1. split (streams the file, never loads it into RAM)
python split_dump.py split dump.sql --out parts --max-chunk-mb 200
# 2. import (re-run the exact same command after any failure)
python split_dump.py import parts --host 127.0.0.1 --user root --db mydb
The importer logs every finished part to parts/_progress.log, so if the
connection drops at part 137 you just re-run it and it resumes at 137.
Assumes standard `mysqldump` output: one SQL statement per line, newlines
inside string data escaped as \\n. That is what mysqldump produces by default.
"""
from __future__ import annotations
import argparse
import gzip
import os
import re
import subprocess
import sys
import time
from getpass import getpass
from pathlib import Path
# --- markers in a normal (commented) mysqldump ------------------------------
TABLE_RE = re.compile(rb"^-- Table structure for table `(.+)`")
VIEW_TMP_RE = re.compile(rb"^-- Temporary (?:table|view) structure for view `(.+)`")
VIEW_FIN_RE = re.compile(rb"^-- Final view structure for view `(.+)`")
ROUTINES_RE = re.compile(rb"^-- Dumping routines for database")
# --- markers used by --mode generic (dumps made with --skip-comments) -------
DROP_RE = re.compile(rb"^DROP TABLE IF EXISTS `(.+?)`")
CREATE_RE = re.compile(rb"^CREATE TABLE (?:IF NOT EXISTS )?`(.+?)`")
LOCK_RE = re.compile(rb"^(LOCK TABLES |UNLOCK TABLES)")
HEADER_NAME = "000_header.sql"
PROGRESS_NAME = "_progress.log"
SKIPPED_NAME = "_skipped_errors.log"
ERR_RE = re.compile(r"^ERROR (\d+)", re.M)
# handy presets for --ignore-errors
ERROR_PRESETS = {
"1146": "table doesn't exist (view/trigger referencing another schema)",
"1050": "table already exists",
"1062": "duplicate entry",
"1091": "can't drop; doesn't exist",
"1449": "definer user doesn't exist",
"1227": "access denied (need SUPER for definer)",
}
FAST_PREAMBLE = b"""
-- injected by split_dump.py
SET autocommit=0;
SET unique_checks=0;
SET foreign_key_checks=0;
"""
NOBINLOG_PREAMBLE = b"SET sql_log_bin=0;\n"
def human(n: float) -> str:
for unit in ("B", "KB", "MB", "GB", "TB"):
if n < 1024 or unit == "TB":
return f"{n:.1f}{unit}"
n /= 1024
return f"{n:.1f}TB"
def sanitize(name) -> str:
if isinstance(name, bytes):
name = name.decode("utf-8", "replace")
return re.sub(r"[^A-Za-z0-9_.-]", "_", name)[:80] or "unnamed"
class PartWriter:
"""Writes 0001_tablename.001.sql, 0001_tablename.002.sql, ..."""
def __init__(self, outdir: Path, max_bytes: int):
self.outdir = outdir
self.max_bytes = max_bytes
self.fh = None
self.label = None
self.index = 0
self.part = 0
self.written = 0
self.files: list[Path] = []
def start(self, label: str):
self.close()
self.index += 1
self.label = label
self.part = 0
self._open()
def _open(self):
self.part += 1
path = self.outdir / f"{self.index:04d}_{self.label}.{self.part:03d}.sql"
self.fh = open(path, "wb")
self.written = 0
self.files.append(path)
if self.part > 1:
self.fh.write(b"-- continued: %s (part %d)\n" % (self.label.encode(), self.part))
def write(self, line: bytes):
if self.fh is None: # data before any recognised table -> own bucket
self.start("preamble_orphan")
self.fh.write(line)
self.written += len(line)
def maybe_roll(self):
if self.max_bytes and self.written >= self.max_bytes:
self.close()
self._open()
def close(self):
if self.fh:
self.fh.close()
self.fh = None
def do_split(args) -> int:
src = Path(args.dump)
if not src.is_file():
sys.exit(f"no such file: {src}")
outdir = Path(args.out)
outdir.mkdir(parents=True, exist_ok=True)
existing = list(outdir.glob("*.sql"))
if existing and not args.force:
sys.exit(f"{outdir} already contains {len(existing)} .sql files - use --force to overwrite")
for p in existing:
p.unlink()
prog = outdir / PROGRESS_NAME
if prog.exists():
prog.unlink()
gz = src.suffix == ".gz"
opener = gzip.open if gz else open
max_bytes = int(args.max_chunk_mb * 1024 * 1024) if args.max_chunk_mb else 0
total = src.stat().st_size
writer = PartWriter(outdir, max_bytes)
header = open(outdir / HEADER_NAME, "wb")
in_header = True
in_data = False
in_delimiter = False
read = 0
t0 = time.time()
next_report = t0 + args.progress_secs
pending: list[bytes] = [] # blank / "--" separator lines, held back
def leave_header():
nonlocal in_header
if in_header:
header.close()
in_header = False
def flush_pending():
for held in pending:
writer.write(held)
pending.clear()
with opener(src, "rb") as fh:
for line in fh:
read += len(line)
label = None
if args.mode == "comments":
m = TABLE_RE.match(line) or VIEW_TMP_RE.match(line) or VIEW_FIN_RE.match(line)
if m:
label = sanitize(m.group(1))
elif ROUTINES_RE.match(line):
label = "routines"
else: # generic
m = DROP_RE.match(line) or CREATE_RE.match(line)
if m:
cand = sanitize(m.group(1))
if cand != writer.label:
label = cand
if label is not None:
leave_header()
in_data = False
pending.clear() # drop the "--" separator that precedes the marker
writer.start(label)
writer.write(line)
continue
if in_header:
header.write(line)
continue
if line.strip() in (b"", b"--"):
pending.append(line)
continue
if args.strip_locks and LOCK_RE.match(line):
continue
if line.startswith(b"INSERT INTO") or line.startswith(b"REPLACE INTO"):
in_data = True
# never split inside a DELIMITER ;; ... DELIMITER ; block (triggers, routines)
if line.startswith(b"DELIMITER"):
in_delimiter = not in_delimiter
flush_pending()
writer.write(line)
# roll only on a real statement end inside a data section. mysqldump puts
# one statement per line, but MariaDB breaks INSERT ... VALUES over several
# lines, so test the terminating ';' rather than the INSERT keyword.
if (in_data and max_bytes and not in_delimiter
and not line.startswith((b"/*!", b"UNLOCK", b"LOCK"))
and line.rstrip().endswith(b";")):
writer.maybe_roll()
now = time.time()
if now >= next_report:
next_report = now + args.progress_secs
elapsed = now - t0
rate = read / elapsed if elapsed else 0
if gz:
print(f" {human(read)} uncompressed | {writer.index} tables | "
f"{human(rate)}/s", flush=True)
else:
eta = (total - read) / rate if rate else 0
print(f" {read * 100 / total:5.1f}% {human(read)} / {human(total)} | "
f"{writer.index} tables | {human(rate)}/s | "
f"ETA {int(eta // 60)}m{int(eta % 60):02d}s", flush=True)
leave_header()
writer.close()
if writer.index == 0:
sys.exit("no table boundaries found. If this dump was made with --skip-comments, "
"re-run with --mode generic")
parts = sorted(outdir.glob("*.sql"))
print(f"\ndone in {time.time() - t0:.0f}s")
print(f"{len(parts)} files in {outdir}/ ({writer.index} tables)")
# sanity check: every part should end on a statement boundary
bad = []
for p in parts:
with open(p, "rb") as fh:
fh.seek(max(0, p.stat().st_size - 8192))
tail_lines = fh.read().splitlines()
while tail_lines and (not tail_lines[-1].strip() or tail_lines[-1].startswith(b"--")):
tail_lines.pop()
if tail_lines and not tail_lines[-1].rstrip().endswith(b";"):
bad.append(p.name)
if bad:
print(f"WARNING: {len(bad)} file(s) do not end on a ';' - check: {', '.join(bad[:5])}")
else:
print("all parts end on a statement boundary")
return 0
def do_inspect(args) -> int:
"""Report the biggest single statement, so you know what max_allowed_packet needs."""
partsdir = Path(args.parts)
files = sorted(partsdir.glob("*.sql"))
if not files:
sys.exit(f"no .sql files in {partsdir}")
worst = (0, None, 0) # (bytes, file, lineno)
per_file = []
for p in files:
fmax, fline = 0, 0
with open(p, "rb") as fh:
for n, line in enumerate(fh, 1):
ln = len(line)
if ln > fmax:
fmax, fline = ln, n
per_file.append((fmax, p.name, fline))
if fmax > worst[0]:
worst = (fmax, p.name, fline)
per_file.sort(reverse=True)
print("largest single statement per file (top 10):")
for size, name, lineno in per_file[:10]:
print(f" {human(size):>10} {name} (line {lineno})")
need = worst[0]
rec = 16 * 1024 * 1024
while rec < need * 2 and rec < 1024 * 1024 * 1024:
rec *= 2
print(f"\nbiggest statement anywhere: {human(need)} "
f"({worst[1]}, line {worst[2]})")
print(f"server needs at least this much max_allowed_packet. Recommended: {human(rec)}")
print("\nCheck what the server is actually using:")
print(" SELECT @@max_allowed_packet, @@wait_timeout, @@net_read_timeout;")
return 0
def do_import(args) -> int:
partsdir = Path(args.parts)
header = partsdir / HEADER_NAME
if not header.is_file():
sys.exit(f"{header} not found - point --parts at the split output directory")
parts = sorted(p for p in partsdir.glob("*.sql") if p.name != HEADER_NAME)
if not parts:
sys.exit(f"no parts found in {partsdir}")
progress = partsdir / PROGRESS_NAME
done = set(progress.read_text().split()) if progress.exists() else set()
todo = [p for p in parts if p.name not in done]
print(f"{len(parts)} parts, {len(done)} already imported, {len(todo)} to go")
if not todo:
return 0
if args.dry_run:
for p in todo:
print(f" would import {p.name} ({human(p.stat().st_size)})")
return 0
password = args.password
if password is None and not args.no_password:
password = getpass("MySQL password (blank for none): ")
env = os.environ.copy()
if password:
env["MYSQL_PWD"] = password
ignore = set()
if args.ignore_errors:
try:
ignore = {int(c) for c in re.split(r"[,\s]+", args.ignore_errors) if c.strip()}
except ValueError:
sys.exit("--ignore-errors takes comma-separated numeric codes, e.g. 1146,1050")
keep_going = bool(ignore) or args.skip_all_errors
if ignore:
print("skipping error codes: " + ", ".join(
f"{c} ({ERROR_PRESETS.get(str(c), 'custom')})" for c in sorted(ignore)))
elif args.skip_all_errors:
print("--skip-all-errors: every failed statement is skipped and logged")
client = [args.mysql, "-u", args.user,
f"--max-allowed-packet={args.max_allowed_packet}",
"--net-buffer-length=1000000"]
if keep_going:
client.append("--force") # keep going past a bad statement instead of aborting
if args.socket:
client += ["-S", args.socket] # socket and -h are mutually exclusive
elif args.docker:
pass # use the container's own local socket
else:
client += ["-h", args.host, "-P", str(args.port)]
client.append(args.db)
if args.docker:
cmd = ["docker", "exec", "-i"]
if password:
cmd += ["-e", f"MYSQL_PWD={password}"]
cmd += [args.docker] + client
else:
cmd = client
print("running: " + " ".join(
"***" if p.startswith("MYSQL_PWD=") else p for p in cmd))
header_bytes = header.read_bytes()
preamble = header_bytes
if not args.no_fast:
preamble += FAST_PREAMBLE
if args.no_binlog:
preamble += NOBINLOG_PREAMBLE
t_all = time.time()
skipped_total = 0
for i, part in enumerate(todo, 1):
size = part.stat().st_size
print(f"[{i}/{len(todo)}] {part.name} ({human(size)}) ... ", end="", flush=True)
t0 = time.time()
errlog = partsdir / "_last_error.log"
with open(errlog, "wb") as ef:
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=ef, env=env)
try:
proc.stdin.write(preamble)
with open(part, "rb") as fh:
while True:
chunk = fh.read(1 << 20)
if not chunk:
break
proc.stdin.write(chunk)
proc.stdin.write(b"\nCOMMIT;\n")
proc.stdin.close()
except BrokenPipeError:
pass
rc = proc.wait()
dt = time.time() - t0
errtext = errlog.read_text("utf-8", "replace") if errlog.exists() else ""
errlines = [l for l in errtext.splitlines() if ERR_RE.match(l)]
codes = [int(m.group(1)) for m in ERR_RE.finditer(errtext)]
# 2000-2999 are client/connection errors (gone away, can't connect). Never skip
# those - the rest of the part never reached the server, so the data would be lost.
fatal = [c for c in codes if 2000 <= c <= 2999]
unexpected = fatal + ([] if args.skip_all_errors
else [c for c in codes if c not in ignore and c not in fatal])
if unexpected or (rc != 0 and not keep_going):
print(f"FAILED (exit {rc}) after {dt:.0f}s")
for eline in errtext.splitlines():
if eline.strip():
print(" " + (eline[:300] + " ..." if len(eline) > 300 else eline))
print(f"\nFull client output: {errlog}")
if fatal:
print("This is a connection-level error - it cannot be skipped, because "
"the rest of the part never reached the server.")
skippable = sorted({c for c in unexpected if c not in fatal})
if skippable:
print("To skip this kind of error, add: "
f"--ignore-errors {','.join(str(c) for c in skippable)}")
print(f"Fix the cause, then re-run the same command - "
f"it will resume at {part.name}.")
return 1
if errlines:
skipped_total += len(errlines)
with open(partsdir / SKIPPED_NAME, "a", encoding="utf-8") as fh:
for eline in errlines:
fh.write(f"{part.name}: {eline[:500]}\n")
print(f"ok in {dt:.0f}s ({len(errlines)} statement(s) skipped)")
else:
print(f"ok in {dt:.0f}s")
errlog.unlink(missing_ok=True)
with open(progress, "a") as fh:
fh.write(part.name + "\n")
print(f"\nall parts imported in {time.time() - t_all:.0f}s")
if skipped_total:
print(f"{skipped_total} statement(s) were skipped - see {partsdir / SKIPPED_NAME}")
return 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
sp = sub.add_parser("split", help="split a dump into per-table parts")
sp.add_argument("dump", help="path to dump.sql or dump.sql.gz")
sp.add_argument("--out", default="parts", help="output directory (default: parts)")
sp.add_argument("--max-chunk-mb", type=float, default=200,
help="further split a table's data every N MB (0 = never)")
sp.add_argument("--mode", choices=["comments", "generic"], default="comments",
help="'comments' uses mysqldump's -- Table structure markers; "
"'generic' splits on DROP/CREATE TABLE")
sp.add_argument("--keep-locks", dest="strip_locks", action="store_false",
help="keep LOCK TABLES / UNLOCK TABLES (stripped by default)")
sp.add_argument("--force", action="store_true", help="overwrite an existing output dir")
sp.add_argument("--progress-secs", type=float, default=2.0,
help="seconds between progress lines (default: 2)")
sp.set_defaults(func=do_split)
np_ = sub.add_parser("inspect", help="report the largest statement in the split parts")
np_.add_argument("parts", help="directory produced by the split command")
np_.set_defaults(func=do_inspect)
ip = sub.add_parser("import", help="import parts one at a time, resumable")
ip.add_argument("parts", help="directory produced by the split command")
ip.add_argument("--host", default="127.0.0.1")
ip.add_argument("--port", type=int, default=3306)
ip.add_argument("--user", default="root")
ip.add_argument("--password", default=None, help="omit to be prompted")
ip.add_argument("--no-password", action="store_true")
ip.add_argument("--socket", default=None, help="unix socket (overrides --host)")
ip.add_argument("--docker", default=None, metavar="CONTAINER",
help="pipe each part through `docker exec -i CONTAINER mysql ...` "
"instead of connecting over TCP")
ip.add_argument("--db", required=True, help="target database (must already exist)")
ip.add_argument("--mysql", default="mysql", help="path to the mysql client")
ip.add_argument("--max-allowed-packet", default="1G")
ip.add_argument("--no-fast", action="store_true",
help="do not disable autocommit/unique_checks/foreign_key_checks")
ip.add_argument("--no-binlog", action="store_true",
help="also SET sql_log_bin=0 (needs SUPER; big speedup)")
ip.add_argument("--ignore-errors", default=None, metavar="CODES",
help="comma-separated MySQL error codes to skip instead of aborting, "
"e.g. 1146,1050. Common: "
+ "; ".join(f"{k}={v}" for k, v in ERROR_PRESETS.items()))
ip.add_argument("--skip-all-errors", action="store_true",
help="skip EVERY failing statement (logged to _skipped_errors.log)")
ip.add_argument("--dry-run", action="store_true")
ip.set_defaults(func=do_import)
args = ap.parse_args()
return args.func(args)
if __name__ == "__main__":
sys.exit(main())