[BUG]: Save, saves related data also (not changed)
I have interesting situation.... @niden can u check out that? A help!
$contractor = \Models\Contractors::findFirst();
$company = $contractor->getCompany();
$contractor->save();
In that case, save will be executed in relation too. I mean object $contractor will be save and object $company too. Why is that?
Originally posted by @borisdelev in https://github.com/phalcon/cphalcon/discussions/16336#discussioncomment-5993602
More details here and description... lets say we have 2 Models: Companies & Contractors. Contractors connected Companies with belongsTo relation (alias Company).
Somewhere in controller action:
$contractor = \Models\Contractors::findFirst();
$company = $contractor->getCompany(); // Get related company
...
$contractor->save();
... this will invoke ->save method on $contractor but and ->save method in company (i added dump in beforeValidation method on Company model). Expected behaviour is to save only $contractor.
PhalconPHP 5.2.*
Not sure is it a feature or a bug... anyway. I want to help somehow.
This is a bug. It appeared in 4.1 branch. To be precise now we are running 4.1.2. There is no such behavior in php7.4-phalcon_4.0.4-908. We even fixed this package in our Docker but now we had to update and got a lot issues.
Lets assume we have a code
class Spendings extends BaseModel {
....
public function initialize(): void {
$this->hasOne('spendings_categories_id',
SpendingsCategories::class,
'id',
[
'reusable' => true,
'alias' => 'Category',
]);
$sp = Spendings::findFirst(627979);
echo $sp->Category->name; //Relation
$sp->amount += 0.01;
sp->save();
Queries will be:
START TRANSACTION
UPDATE `spendings` SET `status` = 1, `.... WHERE `id` = 627979
(!!!) UPDATE `spendings_categories` SET `name` = 'test', `.... WHERE `id` = 12601
COMMIT
On the one hand let it be, just additional update. But if we changed spendings_categories_id in spendings to another the second update will wrongly update a row in spendings_categories. For example you had spendings_categories: id | name 1 | category 1 2 | category 2 You change spendings.spending_category_id from 1 to 2, now you have 1 | category 2 2 | category 2
There is workaround with switches off relation update
public function save(): bool {
$this->related = [];
return parent::save();
}
Do not hesitate to contact me if you need more details or tests.
TLDR: this happens in collectRelatedToSave()
Starts in the Model::__get
if typeof relation == "object" {
/**
* There might be unsaved related records that can be returned
*/
if isset this->dirtyRelated[lowerProperty] {
return this->dirtyRelated[lowerProperty];
}
/**
* Get the related records
*/
return this->getRelated(lowerProperty);
}
if you fetch anything it does not get set in the dirtyRelated, I think the ideas was to only execute presaverelated() and postsaverelated() if hasRelated() and collectRelatedToSave()
Issue is in the collectRelatedToSave()
for name, record in related {
if isset dirtyRelated[name] {
continue;
}
if typeof record !== "object" || !(record instanceof ModelInterface) {
continue;
}
record->setDirtyState(self::DIRTY_STATE_TRANSIENT);
let dirtyRelated[name] = record;
}
so the getRelated() will set this->related[lower_property] = related
and the collectRelatedToSave() will iterate on the related
But since the model is not in the this->dirtyRelated it will be set Transient with record->setDirtyState(self::DIRTY_STATE_TRANSIENT);
So it can be executed in preSaveRelatedRecord with if record->dirtyState !== Model::DIRTY_STATE_PERSISTENT && !record->save()
Right now it's a feature because probably there "is" a bug So lets suppose you have C belongs to B and B belongs to A
if we A->B->C->setSomething(value); C will be in a transient state, but B will not So saving A will not save C unless B is also in a transient State
I can think of 3 ways to fix this:
- has a static "cache" of real dirtyModels to be executed, this could trigger a save on unwanted and unrelated models.
- cascade dirtyState to parents, this will consume a lot of cycles since you have to check if there is a loaded relation and cascade on it everytime you do a __set
- check all loaded relations recursively for any transient models on save, this could trigger infinite loops (my guess is it does already) so an EXECUTED and EXECUTED_TRANSIENT states will/might be needed to differentiate and avoid infinite save loops, this might be possible without a First Level Cache, I am not sure.
FYI to trigger an infinite loop ATM you just have to
A->B
B->setA(A)
A->save()
I am working currently on this in my repo while trying to add FirstLevelCache... not easy without breaking a few things, sorry.
Forgot to mention, my proposal for extra Executed States if not optional they might be a breaking change on model before and prepare Events with business logic. for example if someone as a beforesave or preparesave that B changes A, if A is already executed and B makes a change in A before update, that change will not be saved and might only happen on hasOne and hasMany relations.
This is weird.
We use Phalcon 4.1.3 and have this bug too. But in 4.1.3 in the collectRelatedToSave() doesn't contain the mentioned setDirtyState() call. Anyway, we tried to overwrite the collectRelatedToSave() with this:
protected function collectRelatedToSave(): array
{
$related = $this->related;
$dirtyRelated = $this->dirtyRelated;
foreach ($related as $name => $record) {
if (isset($dirtyRelated[$name]) === true) {
continue;
}
if ($record instanceof ModelInterface === false) {
continue;
}
// We mimic the same behavior like without snapshots.
$changed = true;
if ($record instanceof Model === true) {
$changed = $record->hasChanged();
}
if ($changed === true || $record->getDirtyState() !== self::DIRTY_STATE_PERSISTENT) {
$dirtyRelated[$name] = $record;
}
}
return $dirtyRelated;
}
It completely resolved the issue! We use snapshots, else hasChanged() wouldn't work. So there is definitely something broken.
This is weird.
We use Phalcon 4.1.3 and have this bug too. But in 4.1.3 in the
collectRelatedToSave()doesn't contain the mentionedsetDirtyState()call. Anyway, we tried to overwrite thecollectRelatedToSave()with this:protected function collectRelatedToSave(): array { $related = $this->related; $dirtyRelated = $this->dirtyRelated; foreach ($related as $name => $record) { if (isset($dirtyRelated[$name]) === true) { continue; } if ($record instanceof ModelInterface === false) { continue; } // We mimic the same behavior like without snapshots. $changed = true; if ($record instanceof Model === true) { $changed = $record->hasChanged(); } if ($changed === true || $record->getDirtyState() !== self::DIRTY_STATE_PERSISTENT) { $dirtyRelated[$name] = $record; } } return $dirtyRelated; }It completely resolved the issue! We use snapshots, else
hasChanged()wouldn't work. So there is definitely something broken.
It's a quick fix if you are only trying to save the "first ring" or first level of relations, if you go beyond that it is an issue.
If you have a second level or a second ring, A->B->C and changed only C and trigger A->save();
All ok here A checks for B hasChanged, nothing is changed on B so move on.
Problem is we only changed C and it will never be saved unless you call C->save somewhere in your code. If you have a really heavy business logic in the models, this is going to cause issues with models not being saved.
It's a quick fix for simple level 1 relations, anything above that is broken.
This is weird. We use Phalcon 4.1.3 and have this bug too. But in 4.1.3 in the
collectRelatedToSave()doesn't contain the mentionedsetDirtyState()call. Anyway, we tried to overwrite thecollectRelatedToSave()with this:protected function collectRelatedToSave(): array { $related = $this->related; $dirtyRelated = $this->dirtyRelated; foreach ($related as $name => $record) { if (isset($dirtyRelated[$name]) === true) { continue; } if ($record instanceof ModelInterface === false) { continue; } // We mimic the same behavior like without snapshots. $changed = true; if ($record instanceof Model === true) { $changed = $record->hasChanged(); } if ($changed === true || $record->getDirtyState() !== self::DIRTY_STATE_PERSISTENT) { $dirtyRelated[$name] = $record; } } return $dirtyRelated; }It completely resolved the issue! We use snapshots, else
hasChanged()wouldn't work. So there is definitely something broken.It's a quick fix if you are only trying to save the "first ring" or first level of relations, if you go beyond that it is an issue.
If you have a second level or a second ring, A->B->C and changed only C and trigger A->save();
All ok here A checks for B hasChanged, nothing is changed on B so move on.
Problem is we only changed C and it will never be saved unless you call C->save somewhere in your code. If you have a really heavy business logic in the models, this is going to cause issues with models not being saved.
It's a quick fix for simple level 1 relations, anything above that is broken.
We never used C level, because of the way getRelated() handles not found or null/false results. We also still use php 7.4 so we do not have ?->.
The solution to your case, would be, to call the same method on every $record:
protected function collectRelatedToSave(): array
{
$related = $this->related;
$dirtyRelated = $this->dirtyRelated;
foreach ($related as $name => $record) {
if (isset($dirtyRelated[$name]) === true) {
continue;
}
if ($record instanceof ModelInterface === false) {
continue;
}
$changed = true;
if ($record instanceof Model === true) {
$hasDirtyRelated = $record->collectRelatedToSave();
if (\count($hasDirtyRelated) > 0) {
$record->save();
}
$changed = $record->hasChanged();
}
if ($changed === true || $record->getDirtyState() !== self::DIRTY_STATE_PERSISTENT) {
$dirtyRelated[$name] = $record;
}
}
return $dirtyRelated;
}
That should solve C, D and WhatEverLevel.
@noone-silent no you can't do that! you have prepare, before and after that must me run on it's order of type of relation, that will trigger prepareSave and beforeSave no matter what type of relation there is, it is a breaking change, massive one.
@noone-silent the only way to fix it correctly is with state flags and first level cache (thread cache). Because you need to avoid save loops, run the whole relations to check for changed data and prepareSave might change data, and FLC to keep a single source of truth where if you find a model it will always return the same object instance.
This is something that Java Hibernate ORM has by default and you can't disable it.
https://vladmihalcea.com/jpa-hibernate-first-level-cache/
https://vladmihalcea.com/the-anatomy-of-hibernate-dirty-checking/
I wish it was an easier problem to solve, but it's not, all magic comes with a price, ORM magic comes with a heavy price of data flow complexity, consistency complexity and a lot of cycles to ensure that everything checks out.
To be honest I think prepareSave, while it has good intentions of enabling making a lot of changes just before the model gets saved, it is a bad practice if you rely on it for data consistently. Because the ORM can only run the model once, if devs depend on prepareSave for calculations or data consistency and are not using their own logic and functions before triggering a save(), it will lead to data not being changed because of the type and complexity of relations.
I have a very complex project that relations can go to 5 or 6 layers deep, don't like it but it's the way the customer needs it.
We could however have a dirty cache inside a thread cache that when a save gets triggered it runs normally then checks the cache for unsaved models, this adds more cycles and checks every time a model gets changed or save, and might even be unwanted behaviour, I don't recommend it like this.
So my proposal is dirty_state execution flags to avoid loops, resultset with added logic to append/add and persist models with a clear way for dev to program to make sure that it's get triggered by save(), and avoid magic has much has possible.
I am working on it has we speak, it's slow progress because I am trying not to break previous behaviour, i.e. saving hasMany that is an array instead of a resultset object, keeping collectRelatedToSave function. The hardest part of them all is when you delete or remove a related model, this is the one thing that will drive me nuts, because the model still exists in the database, but you do not want it to be used in a resultset because you deleted it, just not persisted it.
@rudiservo Is this related to this comment: https://github.com/phalcon/cphalcon/issues/15148#issuecomment-1415894473
Because we are having massive performance issues in our application since the Phalcon 5 update :)
To be honest I think prepareSave, while it has good intentions of enabling making a lot of changes just before the model gets saved, it is a bad practice if you rely on it for data consistently. Because the ORM can only run the model once, if devs depend on prepareSave for calculations or data consistency and are not using their own logic and functions before triggering a save(), it will lead to data not being changed because of the type and complexity of relations.
I have a very complex project that relations can go to 5 or 6 layers deep, don't like it but it's the way the customer needs it.
We could however have a dirty cache inside a thread cache that when a save gets triggered it runs normally then checks the cache for unsaved models, this adds more cycles and checks every time a model gets changed or save, and might even be unwanted behaviour, I don't recommend it like this.
So my proposal is dirty_state execution flags to avoid loops, resultset with added logic to append/add and persist models with a clear way for dev to program to make sure that it's get triggered by save(), and avoid magic has much has possible.
I am working on it has we speak, it's slow progress because I am trying not to break previous behaviour, i.e. saving hasMany that is an array instead of a resultset object, keeping collectRelatedToSave function. The hardest part of them all is when you delete or remove a related model, this is the one thing that will drive me nuts, because the model still exists in the database, but you do not want it to be used in a resultset because you deleted it, just not persisted it.
If you find a solution, please patch it into phalcon 4 too. People still use it
I have also replicated this issue in our application. We have installed ClockWork that allows us to see all database calls made in a call. I ran this code:
public function phalconAction()
{
/** @var EventTicket $ticket */
$ticket = EventTicket::query()->andWhere('uuid = "93b006a8-188b-4c2b-bd3c-64f8c6f3101e"')->execute()->getFirst();
$orderItem = $ticket->orderItem;
$orderStatus = $orderItem->order->status;
if ($orderStatus === OrderStatus::COMPLETE) {
$ticket->status = EventTicketStatus::RESERVED;
$ticket->save();
}
}
That results in the following ClockWork result:
The EventTicket Query is not on the screenshot, but you can see that 2 UPDATE queries are done for Order & OrderItem. The data in the UPDATE query is not different from what is currently in the database.
The example code I ran is not too bad, but in our production application this creates a massive performance issue.
@rudiservo Is this related to this comment: #15148 (comment)
Because we are having massive performance issues in our application since the Phalcon 5 update :)
At first glance yes, do you have dynamic update? Just to know if it influences it.
@rudiservo Pleas explain what you mean with dynamic updates? The code example I provided in my previous comment shows what the issue is :)
@rudiservo Pleas explain what you mean with dynamic updates? The code example I provided in my previous comment shows what the issue is :)
It checks the model for changed fields before making and update to the database. It uses more RAM because it keeps a snapshot of original values, and a few more CPU cycles to check for changes.
The increased load you are seeing is in the PHP or the database?
public function initialize()
{
$this->useDynamicUpdate(true);
}
@rudiservo Pleas explain what you mean with dynamic updates? The code example I provided in my previous comment shows what the issue is :)
It checks the model for changed fields before making and update to the database. It uses more RAM because it keeps a snapshot of original values, and a few more CPU cycles to check for changes.
The increased load you are seeing is in the PHP or the database?
public function initialize() { $this->useDynamicUpdate(true); }
Our database is the biggest issue. But that's understandable looking at my example. (https://github.com/phalcon/cphalcon/issues/16343#issuecomment-1633680665)
Every model select triggers a database update as well. That explains why our database has been having a hard time since the Phalcon 5 update.
@larsverp well dynamic updates will save writes to your DB, also they will not issue an update for all the fields of the model, only the ones that have changed, making the update query smaller. It's easier to scale up php workers than it is to scale up the DB, with Relational DB clusters the writing usually happens always in the same node, so pulling easing off the writing will improve the database by a lot.
Test it and give your feedback on how it went.
The solution for this without using dynamic updates, is to forget about "dirty state" on relations has you have to always check the relations for changes and just use the dirty state only for changed fields.
@rudiservo Alright thanks I will do some testing with the Dynamic update. Just to be on the same line, the issue we're trying to solve is about Phalcon marking a model as dirty while no fields are updated , right? Is there a possibility for us to disable Phalcon setting a Dirty state on a model? I'd rather check it myself while it's not working.
@rudiservo We already seem to use DynamicUpdates so this doesn't do anything for us. It still tries to update the entire model in the DB even no fields have been changed.