init
This commit is contained in:
+553
@@ -0,0 +1,553 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Config;
|
||||
|
||||
use Closure;
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Db\Adapter\SQLiteAdapter;
|
||||
use Phinx\Util\Util;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Phinx configuration class.
|
||||
*
|
||||
* @package Phinx
|
||||
* @author Rob Morgan
|
||||
*/
|
||||
class Config implements ConfigInterface, NamespaceAwareInterface
|
||||
{
|
||||
use NamespaceAwareTrait;
|
||||
|
||||
/**
|
||||
* The value that identifies a version order by creation time.
|
||||
*/
|
||||
public const VERSION_ORDER_CREATION_TIME = 'creation';
|
||||
|
||||
/**
|
||||
* The value that identifies a version order by execution time.
|
||||
*/
|
||||
public const VERSION_ORDER_EXECUTION_TIME = 'execution';
|
||||
|
||||
public const TEMPLATE_STYLE_CHANGE = 'change';
|
||||
public const TEMPLATE_STYLE_UP_DOWN = 'up_down';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $values = [];
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $configFilePath;
|
||||
|
||||
/**
|
||||
* @param array $configArray Config array
|
||||
* @param string|null $configFilePath Config file path
|
||||
*/
|
||||
public function __construct(array $configArray, ?string $configFilePath = null)
|
||||
{
|
||||
$this->configFilePath = $configFilePath;
|
||||
$this->values = $this->replaceTokens($configArray);
|
||||
|
||||
if (isset($this->values['feature_flags'])) {
|
||||
FeatureFlags::setFlagsFromConfig($this->values['feature_flags']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the config class using a Yaml file path.
|
||||
*
|
||||
* @param string $configFilePath Path to the Yaml File
|
||||
* @throws \RuntimeException
|
||||
* @return \Phinx\Config\ConfigInterface
|
||||
*/
|
||||
public static function fromYaml(string $configFilePath): ConfigInterface
|
||||
{
|
||||
if (!class_exists('Symfony\\Component\\Yaml\\Yaml', true)) {
|
||||
// @codeCoverageIgnoreStart
|
||||
throw new RuntimeException('Missing yaml parser, symfony/yaml package is not installed.');
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
$configFile = file_get_contents($configFilePath);
|
||||
$configArray = Yaml::parse($configFile);
|
||||
|
||||
if (!is_array($configArray)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'File \'%s\' must be valid YAML',
|
||||
$configFilePath
|
||||
));
|
||||
}
|
||||
|
||||
return new static($configArray, $configFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the config class using a JSON file path.
|
||||
*
|
||||
* @param string $configFilePath Path to the JSON File
|
||||
* @throws \RuntimeException
|
||||
* @return \Phinx\Config\ConfigInterface
|
||||
*/
|
||||
public static function fromJson(string $configFilePath): ConfigInterface
|
||||
{
|
||||
if (!function_exists('json_decode')) {
|
||||
// @codeCoverageIgnoreStart
|
||||
throw new RuntimeException('Need to install JSON PHP extension to use JSON config');
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
$configArray = json_decode(file_get_contents($configFilePath), true);
|
||||
if (!is_array($configArray)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'File \'%s\' must be valid JSON',
|
||||
$configFilePath
|
||||
));
|
||||
}
|
||||
|
||||
return new static($configArray, $configFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the config class using a PHP file path.
|
||||
*
|
||||
* @param string $configFilePath Path to the PHP File
|
||||
* @throws \RuntimeException
|
||||
* @return \Phinx\Config\ConfigInterface
|
||||
*/
|
||||
public static function fromPhp(string $configFilePath): ConfigInterface
|
||||
{
|
||||
ob_start();
|
||||
/** @noinspection PhpIncludeInspection */
|
||||
$configArray = include $configFilePath;
|
||||
|
||||
// Hide console output
|
||||
ob_end_clean();
|
||||
|
||||
if (!is_array($configArray)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'PHP file \'%s\' must return an array',
|
||||
$configFilePath
|
||||
));
|
||||
}
|
||||
|
||||
return new static($configArray, $configFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getEnvironments(): ?array
|
||||
{
|
||||
if (isset($this->values['environments'])) {
|
||||
$environments = [];
|
||||
foreach ($this->values['environments'] as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$environments[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $environments;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getEnvironment(string $name): ?array
|
||||
{
|
||||
$environments = $this->getEnvironments();
|
||||
|
||||
if (isset($environments[$name])) {
|
||||
if (
|
||||
isset($this->values['environments']['default_migration_table'])
|
||||
&& !isset($environments[$name]['migration_table'])
|
||||
) {
|
||||
$environments[$name]['migration_table'] =
|
||||
$this->values['environments']['default_migration_table'];
|
||||
}
|
||||
|
||||
if (
|
||||
isset($environments[$name]['adapter'])
|
||||
&& $environments[$name]['adapter'] === 'sqlite'
|
||||
&& !empty($environments[$name]['memory'])
|
||||
) {
|
||||
$environments[$name]['name'] = SQLiteAdapter::MEMORY;
|
||||
}
|
||||
|
||||
return $this->parseAgnosticDsn($environments[$name]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasEnvironment(string $name): bool
|
||||
{
|
||||
return $this->getEnvironment($name) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getDefaultEnvironment(): string
|
||||
{
|
||||
// The $PHINX_ENVIRONMENT variable overrides all other default settings
|
||||
$env = getenv('PHINX_ENVIRONMENT');
|
||||
if (!empty($env)) {
|
||||
if ($this->hasEnvironment($env)) {
|
||||
return $env;
|
||||
}
|
||||
|
||||
throw new RuntimeException(sprintf(
|
||||
'The environment configuration (read from $PHINX_ENVIRONMENT) for \'%s\' is missing',
|
||||
$env
|
||||
));
|
||||
}
|
||||
|
||||
// deprecated: to be removed 0.13
|
||||
if (isset($this->values['environments']['default_database'])) {
|
||||
trigger_error('default_database in the config has been deprecated since 0.12, use default_environment instead.', E_USER_DEPRECATED);
|
||||
$this->values['environments']['default_environment'] = $this->values['environments']['default_database'];
|
||||
}
|
||||
|
||||
// if the user has configured a default environment then use it,
|
||||
// providing it actually exists!
|
||||
if (isset($this->values['environments']['default_environment'])) {
|
||||
if ($this->hasEnvironment($this->values['environments']['default_environment'])) {
|
||||
return $this->values['environments']['default_environment'];
|
||||
}
|
||||
|
||||
throw new RuntimeException(sprintf(
|
||||
'The environment configuration for \'%s\' is missing',
|
||||
$this->values['environments']['default_environment']
|
||||
));
|
||||
}
|
||||
|
||||
// else default to the first available one
|
||||
if (is_array($this->getEnvironments()) && count($this->getEnvironments()) > 0) {
|
||||
$names = array_keys($this->getEnvironments());
|
||||
|
||||
return $names[0];
|
||||
}
|
||||
|
||||
throw new RuntimeException('Could not find a default environment');
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAlias($alias): ?string
|
||||
{
|
||||
return !empty($this->values['aliases'][$alias]) ? $this->values['aliases'][$alias] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAliases(): array
|
||||
{
|
||||
return !empty($this->values['aliases']) ? $this->values['aliases'] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getConfigFilePath(): ?string
|
||||
{
|
||||
return $this->configFilePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws \UnexpectedValueException
|
||||
*/
|
||||
public function getMigrationPaths(): array
|
||||
{
|
||||
if (!isset($this->values['paths']['migrations'])) {
|
||||
throw new UnexpectedValueException('Migrations path missing from config file');
|
||||
}
|
||||
|
||||
if (is_string($this->values['paths']['migrations'])) {
|
||||
$this->values['paths']['migrations'] = [$this->values['paths']['migrations']];
|
||||
}
|
||||
|
||||
return $this->values['paths']['migrations'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws \UnexpectedValueException
|
||||
*/
|
||||
public function getSeedPaths(): array
|
||||
{
|
||||
if (!isset($this->values['paths']['seeds'])) {
|
||||
throw new UnexpectedValueException('Seeds path missing from config file');
|
||||
}
|
||||
|
||||
if (is_string($this->values['paths']['seeds'])) {
|
||||
$this->values['paths']['seeds'] = [$this->values['paths']['seeds']];
|
||||
}
|
||||
|
||||
return $this->values['paths']['seeds'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getMigrationBaseClassName(bool $dropNamespace = true): string
|
||||
{
|
||||
$className = !isset($this->values['migration_base_class']) ? 'Phinx\Migration\AbstractMigration' : $this->values['migration_base_class'];
|
||||
|
||||
return $dropNamespace ? (substr(strrchr($className, '\\'), 1) ?: $className) : $className;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getSeedBaseClassName(bool $dropNamespace = true): string
|
||||
{
|
||||
$className = !isset($this->values['seed_base_class']) ? 'Phinx\Seed\AbstractSeed' : $this->values['seed_base_class'];
|
||||
|
||||
return $dropNamespace ? substr(strrchr($className, '\\'), 1) : $className;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getTemplateFile()
|
||||
{
|
||||
if (!isset($this->values['templates']['file'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->values['templates']['file'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getTemplateClass()
|
||||
{
|
||||
if (!isset($this->values['templates']['class'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->values['templates']['class'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getTemplateStyle(): string
|
||||
{
|
||||
if (!isset($this->values['templates']['style'])) {
|
||||
return self::TEMPLATE_STYLE_CHANGE;
|
||||
}
|
||||
|
||||
return $this->values['templates']['style'] === self::TEMPLATE_STYLE_UP_DOWN ? self::TEMPLATE_STYLE_UP_DOWN : self::TEMPLATE_STYLE_CHANGE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getDataDomain(): array
|
||||
{
|
||||
if (!isset($this->values['data_domain'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->values['data_domain'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getContainer(): ?ContainerInterface
|
||||
{
|
||||
if (!isset($this->values['container'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->values['container'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getVersionOrder(): string
|
||||
{
|
||||
if (!isset($this->values['version_order'])) {
|
||||
return self::VERSION_ORDER_CREATION_TIME;
|
||||
}
|
||||
|
||||
return $this->values['version_order'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function isVersionOrderCreationTime(): bool
|
||||
{
|
||||
$versionOrder = $this->getVersionOrder();
|
||||
|
||||
return $versionOrder == self::VERSION_ORDER_CREATION_TIME;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getBootstrapFile()
|
||||
{
|
||||
if (!isset($this->values['paths']['bootstrap'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->values['paths']['bootstrap'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace tokens in the specified array.
|
||||
*
|
||||
* @param array $arr Array to replace
|
||||
* @return array
|
||||
*/
|
||||
protected function replaceTokens(array $arr): array
|
||||
{
|
||||
// Get environment variables
|
||||
// Depending on configuration of server / OS and variables_order directive,
|
||||
// environment variables either end up in $_SERVER (most likely) or $_ENV,
|
||||
// so we search through both
|
||||
$tokens = [];
|
||||
foreach (array_merge($_ENV, $_SERVER) as $varname => $varvalue) {
|
||||
if (strpos($varname, 'PHINX_') === 0) {
|
||||
$tokens['%%' . $varname . '%%'] = $varvalue;
|
||||
}
|
||||
}
|
||||
|
||||
// Phinx defined tokens (override env tokens)
|
||||
$tokens['%%PHINX_CONFIG_PATH%%'] = $this->getConfigFilePath();
|
||||
$tokens['%%PHINX_CONFIG_DIR%%'] = $this->getConfigFilePath() !== null ? dirname($this->getConfigFilePath()) : '';
|
||||
|
||||
// Recurse the array and replace tokens
|
||||
return $this->recurseArrayForTokens($arr, $tokens);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recurse an array for the specified tokens and replace them.
|
||||
*
|
||||
* @param array $arr Array to recurse
|
||||
* @param string[] $tokens Array of tokens to search for
|
||||
* @return array
|
||||
*/
|
||||
protected function recurseArrayForTokens(array $arr, array $tokens): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($arr as $name => $value) {
|
||||
if (is_array($value)) {
|
||||
$out[$name] = $this->recurseArrayForTokens($value, $tokens);
|
||||
continue;
|
||||
}
|
||||
if (is_string($value)) {
|
||||
foreach ($tokens as $token => $tval) {
|
||||
$value = str_replace($token, $tval ?? '', $value);
|
||||
}
|
||||
$out[$name] = $value;
|
||||
continue;
|
||||
}
|
||||
$out[$name] = $value;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a database-agnostic DSN into individual options.
|
||||
*
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function parseAgnosticDsn(array $options): array
|
||||
{
|
||||
$parsed = Util::parseDsn($options['dsn'] ?? '');
|
||||
if ($parsed) {
|
||||
unset($options['dsn']);
|
||||
}
|
||||
|
||||
$options += $parsed;
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param mixed $id ID
|
||||
* @param mixed $value Value
|
||||
* @return void
|
||||
*/
|
||||
public function offsetSet($id, $value): void
|
||||
{
|
||||
$this->values[$id] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param mixed $id ID
|
||||
* @throws \InvalidArgumentException
|
||||
* @return mixed
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function offsetGet($id)
|
||||
{
|
||||
if (!array_key_exists($id, $this->values)) {
|
||||
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
|
||||
}
|
||||
|
||||
return $this->values[$id] instanceof Closure ? $this->values[$id]($this) : $this->values[$id];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param mixed $id ID
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($id): bool
|
||||
{
|
||||
return isset($this->values[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param mixed $id ID
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($id): void
|
||||
{
|
||||
unset($this->values[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getSeedTemplateFile(): ?string
|
||||
{
|
||||
return $this->values['templates']['seedFile'] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Config;
|
||||
|
||||
use ArrayAccess;
|
||||
use Psr\Container\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Phinx configuration interface.
|
||||
*
|
||||
* @package Phinx
|
||||
* @author Woody Gilk
|
||||
*/
|
||||
interface ConfigInterface extends ArrayAccess
|
||||
{
|
||||
/**
|
||||
* Returns the configuration for each environment.
|
||||
*
|
||||
* This method returns <code>null</code> if no environments exist.
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function getEnvironments(): ?array;
|
||||
|
||||
/**
|
||||
* Returns the configuration for a given environment.
|
||||
*
|
||||
* This method returns <code>null</code> if the specified environment
|
||||
* doesn't exist.
|
||||
*
|
||||
* @param string $name Environment Name
|
||||
* @return array|null
|
||||
*/
|
||||
public function getEnvironment(string $name): ?array;
|
||||
|
||||
/**
|
||||
* Does the specified environment exist in the configuration file?
|
||||
*
|
||||
* @param string $name Environment Name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasEnvironment(string $name): bool;
|
||||
|
||||
/**
|
||||
* Gets the default environment name.
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* @return string
|
||||
*/
|
||||
public function getDefaultEnvironment(): string;
|
||||
|
||||
/**
|
||||
* Get the aliased value from a supplied alias.
|
||||
*
|
||||
* @param string $alias Alias
|
||||
* @return string|null
|
||||
*/
|
||||
public function getAlias(string $alias): ?string;
|
||||
|
||||
/**
|
||||
* Get all the aliased values.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getAliases(): array;
|
||||
|
||||
/**
|
||||
* Gets the config file path.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getConfigFilePath(): ?string;
|
||||
|
||||
/**
|
||||
* Gets the paths to search for migration files.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getMigrationPaths(): array;
|
||||
|
||||
/**
|
||||
* Gets the paths to search for seed files.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getSeedPaths(): array;
|
||||
|
||||
/**
|
||||
* Get the template file name.
|
||||
*
|
||||
* @return string|false
|
||||
*/
|
||||
public function getTemplateFile();
|
||||
|
||||
/**
|
||||
* Get the template class name.
|
||||
*
|
||||
* @return string|false
|
||||
*/
|
||||
public function getTemplateClass();
|
||||
|
||||
/**
|
||||
* Get the template style to use, either change or up_down.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getTemplateStyle(): string;
|
||||
|
||||
/**
|
||||
* Get the user-provided container for instantiating seeds
|
||||
*
|
||||
* @return \Psr\Container\ContainerInterface|null
|
||||
*/
|
||||
public function getContainer(): ?ContainerInterface;
|
||||
|
||||
/**
|
||||
* Get the data domain array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDataDomain(): array;
|
||||
|
||||
/**
|
||||
* Get the version order.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getVersionOrder(): string;
|
||||
|
||||
/**
|
||||
* Is version order creation time?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isVersionOrderCreationTime(): bool;
|
||||
|
||||
/**
|
||||
* Get the bootstrap file path
|
||||
*
|
||||
* @return string|false
|
||||
*/
|
||||
public function getBootstrapFile();
|
||||
|
||||
/**
|
||||
* Gets the base class name for migrations.
|
||||
*
|
||||
* @param bool $dropNamespace Return the base migration class name without the namespace.
|
||||
* @return string
|
||||
*/
|
||||
public function getMigrationBaseClassName(bool $dropNamespace = true): string;
|
||||
|
||||
/**
|
||||
* Gets the base class name for seeders.
|
||||
*
|
||||
* @param bool $dropNamespace Return the base seeder class name without the namespace.
|
||||
* @return string
|
||||
*/
|
||||
public function getSeedBaseClassName(bool $dropNamespace = true): string;
|
||||
|
||||
/**
|
||||
* Get the seeder template file name or null if not set.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getSeedTemplateFile(): ?string;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Config;
|
||||
|
||||
/**
|
||||
* Class to hold features flags to toggle breaking changes in Phinx.
|
||||
*
|
||||
* New flags should be added very sparingly.
|
||||
*/
|
||||
class FeatureFlags
|
||||
{
|
||||
/**
|
||||
* @var bool Should Phinx create unsigned primary keys by default?
|
||||
*/
|
||||
public static $unsignedPrimaryKeys = true;
|
||||
/**
|
||||
* @var bool Should Phinx create columns NULL by default?
|
||||
*/
|
||||
public static $columnNullDefault = true;
|
||||
|
||||
/**
|
||||
* Set the feature flags from the `feature_flags` section of the overall
|
||||
* config.
|
||||
*
|
||||
* @param array $config The `feature_flags` section of the config
|
||||
*/
|
||||
public static function setFlagsFromConfig(array $config): void
|
||||
{
|
||||
if (isset($config['unsigned_primary_keys'])) {
|
||||
self::$unsignedPrimaryKeys = (bool)$config['unsigned_primary_keys'];
|
||||
}
|
||||
if (isset($config['column_null_default'])) {
|
||||
self::$columnNullDefault = (bool)$config['column_null_default'];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Config;
|
||||
|
||||
/**
|
||||
* Config aware getNamespaceByPath method.
|
||||
*
|
||||
* @package Phinx\Config
|
||||
* @author Andrey N. Mokhov
|
||||
*/
|
||||
interface NamespaceAwareInterface
|
||||
{
|
||||
/**
|
||||
* Get Migration Namespace associated with path.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @return string|null
|
||||
*/
|
||||
public function getMigrationNamespaceByPath(string $path): ?string;
|
||||
|
||||
/**
|
||||
* Get Seed Namespace associated with path.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @return string|null
|
||||
*/
|
||||
public function getSeedNamespaceByPath(string $path): ?string;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Config;
|
||||
|
||||
/**
|
||||
* Trait implemented NamespaceAwareInterface.
|
||||
*
|
||||
* @package Phinx\Config
|
||||
* @author Andrey N. Mokhov
|
||||
*/
|
||||
trait NamespaceAwareTrait
|
||||
{
|
||||
/**
|
||||
* Gets the paths to search for migration files.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
abstract public function getMigrationPaths(): array;
|
||||
|
||||
/**
|
||||
* Gets the paths to search for seed files.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
abstract public function getSeedPaths(): array;
|
||||
|
||||
/**
|
||||
* Search $needle in $haystack and return key associate with him.
|
||||
*
|
||||
* @param string $needle Needle
|
||||
* @param string[] $haystack Haystack
|
||||
* @return string|null
|
||||
*/
|
||||
protected function searchNamespace(string $needle, array $haystack): ?string
|
||||
{
|
||||
$needle = realpath($needle);
|
||||
$haystack = array_map('realpath', $haystack);
|
||||
|
||||
$key = array_search($needle, $haystack, true);
|
||||
|
||||
return is_string($key) ? trim($key, '\\') : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Migration Namespace associated with path.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @return string|null
|
||||
*/
|
||||
public function getMigrationNamespaceByPath(string $path): ?string
|
||||
{
|
||||
$paths = $this->getMigrationPaths();
|
||||
|
||||
return $this->searchNamespace($path, $paths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Seed Namespace associated with path.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @return string|null
|
||||
*/
|
||||
public function getSeedNamespaceByPath(string $path): ?string
|
||||
{
|
||||
$paths = $this->getSeedPaths();
|
||||
|
||||
return $this->searchNamespace($path, $paths);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Config\Config;
|
||||
use Phinx\Config\ConfigInterface;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Migration\Manager;
|
||||
use Phinx\Util\Util;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Config\FileLocator;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Abstract command, contains bootstrapping info
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
abstract class AbstractCommand extends Command
|
||||
{
|
||||
public const FORMAT_JSON = 'json';
|
||||
public const FORMAT_YML_ALIAS = 'yaml';
|
||||
public const FORMAT_YML = 'yml';
|
||||
public const FORMAT_PHP = 'php';
|
||||
public const FORMAT_DEFAULT = 'php';
|
||||
|
||||
/**
|
||||
* The location of the default change migration template.
|
||||
*/
|
||||
protected const DEFAULT_CHANGE_MIGRATION_TEMPLATE = '/../../Migration/Migration.change.template.php.dist';
|
||||
|
||||
/**
|
||||
* The location of the default up/down migration template.
|
||||
*/
|
||||
protected const DEFAULT_UP_DOWN_MIGRATION_TEMPLATE = '/../../Migration/Migration.up_down.template.php.dist';
|
||||
|
||||
/**
|
||||
* The location of the default seed template.
|
||||
*/
|
||||
protected const DEFAULT_SEED_TEMPLATE = '/../../Seed/Seed.template.php.dist';
|
||||
|
||||
/**
|
||||
* @var \Phinx\Config\ConfigInterface|null
|
||||
*/
|
||||
protected $config;
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
protected $adapter;
|
||||
|
||||
/**
|
||||
* @var \Phinx\Migration\Manager
|
||||
*/
|
||||
protected $manager;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $verbosityLevel = OutputInterface::OUTPUT_NORMAL | OutputInterface::VERBOSITY_NORMAL;
|
||||
|
||||
/**
|
||||
* Exit code for when command executes successfully
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const CODE_SUCCESS = 0;
|
||||
|
||||
/**
|
||||
* Exit code for when command hits a non-recoverable error during execution
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const CODE_ERROR = 1;
|
||||
|
||||
/**
|
||||
* Exit code for when status command is run and there are missing migrations
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const CODE_STATUS_MISSING = 2;
|
||||
|
||||
/**
|
||||
* Exit code for when status command is run and there are no missing migations,
|
||||
* but does have down migrations
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const CODE_STATUS_DOWN = 3;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->addOption('--configuration', '-c', InputOption::VALUE_REQUIRED, 'The configuration file to load');
|
||||
$this->addOption('--parser', '-p', InputOption::VALUE_REQUIRED, 'Parser used to read the config file. Defaults to YAML');
|
||||
$this->addOption('--no-info', null, InputOption::VALUE_NONE, 'Hides all debug information');
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap Phinx.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return void
|
||||
*/
|
||||
public function bootstrap(InputInterface $input, OutputInterface $output): void
|
||||
{
|
||||
if ($input->hasParameterOption('--no-info')) {
|
||||
$this->verbosityLevel = OutputInterface::VERBOSITY_VERBOSE;
|
||||
}
|
||||
|
||||
if (!$this->hasConfig()) {
|
||||
$this->loadConfig($input, $output);
|
||||
}
|
||||
|
||||
$this->loadManager($input, $output);
|
||||
|
||||
$bootstrap = $this->getConfig()->getBootstrapFile();
|
||||
if ($bootstrap) {
|
||||
$output->writeln('<info>using bootstrap</info> ' . Util::relativePath($bootstrap) . ' ', $this->verbosityLevel);
|
||||
Util::loadPhpFile($bootstrap, $input, $output, $this);
|
||||
}
|
||||
|
||||
// report the paths
|
||||
$paths = $this->getConfig()->getMigrationPaths();
|
||||
|
||||
$output->writeln('<info>using migration paths</info> ', $this->verbosityLevel);
|
||||
|
||||
foreach (Util::globAll($paths) as $path) {
|
||||
$output->writeln('<info> - ' . realpath($path) . '</info>', $this->verbosityLevel);
|
||||
}
|
||||
|
||||
try {
|
||||
$paths = $this->getConfig()->getSeedPaths();
|
||||
|
||||
$output->writeln('<info>using seed paths</info> ', $this->verbosityLevel);
|
||||
|
||||
foreach (Util::globAll($paths) as $path) {
|
||||
$output->writeln('<info> - ' . realpath($path) . '</info>', $this->verbosityLevel);
|
||||
}
|
||||
} catch (UnexpectedValueException $e) {
|
||||
// do nothing as seeds are optional
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the config.
|
||||
*
|
||||
* @param \Phinx\Config\ConfigInterface $config Config
|
||||
* @return $this
|
||||
*/
|
||||
public function setConfig(ConfigInterface $config)
|
||||
{
|
||||
$this->config = $config;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function hasConfig(): bool
|
||||
{
|
||||
return $this->config !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the config.
|
||||
*
|
||||
* @return \Phinx\Config\ConfigInterface
|
||||
*/
|
||||
public function getConfig(): ConfigInterface
|
||||
{
|
||||
if ($this->config === null) {
|
||||
throw new RuntimeException('No config set yet');
|
||||
}
|
||||
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database adapter.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Adapter
|
||||
* @return $this
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter)
|
||||
{
|
||||
$this->adapter = $adapter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the database adapter.
|
||||
*
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface
|
||||
{
|
||||
return $this->adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the migration manager.
|
||||
*
|
||||
* @param \Phinx\Migration\Manager $manager Manager
|
||||
* @return $this
|
||||
*/
|
||||
public function setManager(Manager $manager)
|
||||
{
|
||||
$this->manager = $manager;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the migration manager.
|
||||
*
|
||||
* @return \Phinx\Migration\Manager|null
|
||||
*/
|
||||
public function getManager(): ?Manager
|
||||
{
|
||||
return $this->manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns config file path
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @return string
|
||||
*/
|
||||
protected function locateConfigFile(InputInterface $input): string
|
||||
{
|
||||
$configFile = $input->hasOption('configuration') ? $input->getOption('configuration') : null;
|
||||
|
||||
$useDefault = false;
|
||||
|
||||
if ($configFile === null || $configFile === false) {
|
||||
$useDefault = true;
|
||||
}
|
||||
|
||||
$cwd = getcwd();
|
||||
|
||||
// locate the phinx config file
|
||||
// In future walk the tree in reverse (max 10 levels)
|
||||
$locator = new FileLocator([
|
||||
$cwd . DIRECTORY_SEPARATOR,
|
||||
]);
|
||||
|
||||
if (!$useDefault) {
|
||||
// Locate() throws an exception if the file does not exist
|
||||
return $locator->locate($configFile, $cwd, true);
|
||||
}
|
||||
|
||||
$possibleConfigFiles = ['phinx.php', 'phinx.json', 'phinx.yaml', 'phinx.yml'];
|
||||
foreach ($possibleConfigFiles as $configFile) {
|
||||
try {
|
||||
return $locator->locate($configFile, $cwd, true);
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
$lastException = $exception;
|
||||
}
|
||||
}
|
||||
throw $lastException;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the config file and load it into the config object
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadConfig(InputInterface $input, OutputInterface $output): void
|
||||
{
|
||||
$configFilePath = $this->locateConfigFile($input);
|
||||
$output->writeln('<info>using config file</info> ' . Util::relativePath($configFilePath), $this->verbosityLevel);
|
||||
|
||||
/** @var string|null $parser */
|
||||
$parser = $input->getOption('parser');
|
||||
|
||||
// If no parser is specified try to determine the correct one from the file extension. Defaults to YAML
|
||||
if ($parser === null) {
|
||||
$extension = pathinfo($configFilePath, PATHINFO_EXTENSION);
|
||||
|
||||
switch (strtolower($extension)) {
|
||||
case self::FORMAT_JSON:
|
||||
$parser = self::FORMAT_JSON;
|
||||
break;
|
||||
case self::FORMAT_YML_ALIAS:
|
||||
case self::FORMAT_YML:
|
||||
$parser = self::FORMAT_YML;
|
||||
break;
|
||||
case self::FORMAT_PHP:
|
||||
default:
|
||||
$parser = self::FORMAT_DEFAULT;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (strtolower($parser)) {
|
||||
case self::FORMAT_JSON:
|
||||
$config = Config::fromJson($configFilePath);
|
||||
break;
|
||||
case self::FORMAT_PHP:
|
||||
$config = Config::fromPhp($configFilePath);
|
||||
break;
|
||||
case self::FORMAT_YML_ALIAS:
|
||||
case self::FORMAT_YML:
|
||||
$config = Config::fromYaml($configFilePath);
|
||||
break;
|
||||
default:
|
||||
throw new InvalidArgumentException(sprintf('\'%s\' is not a valid parser.', $parser));
|
||||
}
|
||||
|
||||
$output->writeln('<info>using config parser</info> ' . $parser, $this->verbosityLevel);
|
||||
|
||||
$this->setConfig($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the migrations manager and inject the config
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return void
|
||||
*/
|
||||
protected function loadManager(InputInterface $input, OutputInterface $output): void
|
||||
{
|
||||
if ($this->getManager() === null) {
|
||||
$manager = new Manager($this->getConfig(), $input, $output);
|
||||
$manager->setVerbosityLevel($this->verbosityLevel);
|
||||
$container = $this->getConfig()->getContainer();
|
||||
if ($container !== null) {
|
||||
$manager->setContainer($container);
|
||||
}
|
||||
$this->setManager($manager);
|
||||
} else {
|
||||
$manager = $this->getManager();
|
||||
$manager->setInput($input);
|
||||
$manager->setOutput($output);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the migration directory exists and is writable.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
protected function verifyMigrationDirectory(string $path): void
|
||||
{
|
||||
if (!is_dir($path)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Migration directory "%s" does not exist',
|
||||
$path
|
||||
));
|
||||
}
|
||||
|
||||
if (!is_writable($path)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Migration directory "%s" is not writable',
|
||||
$path
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the seed directory exists and is writable.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
protected function verifySeedDirectory(string $path): void
|
||||
{
|
||||
if (!is_dir($path)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Seed directory "%s" does not exist',
|
||||
$path
|
||||
));
|
||||
}
|
||||
|
||||
if (!is_writable($path)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Seed directory "%s" is not writable',
|
||||
$path
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the migration template filename.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getMigrationTemplateFilename(string $style): string
|
||||
{
|
||||
return $style === Config::TEMPLATE_STYLE_CHANGE ? __DIR__ . self::DEFAULT_CHANGE_MIGRATION_TEMPLATE : __DIR__ . self::DEFAULT_UP_DOWN_MIGRATION_TEMPLATE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the seed template filename.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getSeedTemplateFilename(): string
|
||||
{
|
||||
return __DIR__ . self::DEFAULT_SEED_TEMPLATE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'breakpoint')]
|
||||
class Breakpoint extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'breakpoint';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->addOption('--environment', '-e', InputOption::VALUE_REQUIRED, 'The target environment.');
|
||||
|
||||
$this->setDescription('Manage breakpoints')
|
||||
->addOption('--target', '-t', InputOption::VALUE_REQUIRED, 'The version number to target for the breakpoint')
|
||||
->addOption('--set', '-s', InputOption::VALUE_NONE, 'Set the breakpoint')
|
||||
->addOption('--unset', '-u', InputOption::VALUE_NONE, 'Unset the breakpoint')
|
||||
->addOption('--remove-all', '-r', InputOption::VALUE_NONE, 'Remove all breakpoints')
|
||||
->setHelp(
|
||||
<<<EOT
|
||||
The <info>breakpoint</info> command allows you to toggle, set, or unset a breakpoint against a specific target to inhibit rollbacks beyond a certain target.
|
||||
If no target is supplied then the most recent migration will be used.
|
||||
You cannot specify un-migrated targets
|
||||
|
||||
<info>phinx breakpoint -e development</info>
|
||||
<info>phinx breakpoint -e development -t 20110103081132</info>
|
||||
<info>phinx breakpoint -e development -r</info>
|
||||
EOT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the breakpoint.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \InvalidArgumentException
|
||||
* @return int integer 0 on success, or an error code.
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
/** @var string|null $environment */
|
||||
$environment = $input->getOption('environment');
|
||||
$version = (int)$input->getOption('target') ?: null;
|
||||
$removeAll = $input->getOption('remove-all');
|
||||
$set = $input->getOption('set');
|
||||
$unset = $input->getOption('unset');
|
||||
|
||||
if ($environment === null) {
|
||||
$environment = $this->getConfig()->getDefaultEnvironment();
|
||||
$output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment, $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<info>using environment</info> ' . $environment, $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (!$this->getConfig()->hasEnvironment($environment)) {
|
||||
$output->writeln(sprintf('<error>The environment "%s" does not exist</error>', $environment));
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
if ($version && $removeAll) {
|
||||
throw new InvalidArgumentException('Cannot toggle a breakpoint and remove all breakpoints at the same time.');
|
||||
}
|
||||
|
||||
if (($set && $unset) || ($set && $removeAll) || ($unset && $removeAll)) {
|
||||
throw new InvalidArgumentException('Cannot use more than one of --set, --unset, or --remove-all at the same time.');
|
||||
}
|
||||
|
||||
if ($removeAll) {
|
||||
// Remove all breakpoints.
|
||||
$this->getManager()->removeBreakpoints($environment);
|
||||
} elseif ($set) {
|
||||
// Set the breakpoint.
|
||||
$this->getManager()->setBreakpoint($environment, $version);
|
||||
} elseif ($unset) {
|
||||
// Unset the breakpoint.
|
||||
$this->getManager()->unsetBreakpoint($environment, $version);
|
||||
} else {
|
||||
// Toggle the breakpoint.
|
||||
$this->getManager()->toggleBreakpoint($environment, $version);
|
||||
}
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Config\Config;
|
||||
use Phinx\Config\NamespaceAwareInterface;
|
||||
use Phinx\Util\Util;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Question\ChoiceQuestion;
|
||||
use Symfony\Component\Console\Question\ConfirmationQuestion;
|
||||
|
||||
#[AsCommand(name: 'create')]
|
||||
class Create extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'create';
|
||||
|
||||
/**
|
||||
* The name of the interface that any external template creation class is required to implement.
|
||||
*/
|
||||
public const CREATION_INTERFACE = 'Phinx\Migration\CreationInterface';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->setDescription('Create a new migration')
|
||||
->addArgument('name', InputArgument::OPTIONAL, 'Class name of the migration (in CamelCase)')
|
||||
->setHelp(sprintf(
|
||||
'%sCreates a new database migration%s',
|
||||
PHP_EOL,
|
||||
PHP_EOL
|
||||
));
|
||||
|
||||
// An alternative template.
|
||||
$this->addOption('template', 't', InputOption::VALUE_REQUIRED, 'Use an alternative template');
|
||||
|
||||
// A classname to be used to gain access to the template content as well as the ability to
|
||||
// have a callback once the migration file has been created.
|
||||
$this->addOption('class', 'l', InputOption::VALUE_REQUIRED, 'Use a class implementing "' . self::CREATION_INTERFACE . '" to generate the template');
|
||||
|
||||
// Allow the migration path to be chosen non-interactively.
|
||||
$this->addOption('path', null, InputOption::VALUE_REQUIRED, 'Specify the path in which to create this migration');
|
||||
|
||||
$this->addOption('style', null, InputOption::VALUE_REQUIRED, 'Specify the style of migration to create');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the confirmation question asking if the user wants to create the
|
||||
* migrations directory.
|
||||
*
|
||||
* @return \Symfony\Component\Console\Question\ConfirmationQuestion
|
||||
*/
|
||||
protected function getCreateMigrationDirectoryQuestion(): ConfirmationQuestion
|
||||
{
|
||||
return new ConfirmationQuestion('Create migrations directory? [y]/n ', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the question that allows the user to select which migration path to use.
|
||||
*
|
||||
* @param string[] $paths Paths
|
||||
* @return \Symfony\Component\Console\Question\ChoiceQuestion
|
||||
*/
|
||||
protected function getSelectMigrationPathQuestion(array $paths): ChoiceQuestion
|
||||
{
|
||||
return new ChoiceQuestion('Which migrations path would you like to use?', $paths, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the migration path to create the migration in.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \Exception
|
||||
* @return string
|
||||
*/
|
||||
protected function getMigrationPath(InputInterface $input, OutputInterface $output): string
|
||||
{
|
||||
// First, try the non-interactive option:
|
||||
$path = $input->getOption('path');
|
||||
|
||||
if (!empty($path)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$paths = $this->getConfig()->getMigrationPaths();
|
||||
|
||||
// No paths? That's a problem.
|
||||
if (empty($paths)) {
|
||||
throw new Exception('No migration paths set in your Phinx configuration file.');
|
||||
}
|
||||
|
||||
$paths = Util::globAll($paths);
|
||||
|
||||
if (empty($paths)) {
|
||||
throw new Exception(
|
||||
'You probably used curly braces to define migration path in your Phinx configuration file, ' .
|
||||
'but no directories have been matched using this pattern. ' .
|
||||
'You need to create a migration directory manually.'
|
||||
);
|
||||
}
|
||||
|
||||
// Only one path set, so select that:
|
||||
if (count($paths) === 1) {
|
||||
return array_shift($paths);
|
||||
}
|
||||
|
||||
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
|
||||
$helper = $this->getHelper('question');
|
||||
$question = $this->getSelectMigrationPathQuestion($paths);
|
||||
|
||||
return $helper->ask($input, $output, $question);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the new migration.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \RuntimeException
|
||||
* @throws \InvalidArgumentException
|
||||
* @return int 0 on success
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
// get the migration path from the config
|
||||
$path = $this->getMigrationPath($input, $output);
|
||||
|
||||
if (!file_exists($path)) {
|
||||
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
|
||||
$helper = $this->getHelper('question');
|
||||
$question = $this->getCreateMigrationDirectoryQuestion();
|
||||
|
||||
if ($helper->ask($input, $output, $question)) {
|
||||
mkdir($path, 0755, true);
|
||||
}
|
||||
}
|
||||
|
||||
$this->verifyMigrationDirectory($path);
|
||||
|
||||
$config = $this->getConfig();
|
||||
$namespace = $config instanceof NamespaceAwareInterface ? $config->getMigrationNamespaceByPath($path) : null;
|
||||
|
||||
$path = realpath($path);
|
||||
$className = $input->getArgument('name');
|
||||
if ($className === null) {
|
||||
$currentTimestamp = Util::getCurrentTimestamp();
|
||||
$className = 'V' . $currentTimestamp;
|
||||
$fileName = $currentTimestamp . '.php';
|
||||
} else {
|
||||
if (!Util::isValidPhinxClassName($className)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The migration class name "%s" is invalid. Please use CamelCase format.',
|
||||
$className
|
||||
));
|
||||
}
|
||||
|
||||
// Compute the file path
|
||||
$fileName = Util::mapClassNameToFileName($className);
|
||||
}
|
||||
|
||||
if (!Util::isUniqueMigrationClassName($className, $path)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The migration class name "%s%s" already exists',
|
||||
$namespace ? $namespace . '\\' : '',
|
||||
$className
|
||||
));
|
||||
}
|
||||
|
||||
$filePath = $path . DIRECTORY_SEPARATOR . $fileName;
|
||||
|
||||
if (is_file($filePath)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The file "%s" already exists',
|
||||
$filePath
|
||||
));
|
||||
}
|
||||
|
||||
// Get the alternative template and static class options from the config, but only allow one of them.
|
||||
$defaultAltTemplate = $this->getConfig()->getTemplateFile();
|
||||
$defaultCreationClassName = $this->getConfig()->getTemplateClass();
|
||||
$defaultStyle = $this->getConfig()->getTemplateStyle();
|
||||
if ($defaultAltTemplate && $defaultCreationClassName) {
|
||||
throw new InvalidArgumentException('Cannot define template:class and template:file at the same time');
|
||||
}
|
||||
|
||||
// Get the alternative template and static class options from the command line, but only allow one of them.
|
||||
/** @var string|null $altTemplate */
|
||||
$altTemplate = $input->getOption('template');
|
||||
/** @var string|null $creationClassName */
|
||||
$creationClassName = $input->getOption('class');
|
||||
$style = $input->getOption('style');
|
||||
|
||||
if ($altTemplate && $creationClassName) {
|
||||
throw new InvalidArgumentException('Cannot use --template and --class at the same time');
|
||||
}
|
||||
|
||||
if ($style && !in_array($style, [Config::TEMPLATE_STYLE_CHANGE, Config::TEMPLATE_STYLE_UP_DOWN])) {
|
||||
throw new InvalidArgumentException('--style should be one of ' . Config::TEMPLATE_STYLE_CHANGE . ' or ' . Config::TEMPLATE_STYLE_UP_DOWN);
|
||||
}
|
||||
|
||||
// If no commandline options then use the defaults.
|
||||
if (!$altTemplate && !$creationClassName) {
|
||||
$altTemplate = $defaultAltTemplate;
|
||||
$creationClassName = $defaultCreationClassName;
|
||||
}
|
||||
|
||||
// Verify the alternative template file's existence.
|
||||
if ($altTemplate && !is_file($altTemplate)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The alternative template file "%s" does not exist',
|
||||
$altTemplate
|
||||
));
|
||||
}
|
||||
|
||||
// Verify that the template creation class (or the aliased class) exists and that it implements the required interface.
|
||||
$aliasedClassName = null;
|
||||
if ($creationClassName) {
|
||||
// Supplied class does not exist, is it aliased?
|
||||
if (!class_exists($creationClassName)) {
|
||||
$aliasedClassName = $this->getConfig()->getAlias($creationClassName);
|
||||
if ($aliasedClassName && !class_exists($aliasedClassName)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The class "%s" via the alias "%s" does not exist',
|
||||
$aliasedClassName,
|
||||
$creationClassName
|
||||
));
|
||||
} elseif (!$aliasedClassName) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The class "%s" does not exist',
|
||||
$creationClassName
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Does the class implement the required interface?
|
||||
if (!$aliasedClassName && !is_subclass_of($creationClassName, self::CREATION_INTERFACE)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The class "%s" does not implement the required interface "%s"',
|
||||
$creationClassName,
|
||||
self::CREATION_INTERFACE
|
||||
));
|
||||
} elseif ($aliasedClassName && !is_subclass_of($aliasedClassName, self::CREATION_INTERFACE)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The class "%s" via the alias "%s" does not implement the required interface "%s"',
|
||||
$aliasedClassName,
|
||||
$creationClassName,
|
||||
self::CREATION_INTERFACE
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Use the aliased class.
|
||||
$creationClassName = $aliasedClassName ?: $creationClassName;
|
||||
|
||||
// Determine the appropriate mechanism to get the template
|
||||
if ($creationClassName) {
|
||||
// Get the template from the creation class
|
||||
$creationClass = new $creationClassName($input, $output);
|
||||
$contents = $creationClass->getMigrationTemplate();
|
||||
} else {
|
||||
// Load the alternative template if it is defined.
|
||||
$contents = file_get_contents($altTemplate ?: $this->getMigrationTemplateFilename($style ?: $defaultStyle));
|
||||
}
|
||||
|
||||
// inject the class names appropriate to this migration
|
||||
$classes = [
|
||||
'$namespaceDefinition' => $namespace !== null ? (PHP_EOL . 'namespace ' . $namespace . ';' . PHP_EOL) : '',
|
||||
'$namespace' => $namespace,
|
||||
'$useClassName' => $this->getConfig()->getMigrationBaseClassName(false),
|
||||
'$className' => $className,
|
||||
'$version' => Util::getVersionFromFileName($fileName),
|
||||
'$baseClassName' => $this->getConfig()->getMigrationBaseClassName(true),
|
||||
];
|
||||
$contents = strtr($contents, $classes);
|
||||
|
||||
if (file_put_contents($filePath, $contents) === false) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'The file "%s" could not be written to',
|
||||
$path
|
||||
));
|
||||
}
|
||||
|
||||
// Do we need to do the post creation call to the creation class?
|
||||
if (isset($creationClass)) {
|
||||
/** @var \Phinx\Migration\CreationInterface $creationClass */
|
||||
$creationClass->postMigrationCreation($filePath, $className, $this->getConfig()->getMigrationBaseClassName());
|
||||
}
|
||||
|
||||
$output->writeln('<info>using migration base class</info> ' . $classes['$useClassName'], $this->verbosityLevel);
|
||||
|
||||
if (!empty($altTemplate)) {
|
||||
$output->writeln('<info>using alternative template</info> ' . $altTemplate, $this->verbosityLevel);
|
||||
} elseif (!empty($creationClassName)) {
|
||||
$output->writeln('<info>using template creation class</info> ' . $creationClassName, $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<info>using default template</info>', $this->verbosityLevel);
|
||||
}
|
||||
|
||||
$output->writeln('<info>created</info> ' . Util::relativePath($filePath), $this->verbosityLevel);
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'init')]
|
||||
class Init extends Command
|
||||
{
|
||||
protected const FILE_NAME = 'phinx';
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
protected static $supportedFormats = [
|
||||
AbstractCommand::FORMAT_JSON,
|
||||
AbstractCommand::FORMAT_YML_ALIAS,
|
||||
AbstractCommand::FORMAT_YML,
|
||||
AbstractCommand::FORMAT_PHP,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'init';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->setDescription('Initialize the application for Phinx')
|
||||
->addOption(
|
||||
'--format',
|
||||
'-f',
|
||||
InputArgument::OPTIONAL,
|
||||
'What format should we use to initialize?',
|
||||
AbstractCommand::FORMAT_DEFAULT
|
||||
)
|
||||
->addArgument('path', InputArgument::OPTIONAL, 'Which path should we initialize for Phinx?')
|
||||
->setHelp(sprintf(
|
||||
'%sInitializes the application for Phinx%s',
|
||||
PHP_EOL,
|
||||
PHP_EOL
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the application.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Interface implemented by all input classes.
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Interface implemented by all output classes.
|
||||
* @return int 0 on success
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$format = strtolower($input->getOption('format'));
|
||||
$path = $this->resolvePath($input, $format);
|
||||
$this->writeConfig($path, $format);
|
||||
|
||||
$output->writeln("<info>created</info> {$path}");
|
||||
|
||||
return AbstractCommand::CODE_SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return valid $path for Phinx's config file.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Interface implemented by all input classes.
|
||||
* @param string $format Format to resolve for
|
||||
* @throws \InvalidArgumentException
|
||||
* @return string
|
||||
*/
|
||||
protected function resolvePath(InputInterface $input, string $format): string
|
||||
{
|
||||
// get the migration path from the config
|
||||
$path = (string)$input->getArgument('path');
|
||||
|
||||
if (!in_array($format, static::$supportedFormats, true)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Invalid format "%s". Format must be either ' . implode(', ', static::$supportedFormats) . '.',
|
||||
$format
|
||||
));
|
||||
}
|
||||
|
||||
// Fallback
|
||||
if (!$path) {
|
||||
$path = getcwd() . DIRECTORY_SEPARATOR . self::FILE_NAME . '.' . $format;
|
||||
}
|
||||
|
||||
// Adding file name if necessary
|
||||
if (is_dir($path)) {
|
||||
$path .= DIRECTORY_SEPARATOR . self::FILE_NAME . '.' . $format;
|
||||
}
|
||||
|
||||
// Check if path is available
|
||||
$dirname = dirname($path);
|
||||
if (is_dir($dirname) && !is_file($path)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
// Path is valid, but file already exists
|
||||
if (is_file($path)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Config file "%s" already exists.',
|
||||
$path
|
||||
));
|
||||
}
|
||||
|
||||
// Dir is invalid
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Invalid path "%s" for config file.',
|
||||
$path
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes Phinx's config in provided $path
|
||||
*
|
||||
* @param string $path Config file's path.
|
||||
* @param string $format Format to use for config file
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \RuntimeException
|
||||
* @return void
|
||||
*/
|
||||
protected function writeConfig(string $path, string $format = AbstractCommand::FORMAT_DEFAULT): void
|
||||
{
|
||||
// Check if dir is writable
|
||||
$dirname = dirname($path);
|
||||
if (!is_writable($dirname)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The directory "%s" is not writable',
|
||||
$dirname
|
||||
));
|
||||
}
|
||||
|
||||
if ($format === AbstractCommand::FORMAT_YML_ALIAS) {
|
||||
$format = AbstractCommand::FORMAT_YML;
|
||||
}
|
||||
|
||||
// load the config template
|
||||
if (is_dir(__DIR__ . '/../../../../data')) {
|
||||
$contents = file_get_contents(__DIR__ . '/../../../../data/' . self::FILE_NAME . '.' . $format . '.dist');
|
||||
} else {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Could not find template for format "%s".',
|
||||
$format
|
||||
));
|
||||
}
|
||||
|
||||
if (file_put_contents($path, $contents) === false) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'The file "%s" could not be written to',
|
||||
$path
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use Phinx\Util\Util;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'list:aliases')]
|
||||
class ListAliases extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'list:aliases';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->setDescription('List template class aliases')
|
||||
->setHelp('The <info>list:aliases</info> command lists the migration template generation class aliases');
|
||||
}
|
||||
|
||||
/**
|
||||
* List migration template creation aliases.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return int 0 on success
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
$aliases = $this->config->getAliases();
|
||||
|
||||
if ($aliases) {
|
||||
$maxAliasLength = max(array_map('strlen', array_keys($aliases)));
|
||||
$maxClassLength = max(array_map('strlen', $aliases));
|
||||
$output->writeln(
|
||||
array_merge(
|
||||
[
|
||||
'',
|
||||
sprintf('%s %s', str_pad('Alias', $maxAliasLength), str_pad('Class', $maxClassLength)),
|
||||
sprintf('%s %s', str_repeat('=', $maxAliasLength), str_repeat('=', $maxClassLength)),
|
||||
],
|
||||
array_map(
|
||||
function ($alias, $class) use ($maxAliasLength, $maxClassLength) {
|
||||
return sprintf('%s %s', str_pad($alias, $maxAliasLength), str_pad($class, $maxClassLength));
|
||||
},
|
||||
array_keys($aliases),
|
||||
$aliases
|
||||
)
|
||||
),
|
||||
$this->verbosityLevel
|
||||
);
|
||||
} else {
|
||||
$output->writeln(
|
||||
sprintf(
|
||||
'<error>No aliases defined in %s</error>',
|
||||
Util::relativePath($this->config->getConfigFilePath())
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use DateTime;
|
||||
use Exception;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Throwable;
|
||||
|
||||
#[AsCommand(name: 'migrate')]
|
||||
class Migrate extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'migrate';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->addOption('--environment', '-e', InputOption::VALUE_REQUIRED, 'The target environment');
|
||||
|
||||
$this->setDescription('Migrate the database')
|
||||
->addOption('--target', '-t', InputOption::VALUE_REQUIRED, 'The version number to migrate to')
|
||||
->addOption('--date', '-d', InputOption::VALUE_REQUIRED, 'The date to migrate to')
|
||||
->addOption('--dry-run', '-x', InputOption::VALUE_NONE, 'Dump query to standard output instead of executing it')
|
||||
->addOption('--fake', null, InputOption::VALUE_NONE, "Mark any migrations selected as run, but don't actually execute them")
|
||||
->setHelp(
|
||||
<<<EOT
|
||||
The <info>migrate</info> command runs all available migrations, optionally up to a specific version
|
||||
|
||||
<info>phinx migrate -e development</info>
|
||||
<info>phinx migrate -e development -t 20110103081132</info>
|
||||
<info>phinx migrate -e development -d 20110103</info>
|
||||
<info>phinx migrate -e development -v</info>
|
||||
|
||||
EOT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate the database.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return int integer 0 on success, or an error code.
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
$version = $input->getOption('target');
|
||||
/** @var string|null $environment */
|
||||
$environment = $input->getOption('environment');
|
||||
$date = $input->getOption('date');
|
||||
$fake = (bool)$input->getOption('fake');
|
||||
|
||||
if ($environment === null) {
|
||||
$environment = $this->getConfig()->getDefaultEnvironment();
|
||||
$output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment, $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<info>using environment</info> ' . $environment, $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (!$this->getConfig()->hasEnvironment($environment)) {
|
||||
$output->writeln(sprintf('<error>The environment "%s" does not exist</error>', $environment));
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
$envOptions = $this->getConfig()->getEnvironment($environment);
|
||||
if (isset($envOptions['adapter'])) {
|
||||
$output->writeln('<info>using adapter</info> ' . $envOptions['adapter'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (isset($envOptions['wrapper'])) {
|
||||
$output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (isset($envOptions['name'])) {
|
||||
$output->writeln('<info>using database</info> ' . $envOptions['name'], $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<error>Could not determine database name! Please specify a database name in your config file.</error>');
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
if (isset($envOptions['table_prefix'])) {
|
||||
$output->writeln('<info>using table prefix</info> ' . $envOptions['table_prefix'], $this->verbosityLevel);
|
||||
}
|
||||
if (isset($envOptions['table_suffix'])) {
|
||||
$output->writeln('<info>using table suffix</info> ' . $envOptions['table_suffix'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
$versionOrder = $this->getConfig()->getVersionOrder();
|
||||
$output->writeln('<info>ordering by</info> ' . $versionOrder . ' time', $this->verbosityLevel);
|
||||
|
||||
if ($fake) {
|
||||
$output->writeln('<comment>warning</comment> performing fake migrations', $this->verbosityLevel);
|
||||
}
|
||||
|
||||
try {
|
||||
// run the migrations
|
||||
$start = microtime(true);
|
||||
if ($date !== null) {
|
||||
$this->getManager()->migrateToDateTime($environment, new DateTime($date), $fake);
|
||||
} else {
|
||||
$this->getManager()->migrate($environment, $version, $fake);
|
||||
}
|
||||
$end = microtime(true);
|
||||
} catch (Exception $e) {
|
||||
$output->writeln('<error>' . $e->__toString() . '</error>');
|
||||
|
||||
return self::CODE_ERROR;
|
||||
} catch (Throwable $e) {
|
||||
$output->writeln('<error>' . $e->__toString() . '</error>');
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
$output->writeln('', $this->verbosityLevel);
|
||||
$output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>', $this->verbosityLevel);
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use DateTime;
|
||||
use InvalidArgumentException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'rollback')]
|
||||
class Rollback extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'rollback';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->addOption('--environment', '-e', InputOption::VALUE_REQUIRED, 'The target environment');
|
||||
|
||||
$this->setDescription('Rollback the last or to a specific migration')
|
||||
->addOption('--target', '-t', InputOption::VALUE_REQUIRED, 'The version number to rollback to')
|
||||
->addOption('--date', '-d', InputOption::VALUE_REQUIRED, 'The date to rollback to')
|
||||
->addOption('--force', '-f', InputOption::VALUE_NONE, 'Force rollback to ignore breakpoints')
|
||||
->addOption('--dry-run', '-x', InputOption::VALUE_NONE, 'Dump query to standard output instead of executing it')
|
||||
->addOption('--fake', null, InputOption::VALUE_NONE, "Mark any rollbacks selected as run, but don't actually execute them")
|
||||
->setHelp(
|
||||
<<<EOT
|
||||
The <info>rollback</info> command reverts the last migration, or optionally up to a specific version
|
||||
|
||||
<info>phinx rollback -e development</info>
|
||||
<info>phinx rollback -e development -t 20111018185412</info>
|
||||
<info>phinx rollback -e development -d 20111018</info>
|
||||
<info>phinx rollback -e development -v</info>
|
||||
<info>phinx rollback -e development -t 20111018185412 -f</info>
|
||||
|
||||
If you have a breakpoint set, then you can rollback to target 0 and the rollbacks will stop at the breakpoint.
|
||||
<info>phinx rollback -e development -t 0 </info>
|
||||
|
||||
The <info>version_order</info> configuration option is used to determine the order of the migrations when rolling back.
|
||||
This can be used to allow the rolling back of the last executed migration instead of the last created one, or combined
|
||||
with the <info>-d|--date</info> option to rollback to a certain date using the migration start times to order them.
|
||||
|
||||
EOT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback the migration.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return int integer 0 on success, or an error code.
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
$environment = $input->getOption('environment');
|
||||
$version = $input->getOption('target');
|
||||
$date = $input->getOption('date');
|
||||
$force = (bool)$input->getOption('force');
|
||||
$fake = (bool)$input->getOption('fake');
|
||||
|
||||
$config = $this->getConfig();
|
||||
|
||||
if ($environment === null) {
|
||||
$environment = $config->getDefaultEnvironment();
|
||||
$output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment, $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<info>using environment</info> ' . $environment, $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (!$this->getConfig()->hasEnvironment($environment)) {
|
||||
$output->writeln(sprintf('<error>The environment "%s" does not exist</error>', $environment));
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
$envOptions = $config->getEnvironment($environment);
|
||||
if (isset($envOptions['adapter'])) {
|
||||
$output->writeln('<info>using adapter</info> ' . $envOptions['adapter'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (isset($envOptions['wrapper'])) {
|
||||
$output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (isset($envOptions['name'])) {
|
||||
$output->writeln('<info>using database</info> ' . $envOptions['name'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
$versionOrder = $this->getConfig()->getVersionOrder();
|
||||
$output->writeln('<info>ordering by</info> ' . $versionOrder . ' time', $this->verbosityLevel);
|
||||
|
||||
if ($fake) {
|
||||
$output->writeln('<comment>warning</comment> performing fake rollbacks', $this->verbosityLevel);
|
||||
}
|
||||
|
||||
// rollback the specified environment
|
||||
if ($date === null) {
|
||||
$targetMustMatchVersion = true;
|
||||
$target = $version;
|
||||
} else {
|
||||
$targetMustMatchVersion = false;
|
||||
$target = $this->getTargetFromDate($date);
|
||||
}
|
||||
|
||||
$start = microtime(true);
|
||||
$this->getManager()->rollback($environment, $target, $force, $targetMustMatchVersion, $fake);
|
||||
$end = microtime(true);
|
||||
|
||||
$output->writeln('', $this->verbosityLevel);
|
||||
$output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>', $this->verbosityLevel);
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Target from Date
|
||||
*
|
||||
* @param string $date The date to convert to a target.
|
||||
* @throws \InvalidArgumentException
|
||||
* @return string The target
|
||||
*/
|
||||
public function getTargetFromDate(string $date): string
|
||||
{
|
||||
if (!preg_match('/^\d{4,14}$/', $date)) {
|
||||
throw new InvalidArgumentException('Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].');
|
||||
}
|
||||
|
||||
// what we need to append to the date according to the possible date string lengths
|
||||
$dateStrlenToAppend = [
|
||||
14 => '',
|
||||
12 => '00',
|
||||
10 => '0000',
|
||||
8 => '000000',
|
||||
6 => '01000000',
|
||||
4 => '0101000000',
|
||||
];
|
||||
|
||||
if (!isset($dateStrlenToAppend[strlen($date)])) {
|
||||
throw new InvalidArgumentException('Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].');
|
||||
}
|
||||
|
||||
$target = $date . $dateStrlenToAppend[strlen($date)];
|
||||
|
||||
$dateTime = DateTime::createFromFormat('YmdHis', $target);
|
||||
|
||||
if ($dateTime === false) {
|
||||
throw new InvalidArgumentException('Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].');
|
||||
}
|
||||
|
||||
return $dateTime->format('YmdHis');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Config\NamespaceAwareInterface;
|
||||
use Phinx\Util\Util;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Question\ChoiceQuestion;
|
||||
use Symfony\Component\Console\Question\ConfirmationQuestion;
|
||||
|
||||
#[AsCommand(name: 'seed:create')]
|
||||
class SeedCreate extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'seed:create';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->setDescription('Create a new database seeder')
|
||||
->addArgument('name', InputArgument::REQUIRED, 'What is the name of the seeder?')
|
||||
->addOption('path', null, InputOption::VALUE_REQUIRED, 'Specify the path in which to create this seeder')
|
||||
->setHelp(sprintf(
|
||||
'%sCreates a new database seeder%s',
|
||||
PHP_EOL,
|
||||
PHP_EOL
|
||||
));
|
||||
|
||||
// An alternative template.
|
||||
$this->addOption('template', 't', InputOption::VALUE_REQUIRED, 'Use an alternative template');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the confirmation question asking if the user wants to create the
|
||||
* seeds directory.
|
||||
*
|
||||
* @return \Symfony\Component\Console\Question\ConfirmationQuestion
|
||||
*/
|
||||
protected function getCreateSeedDirectoryQuestion(): ConfirmationQuestion
|
||||
{
|
||||
return new ConfirmationQuestion('Create seeds directory? [y]/n ', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the question that allows the user to select which seed path to use.
|
||||
*
|
||||
* @param string[] $paths Paths
|
||||
* @return \Symfony\Component\Console\Question\ChoiceQuestion
|
||||
*/
|
||||
protected function getSelectSeedPathQuestion(array $paths): ChoiceQuestion
|
||||
{
|
||||
return new ChoiceQuestion('Which seeds path would you like to use?', $paths, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the seed path to create the seeder in.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \Exception
|
||||
* @return string
|
||||
*/
|
||||
protected function getSeedPath(InputInterface $input, OutputInterface $output): string
|
||||
{
|
||||
// First, try the non-interactive option:
|
||||
$path = $input->getOption('path');
|
||||
|
||||
if (!empty($path)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$paths = $this->getConfig()->getSeedPaths();
|
||||
|
||||
// No paths? That's a problem.
|
||||
if (empty($paths)) {
|
||||
throw new Exception('No seed paths set in your Phinx configuration file.');
|
||||
}
|
||||
|
||||
$paths = Util::globAll($paths);
|
||||
|
||||
if (empty($paths)) {
|
||||
throw new Exception(
|
||||
'You probably used curly braces to define seed path in your Phinx configuration file, ' .
|
||||
'but no directories have been matched using this pattern. ' .
|
||||
'You need to create a seed directory manually.'
|
||||
);
|
||||
}
|
||||
|
||||
// Only one path set, so select that:
|
||||
if (count($paths) === 1) {
|
||||
return array_shift($paths);
|
||||
}
|
||||
|
||||
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
|
||||
$helper = $this->getHelper('question');
|
||||
$question = $this->getSelectSeedPathQuestion($paths);
|
||||
|
||||
return $helper->ask($input, $output, $question);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the new seeder.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \RuntimeException
|
||||
* @throws \InvalidArgumentException
|
||||
* @return int 0 on success
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
// get the seed path from the config
|
||||
$path = $this->getSeedPath($input, $output);
|
||||
|
||||
if (!file_exists($path)) {
|
||||
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
|
||||
$helper = $this->getHelper('question');
|
||||
$question = $this->getCreateSeedDirectoryQuestion();
|
||||
|
||||
if ($helper->ask($input, $output, $question)) {
|
||||
mkdir($path, 0755, true);
|
||||
}
|
||||
}
|
||||
|
||||
$this->verifySeedDirectory($path);
|
||||
|
||||
$path = realpath($path);
|
||||
/** @var string|null $className */
|
||||
$className = $input->getArgument('name');
|
||||
|
||||
if (!Util::isValidPhinxClassName($className)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The seed class name "%s" is invalid. Please use CamelCase format',
|
||||
$className
|
||||
));
|
||||
}
|
||||
|
||||
// Compute the file path
|
||||
$filePath = $path . DIRECTORY_SEPARATOR . $className . '.php';
|
||||
|
||||
if (is_file($filePath)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The file "%s" already exists',
|
||||
basename($filePath)
|
||||
));
|
||||
}
|
||||
|
||||
// Get the alternative template option from the command line.
|
||||
$altTemplate = $input->getOption('template');
|
||||
|
||||
// Verify the alternative template file's existence.
|
||||
if ($altTemplate && !is_file($altTemplate)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The template file "%s" does not exist',
|
||||
$altTemplate
|
||||
));
|
||||
}
|
||||
|
||||
// Command-line option must have higher priority than value from Config
|
||||
$config = $this->getConfig();
|
||||
if (is_null($altTemplate)) {
|
||||
$altTemplate = $config->getSeedTemplateFile();
|
||||
if (!is_null($altTemplate) && !is_file($altTemplate)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The template file `%s` from config does not exist',
|
||||
$altTemplate
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Determine the appropriate mechanism to get the template
|
||||
// Load the alternative template if it is defined.
|
||||
$contents = file_get_contents($altTemplate ?: $this->getSeedTemplateFilename());
|
||||
|
||||
$namespace = $config instanceof NamespaceAwareInterface ? $config->getSeedNamespaceByPath($path) : null;
|
||||
$classes = [
|
||||
'$namespaceDefinition' => $namespace !== null ? ('namespace ' . $namespace . ';') : '',
|
||||
'$namespace' => $namespace,
|
||||
'$useClassName' => $config->getSeedBaseClassName(false),
|
||||
'$className' => $className,
|
||||
'$baseClassName' => $config->getSeedBaseClassName(true),
|
||||
];
|
||||
$contents = strtr($contents, $classes);
|
||||
|
||||
if (file_put_contents($filePath, $contents) === false) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'The file "%s" could not be written to',
|
||||
$path
|
||||
));
|
||||
}
|
||||
|
||||
$output->writeln('<info>using seed base class</info> ' . $classes['$useClassName'], $this->verbosityLevel);
|
||||
$output->writeln('<info>created</info> ' . Util::relativePath($filePath), $this->verbosityLevel);
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'seed:run')]
|
||||
class SeedRun extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'seed:run';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->addOption('--environment', '-e', InputOption::VALUE_REQUIRED, 'The target environment');
|
||||
|
||||
$this->setDescription('Run database seeders')
|
||||
->addOption('--seed', '-s', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'What is the name of the seeder?')
|
||||
->setHelp(
|
||||
<<<EOT
|
||||
The <info>seed:run</info> command runs all available or individual seeders
|
||||
|
||||
<info>phinx seed:run -e development</info>
|
||||
<info>phinx seed:run -e development -s UserSeeder</info>
|
||||
<info>phinx seed:run -e development -s UserSeeder -s PermissionSeeder -s LogSeeder</info>
|
||||
<info>phinx seed:run -e development -v</info>
|
||||
|
||||
EOT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run database seeders.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return int integer 0 on success, or an error code.
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
/** @var array<string>|null $seedSet */
|
||||
$seedSet = $input->getOption('seed');
|
||||
/** @var string|null $environment */
|
||||
$environment = $input->getOption('environment');
|
||||
|
||||
if ($environment === null) {
|
||||
$environment = $this->getConfig()->getDefaultEnvironment();
|
||||
$output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment, $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<info>using environment</info> ' . $environment, $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (!$this->getConfig()->hasEnvironment($environment)) {
|
||||
$output->writeln(sprintf('<error>The environment "%s" does not exist</error>', $environment));
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
$envOptions = $this->getConfig()->getEnvironment($environment);
|
||||
if (isset($envOptions['adapter'])) {
|
||||
$output->writeln('<info>using adapter</info> ' . $envOptions['adapter'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (isset($envOptions['wrapper'])) {
|
||||
$output->writeln('<info>using wrapper</info> ' . $envOptions['wrapper'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (isset($envOptions['name'])) {
|
||||
$output->writeln('<info>using database</info> ' . $envOptions['name'], $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<error>Could not determine database name! Please specify a database name in your config file.</error>');
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
if (isset($envOptions['table_prefix'])) {
|
||||
$output->writeln('<info>using table prefix</info> ' . $envOptions['table_prefix'], $this->verbosityLevel);
|
||||
}
|
||||
if (isset($envOptions['table_suffix'])) {
|
||||
$output->writeln('<info>using table suffix</info> ' . $envOptions['table_suffix'], $this->verbosityLevel);
|
||||
}
|
||||
|
||||
$start = microtime(true);
|
||||
|
||||
if (empty($seedSet)) {
|
||||
// run all the seed(ers)
|
||||
$this->getManager()->seed($environment);
|
||||
} else {
|
||||
// run seed(ers) specified in a comma-separated list of classes
|
||||
foreach ($seedSet as $seed) {
|
||||
$this->getManager()->seed($environment, trim($seed));
|
||||
}
|
||||
}
|
||||
|
||||
$end = microtime(true);
|
||||
|
||||
$output->writeln('', $this->verbosityLevel);
|
||||
$output->writeln('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>', $this->verbosityLevel);
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'status')]
|
||||
class Status extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'status';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->addOption('--environment', '-e', InputOption::VALUE_REQUIRED, 'The target environment.');
|
||||
|
||||
$this->setDescription('Show migration status')
|
||||
->addOption('--format', '-f', InputOption::VALUE_REQUIRED, 'The output format: text or json. Defaults to text.')
|
||||
->setHelp(
|
||||
<<<EOT
|
||||
The <info>status</info> command prints a list of all migrations, along with their current status
|
||||
|
||||
<info>phinx status -e development</info>
|
||||
<info>phinx status -e development -f json</info>
|
||||
|
||||
The <info>version_order</info> configuration option is used to determine the order of the status migrations.
|
||||
EOT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the migration status.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return int 0 if all migrations are up, or an error code
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->bootstrap($input, $output);
|
||||
|
||||
/** @var string|null $environment */
|
||||
$environment = $input->getOption('environment');
|
||||
/** @var string|null $environment */
|
||||
$format = $input->getOption('format');
|
||||
|
||||
if ($environment === null) {
|
||||
$environment = $this->getConfig()->getDefaultEnvironment();
|
||||
$output->writeln('<comment>warning</comment> no environment specified, defaulting to: ' . $environment, $this->verbosityLevel);
|
||||
} else {
|
||||
$output->writeln('<info>using environment</info> ' . $environment, $this->verbosityLevel);
|
||||
}
|
||||
|
||||
if (!$this->getConfig()->hasEnvironment($environment)) {
|
||||
$output->writeln(sprintf('<error>The environment "%s" does not exist</error>', $environment));
|
||||
|
||||
return self::CODE_ERROR;
|
||||
}
|
||||
|
||||
if ($format !== null) {
|
||||
$output->writeln('<info>using format</info> ' . $format, $this->verbosityLevel);
|
||||
}
|
||||
|
||||
$output->writeln('<info>ordering by </info>' . $this->getConfig()->getVersionOrder() . ' time', $this->verbosityLevel);
|
||||
|
||||
// print the status
|
||||
$result = $this->getManager()->printStatus($environment, $format);
|
||||
|
||||
if ($result['hasMissingMigration']) {
|
||||
return self::CODE_STATUS_MISSING;
|
||||
} elseif ($result['hasDownMigration']) {
|
||||
return self::CODE_STATUS_DOWN;
|
||||
}
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console\Command;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Migration\Manager\Environment;
|
||||
use Phinx\Util\Util;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
#[AsCommand(name: 'test')]
|
||||
class Test extends AbstractCommand
|
||||
{
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected static $defaultName = 'test';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
parent::configure();
|
||||
|
||||
$this->addOption('--environment', '-e', InputOption::VALUE_REQUIRED, 'The target environment');
|
||||
|
||||
$this->setDescription('Verify the configuration file')
|
||||
->setHelp(
|
||||
<<<EOT
|
||||
The <info>test</info> command is used to verify the phinx configuration file and optionally an environment
|
||||
|
||||
<info>phinx test</info>
|
||||
<info>phinx test -e development</info>
|
||||
|
||||
If the environment option is set, it will test that phinx can connect to the DB associated with that environment
|
||||
EOT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify configuration file
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @throws \InvalidArgumentException
|
||||
* @return int 0 on success
|
||||
*/
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$this->loadConfig($input, $output);
|
||||
$this->loadManager($input, $output);
|
||||
|
||||
// Verify the migrations path(s)
|
||||
array_map(
|
||||
[$this, 'verifyMigrationDirectory'],
|
||||
Util::globAll($this->getConfig()->getMigrationPaths())
|
||||
);
|
||||
|
||||
// Verify the seed path(s)
|
||||
array_map(
|
||||
[$this, 'verifySeedDirectory'],
|
||||
Util::globAll($this->getConfig()->getSeedPaths())
|
||||
);
|
||||
|
||||
$envName = $input->getOption('environment');
|
||||
if ($envName) {
|
||||
if (!$this->getConfig()->hasEnvironment($envName)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'The environment "%s" does not exist',
|
||||
$envName
|
||||
));
|
||||
}
|
||||
|
||||
$output->writeln(sprintf('<info>validating environment</info> %s', $envName), $this->verbosityLevel);
|
||||
$environment = new Environment(
|
||||
$envName,
|
||||
$this->getConfig()->getEnvironment($envName)
|
||||
);
|
||||
// validate environment connection
|
||||
$environment->getAdapter()->connect();
|
||||
}
|
||||
|
||||
$output->writeln('<info>success!</info>', $this->verbosityLevel);
|
||||
|
||||
return self::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Console;
|
||||
|
||||
use Phinx\Console\Command\Breakpoint;
|
||||
use Phinx\Console\Command\Create;
|
||||
use Phinx\Console\Command\Init;
|
||||
use Phinx\Console\Command\ListAliases;
|
||||
use Phinx\Console\Command\Migrate;
|
||||
use Phinx\Console\Command\Rollback;
|
||||
use Phinx\Console\Command\SeedCreate;
|
||||
use Phinx\Console\Command\SeedRun;
|
||||
use Phinx\Console\Command\Status;
|
||||
use Phinx\Console\Command\Test;
|
||||
use Symfony\Component\Console\Application;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Phinx console application.
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
class PhinxApplication extends Application
|
||||
{
|
||||
/**
|
||||
* Initialize the Phinx console application.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Phinx by CakePHP - https://phinx.org.');
|
||||
|
||||
$this->addCommands([
|
||||
new Init(),
|
||||
new Create(),
|
||||
new Migrate(),
|
||||
new Rollback(),
|
||||
new Status(),
|
||||
new Breakpoint(),
|
||||
new Test(),
|
||||
new SeedCreate(),
|
||||
new SeedRun(),
|
||||
new ListAliases(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the current application.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input An Input instance
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output An Output instance
|
||||
* @return int 0 if everything went fine, or an error code
|
||||
*/
|
||||
public function doRun(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
// always show the version information except when the user invokes the help
|
||||
// command as that already does it
|
||||
if ($input->hasParameterOption('--no-info') === false) {
|
||||
if (($input->hasParameterOption(['--help', '-h']) !== false) || ($input->getFirstArgument() !== null && $input->getFirstArgument() !== 'list')) {
|
||||
$output->writeln($this->getLongVersion());
|
||||
$output->writeln('');
|
||||
}
|
||||
}
|
||||
|
||||
return parent::doRun($input, $output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
abstract class Action
|
||||
{
|
||||
/**
|
||||
* @var \Phinx\Db\Table\Table
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table the Table to apply the action to
|
||||
*/
|
||||
public function __construct(Table $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* The table this action will be applied to
|
||||
*
|
||||
* @return \Phinx\Db\Table\Table
|
||||
*/
|
||||
public function getTable(): Table
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class AddColumn extends Action
|
||||
{
|
||||
/**
|
||||
* The column to add
|
||||
*
|
||||
* @var \Phinx\Db\Table\Column
|
||||
*/
|
||||
protected $column;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to add the column to
|
||||
* @param \Phinx\Db\Table\Column $column The column to add
|
||||
*/
|
||||
public function __construct(Table $table, Column $column)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->column = $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new AddColumn object after assembling the given commands
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to add the column to
|
||||
* @param string $columnName The column name
|
||||
* @param string|\Phinx\Util\Literal $type The column type
|
||||
* @param array<string, mixed> $options The column options
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, string $columnName, $type = null, array $options = [])
|
||||
{
|
||||
$column = new Column();
|
||||
$column->setName($columnName);
|
||||
$column->setType($type);
|
||||
$column->setOptions($options); // map options to column methods
|
||||
|
||||
return new static($table, $column);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the column to be added
|
||||
*
|
||||
* @return \Phinx\Db\Table\Column
|
||||
*/
|
||||
public function getColumn(): Column
|
||||
{
|
||||
return $this->column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\ForeignKey;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class AddForeignKey extends Action
|
||||
{
|
||||
/**
|
||||
* The foreign key to add
|
||||
*
|
||||
* @var \Phinx\Db\Table\ForeignKey
|
||||
*/
|
||||
protected $foreignKey;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to add the foreign key to
|
||||
* @param \Phinx\Db\Table\ForeignKey $fk The foreign key to add
|
||||
*/
|
||||
public function __construct(Table $table, ForeignKey $fk)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->foreignKey = $fk;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AddForeignKey object after building the foreign key with
|
||||
* the passed attributes
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table object to add the foreign key to
|
||||
* @param string|string[] $columns The columns for the foreign key
|
||||
* @param \Phinx\Db\Table\Table|string $referencedTable The table the foreign key references
|
||||
* @param string|string[] $referencedColumns The columns in the referenced table
|
||||
* @param array<string, mixed> $options Extra options for the foreign key
|
||||
* @param string|null $name The name of the foreign key
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, $columns, $referencedTable, $referencedColumns = ['id'], array $options = [], ?string $name = null)
|
||||
{
|
||||
if (is_string($referencedColumns)) {
|
||||
$referencedColumns = [$referencedColumns]; // str to array
|
||||
}
|
||||
|
||||
if (is_string($referencedTable)) {
|
||||
$referencedTable = new Table($referencedTable);
|
||||
}
|
||||
|
||||
$fk = new ForeignKey();
|
||||
$fk->setReferencedTable($referencedTable)
|
||||
->setColumns($columns)
|
||||
->setReferencedColumns($referencedColumns)
|
||||
->setOptions($options);
|
||||
|
||||
if ($name !== null) {
|
||||
$fk->setConstraint($name);
|
||||
}
|
||||
|
||||
return new static($table, $fk);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the foreign key to be added
|
||||
*
|
||||
* @return \Phinx\Db\Table\ForeignKey
|
||||
*/
|
||||
public function getForeignKey(): ForeignKey
|
||||
{
|
||||
return $this->foreignKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Index;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class AddIndex extends Action
|
||||
{
|
||||
/**
|
||||
* The index to add to the table
|
||||
*
|
||||
* @var \Phinx\Db\Table\Index
|
||||
*/
|
||||
protected $index;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to add the index to
|
||||
* @param \Phinx\Db\Table\Index $index The index to be added
|
||||
*/
|
||||
public function __construct(Table $table, Index $index)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->index = $index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AddIndex object after building the index object with the
|
||||
* provided arguments
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to add the index to
|
||||
* @param string|string[]|\Phinx\Db\Table\Index $columns The columns to index
|
||||
* @param array<string, mixed> $options Additional options for the index creation
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, $columns, array $options = [])
|
||||
{
|
||||
// create a new index object if strings or an array of strings were supplied
|
||||
$index = $columns;
|
||||
|
||||
if (!$columns instanceof Index) {
|
||||
$index = new Index();
|
||||
|
||||
$index->setColumns($columns);
|
||||
$index->setOptions($options);
|
||||
}
|
||||
|
||||
return new static($table, $index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index to be added
|
||||
*
|
||||
* @return \Phinx\Db\Table\Index
|
||||
*/
|
||||
public function getIndex(): Index
|
||||
{
|
||||
return $this->index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class ChangeColumn extends Action
|
||||
{
|
||||
/**
|
||||
* The column definition
|
||||
*
|
||||
* @var \Phinx\Db\Table\Column
|
||||
*/
|
||||
protected $column;
|
||||
|
||||
/**
|
||||
* The name of the column to be changed
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $columnName;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to alter
|
||||
* @param string $columnName The name of the column to change
|
||||
* @param \Phinx\Db\Table\Column $column The column definition
|
||||
*/
|
||||
public function __construct(Table $table, string $columnName, Column $column)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->columnName = $columnName;
|
||||
$this->column = $column;
|
||||
|
||||
// if the name was omitted use the existing column name
|
||||
if ($column->getName() === null || strlen($column->getName()) === 0) {
|
||||
$column->setName($columnName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ChangeColumn object after building the column definition
|
||||
* out of the provided arguments
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to alter
|
||||
* @param string $columnName The name of the column to change
|
||||
* @param string|\Phinx\Db\Table\Column|\Phinx\Util\Literal $type The type of the column
|
||||
* @param array<string, mixed> $options Additional options for the column
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, string $columnName, $type = null, array $options = [])
|
||||
{
|
||||
$column = new Column();
|
||||
$column->setName($columnName);
|
||||
$column->setType($type);
|
||||
$column->setOptions($options); // map options to column methods
|
||||
|
||||
return new static($table, $columnName, $column);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the column to change
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getColumnName(): string
|
||||
{
|
||||
return $this->columnName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the column definition
|
||||
*
|
||||
* @return \Phinx\Db\Table\Column
|
||||
*/
|
||||
public function getColumn(): Column
|
||||
{
|
||||
return $this->column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class ChangeComment extends Action
|
||||
{
|
||||
/**
|
||||
* The new comment for the table
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $newComment;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to be changed
|
||||
* @param string|null $newComment The new comment for the table
|
||||
*/
|
||||
public function __construct(Table $table, ?string $newComment)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->newComment = $newComment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the new comment for the table
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getNewComment(): ?string
|
||||
{
|
||||
return $this->newComment;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class ChangePrimaryKey extends Action
|
||||
{
|
||||
/**
|
||||
* The new columns for the primary key
|
||||
*
|
||||
* @var string|string[]|null
|
||||
*/
|
||||
protected $newColumns;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to be changed
|
||||
* @param string|string[]|null $newColumns The new columns for the primary key
|
||||
*/
|
||||
public function __construct(Table $table, $newColumns)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->newColumns = $newColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the new columns for the primary key
|
||||
*
|
||||
* @return string|string[]|null
|
||||
*/
|
||||
public function getNewColumns()
|
||||
{
|
||||
return $this->newColumns;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
class CreateTable extends Action
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\ForeignKey;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class DropForeignKey extends Action
|
||||
{
|
||||
/**
|
||||
* The foreign key to remove
|
||||
*
|
||||
* @var \Phinx\Db\Table\ForeignKey
|
||||
*/
|
||||
protected $foreignKey;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to remove the constraint from
|
||||
* @param \Phinx\Db\Table\ForeignKey $foreignKey The foreign key to remove
|
||||
*/
|
||||
public function __construct(Table $table, ForeignKey $foreignKey)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->foreignKey = $foreignKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new DropForeignKey object after building the ForeignKey
|
||||
* definition out of the passed arguments.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to delete the foreign key from
|
||||
* @param string|string[] $columns The columns participating in the foreign key
|
||||
* @param string|null $constraint The constraint name
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, $columns, ?string $constraint = null)
|
||||
{
|
||||
if (is_string($columns)) {
|
||||
$columns = [$columns];
|
||||
}
|
||||
|
||||
$foreignKey = new ForeignKey();
|
||||
$foreignKey->setColumns($columns);
|
||||
|
||||
if ($constraint) {
|
||||
$foreignKey->setConstraint($constraint);
|
||||
}
|
||||
|
||||
return new static($table, $foreignKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the foreign key to remove
|
||||
*
|
||||
* @return \Phinx\Db\Table\ForeignKey
|
||||
*/
|
||||
public function getForeignKey(): ForeignKey
|
||||
{
|
||||
return $this->foreignKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Index;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class DropIndex extends Action
|
||||
{
|
||||
/**
|
||||
* The index to drop
|
||||
*
|
||||
* @var \Phinx\Db\Table\Index
|
||||
*/
|
||||
protected $index;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table owning the index
|
||||
* @param \Phinx\Db\Table\Index $index The index to be dropped
|
||||
*/
|
||||
public function __construct(Table $table, Index $index)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->index = $index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new DropIndex object after assembling the passed
|
||||
* arguments.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table where the index is
|
||||
* @param string[] $columns the indexed columns
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, array $columns = [])
|
||||
{
|
||||
$index = new Index();
|
||||
$index->setColumns($columns);
|
||||
|
||||
return new static($table, $index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new DropIndex when the name of the index to drop
|
||||
* is known.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table where the index is
|
||||
* @param string $name The name of the index
|
||||
* @return static
|
||||
*/
|
||||
public static function buildFromName(Table $table, string $name)
|
||||
{
|
||||
$index = new Index();
|
||||
$index->setName($name);
|
||||
|
||||
return new static($table, $index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index to be dropped
|
||||
*
|
||||
* @return \Phinx\Db\Table\Index
|
||||
*/
|
||||
public function getIndex(): Index
|
||||
{
|
||||
return $this->index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
class DropTable extends Action
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class RemoveColumn extends Action
|
||||
{
|
||||
/**
|
||||
* The column to be removed
|
||||
*
|
||||
* @var \Phinx\Db\Table\Column
|
||||
*/
|
||||
protected $column;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table where the column is
|
||||
* @param \Phinx\Db\Table\Column $column The column to be removed
|
||||
*/
|
||||
public function __construct(Table $table, Column $column)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->column = $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new RemoveColumn object after assembling the
|
||||
* passed arguments.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table where the column is
|
||||
* @param string $columnName The name of the column to drop
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, string $columnName)
|
||||
{
|
||||
$column = new Column();
|
||||
$column->setName($columnName);
|
||||
|
||||
return new static($table, $column);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the column to be dropped
|
||||
*
|
||||
* @return \Phinx\Db\Table\Column
|
||||
*/
|
||||
public function getColumn(): Column
|
||||
{
|
||||
return $this->column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class RenameColumn extends Action
|
||||
{
|
||||
/**
|
||||
* The column to be renamed
|
||||
*
|
||||
* @var \Phinx\Db\Table\Column
|
||||
*/
|
||||
protected $column;
|
||||
|
||||
/**
|
||||
* The new name for the column
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $newName;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table where the column is
|
||||
* @param \Phinx\Db\Table\Column $column The column to be renamed
|
||||
* @param string $newName The new name for the column
|
||||
*/
|
||||
public function __construct(Table $table, Column $column, string $newName)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->newName = $newName;
|
||||
$this->column = $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new RenameColumn object after building the passed
|
||||
* arguments
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table where the column is
|
||||
* @param string $columnName The name of the column to be changed
|
||||
* @param string $newName The new name for the column
|
||||
* @return static
|
||||
*/
|
||||
public static function build(Table $table, string $columnName, string $newName)
|
||||
{
|
||||
$column = new Column();
|
||||
$column->setName($columnName);
|
||||
|
||||
return new static($table, $column, $newName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the column to be changed
|
||||
*
|
||||
* @return \Phinx\Db\Table\Column
|
||||
*/
|
||||
public function getColumn(): Column
|
||||
{
|
||||
return $this->column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the new name for the column
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getNewName(): string
|
||||
{
|
||||
return $this->newName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Action;
|
||||
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
class RenameTable extends Action
|
||||
{
|
||||
/**
|
||||
* The new name for the table
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $newName;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to be renamed
|
||||
* @param string $newName The new name for the table
|
||||
*/
|
||||
public function __construct(Table $table, string $newName)
|
||||
{
|
||||
parent::__construct($table);
|
||||
$this->newName = $newName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the new name for the table
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getNewName(): string
|
||||
{
|
||||
return $this->newName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Db\Table;
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Util\Literal;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\NullOutput;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Base Abstract Database Adapter.
|
||||
*/
|
||||
abstract class AbstractAdapter implements AdapterInterface
|
||||
{
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected $options = [];
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Input\InputInterface|null
|
||||
*/
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Output\OutputInterface
|
||||
*/
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
protected $createdTables = [];
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $schemaTableName = 'phinxlog';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $dataDomain = [];
|
||||
|
||||
/**
|
||||
* Class Constructor.
|
||||
*
|
||||
* @param array<string, mixed> $options Options
|
||||
* @param \Symfony\Component\Console\Input\InputInterface|null $input Input Interface
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface|null $output Output Interface
|
||||
*/
|
||||
public function __construct(array $options, ?InputInterface $input = null, ?OutputInterface $output = null)
|
||||
{
|
||||
$this->setOptions($options);
|
||||
if ($input !== null) {
|
||||
$this->setInput($input);
|
||||
}
|
||||
if ($output !== null) {
|
||||
$this->setOutput($output);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOptions(array $options): AdapterInterface
|
||||
{
|
||||
$this->options = $options;
|
||||
|
||||
if (isset($options['default_migration_table'])) {
|
||||
trigger_error('The default_migration_table setting for adapter has been deprecated since 0.13.0. Use `migration_table` instead.', E_USER_DEPRECATED);
|
||||
if (!isset($options['migration_table'])) {
|
||||
$options['migration_table'] = $options['default_migration_table'];
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($options['migration_table'])) {
|
||||
$this->setSchemaTableName($options['migration_table']);
|
||||
}
|
||||
|
||||
if (isset($options['data_domain'])) {
|
||||
$this->setDataDomain($options['data_domain']);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasOption(string $name): bool
|
||||
{
|
||||
return isset($this->options[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOption(string $name)
|
||||
{
|
||||
if (!$this->hasOption($name)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->options[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setInput(InputInterface $input): AdapterInterface
|
||||
{
|
||||
$this->input = $input;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getInput(): ?InputInterface
|
||||
{
|
||||
return $this->input;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOutput(OutputInterface $output): AdapterInterface
|
||||
{
|
||||
$this->output = $output;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOutput(): OutputInterface
|
||||
{
|
||||
if ($this->output === null) {
|
||||
$output = new NullOutput();
|
||||
$this->setOutput($output);
|
||||
}
|
||||
|
||||
return $this->output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @return array<int>
|
||||
*/
|
||||
public function getVersions(): array
|
||||
{
|
||||
$rows = $this->getVersionLog();
|
||||
|
||||
return array_keys($rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the schema table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSchemaTableName(): string
|
||||
{
|
||||
return $this->schemaTableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the schema table name.
|
||||
*
|
||||
* @param string $schemaTableName Schema Table Name
|
||||
* @return $this
|
||||
*/
|
||||
public function setSchemaTableName(string $schemaTableName)
|
||||
{
|
||||
$this->schemaTableName = $schemaTableName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the data domain.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDataDomain(): array
|
||||
{
|
||||
return $this->dataDomain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the data domain.
|
||||
*
|
||||
* @param array $dataDomain Array for the data domain
|
||||
* @return $this
|
||||
*/
|
||||
public function setDataDomain(array $dataDomain)
|
||||
{
|
||||
$this->dataDomain = [];
|
||||
|
||||
// Iterate over data domain field definitions and perform initial and
|
||||
// simple normalization. We make sure the definition as a base 'type'
|
||||
// and it is compatible with the base Phinx types.
|
||||
foreach ($dataDomain as $type => $options) {
|
||||
if (!isset($options['type'])) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'You must specify a type for data domain type "%s".',
|
||||
$type
|
||||
));
|
||||
}
|
||||
|
||||
// Replace type if it's the name of a Phinx constant
|
||||
if (defined('static::' . $options['type'])) {
|
||||
$options['type'] = constant('static::' . $options['type']);
|
||||
}
|
||||
|
||||
if (!in_array($options['type'], $this->getColumnTypes(), true)) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'An invalid column type "%s" was specified for data domain type "%s".',
|
||||
$options['type'],
|
||||
$type
|
||||
));
|
||||
}
|
||||
|
||||
$internal_type = $options['type'];
|
||||
unset($options['type']);
|
||||
|
||||
// Do a simple replacement for the 'length' / 'limit' option and
|
||||
// detect hinting values for 'limit'.
|
||||
if (isset($options['length'])) {
|
||||
$options['limit'] = $options['length'];
|
||||
unset($options['length']);
|
||||
}
|
||||
|
||||
if (isset($options['limit']) && !is_numeric($options['limit'])) {
|
||||
if (!defined('static::' . $options['limit'])) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'An invalid limit value "%s" was specified for data domain type "%s".',
|
||||
$options['limit'],
|
||||
$type
|
||||
));
|
||||
}
|
||||
|
||||
$options['limit'] = constant('static::' . $options['limit']);
|
||||
}
|
||||
|
||||
// Save the data domain types in a more suitable format
|
||||
$this->dataDomain[$type] = [
|
||||
'type' => $internal_type,
|
||||
'options' => $options,
|
||||
];
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function getColumnForType(string $columnName, string $type, array $options): Column
|
||||
{
|
||||
$column = new Column();
|
||||
$column->setName($columnName);
|
||||
|
||||
if (array_key_exists($type, $this->getDataDomain())) {
|
||||
$column->setType($this->dataDomain[$type]['type']);
|
||||
$column->setOptions($this->dataDomain[$type]['options']);
|
||||
} else {
|
||||
$column->setType($type);
|
||||
}
|
||||
|
||||
$column->setOptions($options);
|
||||
|
||||
return $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
public function createSchemaTable(): void
|
||||
{
|
||||
try {
|
||||
$options = [
|
||||
'id' => false,
|
||||
'primary_key' => 'version',
|
||||
];
|
||||
|
||||
$table = new Table($this->getSchemaTableName(), $options, $this);
|
||||
$table->addColumn('version', 'biginteger', ['null' => false])
|
||||
->addColumn('migration_name', 'string', ['limit' => 100, 'default' => null, 'null' => true])
|
||||
->addColumn('start_time', 'timestamp', ['default' => null, 'null' => true])
|
||||
->addColumn('end_time', 'timestamp', ['default' => null, 'null' => true])
|
||||
->addColumn('breakpoint', 'boolean', ['default' => false, 'null' => false])
|
||||
->save();
|
||||
} catch (Exception $exception) {
|
||||
throw new InvalidArgumentException(
|
||||
'There was a problem creating the schema table: ' . $exception->getMessage(),
|
||||
(int)$exception->getCode(),
|
||||
$exception
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapterType(): string
|
||||
{
|
||||
return $this->getOption('adapter');
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function isValidColumnType(Column $column): bool
|
||||
{
|
||||
return $column->getType() instanceof Literal || in_array($column->getType(), $this->getColumnTypes(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if instead of executing queries a dump to standard output is needed
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isDryRunEnabled(): bool
|
||||
{
|
||||
/** @var \Symfony\Component\Console\Input\InputInterface|null $input */
|
||||
$input = $this->getInput();
|
||||
|
||||
return $input && $input->hasOption('dry-run') ? (bool)$input->getOption('dry-run') : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds user-created tables (e.g. not phinxlog) to a cached list
|
||||
*
|
||||
* @param string $tableName The name of the table
|
||||
* @return void
|
||||
*/
|
||||
protected function addCreatedTable(string $tableName): void
|
||||
{
|
||||
$tableName = $this->quoteTableName($tableName);
|
||||
if (substr_compare($tableName, 'phinxlog', -strlen('phinxlog')) !== 0) {
|
||||
$this->createdTables[] = $tableName;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the name of the cached table
|
||||
*
|
||||
* @param string $tableName Original name of the table
|
||||
* @param string $newTableName New name of the table
|
||||
* @return void
|
||||
*/
|
||||
protected function updateCreatedTableName(string $tableName, string $newTableName): void
|
||||
{
|
||||
$tableName = $this->quoteTableName($tableName);
|
||||
$newTableName = $this->quoteTableName($newTableName);
|
||||
$key = array_search($tableName, $this->createdTables, true);
|
||||
if ($key !== false) {
|
||||
$this->createdTables[$key] = $newTableName;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes table from the cached created list
|
||||
*
|
||||
* @param string $tableName The name of the table
|
||||
* @return void
|
||||
*/
|
||||
protected function removeCreatedTable(string $tableName): void
|
||||
{
|
||||
$tableName = $this->quoteTableName($tableName);
|
||||
$key = array_search($tableName, $this->createdTables, true);
|
||||
if ($key !== false) {
|
||||
unset($this->createdTables[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the table is in the cached list of created tables
|
||||
*
|
||||
* @param string $tableName The name of the table
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasCreatedTable(string $tableName): bool
|
||||
{
|
||||
$tableName = $this->quoteTableName($tableName);
|
||||
|
||||
return in_array($tableName, $this->createdTables, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Adapter factory and registry.
|
||||
*
|
||||
* Used for registering adapters and creating instances of adapters.
|
||||
*
|
||||
* @author Woody Gilk <woody.gilk@gmail.com>
|
||||
*/
|
||||
class AdapterFactory
|
||||
{
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterFactory|null
|
||||
*/
|
||||
protected static $instance;
|
||||
|
||||
/**
|
||||
* Get the factory singleton instance.
|
||||
*
|
||||
* @return \Phinx\Db\Adapter\AdapterFactory
|
||||
*/
|
||||
public static function instance()
|
||||
{
|
||||
if (!static::$instance) {
|
||||
static::$instance = new static();
|
||||
}
|
||||
|
||||
return static::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class map of database adapters, indexed by PDO::ATTR_DRIVER_NAME.
|
||||
*
|
||||
* @var array<string, \Phinx\Db\Adapter\AdapterInterface|string>
|
||||
* @phpstan-var array<string, \Phinx\Db\Adapter\AdapterInterface|class-string<\Phinx\Db\Adapter\AdapterInterface>>
|
||||
*/
|
||||
protected $adapters = [
|
||||
'mysql' => 'Phinx\Db\Adapter\MysqlAdapter',
|
||||
'pgsql' => 'Phinx\Db\Adapter\PostgresAdapter',
|
||||
'sqlite' => 'Phinx\Db\Adapter\SQLiteAdapter',
|
||||
'sqlsrv' => 'Phinx\Db\Adapter\SqlServerAdapter',
|
||||
];
|
||||
|
||||
/**
|
||||
* Class map of adapters wrappers, indexed by name.
|
||||
*
|
||||
* @var array<string, \Phinx\Db\Adapter\WrapperInterface|string>
|
||||
*/
|
||||
protected $wrappers = [
|
||||
'prefix' => 'Phinx\Db\Adapter\TablePrefixAdapter',
|
||||
'proxy' => 'Phinx\Db\Adapter\ProxyAdapter',
|
||||
'timed' => 'Phinx\Db\Adapter\TimedOutputAdapter',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register an adapter class with a given name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @param object|string $class Class
|
||||
* @throws \RuntimeException
|
||||
* @return $this
|
||||
*/
|
||||
public function registerAdapter(string $name, $class)
|
||||
{
|
||||
if (!is_subclass_of($class, 'Phinx\Db\Adapter\AdapterInterface')) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Adapter class "%s" must implement Phinx\\Db\\Adapter\\AdapterInterface',
|
||||
is_string($class) ? $class : get_class($class)
|
||||
));
|
||||
}
|
||||
$this->adapters[$name] = $class;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an adapter class by name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @throws \RuntimeException
|
||||
* @return object|string
|
||||
* @phpstan-return object|class-string<\Phinx\Db\Adapter\AdapterInterface>
|
||||
*/
|
||||
protected function getClass(string $name)
|
||||
{
|
||||
if (empty($this->adapters[$name])) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Adapter "%s" has not been registered',
|
||||
$name
|
||||
));
|
||||
}
|
||||
|
||||
return $this->adapters[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an adapter instance by name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function getAdapter(string $name, array $options): AdapterInterface
|
||||
{
|
||||
$class = $this->getClass($name);
|
||||
|
||||
return new $class($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add or replace a wrapper with a fully qualified class name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @param object|string $class Class
|
||||
* @throws \RuntimeException
|
||||
* @return $this
|
||||
*/
|
||||
public function registerWrapper(string $name, $class)
|
||||
{
|
||||
if (!is_subclass_of($class, 'Phinx\Db\Adapter\WrapperInterface')) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Wrapper class "%s" must be implement Phinx\\Db\\Adapter\\WrapperInterface',
|
||||
is_string($class) ? $class : get_class($class)
|
||||
));
|
||||
}
|
||||
$this->wrappers[$name] = $class;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a wrapper class by name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @throws \RuntimeException
|
||||
* @return \Phinx\Db\Adapter\WrapperInterface|string
|
||||
*/
|
||||
protected function getWrapperClass(string $name)
|
||||
{
|
||||
if (empty($this->wrappers[$name])) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Wrapper "%s" has not been registered',
|
||||
$name
|
||||
));
|
||||
}
|
||||
|
||||
return $this->wrappers[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a wrapper instance by name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Adapter
|
||||
* @return \Phinx\Db\Adapter\AdapterWrapper
|
||||
*/
|
||||
public function getWrapper(string $name, AdapterInterface $adapter): AdapterWrapper
|
||||
{
|
||||
$class = $this->getWrapperClass($name);
|
||||
|
||||
return new $class($adapter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use Cake\Database\Query;
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table;
|
||||
use Phinx\Migration\MigrationInterface;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Adapter Interface.
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
* @method \PDO getConnection()
|
||||
*/
|
||||
interface AdapterInterface
|
||||
{
|
||||
public const PHINX_TYPE_STRING = 'string';
|
||||
public const PHINX_TYPE_CHAR = 'char';
|
||||
public const PHINX_TYPE_TEXT = 'text';
|
||||
public const PHINX_TYPE_INTEGER = 'integer';
|
||||
public const PHINX_TYPE_TINY_INTEGER = 'tinyinteger';
|
||||
public const PHINX_TYPE_SMALL_INTEGER = 'smallinteger';
|
||||
public const PHINX_TYPE_BIG_INTEGER = 'biginteger';
|
||||
public const PHINX_TYPE_BIT = 'bit';
|
||||
public const PHINX_TYPE_FLOAT = 'float';
|
||||
public const PHINX_TYPE_DECIMAL = 'decimal';
|
||||
public const PHINX_TYPE_DOUBLE = 'double';
|
||||
public const PHINX_TYPE_DATETIME = 'datetime';
|
||||
public const PHINX_TYPE_TIMESTAMP = 'timestamp';
|
||||
public const PHINX_TYPE_TIME = 'time';
|
||||
public const PHINX_TYPE_DATE = 'date';
|
||||
public const PHINX_TYPE_BINARY = 'binary';
|
||||
public const PHINX_TYPE_VARBINARY = 'varbinary';
|
||||
public const PHINX_TYPE_BINARYUUID = 'binaryuuid';
|
||||
public const PHINX_TYPE_BLOB = 'blob';
|
||||
public const PHINX_TYPE_TINYBLOB = 'tinyblob'; // Specific to Mysql.
|
||||
public const PHINX_TYPE_MEDIUMBLOB = 'mediumblob'; // Specific to Mysql
|
||||
public const PHINX_TYPE_LONGBLOB = 'longblob'; // Specific to Mysql
|
||||
public const PHINX_TYPE_BOOLEAN = 'boolean';
|
||||
public const PHINX_TYPE_JSON = 'json';
|
||||
public const PHINX_TYPE_JSONB = 'jsonb';
|
||||
public const PHINX_TYPE_UUID = 'uuid';
|
||||
public const PHINX_TYPE_FILESTREAM = 'filestream';
|
||||
|
||||
// Geospatial database types
|
||||
public const PHINX_TYPE_GEOMETRY = 'geometry';
|
||||
public const PHINX_TYPE_GEOGRAPHY = 'geography';
|
||||
public const PHINX_TYPE_POINT = 'point';
|
||||
public const PHINX_TYPE_LINESTRING = 'linestring';
|
||||
public const PHINX_TYPE_POLYGON = 'polygon';
|
||||
|
||||
public const PHINX_TYPES_GEOSPATIAL = [
|
||||
self::PHINX_TYPE_GEOMETRY,
|
||||
self::PHINX_TYPE_POINT,
|
||||
self::PHINX_TYPE_LINESTRING,
|
||||
self::PHINX_TYPE_POLYGON,
|
||||
];
|
||||
|
||||
// only for mysql so far
|
||||
public const PHINX_TYPE_MEDIUM_INTEGER = 'mediuminteger';
|
||||
public const PHINX_TYPE_ENUM = 'enum';
|
||||
public const PHINX_TYPE_SET = 'set';
|
||||
public const PHINX_TYPE_YEAR = 'year';
|
||||
|
||||
// only for postgresql so far
|
||||
public const PHINX_TYPE_CIDR = 'cidr';
|
||||
public const PHINX_TYPE_INET = 'inet';
|
||||
public const PHINX_TYPE_MACADDR = 'macaddr';
|
||||
public const PHINX_TYPE_INTERVAL = 'interval';
|
||||
|
||||
/**
|
||||
* Get all migrated version numbers.
|
||||
*
|
||||
* @return array<int>
|
||||
*/
|
||||
public function getVersions(): array;
|
||||
|
||||
/**
|
||||
* Get all migration log entries, indexed by version creation time and sorted ascendingly by the configuration's
|
||||
* version order option
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
public function getVersionLog(): array;
|
||||
|
||||
/**
|
||||
* Set adapter configuration options.
|
||||
*
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return $this
|
||||
*/
|
||||
public function setOptions(array $options);
|
||||
|
||||
/**
|
||||
* Get all adapter options.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getOptions(): array;
|
||||
|
||||
/**
|
||||
* Check if an option has been set.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasOption(string $name): bool;
|
||||
|
||||
/**
|
||||
* Get a single adapter option, or null if the option does not exist.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @return mixed
|
||||
*/
|
||||
public function getOption(string $name);
|
||||
|
||||
/**
|
||||
* Sets the console input.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @return $this
|
||||
*/
|
||||
public function setInput(InputInterface $input);
|
||||
|
||||
/**
|
||||
* Gets the console input.
|
||||
*
|
||||
* @return \Symfony\Component\Console\Input\InputInterface|null
|
||||
*/
|
||||
public function getInput(): ?InputInterface;
|
||||
|
||||
/**
|
||||
* Sets the console output.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return $this
|
||||
*/
|
||||
public function setOutput(OutputInterface $output);
|
||||
|
||||
/**
|
||||
* Gets the console output.
|
||||
*
|
||||
* @return \Symfony\Component\Console\Output\OutputInterface
|
||||
*/
|
||||
public function getOutput(): OutputInterface;
|
||||
|
||||
/**
|
||||
* Returns a new Phinx\Db\Table\Column using the existent data domain.
|
||||
*
|
||||
* @param string $columnName The desired column name
|
||||
* @param string $type The type for the column. Can be a data domain type.
|
||||
* @param array<string, mixed> $options Options array
|
||||
* @return \Phinx\Db\Table\Column
|
||||
*/
|
||||
public function getColumnForType(string $columnName, string $type, array $options): Column;
|
||||
|
||||
/**
|
||||
* Records a migration being run.
|
||||
*
|
||||
* @param \Phinx\Migration\MigrationInterface $migration Migration
|
||||
* @param string $direction Direction
|
||||
* @param string $startTime Start Time
|
||||
* @param string $endTime End Time
|
||||
* @return $this
|
||||
*/
|
||||
public function migrated(MigrationInterface $migration, string $direction, string $startTime, string $endTime);
|
||||
|
||||
/**
|
||||
* Toggle a migration breakpoint.
|
||||
*
|
||||
* @param \Phinx\Migration\MigrationInterface $migration Migration
|
||||
* @return $this
|
||||
*/
|
||||
public function toggleBreakpoint(MigrationInterface $migration);
|
||||
|
||||
/**
|
||||
* Reset all migration breakpoints.
|
||||
*
|
||||
* @return int The number of breakpoints reset
|
||||
*/
|
||||
public function resetAllBreakpoints(): int;
|
||||
|
||||
/**
|
||||
* Set a migration breakpoint.
|
||||
*
|
||||
* @param \Phinx\Migration\MigrationInterface $migration The migration target for the breakpoint set
|
||||
* @return $this
|
||||
*/
|
||||
public function setBreakpoint(MigrationInterface $migration);
|
||||
|
||||
/**
|
||||
* Unset a migration breakpoint.
|
||||
*
|
||||
* @param \Phinx\Migration\MigrationInterface $migration The migration target for the breakpoint unset
|
||||
* @return $this
|
||||
*/
|
||||
public function unsetBreakpoint(MigrationInterface $migration);
|
||||
|
||||
/**
|
||||
* Creates the schema table.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function createSchemaTable(): void;
|
||||
|
||||
/**
|
||||
* Returns the adapter type.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAdapterType(): string;
|
||||
|
||||
/**
|
||||
* Initializes the database connection.
|
||||
*
|
||||
* @throws \RuntimeException When the requested database driver is not installed.
|
||||
* @return void
|
||||
*/
|
||||
public function connect(): void;
|
||||
|
||||
/**
|
||||
* Closes the database connection.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function disconnect(): void;
|
||||
|
||||
/**
|
||||
* Does the adapter support transactions?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasTransactions(): bool;
|
||||
|
||||
/**
|
||||
* Begin a transaction.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function beginTransaction(): void;
|
||||
|
||||
/**
|
||||
* Commit a transaction.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function commitTransaction(): void;
|
||||
|
||||
/**
|
||||
* Rollback a transaction.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function rollbackTransaction(): void;
|
||||
|
||||
/**
|
||||
* Executes a SQL statement and returns the number of affected rows.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @param array $params parameters to use for prepared query
|
||||
* @return int
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int;
|
||||
|
||||
/**
|
||||
* Executes a list of migration actions for the given table
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to execute the actions for
|
||||
* @param \Phinx\Db\Action\Action[] $actions The table to execute the actions for
|
||||
* @return void
|
||||
*/
|
||||
public function executeActions(Table $table, array $actions): void;
|
||||
|
||||
/**
|
||||
* Returns a new Query object
|
||||
*
|
||||
* @return \Cake\Database\Query
|
||||
*/
|
||||
public function getQueryBuilder(): Query;
|
||||
|
||||
/**
|
||||
* Executes a SQL statement.
|
||||
*
|
||||
* The return type depends on the underlying adapter being used.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @param array $params parameters to use for prepared query
|
||||
* @return mixed
|
||||
*/
|
||||
public function query(string $sql, array $params = []);
|
||||
|
||||
/**
|
||||
* Executes a query and returns only one row as an array.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @return array|false
|
||||
*/
|
||||
public function fetchRow(string $sql);
|
||||
|
||||
/**
|
||||
* Executes a query and returns an array of rows.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @return array
|
||||
*/
|
||||
public function fetchAll(string $sql): array;
|
||||
|
||||
/**
|
||||
* Inserts data into a table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table where to insert data
|
||||
* @param array $row Row
|
||||
* @return void
|
||||
*/
|
||||
public function insert(Table $table, array $row): void;
|
||||
|
||||
/**
|
||||
* Inserts data into a table in a bulk.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table where to insert data
|
||||
* @param array $rows Rows
|
||||
* @return void
|
||||
*/
|
||||
public function bulkinsert(Table $table, array $rows): void;
|
||||
|
||||
/**
|
||||
* Quotes a table name for use in a query.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return string
|
||||
*/
|
||||
public function quoteTableName(string $tableName): string;
|
||||
|
||||
/**
|
||||
* Quotes a column name for use in a query.
|
||||
*
|
||||
* @param string $columnName Table name
|
||||
* @return string
|
||||
*/
|
||||
public function quoteColumnName(string $columnName): string;
|
||||
|
||||
/**
|
||||
* Checks to see if a table exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasTable(string $tableName): bool;
|
||||
|
||||
/**
|
||||
* Creates the specified database table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table
|
||||
* @param \Phinx\Db\Table\Column[] $columns List of columns in the table
|
||||
* @param \Phinx\Db\Table\Index[] $indexes List of indexes for the table
|
||||
* @return void
|
||||
*/
|
||||
public function createTable(Table $table, array $columns = [], array $indexes = []): void;
|
||||
|
||||
/**
|
||||
* Truncates the specified table
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return void
|
||||
*/
|
||||
public function truncateTable(string $tableName): void;
|
||||
|
||||
/**
|
||||
* Returns table columns
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return \Phinx\Db\Table\Column[]
|
||||
*/
|
||||
public function getColumns(string $tableName): array;
|
||||
|
||||
/**
|
||||
* Checks to see if a column exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string $columnName Column name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasColumn(string $tableName, string $columnName): bool;
|
||||
|
||||
/**
|
||||
* Checks to see if an index exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @return bool
|
||||
*/
|
||||
public function hasIndex(string $tableName, $columns): bool;
|
||||
|
||||
/**
|
||||
* Checks to see if an index specified by name exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string $indexName Index name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasIndexByName(string $tableName, string $indexName): bool;
|
||||
|
||||
/**
|
||||
* Checks to see if the specified primary key exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @param string|null $constraint Constraint name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasPrimaryKey(string $tableName, $columns, ?string $constraint = null): bool;
|
||||
|
||||
/**
|
||||
* Checks to see if a foreign key exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @param string|null $constraint Constraint name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasForeignKey(string $tableName, $columns, ?string $constraint = null): bool;
|
||||
|
||||
/**
|
||||
* Returns an array of the supported Phinx column types.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getColumnTypes(): array;
|
||||
|
||||
/**
|
||||
* Checks that the given column is of a supported type.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Column $column Column
|
||||
* @return bool
|
||||
*/
|
||||
public function isValidColumnType(Column $column): bool;
|
||||
|
||||
/**
|
||||
* Converts the Phinx logical type to the adapter's SQL type.
|
||||
*
|
||||
* @param \Phinx\Util\Literal|string $type Type
|
||||
* @param int|null $limit Limit
|
||||
* @return array
|
||||
*/
|
||||
public function getSqlType($type, ?int $limit = null): array;
|
||||
|
||||
/**
|
||||
* Creates a new database.
|
||||
*
|
||||
* @param string $name Database Name
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return void
|
||||
*/
|
||||
public function createDatabase(string $name, array $options = []): void;
|
||||
|
||||
/**
|
||||
* Checks to see if a database exists.
|
||||
*
|
||||
* @param string $name Database Name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasDatabase(string $name): bool;
|
||||
|
||||
/**
|
||||
* Drops the specified database.
|
||||
*
|
||||
* @param string $name Database Name
|
||||
* @return void
|
||||
*/
|
||||
public function dropDatabase(string $name): void;
|
||||
|
||||
/**
|
||||
* Creates the specified schema or throws an exception
|
||||
* if there is no support for it.
|
||||
*
|
||||
* @param string $schemaName Schema Name
|
||||
* @return void
|
||||
*/
|
||||
public function createSchema(string $schemaName = 'public'): void;
|
||||
|
||||
/**
|
||||
* Drops the specified schema table or throws an exception
|
||||
* if there is no support for it.
|
||||
*
|
||||
* @param string $schemaName Schema name
|
||||
* @return void
|
||||
*/
|
||||
public function dropSchema(string $schemaName): void;
|
||||
|
||||
/**
|
||||
* Cast a value to a boolean appropriate for the adapter.
|
||||
*
|
||||
* @param mixed $value The value to be cast
|
||||
* @return mixed
|
||||
*/
|
||||
public function castToBool($value);
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use Cake\Database\Query;
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table;
|
||||
use Phinx\Migration\MigrationInterface;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Adapter Wrapper.
|
||||
*
|
||||
* Proxy commands through to another adapter, allowing modification of
|
||||
* parameters during calls.
|
||||
*
|
||||
* @author Woody Gilk <woody.gilk@gmail.com>
|
||||
*/
|
||||
abstract class AdapterWrapper implements AdapterInterface, WrapperInterface
|
||||
{
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
protected $adapter;
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __construct(AdapterInterface $adapter)
|
||||
{
|
||||
$this->setAdapter($adapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter): AdapterInterface
|
||||
{
|
||||
$this->adapter = $adapter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface
|
||||
{
|
||||
return $this->adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOptions(array $options): AdapterInterface
|
||||
{
|
||||
$this->adapter->setOptions($options);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->adapter->getOptions();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasOption(string $name): bool
|
||||
{
|
||||
return $this->adapter->hasOption($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOption(string $name)
|
||||
{
|
||||
return $this->adapter->getOption($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setInput(InputInterface $input): AdapterInterface
|
||||
{
|
||||
$this->adapter->setInput($input);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getInput(): InputInterface
|
||||
{
|
||||
return $this->adapter->getInput();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOutput(OutputInterface $output): AdapterInterface
|
||||
{
|
||||
$this->adapter->setOutput($output);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOutput(): OutputInterface
|
||||
{
|
||||
return $this->adapter->getOutput();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getColumnForType(string $columnName, string $type, array $options): Column
|
||||
{
|
||||
return $this->adapter->getColumnForType($columnName, $type, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function connect(): void
|
||||
{
|
||||
$this->getAdapter()->connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function disconnect(): void
|
||||
{
|
||||
$this->getAdapter()->disconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int
|
||||
{
|
||||
return $this->getAdapter()->execute($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function query(string $sql, array $params = [])
|
||||
{
|
||||
return $this->getAdapter()->query($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function insert(Table $table, array $row): void
|
||||
{
|
||||
$this->getAdapter()->insert($table, $row);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function bulkinsert(Table $table, array $rows): void
|
||||
{
|
||||
$this->getAdapter()->bulkinsert($table, $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function fetchRow(string $sql)
|
||||
{
|
||||
return $this->getAdapter()->fetchRow($sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function fetchAll(string $sql): array
|
||||
{
|
||||
return $this->getAdapter()->fetchAll($sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getVersions(): array
|
||||
{
|
||||
return $this->getAdapter()->getVersions();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getVersionLog(): array
|
||||
{
|
||||
return $this->getAdapter()->getVersionLog();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function migrated(MigrationInterface $migration, string $direction, string $startTime, string $endTime): AdapterInterface
|
||||
{
|
||||
$this->getAdapter()->migrated($migration, $direction, $startTime, $endTime);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function toggleBreakpoint(MigrationInterface $migration): AdapterInterface
|
||||
{
|
||||
$this->getAdapter()->toggleBreakpoint($migration);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function resetAllBreakpoints(): int
|
||||
{
|
||||
return $this->getAdapter()->resetAllBreakpoints();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setBreakpoint(MigrationInterface $migration): AdapterInterface
|
||||
{
|
||||
$this->getAdapter()->setBreakpoint($migration);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function unsetBreakpoint(MigrationInterface $migration): AdapterInterface
|
||||
{
|
||||
$this->getAdapter()->unsetBreakpoint($migration);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createSchemaTable(): void
|
||||
{
|
||||
$this->getAdapter()->createSchemaTable();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getColumnTypes(): array
|
||||
{
|
||||
return $this->getAdapter()->getColumnTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function isValidColumnType(Column $column): bool
|
||||
{
|
||||
return $this->getAdapter()->isValidColumnType($column);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasTransactions(): bool
|
||||
{
|
||||
return $this->getAdapter()->hasTransactions();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function beginTransaction(): void
|
||||
{
|
||||
$this->getAdapter()->beginTransaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function commitTransaction(): void
|
||||
{
|
||||
$this->getAdapter()->commitTransaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function rollbackTransaction(): void
|
||||
{
|
||||
$this->getAdapter()->rollbackTransaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function quoteTableName(string $tableName): string
|
||||
{
|
||||
return $this->getAdapter()->quoteTableName($tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function quoteColumnName(string $columnName): string
|
||||
{
|
||||
return $this->getAdapter()->quoteColumnName($columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasTable(string $tableName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasTable($tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createTable(Table $table, array $columns = [], array $indexes = []): void
|
||||
{
|
||||
$this->getAdapter()->createTable($table, $columns, $indexes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getColumns(string $tableName): array
|
||||
{
|
||||
return $this->getAdapter()->getColumns($tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasColumn(string $tableName, string $columnName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasColumn($tableName, $columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasIndex(string $tableName, $columns): bool
|
||||
{
|
||||
return $this->getAdapter()->hasIndex($tableName, $columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasIndexByName(string $tableName, string $indexName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasIndexByName($tableName, $indexName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasPrimaryKey(string $tableName, $columns, ?string $constraint = null): bool
|
||||
{
|
||||
return $this->getAdapter()->hasPrimaryKey($tableName, $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasForeignKey(string $tableName, $columns, ?string $constraint = null): bool
|
||||
{
|
||||
return $this->getAdapter()->hasForeignKey($tableName, $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getSqlType($type, ?int $limit = null): array
|
||||
{
|
||||
return $this->getAdapter()->getSqlType($type, $limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createDatabase(string $name, array $options = []): void
|
||||
{
|
||||
$this->getAdapter()->createDatabase($name, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasDatabase(string $name): bool
|
||||
{
|
||||
return $this->getAdapter()->hasDatabase($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function dropDatabase(string $name): void
|
||||
{
|
||||
$this->getAdapter()->dropDatabase($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createSchema(string $schemaName = 'public'): void
|
||||
{
|
||||
$this->getAdapter()->createSchema($schemaName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function dropSchema(string $schemaName): void
|
||||
{
|
||||
$this->getAdapter()->dropSchema($schemaName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function truncateTable(string $tableName): void
|
||||
{
|
||||
$this->getAdapter()->truncateTable($tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function castToBool($value)
|
||||
{
|
||||
return $this->getAdapter()->castToBool($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \PDO
|
||||
*/
|
||||
public function getConnection()
|
||||
{
|
||||
return $this->getAdapter()->getConnection();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function executeActions(Table $table, array $actions): void
|
||||
{
|
||||
$this->getAdapter()->executeActions($table, $actions);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getQueryBuilder(): Query
|
||||
{
|
||||
return $this->getAdapter()->getQueryBuilder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\ForeignKey;
|
||||
use Phinx\Db\Table\Index;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
/**
|
||||
* Represents an adapter that is capable of directly executing alter
|
||||
* instructions, without having to plan them first.
|
||||
*/
|
||||
interface DirectActionInterface
|
||||
{
|
||||
/**
|
||||
* Renames the specified database table.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string $newName New Name
|
||||
* @return void
|
||||
*/
|
||||
public function renameTable(string $tableName, string $newName): void;
|
||||
|
||||
/**
|
||||
* Drops the specified database table.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return void
|
||||
*/
|
||||
public function dropTable(string $tableName): void;
|
||||
|
||||
/**
|
||||
* Changes the primary key of the specified database table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table
|
||||
* @param string|string[]|null $newColumns Column name(s) to belong to the primary key, or null to drop the key
|
||||
* @return void
|
||||
*/
|
||||
public function changePrimaryKey(Table $table, $newColumns): void;
|
||||
|
||||
/**
|
||||
* Changes the comment of the specified database table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table
|
||||
* @param string|null $newComment New comment string, or null to drop the comment
|
||||
* @return void
|
||||
*/
|
||||
public function changeComment(Table $table, ?string $newComment): void;
|
||||
|
||||
/**
|
||||
* Adds the specified column to a database table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table
|
||||
* @param \Phinx\Db\Table\Column $column Column
|
||||
* @return void
|
||||
*/
|
||||
public function addColumn(Table $table, Column $column): void;
|
||||
|
||||
/**
|
||||
* Renames the specified column.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string $columnName Column Name
|
||||
* @param string $newColumnName New Column Name
|
||||
* @return void
|
||||
*/
|
||||
public function renameColumn(string $tableName, string $columnName, string $newColumnName): void;
|
||||
|
||||
/**
|
||||
* Change a table column type.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string $columnName Column Name
|
||||
* @param \Phinx\Db\Table\Column $newColumn New Column
|
||||
* @return void
|
||||
*/
|
||||
public function changeColumn(string $tableName, string $columnName, Column $newColumn): void;
|
||||
|
||||
/**
|
||||
* Drops the specified column.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param string $columnName Column Name
|
||||
* @return void
|
||||
*/
|
||||
public function dropColumn(string $tableName, string $columnName): void;
|
||||
|
||||
/**
|
||||
* Adds the specified index to a database table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table Table
|
||||
* @param \Phinx\Db\Table\Index $index Index
|
||||
* @return void
|
||||
*/
|
||||
public function addIndex(Table $table, Index $index): void;
|
||||
|
||||
/**
|
||||
* Drops the specified index from a database table.
|
||||
*
|
||||
* @param string $tableName the name of the table
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @return void
|
||||
*/
|
||||
public function dropIndex(string $tableName, $columns): void;
|
||||
|
||||
/**
|
||||
* Drops the index specified by name from a database table.
|
||||
*
|
||||
* @param string $tableName The table name where the index is
|
||||
* @param string $indexName The name of the index
|
||||
* @return void
|
||||
*/
|
||||
public function dropIndexByName(string $tableName, string $indexName): void;
|
||||
|
||||
/**
|
||||
* Adds the specified foreign key to a database table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to add the foreign key to
|
||||
* @param \Phinx\Db\Table\ForeignKey $foreignKey The foreign key to add
|
||||
* @return void
|
||||
*/
|
||||
public function addForeignKey(Table $table, ForeignKey $foreignKey): void;
|
||||
|
||||
/**
|
||||
* Drops the specified foreign key from a database table.
|
||||
*
|
||||
* @param string $tableName The table to drop the foreign key from
|
||||
* @param string[] $columns Column(s)
|
||||
* @param string|null $constraint Constraint name
|
||||
* @return void
|
||||
*/
|
||||
public function dropForeignKey(string $tableName, array $columns, ?string $constraint = null): void;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use Phinx\Db\Action\AddColumn;
|
||||
use Phinx\Db\Action\AddForeignKey;
|
||||
use Phinx\Db\Action\AddIndex;
|
||||
use Phinx\Db\Action\CreateTable;
|
||||
use Phinx\Db\Action\DropForeignKey;
|
||||
use Phinx\Db\Action\DropIndex;
|
||||
use Phinx\Db\Action\DropTable;
|
||||
use Phinx\Db\Action\RemoveColumn;
|
||||
use Phinx\Db\Action\RenameColumn;
|
||||
use Phinx\Db\Action\RenameTable;
|
||||
use Phinx\Db\Plan\Intent;
|
||||
use Phinx\Db\Plan\Plan;
|
||||
use Phinx\Db\Table\Table;
|
||||
use Phinx\Migration\IrreversibleMigrationException;
|
||||
|
||||
/**
|
||||
* Phinx Proxy Adapter.
|
||||
*
|
||||
* Used for recording migration commands to automatically reverse them.
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
class ProxyAdapter extends AdapterWrapper
|
||||
{
|
||||
/**
|
||||
* @var \Phinx\Db\Action\Action[]
|
||||
*/
|
||||
protected $commands = [];
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapterType(): string
|
||||
{
|
||||
return 'ProxyAdapter';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createTable(Table $table, array $columns = [], array $indexes = []): void
|
||||
{
|
||||
$this->commands[] = new CreateTable($table);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function executeActions(Table $table, array $actions): void
|
||||
{
|
||||
$this->commands = array_merge($this->commands, $actions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of the recorded commands in reverse.
|
||||
*
|
||||
* @throws \Phinx\Migration\IrreversibleMigrationException if a command cannot be reversed.
|
||||
* @return \Phinx\Db\Plan\Intent
|
||||
*/
|
||||
public function getInvertedCommands(): Intent
|
||||
{
|
||||
$inverted = new Intent();
|
||||
|
||||
foreach (array_reverse($this->commands) as $command) {
|
||||
switch (true) {
|
||||
case $command instanceof CreateTable:
|
||||
/** @var \Phinx\Db\Action\CreateTable $command */
|
||||
$inverted->addAction(new DropTable($command->getTable()));
|
||||
break;
|
||||
|
||||
case $command instanceof RenameTable:
|
||||
/** @var \Phinx\Db\Action\RenameTable $command */
|
||||
$inverted->addAction(new RenameTable(new Table($command->getNewName()), $command->getTable()->getName()));
|
||||
break;
|
||||
|
||||
case $command instanceof AddColumn:
|
||||
/** @var \Phinx\Db\Action\AddColumn $command */
|
||||
$inverted->addAction(new RemoveColumn($command->getTable(), $command->getColumn()));
|
||||
break;
|
||||
|
||||
case $command instanceof RenameColumn:
|
||||
/** @var \Phinx\Db\Action\RenameColumn $command */
|
||||
$column = clone $command->getColumn();
|
||||
$name = $column->getName();
|
||||
$column->setName($command->getNewName());
|
||||
$inverted->addAction(new RenameColumn($command->getTable(), $column, $name));
|
||||
break;
|
||||
|
||||
case $command instanceof AddIndex:
|
||||
/** @var \Phinx\Db\Action\AddIndex $command */
|
||||
$inverted->addAction(new DropIndex($command->getTable(), $command->getIndex()));
|
||||
break;
|
||||
|
||||
case $command instanceof AddForeignKey:
|
||||
/** @var \Phinx\Db\Action\AddForeignKey $command */
|
||||
$inverted->addAction(new DropForeignKey($command->getTable(), $command->getForeignKey()));
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new IrreversibleMigrationException(sprintf(
|
||||
'Cannot reverse a "%s" command',
|
||||
get_class($command)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return $inverted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the recorded commands in reverse.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function executeInvertedCommands(): void
|
||||
{
|
||||
$plan = new Plan($this->getInvertedCommands());
|
||||
$plan->executeInverse($this->getAdapter());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,494 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use BadMethodCallException;
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Db\Action\AddColumn;
|
||||
use Phinx\Db\Action\AddForeignKey;
|
||||
use Phinx\Db\Action\AddIndex;
|
||||
use Phinx\Db\Action\ChangeColumn;
|
||||
use Phinx\Db\Action\ChangeComment;
|
||||
use Phinx\Db\Action\ChangePrimaryKey;
|
||||
use Phinx\Db\Action\DropForeignKey;
|
||||
use Phinx\Db\Action\DropIndex;
|
||||
use Phinx\Db\Action\DropTable;
|
||||
use Phinx\Db\Action\RemoveColumn;
|
||||
use Phinx\Db\Action\RenameColumn;
|
||||
use Phinx\Db\Action\RenameTable;
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\ForeignKey;
|
||||
use Phinx\Db\Table\Index;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
/**
|
||||
* Table prefix/suffix adapter.
|
||||
*
|
||||
* Used for inserting a prefix or suffix into table names.
|
||||
*
|
||||
* @author Samuel Fisher <sam@sfisher.co>
|
||||
*/
|
||||
class TablePrefixAdapter extends AdapterWrapper implements DirectActionInterface
|
||||
{
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapterType(): string
|
||||
{
|
||||
return 'TablePrefixAdapter';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasTable(string $tableName): bool
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::hasTable($adapterTableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createTable(Table $table, array $columns = [], array $indexes = []): void
|
||||
{
|
||||
$adapterTable = new Table(
|
||||
$this->getAdapterTableName($table->getName()),
|
||||
$table->getOptions()
|
||||
);
|
||||
parent::createTable($adapterTable, $columns, $indexes);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function changePrimaryKey(Table $table, $newColumns): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
|
||||
$adapterTable = new Table(
|
||||
$this->getAdapterTableName($table->getName()),
|
||||
$table->getOptions()
|
||||
);
|
||||
$adapter->changePrimaryKey($adapterTable, $newColumns);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function changeComment(Table $table, ?string $newComment): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
|
||||
$adapterTable = new Table(
|
||||
$this->getAdapterTableName($table->getName()),
|
||||
$table->getOptions()
|
||||
);
|
||||
$adapter->changeComment($adapterTable, $newComment);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function renameTable(string $tableName, string $newTableName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapterNewTableName = $this->getAdapterTableName($newTableName);
|
||||
$adapter->renameTable($adapterTableName, $adapterNewTableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropTable(string $tableName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->dropTable($adapterTableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function truncateTable(string $tableName): void
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
parent::truncateTable($adapterTableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getColumns(string $tableName): array
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::getColumns($adapterTableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasColumn(string $tableName, string $columnName): bool
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::hasColumn($adapterTableName, $columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function addColumn(Table $table, Column $column): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($table->getName());
|
||||
$adapterTable = new Table($adapterTableName, $table->getOptions());
|
||||
$adapter->addColumn($adapterTable, $column);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function renameColumn(string $tableName, string $columnName, string $newColumnName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->renameColumn($adapterTableName, $columnName, $newColumnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function changeColumn(string $tableName, string $columnName, Column $newColumn): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->changeColumn($adapterTableName, $columnName, $newColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropColumn(string $tableName, string $columnName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->dropColumn($adapterTableName, $columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasIndex(string $tableName, $columns): bool
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::hasIndex($adapterTableName, $columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasIndexByName(string $tableName, string $indexName): bool
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::hasIndexByName($adapterTableName, $indexName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function addIndex(Table $table, Index $index): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTable = new Table($table->getName(), $table->getOptions());
|
||||
$adapter->addIndex($adapterTable, $index);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropIndex(string $tableName, $columns): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->dropIndex($adapterTableName, $columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropIndexByName(string $tableName, string $indexName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->dropIndexByName($adapterTableName, $indexName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasPrimaryKey(string $tableName, $columns, ?string $constraint = null): bool
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::hasPrimaryKey($adapterTableName, $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasForeignKey(string $tableName, $columns, ?string $constraint = null): bool
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
|
||||
return parent::hasForeignKey($adapterTableName, $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function addForeignKey(Table $table, ForeignKey $foreignKey): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($table->getName());
|
||||
$adapterTable = new Table($adapterTableName, $table->getOptions());
|
||||
$adapter->addForeignKey($adapterTable, $foreignKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropForeignKey(string $tableName, array $columns, ?string $constraint = null): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The underlying adapter does not implement DirectActionInterface');
|
||||
}
|
||||
$adapterTableName = $this->getAdapterTableName($tableName);
|
||||
$adapter->dropForeignKey($adapterTableName, $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function insert(Table $table, array $row): void
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($table->getName());
|
||||
$adapterTable = new Table($adapterTableName, $table->getOptions());
|
||||
parent::insert($adapterTable, $row);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function bulkinsert(Table $table, array $rows): void
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($table->getName());
|
||||
$adapterTable = new Table($adapterTableName, $table->getOptions());
|
||||
parent::bulkinsert($adapterTable, $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table prefix.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPrefix(): string
|
||||
{
|
||||
return (string)$this->getOption('table_prefix');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table suffix.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSuffix(): string
|
||||
{
|
||||
return (string)$this->getOption('table_suffix');
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the prefix and suffix to the table name.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return string
|
||||
*/
|
||||
public function getAdapterTableName(string $tableName): string
|
||||
{
|
||||
return $this->getPrefix() . $tableName . $this->getSuffix();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
public function executeActions(Table $table, array $actions): void
|
||||
{
|
||||
$adapterTableName = $this->getAdapterTableName($table->getName());
|
||||
$adapterTable = new Table($adapterTableName, $table->getOptions());
|
||||
|
||||
foreach ($actions as $k => $action) {
|
||||
switch (true) {
|
||||
case $action instanceof AddColumn:
|
||||
/** @var \Phinx\Db\Action\AddColumn $action */
|
||||
$actions[$k] = new AddColumn($adapterTable, $action->getColumn());
|
||||
break;
|
||||
|
||||
case $action instanceof AddIndex:
|
||||
/** @var \Phinx\Db\Action\AddIndex $action */
|
||||
$actions[$k] = new AddIndex($adapterTable, $action->getIndex());
|
||||
break;
|
||||
|
||||
case $action instanceof AddForeignKey:
|
||||
/** @var \Phinx\Db\Action\AddForeignKey $action */
|
||||
$foreignKey = clone $action->getForeignKey();
|
||||
$refTable = $foreignKey->getReferencedTable();
|
||||
$refTableName = $this->getAdapterTableName($refTable->getName());
|
||||
$foreignKey->setReferencedTable(new Table($refTableName, $refTable->getOptions()));
|
||||
$actions[$k] = new AddForeignKey($adapterTable, $foreignKey);
|
||||
break;
|
||||
|
||||
case $action instanceof ChangeColumn:
|
||||
/** @var \Phinx\Db\Action\ChangeColumn $action */
|
||||
$actions[$k] = new ChangeColumn($adapterTable, $action->getColumnName(), $action->getColumn());
|
||||
break;
|
||||
|
||||
case $action instanceof DropForeignKey:
|
||||
/** @var \Phinx\Db\Action\DropForeignKey $action */
|
||||
$actions[$k] = new DropForeignKey($adapterTable, $action->getForeignKey());
|
||||
break;
|
||||
|
||||
case $action instanceof DropIndex:
|
||||
/** @var \Phinx\Db\Action\DropIndex $action */
|
||||
$actions[$k] = new DropIndex($adapterTable, $action->getIndex());
|
||||
break;
|
||||
|
||||
case $action instanceof DropTable:
|
||||
/** @var \Phinx\Db\Action\DropTable $action */
|
||||
$actions[$k] = new DropTable($adapterTable);
|
||||
break;
|
||||
|
||||
case $action instanceof RemoveColumn:
|
||||
/** @var \Phinx\Db\Action\RemoveColumn $action */
|
||||
$actions[$k] = new RemoveColumn($adapterTable, $action->getColumn());
|
||||
break;
|
||||
|
||||
case $action instanceof RenameColumn:
|
||||
/** @var \Phinx\Db\Action\RenameColumn $action */
|
||||
$actions[$k] = new RenameColumn($adapterTable, $action->getColumn(), $action->getNewName());
|
||||
break;
|
||||
|
||||
case $action instanceof RenameTable:
|
||||
/** @var \Phinx\Db\Action\RenameTable $action */
|
||||
$actions[$k] = new RenameTable($adapterTable, $this->getAdapterTableName($action->getNewName()));
|
||||
break;
|
||||
|
||||
case $action instanceof ChangePrimaryKey:
|
||||
/** @var \Phinx\Db\Action\ChangePrimaryKey $action */
|
||||
$actions[$k] = new ChangePrimaryKey($adapterTable, $action->getNewColumns());
|
||||
break;
|
||||
|
||||
case $action instanceof ChangeComment:
|
||||
/** @var \Phinx\Db\Action\ChangeComment $action */
|
||||
$actions[$k] = new ChangeComment($adapterTable, $action->getNewComment());
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException(
|
||||
sprintf("Forgot to implement table prefixing for action: '%s'", get_class($action))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
parent::executeActions($adapterTable, $actions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use BadMethodCallException;
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\ForeignKey;
|
||||
use Phinx\Db\Table\Index;
|
||||
use Phinx\Db\Table\Table;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Wraps any adapter to record the time spend executing its commands
|
||||
*/
|
||||
class TimedOutputAdapter extends AdapterWrapper implements DirectActionInterface
|
||||
{
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapterType(): string
|
||||
{
|
||||
return $this->getAdapter()->getAdapterType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start timing a command.
|
||||
*
|
||||
* @return callable A function that is to be called when the command finishes
|
||||
*/
|
||||
public function startCommandTimer(): callable
|
||||
{
|
||||
$started = microtime(true);
|
||||
|
||||
return function () use ($started) {
|
||||
$end = microtime(true);
|
||||
if (OutputInterface::VERBOSITY_VERBOSE <= $this->getOutput()->getVerbosity()) {
|
||||
$this->getOutput()->writeln(' -> ' . sprintf('%.4fs', $end - $started));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a Phinx command to the output.
|
||||
*
|
||||
* @param string $command Command Name
|
||||
* @param array $args Command Args
|
||||
* @return void
|
||||
*/
|
||||
public function writeCommand(string $command, array $args = []): void
|
||||
{
|
||||
if (OutputInterface::VERBOSITY_VERBOSE > $this->getOutput()->getVerbosity()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (count($args)) {
|
||||
$outArr = [];
|
||||
foreach ($args as $arg) {
|
||||
if (is_array($arg)) {
|
||||
$arg = array_map(
|
||||
function ($value) {
|
||||
return '\'' . $value . '\'';
|
||||
},
|
||||
$arg
|
||||
);
|
||||
$outArr[] = '[' . implode(', ', $arg) . ']';
|
||||
continue;
|
||||
}
|
||||
|
||||
$outArr[] = '\'' . $arg . '\'';
|
||||
}
|
||||
$this->getOutput()->writeln(' -- ' . $command . '(' . implode(', ', $outArr) . ')');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->getOutput()->writeln(' -- ' . $command);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function insert(Table $table, array $row): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('insert', [$table->getName()]);
|
||||
parent::insert($table, $row);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function bulkinsert(Table $table, array $rows): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('bulkinsert', [$table->getName()]);
|
||||
parent::bulkinsert($table, $rows);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createTable(Table $table, array $columns = [], array $indexes = []): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('createTable', [$table->getName()]);
|
||||
parent::createTable($table, $columns, $indexes);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function changePrimaryKey(Table $table, $newColumns): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('changePrimaryKey', [$table->getName()]);
|
||||
$adapter->changePrimaryKey($table, $newColumns);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function changeComment(Table $table, ?string $newComment): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('changeComment', [$table->getName()]);
|
||||
$adapter->changeComment($table, $newComment);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function renameTable(string $tableName, string $newTableName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('renameTable', [$tableName, $newTableName]);
|
||||
$adapter->renameTable($tableName, $newTableName);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropTable(string $tableName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropTable', [$tableName]);
|
||||
$adapter->dropTable($tableName);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function truncateTable(string $tableName): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('truncateTable', [$tableName]);
|
||||
parent::truncateTable($tableName);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function addColumn(Table $table, Column $column): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand(
|
||||
'addColumn',
|
||||
[
|
||||
$table->getName(),
|
||||
$column->getName(),
|
||||
$column->getType(),
|
||||
]
|
||||
);
|
||||
$adapter->addColumn($table, $column);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function renameColumn(string $tableName, string $columnName, string $newColumnName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('renameColumn', [$tableName, $columnName, $newColumnName]);
|
||||
$adapter->renameColumn($tableName, $columnName, $newColumnName);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function changeColumn(string $tableName, string $columnName, Column $newColumn): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('changeColumn', [$tableName, $columnName, $newColumn->getType()]);
|
||||
$adapter->changeColumn($tableName, $columnName, $newColumn);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropColumn(string $tableName, string $columnName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropColumn', [$tableName, $columnName]);
|
||||
$adapter->dropColumn($tableName, $columnName);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function addIndex(Table $table, Index $index): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('addIndex', [$table->getName(), $index->getColumns()]);
|
||||
$adapter->addIndex($table, $index);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropIndex(string $tableName, $columns): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropIndex', [$tableName, $columns]);
|
||||
$adapter->dropIndex($tableName, $columns);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropIndexByName(string $tableName, string $indexName): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropIndexByName', [$tableName, $indexName]);
|
||||
$adapter->dropIndexByName($tableName, $indexName);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function addForeignKey(Table $table, ForeignKey $foreignKey): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('addForeignKey', [$table->getName(), $foreignKey->getColumns()]);
|
||||
$adapter->addForeignKey($table, $foreignKey);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function dropForeignKey(string $tableName, array $columns, ?string $constraint = null): void
|
||||
{
|
||||
$adapter = $this->getAdapter();
|
||||
if (!$adapter instanceof DirectActionInterface) {
|
||||
throw new BadMethodCallException('The adapter needs to implement DirectActionInterface');
|
||||
}
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropForeignKey', [$tableName, $columns]);
|
||||
$adapter->dropForeignKey($tableName, $columns, $constraint);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createDatabase(string $name, array $options = []): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('createDatabase', [$name]);
|
||||
parent::createDatabase($name, $options);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function dropDatabase(string $name): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropDatabase', [$name]);
|
||||
parent::dropDatabase($name);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createSchema(string $name = 'public'): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('createSchema', [$name]);
|
||||
parent::createSchema($name);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function dropSchema(string $name): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand('dropSchema', [$name]);
|
||||
parent::dropSchema($name);
|
||||
$end();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function executeActions(Table $table, array $actions): void
|
||||
{
|
||||
$end = $this->startCommandTimer();
|
||||
$this->writeCommand(sprintf('Altering table %s', $table->getName()));
|
||||
parent::executeActions($table, $actions);
|
||||
$end();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Exception thrown when a column type doesn't match a Phinx type.
|
||||
*
|
||||
* @author Martijn Gastkemper <martijngastkemper@gmail.com>
|
||||
*/
|
||||
class UnsupportedColumnTypeException extends RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Adapter;
|
||||
|
||||
/**
|
||||
* Wrapper Interface.
|
||||
*
|
||||
* @author Woody Gilk <woody.gilk@gmail.com>
|
||||
*/
|
||||
interface WrapperInterface
|
||||
{
|
||||
/**
|
||||
* Class constructor, must always wrap another adapter.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Adapter
|
||||
*/
|
||||
public function __construct(AdapterInterface $adapter);
|
||||
|
||||
/**
|
||||
* Sets the database adapter to proxy commands to.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Adapter
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter): AdapterInterface;
|
||||
|
||||
/**
|
||||
* Gets the database adapter.
|
||||
*
|
||||
* @throws \RuntimeException if the adapter has not been set
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Plan;
|
||||
|
||||
use Phinx\Db\Action\Action;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
/**
|
||||
* A collection of ALTER actions for a single table
|
||||
*/
|
||||
class AlterTable
|
||||
{
|
||||
/**
|
||||
* The table
|
||||
*
|
||||
* @var \Phinx\Db\Table\Table
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* The list of actions to execute
|
||||
*
|
||||
* @var \Phinx\Db\Action\Action[]
|
||||
*/
|
||||
protected $actions = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to change
|
||||
*/
|
||||
public function __construct(Table $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds another action to the collection
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action $action The action to add
|
||||
* @return void
|
||||
*/
|
||||
public function addAction(Action $action): void
|
||||
{
|
||||
$this->actions[] = $action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the table associated to this collection
|
||||
*
|
||||
* @return \Phinx\Db\Table\Table
|
||||
*/
|
||||
public function getTable(): Table
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array with all collected actions
|
||||
*
|
||||
* @return \Phinx\Db\Action\Action[]
|
||||
*/
|
||||
public function getActions(): array
|
||||
{
|
||||
return $this->actions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Plan;
|
||||
|
||||
use Phinx\Db\Action\Action;
|
||||
|
||||
/**
|
||||
* An intent is a collection of actions for many tables
|
||||
*/
|
||||
class Intent
|
||||
{
|
||||
/**
|
||||
* List of actions to be executed
|
||||
*
|
||||
* @var \Phinx\Db\Action\Action[]
|
||||
*/
|
||||
protected $actions = [];
|
||||
|
||||
/**
|
||||
* Adds a new action to the collection
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action $action The action to add
|
||||
* @return void
|
||||
*/
|
||||
public function addAction(Action $action): void
|
||||
{
|
||||
$this->actions[] = $action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the full list of actions
|
||||
*
|
||||
* @return \Phinx\Db\Action\Action[]
|
||||
*/
|
||||
public function getActions(): array
|
||||
{
|
||||
return $this->actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges another Intent object with this one
|
||||
*
|
||||
* @param \Phinx\Db\Plan\Intent $another The other intent to merge in
|
||||
* @return void
|
||||
*/
|
||||
public function merge(Intent $another): void
|
||||
{
|
||||
$this->actions = array_merge($this->actions, $another->getActions());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Plan;
|
||||
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Index;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
/**
|
||||
* Represents the collection of actions for creating a new table
|
||||
*/
|
||||
class NewTable
|
||||
{
|
||||
/**
|
||||
* The table to create
|
||||
*
|
||||
* @var \Phinx\Db\Table\Table
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* The list of columns to add
|
||||
*
|
||||
* @var \Phinx\Db\Table\Column[]
|
||||
*/
|
||||
protected $columns = [];
|
||||
|
||||
/**
|
||||
* The list of indexes to create
|
||||
*
|
||||
* @var \Phinx\Db\Table\Index[]
|
||||
*/
|
||||
protected $indexes = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to create
|
||||
*/
|
||||
public function __construct(Table $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a column to the collection
|
||||
*
|
||||
* @param \Phinx\Db\Table\Column $column The column description
|
||||
* @return void
|
||||
*/
|
||||
public function addColumn(Column $column): void
|
||||
{
|
||||
$this->columns[] = $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an index to the collection
|
||||
*
|
||||
* @param \Phinx\Db\Table\Index $index The index description
|
||||
* @return void
|
||||
*/
|
||||
public function addIndex(Index $index): void
|
||||
{
|
||||
$this->indexes[] = $index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the table object associated to this collection
|
||||
*
|
||||
* @return \Phinx\Db\Table\Table
|
||||
*/
|
||||
public function getTable(): Table
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the columns collection
|
||||
*
|
||||
* @return \Phinx\Db\Table\Column[]
|
||||
*/
|
||||
public function getColumns(): array
|
||||
{
|
||||
return $this->columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the indexes collection
|
||||
*
|
||||
* @return \Phinx\Db\Table\Index[]
|
||||
*/
|
||||
public function getIndexes(): array
|
||||
{
|
||||
return $this->indexes;
|
||||
}
|
||||
}
|
||||
+492
@@ -0,0 +1,492 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Plan;
|
||||
|
||||
use ArrayObject;
|
||||
use Phinx\Db\Action\AddColumn;
|
||||
use Phinx\Db\Action\AddForeignKey;
|
||||
use Phinx\Db\Action\AddIndex;
|
||||
use Phinx\Db\Action\ChangeColumn;
|
||||
use Phinx\Db\Action\ChangeComment;
|
||||
use Phinx\Db\Action\ChangePrimaryKey;
|
||||
use Phinx\Db\Action\CreateTable;
|
||||
use Phinx\Db\Action\DropForeignKey;
|
||||
use Phinx\Db\Action\DropIndex;
|
||||
use Phinx\Db\Action\DropTable;
|
||||
use Phinx\Db\Action\RemoveColumn;
|
||||
use Phinx\Db\Action\RenameColumn;
|
||||
use Phinx\Db\Action\RenameTable;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Db\Plan\Solver\ActionSplitter;
|
||||
use Phinx\Db\Table\Table;
|
||||
|
||||
/**
|
||||
* A Plan takes an Intent and transforms int into a sequence of
|
||||
* instructions that can be correctly executed by an AdapterInterface.
|
||||
*
|
||||
* The main focus of Plan is to arrange the actions in the most efficient
|
||||
* way possible for the database.
|
||||
*/
|
||||
class Plan
|
||||
{
|
||||
/**
|
||||
* List of tables to be created
|
||||
*
|
||||
* @var \Phinx\Db\Plan\NewTable[]
|
||||
*/
|
||||
protected $tableCreates = [];
|
||||
|
||||
/**
|
||||
* List of table updates
|
||||
*
|
||||
* @var \Phinx\Db\Plan\AlterTable[]
|
||||
*/
|
||||
protected $tableUpdates = [];
|
||||
|
||||
/**
|
||||
* List of table removals or renames
|
||||
*
|
||||
* @var \Phinx\Db\Plan\AlterTable[]
|
||||
*/
|
||||
protected $tableMoves = [];
|
||||
|
||||
/**
|
||||
* List of index additions or removals
|
||||
*
|
||||
* @var \Phinx\Db\Plan\AlterTable[]
|
||||
*/
|
||||
protected $indexes = [];
|
||||
|
||||
/**
|
||||
* List of constraint additions or removals
|
||||
*
|
||||
* @var \Phinx\Db\Plan\AlterTable[]
|
||||
*/
|
||||
protected $constraints = [];
|
||||
|
||||
/**
|
||||
* List of dropped columns
|
||||
*
|
||||
* @var \Phinx\Db\Plan\AlterTable[]
|
||||
*/
|
||||
protected $columnRemoves = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Phinx\Db\Plan\Intent $intent All the actions that should be executed
|
||||
*/
|
||||
public function __construct(Intent $intent)
|
||||
{
|
||||
$this->createPlan($intent->getActions());
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the given Intent and creates the separate steps to execute
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action[] $actions The actions to use for the plan
|
||||
* @return void
|
||||
*/
|
||||
protected function createPlan(array $actions): void
|
||||
{
|
||||
$this->gatherCreates($actions);
|
||||
$this->gatherUpdates($actions);
|
||||
$this->gatherTableMoves($actions);
|
||||
$this->gatherIndexes($actions);
|
||||
$this->gatherConstraints($actions);
|
||||
$this->resolveConflicts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a nested list of all the steps to execute
|
||||
*
|
||||
* @return \Phinx\Db\Plan\AlterTable[][]
|
||||
*/
|
||||
protected function updatesSequence(): array
|
||||
{
|
||||
return [
|
||||
$this->tableUpdates,
|
||||
$this->constraints,
|
||||
$this->indexes,
|
||||
$this->columnRemoves,
|
||||
$this->tableMoves,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a nested list of all the steps to execute in inverse order
|
||||
*
|
||||
* @return \Phinx\Db\Plan\AlterTable[][]
|
||||
*/
|
||||
protected function inverseUpdatesSequence(): array
|
||||
{
|
||||
return [
|
||||
$this->constraints,
|
||||
$this->tableMoves,
|
||||
$this->indexes,
|
||||
$this->columnRemoves,
|
||||
$this->tableUpdates,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes this plan using the given AdapterInterface
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $executor The executor object for the plan
|
||||
* @return void
|
||||
*/
|
||||
public function execute(AdapterInterface $executor): void
|
||||
{
|
||||
foreach ($this->tableCreates as $newTable) {
|
||||
$executor->createTable($newTable->getTable(), $newTable->getColumns(), $newTable->getIndexes());
|
||||
}
|
||||
|
||||
foreach ($this->updatesSequence() as $updates) {
|
||||
foreach ($updates as $update) {
|
||||
$executor->executeActions($update->getTable(), $update->getActions());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the inverse plan (rollback the actions) with the given AdapterInterface:w
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $executor The executor object for the plan
|
||||
* @return void
|
||||
*/
|
||||
public function executeInverse(AdapterInterface $executor): void
|
||||
{
|
||||
foreach ($this->inverseUpdatesSequence() as $updates) {
|
||||
foreach ($updates as $update) {
|
||||
$executor->executeActions($update->getTable(), $update->getActions());
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->tableCreates as $newTable) {
|
||||
$executor->createTable($newTable->getTable(), $newTable->getColumns(), $newTable->getIndexes());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes certain actions from the plan if they are found to be conflicting or redundant.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function resolveConflicts(): void
|
||||
{
|
||||
foreach ($this->tableMoves as $alterTable) {
|
||||
foreach ($alterTable->getActions() as $action) {
|
||||
if ($action instanceof DropTable) {
|
||||
$this->tableUpdates = $this->forgetTable($action->getTable(), $this->tableUpdates);
|
||||
$this->constraints = $this->forgetTable($action->getTable(), $this->constraints);
|
||||
$this->indexes = $this->forgetTable($action->getTable(), $this->indexes);
|
||||
$this->columnRemoves = $this->forgetTable($action->getTable(), $this->columnRemoves);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Renaming a column and then changing the renamed column is something people do,
|
||||
// but it is a conflicting action. Luckily solving the conflict can be done by moving
|
||||
// the ChangeColumn action to another AlterTable.
|
||||
$splitter = new ActionSplitter(
|
||||
RenameColumn::class,
|
||||
ChangeColumn::class,
|
||||
function (RenameColumn $a, ChangeColumn $b) {
|
||||
return $a->getNewName() === $b->getColumnName();
|
||||
}
|
||||
);
|
||||
$tableUpdates = [];
|
||||
foreach ($this->tableUpdates as $update) {
|
||||
$tableUpdates = array_merge($tableUpdates, $splitter($update));
|
||||
}
|
||||
$this->tableUpdates = $tableUpdates;
|
||||
|
||||
// Dropping indexes used by foreign keys is a conflict, but one we can resolve
|
||||
// if the foreign key is also scheduled to be dropped. If we can find such a a case,
|
||||
// we force the execution of the index drop after the foreign key is dropped.
|
||||
// Changing constraint properties sometimes require dropping it and then
|
||||
// creating it again with the new stuff. Unfortunately, we have already bundled
|
||||
// everything together in as few AlterTable statements as we could, so we need to
|
||||
// resolve this conflict manually.
|
||||
$splitter = new ActionSplitter(
|
||||
DropForeignKey::class,
|
||||
AddForeignKey::class,
|
||||
function (DropForeignKey $a, AddForeignKey $b) {
|
||||
return $a->getForeignKey()->getColumns() === $b->getForeignKey()->getColumns();
|
||||
}
|
||||
);
|
||||
$constraints = [];
|
||||
foreach ($this->constraints as $constraint) {
|
||||
$constraints = array_merge(
|
||||
$constraints,
|
||||
$splitter($this->remapContraintAndIndexConflicts($constraint))
|
||||
);
|
||||
}
|
||||
$this->constraints = $constraints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all actions related to the given table and keeps the
|
||||
* rest
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to find in the list of actions
|
||||
* @param \Phinx\Db\Plan\AlterTable[] $actions The actions to transform
|
||||
* @return \Phinx\Db\Plan\AlterTable[] The list of actions without actions for the given table
|
||||
*/
|
||||
protected function forgetTable(Table $table, array $actions): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($actions as $action) {
|
||||
if ($action->getTable()->getName() === $table->getName()) {
|
||||
continue;
|
||||
}
|
||||
$result[] = $action;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all DropForeignKey actions in an AlterTable and moves
|
||||
* all conflicting DropIndex action in `$this->indexes` into the
|
||||
* given AlterTable.
|
||||
*
|
||||
* @param \Phinx\Db\Plan\AlterTable $alter The collection of actions to inspect
|
||||
* @return \Phinx\Db\Plan\AlterTable The updated AlterTable object. This function
|
||||
* has the side effect of changing the `$this->indexes` property.
|
||||
*/
|
||||
protected function remapContraintAndIndexConflicts(AlterTable $alter): AlterTable
|
||||
{
|
||||
$newAlter = new AlterTable($alter->getTable());
|
||||
|
||||
foreach ($alter->getActions() as $action) {
|
||||
$newAlter->addAction($action);
|
||||
if ($action instanceof DropForeignKey) {
|
||||
[$this->indexes, $dropIndexActions] = $this->forgetDropIndex(
|
||||
$action->getTable(),
|
||||
$action->getForeignKey()->getColumns(),
|
||||
$this->indexes
|
||||
);
|
||||
foreach ($dropIndexActions as $dropIndexAction) {
|
||||
$newAlter->addAction($dropIndexAction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $newAlter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes any DropIndex actions for the given table and exact columns
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to find in the list of actions
|
||||
* @param string[] $columns The column names to match
|
||||
* @param \Phinx\Db\Plan\AlterTable[] $actions The actions to transform
|
||||
* @return array A tuple containing the list of actions without actions for dropping the index
|
||||
* and a list of drop index actions that were removed.
|
||||
*/
|
||||
protected function forgetDropIndex(Table $table, array $columns, array $actions): array
|
||||
{
|
||||
$dropIndexActions = new ArrayObject();
|
||||
$indexes = array_map(function ($alter) use ($table, $columns, $dropIndexActions) {
|
||||
if ($alter->getTable()->getName() !== $table->getName()) {
|
||||
return $alter;
|
||||
}
|
||||
|
||||
$newAlter = new AlterTable($table);
|
||||
foreach ($alter->getActions() as $action) {
|
||||
if ($action instanceof DropIndex && $action->getIndex()->getColumns() === $columns) {
|
||||
$dropIndexActions->append($action);
|
||||
} else {
|
||||
$newAlter->addAction($action);
|
||||
}
|
||||
}
|
||||
|
||||
return $newAlter;
|
||||
}, $actions);
|
||||
|
||||
return [$indexes, $dropIndexActions->getArrayCopy()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes any RemoveColumn actions for the given table and exact columns
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table to find in the list of actions
|
||||
* @param string[] $columns The column names to match
|
||||
* @param \Phinx\Db\Plan\AlterTable[] $actions The actions to transform
|
||||
* @return array A tuple containing the list of actions without actions for removing the column
|
||||
* and a list of remove column actions that were removed.
|
||||
*/
|
||||
protected function forgetRemoveColumn(Table $table, array $columns, array $actions): array
|
||||
{
|
||||
$removeColumnActions = new ArrayObject();
|
||||
$indexes = array_map(function ($alter) use ($table, $columns, $removeColumnActions) {
|
||||
if ($alter->getTable()->getName() !== $table->getName()) {
|
||||
return $alter;
|
||||
}
|
||||
|
||||
$newAlter = new AlterTable($table);
|
||||
foreach ($alter->getActions() as $action) {
|
||||
if ($action instanceof RemoveColumn && in_array($action->getColumn()->getName(), $columns, true)) {
|
||||
$removeColumnActions->append($action);
|
||||
} else {
|
||||
$newAlter->addAction($action);
|
||||
}
|
||||
}
|
||||
|
||||
return $newAlter;
|
||||
}, $actions);
|
||||
|
||||
return [$indexes, $removeColumnActions->getArrayCopy()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all table creation actions from the given intent
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action[] $actions The actions to parse
|
||||
* @return void
|
||||
*/
|
||||
protected function gatherCreates(array $actions): void
|
||||
{
|
||||
foreach ($actions as $action) {
|
||||
if ($action instanceof CreateTable) {
|
||||
$this->tableCreates[$action->getTable()->getName()] = new NewTable($action->getTable());
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($actions as $action) {
|
||||
if (
|
||||
($action instanceof AddColumn || $action instanceof AddIndex)
|
||||
&& isset($this->tableCreates[$action->getTable()->getName()])
|
||||
) {
|
||||
$table = $action->getTable();
|
||||
|
||||
if ($action instanceof AddColumn) {
|
||||
$this->tableCreates[$table->getName()]->addColumn($action->getColumn());
|
||||
}
|
||||
|
||||
if ($action instanceof AddIndex) {
|
||||
$this->tableCreates[$table->getName()]->addIndex($action->getIndex());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all alter table actions from the given intent
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action[] $actions The actions to parse
|
||||
* @return void
|
||||
*/
|
||||
protected function gatherUpdates(array $actions): void
|
||||
{
|
||||
foreach ($actions as $action) {
|
||||
if (
|
||||
!($action instanceof AddColumn)
|
||||
&& !($action instanceof ChangeColumn)
|
||||
&& !($action instanceof RemoveColumn)
|
||||
&& !($action instanceof RenameColumn)
|
||||
) {
|
||||
continue;
|
||||
} elseif (isset($this->tableCreates[$action->getTable()->getName()])) {
|
||||
continue;
|
||||
}
|
||||
$table = $action->getTable();
|
||||
$name = $table->getName();
|
||||
|
||||
if ($action instanceof RemoveColumn) {
|
||||
if (!isset($this->columnRemoves[$name])) {
|
||||
$this->columnRemoves[$name] = new AlterTable($table);
|
||||
}
|
||||
$this->columnRemoves[$name]->addAction($action);
|
||||
} else {
|
||||
if (!isset($this->tableUpdates[$name])) {
|
||||
$this->tableUpdates[$name] = new AlterTable($table);
|
||||
}
|
||||
$this->tableUpdates[$name]->addAction($action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all alter table drop and renames from the given intent
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action[] $actions The actions to parse
|
||||
* @return void
|
||||
*/
|
||||
protected function gatherTableMoves(array $actions): void
|
||||
{
|
||||
foreach ($actions as $action) {
|
||||
if (
|
||||
!($action instanceof DropTable)
|
||||
&& !($action instanceof RenameTable)
|
||||
&& !($action instanceof ChangePrimaryKey)
|
||||
&& !($action instanceof ChangeComment)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
$table = $action->getTable();
|
||||
$name = $table->getName();
|
||||
|
||||
if (!isset($this->tableMoves[$name])) {
|
||||
$this->tableMoves[$name] = new AlterTable($table);
|
||||
}
|
||||
|
||||
$this->tableMoves[$name]->addAction($action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all index creation and drops from the given intent
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action[] $actions The actions to parse
|
||||
* @return void
|
||||
*/
|
||||
protected function gatherIndexes(array $actions): void
|
||||
{
|
||||
foreach ($actions as $action) {
|
||||
if (!($action instanceof AddIndex) && !($action instanceof DropIndex)) {
|
||||
continue;
|
||||
} elseif (isset($this->tableCreates[$action->getTable()->getName()])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$table = $action->getTable();
|
||||
$name = $table->getName();
|
||||
|
||||
if (!isset($this->indexes[$name])) {
|
||||
$this->indexes[$name] = new AlterTable($table);
|
||||
}
|
||||
|
||||
$this->indexes[$name]->addAction($action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all foreign key creation and drops from the given intent
|
||||
*
|
||||
* @param \Phinx\Db\Action\Action[] $actions The actions to parse
|
||||
* @return void
|
||||
*/
|
||||
protected function gatherConstraints(array $actions): void
|
||||
{
|
||||
foreach ($actions as $action) {
|
||||
if (!($action instanceof AddForeignKey || $action instanceof DropForeignKey)) {
|
||||
continue;
|
||||
}
|
||||
$table = $action->getTable();
|
||||
$name = $table->getName();
|
||||
|
||||
if (!isset($this->constraints[$name])) {
|
||||
$this->constraints[$name] = new AlterTable($table);
|
||||
}
|
||||
|
||||
$this->constraints[$name]->addAction($action);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Plan\Solver;
|
||||
|
||||
use Phinx\Db\Plan\AlterTable;
|
||||
|
||||
/**
|
||||
* A Plan takes an Intent and transforms it into a sequence of
|
||||
* instructions that can be correctly executed by an AdapterInterface.
|
||||
*
|
||||
* The main focus of Plan is to arrange the actions in the most efficient
|
||||
* way possible for the database.
|
||||
*/
|
||||
class ActionSplitter
|
||||
{
|
||||
/**
|
||||
* The fully qualified class name of the Action class to match for conflicts
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $conflictClass;
|
||||
|
||||
/**
|
||||
* The fully qualified class name of the Action class to match for conflicts, which
|
||||
* is the dual of $conflictClass. For example `AddColumn` and `DropColumn` are duals.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $conflictClassDual;
|
||||
|
||||
/**
|
||||
* A callback used to signal the actual presence of a conflict, that will be used to
|
||||
* partition the AlterTable into non-conflicting parts.
|
||||
*
|
||||
* The callback receives as first argument amn instance of $conflictClass and as second
|
||||
* argument an instance of $conflictClassDual
|
||||
*
|
||||
* @var callable
|
||||
*/
|
||||
protected $conflictFilter;
|
||||
|
||||
/**
|
||||
* Comstructor
|
||||
*
|
||||
* @param string $conflictClass The fully qualified class name of the Action class to match for conflicts
|
||||
* @param string $conflictClassDual The fully qualified class name of the Action class to match for conflicts,
|
||||
* which is the dual of $conflictClass. For example `AddColumn` and `DropColumn` are duals.
|
||||
* @param callable $conflictFilter The collection of actions to inspect
|
||||
*/
|
||||
public function __construct(string $conflictClass, string $conflictClassDual, callable $conflictFilter)
|
||||
{
|
||||
$this->conflictClass = $conflictClass;
|
||||
$this->conflictClassDual = $conflictClassDual;
|
||||
$this->conflictFilter = $conflictFilter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returs a sequence of AlterTable instructions that are non conflicting
|
||||
* based on the constructor parameters.
|
||||
*
|
||||
* @param \Phinx\Db\Plan\AlterTable $alter The collection of actions to inspect
|
||||
* @return \Phinx\Db\Plan\AlterTable[] A list of AlterTable that can be executed without
|
||||
* this type of conflict
|
||||
*/
|
||||
public function __invoke(AlterTable $alter): array
|
||||
{
|
||||
$conflictActions = array_filter($alter->getActions(), function ($action) {
|
||||
return $action instanceof $this->conflictClass;
|
||||
});
|
||||
|
||||
$originalAlter = new AlterTable($alter->getTable());
|
||||
$newAlter = new AlterTable($alter->getTable());
|
||||
|
||||
foreach ($alter->getActions() as $action) {
|
||||
if (!$action instanceof $this->conflictClassDual) {
|
||||
$originalAlter->addAction($action);
|
||||
continue;
|
||||
}
|
||||
|
||||
$found = false;
|
||||
$matches = $this->conflictFilter;
|
||||
foreach ($conflictActions as $ca) {
|
||||
if ($matches($ca, $action)) {
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($found) {
|
||||
$newAlter->addAction($action);
|
||||
} else {
|
||||
$originalAlter->addAction($action);
|
||||
}
|
||||
}
|
||||
|
||||
return [$originalAlter, $newAlter];
|
||||
}
|
||||
}
|
||||
+721
@@ -0,0 +1,721 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Phinx\Db\Action\AddColumn;
|
||||
use Phinx\Db\Action\AddForeignKey;
|
||||
use Phinx\Db\Action\AddIndex;
|
||||
use Phinx\Db\Action\ChangeColumn;
|
||||
use Phinx\Db\Action\ChangeComment;
|
||||
use Phinx\Db\Action\ChangePrimaryKey;
|
||||
use Phinx\Db\Action\CreateTable;
|
||||
use Phinx\Db\Action\DropForeignKey;
|
||||
use Phinx\Db\Action\DropIndex;
|
||||
use Phinx\Db\Action\DropTable;
|
||||
use Phinx\Db\Action\RemoveColumn;
|
||||
use Phinx\Db\Action\RenameColumn;
|
||||
use Phinx\Db\Action\RenameTable;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Db\Plan\Intent;
|
||||
use Phinx\Db\Plan\Plan;
|
||||
use Phinx\Db\Table\Column;
|
||||
use Phinx\Db\Table\Table as TableValue;
|
||||
use Phinx\Util\Literal;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* This object is based loosely on: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html.
|
||||
*/
|
||||
class Table
|
||||
{
|
||||
/**
|
||||
* @var \Phinx\Db\Table\Table
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterInterface|null
|
||||
*/
|
||||
protected $adapter;
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Plan\Intent
|
||||
*/
|
||||
protected $actions;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $data = [];
|
||||
|
||||
/**
|
||||
* @param string $name Table Name
|
||||
* @param array<string, mixed> $options Options
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface|null $adapter Database Adapter
|
||||
*/
|
||||
public function __construct(string $name, array $options = [], ?AdapterInterface $adapter = null)
|
||||
{
|
||||
$this->table = new TableValue($name, $options);
|
||||
$this->actions = new Intent();
|
||||
|
||||
if ($adapter !== null) {
|
||||
$this->setAdapter($adapter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->table->getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table options.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->table->getOptions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table name and options as an object
|
||||
*
|
||||
* @return \Phinx\Db\Table\Table
|
||||
*/
|
||||
public function getTable(): TableValue
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database adapter.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
|
||||
* @return $this
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter)
|
||||
{
|
||||
$this->adapter = $adapter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the database adapter.
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface
|
||||
{
|
||||
if (!$this->adapter) {
|
||||
throw new RuntimeException('There is no database adapter set yet, cannot proceed');
|
||||
}
|
||||
|
||||
return $this->adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the table have pending actions?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasPendingActions(): bool
|
||||
{
|
||||
return count($this->actions->getActions()) > 0 || count($this->data) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the table exist?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return $this->getAdapter()->hasTable($this->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the database table.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function drop()
|
||||
{
|
||||
$this->actions->addAction(new DropTable($this->table));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames the database table.
|
||||
*
|
||||
* @param string $newTableName New Table Name
|
||||
* @return $this
|
||||
*/
|
||||
public function rename(string $newTableName)
|
||||
{
|
||||
$this->actions->addAction(new RenameTable($this->table, $newTableName));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the primary key of the database table.
|
||||
*
|
||||
* @param string|string[]|null $columns Column name(s) to belong to the primary key, or null to drop the key
|
||||
* @return $this
|
||||
*/
|
||||
public function changePrimaryKey($columns)
|
||||
{
|
||||
$this->actions->addAction(new ChangePrimaryKey($this->table, $columns));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if a primary key exists.
|
||||
*
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @param string|null $constraint Constraint names
|
||||
* @return bool
|
||||
*/
|
||||
public function hasPrimaryKey($columns, ?string $constraint = null): bool
|
||||
{
|
||||
return $this->getAdapter()->hasPrimaryKey($this->getName(), $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the comment of the database table.
|
||||
*
|
||||
* @param string|null $comment New comment string, or null to drop the comment
|
||||
* @return $this
|
||||
*/
|
||||
public function changeComment(?string $comment)
|
||||
{
|
||||
$this->actions->addAction(new ChangeComment($this->table, $comment));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of the table columns.
|
||||
*
|
||||
* @return \Phinx\Db\Table\Column[]
|
||||
*/
|
||||
public function getColumns(): array
|
||||
{
|
||||
return $this->getAdapter()->getColumns($this->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a table column if it exists.
|
||||
*
|
||||
* @param string $name Column name
|
||||
* @return \Phinx\Db\Table\Column|null
|
||||
*/
|
||||
public function getColumn(string $name): ?Column
|
||||
{
|
||||
$columns = array_filter(
|
||||
$this->getColumns(),
|
||||
function ($column) use ($name) {
|
||||
return $column->getName() === $name;
|
||||
}
|
||||
);
|
||||
|
||||
return array_pop($columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets an array of data to be inserted.
|
||||
*
|
||||
* @param array $data Data
|
||||
* @return $this
|
||||
*/
|
||||
public function setData(array $data)
|
||||
{
|
||||
$this->data = $data;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the data waiting to be inserted.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getData(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets all of the pending data to be inserted
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function resetData(): void
|
||||
{
|
||||
$this->setData([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets all of the pending table changes.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reset(): void
|
||||
{
|
||||
$this->actions = new Intent();
|
||||
$this->resetData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a table column.
|
||||
*
|
||||
* Type can be: string, text, integer, float, decimal, datetime, timestamp,
|
||||
* time, date, binary, boolean.
|
||||
*
|
||||
* Valid options can be: limit, default, null, precision or scale.
|
||||
*
|
||||
* @param string|\Phinx\Db\Table\Column $columnName Column Name
|
||||
* @param string|\Phinx\Util\Literal|null $type Column Type
|
||||
* @param array<string, mixed> $options Column Options
|
||||
* @throws \InvalidArgumentException
|
||||
* @return $this
|
||||
*/
|
||||
public function addColumn($columnName, $type = null, array $options = [])
|
||||
{
|
||||
if ($columnName instanceof Column) {
|
||||
$action = new AddColumn($this->table, $columnName);
|
||||
} elseif ($type instanceof Literal) {
|
||||
$action = AddColumn::build($this->table, $columnName, $type, $options);
|
||||
} else {
|
||||
$action = new AddColumn($this->table, $this->getAdapter()->getColumnForType($columnName, $type, $options));
|
||||
}
|
||||
|
||||
// Delegate to Adapters to check column type
|
||||
if (!$this->getAdapter()->isValidColumnType($action->getColumn())) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'An invalid column type "%s" was specified for column "%s".',
|
||||
$type,
|
||||
$action->getColumn()->getName()
|
||||
));
|
||||
}
|
||||
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a table column.
|
||||
*
|
||||
* @param string $columnName Column Name
|
||||
* @return $this
|
||||
*/
|
||||
public function removeColumn(string $columnName)
|
||||
{
|
||||
$action = RemoveColumn::build($this->table, $columnName);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename a table column.
|
||||
*
|
||||
* @param string $oldName Old Column Name
|
||||
* @param string $newName New Column Name
|
||||
* @return $this
|
||||
*/
|
||||
public function renameColumn(string $oldName, string $newName)
|
||||
{
|
||||
$action = RenameColumn::build($this->table, $oldName, $newName);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change a table column type.
|
||||
*
|
||||
* @param string $columnName Column Name
|
||||
* @param string|\Phinx\Db\Table\Column|\Phinx\Util\Literal $newColumnType New Column Type
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return $this
|
||||
*/
|
||||
public function changeColumn(string $columnName, $newColumnType, array $options = [])
|
||||
{
|
||||
if ($newColumnType instanceof Column) {
|
||||
$action = new ChangeColumn($this->table, $columnName, $newColumnType);
|
||||
} else {
|
||||
$action = ChangeColumn::build($this->table, $columnName, $newColumnType, $options);
|
||||
}
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if a column exists.
|
||||
*
|
||||
* @param string $columnName Column Name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasColumn(string $columnName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasColumn($this->getName(), $columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an index to a database table.
|
||||
*
|
||||
* In $options you can specify unique = true/false, and name (index name).
|
||||
*
|
||||
* @param string|array|\Phinx\Db\Table\Index $columns Table Column(s)
|
||||
* @param array<string, mixed> $options Index Options
|
||||
* @return $this
|
||||
*/
|
||||
public function addIndex($columns, array $options = [])
|
||||
{
|
||||
$action = AddIndex::build($this->table, $columns, $options);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given index from a table.
|
||||
*
|
||||
* @param string|string[] $columns Columns
|
||||
* @return $this
|
||||
*/
|
||||
public function removeIndex($columns)
|
||||
{
|
||||
$action = DropIndex::build($this->table, is_string($columns) ? [$columns] : $columns);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given index identified by its name from a table.
|
||||
*
|
||||
* @param string $name Index name
|
||||
* @return $this
|
||||
*/
|
||||
public function removeIndexByName(string $name)
|
||||
{
|
||||
$action = DropIndex::buildFromName($this->table, $name);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if an index exists.
|
||||
*
|
||||
* @param string|string[] $columns Columns
|
||||
* @return bool
|
||||
*/
|
||||
public function hasIndex($columns): bool
|
||||
{
|
||||
return $this->getAdapter()->hasIndex($this->getName(), $columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if an index specified by name exists.
|
||||
*
|
||||
* @param string $indexName Index name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasIndexByName($indexName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasIndexByName($this->getName(), $indexName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a foreign key to a database table.
|
||||
*
|
||||
* In $options you can specify on_delete|on_delete = cascade|no_action ..,
|
||||
* on_update, constraint = constraint name.
|
||||
*
|
||||
* @param string|string[] $columns Columns
|
||||
* @param string|\Phinx\Db\Table\Table $referencedTable Referenced Table
|
||||
* @param string|string[] $referencedColumns Referenced Columns
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return $this
|
||||
*/
|
||||
public function addForeignKey($columns, $referencedTable, $referencedColumns = ['id'], array $options = [])
|
||||
{
|
||||
$action = AddForeignKey::build($this->table, $columns, $referencedTable, $referencedColumns, $options);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a foreign key to a database table with a given name.
|
||||
*
|
||||
* In $options you can specify on_delete|on_delete = cascade|no_action ..,
|
||||
* on_update, constraint = constraint name.
|
||||
*
|
||||
* @param string $name The constraint name
|
||||
* @param string|string[] $columns Columns
|
||||
* @param string|\Phinx\Db\Table\Table $referencedTable Referenced Table
|
||||
* @param string|string[] $referencedColumns Referenced Columns
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return $this
|
||||
*/
|
||||
public function addForeignKeyWithName(string $name, $columns, $referencedTable, $referencedColumns = ['id'], array $options = [])
|
||||
{
|
||||
$action = AddForeignKey::build(
|
||||
$this->table,
|
||||
$columns,
|
||||
$referencedTable,
|
||||
$referencedColumns,
|
||||
$options,
|
||||
$name
|
||||
);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given foreign key from the table.
|
||||
*
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @param string|null $constraint Constraint names
|
||||
* @return $this
|
||||
*/
|
||||
public function dropForeignKey($columns, ?string $constraint = null)
|
||||
{
|
||||
$action = DropForeignKey::build($this->table, $columns, $constraint);
|
||||
$this->actions->addAction($action);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if a foreign key exists.
|
||||
*
|
||||
* @param string|string[] $columns Column(s)
|
||||
* @param string|null $constraint Constraint names
|
||||
* @return bool
|
||||
*/
|
||||
public function hasForeignKey($columns, ?string $constraint = null): bool
|
||||
{
|
||||
return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add timestamp columns created_at and updated_at to the table.
|
||||
*
|
||||
* @param string|false|null $createdAt Alternate name for the created_at column
|
||||
* @param string|false|null $updatedAt Alternate name for the updated_at column
|
||||
* @param bool $withTimezone Whether to set the timezone option on the added columns
|
||||
* @return $this
|
||||
*/
|
||||
public function addTimestamps($createdAt = 'created_at', $updatedAt = 'updated_at', bool $withTimezone = false)
|
||||
{
|
||||
$createdAt = $createdAt ?? 'created_at';
|
||||
$updatedAt = $updatedAt ?? 'updated_at';
|
||||
|
||||
if (!$createdAt && !$updatedAt) {
|
||||
throw new \RuntimeException('Cannot set both created_at and updated_at columns to false');
|
||||
}
|
||||
|
||||
if ($createdAt) {
|
||||
$this->addColumn($createdAt, 'timestamp', [
|
||||
'null' => false,
|
||||
'default' => 'CURRENT_TIMESTAMP',
|
||||
'update' => '',
|
||||
'timezone' => $withTimezone,
|
||||
]);
|
||||
}
|
||||
if ($updatedAt) {
|
||||
$this->addColumn($updatedAt, 'timestamp', [
|
||||
'null' => true,
|
||||
'default' => null,
|
||||
'update' => 'CURRENT_TIMESTAMP',
|
||||
'timezone' => $withTimezone,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias that always sets $withTimezone to true
|
||||
*
|
||||
* @see addTimestamps
|
||||
* @param string|false|null $createdAt Alternate name for the created_at column
|
||||
* @param string|false|null $updatedAt Alternate name for the updated_at column
|
||||
* @return $this
|
||||
*/
|
||||
public function addTimestampsWithTimezone($createdAt = null, $updatedAt = null)
|
||||
{
|
||||
$this->addTimestamps($createdAt, $updatedAt, true);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert data into the table.
|
||||
*
|
||||
* @param array $data array of data in the form:
|
||||
* array(
|
||||
* array("col1" => "value1", "col2" => "anotherValue1"),
|
||||
* array("col2" => "value2", "col2" => "anotherValue2"),
|
||||
* )
|
||||
* or array("col1" => "value1", "col2" => "anotherValue1")
|
||||
* @return $this
|
||||
*/
|
||||
public function insert(array $data)
|
||||
{
|
||||
// handle array of array situations
|
||||
$keys = array_keys($data);
|
||||
$firstKey = array_shift($keys);
|
||||
if ($firstKey !== null && is_array($data[$firstKey])) {
|
||||
foreach ($data as $row) {
|
||||
$this->data[] = $row;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (count($data) > 0) {
|
||||
$this->data[] = $data;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a table from the object instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function create(): void
|
||||
{
|
||||
$this->executeActions(false);
|
||||
$this->saveData();
|
||||
$this->reset(); // reset pending changes
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a table from the object instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function update(): void
|
||||
{
|
||||
$this->executeActions(true);
|
||||
$this->saveData();
|
||||
$this->reset(); // reset pending changes
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the pending data waiting for insertion.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function saveData(): void
|
||||
{
|
||||
$rows = $this->getData();
|
||||
if (empty($rows)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$bulk = true;
|
||||
$row = current($rows);
|
||||
$c = array_keys($row);
|
||||
foreach ($this->getData() as $row) {
|
||||
$k = array_keys($row);
|
||||
if ($k != $c) {
|
||||
$bulk = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($bulk) {
|
||||
$this->getAdapter()->bulkinsert($this->table, $this->getData());
|
||||
} else {
|
||||
foreach ($this->getData() as $row) {
|
||||
$this->getAdapter()->insert($this->table, $row);
|
||||
}
|
||||
}
|
||||
|
||||
$this->resetData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Immediately truncates the table. This operation cannot be undone
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function truncate(): void
|
||||
{
|
||||
$this->getAdapter()->truncateTable($this->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits the table changes.
|
||||
*
|
||||
* If the table doesn't exist it is created otherwise it is updated.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function save(): void
|
||||
{
|
||||
if ($this->exists()) {
|
||||
$this->update(); // update the table
|
||||
} else {
|
||||
$this->create(); // create the table
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the pending actions for this table
|
||||
*
|
||||
* @param bool $exists Whether or not the table existed prior to executing this method
|
||||
* @return void
|
||||
*/
|
||||
protected function executeActions(bool $exists): void
|
||||
{
|
||||
// Renaming a table is tricky, specially when running a reversible migration
|
||||
// down. We will just assume the table already exists if the user commands a
|
||||
// table rename.
|
||||
if (!$exists) {
|
||||
foreach ($this->actions->getActions() as $action) {
|
||||
if ($action instanceof RenameTable) {
|
||||
$exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If the table does not exist, the last command in the chain needs to be
|
||||
// a CreateTable action.
|
||||
if (!$exists) {
|
||||
$this->actions->addAction(new CreateTable($this->table));
|
||||
}
|
||||
|
||||
$plan = new Plan($this->actions);
|
||||
$plan->execute($this->getAdapter());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,801 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Table;
|
||||
|
||||
use Phinx\Config\FeatureFlags;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Db\Adapter\PostgresAdapter;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* This object is based loosely on: https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html.
|
||||
*/
|
||||
class Column
|
||||
{
|
||||
public const BIGINTEGER = AdapterInterface::PHINX_TYPE_BIG_INTEGER;
|
||||
public const SMALLINTEGER = AdapterInterface::PHINX_TYPE_SMALL_INTEGER;
|
||||
public const TINYINTEGER = AdapterInterface::PHINX_TYPE_TINY_INTEGER;
|
||||
public const BINARY = AdapterInterface::PHINX_TYPE_BINARY;
|
||||
public const BOOLEAN = AdapterInterface::PHINX_TYPE_BOOLEAN;
|
||||
public const CHAR = AdapterInterface::PHINX_TYPE_CHAR;
|
||||
public const DATE = AdapterInterface::PHINX_TYPE_DATE;
|
||||
public const DATETIME = AdapterInterface::PHINX_TYPE_DATETIME;
|
||||
public const DECIMAL = AdapterInterface::PHINX_TYPE_DECIMAL;
|
||||
public const FLOAT = AdapterInterface::PHINX_TYPE_FLOAT;
|
||||
public const INTEGER = AdapterInterface::PHINX_TYPE_INTEGER;
|
||||
public const STRING = AdapterInterface::PHINX_TYPE_STRING;
|
||||
public const TEXT = AdapterInterface::PHINX_TYPE_TEXT;
|
||||
public const TIME = AdapterInterface::PHINX_TYPE_TIME;
|
||||
public const TIMESTAMP = AdapterInterface::PHINX_TYPE_TIMESTAMP;
|
||||
public const UUID = AdapterInterface::PHINX_TYPE_UUID;
|
||||
public const BINARYUUID = AdapterInterface::PHINX_TYPE_BINARYUUID;
|
||||
/** MySQL-only column type */
|
||||
public const MEDIUMINTEGER = AdapterInterface::PHINX_TYPE_MEDIUM_INTEGER;
|
||||
/** MySQL-only column type */
|
||||
public const ENUM = AdapterInterface::PHINX_TYPE_ENUM;
|
||||
/** MySQL-only column type */
|
||||
public const SET = AdapterInterface::PHINX_TYPE_STRING;
|
||||
/** MySQL-only column type */
|
||||
public const BLOB = AdapterInterface::PHINX_TYPE_BLOB;
|
||||
/** MySQL-only column type */
|
||||
public const YEAR = AdapterInterface::PHINX_TYPE_YEAR;
|
||||
/** MySQL/Postgres-only column type */
|
||||
public const JSON = AdapterInterface::PHINX_TYPE_JSON;
|
||||
/** Postgres-only column type */
|
||||
public const JSONB = AdapterInterface::PHINX_TYPE_JSONB;
|
||||
/** Postgres-only column type */
|
||||
public const CIDR = AdapterInterface::PHINX_TYPE_CIDR;
|
||||
/** Postgres-only column type */
|
||||
public const INET = AdapterInterface::PHINX_TYPE_INET;
|
||||
/** Postgres-only column type */
|
||||
public const MACADDR = AdapterInterface::PHINX_TYPE_MACADDR;
|
||||
/** Postgres-only column type */
|
||||
public const INTERVAL = AdapterInterface::PHINX_TYPE_INTERVAL;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @var string|\Phinx\Util\Literal
|
||||
*/
|
||||
protected $type;
|
||||
|
||||
/**
|
||||
* @var int|null
|
||||
*/
|
||||
protected $limit;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $null = true;
|
||||
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
protected $default;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $identity = false;
|
||||
|
||||
/**
|
||||
* Postgres-only column option for identity (always|default)
|
||||
*
|
||||
* @var ?string
|
||||
*/
|
||||
protected $generated = PostgresAdapter::GENERATED_BY_DEFAULT;
|
||||
|
||||
/**
|
||||
* @var int|null
|
||||
*/
|
||||
protected $seed;
|
||||
|
||||
/**
|
||||
* @var int|null
|
||||
*/
|
||||
protected $increment;
|
||||
|
||||
/**
|
||||
* @var int|null
|
||||
*/
|
||||
protected $scale;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $after;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $update;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $comment;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $signed = true;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $timezone = false;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $properties = [];
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $collation;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $encoding;
|
||||
|
||||
/**
|
||||
* @var int|null
|
||||
*/
|
||||
protected $srid;
|
||||
|
||||
/**
|
||||
* @var array|null
|
||||
*/
|
||||
protected $values;
|
||||
|
||||
/**
|
||||
* Column constructor
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->null = FeatureFlags::$columnNullDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @return $this
|
||||
*/
|
||||
public function setName(string $name)
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column name.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column type.
|
||||
*
|
||||
* @param string|\Phinx\Util\Literal $type Column type
|
||||
* @return $this
|
||||
*/
|
||||
public function setType($type)
|
||||
{
|
||||
$this->type = $type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column type.
|
||||
*
|
||||
* @return string|\Phinx\Util\Literal
|
||||
*/
|
||||
public function getType()
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column limit.
|
||||
*
|
||||
* @param int|null $limit Limit
|
||||
* @return $this
|
||||
*/
|
||||
public function setLimit(?int $limit)
|
||||
{
|
||||
$this->limit = $limit;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column limit.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getLimit(): ?int
|
||||
{
|
||||
return $this->limit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether the column allows nulls.
|
||||
*
|
||||
* @param bool $null Null
|
||||
* @return $this
|
||||
*/
|
||||
public function setNull(bool $null)
|
||||
{
|
||||
$this->null = (bool)$null;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether the column allows nulls.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getNull(): bool
|
||||
{
|
||||
return $this->null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the column allow nulls?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isNull(): bool
|
||||
{
|
||||
return $this->getNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default column value.
|
||||
*
|
||||
* @param mixed $default Default
|
||||
* @return $this
|
||||
*/
|
||||
public function setDefault($default)
|
||||
{
|
||||
$this->default = $default;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the default column value.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getDefault()
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets generated option for identity columns. Ignored otherwise.
|
||||
*
|
||||
* @param string|null $generated Generated option
|
||||
* @return $this
|
||||
*/
|
||||
public function setGenerated(?string $generated)
|
||||
{
|
||||
$this->generated = $generated;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets generated option for identity columns. Null otherwise
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getGenerated(): ?string
|
||||
{
|
||||
return $this->generated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether or not the column is an identity column.
|
||||
*
|
||||
* @param bool $identity Identity
|
||||
* @return $this
|
||||
*/
|
||||
public function setIdentity(bool $identity)
|
||||
{
|
||||
$this->identity = $identity;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether or not the column is an identity column.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getIdentity(): bool
|
||||
{
|
||||
return $this->identity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the column an identity column?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isIdentity(): bool
|
||||
{
|
||||
return $this->getIdentity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the name of the column to add this column after.
|
||||
*
|
||||
* @param string $after After
|
||||
* @return $this
|
||||
*/
|
||||
public function setAfter(string $after)
|
||||
{
|
||||
$this->after = $after;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the column to add this column after.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getAfter(): ?string
|
||||
{
|
||||
return $this->after;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the 'ON UPDATE' mysql column function.
|
||||
*
|
||||
* @param string $update On Update function
|
||||
* @return $this
|
||||
*/
|
||||
public function setUpdate(string $update)
|
||||
{
|
||||
$this->update = $update;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the ON UPDATE column function.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getUpdate(): ?string
|
||||
{
|
||||
return $this->update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number precision for decimal or float column.
|
||||
*
|
||||
* For example `DECIMAL(5,2)`, 5 is the precision and 2 is the scale,
|
||||
* and the column could store value from -999.99 to 999.99.
|
||||
*
|
||||
* @param int|null $precision Number precision
|
||||
* @return $this
|
||||
*/
|
||||
public function setPrecision(?int $precision)
|
||||
{
|
||||
$this->setLimit($precision);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number precision for decimal or float column.
|
||||
*
|
||||
* For example `DECIMAL(5,2)`, 5 is the precision and 2 is the scale,
|
||||
* and the column could store value from -999.99 to 999.99.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getPrecision(): ?int
|
||||
{
|
||||
return $this->limit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column identity increment.
|
||||
*
|
||||
* @param int $increment Number increment
|
||||
* @return $this
|
||||
*/
|
||||
public function setIncrement(int $increment)
|
||||
{
|
||||
$this->increment = $increment;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column identity increment.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getIncrement(): ?int
|
||||
{
|
||||
return $this->increment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column identity seed.
|
||||
*
|
||||
* @param int $seed Number seed
|
||||
* @return $this
|
||||
*/
|
||||
public function setSeed(int $seed)
|
||||
{
|
||||
$this->seed = $seed;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column identity seed.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getSeed(): ?int
|
||||
{
|
||||
return $this->seed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number scale for decimal or float column.
|
||||
*
|
||||
* For example `DECIMAL(5,2)`, 5 is the precision and 2 is the scale,
|
||||
* and the column could store value from -999.99 to 999.99.
|
||||
*
|
||||
* @param int|null $scale Number scale
|
||||
* @return $this
|
||||
*/
|
||||
public function setScale(?int $scale)
|
||||
{
|
||||
$this->scale = $scale;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number scale for decimal or float column.
|
||||
*
|
||||
* For example `DECIMAL(5,2)`, 5 is the precision and 2 is the scale,
|
||||
* and the column could store value from -999.99 to 999.99.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getScale(): ?int
|
||||
{
|
||||
return $this->scale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number precision and scale for decimal or float column.
|
||||
*
|
||||
* For example `DECIMAL(5,2)`, 5 is the precision and 2 is the scale,
|
||||
* and the column could store value from -999.99 to 999.99.
|
||||
*
|
||||
* @param int $precision Number precision
|
||||
* @param int $scale Number scale
|
||||
* @return $this
|
||||
*/
|
||||
public function setPrecisionAndScale(int $precision, int $scale)
|
||||
{
|
||||
$this->setLimit($precision);
|
||||
$this->scale = $scale;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column comment.
|
||||
*
|
||||
* @param string|null $comment Comment
|
||||
* @return $this
|
||||
*/
|
||||
public function setComment(?string $comment)
|
||||
{
|
||||
$this->comment = $comment;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column comment.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getComment(): ?string
|
||||
{
|
||||
return $this->comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether field should be signed.
|
||||
*
|
||||
* @param bool $signed Signed
|
||||
* @return $this
|
||||
*/
|
||||
public function setSigned(bool $signed)
|
||||
{
|
||||
$this->signed = (bool)$signed;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether field should be signed.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getSigned(): bool
|
||||
{
|
||||
return $this->signed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Should the column be signed?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isSigned(): bool
|
||||
{
|
||||
return $this->getSigned();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether the field should have a timezone identifier.
|
||||
* Used for date/time columns only!
|
||||
*
|
||||
* @param bool $timezone Timezone
|
||||
* @return $this
|
||||
*/
|
||||
public function setTimezone(bool $timezone)
|
||||
{
|
||||
$this->timezone = (bool)$timezone;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether field has a timezone identifier.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getTimezone(): bool
|
||||
{
|
||||
return $this->timezone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Should the column have a timezone?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isTimezone(): bool
|
||||
{
|
||||
return $this->getTimezone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets field properties.
|
||||
*
|
||||
* @param array $properties Properties
|
||||
* @return $this
|
||||
*/
|
||||
public function setProperties(array $properties)
|
||||
{
|
||||
$this->properties = $properties;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets field properties
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getProperties(): array
|
||||
{
|
||||
return $this->properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets field values.
|
||||
*
|
||||
* @param string[]|string $values Value(s)
|
||||
* @return $this
|
||||
*/
|
||||
public function setValues($values)
|
||||
{
|
||||
if (!is_array($values)) {
|
||||
$values = preg_split('/,\s*/', $values) ?: [];
|
||||
}
|
||||
$this->values = $values;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets field values
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function getValues(): ?array
|
||||
{
|
||||
return $this->values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column collation.
|
||||
*
|
||||
* @param string $collation Collation
|
||||
* @return $this
|
||||
*/
|
||||
public function setCollation(string $collation)
|
||||
{
|
||||
$this->collation = $collation;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column collation.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCollation(): ?string
|
||||
{
|
||||
return $this->collation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column character set.
|
||||
*
|
||||
* @param string $encoding Encoding
|
||||
* @return $this
|
||||
*/
|
||||
public function setEncoding(string $encoding)
|
||||
{
|
||||
$this->encoding = $encoding;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column character set.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getEncoding(): ?string
|
||||
{
|
||||
return $this->encoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the column SRID.
|
||||
*
|
||||
* @param int $srid SRID
|
||||
* @return $this
|
||||
*/
|
||||
public function setSrid(int $srid)
|
||||
{
|
||||
$this->srid = $srid;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the column SRID.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getSrid(): ?int
|
||||
{
|
||||
return $this->srid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all allowed options. Each option must have a corresponding `setFoo` method.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getValidOptions(): array
|
||||
{
|
||||
return [
|
||||
'limit',
|
||||
'default',
|
||||
'null',
|
||||
'identity',
|
||||
'scale',
|
||||
'after',
|
||||
'update',
|
||||
'comment',
|
||||
'signed',
|
||||
'timezone',
|
||||
'properties',
|
||||
'values',
|
||||
'collation',
|
||||
'encoding',
|
||||
'srid',
|
||||
'seed',
|
||||
'increment',
|
||||
'generated',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all aliased options. Each alias must reference a valid option.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getAliasedOptions(): array
|
||||
{
|
||||
return [
|
||||
'length' => 'limit',
|
||||
'precision' => 'limit',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method that maps an array of column options to this objects methods.
|
||||
*
|
||||
* @param array<string, mixed> $options Options
|
||||
* @throws \RuntimeException
|
||||
* @return $this
|
||||
*/
|
||||
public function setOptions(array $options)
|
||||
{
|
||||
$validOptions = $this->getValidOptions();
|
||||
$aliasOptions = $this->getAliasedOptions();
|
||||
|
||||
if (isset($options['identity']) && $options['identity'] && !isset($options['null'])) {
|
||||
$options['null'] = false;
|
||||
}
|
||||
|
||||
foreach ($options as $option => $value) {
|
||||
if (isset($aliasOptions[$option])) {
|
||||
// proxy alias -> option
|
||||
$option = $aliasOptions[$option];
|
||||
}
|
||||
|
||||
if (!in_array($option, $validOptions, true)) {
|
||||
throw new RuntimeException(sprintf('"%s" is not a valid column option.', $option));
|
||||
}
|
||||
|
||||
$method = 'set' . ucfirst($option);
|
||||
$this->$method($value);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Table;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
class ForeignKey
|
||||
{
|
||||
public const CASCADE = 'CASCADE';
|
||||
public const RESTRICT = 'RESTRICT';
|
||||
public const SET_NULL = 'SET NULL';
|
||||
public const NO_ACTION = 'NO ACTION';
|
||||
|
||||
/**
|
||||
* @var array<string>
|
||||
*/
|
||||
protected static $validOptions = ['delete', 'update', 'constraint'];
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
protected $columns = [];
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Table\Table
|
||||
*/
|
||||
protected $referencedTable;
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
protected $referencedColumns = [];
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $onDelete;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $onUpdate;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $constraint;
|
||||
|
||||
/**
|
||||
* Sets the foreign key columns.
|
||||
*
|
||||
* @param string[]|string $columns Columns
|
||||
* @return $this
|
||||
*/
|
||||
public function setColumns($columns)
|
||||
{
|
||||
$this->columns = is_string($columns) ? [$columns] : $columns;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the foreign key columns.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getColumns(): array
|
||||
{
|
||||
return $this->columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the foreign key referenced table.
|
||||
*
|
||||
* @param \Phinx\Db\Table\Table $table The table this KEY is pointing to
|
||||
* @return $this
|
||||
*/
|
||||
public function setReferencedTable(Table $table)
|
||||
{
|
||||
$this->referencedTable = $table;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the foreign key referenced table.
|
||||
*
|
||||
* @return \Phinx\Db\Table\Table
|
||||
*/
|
||||
public function getReferencedTable(): Table
|
||||
{
|
||||
return $this->referencedTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the foreign key referenced columns.
|
||||
*
|
||||
* @param string[] $referencedColumns Referenced columns
|
||||
* @return $this
|
||||
*/
|
||||
public function setReferencedColumns(array $referencedColumns)
|
||||
{
|
||||
$this->referencedColumns = $referencedColumns;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the foreign key referenced columns.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getReferencedColumns(): array
|
||||
{
|
||||
return $this->referencedColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets ON DELETE action for the foreign key.
|
||||
*
|
||||
* @param string $onDelete On Delete
|
||||
* @return $this
|
||||
*/
|
||||
public function setOnDelete(string $onDelete)
|
||||
{
|
||||
$this->onDelete = $this->normalizeAction($onDelete);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets ON DELETE action for the foreign key.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOnDelete(): ?string
|
||||
{
|
||||
return $this->onDelete;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets ON UPDATE action for the foreign key.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOnUpdate(): ?string
|
||||
{
|
||||
return $this->onUpdate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets ON UPDATE action for the foreign key.
|
||||
*
|
||||
* @param string $onUpdate On Update
|
||||
* @return $this
|
||||
*/
|
||||
public function setOnUpdate(string $onUpdate)
|
||||
{
|
||||
$this->onUpdate = $this->normalizeAction($onUpdate);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets constraint for the foreign key.
|
||||
*
|
||||
* @param string $constraint Constraint
|
||||
* @return $this
|
||||
*/
|
||||
public function setConstraint(string $constraint)
|
||||
{
|
||||
$this->constraint = $constraint;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets constraint name for the foreign key.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getConstraint(): ?string
|
||||
{
|
||||
return $this->constraint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method that maps an array of index options to this objects methods.
|
||||
*
|
||||
* @param array<string, mixed> $options Options
|
||||
* @throws \RuntimeException
|
||||
* @return $this
|
||||
*/
|
||||
public function setOptions(array $options)
|
||||
{
|
||||
foreach ($options as $option => $value) {
|
||||
if (!in_array($option, static::$validOptions, true)) {
|
||||
throw new RuntimeException(sprintf('"%s" is not a valid foreign key option.', $option));
|
||||
}
|
||||
|
||||
// handle $options['delete'] as $options['update']
|
||||
if ($option === 'delete') {
|
||||
$this->setOnDelete($value);
|
||||
} elseif ($option === 'update') {
|
||||
$this->setOnUpdate($value);
|
||||
} else {
|
||||
$method = 'set' . ucfirst($option);
|
||||
$this->$method($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* From passed value checks if it's correct and fixes if needed
|
||||
*
|
||||
* @param string $action Action
|
||||
* @throws \InvalidArgumentException
|
||||
* @return string
|
||||
*/
|
||||
protected function normalizeAction(string $action): string
|
||||
{
|
||||
$constantName = 'static::' . str_replace(' ', '_', strtoupper(trim($action)));
|
||||
if (!defined($constantName)) {
|
||||
throw new InvalidArgumentException('Unknown action passed: ' . $action);
|
||||
}
|
||||
|
||||
return constant($constantName);
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Table;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class Index
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const UNIQUE = 'unique';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const INDEX = 'index';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const FULLTEXT = 'fulltext';
|
||||
|
||||
/**
|
||||
* @var string[]|null
|
||||
*/
|
||||
protected $columns;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $type = self::INDEX;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @var int|array|null
|
||||
*/
|
||||
protected $limit;
|
||||
|
||||
/**
|
||||
* @var string[]|null
|
||||
*/
|
||||
protected $order;
|
||||
|
||||
/**
|
||||
* @var string[]|null
|
||||
*/
|
||||
protected $includedColumns;
|
||||
|
||||
/**
|
||||
* Sets the index columns.
|
||||
*
|
||||
* @param string|string[] $columns Columns
|
||||
* @return $this
|
||||
*/
|
||||
public function setColumns($columns)
|
||||
{
|
||||
$this->columns = is_string($columns) ? [$columns] : $columns;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the index columns.
|
||||
*
|
||||
* @return string[]|null
|
||||
*/
|
||||
public function getColumns(): ?array
|
||||
{
|
||||
return $this->columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the index type.
|
||||
*
|
||||
* @param string $type Type
|
||||
* @return $this
|
||||
*/
|
||||
public function setType(string $type)
|
||||
{
|
||||
$this->type = $type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the index type.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the index name.
|
||||
*
|
||||
* @param string $name Name
|
||||
* @return $this
|
||||
*/
|
||||
public function setName(string $name)
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the index name.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the index limit.
|
||||
*
|
||||
* @param int|array $limit limit value or array of limit value
|
||||
* @return $this
|
||||
*/
|
||||
public function setLimit($limit)
|
||||
{
|
||||
$this->limit = $limit;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the index limit.
|
||||
*
|
||||
* @return int|array|null
|
||||
*/
|
||||
public function getLimit()
|
||||
{
|
||||
return $this->limit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the index columns sort order.
|
||||
*
|
||||
* @param string[] $order column name sort order key value pair
|
||||
* @return $this
|
||||
*/
|
||||
public function setOrder(array $order)
|
||||
{
|
||||
$this->order = $order;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the index columns sort order.
|
||||
*
|
||||
* @return string[]|null
|
||||
*/
|
||||
public function getOrder(): ?array
|
||||
{
|
||||
return $this->order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the index included columns.
|
||||
*
|
||||
* @param string[] $includedColumns Columns
|
||||
* @return $this
|
||||
*/
|
||||
public function setInclude(array $includedColumns)
|
||||
{
|
||||
$this->includedColumns = $includedColumns;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the index included columns.
|
||||
*
|
||||
* @return string[]|null
|
||||
*/
|
||||
public function getInclude(): ?array
|
||||
{
|
||||
return $this->includedColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method that maps an array of index options to this objects methods.
|
||||
*
|
||||
* @param array<string, mixed> $options Options
|
||||
* @throws \RuntimeException
|
||||
* @return $this
|
||||
*/
|
||||
public function setOptions(array $options)
|
||||
{
|
||||
// Valid Options
|
||||
$validOptions = ['type', 'unique', 'name', 'limit', 'order', 'include'];
|
||||
foreach ($options as $option => $value) {
|
||||
if (!in_array($option, $validOptions, true)) {
|
||||
throw new RuntimeException(sprintf('"%s" is not a valid index option.', $option));
|
||||
}
|
||||
|
||||
// handle $options['unique']
|
||||
if (strcasecmp($option, self::UNIQUE) === 0) {
|
||||
if ((bool)$value) {
|
||||
$this->setType(self::UNIQUE);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$method = 'set' . ucfirst($option);
|
||||
$this->$method($value);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Table;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class Table
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected $options;
|
||||
|
||||
/**
|
||||
* @param string $name The table name
|
||||
* @param array<string, mixed> $options The creation options for this table
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function __construct($name, array $options = [])
|
||||
{
|
||||
if (empty($name)) {
|
||||
throw new InvalidArgumentException('Cannot use an empty table name');
|
||||
}
|
||||
|
||||
$this->name = $name;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the table name.
|
||||
*
|
||||
* @param string $name The name of the table
|
||||
* @return $this
|
||||
*/
|
||||
public function setName(string $name)
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the table options
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the table options
|
||||
*
|
||||
* @param array<string, mixed> $options The options for the table creation
|
||||
* @return $this
|
||||
*/
|
||||
public function setOptions(array $options)
|
||||
{
|
||||
$this->options = $options;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Db\Util;
|
||||
|
||||
/**
|
||||
* Contains all the information for running an ALTER command for a table,
|
||||
* and any post-steps required after the fact.
|
||||
*/
|
||||
class AlterInstructions
|
||||
{
|
||||
/**
|
||||
* @var string[] The SQL snippets to be added to an ALTER instruction
|
||||
*/
|
||||
protected $alterParts = [];
|
||||
|
||||
/**
|
||||
* @var (string|callable)[] The SQL commands to be executed after the ALTER instruction
|
||||
*/
|
||||
protected $postSteps = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string[] $alterParts SQL snippets to be added to a single ALTER instruction per table
|
||||
* @param (string|callable)[] $postSteps SQL commands to be executed after the ALTER instruction
|
||||
*/
|
||||
public function __construct(array $alterParts = [], array $postSteps = [])
|
||||
{
|
||||
$this->alterParts = $alterParts;
|
||||
$this->postSteps = $postSteps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds another part to the single ALTER instruction
|
||||
*
|
||||
* @param string $part The SQL snipped to add as part of the ALTER instruction
|
||||
* @return void
|
||||
*/
|
||||
public function addAlter(string $part): void
|
||||
{
|
||||
$this->alterParts[] = $part;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a SQL command to be executed after the ALTER instruction.
|
||||
* This method allows a callable, with will get an empty array as state
|
||||
* for the first time and will pass the return value of the callable to
|
||||
* the next callable, if present.
|
||||
*
|
||||
* This allows to keep a single state across callbacks.
|
||||
*
|
||||
* @param string|callable $sql The SQL to run after, or a callable to execute
|
||||
* @return void
|
||||
*/
|
||||
public function addPostStep($sql): void
|
||||
{
|
||||
$this->postSteps[] = $sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the alter SQL snippets
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getAlterParts(): array
|
||||
{
|
||||
return $this->alterParts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the SQL commands to run after the ALTER instruction
|
||||
*
|
||||
* @return (string|callable)[]
|
||||
*/
|
||||
public function getPostSteps(): array
|
||||
{
|
||||
return $this->postSteps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges another AlterInstructions object to this one
|
||||
*
|
||||
* @param \Phinx\Db\Util\AlterInstructions $other The other collection of instructions to merge in
|
||||
* @return void
|
||||
*/
|
||||
public function merge(AlterInstructions $other): void
|
||||
{
|
||||
$this->alterParts = array_merge($this->alterParts, $other->getAlterParts());
|
||||
$this->postSteps = array_merge($this->postSteps, $other->getPostSteps());
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the ALTER instruction and all of the post steps.
|
||||
*
|
||||
* @param string $alterTemplate The template for the alter instruction
|
||||
* @param callable $executor The function to be used to execute all instructions
|
||||
* @return void
|
||||
*/
|
||||
public function execute(string $alterTemplate, callable $executor): void
|
||||
{
|
||||
if ($this->alterParts) {
|
||||
$alter = sprintf($alterTemplate, implode(', ', $this->alterParts));
|
||||
$executor($alter);
|
||||
}
|
||||
|
||||
$state = [];
|
||||
|
||||
foreach ($this->postSteps as $instruction) {
|
||||
if (is_callable($instruction)) {
|
||||
$state = $instruction($state);
|
||||
continue;
|
||||
}
|
||||
|
||||
$executor($instruction);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Migration;
|
||||
|
||||
use Cake\Database\Query;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Db\Table;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Abstract Migration Class.
|
||||
*
|
||||
* It is expected that the migrations you write extend from this class.
|
||||
*
|
||||
* This abstract class proxies the various database methods to your specified
|
||||
* adapter.
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
abstract class AbstractMigration implements MigrationInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $environment;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $version;
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterInterface|null
|
||||
*/
|
||||
protected $adapter;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Output\OutputInterface|null
|
||||
*/
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Input\InputInterface|null
|
||||
*/
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* Whether this migration is being applied or reverted
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $isMigratingUp = true;
|
||||
|
||||
/**
|
||||
* List of all the table objects created by this migration
|
||||
*
|
||||
* @var array<\Phinx\Db\Table>
|
||||
*/
|
||||
protected $tables = [];
|
||||
|
||||
/**
|
||||
* @param string $environment Environment Detected
|
||||
* @param int $version Migration Version
|
||||
* @param \Symfony\Component\Console\Input\InputInterface|null $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface|null $output Output
|
||||
*/
|
||||
final public function __construct(string $environment, int $version, ?InputInterface $input = null, ?OutputInterface $output = null)
|
||||
{
|
||||
$this->environment = $environment;
|
||||
$this->version = $version;
|
||||
|
||||
if ($input !== null) {
|
||||
$this->setInput($input);
|
||||
}
|
||||
|
||||
if ($output !== null) {
|
||||
$this->setOutput($output);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter): MigrationInterface
|
||||
{
|
||||
$this->adapter = $adapter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapter(): ?AdapterInterface
|
||||
{
|
||||
return $this->adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setInput(InputInterface $input): MigrationInterface
|
||||
{
|
||||
$this->input = $input;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getInput(): ?InputInterface
|
||||
{
|
||||
return $this->input;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOutput(OutputInterface $output): MigrationInterface
|
||||
{
|
||||
$this->output = $output;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOutput(): ?OutputInterface
|
||||
{
|
||||
return $this->output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return static::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getEnvironment(): string
|
||||
{
|
||||
return $this->environment;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setVersion($version): MigrationInterface
|
||||
{
|
||||
$this->version = $version;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getVersion(): int
|
||||
{
|
||||
return $this->version;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setMigratingUp(bool $isMigratingUp): MigrationInterface
|
||||
{
|
||||
$this->isMigratingUp = $isMigratingUp;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function isMigratingUp(): bool
|
||||
{
|
||||
return $this->isMigratingUp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int
|
||||
{
|
||||
return $this->getAdapter()->execute($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function query(string $sql, array $params = [])
|
||||
{
|
||||
return $this->getAdapter()->query($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getQueryBuilder(): Query
|
||||
{
|
||||
return $this->getAdapter()->getQueryBuilder();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function fetchRow(string $sql)
|
||||
{
|
||||
return $this->getAdapter()->fetchRow($sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function fetchAll(string $sql): array
|
||||
{
|
||||
return $this->getAdapter()->fetchAll($sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createDatabase(string $name, array $options): void
|
||||
{
|
||||
$this->getAdapter()->createDatabase($name, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function dropDatabase(string $name): void
|
||||
{
|
||||
$this->getAdapter()->dropDatabase($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function createSchema(string $name): void
|
||||
{
|
||||
$this->getAdapter()->createSchema($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function dropSchema(string $name): void
|
||||
{
|
||||
$this->getAdapter()->dropSchema($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasTable(string $tableName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasTable($tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function table(string $tableName, array $options = []): Table
|
||||
{
|
||||
$table = new Table($tableName, $options, $this->getAdapter());
|
||||
$this->tables[] = $table;
|
||||
|
||||
return $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform checks on the migration, print a warning
|
||||
* if there are potential problems.
|
||||
*
|
||||
* Right now, the only check is if there is both a `change()` and
|
||||
* an `up()` or a `down()` method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function preFlightCheck(): void
|
||||
{
|
||||
if (method_exists($this, MigrationInterface::CHANGE)) {
|
||||
if (
|
||||
method_exists($this, MigrationInterface::UP) ||
|
||||
method_exists($this, MigrationInterface::DOWN)
|
||||
) {
|
||||
$this->output->writeln(sprintf(
|
||||
'<comment>warning</comment> Migration contains both change() and up()/down() methods. <options=bold>Ignoring up() and down()</>.'
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform checks on the migration after completion
|
||||
*
|
||||
* Right now, the only check is whether all changes were committed
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* @return void
|
||||
*/
|
||||
public function postFlightCheck(): void
|
||||
{
|
||||
foreach ($this->tables as $table) {
|
||||
if ($table->hasPendingActions()) {
|
||||
throw new RuntimeException('Migration has pending actions after execution!');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if the migration should be executed.
|
||||
*
|
||||
* Returns true by default.
|
||||
*
|
||||
* You can use this to prevent a migration from executing.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function shouldExecute(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Migration;
|
||||
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
abstract class AbstractTemplateCreation implements CreationInterface
|
||||
{
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Input\InputInterface
|
||||
*/
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Output\OutputInterface
|
||||
*/
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* @param \Symfony\Component\Console\Input\InputInterface|null $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface|null $output Output
|
||||
*/
|
||||
public function __construct(?InputInterface $input = null, ?OutputInterface $output = null)
|
||||
{
|
||||
if ($input !== null) {
|
||||
$this->setInput($input);
|
||||
}
|
||||
if ($output !== null) {
|
||||
$this->setOutput($output);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getInput(): InputInterface
|
||||
{
|
||||
return $this->input;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setInput(InputInterface $input): CreationInterface
|
||||
{
|
||||
$this->input = $input;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOutput(): OutputInterface
|
||||
{
|
||||
return $this->output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOutput(OutputInterface $output): CreationInterface
|
||||
{
|
||||
$this->output = $output;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Migration;
|
||||
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Migration interface
|
||||
*
|
||||
* @author Richard Quadling <RQuadling@GMail.com>
|
||||
*/
|
||||
interface CreationInterface
|
||||
{
|
||||
/**
|
||||
* @param \Symfony\Component\Console\Input\InputInterface|null $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface|null $output Output
|
||||
*/
|
||||
public function __construct(?InputInterface $input = null, ?OutputInterface $output = null);
|
||||
|
||||
/**
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @return $this
|
||||
*/
|
||||
public function setInput(InputInterface $input);
|
||||
|
||||
/**
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return $this
|
||||
*/
|
||||
public function setOutput(OutputInterface $output);
|
||||
|
||||
/**
|
||||
* @return \Symfony\Component\Console\Input\InputInterface
|
||||
*/
|
||||
public function getInput(): InputInterface;
|
||||
|
||||
/**
|
||||
* @return \Symfony\Component\Console\Output\OutputInterface
|
||||
*/
|
||||
public function getOutput(): OutputInterface;
|
||||
|
||||
/**
|
||||
* Get the migration template.
|
||||
*
|
||||
* This will be the content that Phinx will amend to generate the migration file.
|
||||
*
|
||||
* @return string The content of the template for Phinx to amend.
|
||||
*/
|
||||
public function getMigrationTemplate(): string;
|
||||
|
||||
/**
|
||||
* Post Migration Creation.
|
||||
*
|
||||
* Once the migration file has been created, this method will be called, allowing any additional
|
||||
* processing, specific to the template to be performed.
|
||||
*
|
||||
* @param string $migrationFilename The name of the newly created migration.
|
||||
* @param string $className The class name.
|
||||
* @param string $baseClassName The name of the base class.
|
||||
* @return void
|
||||
*/
|
||||
public function postMigrationCreation(string $migrationFilename, string $className, string $baseClassName): void;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Migration;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Exception class thrown when migrations cannot be reversed using the 'change'
|
||||
* feature.
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
class IrreversibleMigrationException extends Exception
|
||||
{
|
||||
}
|
||||
+1141
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,397 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Migration\Manager;
|
||||
|
||||
use PDO;
|
||||
use Phinx\Db\Adapter\AdapterFactory;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Migration\MigrationInterface;
|
||||
use Phinx\Seed\SeedInterface;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class Environment
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected $options;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Input\InputInterface|null
|
||||
*/
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Output\OutputInterface|null
|
||||
*/
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $currentVersion;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $schemaTableName = 'phinxlog';
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
protected $adapter;
|
||||
|
||||
/**
|
||||
* @param string $name Environment Name
|
||||
* @param array<string, mixed> $options Options
|
||||
*/
|
||||
public function __construct(string $name, array $options)
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the specified migration on this environment.
|
||||
*
|
||||
* @param \Phinx\Migration\MigrationInterface $migration Migration
|
||||
* @param string $direction Direction
|
||||
* @param bool $fake flag that if true, we just record running the migration, but not actually do the migration
|
||||
* @return void
|
||||
*/
|
||||
public function executeMigration(MigrationInterface $migration, string $direction = MigrationInterface::UP, bool $fake = false): void
|
||||
{
|
||||
$direction = $direction === MigrationInterface::UP ? MigrationInterface::UP : MigrationInterface::DOWN;
|
||||
$migration->setMigratingUp($direction === MigrationInterface::UP);
|
||||
|
||||
$startTime = time();
|
||||
$migration->setAdapter($this->getAdapter());
|
||||
|
||||
$migration->preFlightCheck();
|
||||
|
||||
if (method_exists($migration, MigrationInterface::INIT)) {
|
||||
$migration->{MigrationInterface::INIT}();
|
||||
}
|
||||
|
||||
if (!$fake) {
|
||||
// begin the transaction if the adapter supports it
|
||||
if ($this->getAdapter()->hasTransactions()) {
|
||||
$this->getAdapter()->beginTransaction();
|
||||
}
|
||||
|
||||
// Run the migration
|
||||
if (method_exists($migration, MigrationInterface::CHANGE)) {
|
||||
if ($direction === MigrationInterface::DOWN) {
|
||||
// Create an instance of the ProxyAdapter so we can record all
|
||||
// of the migration commands for reverse playback
|
||||
|
||||
/** @var \Phinx\Db\Adapter\ProxyAdapter $proxyAdapter */
|
||||
$proxyAdapter = AdapterFactory::instance()
|
||||
->getWrapper('proxy', $this->getAdapter());
|
||||
$migration->setAdapter($proxyAdapter);
|
||||
$migration->{MigrationInterface::CHANGE}();
|
||||
$proxyAdapter->executeInvertedCommands();
|
||||
$migration->setAdapter($this->getAdapter());
|
||||
} else {
|
||||
$migration->{MigrationInterface::CHANGE}();
|
||||
}
|
||||
} else {
|
||||
$migration->{$direction}();
|
||||
}
|
||||
|
||||
// Record it in the database
|
||||
$this->getAdapter()->migrated($migration, $direction, date('Y-m-d H:i:s', $startTime), date('Y-m-d H:i:s', time()));
|
||||
|
||||
// commit the transaction if the adapter supports it
|
||||
if ($this->getAdapter()->hasTransactions()) {
|
||||
$this->getAdapter()->commitTransaction();
|
||||
}
|
||||
}
|
||||
$migration->postFlightCheck();
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the specified seeder on this environment.
|
||||
*
|
||||
* @param \Phinx\Seed\SeedInterface $seed Seed
|
||||
* @return void
|
||||
*/
|
||||
public function executeSeed(SeedInterface $seed): void
|
||||
{
|
||||
$seed->setAdapter($this->getAdapter());
|
||||
if (method_exists($seed, SeedInterface::INIT)) {
|
||||
$seed->{SeedInterface::INIT}();
|
||||
}
|
||||
|
||||
// begin the transaction if the adapter supports it
|
||||
if ($this->getAdapter()->hasTransactions()) {
|
||||
$this->getAdapter()->beginTransaction();
|
||||
}
|
||||
|
||||
// Run the seeder
|
||||
if (method_exists($seed, SeedInterface::RUN)) {
|
||||
$seed->{SeedInterface::RUN}();
|
||||
}
|
||||
|
||||
// commit the transaction if the adapter supports it
|
||||
if ($this->getAdapter()->hasTransactions()) {
|
||||
$this->getAdapter()->commitTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the environment's name.
|
||||
*
|
||||
* @param string $name Environment Name
|
||||
* @return $this
|
||||
*/
|
||||
public function setName(string $name)
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the environment name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the environment's options.
|
||||
*
|
||||
* @param array<string, mixed> $options Environment Options
|
||||
* @return $this
|
||||
*/
|
||||
public function setOptions(array $options)
|
||||
{
|
||||
$this->options = $options;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the environment's options.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the console input.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @return $this
|
||||
*/
|
||||
public function setInput(InputInterface $input)
|
||||
{
|
||||
$this->input = $input;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the console input.
|
||||
*
|
||||
* @return \Symfony\Component\Console\Input\InputInterface|null
|
||||
*/
|
||||
public function getInput(): ?InputInterface
|
||||
{
|
||||
return $this->input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the console output.
|
||||
*
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return $this
|
||||
*/
|
||||
public function setOutput(OutputInterface $output)
|
||||
{
|
||||
$this->output = $output;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the console output.
|
||||
*
|
||||
* @return \Symfony\Component\Console\Output\OutputInterface|null
|
||||
*/
|
||||
public function getOutput(): ?OutputInterface
|
||||
{
|
||||
return $this->output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all migrated version numbers.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getVersions(): array
|
||||
{
|
||||
return $this->getAdapter()->getVersions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all migration log entries, indexed by version creation time and sorted in ascending order by the configuration's
|
||||
* version_order option
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getVersionLog(): array
|
||||
{
|
||||
return $this->getAdapter()->getVersionLog();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current version of the environment.
|
||||
*
|
||||
* @param int $version Environment Version
|
||||
* @return $this
|
||||
*/
|
||||
public function setCurrentVersion(int $version)
|
||||
{
|
||||
$this->currentVersion = $version;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current version of the environment.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getCurrentVersion(): int
|
||||
{
|
||||
// We don't cache this code as the current version is pretty volatile.
|
||||
// that means they're no point in a setter then?
|
||||
// maybe we should cache and call a reset() method every time a migration is run
|
||||
$versions = $this->getVersions();
|
||||
$version = 0;
|
||||
|
||||
if (!empty($versions)) {
|
||||
$version = end($versions);
|
||||
}
|
||||
|
||||
$this->setCurrentVersion($version);
|
||||
|
||||
return $this->currentVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database adapter.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
|
||||
* @return $this
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter)
|
||||
{
|
||||
$this->adapter = $adapter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the database adapter.
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface
|
||||
{
|
||||
if (isset($this->adapter)) {
|
||||
return $this->adapter;
|
||||
}
|
||||
|
||||
$options = $this->getOptions();
|
||||
if (isset($options['connection'])) {
|
||||
if (!($options['connection'] instanceof PDO)) {
|
||||
throw new RuntimeException('The specified connection is not a PDO instance');
|
||||
}
|
||||
|
||||
$options['connection']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$options['adapter'] = $options['connection']->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
}
|
||||
if (!isset($options['adapter'])) {
|
||||
throw new RuntimeException('No adapter was specified for environment: ' . $this->getName());
|
||||
}
|
||||
|
||||
$factory = AdapterFactory::instance();
|
||||
$adapter = $factory
|
||||
->getAdapter($options['adapter'], $options);
|
||||
|
||||
// Automatically time the executed commands
|
||||
$adapter = $factory->getWrapper('timed', $adapter);
|
||||
|
||||
if (isset($options['wrapper'])) {
|
||||
$adapter = $factory
|
||||
->getWrapper($options['wrapper'], $adapter);
|
||||
}
|
||||
|
||||
/** @var \Symfony\Component\Console\Input\InputInterface|null $input */
|
||||
$input = $this->getInput();
|
||||
if ($input) {
|
||||
$adapter->setInput($this->getInput());
|
||||
}
|
||||
|
||||
/** @var \Symfony\Component\Console\Output\OutputInterface|null $output */
|
||||
$output = $this->getOutput();
|
||||
if ($output) {
|
||||
$adapter->setOutput($this->getOutput());
|
||||
}
|
||||
|
||||
// Use the TablePrefixAdapter if table prefix/suffixes are in use
|
||||
if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
|
||||
$adapter = AdapterFactory::instance()
|
||||
->getWrapper('prefix', $adapter);
|
||||
}
|
||||
|
||||
$this->setAdapter($adapter);
|
||||
|
||||
return $adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the schema table name.
|
||||
*
|
||||
* @param string $schemaTableName Schema Table Name
|
||||
* @return $this
|
||||
*/
|
||||
public function setSchemaTableName($schemaTableName)
|
||||
{
|
||||
$this->schemaTableName = $schemaTableName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the schema table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSchemaTableName(): string
|
||||
{
|
||||
return $this->schemaTableName;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
$namespaceDefinition
|
||||
use $useClassName;
|
||||
|
||||
final class $className extends $baseClassName
|
||||
{
|
||||
/**
|
||||
* Change Method.
|
||||
*
|
||||
* Write your reversible migrations using this method.
|
||||
*
|
||||
* More information on writing migrations is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
|
||||
*
|
||||
* Remember to call "create()" or "update()" and NOT "save()" when working
|
||||
* with the Table class.
|
||||
*/
|
||||
public function change(): void
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
$namespaceDefinition
|
||||
use $useClassName;
|
||||
|
||||
final class $className extends $baseClassName
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Migration;
|
||||
|
||||
use Cake\Database\Query;
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Db\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Migration interface
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
interface MigrationInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const CHANGE = 'change';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const UP = 'up';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const DOWN = 'down';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const INIT = 'init';
|
||||
|
||||
/**
|
||||
* Sets the database adapter.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
|
||||
* @return $this
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter);
|
||||
|
||||
/**
|
||||
* Gets the database adapter.
|
||||
*
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface|null
|
||||
*/
|
||||
public function getAdapter(): ?AdapterInterface;
|
||||
|
||||
/**
|
||||
* Sets the input object to be used in migration object
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @return $this
|
||||
*/
|
||||
public function setInput(InputInterface $input);
|
||||
|
||||
/**
|
||||
* Gets the input object to be used in migration object
|
||||
*
|
||||
* @return \Symfony\Component\Console\Input\InputInterface|null
|
||||
*/
|
||||
public function getInput(): ?InputInterface;
|
||||
|
||||
/**
|
||||
* Sets the output object to be used in migration object
|
||||
*
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return $this
|
||||
*/
|
||||
public function setOutput(OutputInterface $output);
|
||||
|
||||
/**
|
||||
* Gets the output object to be used in migration object
|
||||
*
|
||||
* @return \Symfony\Component\Console\Output\OutputInterface|null
|
||||
*/
|
||||
public function getOutput(): ?OutputInterface;
|
||||
|
||||
/**
|
||||
* Gets the name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string;
|
||||
|
||||
/**
|
||||
* Gets the detected environment
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getEnvironment(): string;
|
||||
|
||||
/**
|
||||
* Sets the migration version number.
|
||||
*
|
||||
* @param int $version Version
|
||||
* @return $this
|
||||
*/
|
||||
public function setVersion(int $version);
|
||||
|
||||
/**
|
||||
* Gets the migration version number.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getVersion(): int;
|
||||
|
||||
/**
|
||||
* Sets whether this migration is being applied or reverted
|
||||
*
|
||||
* @param bool $isMigratingUp True if the migration is being applied
|
||||
* @return $this
|
||||
*/
|
||||
public function setMigratingUp(bool $isMigratingUp);
|
||||
|
||||
/**
|
||||
* Gets whether this migration is being applied or reverted.
|
||||
* True means that the migration is being applied.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isMigratingUp(): bool;
|
||||
|
||||
/**
|
||||
* Executes a SQL statement and returns the number of affected rows.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @param array $params parameters to use for prepared query
|
||||
* @return int
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int;
|
||||
|
||||
/**
|
||||
* Executes a SQL statement.
|
||||
*
|
||||
* The return type depends on the underlying adapter being used. To improve
|
||||
* IDE auto-completion possibility, you can overwrite the query method
|
||||
* phpDoc in your (typically custom abstract parent) migration class, where
|
||||
* you can set the return type by the adapter in your current use.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @param array $params parameters to use for prepared query
|
||||
* @return mixed
|
||||
*/
|
||||
public function query(string $sql, array $params = []);
|
||||
|
||||
/**
|
||||
* Returns a new Query object that can be used to build complex SELECT, UPDATE, INSERT or DELETE
|
||||
* queries and execute them against the current database.
|
||||
*
|
||||
* Queries executed through the query builder are always sent to the database, regardless of the
|
||||
* the dry-run settings.
|
||||
*
|
||||
* @see https://api.cakephp.org/3.6/class-Cake.Database.Query.html
|
||||
* @return \Cake\Database\Query
|
||||
*/
|
||||
public function getQueryBuilder(): Query;
|
||||
|
||||
/**
|
||||
* Executes a query and returns only one row as an array.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @return array|false
|
||||
*/
|
||||
public function fetchRow(string $sql);
|
||||
|
||||
/**
|
||||
* Executes a query and returns an array of rows.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @return array
|
||||
*/
|
||||
public function fetchAll(string $sql): array;
|
||||
|
||||
/**
|
||||
* Create a new database.
|
||||
*
|
||||
* @param string $name Database Name
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return void
|
||||
*/
|
||||
public function createDatabase(string $name, array $options): void;
|
||||
|
||||
/**
|
||||
* Drop a database.
|
||||
*
|
||||
* @param string $name Database Name
|
||||
* @return void
|
||||
*/
|
||||
public function dropDatabase(string $name): void;
|
||||
|
||||
/**
|
||||
* Creates schema.
|
||||
*
|
||||
* This will thrown an error for adapters that do not support schemas.
|
||||
*
|
||||
* @param string $name Schema name
|
||||
* @return void
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
public function createSchema(string $name): void;
|
||||
|
||||
/**
|
||||
* Drops schema.
|
||||
*
|
||||
* This will thrown an error for adapters that do not support schemas.
|
||||
*
|
||||
* @param string $name Schema name
|
||||
* @return void
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
public function dropSchema(string $name): void;
|
||||
|
||||
/**
|
||||
* Checks to see if a table exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasTable(string $tableName): bool;
|
||||
|
||||
/**
|
||||
* Returns an instance of the <code>\Table</code> class.
|
||||
*
|
||||
* You can use this class to create and manipulate tables.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return \Phinx\Db\Table
|
||||
*/
|
||||
public function table(string $tableName, array $options): Table;
|
||||
|
||||
/**
|
||||
* Perform checks on the migration, printing a warning
|
||||
* if there are potential problems.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function preFlightCheck(): void;
|
||||
|
||||
/**
|
||||
* Perform checks on the migration after completion
|
||||
*
|
||||
* Right now, the only check is whether all changes were committed
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function postFlightCheck(): void;
|
||||
|
||||
/**
|
||||
* Checks to see if the migration should be executed.
|
||||
*
|
||||
* Returns true by default.
|
||||
*
|
||||
* You can use this to prevent a migration from executing.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function shouldExecute(): bool;
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Seed;
|
||||
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Phinx\Db\Table;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Abstract Seed Class.
|
||||
*
|
||||
* It is expected that the seeds you write extend from this class.
|
||||
*
|
||||
* This abstract class proxies the various database methods to your specified
|
||||
* adapter.
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
abstract class AbstractSeed implements SeedInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $environment;
|
||||
|
||||
/**
|
||||
* @var \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
protected $adapter;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Input\InputInterface
|
||||
*/
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Console\Output\OutputInterface
|
||||
*/
|
||||
protected $output;
|
||||
|
||||
/**
|
||||
* Override to specify dependencies for dependency injection from the configured PSR-11 container
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setEnvironment(string $environment)
|
||||
{
|
||||
$this->environment = $environment;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getEnvironment(): string
|
||||
{
|
||||
return $this->environment;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter): SeedInterface
|
||||
{
|
||||
$this->adapter = $adapter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface
|
||||
{
|
||||
return $this->adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setInput(InputInterface $input)
|
||||
{
|
||||
$this->input = $input;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getInput(): InputInterface
|
||||
{
|
||||
return $this->input;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOutput(OutputInterface $output): SeedInterface
|
||||
{
|
||||
$this->output = $output;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getOutput(): OutputInterface
|
||||
{
|
||||
return $this->output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return static::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function execute(string $sql, array $params = [])
|
||||
{
|
||||
return $this->getAdapter()->execute($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function query(string $sql, array $params = [])
|
||||
{
|
||||
return $this->getAdapter()->query($sql, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function fetchRow(string $sql)
|
||||
{
|
||||
return $this->getAdapter()->fetchRow($sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function fetchAll(string $sql): array
|
||||
{
|
||||
return $this->getAdapter()->fetchAll($sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function insert(string $table, array $data): void
|
||||
{
|
||||
// convert to table object
|
||||
if (is_string($table)) {
|
||||
$table = new Table($table, [], $this->getAdapter());
|
||||
}
|
||||
$table->insert($data)->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function hasTable(string $tableName): bool
|
||||
{
|
||||
return $this->getAdapter()->hasTable($tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function table(string $tableName, array $options = []): Table
|
||||
{
|
||||
return new Table($tableName, $options, $this->getAdapter());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if the seed should be executed.
|
||||
*
|
||||
* Returns true by default.
|
||||
*
|
||||
* You can use this to prevent a seed from executing.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function shouldExecute(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
$namespaceDefinition
|
||||
|
||||
use $useClassName;
|
||||
|
||||
class $className extends $baseClassName
|
||||
{
|
||||
/**
|
||||
* Run Method.
|
||||
*
|
||||
* Write your database seeder using this method.
|
||||
*
|
||||
* More information on writing seeders is available here:
|
||||
* https://book.cakephp.org/phinx/0/en/seeding.html
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Seed;
|
||||
|
||||
use Phinx\Db\Adapter\AdapterInterface;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
/**
|
||||
* Seed interface
|
||||
*
|
||||
* @author Rob Morgan <robbym@gmail.com>
|
||||
*/
|
||||
interface SeedInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const RUN = 'run';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const INIT = 'init';
|
||||
|
||||
/**
|
||||
* Run the seeder.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function run(): void;
|
||||
|
||||
/**
|
||||
* Return seeds dependencies.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDependencies(): array;
|
||||
|
||||
/**
|
||||
* Sets the environment.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function setEnvironment(string $environment);
|
||||
|
||||
/**
|
||||
* Gets the environment.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getEnvironment(): string;
|
||||
|
||||
/**
|
||||
* Sets the database adapter.
|
||||
*
|
||||
* @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
|
||||
* @return $this
|
||||
*/
|
||||
public function setAdapter(AdapterInterface $adapter);
|
||||
|
||||
/**
|
||||
* Gets the database adapter.
|
||||
*
|
||||
* @return \Phinx\Db\Adapter\AdapterInterface
|
||||
*/
|
||||
public function getAdapter(): AdapterInterface;
|
||||
|
||||
/**
|
||||
* Sets the input object to be used in migration object
|
||||
*
|
||||
* @param \Symfony\Component\Console\Input\InputInterface $input Input
|
||||
* @return $this
|
||||
*/
|
||||
public function setInput(InputInterface $input);
|
||||
|
||||
/**
|
||||
* Gets the input object to be used in migration object
|
||||
*
|
||||
* @return \Symfony\Component\Console\Input\InputInterface
|
||||
*/
|
||||
public function getInput(): InputInterface;
|
||||
|
||||
/**
|
||||
* Sets the output object to be used in migration object
|
||||
*
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface $output Output
|
||||
* @return $this
|
||||
*/
|
||||
public function setOutput(OutputInterface $output);
|
||||
|
||||
/**
|
||||
* Gets the output object to be used in migration object
|
||||
*
|
||||
* @return \Symfony\Component\Console\Output\OutputInterface
|
||||
*/
|
||||
public function getOutput(): OutputInterface;
|
||||
|
||||
/**
|
||||
* Gets the name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string;
|
||||
|
||||
/**
|
||||
* Executes a SQL statement and returns the number of affected rows.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @param array $params parameters to use for prepared query
|
||||
* @return int
|
||||
*/
|
||||
public function execute(string $sql, array $params = []);
|
||||
|
||||
/**
|
||||
* Executes a SQL statement.
|
||||
*
|
||||
* The return type depends on the underlying adapter being used. To improve
|
||||
* IDE auto-completion possibility, you can overwrite the query method
|
||||
* phpDoc in your (typically custom abstract parent) seed class, where
|
||||
* you can set the return type by the adapter in your current use.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @param array $params parameters to use for prepared query
|
||||
* @return mixed
|
||||
*/
|
||||
public function query(string $sql, array $params = []);
|
||||
|
||||
/**
|
||||
* Executes a query and returns only one row as an array.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @return array|false
|
||||
*/
|
||||
public function fetchRow(string $sql);
|
||||
|
||||
/**
|
||||
* Executes a query and returns an array of rows.
|
||||
*
|
||||
* @param string $sql SQL
|
||||
* @return array
|
||||
*/
|
||||
public function fetchAll(string $sql): array;
|
||||
|
||||
/**
|
||||
* Insert data into a table.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param array $data Data
|
||||
* @return void
|
||||
*/
|
||||
public function insert(string $tableName, array $data): void;
|
||||
|
||||
/**
|
||||
* Checks to see if a table exists.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasTable(string $tableName): bool;
|
||||
|
||||
/**
|
||||
* Returns an instance of the <code>\Table</code> class.
|
||||
*
|
||||
* You can use this class to create and manipulate tables.
|
||||
*
|
||||
* @param string $tableName Table name
|
||||
* @param array<string, mixed> $options Options
|
||||
* @return \Phinx\Db\Table
|
||||
*/
|
||||
public function table(string $tableName, array $options): \Phinx\Db\Table;
|
||||
|
||||
/**
|
||||
* Checks to see if the seed should be executed.
|
||||
*
|
||||
* Returns true by default.
|
||||
*
|
||||
* You can use this to prevent a seed from executing.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function shouldExecute(): bool;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Util;
|
||||
|
||||
class Expression
|
||||
{
|
||||
/**
|
||||
* @var string The expression
|
||||
*/
|
||||
protected $value;
|
||||
|
||||
/**
|
||||
* @param string $value The expression
|
||||
*/
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Returns the expression
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value The expression
|
||||
* @return self
|
||||
*/
|
||||
public static function from(string $value): Expression
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Util;
|
||||
|
||||
class Literal
|
||||
{
|
||||
/**
|
||||
* @var string The literal's value
|
||||
*/
|
||||
protected $value;
|
||||
|
||||
/**
|
||||
* @param string $value The literal's value
|
||||
*/
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Returns the literal's value
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value The literal's value
|
||||
* @return self
|
||||
*/
|
||||
public static function from(string $value): Literal
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
}
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Util;
|
||||
|
||||
use DateTime;
|
||||
use DateTimeZone;
|
||||
use Exception;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class Util
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const DATE_FORMAT = 'YmdHis';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected const MIGRATION_FILE_NAME_PATTERN = '/^\d+_([a-z][a-z\d]*(?:_[a-z\d]+)*)\.php$/i';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected const MIGRATION_FILE_NAME_NO_NAME_PATTERN = '/^[0-9]{14}\.php$/';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected const SEED_FILE_NAME_PATTERN = '/^([a-z][a-z\d]*)\.php$/i';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected const CLASS_NAME_PATTERN = '/^(?:[A-Z][a-z\d]*)+$/';
|
||||
|
||||
/**
|
||||
* Gets the current timestamp string, in UTC.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function getCurrentTimestamp(): string
|
||||
{
|
||||
$dt = new DateTime('now', new DateTimeZone('UTC'));
|
||||
|
||||
return $dt->format(static::DATE_FORMAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of all the existing migration class names.
|
||||
*
|
||||
* @param string $path Path
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getExistingMigrationClassNames(string $path): array
|
||||
{
|
||||
$classNames = [];
|
||||
|
||||
if (!is_dir($path)) {
|
||||
return $classNames;
|
||||
}
|
||||
|
||||
// filter the files to only get the ones that match our naming scheme
|
||||
$phpFiles = static::getFiles($path);
|
||||
|
||||
foreach ($phpFiles as $filePath) {
|
||||
$fileName = basename($filePath);
|
||||
if (preg_match(static::MIGRATION_FILE_NAME_PATTERN, $fileName)) {
|
||||
$classNames[] = static::mapFileNameToClassName($fileName);
|
||||
}
|
||||
}
|
||||
|
||||
return $classNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the version from the beginning of a file name.
|
||||
*
|
||||
* @param string $fileName File Name
|
||||
* @return int
|
||||
*/
|
||||
public static function getVersionFromFileName(string $fileName): int
|
||||
{
|
||||
$matches = [];
|
||||
preg_match('/^[0-9]+/', basename($fileName), $matches);
|
||||
$value = (int)($matches[0] ?? null);
|
||||
if (!$value) {
|
||||
throw new RuntimeException(sprintf('Cannot get a valid version from filename `%s`', $fileName));
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn migration names like 'CreateUserTable' into file names like
|
||||
* '12345678901234_create_user_table.php' or 'LimitResourceNamesTo30Chars' into
|
||||
* '12345678901234_limit_resource_names_to_30_chars.php'.
|
||||
*
|
||||
* @param string $className Class Name
|
||||
* @return string
|
||||
*/
|
||||
public static function mapClassNameToFileName(string $className): string
|
||||
{
|
||||
$snake = function ($matches) {
|
||||
return '_' . strtolower($matches[0]);
|
||||
};
|
||||
$fileName = preg_replace_callback('/\d+|[A-Z]/', $snake, $className);
|
||||
$fileName = static::getCurrentTimestamp() . "$fileName.php";
|
||||
|
||||
return $fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn file names like '12345678901234_create_user_table.php' into class
|
||||
* names like 'CreateUserTable'.
|
||||
*
|
||||
* @param string $fileName File Name
|
||||
* @return string
|
||||
*/
|
||||
public static function mapFileNameToClassName(string $fileName): string
|
||||
{
|
||||
$matches = [];
|
||||
if (preg_match(static::MIGRATION_FILE_NAME_PATTERN, $fileName, $matches)) {
|
||||
$fileName = $matches[1];
|
||||
} elseif (preg_match(static::MIGRATION_FILE_NAME_NO_NAME_PATTERN, $fileName)) {
|
||||
return 'V' . substr($fileName, 0, strlen($fileName) - 4);
|
||||
}
|
||||
|
||||
$className = str_replace('_', '', ucwords($fileName, '_'));
|
||||
|
||||
return $className;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a migration class name is unique regardless of the
|
||||
* timestamp.
|
||||
*
|
||||
* This method takes a class name and a path to a migrations directory.
|
||||
*
|
||||
* Migration class names must be in PascalCase format but consecutive
|
||||
* capitals are allowed.
|
||||
* e.g: AddIndexToPostsTable or CustomHTMLTitle.
|
||||
*
|
||||
* @param string $className Class Name
|
||||
* @param string $path Path
|
||||
* @return bool
|
||||
*/
|
||||
public static function isUniqueMigrationClassName(string $className, string $path): bool
|
||||
{
|
||||
$existingClassNames = static::getExistingMigrationClassNames($path);
|
||||
|
||||
return !in_array($className, $existingClassNames, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a migration/seed class name is valid.
|
||||
*
|
||||
* Migration & Seed class names must be in CamelCase format.
|
||||
* e.g: CreateUserTable, AddIndexToPostsTable or UserSeeder.
|
||||
*
|
||||
* Single words are not allowed on their own.
|
||||
*
|
||||
* @param string $className Class Name
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidPhinxClassName(string $className): bool
|
||||
{
|
||||
return (bool)preg_match(static::CLASS_NAME_PATTERN, $className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a migration file name is valid.
|
||||
*
|
||||
* @param string $fileName File Name
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidMigrationFileName(string $fileName): bool
|
||||
{
|
||||
return (bool)preg_match(static::MIGRATION_FILE_NAME_PATTERN, $fileName)
|
||||
|| (bool)preg_match(static::MIGRATION_FILE_NAME_NO_NAME_PATTERN, $fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a seed file name is valid.
|
||||
*
|
||||
* @param string $fileName File Name
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidSeedFileName(string $fileName): bool
|
||||
{
|
||||
return (bool)preg_match(static::SEED_FILE_NAME_PATTERN, $fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expands a set of paths with curly braces (if supported by the OS).
|
||||
*
|
||||
* @param string[] $paths Paths
|
||||
* @return string[]
|
||||
*/
|
||||
public static function globAll(array $paths): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($paths as $path) {
|
||||
$result = array_merge($result, static::glob($path));
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expands a path with curly braces (if supported by the OS).
|
||||
*
|
||||
* @param string $path Path
|
||||
* @return string[]
|
||||
*/
|
||||
public static function glob(string $path): array
|
||||
{
|
||||
return glob($path, defined('GLOB_BRACE') ? GLOB_BRACE : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes the path to a php file and attempts to include it if readable
|
||||
*
|
||||
* @param string $filename Filename
|
||||
* @param \Symfony\Component\Console\Input\InputInterface|null $input Input
|
||||
* @param \Symfony\Component\Console\Output\OutputInterface|null $output Output
|
||||
* @param \Phinx\Console\Command\AbstractCommand|mixed|null $context Context
|
||||
* @throws \Exception
|
||||
* @return string
|
||||
*/
|
||||
public static function loadPhpFile(string $filename, ?InputInterface $input = null, ?OutputInterface $output = null, $context = null): string
|
||||
{
|
||||
$filePath = realpath($filename);
|
||||
if (!file_exists($filePath)) {
|
||||
throw new Exception(sprintf("File does not exist: %s \n", $filename));
|
||||
}
|
||||
|
||||
/**
|
||||
* I lifed this from phpunits FileLoader class
|
||||
*
|
||||
* @see https://github.com/sebastianbergmann/phpunit/pull/2751
|
||||
*/
|
||||
$isReadable = @fopen($filePath, 'r') !== false;
|
||||
|
||||
if (!$isReadable) {
|
||||
throw new Exception(sprintf("Cannot open file %s \n", $filename));
|
||||
}
|
||||
|
||||
// prevent this to be propagated to the included file
|
||||
unset($isReadable);
|
||||
|
||||
include_once $filePath;
|
||||
|
||||
return $filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an array of paths, return all unique PHP files that are in them
|
||||
*
|
||||
* @param string|string[] $paths Path or array of paths to get .php files.
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getFiles($paths): array
|
||||
{
|
||||
$files = static::globAll(array_map(function ($path) {
|
||||
return $path . DIRECTORY_SEPARATOR . '*.php';
|
||||
}, (array)$paths));
|
||||
// glob() can return the same file multiple times
|
||||
// This will cause the migration to fail with a
|
||||
// false assumption of duplicate migrations
|
||||
// https://php.net/manual/en/function.glob.php#110340
|
||||
$files = array_unique($files);
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to remove the current working directory from a path for output.
|
||||
*
|
||||
* @param string $path Path to remove cwd prefix from
|
||||
* @return string
|
||||
*/
|
||||
public static function relativePath(string $path): string
|
||||
{
|
||||
$realpath = realpath($path);
|
||||
if ($realpath !== false) {
|
||||
$path = $realpath;
|
||||
}
|
||||
|
||||
$cwd = getcwd();
|
||||
if ($cwd !== false) {
|
||||
$cwd .= DIRECTORY_SEPARATOR;
|
||||
$cwdLen = strlen($cwd);
|
||||
|
||||
if (substr($path, 0, $cwdLen) === $cwd) {
|
||||
$path = substr($path, $cwdLen);
|
||||
}
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses DSN string into db config array.
|
||||
*
|
||||
* @param string $dsn DSN string
|
||||
* @return array
|
||||
*/
|
||||
public static function parseDsn(string $dsn): array
|
||||
{
|
||||
$pattern = <<<'REGEXP'
|
||||
{
|
||||
^
|
||||
(?:
|
||||
(?P<adapter>[\w\\\\]+)://
|
||||
)
|
||||
(?:
|
||||
(?P<user>.*?)
|
||||
(?:
|
||||
:(?P<pass>.*?)
|
||||
)?
|
||||
@
|
||||
)?
|
||||
(?:
|
||||
(?P<host>[^?#/:@]+)
|
||||
(?:
|
||||
:(?P<port>\d+)
|
||||
)?
|
||||
)?
|
||||
(?:
|
||||
/(?P<name>[^?#]*)
|
||||
)?
|
||||
(?:
|
||||
\?(?P<query>[^#]*)
|
||||
)?
|
||||
$
|
||||
}x
|
||||
REGEXP;
|
||||
|
||||
if (!preg_match($pattern, $dsn, $parsed)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// filter out everything except the matched groups
|
||||
$config = array_intersect_key($parsed, array_flip(['adapter', 'user', 'pass', 'host', 'port', 'name']));
|
||||
$config = array_filter($config);
|
||||
|
||||
parse_str($parsed['query'] ?? '', $query);
|
||||
$config = array_merge($query, $config);
|
||||
|
||||
return $config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MIT License
|
||||
* For full license information, please view the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Phinx\Wrapper;
|
||||
|
||||
use Phinx\Console\PhinxApplication;
|
||||
use Symfony\Component\Console\Input\ArrayInput;
|
||||
use Symfony\Component\Console\Output\StreamOutput;
|
||||
|
||||
/**
|
||||
* Phinx text wrapper: a way to run `status`, `migrate`, and `rollback` commands
|
||||
* and get the output of the command back as plain text.
|
||||
*
|
||||
* @author Woody Gilk <woody.gilk@gmail.com>
|
||||
*/
|
||||
class TextWrapper
|
||||
{
|
||||
/**
|
||||
* @var \Phinx\Console\PhinxApplication
|
||||
*/
|
||||
protected $app;
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected $options;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $exitCode;
|
||||
|
||||
/**
|
||||
* @param \Phinx\Console\PhinxApplication $app Application
|
||||
* @param array<string, mixed> $options Options
|
||||
*/
|
||||
public function __construct(PhinxApplication $app, array $options = [])
|
||||
{
|
||||
$this->app = $app;
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the application instance.
|
||||
*
|
||||
* @return \Phinx\Console\PhinxApplication
|
||||
*/
|
||||
public function getApp(): PhinxApplication
|
||||
{
|
||||
return $this->app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the exit code from the last run command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getExitCode(): int
|
||||
{
|
||||
return $this->exitCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output from running the "status" command.
|
||||
*
|
||||
* @param string|null $env environment name (optional)
|
||||
* @return string
|
||||
*/
|
||||
public function getStatus(?string $env = null): string
|
||||
{
|
||||
$command = ['status'];
|
||||
if ($this->hasEnvValue($env)) {
|
||||
$command['-e'] = $env ?: $this->getOption('environment');
|
||||
}
|
||||
if ($this->hasOption('configuration')) {
|
||||
$command['-c'] = $this->getOption('configuration');
|
||||
}
|
||||
if ($this->hasOption('parser')) {
|
||||
$command['-p'] = $this->getOption('parser');
|
||||
}
|
||||
if ($this->hasOption('format')) {
|
||||
$command['-f'] = $this->getOption('format');
|
||||
}
|
||||
|
||||
return $this->executeRun($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|null $env environment name
|
||||
* @return bool
|
||||
*/
|
||||
private function hasEnvValue($env): bool
|
||||
{
|
||||
return $env || $this->hasOption('environment');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output from running the "migrate" command.
|
||||
*
|
||||
* @param string|null $env environment name (optional)
|
||||
* @param string|null $target target version (optional)
|
||||
* @return string
|
||||
*/
|
||||
public function getMigrate(?string $env = null, ?string $target = null): string
|
||||
{
|
||||
$command = ['migrate'];
|
||||
if ($this->hasEnvValue($env)) {
|
||||
$command += ['-e' => $env ?: $this->getOption('environment')];
|
||||
}
|
||||
if ($this->hasOption('configuration')) {
|
||||
$command += ['-c' => $this->getOption('configuration')];
|
||||
}
|
||||
if ($this->hasOption('parser')) {
|
||||
$command += ['-p' => $this->getOption('parser')];
|
||||
}
|
||||
if ($target) {
|
||||
$command += ['-t' => $target];
|
||||
}
|
||||
|
||||
return $this->executeRun($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output from running the "seed:run" command.
|
||||
*
|
||||
* @param string|null $env Environment name
|
||||
* @param string|null $target Target version
|
||||
* @param string[]|string|null $seed Array of seed names or seed name
|
||||
* @return string
|
||||
*/
|
||||
public function getSeed(?string $env = null, ?string $target = null, $seed = null): string
|
||||
{
|
||||
$command = ['seed:run'];
|
||||
if ($this->hasEnvValue($env)) {
|
||||
$command += ['-e' => $env ?: $this->getOption('environment')];
|
||||
}
|
||||
if ($this->hasOption('configuration')) {
|
||||
$command += ['-c' => $this->getOption('configuration')];
|
||||
}
|
||||
if ($this->hasOption('parser')) {
|
||||
$command += ['-p' => $this->getOption('parser')];
|
||||
}
|
||||
if ($target) {
|
||||
$command += ['-t' => $target];
|
||||
}
|
||||
if ($seed) {
|
||||
$seed = (array)$seed;
|
||||
$command += ['-s' => $seed];
|
||||
}
|
||||
|
||||
return $this->executeRun($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output from running the "rollback" command.
|
||||
*
|
||||
* @param string|null $env Environment name (optional)
|
||||
* @param mixed $target Target version, or 0 (zero) fully revert (optional)
|
||||
* @return string
|
||||
*/
|
||||
public function getRollback(?string $env = null, $target = null): string
|
||||
{
|
||||
$command = ['rollback'];
|
||||
if ($this->hasEnvValue($env)) {
|
||||
$command += ['-e' => $env ?: $this->getOption('environment')];
|
||||
}
|
||||
if ($this->hasOption('configuration')) {
|
||||
$command += ['-c' => $this->getOption('configuration')];
|
||||
}
|
||||
if ($this->hasOption('parser')) {
|
||||
$command += ['-p' => $this->getOption('parser')];
|
||||
}
|
||||
if (isset($target)) {
|
||||
// Need to use isset() with rollback, because -t0 is a valid option!
|
||||
// See https://book.cakephp.org/phinx/0/en/commands.html#the-rollback-command
|
||||
$command += ['-t' => $target];
|
||||
}
|
||||
|
||||
return $this->executeRun($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check option from options array
|
||||
*
|
||||
* @param string $key Key
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasOption(string $key): bool
|
||||
{
|
||||
return isset($this->options[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get option from options array
|
||||
*
|
||||
* @param string $key Key
|
||||
* @return string|null
|
||||
*/
|
||||
protected function getOption(string $key): ?string
|
||||
{
|
||||
if (!isset($this->options[$key])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->options[$key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set option in options array
|
||||
*
|
||||
* @param string $key Key
|
||||
* @param string $value Value
|
||||
* @return $this
|
||||
*/
|
||||
public function setOption(string $key, string $value)
|
||||
{
|
||||
$this->options[$key] = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command, capturing output and storing the exit code.
|
||||
*
|
||||
* @param array $command Command
|
||||
* @return string
|
||||
*/
|
||||
protected function executeRun(array $command): string
|
||||
{
|
||||
// Output will be written to a temporary stream, so that it can be
|
||||
// collected after running the command.
|
||||
$stream = fopen('php://temp', 'w+');
|
||||
|
||||
// Execute the command, capturing the output in the temporary stream
|
||||
// and storing the exit code for debugging purposes.
|
||||
$this->exitCode = $this->app->doRun(new ArrayInput($command), new StreamOutput($stream));
|
||||
|
||||
// Get the output of the command and close the stream, which will
|
||||
// destroy the temporary file.
|
||||
$result = stream_get_contents($stream, -1, 0);
|
||||
fclose($stream);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Attempts to load Composer's autoload.php as either a dependency or a
|
||||
* stand-alone package.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
return function () {
|
||||
$files = [
|
||||
__DIR__ . '/../../../autoload.php', // composer dependency
|
||||
__DIR__ . '/../vendor/autoload.php', // stand-alone package
|
||||
];
|
||||
foreach ($files as $file) {
|
||||
if (is_file($file)) {
|
||||
require_once $file;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
Reference in New Issue
Block a user