Set autocommit off at doctrine config level - php

I am aware that I can switch this off at mysql level as part of its config. This is limiting as its once per instance, and I dont want to switch on and off/introduce docker to circumvent it.
However, I would like to specify this at configuration level, ie in the array that you pass to doctrine when instantiating the object, so I can have one config that rolls every back at the end of the PHP run:
$conn = array(
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/db.sqlite',
'autocommit' => false // <- Does this exist?
);
$entityManager = EntityManager::create($conn, $config);
The best I can come up with is to grab the entity manager and switch autocommit off in the setUp() and tearDown() functions, it would be nice to not to have to remember to do that or specify globally. That, and I can do ad-hoc operations outside of phpunit and get the auto rollback.

It's not tested, but you could try the following
$db = new PDO('sqlite:dogsDb_PDO.sqlite', $user, $pass, array(
PDO::ATTR_AUTOCOMMIT => false
));
$config = new \Doctrine\DBAL\Configuration();
$connectionParams = array(
'dbname' => 'mydb',
'user' => 'user',
'password' => 'secret',
'host' => 'localhost',
'pdo' => $db,
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
$entityManager = EntityManager::create($conn, $config);
Source / simillar issue - https://github.com/doctrine/dbal/issues/2315

You could do something like:
/** #var EntityManagerInterface */
private $em;
public function setUp()
{
// initialize the entity manager in some manner .....
$this->em->beginTransaction();
}
public function tearDown()
{
$this->em->rollback();
}
Hope this help

Related

How to get php-native handle from Doctrine\DBAL\Connection?

Given the code
$connectionParams = array(
'dbname' => $this->dbname,
'user' => $this->dbuser,
'password' => $this->dbpass,
'host' => $this->dbhost,
'driver' => 'mysqli',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
var_dump($conn);
How can I get the underlying mysqli handle from $conn (which is a Doctrine\DBAL\Connection)?
I have found *a way* to access it, but its obviously not the way it's supposed to be done, so I'm up for suggestions:
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
foreach((array)$conn->getWrappedConnection() as $mysqli){
// TODO: find official way of getting the handle.
// here we are casting it to (array) to access its PRIVATE PROPERTIES
// it's a fugly hack.
break;
}
var_dump($mysqli);
You can get it this way:
$mysqli = $conn->getWrappedConnection()->getWrappedResourceHandle();

Database created with doctrine, not shown in phpmyadmin

I am following the tutorial for Doctrine: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/getting-started.html
I changed the bootstrap file to include my database to:
<?php
// bootstrap.php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
require_once "vendor/autoload.php";
// Create a simple "default" Doctrine ORM configuration for Annotations
$isDevMode = false;
$paths = array(__DIR__."/src");
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
// or if you prefer yaml or XML
//$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);
//$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yaml"), $isDevMode);
// database configuration parameters
$conn = array(
'host' => '*********',
'port' => '3306',
'user' => '********',
'password' => '****',
'dbname' => 'bugs',
'charset' => 'UTF8',
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/db.sqlite',
);
// obtaining the entity manager
$entityManager = EntityManager::create($conn, $config);
Then, I did the rest and create the tables, etc using the following commnad:
vendor/bin/doctrine orm:schema-tool:create
Later, I logged to my 'myphpadmin' and the database was not there.
Am I missing any step?
Thank you
That is because you are using the driver pdo_sqlite. It is creating an SQLite database and not a MySQL database. It should have created the file db.sqlite.
Change it to pdo_mysql to get the database to show up in phpmyadmin.

Doctrine cannot redeclare class Annotation

i've got my bootstrap
<?php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
// Log Filename
define ('LOG_FILENAME', 'clicktocall-'.date("Ymd").'log');
$loader = require "vendor/autoload.php";
// Doctrine parser
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
// Create a simple "default" Doctrine ORM configuration for Annotations
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array("./src/acme"), $isDevMode);
// Database configuration parameters
$dbParams = array(
'driver' => 'pdo_mysql',
'host' => 'localhost',
'user' => 'xxx',
'password' => 'yyy',
'dbname' => 'zzz',
);
// Obtaining the entity manager
$em = EntityManager::create($dbParams, $config);
// Setting Logger Monolog
$Logger = new \Monolog\Logger('CTLogger');
$Logger->pushHandler(new \Monolog\Handler\StreamHandler('./log/'.LOG_FILENAME, \Monolog\Logger::INFO));
When i'm trying to execute
vendor\bin\doctrine orm:schema-tool:update --force
I obtain this message
Fatal error: Cannot redeclare class Doctrine\ORM\Mapping\Annotation in E:\www\acme\vendor\doctri
ne\orm\lib\Doctrine\ORM\Mapping\Annotation.php on line 22
I'm just using Doctrine bundle.
Any idea?
Thanks a lot
[Edit]
I've found that the problem is caused by
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
I use this row to parse the annotations for the symfony\validator bundle, without this the validation doesn't work...

Cakephp set database timezone

I'm setting timezone to php and mysql to internacionalize my CakePHP application.
When the server receives a request from a client, before process request, it connects to a GeoIp location server and gets the Timezone. Then I use date_default_timezone_set() to set php timezone. The problem comes up when I want to set database timezone. Once Cakephp connected, I need to execute sql query like SET time_zone='-06:00'.
In /lib/Cake/Model/Datasource/Database/Mysql.php I can see at connect() function the following code:
try {
$this->_connection = new PDO(
$dsn,
$config['login'],
$config['password'],
$flags
);
$this->connected = true;
if (!empty($config['settings'])) {
foreach ($config['settings'] as $key => $value) {
$this->_execute("SET $key=$value");
}
}
} catch (PDOException $e) {
throw new MissingConnectionException(array(
'class' => get_class($this),
'message' => $e->getMessage()
));
}
There is a $config['settings'] array that can be configured to do it. But I don't know how to fill settings array and where it's the best place to do that.
What I need is modify default datasource config on-the-fly
You can add an additional key to config array located at app/Config/database.php like this:
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'db_user',
'password' => 'db_pass',
'database' => 'db_name',
'prefix' => '',
'settings' => array(
'time_zone' => "'+01:00'", // note the quotes!
)
);
Related: CakePHP switch database (using same datasource) on the fly?
I solved it in the following way.
First of all, adding setOptions() method into DATABASE_CONFIG class as follows:
public function setOptions ($datasource, array $options){
$this->{$datasource} = array_merge($this->{$datasource}, $options);
}
Afterwards, extending ConnectionManager class to initialize it:
class ConnectionManagerCustomConfig extends ConnectionManager
{
public static function initialize(){
self::_init();
}
}
Now I initialize the class and add new options:
ConnectionManagerCustomConfig::initialize();
$configClass = ConnectionManagerCustomConfig::$config;
$configClass->setOptions('default', array(
'settings' => array(
'time_zone' => $offset
)
));

Doctrine Console program

I am learning Doctrine. I config doctrine 2.2.0 by Tarball Download. Now getting trouble when generating-the-database-schema. Can't use command-line tool with the code below:
<?php
// doctrine.php - Put in your application root
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\DBAL\Tools\Console\Helper\EntityManagerHelper;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use Symfony\Component\Console\Helper\HelperSet;
$lib = "../DoctrineORM-2.2.0";
require $lib . '/Doctrine/ORM/Tools/Setup.php';
Setup::registerAutoloadDirectory($lib);
$paths = array("/path/to/entities-or-mapping-files");
$isDevMode = false;
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$dbParams = array(
'dbname' => 'mydb',
'user' => 'root',
'password' => '',
'host' => '127.0.0.1',
'driver' => 'pdo_mysql'
);
$em = EntityManager::create($dbParams, $config);
$helperSet = new HelperSet(array(
'db' => new ConnectionHelper($em->getConnection()),
'em' => new EntityManagerHelper($em)
));
ConsoleRunner::run($helperSet);
The error here.
Fatal error: Class 'Doctrine\DBAL\Tools\Console\Helper\EntityManagerHelper' not found in E:\wamp\www\project\doctrine.php on line 30
and I can not find EntityManagerHelper.php under DoctrineORM-2.2.0\Doctrine\DBAL\Tools\Console\Helper .
Seems like EntityManagerHelper is under different namespace:
namespace Doctrine\ORM\Tools\Console\Helper;

Categories