Skip to content

Commit

Permalink
Merge pull request #41 from richecr/develop
Browse files Browse the repository at this point in the history
Version 1.0.1
  • Loading branch information
richecr authored Nov 7, 2021
2 parents dfd1e0d + 65ca4d6 commit 2480aa1
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 37 deletions.
17 changes: 16 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,22 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [1.0.0] - 10-31-2021: Not Released
## [1.0.1] - 11-06-2021: Not Released

### Added
- Added `__tablename__` attribute of models in ModelManager.

### Corretion
- ModelManager `create_all_tables` method does not create the tables
and neither the relationships already created, before it generated an error.
- The `drop_all_tables` to ModelManager method does not drop the tables
that do not exist, before it generated an error.
- Fixed the `add` and `get_all` method of the `OneToMany` field.
- Fixed the `add`, `add_models` and `get_all` method of the `ManyToMany` field.
- Fixed `parser` method of `QueryExecutor` module.


## [1.0.0] - 10-31-2021: Released

### Added
- Implement method `find_by_id` and documentation. #9
Expand Down
4 changes: 2 additions & 2 deletions docs/fields/one_to_many.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ person_2 = Person(
first_name="Elton", last_name="Carvalho", age=25, salary=1450, city=city_cg)

city_cg = await City.save(city_cg)
person_1 = await Person.save(person_1)
person_2 = await Person.save(person_2)
person_1 = await City.persons.add(person_1)
person_2 = await City.persons.add(person_2)

# Return all the people in this city
persons: list[Person] = await City.persons.get_all()
Expand Down
2 changes: 1 addition & 1 deletion duck_orm/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.0.0'
__version__ = '1.0.1'
25 changes: 17 additions & 8 deletions duck_orm/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ def __new__(cls, name, bases, attrs):
model_class = super().__new__(cls, name, bases, attrs)

if ("model_manager" in attrs):
try:
name = attrs['__tablename__']
except KeyError:
name = name.lower()

attrs['model_manager'].add_model(name, model_class)

return model_class
Expand All @@ -30,17 +35,18 @@ def __init__(self, **kwargs):
for key, value in kwargs.items():
self._instance[key] = value

for name, field in inspect.getmembers(self):
from duck_orm.sql.relationship import OneToMany, ManyToMany
if isinstance(field, (OneToMany, ManyToMany)):
field.model_ = self
self.__setattr__(name, field)

def __getattribute__(self, key: str):
_instance = object.__getattribute__(self, '_instance')
result = None
if key in _instance:
return _instance[key]
return object.__getattribute__(self, key)
result = _instance[key]
else:
result = object.__getattribute__(self, key)

from duck_orm.sql.relationship import OneToMany, ManyToMany
if (isinstance(result, (OneToMany, ManyToMany))):
result.model_ = self
return result

def __getitem__(self, key):
return getattr(self, key)
Expand Down Expand Up @@ -120,6 +126,7 @@ async def create(cls):

@ classmethod
def __get_fields_all(cls) -> List[str]:
cls.relationships()
fields_all: List[str] = []
for name, field in inspect.getmembers(cls):
from duck_orm.sql.relationship import OneToMany, ManyToMany
Expand Down Expand Up @@ -180,6 +187,8 @@ async def __parser_fields(cls, data: dict):
condition_with_id
])
fields_foreign_key[name] = model_entity
elif isinstance(field, OneToMany):
fields_foreign_key[name] = field

return fields_all, fields_foreign_key

Expand Down
28 changes: 22 additions & 6 deletions duck_orm/model_manager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict
from typing import Dict, List
from .model import Model


Expand All @@ -12,12 +12,28 @@ def add_model(self, name: str, model: Model):
def remove_model(self, name: str):
del self.models[name]

async def create_all_tables(self):
for _, model in self.models.items():
await model.create()
def __get_table_name(self, table_obj: dict[str, str]) -> str:
try:
return table_obj['name']
except KeyError:
return table_obj['tablename']

for _, model in self.models.items():
await model.associations()
async def create_all_tables(self, models_db: List = []):
if len(self.models) > 0:
for _, model in self.models.items():
await model.create()

models_db = list(
map(lambda model: self.__get_table_name(model), models_db))
for name, model in self.models.items():
if name not in models_db:
await model.associations()
else:
model.relationships()
else:
Exception(
"No models found: I created your models and put the " +
"model_manager attribute on them.")

async def drop_all_tables(self):
for _, model in self.models.items():
Expand Down
43 changes: 28 additions & 15 deletions duck_orm/sql/relationship.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import inspect
from typing import Any, Dict, Type
from typing import Any, Dict, List, Type

from duck_orm.model import Model
from duck_orm.sql.fields import Column, ActionsEnum
Expand Down Expand Up @@ -66,17 +66,21 @@ def __init__(
super().__init__('OneToMany')

async def add(self, model: Type[Model]):
model._instance[self.name_in_table_fk] = self.model_
if self.model_:
model._instance[self.name_in_table_fk] = self.model_
self.model_ = None
return await self.model.save(model)

async def get_all(self):
return await self.model.find_all(conditions=[
Condition(
self.name_in_table_fk,
'=',
self.model_[self.model_.get_id()[0]]
)
])
result: List[Model] = []
if self.model_:
field_name = self.model_.get_id()[0]
condition = Condition(
self.name_in_table_fk, '=', self.model_[field_name])
result = await self.model.find_all(conditions=[condition])
else:
result = await self.model.find_all()
return result


class ManyToOne(Column):
Expand Down Expand Up @@ -164,6 +168,7 @@ async def add_models(self, model_instance_one: Model,
model_dict[name] = model_instance_two[name_field]

model_save = self.model_relation(**model_dict)
self.model_ = None
return await self.model_relation.save(model_save)

async def add(self, model_instance_one: Model):
Expand All @@ -178,12 +183,15 @@ async def add(self, model_instance_one: Model):
model_dict[name] = self.model_[name_field]

model_save = self.model_relation(**model_dict)
self.model_ = None
return await self.model_relation.save(model_save)

async def get_all(self):
field_name = self.model_.get_id()[0]
value_field = self.model_[field_name]
field_name_relation = ''
if self.model_:
field_name = self.model_.get_id()[0]
value_field = self.model_[field_name]
field_name_relation = ''

field_name_other_model = ''
for name, field in inspect.getmembers(self.model_relation):
if (isinstance(field, ForeignKey)) and not field.primary_key:
Expand All @@ -192,9 +200,14 @@ async def get_all(self):
elif isinstance(self.model_, field.model):
field_name_relation = name

condition = Condition(field_name_relation, '=', value_field)
models_relations = await self.model_relation.find_all(
conditions=[condition])
models_relations: List[Model] = []
if self.model_:
condition = Condition(field_name_relation, '=', value_field)
models_relations = await self.model_relation.find_all(
conditions=[condition])
else:
models_relations = await self.model_relation.find_all()

result_models = list(
map(lambda model: model[field_name_other_model], models_relations))
return result_models
8 changes: 5 additions & 3 deletions duck_orm/sql/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
CREATE_SQL = "CREATE TABLE IF NOT EXISTS {name} ({fields});"
UPDATE_SQL = "UPDATE {table} SET {fields_values} WHERE {conditions};"
DELETE_SQL = "DELETE FROM {table} WHERE {conditions};"
DROP_TABLE_SQL = "DROP TABLE {name}"
DROP_TABLE_SQL = "DROP TABLE IF EXISTS {name}"

ADD_COLUMN_SQL = "ALTER TABLE {table_name} " + \
"ADD COLUMN {field_name} {field_type} "
Expand Down Expand Up @@ -152,7 +152,7 @@ def parser(
cls,
row: Mapping,
fields: List[str] = [],
fields_foreign_key={}
fields_foreign_key: dict = {}
) -> dict:
entity = {}
if (fields != []):
Expand All @@ -161,10 +161,12 @@ def parser(
field = field[0]

if (row.__contains__(field)):
if field in fields_foreign_key.keys():
if fields_foreign_key.__contains__(field):
entity[field] = fields_foreign_key.get(field)
else:
entity[field] = row.get(field)
elif fields_foreign_key.__contains__(field):
entity[field] = fields_foreign_key[field]
else:
entity[field] = None
else:
Expand Down
4 changes: 3 additions & 1 deletion duck_orm/sql/sqlite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from duck_orm.sql.sql import QueryExecutor

SELECT_TABLES_SQL = "SELECT name FROM sqlite_master where type = 'table';"
DROP_TABLE_SQL = "DROP TABLE {name};"
DROP_TABLE_SQL = "DROP TABLE IF EXISTS {name};"
TYPES_SQL = {
'str': 'TEXT',
'int': 'INTEGER',
Expand Down Expand Up @@ -44,6 +44,8 @@ def parser(
entity[field] = fields_foreign_key.get(field)
else:
entity[field] = row.get(field)
elif fields_foreign_key.__contains__(field):
entity[field] = fields_foreign_key[field]
else:
entity[field] = None
else:
Expand Down

0 comments on commit 2480aa1

Please sign in to comment.