How to rename a table in Symfony 3/Doctrine? - php

I want to change a table from order to shop_order. First I alter the table name in phpmyadmin.
Furthermore I would have guessed, that changing the annotations would be sufficient:
/**
* Order
*
* #ORM\Table(name="shop_order")
* #ORM\Entity
*/
class Order { ...
But when running
php bin/console doctrine:schema:update --dump-sql
It tries to create the table again:
CREATE TABLE `order` (id INT AUTO_INCREMENT NOT NULL ...
Is there any other file I need to change?

Clear the cache and try to alter the table name back with phpMyAdmin again. Once it is order again then use the doctrine command:
php bin/console doctrine:schema:update --dump-sql
If you want Doctrine to execute the changes then add --force as well.
Also check your Doctrine configuration, it could be that is caching the metadata somewhere else (e.g. Memcache). You might need to clear that as well.
Doctrine caches on three levels: query cache, metadata cache and result cache. You may want to take a look at the metadata one.
doctrine:
orm:
auto_mapping: true
# each caching driver type defines its own config options
metadata_cache_driver: apc
result_cache_driver:
type: memcache
host: localhost
port: 11211
instance_class: Memcache
# the 'service' type requires to define the 'id' option too
query_cache_driver:
type: service
id: my_doctrine_common_cache_service
So, if for example yours is set to Memcache then you'll have to reset Memcache as well.
Take a look at the docs here.

try to use force, like this:
php bin/console doctrine:schema:update --force --dump-sql
And delete the cache please
If It doesn't work I advise you to use migration because seems tha doctrine doesn't recognize the change of the table name:
Generate a new migration.
Erase contents of up() and down() methods and replace them with custom SQL (ALTER TABLE ... RENAME TO ...).
Migration docs

Just change the name with DB administration tool, change the name in the entity accordingly, clear cache and you are good to go - doctrine:schema:update --dump-sql will then export no change.

Related

The version "latest" couldn't be reached, there are no registered migrations

So I'm setting up a Symfony 5 project and running the following commands to generate the database from entity annotations like this:
php bin/console doctrine:schema:validate
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
But it's not working as expected, and instead I'm just getting this error:
**[ERROR]** The version "latest" couldn't be reached, there are no registered migrations.
The diff command correctly generates the migration file containing the up() and down() functions however when I subsequently run the migrate command to generate the database it fails with the above error.
I also notice the file /config/packages/doctrine_migrations.yml has changed recently to this:
doctrine_migrations:
migrations_paths:
'App\Migrations': '%kernel.project_dir%/src/Migrations'
However it appears doctrine is looking outside this path for the migrations in the following path:
'%kernel.project_dir%/migrations'
How do you resolve the above error so that the migrate command works as expected and generates the database tables from the generated migration file?
php bin/console debug:config doctrine_migrations
Current configuration for extension with alias "doctrine_migrations"
================================================================= ===
doctrine_migrations:
migrations_paths:
App\Migrations: /var/www/src/Migrations
services: { }
factories: { }
storage:
table_storage:
table_name: null
version_column_name: null
version_column_length: null
executed_at_column_name: null
execution_time_column_name: null
migrations: { }
connection: null
em: null
all_or_nothing: false
check_database_platform: true
custom_template: null
organize_migrations: false
Check the namespace of your migration scripts and the config of the migration bundle. After moving the directory from src/migrations to migrations you have to change the namespace of the files to DoctrineMigrations and change the storage table name to the one, which exists (otherwise the new default migration table name is doctrine_migration_versions).
Here is my proposal:
some migration file in /migrations
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
// ...
Config:
doctrine_migrations:
migrations_paths:
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
'DoctrineMigrations': '%kernel.project_dir%/migrations'
storage:
# Default (SQL table) metadata storage configuration
table_storage:
table_name: 'migration_versions'
this helps me to setup the project from scratch with Symfony5 and be backwards compatible with the current running production system.
I think you need to run the command "php bin/console make:migration" before "php bin/console make:migration:migrate"
I hope this is helpful.

Symfony 5: Base table or view already exists: 1050 Table 'migration_versions' already exists

I have a Symfony 5 app, which includes three doctrine migrations. I try to run the following commands:
bin/console doctrine:database:drop --force
bin/console doctrine:database:create
bin/console doctrine:migrations:migrate
... but when running the third command, I get these errors:
In AbstractMySQLDriver.php line 38:
An exception occurred while executing 'CREATE TABLE migration_versions (version VARCHAR(14) NOT NULL, executed_a
t DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', PRIMARY KEY(version)) DEFAULT CHARACTER SET utf8mb4
COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB':
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'migration_versions' already exists
In PDOConnection.php line 43:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'migration_versions' already exists
In PDOConnection.php line 41:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'migration_versions' already exists
I have tried adding the following code in doctrine.yaml:
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
schema_filter: ~^(migration_versions)$~
... per this answer on a different question, but this does not solve the problem. What am I doing wrong here?
====
EDIT 1: Here is the content of doctrine_migrations.yaml:
doctrine_migrations:
dir_name: '%kernel.project_dir%/src/Migrations'
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
namespace: DoctrineMigrations
EDIT 2: I double-checked to make sure that none of my three migrations contains a creation of the migration_versions table. It's not being created in any of those three migrations. So it's very mysterious where the error is coming from.
EDIT 3: I ran these three commands:
bin/console doctrine:migrations:execute --up --version 20191210174025
bin/console doctrine:migrations:execute --up --version 20201219113811
bin/console doctrine:migrations:execute --up --version 20201221174858
... and got back Symfony 5.0.1 (env: dev, debug: true) each time, with no error appearing. So I don't think the problem is in the migrations themselves.
Every time when you run the migration command, doctrine migrator check if the migration table exists. The migrator checks by doctrine schema manager. It seems that in your situation the isInitialized method always returns false.
You can debug the isInitialized method. Especially rows
$this->schemaManager->tablesExist([$this->configuration->getTableName()])
Doctrine checks if a table exists by getting a list of tables from information_schema (for MySQL). The SQL will be something like that:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
It seems in your case there is desynchronization between information_schema.tables and tables in your database.
The faster fix: change your database name
ry to run the following commands:
bin/console doctrine:schema:update
doctrine:schema:update --force to execute the command
doctrine:schema:update --dump-sql to dump the SQL statements to the screen
to see :: https://symfony.com/doc/current/DoctrineMigrationsBundle/index.html

Doctrine commands not showing up in Symfony 3.4 console even though doctrine/doctrine-bundle is installed

I have an old Symfony 3.4 app (https://github.com/opencfp/opencfp) that needs to have Doctrine added to it so I can replace an existing auth/acl solution with Symfony Guard and then get moving towards upgrading towards Symfony 5. I've installed doctrine/doctrine-bundle and can see that the commands are in the vendor directory but when I run bin/console none of the doctrine commands show up.
Here's what I found when I searched my vendor directory for Doctrine console commands.
doctrine/doctrine-bundle/Resources/config/dbal.xml
87: <tag name="console.command" command="doctrine:database:create" />
93: <tag name="console.command" command="doctrine:database:drop" />
97: <tag name="console.command" command="doctrine:database:import" />
doctrine/doctrine-bundle/Command/Proxy/ImportDoctrineCommand.php
23: ->setName('doctrine:database:import')
doctrine/doctrine-bundle/Command/DropDatabaseDoctrineCommand.php
29: ->setName('doctrine:database:drop')
doctrine/doctrine-bundle/Command/CreateDatabaseDoctrineCommand.php
25: ->setName('doctrine:database:create')
When I run bin/console I don't see any of the commands in the doctrine namespace
Symfony 3.4.35 (kernel: OpenCFP, env: development, debug: true)
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-e, --env=ENV The Environment name. [default: "development"]
--no-debug Switches off debug mode.
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
about Displays information about the current project
help Displays help for a command
list Lists commands
assets
assets:install Installs bundles web assets under a public directory
cache
cache:clear Clears the cache
cache:pool:clear Clears cache pools
cache:pool:prune Prunes cache pools
cache:warmup Warms up an empty cache
config
config:dump-reference Dumps the default configuration for an extension
debug
debug:autowiring Lists classes/interfaces you can use for autowiring
debug:config Dumps the current configuration for an extension
debug:container Displays current services for an application
debug:event-dispatcher Displays configured listeners for an application
debug:form Displays form type information
debug:router Displays current routes for an application
debug:swiftmailer Displays current mailers for an application
debug:translation Displays translation messages information
debug:twig Shows a list of twig functions, filters, globals and tests
eloquent
eloquent:make:seeder Create a new seeder class
eloquent:migrate Executes a migration.
eloquent:migrate:fresh Drop all tables and re-run all migrations.
eloquent:migrate:install Creates the migration repository.
eloquent:migrate:make Creates a new migration file
eloquent:migrate:refresh Reset and re-run all migrations
eloquent:migrate:reset Rollback all database migrations
eloquent:migrate:rollback Rollback the last database migration
eloquent:migrate:status Show the status of each migration
eloquent:seed Seed the database with records
lint
lint:twig Lints a template and outputs encountered errors
lint:xliff Lints a XLIFF file and outputs encountered errors
lint:yaml Lints a file and outputs encountered errors
router
router:match Helps debug routes by simulating a path info match
server
server:log Starts a log server that displays logs in real time
server:run Runs a local web server
server:start Starts a local web server in the background
server:status Outputs the status of the local web server
server:stop Stops the local web server that was started with the server:start command
swiftmailer
swiftmailer:email:send Send simple email message
swiftmailer:spool:send Sends emails from the spool
translation
translation:update Updates the translation file
user
user:create Creates a new user
user:demote Demote an existing user from a role
user:promote Promote an existing user to a role
I do have some custom commands in there as well.
Any help is greatly appreciated.
From what I gather from vendor/doctrine/doctrine-bundle/DependencyInjection/DoctrineExtension.php, a proper configuration for both the DBAL and the ORM are required to enable the commands:
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$this->adapter->loadServicesConfiguration($container);
if (! empty($config['dbal'])) {
$this->dbalLoad($config['dbal'], $container);
$this->loadMessengerServices($container);
}
if (empty($config['orm'])) {
return;
}
if (empty($config['dbal'])) {
throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.');
}
$this->ormLoad($config['orm'], $container);
}
The ormLoad and dbalLoad are responsible for registering the commands.
In this specific instance, Doctrine needs to be registered:
doctrine:
dbal:
url: mysql://db_user:db_password#127.0.0.1:3306/db_name
orm: ~
The above goes at the end of resources/config/config.yml, or any other file of that folder. Also, you'd need to make the proper adjustments.
doctrine
doctrine:cache:clear-collection-region Clear a second-level cache collection region
doctrine:cache:clear-entity-region Clear a second-level cache entity region
doctrine:cache:clear-metadata Clears all metadata cache for an entity manager
doctrine:cache:clear-query Clears all query cache for an entity manager
doctrine:cache:clear-query-region Clear a second-level cache query region
doctrine:cache:clear-result Clears result cache for an entity manager
doctrine:cache:contains Check if a cache entry exists
doctrine:cache:delete Delete a cache entry
doctrine:cache:flush [doctrine:cache:clear] Flush a given cache
doctrine:cache:stats Get stats on a given cache provider
doctrine:database:create Creates the configured database
doctrine:database:drop Drops the configured database
doctrine:database:import Import SQL file(s) directly to Database.
doctrine:ensure-production-settings Verify that Doctrine is properly configured for a production environment
doctrine:generate:entities [generate:doctrine:entities] Generates entity classes and method stubs from your mapping information
doctrine:mapping:convert [orm:convert:mapping] Convert mapping information between supported formats
doctrine:mapping:import Imports mapping information from an existing database
doctrine:mapping:info
doctrine:query:dql Executes arbitrary DQL directly from the command line
doctrine:query:sql Executes arbitrary SQL directly from the command line.
doctrine:schema:create Executes (or dumps) the SQL needed to generate the database schema
doctrine:schema:drop Executes (or dumps) the SQL needed to drop the current database schema
doctrine:schema:update Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata
doctrine:schema:validate Validate the mapping files

how set up symfony 3 doctrine migrations with multiple db?

I am struggling to have symfony/doctrine exclude db views when validating and updating schema.
I first tried without doctrine migrations ( see this question) but that did not work.
I found out that doctrine migrations would filter out views from validation/update and it actually does, so that step seems to work with migrations.
So, if one has just one db doctrine migrations will work fine, but the set up with multiple db is not clean cut, to say the least.
This is a known issue as you can see on this link. Unfortunately when attempting to follow the solutions described in the link the results are messy.
Even though the command migrations:update --em=default will indicate the correct database is set up, when generating migrations:diff --em=default it will mingle with other db and likewise with migrations:migrate --em=default which ends up creating tables on the other db.
More specifically the errors are:
- it will create the separate directories for the migrations files as indicated in the config files, but not to the corresponding em
- it will generate mysql queries mixing up the two em
- consequently it will update db
My set up is as follows:
config.yml
imports:
....
- { resource: doctrine_migrations_default.yml }
- { resource: doctrine_migrations_used.yml }
doctrine:
dbal:
default_connection: default
connections:
default:
.....
#schema_filter: "~^(?!view).*$~"
schema_filter: ~^(?!view_)~
used:
......
orm:
auto_generate_proxy_classes: '%kernel.debug%'
default_entity_manager: default
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: default
auto_mapping: true
mappings:
AppBundle: ~
used:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: used
mappings:
UsedBundle: ~
Then, the specific configuration files for migrations are:
doctrine_migrations_default.yml
doctrine_migrations:
dir_name: "%kernel.root_dir%/DoctrineMigrationsDefault"
namespace: App\DoctrineMigrationsDefault
table_name: migration_versions
name: Application_Migrations_Default
doctrine_migrations_used.yml
doctrine_migrations:
dir_name: "%kernel.root_dir%/DoctrineMigrationsUsed"
namespace: Used\DoctrineMigrationsUsed
table_name: migration_versions
name: Application Migrations Used
organize_migrations: false
This is one example of how it mixes up the configs. The database name is correct. It corresponds to the em=default. But other info are coming from the em=used
Thanks
php bin/console doctrine:migrations:status --em=default
== Configuration
>> Name: Application Migrations Used
>> Database Driver: pdo_mysql
>> Database Name: symfony_cars
>> Configuration Source: manually configured
>> Version Table Name: migration_versions
>> Version Column Name: version
>> Migrations Namespace: Used\DoctrineMigrationsUsed
>> Migrations Directory: /Users/BAMAC/Sites/Symfony1/app/DoctrineMigrationsUsed
>> Previous Version: Already at first version
>> Current Version: 0
>> Next Version: 2017-10-19 08:03:52 (20171019080352)
>> Latest Version: 2017-10-19 08:03:52 (20171019080352)
>> Executed Migrations: 0
>> Executed Unavailable Migrations: 0
>> Available Migrations: 1
>> New Migrations: 1
Also, if I try to specifically indicate the configuration file with:
php bin/console doctrine:migrations:status --em=default --configuration=./app/config/doctrine_migrations_default.yml
It will not recognize the file info, even though it does so when it gets the info directly from config.yml. The following error is thrown.
[Doctrine\DBAL\Migrations\MigrationException]
Migrations configuration key "doctrine_migrations" does not exists.
If I take the doctrine_migrations key out it will generate an error on the next info it encounters.
Don't import the migrations settings in your config.yml file.
Your individual configuration files aren't actually configured correctly which is why you are receiving the error about the configuration keys not existing. The keys are different than they are in the normal migrations config. I had to search the code to find the right settings. (I found them around ln35 of the AbstractFileConfiguration.php file)
Try these -
doctrine_migrations_default.yml
migrations_directory: "app/DoctrineMigrationsDefault"
migrations_namespace: App\DoctrineMigrationsDefault
table_name: migration_versions
name: Application_Migrations_Default
doctrine_migrations_used.yml
migrations_directory: "app/DoctrineMigrationsUsed"
migrations_namespace: Used\DoctrineMigrationsUsed
table_name: migration_versions
name: Application Migrations Used
organize_migrations: false #valid entries are false, 'year', and 'year_and_month'
doctrine_migrations, dir_name, and namespace are not valid entries for that configuration file.
Also, you can't use %kernel.root_dir% in your directory path but what worked for me was either changing it to 'app' or providing a full path.
Leaving this for future references:
The files doctrine_migrations_default.yaml and doctrine_migrations_used.yaml are for extra configurations to use when performing migrations across multiple entity managers.
These files should not be autoloaded by symfony, you can put them under config/ directly, not in config/packages where the doctrine_migrations.yaml is located.
I tested it on symfony 5.0.4 and it is working perfectly:
php bin/console doctrine:migrations:migrate --em=used --configuration=config/doctrine_migrations_used.yaml

How to delete Entity is generated from generate:doctrine:entity

I create an Entity by using commandline php app/console generate:doctrine:entity.
Now I want to delete that Entity(yml, schema..). I delete Doctrine yml file and Entity directory but when I use command line doctrine:schemal:create that always create Table which name = that Entity in Database?
To delete a generated entity, please delete the yml that contains the schema, which is located in BundleName/Resources/config/doctrine/entityName.orm.yml file. Then, delete the entityName.php in BundleName/Entities/ and clear the cache using
php app/console cache:clear
after removing the entity and clearing the cache try this command : doctrine:schema:update --force --complete

Categories