Skip to content

Instantly share code, notes, and snippets.

@FernandoCelmer
Last active July 3, 2023 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FernandoCelmer/c8ec617efed17653217a8202abaa70ce to your computer and use it in GitHub Desktop.
Save FernandoCelmer/c8ec617efed17653217a8202abaa70ce to your computer and use it in GitHub Desktop.
from json import dumps
from typing import Any, List, _GenericAlias
from dataclasses import dataclass, Field
from abc import ABC, abstractmethod
@dataclass
class DataClass:
id: int
def __serializer__(self, dataset: dict) -> dict:
for attr in dataset:
field = self.__dataclass_fields__.get(attr)
field_content = dataset.get(field.name)
if field.type in (int, str):
dataset[field.name] = field.type(field_content)
if hasattr(field_content, "__dict__"):
dataset[field.name] = self.__serializer__(dataset=field_content.__dict__)
if isinstance(field_content, list):
temp_content = []
for item in field_content:
if hasattr(item, "__dict__"):
temp_content.append(self.__serializer__(dataset=item.__dict__))
else:
temp_content.append(item)
dataset[field.name] = temp_content
return dataset
def __load__(self):
return self.__serializer__(dataset=self.__dict__)
def __dump__(self):
return dumps(self.__load__())
class DataBase(ABC):
def __init__(self, **kwargs) -> None:
self.environment = kwargs
@abstractmethod
def __session__(self) -> None:
pass
@abstractmethod
def upsert(self, data: List[DataClass]) -> None:
pass
@abstractmethod
def read(self, query: str) -> None:
pass
@abstractmethod
def delete(self, id: List[int]) -> None:
pass
@dataclass
class Category(DataClass):
name: str
@dataclass
class User(DataClass):
name: str
email: str
status: bool
category: List[Category]
class SQL:
def __init__(self, model_class: List[DataClass]) -> None:
self.model_class = model_class
self.__setup__()
def __setup__(self):
self.sql_update = self.load_update(self.model_class)
self.sql_insert = self.load_insert(self.model_class)
def load_update(self):
pass
def load_insert(self):
pass
class ModelSQL:
def __new__(cls, model_class: List[DataClass]) -> SQL:
cls.model_class = SQL(model_class)
return cls.model_class
user = User(
id=1,
name="Fernando",
email="email@fernandocelmer.com",
status=True,
category=[
Category(
id=1,
name="Defaul"
)
]
)
user.__dump__()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment