Symfony's Command : No default connection - php

In my Symfony2 project, I need to do some work in database with a Command.
When I launch it, I have this error :
[Exception]
There is no default connection
I don't understand why ?
My code :
1. $this->output = $output;
2. $this->writeln( 'ImportBase' );
3. $importBase = Model\ImportBase::builder()
->whereEgal('termine', 0)
->limit(1)
->getObject();
For information, there is just one connection in my project.
Also, I do not use Doctrine but ORM (I guess ? This is not my project)
Do you have any idea ? I can't find anything...
EDIT :
config.yml :
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
Parameters.yml
parameters:
database_driver: pdo_mysql
database_host: 127.0.0.1
database_port: null
database_name: [...]
database_user: [...]
database_password: [...]
Model :
<?php
namespace xxx\xxxhBundle\Model;
use xxx\ORM\Model;
class ImportBase extends Model
{
protected static $table_name = 'import_base';
protected static $primary_key = 'import_base_id';
}
Builder in Model file
/**
* Get command builder for the class
*
* #return DbCommandBuilder builder
*/
public static function builder() {
if( static::$table_name == null )
throw new \Exception('Canot get builder, table_name is not set');
$builder = static::dbConnection()->builder( static::tableName(), static::$builder_class );
$builder->setFetchClassName( get_called_class() );
return $builder;
}

That seems a little strange... I don't notice anything wrong based on the configuration you've supplied.
However, since you appear to only have one dbal connection, you could simply use the "terser" configuration:
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
Hope this helps :)

Related

Symfony3 - multiple Entity Managers and Connections

I tried to create an entity from a table in a pre-existing database :
php bin/console doctrine:mapping:import --force AppBundle yml --filter="someTable"
But a message showed up stating :
Table someTable has no primary key. Doctrine does not support reverse
engineering from tables that don't have a primary key.
I checked, and in the DB, there were some tables without any PK (and I cannot change that).
So I read this page : http://symfony.com/doc/current/doctrine/multiple_entity_managers.html
... and tried this solution on github :
https://github.com/doctrine/DoctrineBundle/issues/441
My config.yml is like this :
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
mapping_types:
enum: string
forMapping:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
schema_filter: someTable
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
AppBundle:
type: yml
dir: Resources/config
forMapping:
connection: forMapping
mappings:
AppBundle:
type: yml
dir: Resources/config
But when I try :
php bin/console doctrine:mapping:import --em=forMapping --filter="someTable" AppBundle yml
I get :
[InvalidArgumentException] Doctrine ORM Manager named "forMapping" does not exist.
Emptied the cache, but nope. Any help appreciated.
MC
Sorry, I goofed on my previous answer.
How about you try the command like this instead:
php bin/console doctrine:mapping:import "AppBundle" yml --em=forMapping --filter="someTable"
Does it make a difference? I see from a command line using the --help, it show in that order.
[Solved] Was due to the "auto_mapping". Correct sequence seems to be :
orm:
default_entity_manager: default
entity_managers:
auto_mapping: true
default:
connection: default
mappings:
AppBundle:
type: yml
dir: Resources/config
# See https://github.com/doctrine/DoctrineBundle/issues/441
forMapping:
connection: forMapping
mappings:
AppBundle:
type: yml
dir: Resources/config
It works one step further to the next error message. When I try :
php bin/console doctrine:mapping:import "AppBundle" yml --em=forMapping
The following error message pops up :
[Symfony\Component\Debug\Exception\ContextErrorException]
Warning: preg_match(): Delimiter must not be alphanumeric or backslash
Ok, let's see to this. The schema_filter was wrong. Correct code is :
schema_filter: ~^spip_rubriques$~
My entity has been correctly generated. I thank you all for your help.
MC
It looks like your "forMapping" is not correct in
orm:
entity_managers:
#problem here
forMapping:
Try to find out what is going wrong here

Cannot connect database oracle with symfony2

what i need
i need to connect oracle database with symfony2.
i have checked by php -m
oci8
pdo_odbc
odbc
here is the link i follow https://gist.github.com/johnkary/6481664
a.)config.yml
Doctrine Configuration
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: "%database_charset%"
b.) parameter.yml
# If connecting via SID
parameters:
database_driver: oci8
database_host: abc
database_port: '1521'
database_name: test
database_user: aa
database_password: aa
database_charset: AL32UTF8
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
locale: en
secret: zzzz
c.)services.orcale.yml
services:
acme.doctrine.dbal.events.oracle_session_init.listener:
class: %doctrine.dbal.events.oracle_session_init.class%
tags:
- { name: doctrine.event_listener, event: postConnect }
acme.doctrine.dbal.oracle_platform.type_mapping.listener:
class: Acme\MisBundle\Listener\OracleDoctrineTypeMappingListener
tags:
- { name: doctrine.event_listener, event: postConnect }
then run symfony database cmd
php bin/console doctrine:database:create
error:
cannot create database test for connection named default.
notice: undefined index dbname
i have googled a day but i think there are few developer who works with symfony2 and oracle.
i had made simple php script that works to test connections
$userName = ""; $password = ""; $dtabasePort = "1521"; $serverName = "";
$databaseName = "testingdb";
$c = oci_connect($userName, $password, '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = host)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = ) (SID =)))');
print_r($c);
output
Resource id #3
tsnames.ora
test=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = sss)(PORT = 1521))
(CONNECT_DATA = (SID = test))
)
i have worked sf3 and mysql but im new to oracle thats why i don"t knew how to connect oracle db with symfony.
please give some solution where i have done wrong.
Can anyone suggest in steps how to connect oracle db with sf2/3 is most appreciated.
link of github relies same issue that im facing https://github.com/doctrine/dbal/issues/1564
i have also changed the parameter.yml file
parameters:
database_driver: oci8
database_user: <user>
database_password: <password>
database_charset: WE8MSWIN1252
database_name: (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<host>)(PORT=<port>))(CONNECT_DATA=(SERVICE_NAME=<service_name>)))
then error you have requested non-existence parameter "database_host"
last & final solution i tried but didn"t worked i think there bug in sf2 for oracle
parameters:
database_driver: oci8
database_host:
database_port: 1521
database_name:
database_user:
database_password:
domain_name:
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
persistent: true
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
services:
pdo:
class: PDO
arguments:
- "oci8:Server=%database_host%;Database=%database_name%"
- "%database_user%"
- "%database_password%"
calls:
- [setAttribute, [3, 2]] # \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION
session.handler.pdo:
class: ESERV\MAIN\FrameworkChanges\MtlPdoSessionHandler
arguments: ["#pdo", "%pdo.db_options%"]
here is what I use to connect MSSQL : https://github.com/realestateconz/MssqlBundle
config.yml :
doctrine:
dbal:
types:
string: ***\BacsManagementBundle\Type\StringType
default_connection: default
connections:
default:
host: "%database_host%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
driver_class: Realestate\MssqlBundle\Driver\PDODblib\Driver
mapping_types:
enum: string
string: string
hope it helps.
This might be a little old but I think it is still useful. I am working on a Symfony 5 project connected to a legacy Oracle 11G database. For the most part Doctrine works fine. In some cases you need to perform a raw query.
Your env file:
DATABASE_URL2="oci8://USERNAME:PASSWORD#HOSTNAME:1521/DATABASENAME"
Note: if you are using Oracle 11G Express Edition your database name most likely will be XE
Next update your doctrine.yaml file. In my case I have two databases. The default one is MySQL and the 2nd database is Oracle 11G. It would also be a good idea to install the DoctrineExtensions package that gives a little more support to Oracle and MySQL in Doctrine.
doctrine:
dbal:
default_connection: default
connections:
default:
# configure these for your database server
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
mapping_types:
enum: string
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
oracle:
# configure these for your database server
url: '%env(resolve:DATABASE_URL2)%'
driver: 'oci8'
server_version: '11'
charset: AL32UTF8
orm:
auto_generate_proxy_classes: '%kernel.debug%'
default_entity_manager: default
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
connection: default
auto_mapping: true
dql:
numeric_functions:
rand: DoctrineExtensions\Query\Mysql\Rand
datetime_functions:
DATE_FORMAT: DoctrineExtensions\Query\Mysql\DateFormat
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
oracle:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
connection: oracle
dql:
datetime_functions:
TO_CHAR: DoctrineExtensions\Query\Oracle\ToChar
TO_DATE: DoctrineExtensions\Query\Oracle\ToDate
mappings:
Oracle:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Oracle'
prefix: 'App\Entity\Oracle'
alias: Oracle
Now this is where it gets tricky. My database does not have any primary keys so I had to add them manually to each table in order to import the entities. Once I imported the entities I then removed the primary keys and updated the entities manually.
php bin/console doctrine:mapping:import "App\Entity\Oracle" annotation --path=src/Entity/Oracle --em=oracle
You should now be able to use Doctrine to perform a query. I like using repositories so I do not use Query Builder.
Example:
public function getEmployeeInfo($clientID)
{
$sql =
"
SELECT
p.employeeId,
p.clientId,
p.firstname,
p.lastname
FROM
Oracle:Phoneext p
WHERE
p.clientId = :clientID
ORDER BY p.lastname ASC
"
;
$query = $this->getEntityManager()->createQuery($sql);
$query->setParameter('clientID', $clientID);
$results = $query->getResult();
return ($results);
}
In a case you need to perform a RAW query:
public function getMultiStatusRowId($employeeID, $status, $date, $time, $em)
{
$conn = $em->getConnection();
$sql =
"
SELECT
ROWIDTOCHAR(ROWID) as row_id
FROM
MULTI_STATUS
WHERE
EMPLOYEE_ID = ?
AND STATUS = ?
AND IN_DATE = ?
AND IN_TIME = ?
ORDER BY ORDER_NUM ASC
"
;
$result = $conn->prepare($sql);
$result->bindValue(1, $employeeID);
$result->bindValue(2, $status);
$result->bindValue(3, $date);
$result->bindValue(4, $time);
$result->execute();
$data = array();
$i = "0";
while ($row = $result->fetch()) {
$data[$i]['ROW_ID'] = $row['ROW_ID'];
$i++;
}
return $data;
}
One final item if you need help setting up a local system on a Mac you can use this to help setup Lando. Note I had to setup Oracle 11G on AWS EC2 then was able to use the IMP tool to import my dump files.
If you setup RDS Amazon will default to Oracle 20 or some newer version. AWS RDS does not support the older backups from IMP. RDS will only support data pump using S3.
https://github.com/rsaylor73/lando-apache-php-mysql-oci8

The class 'ScheduleBundle\Entity\schedule' was not found in the chain configured namespaces StudentsBundle\Entity

I am making a application with multiply bundels and database connections.
I keep getting this error:
The class 'ScheduleBundle\Entity\schedule' was not found in the chain configured namespaces StudentsBundle\Entity
500 Internal Server Error - MappingException
Here is the code from the controller
<?php
namespace ScheduleBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
//Json Response
use Symfony\Component\HttpFoundation\JsonResponse;
//Class Controller
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
//Request
use Symfony\Component\HttpFoundation\Request;
use ScheduleBundle\Entity\schedule;
class ApiController extends Controller
{
/**
* #Route("/api/{week}")
*/
public function roosterApi(Request $request, $week)
{
$rooster = array('week' => '1');
$entityManager = $this->get('doctrine')->getManager();
$roosterConnection = $this->get('doctrine')->getRepository('ScheduleBundle:schedule', 'schedule');
$dataRooster = $roosterConnection->findOneByStudentId('36838');
$dataRooster->setSchedule($rooster);
$entityManager->persist($dataRooster);
$entityManager->flush();
$out = array('1' => $week);
return new JsonResponse($out, 200, array('Content-Type' => 'application/json'));
}
}
?>
I think the problem is with my orm mapping so i include the doctrine code from config.yml
# Doctrine Configuration
doctrine:
dbal:
default_connection: StudentDB
connections:
StudentDB:
driver: '%database_driver%'
host: '%database_host%'
port: '%database_port%'
dbname: '%database_students%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
TeacherDB:
driver: '%database_driver%'
host: '%database_host%'
port: '%database_port%'
dbname: '%database_teachers%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
GradesDB:
driver: '%database_driver%'
host: '%database_host%'
port: '%database_port%'
dbname: '%database_grades%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
ScheduleDB:
driver: '%database_driver%'
host: '%database_host%'
port: '%database_port%'
dbname: '%database_schedule%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
SpecialGroupDB:
driver: '%database_driver%'
host: '%database_host%'
port: '%database_port%'
dbname: '%database_specialgroup%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
ToDoListDB:
driver: '%database_driver%'
host: '%database_host%'
port: '%database_port%'
dbname: '%database_todolist%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
orm:
default_entity_manager: students
entity_managers:
students:
connection: StudentDB
mappings:
StudentsBundle: ~
teachers:
connection: TeacherDB
mappings:
TeachersBundle: ~
grades:
connection: GradesDB
mappings:
GradesBundle: ~
schedule:
connection: ScheduleDB
mappings:
ScheduleBundle: ~
specialgroup:
connection: SpecialGroupDB
mappings:
SpecialGroupBundle: ~
todolist:
connection: ToDoListDB
mappings:
ToDoListBundle: ~
I am using symfony 3.0.3 and doctrine
edit: changed use ScheduleBundle\Entity to use ScheduleBundle\Entity\schedule this did not fix the problem
You need to use the correct doctrine entity manager service. In your code you refer to the doctrine service which is an alias of the default entity manager. For the schedule entity manager you need to use the following service:
doctrine.orm.schedule_entity_manager
So try using this:
$this->get('doctrine.orm.schedule_entity_manager')
Instead of this:
$this->get('doctrine')
For dump current service definition you can use the console command:
app/console debug:container |grep entity
Hope this help

Symfony2 Doctrine ORM Manager named "customer" does not exist

Hello I coopied the example for using two different database connections from the Symfony2 documentation: Symfony2 multiple connections documentation
So however Symfony does not find the the costumer entity manager.
(The parameters are defined properly)
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
customer:
driver: "%database_driver%"
host: "%database_host2%"
port: "%database_port2%"
dbname: "%database_name2%"
user: "%database_user2%"
password: "%database_password2%"
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
AppBundle: ~
customer:
connection: customer
mappings:
AppBundle: ~
The Controller looks like this:
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$em = $this->get('doctrine')->getManager();
$em = $this->get('doctrine')->getManager('default');
$em = $this->get('doctrine.orm.default_entity_manager');
// Both of these return the "customer" entity manager
$customerEm = $this->get('doctrine')->getManager('customer');
$customerEm = $this->get('doctrine.orm.customer_entity_manager');
return $this->render('default/index.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'),
));
}
I should get the costumer entity manager, but however Symfony throws an invalid argument exception with the message.
[2015-10-19 23:19:18] request.CRITICAL: Uncaught PHP Exception
InvalidArgumentException: "Doctrine ORM Manager named "customer" does
not exist." at /srv/www/htdocs/symfony/my_project_name/app/cache
/prod/classes.php line 7344 {"exception":"[object]
(InvalidArgumentException(code: 0): Doctrine ORM Manager named
\"customer\" does not exist. at /srv/www/htdocs/symfony/my_project_name
/app/cache/prod/classes.php:7344)"} []
I cleaned the cache with php app/console cache:clear but this does not help.
Artamiel had the right answer in a comment:
Symfony2 Doctrine ORM Manager named "customer" does not exist
cache:clear clears the dev environment by default, but looking at your error log, you receive the error in your prod environment. To clear the cache on your production environment, add -e prod flag, like this cache:clear -e prod and refresh your page.
First, I think, one declaration of entity manager in your controller is enough:
/ *** /
public function indexAction(Request $request)
{
$em = $this->get('doctrine')->getManager('default');
$customerEm = $this->get('doctrine')->getManager('customer');
/ *** /
}
Second, are you sure that you can declare the same bundle in your mapping configuration (AppBundle: ~ in this case) ?

Doctrine connection with db

I am about to start a project in doctrine symfony, but I have to make connection with multiple databases. One of them is an existing database (SQL SERVER) that cannot be mapped with ORM. Is there any possibility to connect with this db with another db that is NOT mapped in doctrine and work with controllers normally?
I develop a multi-database sf2 app with doctrine2 orm mapping.
We use intellectsoft-uk/MssqlBundle
Our configuration is:
config.yml
# Doctrine Configuration
doctrine:
dbal:
default_connection: acme_mysql
connections:
acme_mysql:
host: %acme_mysql_database_host%
port: %acme_mysql_database_port%
dbname: %acme_mysql_database_name%
user: %acme_mysql_database_user%
password: %acme_mysql_database_password%
charset: UTF8
acme_slqsrv:
driver: sqlsrv
driver_class: \Realestate\MssqlBundle\Driver\PDODblib\Driver
host: %acme_slqsrv%
port: %acme_slqsrv%
dbname: %acme_slqsrv%
user: %acme_slqsrv%
password: %acme_slqsrv%
charset: UTF8
orm: #optional if you want to map some entity in doctrine2
auto_generate_proxy_classes: %kernel.debug%
default_entity_manager: acme_mysql
entity_managers:
em_mysql:
connection: acme_mysql
mappings:
AcmeMysqlBundle: ~
em_sqlsrv:
connection: acme_sqlsrv
mappings:
AcmeSqlSrvBundle: ~
This configuration permit you to take a connection instance in a controller/service and use it for access database and execute stored procedures and so on...
Hope this help

Categories