Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions DB/NEW_KT_DB/Controller/DBSnapshotControllerNaive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..","..")))
from DB.NEW_KT_DB.Service.Classes.DBSnapshotServiceNaive import DBSnapshotServiceNaive
from DB.NEW_KT_DB.Validation.DBSnapshotValidationsNaive import (
is_valid_db_instance_id,
is_valid_db_snapshot_description,
is_valid_progress
)
class DBSnapshotControllerNaive:
def __init__(self, service: DBSnapshotServiceNaive):
self.service = service

def create_db_snapshot(self, db_instance_identifier: str, description: str = None, progress: str = None):
# Validate parameters
if not is_valid_db_instance_id(db_instance_identifier):
raise ValueError(f"Invalid db_name: {db_instance_identifier}")
if description and not is_valid_db_snapshot_description(description):
raise ValueError(f"Invalid description: {description}")
if progress and not is_valid_progress(progress):
raise ValueError(f"Invalid progress: {progress}")

self.service.create(db_instance_identifier, description, progress)

def delete_db_snapshot(self):
# No validation needed for delete operation
self.service.delete()

def modify_db_snapshot(self, owner_alias: str = None, status: str = None,
description: str = None, progress: str = None):
# Validate parameters
if description and not is_valid_db_snapshot_description(description):
raise ValueError(f"Invalid description: {description}")
if progress and not is_valid_progress(progress):
raise ValueError(f"Invalid progress: {progress}")

self.service.modify(owner_alias, status, description, progress)


def describe_db_instance(self, db_snapshot_identifier: str):
"""
Retrieve details of a DBInstance by its identifier.

Params: db_instance_identifier: The primary key (ID) of the DBInstance to describe.
Return: A dictionary containing the details of the DBInstance.
"""
return self.service.describe(db_snapshot_identifier)
70 changes: 35 additions & 35 deletions DB/NEW_KT_DB/DataAccess/DBManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@ def __init__(self, db_file: str):

# rachel-8511, ShaniStrassProg
def close(self):
'''Close the database connection.'''
self.connection.close()
'''Close the database connection.'''
self.connection.close()


# saraNoigershel
def execute_query_with_multiple_results(self, query: str) -> Optional[List[Tuple]]:
'''Execute a given query and return the results.'''
try:
c = self.connection.cursor()
c.execute(query)
results = c.fetchall()
# self.connection.commit() ???
return results if results else None
except OperationalError as e:
raise Exception(f'Error executing query {query}: {e}')
'''Execute a given query and return the results.'''
try:
c = self.connection.cursor()
c.execute(query)
results = c.fetchall()
# self.connection.commit() ???
return results if results else None
except OperationalError as e:
raise Exception(f'Error executing query {query}: {e}')


# ShaniStrassProg
Expand Down Expand Up @@ -56,42 +56,42 @@ def execute_query_without_results(self, query: str):
def create_table(self, table_name, table_structure):
'''create a table in a given db by given table_structure'''
create_statement = f'''CREATE TABLE IF NOT EXISTS {table_name} ({table_structure})'''
execute_query_without_results(create_statement)
self.execute_query_without_results(create_statement)


# Riki7649255 based on rachel-8511, ShaniStrassProg
def insert_data_into_table(self, table_name, data):
insert_statement = f'''INSERT INTO {table_name} VALUES {data}'''
execute_query_without_results(insert_statement)
self.execute_query_without_results(insert_statement)


# Riki7649255 based on rachel-8511, Shani
def update_records_in_table(self, table_name: str, updates: Dict[str, Any], criteria: str) -> None:
'''Update records in the specified table based on criteria.'''

# add documentation here
set_clause = ', '.join([f'{k} = ?' for k in updates.keys()])
values = list(updates.values())

update_statement = f'''
UPDATE {table_name}
SET {set_clause}
WHERE {criteria}
'''

execute_query_without_results(update_statement)
'''Update records in the specified table based on criteria.'''
# add documentation here
set_clause = ', '.join([f'{k} = ?' for k in updates.keys()])
values = list(updates.values())
update_statement = f'''
UPDATE {table_name}
SET {set_clause}
WHERE {criteria}
'''
self.execute_query_without_results(update_statement)


# Riki7649255 based on rachel-8511
def delete_data_from_table(self, table_name: str, criteria: str) -> None:
'''Delete a record from the specified table based on criteria.'''

delete_statement = f'''
DELETE FROM {table_name}
WHERE {criteria}
''')
'''Delete a record from the specified table based on criteria.'''

execute_query_without_results(delete_statement)
delete_statement = f'''
DELETE FROM {table_name}
WHERE {criteria}
'''

self.execute_query_without_results(delete_statement)


# rachel-8511, Riki7649255
Expand All @@ -109,7 +109,7 @@ def select_and_return_records_from_table(self, table_name: str, columns: List[st
if criteria:
query += f' WHERE {criteria}'
try:
results = execute_query_with_multiple_results(query)
results = self.execute_query_with_multiple_results(query)
return {result[0]: dict(zip(columns, result[1:])) for result in results}
except OperationalError as e:
raise Exception(f'Error selecting from {table_name}: {e}')
Expand All @@ -120,7 +120,7 @@ def describe_table(self, table_name: str) -> Dict[str, str]:
'''Describe table structure.'''
try:
desc_statement = f'PRAGMA table_info({table_name})'
columns = execute_query_with_multiple_results(desc_statement)
columns = self.execute_query_with_multiple_results(desc_statement)
return {col[1]: col[2] for col in columns}
except OperationalError as e:
raise Exception(f'Error describing table {table_name}: {e}')
Expand Down
67 changes: 67 additions & 0 deletions DB/NEW_KT_DB/DataAccess/DBSnapshotManagerNaive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import json
import sqlite3
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..","..")))
from typing import Dict, Any
from DB.NEW_KT_DB.Validation.DBSnapshotValidationsNaive import is_valid_db_instance_id
from DB.NEW_KT_DB.DataAccess.ObjectManager import ObjectManager
from DB.NEW_KT_DB.Models.DBSnapshotModelNaive import SnapshotNaive

class DBSnapshotManagerNaive:

def __init__(self, object_manager: ObjectManager):
self.object_manager = object_manager
# Create the management table for DBSnapshot using its object name and table structure
self.object_manager.create_management_table(SnapshotNaive.object_name, SnapshotNaive.table_structure)

def createInMemoryDBSnapshot(self, db_instance_identifier: SnapshotNaive):
# Validate db_instance_identifier
if not is_valid_db_instance_id(db_instance_identifier):
raise ValueError(f"Invalid db_instance_identifier: {db_instance_identifier}")

self.object_manager.save_in_memory(SnapshotNaive.object_name, db_instance_identifier.to_sql())

def deleteInMemoryDBSnapshot(self, db_snapshot_identifier: str):
# Validate db_instance_identifier
if not is_valid_db_instance_id(db_snapshot_identifier, 15):
raise ValueError(f"Invalid db_instance_identifier: {db_snapshot_identifier}")

self.object_manager.delete_from_memory(
pk_column = SnapshotNaive.pk_column,
pk_value = db_snapshot_identifier,
object_name = SnapshotNaive.object_name
)

def describeDBSnapshot(self, db_snapshot_identifier: str):
# Validate db_instance_identifier
if not is_valid_db_instance_id(db_snapshot_identifier, 15):
raise ValueError(f"Invalid db_instance_identifier: {db_snapshot_identifier}")

self.object_manager.get_from_memory(
criteria=f"{SnapshotNaive.pk_column} = '{db_snapshot_identifier}'",
object_name=SnapshotNaive.object_name,
columns='*'
)

def modifyDBSnapshot(self, db_snapshot_identifier: str, updates: str):
# Validate db_instance_identifier
if not is_valid_db_instance_id(db_snapshot_identifier, 15):
raise ValueError(f"Invalid db_instance_identifier: {db_snapshot_identifier}")

# Assuming new_data contains fields to update, you might want to validate these fields as well
# For example:
# if 'description' in new_data and not is_valid_db_snapshot_description(new_data['description']):
# raise ValueError(f"Invalid description: {new_data['description']}")

self.object_manager.update_in_memory(
criteria=f"{SnapshotNaive.pk_column} = '{db_snapshot_identifier}'",
object_name=SnapshotNaive.object_name,
updates=updates
)

def is_db_snapshot_exist(self, db_snapshot_identifier: int) -> bool:
return bool(self.object_manager.db_manager.is_object_exist(
self.object_manager._convert_object_name_to_management_table_name(SnapshotNaive.object_name),
criteria=f"{SnapshotNaive.pk_column} = '{db_snapshot_identifier}'"
))
32 changes: 18 additions & 14 deletions DB/NEW_KT_DB/DataAccess/ObjectManager.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from typing import Dict, Any
import json
import sqlite3
from DBManager import DBManager
import os
import sys
from typing import Dict, Any
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..","..")))
from DB.NEW_KT_DB.DataAccess.DBManager import DBManager


class ObjectManager:
def __init__(self, db_file: str):
Expand All @@ -12,7 +16,7 @@ def __init__(self, db_file: str):
# for internal use only:

# Riki7649255 based on rachel-8511
def create_management_table(self, table_name, table_structure='object_id INTEGER PRIMARY KEY AUTOINCREMENT,type_object TEXT NOT NULL,metadata TEXT NOT NULL')
def create_management_table(self, table_name, table_structure='object_id INTEGER PRIMARY KEY AUTOINCREMENT,type_object TEXT NOT NULL,metadata TEXT NOT NULL'):
self.db_manager.create_table(table_name, table_structure)


Expand Down Expand Up @@ -58,22 +62,22 @@ def convert_object_name_to_management_table_name(object_name):
return f'mng_{object_name}s'


def is_management_table_exist(table_name):
def is_management_table_exist(self, table_name):
# check if table exists using single result query
return db_manager.execute_query_with_single_result(f'desc table {table_name}')
return self.db_manager.execute_query_with_single_result(f'desc table {table_name}')


# for outer use:
def save_in_memory(self, object):

# insert object info into management table mng_{object_name}s
# for exmple: object db_instance will be saved in table mng_db_instances
table_name = convert_object_name_to_management_table_name(self.object_name)
table_name = self.convert_object_name_to_management_table_name(self.object_name)

if not is_management_table_exist(table_name):
create_management_table(table_name)
if not self.is_management_table_exist(table_name):
self.create_management_table(table_name)

insert_object_to_management_table(table_name, object)
self.insert_object_to_management_table(table_name, object)


def delete_from_memory(self,criteria='default'):
Expand All @@ -82,9 +86,9 @@ def delete_from_memory(self,criteria='default'):
if criteria == 'default':
criteria = f'{self.pk_column} = {self.pk_value}'

table_name = convert_object_name_to_management_table_name(self.object_name)
table_name = self.convert_object_name_to_management_table_name(self.object_name)

delete_data_from_table(table_name, criteria)
self.db_manager.delete_data_from_table(table_name, criteria)


def update_in_memory(self, updates, criteria='default'):
Expand All @@ -93,13 +97,13 @@ def update_in_memory(self, updates, criteria='default'):
if criteria == 'default':
criteria = f'{self.pk_column} = {self.pk_value}'

table_name = convert_object_name_to_management_table_name(self.object_name)
table_name = self.convert_object_name_to_management_table_name(self.object_name)

update_object_in_management_table_by_criteria(table_name, updates, criteria)
self.update_object_in_management_table_by_criteria(table_name, updates, criteria)


def get_from_memory(self):
get_object_from_management_table(self.object_id)
self.get_object_from_management_table(self.object_id)


def convert_object_attributes_to_dictionary(**kwargs):
Expand Down
70 changes: 70 additions & 0 deletions DB/NEW_KT_DB/Models/DBSnapshotModelNaive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import os
import sys
import json
from datetime import datetime
from typing import Dict, Optional
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..","..")))
from DB.NEW_KT_DB.DataAccess import ObjectManager
from DB.NEW_KT_DB.Validation.DBSnapshotValidationsNaive import is_valid_db_instance_id, is_valid_db_snapshot_description, is_valid_progress, is_valid_date, is_valid_url_parameter

class SnapshotNaive:
BASE_PATH = "db_snapshot"
object_name = "db_snapshot_naive"
pk_column = "db_snapshot_id"
pk_column_data_type = 'TEXT'
table_structure = f'''
db_instance_identifier TEXT PRIMARY KEY,
metadata TEXT NOT NULL
'''
def __init__(self, db_snapshot_identifier, db_instance_identifier: str, creation_date: datetime, owner_alias: str, status: str,
description: Optional[str] = None, progress: Optional[str] = None, url_snapshot: Optional[str] = None):

# Validate parameters
if not is_valid_db_instance_id(db_instance_identifier):
raise ValueError(f"Invalid db_instance_identifier: {db_instance_identifier}")
if not is_valid_date(creation_date.strftime('%Y-%m-%d')):
raise ValueError(f"Invalid creation_date: {creation_date}")
if description:
if not is_valid_db_snapshot_description(description):
raise ValueError(f"Invalid description: {description}")
if progress:
if not is_valid_progress(progress):
raise ValueError(f"Invalid progress: {progress}")
if url_snapshot:
if not is_valid_url_parameter(url_snapshot):
raise ValueError(f"Invalid url_snapshot: {url_snapshot}")
self.db_snapshot_identifier = db_snapshot_identifier
self.db_instance_identifier = db_instance_identifier
self.creation_date = creation_date
self.owner_alias = owner_alias
self.status = status
self.description = description
self.progress = progress
self.url_snapshot = url_snapshot
self.object_name = "Snapshot"
self.table_structure = {}

def to_dict(self) -> Dict:
'''Retrieve the data of the DB snapshot as a dictionary.'''

return ObjectManager.convert_object_attributes_to_dictionary(
db_snapshot_identifier = self.db_snapshot_identifier,
db_instance_identifier = self.db_instance_identifier,
creation_date = self.creation_date,
owner_alias = self.owner_alias,
status = self.status,
description = self.description,
progress = self.progress,
url_snapshot = self.url_snapshot,
object_name = self.object_name,
table_structure = self.table_structure
)

def to_sql(self):
# Convert the model snapshot to a dictionary
data_dict = self.to_dict()
values = '(' + ", ".join(f'\'{json.dumps(v)}\'' if isinstance(v, dict) or isinstance(v, list) else f'\'{v}\'' if isinstance(v, str) else f'\'{str(v)}\''
for v in data_dict.values()) + ')'
return values


Loading