-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13 from akaihola/large-tables
Support large tables which don't fit in RAM
- Loading branch information
Showing
7 changed files
with
376 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
"""Merge sort implementation to handle large files by sorting them in partitions.""" | ||
|
||
from __future__ import annotations | ||
|
||
import sys | ||
from heapq import merge | ||
from tempfile import TemporaryFile | ||
from typing import IO, Any, Callable, Iterable, Iterator, cast | ||
|
||
|
||
class MergeSort(Iterable[str]): | ||
"""Merge sort implementation to handle large files by sorting them in partitions.""" | ||
|
||
def __init__( | ||
self, | ||
key: Callable[[str], Any] = str, | ||
directory: str = ".", | ||
max_memory: int = 190, | ||
) -> None: | ||
"""Initialize the merge sort object.""" | ||
self._key = key | ||
self._directory = directory | ||
self._max_memory = max_memory | ||
# Use binary mode to avoid newline conversion on Windows. | ||
self._partitions: list[IO[bytes]] = [] | ||
self._iterating: Iterable[str] | None = None | ||
self._buffer: list[str] = [] | ||
self._memory_counter: int = sys.getsizeof(self._buffer) | ||
self._flush() | ||
|
||
def append(self, line: str) -> None: | ||
"""Append a line to the set of lines to be sorted.""" | ||
if self._iterating: | ||
message = "Can't append lines after starting to sort" | ||
raise ValueError(message) | ||
self._memory_counter -= sys.getsizeof(self._buffer) | ||
self._buffer.append(line) | ||
self._memory_counter += sys.getsizeof(self._buffer) | ||
self._memory_counter += sys.getsizeof(line) | ||
if self._memory_counter >= self._max_memory: | ||
self._flush() | ||
|
||
def _flush(self) -> None: | ||
if self._buffer: | ||
# Use binary mode to avoid newline conversion on Windows. | ||
self._partitions.append(TemporaryFile(mode="w+b", dir=self._directory)) | ||
self._partitions[-1].writelines( | ||
line.encode("UTF-8") for line in sorted(self._buffer, key=self._key) | ||
) | ||
self._buffer = [] | ||
self._memory_counter = sys.getsizeof(self._buffer) | ||
|
||
def __next__(self) -> str: | ||
"""Return the next line in the sorted list of lines.""" | ||
if not self._iterating: | ||
if self._partitions: | ||
# At least one partition has already been flushed to disk. | ||
# Iterate the merge sort for all partitions. | ||
self._flush() | ||
for partition in self._partitions: | ||
partition.seek(0) | ||
self._iterating = merge( | ||
*[ | ||
(line.decode("UTF-8") for line in partition) | ||
for partition in self._partitions | ||
], | ||
key=self._key, | ||
) | ||
else: | ||
# All lines fit in memory. Iterate the list of lines directly. | ||
self._iterating = iter(sorted(self._buffer, key=self._key)) | ||
return next(cast(Iterator[str], self._iterating)) | ||
|
||
def __iter__(self) -> Iterator[str]: | ||
"""Return the iterator object for the sorted list of lines.""" | ||
return self |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
"""Tests for the `pgtricks.mergesort` module.""" | ||
|
||
import functools | ||
from types import GeneratorType | ||
from typing import Iterable, cast | ||
|
||
import pytest | ||
|
||
from pgtricks.mergesort import MergeSort | ||
from pgtricks.pg_dump_splitsort import linecomp | ||
|
||
# This is the biggest amount of memory which can't hold two one-character lines on any | ||
# platform. On Windows it's slightly smaller than on Unix. | ||
JUST_BELOW_TWO_SHORT_LINES = 174 | ||
|
||
|
||
@pytest.mark.parametrize("lf", ["\n", "\r\n"]) | ||
def test_mergesort_append(tmpdir, lf): | ||
"""Test appending lines to the merge sort object.""" | ||
m = MergeSort(directory=tmpdir, max_memory=JUST_BELOW_TWO_SHORT_LINES) | ||
m.append(f"1{lf}") | ||
assert m._buffer == [f"1{lf}"] | ||
m.append(f"2{lf}") | ||
assert m._buffer == [] | ||
m.append(f"3{lf}") | ||
assert m._buffer == [f"3{lf}"] | ||
assert len(m._partitions) == 1 | ||
pos = m._partitions[0].tell() | ||
m._partitions[0].seek(0) | ||
assert m._partitions[0].read() == f"1{lf}2{lf}".encode() | ||
assert pos == len(f"1{lf}2{lf}") | ||
|
||
|
||
@pytest.mark.parametrize("lf", ["\n", "\r\n"]) | ||
def test_mergesort_flush(tmpdir, lf): | ||
"""Test flushing the buffer to disk.""" | ||
m = MergeSort(directory=tmpdir, max_memory=JUST_BELOW_TWO_SHORT_LINES) | ||
for value in [1, 2, 3]: | ||
m.append(f"{value}{lf}") | ||
m._flush() | ||
assert len(m._partitions) == 2 | ||
assert m._partitions[0].tell() == len(f"1{lf}2{lf}") | ||
m._partitions[0].seek(0) | ||
assert m._partitions[0].read() == f"1{lf}2{lf}".encode() | ||
pos = m._partitions[1].tell() | ||
m._partitions[1].seek(0) | ||
assert m._partitions[1].read() == f"3{lf}".encode() | ||
assert pos == len(f"3{lf}") | ||
|
||
|
||
@pytest.mark.parametrize("lf", ["\n", "\r\n"]) | ||
def test_mergesort_iterate_disk(tmpdir, lf): | ||
"""Test iterating over the sorted lines on disk.""" | ||
m = MergeSort(directory=tmpdir, max_memory=JUST_BELOW_TWO_SHORT_LINES) | ||
for value in [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 8, 4]: | ||
m.append(f"{value}{lf}") | ||
assert next(m) == f"1{lf}" | ||
assert isinstance(m._iterating, GeneratorType) | ||
assert next(m) == f"1{lf}" | ||
assert next(m) == f"2{lf}" | ||
assert next(m) == f"3{lf}" | ||
assert next(m) == f"3{lf}" | ||
assert next(m) == f"4{lf}" | ||
assert next(m) == f"4{lf}" | ||
assert next(m) == f"5{lf}" | ||
assert next(m) == f"5{lf}" | ||
assert next(m) == f"6{lf}" | ||
assert next(m) == f"8{lf}" | ||
assert next(m) == f"9{lf}" | ||
with pytest.raises(StopIteration): | ||
next(m) | ||
|
||
|
||
@pytest.mark.parametrize("lf", ["\n", "\r\n"]) | ||
def test_mergesort_iterate_memory(tmpdir, lf): | ||
"""Test iterating over the sorted lines when all lines fit in memory.""" | ||
m = MergeSort( | ||
directory=tmpdir, | ||
max_memory=1000000, | ||
key=functools.cmp_to_key(linecomp), | ||
) | ||
for value in [3, 1, 4, 1, 5, 9, 2, 10, 6, 5, 3, 8, 4]: | ||
m.append(f"{value}{lf}") | ||
assert next(m) == f"1{lf}" | ||
assert not isinstance(m._iterating, GeneratorType) | ||
assert iter(cast(Iterable[str], m._iterating)) is m._iterating | ||
assert next(m) == f"1{lf}" | ||
assert next(m) == f"2{lf}" | ||
assert next(m) == f"3{lf}" | ||
assert next(m) == f"3{lf}" | ||
assert next(m) == f"4{lf}" | ||
assert next(m) == f"4{lf}" | ||
assert next(m) == f"5{lf}" | ||
assert next(m) == f"5{lf}" | ||
assert next(m) == f"6{lf}" | ||
assert next(m) == f"8{lf}" | ||
assert next(m) == f"9{lf}" | ||
assert next(m) == f"10{lf}" | ||
with pytest.raises(StopIteration): | ||
next(m) | ||
|
||
|
||
@pytest.mark.parametrize("lf", ["\n", "\r\n"]) | ||
def test_mergesort_key(tmpdir, lf): | ||
"""Test sorting lines based on a key function.""" | ||
m = MergeSort(directory=tmpdir, key=lambda line: -int(line[0])) | ||
for value in [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 8, 4]: | ||
m.append(f"{value}{lf}") | ||
result = "".join(value[0] for value in m) | ||
assert result == "986554433211" |
Oops, something went wrong.