Expected known function, got 'MD5' - symfony

I need to do a search like this:
//Project\MyBundle\Repository
$query = $this->getEntityManager()->getRepository('ProjectMyBundle:Product')->createQueryBuilder('p')
->where('MD5(p.id) = :id')
->setParameter('id', $id )
->getQuery()
->getSingleResult();
I get the id on MD5 and have to search for an id on MD5 in the database.
When I do a search, I showed up, gives me the following error:
[Syntax Error] line 0, col 51: Error: Expected known function, got 'MD5'
Indicated that lib:
https://github.com/beberlei/DoctrineExtensions/blob/master/lib/DoctrineExtensions/Query/Mysql/Md5.php
But I've put it inside the folder and now I need to know where it should matter.
I am using MySQL, Doctrine 2.2 in Symfony 2.1.6.

You'll need to register MD5 as a custom DQL function:
# app/config/config.yml
doctrine:
orm:
# ...
entity_managers:
default:
# ...
dql:
string_functions:
MD5: Acme\HelloBundle\DQL\MD5Function
For more info, see: http://symfony.com/doc/2.0/cookbook/doctrine/custom_dql_functions.html

Related

Empty result for Doctrine using Entity and Repository folder - migration from Symfony 3.4 to 4.4

I'm working in app upgrade from symfony 3.4 to 4.4.
But I'm having an issue with the query selects, I'm not sure why the result is always empty:
return $this
->_em
->createQuery('SELECT u FROM App\Entity\InternalUsers u')
->getResult();
Result: Array ( )
Using with getRepository:
$user = $this
->getDoctrine()
->getRepository(InternalUsers::class)
->validate($this->_getFilterParams(), $this->getParameter('ENCRYPTION_KEY'));
print_r($user);
Result: Array ( )
Validate function is inside InternalUserRepository
<?php
namespace App\Repository;
use CoreBundle\DoctrineExtensions\Paginate\Paginate;
use CoreBundle\Utils\Validate;
use App\Repository\BaseRepository;
use App\Entity\InternalUsers;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
/**
* Internal Users
* Controls DB operations of internal users.
*/
class InternalUserRepository extends ServiceEntityRepository {
/**
*
* #var type
*/
protected $InternalUsers;
public function __construct(ManagerRegistry $registry) {
parent::__construct($registry, InternalUsers::class);
}
/**
* Validate credentias.
*
* #param array $userData User creteria.
* #param string $encryptionKey Entrypt key.
*
* #return type
*/
public function validate(array $userData, string $encryptionKey) {
$criteria = [
'username' => $userData['username'],
'password' => sha1($encryptionKey . $userData['password'])
];
$user = $this->findOneBy($criteria);
var_dump($user); // NULL
if ($user) {
return $user;
}
}
It's using my cli:
$ php bin/console doctrine:query:dql "SELECT cat FROM App\Entity\InternalUsers cat"
array(0) {
}
I've a supposition with the ORM manually adjusted:
orm:
auto_generate_proxy_classes: '%kernel.debug%'
default_entity_manager: default
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
# alias: App
# AppBundle:
# is_bundle: false
# type: annotation
# dir: '%kernel.project_dir%/src/AppBundle/Entity'
# prefix: 'AppBundle\Entity'
# alias: AppBundle
App\Entity\:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/'
prefix: 'App\Entity\'
alias: App\Entity\
But I'm still not getting results, I've almost 2 days working on this issue and there is no answer after investigating and reading the documentations.
It was another try, but there were no results as well.
orm:
auto_generate_proxy_classes: '%kernel.debug%'
default_entity_manager: default
entity_managers:
default:
auto_mapping: true
metadata_cache_driver:
type: 'service'
id: doctrine.cache.memcached
query_cache_driver:
type: 'service'
id: doctrine.cache.memcached
result_cache_driver:
type: 'service'
id: doctrine.cache.memcached
dql:
string_functions:
STRING_AGG: GalleryCore\CoreBundle\DoctrineExtensions\DQL\StringAgg
Here an update!
It looks like related to type of Entity mapping.
After configuring the doctrine.orm.
orm:
auto_generate_proxy_classes: '%kernel.debug%'
#default_entity_manager: default
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
#entity_managers:
#default:
#metadata_cache_driver:
# type: 'service'
# id: doctrine.cache.memcached
#query_cache_driver:
# type: 'service'
# id: doctrine.cache.memcached
#dql:
# string_functions:
# STRING_AGG: GalleryCore\CoreBundle\DoctrineExtensions\DQL\StringAgg
#connection: default
#naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
# alias: App
# AppBundle:
# is_bundle: false
# type: annotation
# dir: '%kernel.project_dir%/src/AppBundle/Entity'
# prefix: 'AppBundle\Entity'
# alias: AppBundle
#App\Entity:
#is_bundle: false
#type: annotation
#dir: '%kernel.project_dir%/src/Entity'
#prefix: 'App\Entity'
#alias: App
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/'
prefix: 'App\Entity'
alias: App
I ran this command:
php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity
to generate the entities correctly in my src/Entity folder
output:
$ php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity
Importing mapping information from "default" entity manager
> writing src/Entity/Bonsai.trackSites.php
> writing src/Entity/Gallery.adTagTypes.php
> writing src/Entity/Gallery.albumAssets.php
> writing src/Entity/Gallery.appUrls.php
> writing src/Entity/Gallery.adTags.php
> writing src/Entity/Bonsai.trackAssettypes.php
> writing src/Entity/Bonsai.trackViews.php
> writing src/Entity/Bonsai.trackVisitors.php
> writing src/Entity/Gallery.apps.php
> writing src/Entity/Gallery.adGptTags.php
> writing src/Entity/Gallery.appConfigurations.php
> writing src/Entity/Gallery.appFeatures.php
> writing src/Entity/Gallery.appUrlTypes.php
> writing src/Entity/Gallery.assetFlags.php
> writing src/Entity/Gallery.assetTypes.php
> writing src/Entity/Gallery.assetVotes.php
> writing src/Entity/Gallery.assets.php
> writing src/Entity/Gallery.assetsKeywords.php
> writing src/Entity/Gallery.exifValues.php
> writing src/Entity/Gallery.comments.php
> writing src/Entity/Gallery.exifFields.php
> writing src/Entity/Gallery.domains.php
> writing src/Entity/Gallery.countries.php
> writing src/Entity/Gallery.featuredAssetsData.php
> writing src/Entity/Gallery.fieldValues.php
> writing src/Entity/Gallery.jobsQueue.php
> writing src/Entity/Gallery.regions.php
> writing src/Entity/Gallery.indexJobs.php
> writing src/Entity/Gallery.keywords.php
> writing src/Entity/Gallery.externalValues.php
> writing src/Entity/Gallery.releaseDates.php
> writing src/Entity/Gallery.requestTypes.php
> writing src/Entity/Gallery.responseLogs.php
> writing src/Entity/Gallery.userRoles.php
> writing src/Entity/Gallery.trendingConfiguration.php
> writing src/Entity/Gallery.votesConfiguration.php
> writing src/Entity/Bonsai.trackAssets.php
> writing src/Entity/Gallery.internalUsers.php
> writing src/Entity/Gallery.commentFlags.php
> writing src/Entity/Gallery.verticals.php
> writing src/Entity/Gallery.fields.php
> writing src/Entity/Gallery.fieldTypes.php
> writing src/Entity/Gallery.imageTags.php
> writing src/Entity/Gallery.internalCategories.php
> writing src/Entity/Gallery.sitesConnections.php
> writing src/Entity/Gallery.threadAssets.php
> writing src/Entity/Gallery.trendingCriterias.php
> writing src/Entity/Gallery.trendingFormulaDetails.php
> writing src/Entity/Gallery.trendingFormulas.php
> writing src/Entity/Gallery.userSettings.php
> writing src/Entity/Gallery.userVariables.php
> writing src/Entity/AdGptTags.php
after made a couple of adjustments:
$user = $this
->getDoctrine()
->getRepository(InternalUsers::class)
->findOneBy(
$criteria = [
'username' => $this->_getFilterParams()['username'],
'password' => sha1($this->getParameter('ENCRYPTION_KEY') . $this->_getFilterParams()['password'])
]
);
// validate($this->_getFilterParams(), $this->getParameter('ENCRYPTION_KEY'));
var_dump($user->getUsername());
exit;
it's my output:
string(10) "superadmin"

How to fix the "key too long" error and generate the Doctrine migrations table?

I'm using / setting up the Symfony DoctrineMigrationsBundle v2.2 configured as followed:
doctrine_migrations:
name: 'My Migrations'
migrations_paths:
'DoctrineMigrations': '%kernel.project_dir%/src/Migrations'
storage:
table_storage:
table_name: 'migrations'
version_column_name: 'version'
version_column_length: 1024
executed_at_column_name: 'executed_at'
# Seems not to be supported:
# Unrecognized option "execution_time_column_name" under "doctrine_migrations.storage.table_storage"
# execution_time_column_name: 'execution_time'
organize_migrations: false
# custom_template: ~
all_or_nothing: false
The RDBMS is MySQL v8, running (locally) on Ubuntu Desktop v20.04:
$ mysql --version
mysql Ver 8.0.22-0ubuntu0.20.04.2 for Linux on x86_64 ((Ubuntu))
The DEFAULT_CHARACTER_SET_NAME is utf8mb4, the DEFAULT_COLLATION_NAME is utf8mb4_unicode_ci:
SELECT
`DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`
FROM
`INFORMATION_SCHEMA`.`SCHEMATA`
WHERE
`SCHEMA_NAME` = "payment"
;
+----------------------------+------------------------+
| DEFAULT_CHARACTER_SET_NAME | DEFAULT_COLLATION_NAME |
+----------------------------+------------------------+
| utf8mb4 | utf8mb4_unicode_ci |
+----------------------------+------------------------+
While I was playing with the configs, I created two migrations tables (I changed the doctrine_migrations.storage.table_storage.table_name multiple times), somehow... Now, after the configuration has bee completed I want to go the setup through cleanly again from scratch. So I removed both migrations tables and started again. But now I'm getting following error:
$ ./bin/console doctrine:migrations:status
...
In AbstractMySQLDriver.php line 106:
An exception occurred while executing 'CREATE TABLE migrations (version VARCHAR(1024) NOT NULL, executed_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', PRIMARY KEY(version)) DEFAULT CHARACTER
SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB':
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes
In PDOConnection.php line 43:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes
In PDOConnection.php line 41:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes
I tried to reduce the doctrine_migrations.storage.table_storage.version_column_length, but then I'm running in another error:
$ ./bin/console doctrine:migrations:status
...
In BaseNode.php line 348:
Invalid configuration for path "doctrine_migrations.storage.table_storage.version_column_length": The minimum length for the version column is 1024.
In ExprBuilder.php line 189:
The minimum length for the version column is 1024.
How to set this up correctly and get the migrations tables generated?
It's not a (clean) solution, but at least a workaround:
Removing the configuration doctrine_migrations.storage.table_storage.version_column_length makes it work again. The resulting configuration looks then like this:
$ bin/console debug:config doctrine_migrations
...
Current configuration for extension with alias "doctrine_migrations"
====================================================================
doctrine_migrations:
name: 'My Migrations'
migrations_paths:
DoctrineMigrations: /var/www/html/src/Migrations
storage:
table_storage:
table_name: migrations
version_column_name: version
executed_at_column_name: executed_at
version_column_length: null
organize_migrations: false
all_or_nothing: false
dir_name: /var/www/html/src/bundles/Wings/DoctrineMigrations
namespace: Application\Migrations
table_name: migration_versions
column_name: version
column_length: 14
executed_at_column_name: executed_at
custom_template: null

Can't add a field to a model in Symfony, bin/console crashes

I'm working with Sylius framework. I'm following the guide to customize models.
I am trying to add a field notice to a model Taxon which is already overridden in my project. For that, I added the field description to Taxon.orm.yml of the model:
MyProject\Bundle\ShopBundle\Entity\Taxon:
type: entity
table: sylius_taxon
# {Relationships code...}
fields:
# {Some existing fields...}
notice:
type: text
nullable: true
I also added a field, a getter and a setter to the overriding Taxon class.
Then I'm trying to run bin/console doctrine:migrations:diff, but when I run bin/console even without any arguments, it crashes with the following exception:
[Doctrine\DBAL\Exception\InvalidFieldNameException]
An exception occurred while executing 'SELECT s0_.code AS code_0, s0_.tree_left AS tree_left_1, s0_.tree_right AS tree_right_2, s0_.tree_level AS tree_level_3, s0_.position AS position_4, s0_.id AS id_5, s0_
.created_at AS created_at_6, s0_.updated_at AS updated_at_7, s0_.enabled AS enabled_8, s0_.default_markup AS default_markup_9, s0_.notice AS notice_10, s0_.tree_root AS tree_root_11, s0_.parent_id AS parent_
id_12 FROM sylius_taxon s0_ WHERE s0_.parent_id IS NULL ORDER BY s0_.tree_left ASC':
SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.notice' in 'field list'`
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.notice' in 'field list'`
[PDOException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 's0_.notice' in 'field list'
If I remove the changes to Taxon.orm.yml then bin/console works again. What is missing in my changes?
One of my bundles' configruation contained that model's repository, that's it. I temporarily deleted the bundle's configuration from config.yml, and bin/console worked.
When you add new field you should doctrine:schema:update

symfony2 - createQueryBuilder Doctrine build query with first capital letter

I' following a symfony2 tutorial and I've problems with one step.
Tutorial link: http://intelligentbee.com/blog/2013/08/12/symfony2-jobeet-day-6-more-with-the-model/
I'm in 'Refactoring' step. I've one this 3 steps:
1- I've correctly modified /src/Ibw/JobeetBundle/Resources/config/doctrine/Job.orm.yml file specifiying the repository
2- I've run the command: php app/console doctrine:generate:entities IbwJobeetBundle
3- And I've added the specified tutorial function por JobRepository.php
$qb = $this->createQueryBuilder('j')
->where('j.expires_at > :date')
->setParameter('date', date('Y-m-d H:i:s', time()))
->orderBy('j.expires_at', 'DESC');
BUT when I refresh my code I get this error:
An exception occurred while executing 'SELECT j0_.id AS id0, j0_.type
AS type1, j0_.company AS company2, j0_.logo AS logo3, j0_.url AS url4,
j0_.position AS position5, j0_.location AS location6, j0_.description
AS description7, j0_.how_to_apply AS how_to_apply8, j0_.token AS
token9, j0_.is_public AS is_public10, j0_.is_activated AS
is_activated11, j0_.email AS email12, j0_.expires_at AS expires_at13,
j0_.created_at AS created_at14, j0_.updated_at AS updated_at15,
j0_.category_id AS category_id16 FROM Job j0_ WHERE j0_.expires_at > ?
ORDER BY j0_.expires_at DESC' with params ["2016-03-17 15:47:19"]:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jobeet.Job'
doesn't exist
In the symfony profiler I can see the full query:
SELECT j0_.id AS id0, j0_.type AS type1, j0_.company AS company2,
j0_.logo AS logo3, j0_.url AS url4, j0_.position AS position5,
j0_.location AS location6, j0_.description AS description7,
j0_.how_to_apply AS how_to_apply8, j0_.token AS token9, j0_.is_public
AS is_public10, j0_.is_activated AS is_activated11, j0_.email AS
email12, j0_.expires_at AS expires_at13, j0_.created_at AS
created_at14, j0_.updated_at AS updated_at15, j0_.category_id AS
category_id16 FROM Job j0_ WHERE j0_.expires_at > '2016-03-17
15:47:19' ORDER BY j0_.expires_at DESC
the table name it's in uppercase! 'Job', not 'job'
Any can help me, please?
You can try by modifying the entity definition in Job.orm.yml by adding the table attribute:
IbwJobeetBundleEntityJob:
type: entity
table: job
repositoryClass: IbwJobeetBundleRepositoryJobRepository

Concat three or more fields in doctrine

Doctrine query builder allows me to concat two fields only.
class Expr {
// ...
public function concat($x, $y); // Returns Expr\Func
To concatenate 3 fields I use:
$qb->expr()->concat(
'table.field1',
$qb->expr()->concat('table.field2', 'table.field3')
);
And the SQL will be:
CONCAT('table.field1', CONCAT('table.field2', 'table.field3'))
How to get one concat?
When I try to call directly
new Expr\Func('CONCAT', array('table.field1', 'table.field2', 'table.field3'));
Executing query gives me an error
[Syntax Error] line 0, col 237: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','
Dumping DQL:
CONCAT('table.field1', 'table.field2', 'table.field3')
Dumping SQL using $qb->getQuery()->getSQL():
[Syntax Error] line 0, col 237: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','
CONCAT with variable number of arguments has been introduced in Doctrine ORM version 2.4.0, so you are probably using an older version. I've tested a similar DQL in my project and works as expected.
You should upgrade your Doctrine ORM deps with:
php composer.phar require doctrine/orm:~2.4
Note that (for now) variable arguments are supported only by Expr\Func constructor, but is not supported in Expr::concat method; you still need this syntax:
new Expr\Func('CONCAT', array('table.field1', 'table.field2', 'table.field3'));
UPDATE I've created a PR on GitHub to support multiple arguments in Expr::concat

Resources