backup and recover

This commit is contained in:
AF 2021-12-08 14:40:56 +03:00
parent 4dcca8067f
commit b2a3503e0f

View File

@ -2,6 +2,7 @@ import asyncio
import json
import pathlib
import pickle
import shutil
from io import StringIO
from typing import Any, Optional, IO, Type
@ -80,9 +81,12 @@ class Db:
__task: Optional[asyncio.Future]
def __init__(self, path: str, *, kvrequest_type: Type[KVRequest], buffersize=1048576):
path = str(path)
self.kvrequest_type = kvrequest_type
self.buffersize = buffersize
self.__path = pathlib.Path(path)
self.__path_backup = pathlib.Path(path + '.backup')
self.__path_recover = pathlib.Path(path + '.recover')
self.__task = None
def io2db(self, io: IO[str], db: dict) -> int:
@ -174,11 +178,19 @@ class Db:
await self._background_cycle()
def _rebuild_file(self, db: {}):
if self.__path_recover.exists():
shutil.copy(self.__path_backup, self.__path)
self.__path_recover.unlink()
self.__path_backup.unlink()
self.__path.touch()
with open(self.__path) as file:
self.io2db(file, db)
with open(self.__path, "w") as file:
with open(self.__path_backup, "w") as file:
self.__initial_size = self.db2io(db, file)
self.__path_recover.touch()
shutil.copy(self.__path_backup, self.__path)
self.__path_recover.unlink()
self.__path_backup.unlink()
def _reload(self):
self.__file.close()