protected function setUp() { $this->app = $app = new Container(); $db_config = ['driver' => 'pdo_sqlite', 'dbname' => 'sqlite:///:memory:']; $models = ['post.model' => function () use($app) { return new Post($app); }, 'comment.model' => 'Comment']; $app['db'] = function () use($db_config) { $db = \Doctrine\DBAL\DriverManager::getConnection($db_config); $sql = file_get_contents(codecept_data_dir() . '/dump.sql'); $db->exec($sql); return $db; }; foreach ($models as $name => $class) { if (is_callable($class)) { $callable = $class; } else { $callable = function () use($class, $app) { return new $class($app); }; } $app[$name] = $app->factory($callable); } $this->loadFixtures(); }
private static function getSpecifiedConnectionParams() { $realDbParams = self::getParamsForMainConnection(); if (!self::$initialized) { $tmpDbParams = self::getParamsForTemporaryConnection(); $realConn = DriverManager::getConnection($realDbParams); // Connect to tmpdb in order to drop and create the real test db. $tmpConn = DriverManager::getConnection($tmpDbParams); $platform = $tmpConn->getDatabasePlatform(); if ($platform->supportsCreateDropDatabase()) { $dbname = $realConn->getDatabase(); $realConn->close(); $tmpConn->getSchemaManager()->dropAndCreateDatabase($dbname); $tmpConn->close(); } else { $sm = $realConn->getSchemaManager(); $schema = $sm->createSchema(); $stmts = $schema->toDropSql($realConn->getDatabasePlatform()); foreach ($stmts as $stmt) { $realConn->exec($stmt); } } self::$initialized = true; } return $realDbParams; }
private function connectDatabase(OutputInterface $output) { $param = array(); $param['host'] = $this->dialog->ask($output, '<question>Where is your database server? [localhost]</question> ', 'localhost'); $param['user'] = $this->dialog->ask($output, '<question>What is your database username? [root]</question> ', 'root'); $param['password'] = $this->dialog->ask($output, '<question>What is your database password?</question> ', ''); $param['driver'] = 'pdo_mysql'; // Save dbName for later use to create database $this->dbName = $this->dialog->ask($output, '<question>What is your database name? [BungaWire]</question> ', 'BungaWire'); $output->writeln(''); // Write empty line for easy read $config = new Configuration(); $this->dbConnection = DriverManager::getConnection($param, $config); $this->dbConnection->connect(); if ($this->dbConnection->isConnected() === false) { $output->writeln('Database connection failed, please check your setting'); $output->writeln('You connection configuration is:'); $output->writeln('host: ' . $param['host']); $output->writeln('user: '******'user']); $output->writeln('password: '******'password']); $output->writeln('Database Name: ' . $param['dbname']); $output->writeln('Driver: ' . $param['driver']); $output->writeln($this->dbConnection->errorInfo()); $output->writeln('Please try again!'); $this->connectDatabase($output); } else { $output->writeln('Database connected!'); } }
/** * Just for internal use, could be overridden in child classes * User $em property in case if you need EntityManager * * @return EntityManagerMock */ protected function getEntityManagerInstanceMock() { $this->config = Setup::createAnnotationMetadataConfiguration(array('./Fixtures'), true); $this->config->setQuoteStrategy(new QuotingStrategy()); $conn = array('driverClass' => 'Luxifer\\Tests\\Mocks\\DriverMock', 'wrapperClass' => 'Luxifer\\Tests\\Mocks\\ConnectionMock', 'user' => 'john', 'password' => 'wayne'); $conn = DriverManager::getConnection($conn, $this->config); $this->config->setProxyDir(__DIR__ . '/Proxies'); $this->config->setProxyNamespace('Luxifer\\Tests\\Proxies'); $this->config->addCustomDatetimeFunction('date', 'Luxifer\\DQL\\Datetime\\Date'); $this->config->addCustomDatetimeFunction('datediff', 'Luxifer\\DQL\\Datetime\\DateDiff'); $this->config->addCustomDatetimeFunction('day', 'Luxifer\\DQL\\Datetime\\Day'); $this->config->addCustomDatetimeFunction('dayofmonth', 'Luxifer\\DQL\\Datetime\\DayOfMonth'); $this->config->addCustomDatetimeFunction('week', 'Luxifer\\DQL\\Datetime\\Week'); $this->config->addCustomDatetimeFunction('dayofweek', 'Luxifer\\DQL\\Datetime\\DayOfWeek'); $this->config->addCustomDatetimeFunction('dayofyear', 'Luxifer\\DQL\\Datetime\\DayOfYear'); $this->config->addCustomDatetimeFunction('hour', 'Luxifer\\DQL\\Datetime\\Hour'); $this->config->addCustomDatetimeFunction('minute', 'Luxifer\\DQL\\Datetime\\Minute'); $this->config->addCustomDatetimeFunction('month', 'Luxifer\\DQL\\Datetime\\Month'); $this->config->addCustomDatetimeFunction('quarter', 'Luxifer\\DQL\\Datetime\\Quarter'); $this->config->addCustomDatetimeFunction('second', 'Luxifer\\DQL\\Datetime\\Second'); $this->config->addCustomDatetimeFunction('time', 'Luxifer\\DQL\\Datetime\\Time'); $this->config->addCustomDatetimeFunction('year', 'Luxifer\\DQL\\Datetime\\Year'); $this->config->addCustomDatetimeFunction('convert_tz', 'Luxifer\\DQL\\Datetime\\ConvertTZ'); $this->config->addCustomDatetimeFunction('date_format', 'Luxifer\\DQL\\Datetime\\DateFormat'); $this->config->addCustomDatetimeFunction('concat_ws', 'Luxifer\\DQL\\String\\ConcatWs'); return EntityManagerMock::create($conn, $this->config); }
protected static function createDatabase() { if (empty(getenv('PGSQL_HOST')) && file_exists(__DIR__ . '/../../.env')) { $dotenv = new Dotenv(__DIR__ . '/../../'); $dotenv->load(); } if (empty(getenv('PGSQL_HOST')) || empty(getenv('PGSQL_USER'))) { throw new \RuntimeException('Create a .env file with PGSQL_HOST, PGSQL_USER, and PGSQL_PASS to run this test.'); } $pass = getenv('PGSQL_PASS') ? getenv('PGSQL_PASS') : ''; $pdo = new \PDO('pgsql:host=' . getenv('PGSQL_HOST'), getenv('PGSQL_USER'), $pass); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); self::$connection = DriverManager::getConnection(['driver' => 'pdo_pgsql', 'pdo' => $pdo, 'dbname' => 'public']); self::$connection->query('drop schema public cascade'); self::$connection->query('create schema public'); self::$connection->query('CREATE TABLE extended_data_objects ( id SERIAL PRIMARY KEY, "isDeleted" BOOLEAN NOT NULL DEFAULT FALSE, "myColumn" VARCHAR(255) NOT NULL, "myNullableColumn" INT NULL DEFAULT NULL, "otherDataObjectId" INT NULL )'); self::$connection->query('CREATE TABLE other_data_objects ( id SERIAL PRIMARY KEY, "isDeleted" BOOLEAN NOT NULL DEFAULT FALSE, "name" VARCHAR(255) NOT NULL, "extendedDataObjectId" INT NULL REFERENCES extended_data_objects (id) )'); self::$connection->query('CREATE TABLE extended_other_rel ( "extendedDataObjectId" INT NOT NULL REFERENCES extended_data_objects (id), "otherDataObjectId" INT NOT NULL REFERENCES other_data_objects (id) )'); }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $database = array(); if (extension_loaded('pdo_pgsql')) { $database['pdo_pgsql'] = 'PostgreSQL'; } if (extension_loaded('pdo_mysql')) { $database['pdo_mysql'] = 'MySQL'; } if (extension_loaded('pdo_sqlite')) { $database['pdo_sqlite'] = 'SQLite(開発者用)'; } $builder->add('database', 'choice', array('label' => 'データベースの種類', 'choices' => $database, 'expanded' => false, 'multiple' => false, 'constraints' => array(new Assert\NotBlank())))->add('database_host', 'text', array('label' => 'データベースのホスト名', 'required' => false))->add('database_port', 'text', array('label' => 'ポート番号', 'required' => false))->add('database_name', 'text', array('label' => 'データベース名', 'constraints' => array(new Assert\Callback(array($this, 'validate')))))->add('database_user', 'text', array('label' => 'ユーザ名', 'constraints' => array(new Assert\Callback(array($this, 'validate')))))->add('database_password', 'password', array('label' => 'パスワード', 'required' => false))->addEventListener(FormEvents::POST_SUBMIT, function ($event) { $form = $event->getForm(); $data = $form->getData(); try { $config = new \Doctrine\DBAL\Configuration(); if ($data['database'] == 'pdo_sqlite') { $connectionParams = array('driver' => $data['database'], 'path' => __DIR__ . '/../../../../../app/config/eccube/eccube.db'); } else { $connectionParams = array('dbname' => $data['database_name'], 'user' => $data['database_user'], 'password' => $data['database_password'], 'host' => $data['database_host'], 'driver' => $data['database'], 'port' => $data['database_port']); } // todo MySQL, PostgreSQLのバージョンチェックも欲しい.DBALで接続すればエラーになる? $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); $conn->connect(); } catch (\Exception $e) { $form['database']->addError(new FormError('データベースに接続できませんでした。' . $e->getMessage())); } }); }
/** * 单例模式,获取一个指定的实例 * * // 加载默认实例 * $db = Database::instance(); * * // 指定实例名称和配置 * $db = Database::instance('custom', $config); * * @param string $name 实例名 * @param array $config 配置参数 * @return Connection */ public static function instance($name = null, array $config = null) { if (null === $name) { $name = Db::$default; } if (!isset(Db::$instances[$name])) { // 读取配置 if (null === $config) { $config = (array) Config::load(self::$configFile)->get($name); Base::getLog()->debug(__METHOD__ . ' get default config', ['name' => $name]); } // 合并默认配置 if (isset(self::$defaultConfig[Arr::get($config, 'driver')])) { $config = Arr::merge(self::$defaultConfig[Arr::get($config, 'driver')], $config); Base::getLog()->debug(__METHOD__ . ' merge config', ['name' => $name]); } $conn = DriverManager::getConnection($config); Base::getLog()->debug(__METHOD__ . ' create dbal connection', ['name' => $name]); // 额外注册字段类型 if (isset(self::$mappingType[Arr::get($config, 'driver')])) { $platform = $conn->getDatabasePlatform(); foreach (self::$mappingType[Arr::get($config, 'driver')] as $dbType => $doctrineType) { if (!$platform->hasDoctrineTypeMappingFor($dbType)) { Base::getLog()->debug(__METHOD__ . ' add dbal mapping type', ['raw' => $dbType, 'dbal' => $doctrineType]); $platform->registerDoctrineTypeMapping($dbType, $doctrineType); } } } Db::$instances[$name] = $conn; Base::getLog()->debug(__METHOD__ . ' save db instance', ['name' => $name]); } return Db::$instances[$name]; }
protected function setUp() { parent::setUp(); $this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::SQLITE_PATH], new Configuration()); $config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../..'], true); $this->entityManager = EntityManager::create($this->connection, $config); }
/** * Add database connection * * @param string $name Unique name for the connection * @param string $dsn DSN string for this connection * @param boolean $defaut Use this connection as the default? The first connection added is automatically set as the default, even if this flag is false. * * @return \Doctrine\DBAL\Connection * @throws \Spot\Exception */ public function addConnection($name, $dsn, $default = false) { // Connection name must be unique if (isset($this->_connections[$name])) { throw new Exception("Connection for '" . $name . "' already exists. Connection name must be unique."); } if ($dsn instanceof DBAL\Connection) { $connection = $dsn; } else { if (is_array($dsn)) { $connectionParams = $dsn; } else { $connectionParams = $this->parseDsn($dsn); if ($connectionParams === false) { throw new Exception("Unable to parse given DSN string"); } } $config = new DBAL\Configuration(); $connection = DBAL\DriverManager::getConnection($connectionParams, $config); } // Set as default connection? if (true === $default || null === $this->_defaultConnection) { $this->_defaultConnection = $name; } // Store connection and return adapter instance $this->_connections[$name] = $connection; return $connection; }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $connection = $this->getDoctrineConnection($input->getOption('connection')); $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false); if (!$name) { throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped."); } unset($params['dbname']); $tmpConnection = DriverManager::getConnection($params); // Only quote if we don't have a path if (!isset($params['path'])) { $name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name); } $error = false; try { $tmpConnection->getSchemaManager()->createDatabase($name); $output->writeln(sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name)); } catch (\Exception $e) { $output->writeln(sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name)); $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); $error = true; } $tmpConnection->close(); return $error ? 1 : 0; }
public function getDBAL($conn = 'default') { if (in_array($conn, self::$dbal_conns)) { return self::$dbal_conns[$conn]; } return self::$dbal_conns[$conn] = \Doctrine\DBAL\DriverManager::getConnection($this->getConnection($conn), new \Doctrine\DBAL\Configuration()); }
public function initDb() { $params = $this->connection->getParams(); $name = $params['dbname']; unset($params['dbname']); $conn = DriverManager::getConnection($params); $conn->exec('CREATE DATABASE IF NOT EXISTS ' . $name); $conn->exec('USE ' . $name); $conn->exec('CREATE TABLE IF NOT EXISTS bl_run ( id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR(64), project_name VARCHAR(64) NOT NULL, properties TEXT NOT NULL, created_at DATETIME NOT NULL )'); $conn->exec('CREATE TABLE IF NOT EXISTS bl_run_unit ( id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, run_id INTEGER NOT NULL, feature TEXT NOT NULL, created_at DATETIME NOT NULL, started_at DATETIME, finished_at DATETIME, return_code INTEGER, output_files TEXT )'); }
/** * @return \Doctrine\DBAL\Connection */ protected function getDbal() { if (self::$dbal === null) { self::$dbal = DriverManager::getConnection(array('pdo' => $this->getPdo())); } return self::$dbal; }
/** * Initializes the database (once). * * @throws \Doctrine\DBAL\DBALException * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\Tools\ToolsException */ protected function setUp() { if (null === static::$_conn) { $dbPath = __DIR__ . '/../../../db.sqlite'; if (file_exists($dbPath)) { unlink($dbPath); } $params = ['driver' => 'pdo_sqlite', 'path' => $dbPath]; static::$_conn = DriverManager::getConnection($params); static::$_conn->getConfiguration()->setSQLLogger(null); } if (null === static::$_em) { $paths = [__DIR__ . '/../../../../../src/Ekyna/Commerce/Bridge/Doctrine/ORM/Resources/mapping']; $isDevMode = true; $config = Setup::createXMLMetadataConfiguration($paths, $isDevMode); $em = EntityManager::create(static::$_conn, $config); $classes = []; foreach (static::$_classes as $class) { array_push($classes, $em->getClassMetadata($class)); } $schemaTool = new SchemaTool($em); $schemaTool->dropSchema($classes); $schemaTool->createSchema($classes); // Load fixtures $loader = new Loader(); $loader->loadFromDirectory(__DIR__ . '/../../../../../src/Ekyna/Commerce/Bridge/Doctrine/Fixtures'); $purger = new ORMPurger(); $executor = new ORMExecutor($em, $purger); $executor->execute($loader->getFixtures()); static::$_em = $em; } }
/** * Get an instance of a DBAL Connection * * @param sting $name the connection name * @return Doctrine\DBAL\Connection */ public function newConnection() { $configuration = new DBAL\Configuration(); $logger = new MSQLLogger($this); $configuration->setSQLLogger($logger); return DBAL\DriverManager::getConnection($this->config, $configuration); }
/** * {@inheritdoc} */ public static function create($conn, Configuration $config, EventManager $eventManager = null) { if (!$config->getMetadataDriverImpl()) { throw ORMException::missingMappingDriverImpl(); } switch (true) { case is_array($conn): if (!$eventManager) { $eventManager = new EventManager(); } if (isset($conn['prefix']) && $conn['prefix']) { $eventManager->addEventListener(Events::loadClassMetadata, new TablePrefix($conn['prefix'])); } $conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, $eventManager); break; case $conn instanceof Connection: if ($eventManager !== null && $conn->getEventManager() !== $eventManager) { throw ORMException::mismatchedEventManager(); } break; default: throw new \InvalidArgumentException("Invalid argument: " . $conn); } return new self($conn, $config, $conn->getEventManager()); }
public function testDBAL() { $connectionParams = ['dbname' => $this->conf['dbname'], 'user' => $this->conf['username'], 'password' => $this->conf['password'], 'host' => $this->conf['host'], 'driver' => 'pdo_pgsql']; $conn = DriverManager::getConnection($connectionParams); $conn->exec(file_get_contents(__DIR__ . '/fixtures/createTable.sql')); $sth = $conn->query("SELECT * FROM PUBLIC.TBUPSERTEXAMPLE"); $result = $sth->fetchAll(); $this->assertEquals(0, count($result)); $conn->transactional(function ($conn) { Upsert::createFromDBAL($conn)->exec('PUBLIC.TBUPSERTEXAMPLE', ['key1' => 'key1', 'key2' => 'key2', 'key3' => 'key3', 'key4' => 'key4'], ['value1' => 'value1', 'value2' => 'value2', 'value3' => 'value3', 'value4' => null, 'value5' => 'value5']); }); $sth = $conn->query("SELECT * FROM PUBLIC.TBUPSERTEXAMPLE"); $result = $sth->fetchAll(); $this->assertEquals('value1', $result[0]['value1']); $this->assertEquals('value2', $result[0]['value2']); $this->assertEquals('value3', $result[0]['value3']); $this->assertEquals(null, $result[0]['value4']); $this->assertEquals('value5', $result[0]['value5']); $conn->transactional(function ($conn) { Upsert::createFromDBAL($conn)->exec('PUBLIC.TBUPSERTEXAMPLE', ['key1' => 'key1', 'key2' => 'key2', 'key3' => 'key3', 'key4' => 'key4'], ['value1' => 'value1', 'value2' => 'value2', 'value3' => 'value3', 'value4' => 'value4', 'value5' => 'value5']); }); $sth = $conn->query("SELECT * FROM PUBLIC.TBUPSERTEXAMPLE"); $result = $sth->fetchAll(); $this->assertEquals('value1', $result[0]['value1']); $this->assertEquals('value2', $result[0]['value2']); $this->assertEquals('value3', $result[0]['value3']); $this->assertEquals('value4', $result[0]['value4']); $this->assertEquals('value5', $result[0]['value5']); $conn->exec(file_get_contents(__DIR__ . '/fixtures/dropTable.sql')); }
/** * Sets up the tests */ public function setUp() { $dataPath = realpath(__DIR__ . '/..'); $this->config = parse_ini_file($dataPath . '/data/entities.doctrine.ini', true); $connection = DriverManager::getConnection(['url' => $this->config['databaseUrl']]); $this->transactor = new DoctrineTransactor($connection); $this->idAccessorRegistry = new IdAccessorRegistry(); $repositoryFactory = new RepositoryFactory($this->config, $connection, $this->transactor); $this->idAccessorRegistry->registerIdAccessors(User::class, function (User $user) { return $user->getId(); }, function (User $user, $id) { $user->setId($id); }); $strategy = new RecursiveDirectoryStrategy($this->config['definitionPath']); $locator = new Locator([$strategy]); $this->builder = new EntityBuilder($locator, $repositoryFactory); $this->repo = $repositoryFactory->forEntity(User::class); $this->entityRegistry = $repositoryFactory->getEntityRegistry(); $this->unitOfWork = new UnitOfWorkAccessDecorator($repositoryFactory->getUnitOfWork()); $this->dataMapper = $this->unitOfWork->getDataMapper(User::class); /** * The Ids are purposely unique so that we can identify them as such without having to first insert them to * assign unique Ids * They are also purposely set to 724, 1987, and 345 so that they won't potentially overlap with any default * values set to the Ids */ $this->entity1 = new User(724, "foo"); $this->entity2 = new User(1987, "bar"); $this->entity3 = new User(345, "baz"); }
public function handleDatabaseCreate(Args $args, IO $io, Command $command) { $params = $this->app['doctrine.settings']['dbal']; $name = $params['dbname'] ?? null; if (false == $name) { $io->writeLine("<error>Database's name is missing from provided settings.</error>"); return 1; } unset($params['dbname']); $tmpConn = DriverManager::getConnection($params); if (!$tmpConn->getDriver()->getDatabasePlatform() instanceof MySqlPlatform) { $io->writeLine("<warn>This command only support MySQL database, sorry!</warn>"); return 1; } $shouldNotCreateDatabase = in_array($name, $tmpConn->getSchemaManager()->listDatabases()); if ($shouldNotCreateDatabase) { $io->writeLine("<warn>Database '{$name}' already exists.</warn>"); return 1; } $sql = "CREATE DATABASE `{$name}`"; if (isset($params['collation']) && isset($params['charset'])) { $sql .= ' CHARACTER SET ' . $params['charset'] . ' COLLATE ' . $params['collation']; } $tmpConn->executeUpdate($sql); $tmpConn->close(); $io->writeLine("<info>Database '{$name}' created.</info>"); return 0; }
/** * @return \Doctrine\DBAL\Connection */ public static function getConnection() { //setup configuration for connect to the database $configuration = array('dbname' => getenv("DB_NAME"), 'user' => getenv("DB_USER"), 'password' => getenv("DB_PASS"), 'host' => getenv("DB_HOST"), 'driver' => getenv("DB_DRIVER"), 'charset' => getenv("DB_CHARSET")); //connect to the database using Doctrine\DBAL library return DriverManager::getConnection($configuration); }
public function testSwitchShardWithOpenTransactionException() { $conn = DriverManager::getConnection(array('wrapperClass' => 'Doctrine\\Shards\\DBAL\\PoolingShardConnection', 'driver' => 'pdo_sqlite', 'global' => array('memory' => true), 'shards' => array(array('id' => 1, 'memory' => true)), 'shardChoser' => 'Doctrine\\Shards\\DBAL\\ShardChoser\\MultiTenantShardChoser')); $conn->beginTransaction(); $this->setExpectedException('Doctrine\\Shards\\DBAL\\ShardingException', 'Cannot switch shard when transaction is active.'); $conn->connect(1); }
/** * Initialize bindings after the application is initialized and config is loaded * * @param array $configuration */ public function postBind(array $configuration) { $this->container->instance('config', $configuration); $this->container->singleton('connection', function ($container) { $connectionParams = $container['config']['database']; return DoctrineDriverManager::getConnection($connectionParams, new DbalConfiguration()); }); $this->container->singleton('db', function ($container) { return new Database($container['connection']); }); $this->container->singleton('column-helper', function () { return new ColumnHelper(); }); $this->container->singleton('mapper', function ($container) { return new Mapper($container['column-helper']); }); $this->container->singleton('formatter', function () { return new Formatter(); }); $this->container->singleton('form-template', function () { return new BootstrapTemplate(); }); $this->container->singleton('form-generator', function ($container) { $generatorClass = $container['config']['generators']['form']; $generator = new $generatorClass(); $generator->setContainer($container); $generator->setTemplate($container['form-template']); return $generator; }); }
/** * @brief Get default connection parameters for a given DBMS. * @param string $type DBMS type * @param array $additionalConnectionParams Additional connection parameters * @return \OC\DB\Connection */ public function getConnection($type, $additionalConnectionParams) { $normalizedType = $this->normalizeType($type); $eventManager = new \Doctrine\Common\EventManager(); switch ($normalizedType) { case 'mysql': // Send "SET NAMES utf8". Only required on PHP 5.3 below 5.3.6. // See http://stackoverflow.com/questions/4361459/php-pdo-charset-set-names#4361485 $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit()); break; case 'oci': $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\OracleSessionInit()); break; case 'sqlite3': $eventManager->addEventSubscriber(new SQLiteSessionInit()); break; } $connection = \Doctrine\DBAL\DriverManager::getConnection(array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams), new \Doctrine\DBAL\Configuration(), $eventManager); switch ($normalizedType) { case 'sqlite3': // Sqlite doesn't handle query caching and schema changes // TODO: find a better way to handle this /** @var $connection \OC\DB\Connection */ $connection->disableQueryStatementCaching(); break; } return $connection; }
protected function getDbalConnection() { $config = new \Doctrine\DBAL\Configuration(); $params = $this->getServiceLocator()->get('Config'); $params = $params['doctrine']['connection']['orm_default']['params']; return DriverManager::getConnection($params, $config); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->getApp()->getContainer()->get('logger')->critical('Dropping database attempt'); $env = $this->getApp()->getContainer()->get('ENV'); if ($env != 'test' && !$input->getOption('force')) { throw new \Exception(sprintf('Access denied - can not drop database in "%s" environment', $env)); } $connection = $this->getDoctrineConnection(); $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false); if (!$name) { throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname'."); } unset($params['dbname']); $tmpConnection = DriverManager::getConnection($params); // Only quote if we don't have a path if (!isset($params['path'])) { $name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name); } $error = false; try { $tmpConnection->getSchemaManager()->dropDatabase($name); $output->writeln(sprintf('<info>Dropped database <comment>%s</comment></info>', $name)); } catch (\Exception $e) { $output->writeln(sprintf('<error>Could not drop database <comment>%s</comment></error>', $name)); $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); $error = true; } $tmpConnection->close(); return $error ? 1 : 0; }
/** * Create service with name * * @param ServiceLocatorInterface $serviceLocator * @param $name * @param $requestedName * @throws \InvalidArgumentException * @return mixed */ public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { /** @var $config ProcessingConfig */ $config = $serviceLocator->get("processing_config"); $connector = $config->getConnectors()[$requestedName]; if (!isset($connector['dbal_connection'])) { throw new \InvalidArgumentException(sprintf('Missing dbal_connection for sql connector %s', $requestedName)); } if (!isset($connector['table'])) { throw new \InvalidArgumentException(sprintf('Missing table definition for sql connector %s', $requestedName)); } $appConfig = $serviceLocator->get('config'); if (!isset($appConfig['prooph.link.sqlconnector']['connections'][$connector['dbal_connection']])) { throw new \InvalidArgumentException(sprintf('The DBAL connection %s can not be found. Please check config/autoload/sqlconnector.local.php!', $connector['dbal_connection'])); } $actionEventDispatcher = null; $listeners = null; if (isset($appConfig['prooph.link.sqlconnector']['action_listeners'][$requestedName])) { $actionEventDispatcher = new Zf2ActionEventDispatcher([$requestedName]); if (!is_array($appConfig['prooph.link.sqlconnector']['action_listeners'][$requestedName])) { throw new \InvalidArgumentException(sprintf("Key prooph.link.sqlconnector.action_listeners.{$requestedName} of config should be of type array. Got %s", gettype($appConfig['prooph.link.sqlconnector']['action_listeners'][$requestedName]))); } foreach ($appConfig['prooph.link.sqlconnector']['action_listeners'][$requestedName] as $listenerAlias) { $listenerAggregate = $serviceLocator->get($listenerAlias); if (!$listenerAggregate instanceof ActionEventListenerAggregate) { throw new \InvalidArgumentException(sprintf("Action listeners for sqlconnector %s should be of type Prooph\\Common\\ActionEventListenerAggregate. Got %s", $requestedName, is_object($listenerAggregate) ? get_class($listenerAggregate) : gettype($listenerAggregate))); } $listeners[] = $listenerAggregate; } } return new DoctrineTableGateway(DriverManager::getConnection($appConfig['prooph.link.sqlconnector']['connections'][$connector['dbal_connection']]), $connector['table'], $actionEventDispatcher, $listeners); }
/** * setup configuration for Doctrine Dbal. * * @param array $db_config array config for override the default configuration. */ public function setupConfigurationDbal(array $db_config = []) { $dbal_config = new Configuration(); if (empty($db_config)) { //setup connection configuration. $config = new SystemConfig(); $config->load('db'); $db_params = $config->get('ALL', 'db'); unset($config, $db_params['table_prefix']); } else { $db_params = $db_config; unset($db_params['table_prefix']); } $dbal_config->setSQLLogger(new \System\Libraries\Db\Logger()); try { $this->Conn = DriverManager::getConnection($db_params, $dbal_config); $this->Conn->connect(); } catch (\Doctrine\DBAL\DBALException $e) { http_response_code(500); echo $e->getMessage(); exit; } $this->Conn->setFetchMode(\PDO::FETCH_OBJ); unset($dbal_config, $db_params); }
private function registerServices() { $this['db'] = $this->share(function ($app) { return DriverManager::getConnection(array('driver' => 'pdo_mysql', 'host' => $app['db_host'], 'dbname' => $app['db_name'], 'user' => $app['db_user'], 'password' => $app['db_password'])); }); $this['project_list'] = $this->share(function () { return new ProjectList(); }); $this['run_storage'] = $this->share(function ($app) { return new MysqlStorage($app['db'], __DIR__ . '/../../../data/output_files'); }); $this['workspace'] = $this->share(function ($app) { return new Workspace($app['project_list'], $app['run_storage']); }); $this['template_loader'] = $this->share(function ($app) { $loader = new TemplateLoader(); $loader->addDirectory(__DIR__ . '/../../../assets/templates'); return $loader; }); $this->extend('twig', function ($twig, $app) { $twig->addExtension(new DateExtension($app['translator'])); $twig->addExtension(new \Twig_Extension_StringLoader()); return $twig; }); $this->extend('form.extensions', function ($extensions, $app) { $extensions[] = new BehatLauncherExtension(); return $extensions; }); }
protected function getConnection() { $pdo = new PDO('sqlite::memory:'); $this->connection = DriverManager::getConnection(array('pdo' => $pdo)); DoctrineConfig::createTable($this->connection); return $this->createDefaultDBConnection($pdo, ':memory:'); }
public static function getConnection() { if (self::$conn == null) { self::$conn = \Doctrine\DBAL\DriverManager::getConnection(array('driver' => $GLOBALS['DC2_DRIVER'], 'dbname' => $GLOBALS['DC2_DBNAME'], 'user' => $GLOBALS['DC2_USER'], 'password' => $GLOBALS['DC2_PASSWORD'], 'memory' => true)); } return self::$conn; }