Possible bug with remove() in global scope.
Trying to use the newly documented Global Scopes to restrict queries on a multi tenant app. When I try to use remove() the query returns no results, not just un-scoped results. As far as I can tell, the un-scoped query is correct, but the there still is an error because an unnecessary value exists in 'bindings' still.
Scoped: (Works as expected!) var_dump(DB::getQueryLog());
array (size=1)
0 =>
array (size=3)
'query' => string 'select * from `surveys` where `surveys`.`deleted_at` is null and `organization_id` = ?' (length=86)
'bindings' =>
array (size=1)
0 => int 10023
'time' => float 0.5
Un-scoped (Returns NO results. Should be far more than scoped above): var_dump(DB::getQueryLog());
array (size=1)
0 =>
array (size=3)
'query' => string 'select * from `surveys` where `surveys`.`deleted_at` is null' (length=60)
'bindings' =>
array (size=1)
0 => int 10023
'time' => float 0.35
It appears that since the 'bindings' value still exists, the query fails. I've managed to get the result I'm looking for by just setting $builder->setBindings(array()); to an empty array, but that surely can't be right:
public function remove(Builder $builder)
{
$column = $builder->getModel()->getQualifiedTenantColumn();
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where)
{
if ($this->isTenantConstraint($where, $column))
{
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
// ------------------------------------------------------------
// @TODO This works, as in it makes my query work, but
// I have no idea if this is a kosher maneuver or not.
// ------------------------------------------------------------
$builder->setBindings(array());
// ------------------------------------------------------------
}
}
}
Un-scoped, after nulling bindings (returns ALL results as expected): var_dump(DB::getQueryLog());
array (size=1)
0 =>
array (size=3)
'query' => string 'select * from `surveys` where `surveys`.`deleted_at` is null' (length=60)
'bindings' =>
array (size=0)
empty
'time' => float 1.01
There is a high possibility I am doing something wrong, I'll admit. However it seems that once you unset($query->wheres[$key]); the bindings should go to, no?
If you'd like to take a look at the TenantScope.php and TenantTrait files, look here: http://pastebin.com/CAF6nFXS
Yeah you will need to remove the binding. That isn't done automatically or anything.
Ok, thank you. Any comment on just setting setBindings() to an empty array as a solution? Will that break anything else you can think of? The bindings array doesn't seem to be keyed to the $query->wheres[$key] so I have no idea how to target just the associated bindings.
I'm not sure if that will break anything else. :)
Probably we need to do something in the future to more easily be able to tie bindings to where clauses.
Thanks. So far, all of my Eloquent queries appear to be working. I think all of a sudden a light bulb just went on the value of tests in this situation. :)
@taylorotwell We've done some further investigation, and it certainly will break other things - if you've got other global scopes registered for example.
In fact, it seems to be impossible to have a global scope with a normal where clause, and the softDeletingTrait for example, and have the first global scope be removable.
I think this is a proper bug, as there is no way to properly use the remove method if the apply method added any bindings. Perhaps you could reopen this issue?
I've come across this issue too (after hacking laravel code for 2 days...) and I'd love to see a fix for this issue. Please reopen.
softDeletingTrait does seem to re-apply scopes that have been removed. Any way around this?
Can you link to were the re-apply happens? I couldn't find it.
I got around the issue in a hackish way for now by adding a special delete function on my model:
public function scoped_delete() { if(Auth::user()->isSuperuser()) { $this->allTenants()->where($this->getKeyName(), $this->getKey())->delete(); }else { $this->delete(); } }
I believe the issue is in how the Eloquent softDeletingTrait runSoftDelete() method uses a newQuery(): $query = $this->newQuery()->where($this->getKeyName(), $this->getKey()) which would re-apply any scopes that had been removed.
I could be wrong here, but hacking that line of code fixed the issue for me, so I then figured out a way to do it without hacking the core.
Hope that helps... And I hope to find a better solution than the one posted above. Anyone have any thoughts? Should this be re-openned? or filed as a separate issue?
oh... found out the re-application of the scope was happening when using findOrFail. In my case I want a superuser to be able to delete any user, but all other admins would only be allowed to delete users within a tenant account.
User::allTenants()->findOrFail($id)->delete(); //tenant scope would be re-applied and delete would fail User::allTenants()->where('id',$id)->delete(); //tenant scope removal persists and delete works
also note destroy($id) doesn't work at all because that takes a list of id's and then instantiates models, which will have default scopes applied.
So in short the bug exists.
The bug definately exists.
I have just met with this issue. By assuming sequence of wheres and bindings are same, I wrote a remove function as below.
public function remove(Builder $builder)
{
$column = $builder->getModel()->getQualifiedDeletedAtColumn();
$query = $builder->getQuery();
$bindings = $builder->getBindings();
$bindKey = 0;
foreach ((array) $query->wheres as $key => $where)
{
if ($where['column'] == $this->wliColumn)
{
unset($query->wheres[$key]);
unset($bindings[$bindKey]);
$query->wheres = array_values($query->wheres);
}
// if with where there is a binding value increase bindkey
if($where['type'] != 'Null')
{
$bindKey++;
}
}
$builder->setBindings($bindings);
}
I am not sure if it breaks something, but it seems working for now.
@bllim Does that work with this sequence:
$query->where('column', '=', 'value');
$query->whereNull('column');
$query->where('column', '=', 'value');
where you now have three wheres, but only two bindings, not with the same keys?
@HipsterJazzbo yes it worked. I control if it is null value or binded via:
// if with where there is a binding value increase bindkey
if($where['type'] != 'Null')
{
$bindKey++;
}
There may be other conditions which break this. But I guess when it occured, it can be handled with similar logic.
I just ran across this issue as well and came up with a similar workaround, but then realized that there are just a lot more cases that I hadn't covered:
- $where['type'] = 'NotNull' (handled pretty much the same as when it is 'Null')
- $where['type'] = 'In' or 'raw' (there may be more than one binding per where)
- $where['type'] = 'Nested' (nested wheres may also have added bindings)
What I came up with needed to handle whereIn() and whereRaw(), but it still needs to be reworked to handle nested wheres.
// if with where there is a binding value increase bindkey
if (isset($where['values']))
{
$bindKey += count($where['values']);
}
else if (isset($where['value'] ))
{
$bindKey++;
}
Alternatively I thought about adding a recompileBindings() to the Query\Builder class which would work somewhat like the above with the same shortcomings.
$newBindings = array();
foreach ((array)$query->wheres as $where)
{
if (isset($where['value']))
{
$newBindings[] = $where['value'];
}
if (isset($where['values']))
{
$newBindings = array_merge($newBindings, $where['values']);
}
}
$query->setBindings($newBindings);
I'm sure there are more cases that would have to be considered for a more robust solution (joins and behavior under unions comes to mind), but this was working well enough for me right now.
I have the same problem when I call the method I have added to remove the global scope on the builder the query returns empty result set.
Does it get a fix?
It appears that when you remove a $where its bindings should be removed too.
Can't bindings of a $where stored inside it or a reference of them stored there?
I came to this solution to use whereRaw() instead of a regular where() to bypass the variable bindings, of course you need to first escape user input before doing this to prevent query injections.
I think it should be treated as a bug because you can`t remove a global scope that applies query variable bindings.
Any update on this? Have the same issue...