Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added method _deleting_ for models #818

Merged
merged 1 commit into from
Oct 19, 2023
Merged
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
60 changes: 59 additions & 1 deletion asyncdb/drivers/pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -1714,5 +1714,63 @@ async def _updating_(self, *args, _filter: dict = None, **kwargs):
return [model(**dict(r)) for r in result]
except Exception as err:
raise DriverError(
message=f"Error on Insert over table {model.Meta.name}: {err!s}"
message=f"Error on UPDATE over table {model.Meta.name}: {err!s}"
) from err

async def _deleting_(self, *args, _filter: dict = None, **kwargs):
"""
Deleting records using Model.
"""
try:
model = kwargs['_model']
except KeyError as e:
raise DriverError(
f'Missing Model for SELECT {kwargs!s}'
) from e
try:
schema = ''
sc = model.Meta.schema
if sc:
schema = f"{sc}."
table = f"{schema}{model.Meta.name}"
except AttributeError:
table = model.__name__
fields = model.columns(model)
if _filter is None:
if args:
_filter = args[0]
cols = []
source = []
new_cond = {}
n = 1
for name, field in fields.items():
try:
val = kwargs[name]
except (KeyError, AttributeError):
continue
## getting the value of column:
value = self._get_value(field, val)
source.append(value)
if name in _filter:
new_cond[name] = value
cols.append("{} = {}".format(name, "${}".format(n))) # pylint: disable=C0209
n += 1
try:
condition = self._where(fields, **_filter)
_delete = f"DELETE FROM {table} {condition}"
self._logger.debug(f'DELETE: {_delete}')
stmt = await self._connection.prepare(_delete)
result = await stmt.fetchrow(*source, timeout=2)
self._logger.debug(stmt.get_statusmsg())
print(f'DELETE {result}: {_filter!s}')

new_conditions = {**_filter, **new_cond}
condition = self._where(fields, **new_conditions)

_all = f"SELECT * FROM {table} {condition}"
if result := await self._connection.fetch(_all):
return [model(**dict(r)) for r in result]
except Exception as err:
raise DriverError(
message=f"Error on DELETE over table {model.Meta.name}: {err!s}"
) from err
25 changes: 25 additions & 0 deletions asyncdb/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,31 @@ async def updating(cls, *args, _filter: dict = None, **kwargs):
f"Error Updating Table {cls.Meta.name}: {err}"
) from err

@classmethod
async def deleting(cls, *args, _filter: dict = None, **kwargs):
if not cls.Meta.connection:
raise ConnectionMissing(
f"Missing Connection for Model: {cls}"
)
try:
result = await cls.Meta.connection._deleting_(
_model=cls, _filter=_filter, *args, **kwargs
)
if result:
return result
else:
return []
except (AttributeError, StatementError) as err:
raise StatementError(
f"Error on Attribute {cls.Meta.name}: {err}"
) from err
except DriverError:
raise
except Exception as err:
print(traceback.format_exc())
raise ModelError(
f"Error Updating Table {cls.Meta.name}: {err}"
) from err

@classmethod
async def select(cls, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion asyncdb/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
__title__ = 'asyncdb'
__description__ = ('Library for Asynchronous data source connections '
'Collection of asyncio drivers.')
__version__ = '2.5.1'
__version__ = '2.5.2'
__author__ = 'Jesus Lara'
__author_email__ = '[email protected]'
__license__ = 'BSD'