Symfony doctrine:schema:update not working - php

I have a strange problem :
I have an application symfony 2.3 (with sonata user)
I created a bundle with one entity - the entity was created without a problem
then I had to modify the entity and now it seems to be impossible to modify the schema :
To see what happens I increased all the string lengths with +1
The entity code (with annotations) :
namespace Too\ConfigAppBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* ConfigApp
*
* #ORM\Table(name="ConfigApp")
* #ORM\Entity(repositoryClass="Too\ConfigAppBundle\Entity\ActiviteRepository")
*/
class ConfigApp
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $nom
*
* #ORM\Column(name="nom", type="string", length=101, unique=true)
*/
private $nom;
/**
* #var string $nomSlug
*
* #Gedmo\Slug(fields={"nom"}, updatable=true, separator="_")
* #ORM\Column(name="nomSlug", type="string", length=101, nullable=true)
*/
private $nomSlug;
/**
* #var string $email
*
* #ORM\Column(name="email", type="string", length=151)
*/
private $email;
/**
* #var string $telephone
*
* #ORM\Column(name="telephone", type="string", length=16)
*/
private $telephone;
/**
* #var datetime $cree_le
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="cree_le", type="datetime")
*/
private $cree_le;
/**
* #var datetime $modifie_le
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(name="modifie_le", type="datetime")
*/
private $modifie_le;
...
Now see the result of :
php app/console doctrine:schema:update --dump-sql
CREATE TABLE ConfigApp (id INT AUTO_INCREMENT NOT NULL, nom VARCHAR(100) NOT NULL, nomSlug VARCHAR(100) NOT NULL, email VARCHAR(150) NOT NULL, telephone VARCHAR(15) NOT NULL, cree_le DATETIME NOT NULL, modifie_le DATETIME NOT NULL, PRIMARYKEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
None of the new length is taken in account :
for example the field nom should have length=101,
but the dump-sql gives nom VARCHAR(100) !
Could anyone try to figure out whats going wrong ?
Thanks !
EDIT :
I tried to clear the cache before with :
* php app/console doctrine:cache:clear-metadata
* php app/console cache:clear
* by deleting all content in cache folders
I also tried --dump-sql and --force.
This changes nothing at all.
Please any hint would be welcome !

I just ended up on the exact same issue: schema doesn't update.
Note that --force returns exactly the same thing as --dump-sql, the only difference is that --force runs the SQL against the database.
Although, in my case, the issue wasn't because of the .orm.xml file. It was because I've set this in the config_dev.xml:
doctrine:
orm:
metadata_cache_driver:
type: memcached
host: localhost
port: 11211
instance_class: Memcached
query_cache_driver:
type: memcached
host: localhost
port: 11211
instance_class: Memcached
result_cache_driver:
type: memcached
host: localhost
port: 11211
instance_class: Memcached
Even when I issue an often salvatory:
php app/console cache:clear
the memcached data isn't flushed. So I had to restart memcached, then everything was up and running again!
So thanks for your question, it led me to the right spot in my case.
UPDATE: as Phil suggested above, running this command does the trick too:
php app/console doctrine:cache:clear-metadata

It is possible that you forget to enable Doctrine auto mapping;
orm:
#auto_mapping: true
If auto mapping is disabled (or commented like above) , you should register Entities of each bundle manually.
orm:
entity_managers:
default:
mappings:
AcmeHelloBundle: ~

Try to use YAML instead of the default annotation when you run
php app/console doctrine:generate:entity
Or instead of running
app/console doctrine:schema:update --force
You can just manually create your MySql table which is a very tedious task

I found the solution :
I did not see before but there was a doctrine folder in src\Too\ConfigAppBundle\Resources\config containing a file called ConfigApp.orm.yml :
Too\ConfigAppBundle\Entity\ConfigApp:
type: entity
table: null
repositoryClass: Too\ConfigAppBundle\Entity\ConfigAppRepository
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
nom:
type: string
length: '100'
nomSlug:
type: string
length: '100'
email:
type: string
length: '150'
telephone:
type: string
length: '15'
cree_le:
type: datetime
length: null
modifie_le:
type: datetime
length: null
lifecycleCallbacks: { }
I deleted this folder and now updating the schema works again.
Surely I did something to generate this doctrine folder but I don't know what it was - if someone could tell me how this stuff is generated - and why ?

Though some of the answers given by #rai and others are correct, one more suggestion for Symfony version is equal to or above 3.0 please use bin/console instead app/console, as shown below,
bin/console doctrine:schema:update --force

i think its beacause of the doctrine:mapping:import command. This command stores the schema of an existing database into .orm.xml files. Probebly you execute this command.
I had the same issue, coast me a lot of time to find out.

Because I was using .orm.yml-mapping I had the issue that I created the doctrine-folder, in which the yml mappings were present, under the wrong path, so I fixed it by moving the doctrine-folder to the the config folder:
...\BundleName\Resources\config\doctrine\MyEntity.orm.yml

Try
php app/console doctrine:schema:update --force
this is update your database schema with entity

Type php app/console help doctrine:schema:update in CLI
--dump-sql Dumps the generated SQL statements to the screen (does no
t execute them).
...
--force Causes the generated SQL statements to be physically exec
uted against your database.
So try the --force instead of --dump-sql.
And here is the command for cache clearing :
php app/console cache:clear
Don't forget to use the help keyword before a command namespace in order to get the help message for that command.
Hope it helps

Related

ULID is falsely stored as UUID in database (vanilla symfony app)

Yesterday I tried to do what Symfony shouted out in some blog post (https://symfony.com/blog/new-in-symfony-5-2-doctrine-types-for-uuid-and-ulid) but failed hard. I want to store ULID (format "TTTTTTTTTTRRRRRRRRRRRRRRRR") in the database because they are not only sorteable but also contain a timestamp which is just perfect for my application. But when I tell a property to be "type=ulid" then it is stored as UUID (format: "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx") in the database.
I debugged half day long and got so annoyed by this that I started from scratch and still the problem exists.
Where did I go wrong?
(skip to the ULID heading if you like, the following may look long but 50% of it is just basic stuff)
Symfony
The thing I do over and over again taken from https://symfony.com/doc/5.4/setup.html :
stat shyt # does not exist
composer create-project symfony/skeleton:5.4.* shyt
cd shyt; composer require webapp
Do you want to include Docker configuration from recipes? YES (default)
bin/console about shows Symfony Version 5.4.10 and PHP 7.4
ORM
Taken from https://symfony.com/doc/5.4/doctrine.html :
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle
docker-compose up -d
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network
So I add some lines to the docker-compose.override.yml file:
networks:
default:
ipam:
config:
- subnet: 10.1.2.1/24
services:
database:
# [...] doctrine/doctrine-bundle stuff [...]
networks:
default:
ipv4_address: 10.1.2.3
In ".env" set DATABASE_URL for the host "10.1.2.3"
bin/console doctrine:database:create (silly but as documented)
Could not create database "app" for connection named default
An exception occurred while executing a query: SQLSTATE[42P04]: Duplicate database: 7 ERROR: database "app" already exists
Well, yes. Docker already did this.
The make:entity is postponed until we have ULID capabilities.
ULID
We already lean into https://symfony.com/doc/5.4/components/uid.html (especially section ULIDs) :
composer require symfony/uid
bin/console make:entity Product
"someProperty" as "ulid" not nullable
Inspect the Product entity
Looks almost like in the documentation except it has an additional field (the primary key, an integer) and some getter/setter.
bin/console make:migration
Test the ULID entity
In between we use tests to programatically create a DB entry:
composer require phpunit to programatically create a database entry
bin/console --env=test doctrine:migrations:migrate
bin/console --env=test doctrine:database:create
The file "tests/FooTest.php" contains:
<?php
namespace App\Tests;
use App\Entity\Product;
use App\Repository\ProductRepository;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Uid\Ulid;
class FooTest extends KernelTestCase
{
public function testFoo(): void
{
$product = new Product();
$product->setSomeProperty(new Ulid());
static::assertNotNull($product->getSomeProperty());
self::getContainer()->get(ProductRepository::class)
->add($product);
self::getContainer()->get('doctrine.orm.entity_manager')
->flush();
}
}
bin/console --env=test doctrine:query:sql 'TRUNCATE product' just to be sure
bin/phpunit
bin/console --env=test doctrine:query:sql 'SELECT * FROM product'
A UUID is shown instead of a ULID.
Shows ULID instead of UUID in the database
Using ULID as Primary Key
First clean up a bit then do the example shown in https://symfony.com/doc/5.4/components/uid.html#ulids :
rm migrations/* to start again
bin/console --env=test doctrine:database:drop --force
bin/console --env=test doctrine:database:create
bin/console doctrine:database:drop --force
bin/console --env=test doctrine:database:create
Edit "src/Entity/Product.php" to only contain the second ULID example from the documentation:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Ulid;
use App\Repository\ProductRepository;
/**
* #ORM\Entity(repositoryClass=ProductRepository::class)
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="ulid", unique=true)
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class="doctrine.ulid_generator")
*/
private $id;
public function getId(): ?Ulid
{
return $this->id;
}
// ...
}
(example from documentation was missing the repository line)
bin/console make:migration
bin/console --env=test doctrine:migrations:migrate
Test is now a bit simpler:
public function testFoo(): void
{
self::getContainer()->get(ProductRepository::class)
->add(new Product());
self::getContainer()->get('doctrine.orm.entity_manager')
->flush();
}
bin/phpunit (Risky is ok)
bin/console --env=test doctrine:query:sql 'SELECT * FROM product'
Again those UUID instead of ULID
Database shows UUID instead of ULID
It's bit late but for anyone whom facing this issue, I too have the database showing UUID instead of ULID and it seems to be the expected behavior from doctrine since you can use UUID/ULID interchangeably meaning even if you have UUID stored in the database but your entity is mapped on ULID you will have an ULID when retrieving the object from the database, also you can retrieve your same object by using ULID or UUID.
so for instance I have a User entity having ULID for its identifier so the stored object will have uuid as below :
018477e6-eebc-164c-12e3-22ca8f1a88f3 myemail#mail.com []
if I retrieve my user with that UUID I'll get :
App\Entity\User {#430 ▼
-id: "01GHVYDVNW2S615RS2SA7HN27K"
-email: "myemail#mail.com"
-roles: []
#createdAt: DateTime #1668458933 {#423 ▶}
#updatedAt: DateTime #1668458998 {#428 ▶}
-password: "$2y$13$/2i9Ovc2lCQBRfSVgsnmoul1FhF.Kyki3irF6GQvrMrjacQX6ees6"
-isVerified: true
}
now if you use that ULID to retrieve your user it will work too !
going further if you inspect that UUID you'll see that the returned object has that uuid converted to base 32 :
bash-5.1$ bin/console uuid:inspect 018477e6-eebc-164c-12e3-22ca8f1a88f3
----------------------- --------------------------------------
Label Value
----------------------- --------------------------------------
Version 1
toRfc4122 (canonical) 018477e6-eebc-164c-12e3-22ca8f1a88f3
toBase58 1BsMRvKcgozP4Kw2m4Fb1C
toBase32 01GHVYDVNW2S615RS2SA7HN27K
----------------------- --------------------------------------
and finally you can get that stored uuid by converting it to refc4122 as you can see below:
bin/console ulid:inspect 01GHVYDVNW2S615RS2SA7HN27K
---------------------- --------------------------------------
Label Value
---------------------- --------------------------------------
toBase32 (canonical) 01GHVYDVNW2S615RS2SA7HN27K
toBase58 1BsMRvKcgozP4Kw2m4Fb1C
toRfc4122 018477e6-eebc-164c-12e3-22ca8f1a88f3
---------------------- --------------------------------------
Time 2022-11-14 20:48:53.948 UTC
---------------------- --------------------------------------
I'm not sure why doctrine doesn't just store the ULID but its current behavior is not blocking you from using ULID in your project.
Hope this help !
I'm trying out the ULID as well and followed the same documentation (https://symfony.com/blog/new-in-symfony-5-2-doctrine-types-for-uuid-and-ulid). I noticed you did one thing different in your code compared to the documentation.
In the entity change:
* #ORM\CustomIdGenerator(class="doctrine.ulid_generator")
to
* #ORM\CustomIdGenerator(class=UlidGenerator::class)
And add the following
use Symfony\Bridge\Doctrine\IdGenerator\UlidGenerator;
This should the make the ULID work.
The dump of this would be something like this (sorry this is a dump in the console as I was testing the ulid, but I hope it gives you the information you need):
^ Symfony\Component\Uid\Ulid^ {#842
#uid: "01G7MCSCANWA2XXZ1NT1TZV6KQ"
toBase58: "1BoCbKTaPcpbAuQVieEW54"
toRfc4122: "0181e8cc-b155-e285-defc-35d075fd9a77"
time: "2022-07-10 15:48:57.813 UTC"
}
In the database it looks as followed:
Ulid in mariaDB
I hope this helps.

NelmioApiDocBundle not generate documentation

I want to use NelmioApiDocBundle for generating documentation automatically. I fallowed standard Symfony doc to install and configure it: https://symfony.com/doc/current/bundles/NelmioApiDocBundle/index.html. Unfortunately when I go to /api/doc my doc is empty.
I use Symfony 3.4 and NelmioApiDocBundle in v. 3.2.0.
Here is my config:
nelmio_api_doc:
areas:
path_patterns: # an array of regexps
- ^/api(?!/doc$)
host_patterns:
- ^api\.
documentation:
host: 127.0.0.1
schemes: [http, https]
info:
title: Thanatos API
description: This is documentation of Thanatos
version: 1.0.0
security:
- Bearer: []
And annotations in my controller (in beginning I want to see any data in my documentation):
/**
* #Route(
* "/",
* name="thanatos_dashboard_index",
* )
*
* #SWG\Response(
* response=200,
* description="Returns the rewards of an user",
* #SWG\Schema(
* type="array",
* #SWG\Items(ref=#Model(type=Reward::class, groups={"full"}))
* )
* )
* #SWG\Parameter(
* name="order",
* in="query",
* type="string",
* description="The field used to order rewards"
* )
* #SWG\Tag(name="rewards")
* #NelmioSecurity(name="Bearer")
*/
public function indexAction()
{
return $this->render("#AppThanatos/Dashboard/index.html.twig");
}
In /api/doc I see "No operations defined in spec!". What am I doing wrong?
#UPDATE
I just start to use Sami: http://symfony.com/projects/sami
I've the same problem. Working on my Mac I have always ERR_EMPTY_RESPONSE (using Chrome) but in the production environment the same configuration works fine.
The only difference was Xdebug, I've tried disabling the module and now everything works.
The assets normally are installed by composer if any command event (usually post-install-cmd or post-update-cmd) triggers the ScriptHandler::installAssets script. If you have not set up this script, you can manually execute this command:
php bin/console assets:install --symlink
Try this :
Replace
* #Route(
* "/",
* name="thanatos_dashboard_index",
* )
By
#Rest\Get("/getVehicles")
And, in your action controller, return array or object like this :
$em = $this->getDoctrine();
return $em->getRepository('AppBundle:Vehicle')->findAll();

Doctrine MappingException with message 'The target-entity Entity\\ItemsBags cannot be found in 'Entity\\Players#itemsBag'

Good day. I'm already on my second day and I can not understand what's the matter ... I get the error in runtime:
PHP Fatal error: Uncaught exception
'Doctrine\ORM\Mapping\MappingException' with message 'The
target-entity Entity\ItemsBags cannot be found in
'Entity\Players#itemsBag'.' in
/var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php:762
Stack trace:
#0./var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php(1028):
Doctrine\ORM\Mapping\MappingException::invalidTargetEntityClass('Entity\\ItemsBag...',
'Entity\\Players', 'itemsBag')
#1./var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(272):
Doctrine\ORM\Mapping\ClassMetadataInfo->validateAssociations()
#2./var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(251):
Doctrine\ORM\Mapping\ClassMetadataFactory->validateRuntimeMetadata(Object(Doctrine\ORM\Mapping\ClassMetadata),
NULL)
#3./var/www/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(332):
Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadM in
/var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php
on line 762
When I check the doctrine, and the update, everything goes well:
root#comp:# php vendor/bin/doctrine orm:schema:update --force Updating
database schema... Database schema updated successfully! "4" queries
were executed
root#comp:# php vendor/bin/doctrine orm:validate-schema [Mapping] OK
- The mapping files are correct. [Database] OK - The database schema is in sync with the mapping files.
I tried to clear the cache, delete the proxy and regenerate them, but nothing produced results ...
root#comp:# php vendor/bin/doctrine orm:clear-cache:metadata
Clearing ALL Metadata cache entries
Successfully deleted cache entries.
root#comp:# php vendor/bin/doctrine orm:clear-cache:query
Clearing ALL Query cache entries
Successfully deleted cache entries.
root#comp:# php vendor/bin/doctrine orm:clear-cache:result
Clearing ALL Result cache entries
Successfully deleted cache entries.
root#comp:# php vendor/bin/doctrine orm:generate-proxies
Processing entity "Entity\Objects"
Processing entity "Entity\Weapons"
Processing entity "Entity\ItemsBags"
Processing entity "Entity\Players"
Processing entity "Entity\Translations"
Processing entity "Entity\Worlds"
Processing entity "Entity\Tiles"
Processing entity "Entity\WorldStructures"
Proxy classes generated to "/tmp"
Players.php
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
*
* #Entity
* #Table(name="players")
*
*/
class Players{
...
/**
* #var ItemsBags
*
* #OneToOne(targetEntity="ItemsBags", mappedBy="player")
*/
private $itemsBag;
...
}
ItemsBags.php
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
*
* #Entity
* #Table(name="item_bags")
*
*/
class ItemsBags{
...
/**
* #var Players
*
* #OneToOne(targetEntity="Players", inversedBy="itemsBag")
* #JoinColumn(name="player_id", referencedColumnName="id")
*/
private $player;
...
}
Tell me please, what am I doing wrong?
Thanks to #Sarcoma. I just forgot to specify autoload section in my composer.json
"autoload": {
"psr-4": { "": "core/" }
},
P.S Can enyone me tell, why my project running normal before?) Before I too have many entinties, no have that section in my composer.json, but all works fine.

Symfony2 doctrine:schema:update keeps updating

I've just added a new attribute in my model:
/**
* #ORM\Column(name="has_donation", type="boolean", options ={"default":false})
*/
private $hasDonation;
And then I tried running:
php app/console doctrine:schema:update --force
which gave me the following result:
Updating database schema...
Database schema updated successfully! "1" queries were executed
The problem is that each time I run the schema:update command, I get the same result - without making any changes to my entities. Any idea why? Thanks!
Update
Here's the out for php app/console doctrine:schema:update --dump-sql:
ALTER TABLE Clinic CHANGE has_donation has_donation TINYINT(1) DEFAULT '0' NOT NULL;
I can assume that this issue arises because of usage of illegal or irrelevant mapping information.
In case of the question author, the option "default":false was illegal.
I had same issue with code:
/**
* #ORM\Column(
* type="boolean",
* nullable=false,
* options={"unsigned":true, "comment":"Is file uploaded manually?"}
* )
*/
protected $manual = false;
In my case the option "unsigned":true was irrelevant. After removing this option, I got the code working.
First, try deleting cache.
Then, try php app/console doctrine:schema:update --dump-sql to see what updated.
These options with "default": false differences are not recorded sometimes. At least on PostgreSQL we use.
You might need them to run them manually.
Tip from our workflow:
1) we setup entities
2) then run php app/console doctrine:schema:update --force
3) then run migrations that add there details that are not transformed to database

Doctrine2 Duplicate key name error

I'm trying to use doctrine2 migration and schema update with symfony2's console. All my entities are being generated with no problems via:
php app/console doctrine:generate:entities myProject
Also, I am able to create my database and build my schema from scratch with no problems given the following commands:
php app/console doctrine:database:create
php app/console doctrine:schema:create
Whenever I modify, remove, or add in another entity, I always regenerate my entities with:
php app/console doctrine:generate:entities myProject
The problem however, is whenever I want to update my schema I always get the following error:
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'CREATE INDEX IDX_F7129A80A76ED395 ON
user_user (user_id)':
SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name
'IDX_F7129A80A76ED395'
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name
'IDX_F7129A80A76ED395'
I have tried doing:
php app/console doctrine:schema:update --force
or
php app/console doctrine:migrations:diff
php app/console doctrine:migrations:migrate
But I always get the same error. What am I doing wrong? Is there any way for me to update my database without having to destroy and build a whole new one every time? I have over 25 entities which consist of large files with many associative mappings (OneToOne, OneToMany, ManyToMany,.. etc) which seems to be causing problems. Any help would be great! Thanks!
On a side note I have a feeling that this piece of code might be causing the problem:
/**
* #ORM\ ManyToMany(targetEntity="User", inversedBy="myFriends")
*/
protected $friendsWithMe;
/**
* #ORM\ ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
* #ORM\ JoinTable(name="friends",
* joinColumns={#ORM\ JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\ JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
**/
protected $myFriends;
In my user entity, I wanted to build a self-referencing many to many relationship. This is how I'm building out a friends list. Maybe there is something wrong with my logic, but I took this directly off from the doctrine2 documentation on associative mapping.
Not sure it is the cause of the Exception, but there is an error in your ORM mapping. $myFriends is the owning side, $friendsWithMe is the inverse side, so inversedBy attribute should be only present on $friendsWithMe.
Try to rewrite $myFriendswith mappedBy attribute :
/**
* #ORM\ ManyToMany(targetEntity="User", mappedBy="friendsWithMe")
* #ORM\ JoinTable(name="friends",
* joinColumns={#ORM\ JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\ JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
**/
protected $myFriends;

Categories