Skip to content

Commit

Permalink
Merge pull request #113 from rirex/development
Browse files Browse the repository at this point in the history
Fix single field update and excess fields set
  • Loading branch information
monobot committed Aug 14, 2020
2 parents 35e11b5 + 6a0bc48 commit dce658e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
15 changes: 14 additions & 1 deletion asyncorm/database/backends/sql_base_backend.py
Expand Up @@ -72,6 +72,15 @@ def _db__update(self):
RETURNING *
"""

@property
def _db__update_single_field(self):
return """
UPDATE ONLY {table_name}
SET {field_names} = {field_schema}
WHERE {id_data}
RETURNING *
"""

@property
def _db__delete(self):
return "DELETE FROM {table_name} WHERE {id_data} "
Expand Down Expand Up @@ -144,11 +153,15 @@ def _construct_query(self, query_chain):

# if we are not counting, then we can assign ordering
operations = ["COUNT", "MAX", "MIN", "SUM", "AVG", "STDDEV"]

# we must get error, if we set only one field and update instance
if res_dict["action"] == "_db__update" and len(res_dict["field_values"]) == 1:
res_dict.update({"action": "_db__update_single_field"})

if res_dict.get("select", "").split("(")[0] not in operations:
res_dict["ordering"] = self._ordering_syntax(res_dict.get("ordering", []))
else:
res_dict["ordering"] = ""

query = getattr(self, res_dict["action"]).format(**res_dict)
query = self._query_clean(query)

Expand Down
10 changes: 5 additions & 5 deletions asyncorm/manager/model_manager.py
Expand Up @@ -28,14 +28,14 @@ async def save(self, instanced_model):
# performs the database save
fields, field_data = [], []

for k, data in instanced_model.data.items():
f_class = getattr(instanced_model.__class__, k)

field_name = f_class.db_column or k
field_names_mapping = instanced_model.__class__.orm_attr_names()
for column_name, data in instanced_model.data.items():
field_name = field_names_mapping[column_name]
f_class = getattr(instanced_model.__class__, field_name)

data = f_class.sanitize_data(data)

fields.append(field_name)
fields.append(column_name)
field_data.append(data)

for field in instanced_model.fields.keys():
Expand Down
8 changes: 7 additions & 1 deletion asyncorm/models/models.py
Expand Up @@ -170,6 +170,10 @@ def m2m_data(self):
d.pop(db)
return d

@classmethod
def orm_attr_names(cls):
return {v: k for k, v in cls.attr_names.items()}

@classmethod
def get_fields(cls):
fields = {}
Expand Down Expand Up @@ -298,7 +302,9 @@ def construct(self, data, deleted=False, subitems=None):
k = orm
break
# get the recomposed value
field_class = getattr(self.__class__, k)
field_class = getattr(self.__class__, k, None)
if field_class is None:
continue
v = field_class.recompose(v)

if field_class in [ForeignKey, ManyToManyField]:
Expand Down

0 comments on commit dce658e

Please sign in to comment.