From 80e0d8a06e5e16edaa0d12428763ffb1e8cafa71 Mon Sep 17 00:00:00 2001 From: mscherer Date: Mon, 4 Aug 2025 13:15:28 +0200 Subject: [PATCH 1/8] Refactor to fully remove phinx dependency. --- README.md | 17 +- composer.json | 5 +- config/app.example.php | 1 - docs/en/index.rst | 2 +- docs/en/upgrading-to-builtin-backend.rst | 29 +- docs/fr/conf.py | 9 - docs/fr/contents.rst | 5 - docs/fr/index.rst | 1178 ------------ docs/ja/conf.py | 9 - docs/ja/contents.rst | 5 - docs/ja/index.rst | 1052 ---------- docs/pt/conf.py | 9 - docs/pt/contents.rst | 5 - docs/pt/index.rst | 943 --------- docs/ru/conf.py | 9 - docs/ru/contents.rst | 5 - docs/ru/index.rst | 1020 ---------- phpstan-baseline.neon | 60 - phpstan.neon | 1 - src/AbstractMigration.php | 68 - src/AbstractSeed.php | 130 -- src/CakeAdapter.php | 110 -- src/CakeManager.php | 391 ---- src/Command/BakeMigrationCommand.php | 4 +- src/Command/BakeMigrationDiffCommand.php | 3 +- src/Command/BakeMigrationSnapshotCommand.php | 2 +- src/Command/BakeSeedCommand.php | 2 +- src/Command/EntryCommand.php | 7 - src/Config/ConfigInterface.php | 2 +- src/Db/Adapter/AbstractAdapter.php | 15 +- src/Db/Adapter/PhinxAdapter.php | 828 -------- src/Db/Adapter/PostgresAdapter.php | 7 +- src/Db/Adapter/SqlserverAdapter.php | 7 +- src/Db/Table.php | 53 +- src/Db/Table/ForeignKey.php | 27 - src/Migration/Environment.php | 45 +- src/Migration/Manager.php | 28 +- src/Migrations.php | 94 +- src/MigrationsPlugin.php | 6 - src/Shim/MigrationAdapter.php | 405 ---- src/Shim/SeedAdapter.php | 252 --- src/Table.php | 249 --- templates/Phinx/create.php.template | 18 - templates/bake/Seed/seed.twig | 13 - templates/bake/config/diff.twig | 16 +- templates/bake/config/skeleton.twig | 10 - templates/bake/config/snapshot.twig | 13 +- templates/bake/element/add-foreign-keys.twig | 15 +- templates/bake/element/add-indexes.twig | 10 - tests/ExampleCommand.php | 20 - tests/RawBufferedOutput.php | 3 +- .../Command/BakeMigrationCommandTest.php | 3 - .../Command/BakeMigrationDiffCommandTest.php | 1 - .../BakeMigrationSnapshotCommandTest.php | 1 - .../TestCase/Command/BakeSeedCommandTest.php | 2 - tests/TestCase/Command/DumpCommandTest.php | 2 - tests/TestCase/Command/EntryCommandTest.php | 3 - tests/TestCase/Command/MarkMigratedTest.php | 2 - tests/TestCase/Command/MigrateCommandTest.php | 2 - .../TestCase/Command/RollbackCommandTest.php | 2 - tests/TestCase/Command/SeedCommandTest.php | 25 +- tests/TestCase/Command/StatusCommandTest.php | 2 - .../Db/Adapter/AbstractAdapterTest.php | 4 +- .../TestCase/Db/Adapter/PhinxAdapterTest.php | 1697 ----------------- tests/TestCase/Migration/EnvironmentTest.php | 24 +- tests/TestCase/Migration/ManagerTest.php | 5 +- tests/TestCase/MigrationsTest.php | 32 +- .../20120111235330_test_migration.php | 4 +- .../20120116183504_test_migration_2.php | 4 +- tests/comparisons/Create/TestCreateChange.php | 6 +- .../addRemove/the_diff_add_remove_mysql.php | 2 +- .../addRemove/the_diff_add_remove_pgsql.php | 8 +- .../Diff/default/the_diff_default_mysql.php | 2 +- .../Diff/default/the_diff_default_pgsql.php | 8 +- .../Diff/simple/the_diff_simple_mysql.php | 2 +- .../Diff/simple/the_diff_simple_pgsql.php | 8 +- ...d_compatible_signed_primary_keys_mysql.php | 2 +- ...incompatible_signed_primary_keys_mysql.php | 2 +- ...compatible_unsigned_primary_keys_mysql.php | 2 +- .../test_snapshot_auto_id_disabled_pgsql.php | 4 +- .../pgsql/test_snapshot_not_empty_pgsql.php | 4 +- .../pgsql/test_snapshot_plugin_blog_pgsql.php | 4 +- .../test_snapshot_auto_id_disabled_sqlite.php | 4 +- .../sqlite/test_snapshot_not_empty_sqlite.php | 4 +- .../test_snapshot_plugin_blog_sqlite.php | 4 +- ...st_snapshot_auto_id_disabled_sqlserver.php | 4 +- .../test_snapshot_not_empty_sqlserver.php | 4 +- .../test_snapshot_plugin_blog_sqlserver.php | 4 +- .../comparisons/Migration/testCreatePhinx.php | 6 +- .../test_snapshot_auto_id_disabled.php | 4 +- .../Migration/test_snapshot_not_empty.php | 4 +- .../Migration/test_snapshot_plugin_blog.php | 4 +- ...auto_id_compatible_signed_primary_keys.php | 4 +- ...to_id_incompatible_signed_primary_keys.php | 4 +- ..._id_incompatible_unsigned_primary_keys.php | 4 +- ...st_snapshot_with_non_default_collation.php | 4 +- .../Seeds/testBasicBakingPhinx.php | 6 +- tests/comparisons/Seeds/testWithData.php | 6 +- .../Seeds/testWithDataAndLimit.php | 6 +- .../Migrations/20211001000000_migrator.php | 4 +- .../Migrations2/20211002000000_migrator2.php | 4 +- .../config/CallSeeds/PluginLettersSeed.php | 2 +- .../config/CallSeeds/PluginSubLettersSeed.php | 6 +- .../config/AltSeeds/AnotherNumbersSeed.php | 6 +- .../config/AltSeeds/NumbersAltSeed.php | 6 +- .../config/BaseSeeds/MigrationSeedNumbers.php | 2 +- .../config/CallSeeds/DatabaseSeed.php | 2 +- .../test_app/config/CallSeeds/LettersSeed.php | 2 +- .../config/CallSeeds/NumbersCallSeed.php | 2 +- ...0190928205056_first_fk_index_migration.php | 4 +- ...190928205060_second_fk_index_migration.php | 4 +- ...13232502_create_drop_fk_initial_schema.php | 4 +- .../20121223011815_add_regression_drop_fk.php | 4 +- .../20121223011816_change_fk_regression.php | 4 +- ...0121223011817_change_column_regression.php | 4 +- ...20190928205056_first_drop_fk_migration.php | 4 +- ...0190928205060_second_drop_fk_migration.php | 4 +- ...0120111235330_duplicate_migration_name.php | 4 +- ...0120111235331_duplicate_migration_name.php | 4 +- .../20120111235330_duplicate_migration.php | 4 +- .../20120111235330_duplicate_migration_2.php | 4 +- .../20120111235330_invalid_class.php | 4 +- .../20120111235330_test_migration.php | 4 +- .../20120116183504_test_migration_2.php | 4 +- .../test_app/config/ManagerSeeds/Gseeder.php | 4 +- .../config/ManagerSeeds/PostSeeder.php | 4 +- .../config/ManagerSeeds/UserSeeder.php | 4 +- .../ManagerSeeds/UserSeederNotExecuted.php | 4 +- .../20150416223600_mark_migrated_test.php | 4 +- ...240309223600_mark_migrated_test_second.php | 4 +- ...20151218183450_CreateArticlesAddRemove.php | 4 +- .../20151218183450_CreateArticlesDefault.php | 4 +- .../20160128183623_AlterArticlesDefault.php | 6 +- ...0160128183652_AlterArticlesSlugDefault.php | 6 +- .../20160128183952_CreateUsersDefault.php | 6 +- .../20160128184109_AlterArticlesFkDefault.php | 6 +- .../20160414193900_CreateTagsDefault.php | 6 +- .../20151218183450_CreateArticlesSimple.php | 4 +- .../20160128183623_AlterArticlesSimple.php | 6 +- ...sWithAutoIdCompatibleSignedPrimaryKeys.php | 4 +- ...ithAutoIdIncompatibleSignedPrimaryKeys.php | 4 +- ...hAutoIdIncompatibleUnsignedPrimaryKeys.php | 4 +- .../20180516025208_snapshot_pgsql.php | 4 +- .../20121213232502_create_initial_schema.php | 6 +- .../20121223011815_update_info_table.php | 6 +- ...49_rename_info_table_to_statuses_table.php | 4 +- ...20121224200739_rename_bio_to_biography.php | 4 +- ...0121224200852_create_user_logins_table.php | 6 +- ...24134305_direction_aware_reversible_up.php | 6 +- ...121929_direction_aware_reversible_down.php | 6 +- .../20180431121930_tricky_edge_case.php | 6 +- ...reate_test_index_limit_specifier_table.php | 8 +- .../20190928220334_add_column_index_fk.php | 10 +- tests/test_app/config/Seeds/NumbersSeed.php | 4 +- tests/test_app/config/Seeds/StoresSeed.php | 4 +- ...207205056_should_not_execute_migration.php | 4 +- ...0201207205057_should_execute_migration.php | 4 +- .../20150704160200_create_numbers_table.php | 4 +- .../20150724233100_update_numbers_table.php | 4 +- .../20150826191400_create_letters_table.php | 4 +- .../20230628181900_create_stores_table.php | 4 +- 161 files changed, 302 insertions(+), 9138 deletions(-) delete mode 100644 docs/fr/conf.py delete mode 100644 docs/fr/contents.rst delete mode 100644 docs/fr/index.rst delete mode 100644 docs/ja/conf.py delete mode 100644 docs/ja/contents.rst delete mode 100644 docs/ja/index.rst delete mode 100644 docs/pt/conf.py delete mode 100644 docs/pt/contents.rst delete mode 100644 docs/pt/index.rst delete mode 100644 docs/ru/conf.py delete mode 100644 docs/ru/contents.rst delete mode 100644 docs/ru/index.rst delete mode 100644 src/AbstractMigration.php delete mode 100644 src/AbstractSeed.php delete mode 100644 src/CakeAdapter.php delete mode 100644 src/CakeManager.php delete mode 100644 src/Db/Adapter/PhinxAdapter.php delete mode 100644 src/Shim/MigrationAdapter.php delete mode 100644 src/Shim/SeedAdapter.php delete mode 100644 src/Table.php delete mode 100644 templates/Phinx/create.php.template delete mode 100644 tests/ExampleCommand.php delete mode 100644 tests/TestCase/Db/Adapter/PhinxAdapterTest.php diff --git a/README.md b/README.md index 878cca37..4faf49d8 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This is a Database Migrations system for CakePHP. -The plugin consists of a CakePHP CLI wrapper for the [Phinx](https://book.cakephp.org/phinx/0/en/index.html) migrations library. +The plugin provides a complete database migration solution with support for creating, running, and managing migrations. This branch is for use with CakePHP **5.x**. See [version map](https://github.com/cakephp/migrations/wiki#version-map) for details. @@ -33,21 +33,6 @@ If you are using the PendingMigrations middleware, use: bin/cake plugin load Migrations ``` -### Enabling the builtin backend - -In a future release, migrations will be switching to a new backend based on the CakePHP ORM. We're aiming -to be compatible with as many existing migrations as possible, and could use your feedback. Enable the -new backend with: - -```php -// in app/config/app_local.php -$config = [ - // Other configuration - 'Migrations' => ['backend' => 'builtin'], -]; - -``` - ## Documentation Full documentation of the plugin can be found on the [CakePHP Cookbook](https://book.cakephp.org/migrations/4/). diff --git a/composer.json b/composer.json index ddaef1b4..e4761a88 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "cakephp/migrations", - "description": "Database Migration plugin for CakePHP based on Phinx", + "description": "Database Migration plugin for CakePHP", "license": "MIT", "type": "cakephp-plugin", "keywords": [ @@ -25,7 +25,8 @@ "php": ">=8.1", "cakephp/cache": "^5.2", "cakephp/orm": "^5.2", - "robmorgan/phinx": "^0.16.10" + "symfony/config": "^6.0 || ^7.0", + "symfony/console": "^6.0 || ^7.0" }, "require-dev": { "cakephp/bake": "^3.3", diff --git a/config/app.example.php b/config/app.example.php index ee200e9c..7a83dd3f 100644 --- a/config/app.example.php +++ b/config/app.example.php @@ -6,7 +6,6 @@ return [ 'Migrations' => [ - 'backend' => 'builtin', 'unsigned_primary_keys' => null, 'column_null_default' => null, ], diff --git a/docs/en/index.rst b/docs/en/index.rst index e59cfc06..aeddb5ed 100644 --- a/docs/en/index.rst +++ b/docs/en/index.rst @@ -867,7 +867,7 @@ pass them to the method:: Feature Flags ============= -Migrations offers a few feature flags to compatibility with phinx. These features are disabled by default but can be enabled if required: +Migrations offers a few feature flags for compatibility. These features are disabled by default but can be enabled if required: * ``unsigned_primary_keys``: Should Migrations create primary keys as unsigned integers? (default: ``false``) * ``column_null_default``: Should Migrations create columns as null by default? (default: ``false``) diff --git a/docs/en/upgrading-to-builtin-backend.rst b/docs/en/upgrading-to-builtin-backend.rst index b1837263..001fed31 100644 --- a/docs/en/upgrading-to-builtin-backend.rst +++ b/docs/en/upgrading-to-builtin-backend.rst @@ -3,18 +3,17 @@ Upgrading to the builtin backend As of migrations 4.3 there is a new migrations backend that uses CakePHP's database abstractions and ORM. In 4.4, the ``builtin`` backend became the -default backend. Longer term this will allow for phinx to be -removed as a dependency. This greatly reduces the dependency footprint of -migrations. +default backend. As of migrations 5.0, phinx has been removed as a dependency +and only the builtin backend is supported. This greatly reduces the dependency +footprint of migrations. What is the same? ================= Your migrations shouldn't have to change much to adapt to the new backend. -The migrations backend implements all of the phinx interfaces and can run -migrations based on phinx classes. If your migrations don't work in a way that -could be addressed by the changes outlined below, please open an issue, as we'd -like to maintain as much compatibility as we can. +The builtin backend provides similar functionality to what was available with +phinx. If your migrations don't work in a way that could be addressed by the +changes outlined below, please open an issue. What is different? ================== @@ -43,16 +42,8 @@ Similar changes are for fetching a single row:: $stmt = $this->getAdapter()->query('SELECT * FROM articles'); $rows = $stmt->fetch('assoc'); -Problems with the new backend? -============================== +Problems with the builtin backend? +================================== -The new backend is enabled by default. If your migrations contain errors when -run with the builtin backend, please open `an issue -`_. You can also switch back -to the ``phinx`` backend through application configuration. Add the -following to your ``config/app.php``:: - - return [ - // Other configuration. - 'Migrations' => ['backend' => 'phinx'], - ]; +If your migrations contain errors when run with the builtin backend, please +open `an issue `_. diff --git a/docs/fr/conf.py b/docs/fr/conf.py deleted file mode 100644 index b02032ef..00000000 --- a/docs/fr/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'fr' diff --git a/docs/fr/contents.rst b/docs/fr/contents.rst deleted file mode 100644 index 1459b1f1..00000000 --- a/docs/fr/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP Migrations - - /index diff --git a/docs/fr/index.rst b/docs/fr/index.rst deleted file mode 100644 index 10fca16d..00000000 --- a/docs/fr/index.rst +++ /dev/null @@ -1,1178 +0,0 @@ -Migrations -########## - -Migrations est un plugin supporté par la core team pour vous aider à gérer les -changements dans la base de données en écrivant des fichiers PHP qui peuvent -être versionnés par votre système de gestion de version. - -Il vous permet de faire évoluer vos tables au fil du temps. -Au lieu d'écrire vos modifications de schéma en SQL, ce plugin vous permet -d'utiliser un ensemble intuitif de méthodes qui facilite la mise en œuvre des -modifications au sein de la base de données. - -Ce plugin est un wrapper pour la librairie de gestion des migrations de bases de -données `Phinx `_. - -Installation -============ - -Par défaut Migrations est installé avec le squelette d’application. Si vous le -retirez et voulez le réinstaller, vous pouvez le faire en lançant ce qui suit à -partir du répertoire ROOT de votre application (où le fichier composer.json est -localisé): - -.. code-block:: bash - - php composer.phar require cakephp/migrations "@stable" - - # Ou si composer est installé globalement - - composer require cakephp/migrations "@stable" - -Pour utiliser le plugin, vous devrez le charger dans le fichier -**config/bootstrap.php** de votre application. -Vous pouvez utiliser `le shell de Plugin de CakePHP -`__ pour -charger et décharger les plugins de votre **config/bootstrap.php**: - -.. code-block:: bash - - bin/cake plugin load Migrations - -Ou vous pouvez charger le plugin en modifiant votre fichier -**config/bootstrap.php**, en ajoutant ce qui suit:: - - Plugin::load('Migrations'); - -De plus, vous devrez configurer la base de données par défaut pour votre -application dans le fichier **config/app.php** comme expliqué dans la section -sur la `configuration des bases de données -`__. - -Vue d'ensemble -============== - -Une migration est simplement un fichier PHP qui décrit les changements à -effectuer sur la base de données. Un fichier de migration peut créer ou -supprimer des tables, ajouter ou supprimer des colonnes, créer des index et même -insérer des données dans votre base de données. - -Ci-dessous un exemple de migration:: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -Cette migration va ajouter une table à votre base de données nommée ``products`` -avec les définitions de colonne suivantes: - -- ``id`` colonne de type ``integer`` comme clé primaire -- ``name`` colonne de type ``string`` -- ``description`` colonne de type ``text`` -- ``created`` colonne de type ``datetime`` - -.. tip:: - - La colonne avec clé primaire nommée ``id`` sera ajoutée **implicitement**. - -.. note:: - - Notez que ce fichier décrit ce à quoi la base de données devrait ressembler - **après** l'application de la migration. À ce stade la table ``products`` - n'existe pas dans votre base de données, nous avons simplement créé un - fichier qui est à la fois capable de créer la table ``products`` avec les - bonnes colonnes mais aussi de supprimer la table quand une opération de - ``rollback`` (retour en arrière) de la migration est effectuée. - -Une fois que le fichier a été créé dans le dossier **config/Migrations**, vous -pourrez exécuter la commande ``migrations`` suivante pour créer la table dans -votre base de données: - -.. code-block:: bash - - bin/cake migrations migrate - -La commande ``migrations`` suivante va effectuer un ``rollback`` (retour en -arrière) et supprimer la table de votre base de données: - -.. code-block:: bash - - bin/cake migrations rollback - -Création de Migrations -====================== - -Les fichiers de migrations sont stockés dans le répertoire **config/Migrations** -de votre application. Le nom des fichiers de migration est précédé de la -date/heure du jour de création, dans le format -**YYYYMMDDHHMMSS_MigrationName.php**. -Voici quelques exemples de noms de fichiers de migration: - -* 20160121163850_CreateProducts.php -* 20160210133047_AddRatingToProducts.php - -La meilleure façon de créer un fichier de migration est d'utiliser la ligne de -commande ``bin/cake bake migration``. - -Assurez-vous de bien lire la `documentation officielle de Phinx `_ afin de connaître la liste -complète des méthodes que vous pouvez utiliser dans l'écriture des fichiers de -migration. - -.. note:: - - Quand vous utilisez l'option ``bake``, vous pouvez toujours modifier la - migration avant de l'exécuter si besoin. - -Syntaxe -------- - -La syntaxe de la commande ``bake`` est de la forme suivante: - -.. code-block:: bash - - bin/cake bake migration CreateProducts name:string description:text created modified - -Quand vous utilisez ``bake`` pour créer des tables, ajouter des colonnes ou -effectuer diverses opérations sur votre base de données, vous devez en général -fournir deux choses: - -* le nom de la migration que vous allez générer (``CreateProducts`` dans notre - exemple) -* les colonnes de la table qui seront ajoutées ou retirées dans la migration - (``name:string description:text created modified`` dans notre exemple) - -Étant données les conventions, tous les changements de schéma ne peuvent pas -être effectuées avec les commandes shell. - -De plus, vous pouvez créer un fichier de migration vide si vous voulez un -contrôle total sur ce qui doit être executé, en ne spécifiant pas de définition -de colonnes: - -.. code-block:: bash - - bin/cake migrations create MyCustomMigration - -Nom de Fichier des Migrations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Les noms des migrations peuvent suivre l'une des structures suivantes: - -* (``/^(Create)(.*)/``) Crée la table spécifiée. -* (``/^(Drop)(.*)/``) Supprime la table spécifiée. Ignore les arguments de champ spécifié. -* (``/^(Add).*(?:To)(.*)/``) Ajoute les champs à la table spécifiée. -* (``/^(Remove).*(?:From)(.*)/``) Supprime les champs de la table spécifiée. -* (``/^(Alter)(.*)/``) Modifie la table spécifiée. Un alias pour CreateTable et AddField. -* (``/^(Alter).*(?:On)(.*)/``) Modifie les champs de la table spécifiée. - -Vous pouvez aussi utiliser ``la_forme_avec_underscores`` comme nom pour vos -migrations par exemple ``create_products``. - -.. versionadded:: cakephp/migrations 1.5.2 - - Depuis la version 1.5.2 du `plugin migrations `_, - le nom de fichier de migration sera automatiquement avec des majuscules. - Cette version du plugin est seulement disponible pour une version de - CakePHP >= to 3.1. Avant cette version du plugin, le nom des migrations - serait sous la forme avec des underscores, par exemple - ``20160121164955_create_products.php``. - -.. warning:: - - Les noms des migrations sont utilisés comme noms de classe de migration, et - peuvent donc être en conflit avec d'autres migrations si les noms de classe - ne sont pas uniques. Dans ce cas, il peut être nécessaire de remplacer - manuellement le nom plus tard, ou simplement changer le nom - que vous avez spécifié. - -Définition de Colonnes -~~~~~~~~~~~~~~~~~~~~~~ - -Quand vous définissez des colonnes avec la ligne de commande, il peut être -pratique de se souvenir qu'elles suivent le modèle suivant:: - - fieldName:fieldType?[length]:indexType:indexName - -Par exemple, les façons suivantes sont toutes des façons valides pour spécifier -un champ d'email: - -* ``email:string?`` -* ``email:string:unique`` -* ``email:string?[50]`` -* ``email:string:unique:EMAIL_INDEX`` -* ``email:string[120]:unique:EMAIL_INDEX`` - -Le point d'interrogation qui suit le type du champ entrainera que la colonne -peut être null. - -Le paramètre ``length`` pour ``fieldType`` est optionnel et doit toujours être -écrit entre crochets. - -Les champs nommés ``created`` et ``modified``, tout comme les champs ayant pour -suffixe ``_at``, vont automatiquement être définis avec le type ``datetime``. - -Les types de champ sont ceux qui sont disponibles avec la librairie ``Phinx``. -Ce sont les suivants: - -* string -* text -* integer -* biginteger -* float -* decimal -* datetime -* timestamp -* time -* date -* binary -* boolean -* uuid - -Il existe quelques heuristiques pour choisir les types de champ quand ils ne -sont pas spécifiés ou définis avec une valeur invalide. Par défaut, le type est -``string``: - -* id: integer -* created, modified, updated: datetime - -Créer une Table ---------------- - -Vous pouvez utiliser ``bake`` pour créer une table: - -.. code-block:: bash - - bin/cake bake migration CreateProducts name:string description:text created modified - -La ligne de commande ci-dessus va générer un fichier de migration qui ressemble -à:: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -Ajouter des Colonnes à une Table Existante ------------------------------------------- - -Si le nom de la migration dans la ligne de commande est de la forme -"AddXXXToYYY" et est suivie d'une liste de noms de colonnes et de types alors -un fichier de migration contenant le code pour la création des colonnes sera -généré: - -.. code-block:: bash - - bin/cake bake migration AddPriceToProducts price:decimal - -L'exécution de la ligne de commande ci-dessus va générer:: - - table('products'); - $table->addColumn('price', 'decimal') - ->update(); - } - } - -Ajouter un Index de Colonne à une Table ---------------------------------------- - -Il est également possible d'ajouter des indexes de colonnes: - -.. code-block:: bash - - bin/cake bake migration AddNameIndexToProducts name:string:index - -va générer:: - - table('products'); - $table->addColumn('name', 'string') - ->addIndex(['name']) - ->update(); - } - } - -Spécifier la Longueur d'un Champ --------------------------------- - -.. versionadded:: cakephp/migrations 1.4 - -Si vous voulez spécifier une longueur de champ, vous pouvez le faire entre -crochets dans le type du champ, par exemple: - -.. code-block:: bash - - bin/cake bake migration AddFullDescriptionToProducts full_description:string[60] - -L'exécution de la ligne de commande ci-dessus va générer:: - - table('products'); - $table->addColumn('full_description', 'string', [ - 'default' => null, - 'limit' => 60, - 'null' => false, - ]) - ->update(); - } - } - -Si aucune longueur n'est spécifiée, les longueurs pour certain types de -colonnes sont par défaut: - -* string: 255 -* integer: 11 -* biginteger: 20 - -Modifier une colonne d'une table ------------------------------------ - -De la même manière, vous pouvez générer une migration pour modifier une colonne à l'aide de la commande -ligne de commande, si le nom de la migration est de la forme "AlterXXXOnYYY": - -.. code-block:: bash - - bin/cake bake migration AlterPriceOnProducts name:float - -créé le fichier:: - - table('products'); - $table->changeColumn('name', 'float'); - $table->update(); - } - } - -Retirer une Colonne d'une Table -------------------------------- - -De la même façon, vous pouvez générer une migration pour retirer une colonne -en utilisant la ligne de commande, si le nom de la migration est de la forme -"RemoveXXXFromYYY": - -.. code-block:: bash - - bin/cake bake migration RemovePriceFromProducts price - -créé le fichier:: - - table('products'); - $table->removeColumn('price') - ->save(); - } - } - -.. note:: - - La commande `removeColumn` n'est pas réversible, donc elle doit être appelée - dans la méthode `up`. Un appel correspondant au `addColumn` doit être - ajouté à la méthode `down`. - -Générer une Migration à partir d'une Base de Données Existante -============================================================== - -Si vous avez affaire à une base de données pré-existante et que vous voulez -commencer à utiliser migrations, ou que vous souhaitez versionner le schéma -initial de votre base de données, vous pouvez exécuter la commande -``migration_snapshot``: - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial - -Elle va générer un fichier de migration appelé **Initial** contenant toutes les -déclarations pour toutes les tables de votre base de données. - -Par défaut, le snapshot va être créé en se connectant à la base de données -définie dans la configuration de la connection ``default``. -Si vous devez créer un snapshot à partir d'une autre source de données, vous -pouvez utiliser l'option ``--connection``: - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial --connection my_other_connection - -Vous pouvez aussi vous assurer que le snapshot inclut seulement les tables pour -lesquelles vous avez défini les classes de model correspondantes en utilisant -le flag ``--require-table``: - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial --require-table - -Quand vous utilisez le flag ``--require-table``, le shell va chercher les -classes ``Table`` de votre application et va seulement ajouter les tables de -model dans le snapshot. - -La même logique sera appliquée implicitement si vous souhaitez créer un -snapshot pour un plugin. Pour ce faire, vous devez utiliser l'option -``--plugin``: - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial --plugin MyPlugin - -Seules les tables ayant une classe d'un objet model ``Table`` définie seront -ajoutées au snapshot de votre plugin. - -.. note:: - - Quand vous créez un snapshot pour un plugin, les fichiers de migration sont - créés dans le répertoire **config/Migrations** de votre plugin. - -Notez que quand vous créez un snapshot, il est automatiquement marqué dans la -table de log de phinx comme migré. - -Générer un diff entre deux états de base de données -=================================================== - -.. versionadded:: cakephp/migrations 1.6.0 - -Vous pouvez générer un fichier de migrations qui regroupera toutes les -différences entre deux états de base de données en utilisant le template bake -``migration_diff``. Pour cela, vous pouvez utiliser la commande suivante: - -.. code-block:: bash - - bin/cake bake migration_diff NameOfTheMigrations - -Pour avoir un point de comparaison avec l'état actuel de votre base de données, -le shell migrations va générer, après chaque appel de ``migrate`` ou -``rollback`` un fichier "dump". Ce fichier dump est un fichier qui contient -l'ensemble de l'état de votre base de données à un point précis dans le temps. - -Quand un fichier dump a été généré, toutes les modifications que vous ferez -directement dans votre SGBD seront ajoutées au fichier de migration qui sera -généré quand vous appelerez la commande ``bake migration_diff``. - -Par défaut, le diff sera fait en se connectant à la base de données définie -dans votre configuration de Connection ``default``. -Si vous avez besoin de faire un diff depuis une source différente, vous pouvez -utiliser l'option ``--connection``: - -.. code-block:: bash - - bin/cake bake migration_diff NameOfTheMigrations --connection my_other_connection - -Si vous souhaitez utiliser la fonctionnalité de diff sur une application qui -possède déjà un historique de migrations, vous allez avoir besoin de créer le -fichier dump manuellement pour qu'il puisse être utilisé comme point de -comparaison: - -.. code-block:: bash - - bin/cake migrations dump - -L'état de votre base de données devra être le même que si vous aviez migré tous -vos fichiers de migrations avant de créer le fichier dump. -Une fois que le fichier dump est créé, vous pouvez opérer des changements dans -votre base de données et utiliser la commande ``bake migration_diff`` quand -vous voulez - -.. note:: - - Veuillez noter que le système n'est pas capable de détecter les colonnes - renommées. - -Les Commandes -============= - -``migrate`` : Appliquer les Migrations --------------------------------------- - -Une fois que vous avez généré ou écrit votre fichier de migration, vous devez -exécuter la commande suivante pour appliquer les modifications à votre base de -données: - -.. code-block:: bash - - # Exécuter toutes les migrations - bin/cake migrations migrate - - # Pour migrer vers une version spécifique, utilisez - # le paramètre ``--target`` ou -t (version courte) - # Cela correspond à l'horodatage qui est ajouté au début - # du nom de fichier des migrations. - bin/cake migrations migrate -t 20150103081132 - - # Par défaut, les fichiers de migration se trouvent dans - # le répertoire **config/Migrations**. Vous pouvez spécifier le répertoire - # en utilisant l'option ``--source`` ou ``-s`` (version courte). - # L'exemple suivant va exécuter les migrations - # du répertoire **config/Alternate** - bin/cake migrations migrate -s Alternate - - # Vous pouvez exécuter les migrations avec une connection différente - # de celle par défaut ``default`` en utilisant l'option ``--connection`` - # ou ``-c`` (version courte) - bin/cake migrations migrate -c my_custom_connection - - # Les migrations peuvent aussi être exécutées pour les plugins. Utilisez - # simplement l'option ``--plugin`` ou ``-p`` (version courte) - bin/cake migrations migrate -p MyAwesomePlugin - -``rollback`` : Annuler les Migrations -------------------------------------- - -La commande de restauration est utilisée pour annuler les précédentes migrations -réalisées par ce plugin. C'est l'inverse de la commande ``migrate``.: - -.. code-block:: bash - - # Vous pouvez annuler la migration précédente en utilisant - # la commande ``rollback``:: - bin/cake migrations rollback - - # Vous pouvez également passer un numéro de version de migration - # pour revenir à une version spécifique:: - bin/cake migrations rollback -t 20150103081132 - -Vous pouvez aussi utilisez les options ``--source``, ``--connection`` et -``--plugin`` comme pour la commande ``migrate``. - -``status`` : Statuts de Migrations ----------------------------------- - -La commande ``status`` affiche une liste de toutes les migrations, ainsi que -leur état actuel. Vous pouvez utiliser cette commande pour déterminer les -migrations qui ont été exécutées: - -.. code-block:: bash - - bin/cake migrations status - -Vous pouvez aussi afficher les résultats avec le format JSON en utilisant -l'option ``--format`` (ou ``-f`` en raccourci): - -.. code-block:: bash - - bin/cake migrations status --format json - -Vous pouvez aussi utiliser les options ``--source``, ``--connection`` et -``--plugin`` comme pour la commande ``migrate``. - -``mark_migrated`` : Marquer une Migration en Migrée ---------------------------------------------------- - -.. versionadded:: 1.4.0 - -Il peut parfois être utile de marquer une série de migrations comme "migrées" -sans avoir à les exécuter. -Pour ce faire, vous pouvez utiliser la commande ``mark_migrated``. -Cette commande fonctionne de la même manière que les autres commandes. - -Vous pouvez marquer toutes les migrations comme migrées en utilisant cette -commande: - -.. code-block:: bash - - bin/cake migrations mark_migrated - -Vous pouvez également marquer toutes les migrations jusqu'à une version -spécifique en utilisant l'option ``--target``: - -.. code-block:: bash - - bin/cake migrations mark_migrated --target=20151016204000 - -Si vous ne souhaitez pas que la migration "cible" soit marquée, vous pouvez -utiliser le _flag_ ``--exclude``: - -.. code-block:: bash - - bin/cake migrations mark_migrated --target=20151016204000 --exclude - -Enfin, si vous souhaitez marquer seulement une migration, vous pouvez utiliser -le _flag_ ``--only``: - -.. code-block:: bash - - bin/cake migrations mark_migrated --target=20151016204000 --only - -Vous pouvez aussi utilisez les options ``--source``, ``--connection`` et -``--plugin`` comme pour la commande ``migrate``. - -.. note:: - - Lorsque vous créez un snapshot avec la commande - ``cake bake migration_snapshot``, la migration créée sera automatiquement - marquée comme "migrée". - -.. deprecated:: 1.4.0 - - Les instructions suivantes ont été dépréciées. Utilisez les seulement si - vous utilisez une version du plugin inférieure à 1.4.0. - -La commande attend le numéro de version de la migration comme argument: - -.. code-block:: bash - - bin/cake migrations mark_migrated 20150420082532 - -Si vous souhaitez marquer toutes les migrations comme "migrées", vous pouvez -utiliser la valeur spéciale ``all``. Si vous l'utilisez, toutes les migrations -trouvées seront marquées comme "migrées": - -.. code-block:: bash - - bin/cake migrations mark_migrated all - -``seed`` : Remplir votre Base de Données (Seed) ------------------------------------------------ - -Depuis la version 1.5.5, vous pouvez utiliser le shell ``migrations`` pour -remplir votre base de données. Cela vient de la `fonctionnalité de seed -de la librairie Phinx `_. -Par défaut, les fichiers de seed vont être recherchés dans le répertoire -``config/Seeds`` de votre application. Assurez-vous de suivre les -`instructions de Phinx pour construire les fichiers de seed `_. - -En ce qui concerne migrations, une interface ``bake`` est fournie pour les -fichiers de seed: - -.. code-block:: bash - - # Ceci va créer un fichier ArticlesSeed.php dans le répertoire config/Seeds - # de votre application - # Par défaut, la table que le seed va essayer de modifier est la version - # "tableized" du nom de fichier du seed - bin/cake bake seed Articles - - # Vous spécifiez le nom de la table que les fichiers de seed vont modifier - # en utilisant l'option ``--table`` - bin/cake bake seed Articles --table my_articles_table - - # Vous pouvez spécifier un plugin dans lequel faire la création - bin/cake bake seed Articles --plugin PluginName - - # Vous pouvez spécifier une connection alternative quand vous générez un - # seeder. - bin/cake bake seed Articles --connection connection - -.. versionadded:: cakephp/migrations 1.6.4 - - Les options ``--data``, ``--limit`` and ``--fields`` ont été ajoutées pour - permettre d'exporter des données extraites depuis votre base de données. - -A partir de 1.6.4, la commande ``bake seed`` vous permet de créer des fichiers -de seed avec des lignes exportées de votre base de données en utilisant -l'option ``--data``: - -.. code-block:: bash - - bin/cake bake seed --data Articles - -Par défaut, cela exportera toutes les lignes trouvées dans la table. Vous -pouvez limiter le nombre de lignes exportées avec l'option ``--limit``: - -.. code-block:: bash - - # N'exportera que les 10 premières lignes trouvées - bin/cake bake seed --data --limit 10 Articles - -Si vous ne souhaitez inclure qu'une sélection des champs de la table dans votre -fichier de seed, vous pouvez utiliser l'option ``--fields``. Elle prend la -liste des champs séparés par une virgule comme argument: - -.. code-block:: bash - - # N'exportera que les champs `id`, `title` et `excerpt` - bin/cake bake seed --data --fields id,title,excerpt Articles - -.. tip:: - - Vous pouvez bien sûr utiliser les options ``--limit`` et ``--fields`` - ensemble dans le même appel. - -Pour faire un seed de votre base de données, vous pouvez utiliser la -sous-commande ``seed``: - -.. code-block:: bash - - # Sans paramètres, la sous-commande seed va exécuter tous les seeders - # disponibles du répertoire cible, dans l'ordre alphabétique. - bin/cake migrations seed - - # Vous pouvez spécifier seulement un seeder à exécuter en utilisant - # l'option `--seed` - bin/cake migrations seed --seed ArticlesSeed - - # Vous pouvez exécuter les seeders d'un autre répertoire - bin/cake migrations seed --source AlternativeSeeds - - # Vous pouvez exécuter les seeders d'un plugin - bin/cake migrations seed --plugin PluginName - - # Vous pouvez exécuter les seeders d'une connection spécifique - bin/cake migrations seed --connection connection - -Notez que, à l'opposé des migrations, les seeders ne sont pas suivies, ce qui -signifie que le même seeder peut être appliqué plusieurs fois. - -Appeler un Seeder depuis un autre Seeder -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: cakephp/migrations 1.6.2 - -Généralement, quand vous remplissez votre base de données avec des *seeders*, -l'ordre dans lequel vous faites les insertions est important pour éviter de -rencontrer des erreurs dûes à des *constraints violations*. -Puisque les *seeders* sont exécutés dans l'ordre alphabétique par défaut, vous -pouvez utiliser la méthode ``\Migrations\AbstractSeed::call()`` pour définir -votre propre séquence d'exécution de *seeders*:: - - use Migrations\AbstractSeed; - - class DatabaseSeed extends AbstractSeed - { - public function run(): void - { - $this->call('AnotherSeed'); - $this->call('YetAnotherSeed'); - - // Vous pouvez utiliser la syntaxe "plugin" pour appeler un seeder - // d'un autre plugin - $this->call('PluginName.FromPluginSeed'); - } - } - -.. note:: - - Assurez vous d'*extend* la classe du plugin Migrations ``AbstractSeed`` si - vous voulez pouvoir utiliser la méthode ``call()``. Cette classe a été - ajoutée dans la version 1.6.2. - -``dump`` : Générer un fichier dump pour la fonctionnalité de diff ------------------------------------------------------------------ - -La commande Dump crée un fichier qui sera utilisé avec le template bake -``migration_diff``: - -.. code-block:: bash - - bin/cake migrations dump - -Chaque fichier dump généré est spécifique à la _Connection_ par laquelle il a -été générée (le nom du fichier est suffixé par ce nom). Cela permet à la -commande ``bake migration_diff`` de calculer le diff correctement dans le cas -où votre application gérerait plusieurs bases de données (qui pourraient être -basées sur plusieurs SGDB. - -Les fichiers de dump sont créés dans le même dossier que vos fichiers de -migrations. - -Vous pouvez aussi utiliser les options ``--source``, ``--connection`` et -``--plugin`` comme pour la commande ``migrate``. - - -Utiliser Migrations dans les Tests -================================== - -Si votre application fait usage des migrations, vous pouvez ré-utiliser -celles-ci afin de maintenir le schéma de votre base de données de test. Dans -le fichier ``tests/bootstrap.php``, vous pouvez utiliser la -classe ``Migrator`` pour construire le schéma avant que vos tests ne soient lancés. -La classe ``Migrator`` réutilisera le schéma existant si il correspond à vos migrations. -Si vos migrations ont évolué depuis le dernier lancement de vos tests, toutes les -tables des connections de test concernées seront effacées et les migrations seront relancées -afin d'actualiser le schéma:: - - // dans tests/bootstrap.php - use Migrations\TestSuite\Migrator; - - $migrator = new Migrator(); - - // Simple setup sans plugins - $migrator->run(); - - // Setup sur une base de données autre que 'test' - $migrator->run(['connection' => 'test_other']); - - // Setup pour un plugin - $migrator->run(['plugin' => 'Contacts']); - - // Lancer les migrations du plugin Documents sur la connection test_docs. - $migrator->run(['plugin' => 'Documents', 'connection' => 'test_docs']); - - -Si vos migrations se trouvent à différents endroits, celles-ci doivent être executées ainsi:: - - // Migrations du plugin Contacts sur la connection ``test``, et du plugin Documents sur la connection ``test_docs`` - $migrator->runMany([ - ['plugin' => 'Contacts'], - ['plugin' => 'Documents', 'connection' => 'test_docs'] - ]); - -Les informations relatives au status des migrations de test sont rapportées dans les logs de l'application. - -.. versionadded: 3.2.0 - Migrator was added to complement the new fixtures in CakePHP 4.3.0. - -Utiliser Migrations dans les Plugins -==================================== - -Les plugins peuvent également contenir des fichiers de migration. Cela rend les -plugins destinés à la communauté beaucoup plus portable et plus facile à -installer. Toutes les commandes du plugin Migrations supportent l'option -``--plugin`` ou ``-p`` afin d'exécuter les commandes par rapport à ce plugin: - -.. code-block:: bash - - bin/cake migrations status -p PluginName - - bin/cake migrations migrate -p PluginName - -Effectuer des Migrations en dehors d'un environnement Console -============================================================= - -.. versionadded:: cakephp/migrations 1.2.0 - -Depuis la sortie de la version 1.2 du plugin migrations, vous pouvez effectuer -des migrations en dehors d'un environnement Console, directement depuis une -application, en utilisant la nouvelle classe ``Migrations``. -Cela peut être pratique si vous développez un installeur de plugins pour un CMS -par exemple. -La classe ``Migrations`` vous permet de lancer les commandes de la console de -migrations suivantes: - -* migrate -* rollback -* markMigrated -* status -* seed - -Chacune de ces commandes possède une méthode définie dans la classe -``Migrations``. - -Voici comment l'utiliser:: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // Va retourner un tableau des migrations et leur statut - $status = $migrations->status(); - - // Va retourner true en cas de succès. Si une erreur se produit, une exception est lancée - $migrate = $migrations->migrate(); - - // Va retourner true en cas de succès. Si une erreur se produit, une exception est lancée - $rollback = $migrations->rollback(); - - // Va retourner true en cas de succès. Si une erreur se produit, une exception est lancée - $markMigrated = $migrations->markMigrated(20150804222900); - - // Va retourner true en cas de succès. Su une erreur se produit, une exception est lancée - $seeded = $migrations->seed(); - -Ces méthodes acceptent un tableau de paramètres qui doivent correspondre aux -options de chacune des commandes:: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // Va retourner un tableau des migrations et leur statut - $status = $migrations->status(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - -Vous pouvez passer n'importe quelle option que la commande de la console -accepterait. -La seule exception étant la commande ``markMigrated`` qui attend le numéro de -version de la migration à marquer comme "migrée" comme premier argument. -Passez le tableau de paramètres en second argument pour cette méthode. - -En option, vous pouvez passer ces paramètres au constructeur de la classe. -Ils seront utilisés comme paramètres par défaut et vous éviteront ainsi d'avoir -à les passer à chaque appel de méthode:: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // Tous les appels suivant seront faits avec les paramètres passés au constructeur de la classe Migrations - $status = $migrations->status(); - $migrate = $migrations->migrate(); - -Si vous avez besoin d'écraser un ou plusieurs paramètres pour un appel, vous -pouvez les passer à la méthode:: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // Cet appel sera fait avec la connexion "custom" - $status = $migrations->status(); - // Cet appel avec la connexion "default" - $migrate = $migrations->migrate(['connection' => 'default']); - -Trucs et Astuces -================ - -Créer des Clés Primaires Personnalisées ---------------------------------------- - -Pour personnaliser la création automatique de la clé primaire ``id`` lors -de l'ajout de nouvelles tables, vous pouvez utiliser le deuxième argument de la -méthode ``table()``:: - - table('products', ['id' => false, 'primary_key' => ['id']]); - $table - ->addColumn('id', 'uuid') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -Le code ci-dessus va créer une colonne ``CHAR(36)`` ``id`` également utilisée -comme clé primaire. - -.. note:: - - Quand vous spécifiez une clé primaire personnalisée avec les lignes de - commande, vous devez la noter comme clé primaire dans le champ id, - sinon vous obtiendrez une erreur de champs id dupliqués, par exemple: - - .. code-block:: bash - - bin/cake bake migration CreateProducts id:uuid:primary name:string description:text created modified - -Depuis Migrations 1.3, une nouvelle manière de gérer les clés primaires a été -introduite. Pour l'utiliser, votre classe de migration devra étendre la -nouvelle classe ``Migrations\AbstractMigration``. -Vous pouvez définir la propriété ``autoId`` à ``false`` dans la classe de -Migration, ce qui désactivera la création automatique de la colonne ``id``. -Vous aurez cependant besoin de manuellement créer la colonne qui servira de clé -primaire et devrez l'ajouter à la déclaration de la table:: - - table('products'); - $table - ->addColumn('id', 'integer', [ - 'autoIncrement' => true, - 'limit' => 11 - ]) - ->addPrimaryKey('id') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -Comparée à la méthode précédente de gestion des clés primaires, cette méthode -vous donne un plus grand contrôle sur la définition de la colonne de la clé -primaire : signée ou non, limite, commentaire, etc. - -Toutes les migrations et les snapshots créés avec ``bake`` utiliseront cette -nouvelle méthode si nécessaire. - -.. warning:: - - Gérer les clés primaires ne peut être fait que lors des opérations de - créations de tables. Ceci est dû à des limitations pour certains serveurs - de base de données supportés par le plugin. - -Collations ----------- - -Si vous avez besoin de créer une table avec une ``collation`` différente -de celle par défaut de la base de données, vous pouvez la définir comme option -de la méthode ``table()``:: - - table('categories', [ - 'collation' => 'latin1_german1_ci' - ]) - ->addColumn('title', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]) - ->create(); - } - } - -Notez cependant que ceci ne peut être fait qu'en cas de création de table : -il n'y a actuellement aucun moyen d'ajouter une colonne avec une ``collation`` -différente de celle de la table ou de la base de données. -Seuls ``MySQL`` et ``SqlServer`` supportent cette option de configuration pour -le moment. - -Mettre à jour les Noms de Colonne et Utiliser les Objets Table --------------------------------------------------------------- - -Si vous utilisez un objet Table de l'ORM de CakePHP pour manipuler des valeurs -de votre base de données, comme renommer ou retirer une colonne, assurez-vous -de créer une nouvelle instance de votre objet Table après l'appel à -``update()``. Le registre de l'objet Table est nettoyé après un appel à -``update()`` afin de rafraîchir le schéma qui est reflèté et stocké dans l'objet -Table lors de l'instanciation. - -Migrations et déploiement -------------------------- -Si vous utilisez le plugin dans vos processus de déploiement, assurez-vous de -vider le cache de l'ORM pour qu'il renouvelle les _metadata_ des colonnes de vos -tables. -Autrement, vous pourrez rencontrer des erreurs de colonnes inexistantes quand -vous effectuerez des opérations sur vos nouvelles colonnes. -Le Core de CakePHP inclut un `Shell de Cache du Schéma -`__ que vous pouvez -utilisez pour vider le cache: - -.. code-block:: bash - - // Avant 3.6, utilisez orm_cache - bin/cake schema_cache clear - -Veuillez vous référer à la section du cookbook à propos du `Shell du Cache du Schéma -`__ si vous voulez -plus de détails à propos de ce shell. - -Renommer une table ------------------- - -Le plugin vous donne la possibilité de renommer une table en utilisant la -méthode ``rename()``. -Dans votre fichier de migration, vous pouvez utiliser la syntaxe suivante:: - - public function up(): void - { - $this->table('old_table_name') - ->rename('new_table_name'); - } - -Ne pas générer le fichier ``schema.lock`` ------------------------------------------ - -.. versionadded:: cakephp/migrations 1.6.5 - -Pour que la fonctionnalité de "diff" fonctionne, un fichier **.lock** est -généré à chaque que vous faites un migrate, un rollback ou que vous générez un -snapshot via bake pour permettre de suivre l'état de votre base de données à -n'importe quel moment. Vous pouvez empêcher que ce fichier ne soit généré, -comme par exemple lors d'un déploiement sur votre environnement de production, -en utilisant l'option ``--no-lock`` sur les commandes mentionnées ci-dessus: - -.. code-block:: bash - - bin/cake migrations migrate --no-lock - - bin/cake migrations rollback --no-lock - - bin/cake bake migration_snapshot MyMigration --no-lock diff --git a/docs/ja/conf.py b/docs/ja/conf.py deleted file mode 100644 index 5871da64..00000000 --- a/docs/ja/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'ja' diff --git a/docs/ja/contents.rst b/docs/ja/contents.rst deleted file mode 100644 index 1459b1f1..00000000 --- a/docs/ja/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP Migrations - - /index diff --git a/docs/ja/index.rst b/docs/ja/index.rst deleted file mode 100644 index cc7685dd..00000000 --- a/docs/ja/index.rst +++ /dev/null @@ -1,1052 +0,0 @@ -Migrations -########## - -マイグレーションは、バージョン管理システムを使用して追跡することができる PHP ファイルを -記述することによって、あなたのデータベースのスキーマ変更を行うための、コアチームによって -サポートされているプラグインです。 - -それはあなたが時間をかけてあなたのデータベーステーブルを進化させることができます。 -スキーマ変更の SQL を書く代わりに、このプラグインでは、直観的にデータベースの変更を -実現するための手段を使用することができます。 - -このプラグインは、データベースマイグレーションライブラリーの -`Phinx `_ のラッパーです。 - -インストール -============ - -初期状態で Migrations は、デフォルトのアプリケーションの雛形と一緒にインストールされます。 -もしあなたがそれを削除して再インストールしたい場合は、(composer.json ファイルが -配置されている)アプリケーションルートディレクトリーから次のコマンドを実行します。 - -.. code-block:: bash - - php composer.phar require cakephp/migrations "@stable" - - # また、composer がグローバルにインストールされていた場合は、 - - composer require cakephp/migrations "@stable" - -このプラグインを使用するためには、あなたは、アプリケーションの **config/bootstrap.php** -ファイルでロードする必要があります。あなたの **config/bootstrap.php** からプラグインを -ロード・アンロードするために `CakePHP の Plugin シェル -`__ -が利用できます。 : - -.. code-block:: bash - - bin/cake plugin load Migrations - -もしくは、あなたの **src/Application.php** ファイルを編集し、次の行を追加することで -ロードすることができます。 :: - - $this->addPlugin('Migrations'); - - // 3.6.0 より前は Plugin::load() を使用する必要があります - -また、 `データベース設定 -`__ の項で説明したように、 -あなたの **config/app.php** ファイル内のデフォルトのデータベース構成を設定する必要が -あります。 - -概要 -==== - -マイグレーションは、基本的にはデータベースの変更の操作を PHP ファイルで表します。 -マイグレーションファイルはテーブルを作成し、カラムの追加や削除、インデックスの作成や -データの作成さえ可能です。 - -ここにマイグレーションの例があります。 :: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -マイグレーションは、データベースに ``products`` という名前のテーブルを追加します。 -以下のカラムが定義します。 - -- ``id`` カラムの型は、主キーの ``integer`` -- ``name`` カラムの型は ``string`` -- ``description`` カラムの型は ``text`` -- ``created`` カラムの型は ``datetime`` -- ``modified`` カラムの型は ``datetime`` - -.. tip:: - - 主キーのカラム名 ``id`` は、 **暗黙のうちに** 追加されます。 - -.. note:: - - このファイルは変更を **適用後** にデータベースがどのようになるかを記述していることに - 注意してください。この時点でデータベースに ``products`` テーブルは存在せず、 - ``products`` テーブルを作って項目を追加することができるのと同様に、マイグレーションを - ``rollback`` すればテーブルが消えてしまいます。 - -マイグレーションファイルを **config/Migrations** フォルダーに作成したら、下記の -``migrations`` コマンドを実行することでデータベースにテーブルを作成することがでます。 : - -.. code-block:: bash - - bin/cake migrations migrate - -以下の ``migrations`` コマンドは、 ``rollback`` を実行するとあなたのデータベースから -テーブルが削除されます。 - -.. code-block:: bash - - bin/cake migrations rollback - -マイグレーションファイルの作成 -============================== - -マイグレーションファイルは、あなたのアプリケーションの **config/Migration** -ディレクトリーに配置します。マイグレーションファイルの名前には、先頭に -**YYYYMMDDHHMMSS_MigrationName.php** というように作成した日付を付けます。 -以下がマイグレーションファイルの例です。 - -* 20160121163850_CreateProducts.php -* 20160210133047_AddRatingToProducts.php - -マイグレーションファイルを作成する最も簡単な方法は ``bake`` CLI -コマンドを使用することです。 - -マイグレーションファイルに記述可能なメソッドの一覧については、オフィシャルの -`Phinx ドキュメント `_ -をご覧ください。 - -.. note:: - - ``bake`` オプションを使用する場合、もし望むなら実行する前にマイグレーションを修正できます。 - -シンタックス ------------- - -以下の ``bake`` コマンドは、 ``products`` テーブルを追加するためのマイグレーションファイルを -作成します。 : - -.. code-block:: bash - - bin/cake bake migration CreateProducts name:string description:text created modified - -あなたのデータベースにテーブルの作成、カラムの追加などをするために ``bake`` を使用する場合、 -一般に以下の2点を指定します。 - -* あなたが生成するマイグレーションの名前 (例えば、 ``CreateProducts``) -* マイグレーションで追加や削除を行うテーブルのカラム - (例えば、 ``name:string description:text created modified``) - -規約のために、すべてのスキーマの変更がこれらのシェルコマンドで動作するわけではありません。 - -さらに、実行内容を完全に制御したいのであれば、空のマイグレーションファイルを -作る事ができます。 - -.. code-block:: bash - - bin/cake migrations create MyCustomMigration - -マイグレーションファイル名 -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -マイグレーション名は下記のパターンに従うことができます。 - -* (``/^(Create)(.*)/``) 指定したテーブルを作成します。 -* (``/^(Drop)(.*)/``) 指定したテーブルを削除します。フィールドの指定は無視されます。 -* (``/^(Add).*(?:To)(.*)/``) 指定したテーブルにカラム追加します。 -* (``/^(Remove).*(?:From)(.*)/``) 指定のテーブルのカラムを削除します。 -* (``/^(Alter)(.*)/``) 指定したテーブルを変更します。 CreateTable と AddField の別名。 -* (``/^(Alter).*(?:On)(.*)/``) 指定されたテーブルのフィールドを変更します。 - -マイグレーションの名前に ``アンダースコアー_形式`` を使用できます。例: create_products - -.. versionadded:: cakephp/migrations 1.5.2 - - マイグレーションファイル名のキャメルケースへの変換は `migrations プラグイン - `_ の v1.5.2 に含まれます。 - このプラグインのバージョンは、 CakePHP 3.1 以上のリリースで利用できます。 - このプラグインのバージョン以前では、マイグレーション名はアンダースコアー形式です。 - 例: 20160121164955_create_products.php - -.. warning:: - - マイグレーション名は、マイグレーションのクラス名として使われます。そして、 - クラス名はユニークでない場合、他のマイグレーションと衝突するかもしれません。この場合、後日、 - 名前を手動で上書きするか、単純にあなたが指定した名前に変更する必要があるかもしれません。 - -カラムの定義 -~~~~~~~~~~~~ - -コマンドラインでカラムを使用する場合には、次のようなパターンに従っている事を -覚えておくと便利です。 :: - - fieldName:fieldType?[length]:indexType:indexName - -例えば、以下はメールアドレスのカラムを指定する方法です。 - -* ``email:string?`` -* ``email:string:unique`` -* ``email:string?[50]`` -* ``email:string:unique:EMAIL_INDEX`` -* ``email:string[120]:unique:EMAIL_INDEX`` - -fieldType の後のクエスチョンマークは、ヌルを許可するカラムを作成します。 - -``fieldType`` のための ``length`` パラメーターは任意です。カッコの中に記述します。 - -フィールド名が ``created`` と ``modified`` 、それに ``_at`` サフィックス付きの -任意のフィールドなら、自動的に ``datetime`` 型が設定されます。 - -``Phinx`` で一般的に利用可能なフィールドの型は次の通り: - -* string -* text -* integer -* biginteger -* float -* decimal -* datetime -* timestamp -* time -* date -* binary -* boolean -* uuid - -未確定で無効な値のままのフィールド型を選ぶためのいくつかの発見的手法があります。 -デフォルトのフィールド型は ``string`` です。 - -* id: integer -* created, modified, updated: datetime - -テーブルの作成 --------------- - -テーブルを作成するために ``bake`` が使えます。 : - -.. code-block:: bash - - bin/cake bake migration CreateProducts name:string description:text created modified - -上記のコマンドラインは、よく似たマイグレーションファイルを生成します。 :: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -既存のテーブルにカラムを追加 ----------------------------- - -もしコマンドラインのマイグレーション名が "AddXXXToYYY" といった -書式で、その後にカラム名と型が続けば、カラムの追加を行うコードを含んだ -マイグレーションファイルが生成されます。 : - -.. code-block:: bash - - bin/cake bake migration AddPriceToProducts price:decimal - -コマンドラインを実行すると下記のようなファイルが生成されます。 :: - - table('products'); - $table->addColumn('price', 'decimal') - ->update(); - } - } - -テーブルにインデックスとしてカラムを追加 ----------------------------------------- - -カラムにインデックスを追加することも可能です。 : - -.. code-block:: bash - - bin/cake bake migration AddNameIndexToProducts name:string:index - -このようなファイルが生成されます。 :: - - table('products'); - $table->addColumn('name', 'string') - ->addIndex(['name']) - ->update(); - } - } - -フィールド長を指定 ------------------- - -.. versionadded:: cakephp/migrations 1.4 - -もし、フィールド長を指定する必要がある場合、フィールドタイプにカギ括弧の中で指定できます。例: - -.. code-block:: bash - - bin/cake bake migration AddFullDescriptionToProducts full_description:string[60] - -上記のコマンドラインを実行すると生成されます。 :: - - table('products'); - $table->addColumn('full_description', 'string', [ - 'default' => null, - 'limit' => 60, - 'null' => false, - ]) - ->update(); - } - } - -長さが未指定の場合、いくつかのカラム型の長さは初期値が設定されます。 - -* string: 255 -* integer: 11 -* biginteger: 20 - -テーブルから列を変更する ------------------------------------ - -同様に、移行名が「AlterXXXOnYYY」の形式の場合、コマンドラインを使用して、列を変更する移行を生成できます。 - -.. code-block:: bash - - bin/cake bake migration AlterPriceOnProducts name:float - -生成されます:: - - table('products'); - $table->changeColumn('name', 'float'); - $table->update(); - } - } - -テーブルからカラムを削除 ------------------------- - -もしマイグレーション名が "RemoveXXXFromYYY" であるなら、同様にコマンドラインを使用して、 -カラム削除のマイグレーションファイルを生成することができます。 : - -.. code-block:: bash - - bin/cake bake migration RemovePriceFromProducts price - -このようなファイルが生成されます。 :: - - table('products'); - $table->removeColumn('price') - ->save(); - } - } - -.. note:: - - `removeColumn` は不可逆ですので、 `up` メソッドの中で呼び出してください。 - それに対する `addColumn` の呼び出しは、 `down` メソッドに追加してください。 - -既存のデータベースからマイグレーションファイルを作成する --------------------------------------------------------- - -もしあなたが既存のデータベースで、マイグレーションの使用を始めたい場合や、 -あなたのアプリケーションのデータベースで初期状態のスキーマのバージョン管理を -行いたい場合、 ``migration_snapshot`` コマンドを実行します。 : - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial - -これはデータベース内のすべてのテーブルの create 文を含んだ **YYYYMMDDHHMMSS_Initial.php** -と呼ばれるマイグレーションファイルを生成します。 - -デフォルトで、スナップショットは、 ``default`` 接続設定で定義されたデータベースに -接続することによって作成されます。 -もし、異なるデータベースからスナップショットを bake する必要があるなら、 -``--connection`` オプションが使用できます。 : - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial --connection my_other_connection - -``--require-table`` フラグを使用することによって対応するモデルクラスを定義したテーブルだけを -含まれることを確認することができます。 : - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial --require-table - -``--require-table`` フラグを使用した時、シェルは、あなたのアプリケーションを通して -``Table`` クラスを見つけて、スナップショットのモデルテーブルのみ追加します。 - -プラグインのためのスナップショットを bake したい場合、同じロジックが暗黙的に適用されます。 -そうするために、 ``--plugin`` オプションを使用する必要があります。 : - -.. code-block:: bash - - bin/cake bake migration_snapshot Initial --plugin MyPlugin - -定義された ``Table`` オブジェクトモデルを持つテーブルだけプラグインのスナップショットに -追加されます。 - -.. note:: - - プラグインのためのスナップショットを bake した時、マイグレーションファイルは、 - あなたのプラグインの **config/Migrations** ディレクトリーに作成されます。 - -スナップショットを bake した時、phinx のログテーブルに自動的に追加されることに注意してください。 - -2つのデータベース間の状態の差分を生成する -============================================= - -.. versionadded:: cakephp/migrations 1.6.0 - -``migration_diff`` の bake テンプレートを使用して2つのデータベースの状態の -すべての差分をまとめたマイグレーションファイルを生成することができます。 -そのためには、以下のコマンドを使用します。 : - -.. code-block:: bash - - bin/cake bake migration_diff NameOfTheMigrations - -現在のデータベースの状態からの比較のポイントを保持するために、migrations シェルは、 -``migrate`` もしくは ``rollback`` が呼ばれた後に "dump" ファイルを生成します。 -ダンプファイルは、取得した時点でのあなたのデータベースの全スキーマの状態を含むファイルです。 - -一度ダンプファイルが生成されると、あなたのデータベース管理システムに直接行ったすべての変更は、 -``bake migration_diff`` コマンドが呼ばれた時に生成されたマイグレーションファイルに追加されます。 - -デフォルトでは、 ``default`` 接続設定に定義されたデータベースに接続することによって -差分が作成されます。もし、あなたが異なるデータソースから差分を bake する必要がある場合、 -``--connection`` オプションを使用できます。 : - -.. code-block:: bash - - bin/cake bake migration_diff NameOfTheMigrations --connection my_other_connection - -もし、すでにマイグレーションの履歴を持つアプリケーション上で diff 機能を使用したい場合、 -マニュアルで比較に使用するダンプファイルを作成する必要があります。 : - -.. code-block:: bash - - bin/cake migrations dump - -データベースの状態は、あなたがダンプファイルを作成する前にマイグレーションを全て実行した状態と -同じでなければなりません。一度ダンプファイルが生成されると、あなたのデータベースの変更を始めて、 -都合の良い時に ``bake migration_diff`` コマンドを使用することができます。 - -.. note:: - - migrations シェルは、カラム名の変更は検知できません。 - -コマンド -======== - -``migrate`` : マイグレーションを適用する ----------------------------------------- - -マイグレーションファイルを生成したり記述したら、以下のコマンドを実行して -変更をデータベースに適用しましょう。 : - -.. code-block:: bash - - # マイグレーションをすべて実行 - bin/cake migrations migrate - - # 特定のバージョンに移行するためには、 ``--target`` オプション - # (省略形は ``-t`` )を使用します。 - # これはマイグレーションファイル名の前に付加されるタイムスタンプに対応しています。 - bin/cake migrations migrate -t 20150103081132 - - # デフォルトで、マイグレーションファイルは、 **config/Migrations** ディレクトリーに - # あります。 ``--source`` オプション (省略形は ``-s``) を使用することで、 - # ディレクトリーを指定できます。 - # 次の例は、 **config/Alternate** ディレクトリー内でマイグレーションを実行します。 - bin/cake migrations migrate -s Alternate - - # ``--connection`` オプション (省略形は ``-c``) を使用することで - # ``default`` とは異なる接続でマイグレーションを実行できます。 - bin/cake migrations migrate -c my_custom_connection - - # マイグレーションは、プラグインのためにも実行できます。 ``--plugin`` オプション - # (省略形は ``-p``) を使用します。 - bin/cake migrations migrate -p MyAwesomePlugin - -``rollback`` : マイグレーションを戻す -------------------------------------- - -ロールバックコマンドは、このプラグインを実行する前の状態に戻すために使われます。 -これは ``migrate`` コマンドの逆向きの動作をします。 : - -.. code-block:: bash - - # あなたは ``rollback`` コマンドを使って以前のマイグレーション状態に戻すことができます。 - bin/cake migrations rollback - - # また、特定のバージョンに戻すために、マイグレーションバージョン番号を引き渡すこともできます。 - bin/cake migrations rollback -t 20150103081132 - -``migrate`` コマンドのように ``--source`` 、 ``--connection`` そして ``--plugin`` -オプションが使用できます。 - -``status`` : マイグレーションのステータス ------------------------------------------ - -Status コマンドは、現在の状況とすべてのマイグレーションのリストを出力します。 -あなたはマイグレーションが実行されたかを判断するために、このコマンドを使用することができます。 : - -.. code-block:: bash - - bin/cake migrations status - -``--format`` (省略形は ``-f``) オプションを使用することで -JSON 形式の文字列として結果を出力できます。 : - -.. code-block:: bash - - bin/cake migrations status --format json - -``migrate`` コマンドのように ``--source`` 、 ``--connection`` そして ``--plugin`` -オプションが使用できます。 - -``mark_migrated`` : マイグレーション済みとしてマーキングする ------------------------------------------------------------- - -.. versionadded:: 1.4.0 - -時には、実際にはマイグレーションを実行せずにマークだけすることが便利な事もあります。 -これを実行するためには、 ``mark_migrated`` コマンドを使用します。 -コマンドは、他のコマンドとしてシームレスに動作します。 - -このコマンドを使用して、すべてのマイグレーションをマイグレーション済みとして -マークすることができます。 : - -.. code-block:: bash - - bin/cake migrations mark_migrated - -また、 ``--target`` オプションを使用して、指定したバージョンに対して、 -すべてマイグレーション済みとしてマークすることができます。 : - -.. code-block:: bash - - bin/cake migrations mark_migrated --target=20151016204000 - -もし、指定したマイグレーションを処理中にマーク済みにしたくない場合、 -``--exclude`` フラグをつけて使用することができます。 : - -.. code-block:: bash - - bin/cake migrations mark_migrated --target=20151016204000 --exclude - -最後に、指定したマイグレーションだけをマイグレーション済みとしてマークしたい場合、 -``--only`` フラグを使用できます。 : - -.. code-block:: bash - - bin/cake migrations mark_migrated --target=20151016204000 --only - -``migrate`` コマンドのように ``--source`` 、 ``--connection`` そして ``--plugin`` -オプションが使用できます。 - -.. note:: - - あなたが ``cake bake migration_snapshot`` コマンドでスナップショットを作成したとき、 - 自動的にマイグレーション済みとしてマーキングされてマイグレーションが作成されます。 - -.. deprecated:: 1.4.0 - - 以下のコマンドの使用方法は非推奨になりました。もし、あなたが 1.4.0 より前のバージョンの - プラグインの場合のみに使用してください。 - -このコマンドは、引数としてマイグレーションバージョン番号を想定しています。 : - -.. code-block:: bash - - bin/cake migrations mark_migrated 20150420082532 - -もし、すべてのマイグレーションをマイグレーション済みとしてマークしたい場合、 -特別な値 ``all`` を使用できます。もし使用した場合、すべての見つかったマイグレーションを -マイグレーション済みとしてマークします。 : - -.. code-block:: bash - - bin/cake migrations mark_migrated all - -``seed`` : データベースの初期データ投入 ----------------------------------------- - -1.5.5 より、データベースの初期データ投入のために ``migrations`` シェルが使用できます。 -これは、 `Phinx ライブラリーの seed 機能 `_ -を利用しています。デフォルトで、seed ファイルは、あなたのアプリケーションの ``config/Seeds`` -ディレクトリーの中に置かれます。 `seed ファイル作成のための Phinx の命令 -`_ -を確認してください。 - -マイグレーションに関して、 seed ファイルのための ``bake`` インターフェースが提供されます。 : - -.. code-block:: bash - - # これは、あなたのアプリケーションの config/Seeds ディレクトリー内に ArticlesSeed.php を作成します。 - # デフォルトでは、変換対象の seed は、 "tableized" バージョンの seed ファイル名です。 - bin/cake bake seed Articles - - # ``--table`` オプションを使用することで seed ファイルに変換するテーブル名を指定します。 - bin/cake bake seed Articles --table my_articles_table - - # bake するプラグインを指定できます。 - bin/cake bake seed Articles --plugin PluginName - - # シーダーの生成時に別の接続を指定できます。 - bin/cake bake seed Articles --connection connection - -.. versionadded:: cakephp/migrations 1.6.4 - - オプションの ``--data``, ``--limit`` そして ``--fields`` は、 - データベースからデータをエクスポートするために追加されました。 - -1.6.4 から、 ``bake seed`` コマンドは、 ``--data`` フラグを使用することによって、 -データベースからエクスポートされたデータを元に seed ファイルを作成することができます。 : - -.. code-block:: bash - - bin/cake bake seed --data Articles - -デフォルトでは、テーブル内にある行を全てエクスポートします。 ``--limit`` オプションを -使用することによって、エクスポートされる行の数を制限できます。 : - -.. code-block:: bash - - # 10 行のみエクスポート - bin/cake bake seed --data --limit 10 Articles - -もし、seed ファイルの中にテーブルから選択したフィールドのみを含めたい場合、 -``--fields`` オプションが使用できます。そのオプションは、 -フィールドのリストをカンマ区切りの値の文字列として含めます。 : - -.. code-block:: bash - - # `id`, `title` そして `excerpt` フィールドのみをエクスポート - bin/cake bake seed --data --fields id,title,excerpt Articles - -.. tip:: - - もちろん、同じコマンド呼び出し中に ``--limit`` と ``--fields`` - オプションの両方が利用できます。 - -データベースの初期データ投入のために、 ``seed`` サブコマンドが使用できます。 : - -.. code-block:: bash - - # パラメーターなしの seed サブコマンドは、対象のディレクトリーのアルファベット順で、 - # すべての利用可能なシーダーを実行します。 - bin/cake migrations seed - - # `--seed` オプションを使用して実行するための一つだけシーダーを指定できます。 - bin/cake migrations seed --seed ArticlesSeed - - # 別のディレクトリーでシーダーを実行できます。 - bin/cake migrations seed --source AlternativeSeeds - - # プラグインのシーダーを実行できます - bin/cake migrations seed --plugin PluginName - - # 指定したコネクションでシーダーを実行できます - bin/cake migrations seed --connection connection - -マイグレーションとは対照的にシーダーは追跡されないことに注意してください。 -それは、同じシーダーは、複数回適用することができることを意味します。 - -シーダーから別のシーダーの呼び出し -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: cakephp/migrations 1.6.2 - -たいてい初期データ投入時は、データの挿入する順番は、規約違反しないように遵守しなければなりません。 -デフォルトでは、アルファベット順でシーダーが実行されますが、独自にシーダーの実行順を定義するために -``\Migrations\AbstractSeed::call()`` メソッドが利用できます。 :: - - use Migrations\AbstractSeed; - - class DatabaseSeed extends AbstractSeed - { - public function run(): void - { - $this->call('AnotherSeed'); - $this->call('YetAnotherSeed'); - - // プラグインからシーダーを呼ぶためにプラグインドット記法が使えます - $this->call('PluginName.FromPluginSeed'); - } - } - -.. note:: - - もし、 ``call()`` メソッドを使いたい場合、Migrations プラグインの ``AbstractSeed`` - クラスを継承していることを確認してください。このクラスは、リリース 1.6.2 で追加されました。 - -``dump`` : 差分を bake する機能のためのダンプファイルの生成 -------------------------------------------------------------- - -dump コマンドは、 ``migration_diff`` の bake テンプレートで使用するファイルを作成します。 : - -.. code-block:: bash - - bin/cake migrations dump - -各生成されたダンプファイルは、生成元の接続固有のものです(そして、そのようにサフィックスされます)。 -これは、アプリケーションが、異なるデータベースベンダーの複数のデータベースを扱う場合、 -``bake migration_diff`` コマンドで正しく差分を算出することができます。 - -ダンプファイルは、マイグレーションファイルと同じディレクトリーに作成されます。 - -``migrate`` コマンドのように ``--source`` 、 ``--connection`` そして ``--plugin`` -オプションが使用できます。 - -プラグイン内のマイグレーションファイルを使う -============================================ - -プラグインはマイグレーションファイルも提供することができます。 -これはプラグインの移植性とインストールの容易さを高め、配布しやすくなるように意図されています。 -Migrations プラグインの全てのコマンドは、プラグイン関連のマイグレーションを行うための -``--plugin`` か ``-p`` オプションをサポートしています。 : - -.. code-block:: bash - - bin/cake migrations status -p PluginName - - bin/cake migrations migrate -p PluginName - -非シェルの環境でマイグレーションを実行する -========================================== - -.. versionadded:: cakephp/migrations 1.2.0 - -migrations プラグインのバージョン 1.2 から、非シェル環境でも app から直接 -``Migrations`` クラスを使ってマイグレーションを実行できるようになりました。 -これは CMS のプラグインインストーラーを作る時などに便利です。 -``Migrations`` クラスを使用すると、マイグレーションシェルから下記のコマンドを -実行することができます。: - -* migrate -* rollback -* markMigrated -* status -* seed - -それぞれのコマンドは ``Migrations`` クラスのメソッドとして実装されています。 - -使い方は以下の通りです。 :: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // 全てのマイグレーションバージョンとそのステータスの配列を返します。 - $status = $migrations->status(); - - // 成功した場合、 true を返し、エラーが発生した場合、例外が投げられます。 - $migrate = $migrations->migrate(); - - // 成功した場合、 true を返し、エラーが発生した場合、例外が投げられます。 - $rollback = $migrations->rollback(); - - // 成功した場合、 true を返し、エラーが発生した場合、例外が投げられます。 - $markMigrated = $migrations->markMigrated(20150804222900); - - // 成功した場合、 true を返し、エラーが発生した場合、例外が投げられます。 - $seeded = $migrations->seed(); - -メソッドはコマンドラインのオプションと同じパラメーター配列を受け取ります。 :: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // 全てのマイグレーションバージョンとそのステータスの配列を返す - $status = $migrations->status(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - -あなたはシェルコマンドのように任意のオプションを引き渡すことができます。 -唯一の例外は ``markMigrated`` コマンドで、第1引数にはマイグレーション済みとして -マーキングしたいマイグレーションバージョン番号を渡し、第2引数にパラメーターの配列を -渡します。 - -必要に応じて、クラスのコンストラクターでこれらのパラメーターを引き渡すことができます。 -それはデフォルトとして使用され、それぞれのメソッド呼び出しの時に引き渡されることを -防止します。 :: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // 以下のすべての呼び出しは、マイグレーションクラスのコンストラクターに渡されたパラメーターを使用して行われます - $status = $migrations->status(); - $migrate = $migrations->migrate(); - -個別の呼び出しでデフォルトのパラメーターを上書きしたい場合は、メソッド呼び出し時に引き渡します。 :: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // この呼び出しでは "custom" コネクションを使用します。 - $status = $migrations->status(); - // こちらでは "default" コネクションを使用します。 - $migrate = $migrations->migrate(['connection' => 'default']); - -小技と裏技 -=============== - -主キーをカスタマイズする ------------------------- - -あなたがデータベースに新しいテーブルを作成する時、 ``id`` を主キーとして -自動生成したくない場合、 ``table()`` メソッドの第2引数を使うことができます。 :: - - table('products', ['id' => false, 'primary_key' => ['id']]); - $table - ->addColumn('id', 'uuid') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -上記の例では、 ``CHAR(36)`` の ``id`` というカラムを主キーとして作成します。 - -.. note:: - - 独自の主キーをコマンドラインで指定した時、id フィールドの中の主キーとして注意してください。 - そうしなければ、id フィールドが重複してエラーになります。例: - - .. code-block:: bash - - bin/cake bake migration CreateProducts id:uuid:primary name:string description:text created modified - -さらに、Migrations 1.3 以降では 主キーに対処するための新しい方法が導入されました。 -これを行うには、あなたのマイグレーションクラスは新しい ``Migrations\AbstractMigration`` -クラスを継承する必要があります。 -あなたは Migration クラスの ``autoId`` プロパティーに ``false`` を設定することで、 -自動的な ``id`` カラムの生成をオフにすることができます。 -あなたは手動で主キーカラムを作成し、テーブル宣言に追加する必要があります。 :: - - table('products'); - $table - ->addColumn('id', 'integer', [ - 'autoIncrement' => true, - 'limit' => 11 - ]) - ->addPrimaryKey('id') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -主キーを扱うこれまでの方法と比較すると、この方法は、unsigned や not や limit や comment など -さらに多くの主キーの定義を操作することができるようになっています。 - -Bake で生成されたマイグレーションファイルとスナップショットは、この新しい方法を -必要に応じて使用します。 - -.. warning:: - - 主キーの操作ができるのは、テーブル作成時のみです。これはプラグインがサポートしている - いくつかのデータベースサーバーの制限によるものです。 - -照合順序 --------- - -もしデータベースのデフォルトとは別の照合順序を持つテーブルを作成する必要がある場合は、 -``table()`` メソッドのオプションとして定義することができます。:: - - table('categories', [ - 'collation' => 'latin1_german1_ci' - ]) - ->addColumn('title', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]) - ->create(); - } - } - -ですが、これはテーブル作成時にしかできず、既存のテーブルに対してカラムを追加する時に -テーブルやデータベースと異なる照合順序を指定する方法がないことに注意してください。 -ただ ``MySQL`` と ``SqlServer`` だけはこの設定キーをサポートしています。 - -カラム名の更新と Table オブジェクトの使用 ------------------------------------------ - -カラムのリネームや移動とともに、あなたのデータベースから値を操作するために -CakePHP ORM Table オブジェクトを使用している場合、 ``update()`` を呼んだ後に Table -オブジェクトの新しいインスタンスを作成できることを確かめてください。 -インスタンス上の Table オブジェクトに反映し保存されたスキーマをリフレッシュするために -Table オブジェクトのレジストリーは、 ``update()`` が呼ばれた後にクリアされます。 - -マイグレーションとデプロイメント --------------------------------- - -もし、アプリケーションをデプロイする時にプラグインを使用する場合、 -テーブルのカラムメタデータを更新するように、必ず ORM キャッシュをクリアしてください。 -そうしなければ、それらの新しいカラムの操作を実行する時に、カラムが存在しないエラーになります。 -CakePHP コアは、この操作を行うために使用できる `スキーマキャッシュシェル -`__ を含みます。 : - -.. code-block:: bash - - // 3.6.0 より前の場合、orm_cache を使用 - bin/cake schema_cache clear - -このシェルについてもっと知りたい場合、クックブックの -`スキーマキャッシュシェル `__ -セクションをご覧ください。 - -テーブルのリネーム ------------------- - -プラグインは、 ``rename()`` メソッドを使用することでテーブルのリネームができます。 -あなたのマイグレーションファイルの中で、以下のように記述できます。 :: - - public function up(): void - { - $this->table('old_table_name') - ->rename('new_table_name') - ->save(); - } - -``schema.lock`` ファイル生成のスキップ --------------------------------------------- - -.. versionadded:: cakephp/migrations 1.6.5 - -diff 機能を動作させるために、 **.lock** ファイルは、migrate、rollback または -スナップショットの bake の度に生成され、指定された時点でのデータベーススキーマの状態を追跡します。 -例えば本番環境上にデプロイするときなど、前述のコマンドに ``--no-lock`` -オプションを使用することによって、このファイルの生成をスキップすることができます。 : - -.. code-block:: bash - - bin/cake migrations migrate --no-lock - - bin/cake migrations rollback --no-lock - - bin/cake bake migration_snapshot MyMigration --no-lock - diff --git a/docs/pt/conf.py b/docs/pt/conf.py deleted file mode 100644 index 9e22cb01..00000000 --- a/docs/pt/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'pt' diff --git a/docs/pt/contents.rst b/docs/pt/contents.rst deleted file mode 100644 index 1459b1f1..00000000 --- a/docs/pt/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP Migrations - - /index diff --git a/docs/pt/index.rst b/docs/pt/index.rst deleted file mode 100644 index be48eb7a..00000000 --- a/docs/pt/index.rst +++ /dev/null @@ -1,943 +0,0 @@ -Migrations -########## - -Migrations é um plugin suportado pela equipe oficial do CakePHP que ajuda você a -fazer mudanças no **schema** do banco de dados utilizando arquivos PHP, -que podem ser versionados utilizando um sistema de controle de versão. - -Ele permite que você atualize suas tabelas ao longo do tempo. Ao invés de -escrever modificações de **schema** via SQL, este plugin permite que você -utilize um conjunto intuitivo de métodos para fazer mudanças no seu banco de -dados. - -Esse plugin é um **wrapper** para a biblioteca `Phinx `_. - -Instalação -========== - -Por padrão o plugin é instalado junto com o esqueleto da aplicação. -Se você o removeu e quer reinstalá-lo, execute o comando a seguir a partir do -diretório **ROOT** da sua aplicação -(onde o arquivo composer.json está localizado): - -.. code-block:: bash - - $ php composer.phar require cakephp/migrations "@stable" - - # Or if composer is installed globally - - $ composer require cakephp/migrations "@stable" - -Para usar o plugin você precisa carregá-lo no arquivo **config/bootstrap.php** -da sua aplicação. Você pode usar o -`shell de plugins do CakePHP -`__ para carregar e descarregar -plugins do seu arquivo **config/bootstrap.php**:: - - $ bin/cake plugin load Migrations - -Ou você pode carregar o plugin editando seu arquivo **config/bootstrap.php** e -adicionando a linha:: - - Plugin::load('Migrations'); - -Adicionalmente, você precisará configurar o banco de dados padrão da sua -aplicação, no arquivo **config/app.php** como explicado na seção -`Configuração de banco de dados `__. - -Visão Geral -=========== - -Uma migração é basicamente um arquivo PHP que descreve as mudanças a -serem feitas no banco de dados. Um arquivo de migração pode criar ou excluir -tabelas, adicionar ou remover colunas, criar índices e até mesmo inserir -dados em seu banco de dados. - -Aqui segue um exemplo de migração:: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -Essa migração irá adicionar uma tabela chamada ``products`` ao banco de dados -com as seguintes colunas: - -- ``id`` coluna do tipo ``integer`` como chave primária -- ``name`` coluna do tipo ``string`` -- ``description`` coluna do tipo ``text`` -- ``created`` coluna do tipo ``datetime`` -- ``modified`` coluna do tipo ``datetime`` - -.. tip:: - - A coluna de chave primária ``id`` será adicionada **implicitamente**. - -.. note:: - - Note que este arquivo descreve como o banco de dados deve ser **após** a - aplicação da migração. Neste ponto, a tabela ``products``ainda não existe - no banco de dados, nós apenas criamos um arquivo que é capaz de criar a - tabela ``products`` com seus devidos campos ou excluir a tabela caso uma - operação rollback seja executada. - -Com o arquivo criado na pasta **config/MIgrations**, você será capaz de executar -o comando abaixo para executar as migrações no seu banco de dados:: - - bin/cake migrations migrate - -O comando seguinte irá executar um **rollback** na migração e irá excluir a -tabela recém criada:: - - bin/cake migrations rollback - -Criando migrations -================== - -Arquivos de migração são armazeados no diretório **config/Migrations** da -sua aplicação. O nome dos arquivos de migração têm como prefixo a data -em que foram criados, no formato **YYYYMMDDHHMMSS_MigrationName.php**. Aqui -estão exemplos de arquivos de migração: - -* 20160121163850_CreateProducts.php -* 20160210133047_AddRatingToProducts.php - -A maneira mais fácil de criar um arquivo de migrações é usando o -``bin/cake bake migration`` a linha de comando. - -Por favor, leia a `documentação do Phinx ` -a fim de conhecer a lista completa dos métodos que você pode usar para escrever -os arquivos de migração. - -.. note:: - - Ao gerar as migrações através do ``bake`` você ainda pode alterá-las antes - da sua execução, caso seja necessário. - -Sintaxe -------- - -A sintaxe do ``bake`` para a geração de migrações segue o formato abaixo:: - - $ bin/cake bake migration CreateProducts name:string description:text created modified - -Quando utilizar o ``bake`` para criar as migrações, você normalmente precisará -informar os seguintes dados:: - - * o nome da migração que você irá gerar (``CreateProducts`` por exemplo) - * as colunas da tabela que serão adicionadas ou removidas na migração - (``name:string description:text created modified`` no nosso caso) - -Devido às convenções, nem todas as alterações de schema podem ser realizadas -através destes comandos. - -Além disso, você pode criar um arquivo de migração vazio caso deseje ter um -controle total do que precisa ser executado. Para isto, apenas omita a definição -das colunas:: - - $ bin/cake migrations create MyCustomMigration - -Nomenclatura de migrations -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A nomenclatura das migrações pode seguir qualquer um dos padrões apresentados a -seguir: - -* (``/^(Create)(.*)/``) Cria a tabela especificada. -* (``/^(Drop)(.*)/``) Exclui a tabela especificada. - Ignora campos especificados nos argumentos -* (``/^(Add).*(?:To)(.*)/``) Adiciona campos a - tabela especificada -* (``/^(Remove).*(?:From)(.*)/``) Remove campos de uma - tabela específica -* (``/^(Alter)(.*)/``) Altera a tabela especificada. Um apelido para - um CreateTable seguido de um AlterTable -* (``/^(Alter).*(?:On)(.*)/``) Alterar os campos da tabela especificada - -Você também pode usar ``underscore_form`` como nome das suas **migrations**. -Ex.: ``create_products``. - -.. versionadded:: cakephp/migrations 1.5.2 - - A partir da versão 1.5.2 do `plugin migrations `_, - o nome dos arquivos de migrações são colocados automaticamente no padrão - **camel case**. - Esta versão do plugin está disponível apenas a partir da versão 3.1 do - CakePHP. - Antes disto, o padrão de nomes do plugin migrations utilizava a nomenclatura - baseada em **underlines**, ex.: ``20160121164955_create_products.php``. - -.. warning:: - - O nome das migrações são usados como nomes de classe, e podem colidir com - outras migrações se o nome das classes não forem únicos. Neste caso, pode - ser necessário sobreescrever manualmente os nomes mais tarde ou simplesmente - mudar os nomes que você está especificando. - -Definição de colunas -~~~~~~~~~~~~~~~~~~~~ - -Quando utilizar colunas na linha de comando, pode ser útil lembrar que eles seguem o -seguinte padrão:: - - fieldName:fieldType[length]:indexType:indexName - -Por exemplo, veja formas válidas de especificar um campo de e-mail: - -* ``email:string:unique`` -* ``email:string:unique:EMAIL_INDEX`` -* ``email:string[120]:unique:EMAIL_INDEX`` - -O parâmetro ``length`` para o ``fieldType`` é opcional e deve sempre ser -escrito entre colchetes - -Os campos ``created`` e ``modified`` serão automaticamente definidos -como ``datetime``. - -Os tipos de campos são genericamente disponibilizados pela biblioteca ``Phinx``. -Eles podem ser: - -* string -* text -* integer -* biginteger -* float -* decimal -* datetime -* timestamp -* time -* date -* binary -* boolean -* uuid - -Há algumas heurísticas para a escolha de tipos de campos que não são especificados -ou são definidos com valor inválido. O tipo de campo padrão é ``string``; - -* id: integer -* created, modified, updated: datetime - -Criando uma tabela ------------------- - -Você pode utilizar o ``bake`` para criar uma tabela:: - - $ bin/cake bake migration CreateProducts name:string description:text created modified - -A linha de comando acima irá gerar um arquivo de migração parecido com este:: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -Adicionando colunas a uma tabela existente ------------------------------------------- - -Se o nome da migração na linha de comando estiver na forma "AddXXXToYYY" e -for seguido por uma lista de nomes de colunas e tipos, então o arquivo de -migração com o código para criar as colunas será gerado:: - - $ bin/cake bake migration AddPriceToProducts price:decimal - -A linha de comando acima irá gerar um arquivo com o seguinte conteúdo:: - - table('products'); - $table->addColumn('price', 'decimal') - ->update(); - } - } - -Adicionando uma coluna como indice a uma tabela ------------------------------------------------ - -Também é possível adicionar índices a colunas:: - - $ bin/cake bake migration AddNameIndexToProducts name:string:index - -irá gerar:: - - table('products'); - $table->addColumn('name', 'string') - ->addIndex(['name']) - ->update(); - } - } - -Especificando o tamanho do campo --------------------------------- - -.. versionadded:: cakephp/migrations 1.4 - -Se você precisar especificar o tamanho do campo, você pode fazer isto entre -colchetes logo após o tipo do campo, ex.:: - - $ bin/cake bake migration AddFullDescriptionToProducts full_description:string[60] - -Executar o comando acima irá gerar:: - - table('products'); - $table->addColumn('full_description', 'string', [ - 'default' => null, - 'limit' => 60, - 'null' => false, - ]) - ->update(); - } - } - -Se o tamanho não for especificado, os seguintes padrões serão utilizados: - -* string: 255 -* integer: 11 -* biginteger: 20 - -Alterar uma coluna de uma tabela ------------------------------------ - -Da mesma maneira, você pode gerar uma migração para alterar uma coluna usando a -linha de comando, se o nome da migração estiver no formato "X""AlterXXXOnYYY": - -.. code-block:: bash - - bin/cake bake migration AlterPriceOnProducts name:float - -Cria o arquivo:: - - table('products'); - $table->changeColumn('name', 'float'); - $table->update(); - } - } - -Removendo uma coluna de uma tabela ----------------------------------- - -Da mesma forma, você pode gerar uma migração para remover uma coluna -utilizando a linha de comando, se o nome da migração estiver na forma -"RemoveXXXFromYYY":: - - $ bin/cake bake migration RemovePriceFromProducts price - -Cria o arquivo:: - - table('products'); - $table->removeColumn('price'); - } - } - -Gerando migrações a partir de uma base de dados existente -========================================================= - -Se você está trabalhando com um banco de dados pré-existente e quer começar -a usar migrações, ou para versionar o schema inicial da base de dados da sua -aplicação, você pode executar o comando ``migration_snapshot``:: - - $ bin/cake bake migration_snapshot Initial - -Isto irá gerar um arquivo de migração chamado **YYYYMMDDHHMMSS_Initial.php** -contendo todas as instruções CREATE para todas as tabelas no seu banco de dados. - -Por padrão, o snapshot será criado a partir da conexão ``default`` definida na -configuração. -Se você precisar fazer o bake de um snapshot de uma fonte de dados diferente, -você pode utilizar a opção ``--connection``:: - - $ bin/cake bake migration_snapshot Initial --connection my_other_connection - -Você também pode definir que o snapshot inclua apenas as tabelas para as quais -você tenha definido models correspendentes, utilizando a flag -``require-table``:: - - $ bin/cake bake migration_snapshot Initial --require-table - -Quando utilizar a flag ``--require-table``, o shell irá olhar através das -classes do diretório ``Table`` da sua aplicação e apenas irá adicionar no -snapshot as tabelas lá definidas. - -A mesma lógica será aplicada implicitamente se você quiser fazer o bake de um -snapshot para um plugin. Para fazer isso, você precisa usar a opção -``--plugin``, veja a seguir:: - - $ bin/cake bake migration_snapshot Initial --plugin MyPlugin - -Apenas as tabelas que tiverem um objeto ``Table`` definido serão adicionadas -ao snapshot do seu plugin. - -.. note:: - - Quando fizer o bake de um snapshot para um plugin, os arquivos de migrações - serão criados no diretório **config/Migrations** do seu plugin. - -Fique atento que quando você faz o bake de um snapshot, ele é automaticamente - adicionado ao log do phinx como migrado. - -Gerando um *diff* entre dois estados da base de dados -===================================================== - -.. versionadded:: cakephp/migrations 1.6.0 - -Você pode gerar um arquivo de migração que agrupará todas as diferenças entre -dois estados de uma base de dados usando ``migration_diff``. Para fazê-lo, -você pode usar o seguinte comando:: - - $ bin/cake bake migration_diff NomeDasMigrações - -De forma a ter um ponto de comparação do estado atual da sua base de dados, a -*shell* de ``migrations`` gerará um arquivo de *dump* após cada chamada de -``migrate`` ou ``rollback``. O arquivo de *dump* é um arquivo contendo o -estado completo do esquema da sua base de dados em um determinado instante no -tempo. - -Uma vez gerado o arquivo de *dump*, cada modificação que você fizer -diretamente no seu sistema de gerenciamento da base de dados será adicionada -quando você chamar o comando ``bake migration_diff``. - -Por padrão, o *diff* será criado através de uma conexão com a base de dados -definida na configuração de conexão ``default``. -Se você precisar criar um *diff* de uma fonte de dados diferente, você pode -usar a opção ``--connection``:: - - $ bin/cake bake migration_diff NomeDasMigrações --connection minha_outra_conexão - -Se você quiser usar a funcionalidade de *diff* em uma aplicação que já possui -um histórico de migrações, você precisará criar manualmente o arquivo de -*dump* a ser usado como base da comparação:: - - $ bin/cake migrations dump - -O estado da base de dados deve ser o mesmo que você teria caso você tivesse -migrado todas as suas migrações antes de criar o arquivo de *dump*. -Uma vez que o arquivo de *dump* for gerado, você pode começar a fazer -modificações na sua base de dados e usar o comando ``bake migration_diff`` -sempre que desejar. - -.. note:: - - A *shell* de migrações não é capaz de detectar colunas renomeadas. - -Os Comandos -=========== - -``migrate`` : Aplicando migrações ---------------------------------- - -Depois de ter gerado ou escrito seu arquivo de migração, você precisa executar -o seguinte comando para aplicar as mudanças a sua base de dados:: - - # Executa todas as migrações - $ bin/cake migrations migrate - - # Execute uma migração específica utilizando a opção ``--target`` ou ``-t`` - # O valor é um timestamp que serve como prefixo para cada migração:: - $ bin/cake migrations migrate -t 20150103081132 - - # Por padrão, as migrações ficam no diretório **config/Migrations**. Você - # pode especificar um diretório utilizando a opção ``--source`` ou ``-s``. - # O comando abaixo executa as migrações no diretório **config/Alternate** - $ bin/cake migrations migrate -s Alternate - - # Você pode executar as migrações de uma conexão diferente da ``default`` - # utilizando a opção ``--connection`` ou ``-c``. - $ bin/cake migrations migrate -c my_custom_connection - - # Migrações também podem ser executadas para plugins. Simplesmente utilize - # a opção ``--plugin`` ou ``-p`` - $ bin/cake migrations migrate -p MyAwesomePlugin - -``rollback`` : Revertendo migrações ------------------------------------ - -O comando rollback é utilizado para desfazer migrações realizadas anteriormente -pelo plugin Migrations. É o inverso do comando ``migrate``:: - - # Você pode desfazer uma migração anterior utilizando o - # comando ``rollback``:: - $ bin/cake migrations rollback - - # Você também pode passar a versão da migração para voltar - # para uma versão específica:: - $ bin/cake migrations rollback -t 20150103081132 - -Você também pode utilizar as opções ``--source``, ``--connection`` e -``--plugin`` exatamente como no comando ``migrate``. - -``status`` : Status da migração -------------------------------- - -O comando status exibe uma lista de todas as migrações juntamente com seu -status. Você pode utilizar este comando para ver quais migrações foram -executadas:: - - $ bin/cake migrations status - -Você também pode ver os resultados como JSON utilizando a opção -``--format`` (ou ``-f``):: - - $ bin/cake migrations status --format json - -Você também pode utilizar as opções ``--source``, ``--connection`` e -``--plugin`` exatamente como no comando ``migrate``. - -``mark_migrated`` : Marcando uma migração como migrada ------------------------------------------------------- - -.. versionadded:: 1.4.0 - -Algumas vezes pode ser útil marcar uma lista de migrações como migrada sem -efetivamente executá-las. -Para fazer isto, você pode usar o comando ``mark_migrated``. O comando é -bastante semelhante aos outros comandos. - -Você pode marcar todas as migrações como migradas utilizando este comando:: - - $ bin/cake migrations mark_migrated - -Você também pode marcar todas as migrações de uma versão específica -utilizando a opção ``--target``:: - - $ bin/cake migrations mark_migrated --target=20151016204000 - -Se você não quer marcar a migração alvo como migrada durante o processo, você -pode utilizar a opção ``--exclude``:: - - $ bin/cake migrations mark_migrated --target=20151016204000 --exclude - -Finalmente, se você deseja marcar somente a migração alvo como migrada, -você pode utilizar a opção ``--only``:: - - $ bin/cake migrations mark_migrated --target=20151016204000 --only - -Você também pode utilizar as opções ``--source``, ``--connection`` e -``--plugin`` exatamente como no comando ``migrate``. - -.. note:: - - Quando você criar um snapshot utilizando o bake com o comando - ``cake bake migration_snapshot``, a migração criada será automaticamente - marcada como migrada. - -.. deprecated:: 1.4.0 - - A seguinte maneira de utilizar o comando foi depreciada. Use somente se - você estiver utilizando uma versão do plugin inferior a 1.4.0. - -Este comando espera um número de versão de migração como argumento:: - - $ bin/cake migrations mark_migrated - -Se você deseja marcar todas as migrações como migradas, você pode utilizar -o valor especial ``all``. Se você o utilizar, ele irá marcar todas as migrações -como migradas:: - - $ bin/cake migrations mark_migrated all - -``seed`` : Populando seu banco de dados ---------------------------------------- - -A partir da versão 1.5.5, você pode usar a **shell** de ``migrations`` para -popular seu banco de dados. Essa função é oferecida graças ao -`recurso de seed da biblioteca Phinx `_. -Por padrão, arquivos **seed** ficarão no diretório ``config/Seeds`` de sua -aplicação. Por favor, tenha certeza de seguir as -`instruções do Phinx para construir seus arquivos de seed `_. - -Assim como nos **migrations**, uma interface do ```bake`` é oferecida para gerar -arquivos de **seed**:: - - # This will create a ArticlesSeed.php file in the directory config/Seeds of your application - # By default, the table the seed will try to alter is the "tableized" version of the seed filename - $ bin/cake bake seed Articles - - # You specify the name of the table the seed files will alter by using the ``--table`` option - $ bin/cake bake seed Articles --table my_articles_table - - # You can specify a plugin to bake into - $ bin/cake bake seed Articles --plugin PluginName - - # You can specify an alternative connection when generating a seeder. - $ bin/cake bake seed Articles --connection connection - -.. versionadded:: cakephp/migrations 1.6.4 - - As opções ``--data``, ``--limit`` e ``--fields`` foram adicionadas para - exportar dados da sua base de dados. - -A partir da versão 16.4, o comando ``bake seed`` permite que você crie um -arquivo de *seed* com dados exportados da sua base de dados com o uso da -*flag* ``--data``:: - - $ bin/cake bake seed --data Articles - -Por padrão, esse comando exportará todas as linhas encontradas na sua -tabela. Você pode limitar o número de linhas a exportar usando a opção -``--limit``:: - - # Exportará apenas as 10 primeiras linhas encontradas - $ bin/cake bake seed --data --limit 10 Articles - -Se você deseja incluir apenas uma seleção dos campos da tabela no seu -arquivo de *seed*, você pode usar a opção ``--fields``. Ela recebe a -lista de campos a incluir na forma de uma *string* separada por -vírgulas:: - - # Exportará apenas os campos `id`, `title` e `excerpt` - $ bin/cake bake seed --data --fields id,title,excerpt Articles - -.. tip:: - - Você pode utilizar ambas as opções ``--limit`` e ``--fields`` - simultaneamente em uma mesma chamada. - -Para popular seu banco de dados, você pode usar o subcomando ``seed``:: - - # Without parameters, the seed subcommand will run all available seeders - # in the target directory, in alphabetical order. - $ bin/cake migrations seed - - # You can specify only one seeder to be run using the `--seed` option - $ bin/cake migrations seed --seed ArticlesSeed - - # You can run seeders from an alternative directory - $ bin/cake migrations seed --source AlternativeSeeds - - # You can run seeders from a plugin - $ bin/cake migrations seed --plugin PluginName - - # You can run seeders from a specific connection - $ bin/cake migrations seed --connection connection - -Esteja ciente que, ao oposto das **migrations**, **seeders** não são -versionados, o que significa que o mesmo **seeder** pode ser aplicado diversas -vezes. - -Usando migrations em plugins -============================ - -**Plugins** também podem oferecer **migrations**. Isso faz com que **plugins** -que são planejados para serem distribuídos tornem-se muito mais práticos e -fáceis de instalar. Todos os comandos do plugin **Migrations** suportam a opção -``--plugin`` ou ``-p``, que por sua vez vai delegar a execução da tarefa ao -escopo relativo a um determinado **plugin**:: - - $ bin/cake migrations status -p PluginName - - $ bin/cake migrations migrate -p PluginName - -Executando migrations em ambientes fora da linha de comando -=========================================================== - -.. versionadded:: cakephp/migrations 1.2.0 - -Desde o lançamento da versão 1.2 do plugin, você pode executar **migrations** -fora da linha de comando, diretamente de uma aplicação, ao usar a nova classe -``Migrations``. Isso pode ser muito útil caso você esteja desenvolvendo um -instalador de **plugins** para um CMS, para exemplificar. - -A classe ``Migrations`` permite que você execute os seguintes comandos -disponíveis na **shell**: - -* migrate -* rollback -* markMigrated -* status -* seed - -Cada um desses comandos tem um método definido na classe ``Migrations``. - -Veja como usá-la:: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // Retornará um array de todos migrations e seus status - $status = $migrations->status(); - - // Retornará true se bem sucedido. Se um erro ocorrer, uma exceção será lançada - $migrate = $migrations->migrate(); - - // Retornará true se bem sucedido. Se um erro ocorrer, uma exceção será lançada - $rollback = $migrations->rollback(); - - // Retornará true se bem sucedido. Se um erro ocorrer, uma exceção será lançada - $markMigrated = $migrations->markMigrated(20150804222900); - - // Retornará true se bem sucedido. Se um erro ocorrer, uma exceção será lançada - $seeded = $migrations->seed(); - -Os métodos aceitam um **array** de parâmetros que devem combinar com as opções -dos comandos:: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // Retornará um array de todos migrations e seus status - $status = $migrations->status(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - -Você pode passar qualquer opção que esteja disponível pelos comandos **shell**. -A única exceção é o comando ``markMigrated`` que espera um número de versão a -ser marcado como migrado, como primeiro argumento. Passe o **array** de -parâmetros como segundo argumento nesse caso. - -Opcionalmente, você pode passar esses parâmetros pelo construtor da classe. -Eles serão usados como padrão evitando que você tenha que passá-los em cada -chamada do método:: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // Todas as chamadas de métodos serão executadas usando os parâmetros passados pelo construtor da classe - $status = $migrations->status(); - $migrate = $migrations->migrate(); - -Se você precisar sobrescrever um ou mais parâmetros definidos previamente, você -pode passá-los para um método:: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // Essa chamada será feita com a conexão "custom" - $status = $migrations->status(); - // Essa chamada será feita com a conexão "default" - $migrate = $migrations->migrate(['connection' => 'default']); - -Dicas e truques -=============== - -Criando chaves primárias customizadas -------------------------------------- - -Se você precisa evitar a criação automática da chave primária ``id`` ao -adicioanr novas tabelas ao banco de dados, é possível usar o segundo argumento -do método ``table()``:: - - table('products', ['id' => false, 'primary_key' => ['id']]); - $table - ->addColumn('id', 'uuid') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -O código acima vai criar uma coluna ``CHAR(36)`` ``id`` que também é a chave -primária. - -.. note:: - - Ao especificar chaves primárias customizadas pela linha de comando, você - deve apontá-las como chave primária no campo id, caso contrário você pode - receber um erro apontando campos diplicados, i.e.:: - - $ bin/cake bake migration CreateProducts id:uuid:primary name:string description:text created modified - -Adicionalmente, desde a versão 1.3, uma novo meio de lidar com chaves primárias -foi introduzido. Para tal, sua classe de migração deve estender a nova classe -``Migrations\AbstractMigration``. - -Você pode especificar uma propriedade ``autoId`` na sua classe e defini-la como -``false``, o quê desabilitará a geração automática da coluna ``id``. Você -vai precisar criar manualmente a coluna que será usada como chave primária e -adicioná-la à declaração da tabela:: - - table('products'); - $table - ->addColumn('id', 'integer', [ - 'autoIncrement' => true, - 'limit' => 11 - ]) - ->addPrimaryKey('id') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -Comparado ao método apresentado anteriormente de lidar com chaves primárias, -nesse método, temos a possibilidade de ter maior controle sobre as definições -da coluna da chave primária: -unsigned, limit, comentários, etc. - -Todas as migrations e snapshots criadas pelo bake vão usar essa nova forma -quando necessário. - -.. warning:: - - Lidar com chaves primárias só é possível no momento de criação de tabelas. - Isso é devido a algumas limitações de alguns servidores de banco de dados - que o plugin suporta. - -Colações --------- - -Se você precisar criar uma tabela com colação diferente do padrão do banco de -dados, você pode defini-la pelo método ``table()``, como uma opção:: - - table('categories', [ - 'collation' => 'latin1_german1_ci' - ]) - ->addColumn('title', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]) - ->create(); - } - } - -Note que isso só pode ser feito na criação da tabela : não há atualmente uma -forma de adicionar uma coluna a uma tabela existente com uma colação diferente -do padrão da tabela, ou mesmo do banco de dados. -Apenas ``MySQL`` e ``SqlServer`` suportam essa chave de configuração. - -Atualizando nome de colunas e usando objetos de tabela ------------------------------------------------------- - -Se você usa um objeto ORM Table do CakePHP para manipular valores do seu banco -de dados, renomeando ou removendo uma coluna, certifique-se de criar uma nova -instância do seu objeto depois da chamada do ``update()``. O registro do objeto -é limpo depois da chamada do ``update()`` para atualizar o **schema** que é -refletido e armazenado no objeto ``Table`` paralelo à instanciação. - -Migrations e Deployment ------------------------ - -Se você usa o plugin ao fazer o **deploy** de sua aplicação, garanta que o cache -ORM seja limpo para renovar os metadados das colunas de suas tabelas. -Caso contrário, você pode acabar recebendo erros relativos a colunas -inexistentes ao criar operações nessas mesmas colunas. -O **core** do CakePHP possui uma -`Schema Cache Shell `__ -que você pode usar para realizar essas operação:: - - $ bin/cake schema_cache clear - -Leia a seção `Schema Cache Shell -`__ do cookbook -se você quiser conhecer mais sobre essa **shell**. diff --git a/docs/ru/conf.py b/docs/ru/conf.py deleted file mode 100644 index f8a170ee..00000000 --- a/docs/ru/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'ru' diff --git a/docs/ru/contents.rst b/docs/ru/contents.rst deleted file mode 100644 index 1459b1f1..00000000 --- a/docs/ru/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP Migrations - - /index diff --git a/docs/ru/index.rst b/docs/ru/index.rst deleted file mode 100644 index 92f1a7e1..00000000 --- a/docs/ru/index.rst +++ /dev/null @@ -1,1020 +0,0 @@ -Миграции -######## - -Миграции (Migrations) - это плагин, поддерживаемый основной командой, который помогает вам выполнять -изменение схемы вашей базе данных путём написания файлов PHP, которые можно отслеживать с помощью -системы управления версиями. - -Это позволяет вам постепенно менять таблицы базы данных. Вместо написания -модификации схемы в виде SQL, этот плагин позволяет вам использовать интуитивно -понятный набор методов для изменения вашей базы данных. - -Этот плагин является обёрткой для библиотеки миграции баз данных `Phinx `_. - -Установка -========= - -По умолчанию Migrations устанавливается вместе с дефолтным скелетом приложения. -Если вы удалили его и хотите его переустановить, вы можете сделать это, запустив -следующее из каталога ROOT вашего приложения (где находится файл composer.json): - -.. code-block:: bash - - $ php composer.phar require cakephp/migrations "@stable" - - # Или, если композитор установлен глобально - - $ composer require cakephp/migrations "@stable" - -Чтобы использовать плагин, вам нужно загрузить его в файле **config/bootstrap.php** -вашего приложения. Вы можете использовать -`CakePHP's Plugin shell -`__ для загрузки и выгрузки плагинов из -вашего **config/bootstrap.php**:: - - $ bin/cake plugin load Migrations - -Или вы можете загрузить плагин, отредактировав файл **config/bootstrap.php** -и добавив следующий оператор:: - - Plugin::load('Migrations'); - -Кроме того, вам нужно будет настроить конфигурацию базы данных по умолчанию для вашего -приложения в файле **config/app.php**, как описано в -`Раздел о конфигурации БД -`__. - -Обзор -===== - -Миграция в основном представляет собой один файл PHP, который описывает изменения -для работы с базой данных. Файл миграции может создавать или удалять таблицы, -добавлять или удалять столбцы, создавать индексы и даже вставлять данные в вашу базу данных. - -Вот пример миграции:: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -Эта миграция добавит таблицу в вашу базу данных под названием ``products`` -со следующими определениями столбцов: - -- ``id`` столбец типа ``integer`` как primary key (первичный ключ) -- ``name`` столбец типа ``string`` -- ``description`` столбец типа ``text`` -- ``created`` столбец типа ``datetime`` -- ``modified`` столбец типа ``datetime`` - -.. tip:: - - Столбец первичного ключа с именем ``id`` будет добавлен **неявно**. - -.. note:: - - Обратите внимание, что этот файл описывает, как будет выглядеть база - данных **после** применения миграции. На данный момент в вашей базе - данных нет таблицы ``products``, мы просто создали файл, который способен - создавать таблицу ``products`` с указанными столбцами, а также удалить её, - когда выполняется ``rollback`` операция миграции. - -После того, как файл был создан в папке **config/Migrations**, вы сможете -выполнить следующую команду ``migrations``, чтобы создать таблицу в своей -базе данных:: - - bin/cake migrations migrate - -Следующая команда ``migrations`` выполнит ``rollback`` и удалит эту таблицу -из вашей базы данных:: - - bin/cake migrations rollback - -Создание миграций -================= - -Файлы миграции хранятся в каталоге **config/Migrations** вашего приложения. -Имя файлов миграции имеет префикс даты, в которой они были созданы, в -формате **YYYYMMDDHHMMSS_MigrationName.php**. Ниже приведены примеры имён -файлов миграции: - -* 20160121163850_CreateProducts.php -* 20160210133047_AddRatingToProducts.php - -Самый простой способ создать файл миграции - это использовать команду CLI -``bin/cake bake migration``. - -Пожалуйста, убедитесь, что вы читали официальную -`Phinx documentation `_ -чтобы узнать полный список методов, которые вы можете использовать для -записи файлов миграции. - -.. note:: - - При использовании опции ``bake`` вы всё равно можете изменить миграции, - прежде чем запускать их, если это необходимо. - -Синтаксис ---------- - -Синтаксис команды ``bake`` следует форме ниже:: - - $ bin/cake bake migration CreateProducts name:string description:text created modified - -При использовании ``bake`` для создания таблиц, добавления столбцов и т. п. в -вашей базе данных, вы обычно предоставляете две вещи: - -* имя миграции, которую вы создадите (``CreateProducts`` в нашем примере) -* столбцы таблицы, которые будут добавлены или удалены в процессе миграции - (``name: string description: text created modified`` в нашем примере) - -В связи с соглашениями CakePHP, не все изменения схемы могут выполняться с помощью этих -команд оболочки. - -Кроме того, вы можете создать пустой файл миграции, если хотите получить полный контроль -над тем, что нужно выполнить, указав определение столбцов:: - - $ bin/cake migrations create MyCustomMigration - -Имя файла миграции -~~~~~~~~~~~~~~~~~~ - -Имена миграции могут следовать любому из следующих шаблонов: - -* (``/^(Create)(.*)/``) Создаёт указанную таблицу. -* (``/^(Drop)(.*)/``) Уничтожает указанную таблицу. - Игнорирует аргументы заданного поля. -* (``/^(Add).*(?:To)(.*)/``) Добавляет поля в указанную таблицу. -* (``/^(Remove).*(?:From)(.*)/``) Удаляет поля из указанной таблицы. -* (``/^(Alter)(.*)/``) Изменяет указанную таблицу. Псевдоним для - CreateTable и AddField. -* (``/^(Alter).*(?:On)(.*)/``) Изменяет поля указанной таблицы. - -Вы также можете использовать ``underscore_form`` как имя для своих миграций, например -``create_products``. - -.. versionadded:: cakephp/migrations 1.5.2 - - Начиная с версии 1.5.2 `migrations plugin `_, - имя файла миграции будет автоматически изменено. Эта версия плагина доступна только - с выпуском CakePHP> = to 3.1. До этой версии плагина имя миграции было бы в форме - подчеркивания, то есть ``20160121164955_create_products.php``. - -.. warning:: - - Имена миграции используются как имена классов миграции и, таким образом, - могут сталкиваться с другими миграциями, если имена классов не уникальны. - В этом случае может потребоваться вручную переопределить имя на более - позднюю дату или просто изменить имя, которое вы указываете. - -Определение столбцов -~~~~~~~~~~~~~~~~~~~~ - -При использовании столбцов в командной строке может быть удобно запомнить, что они -используют следующий шаблон:: - - fieldName:fieldType?[length]:indexType:indexName - -Например, все допустимые способы указания поля электронной почты: - -* ``email:string?`` -* ``email:string:unique`` -* ``email:string?[50]`` -* ``email:string:unique:EMAIL_INDEX`` -* ``email:string[120]:unique:EMAIL_INDEX`` - -Знак вопроса, следующий за типом fieldType, сделает столбец нулевым. - -Параметр ``length`` для ``fieldType`` является необязательным и всегда должен быть -записан в скобках. - -Поля с именем ``created`` и ``modified``, а также любое поле с суффиксом ``_at`` -автоматически будут установлены в тип ``datetime``. - -Типы полей поддерживаемые библиотекой ``Sphinx``: - -* string -* text -* integer -* biginteger -* float -* decimal -* datetime -* timestamp -* time -* date -* binary -* boolean -* uuid - -Существуют некоторые эвристики для выбора типов полей, если они не указаны или -установлено недопустимое значение. Тип поля по умолчанию - ``string``: - -* id: integer -* created, modified, updated: datetime - -Создание таблицы ----------------- - -Вы можете использовать ``bake`` для создания таблицы:: - - $ bin/cake bake migration CreateProducts name:string description:text created modified - -В приведённой выше командной строке будет создан файл миграции, напоминающий:: - - table('products'); - $table->addColumn('name', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]); - $table->addColumn('description', 'text', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('created', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->addColumn('modified', 'datetime', [ - 'default' => null, - 'null' => false, - ]); - $table->create(); - } - } - -Добавление столбцов в существующую таблицу ------------------------------------------- - -Если имя миграции в командной строке имеет форму "AddXXXToYYY" и за ней следует -список имён столбцов и типов, тогда будет создан файл миграции, содержащий код -для создания столбцов:: - - $ bin/cake bake migration AddPriceToProducts price:decimal - -Выполнение приведенной выше командной строки сгенерирует:: - - table('products'); - $table->addColumn('price', 'decimal') - ->update(); - } - } - -Добавление столбца в качестве индекса в таблицу ------------------------------------------------ - -Также можно добавлять индексы в столбцы:: - - $ bin/cake bake migration AddNameIndexToProducts name:string:index - -будет сгенерировано:: - - table('products'); - $table->addColumn('name', 'string') - ->addIndex(['name']) - ->update(); - } - } - -Указание длины поля -------------------- - -.. versionadded:: cakephp/migrations 1.4 - -Если вам нужно указать длину поля, вы можете сделать это в квадратных скобках -в поле типа:: - - $ bin/cake bake migration AddFullDescriptionToProducts full_description:string[60] - -Выполнение приведенной выше командной строки будет генерировать:: - - table('products'); - $table->addColumn('full_description', 'string', [ - 'default' => null, - 'limit' => 60, - 'null' => false, - ]) - ->update(); - } - } - -Если длина не указана, значения длины для определённого типа столбцов установятся -по умолчания как: - -* string: 255 -* integer: 11 -* biginteger: 20 - -Изменить столбец из таблицы ------------------------------------ - -Таким же образом вы можете сгенерировать миграцию для изменения столбца с помощью -командной строки, если имя миграции имеет вид "AlterXXXOnYYY": - -.. code-block:: bash - - bin/cake bake migration AlterPriceOnProducts name:float - -создаст файл:: - - table('products'); - $table->changeColumn('name', 'float'); - $table->update(); - } - } - -Удаление столбца из таблицы ---------------------------- - -Аналогичным образом вы можете сгенерировать миграцию для удаления столбца с помощью -командной строки, если имя миграции имеет форму "RemoveXXXFromYYY":: - - $ bin/cake bake migration RemovePriceFromProducts price - -создаст файл:: - - table('products'); - $table->removeColumn('price') - ->save(); - } - } - -.. note:: - - Команда `removeColumn` не является обратимой, поэтому её нужно вызывать - в методе `up`. Соответствующий вызов `addColumn` должен быть добавлен к - методу `down`. - -Создание миграции для существующей базы данных -============================================== - -Если вы имеете дело с уже существующей базой данных и хотите начать -использовать миграцию или управлять версией исходной схемы базы данных -вашего приложения, вы можете запустить команду ``migration_snapshot``:: - - $ bin/cake bake migration_snapshot Initial - -Это заставит сгенерировать файл миграции с именем **YYYYMMDDHHMMSS_Initial.php**, -содержащий все инструкции create для всех таблиц в вашей базе данных. - -По умолчанию, моментальный снимок будет создан путём подключения к базе данных, -определённой в ``default`` конфигурации подключения. - -Если же вам нужно создать снимок из другого источника данных (из другой настройки), -вы можете использовать опцию ``--connection``:: - - $ bin/cake bake migration_snapshot Initial --connection my_other_connection - -Вы также можете убедиться, что моментальный снимок содержит только те таблицы, -для которых вы определили соответствующие классы моделей, используя флаг -``--require-table``:: - - $ bin/cake bake migration_snapshot Initial --require-table - -При использовании флага ``--require-table`` оболочка будет просматривать классы -вашего приложения ``Table`` и будет добавлять таблицы модели в моментальный снимок. - -Эта же логика будет применяться неявно, если вы хотите создать снимок для плагина. -Для этого вам нужно использовать опцию ``--plugin``:: - - $ bin/cake bake migration_snapshot Initial --plugin MyPlugin - -В моментальный снимок вашего плагина будут добавлены только те таблицы, у которых -есть класс объектной модели ``Table``. - -.. note:: - - При создании моментального снимка для плагина, файлы миграции будут созданы - в каталоге **config/Migrations** вашего плагина. - -Имейте в виду, что когда вы создаёте моментальный снимок, он автоматически -добавляется в таблицу журналов sphinx как перенесённый. - -Создание разницы между двумя состояниями базы данных -==================================================== - -.. versionadded:: cakephp/migrations 1.6.0 - -Вы можете создать файл миграции, в котором будут группироваться все различия -между двумя состояниями базы данных с использованием шаблона ``migration_diff``. -Для этого вы можете использовать следующую команду:: - - $ bin/cake bake migration_diff NameOfTheMigrations - -Чтобы иметь точку сравнения с текущим состоянием базы данных, оболочка миграции -будет генерировать файл "дампа" после каждого вызова ``migrate`` или -``rollback``. Файл дампа - это файл, содержащий полное состояние схемы вашей -базы данных в данный момент времени. - -После создания дамп-файла все изменения, которые вы делаете непосредственно -в вашей системе управления базой данных, будут добавлены в файл миграции, -сгенерированный при вызове команды ``bake migration_diff``. - -По умолчанию diff будет создан путём подключения к базе данных, определенной -в конфигурации ``default``. Если вам нужно испечь diff от другого источника -данных, вы можете использовать опцию ``--connection``:: - - $ bin/cake bake migration_diff NameOfTheMigrations --connection my_other_connection - -Если вы хотите использовать функцию diff в приложении, которое уже имеет историю -миграции, вам необходимо вручную создать файл дампа, который будет использоваться -в качестве сравнения:: - - $ bin/cake migrations dump - -Состояние базы данных должно быть таким же, как если бы вы просто перенесли все -свои миграции перед созданием файла дампа. После создания файла дампа вы можете -начать делать изменения в своей базе данных и использовать команду -``bake migration_diff`` всякий раз, когда вы считаете нужным. - -.. note:: - - Оболочка миграций не может обнаруживать переименования столбцов. - -Команды -======= - -``migrate`` : Применение миграции ---------------------------------- - -После создания или записи файла миграции вам необходимо выполнить одну из -следующих команд, чтобы применить изменения в своей базе данных:: - - # Запуск всех миграций - $ bin/cake migrations migrate - - # Миграция к определённой версии, используя опцию ``--target`` - # или ``-t`` для краткости. - # Значение - это метка времени, которая имеет префикс имени файла миграции:: - $ bin/cake migrations migrate -t 20150103081132 - - # По умолчанию файлы миграции ищются в каталоге **config/Migrations**. - # Вы можете указать альтернативный каталог, используя опцию ``--source`` - # или ``-s`` для краткости. - # В следующем примере будут выполняться миграции в каталоге - # **config/Alternate** - $ bin/cake migrations migrate -s Alternate - - # Вы можете запускать миграции используя другое соединение, чем ``default``, - # для этого используйте опцию ``--connection`` или ``-c`` для краткости. - $ bin/cake migrations migrate -c my_custom_connection - - # Миграции также могут выполняться для плагинов. Просто используйте опцию - # ``--plugin`` или ``-p`` для краткости. - $ bin/cake migrations migrate -p MyAwesomePlugin - -``rollback`` : Откат миграций ------------------------------ - -Команда Rollback используется для отмены предыдущих миграций, выполняемых -этим плагином. Это обратное действие по отношения к команде ``migrate``:: - - # Вы можете вернуться к предыдущей миграции, используя команду - # ``rollback``:: - $ bin/cake migrations rollback - - # Вы также можете передать номер версии миграции для отката - # к определённой версии:: - $ bin/cake migrations rollback -t 20150103081132 - -Вы также можете использовать параметры ``--source``, ``--connection`` -и ``--plugin``, как и для ``migrate``. - -``status`` : Статус миграции ----------------------------- - -Команда Status выводит список всех миграций вместе с их текущим статусом. -Вы можете использовать эту команду, чтобы определить, какие миграции были -выполнены:: - - $ bin/cake migrations status - -Вы также можете выводить результаты как форматированную JSON строку, -используя опцию ``--format`` или ``-f`` для краткости.:: - - $ bin/cake migrations status --format json - -Вы также можете использовать параметры ``--source``, ``--connection`` -и ``--plugin``, как и для ``migrate``. - -``mark_migrated`` : Пометка миграций как перенесённые ------------------------------------------------------ - -.. versionadded:: 1.4.0 - -Иногда бывает полезно отметить набор миграций, перенесённых без их -фактического запуска. Для этого вы можете использовать команду -``mark_migrated``. Команда работает плавно, как и другие команды. - -Вы можете пометить все миграции как перенесенные с помощью этой команды:: - - $ bin/cake migrations mark_migrated - -Вы также можете пометить все миграции до определённой версии как перенесенные -с помощью параметра ``--target``:: - - $ bin/cake migrations mark_migrated --target=20151016204000 - -Если вы не хотите, чтобы целевая миграция была помечена как перенесённая во -время процесса миграции, вы можете использовать флаг ``--exclude``:: - - $ bin/cake migrations mark_migrated --target=20151016204000 --exclude - -Наконец, если вы хотите пометить только перенесённую миграцию, вы можете -использовать флаг ``--only``:: - - $ bin/cake migrations mark_migrated --target=20151016204000 --only - -Вы также можете использовать параметры ``--source``, ``--connection`` -и ``--plugin``, как и для ``migrate``. - -.. note:: - - Когда вы выпекаете моментальный снимок с помощью команды - ``cake bake migration_snapshot``, созданная миграция будет автоматически - помечена как перенесенная. - -.. deprecated:: 1.4.0 - - Следующий способ использования команды устарел. Используйте его - только в том случае, если вы используете версию плагина < 1.4.0. - -Эта команда ожидает номер версии миграции в качестве аргумента:: - - $ bin/cake migrations mark_migrated 20150420082532 - -Если вы хотите пометить все миграции как перенесенные, вы можете использовать -специальное значение ``all``. Если вы используете его, оно будет отмечать все -найденные миграции как перенесенные:: - - $ bin/cake migrations mark_migrated all - -``seed`` : Засеивание базы данных ---------------------------------- - -Начиная с 1.5.5, вы можете использовать оболочку ``migrations`` для засеивания -вашей базы данных. Это использует -`Phinx library seed feature `_. -По умолчанию файлы семян будут искать в каталоге ``config/Seeds`` вашего приложения. -Пожалуйста, убедитесь, что вы следуете -`Phinx instructions to build your seed files `_. - -Что касается миграций, для файлов семян предоставляется интерфейс ``bake``:: - - # Это создаст файл ArticlesSeed.php в каталоге config/Seeds вашего приложения. - # По умолчанию таблица, которую семя будет пытаться изменить, является "табличной" - # версией имени файла семени. - $ bin/cake bake seed Articles - - # Вы указываете имя таблицы, которую будут изменять семенные файлы, - # используя опцию ``--table`` - $ bin/cake bake seed Articles --table my_articles_table - - # Вы можете указать плагин для выпечки - $ bin/cake bake seed Articles --plugin PluginName - - # Вы можете указать альтернативное соединение при создании сеялки. - $ bin/cake bake seed Articles --connection connection - -.. versionadded:: cakephp/migrations 1.6.4 - - Для экспорта данных из базы данных были добавлены опции ``--data``, - ``--limit`` и ``--fields``. - -Начиная с версии 1.6.4 команда ``bake seed`` позволяет создать файл семян с данными, -экспортированными из вашей базы данных, с помощью флага ``--data``:: - - $ bin/cake bake seed --data Articles - -По умолчанию он будет экспортировать все строки, найденные в вашей таблице. -Вы можете ограничить количество строк, экспортированных с помощью опции -``-limit``:: - - # Будет экспортировано только первые 10 найденных строк - $ bin/cake bake seed --data --limit 10 Articles - -Если вы хотите включить только поле из таблицы в файл семени, вы можете -использовать опцию ``--fields``. Она принимает список полей для включения -в виде строки значений, разделенных запятой:: - - # Будет экспортировать только поля `id`, `title` и `excerpt` - $ bin/cake bake seed --data --fields id,title,excerpt Articles - -.. tip:: - - Конечно, вы можете использовать оба параметра ``--limit`` и ``--fields`` - в том же командном вызове. - -Чтобы засеять вашу базу данных, вы можете использовать подкоманду ``seed``:: - - # Без параметров подкоманда seed будет запускать все доступные сеялки - # в целевом каталоге, в алфавитном порядке. - $ bin/cake migrations seed - - # Вы можете указать только одну сеялку для запуска с использованием - # опции `--seed` - $ bin/cake migrations seed --seed ArticlesSeed - - # Вы можете запускать сеялки из альтернативного каталога - $ bin/cake migrations seed --source AlternativeSeeds - - # Вы можете запускать сеялки из плагина - $ bin/cake migrations seed --plugin PluginName - - # Вы можете запускать сеялки из определённого соединения - $ bin/cake migrations seed --connection connection - -Имейте в виду, что в отличие от миграций сеялки не отслеживаются, а это -означает, что одну и ту же сеялку можно применять несколько раз. - -Вызов сеялки из другой сеялки -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: cakephp/migrations 1.6.2 - -Обычно при посеве необходимо соблюдать порядок, в котором нужно вставлять данные, -чтобы не встречаться с нарушениями ограничений. Поскольку по умолчанию Seeders -выполняются в алфавитном порядке, вы можете использовать метод -``\Migrations\AbstractSeed::call()`` для определения вашей собственной -последовательности выполнения сеялок:: - - use Migrations\AbstractSeed; - - class DatabaseSeed extends AbstractSeed - { - public function run(): void - { - $this->call('AnotherSeed'); - $this->call('YetAnotherSeed'); - - // Вы можете использовать plugin dot syntax, чтобы - // вызывать сеялки из плагина - $this->call('PluginName.FromPluginSeed'); - } - } - -.. note:: - - Не забудьте расширить модуль плагина Migrations ``AbstractSeed``, если вы - хотите использовать метод ``call()``. Этот класс был добавлен с выпуском 1.6.2. - -``dump`` : Создание файла дампа для разницы выпечек ---------------------------------------------------- - -Команда Dump создаёт файл, который будет использоваться с bake шаблоном -``migration_diff``:: - - $ bin/cake migrations dump - -Каждый сгенерированный файл дампа относится к соединению, из которого он создан -(и суффикс как таковой). Это позволяет команде ``bake migration_diff`` правильно -вычислять разницу, если ваше приложение имеет дело с несколькими базами данных, -возможно, от разных поставщиков баз данных. - -Файлы дампов создаются в том же каталоге, что и файлы миграции. - -Вы также можете использовать параметры ``--source``, ``--connection`` -и ``--plugin``, как и для ``migrate``. - -Использование миграции в плагинах -================================= - -Плагины также могут предоставлять файлы миграции. Это делает плагины, которые -предназначены для распространения, гораздо более портативны и простыми в -установке. Все команды в плагине Migrations поддерживают опцию ``--plugin`` -или ``-p``, которая охватит выполнение миграции относительно этого -плагина:: - - $ bin/cake migrations status -p PluginName - - $ bin/cake migrations migrate -p PluginName - -Выполнение миграции в среде без оболочки -======================================== - -.. versionadded:: cakephp/migrations 1.2.0 - -Начиная с версии 1.2 плагина миграции вы можете запускать миграции из среды -без оболочки, непосредственно из приложения, используя новый класс ``Migrations``. -Это может быть удобно, если вы разрабатываете например инсталлятор плагинов для CMS. -Класс ``Migrations`` позволяет запускать следующие команды из оболочки миграции: - -* migrate -* rollback -* markMigrated -* status -* seed - -Каждая из этих команд имеет метод, определённый в классе ``Migrations``. - -Вот как его использовать:: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // Вернёт массив всех миграций и их статус - $status = $migrations->status(); - - // Вернёт true, если успешно. Если произошла ошибка, будет возвращено исключение - $migrate = $migrations->migrate(); - - // Вернёт true, если успешно. Если произошла ошибка, будет возвращено исключение - $rollback = $migrations->rollback(); - - // Вернёт true, если успешно. Если произошла ошибка, будет возвращено исключение - $markMigrated = $migrations->markMigrated(20150804222900); - - // Вернёт true, если успешно. Если произошла ошибка, будет возвращено исключение - $seeded = $migrations->seed(); - -Методы могут принимать массив параметров, которые должны соответствовать параметрам -из команд:: - - use Migrations\Migrations; - - $migrations = new Migrations(); - - // Вернёт массив всех миграций и их статус - $status = $migrations->status(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - -Вы можете передать любые параметры, которые потребуются командам оболочки. -Единственным исключением является команда ``markMigrated``, которая ожидает, -что номер версии миграции будет отмечен как перенесённый как первый аргумент. -Передайте массив параметров в качестве второго аргумента для этого метода. - -При желании вы можете передать эти параметры в конструкторе класса. -Они будут использоваться по умолчанию, и это не позволит вам передать их -при каждом вызове метода:: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // Все последующие вызовы будут выполнены с параметрами, переданными конструктору класса Migrations - $status = $migrations->status(); - $migrate = $migrations->migrate(); - -Если вам необходимо переопределить один или несколько параметров по умолчанию для одного вызова, -вы можете передать их методу:: - - use Migrations\Migrations; - - $migrations = new Migrations(['connection' => 'custom', 'source' => 'MyMigrationsFolder']); - - // Этот вызов будет выполнен с использованием "пользовательского" соединения - $status = $migrations->status(); - // Этот с подключением "по умолчанию" - $migrate = $migrations->migrate(['connection' => 'default']); - -Советы и приёмы -=============== - -Создание пользовательских первичных ключей ------------------------------------------- - -Если вам нужно избегать автоматического создания первичного ключа ``id`` -при добавлении новых таблиц в базу данных, вы можете использовать второй -аргумент метода ``table()``:: - - table('products', ['id' => false, 'primary_key' => ['id']]); - $table - ->addColumn('id', 'uuid') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -Вышеупомянутый элемент создаст столбец ``id`` с типом ``CHAR(36)``, который также является первичным ключом. - -.. note:: - - При указании настраиваемого первичного ключа в командной строке вы - должны отметить его как первичный ключ в поле id, иначе вы можете - получить ошибку в отношении повторяющихся полей id, т.е.:: - - $ bin/cake bake migration CreateProducts id:uuid:primary name:string description:text created modified - -Кроме того, начиная с Migrations 1.3 был введён новый способ обработки -первичного ключа. Для этого ваш класс миграции должен расширить новый -класс ``Migrations\AbstractMigration``. - -Вы можете указать свойство ``autoId`` в классе Migration и установить его в -``false``, что отключит автоматическое создание столбца ``id``. Вам нужно -будет вручную создать столбец, который будет использоваться в качестве -первичного ключа, и добавить его в объявление таблицы:: - - table('products'); - $table - ->addColumn('id', 'integer', [ - 'autoIncrement' => true, - 'limit' => 11 - ]) - ->addPrimaryKey('id') - ->addColumn('name', 'string') - ->addColumn('description', 'text') - ->create(); - } - } - -По сравнению с предыдущим способом работы с первичным ключом, этот метод даёт -вам возможность больше контролировать определение столбца первичного ключа: -unsigned или not, limit, comment и т.д. - -Все запечённые миграции и моментальные снимки будут использовать этот новый -способ, когда это необходимо. - -.. warning:: - - Работа с первичным ключом может выполняться только при выполнении операций - создания таблиц. Это связано с ограничениями для некоторых серверов баз данных, - поддерживаемых плагинами. - -Параметры сортировки --------------------- - -Если вам нужно создать таблицу с другой сортировкой, чем стандартная по -умолчанию, вы можете определить её с помощью метода ``table()`` в качестве -опции:: - - table('categories', [ - 'collation' => 'latin1_german1_ci' - ]) - ->addColumn('title', 'string', [ - 'default' => null, - 'limit' => 255, - 'null' => false, - ]) - ->create(); - } - } - - -Обратите внимание, что это можно сделать только при создании таблицы: -в настоящее время нет способа добавить столбец в существующую таблицу с -другой сортировкой, чем таблица или база данных. -В настоящее время только ``MySQL`` и ``SqlServer`` поддерживают этот -ключ конфигурации. - -Обновление имени столбцов и использование объектов Table --------------------------------------------------------- - -Если вы используете объект CakePHP ORM Table для управления значениями из -своей базы данных вместе с переименованием или удалением столбца, убедитесь, -что вы создали новый экземпляр объекта Table после вызова ``update()``. -Реестр объектов таблицы очищается после вызова ``update()``, чтобы обновить -схему, которая отражается и хранится в объекте Table при создании экземпляра. - -Миграции и развёртывание ------------------------- - -Если вы используете плагин при развёртывании приложения, обязательно очистите -кэш ORM, чтобы он обновил метаданные столбца ваших таблиц. В противном случае -вы можете столкнуться с ошибками в отношении столбцов, которые не существуют -при выполнении операций над этими новыми столбцами. -Ядро CakePHP включает `Schema Cache Shell -`__ -который вы можете использовать для выполнения этой операции:: - - $ bin/cake schema_cache clear - -Обязательно прочитайте раздел `Schema Cache Shell -`__, -если вы хотите узнать больше об этой оболочке. - -Переименование таблицы ----------------------- - -Плагин даёт вам возможность переименовать таблицу, используя метод ``rename()``. -В файле миграции вы можете сделать следующее:: - - public function up(): void - { - $this->table('old_table_name') - ->rename('new_table_name'); - } - -Пропуск генерации файла ``schema.lock`` ---------------------------------------- - -.. versionadded:: cakephp/migrations 1.6.5 - -Для того, чтобы функция diff работала, каждый раз, когда вы переносите, -откатываете или выпекаете снимок, создается файл **.Lock**, чтобы отслеживать -состояние вашей схемы базы данных в любой момент времени. Вы можете пропустить -создание этого файла, например, при развёртывании в рабочей среде, используя -опцию ``--no-lock`` для вышеупомянутой команды:: - - $ bin/cake migrations migrate --no-lock - - $ bin/cake migrations rollback --no-lock - - $ bin/cake bake migration_snapshot MyMigration --no-lock - diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 76399bbd..648c9543 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -54,60 +54,6 @@ parameters: count: 1 path: src/Db/Adapter/MysqlAdapter.php - - - message: '#^Parameter \#1 \$columns of method Migrations\\Db\\Table\\Index\:\:setColumns\(\) expects array\\|string, array\|int\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$constraint of method Migrations\\Db\\Table\\ForeignKey\:\:setConstraint\(\) expects string, array\\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$includedColumns of method Migrations\\Db\\Table\\Index\:\:setInclude\(\) expects array\, array\|int\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$limit of method Migrations\\Db\\Table\\Index\:\:setLimit\(\) expects array\|int, array\|int\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$name of method Migrations\\Db\\Table\\Index\:\:setName\(\) expects string, array\|int\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$onDelete of method Migrations\\Db\\Table\\ForeignKey\:\:setOnDelete\(\) expects string, array\\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$onUpdate of method Migrations\\Db\\Table\\ForeignKey\:\:setOnUpdate\(\) expects string, array\\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$order of method Migrations\\Db\\Table\\Index\:\:setOrder\(\) expects array\, array\|int\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - - - message: '#^Parameter \#1 \$type of method Migrations\\Db\\Table\\Index\:\:setType\(\) expects string, array\|int\|string given\.$#' - identifier: argument.type - count: 1 - path: src/Db/Adapter/PhinxAdapter.php - - message: '#^Right side of && is always true\.$#' identifier: booleanAnd.rightAlwaysTrue @@ -120,12 +66,6 @@ parameters: count: 1 path: src/Db/Adapter/SqliteAdapter.php - - - message: '#^PHPDoc tag @return with type Phinx\\Db\\Adapter\\AdapterInterface is not subtype of native type Migrations\\Db\\Adapter\\AdapterInterface\.$#' - identifier: return.phpDocType - count: 1 - path: src/Db/Adapter/SqlserverAdapter.php - - message: '#^Call to an undefined method Migrations\\Db\\Table\\Index\:\:setUnique\(\)\.$#' identifier: method.notFound diff --git a/phpstan.neon b/phpstan.neon index cd57a9b2..d3803bde 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -10,4 +10,3 @@ parameters: ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics - diff --git a/src/AbstractMigration.php b/src/AbstractMigration.php deleted file mode 100644 index 61a85922..00000000 --- a/src/AbstractMigration.php +++ /dev/null @@ -1,68 +0,0 @@ -getAdapter()->hasTransactions(); - } - - /** - * Returns an instance of the Table class. - * - * You can use this class to create and manipulate tables. - * - * @param string $tableName Table Name - * @param array $options Options - * @return \Migrations\Table - */ - public function table(string $tableName, array $options = []): Table - { - if ($this->autoId === false) { - $options['id'] = false; - } - - $table = new Table($tableName, $options, $this->getAdapter()); - $this->tables[] = $table; - - return $table; - } -} diff --git a/src/AbstractSeed.php b/src/AbstractSeed.php deleted file mode 100644 index 125a569c..00000000 --- a/src/AbstractSeed.php +++ /dev/null @@ -1,130 +0,0 @@ -getOutput()->writeln(''); - $this->getOutput()->writeln( - ' ====' . - ' ' . $seeder . ':' . - ' seeding', - ); - - $start = microtime(true); - $this->runCall($seeder); - $end = microtime(true); - - $this->getOutput()->writeln( - ' ====' . - ' ' . $seeder . ':' . - ' seeded' . - ' ' . sprintf('%.4fs', $end - $start) . '', - ); - $this->getOutput()->writeln(''); - } - - /** - * Calls another seeder from this seeder. - * It will load the Seed class you are calling and run it. - * - * @param string $seeder Name of the seeder to call from the current seed - * @return void - */ - protected function runCall(string $seeder): void - { - [$pluginName, $seeder] = pluginSplit($seeder); - - $argv = [ - 'seed', - '--seed', - $seeder, - ]; - - $plugin = $pluginName ?: $this->input->getOption('plugin'); - if ($plugin !== null) { - $argv[] = '--plugin'; - $argv[] = $plugin; - } - - $connection = $this->input->getOption('connection'); - if ($connection !== null) { - $argv[] = '--connection'; - $argv[] = $connection; - } - - $source = $this->input->getOption('source'); - if ($source !== null) { - $argv[] = '--source'; - $argv[] = $source; - } - - /* - $seedCommand = new Seed(); - $input = new ArgvInput($argv, $seedCommand->getDefinition()); - $seedCommand->setInput($input); - $config = $seedCommand->getConfig(); - - $seedPaths = $config->getSeedPaths(); - require_once array_pop($seedPaths) . DS . $seeder . '.php'; - /** @var \Phinx\Seed\SeedInterface $seeder * / - $seeder = new $seeder(); - $seeder->setOutput($this->getOutput()); - $seeder->setAdapter($this->getAdapter()); - $seeder->setInput($this->input); - $seeder->run(); - */ - } - - /** - * Sets the InputInterface this Seed class is being used with. - * - * @param \Symfony\Component\Console\Input\InputInterface $input Input object. - * @return $this - */ - public function setInput(InputInterface $input) - { - $this->input = $input; - - return $this; - } -} diff --git a/src/CakeAdapter.php b/src/CakeAdapter.php deleted file mode 100644 index a837a62a..00000000 --- a/src/CakeAdapter.php +++ /dev/null @@ -1,110 +0,0 @@ -connection = $connection; - $pdo = $adapter->getConnection(); - - if ($pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION) { - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - $connection->cacheMetadata(false); - - if ($connection->getDriver() instanceof Postgres) { - $config = $connection->config(); - $schema = empty($config['schema']) ? 'public' : $config['schema']; - $pdo->exec('SET search_path TO ' . $pdo->quote($schema)); - } - - $driver = $connection->getDriver(); - $prop = new ReflectionProperty($driver, 'pdo'); - $prop->setValue($driver, $pdo); - } - - /** - * Gets the CakePHP Connection object. - * - * @return \Cake\Database\Connection - */ - public function getCakeConnection(): Connection - { - return $this->connection; - } - - /** - * Returns a new Query object - * - * @param string $type The type of query to generate - * (one of the `\Cake\Database\Query::TYPE_*` constants). - * @return \Cake\Database\Query - */ - public function getQueryBuilder(string $type): Query - { - return match ($type) { - Query::TYPE_SELECT => $this->getCakeConnection()->selectQuery(), - Query::TYPE_INSERT => $this->getCakeConnection()->insertQuery(), - Query::TYPE_UPDATE => $this->getCakeConnection()->updateQuery(), - Query::TYPE_DELETE => $this->getCakeConnection()->deleteQuery(), - default => throw new InvalidArgumentException( - 'Query type must be one of: `select`, `insert`, `update`, `delete`.', - ) - }; - } - - /** - * Returns the adapter type name, for example mysql - * - * @return string - */ - public function getAdapterType(): string - { - return $this->getAdapter()->getAdapterType(); - } -} diff --git a/src/CakeManager.php b/src/CakeManager.php deleted file mode 100644 index 3b217697..00000000 --- a/src/CakeManager.php +++ /dev/null @@ -1,391 +0,0 @@ -migrations = null; - } - - /** - * Reset the seeds stored in the object - * - * @return void - */ - public function resetSeeds(): void - { - $this->seeds = null; - } - - /** - * Prints the specified environment's migration status. - * - * @param string $environment Environment name. - * @param null|string $format Format (`json` or `array`). - * @return array Array of migrations. - */ - public function printStatus(string $environment, ?string $format = null): array - { - $migrations = []; - $isJson = $format === 'json'; - $defaultMigrations = $this->getMigrations('default'); - if ($defaultMigrations) { - $env = $this->getEnvironment($environment); - $versions = $env->getVersionLog(); - $this->maxNameLength = $versions ? max(array_map(function ($version) { - return strlen((string)$version['migration_name']); - }, $versions)) : 0; - - foreach ($defaultMigrations as $migration) { - if (array_key_exists($migration->getVersion(), $versions)) { - $status = 'up'; - unset($versions[$migration->getVersion()]); - } else { - $status = 'down'; - } - - $version = $migration->getVersion(); - $migrationParams = [ - 'status' => $status, - 'id' => $migration->getVersion(), - 'name' => $migration->getName(), - ]; - - $migrations[$version] = $migrationParams; - } - - foreach ($versions as $missing) { - $version = $missing['version']; - $migrationParams = [ - 'status' => 'up', - 'id' => $version, - 'name' => $missing['migration_name'], - ]; - - if (!$isJson) { - $migrationParams = [ - 'missing' => true, - ] + $migrationParams; - } - - $migrations[$version] = $migrationParams; - } - } - - ksort($migrations); - $migrations = array_values($migrations); - - return $migrations; - } - - /** - * @param string $environment Environment - * @param \DateTime $dateTime Date to migrate to - * @param bool $fake flag that if true, we just record running the migration, but not actually do the - * migration - * @return void - */ - public function migrateToDateTime(string $environment, DateTime $dateTime, bool $fake = false): void - { - /** @var array $versions */ - $versions = array_keys($this->getMigrations('default')); - $dateString = $dateTime->format('Ymdhis'); - $versionToMigrate = null; - foreach ($versions as $version) { - if ($dateString > $version) { - $versionToMigrate = $version; - } - } - - if ($versionToMigrate === null) { - $this->getOutput()->writeln( - 'No migrations to run', - ); - - return; - } - - $this->getOutput()->writeln( - 'Migrating to version ' . $versionToMigrate, - ); - $this->migrate($environment, $versionToMigrate, $fake); - } - - /** - * @inheritDoc - */ - public function rollbackToDateTime(string $environment, DateTime $dateTime, bool $force = false): void - { - $env = $this->getEnvironment($environment); - $versions = $env->getVersions(); - $dateString = $dateTime->format('Ymdhis'); - sort($versions); - $versions = array_reverse($versions); - - if (!$versions || $dateString > $versions[0]) { - $this->getOutput()->writeln('No migrations to rollback'); - - return; - } - - if ($dateString < end($versions)) { - $this->getOutput()->writeln('Rolling back all migrations'); - $this->rollback($environment, 0); - - return; - } - - $index = 0; - foreach ($versions as $index => $version) { - if ($dateString > $version) { - break; - } - } - - $versionToRollback = $versions[$index]; - - $this->getOutput()->writeln('Rolling back to version ' . $versionToRollback); - $this->rollback($environment, $versionToRollback, $force); - } - - /** - * Checks if the migration with version number $version as already been mark migrated - * - * @param int $version Version number of the migration to check - * @return bool - */ - public function isMigrated(int $version): bool - { - $adapter = $this->getEnvironment('default')->getAdapter(); - /** @var array $versions */ - $versions = array_flip($adapter->getVersions()); - - return isset($versions[$version]); - } - - /** - * Marks migration with version number $version migrated - * - * @param int $version Version number of the migration to check - * @param string $path Path where the migration file is located - * @return bool True if success - */ - public function markMigrated(int $version, string $path): bool - { - $adapter = $this->getEnvironment('default')->getAdapter(); - - $migrationFile = glob($path . DS . $version . '*'); - - if (!$migrationFile) { - throw new RuntimeException( - sprintf('A migration file matching version number `%s` could not be found', $version), - ); - } - - $migrationFile = $migrationFile[0]; - /** @var class-string<\Phinx\Migration\MigrationInterface> $className */ - $className = $this->getMigrationClassName($migrationFile); - require_once $migrationFile; - $Migration = new $className('default', $version); - - $time = date('Y-m-d H:i:s', time()); - - $adapter->migrated($Migration, 'up', $time, $time); - - return true; - } - - /** - * Decides which versions it should mark as migrated - * - * @param \Symfony\Component\Console\Input\InputInterface $input Input interface from which argument and options - * will be extracted to determine which versions to be marked as migrated - * @return array Array of versions that should be marked as migrated - * @throws \InvalidArgumentException If the `--exclude` or `--only` options are used without `--target` - * or version not found - */ - public function getVersionsToMark(InputInterface $input): array - { - $migrations = $this->getMigrations('default'); - $versions = array_keys($migrations); - - $versionArg = $input->getArgument('version'); - $targetArg = $input->getOption('target'); - $hasAllVersion = in_array($versionArg, ['all', '*'], true); - if ((!$versionArg && !$targetArg) || $hasAllVersion) { - return $versions; - } - - $version = (int)$targetArg ?: (int)$versionArg; - - if ($input->getOption('only') || $versionArg) { - if (!in_array($version, $versions)) { - throw new InvalidArgumentException("Migration `$version` was not found !"); - } - - return [$version]; - } - - $lengthIncrease = $input->getOption('exclude') ? 0 : 1; - $index = array_search($version, $versions); - - if ($index === false) { - throw new InvalidArgumentException("Migration `$version` was not found !"); - } - - return array_slice($versions, 0, $index + $lengthIncrease); - } - - /** - * Mark all migrations in $versions array found in $path as migrated - * - * It will start a transaction and rollback in case one of the operation raises an exception - * - * @param string $path Path where to look for migrations - * @param array $versions Versions which should be marked - * @param \Symfony\Component\Console\Output\OutputInterface $output OutputInterface used to store - * the command output - * @return void - */ - public function markVersionsAsMigrated(string $path, array $versions, OutputInterface $output): void - { - $adapter = $this->getEnvironment('default')->getAdapter(); - - if (!$versions) { - $output->writeln('No migrations were found. Nothing to mark as migrated.'); - - return; - } - - $adapter->beginTransaction(); - foreach ($versions as $version) { - if ($this->isMigrated($version)) { - $output->writeln(sprintf('Skipping migration `%s` (already migrated).', $version)); - continue; - } - - try { - $this->markMigrated($version, $path); - $output->writeln( - sprintf('Migration `%s` successfully marked migrated !', $version), - ); - } catch (Exception $e) { - $adapter->rollbackTransaction(); - $output->writeln( - sprintf( - 'An error occurred while marking migration `%s` as migrated : %s', - $version, - $e->getMessage(), - ), - ); - $output->writeln('All marked migrations during this process were unmarked.'); - - return; - } - } - $adapter->commitTransaction(); - } - - /** - * Resolves a migration class name based on $path - * - * @param string $path Path to the migration file of which we want the class name - * @return string Migration class name - */ - protected function getMigrationClassName(string $path): string - { - $class = (string)preg_replace('/^[0-9]+_/', '', basename($path)); - $class = str_replace('_', ' ', $class); - $class = ucwords($class); - $class = str_replace(' ', '', $class); - if (strpos($class, '.') !== false) { - $class = substr($class, 0, strpos($class, '.')); - } - - return $class; - } - - /** - * Sets the InputInterface the Manager is dealing with for the current shell call - * - * @param \Symfony\Component\Console\Input\InputInterface $input Instance of InputInterface - * @return $this - */ - public function setInput(InputInterface $input) - { - $this->input = $input; - - return $this; - } - - /** - * Gets an array of database seeders. - * - * Overload the basic behavior to add an instance of the InputInterface the shell call is - * using in order to give the ability to the AbstractSeed::call() method to propagate options - * to the other MigrationsDispatcher it is generating. - * - * @throws \InvalidArgumentException - * @param string $environment Environment. - * @return \Phinx\Seed\SeedInterface[] - */ - public function getSeeds(string $environment): array - { - parent::getSeeds($environment); - if (!$this->seeds) { - return []; - } - - foreach ($this->seeds as $instance) { - if ($instance instanceof AbstractSeed) { - $instance->setInput($this->input); - } - } - - return $this->seeds; - } -} diff --git a/src/Command/BakeMigrationCommand.php b/src/Command/BakeMigrationCommand.php index 23ecbdc7..81bba92a 100644 --- a/src/Command/BakeMigrationCommand.php +++ b/src/Command/BakeMigrationCommand.php @@ -98,7 +98,7 @@ public function templateData(Arguments $arguments): array 'tables' => [], 'action' => null, 'name' => $className, - 'backend' => Configure::read('Migrations.backend', 'builtin'), + 'backend' => 'builtin', ]; } @@ -120,7 +120,7 @@ public function templateData(Arguments $arguments): array 'primaryKey' => $primaryKey, ], 'name' => $className, - 'backend' => Configure::read('Migrations.backend', 'builtin'), + 'backend' => 'builtin', ]; } diff --git a/src/Command/BakeMigrationDiffCommand.php b/src/Command/BakeMigrationDiffCommand.php index 74eaeb87..8071ea91 100644 --- a/src/Command/BakeMigrationDiffCommand.php +++ b/src/Command/BakeMigrationDiffCommand.php @@ -18,7 +18,6 @@ use Cake\Console\Arguments; use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; -use Cake\Core\Configure; use Cake\Database\Connection; use Cake\Database\Schema\CollectionInterface; use Cake\Database\Schema\TableSchema; @@ -197,7 +196,7 @@ public function templateData(Arguments $arguments): array 'data' => $this->templateData, 'dumpSchema' => $this->dumpSchema, 'currentSchema' => $this->currentSchema, - 'backend' => Configure::read('Migrations.backend', 'builtin'), + 'backend' => 'builtin', ]; } diff --git a/src/Command/BakeMigrationSnapshotCommand.php b/src/Command/BakeMigrationSnapshotCommand.php index 7108969a..9f88973e 100644 --- a/src/Command/BakeMigrationSnapshotCommand.php +++ b/src/Command/BakeMigrationSnapshotCommand.php @@ -115,7 +115,7 @@ public function templateData(Arguments $arguments): array 'action' => 'create_table', 'name' => $this->_name, 'autoId' => $autoId, - 'backend' => Configure::read('Migrations.backend', 'builtin'), + 'backend' => 'builtin', ]; } diff --git a/src/Command/BakeSeedCommand.php b/src/Command/BakeSeedCommand.php index dd070085..c3bec484 100644 --- a/src/Command/BakeSeedCommand.php +++ b/src/Command/BakeSeedCommand.php @@ -142,7 +142,7 @@ public function templateData(Arguments $arguments): array 'namespace' => $namespace, 'records' => $records, 'table' => $table, - 'backend' => Configure::read('Migrations.backend', 'builtin'), + 'backend' => 'builtin', ]; } diff --git a/src/Command/EntryCommand.php b/src/Command/EntryCommand.php index 21998386..3651d928 100644 --- a/src/Command/EntryCommand.php +++ b/src/Command/EntryCommand.php @@ -23,7 +23,6 @@ use Cake\Console\CommandCollectionAwareInterface; use Cake\Console\ConsoleIo; use Cake\Console\Exception\ConsoleException; -use Cake\Core\Configure; /** * Command that provides help and an entry point to migrations tools. @@ -83,18 +82,12 @@ public function run(array $argv, ConsoleIo $io): ?int // This is the variance from Command::run() if (!$args->getArgumentAt(0) && $args->getOption('help')) { - $backend = Configure::read('Migrations.backend', 'builtin'); $io->out([ 'Migrations', '', "Migrations provides commands for managing your application's database schema and initial data.", '', - "Using {$backend} backend.", - '', ]); - if ($backend !== 'builtin') { - $io->warning("You are using the {$backend} backend which is no longer supported."); - } $help = $this->getHelp(); $this->executeCommand($help, [], $io); diff --git a/src/Config/ConfigInterface.php b/src/Config/ConfigInterface.php index 2a019165..2aa11206 100644 --- a/src/Config/ConfigInterface.php +++ b/src/Config/ConfigInterface.php @@ -11,7 +11,7 @@ use ArrayAccess; /** - * Phinx configuration interface. + * Configuration interface. * * @template-implemements ArrayAccess */ diff --git a/src/Db/Adapter/AbstractAdapter.php b/src/Db/Adapter/AbstractAdapter.php index 0e344fd3..43fe62b7 100644 --- a/src/Db/Adapter/AbstractAdapter.php +++ b/src/Db/Adapter/AbstractAdapter.php @@ -44,7 +44,6 @@ use Migrations\MigrationInterface; use Migrations\Shim\OutputAdapter; use PDOException; -use Phinx\Util\Literal as PhinxLiteral; use RuntimeException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -612,7 +611,7 @@ public function insert(TableMetadata $table, array $row): void $vals = []; foreach ($row as $value) { $placeholder = '?'; - if ($value instanceof Literal || $value instanceof PhinxLiteral) { + if ($value instanceof Literal) { $placeholder = (string)$value; } if ($placeholder === '?') { @@ -653,7 +652,7 @@ protected function generateInsertSql(TableMetadata $table, array $row): string $values = []; foreach ($row as $value) { $placeholder = '?'; - if ($value instanceof Literal || $value instanceof PhinxLiteral) { + if ($value instanceof Literal) { $placeholder = (string)$value; } $values[] = $placeholder; @@ -680,7 +679,7 @@ protected function quoteValue(mixed $value): mixed return 'null'; } - if ($value instanceof Literal || $value instanceof PhinxLiteral) { + if ($value instanceof Literal) { return (string)$value; } @@ -724,10 +723,10 @@ public function bulkinsert(TableMetadata $table, array $rows): void foreach ($rows as $row) { foreach ($row as $v) { $placeholder = '?'; - if ($v instanceof Literal || $v instanceof PhinxLiteral) { + if ($v instanceof Literal) { $placeholder = (string)$v; } - if ($placeholder == '?') { + if ($placeholder === '?') { if ($v instanceof DateTime) { $vals[] = $v->toDateTimeString(); } elseif ($v instanceof Date) { @@ -775,7 +774,7 @@ protected function generateBulkInsertSql(TableMetadata $table, array $rows): str $values = []; foreach ($row as $v) { $placeholder = '?'; - if ($v instanceof Literal || $v instanceof PhinxLiteral) { + if ($v instanceof Literal) { $placeholder = (string)$v; } $values[] = $placeholder; @@ -1371,7 +1370,7 @@ public function executeActions(TableMetadata $table, array $actions): void )); break; - case $action instanceof DropIndex && $action->getIndex()->getName() == null: + case $action instanceof DropIndex && $action->getIndex()->getName() === null: /** @var \Migrations\Db\Action\DropIndex $action */ $instructions->merge($this->getDropIndexByColumnsInstructions( $table->getName(), diff --git a/src/Db/Adapter/PhinxAdapter.php b/src/Db/Adapter/PhinxAdapter.php deleted file mode 100644 index 01676939..00000000 --- a/src/Db/Adapter/PhinxAdapter.php +++ /dev/null @@ -1,828 +0,0 @@ -getName(), - $phinxTable->getOptions(), - ); - - return $table; - } - - /** - * Convert a phinx column into a migrations object - * - * @param \Phinx\Db\Table\Column $phinxColumn The column to convert. - * @return \Migrations\Db\Table\Column - */ - protected function convertColumn(PhinxColumn $phinxColumn): Column - { - $column = new Column(); - $attrs = [ - 'name', 'null', 'default', 'identity', - 'generated', 'seed', 'increment', 'scale', - 'after', 'update', 'comment', 'signed', - 'timezone', 'properties', 'collation', - 'encoding', 'srid', 'values', 'limit', - ]; - foreach ($attrs as $attr) { - $get = 'get' . ucfirst($attr); - $set = 'set' . ucfirst($attr); - try { - $value = $phinxColumn->{$get}(); - } catch (RuntimeException $e) { - $value = null; - } - if ($value !== null) { - $column->{$set}($value); - } - } - try { - $type = $phinxColumn->getType(); - } catch (RuntimeException $e) { - $type = null; - } - if ($type instanceof PhinxLiteral) { - $type = Literal::from((string)$type); - } - if ($type) { - $column->setType($type); - } - - return $column; - } - - /** - * Convert a migrations column into a phinx object - * - * @param \Migrations\Db\Table\Column $column The column to convert. - * @return \Phinx\Db\Table\Column - */ - protected function convertColumnToPhinx(Column $column): PhinxColumn - { - $phinx = new PhinxColumn(); - $attrs = [ - 'name', 'type', 'null', 'default', 'identity', - 'generated', 'seed', 'increment', 'scale', - 'after', 'update', 'comment', 'signed', - 'timezone', 'properties', 'collation', - 'encoding', 'srid', 'values', 'limit', - ]; - foreach ($attrs as $attr) { - $get = 'get' . ucfirst($attr); - $set = 'set' . ucfirst($attr); - $value = $column->{$get}(); - $value = $column->{$get}(); - if ($value !== null) { - $phinx->{$set}($value); - } - } - - return $phinx; - } - - /** - * Convert a migrations Index into a phinx object - * - * @param \Phinx\Db\Table\Index $phinxIndex The index to convert. - * @return \Migrations\Db\Table\Index - */ - protected function convertIndex(PhinxIndex $phinxIndex): Index - { - $index = new Index(); - $attrs = [ - 'name', 'columns', 'type', 'limit', 'order', - 'include', - ]; - foreach ($attrs as $attr) { - $get = 'get' . ucfirst($attr); - $set = 'set' . ucfirst($attr); - try { - $value = $phinxIndex->{$get}(); - } catch (RuntimeException $e) { - $value = null; - } - if ($value !== null) { - $index->{$set}($value); - } - } - - return $index; - } - - /** - * Convert a phinx ForeignKey into a migrations object - * - * @param \Phinx\Db\Table\ForeignKey $phinxKey The index to convert. - * @return \Migrations\Db\Table\ForeignKey - */ - protected function convertForeignKey(PhinxForeignKey $phinxKey): ForeignKey - { - $foreignKey = new ForeignKey(); - $attrs = [ - 'columns', 'referencedColumns', 'onDelete', 'onUpdate', 'constraint', - ]; - - foreach ($attrs as $attr) { - $get = 'get' . ucfirst($attr); - $set = 'set' . ucfirst($attr); - try { - $value = $phinxKey->{$get}(); - } catch (RuntimeException $e) { - $value = null; - } - if ($value !== null) { - $foreignKey->{$set}($value); - } - } - - try { - $referenced = $phinxKey->getReferencedTable(); - } catch (RuntimeException $e) { - $referenced = null; - } - if ($referenced) { - $foreignKey->setReferencedTable($this->convertTable($referenced)); - } - - return $foreignKey; - } - - /** - * Convert a phinx Action into a migrations object - * - * @param \Phinx\Db\Action\Action $phinxAction The index to convert. - * @return \Migrations\Db\Action\Action - */ - protected function convertAction(PhinxAction $phinxAction): Action - { - $action = null; - if ($phinxAction instanceof PhinxAddColumn) { - $action = new AddColumn( - $this->convertTable($phinxAction->getTable()), - $this->convertColumn($phinxAction->getColumn()), - ); - } elseif ($phinxAction instanceof PhinxAddForeignKey) { - $action = new AddForeignKey( - $this->convertTable($phinxAction->getTable()), - $this->convertForeignKey($phinxAction->getForeignKey()), - ); - } elseif ($phinxAction instanceof PhinxAddIndex) { - $action = new AddIndex( - $this->convertTable($phinxAction->getTable()), - $this->convertIndex($phinxAction->getIndex()), - ); - } elseif ($phinxAction instanceof PhinxChangeColumn) { - $action = new ChangeColumn( - $this->convertTable($phinxAction->getTable()), - $phinxAction->getColumnName(), - $this->convertColumn($phinxAction->getColumn()), - ); - } elseif ($phinxAction instanceof PhinxChangeComment) { - $action = new ChangeComment( - $this->convertTable($phinxAction->getTable()), - $phinxAction->getNewComment(), - ); - } elseif ($phinxAction instanceof PhinxChangePrimaryKey) { - $action = new ChangePrimaryKey( - $this->convertTable($phinxAction->getTable()), - $phinxAction->getNewColumns(), - ); - } elseif ($phinxAction instanceof PhinxCreateTable) { - $action = new CreateTable( - $this->convertTable($phinxAction->getTable()), - ); - } elseif ($phinxAction instanceof PhinxDropForeignKey) { - $action = new DropForeignKey( - $this->convertTable($phinxAction->getTable()), - $this->convertForeignKey($phinxAction->getForeignKey()), - ); - } elseif ($phinxAction instanceof PhinxDropIndex) { - $action = new DropIndex( - $this->convertTable($phinxAction->getTable()), - $this->convertIndex($phinxAction->getIndex()), - ); - } elseif ($phinxAction instanceof PhinxDropTable) { - $action = new DropTable( - $this->convertTable($phinxAction->getTable()), - ); - } elseif ($phinxAction instanceof PhinxRemoveColumn) { - $action = new RemoveColumn( - $this->convertTable($phinxAction->getTable()), - $this->convertColumn($phinxAction->getColumn()), - ); - } elseif ($phinxAction instanceof PhinxRenameColumn) { - $action = new RenameColumn( - $this->convertTable($phinxAction->getTable()), - $this->convertColumn($phinxAction->getColumn()), - $phinxAction->getNewName(), - ); - } elseif ($phinxAction instanceof PhinxRenameTable) { - $action = new RenameTable( - $this->convertTable($phinxAction->getTable()), - $phinxAction->getNewName(), - ); - } - if (!$action) { - throw new RuntimeException('Unable to map action of type ' . get_class($phinxAction)); - } - - return $action; - } - - /** - * Convert a phinx Literal into a migrations object - * - * @param \Phinx\Util\Literal|string $phinxLiteral The literal to convert. - * @return \Migrations\Db\Literal|string - */ - protected function convertLiteral(PhinxLiteral|string $phinxLiteral): Literal|string - { - if (is_string($phinxLiteral)) { - return $phinxLiteral; - } - - return new Literal((string)$phinxLiteral); - } - - /** - * @inheritDoc - */ - public function __construct(AdapterInterface $adapter) - { - $this->adapter = $adapter; - } - - /** - * @inheritDoc - */ - public function setOptions(array $options): PhinxAdapterInterface - { - $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): mixed - { - return $this->adapter->getOption($name); - } - - /** - * @inheritDoc - */ - public function setInput(InputInterface $input): PhinxAdapterInterface - { - throw new RuntimeException('Using setInput() on Adapters is no longer supported'); - } - - /** - * @inheritDoc - */ - public function getInput(): InputInterface - { - throw new RuntimeException('Using getInput() on Adapters is no longer supported'); - } - - /** - * @inheritDoc - */ - public function setOutput(OutputInterface $output): PhinxAdapterInterface - { - throw new RuntimeException('Using setOutput() on Adapters is no longer supported'); - } - - /** - * @inheritDoc - */ - public function getOutput(): OutputInterface - { - throw new RuntimeException('Using getOutput() on Adapters is no longer supported'); - } - - /** - * @inheritDoc - */ - public function getColumnForType(string $columnName, string $type, array $options): PhinxColumn - { - $column = $this->adapter->getColumnForType($columnName, $type, $options); - - return $this->convertColumnToPhinx($column); - } - - /** - * @inheritDoc - */ - public function connect(): void - { - $this->adapter->connect(); - } - - /** - * @inheritDoc - */ - public function disconnect(): void - { - $this->adapter->disconnect(); - } - - /** - * @inheritDoc - */ - public function execute(string $sql, array $params = []): int - { - return $this->adapter->execute($sql, $params); - } - - /** - * @inheritDoc - */ - public function query(string $sql, array $params = []): mixed - { - return $this->adapter->query($sql, $params); - } - - /** - * @inheritDoc - */ - public function insert(PhinxTable $table, array $row): void - { - $this->adapter->insert($this->convertTable($table), $row); - } - - /** - * @inheritDoc - */ - public function bulkinsert(PhinxTable $table, array $rows): void - { - $this->adapter->bulkinsert($this->convertTable($table), $rows); - } - - /** - * @inheritDoc - */ - public function fetchRow(string $sql): array|false - { - return $this->adapter->fetchRow($sql); - } - - /** - * @inheritDoc - */ - public function fetchAll(string $sql): array - { - return $this->adapter->fetchAll($sql); - } - - /** - * @inheritDoc - */ - public function getVersions(): array - { - return $this->adapter->getVersions(); - } - - /** - * @inheritDoc - */ - public function getVersionLog(): array - { - return $this->adapter->getVersionLog(); - } - - /** - * @inheritDoc - */ - public function migrated(PhinxMigrationInterface $migration, string $direction, string $startTime, string $endTime): PhinxAdapterInterface - { - $wrapped = new MigrationAdapter($migration, $migration->getVersion()); - $this->adapter->migrated($wrapped, $direction, $startTime, $endTime); - - return $this; - } - - /** - * @inheritDoc - */ - public function toggleBreakpoint(PhinxMigrationInterface $migration): PhinxAdapterInterface - { - $wrapped = new MigrationAdapter($migration, $migration->getVersion()); - $this->adapter->toggleBreakpoint($wrapped); - - return $this; - } - - /** - * @inheritDoc - */ - public function resetAllBreakpoints(): int - { - return $this->adapter->resetAllBreakpoints(); - } - - /** - * @inheritDoc - */ - public function setBreakpoint(PhinxMigrationInterface $migration): PhinxAdapterInterface - { - $wrapped = new MigrationAdapter($migration, $migration->getVersion()); - $this->adapter->setBreakpoint($wrapped); - - return $this; - } - - /** - * @inheritDoc - */ - public function unsetBreakpoint(PhinxMigrationInterface $migration): PhinxAdapterInterface - { - $wrapped = new MigrationAdapter($migration, $migration->getVersion()); - $this->adapter->unsetBreakpoint($wrapped); - - return $this; - } - - /** - * @inheritDoc - */ - public function createSchemaTable(): void - { - $this->adapter->createSchemaTable(); - } - - /** - * @inheritDoc - */ - public function getColumnTypes(): array - { - return $this->adapter->getColumnTypes(); - } - - /** - * @inheritDoc - */ - public function isValidColumnType(PhinxColumn $column): bool - { - return $this->adapter->isValidColumnType($this->convertColumn($column)); - } - - /** - * @inheritDoc - */ - public function hasTransactions(): bool - { - return $this->adapter->hasTransactions(); - } - - /** - * @inheritDoc - */ - public function beginTransaction(): void - { - $this->adapter->beginTransaction(); - } - - /** - * @inheritDoc - */ - public function commitTransaction(): void - { - $this->adapter->commitTransaction(); - } - - /** - * @inheritDoc - */ - public function rollbackTransaction(): void - { - $this->adapter->rollbackTransaction(); - } - - /** - * @inheritDoc - */ - public function quoteTableName(string $tableName): string - { - return $this->adapter->quoteTableName($tableName); - } - - /** - * @inheritDoc - */ - public function quoteColumnName(string $columnName): string - { - return $this->adapter->quoteColumnName($columnName); - } - - /** - * @inheritDoc - */ - public function hasTable(string $tableName): bool - { - return $this->adapter->hasTable($tableName); - } - - /** - * @inheritDoc - */ - public function createTable(PhinxTable $table, array $columns = [], array $indexes = []): void - { - $columns = array_map(function ($col) { - return $this->convertColumn($col); - }, $columns); - $indexes = array_map(function ($ind) { - return $this->convertIndex($ind); - }, $indexes); - $this->adapter->createTable($this->convertTable($table), $columns, $indexes); - } - - /** - * @inheritDoc - */ - public function getColumns(string $tableName): array - { - $columns = $this->adapter->getColumns($tableName); - - return array_map(function ($col) { - return $this->convertColumnToPhinx($col); - }, $columns); - } - - /** - * @inheritDoc - */ - public function hasColumn(string $tableName, string $columnName): bool - { - return $this->adapter->hasColumn($tableName, $columnName); - } - - /** - * @inheritDoc - */ - public function hasIndex(string $tableName, string|array $columns): bool - { - return $this->adapter->hasIndex($tableName, $columns); - } - - /** - * @inheritDoc - */ - public function hasIndexByName(string $tableName, string $indexName): bool - { - return $this->adapter->hasIndexByName($tableName, $indexName); - } - - /** - * @inheritDoc - */ - public function hasPrimaryKey(string $tableName, $columns, ?string $constraint = null): bool - { - return $this->adapter->hasPrimaryKey($tableName, $columns, $constraint); - } - - /** - * @inheritDoc - */ - public function hasForeignKey(string $tableName, $columns, ?string $constraint = null): bool - { - return $this->adapter->hasForeignKey($tableName, $columns, $constraint); - } - - /** - * @inheritDoc - */ - public function getSqlType(PhinxLiteral|string $type, ?int $limit = null): array - { - return $this->adapter->getSqlType($this->convertLiteral($type), $limit); - } - - /** - * @inheritDoc - */ - public function createDatabase(string $name, array $options = []): void - { - $this->adapter->createDatabase($name, $options); - } - - /** - * @inheritDoc - */ - public function hasDatabase(string $name): bool - { - return $this->adapter->hasDatabase($name); - } - - /** - * @inheritDoc - */ - public function dropDatabase(string $name): void - { - $this->adapter->dropDatabase($name); - } - - /** - * @inheritDoc - */ - public function createSchema(string $schemaName = 'public'): void - { - $this->adapter->createSchema($schemaName); - } - - /** - * @inheritDoc - */ - public function dropSchema(string $schemaName): void - { - $this->adapter->dropSchema($schemaName); - } - - /** - * @inheritDoc - */ - public function truncateTable(string $tableName): void - { - $this->adapter->truncateTable($tableName); - } - - /** - * @inheritDoc - */ - public function castToBool($value): mixed - { - return $this->adapter->castToBool($value); - } - - /** - * @return \Cake\Database\Connection - */ - public function getConnection(): Connection - { - return $this->adapter->getConnection(); - } - - /** - * @inheritDoc - */ - public function executeActions(PhinxTable $table, array $actions): void - { - $actions = array_map(function ($act) { - return $this->convertAction($act); - }, $actions); - $this->adapter->executeActions($this->convertTable($table), $actions); - } - - /** - * @inheritDoc - */ - public function getAdapterType(): string - { - return $this->adapter->getAdapterType(); - } - - /** - * @inheritDoc - */ - public function getQueryBuilder(string $type): Query - { - return $this->adapter->getQueryBuilder($type); - } - - /** - * @inheritDoc - */ - public function getSelectBuilder(): SelectQuery - { - return $this->adapter->getSelectBuilder(); - } - - /** - * @inheritDoc - */ - public function getInsertBuilder(): InsertQuery - { - return $this->adapter->getInsertBuilder(); - } - - /** - * @inheritDoc - */ - public function getUpdateBuilder(): UpdateQuery - { - return $this->adapter->getUpdateBuilder(); - } - - /** - * @inheritDoc - */ - public function getDeleteBuilder(): DeleteQuery - { - return $this->adapter->getDeleteBuilder(); - } - - /** - * @inheritDoc - */ - public function getCakeConnection(): Connection - { - return $this->adapter->getConnection(); - } -} diff --git a/src/Db/Adapter/PostgresAdapter.php b/src/Db/Adapter/PostgresAdapter.php index 44c49e23..1f3b9bdd 100644 --- a/src/Db/Adapter/PostgresAdapter.php +++ b/src/Db/Adapter/PostgresAdapter.php @@ -19,7 +19,6 @@ use Migrations\Db\Table\ForeignKey; use Migrations\Db\Table\Index; use Migrations\Db\Table\Table; -use Phinx\Util\Literal as PhinxLiteral; class PostgresAdapter extends AbstractAdapter { @@ -1337,7 +1336,7 @@ public function insert(Table $table, array $row): void $vals = []; foreach ($row as $value) { $placeholder = '?'; - if ($value instanceof Literal || $value instanceof PhinxLiteral) { + if ($value instanceof Literal) { $placeholder = (string)$value; } $values[] = $placeholder; @@ -1383,11 +1382,11 @@ public function bulkinsert(Table $table, array $rows): void $values = []; foreach ($row as $v) { $placeholder = '?'; - if ($v instanceof Literal || $v instanceof PhinxLiteral) { + if ($v instanceof Literal) { $placeholder = (string)$v; } $values[] = $placeholder; - if ($placeholder == '?') { + if ($placeholder === '?') { if ($v instanceof DateTime) { $vals[] = $v->toDateTimeString(); } elseif ($v instanceof Date) { diff --git a/src/Db/Adapter/SqlserverAdapter.php b/src/Db/Adapter/SqlserverAdapter.php index 0c0d6655..239f2ca6 100644 --- a/src/Db/Adapter/SqlserverAdapter.php +++ b/src/Db/Adapter/SqlserverAdapter.php @@ -21,7 +21,6 @@ use Migrations\Db\Table\Table; use Migrations\Db\Table\Table as TableMetadata; use Migrations\MigrationInterface; -use Phinx\Util\Literal as PhinxLiteral; /** * Migrations SqlServer Adapter. @@ -1201,7 +1200,7 @@ public function getColumnTypes(): array * @param string $direction Direction * @param string $startTime Start Time * @param string $endTime End Time - * @return \Phinx\Db\Adapter\AdapterInterface + * @return \Migrations\Db\Adapter\AdapterInterface */ public function migrated(MigrationInterface $migration, string $direction, string $startTime, string $endTime): AdapterInterface { @@ -1226,7 +1225,7 @@ public function insert(TableMetadata $table, array $row): void $vals = []; foreach ($row as $value) { $placeholder = '?'; - if ($value instanceof Literal || $value instanceof PhinxLiteral) { + if ($value instanceof Literal) { $placeholder = (string)$value; } if ($placeholder === '?') { @@ -1253,7 +1252,7 @@ public function bulkinsert(TableMetadata $table, array $rows): void foreach ($rows as $row) { foreach ($row as $v) { $placeholder = '?'; - if ($v instanceof Literal || $v instanceof PhinxLiteral) { + if ($v instanceof Literal) { $placeholder = (string)$v; } if ($placeholder == '?') { diff --git a/src/Db/Table.php b/src/Db/Table.php index eb2e29b9..1b022209 100644 --- a/src/Db/Table.php +++ b/src/Db/Table.php @@ -32,7 +32,6 @@ use Migrations\Db\Table\Index; use Migrations\Db\Table\Table as TableValue; use RuntimeException; -use function Cake\Core\deprecationWarning; /** * Migration Table @@ -509,55 +508,6 @@ public function addForeignKey(string|array|ForeignKey $columns, string|TableValu 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|\Migrations\Db\Table\ForeignKey $name The constraint name or a foreign key object. - * @param string|string[] $columns Columns - * @param string|\Migrations\Db\Table\Table $referencedTable Referenced Table - * @param string|string[] $referencedColumns Referenced Columns - * @param array $options Options - * @return $this - * @deprecated 4.6.0 Use addForeignKey() instead. Use `BaseMigration::foreignKey()` to get - * a fluent interface for building foreign keys. - */ - public function addForeignKeyWithName( - string|ForeignKey $name, - string|array|null $columns = null, - string|TableValue|null $referencedTable = null, - string|array $referencedColumns = ['id'], - array $options = [], - ) { - deprecationWarning( - '4.6.0', - 'Use addForeignKey() instead. Use `BaseMigration::foreignKey()` to get a fluent' . - ' interface for building foreign keys.', - ); - if (is_string($name)) { - if ($columns === null || $referencedTable === null) { - throw new InvalidArgumentException( - 'Columns and referencedTable are required when adding a foreign key with a name', - ); - } - $action = AddForeignKey::build( - $this->table, - $columns, - $referencedTable, - $referencedColumns, - $options, - $name, - ); - } else { - $action = new AddForeignKey($this->table, $name); - } - $this->actions->addAction($action); - - return $this; - } - /** * Removes the given foreign key from the table. * @@ -731,12 +681,13 @@ protected function filterPrimaryKey(array $options): void } $primaryKey = array_flip($primaryKey); + /** @var \Cake\Collection\Collection $columnsCollection */ $columnsCollection = (new Collection($this->actions->getActions())) ->filter(function ($action) { return $action instanceof AddColumn; }) ->map(function ($action) { - /** @var \Phinx\Db\Action\ChangeColumn|\Phinx\Db\Action\RenameColumn|\Phinx\Db\Action\RemoveColumn|\Phinx\Db\Action\AddColumn $action */ + /** @var \Migrations\Db\Action\ChangeColumn|\Migrations\Db\Action\RenameColumn|\Migrations\Db\Action\RemoveColumn|\Migrations\Db\Action\AddColumn $action */ return $action->getColumn(); }); $primaryKeyColumns = $columnsCollection->filter(function (Column $columnDef, $key) use ($primaryKey) { diff --git a/src/Db/Table/ForeignKey.php b/src/Db/Table/ForeignKey.php index 90da53e2..66814709 100644 --- a/src/Db/Table/ForeignKey.php +++ b/src/Db/Table/ForeignKey.php @@ -10,7 +10,6 @@ use InvalidArgumentException; use RuntimeException; -use function Cake\Core\deprecationWarning; /** * Foreign key value object @@ -212,32 +211,6 @@ public function getName(): ?string return $this->name; } - /** - * Sets constraint for the foreign key. - * - * @param string $constraint Constraint - * @return $this - */ - public function setConstraint(string $constraint) - { - deprecationWarning('4.6.0', 'setConstraint() is deprecated. Use setName() instead.'); - $this->name = $constraint; - - return $this; - } - - /** - * Gets constraint name for the foreign key. - * - * @return string|null - */ - public function getConstraint(): ?string - { - deprecationWarning('4.6.0', 'getConstraint() is deprecated. Use getName() instead.'); - - return $this->name; - } - /** * Sets deferrable mode for the foreign key. * diff --git a/src/Migration/Environment.php b/src/Migration/Environment.php index ecde844c..46dbd99a 100644 --- a/src/Migration/Environment.php +++ b/src/Migration/Environment.php @@ -14,7 +14,6 @@ use Migrations\Db\Adapter\AdapterInterface; use Migrations\MigrationInterface; use Migrations\SeedInterface; -use Migrations\Shim\MigrationAdapter; use RuntimeException; class Environment @@ -95,32 +94,28 @@ public function executeMigration(MigrationInterface $migration, string $directio } if (!$fake) { - if ($migration instanceof MigrationAdapter) { - $migration->applyDirection($direction); - } else { - // Run the migration - if (method_exists($migration, MigrationInterface::CHANGE)) { - if ($direction === MigrationInterface::DOWN) { - // Create an instance of the RecordingAdapter so we can record all - // of the migration commands for reverse playback - - /** @var \Migrations\Db\Adapter\RecordingAdapter $recordAdapter */ - $recordAdapter = AdapterFactory::instance() - ->getWrapper('record', $adapter); - - // Wrap the adapter with a phinx shim to maintain contain - $migration->setAdapter($recordAdapter); - - $migration->{MigrationInterface::CHANGE}(); - $recordAdapter->executeInvertedCommands(); - - $migration->setAdapter($this->getAdapter()); - } else { - $migration->{MigrationInterface::CHANGE}(); - } + // Run the migration + if (method_exists($migration, MigrationInterface::CHANGE)) { + if ($direction === MigrationInterface::DOWN) { + // Create an instance of the RecordingAdapter so we can record all + // of the migration commands for reverse playback + + /** @var \Migrations\Db\Adapter\RecordingAdapter $recordAdapter */ + $recordAdapter = AdapterFactory::instance() + ->getWrapper('record', $adapter); + + // Wrap the adapter with a phinx shim to maintain contain + $migration->setAdapter($recordAdapter); + + $migration->{MigrationInterface::CHANGE}(); + $recordAdapter->executeInvertedCommands(); + + $migration->setAdapter($this->getAdapter()); } else { - $migration->{$direction}(); + $migration->{MigrationInterface::CHANGE}(); } + } else { + $migration->{$direction}(); } } diff --git a/src/Migration/Manager.php b/src/Migration/Manager.php index 37bdc9b4..7a4d33e5 100644 --- a/src/Migration/Manager.php +++ b/src/Migration/Manager.php @@ -16,11 +16,7 @@ use Migrations\Config\ConfigInterface; use Migrations\MigrationInterface; use Migrations\SeedInterface; -use Migrations\Shim\MigrationAdapter; -use Migrations\Shim\SeedAdapter; use Migrations\Util\Util; -use Phinx\Migration\MigrationInterface as PhinxMigrationInterface; -use Phinx\Seed\SeedInterface as PhinxSeedInterface; use Psr\Container\ContainerInterface; use RuntimeException; @@ -230,15 +226,10 @@ public function markMigrated(int $version, string $path): bool } $migrationFile = $migrationFile[0]; - /** @var class-string<\Phinx\Migration\MigrationInterface|\Migrations\MigrationInterface> $className */ $className = $this->getMigrationClassName($migrationFile); require_once $migrationFile; - if (is_subclass_of($className, PhinxMigrationInterface::class)) { - $migration = new MigrationAdapter($className, $version); - } else { - $migration = new $className($version); - } + $migration = new $className($version); /** @var \Migrations\MigrationInterface $migration */ $config = $this->getConfig(); $migration->setConfig($config); @@ -254,7 +245,7 @@ public function markMigrated(int $version, string $path): bool * Resolves a migration class name based on $path * * @param string $path Path to the migration file of which we want the class name - * @return string Migration class name + * @return class-string<\Migrations\MigrationInterface> Migration class name */ protected function getMigrationClassName(string $path): string { @@ -266,6 +257,7 @@ protected function getMigrationClassName(string $path): string $class = substr($class, 0, strpos($class, '.')); } + /** @var class-string<\Migrations\MigrationInterface> */ return $class; } @@ -870,11 +862,7 @@ function ($phpFile) { } $io->verbose("Constructing $class."); - if (is_subclass_of($class, PhinxMigrationInterface::class)) { - $migration = new MigrationAdapter($class, $version); - } else { - $migration = new $class($version); - } + $migration = new $class($version); /** @var \Migrations\MigrationInterface $migration */ $config = $this->getConfig(); $migration->setConfig($config); @@ -983,6 +971,7 @@ public function getSeeds(): array foreach ($phpFiles as $filePath) { if (Util::isValidSeedFileName(basename($filePath))) { // convert the filename to a class name + /** @var class-string<\Migrations\SeedInterface> $class */ $class = pathinfo($filePath, PATHINFO_FILENAME); $fileNames[$class] = basename($filePath); @@ -998,17 +987,12 @@ public function getSeeds(): array } // instantiate it - /** @var \Phinx\Seed\AbstractSeed|\Migrations\SeedInterface $seed */ + /** @var \Migrations\SeedInterface $seed */ if (isset($this->container)) { $seed = $this->container->get($class); } else { $seed = new $class(); } - // Shim phinx seeds so that the rest of migrations - // can be isolated from phinx. - if ($seed instanceof PhinxSeedInterface) { - $seed = new SeedAdapter($seed); - } /** @var \Migrations\SeedInterface $seed */ $seed->setIo($io); $seed->setConfig($config); diff --git a/src/Migrations.php b/src/Migrations.php index cd6dfc86..f227e09c 100644 --- a/src/Migrations.php +++ b/src/Migrations.php @@ -13,12 +13,8 @@ */ namespace Migrations; -use Cake\Core\Configure; -use InvalidArgumentException; use Migrations\Migration\BackendInterface; use Migrations\Migration\BuiltinBackend; -use Phinx\Config\ConfigInterface; -use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\NullOutput; @@ -38,13 +34,6 @@ class Migrations */ protected OutputInterface $output; - /** - * CakeManager instance - * - * @var \Migrations\CakeManager|null - */ - protected ?CakeManager $manager = null; - /** * Default options to use * @@ -88,35 +77,6 @@ public function __construct(array $default = []) } } - /** - * Sets the command - * - * TODO(mark) Remove as part of phinx removal - * - * @param string $command Command name to store. - * @return $this - */ - public function setCommand(string $command) - { - $this->command = $command; - - return $this; - } - - /** - * Sets the input object that should be used for the command class. This object - * is used to inspect the extra options that are needed for CakePHP apps. - * - * TODO(mark) Remove as part of phinx removal - * - * @param \Symfony\Component\Console\Input\InputInterface $input the input object - * @return void - */ - public function setInput(InputInterface $input): void - { - // $this->input = $input; - } - /** * Gets the command * @@ -128,19 +88,13 @@ public function getCommand(): string } /** - * Get the Migrations interface backend based on configuration data. + * Get the Migrations interface backend. * * @return \Migrations\Migration\BackendInterface */ protected function getBackend(): BackendInterface { - // TODO(mark) Always return `BuiltinBackend` in the future, or remove this method. - $backend = (string)(Configure::read('Migrations.backend') ?? 'builtin'); - if ($backend === 'builtin') { - return new BuiltinBackend($this->default); - } - - throw new RuntimeException("Unknown `Migrations.backend` of `{$backend}`"); + return new BuiltinBackend($this->default); } /** @@ -242,48 +196,6 @@ public function seed(array $options = []): bool return $backend->seed($options); } - /** - * Returns an instance of CakeManager - * - * TODO(mark) Remove as part of phinx removal - * - * @param \Phinx\Config\ConfigInterface|null $config ConfigInterface the Manager needs to run - * @return \Migrations\CakeManager Instance of CakeManager - */ - public function getManager(?ConfigInterface $config = null): CakeManager - { - if (!($this->manager instanceof CakeManager)) { - if (!($config instanceof ConfigInterface)) { - throw new RuntimeException( - 'You need to pass a ConfigInterface object for your first getManager() call', - ); - } - - // $input = $this->input ?: $this->stubInput; - // $this->manager = new CakeManager($config, $input, $this->output); - } elseif ($config !== null) { - $defaultEnvironment = $config->getEnvironment('default'); - try { - $environment = $this->manager->getEnvironment('default'); - $oldConfig = $environment->getOptions(); - unset($oldConfig['connection']); - if ($oldConfig === $defaultEnvironment) { - $defaultEnvironment['connection'] = $environment - ->getAdapter() - ->getConnection(); - } - } catch (InvalidArgumentException $e) { - } - $config['environments'] = ['default' => $defaultEnvironment]; - $this->manager->setEnvironments([]); - $this->manager->setConfig($config); - } - - // $this->setAdapter(); - - return $this->manager; - } - /** * Get the input needed for each commands to be run * @@ -299,7 +211,7 @@ public function getManager(?ConfigInterface $config = null): CakeManager */ public function getInput(string $command, array $arguments, array $options): InputInterface { - $className = 'Migrations\Command\Phinx\\' . $command; + $className = 'Migrations\Command\\' . $command; $options = $arguments + $this->prepareOptions($options); /** @var \Symfony\Component\Console\Command\Command $command */ $command = new $className(); diff --git a/src/MigrationsPlugin.php b/src/MigrationsPlugin.php index 5c276bfc..1fd0d3ef 100644 --- a/src/MigrationsPlugin.php +++ b/src/MigrationsPlugin.php @@ -16,7 +16,6 @@ use Bake\Command\SimpleBakeCommand; use Cake\Console\CommandCollection; use Cake\Core\BasePlugin; -use Cake\Core\Configure; use Cake\Core\PluginApplicationInterface; use Migrations\Command\BakeMigrationCommand; use Migrations\Command\BakeMigrationDiffCommand; @@ -54,11 +53,6 @@ class MigrationsPlugin extends BasePlugin public function bootstrap(PluginApplicationInterface $app): void { parent::bootstrap($app); - - // TODO(mark) Remove this once phinx has been removed - if (!Configure::check('Migrations.backend')) { - Configure::write('Migrations.backend', 'builtin'); - } } /** diff --git a/src/Shim/MigrationAdapter.php b/src/Shim/MigrationAdapter.php deleted file mode 100644 index 5ac6003c..00000000 --- a/src/Shim/MigrationAdapter.php +++ /dev/null @@ -1,405 +0,0 @@ -migration = new $migrationClass('default', $version); - } else { - if (!is_subclass_of($migrationClass, PhinxMigrationInterface::class)) { - throw new RuntimeException( - 'The provided $migrationClass must be a ' . - 'subclass of Phinx\Migration\MigrationInterface', - ); - } - $this->migration = $migrationClass; - } - } - - /** - * Because we're a compatibility shim, we implement this hook - * so that it can be conditionally called when it is implemented. - * - * @return void - */ - public function init(): void - { - if (method_exists($this->migration, MigrationInterface::INIT)) { - $this->migration->{MigrationInterface::INIT}(); - } - } - - /** - * Compatibility shim for executing change/up/down - */ - public function applyDirection(string $direction): void - { - $adapter = $this->getAdapter(); - - // Run the migration - if (method_exists($this->migration, MigrationInterface::CHANGE)) { - if ($direction === MigrationInterface::DOWN) { - // Create an instance of the RecordingAdapter so we can record all - // of the migration commands for reverse playback - $adapter = $this->migration->getAdapter(); - assert($adapter !== null, 'Adapter must be set in migration'); - - /** @var \Phinx\Db\Adapter\ProxyAdapter $proxyAdapter */ - $proxyAdapter = PhinxAdapterFactory::instance() - ->getWrapper('proxy', $adapter); - - // Wrap the adapter with a phinx shim to maintain contain - $this->migration->setAdapter($proxyAdapter); - - $this->migration->{MigrationInterface::CHANGE}(); - $proxyAdapter->executeInvertedCommands(); - - $this->migration->setAdapter($adapter); - } else { - $this->migration->{MigrationInterface::CHANGE}(); - } - } else { - $this->migration->{$direction}(); - } - } - - /** - * {@inheritDoc} - */ - public function setAdapter(AdapterInterface $adapter) - { - $phinxAdapter = new PhinxAdapter($adapter); - $this->migration->setAdapter($phinxAdapter); - $this->adapter = $adapter; - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getAdapter(): AdapterInterface - { - if (!$this->adapter) { - throw new RuntimeException('Cannot call getAdapter() until after setAdapter().'); - } - - return $this->adapter; - } - - /** - * {@inheritDoc} - */ - public function setIo(ConsoleIo $io) - { - $this->io = $io; - $this->migration->setOutput(new OutputAdapter($io)); - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getIo(): ?ConsoleIo - { - return $this->io; - } - - /** - * {@inheritDoc} - */ - public function getConfig(): ?ConfigInterface - { - return $this->config; - } - - /** - * {@inheritDoc} - */ - public function setConfig(ConfigInterface $config) - { - $input = new ArrayInput([ - '--plugin' => $config['plugin'] ?? null, - '--source' => $config['source'] ?? null, - '--connection' => $config->getConnection(), - ]); - - $this->migration->setInput($input); - $this->config = $config; - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getName(): string - { - return $this->migration->getName(); - } - - /** - * {@inheritDoc} - */ - public function setVersion(int $version) - { - $this->migration->setVersion($version); - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getVersion(): int - { - return $this->migration->getVersion(); - } - - /** - * {@inheritDoc} - */ - public function useTransactions(): bool - { - if (method_exists($this->migration, 'useTransactions')) { - return $this->migration->useTransactions(); - } - - return $this->migration->getAdapter()->hasTransactions(); - } - - /** - * {@inheritDoc} - */ - public function setMigratingUp(bool $isMigratingUp) - { - $this->migration->setMigratingUp($isMigratingUp); - - return $this; - } - - /** - * {@inheritDoc} - */ - public function isMigratingUp(): bool - { - return $this->migration->isMigratingUp(); - } - - /** - * {@inheritDoc} - */ - public function execute(string $sql, array $params = []): int - { - return $this->migration->execute($sql, $params); - } - - /** - * {@inheritDoc} - */ - public function query(string $sql, array $params = []): mixed - { - return $this->migration->query($sql, $params); - } - - /** - * {@inheritDoc} - */ - public function getQueryBuilder(string $type): Query - { - return $this->migration->getQueryBuilder($type); - } - - /** - * {@inheritDoc} - */ - public function getSelectBuilder(): SelectQuery - { - return $this->migration->getSelectBuilder(); - } - - /** - * {@inheritDoc} - */ - public function getInsertBuilder(): InsertQuery - { - return $this->migration->getInsertBuilder(); - } - - /** - * {@inheritDoc} - */ - public function getUpdateBuilder(): UpdateQuery - { - return $this->migration->getUpdateBuilder(); - } - - /** - * {@inheritDoc} - */ - public function getDeleteBuilder(): DeleteQuery - { - return $this->migration->getDeleteBuilder(); - } - - /** - * {@inheritDoc} - */ - public function fetchRow(string $sql): array|false - { - return $this->migration->fetchRow($sql); - } - - /** - * {@inheritDoc} - */ - public function fetchAll(string $sql): array - { - return $this->migration->fetchAll($sql); - } - - /** - * {@inheritDoc} - */ - public function createDatabase(string $name, array $options): void - { - $this->migration->createDatabase($name, $options); - } - - /** - * {@inheritDoc} - */ - public function dropDatabase(string $name): void - { - $this->migration->dropDatabase($name); - } - - /** - * {@inheritDoc} - */ - public function createSchema(string $name): void - { - $this->migration->createSchema($name); - } - - /** - * {@inheritDoc} - */ - public function dropSchema(string $name): void - { - $this->migration->dropSchema($name); - } - - /** - * {@inheritDoc} - */ - public function hasTable(string $tableName): bool - { - return $this->migration->hasTable($tableName); - } - - /** - * {@inheritDoc} - */ - public function table(string $tableName, array $options = []): Table - { - throw new RuntimeException('MigrationAdapter::table is not implemented'); - } - - /** - * {@inheritDoc} - */ - public function preFlightCheck(): void - { - $this->migration->preFlightCheck(); - } - - /** - * {@inheritDoc} - */ - public function postFlightCheck(): void - { - $this->migration->postFlightCheck(); - } - - /** - * {@inheritDoc} - */ - public function shouldExecute(): bool - { - return $this->migration->shouldExecute(); - } -} diff --git a/src/Shim/SeedAdapter.php b/src/Shim/SeedAdapter.php deleted file mode 100644 index f5028b87..00000000 --- a/src/Shim/SeedAdapter.php +++ /dev/null @@ -1,252 +0,0 @@ -seed, PhinxSeedInterface::INIT)) { - $this->seed->{PhinxSeedInterface::INIT}(); - } - } - - /** - * {@inheritDoc} - */ - public function run(): void - { - $this->seed->run(); - } - - /** - * {@inheritDoc} - */ - public function getDependencies(): array - { - return $this->seed->getDependencies(); - } - - /** - * {@inheritDoc} - */ - public function setAdapter(AdapterInterface $adapter) - { - $phinxAdapter = new PhinxAdapter($adapter); - $this->seed->setAdapter($phinxAdapter); - $this->adapter = $adapter; - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getAdapter(): AdapterInterface - { - if (!$this->adapter) { - throw new RuntimeException('Cannot call getAdapter() until after setAdapter().'); - } - - return $this->adapter; - } - - /** - * {@inheritDoc} - */ - public function setIo(ConsoleIo $io) - { - $this->io = $io; - $this->seed->setOutput(new OutputAdapter($io)); - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getIo(): ?ConsoleIo - { - return $this->io; - } - - /** - * {@inheritDoc} - */ - public function getConfig(): ?ConfigInterface - { - return $this->config; - } - - /** - * {@inheritDoc} - */ - public function setConfig(ConfigInterface $config) - { - $optionDef = new InputDefinition([ - new InputOption('plugin', mode: InputOption::VALUE_OPTIONAL, default: ''), - new InputOption('connection', mode: InputOption::VALUE_OPTIONAL, default: ''), - new InputOption('source', mode: InputOption::VALUE_OPTIONAL, default: ''), - ]); - $input = new ArrayInput([ - '--plugin' => $config['plugin'] ?? null, - '--source' => $config['source'] ?? null, - '--connection' => $config->getConnection(), - ], $optionDef); - - $this->seed->setInput($input); - $this->config = $config; - - return $this; - } - - /** - * {@inheritDoc} - */ - public function getName(): string - { - return $this->seed->getName(); - } - - /** - * {@inheritDoc} - */ - public function execute(string $sql, array $params = []): int - { - return $this->seed->execute($sql, $params); - } - - /** - * {@inheritDoc} - */ - public function query(string $sql, array $params = []): mixed - { - return $this->seed->query($sql, $params); - } - - /** - * {@inheritDoc} - */ - public function fetchRow(string $sql): array|false - { - return $this->seed->fetchRow($sql); - } - - /** - * {@inheritDoc} - */ - public function fetchAll(string $sql): array - { - return $this->seed->fetchAll($sql); - } - - /** - * {@inheritDoc} - */ - public function insert(string $tableName, array $data): void - { - $this->seed->insert($tableName, $data); - } - - /** - * {@inheritDoc} - */ - public function hasTable(string $tableName): bool - { - return $this->seed->hasTable($tableName); - } - - /** - * {@inheritDoc} - */ - public function table(string $tableName, array $options = []): Table - { - throw new RuntimeException('Not implemented'); - } - - /** - * {@inheritDoc} - */ - public function shouldExecute(): bool - { - return $this->seed->shouldExecute(); - } - - /** - * {@inheritDoc} - */ - public function call(string $seeder, array $options = []): void - { - throw new RuntimeException('Not implemented'); - } -} diff --git a/src/Table.php b/src/Table.php deleted file mode 100644 index f43f3b41..00000000 --- a/src/Table.php +++ /dev/null @@ -1,249 +0,0 @@ -primaryKey = $columns; - - return $this; - } - - /** - * {@inheritDoc} - * - * You can pass `autoIncrement` as an option and it will be converted - * to the correct option for phinx to create the column with an - * auto increment attribute - * - * @param string|\Phinx\Db\Table\Column $columnName Column Name - * @param string|\Phinx\Util\Literal|null $type Column Type - * @param array $options Column Options - * @throws \InvalidArgumentException - * @return $this - */ - public function addColumn(Column|string $columnName, string|Literal|null $type = null, $options = []) - { - $options = $this->convertedAutoIncrement($options); - - return parent::addColumn($columnName, $type, $options); - } - - /** - * {@inheritDoc} - * - * You can pass `autoIncrement` as an option and it will be converted - * to the correct option for phinx to create the column with an - * auto increment attribute - * - * @param string $columnName Column Name - * @param string|\Phinx\Db\Table\Column|\Phinx\Util\Literal $newColumnType New Column Type - * @param array $options Options - * @return $this - */ - public function changeColumn(string $columnName, string|Column|Literal $newColumnType, array $options = []) - { - $options = $this->convertedAutoIncrement($options); - - return parent::changeColumn($columnName, $newColumnType, $options); - } - - /** - * Convert the `autoIncrement` option to the correct options for phinx. - * - * @param array $options Options - * @return array Converted options - */ - protected function convertedAutoIncrement(array $options): array - { - if (isset($options['autoIncrement']) && $options['autoIncrement'] === true) { - $options['identity'] = true; - unset($options['autoIncrement']); - } - - return $options; - } - - /** - * {@inheritDoc} - * - * If using MySQL and no collation information has been given to the table options, a request to the information - * schema will be made to get the default database collation and apply it to the database. This is to prevent - * phinx default mechanism to put the collation to a default of "utf8_general_ci". - * - * @return void - */ - public function create(): void - { - $options = $this->getTable()->getOptions(); - if ((!isset($options['id']) || $options['id'] === false) && !empty($this->primaryKey)) { - $options['primary_key'] = $this->primaryKey; - $this->filterPrimaryKey(); - } - - if ($this->getAdapter()->getAdapterType() === 'mysql' && empty($options['collation'])) { - $encodingRequest = 'SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME - FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = :dbname'; - - $cakeConnection = $this->getAdapter()->getCakeConnection(); - $connectionConfig = $cakeConnection->config(); - - $statement = $cakeConnection->execute($encodingRequest, ['dbname' => $connectionConfig['database']]); - $defaultEncoding = $statement->fetch('assoc'); - if (!empty($defaultEncoding['DEFAULT_COLLATION_NAME'])) { - $options['collation'] = $defaultEncoding['DEFAULT_COLLATION_NAME']; - } - } - - $this->getTable()->setOptions($options); - - parent::create(); - } - - /** - * {@inheritDoc} - * - * After a table update, the TableRegistry should be cleared in order to prevent issues with - * table schema stored in Table objects having columns that might have been renamed or removed during - * the update process. - * - * @return void - */ - public function update(): void - { - parent::update(); - $this->getTableLocator()->clear(); - } - - /** - * {@inheritDoc} - * - * We disable foreign key deletion for the SQLite adapter as SQLite does not support the feature natively and the - * process implemented by Phinx has serious side-effects (for instance it renames FK references in existing tables - * which breaks the database schema cohesion). - * - * @param string|array $columns Column(s) - * @param string|null $constraint Constraint names - * @return $this - */ - public function dropForeignKey($columns, $constraint = null) - { - if ($this->getAdapter()->getAdapterType() === 'sqlite') { - return $this; - } - - return parent::dropForeignKey($columns, $constraint); - } - - /** - * This method is called in case a primary key was defined using the addPrimaryKey() method. - * It currently does something only if using SQLite. - * If a column is an auto-increment key in SQLite, it has to be a primary key and it has to defined - * when defining the column. Phinx takes care of that so we have to make sure columns defined as autoincrement were - * not added with the addPrimaryKey method, otherwise, SQL queries will be wrong. - * - * @return void - */ - protected function filterPrimaryKey(): void - { - $options = $this->getTable()->getOptions(); - if ($this->getAdapter()->getAdapterType() !== 'sqlite' || empty($options['primary_key'])) { - return; - } - - $primaryKey = $options['primary_key']; - if (!is_array($primaryKey)) { - $primaryKey = [$primaryKey]; - } - $primaryKey = array_flip($primaryKey); - - $columnsCollection = (new Collection($this->actions->getActions())) - ->filter(function ($action) { - return $action instanceof AddColumn; - }) - ->map(function ($action) { - /** @var \Phinx\Db\Action\ChangeColumn|\Phinx\Db\Action\RenameColumn|\Phinx\Db\Action\RemoveColumn|\Phinx\Db\Action\AddColumn $action */ - return $action->getColumn(); - }); - $primaryKeyColumns = $columnsCollection->filter(function (Column $columnDef, $key) use ($primaryKey) { - return isset($primaryKey[$columnDef->getName()]); - })->toArray(); - - if (!$primaryKeyColumns) { - return; - } - - foreach ($primaryKeyColumns as $primaryKeyColumn) { - if ($primaryKeyColumn->isIdentity()) { - unset($primaryKey[$primaryKeyColumn->getName()]); - } - } - - $primaryKey = array_flip($primaryKey); - - if ($primaryKey) { - $options['primary_key'] = $primaryKey; - } else { - unset($options['primary_key']); - } - - $this->getTable()->setOptions($options); - } - - /** - * @inheritDoc - */ - public function addTimestamps($createdAt = '', $updatedAt = '', bool $withTimezone = false) - { - $createdAt = $createdAt ?: 'created'; - $updatedAt = $updatedAt ?: 'modified'; - - return parent::addTimestamps($createdAt, $updatedAt, $withTimezone); - } -} diff --git a/templates/Phinx/create.php.template b/templates/Phinx/create.php.template deleted file mode 100644 index 82a91ba0..00000000 --- a/templates/Phinx/create.php.template +++ /dev/null @@ -1,18 +0,0 @@ -update(); @@ -111,7 +101,7 @@ not empty %} {{ Migration.element( 'Migrations.add-foreign-keys', - {'constraints': tableDiff['constraints']['add'], 'table': tableName, 'backend': backend} + {'constraints': tableDiff['constraints']['add'], 'table': tableName} ) | raw -}} {% endif -%} {% endfor -%} @@ -127,7 +117,7 @@ not empty %} * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/phinx/0/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/templates/bake/config/skeleton.twig b/templates/bake/config/skeleton.twig index 5e2cbe5f..3f04d3a7 100644 --- a/templates/bake/config/skeleton.twig +++ b/templates/bake/config/skeleton.twig @@ -20,15 +20,9 @@ 1 %} {% set storedColumnList = '[' ~ Migration.stringifyList(constraint['columns'], {'indent': 5}) ~ ']' %} {% set columnsList = '[' ~ Migration.stringifyList(constraint['columns'], {'indent': indent}) ~ ']' %} @@ -25,7 +25,6 @@ {{ statement | raw }} {% set statement = null %} {% endif %} -{% if backend == 'builtin' %} ->addForeignKey( $this->foreignKey({{ columnsList | raw }}) ->setReferencedTable('{{ constraint['references'][0] }}') @@ -34,18 +33,6 @@ ->setOnUpdate('{{ Migration.formatConstraintAction(constraint['update']) | raw }}') ->setName('{{ constraintName }}') ) -{% else %} - ->addForeignKey( - {{ columnsList | raw }}, - '{{ constraint['references'][0] }}', - {{ columnsReference | raw }}, - [ - 'update' => '{{ Migration.formatConstraintAction(constraint['update']) | raw }}', - 'delete' => '{{ Migration.formatConstraintAction(constraint['delete']) | raw }}', - 'constraint' => '{{ constraintName }}' - ] - ) -{% endif %} {% endif %} {% endfor %} {% if Migration.wasTableStatementGeneratedFor(table) and hasProcessedConstraint %} diff --git a/templates/bake/element/add-indexes.twig b/templates/bake/element/add-indexes.twig index 42900b25..388349ea 100644 --- a/templates/bake/element/add-indexes.twig +++ b/templates/bake/element/add-indexes.twig @@ -4,7 +4,6 @@ {% set columnsList = '[' ~ Migration.stringifyList(index['columns'], {'indent': 6}) ~ ']' %} {% endif %} ->addIndex( -{% if backend == 'builtin' %} $this->index({{ columnsList | raw }}) ->setName('{{ indexName }}') {% if index['type'] == 'unique' %} @@ -16,13 +15,4 @@ ->setOptions([{{ Migration.stringifyList(index['options'], {'indent': 6}) | raw }}]) {% endif %} ) -{% else %} - [{{ Migration.stringifyList(index['columns'], {'indent': 5}) | raw }}], -{% set params = {'name': indexName} %} -{% if index['type'] == 'unique' %} -{% set params = params|merge({'unique': true}) %} -{% endif %} - [{{ Migration.stringifyList(params, {'indent': 5}) | raw }}] - ) -{% endif %} {% endfor %} diff --git a/tests/ExampleCommand.php b/tests/ExampleCommand.php deleted file mode 100644 index a4f68b60..00000000 --- a/tests/ExampleCommand.php +++ /dev/null @@ -1,20 +0,0 @@ -write($messages, true, $options | self::OUTPUT_RAW); } diff --git a/tests/TestCase/Command/BakeMigrationCommandTest.php b/tests/TestCase/Command/BakeMigrationCommandTest.php index 505ec595..6b240425 100644 --- a/tests/TestCase/Command/BakeMigrationCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationCommandTest.php @@ -14,7 +14,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\BaseCommand; -use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\TestSuite\StringCompareTrait; use Migrations\Command\BakeMigrationCommand; @@ -115,7 +114,6 @@ public function testCreate($name, $fileSuffix) */ public function testCreatePhinx() { - Configure::write('Migrations.backend', 'phinx'); $this->exec('bake migration CreateUsers name --connection test'); $file = glob(ROOT . DS . 'config' . DS . 'Migrations' . DS . '*_CreateUsers.php'); @@ -150,7 +148,6 @@ public function testCreateWithReservedKeyword() public function testCreateBuiltinAlias() { - Configure::write('Migrations.backend', 'builtin'); $this->exec('migrations create CreateUsers --connection test'); $this->assertExitCode(BaseCommand::CODE_SUCCESS); $this->assertOutputRegExp('/Wrote.*?CreateUsers\.php/'); diff --git a/tests/TestCase/Command/BakeMigrationDiffCommandTest.php b/tests/TestCase/Command/BakeMigrationDiffCommandTest.php index 0de89739..b6ae153c 100644 --- a/tests/TestCase/Command/BakeMigrationDiffCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationDiffCommandTest.php @@ -46,7 +46,6 @@ public function setUp(): void parent::setUp(); $this->generatedFiles = []; - Configure::write('Migrations.backend', 'builtin'); } public function tearDown(): void diff --git a/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php b/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php index 238e3c37..4960d542 100644 --- a/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php @@ -61,7 +61,6 @@ public function setUp(): void $this->migrationPath = ROOT . DS . 'config' . DS . 'Migrations' . DS; $this->generatedFiles = []; - Configure::write('Migrations.backend', 'builtin'); } /** diff --git a/tests/TestCase/Command/BakeSeedCommandTest.php b/tests/TestCase/Command/BakeSeedCommandTest.php index 0ab7be7b..14c5b07e 100644 --- a/tests/TestCase/Command/BakeSeedCommandTest.php +++ b/tests/TestCase/Command/BakeSeedCommandTest.php @@ -14,7 +14,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\BaseCommand; -use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\TestSuite\StringCompareTrait; use Migrations\Test\TestCase\TestCase; @@ -59,7 +58,6 @@ public function setUp(): void */ public function testBasicBakingPhinx() { - Configure::write('Migrations.backend', 'phinx'); $this->generatedFile = ROOT . DS . 'config/Seeds/ArticlesSeed.php'; $this->exec('bake seed Articles --connection test'); diff --git a/tests/TestCase/Command/DumpCommandTest.php b/tests/TestCase/Command/DumpCommandTest.php index 45c07b04..e6035f6f 100644 --- a/tests/TestCase/Command/DumpCommandTest.php +++ b/tests/TestCase/Command/DumpCommandTest.php @@ -4,7 +4,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\Core\Exception\MissingPluginException; use Cake\Core\Plugin; use Cake\Database\Connection; @@ -24,7 +23,6 @@ class DumpCommandTest extends TestCase public function setUp(): void { parent::setUp(); - Configure::write('Migrations.backend', 'builtin'); /** @var \Cake\Database\Connection $this->connection */ $this->connection = ConnectionManager::get('test'); diff --git a/tests/TestCase/Command/EntryCommandTest.php b/tests/TestCase/Command/EntryCommandTest.php index 539b014f..e3607137 100644 --- a/tests/TestCase/Command/EntryCommandTest.php +++ b/tests/TestCase/Command/EntryCommandTest.php @@ -17,7 +17,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\TestSuite\TestCase; /** @@ -30,8 +29,6 @@ class EntryCommandTest extends TestCase public function setUp(): void { parent::setUp(); - - Configure::write('Migrations.backend', 'builtin'); } /** diff --git a/tests/TestCase/Command/MarkMigratedTest.php b/tests/TestCase/Command/MarkMigratedTest.php index e1c94ec3..8237c65e 100644 --- a/tests/TestCase/Command/MarkMigratedTest.php +++ b/tests/TestCase/Command/MarkMigratedTest.php @@ -14,7 +14,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\Core\Exception\MissingPluginException; use Cake\Datasource\ConnectionManager; use Cake\TestSuite\TestCase; @@ -41,7 +40,6 @@ class MarkMigratedTest extends TestCase public function setUp(): void { parent::setUp(); - Configure::write('Migrations.backend', 'builtin'); $this->connection = ConnectionManager::get('test'); $this->connection->execute('DROP TABLE IF EXISTS migrator_phinxlog'); diff --git a/tests/TestCase/Command/MigrateCommandTest.php b/tests/TestCase/Command/MigrateCommandTest.php index a7040aae..b66d5644 100644 --- a/tests/TestCase/Command/MigrateCommandTest.php +++ b/tests/TestCase/Command/MigrateCommandTest.php @@ -4,7 +4,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\Core\Exception\MissingPluginException; use Cake\Database\Exception\DatabaseException; use Cake\Datasource\ConnectionManager; @@ -21,7 +20,6 @@ class MigrateCommandTest extends TestCase public function setUp(): void { parent::setUp(); - Configure::write('Migrations.backend', 'builtin'); try { $table = $this->fetchTable('Phinxlog'); diff --git a/tests/TestCase/Command/RollbackCommandTest.php b/tests/TestCase/Command/RollbackCommandTest.php index c233e6d2..1c0cab47 100644 --- a/tests/TestCase/Command/RollbackCommandTest.php +++ b/tests/TestCase/Command/RollbackCommandTest.php @@ -4,7 +4,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\Database\Exception\DatabaseException; use Cake\Datasource\ConnectionManager; use Cake\Event\EventInterface; @@ -22,7 +21,6 @@ class RollbackCommandTest extends TestCase public function setUp(): void { parent::setUp(); - Configure::write('Migrations.backend', 'builtin'); try { $table = $this->fetchTable('Phinxlog'); diff --git a/tests/TestCase/Command/SeedCommandTest.php b/tests/TestCase/Command/SeedCommandTest.php index 2f219f92..812c8c24 100644 --- a/tests/TestCase/Command/SeedCommandTest.php +++ b/tests/TestCase/Command/SeedCommandTest.php @@ -4,15 +4,12 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\Database\Exception\DatabaseException; use Cake\Datasource\ConnectionManager; use Cake\Event\EventInterface; use Cake\Event\EventManager; use Cake\TestSuite\TestCase; use InvalidArgumentException; -use Phinx\Config\FeatureFlags; -use ReflectionClass; use ReflectionProperty; class SeedCommandTest extends TestCase @@ -22,7 +19,6 @@ class SeedCommandTest extends TestCase public function setUp(): void { parent::setUp(); - Configure::write('Migrations.backend', 'builtin'); $table = $this->fetchTable('Phinxlog'); try { @@ -40,13 +36,6 @@ public function tearDown(): void $connection->execute('DROP TABLE IF EXISTS numbers'); $connection->execute('DROP TABLE IF EXISTS letters'); $connection->execute('DROP TABLE IF EXISTS stores'); - - if (class_exists(FeatureFlags::class)) { - $reflection = new ReflectionClass(FeatureFlags::class); - if ($reflection->hasProperty('addTimestampsUseDateTime')) { - FeatureFlags::$addTimestampsUseDateTime = false; - } - } } protected function resetOutput(): void @@ -204,13 +193,6 @@ public function testSeederSourceNotFound(): void public function testSeederWithTimestampFields(): void { - if (class_exists(FeatureFlags::class)) { - $reflection = new ReflectionClass(FeatureFlags::class); - if ($reflection->hasProperty('addTimestampsUseDateTime')) { - FeatureFlags::$addTimestampsUseDateTime = false; - } - } - $this->createTables(); $this->exec('migrations seed -c test --seed StoresSeed'); @@ -236,12 +218,9 @@ public function testSeederWithTimestampFields(): void public function testSeederWithDateTimeFields(): void { - $this->skipIf(!class_exists(FeatureFlags::class)); - - $reflection = new ReflectionClass(FeatureFlags::class); - $this->skipIf(!$reflection->hasProperty('addTimestampsUseDateTime')); + $this->markTestSkipped('FeatureFlags test no longer needed without Phinx.'); - FeatureFlags::$addTimestampsUseDateTime = true; + return; $this->createTables(); $this->exec('migrations seed -c test --seed StoresSeed'); diff --git a/tests/TestCase/Command/StatusCommandTest.php b/tests/TestCase/Command/StatusCommandTest.php index d9562b73..a1a153b8 100644 --- a/tests/TestCase/Command/StatusCommandTest.php +++ b/tests/TestCase/Command/StatusCommandTest.php @@ -4,7 +4,6 @@ namespace Migrations\Test\TestCase\Command; use Cake\Console\TestSuite\ConsoleIntegrationTestTrait; -use Cake\Core\Configure; use Cake\Core\Exception\MissingPluginException; use Cake\Database\Exception\DatabaseException; use Cake\TestSuite\TestCase; @@ -17,7 +16,6 @@ class StatusCommandTest extends TestCase public function setUp(): void { parent::setUp(); - Configure::write('Migrations.backend', 'builtin'); $table = $this->fetchTable('Phinxlog'); try { diff --git a/tests/TestCase/Db/Adapter/AbstractAdapterTest.php b/tests/TestCase/Db/Adapter/AbstractAdapterTest.php index abb83da1..14fc6db4 100644 --- a/tests/TestCase/Db/Adapter/AbstractAdapterTest.php +++ b/tests/TestCase/Db/Adapter/AbstractAdapterTest.php @@ -3,10 +3,10 @@ namespace Migrations\Test\Db\Adapter; +use Migrations\Config\Config; use Migrations\Db\Adapter\AbstractAdapter; use Migrations\Test\TestCase\Db\Adapter\DefaultAdapterTrait; use PDOException; -use Phinx\Config\Config; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -14,7 +14,7 @@ class AbstractAdapterTest extends TestCase { /** - * @var \Phinx\Db\Adapter\AbstractAdapter|\PHPUnit\Framework\MockObject\MockObject + * @var \Migrations\Db\Adapter\AbstractAdapter|\PHPUnit\Framework\MockObject\MockObject */ private $adapter; diff --git a/tests/TestCase/Db/Adapter/PhinxAdapterTest.php b/tests/TestCase/Db/Adapter/PhinxAdapterTest.php deleted file mode 100644 index e8726495..00000000 --- a/tests/TestCase/Db/Adapter/PhinxAdapterTest.php +++ /dev/null @@ -1,1697 +0,0 @@ - $config */ - $config = ConnectionManager::getConfig('test'); - if ($config['scheme'] !== 'sqlite') { - $this->markTestSkipped('phinx adapter tests require sqlite'); - } - // Emulate the results of Util::parseDsn() - $this->config = [ - 'adapter' => 'sqlite', - 'connection' => ConnectionManager::get('test'), - 'database' => $config['database'], - 'suffix' => '', - ]; - $this->adapter = new PhinxAdapter( - new SqliteAdapter( - $this->config, - $this->getConsoleIo(), - ), - ); - - if ($config['database'] !== ':memory:') { - // ensure the database is empty for each test - $this->adapter->dropDatabase($config['database']); - $this->adapter->createDatabase($config['database']); - } - - // leave the adapter in a disconnected state for each test - $this->adapter->disconnect(); - } - - protected function tearDown(): void - { - unset($this->adapter, $this->out, $this->io); - } - - protected function getConsoleIo(): ConsoleIo - { - $out = new StubConsoleOutput(); - $in = new StubConsoleInput([]); - $io = new ConsoleIo($out, $out, $in); - - $this->out = $out; - $this->io = $io; - - return $this->io; - } - - public function testBeginTransaction() - { - $this->adapter->beginTransaction(); - - $this->assertTrue( - $this->adapter->getConnection()->inTransaction(), - 'Underlying PDO instance did not detect new transaction', - ); - $this->adapter->rollbackTransaction(); - } - - public function testRollbackTransaction() - { - $this->adapter->beginTransaction(); - $this->adapter->rollbackTransaction(); - - $this->assertFalse( - $this->adapter->getConnection()->inTransaction(), - 'Underlying PDO instance did not detect rolled back transaction', - ); - } - - public function testQuoteTableName() - { - $this->assertEquals('"test_table"', $this->adapter->quoteTableName('test_table')); - } - - public function testQuoteColumnName() - { - $this->assertEquals('"test_column"', $this->adapter->quoteColumnName('test_column')); - } - - public function testCreateTable() - { - $table = new PhinxTable('ntable', [], $this->adapter); - $table->addColumn('realname', 'string') - ->addColumn('email', 'integer') - ->save(); - $this->assertTrue($this->adapter->hasTable('ntable')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'id')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'realname')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'email')); - $this->assertFalse($this->adapter->hasColumn('ntable', 'address')); - } - - public function testCreateTableCustomIdColumn() - { - $table = new PhinxTable('ntable', ['id' => 'custom_id'], $this->adapter); - $table->addColumn('realname', 'string') - ->addColumn('email', 'integer') - ->save(); - - $this->assertTrue($this->adapter->hasTable('ntable')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'custom_id')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'realname')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'email')); - $this->assertFalse($this->adapter->hasColumn('ntable', 'address')); - - //ensure the primary key is not nullable - /** @var \Phinx\Db\Table\Column $idColumn */ - $idColumn = $this->adapter->getColumns('ntable')[0]; - $this->assertInstanceOf(PhinxColumn::class, $idColumn); - $this->assertTrue($idColumn->getIdentity()); - $this->assertFalse($idColumn->isNull()); - } - - public function testCreateTableIdentityIdColumn() - { - $table = new PhinxTable('ntable', ['id' => false, 'primary_key' => ['custom_id']], $this->adapter); - $table->addColumn('custom_id', 'integer', ['identity' => true]) - ->save(); - - $this->assertTrue($this->adapter->hasTable('ntable')); - $this->assertTrue($this->adapter->hasColumn('ntable', 'custom_id')); - - /** @var \Phinx\Db\Table\Column $idColumn */ - $idColumn = $this->adapter->getColumns('ntable')[0]; - $this->assertInstanceOf(PhinxColumn::class, $idColumn); - $this->assertTrue($idColumn->getIdentity()); - } - - public function testCreateTableWithNoPrimaryKey() - { - $options = [ - 'id' => false, - ]; - $table = new PhinxTable('atable', $options, $this->adapter); - $table->addColumn('user_id', 'integer') - ->save(); - $this->assertFalse($this->adapter->hasColumn('atable', 'id')); - } - - public function testCreateTableWithMultiplePrimaryKeys() - { - $options = [ - 'id' => false, - 'primary_key' => ['user_id', 'tag_id'], - ]; - $table = new PhinxTable('table1', $options, $this->adapter); - $table->addColumn('user_id', 'integer') - ->addColumn('tag_id', 'integer') - ->save(); - $this->assertTrue($this->adapter->hasIndex('table1', ['user_id', 'tag_id'])); - $this->assertTrue($this->adapter->hasIndex('table1', ['USER_ID', 'tag_id'])); - $this->assertFalse($this->adapter->hasIndex('table1', ['tag_id', 'USER_ID'])); - $this->assertFalse($this->adapter->hasIndex('table1', ['tag_id', 'user_email'])); - } - - /** - * @return void - */ - public function testCreateTableWithPrimaryKeyAsUuid() - { - $options = [ - 'id' => false, - 'primary_key' => 'id', - ]; - $table = new PhinxTable('ztable', $options, $this->adapter); - $table->addColumn('id', 'uuid')->save(); - $this->assertTrue($this->adapter->hasColumn('ztable', 'id')); - $this->assertTrue($this->adapter->hasIndex('ztable', 'id')); - } - - /** - * @return void - */ - public function testCreateTableWithPrimaryKeyAsBinaryUuid() - { - $options = [ - 'id' => false, - 'primary_key' => 'id', - ]; - $table = new PhinxTable('ztable', $options, $this->adapter); - $table->addColumn('id', 'binaryuuid')->save(); - $this->assertTrue($this->adapter->hasColumn('ztable', 'id')); - $this->assertTrue($this->adapter->hasIndex('ztable', 'id')); - } - - public function testCreateTableWithMultipleIndexes() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('email', 'string') - ->addColumn('name', 'string') - ->addIndex('email') - ->addIndex('name') - ->save(); - $this->assertTrue($this->adapter->hasIndex('table1', ['email'])); - $this->assertTrue($this->adapter->hasIndex('table1', ['name'])); - $this->assertFalse($this->adapter->hasIndex('table1', ['email', 'user_email'])); - $this->assertFalse($this->adapter->hasIndex('table1', ['email', 'user_name'])); - } - - public function testCreateTableWithUniqueIndexes() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('email', 'string') - ->addIndex('email', ['unique' => true]) - ->save(); - $this->assertTrue($this->adapter->hasIndex('table1', ['email'])); - $this->assertFalse($this->adapter->hasIndex('table1', ['email', 'user_email'])); - } - - public function testCreateTableWithNamedIndexes() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('email', 'string') - ->addIndex('email', ['name' => 'myemailindex']) - ->save(); - $this->assertTrue($this->adapter->hasIndex('table1', ['email'])); - $this->assertFalse($this->adapter->hasIndex('table1', ['email', 'user_email'])); - $this->assertTrue($this->adapter->hasIndexByName('table1', 'myemailindex')); - } - - public function testCreateTableWithForeignKey() - { - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn('field1', 'string')->save(); - - $table = new PhinxTable('table', [], $this->adapter); - $table->addColumn('ref_table_id', 'integer'); - $table->addForeignKey('ref_table_id', 'ref_table', 'id'); - $table->save(); - - $this->assertTrue($this->adapter->hasTable($table->getName())); - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), ['ref_table_id'])); - } - - public function testCreateTableWithIndexesAndForeignKey() - { - $refTable = new PhinxTable('tbl_master', [], $this->adapter); - $refTable->create(); - - $table = new PhinxTable('tbl_child', [], $this->adapter); - $table - ->addColumn('column1', 'integer') - ->addColumn('column2', 'integer') - ->addColumn('master_id', 'integer') - ->addIndex(['column2']) - ->addIndex(['column1', 'column2'], ['unique' => true, 'name' => 'uq_tbl_child_column1_column2_ndx']) - ->addForeignKey( - 'master_id', - 'tbl_master', - 'id', - ['delete' => 'NO_ACTION', 'update' => 'NO_ACTION', 'constraint' => 'fk_master_id'], - ) - ->create(); - - $this->assertTrue($this->adapter->hasIndex('tbl_child', 'column2')); - $this->assertTrue($this->adapter->hasIndex('tbl_child', ['column1', 'column2'])); - $this->assertTrue($this->adapter->hasForeignKey('tbl_child', ['master_id'])); - - $row = $this->adapter->fetchRow( - "SELECT * FROM sqlite_master WHERE \"type\" = 'table' AND \"tbl_name\" = 'tbl_child'", - ); - $this->assertStringContainsString( - 'CONSTRAINT "fk_master_id" FOREIGN KEY ("master_id") REFERENCES "tbl_master" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION', - $row['sql'], - ); - } - - public function testCreateTableWithoutAutoIncrementingPrimaryKeyAndWithForeignKey() - { - $refTable = (new PhinxTable('tbl_master', ['id' => false, 'primary_key' => 'id'], $this->adapter)) - ->addColumn('id', 'text'); - $refTable->create(); - - $table = (new PhinxTable('tbl_child', ['id' => false, 'primary_key' => 'master_id'], $this->adapter)) - ->addColumn('master_id', 'text') - ->addForeignKey( - 'master_id', - 'tbl_master', - 'id', - ['delete' => 'NO_ACTION', 'update' => 'NO_ACTION', 'constraint' => 'fk_master_id'], - ); - $table->create(); - - $this->assertTrue($this->adapter->hasForeignKey('tbl_child', ['master_id'])); - - $row = $this->adapter->fetchRow( - "SELECT * FROM sqlite_master WHERE \"type\" = 'table' AND \"tbl_name\" = 'tbl_child'", - ); - $this->assertStringContainsString( - 'CONSTRAINT "fk_master_id" FOREIGN KEY ("master_id") REFERENCES "tbl_master" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION', - $row['sql'], - ); - } - - public function testAddPrimaryKey() - { - $table = new PhinxTable('table1', ['id' => false], $this->adapter); - $table - ->addColumn('column1', 'integer') - ->addColumn('column2', 'integer') - ->save(); - - $table - ->changePrimaryKey('column1') - ->save(); - - $this->assertTrue($this->adapter->hasPrimaryKey('table1', ['column1'])); - } - - public function testChangePrimaryKey() - { - $table = new PhinxTable('table1', ['id' => false, 'primary_key' => 'column1'], $this->adapter); - $table - ->addColumn('column1', 'integer') - ->addColumn('column2', 'integer') - ->save(); - - $table - ->changePrimaryKey('column2') - ->save(); - - $this->assertFalse($this->adapter->hasPrimaryKey('table1', ['column1'])); - $this->assertTrue($this->adapter->hasPrimaryKey('table1', ['column2'])); - } - - public function testChangePrimaryKeyNonInteger() - { - $table = new PhinxTable('table1', ['id' => false, 'primary_key' => 'column1'], $this->adapter); - $table - ->addColumn('column1', 'string') - ->addColumn('column2', 'string') - ->save(); - - $table - ->changePrimaryKey('column2') - ->save(); - - $this->assertFalse($this->adapter->hasPrimaryKey('table1', ['column1'])); - $this->assertTrue($this->adapter->hasPrimaryKey('table1', ['column2'])); - } - - public function testDropPrimaryKey() - { - $table = new PhinxTable('table1', ['id' => false, 'primary_key' => 'column1'], $this->adapter); - $table - ->addColumn('column1', 'integer') - ->addColumn('column2', 'integer') - ->save(); - - $table - ->changePrimaryKey(null) - ->save(); - - $this->assertFalse($this->adapter->hasPrimaryKey('table1', ['column1'])); - } - - public function testAddMultipleColumnPrimaryKeyFails() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table - ->addColumn('column1', 'integer') - ->addColumn('column2', 'integer') - ->save(); - - $this->expectException(InvalidArgumentException::class); - - $table - ->changePrimaryKey(['column1', 'column2']) - ->save(); - } - - public function testChangeCommentFails() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->save(); - - $this->expectException(BadMethodCallException::class); - - $table - ->changeComment('comment1') - ->save(); - } - - public function testAddColumn() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->save(); - $this->assertFalse($table->hasColumn('email')); - $table->addColumn('email', 'string', ['null' => true]) - ->save(); - $this->assertTrue($table->hasColumn('email')); - - // In SQLite it is not possible to dictate order of added columns. - // $table->addColumn('realname', 'string', array('after' => 'id')) - // ->save(); - // $this->assertEquals('realname', $rows[1]['Field']); - } - - public function testAddColumnWithDefaultValue() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->save(); - $table->addColumn('default_zero', 'string', ['default' => 'test']) - ->save(); - $rows = $this->adapter->fetchAll(sprintf('pragma table_info(%s)', 'table1')); - $this->assertEquals("'test'", $rows[1]['dflt_value']); - } - - public function testAddColumnWithDefaultZero() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->save(); - $table->addColumn('default_zero', 'integer', ['default' => 0]) - ->save(); - $rows = $this->adapter->fetchAll(sprintf('pragma table_info(%s)', 'table1')); - $this->assertNotNull($rows[1]['dflt_value']); - $this->assertEquals('0', $rows[1]['dflt_value']); - } - - public function testAddColumnWithDefaultEmptyString() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->save(); - $table->addColumn('default_empty', 'string', ['default' => '']) - ->save(); - $rows = $this->adapter->fetchAll(sprintf('pragma table_info(%s)', 'table1')); - $this->assertEquals("''", $rows[1]['dflt_value']); - } - - public function testRenameColumnWithIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex('indexcol') - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'newindexcol')); - - $table->renameColumn('indexcol', 'newindexcol')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'newindexcol')); - } - - public function testRenameColumnWithUniqueIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex('indexcol', ['unique' => true]) - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'newindexcol')); - - $table->renameColumn('indexcol', 'newindexcol')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'newindexcol')); - } - - public function testRenameColumnWithCompositeIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol1', 'integer') - ->addColumn('indexcol2', 'integer') - ->addIndex(['indexcol1', 'indexcol2']) - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), ['indexcol1', 'indexcol2'])); - $this->assertFalse($this->adapter->hasIndex($table->getName(), ['indexcol1', 'newindexcol2'])); - - $table->renameColumn('indexcol2', 'newindexcol2')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), ['indexcol1', 'indexcol2'])); - $this->assertTrue($this->adapter->hasIndex($table->getName(), ['indexcol1', 'newindexcol2'])); - } - - /** - * Tests that rewriting the index SQL does not accidentally change - * the table name in case it matches the column name. - */ - public function testRenameColumnWithIndexMatchingTheTableName() - { - $table = new PhinxTable('indexcol', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex('indexcol') - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'newindexcol')); - - $table->renameColumn('indexcol', 'newindexcol')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'newindexcol')); - } - - /** - * Tests that rewriting the index SQL does not accidentally change - * column names that partially match the column to rename. - */ - public function testRenameColumnWithIndexColumnPartialMatch() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addColumn('indexcolumn', 'integer') - ->create(); - - $this->adapter->execute('CREATE INDEX custom_idx ON t (indexcolumn, indexcol)'); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), ['indexcolumn', 'indexcol'])); - $this->assertFalse($this->adapter->hasIndex($table->getName(), ['indexcolumn', 'newindexcol'])); - - $table->renameColumn('indexcol', 'newindexcol')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), ['indexcolumn', 'indexcol'])); - $this->assertTrue($this->adapter->hasIndex($table->getName(), ['indexcolumn', 'newindexcol'])); - } - - public function testRenameColumnWithIndexColumnRequiringQuoting() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex('indexcol') - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'new index col')); - - $table->renameColumn('indexcol', 'new index col')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'indexcol')); - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'new index col')); - } - - /** - * Indices that are using expressions are not being updated. - */ - public function testRenameColumnWithExpressionIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->create(); - - $this->adapter->execute('CREATE INDEX custom_idx ON t (`indexcol`, ABS(`indexcol`))'); - - $this->assertTrue($this->adapter->hasIndexByName('t', 'custom_idx')); - - $this->expectException(PDOException::class); - $this->expectExceptionMessage('no such column: indexcol'); - - $table->renameColumn('indexcol', 'newindexcol')->update(); - } - - public function testChangeColumn() - { - $table = new PhinxTable('t', [], $this->adapter); - $table->addColumn('column1', 'string') - ->save(); - $this->assertTrue($this->adapter->hasColumn('t', 'column1')); - $newColumn1 = new PhinxColumn(); - $newColumn1->setName('column1'); - $newColumn1->setType('string'); - $table->changeColumn('column1', $newColumn1); - $this->assertTrue($this->adapter->hasColumn('t', 'column1')); - $newColumn2 = new PhinxColumn(); - $newColumn2->setName('column2') - ->setType('string'); - $table->changeColumn('column1', $newColumn2)->save(); - $this->assertFalse($this->adapter->hasColumn('t', 'column1')); - $this->assertTrue($this->adapter->hasColumn('t', 'column2')); - } - - public function testChangeColumnDefaultValue() - { - $table = new PhinxTable('t', [], $this->adapter); - $table->addColumn('column1', 'string', ['default' => 'test']) - ->save(); - $newColumn1 = new PhinxColumn(); - $newColumn1 - ->setName('column1') - ->setDefault('test1') - ->setType('string'); - $table->changeColumn('column1', $newColumn1)->save(); - $rows = $this->adapter->fetchAll('pragma table_info(t)'); - - $this->assertEquals("'test1'", $rows[1]['dflt_value']); - } - - public function testChangeColumnWithForeignKey() - { - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn('field1', 'string')->save(); - - $table = new PhinxTable('another_table', [], $this->adapter); - $table - ->addColumn('ref_table_id', 'integer') - ->addForeignKey(['ref_table_id'], 'ref_table', ['id']) - ->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), ['ref_table_id'])); - - $table->changeColumn('ref_table_id', 'float')->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), ['ref_table_id'])); - } - - public function testChangeColumnWithIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex( - 'indexcol', - ['unique' => true], - ) - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - - $table->changeColumn('indexcol', 'integer', ['null' => false])->update(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - } - - public function testChangeColumnWithTrigger() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('triggercol', 'integer') - ->addColumn('othercol', 'integer') - ->create(); - - $triggerSQL = - 'CREATE TRIGGER update_t_othercol UPDATE OF triggercol ON t - BEGIN - UPDATE t SET othercol = new.triggercol; - END'; - - $this->adapter->execute($triggerSQL); - - $rows = $this->adapter->fetchAll( - "SELECT * FROM sqlite_master WHERE `type` = 'trigger' AND tbl_name = 't'", - ); - $this->assertCount(1, $rows); - $this->assertEquals('trigger', $rows[0]['type']); - $this->assertEquals('update_t_othercol', $rows[0]['name']); - $this->assertEquals($triggerSQL, $rows[0]['sql']); - - $table->changeColumn('triggercol', 'integer', ['null' => false])->update(); - - $rows = $this->adapter->fetchAll( - "SELECT * FROM sqlite_master WHERE `type` = 'trigger' AND tbl_name = 't'", - ); - $this->assertCount(1, $rows); - $this->assertEquals('trigger', $rows[0]['type']); - $this->assertEquals('update_t_othercol', $rows[0]['name']); - $this->assertEquals($triggerSQL, $rows[0]['sql']); - } - - public function testChangeColumnDefaultToZero() - { - $table = new PhinxTable('t', [], $this->adapter); - $table->addColumn('column1', 'integer') - ->save(); - $newColumn1 = new PhinxColumn(); - $newColumn1->setDefault(0) - ->setName('column1') - ->setType('integer'); - $table->changeColumn('column1', $newColumn1)->save(); - $rows = $this->adapter->fetchAll('pragma table_info(t)'); - $this->assertEquals('0', $rows[1]['dflt_value']); - } - - public function testChangeColumnDefaultToNull() - { - $table = new PhinxTable('t', [], $this->adapter); - $table->addColumn('column1', 'string', ['default' => 'test']) - ->save(); - $newColumn1 = new PhinxColumn(); - $newColumn1->setDefault(null) - ->setName('column1') - ->setType('string'); - $table->changeColumn('column1', $newColumn1)->save(); - $rows = $this->adapter->fetchAll('pragma table_info(t)'); - $this->assertNull($rows[1]['dflt_value']); - } - - public function testChangeColumnWithCommasInCommentsOrDefaultValue() - { - $table = new PhinxTable('t', [], $this->adapter); - $table->addColumn('column1', 'string', ['default' => 'one, two or three', 'comment' => 'three, two or one']) - ->save(); - $newColumn1 = new PhinxColumn(); - $newColumn1->setDefault('another default') - ->setName('column1') - ->setComment('another comment') - ->setType('string'); - $table->changeColumn('column1', $newColumn1)->save(); - $cols = $this->adapter->getColumns('t'); - $this->assertEquals('another default', (string)$cols[1]->getDefault()); - } - - public function testDropColumnWithIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex('indexcol') - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - - $table->removeColumn('indexcol')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'indexcol')); - } - - public function testDropColumnWithUniqueIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addIndex('indexcol', ['unique' => true]) - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcol')); - - $table->removeColumn('indexcol')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), 'indexcol')); - } - - public function testDropColumnWithCompositeIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol1', 'integer') - ->addColumn('indexcol2', 'integer') - ->addIndex(['indexcol1', 'indexcol2']) - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), ['indexcol1', 'indexcol2'])); - - $table->removeColumn('indexcol2')->update(); - - $this->assertFalse($this->adapter->hasIndex($table->getName(), ['indexcol1', 'indexcol2'])); - } - - /** - * Tests that removing columns does not accidentally drop indices - * on table names that match the column to remove. - */ - public function testDropColumnWithIndexMatchingTheTableName() - { - $table = new PhinxTable('indexcol', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addColumn('indexcolumn', 'integer') - ->addIndex('indexcolumn') - ->create(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcolumn')); - - $table->removeColumn('indexcol')->update(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcolumn')); - } - - /** - * Tests that removing columns does not accidentally drop indices - * that contain column names that partially match the column to remove. - */ - public function testDropColumnWithIndexColumnPartialMatch() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->addColumn('indexcolumn', 'integer') - ->create(); - - $this->adapter->execute('CREATE INDEX custom_idx ON t (indexcolumn)'); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcolumn')); - - $table->removeColumn('indexcol')->update(); - - $this->assertTrue($this->adapter->hasIndex($table->getName(), 'indexcolumn')); - } - - /** - * Indices with expressions are not being removed. - */ - public function testDropColumnWithExpressionIndex() - { - $table = new PhinxTable('t', [], $this->adapter); - $table - ->addColumn('indexcol', 'integer') - ->create(); - - $this->adapter->execute('CREATE INDEX custom_idx ON t (ABS(indexcol))'); - - $this->assertTrue($this->adapter->hasIndexByName('t', 'custom_idx')); - - $this->expectException(PDOException::class); - $this->expectExceptionMessage('no such column: indexcol'); - - $table->removeColumn('indexcol')->update(); - } - - public static function columnsProvider() - { - return [ - ['column1', 'string', []], - ['column2', 'integer', []], - ['column3', 'biginteger', []], - ['column4', 'text', []], - ['column5', 'float', []], - ['column7', 'datetime', []], - ['column8', 'time', []], - ['column9', 'timestamp', []], - ['column10', 'date', []], - ['column11', 'binary', []], - ['column13', 'string', ['limit' => 10]], - ['column15', 'smallinteger', []], - ['column15', 'integer', []], - ['column23', 'json', []], - ]; - } - - public function testAddIndex() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('email', 'string') - ->save(); - $this->assertFalse($table->hasIndex('email')); - $table->addIndex('email') - ->save(); - $this->assertTrue($table->hasIndex('email')); - } - - public function testAddForeignKey() - { - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn('field1', 'string')->save(); - - $table = new PhinxTable('table', [], $this->adapter); - $table - ->addColumn('ref_table_id', 'integer') - ->addForeignKey(['ref_table_id'], 'ref_table', ['id']) - ->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), ['ref_table_id'])); - } - - public function testHasDatabase() - { - if ($this->config['database'] === ':memory:') { - $this->markTestSkipped('Skipping hasDatabase() when testing in-memory db.'); - } - $this->assertFalse($this->adapter->hasDatabase('fake_database_name')); - $this->assertTrue($this->adapter->hasDatabase($this->config['database'])); - } - - public function testDropDatabase() - { - $this->assertFalse($this->adapter->hasDatabase('phinx_temp_database')); - $this->adapter->createDatabase('phinx_temp_database'); - $this->assertTrue($this->adapter->hasDatabase('phinx_temp_database')); - $this->adapter->dropDatabase('phinx_temp_database'); - } - - public function testAddColumnWithComment() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('column1', 'string', ['comment' => $comment = 'Comments from "column1"']) - ->save(); - - $rows = $this->adapter->fetchAll('select * from sqlite_master where `type` = \'table\''); - - foreach ($rows as $row) { - if ($row['tbl_name'] === 'table1') { - $sql = $row['sql']; - } - } - - $this->assertMatchesRegularExpression('/\/\* Comments from "column1" \*\//', $sql); - } - - public function testAddIndexTwoTablesSameIndex() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('email', 'string') - ->save(); - $table2 = new PhinxTable('table2', [], $this->adapter); - $table2->addColumn('email', 'string') - ->save(); - - $this->assertFalse($table->hasIndex('email')); - $this->assertFalse($table2->hasIndex('email')); - - $table->addIndex('email') - ->save(); - $table2->addIndex('email') - ->save(); - - $this->assertTrue($table->hasIndex('email')); - $this->assertTrue($table2->hasIndex('email')); - } - - public function testBulkInsertData() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('column1', 'string') - ->addColumn('column2', 'integer', ['null' => true]) - ->insert([ - [ - 'column1' => 'value1', - 'column2' => 1, - ], - [ - 'column1' => 'value2', - 'column2' => 2, - ], - ]) - ->insert( - [ - 'column1' => 'value3', - 'column2' => 3, - ], - ) - ->insert( - [ - 'column1' => '\'value4\'', - 'column2' => null, - ], - ) - ->save(); - $rows = $this->adapter->fetchAll('SELECT * FROM table1'); - - $this->assertEquals('value1', $rows[0]['column1']); - $this->assertEquals('value2', $rows[1]['column1']); - $this->assertEquals('value3', $rows[2]['column1']); - $this->assertEquals('\'value4\'', $rows[3]['column1']); - $this->assertEquals(1, $rows[0]['column2']); - $this->assertEquals(2, $rows[1]['column2']); - $this->assertEquals(3, $rows[2]['column2']); - $this->assertNull($rows[3]['column2']); - } - - public function testInsertData() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('column1', 'string') - ->addColumn('column2', 'integer', ['null' => true]) - ->insert([ - [ - 'column1' => 'value1', - 'column2' => 1, - ], - [ - 'column1' => 'value2', - 'column2' => 2, - ], - ]) - ->insert( - [ - 'column1' => 'value3', - 'column2' => 3, - ], - ) - ->insert( - [ - 'column1' => '\'value4\'', - 'column2' => null, - ], - ) - ->save(); - - $rows = $this->adapter->fetchAll('SELECT * FROM table1'); - - $this->assertEquals('value1', $rows[0]['column1']); - $this->assertEquals('value2', $rows[1]['column1']); - $this->assertEquals('value3', $rows[2]['column1']); - $this->assertEquals('\'value4\'', $rows[3]['column1']); - $this->assertEquals(1, $rows[0]['column2']); - $this->assertEquals(2, $rows[1]['column2']); - $this->assertEquals(3, $rows[2]['column2']); - $this->assertNull($rows[3]['column2']); - } - - public function testBulkInsertDataEnum() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('column1', 'string') - ->addColumn('column2', 'string', ['null' => true]) - ->addColumn('column3', 'string', ['default' => 'c']) - ->insert([ - 'column1' => 'a', - ]) - ->save(); - - $rows = $this->adapter->fetchAll('SELECT * FROM table1'); - - $this->assertEquals('a', $rows[0]['column1']); - $this->assertNull($rows[0]['column2']); - $this->assertEquals('c', $rows[0]['column3']); - } - - public function testNullWithoutDefaultValue() - { - $this->markTestSkipped('Skipping for now. See Github Issue #265.'); - - // construct table with default/null combinations - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('aa', 'string', ['null' => true]) // no default value - ->addColumn('bb', 'string', ['null' => false]) // no default value - ->addColumn('cc', 'string', ['null' => true, 'default' => 'some1']) - ->addColumn('dd', 'string', ['null' => false, 'default' => 'some2']) - ->save(); - - // load table info - $columns = $this->adapter->getColumns('table1'); - - $this->assertCount(5, $columns); - - $aa = $columns[1]; - $bb = $columns[2]; - $cc = $columns[3]; - $dd = $columns[4]; - - $this->assertEquals('aa', $aa->getName()); - $this->assertTrue($aa->isNull()); - $this->assertNull($aa->getDefault()); - - $this->assertEquals('bb', $bb->getName()); - $this->assertFalse($bb->isNull()); - $this->assertNull($bb->getDefault()); - - $this->assertEquals('cc', $cc->getName()); - $this->assertTrue($cc->isNull()); - $this->assertEquals('some1', $cc->getDefault()); - - $this->assertEquals('dd', $dd->getName()); - $this->assertFalse($dd->isNull()); - $this->assertEquals('some2', $dd->getDefault()); - } - - public function testDumpCreateTable() - { - $this->adapter->setOptions(['dryrun' => true]); - - $table = new PhinxTable('table1', [], $this->adapter); - - $table->addColumn('column1', 'string', ['null' => false]) - ->addColumn('column2', 'integer') - ->addColumn('column3', 'string', ['default' => 'test']) - ->save(); - - $expectedOutput = <<<'OUTPUT' -CREATE TABLE "table1" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "column1" VARCHAR NOT NULL, "column2" INTEGER, "column3" VARCHAR DEFAULT 'test'); -OUTPUT; - $actualOutput = join("\n", $this->out->messages()); - $this->assertStringContainsString($expectedOutput, $actualOutput, 'Passing the --dry-run option does not dump create table query to the output'); - } - - /** - * Creates the table "table1". - * Then sets phinx to dry run mode and inserts a record. - * Asserts that phinx outputs the insert statement and doesn't insert a record. - */ - public function testDumpInsert() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('string_col', 'string') - ->addColumn('int_col', 'integer') - ->save(); - - $this->adapter->setOptions(['dryrun' => true]); - $this->adapter->insert($table->getTable(), [ - 'string_col' => 'test data', - ]); - - $this->adapter->insert($table->getTable(), [ - 'string_col' => null, - ]); - - $this->adapter->insert($table->getTable(), [ - 'int_col' => 23, - ]); - - $expectedOutput = <<<'OUTPUT' -INSERT INTO "table1" ("string_col") VALUES ('test data'); -INSERT INTO "table1" ("string_col") VALUES (null); -INSERT INTO "table1" ("int_col") VALUES (23); -OUTPUT; - $actualOutput = join("\n", $this->out->messages()); - $actualOutput = preg_replace("/\r\n|\r/", "\n", $actualOutput); // normalize line endings for Windows - $this->assertStringContainsString($expectedOutput, $actualOutput, 'Passing the --dry-run option doesn\'t dump the insert to the output'); - - $countQuery = $this->adapter->query('SELECT COUNT(*) FROM table1'); - $this->assertTrue($countQuery->execute()); - $res = $countQuery->fetchAll('assoc'); - $this->assertEquals(0, $res[0]['COUNT(*)']); - } - - /** - * Creates the table "table1". - * Then sets phinx to dry run mode and inserts some records. - * Asserts that phinx outputs the insert statement and doesn't insert any record. - */ - public function testDumpBulkinsert() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('string_col', 'string') - ->addColumn('int_col', 'integer') - ->save(); - - $this->adapter->setOptions(['dryrun' => true]); - $this->adapter->bulkinsert($table->getTable(), [ - [ - 'string_col' => 'test_data1', - 'int_col' => 23, - ], - [ - 'string_col' => null, - 'int_col' => 42, - ], - ]); - - $expectedOutput = <<<'OUTPUT' -INSERT INTO "table1" ("string_col", "int_col") VALUES ('test_data1', 23), (null, 42); -OUTPUT; - $actualOutput = join("\n", $this->out->messages()); - $this->assertStringContainsString($expectedOutput, $actualOutput, 'Passing the --dry-run option doesn\'t dump the bulkinsert to the output'); - - $countQuery = $this->adapter->query('SELECT COUNT(*) FROM table1'); - $this->assertTrue($countQuery->execute()); - $res = $countQuery->fetchAll('assoc'); - $this->assertEquals(0, $res[0]['COUNT(*)']); - } - - public function testDumpCreateTableAndThenInsert() - { - $this->adapter->setOptions(['dryrun' => true]); - - $table = new PhinxTable('table1', ['id' => false, 'primary_key' => ['column1']], $this->adapter); - - $table->addColumn('column1', 'string', ['null' => false]) - ->addColumn('column2', 'integer') - ->save(); - - $expectedOutput = 'C'; - - $table = new PhinxTable('table1', [], $this->adapter); - $table->insert([ - 'column1' => 'id1', - 'column2' => 1, - ])->save(); - - $expectedOutput = <<<'OUTPUT' -CREATE TABLE "table1" ("column1" VARCHAR NOT NULL, "column2" INTEGER, PRIMARY KEY ("column1")); -INSERT INTO "table1" ("column1", "column2") VALUES ('id1', 1); -OUTPUT; - $actualOutput = join("\n", $this->out->messages()); - $actualOutput = preg_replace("/\r\n|\r/", "\n", $actualOutput); // normalize line endings for Windows - $this->assertStringContainsString($expectedOutput, $actualOutput, 'Passing the --dry-run option does not dump create and then insert table queries to the output'); - } - - /** - * Tests interaction with the query builder - */ - public function testQueryBuilder() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('string_col', 'string') - ->addColumn('int_col', 'integer') - ->save(); - - $builder = $this->adapter->getQueryBuilder(Query::TYPE_INSERT); - $stm = $builder - ->insert(['string_col', 'int_col']) - ->into('table1') - ->values(['string_col' => 'value1', 'int_col' => 1]) - ->values(['string_col' => 'value2', 'int_col' => 2]) - ->execute(); - - $this->assertEquals(2, $stm->rowCount()); - - $builder = $this->adapter->getQueryBuilder(Query::TYPE_SELECT); - $stm = $builder - ->select('*') - ->from('table1') - ->where(['int_col >=' => 2]) - ->execute(); - - $this->assertEquals(0, $stm->rowCount()); - $this->assertEquals( - ['id' => 2, 'string_col' => 'value2', 'int_col' => '2'], - $stm->fetch('assoc'), - ); - - $builder = $this->adapter->getQueryBuilder(Query::TYPE_DELETE); - $stm = $builder - ->delete('table1') - ->where(['int_col <' => 2]) - ->execute(); - - $this->assertEquals(1, $stm->rowCount()); - } - - public function testQueryWithParams() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->addColumn('string_col', 'string') - ->addColumn('int_col', 'integer') - ->save(); - - $this->adapter->insert($table->getTable(), [ - 'string_col' => 'test data', - 'int_col' => 10, - ]); - - $this->adapter->insert($table->getTable(), [ - 'string_col' => null, - ]); - - $this->adapter->insert($table->getTable(), [ - 'int_col' => 23, - ]); - - $countQuery = $this->adapter->query('SELECT COUNT(*) AS c FROM table1 WHERE int_col > ?', [5]); - $res = $countQuery->fetchAll('assoc'); - $this->assertEquals(2, $res[0]['c']); - - $this->adapter->execute('UPDATE table1 SET int_col = ? WHERE int_col IS NULL', [12]); - - $countQuery->execute([1]); - $res = $countQuery->fetchAll('assoc'); - $this->assertEquals(3, $res[0]['c']); - } - - /** - * Tests adding more than one column to a table - * that already exists due to adapters having different add column instructions - */ - public function testAlterTableColumnAdd() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->create(); - - $table->addColumn('string_col', 'string', ['default' => '']); - $table->addColumn('string_col_2', 'string', ['null' => true]); - $table->addColumn('string_col_3', 'string', ['null' => false]); - $table->addTimestamps(); - $table->save(); - - $columns = $this->adapter->getColumns('table1'); - $expected = [ - ['name' => 'id', 'type' => 'integer', 'default' => null, 'null' => false], - ['name' => 'string_col', 'type' => 'string', 'default' => '', 'null' => true], - ['name' => 'string_col_2', 'type' => 'string', 'default' => null, 'null' => true], - ['name' => 'string_col_3', 'type' => 'string', 'default' => null, 'null' => false], - ['name' => 'created_at', 'type' => 'timestamp', 'default' => 'CURRENT_TIMESTAMP', 'null' => false], - ['name' => 'updated_at', 'type' => 'timestamp', 'default' => null, 'null' => true], - ]; - - $this->assertEquals(count($expected), count($columns)); - - $columnCount = count($columns); - for ($i = 0; $i < $columnCount; $i++) { - $this->assertSame($expected[$i]['name'], $columns[$i]->getName(), "Wrong name for {$expected[$i]['name']}"); - $this->assertSame($expected[$i]['type'], $columns[$i]->getType(), "Wrong type for {$expected[$i]['name']}"); - $this->assertSame($expected[$i]['default'], $columns[$i]->getDefault() instanceof Literal ? (string)$columns[$i]->getDefault() : $columns[$i]->getDefault(), "Wrong default for {$expected[$i]['name']}"); - $this->assertSame($expected[$i]['null'], $columns[$i]->getNull(), "Wrong null for {$expected[$i]['name']}"); - } - } - - public function testAlterTableWithConstraints() - { - $table = new PhinxTable('table1', [], $this->adapter); - $table->create(); - - $table2 = new PhinxTable('table2', [], $this->adapter); - $table2->create(); - - $table - ->addColumn('table2_id', 'integer', ['null' => false]) - ->addForeignKey('table2_id', 'table2', 'id', [ - 'delete' => 'SET NULL', - ]); - $table->update(); - - $table->addColumn('column3', 'string', ['default' => null, 'null' => true]); - $table->update(); - - $columns = $this->adapter->getColumns('table1'); - $expected = [ - ['name' => 'id', 'type' => 'integer', 'default' => null, 'null' => false], - ['name' => 'table2_id', 'type' => 'integer', 'default' => null, 'null' => false], - ['name' => 'column3', 'type' => 'string', 'default' => null, 'null' => true], - ]; - - $this->assertEquals(count($expected), count($columns)); - - $columnCount = count($columns); - for ($i = 0; $i < $columnCount; $i++) { - $this->assertSame($expected[$i]['name'], $columns[$i]->getName(), "Wrong name for {$expected[$i]['name']}"); - $this->assertSame($expected[$i]['type'], $columns[$i]->getType(), "Wrong type for {$expected[$i]['name']}"); - $this->assertSame($expected[$i]['default'], $columns[$i]->getDefault() instanceof Literal ? (string)$columns[$i]->getDefault() : $columns[$i]->getDefault(), "Wrong default for {$expected[$i]['name']}"); - $this->assertSame($expected[$i]['null'], $columns[$i]->getNull(), "Wrong null for {$expected[$i]['name']}"); - } - } - - /** - * Tests that operations that trigger implicit table drops will not cause - * a foreign key constraint violation error. - */ - public function testAlterTableDoesNotViolateRestrictedForeignKeyConstraint() - { - $this->adapter->execute('PRAGMA foreign_keys = ON'); - - $articlesTable = new PhinxTable('articles', [], $this->adapter); - $articlesTable - ->insert(['id' => 1]) - ->save(); - - $commentsTable = new PhinxTable('comments', [], $this->adapter); - $commentsTable - ->addColumn('article_id', 'integer') - ->addForeignKey('article_id', 'articles', 'id', [ - 'update' => ForeignKey::RESTRICT, - 'delete' => ForeignKey::RESTRICT, - ]) - ->insert(['id' => 1, 'article_id' => 1]) - ->save(); - - $this->assertTrue($this->adapter->hasForeignKey('comments', ['article_id'])); - - $articlesTable - ->addColumn('new_column', 'integer') - ->update(); - - $articlesTable - ->renameColumn('new_column', 'new_column_renamed') - ->update(); - - $articlesTable - ->changeColumn('new_column_renamed', 'integer', [ - 'default' => 1, - ]) - ->update(); - - $articlesTable - ->removeColumn('new_column_renamed') - ->update(); - - $articlesTable - ->addIndex('id', ['name' => 'ID_IDX']) - ->update(); - - $articlesTable - ->removeIndex('id') - ->update(); - - $articlesTable - ->addForeignKey('id', 'comments', 'id') - ->update(); - - $articlesTable - ->dropForeignKey('id') - ->update(); - - $articlesTable - ->addColumn('id2', 'integer') - ->addIndex('id', ['unique' => true]) - ->changePrimaryKey('id2') - ->update(); - } - - /** - * Tests that foreign key constraint violations introduced around the table - * alteration process (being it implicitly by the process itself or by the user) - * will trigger an error accordingly. - */ - public function testAlterTableDoesViolateForeignKeyConstraintOnTargetTableChange() - { - $articlesTable = new PhinxTable('articles', [], $this->adapter); - $articlesTable - ->insert(['id' => 1]) - ->save(); - - $commentsTable = new PhinxTable('comments', [], $this->adapter); - $commentsTable - ->addColumn('article_id', 'integer') - ->addForeignKey('article_id', 'articles', 'id', [ - 'update' => ForeignKey::RESTRICT, - 'delete' => ForeignKey::RESTRICT, - ]) - ->insert(['id' => 1, 'article_id' => 1]) - ->save(); - - $this->assertTrue($this->adapter->hasForeignKey('comments', ['article_id'])); - - $this->adapter->execute('PRAGMA foreign_keys = OFF'); - $this->adapter->execute('DELETE FROM articles'); - $this->adapter->execute('PRAGMA foreign_keys = ON'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Integrity constraint violation: FOREIGN KEY constraint on `comments` failed.'); - - $articlesTable - ->addColumn('new_column', 'integer') - ->update(); - } - - public function testLiteralSupport() - { - $createQuery = <<<'INPUT' -CREATE TABLE `test` (`real_col` DECIMAL) -INPUT; - $this->adapter->execute($createQuery); - $table = new PhinxTable('test', [], $this->adapter); - $columns = $table->getColumns(); - $this->assertCount(1, $columns); - $this->assertEquals(Literal::from('decimal'), array_pop($columns)->getType()); - } - - public function testHasNamedPrimaryKey() - { - $this->expectException(InvalidArgumentException::class); - - $this->adapter->hasPrimaryKey('t', [], 'named_constraint'); - } - - public function testGetColumnTypes() - { - $columnTypes = $this->adapter->getColumnTypes(); - $expected = [ - SqliteAdapter::PHINX_TYPE_BIG_INTEGER, - SqliteAdapter::PHINX_TYPE_BINARY, - SqliteAdapter::PHINX_TYPE_BLOB, - SqliteAdapter::PHINX_TYPE_BOOLEAN, - SqliteAdapter::PHINX_TYPE_CHAR, - SqliteAdapter::PHINX_TYPE_DATE, - SqliteAdapter::PHINX_TYPE_DATETIME, - SqliteAdapter::PHINX_TYPE_DECIMAL, - SqliteAdapter::PHINX_TYPE_DOUBLE, - SqliteAdapter::PHINX_TYPE_FLOAT, - SqliteAdapter::PHINX_TYPE_INTEGER, - SqliteAdapter::PHINX_TYPE_JSON, - SqliteAdapter::PHINX_TYPE_JSONB, - SqliteAdapter::PHINX_TYPE_SMALL_INTEGER, - SqliteAdapter::PHINX_TYPE_STRING, - SqliteAdapter::PHINX_TYPE_TEXT, - SqliteAdapter::PHINX_TYPE_TIME, - SqliteAdapter::PHINX_TYPE_UUID, - SqliteAdapter::PHINX_TYPE_BINARYUUID, - SqliteAdapter::PHINX_TYPE_TIMESTAMP, - SqliteAdapter::PHINX_TYPE_TINY_INTEGER, - SqliteAdapter::PHINX_TYPE_VARBINARY, - ]; - sort($columnTypes); - sort($expected); - - $this->assertEquals($expected, $columnTypes); - } - - #[DataProvider('provideColumnTypesForValidation')] - public function testIsValidColumnType($phinxType, $exp) - { - $col = (new PhinxColumn())->setType($phinxType); - $this->assertSame($exp, $this->adapter->isValidColumnType($col)); - } - - public static function provideColumnTypesForValidation() - { - return [ - [SqliteAdapter::PHINX_TYPE_BIG_INTEGER, true], - [SqliteAdapter::PHINX_TYPE_BINARY, true], - [SqliteAdapter::PHINX_TYPE_BLOB, true], - [SqliteAdapter::PHINX_TYPE_BOOLEAN, true], - [SqliteAdapter::PHINX_TYPE_CHAR, true], - [SqliteAdapter::PHINX_TYPE_DATE, true], - [SqliteAdapter::PHINX_TYPE_DATETIME, true], - [SqliteAdapter::PHINX_TYPE_DOUBLE, true], - [SqliteAdapter::PHINX_TYPE_FLOAT, true], - [SqliteAdapter::PHINX_TYPE_INTEGER, true], - [SqliteAdapter::PHINX_TYPE_JSON, true], - [SqliteAdapter::PHINX_TYPE_JSONB, true], - [SqliteAdapter::PHINX_TYPE_SMALL_INTEGER, true], - [SqliteAdapter::PHINX_TYPE_STRING, true], - [SqliteAdapter::PHINX_TYPE_TEXT, true], - [SqliteAdapter::PHINX_TYPE_TIME, true], - [SqliteAdapter::PHINX_TYPE_UUID, true], - [SqliteAdapter::PHINX_TYPE_TIMESTAMP, true], - [SqliteAdapter::PHINX_TYPE_VARBINARY, true], - [SqliteAdapter::PHINX_TYPE_BIT, false], - [SqliteAdapter::PHINX_TYPE_CIDR, false], - [SqliteAdapter::PHINX_TYPE_DECIMAL, true], - [SqliteAdapter::PHINX_TYPE_ENUM, false], - [SqliteAdapter::PHINX_TYPE_FILESTREAM, false], - [SqliteAdapter::PHINX_TYPE_GEOMETRY, false], - [SqliteAdapter::PHINX_TYPE_INET, false], - [SqliteAdapter::PHINX_TYPE_INTERVAL, false], - [SqliteAdapter::PHINX_TYPE_LINESTRING, false], - [SqliteAdapter::PHINX_TYPE_MACADDR, false], - [SqliteAdapter::PHINX_TYPE_POINT, false], - [SqliteAdapter::PHINX_TYPE_POLYGON, false], - [SqliteAdapter::PHINX_TYPE_SET, false], - [PhinxLiteral::from('someType'), true], - ['someType', false], - ]; - } - - public function testGetColumns() - { - $conn = $this->adapter->getConnection(); - $conn->execute('create table t(a integer, b text, c char(5), d decimal(12,6), e integer not null, f integer null)'); - $exp = [ - ['name' => 'a', 'type' => 'integer', 'null' => true, 'limit' => null, 'precision' => null, 'scale' => null], - ['name' => 'b', 'type' => 'text', 'null' => true, 'limit' => null, 'precision' => null, 'scale' => null], - ['name' => 'c', 'type' => 'char', 'null' => true, 'limit' => 5, 'precision' => 5, 'scale' => null], - ['name' => 'd', 'type' => 'decimal', 'null' => true, 'limit' => 12, 'precision' => 12, 'scale' => 6], - ['name' => 'e', 'type' => 'integer', 'null' => false, 'limit' => null, 'precision' => null, 'scale' => null], - ['name' => 'f', 'type' => 'integer', 'null' => true, 'limit' => null, 'precision' => null, 'scale' => null], - ]; - $act = $this->adapter->getColumns('t'); - $this->assertCount(count($exp), $act); - foreach ($exp as $index => $data) { - $this->assertInstanceOf(PhinxColumn::class, $act[$index]); - foreach ($data as $key => $value) { - $m = 'get' . ucfirst($key); - $this->assertEquals($value, $act[$index]->$m(), "Parameter '$key' of column at index $index did not match expectations."); - } - } - } - - public function testForeignKeyReferenceCorrectAfterRenameColumn() - { - $refTableColumnId = 'ref_table_id'; - $refTableColumnToRename = 'columnToRename'; - $refTableRenamedColumn = 'renamedColumn'; - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn($refTableColumnToRename, 'string')->save(); - - $table = new PhinxTable('table', [], $this->adapter); - $table->addColumn($refTableColumnId, 'integer'); - $table->addForeignKey($refTableColumnId, $refTable->getName(), 'id'); - $table->save(); - - $refTable->renameColumn($refTableColumnToRename, $refTableRenamedColumn)->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), [$refTableColumnId])); - $this->assertFalse($this->adapter->hasTable("tmp_{$refTable->getName()}")); - $this->assertTrue($this->adapter->hasColumn($refTable->getName(), $refTableRenamedColumn)); - - $rows = $this->adapter->fetchAll('select * from sqlite_master where `type` = \'table\''); - foreach ($rows as $row) { - if ($row['tbl_name'] === $table->getName()) { - $sql = $row['sql']; - } - } - $this->assertStringContainsString("REFERENCES \"{$refTable->getName()}\" (\"id\")", $sql); - } - - public function testForeignKeyReferenceCorrectAfterChangeColumn() - { - $refTableColumnId = 'ref_table_id'; - $refTableColumnToChange = 'columnToChange'; - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn($refTableColumnToChange, 'string')->save(); - - $table = new PhinxTable('table', [], $this->adapter); - $table->addColumn($refTableColumnId, 'integer'); - $table->addForeignKey($refTableColumnId, $refTable->getName(), 'id'); - $table->save(); - - $refTable->changeColumn($refTableColumnToChange, 'text')->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), [$refTableColumnId])); - $this->assertFalse($this->adapter->hasTable("tmp_{$refTable->getName()}")); - $this->assertEquals('text', $this->adapter->getColumns($refTable->getName())[1]->getType()); - - $rows = $this->adapter->fetchAll('select * from sqlite_master where `type` = \'table\''); - foreach ($rows as $row) { - if ($row['tbl_name'] === $table->getName()) { - $sql = $row['sql']; - } - } - $this->assertStringContainsString("REFERENCES \"{$refTable->getName()}\" (\"id\")", $sql); - } - - public function testForeignKeyReferenceCorrectAfterRemoveColumn() - { - $refTableColumnId = 'ref_table_id'; - $refTableColumnToRemove = 'columnToRemove'; - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn($refTableColumnToRemove, 'string')->save(); - - $table = new PhinxTable('table', [], $this->adapter); - $table->addColumn($refTableColumnId, 'integer'); - $table->addForeignKey($refTableColumnId, $refTable->getName(), 'id'); - $table->save(); - - $refTable->removeColumn($refTableColumnToRemove)->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), [$refTableColumnId])); - $this->assertFalse($this->adapter->hasTable("tmp_{$refTable->getName()}")); - $this->assertFalse($this->adapter->hasColumn($refTable->getName(), $refTableColumnToRemove)); - - $rows = $this->adapter->fetchAll('select * from sqlite_master where "type" = \'table\''); - foreach ($rows as $row) { - if ($row['tbl_name'] === $table->getName()) { - $sql = $row['sql']; - } - } - $this->assertStringContainsString("REFERENCES \"{$refTable->getName()}\" (\"id\")", $sql); - } - - public function testForeignKeyReferenceCorrectAfterChangePrimaryKey() - { - $refTableColumnAdditionalId = 'additional_id'; - $refTableColumnId = 'ref_table_id'; - $refTable = new PhinxTable('ref_table', [], $this->adapter); - $refTable->addColumn($refTableColumnAdditionalId, 'integer')->save(); - - $table = new PhinxTable('table', [], $this->adapter); - $table->addColumn($refTableColumnId, 'integer'); - $table->addForeignKey($refTableColumnId, $refTable->getName(), 'id'); - $table->save(); - - $refTable - ->addIndex('id', ['unique' => true]) - ->changePrimaryKey($refTableColumnAdditionalId) - ->save(); - - $this->assertTrue($this->adapter->hasForeignKey($table->getName(), [$refTableColumnId])); - $this->assertFalse($this->adapter->hasTable("tmp_{$refTable->getName()}")); - $this->assertTrue($this->adapter->getColumns($refTable->getName())[1]->getIdentity()); - - $rows = $this->adapter->fetchAll('select * from sqlite_master where `type` = \'table\''); - foreach ($rows as $row) { - if ($row['tbl_name'] === $table->getName()) { - $sql = $row['sql']; - } - } - $this->assertStringContainsString("REFERENCES \"{$refTable->getName()}\" (\"id\")", $sql); - } -} diff --git a/tests/TestCase/Migration/EnvironmentTest.php b/tests/TestCase/Migration/EnvironmentTest.php index 2a3aabd3..1694688a 100644 --- a/tests/TestCase/Migration/EnvironmentTest.php +++ b/tests/TestCase/Migration/EnvironmentTest.php @@ -5,14 +5,14 @@ use Cake\Console\ConsoleIo; use Cake\Datasource\ConnectionManager; +use Migrations\BaseMigration; +use Migrations\BaseSeed; use Migrations\Db\Adapter\AbstractAdapter; use Migrations\Db\Adapter\AdapterWrapper; use Migrations\Migration\Environment; +use Migrations\MigrationInterface; use Migrations\Shim\MigrationAdapter; use Migrations\Shim\SeedAdapter; -use Phinx\Migration\AbstractMigration; -use Phinx\Migration\MigrationInterface; -use Phinx\Seed\AbstractSeed; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -123,7 +123,7 @@ public function testExecutingAMigrationUp() $this->environment->setAdapter($adapterStub); // up - $upMigration = new class ('mockenv', 20110301080000) extends AbstractMigration { + $upMigration = new class ('mockenv', 20110301080000) extends BaseMigration { public bool $executed = false; public function up(): void { @@ -149,7 +149,7 @@ public function testExecutingAMigrationDown() $this->environment->setAdapter($adapterStub); // down - $downMigration = new class ('mockenv', 20110301080000) extends AbstractMigration { + $downMigration = new class ('mockenv', 20110301080000) extends BaseMigration { public bool $executed = false; public function down(): void { @@ -181,7 +181,7 @@ public function testExecutingAMigrationWithTransactions() $this->environment->setAdapter($adapterStub); // migrate - $migration = new class ('mockenv', 20110301080000) extends AbstractMigration { + $migration = new class ('mockenv', 20110301080000) extends BaseMigration { public bool $executed = false; public function up(): void { @@ -213,7 +213,7 @@ public function testExecutingAMigrationWithUseTransactions() $this->environment->setAdapter($adapterStub); // migrate - $migration = new class ('mockenv', 20110301080000) extends AbstractMigration { + $migration = new class ('mockenv', 20110301080000) extends BaseMigration { public bool $executed = false; public function useTransactions(): bool @@ -245,7 +245,7 @@ public function testExecutingAChangeMigrationUp() $this->environment->setAdapter($adapterStub); // migration - $migration = new class ('mockenv', 20130301080000) extends AbstractMigration { + $migration = new class ('mockenv', 20130301080000) extends BaseMigration { public bool $executed = false; public function change(): void { @@ -271,7 +271,7 @@ public function testExecutingAChangeMigrationDown() $this->environment->setAdapter($adapterStub); // migration - $migration = new class ('mockenv', 20130301080000) extends AbstractMigration { + $migration = new class ('mockenv', 20130301080000) extends BaseMigration { public bool $executed = false; public function change(): void { @@ -297,7 +297,7 @@ public function testExecutingAFakeMigration() $this->environment->setAdapter($adapterStub); // migration - $migration = new class ('mockenv', 20130301080000) extends AbstractMigration { + $migration = new class ('mockenv', 20130301080000) extends BaseMigration { public bool $executed = false; public function change(): void { @@ -331,7 +331,7 @@ public function testExecuteMigrationCallsInit() $this->environment->setAdapter($adapterStub); // up - $upMigration = new class ('mockenv', 20110301080000) extends AbstractMigration { + $upMigration = new class ('mockenv', 20110301080000) extends BaseMigration { public bool $initExecuted = false; public bool $upExecuted = false; @@ -360,7 +360,7 @@ public function testExecuteSeedInit() $this->environment->setAdapter($adapterStub); - $seed = new class ('mockenv', 20110301080000) extends AbstractSeed { + $seed = new class ('mockenv', 20110301080000) extends BaseSeed { public bool $initExecuted = false; public bool $runExecuted = false; diff --git a/tests/TestCase/Migration/ManagerTest.php b/tests/TestCase/Migration/ManagerTest.php index 26035d24..42d806c5 100644 --- a/tests/TestCase/Migration/ManagerTest.php +++ b/tests/TestCase/Migration/ManagerTest.php @@ -13,7 +13,6 @@ use Migrations\Db\Adapter\AdapterInterface; use Migrations\Migration\Environment; use Migrations\Migration\Manager; -use Phinx\Console\Command\AbstractCommand; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use ReflectionClass; @@ -22,7 +21,7 @@ class ManagerTest extends TestCase { /** - * @var \Phinx\Config\Config + * @var \Migrations\Config\Config */ protected $config; @@ -241,7 +240,7 @@ public function testPrintStatusMethodJsonFormat(): void ], ); $this->manager->setEnvironment($envStub); - $return = $this->manager->printStatus(AbstractCommand::FORMAT_JSON); + $return = $this->manager->printStatus('json'); $expected = [ [ 'status' => 'up', diff --git a/tests/TestCase/MigrationsTest.php b/tests/TestCase/MigrationsTest.php index 91da82ba..4e67c9b1 100644 --- a/tests/TestCase/MigrationsTest.php +++ b/tests/TestCase/MigrationsTest.php @@ -107,14 +107,6 @@ public function tearDown(): void } } - public static function backendProvider(): array - { - return [ - ['builtin'], - ['phinx'], - ]; - } - /** * Tests the status method * @@ -1022,21 +1014,6 @@ public function testSeedWrongSeed() $this->migrations->seed(['source' => 'AltSeeds', 'seed' => 'DerpSeed']); } - /** - * Tests migrating the baked snapshots with builtin backend - * - * @param string $basePath Snapshot file path - * @param string $filename Snapshot file name - * @param array $flags Feature flags - * @return void - */ - #[DataProvider('snapshotMigrationsProvider')] - public function testMigrateSnapshotsBuiltin(string $basePath, string $filename, array $flags = []): void - { - Configure::write('Migrations.backend', 'builtin'); - $this->runMigrateSnapshots($basePath, $filename, $flags); - } - /** * Tests migrating the baked snapshots * @@ -1046,12 +1023,7 @@ public function testMigrateSnapshotsBuiltin(string $basePath, string $filename, * @return void */ #[DataProvider('snapshotMigrationsProvider')] - public function testMigrateSnapshotsPhinx(string $basePath, string $filename, array $flags = []): void - { - $this->runMigrateSnapshots($basePath, $filename, $flags); - } - - protected function runMigrateSnapshots(string $basePath, string $filename, array $flags): void + public function testMigrateSnapshotsBuiltin(string $basePath, string $filename, array $flags = []): void { if ($this->Connection->getDriver() instanceof Sqlserver) { // TODO once migrations is using the inlined sqlserver adapter, this skip should @@ -1083,7 +1055,7 @@ protected function runMigrateSnapshots(string $basePath, string $filename, array // change class name to avoid conflict with other classes // to avoid 'Fatal error: Cannot declare class Test...., because the name is already in use' $content = file_get_contents($destination . $copiedFileName); - $patterns = [' extends AbstractMigration', ' extends BaseMigration']; + $patterns = [' extends BaseMigration', ' extends BaseMigration']; foreach ($patterns as $pattern) { $content = str_replace($pattern, 'NewSuffix' . $pattern, $content); } diff --git a/tests/TestCase/Util/_files/migrations/20120111235330_test_migration.php b/tests/TestCase/Util/_files/migrations/20120111235330_test_migration.php index 27b10239..fd8abe27 100644 --- a/tests/TestCase/Util/_files/migrations/20120111235330_test_migration.php +++ b/tests/TestCase/Util/_files/migrations/20120111235330_test_migration.php @@ -1,9 +1,9 @@ Date: Mon, 4 Aug 2025 13:28:56 +0200 Subject: [PATCH 2/8] Fix tests. --- src/Db/Action/AddForeignKey.php | 6 ++++++ .../Command/BakeMigrationCommandTest.php | 2 +- tests/TestCase/Command/EntryCommandTest.php | 1 - tests/TestCase/Command/MigrateCommandTest.php | 2 +- tests/TestCase/Command/SeedCommandTest.php | 2 +- tests/TestCase/Migration/EnvironmentTest.php | 19 ++++++++++--------- tests/TestCase/MigrationsTest.php | 4 ++-- .../20250307183600_change_test_table.php | 1 - tests/test_app/config/Seeds/StoresSeed.php | 4 ++-- 9 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/Db/Action/AddForeignKey.php b/src/Db/Action/AddForeignKey.php index b8f682b5..aac08c87 100644 --- a/src/Db/Action/AddForeignKey.php +++ b/src/Db/Action/AddForeignKey.php @@ -54,6 +54,12 @@ public static function build(Table $table, string|array $columns, Table|string $ $referencedTable = new Table($referencedTable); } + // Shimming old 4.x + if (isset($options['constraint'])) { + $options['name'] = $options['constraint']; + unset($options['constraint']); + } + $fk = new ForeignKey(); $fk->setReferencedTable($referencedTable) ->setColumns($columns) diff --git a/tests/TestCase/Command/BakeMigrationCommandTest.php b/tests/TestCase/Command/BakeMigrationCommandTest.php index 6b240425..1cd994f0 100644 --- a/tests/TestCase/Command/BakeMigrationCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationCommandTest.php @@ -146,7 +146,7 @@ public function testCreateWithReservedKeyword() $this->assertOutputRegExp('/Wrote.*?PrefixNew\.php/'); } - public function testCreateBuiltinAlias() + public function testCreateBuiltInAlias() { $this->exec('migrations create CreateUsers --connection test'); $this->assertExitCode(BaseCommand::CODE_SUCCESS); diff --git a/tests/TestCase/Command/EntryCommandTest.php b/tests/TestCase/Command/EntryCommandTest.php index e3607137..aa12d35f 100644 --- a/tests/TestCase/Command/EntryCommandTest.php +++ b/tests/TestCase/Command/EntryCommandTest.php @@ -41,7 +41,6 @@ public function testExecuteHelp() $this->exec('migrations --help'); $this->assertExitSuccess(); - $this->assertOutputContains('Using builtin backend'); $this->assertOutputContains('Available Commands'); $this->assertOutputContains('migrations migrate'); $this->assertOutputContains('migrations status'); diff --git a/tests/TestCase/Command/MigrateCommandTest.php b/tests/TestCase/Command/MigrateCommandTest.php index b66d5644..63f82dea 100644 --- a/tests/TestCase/Command/MigrateCommandTest.php +++ b/tests/TestCase/Command/MigrateCommandTest.php @@ -102,7 +102,7 @@ public function testMigrateSourceDefault(): void } /** - * Integration test for BaseMigration with built-in backend. + * Integration test for BaseMigration. */ public function testMigrateBaseMigration(): void { diff --git a/tests/TestCase/Command/SeedCommandTest.php b/tests/TestCase/Command/SeedCommandTest.php index 812c8c24..570d67c7 100644 --- a/tests/TestCase/Command/SeedCommandTest.php +++ b/tests/TestCase/Command/SeedCommandTest.php @@ -213,7 +213,7 @@ public function testSeederWithTimestampFields(): void $store = $result[0]; $this->assertEquals('foo_with_date', $store['name']); $this->assertNotEmpty($store['created']); - $this->assertNotEmpty($store['modified']); + $this->assertNotEmpty($store['updated']); } public function testSeederWithDateTimeFields(): void diff --git a/tests/TestCase/Migration/EnvironmentTest.php b/tests/TestCase/Migration/EnvironmentTest.php index 1694688a..9db92cdb 100644 --- a/tests/TestCase/Migration/EnvironmentTest.php +++ b/tests/TestCase/Migration/EnvironmentTest.php @@ -123,7 +123,7 @@ public function testExecutingAMigrationUp() $this->environment->setAdapter($adapterStub); // up - $upMigration = new class ('mockenv', 20110301080000) extends BaseMigration { + $upMigration = new class (20110301080000) extends BaseMigration { public bool $executed = false; public function up(): void { @@ -149,7 +149,7 @@ public function testExecutingAMigrationDown() $this->environment->setAdapter($adapterStub); // down - $downMigration = new class ('mockenv', 20110301080000) extends BaseMigration { + $downMigration = new class (20110301080000) extends BaseMigration { public bool $executed = false; public function down(): void { @@ -181,7 +181,7 @@ public function testExecutingAMigrationWithTransactions() $this->environment->setAdapter($adapterStub); // migrate - $migration = new class ('mockenv', 20110301080000) extends BaseMigration { + $migration = new class (20110301080000) extends BaseMigration { public bool $executed = false; public function up(): void { @@ -213,7 +213,7 @@ public function testExecutingAMigrationWithUseTransactions() $this->environment->setAdapter($adapterStub); // migrate - $migration = new class ('mockenv', 20110301080000) extends BaseMigration { + $migration = new class (20110301080000) extends BaseMigration { public bool $executed = false; public function useTransactions(): bool @@ -245,7 +245,7 @@ public function testExecutingAChangeMigrationUp() $this->environment->setAdapter($adapterStub); // migration - $migration = new class ('mockenv', 20130301080000) extends BaseMigration { + $migration = new class (20130301080000) extends BaseMigration { public bool $executed = false; public function change(): void { @@ -271,7 +271,7 @@ public function testExecutingAChangeMigrationDown() $this->environment->setAdapter($adapterStub); // migration - $migration = new class ('mockenv', 20130301080000) extends BaseMigration { + $migration = new class (20130301080000) extends BaseMigration { public bool $executed = false; public function change(): void { @@ -279,6 +279,7 @@ public function change(): void } }; + //FIXME $migrationWrapper = new MigrationAdapter($migration, $migration->getVersion()); $this->environment->executeMigration($migrationWrapper, MigrationInterface::DOWN); $this->assertTrue($migration->executed); @@ -297,7 +298,7 @@ public function testExecutingAFakeMigration() $this->environment->setAdapter($adapterStub); // migration - $migration = new class ('mockenv', 20130301080000) extends BaseMigration { + $migration = new class (20130301080000) extends BaseMigration { public bool $executed = false; public function change(): void { @@ -331,7 +332,7 @@ public function testExecuteMigrationCallsInit() $this->environment->setAdapter($adapterStub); // up - $upMigration = new class ('mockenv', 20110301080000) extends BaseMigration { + $upMigration = new class (20110301080000) extends BaseMigration { public bool $initExecuted = false; public bool $upExecuted = false; @@ -360,7 +361,7 @@ public function testExecuteSeedInit() $this->environment->setAdapter($adapterStub); - $seed = new class ('mockenv', 20110301080000) extends BaseSeed { + $seed = new class (20110301080000) extends BaseSeed { public bool $initExecuted = false; public bool $runExecuted = false; diff --git a/tests/TestCase/MigrationsTest.php b/tests/TestCase/MigrationsTest.php index 4e67c9b1..a4f64dd7 100644 --- a/tests/TestCase/MigrationsTest.php +++ b/tests/TestCase/MigrationsTest.php @@ -201,7 +201,7 @@ public function testMigrateAndRollback() $storesTable = $this->getTableLocator()->get('Stores', ['connection' => $this->Connection]); $columns = $storesTable->getSchema()->columns(); - $expected = ['id', 'name', 'created', 'modified']; + $expected = ['id', 'name', 'created', 'updated']; $this->assertEquals($expected, $columns); $createdColumn = $storesTable->getSchema()->getColumn('created'); $expected = 'CURRENT_TIMESTAMP'; @@ -1023,7 +1023,7 @@ public function testSeedWrongSeed() * @return void */ #[DataProvider('snapshotMigrationsProvider')] - public function testMigrateSnapshotsBuiltin(string $basePath, string $filename, array $flags = []): void + public function testMigrateSnapshots(string $basePath, string $filename, array $flags = []): void { if ($this->Connection->getDriver() instanceof Sqlserver) { // TODO once migrations is using the inlined sqlserver adapter, this skip should diff --git a/tests/test_app/config/MigrationsRollback/20250307183600_change_test_table.php b/tests/test_app/config/MigrationsRollback/20250307183600_change_test_table.php index e4199213..251ca563 100644 --- a/tests/test_app/config/MigrationsRollback/20250307183600_change_test_table.php +++ b/tests/test_app/config/MigrationsRollback/20250307183600_change_test_table.php @@ -2,7 +2,6 @@ use Migrations\BaseMigration; -// This NEEDs to be the new BaseMigration class to check if rollbacks work correctly with the new builtin backend class ChangeTestTable extends BaseMigration { public function change(): void diff --git a/tests/test_app/config/Seeds/StoresSeed.php b/tests/test_app/config/Seeds/StoresSeed.php index ddd0877a..961bd42e 100644 --- a/tests/test_app/config/Seeds/StoresSeed.php +++ b/tests/test_app/config/Seeds/StoresSeed.php @@ -18,12 +18,12 @@ public function run(): void [ 'name' => 'foo', 'created' => new Date(), - 'modified' => new Date(), + 'updated' => new Date(), ], [ 'name' => 'foo_with_date', 'created' => new DateTime(), - 'modified' => new DateTime(), + 'updated' => new DateTime(), ], ]; From c09fded520018b5fb3fbc869b9ef1f10a0da962c Mon Sep 17 00:00:00 2001 From: mscherer Date: Mon, 4 Aug 2025 14:07:52 +0200 Subject: [PATCH 3/8] Fix tests. --- tests/TestCase/Db/Table/TableTest.php | 41 --------------------------- 1 file changed, 41 deletions(-) diff --git a/tests/TestCase/Db/Table/TableTest.php b/tests/TestCase/Db/Table/TableTest.php index 32461a44..82a0b3b9 100644 --- a/tests/TestCase/Db/Table/TableTest.php +++ b/tests/TestCase/Db/Table/TableTest.php @@ -158,47 +158,6 @@ public function testAddForeignKeyWithObject(): void $this->assertSame($key->getName(), 'fk_user_id'); } - public function testAddForeignKeyWithNamePositionalParameters(): void - { - $adapter = new MysqlAdapter([]); - $table = new Table('ntable', [], $adapter); - $table->addForeignKeyWithName('fk_user_id', 'user_id', 'users', 'id', [ - 'delete' => 'CASCADE', - 'update' => 'CASCADE', - ]); - - $actions = $this->getPendingActions($table); - $this->assertInstanceOf(AddForeignKey::class, $actions[0]); - $key = $actions[0]->getForeignKey(); - $this->assertSame($key->getReferencedTable()->getName(), 'users'); - $this->assertSame($key->getReferencedColumns(), ['id']); - $this->assertSame($key->getColumns(), ['user_id']); - $this->assertSame($key->getName(), 'fk_user_id'); - } - - public function testAddForeignKeyWithNameObject(): void - { - $adapter = new MysqlAdapter([]); - $table = new Table('ntable', [], $adapter); - $key = new ForeignKey(); - $table->addForeignKeyWithName( - $key->setColumns('user_id') - ->setReferencedTable('users') - ->setReferencedColumns(['id']) - ->setOnDelete('CASCADE') - ->setOnUpdate('CASCADE') - ->setName('fk_user_id'), - ); - - $actions = $this->getPendingActions($table); - $this->assertInstanceOf(AddForeignKey::class, $actions[0]); - $key = $actions[0]->getForeignKey(); - $this->assertSame($key->getReferencedTable()->getName(), 'users'); - $this->assertSame($key->getReferencedColumns(), ['id']); - $this->assertSame($key->getColumns(), ['user_id']); - $this->assertSame($key->getName(), 'fk_user_id'); - } - /** * @param AdapterInterface $adapter * @param string|null $createdAtColumnName From 5cf9ad425678b1486a675b95df03815a908608b8 Mon Sep 17 00:00:00 2001 From: mscherer Date: Tue, 5 Aug 2025 00:19:45 +0200 Subject: [PATCH 4/8] Fix URL. --- README.md | 2 +- docs/en/writing-migrations.rst | 2 +- src/Command/BakeMigrationCommand.php | 4 +--- src/Command/BakeMigrationDiffCommand.php | 1 - src/Command/BakeMigrationSnapshotCommand.php | 1 - src/Command/BakeSeedCommand.php | 1 - templates/bake/Seed/seed.twig | 2 +- templates/bake/config/diff.twig | 4 ++-- templates/bake/config/skeleton.twig | 2 +- templates/bake/config/snapshot.twig | 4 ++-- tests/comparisons/Create/TestCreateChange.php | 2 +- .../comparisons/Diff/addRemove/the_diff_add_remove_mysql.php | 4 ++-- .../comparisons/Diff/addRemove/the_diff_add_remove_pgsql.php | 4 ++-- tests/comparisons/Diff/default/the_diff_default_mysql.php | 4 ++-- tests/comparisons/Diff/default/the_diff_default_pgsql.php | 4 ++-- tests/comparisons/Diff/simple/the_diff_simple_mysql.php | 4 ++-- tests/comparisons/Diff/simple/the_diff_simple_pgsql.php | 4 ++-- ...diff_with_auto_id_compatible_signed_primary_keys_mysql.php | 4 ++-- ...ff_with_auto_id_incompatible_signed_primary_keys_mysql.php | 4 ++-- ..._with_auto_id_incompatible_unsigned_primary_keys_mysql.php | 4 ++-- .../Migration/pgsql/test_snapshot_auto_id_disabled_pgsql.php | 4 ++-- .../Migration/pgsql/test_snapshot_not_empty_pgsql.php | 4 ++-- .../Migration/pgsql/test_snapshot_plugin_blog_pgsql.php | 4 ++-- .../sqlite/test_snapshot_auto_id_disabled_sqlite.php | 4 ++-- .../Migration/sqlite/test_snapshot_not_empty_sqlite.php | 4 ++-- .../Migration/sqlite/test_snapshot_plugin_blog_sqlite.php | 4 ++-- .../sqlserver/test_snapshot_auto_id_disabled_sqlserver.php | 4 ++-- .../Migration/sqlserver/test_snapshot_not_empty_sqlserver.php | 4 ++-- .../sqlserver/test_snapshot_plugin_blog_sqlserver.php | 4 ++-- tests/comparisons/Migration/testCreate.php | 2 +- tests/comparisons/Migration/testCreateDatetime.php | 2 +- tests/comparisons/Migration/testCreateDropMigration.php | 2 +- tests/comparisons/Migration/testCreateFieldLength.php | 2 +- tests/comparisons/Migration/testCreatePhinx.php | 2 +- tests/comparisons/Migration/testCreatePrimaryKey.php | 2 +- tests/comparisons/Migration/testCreatePrimaryKeyUuid.php | 2 +- tests/comparisons/Migration/testNoContents.php | 2 +- .../comparisons/Migration/test_snapshot_auto_id_disabled.php | 4 ++-- tests/comparisons/Migration/test_snapshot_not_empty.php | 4 ++-- tests/comparisons/Migration/test_snapshot_plugin_blog.php | 4 ++-- ...t_snapshot_with_auto_id_compatible_signed_primary_keys.php | 4 ++-- ...snapshot_with_auto_id_incompatible_signed_primary_keys.php | 4 ++-- ...apshot_with_auto_id_incompatible_unsigned_primary_keys.php | 4 ++-- .../Migration/test_snapshot_with_non_default_collation.php | 4 ++-- tests/comparisons/Seeds/pgsql/testWithData.php | 2 +- tests/comparisons/Seeds/pgsql/testWithDataAndLimit.php | 2 +- tests/comparisons/Seeds/php81/testWithData.php | 2 +- tests/comparisons/Seeds/php81/testWithDataAndLimit.php | 2 +- tests/comparisons/Seeds/sqlserver/testWithData.php | 2 +- tests/comparisons/Seeds/sqlserver/testWithDataAndLimit.php | 2 +- tests/comparisons/Seeds/testBasicBaking.php | 2 +- tests/comparisons/Seeds/testBasicBakingPhinx.php | 2 +- tests/comparisons/Seeds/testPrettifyArray.php | 2 +- tests/comparisons/Seeds/testWithData.php | 2 +- tests/comparisons/Seeds/testWithDataAndFields.php | 2 +- tests/comparisons/Seeds/testWithDataAndLimit.php | 2 +- .../Plugin/TestBlog/config/CallSeeds/PluginLettersSeed.php | 2 +- .../Plugin/TestBlog/config/CallSeeds/PluginSubLettersSeed.php | 2 +- tests/test_app/config/AltSeeds/AnotherNumbersSeed.php | 2 +- tests/test_app/config/AltSeeds/NumbersAltSeed.php | 2 +- tests/test_app/config/BaseSeeds/MigrationSeedNumbers.php | 2 +- tests/test_app/config/CallSeeds/DatabaseSeed.php | 2 +- tests/test_app/config/CallSeeds/LettersSeed.php | 2 +- tests/test_app/config/CallSeeds/NumbersCallSeed.php | 2 +- .../20160128183623_AlterArticlesDefault.php | 2 +- .../20160128183652_AlterArticlesSlugDefault.php | 2 +- .../20160128183952_CreateUsersDefault.php | 2 +- .../20160128184109_AlterArticlesFkDefault.php | 2 +- .../20160414193900_CreateTagsDefault.php | 2 +- .../20160128183623_AlterArticlesSimple.php | 2 +- ...20180516025208_create_test_index_limit_specifier_table.php | 2 +- .../20190928220334_add_column_index_fk.php | 2 +- 72 files changed, 96 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 4faf49d8..e7977860 100644 --- a/README.md +++ b/README.md @@ -35,4 +35,4 @@ bin/cake plugin load Migrations ## Documentation -Full documentation of the plugin can be found on the [CakePHP Cookbook](https://book.cakephp.org/migrations/4/). +Full documentation of the plugin can be found on the [CakePHP Cookbook](https://book.cakephp.org/migrations/5/). diff --git a/docs/en/writing-migrations.rst b/docs/en/writing-migrations.rst index e0e71a15..e1890a29 100644 --- a/docs/en/writing-migrations.rst +++ b/docs/en/writing-migrations.rst @@ -37,7 +37,7 @@ Bake will automatically creates a skeleton migration file with a single method: * Write your reversible migrations using this method. * * More information on writing migrations is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * Remember to call "create()" or "update()" and NOT "save()" when working * with the Table class. diff --git a/src/Command/BakeMigrationCommand.php b/src/Command/BakeMigrationCommand.php index 81bba92a..0c3cf082 100644 --- a/src/Command/BakeMigrationCommand.php +++ b/src/Command/BakeMigrationCommand.php @@ -87,7 +87,7 @@ public function templateData(Arguments $arguments): array $action = $this->detectAction($className); if (!$action && count($fields)) { - $this->io->abort('When applying fields the migration name should start with one of the following prefixes: `Create`, `Drop`, `Add`, `Remove`, `Alter`. See: https://book.cakephp.org/migrations/4/en/index.html#migrations-file-name'); + $this->io->abort('When applying fields the migration name should start with one of the following prefixes: `Create`, `Drop`, `Add`, `Remove`, `Alter`. See: https://book.cakephp.org/migrations/5/en/index.html#migrations-file-name'); } if (!$action) { @@ -98,7 +98,6 @@ public function templateData(Arguments $arguments): array 'tables' => [], 'action' => null, 'name' => $className, - 'backend' => 'builtin', ]; } @@ -120,7 +119,6 @@ public function templateData(Arguments $arguments): array 'primaryKey' => $primaryKey, ], 'name' => $className, - 'backend' => 'builtin', ]; } diff --git a/src/Command/BakeMigrationDiffCommand.php b/src/Command/BakeMigrationDiffCommand.php index 8071ea91..41767602 100644 --- a/src/Command/BakeMigrationDiffCommand.php +++ b/src/Command/BakeMigrationDiffCommand.php @@ -196,7 +196,6 @@ public function templateData(Arguments $arguments): array 'data' => $this->templateData, 'dumpSchema' => $this->dumpSchema, 'currentSchema' => $this->currentSchema, - 'backend' => 'builtin', ]; } diff --git a/src/Command/BakeMigrationSnapshotCommand.php b/src/Command/BakeMigrationSnapshotCommand.php index 9f88973e..c05b0305 100644 --- a/src/Command/BakeMigrationSnapshotCommand.php +++ b/src/Command/BakeMigrationSnapshotCommand.php @@ -115,7 +115,6 @@ public function templateData(Arguments $arguments): array 'action' => 'create_table', 'name' => $this->_name, 'autoId' => $autoId, - 'backend' => 'builtin', ]; } diff --git a/src/Command/BakeSeedCommand.php b/src/Command/BakeSeedCommand.php index c3bec484..f210f756 100644 --- a/src/Command/BakeSeedCommand.php +++ b/src/Command/BakeSeedCommand.php @@ -142,7 +142,6 @@ public function templateData(Arguments $arguments): array 'namespace' => $namespace, 'records' => $records, 'table' => $table, - 'backend' => 'builtin', ]; } diff --git a/templates/bake/Seed/seed.twig b/templates/bake/Seed/seed.twig index f1fc6357..17b079d4 100644 --- a/templates/bake/Seed/seed.twig +++ b/templates/bake/Seed/seed.twig @@ -29,7 +29,7 @@ class {{ name }}Seed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/templates/bake/config/diff.twig b/templates/bake/config/diff.twig index 3c8d0040..a9719757 100644 --- a/templates/bake/config/diff.twig +++ b/templates/bake/config/diff.twig @@ -31,7 +31,7 @@ class {{ name }} extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -117,7 +117,7 @@ not empty %} * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/templates/bake/config/skeleton.twig b/templates/bake/config/skeleton.twig index 3f04d3a7..7141c828 100644 --- a/templates/bake/config/skeleton.twig +++ b/templates/bake/config/skeleton.twig @@ -32,7 +32,7 @@ class {{ name }} extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/templates/bake/config/snapshot.twig b/templates/bake/config/snapshot.twig index 53d2da23..05b55fec 100644 --- a/templates/bake/config/snapshot.twig +++ b/templates/bake/config/snapshot.twig @@ -34,7 +34,7 @@ class {{ name }} extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -50,7 +50,7 @@ class {{ name }} extends BaseMigration * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Create/TestCreateChange.php b/tests/comparisons/Create/TestCreateChange.php index 58eae8a0..071aa889 100644 --- a/tests/comparisons/Create/TestCreateChange.php +++ b/tests/comparisons/Create/TestCreateChange.php @@ -9,7 +9,7 @@ class TestCreateChange extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Diff/addRemove/the_diff_add_remove_mysql.php b/tests/comparisons/Diff/addRemove/the_diff_add_remove_mysql.php index daeceb7d..4220fb04 100644 --- a/tests/comparisons/Diff/addRemove/the_diff_add_remove_mysql.php +++ b/tests/comparisons/Diff/addRemove/the_diff_add_remove_mysql.php @@ -9,7 +9,7 @@ class TheDiffAddRemoveMysql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -41,7 +41,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/addRemove/the_diff_add_remove_pgsql.php b/tests/comparisons/Diff/addRemove/the_diff_add_remove_pgsql.php index 6cb02884..f7cb4873 100644 --- a/tests/comparisons/Diff/addRemove/the_diff_add_remove_pgsql.php +++ b/tests/comparisons/Diff/addRemove/the_diff_add_remove_pgsql.php @@ -9,7 +9,7 @@ class TheDiffAddRemovePgsql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -32,7 +32,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/default/the_diff_default_mysql.php b/tests/comparisons/Diff/default/the_diff_default_mysql.php index c9916953..1c0d6e1f 100644 --- a/tests/comparisons/Diff/default/the_diff_default_mysql.php +++ b/tests/comparisons/Diff/default/the_diff_default_mysql.php @@ -9,7 +9,7 @@ class TheDiffDefaultMysql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -146,7 +146,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/default/the_diff_default_pgsql.php b/tests/comparisons/Diff/default/the_diff_default_pgsql.php index 3dd75232..efec4eeb 100644 --- a/tests/comparisons/Diff/default/the_diff_default_pgsql.php +++ b/tests/comparisons/Diff/default/the_diff_default_pgsql.php @@ -9,7 +9,7 @@ class TheDiffDefaultPgsql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -125,7 +125,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/simple/the_diff_simple_mysql.php b/tests/comparisons/Diff/simple/the_diff_simple_mysql.php index 3d5e8d75..0408cdb2 100644 --- a/tests/comparisons/Diff/simple/the_diff_simple_mysql.php +++ b/tests/comparisons/Diff/simple/the_diff_simple_mysql.php @@ -9,7 +9,7 @@ class TheDiffSimpleMysql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -73,7 +73,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/simple/the_diff_simple_pgsql.php b/tests/comparisons/Diff/simple/the_diff_simple_pgsql.php index 0a733d5c..93601d9f 100644 --- a/tests/comparisons/Diff/simple/the_diff_simple_pgsql.php +++ b/tests/comparisons/Diff/simple/the_diff_simple_pgsql.php @@ -9,7 +9,7 @@ class TheDiffSimplePgsql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -61,7 +61,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/withAutoIdCompatibleSignedPrimaryKeys/the_diff_with_auto_id_compatible_signed_primary_keys_mysql.php b/tests/comparisons/Diff/withAutoIdCompatibleSignedPrimaryKeys/the_diff_with_auto_id_compatible_signed_primary_keys_mysql.php index 6ff5a4b9..84b7c029 100644 --- a/tests/comparisons/Diff/withAutoIdCompatibleSignedPrimaryKeys/the_diff_with_auto_id_compatible_signed_primary_keys_mysql.php +++ b/tests/comparisons/Diff/withAutoIdCompatibleSignedPrimaryKeys/the_diff_with_auto_id_compatible_signed_primary_keys_mysql.php @@ -9,7 +9,7 @@ class TheDiffWithAutoIdCompatibleSignedPrimaryKeysMysql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -24,7 +24,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/withAutoIdIncompatibleSignedPrimaryKeys/the_diff_with_auto_id_incompatible_signed_primary_keys_mysql.php b/tests/comparisons/Diff/withAutoIdIncompatibleSignedPrimaryKeys/the_diff_with_auto_id_incompatible_signed_primary_keys_mysql.php index d252dc68..c3f159f0 100644 --- a/tests/comparisons/Diff/withAutoIdIncompatibleSignedPrimaryKeys/the_diff_with_auto_id_incompatible_signed_primary_keys_mysql.php +++ b/tests/comparisons/Diff/withAutoIdIncompatibleSignedPrimaryKeys/the_diff_with_auto_id_incompatible_signed_primary_keys_mysql.php @@ -11,7 +11,7 @@ class TheDiffWithAutoIdIncompatibleSignedPrimaryKeysMysql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -34,7 +34,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Diff/withAutoIdIncompatibleUnsignedPrimaryKeys/the_diff_with_auto_id_incompatible_unsigned_primary_keys_mysql.php b/tests/comparisons/Diff/withAutoIdIncompatibleUnsignedPrimaryKeys/the_diff_with_auto_id_incompatible_unsigned_primary_keys_mysql.php index 7c4b2d8f..314dfa91 100644 --- a/tests/comparisons/Diff/withAutoIdIncompatibleUnsignedPrimaryKeys/the_diff_with_auto_id_incompatible_unsigned_primary_keys_mysql.php +++ b/tests/comparisons/Diff/withAutoIdIncompatibleUnsignedPrimaryKeys/the_diff_with_auto_id_incompatible_unsigned_primary_keys_mysql.php @@ -11,7 +11,7 @@ class TheDiffWithAutoIdIncompatibleUnsignedPrimaryKeysMysql extends BaseMigratio * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -34,7 +34,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/pgsql/test_snapshot_auto_id_disabled_pgsql.php b/tests/comparisons/Migration/pgsql/test_snapshot_auto_id_disabled_pgsql.php index 682d92b0..e77e6fd4 100644 --- a/tests/comparisons/Migration/pgsql/test_snapshot_auto_id_disabled_pgsql.php +++ b/tests/comparisons/Migration/pgsql/test_snapshot_auto_id_disabled_pgsql.php @@ -11,7 +11,7 @@ class TestSnapshotAutoIdDisabledPgsql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -408,7 +408,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/pgsql/test_snapshot_not_empty_pgsql.php b/tests/comparisons/Migration/pgsql/test_snapshot_not_empty_pgsql.php index 33bf72cd..ea0c8745 100644 --- a/tests/comparisons/Migration/pgsql/test_snapshot_not_empty_pgsql.php +++ b/tests/comparisons/Migration/pgsql/test_snapshot_not_empty_pgsql.php @@ -9,7 +9,7 @@ class TestSnapshotNotEmptyPgsql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -348,7 +348,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/pgsql/test_snapshot_plugin_blog_pgsql.php b/tests/comparisons/Migration/pgsql/test_snapshot_plugin_blog_pgsql.php index 280e5ebc..ec810942 100644 --- a/tests/comparisons/Migration/pgsql/test_snapshot_plugin_blog_pgsql.php +++ b/tests/comparisons/Migration/pgsql/test_snapshot_plugin_blog_pgsql.php @@ -9,7 +9,7 @@ class TestSnapshotPluginBlogPgsql extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -132,7 +132,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/sqlite/test_snapshot_auto_id_disabled_sqlite.php b/tests/comparisons/Migration/sqlite/test_snapshot_auto_id_disabled_sqlite.php index c9ec51a9..efe9dca9 100644 --- a/tests/comparisons/Migration/sqlite/test_snapshot_auto_id_disabled_sqlite.php +++ b/tests/comparisons/Migration/sqlite/test_snapshot_auto_id_disabled_sqlite.php @@ -11,7 +11,7 @@ class TestSnapshotAutoIdDisabledSqlite extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -389,7 +389,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/sqlite/test_snapshot_not_empty_sqlite.php b/tests/comparisons/Migration/sqlite/test_snapshot_not_empty_sqlite.php index b5f88258..f6daa832 100644 --- a/tests/comparisons/Migration/sqlite/test_snapshot_not_empty_sqlite.php +++ b/tests/comparisons/Migration/sqlite/test_snapshot_not_empty_sqlite.php @@ -9,7 +9,7 @@ class TestSnapshotNotEmptySqlite extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -329,7 +329,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/sqlite/test_snapshot_plugin_blog_sqlite.php b/tests/comparisons/Migration/sqlite/test_snapshot_plugin_blog_sqlite.php index 926c4790..48d52563 100644 --- a/tests/comparisons/Migration/sqlite/test_snapshot_plugin_blog_sqlite.php +++ b/tests/comparisons/Migration/sqlite/test_snapshot_plugin_blog_sqlite.php @@ -9,7 +9,7 @@ class TestSnapshotPluginBlogSqlite extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -123,7 +123,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/sqlserver/test_snapshot_auto_id_disabled_sqlserver.php b/tests/comparisons/Migration/sqlserver/test_snapshot_auto_id_disabled_sqlserver.php index 730c6197..346bc106 100644 --- a/tests/comparisons/Migration/sqlserver/test_snapshot_auto_id_disabled_sqlserver.php +++ b/tests/comparisons/Migration/sqlserver/test_snapshot_auto_id_disabled_sqlserver.php @@ -11,7 +11,7 @@ class TestSnapshotAutoIdDisabledSqlserver extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -424,7 +424,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/sqlserver/test_snapshot_not_empty_sqlserver.php b/tests/comparisons/Migration/sqlserver/test_snapshot_not_empty_sqlserver.php index 3139e7be..1e9571c4 100644 --- a/tests/comparisons/Migration/sqlserver/test_snapshot_not_empty_sqlserver.php +++ b/tests/comparisons/Migration/sqlserver/test_snapshot_not_empty_sqlserver.php @@ -9,7 +9,7 @@ class TestSnapshotNotEmptySqlserver extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -364,7 +364,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/sqlserver/test_snapshot_plugin_blog_sqlserver.php b/tests/comparisons/Migration/sqlserver/test_snapshot_plugin_blog_sqlserver.php index 08e08e59..413bce06 100644 --- a/tests/comparisons/Migration/sqlserver/test_snapshot_plugin_blog_sqlserver.php +++ b/tests/comparisons/Migration/sqlserver/test_snapshot_plugin_blog_sqlserver.php @@ -9,7 +9,7 @@ class TestSnapshotPluginBlogSqlserver extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -137,7 +137,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/testCreate.php b/tests/comparisons/Migration/testCreate.php index 98225f72..14d4d51e 100644 --- a/tests/comparisons/Migration/testCreate.php +++ b/tests/comparisons/Migration/testCreate.php @@ -9,7 +9,7 @@ class CreateUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testCreateDatetime.php b/tests/comparisons/Migration/testCreateDatetime.php index 2846aecf..926cf1bd 100644 --- a/tests/comparisons/Migration/testCreateDatetime.php +++ b/tests/comparisons/Migration/testCreateDatetime.php @@ -9,7 +9,7 @@ class CreateUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testCreateDropMigration.php b/tests/comparisons/Migration/testCreateDropMigration.php index a7cf2868..766bb43f 100644 --- a/tests/comparisons/Migration/testCreateDropMigration.php +++ b/tests/comparisons/Migration/testCreateDropMigration.php @@ -9,7 +9,7 @@ class DropUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testCreateFieldLength.php b/tests/comparisons/Migration/testCreateFieldLength.php index 38a6131f..923830ab 100644 --- a/tests/comparisons/Migration/testCreateFieldLength.php +++ b/tests/comparisons/Migration/testCreateFieldLength.php @@ -9,7 +9,7 @@ class CreateUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testCreatePhinx.php b/tests/comparisons/Migration/testCreatePhinx.php index 98225f72..14d4d51e 100644 --- a/tests/comparisons/Migration/testCreatePhinx.php +++ b/tests/comparisons/Migration/testCreatePhinx.php @@ -9,7 +9,7 @@ class CreateUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testCreatePrimaryKey.php b/tests/comparisons/Migration/testCreatePrimaryKey.php index cec07a2c..aef898c5 100644 --- a/tests/comparisons/Migration/testCreatePrimaryKey.php +++ b/tests/comparisons/Migration/testCreatePrimaryKey.php @@ -11,7 +11,7 @@ class CreateUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testCreatePrimaryKeyUuid.php b/tests/comparisons/Migration/testCreatePrimaryKeyUuid.php index 8c7c65d7..7282686d 100644 --- a/tests/comparisons/Migration/testCreatePrimaryKeyUuid.php +++ b/tests/comparisons/Migration/testCreatePrimaryKeyUuid.php @@ -11,7 +11,7 @@ class CreateUsers extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/testNoContents.php b/tests/comparisons/Migration/testNoContents.php index dd4b84ce..1cbbf59e 100644 --- a/tests/comparisons/Migration/testNoContents.php +++ b/tests/comparisons/Migration/testNoContents.php @@ -9,7 +9,7 @@ class NoContents extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * @return void */ public function change(): void diff --git a/tests/comparisons/Migration/test_snapshot_auto_id_disabled.php b/tests/comparisons/Migration/test_snapshot_auto_id_disabled.php index f27fd4cf..0b2a5960 100644 --- a/tests/comparisons/Migration/test_snapshot_auto_id_disabled.php +++ b/tests/comparisons/Migration/test_snapshot_auto_id_disabled.php @@ -11,7 +11,7 @@ class TestSnapshotAutoIdDisabled extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -414,7 +414,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/test_snapshot_not_empty.php b/tests/comparisons/Migration/test_snapshot_not_empty.php index e106cc26..3cfbb7c1 100644 --- a/tests/comparisons/Migration/test_snapshot_not_empty.php +++ b/tests/comparisons/Migration/test_snapshot_not_empty.php @@ -9,7 +9,7 @@ class TestSnapshotNotEmpty extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -346,7 +346,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/test_snapshot_plugin_blog.php b/tests/comparisons/Migration/test_snapshot_plugin_blog.php index 32fd1080..68cb0665 100644 --- a/tests/comparisons/Migration/test_snapshot_plugin_blog.php +++ b/tests/comparisons/Migration/test_snapshot_plugin_blog.php @@ -9,7 +9,7 @@ class TestSnapshotPluginBlog extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -133,7 +133,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/test_snapshot_with_auto_id_compatible_signed_primary_keys.php b/tests/comparisons/Migration/test_snapshot_with_auto_id_compatible_signed_primary_keys.php index 3d402cd0..64be4697 100644 --- a/tests/comparisons/Migration/test_snapshot_with_auto_id_compatible_signed_primary_keys.php +++ b/tests/comparisons/Migration/test_snapshot_with_auto_id_compatible_signed_primary_keys.php @@ -9,7 +9,7 @@ class TestSnapshotWithAutoIdCompatibleSignedPrimaryKeys extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -37,7 +37,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_signed_primary_keys.php b/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_signed_primary_keys.php index bea1ba62..8f01a28b 100644 --- a/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_signed_primary_keys.php +++ b/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_signed_primary_keys.php @@ -11,7 +11,7 @@ class TestSnapshotWithAutoIdIncompatibleSignedPrimaryKeys extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -47,7 +47,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_unsigned_primary_keys.php b/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_unsigned_primary_keys.php index 1f68522f..f99d8cc6 100644 --- a/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_unsigned_primary_keys.php +++ b/tests/comparisons/Migration/test_snapshot_with_auto_id_incompatible_unsigned_primary_keys.php @@ -11,7 +11,7 @@ class TestSnapshotWithAutoIdIncompatibleUnsignedPrimaryKeys extends BaseMigratio * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -47,7 +47,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Migration/test_snapshot_with_non_default_collation.php b/tests/comparisons/Migration/test_snapshot_with_non_default_collation.php index fc2c071f..fa5f3a9c 100644 --- a/tests/comparisons/Migration/test_snapshot_with_non_default_collation.php +++ b/tests/comparisons/Migration/test_snapshot_with_non_default_collation.php @@ -9,7 +9,7 @@ class TestSnapshotWithNonDefaultCollation extends BaseMigration * Up Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-up-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-up-method * @return void */ public function up(): void @@ -38,7 +38,7 @@ public function up(): void * Down Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-down-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-down-method * @return void */ public function down(): void diff --git a/tests/comparisons/Seeds/pgsql/testWithData.php b/tests/comparisons/Seeds/pgsql/testWithData.php index 63047b5b..272d14ec 100644 --- a/tests/comparisons/Seeds/pgsql/testWithData.php +++ b/tests/comparisons/Seeds/pgsql/testWithData.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/pgsql/testWithDataAndLimit.php b/tests/comparisons/Seeds/pgsql/testWithDataAndLimit.php index f5346af8..45fda5df 100644 --- a/tests/comparisons/Seeds/pgsql/testWithDataAndLimit.php +++ b/tests/comparisons/Seeds/pgsql/testWithDataAndLimit.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/php81/testWithData.php b/tests/comparisons/Seeds/php81/testWithData.php index 63047b5b..272d14ec 100644 --- a/tests/comparisons/Seeds/php81/testWithData.php +++ b/tests/comparisons/Seeds/php81/testWithData.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/php81/testWithDataAndLimit.php b/tests/comparisons/Seeds/php81/testWithDataAndLimit.php index f5346af8..45fda5df 100644 --- a/tests/comparisons/Seeds/php81/testWithDataAndLimit.php +++ b/tests/comparisons/Seeds/php81/testWithDataAndLimit.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/sqlserver/testWithData.php b/tests/comparisons/Seeds/sqlserver/testWithData.php index ff9d221b..6cd3d80d 100644 --- a/tests/comparisons/Seeds/sqlserver/testWithData.php +++ b/tests/comparisons/Seeds/sqlserver/testWithData.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/sqlserver/testWithDataAndLimit.php b/tests/comparisons/Seeds/sqlserver/testWithDataAndLimit.php index a5c8fec7..3da22627 100644 --- a/tests/comparisons/Seeds/sqlserver/testWithDataAndLimit.php +++ b/tests/comparisons/Seeds/sqlserver/testWithDataAndLimit.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/testBasicBaking.php b/tests/comparisons/Seeds/testBasicBaking.php index 086dd451..ce5dc991 100644 --- a/tests/comparisons/Seeds/testBasicBaking.php +++ b/tests/comparisons/Seeds/testBasicBaking.php @@ -14,7 +14,7 @@ class ArticlesSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/testBasicBakingPhinx.php b/tests/comparisons/Seeds/testBasicBakingPhinx.php index 086dd451..ce5dc991 100644 --- a/tests/comparisons/Seeds/testBasicBakingPhinx.php +++ b/tests/comparisons/Seeds/testBasicBakingPhinx.php @@ -14,7 +14,7 @@ class ArticlesSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/testPrettifyArray.php b/tests/comparisons/Seeds/testPrettifyArray.php index 5f48bac7..c5a2978d 100644 --- a/tests/comparisons/Seeds/testPrettifyArray.php +++ b/tests/comparisons/Seeds/testPrettifyArray.php @@ -14,7 +14,7 @@ class TextsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/testWithData.php b/tests/comparisons/Seeds/testWithData.php index ff9d221b..6cd3d80d 100644 --- a/tests/comparisons/Seeds/testWithData.php +++ b/tests/comparisons/Seeds/testWithData.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/testWithDataAndFields.php b/tests/comparisons/Seeds/testWithDataAndFields.php index daef7fbd..02bdace5 100644 --- a/tests/comparisons/Seeds/testWithDataAndFields.php +++ b/tests/comparisons/Seeds/testWithDataAndFields.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/comparisons/Seeds/testWithDataAndLimit.php b/tests/comparisons/Seeds/testWithDataAndLimit.php index a5c8fec7..3da22627 100644 --- a/tests/comparisons/Seeds/testWithDataAndLimit.php +++ b/tests/comparisons/Seeds/testWithDataAndLimit.php @@ -14,7 +14,7 @@ class EventsSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeds is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html * * @return void */ diff --git a/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginLettersSeed.php b/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginLettersSeed.php index 23c3a58b..952893f7 100644 --- a/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginLettersSeed.php +++ b/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginLettersSeed.php @@ -13,7 +13,7 @@ class PluginLettersSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginSubLettersSeed.php b/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginSubLettersSeed.php index 0fb24dc7..1a3f77c3 100644 --- a/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginSubLettersSeed.php +++ b/tests/test_app/Plugin/TestBlog/config/CallSeeds/PluginSubLettersSeed.php @@ -13,7 +13,7 @@ class PluginSubLettersSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/AltSeeds/AnotherNumbersSeed.php b/tests/test_app/config/AltSeeds/AnotherNumbersSeed.php index eaa7c479..f72c0a34 100644 --- a/tests/test_app/config/AltSeeds/AnotherNumbersSeed.php +++ b/tests/test_app/config/AltSeeds/AnotherNumbersSeed.php @@ -13,7 +13,7 @@ class AnotherNumbersSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/AltSeeds/NumbersAltSeed.php b/tests/test_app/config/AltSeeds/NumbersAltSeed.php index 7fbbdc20..4c9e3c6d 100644 --- a/tests/test_app/config/AltSeeds/NumbersAltSeed.php +++ b/tests/test_app/config/AltSeeds/NumbersAltSeed.php @@ -13,7 +13,7 @@ class NumbersAltSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/BaseSeeds/MigrationSeedNumbers.php b/tests/test_app/config/BaseSeeds/MigrationSeedNumbers.php index fcd988b3..d12df269 100644 --- a/tests/test_app/config/BaseSeeds/MigrationSeedNumbers.php +++ b/tests/test_app/config/BaseSeeds/MigrationSeedNumbers.php @@ -13,7 +13,7 @@ class MigrationSeedNumbers extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/CallSeeds/DatabaseSeed.php b/tests/test_app/config/CallSeeds/DatabaseSeed.php index 64081620..90954c90 100644 --- a/tests/test_app/config/CallSeeds/DatabaseSeed.php +++ b/tests/test_app/config/CallSeeds/DatabaseSeed.php @@ -13,7 +13,7 @@ class DatabaseSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/CallSeeds/LettersSeed.php b/tests/test_app/config/CallSeeds/LettersSeed.php index 6ae31a42..300d6688 100644 --- a/tests/test_app/config/CallSeeds/LettersSeed.php +++ b/tests/test_app/config/CallSeeds/LettersSeed.php @@ -13,7 +13,7 @@ class LettersSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/CallSeeds/NumbersCallSeed.php b/tests/test_app/config/CallSeeds/NumbersCallSeed.php index 8539fed1..a6843abb 100644 --- a/tests/test_app/config/CallSeeds/NumbersCallSeed.php +++ b/tests/test_app/config/CallSeeds/NumbersCallSeed.php @@ -13,7 +13,7 @@ class NumbersCallSeed extends BaseSeed * Write your database seeder using this method. * * More information on writing seeders is available here: - * https://book.cakephp.org/migrations/4/en/seeding.html + * https://book.cakephp.org/migrations/5/en/seeding.html */ public function run(): void { diff --git a/tests/test_app/config/MigrationsDiffDefault/20160128183623_AlterArticlesDefault.php b/tests/test_app/config/MigrationsDiffDefault/20160128183623_AlterArticlesDefault.php index c5e328ac..ca59807b 100644 --- a/tests/test_app/config/MigrationsDiffDefault/20160128183623_AlterArticlesDefault.php +++ b/tests/test_app/config/MigrationsDiffDefault/20160128183623_AlterArticlesDefault.php @@ -8,7 +8,7 @@ class AlterArticlesDefault extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * @return void */ diff --git a/tests/test_app/config/MigrationsDiffDefault/20160128183652_AlterArticlesSlugDefault.php b/tests/test_app/config/MigrationsDiffDefault/20160128183652_AlterArticlesSlugDefault.php index 93d721fe..db70be01 100644 --- a/tests/test_app/config/MigrationsDiffDefault/20160128183652_AlterArticlesSlugDefault.php +++ b/tests/test_app/config/MigrationsDiffDefault/20160128183652_AlterArticlesSlugDefault.php @@ -8,7 +8,7 @@ class AlterArticlesSlugDefault extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * @return void */ diff --git a/tests/test_app/config/MigrationsDiffDefault/20160128183952_CreateUsersDefault.php b/tests/test_app/config/MigrationsDiffDefault/20160128183952_CreateUsersDefault.php index 45da7f84..6fd76720 100644 --- a/tests/test_app/config/MigrationsDiffDefault/20160128183952_CreateUsersDefault.php +++ b/tests/test_app/config/MigrationsDiffDefault/20160128183952_CreateUsersDefault.php @@ -8,7 +8,7 @@ class CreateUsersDefault extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * @return void */ diff --git a/tests/test_app/config/MigrationsDiffDefault/20160128184109_AlterArticlesFkDefault.php b/tests/test_app/config/MigrationsDiffDefault/20160128184109_AlterArticlesFkDefault.php index 69a17daa..a66b5645 100644 --- a/tests/test_app/config/MigrationsDiffDefault/20160128184109_AlterArticlesFkDefault.php +++ b/tests/test_app/config/MigrationsDiffDefault/20160128184109_AlterArticlesFkDefault.php @@ -8,7 +8,7 @@ class AlterArticlesFkDefault extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * @return void */ diff --git a/tests/test_app/config/MigrationsDiffDefault/20160414193900_CreateTagsDefault.php b/tests/test_app/config/MigrationsDiffDefault/20160414193900_CreateTagsDefault.php index b30ba672..e1f87ef2 100644 --- a/tests/test_app/config/MigrationsDiffDefault/20160414193900_CreateTagsDefault.php +++ b/tests/test_app/config/MigrationsDiffDefault/20160414193900_CreateTagsDefault.php @@ -8,7 +8,7 @@ class CreateTagsDefault extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * @return void */ diff --git a/tests/test_app/config/MigrationsDiffSimple/20160128183623_AlterArticlesSimple.php b/tests/test_app/config/MigrationsDiffSimple/20160128183623_AlterArticlesSimple.php index 3210d3f4..df5ad722 100644 --- a/tests/test_app/config/MigrationsDiffSimple/20160128183623_AlterArticlesSimple.php +++ b/tests/test_app/config/MigrationsDiffSimple/20160128183623_AlterArticlesSimple.php @@ -8,7 +8,7 @@ class AlterArticlesSimple extends BaseMigration * Change Method. * * More information on this method is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method + * https://book.cakephp.org/migrations/5/en/migrations.html#the-change-method * * @return void */ diff --git a/tests/test_app/config/Reversiblemigrations/20180516025208_create_test_index_limit_specifier_table.php b/tests/test_app/config/Reversiblemigrations/20180516025208_create_test_index_limit_specifier_table.php index e1bdb40e..3f7f7f87 100644 --- a/tests/test_app/config/Reversiblemigrations/20180516025208_create_test_index_limit_specifier_table.php +++ b/tests/test_app/config/Reversiblemigrations/20180516025208_create_test_index_limit_specifier_table.php @@ -11,7 +11,7 @@ class CreateTestIndexLimitSpecifierTable extends BaseMigration * Write your reversible migrations using this method. * * More information on writing migrations is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html + * https://book.cakephp.org/migrations/5/en/migrations.html * * The following commands can be used in this method and Phinx will * automatically reverse them when rolling back: diff --git a/tests/test_app/config/Reversiblemigrations/20190928220334_add_column_index_fk.php b/tests/test_app/config/Reversiblemigrations/20190928220334_add_column_index_fk.php index 03616764..e25591b3 100644 --- a/tests/test_app/config/Reversiblemigrations/20190928220334_add_column_index_fk.php +++ b/tests/test_app/config/Reversiblemigrations/20190928220334_add_column_index_fk.php @@ -12,7 +12,7 @@ class AddColumnIndexFk extends BaseMigration * Write your reversible migrations using this method. * * More information on writing migrations is available here: - * https://book.cakephp.org/migrations/4/en/migrations.html + * https://book.cakephp.org/migrations/5/en/migrations.html * * The following commands can be used in this method and Phinx will * automatically reverse them when rolling back: From 35cecb194e6d6d781bfcfa28fee65b82d0d0e997 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 5 Aug 2025 22:49:22 -0400 Subject: [PATCH 5/8] Fix tests --- tests/TestCase/Migration/EnvironmentTest.php | 28 +++++++------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/tests/TestCase/Migration/EnvironmentTest.php b/tests/TestCase/Migration/EnvironmentTest.php index 9db92cdb..7196ae34 100644 --- a/tests/TestCase/Migration/EnvironmentTest.php +++ b/tests/TestCase/Migration/EnvironmentTest.php @@ -131,8 +131,7 @@ public function up(): void } }; - $migrationWrapper = new MigrationAdapter($upMigration, $upMigration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::UP); + $this->environment->executeMigration($upMigration, MigrationInterface::UP); $this->assertTrue($upMigration->executed); } @@ -157,8 +156,7 @@ public function down(): void } }; - $migrationWrapper = new MigrationAdapter($downMigration, $downMigration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::DOWN); + $this->environment->executeMigration($downMigration, MigrationInterface::DOWN); $this->assertTrue($downMigration->executed); } @@ -189,8 +187,7 @@ public function up(): void } }; - $migrationWrapper = new MigrationAdapter($migration, $migration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::UP); + $this->environment->executeMigration($migration, MigrationInterface::UP); $this->assertTrue($migration->executed); } @@ -227,8 +224,7 @@ public function up(): void } }; - $migrationWrapper = new MigrationAdapter($migration, $migration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::UP); + $this->environment->executeMigration($migration, MigrationInterface::UP); $this->assertTrue($migration->executed); } @@ -253,8 +249,7 @@ public function change(): void } }; - $migrationWrapper = new MigrationAdapter($migration, $migration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::UP); + $this->environment->executeMigration($migration, MigrationInterface::UP); $this->assertTrue($migration->executed); } @@ -279,9 +274,7 @@ public function change(): void } }; - //FIXME - $migrationWrapper = new MigrationAdapter($migration, $migration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::DOWN); + $this->environment->executeMigration($migration, MigrationInterface::DOWN); $this->assertTrue($migration->executed); } @@ -306,8 +299,7 @@ public function change(): void } }; - $migrationWrapper = new MigrationAdapter($migration, $migration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::UP, true); + $this->environment->executeMigration($migration, MigrationInterface::UP, true); $this->assertFalse($migration->executed); } @@ -346,8 +338,7 @@ public function up(): void $this->upExecuted = true; } }; - $migrationWrapper = new MigrationAdapter($upMigration, $upMigration->getVersion()); - $this->environment->executeMigration($migrationWrapper, MigrationInterface::UP); + $this->environment->executeMigration($upMigration, MigrationInterface::UP); $this->assertTrue($upMigration->initExecuted); $this->assertTrue($upMigration->upExecuted); } @@ -376,8 +367,7 @@ public function run(): void } }; - $seedWrapper = new SeedAdapter($seed); - $this->environment->executeSeed($seedWrapper); + $this->environment->executeSeed($seed); $this->assertTrue($seed->initExecuted); $this->assertTrue($seed->runExecuted); From e8b99555d1e2b0cff435185d22c49e8d30f43948 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 5 Aug 2025 23:15:13 -0400 Subject: [PATCH 6/8] Fix more tests. --- tests/TestCase/Command/BakeMigrationDiffCommandTest.php | 2 +- tests/TestCase/MigrationsTest.php | 2 +- tests/comparisons/Diff/simple/the_diff_simple_mysql.php | 9 +++++++++ .../App/Command/CustomBakeMigrationDiffCommand.php | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/TestCase/Command/BakeMigrationDiffCommandTest.php b/tests/TestCase/Command/BakeMigrationDiffCommandTest.php index b6ae153c..27a87b22 100644 --- a/tests/TestCase/Command/BakeMigrationDiffCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationDiffCommandTest.php @@ -59,7 +59,7 @@ public function tearDown(): void if (env('DB_URL_COMPARE')) { // Clean up the comparison database each time. Table order is important. $connection = ConnectionManager::get('test_comparisons'); - $tables = ['articles', 'categories', 'comments', 'users', 'phinxlog']; + $tables = ['articles', 'categories', 'comments', 'users', 'phinxlog', 'tags']; foreach ($tables as $table) { $connection->execute("DROP TABLE IF EXISTS $table"); } diff --git a/tests/TestCase/MigrationsTest.php b/tests/TestCase/MigrationsTest.php index a4f64dd7..7b86f1c1 100644 --- a/tests/TestCase/MigrationsTest.php +++ b/tests/TestCase/MigrationsTest.php @@ -1055,7 +1055,7 @@ public function testMigrateSnapshots(string $basePath, string $filename, array $ // change class name to avoid conflict with other classes // to avoid 'Fatal error: Cannot declare class Test...., because the name is already in use' $content = file_get_contents($destination . $copiedFileName); - $patterns = [' extends BaseMigration', ' extends BaseMigration']; + $patterns = [' extends BaseMigration']; foreach ($patterns as $pattern) { $content = str_replace($pattern, 'NewSuffix' . $pattern, $content); } diff --git a/tests/comparisons/Diff/simple/the_diff_simple_mysql.php b/tests/comparisons/Diff/simple/the_diff_simple_mysql.php index 0408cdb2..3585bbdc 100644 --- a/tests/comparisons/Diff/simple/the_diff_simple_mysql.php +++ b/tests/comparisons/Diff/simple/the_diff_simple_mysql.php @@ -30,6 +30,14 @@ public function up(): void 'null' => false, ]) ->update(); + $this->table('tags') + ->addColumn('name', 'string', [ + 'default' => null, + 'limit' => 255, + 'null' => false, + ]) + ->create(); + $this->table('users') ->addColumn('username', 'string', [ 'default' => null, @@ -102,6 +110,7 @@ public function down(): void ->removeColumn('user_id') ->update(); + $this->table('tags')->drop()->save(); $this->table('users')->drop()->save(); } } diff --git a/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php b/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php index b91c347c..e7bc5ae2 100644 --- a/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php +++ b/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php @@ -63,6 +63,6 @@ protected function getDumpSchema(Arguments $args): array $diffConfigFolder = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Diff' . DS . $comparison . DS; $diffDumpPath = $diffConfigFolder . 'schema-dump-test_comparisons_' . env('DB') . '.lock'; - return unserialize(file_get_contents($diffDumpPath)); + return unserialize(trim(file_get_contents($diffDumpPath))); } } From 045f746fe483172fd862eefcf76e8c794d0947a0 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 5 Aug 2025 23:16:41 -0400 Subject: [PATCH 7/8] Fix phpcs --- tests/TestCase/Migration/EnvironmentTest.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/TestCase/Migration/EnvironmentTest.php b/tests/TestCase/Migration/EnvironmentTest.php index 7196ae34..84d06058 100644 --- a/tests/TestCase/Migration/EnvironmentTest.php +++ b/tests/TestCase/Migration/EnvironmentTest.php @@ -11,8 +11,6 @@ use Migrations\Db\Adapter\AdapterWrapper; use Migrations\Migration\Environment; use Migrations\MigrationInterface; -use Migrations\Shim\MigrationAdapter; -use Migrations\Shim\SeedAdapter; use PHPUnit\Framework\TestCase; use RuntimeException; From 62a4e89b8c6264edb51534d138e20ab53663247d Mon Sep 17 00:00:00 2001 From: Mark Story Date: Wed, 6 Aug 2025 15:40:25 -0400 Subject: [PATCH 8/8] Fix constraint action generation --- src/View/Helper/MigrationHelper.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/View/Helper/MigrationHelper.php b/src/View/Helper/MigrationHelper.php index f61f26f2..3f5d54d6 100644 --- a/src/View/Helper/MigrationHelper.php +++ b/src/View/Helper/MigrationHelper.php @@ -24,6 +24,7 @@ use Cake\Utility\Inflector; use Cake\View\Helper; use Cake\View\View; +use Migrations\Db\Table\ForeignKey; /** * Migration Helper class for output of field data in migration files. @@ -264,7 +265,7 @@ public function constraints(TableSchemaInterface|string $table): array */ public function formatConstraintAction(string $constraint): string { - if (defined('\Phinx\Db\Table\ForeignKey::' . $constraint)) { + if (defined(ForeignKey::class . '::' . $constraint)) { return $constraint; }