index.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. DoctrineMigrationsBundle
  2. ========================
  3. Database migrations are a way to safely update your database schema both locally
  4. and on production. Instead of running the ``doctrine:schema:update`` command or
  5. applying the database changes manually with SQL statements, migrations allow to
  6. replicate the changes in your database schema in a safe manner.
  7. Migrations are available in Symfony applications via the `DoctrineMigrationsBundle`_,
  8. which uses the external `Doctrine Database Migrations`_ library. Read the
  9. `documentation`_ of that library if you need a general introduction about migrations.
  10. Installation
  11. ------------
  12. Run this command in your terminal:
  13. .. code-block:: terminal
  14. $ composer require doctrine/doctrine-migrations-bundle "^3.0"
  15. If you don't use `Symfony Flex`_, you must enable the bundle manually in the application:
  16. .. code-block:: php
  17. // config/bundles.php
  18. // in older Symfony apps, enable the bundle in app/AppKernel.php
  19. return [
  20. // ...
  21. Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
  22. ];
  23. Configuration
  24. -------------
  25. If you use Symfony Flex, the ``doctrine_migrations.yaml`` config file is created
  26. automatically. Otherwise, create the following file and configure it for your
  27. application:
  28. .. code-block:: yaml
  29. # config/packages/doctrine_migrations.yaml
  30. doctrine_migrations:
  31. # List of namespace/path pairs to search for migrations, at least one required
  32. migrations_paths:
  33. 'App\Migrations': 'src/App'
  34. 'AnotherApp\Migrations': '/path/to/other/migrations'
  35. 'SomeBundle\Migrations': '@SomeBundle/Migrations'
  36. # List of additional migration classes to be loaded, optional
  37. migrations:
  38. - 'App\Migrations\Version123'
  39. - 'App\Migrations\Version123'
  40. # Connection to use for the migrations
  41. connection: default
  42. # Entity manager to use for migrations. This overrides the "connection" setting.
  43. em: default
  44. storage:
  45. # Default (SQL table) metadata storage configuration
  46. table_storage:
  47. table_name: 'doctrine_migration_versions'
  48. version_column_name: 'version'
  49. version_column_length: 1024
  50. executed_at_column_name: 'executed_at'
  51. execution_time_column_name: 'execution_time'
  52. # Possible values: "BY_YEAR", "BY_YEAR_AND_MONTH", false
  53. organize_migrations: false
  54. # Path to your custom migrations template
  55. custom_template: ~
  56. # Run all migrations in a transaction.
  57. all_or_nothing: false
  58. # Adds an extra check in the generated migrations to ensure that is executed on the same database type.
  59. check_database_platform: true
  60. services:
  61. # Custom migration sorting service id
  62. 'Doctrine\Migrations\Version\Comparator': ~
  63. # Custom migration classes factory
  64. 'Doctrine\Migrations\Version\MigrationFactory': ~
  65. factories:
  66. # Custom migration sorting service id via callables (MyCallableFactory must be a callable)
  67. 'Doctrine\Migrations\Version\Comparator': 'MyCallableFactory'
  68. - The ``services`` node allows you to provide custom services to the underlying ``DependencyFactory`` part
  69. of ``doctrine/migrations``.
  70. - The node ``factories`` is similar to ``services``, with the difference that it accepts only callables.
  71. The provided callable must return the service to be passed to the ``DependencyFactory``.
  72. The callable will receive as first argument the ``DependencyFactory`` itself,
  73. allowing you to fetch other dependencies from the factory while instantiating your custom dependencies.
  74. Usage
  75. -----
  76. All of the migrations functionality is contained in a few console commands:
  77. .. code-block:: terminal
  78. doctrine
  79. doctrine:migrations:current [current] Outputs the current version.
  80. doctrine:migrations:diff [diff] Generate a migration by comparing your current database to your mapping information.
  81. doctrine:migrations:dump-schema [dump-schema] Dump the schema for your database to a migration.
  82. doctrine:migrations:execute [execute] Execute a single migration version up or down manually.
  83. doctrine:migrations:generate [generate] Generate a blank migration class.
  84. doctrine:migrations:latest [latest] Outputs the latest version number
  85. doctrine:migrations:migrate [migrate] Execute a migration to a specified version or the latest available version.
  86. doctrine:migrations:rollup [rollup] Roll migrations up by deleting all tracked versions and inserting the one version that exists.
  87. doctrine:migrations:status [status] View the status of a set of migrations.
  88. doctrine:migrations:up-to-date [up-to-date] Tells you if your schema is up-to-date.
  89. doctrine:migrations:version [version] Manually add and delete migration versions from the version table.
  90. doctrine:migrations:sync-metadata-storage [sync-metadata-storage] Ensures that the metadata storage is at the latest version.
  91. doctrine:migrations:list [list-migrations] Display a list of all available migrations and their status.
  92. Start by getting the status of migrations in your application by running
  93. the ``status`` command:
  94. .. code-block:: terminal
  95. $ php bin/console doctrine:migrations:status
  96. This command will show you generic information about the migration status, such as how many migrations have been
  97. already executed, which still need to run, and the database in use.
  98. Now, you can start working with migrations by generating a new blank migration
  99. class. Later, you'll learn how Doctrine can generate migrations automatically
  100. for you.
  101. .. code-block:: terminal
  102. $ php bin/console doctrine:migrations:generate
  103. Have a look at the newly generated migration class and you will see something
  104. like the following:
  105. .. code-block:: php
  106. declare(strict_types=1);
  107. namespace DoctrineMigrations;
  108. use Doctrine\DBAL\Schema\Schema;
  109. use Doctrine\Migrations\AbstractMigration;
  110. /**
  111. * Auto-generated Migration: Please modify to your needs!
  112. */
  113. final class Version20180605025653 extends AbstractMigration
  114. {
  115. public function getDescription() : string
  116. {
  117. return '';
  118. }
  119. public function up(Schema $schema) : void
  120. {
  121. // this up() migration is auto-generated, please modify it to your needs
  122. }
  123. public function down(Schema $schema) : void
  124. {
  125. // this down() migration is auto-generated, please modify it to your needs
  126. }
  127. }
  128. If you run the ``status`` command again it will now show that you have one new
  129. migration to execute:
  130. .. code-block:: terminal
  131. $ php bin/console doctrine:migrations:status --show-versions
  132. Now you can add some migration code to the ``up()`` and ``down()`` methods and
  133. finally migrate when you're ready:
  134. .. code-block:: terminal
  135. $ php bin/console doctrine:migrations:migrate 'DoctrineMigrations\Version20180605025653'
  136. For more information on how to write the migrations themselves (i.e. how to
  137. fill in the ``up()`` and ``down()`` methods), see the official Doctrine Migrations
  138. `documentation`_.
  139. Running Migrations during Deployment
  140. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  141. Of course, the end goal of writing migrations is to be able to use them to
  142. reliably update your database structure when you deploy your application.
  143. By running the migrations locally (or on a beta server), you can ensure that
  144. the migrations work as you expect.
  145. When you do finally deploy your application, you just need to remember to run
  146. the ``doctrine:migrations:migrate`` command. Internally, Doctrine creates
  147. a ``migration_versions`` table inside your database and tracks which migrations
  148. have been executed there. So, no matter how many migrations you've created
  149. and executed locally, when you run the command during deployment, Doctrine
  150. will know exactly which migrations it hasn't run yet by looking at the ``migration_versions``
  151. table of your production database. Regardless of what server you're on, you
  152. can always safely run this command to execute only the migrations that haven't
  153. been run yet on *that* particular database.
  154. Skipping Migrations
  155. ~~~~~~~~~~~~~~~~~~~
  156. You can skip single migrations by explicitly adding them to the ``migration_versions`` table:
  157. .. code-block:: terminal
  158. $ php bin/console doctrine:migrations:version 'App\Migrations\Version123' --add
  159. .. tip::
  160. Pay attention to the single quotes (``'``) used in the command above, without them
  161. or with the double quotes (``"``) the command will not work properly.
  162. Doctrine will then assume that this migration has already been run and will ignore it.
  163. Generating Migrations Automatically
  164. -----------------------------------
  165. In reality, you should rarely need to write migrations manually, as the migrations
  166. library can generate migration classes automatically by comparing your Doctrine
  167. mapping information (i.e. what your database *should* look like) with your
  168. actual current database structure.
  169. For example, suppose you create a new ``User`` entity and add mapping information
  170. for Doctrine's ORM:
  171. .. configuration-block::
  172. .. code-block:: php-annotations
  173. // src/Entity/User.php
  174. namespace App\Entity;
  175. use Doctrine\ORM\Mapping as ORM;
  176. /**
  177. * @ORM\Entity
  178. * @ORM\Table(name="hello_user")
  179. */
  180. class User
  181. {
  182. /**
  183. * @ORM\Id
  184. * @ORM\Column(type="integer")
  185. * @ORM\GeneratedValue(strategy="AUTO")
  186. */
  187. private $id;
  188. /**
  189. * @ORM\Column(type="string", length=255)
  190. */
  191. private $name;
  192. .. code-block:: yaml
  193. # config/doctrine/User.orm.yml
  194. App\Entity\User:
  195. type: entity
  196. table: user
  197. id:
  198. id:
  199. type: integer
  200. generator:
  201. strategy: AUTO
  202. fields:
  203. name:
  204. type: string
  205. length: 255
  206. .. code-block:: xml
  207. <!-- config/doctrine/User.orm.xml -->
  208. <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
  209. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  210. xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
  211. http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  212. <entity name="App\Entity\User" table="user">
  213. <id name="id" type="integer" column="id">
  214. <generator strategy="AUTO"/>
  215. </id>
  216. <field name="name" column="name" type="string" length="255" />
  217. </entity>
  218. </doctrine-mapping>
  219. With this information, Doctrine is now ready to help you persist your new
  220. ``User`` object to and from the ``user`` table. Of course, this table
  221. doesn't exist yet! Generate a new migration for this table automatically by
  222. running the following command:
  223. .. code-block:: terminal
  224. $ php bin/console doctrine:migrations:diff
  225. You should see a message that a new migration class was generated based on
  226. the schema differences. If you open this file, you'll find that it has the
  227. SQL code needed to create the ``user`` table. Next, run the migration
  228. to add the table to your database:
  229. .. code-block:: terminal
  230. $ php bin/console doctrine:migrations:migrate
  231. The moral of the story is this: after each change you make to your Doctrine
  232. mapping information, run the ``doctrine:migrations:diff`` command to automatically
  233. generate your migration classes.
  234. If you do this from the very beginning of your project (i.e. so that even
  235. the first tables were loaded via a migration class), you'll always be able
  236. to create a fresh database and run your migrations in order to get your database
  237. schema fully up to date. In fact, this is an easy and dependable workflow
  238. for your project.
  239. If you don't want to use this workflow and instead create your schema via
  240. ``doctrine:schema:create``, you can tell Doctrine to skip all existing migrations:
  241. .. code-block:: terminal
  242. $ php bin/console doctrine:migrations:version --add --all
  243. Otherwise Doctrine will try to run all migrations, which probably will not work.
  244. Manual Tables
  245. -------------
  246. It is a common use case, that in addition to your generated database structure
  247. based on your doctrine entities you might need custom tables. By default such
  248. tables will be removed by the ``doctrine:migrations:diff`` command.
  249. If you follow a specific scheme you can configure doctrine/dbal to ignore those
  250. tables. Let's say all custom tables will be prefixed by ``t_``. In this case you
  251. just have to add the following configuration option to your doctrine configuration:
  252. .. configuration-block::
  253. .. code-block:: yaml
  254. doctrine:
  255. dbal:
  256. schema_filter: ~^(?!t_)~
  257. .. code-block:: xml
  258. <doctrine:dbal schema-filter="~^(?!t_)~" ... />
  259. .. code-block:: php
  260. $container->loadFromExtension('doctrine', array(
  261. 'dbal' => array(
  262. 'schema_filter' => '~^(?!t_)~',
  263. // ...
  264. ),
  265. // ...
  266. ));
  267. This ignores the tables, and any named objects such as sequences, on the DBAL level and they will be ignored by the diff command.
  268. Note that if you have multiple connections configured then the ``schema_filter`` configuration
  269. will need to be placed per-connection.
  270. .. _documentation: https://www.doctrine-project.org/projects/doctrine-migrations/en/current/index.html
  271. .. _DoctrineMigrationsBundle: https://github.com/doctrine/DoctrineMigrationsBundle
  272. .. _`Doctrine Database Migrations`: https://github.com/doctrine/migrations
  273. .. _`Symfony Flex`: https://symfony.com/doc/current/setup/flex.html