Unknown column type when generating schema - exception

I am developing an application using Symfony2 and Doctrine, the problem comes when
I try to create tables for Role and User Entities using php app/console doctrine:schema:update --force, the relation is ManyToMany and although the mapping information, the annotations, seem to be correct it throws the following exception:
[Doctrine\DBAL\DBALException] Unknown column type role requested
What can I do? Thank you very much.

You probably have a annotation like this:
/**
* #Column(type="role")
*/
protected $role;
This is a problem, because Doctrine doesn't know of any type named role.
I have to say that this is an assumption because you haven't posted any code...

Related

Laravel: Unknown column type "timestamp" requested

I am trying to perform a migration and I am getting the following problem.
Unknown column type "timestamp" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database introspection then you might have forgotten to register all database types for a Doctrine Type. Use AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMappedDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot some mapping information.
My code is the following:
Schema::table('XXXXXXXX', function (Blueprint $table) {
$table->timestamp('start')->change();
$table->timestamp('end')->change();
});
The strange thing is that I have already performed migrations with that type of data:
Schema::create('XXXXXX', function (Blueprint $table) {
...
$table->timestamp('date_expired')->nullable();
...
});
Does anyone know how to fix it or see the error I'm doing.
Thanks
UPDATE
In the end I have deleted the migration, I have modified it putting timestamp in the necessary columns and I have executed it again. (Having deleted the table before from the database)
On the laravel docs page you can find a warning telling you that there are certain types that you can't use with the ->change() method.
Link to laravel docs
It also says this:
To modify a timestamp column type a Doctrine type must be registered.

(1054, "Unknown column '' in 'field list'")

I know this question has been asked a couple of time but no previous answer was able to solve my problem.
I had a perfectly working model in Django that looked like this:
class Template(models.Model):
mat = models.CharField(max_length=50, null=True)
...
I had many instances of this model and up to now I was very happy with it. I recently decided that instead of a Charfield, this model was better suited to work with a ForeignKey in this position instead.
To get into details, the attribute ''mat'' was previously only referring to the name of another object instance. I decided to change it to the full fledged instance with a ForeignKey instead, like it should have always been. Therefore, the model was modified as follows:
class Template(models.Model):
mat = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='mat_stock', verbose_name="mat", null=True)
...
I followed this change with the regular */manage.py makemigrations, */manage.py migrate. While these two commands worked, I was unable to select any instance of Template in the shell without raising the following error:
OperationalError: (1054, "Unknown column 'myapp_template.mat_id' in 'field list'")
Similar situations I encountered were solved by manually adding a column in SQL with the following line:
ALTER TABLE database.myapp_template ADD mat INT;
Unfortunately this did not solve my problem.
I figured maybe the problem was that I already had instances of my object that had character values in the ''mat'' column. Django would expect integer values (specifically "id") after my migration, so I decided to create a completely new attribute for Template as follows:
class Template(models.Model):
pos_mat = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='mat_stock', verbose_name="mat", null=True)
...
This, I thought, would delete (or disregard) the "mat" column and create new "pos_mat" columns with the desired properties without having to handle old character values that wouldn't fit with the requirements. From there on it should be like adding a completely new ForeignKey attribute.
After the required and successful */manage.py makemigrations, */manage.py migrate I am still unable to access an instance of my model in the shell. I still get the same unpleasing:
OperationalError: (1054, "Unknown column 'myapp_template.mat_id' in 'field list'")
Would anybody know how to convince Django to go along with my changes? I am skeptical that rolling back migrations to zero will help me (it did not solve my problems in the past) and I hope it will not come to the deletion of my data. It is acceptable for my model to have an empty field in this column since I added a null=True to my attribute.
Thank you very much for your help. Have a good day.
I have solved my problem by rolling back to my last stable migration. From there I was able to migrate a model where 'mat' was absent and 'pos_mat' was the only attribute. This means my problem arose in the first migration from the old version of 'mat' to the new version of 'mat'. Basically keeping the same name but changing the attribute characteristics is a no go. I hope those with the same problem will be able to fix it with this.

JPA Hibernate - Multiple Database Dialects and nvarchar(length) data type

I have to do a project using JPA + Hibernate in which I'm using 3 dialects: MySQL5InnoDBDialect, MSSQL2012Dialect and Oracle12cDialect.
Right now I have a specification which is telling me that for some column from:
Oracle database, I have to use NVARCHAR2(LENGTH) data type
MySql database, I have to use VARCHAR(LENGTH) data type
MSSQL database, I have to use NVARCHAR(LENGTH) data type
... and here is my problem..
If I use:
#Column(name="columnName" length = 255)
private String columnName;
hibernate generates varchar(255) and this is good just for MySQL
If I use:
#Column(name="columnName", columnDefinition="nvarchar2(255)")
private String columnName;
it's not possible in MySQL, i get error because of columnDefinition, but in oracle is okay
I tried to customize MySQL dialect creating
public class CustomMySQL5InnoDBDialect extends MySQL5InnoDBDialect{
public CustomMySQL5InnoDBDialect() {
super();
registerColumnType(Types.NVARCHAR, "nvarchar2($l)");//$l not $1
registerHibernateType(Types.NVARCHAR, StandardBasicTypes.STRING.getName());
}
}
and giving this class in hibernate configuration for MySQL dialect.
I have the same problem in MySQL if I'm using columnDefinition property.
Can you help with this problem please?
The solution is to make use of the feature that the JPA API spec provides you with for just this situation. Define a file orm.xml for each datastore that you need to support, and enable the requisite one when using each database. See this link for details of the file format. That way you don't need to think about hacking the internal features of whichever JPA provider you are using, and you also retain JPA provider portability, as well as database portability
The idea of putting schema specific information info (static) Java annotations is an odd one, even more so when wanting database portability.

Automatically generated Entities from mysql database in Netbeans always fail to deploy

I am new to Java EE (and to Netbeans). I have am trying to automatically generate entity classes from my mysql database... For simple relationships it works, but for the following it always fails:
i get the following error:
Internal Exception: Exception [EclipseLink-7220] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The #JoinColumns on the annotated element [field tblExpandituresTranx] from the entity class [class entities.restaurant.TblContents] is incomplete. When the source entity class uses a composite primary key, a #JoinColumn must be specified for each join column using the #JoinColumns. Both the name and the referencedColumnName elements must be specified in each such #JoinColumn.. Please see server.log for more details.
I think... I have some error in my database or perhaps EclipseLink JPA tool is kaput!
please help!
Could be that your schema is upside down.
Or you could actually read the exception you're getting and figure out what it's telling you:
The #JoinColumns on the annotated element [field tblExpandituresTranx] from the entity class [class entities.restaurant.TblContents] is incomplete. When the source entity class uses a composite primary key, a #JoinColumn must be specified for each join column using the #JoinColumns. Both the name and the referencedColumnName elements must be specified in each such #JoinColumn
Looks like you've got an incomplete specification for the JOIN.
I solved the problem myself...
Apparently JPA has a problem with multiple primary keys in bridge tables. So, instead of having foreign keys as primaries I just converted them to unique indexed and everything worked just fine!! wuhu!!

Unable to create table in MySQL using Doctrine and Symfony2

I am working with Symfony2 and Doctrine ORM using MySql .
After creating an Entity, I am not able to create the table. It throws an exception.
anu#anu-bridge:/var/www/Symfony$ php app/console doctrine:schema:update --force --dump-sql
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'product' already exists.
doctrine:schema:update [--complete] [--dump-sql] [--force] [--em[="..."]]
I tried to drop it , but still it throws the error.
anu#anu-bridge:/var/www/Symfony$ php app/console doctrine:schema:drop --force
Dropping database schema...
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'product' already exists.
doctrine:schema:drop [--dump-sql] [--force] [--full-database] [--em[="..."]]
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'product' already exists.
There is no tables in the database. Cleared all the cache for symfony and doctrine, but still the error is throwing.
Symfony2 version is 2.0.1 .
I've had a similar problem. Most likely you have two entities named Category inside different Bundles. For instance:
src/Acme/SomeBundle/Entity/Product.php
src/Acme/OtherBundle/Entity/Product.php
Comment one of these files and retry the console command.
I was getting this problem from a conflict with join table defined in an association class annotation and a join table defined in a ManyToMany annotation.
The mapping definitions in two entities with a direct ManytoMany relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.
The explanation and solution was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the Associative Entity class. There is an example provided in this forum post Association models with extra fields:
public class Person
{
/**
* #OneToMany(targetEntity="AssignedItems", mappedBy="person")
*/
private $assignedItems;
}
public class Items
{
/**
* #OneToMany(targetEntity="AssignedItems", mappedBy="item")
*/
private $assignedPeople;
}
public class AssignedItems
{
/**
* #ManyToOne(targetEntity="Person")
* #JoinColumn(name="person_id", referencedColumnName="id")
*/
private $person;
/**
* #ManyToOne(targetEntity="Item")
* #JoinColumn(name="item_id", referencedColumnName="id")
*/
private $item;
}
I got this error when editing my Product.orm.yml file.
I added a new manyToMany relation with a Category entity, and made a mistake on the joinTable line :
manyToMany:
categories:
targetEntity: Acme\ProductBundle\Entity\Category
inversedBy: products
joinTable:
name: Product # My mistake: joinTable should be something like ProductCategory
[...]
Indeed it's a silly error, I share anyway.
If you can, you can do this as this worked for me:
Drop the entire database:
app/console doctrine:schema:drop --force --full-database
Run all DB migrations:
app/console doctrine:migrations:migrate
I imagine It can happen quite often when copying entities. In my case it was a ORM table name annotation that was misfortunately duplicated.
/**
* #ORM\Entity()
* #ORM\Table(name="category")
* */
class Category {
I had this problem with an One-To-Many, Unidirectional with Join Table relation like (see doctrine doc). I did not find this error case with this relation type through the internet or stackoverflow, so i post here my solution for let help others with the same problem.
What caused this problem:
After reverse engineering the legacy db tables with ORM (see doc "How to Generate Entities from an Existing Database"), all tables also only join tables recieved an entity PHP class.
With annotations on a category entity i described the joining. Results this code:
/**
* #ORM\ManyToMany(targetEntity="Category")
* #ORM\JoinTable(name="category_child",
* joinColumns={#JoinColumn(name="category_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="category_child_id", referencedColumnName="id")}
* )
*/
public $children;
The #ORM\JoinTable(name="category_child" caused that doctrine wants to create this table again. One time because of the already existing Category_Child entity, and then the #ORM\JoinTable expression that points to the same table.
Solution
Solution was to delete the Category_Child entity that was created from reverse engineering. If you used Category_Child entity in some $em queries, you have to select those datas othwerwise. E.g. Through the parent that holds those child datas in an ArrayCollection, or over DBAL.