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

[12.x] Enhance multi-database support #54274

Merged
merged 10 commits into from
Jan 22, 2025
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
12 changes: 7 additions & 5 deletions src/Illuminate/Database/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1650,17 +1650,19 @@ public function withTablePrefix(Grammar $grammar)
* Execute the given callback without table prefix.
*
* @param \Closure $callback
* @return void
* @return mixed
*/
public function withoutTablePrefix(Closure $callback): void
public function withoutTablePrefix(Closure $callback): mixed
{
$tablePrefix = $this->getTablePrefix();

$this->setTablePrefix('');

$callback($this);

$this->setTablePrefix($tablePrefix);
try {
return $callback($this);
} finally {
$this->setTablePrefix($tablePrefix);
}
}

/**
Expand Down
16 changes: 0 additions & 16 deletions src/Illuminate/Database/Console/DatabaseInspectionCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,4 @@ protected function getConfigFromDatabase($database)

return Arr::except(config('database.connections.'.$database), ['password']);
}

/**
* Remove the table prefix from a table name, if it exists.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param string $table
* @return string
*/
protected function withoutTablePrefix(ConnectionInterface $connection, string $table)
{
$prefix = $connection->getTablePrefix();

return str_starts_with($table, $prefix)
? substr($table, strlen($prefix))
: $table;
}
}
7 changes: 3 additions & 4 deletions src/Illuminate/Database/Console/ShowCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Number;
use Illuminate\Support\Stringable;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'db:show')]
Expand Down Expand Up @@ -80,9 +79,10 @@ protected function tables(ConnectionInterface $connection, Builder $schema)
return (new Collection($schema->getTables()))->map(fn ($table) => [
'table' => $table['name'],
'schema' => $table['schema'],
'schema_qualified_name' => $table['schema_qualified_name'],
'size' => $table['size'],
'rows' => $this->option('counts')
? ($connection->table($table['schema'] ? $table['schema'].'.'.$table['name'] : $table['name'])->count())
? $connection->withoutTablePrefix(fn ($connection) => $connection->table($table['schema_qualified_name'])->count())
: null,
'engine' => $table['engine'],
'collation' => $table['collation'],
Expand All @@ -100,11 +100,10 @@ protected function tables(ConnectionInterface $connection, Builder $schema)
protected function views(ConnectionInterface $connection, Builder $schema)
{
return (new Collection($schema->getViews()))
->reject(fn ($view) => (new Stringable($view['name']))->startsWith(['pg_catalog', 'information_schema', 'spt_']))
->map(fn ($view) => [
'view' => $view['name'],
'schema' => $view['schema'],
'rows' => $connection->table($view['schema'] ? $view['schema'].'.'.$view['name'] : $view['name'])->count(),
'rows' => $connection->withoutTablePrefix(fn ($connection) => $connection->table($view['schema_qualified_name'])->count()),
]);
}

Expand Down
22 changes: 13 additions & 9 deletions src/Illuminate/Database/Console/TableCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,8 @@ class TableCommand extends DatabaseInspectionCommand
public function handle(ConnectionResolverInterface $connections)
{
$connection = $connections->connection($this->input->getOption('database'));
$schema = $connection->getSchemaBuilder();
$tables = (new Collection($schema->getTables()))
->keyBy(fn ($table) => $table['schema'] ? $table['schema'].'.'.$table['name'] : $table['name'])
->all();
$tables = (new Collection($connection->getSchemaBuilder()->getTables()))
->keyBy('schema_qualified_name')->all();

$tableName = $this->argument('table') ?: select(
'Which table would you like to inspect?',
Expand All @@ -57,16 +55,22 @@ public function handle(ConnectionResolverInterface $connections)
return 1;
}

$tableName = ($table['schema'] ? $table['schema'].'.' : '').$this->withoutTablePrefix($connection, $table['name']);
[$columns, $indexes, $foreignKeys] = $connection->withoutTablePrefix(function ($connection) use ($table) {
$schema = $connection->getSchemaBuilder();
$tableName = $table['schema_qualified_name'];

$columns = $this->columns($schema, $tableName);
$indexes = $this->indexes($schema, $tableName);
$foreignKeys = $this->foreignKeys($schema, $tableName);
return [
$this->columns($schema, $tableName),
$this->indexes($schema, $tableName),
$this->foreignKeys($schema, $tableName),
];
});

$data = [
'table' => [
'schema' => $table['schema'],
'name' => $table['name'],
'schema_qualified_name' => $table['schema_qualified_name'],
'columns' => count($columns),
'size' => $table['size'],
'comment' => $table['comment'],
Expand Down Expand Up @@ -205,7 +209,7 @@ protected function displayForCli(array $data)

$this->newLine();

$this->components->twoColumnDetail('<fg=green;options=bold>'.($table['schema'] ? $table['schema'].'.'.$table['name'] : $table['name']).'</>', $table['comment'] ? '<fg=gray>'.$table['comment'].'</>' : null);
$this->components->twoColumnDetail('<fg=green;options=bold>'.$table['schema_qualified_name'].'</>', $table['comment'] ? '<fg=gray>'.$table['comment'].'</>' : null);
$this->components->twoColumnDetail('Columns', $table['columns']);

if (! is_null($table['size'])) {
Expand Down
9 changes: 6 additions & 3 deletions src/Illuminate/Database/Grammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,10 @@ public function wrapArray(array $values)
* Wrap a table in keyword identifiers.
*
* @param \Illuminate\Contracts\Database\Query\Expression|string $table
* @param string|null $prefix
* @return string
*/
public function wrapTable($table)
public function wrapTable($table, $prefix = null)
{
if ($this->isExpression($table)) {
return $this->getValue($table);
Expand All @@ -55,18 +56,20 @@ public function wrapTable($table)
return $this->wrapAliasedTable($table);
}

$prefix ??= $this->tablePrefix;

// If the table being wrapped has a custom schema name specified, we need to
// prefix the last segment as the table name then wrap each segment alone
// and eventually join them both back together using the dot connector.
if (str_contains($table, '.')) {
$table = substr_replace($table, '.'.$this->tablePrefix, strrpos($table, '.'), 1);
$table = substr_replace($table, '.'.$prefix, strrpos($table, '.'), 1);

return (new Collection(explode('.', $table)))
->map($this->wrapValue(...))
->implode('.');
}

return $this->wrapValue($this->tablePrefix.$table);
return $this->wrapValue($prefix.$table);
}

/**
Expand Down
6 changes: 5 additions & 1 deletion src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,12 @@ protected function compileDeleteWithJoinsOrLimit(Builder $query)
*/
public function compileTruncate(Builder $query)
{
[$schema, $table] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($query->from);

$schema = $schema ? $this->wrapValue($schema).'.' : '';

return [
'delete from sqlite_sequence where name = ?' => [$this->getTablePrefix().$query->from],
'delete from '.$schema.'sqlite_sequence where name = ?' => [$this->getTablePrefix().$table],
'delete from '.$this->wrapTable($query->from) => [],
];
}
Expand Down
5 changes: 3 additions & 2 deletions src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -557,12 +557,13 @@ protected function wrapJsonBooleanValue($value)
* Wrap a table in keyword identifiers.
*
* @param \Illuminate\Contracts\Database\Query\Expression|string $table
* @param string|null $prefix
* @return string
*/
public function wrapTable($table)
public function wrapTable($table, $prefix = null)
{
if (! $this->isExpression($table)) {
return $this->wrapTableValuedFunction(parent::wrapTable($table));
return $this->wrapTableValuedFunction(parent::wrapTable($table, $prefix));
}

return $this->getValue($table);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public function processTypes($results)
return [
'name' => $result->name,
'schema' => $result->schema,
'schema_qualified_name' => $result->schema.'.'.$result->name,
'implicit' => (bool) $result->implicit,
'type' => match (strtolower($result->type)) {
'b' => 'base',
Expand Down
25 changes: 23 additions & 2 deletions src/Illuminate/Database/Query/Processors/Processor.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ public function processInsertGetId(Builder $query, $sql, $values, $sequence = nu
return is_numeric($id) ? (int) $id : $id;
}

/**
* Process the results of a schemas query.
*
* @param array $results
* @return array
*/
public function processSchemas($results)
{
return array_map(function ($result) {
$result = (object) $result;

return [
'name' => $result->name,
'path' => $result->path ?? null, // SQLite Only...
'default' => (bool) $result->default,
];
}, $results);
}

/**
* Process the results of a tables query.
*
Expand All @@ -49,7 +68,8 @@ public function processTables($results)

return [
'name' => $result->name,
'schema' => $result->schema ?? null, // PostgreSQL and SQL Server
'schema' => $result->schema ?? null,
'schema_qualified_name' => isset($result->schema) ? $result->schema.'.'.$result->name : $result->name,
'size' => isset($result->size) ? (int) $result->size : null,
'comment' => $result->comment ?? null, // MySQL and PostgreSQL
'collation' => $result->collation ?? null, // MySQL only
Expand All @@ -71,7 +91,8 @@ public function processViews($results)

return [
'name' => $result->name,
'schema' => $result->schema ?? null, // PostgreSQL and SQL Server
'schema' => $result->schema ?? null,
'schema_qualified_name' => isset($result->schema) ? $result->schema.'.'.$result->name : $result->name,
'definition' => $result->definition,
];
}, $results);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public function processForeignKeys($results)
return [
'name' => null,
'columns' => explode(',', $result->columns),
'foreign_schema' => null,
'foreign_schema' => $result->foreign_schema,
'foreign_table' => $result->foreign_table,
'foreign_columns' => explode(',', $result->foreign_columns),
'on_update' => strtolower($result->on_update),
Expand Down
Loading