Skip to content
This repository has been archived by the owner on Sep 27, 2023. It is now read-only.

Commit

Permalink
Save record on DB for each file on backup
Browse files Browse the repository at this point in the history
  • Loading branch information
kennylajara committed Jun 18, 2021
1 parent 1255565 commit d3d304a
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 22 deletions.
8 changes: 6 additions & 2 deletions runup/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,9 @@ def create_backup(self, yaml_config:Dict[str, Any], backup_id:str) -> Optional[s
vResponse(self._verbose, f'Interpreter_1:_working_directories', working_directories)

# Create backup
db:RunupDB = RunupDB(self._context, self._verbose)
vCall(self._verbose, f'RunupDB:insert_job')
job_id = RunupDB(self._context, self._verbose).insert_job(backup)
job_id = db.insert_job(backup)
vResponse(self._verbose, f'RunupDB:insert_job', job_id)

# Make context relative
Expand All @@ -184,6 +185,9 @@ def create_backup(self, yaml_config:Dict[str, Any], backup_id:str) -> Optional[s
for path in working_directories:
vInfo(self._verbose, f'Zipping file: {path}')
my_zip.write(path)
vCall(self._verbose, f'RunupDB:insert_file')
res = db.insert_file(job_id, path)
vResponse(self._verbose, f'RunupDB:insert_file', res)

return job_id

Expand Down Expand Up @@ -299,7 +303,7 @@ def validate_parameters(self, yaml_config:Dict[str, Any], prefix:str='') -> bool
def _validate_prev_init(self, yaml_config:Dict[str, Any]):
"""Validate RunUp havs been previously initialized."""
if not os.path.exists(f'{self._context}/.runup'):
vInfo(self._verbose, f'RunUp has not been initialized.')
click.echo(f'RunUp has not been initialized.')
return False

for project in yaml_config['project'].keys():
Expand Down
47 changes: 32 additions & 15 deletions runup/runupdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ def execute(self, name:str, query:str):
try:
c = self._conn.cursor()
c.execute(query)
if query.lower().strip().startswith('insert into '):
return c.lastrowid
elif query.lower().strip().startswith('insert or ignore into '):
return c.lastrowid
return c
except Error as e:
click.echo(e)
Expand Down Expand Up @@ -134,36 +138,49 @@ def insert_backup(self, name:str) -> bool:
def insert_file(self, job_id:int, filename:str):
"""Insert a file"""

sha256:str = hashfile(filename, "sha256")
sha512:str = hashfile(filename, "sha512")

self.connect()

# Find
sql:str = f"""
SELECT sha256, sha512, job_loc
FROM files
WHERE sha256='{hashfile(filename, "sha256")}' AND sha{hashfile(filename, "sha512")}
LIMIT 1;
"""
if sha256 == 'dir' or sha512 == 'dir':
sql:str = f"""
SELECT sha256, sha512, job_loc
FROM files
WHERE sha256='{sha256}' AND sha512='{sha512}' AND path='{filename}'
LIMIT 1;
"""
else:
sql:str = f"""
SELECT sha256, sha512, job_loc
FROM files
WHERE sha256='{sha256}' AND sha512='{sha512}'
LIMIT 1;
"""

cursor = self.execute(f'Insert file: {filename}', sql)
result = cursor.fetchall()
id:int

if len(result) == 0:
# Insert
sql:str = f"""
INSERT INTO files (job_id, sha256, sha512, job_loc, path)
VALUES ({job_id}, '{hashfile(filename, "sha256")}', '{hashfile(filename, "sha512")}', {job_id}, {filename})
INSERT OR IGNORE INTO files (job_id, sha256, sha512, job_loc, path)
VALUES ({job_id}, '{sha256}', '{sha512}', {job_id}, '{filename}')
"""
cursor = self.execute(f'Insert file: {filename}', sql)
id = self.execute(f'Insert file: {filename}', sql)
else:
# Insert
sql:str = f"""
INSERT INTO files (job_id, sha256, sha512, job_loc, path)
VALUES ({job_id}, '{result['sha256']}', '{result['sha512']}', {result['job_loc']}, {filename})
INSERT OR IGNORE INTO files (job_id, sha256, sha512, job_loc, path)
VALUES ({job_id}, '{result[0][0]}', '{result[0][1]}', {result[0][2]}, '{filename}')
"""
cursor = self.execute(f'Insert file: {filename}', sql)
id = self.execute(f'Insert file: {filename}', sql)

self.close_connection()

return cursor.lastrowid
return id


def insert_job(self, backup_name:str):
Expand All @@ -175,7 +192,7 @@ def insert_job(self, backup_name:str):
"""

self.connect()
cursor = self.execute('Insert job', sql)
id:str = self.execute('Insert job', sql)
self.close_connection()

return cursor.lastrowid
return id
8 changes: 6 additions & 2 deletions runup/utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Built-in
from os import path
from typing import Any, Optional
import hashlib


# 3rd party
from click import echo
import click


# ------- #
Expand Down Expand Up @@ -46,11 +46,15 @@ def file_as_blockiter(afile, blocksize=65536):
block = afile.read(blocksize)

def hashfile( fname, algo:str ):
algorithm:str
if not path.isfile(fname):
return 'dir'

if algo == 'sha256':
algorithm = hashlib.sha256()
elif algo == 'sha512':
algorithm = hashlib.sha512()
else:
raise ValueError(f'Incorrect hash algorithm: {algo}')
raise ValueError(f'Unsupported hash algorithm: {algo}')
return hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), algorithm)

6 changes: 3 additions & 3 deletions tests/cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ def tearDown(self) -> None:
"""Clean the environment after running the tests."""
if os.path.exists(f"{self._context}/init/.runup"):
rmdir_recursive(f"{self._context}/init/.runup")
if os.path.exists(f"{self._context}/create-backup/.runup"):
rmdir_recursive(f"{self._context}/create-backup/.runup")
# if os.path.exists(f"{self._context}/create-backup/.runup"):
# rmdir_recursive(f"{self._context}/create-backup/.runup")


def test_help(self):
Expand Down Expand Up @@ -87,7 +87,7 @@ def test_create_backup(self):
runner:CliRunner = CliRunner()
context:Path = f'{self._context}/create-backup'
# Execute
result = runner.invoke(cli, ['--context', context, 'backup'])
result = runner.invoke(cli, ['--context', context, 'backup'])
# Assert
self.assertEqual(result.output, f'New backup created.\n')
self.assertEqual(result.exit_code, 0)

1 comment on commit d3d304a

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pytest-coverage-badge

Name Stmts Miss Cover
runup/init.py 0 0 100%
runup/cli.py 62 8 87%
runup/interpreter.py 209 41 80%
runup/runupdb.py 71 4 94%
runup/utils.py 32 0 100%
runup/version.py 3 0 100%
runup/yaml_parser.py 101 16 84%
TOTAL 478 69 86%

Please sign in to comment.