Skip to content

Commit

Permalink
new(project) Add insert factory, insert method to the model and some …
Browse files Browse the repository at this point in the history
…utils
  • Loading branch information
RedmanPlus committed Jan 24, 2023
1 parent 93d9d11 commit eaf6480
Show file tree
Hide file tree
Showing 15 changed files with 158 additions and 68 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/__pycache__
/venv
*.pyc
*.egg-info/
*.egg-info/
main.py
1 change: 1 addition & 0 deletions noio_db/core/sql_object_factories/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
)
from .create_sql_object_factory import CreateTableSQLObjectFactory
from .for_sql_object_factory import FromSQLObjectFactory
from .insert_sql_object_factory import InsertSQLObjectFactory
from .mul_arg_sql_object_factories import (
GroupBySQLObjectFactory,
OrderBySQLObjectFactory,
Expand Down
31 changes: 31 additions & 0 deletions noio_db/core/sql_object_factories/insert_sql_object_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from noio_db.core.sql_object_factories import AbstractSQLObjectFactory
from noio_db.core.sql_objects import (
ArgInBracesSQLObject,
BaseSQLObject,
InsertSQLObject,
)
from noio_db.utils import list_into_comma_sql_object


class InsertSQLObjectFactory(AbstractSQLObjectFactory):
def get_object(self, *args) -> BaseSQLObject:

if len(args) < 3:
raise Exception(
f"Must have at least 3 args for the insert factoty, got {len(args)}"
)

destination = args[0]

field_mappings = ArgInBracesSQLObject(list_into_comma_sql_object(*args[1]))

values = []

for val_group in args[2:]:

val_mappings = ArgInBracesSQLObject(list_into_comma_sql_object(*val_group))
values.append(val_mappings)

values = list_into_comma_sql_object(*values)

return InsertSQLObject(destination, field_mappings, values)
12 changes: 2 additions & 10 deletions noio_db/core/sql_object_factories/mul_arg_sql_object_factories.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from noio_db.core.sql_objects import (
BaseSQLObject,
CommaSQLObject,
GroupBySQLObject,
OrderBySQLObject,
SelectSQLObject,
)
from noio_db.utils import list_into_comma_sql_object

from .abstract_sql_object_factory import AbstractSQLObjectFactory

Expand All @@ -18,15 +18,7 @@ def get_object(self, *args) -> BaseSQLObject:
if isinstance(root, str):
return self.SQLObjectClass(root)
if len(args) > 1:
root = None
for i, arg in enumerate(args):
if i == 0:
root = CommaSQLObject(arg, args[i + 1])
continue
if i == len(args) - 1:
break

root = CommaSQLObject(root, args[i + 1])
root = list_into_comma_sql_object(*args)

return self.SQLObjectClass(root)

Expand Down
3 changes: 2 additions & 1 deletion noio_db/core/sql_objects/insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@

class InsertSQLObject(BaseSQLObject):

template = Template("INSERT INTO $where $what")
template = Template("INSERT INTO $where $fields VALUES $what")
template_keys = [
"where",
"fields",
"what",
]
2 changes: 2 additions & 0 deletions noio_db/core/sql_query_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
FromSQLObjectFactory,
GroupBySQLObjectFactory,
HavingSQLObjectFactory,
InsertSQLObjectFactory,
OrderBySQLObjectFactory,
SelectSQLObjectFactory,
WhereSQLObjectFactory,
Expand All @@ -30,6 +31,7 @@ class SelectSQLQueryConstructor(AbstractSQLQueryConstructor):
"group_by": GroupBySQLObjectFactory(),
"having": HavingSQLObjectFactory(),
"order_by": OrderBySQLObjectFactory(),
"insert": InsertSQLObjectFactory(),
}

def compile(self, query: dict) -> str:
Expand Down
5 changes: 5 additions & 0 deletions noio_db/models/fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class IDField:
def __init__(self, parent):
self.__counter__ = 1
self.parent = parent
self.parent_id = self.__counter__
90 changes: 48 additions & 42 deletions noio_db/models/model.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# pylint: disable=E0611
from inspect import currentframe, getouterframes

from pydantic import BaseModel

from noio_db.core import AST, CreateTableSQLObjectFactory
from noio_db.core import AST, CreateTableSQLObjectFactory, SelectSQLQueryConstructor
from noio_db.query import Query
from noio_db.utils import ToAsync, get_current_settings


# pylint: enable=E0611
class ObjectCounter:

__count__: int = 0


class SelectMixin:
Expand All @@ -19,7 +21,8 @@ def _get_fields(cls) -> dict:
return cls.__annotations__

@classmethod
def _get_sync(cls, **kwargs) -> Query:
@ToAsync
def filter(cls, **kwargs) -> Query:
fields = cls._get_fields()
for k in kwargs:
field_val = fields.get(k, False)
Expand All @@ -41,12 +44,8 @@ def _get_sync(cls, **kwargs) -> Query:
return queryset

@classmethod
async def _get_async(cls, **kwargs) -> Query:

return cls._get_sync(**kwargs)

@classmethod
def _all_sync(cls) -> Query:
@ToAsync
def all(cls) -> Query:

ast = AST()

Expand All @@ -59,52 +58,59 @@ def _all_sync(cls) -> Query:

return query

@classmethod
async def _all_async(cls) -> Query:

return cls._all_sync()

class CreateModelMixin:
@classmethod
def all(cls) -> Query:

curframe = currentframe()
outframe = getouterframes(curframe, 1)

cls.is_called_async = False

if "await" in outframe[1][4][0]:
def create(cls):
name = cls.__name__.lower()
annotations = cls.__annotations__

cls.is_called_async = True
return CreateTableSQLObjectFactory().get_object(name, annotations)

return cls._all_async()

return cls._all_sync()
class InsertMixin:
def __init__(self, *args, **kwargs):
self.is_called_async: bool = False
super().__init__(*args, **kwargs)

@classmethod
def get(cls, **kwargs) -> Query:
@ToAsync
def insert(self):

curframe = currentframe()
outframe = getouterframes(curframe, 1)
table_name = self.table_name
table_fields = list(self.__dict__.keys())
table_fields.insert(0, "id")
table_values = list(self.__dict__.values())
table_values.insert(0, self.__count__)

cls.is_called_async = False
# pylint: disable=W0212
ast = AST()
ast._insert(table_name, table_fields, table_values)
# pylint: enable=W0212

if "await" in outframe[1][4][0]:
cls.is_called_async = True
query = SelectSQLQueryConstructor().compile(ast.to_dict())
driver = get_current_settings(self)

return cls._get_async(**kwargs)
driver(query)

return cls._get_sync(**kwargs)

class Model(BaseModel, SelectMixin, CreateModelMixin, InsertMixin, ObjectCounter):

class CreateModelMixin:
@classmethod
def create(cls):
name = cls.__name__.lower()
annotations = cls.__annotations__
__from_orm__: bool = False

return CreateTableSQLObjectFactory().get_object(name, annotations)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__count__ += 1

@property
def table_name(self):
return self.__class__.__name__.lower()

class Model(BaseModel, SelectMixin, CreateModelMixin):
@property
def table_fields(self):
return list(self.__annotations__.keys())

id: int
def save(self):
if self.__from_orm__:
pass
else:
self.insert()
15 changes: 3 additions & 12 deletions noio_db/query/query.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from importlib import import_module
from typing import Union

from noio_db.core import AST, SelectSQLQueryConstructor
from noio_db.settings import Settings
from noio_db.utils import zip_into_dict
from noio_db.utils import get_current_settings, zip_into_dict


class Query:
Expand All @@ -19,14 +17,7 @@ def __init__(self, model, ast: AST):

self.is_called_async: bool = False

if user_settings := Settings.__subclasses__():
self.db_driver = import_module(user_settings[0]().driver_path).Driver(
self, user_settings[0]()
)
else:
self.db_driver = import_module(Settings().driver_path).Driver(
self, Settings()
)
self.db_driver = get_current_settings(self)

def __getitem__(self, item):

Expand All @@ -40,7 +31,7 @@ def __getitem__(self, item):

for i, result in enumerate(self.objects):
kwargs = zip_into_dict(model_field_names, result)
self.objects[i] = self.model_class(**kwargs)
self.objects[i] = self.model_class(__from_orm__=True, **kwargs)

self.called = True
return self.objects[item]
8 changes: 7 additions & 1 deletion noio_db/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
from noio_db.utils.arg_manipulation import pair_up_args, zip_into_dict
from noio_db.utils.arg_manipulation import (
list_into_comma_sql_object,
pair_up_args,
zip_into_dict,
)
from noio_db.utils.async_decorator import ToAsync
from noio_db.utils.get_settings import get_current_settings
from noio_db.utils.mappings import SQLITE_MAPPINGS
16 changes: 16 additions & 0 deletions noio_db/utils/arg_manipulation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import List

from noio_db.core.sql_objects import CommaSQLObject
from noio_db.utils.consts import ARG_METHOD_NAMES, KWARG_METHOD_NAMES


Expand Down Expand Up @@ -65,3 +66,18 @@ def zip_into_dict(list_a: list, list_b: list) -> dict:
result[a] = b

return result


def list_into_comma_sql_object(*args) -> CommaSQLObject:

root = None
for i, arg in enumerate(args):
if i == 0:
root = CommaSQLObject(arg, args[i + 1])
continue
if i == len(args) - 1:
break

root = CommaSQLObject(root, args[i + 1])

return root
24 changes: 24 additions & 0 deletions noio_db/utils/async_decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from inspect import currentframe, getouterframes


class ToAsync:
def __init__(self, func):
self.func = func

async def _run_async(self, *args, **kwargs):

return self.func(*args, **kwargs)

def _run_sync(self, *args, **kwargs):

return self.func(*args, **kwargs)

def __call__(self, *args, **kwargs):

curframe = currentframe()
outframe = getouterframes(curframe, 1)

if "await" in outframe[1][4][0]:
return self._run_async(*args, **kwargs)

return self._run_sync(*args, **kwargs)
1 change: 1 addition & 0 deletions noio_db/utils/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"_from",
"_group_by",
"_order_by",
"_insert",
}

KWARG_METHOD_NAMES = {
Expand Down
13 changes: 13 additions & 0 deletions noio_db/utils/get_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from importlib import import_module

from noio_db.core.db_drivers import BaseDriver
from noio_db.settings import Settings


def get_current_settings(obj) -> BaseDriver:
if user_settings := Settings.__subclasses__():
return import_module(user_settings[0]().driver_path).Driver(
obj, user_settings[0]()
)

return import_module(Settings().driver_path).Driver(obj, Settings())
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = noio_db
version = 0.0.1
version = 0.1.0
description = No I/O ORM for the future
author = Anton Rumyantsev
license = MIT
Expand Down

0 comments on commit eaf6480

Please sign in to comment.