Skip to content

[9.x] Cross-database support for all relations #46675

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

Closed
wants to merge 21 commits into from
Closed
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
2 changes: 2 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,8 @@ protected function eagerLoadRelation(array $models, $name, Closure $constraints)

$constraints($relation);

$this->query->prependDatabaseNameIfCrossDatabaseQuery($relation->getBaseQuery());

// Once we have the results, we just match those back up to their parent models
// using the relationship instance. Then we just return the finished arrays
// of models which have been eagerly hydrated and are readied for return.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', C
$relation->getRelated()->newQueryWithoutRelationships(), $this
);

$this->query->prependDatabaseNameIfCrossDatabaseQuery($hasQuery->getQuery());

// Next we will call any given callback as an "anonymous" scope so they can get the
// proper logical grouping of the where clauses if needed by this Eloquent query
// builder. Then, we will be ready to finalize and return this query instance.
Expand Down
13 changes: 10 additions & 3 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,12 @@ protected function performJoin($query = null)
// model instance. Then we can set the "where" for the parent models.
$query->join(
$this->table,
$this->getQualifiedRelatedKeyName(),
'=',
$this->getQualifiedRelatedPivotKeyName()
function ($join) {
$join->on($this->getQualifiedRelatedKeyName(), '=', $this->getQualifiedRelatedPivotKeyName());
if (is_null($this->using)) {
$join->setConnection($this->parent->getConnection());
}
}
);

return $this;
Expand Down Expand Up @@ -334,6 +337,10 @@ public function using($class)
{
$this->using = $class;

foreach ($this->query?->getQuery()->joins ?? [] as $join) {
$join->setConnection((new $class)->getConnection());
}

return $this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,13 @@ protected function performJoin(Builder $query = null)

$farKey = $this->getQualifiedFarKeyName();

$query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $farKey);
$query->join(
$this->throughParent->getTable(),
function ($join) use ($farKey) {
$join->on($this->getQualifiedParentKeyName(), '=', $farKey);
$join->setConnection($this->parent->getConnection());
}
);

if ($this->throughParentSoftDeletes()) {
$query->withGlobalScope('SoftDeletableHasManyThrough', function ($query) {
Expand Down
54 changes: 42 additions & 12 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Builder implements BuilderContract
/**
* The table joins for the query.
*
* @var array
* @var \Illuminate\Database\Query\JoinClause[]|null
*/
public $joins;

Expand Down Expand Up @@ -367,8 +367,8 @@ protected function createSub($query)
*/
protected function parseSub($query)
{
if ($query instanceof self || $query instanceof EloquentBuilder || $query instanceof Relation) {
$query = $this->prependDatabaseNameIfCrossDatabaseQuery($query);
if ($query instanceof self || $query instanceof EloquentBuilder) {
$this->prependDatabaseNameIfCrossDatabaseQuery($query instanceof EloquentBuilder ? $query->getQuery() : $query);

return [$query->toSql(), $query->getBindings()];
} elseif (is_string($query)) {
Expand All @@ -383,21 +383,51 @@ protected function parseSub($query)
/**
* Prepend the database name if the given query is on another database.
*
* @param mixed $query
* @return mixed
* @param self $query
* @return void
*/
public function prependDatabaseNameIfCrossDatabaseQuery($query)
{
if (($database = $query->getConnection()->getDatabaseName()) !== $this->getConnection()->getDatabaseName()) {
$schema = '';
if ($query->getConnection()->getDriverName() === 'sqlsrv') {
$schema = ($query->getConnection()->getConfig('schema') ?? 'dbo').'.';
}

if ($this->shouldPrefixDatabaseName($query->from, $database)) {
$query->from($database.'.'.$schema.$query->from);
$query->prependDatabaseNameForJoins();
}
}
}

/**
* Prepend the database name to each join table.
*
* @return void
*/
protected function prependDatabaseNameIfCrossDatabaseQuery($query)
public function prependDatabaseNameForJoins()
{
if ($query->getConnection()->getDatabaseName() !==
$this->getConnection()->getDatabaseName()) {
$databaseName = $query->getConnection()->getDatabaseName();
foreach ($this->joins ?? [] as $join) {
$schema = '';
if ($join->getConnection()->getDriverName() === 'sqlsrv') {
$schema = ($join->getConnection()->getConfig('schema') ?? 'dbo').'.';
}

if (! str_starts_with($query->from, $databaseName) && ! str_contains($query->from, '.')) {
$query->from($databaseName.'.'.$query->from);
if ($this->shouldPrefixDatabaseName($join->table, $joinDatabase = $join->getConnection()->getDatabaseName())) {
$join->table = $joinDatabase.'.'.$schema.$join->table;
}
}
}

return $query;
/**
* @param string $table
* @param string $database
* @return bool
*/
protected function shouldPrefixDatabaseName($table, $database)
{
return ! str_starts_with($table, $database) && ! str_contains($table, '.');
}

/**
Expand Down
14 changes: 14 additions & 0 deletions src/Illuminate/Database/Query/JoinClause.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Database\Query;

use Closure;
use Illuminate\Database\ConnectionInterface;

class JoinClause extends Builder
{
Expand Down Expand Up @@ -122,6 +123,19 @@ public function newQuery()
return new static($this->newParentQuery(), $this->type, $this->table);
}

/**
* Set the connection for this join clause.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @return $this
*/
public function setConnection(ConnectionInterface $connection)
{
$this->connection = $connection;

return $this;
}

/**
* Create a new query instance for sub-query.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ public function getRelationArguments()
$related->shouldReceive('getKeyName')->andReturn('id');
$related->shouldReceive('qualifyColumn')->with('id')->andReturn('users.id');

$builder->shouldReceive('join')->once()->with('club_user', 'users.id', '=', 'club_user.user_id');
$builder->shouldReceive('join')->once()->with(
m::on(fn ($arg) => is_string($arg)), m::on(fn ($arg) => is_callable($arg))
);
$builder->shouldReceive('where')->once()->with('club_user.club_id', '=', 1);
$builder->shouldReceive('where')->once()->with('club_user.is_admin', '=', 1, 'and');

Expand Down
5 changes: 4 additions & 1 deletion tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,9 @@ public function testEagerLoadRelationsCanBeFlushed()

public function testRelationshipEagerLoadProcess()
{
$builder = m::mock(Builder::class.'[getRelation]', [$this->getMockQueryBuilder()]);
$baseBuilder = $this->getMockQueryBuilder();
$baseBuilder->shouldReceive('prependDatabaseNameIfCrossDatabaseQuery')->once();
$builder = m::mock(Builder::class.'[getRelation]', [$baseBuilder]);
$builder->setEagerLoads(['orders' => function ($query) {
$_SERVER['__eloquent.constrain'] = $query;
}]);
Expand All @@ -772,6 +774,7 @@ public function testRelationshipEagerLoadProcess()
$relation->shouldReceive('initRelation')->once()->with(['models'], 'orders')->andReturn(['models']);
$relation->shouldReceive('getEager')->once()->andReturn(['results']);
$relation->shouldReceive('match')->once()->with(['models'], ['results'], 'orders')->andReturn(['models.matched']);
$relation->shouldReceive('getBaseQuery')->once()->andReturn(new \stdClass);
$builder->shouldReceive('getRelation')->once()->with('orders')->andReturn($relation);
$results = $builder->eagerLoadRelations(['models']);

Expand Down
4 changes: 4 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,8 @@ public function testEagerLoadingWithColumns()
public function testWithWhereHasWithSpecificColumns()
{
$model = new EloquentModelWithWhereHasStub;
$connection = $this->addMockConnection($model);
$connection->shouldReceive('getDatabaseName')->andReturn('forge');
$instance = $model->newInstance()->newQuery()->withWhereHas('foo:diaa,fares');
$builder = m::mock(Builder::class);
$builder->shouldReceive('select')->once()->with(['diaa', 'fares']);
Expand Down Expand Up @@ -2524,6 +2526,8 @@ protected function addMockConnection($model)
$connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) {
return new BaseBuilder($connection, $grammar, $processor);
});

return $connection;
}

public function testTouchingModelWithTimestamps()
Expand Down
4 changes: 3 additions & 1 deletion tests/Database/DatabaseEloquentMorphToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ public function getRelationArguments()
$related->shouldReceive('qualifyColumn')->with('id')->andReturn('tags.id');
$related->shouldReceive('getMorphClass')->andReturn(get_class($related));

$builder->shouldReceive('join')->once()->with('taggables', 'tags.id', '=', 'taggables.tag_id');
$builder->shouldReceive('join')->once()->with(
m::on(fn ($arg) => is_string($arg)), m::on(fn ($arg) => is_callable($arg))
);
$builder->shouldReceive('where')->once()->with('taggables.taggable_id', '=', 1);
$builder->shouldReceive('where')->once()->with('taggables.taggable_type', get_class($parent));

Expand Down
Loading