Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Commit

Permalink
schema aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
wolfy-j committed Mar 5, 2016
1 parent f99f9c8 commit e6cc13a
Showing 1 changed file with 55 additions and 6 deletions.
61 changes: 55 additions & 6 deletions source/Spiral/ORM/Entities/SchemaBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ class SchemaBuilder extends Component
*/
private $tables = [];

/**
* Associations between tables and their database and original table aliases.
*
* @var array
*/
private $aliases = [];

/**
* @var ORMConfig
*/
Expand Down Expand Up @@ -131,15 +138,57 @@ public function hasTable($database, $table)
*/
public function declareTable($database, $table)
{
$database = $this->resolveDatabase($database);
$normalizedDatabase = $this->resolveDatabase($database);

if (isset($this->tables[$normalizedDatabase . '/' . $table])) {
return $this->tables[$normalizedDatabase . '/' . $table];
}

$schema = $this->orm->database($normalizedDatabase)->table($table)->schema();

$this->aliases[] = [
'schema' => $schema,
'database' => $database,
'table' => $table
];

if (isset($this->tables[$database . '/' . $table])) {
return $this->tables[$database . '/' . $table];
return $this->tables[$normalizedDatabase . '/' . $table] = $schema;
}

/**
* Database aliases associated with given table schema.
*
* @param AbstractTable $table
* @return string
* @throws SchemaException
*/
public function databaseAlias(AbstractTable $table)
{
foreach ($this->aliases as $item) {
if ($item['schema'] === $table) {
return $item['database'];
}
}

$schema = $this->orm->database($database)->table($table)->schema();
throw new SchemaException("Unable to resolve database alias for table '{$table->getName()}'");
}

return $this->tables[$database . '/' . $table] = $schema;
/**
* Table aliases associated with given table schema.
*
* @param AbstractTable $table
* @return string
* @throws SchemaException
*/
public function tableAlias(AbstractTable $table)
{
foreach ($this->aliases as $item) {
if ($item['schema'] === $table) {
return $item['table'];
}
}

throw new SchemaException("Unable to resolve table alias for table '{$table->getName()}'");
}

/**
Expand Down Expand Up @@ -385,7 +434,7 @@ protected function castSchemas()
foreach ($this->records as $record) {
$record->castSchema();
}

$inversedRelations = [];
foreach ($this->records as $record) {
if ($record->isAbstract()) {
Expand Down

0 comments on commit e6cc13a

Please sign in to comment.