/** * @param string $databaseName * @return \MongoDB\Database */ public static function connect($databaseName) { if (static::$_mongoClient == null) { // MongoDB Client that will unserialize everything as PHP Arrays consistent with the legacy driver (which our code was built on) // see http://mongodb.github.io/mongo-php-library/classes/client/#example static::$_mongoClient = new Client(MONGODB_CONN, [], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]); } return static::$_mongoClient->selectDatabase($databaseName); }
/** * Create a new database connection instance. * * @param array $config */ public function __construct(array $config) { $this->config = $config; // Build the connection string $dsn = $this->getDsn($config); // You can pass options directly to the MongoDB constructor $options = array_get($config, 'options', []); // Create the connection $this->connection = $this->createConnection($dsn, $config, $options); // Select database $this->db = $this->connection->selectDatabase($config['database']); $this->useDefaultPostProcessor(); }
/** * @return MongoDBDatabase * * @throws InvalidArgumentException */ protected function getDatabaseConnection() : MongoDBDatabase { if (!$this->databaseConnection) { $client = new MongoDBClient($this->getConnectionString()); $this->databaseConnection = $client->selectDatabase($this->configuration->getDatabaseName()); } return $this->databaseConnection; }
/** * {@inheritdoc} */ protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $client = new Client($input->getOption('server')); $db = $client->selectDatabase($input->getArgument('database')); $output->writeln("<info>✓ Successfully established database connection</info>", $output::VERBOSITY_VERBOSE); $databaseMigrationsLockCollection = $db->selectCollection('DATABASE_MIGRATIONS_LOCK'); $databaseMigrationsLockCollection->updateOne(['locked' => ['$exists' => true]], ['$set' => ['locked' => false]], ['upsert' => true]); $output->writeln("<info>✓ Successfully released migration lock</info>"); }
/** * Return a new Database instance. * * If a logger callable was defined, a LoggableDatabase will be returned. * * @see Connection::selectDatabase() * @param string $name * @return Database */ protected function doSelectDatabase($name) { $mongoDB = $this->mongoClient->selectDatabase($name); $numRetries = $this->config->getRetryQuery(); $loggerCallable = $this->config->getLoggerCallable(); return new Database($this, $mongoDB, $this->eventManager, $numRetries); // return $loggerCallable !== null // ? new LoggableDatabase($this, $mongoDB, $this->eventManager, $numRetries, $loggerCallable) // : new Database($this, $mongoDB, $this->eventManager, $numRetries); }
public function testSelectDatabasePassesReadPreferenceAndWriteConcern() { $databaseOptions = ['readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY)]; $client = new Client($this->getUri()); $database = $client->selectDatabase($this->getDatabaseName(), $databaseOptions); $debug = $database->__debugInfo(); $this->assertInstanceOf('MongoDB\\Driver\\ReadPreference', $debug['readPreference']); $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode()); $this->assertInstanceOf('MongoDB\\Driver\\WriteConcern', $debug['writeConcern']); $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW()); }
/** * @before */ protected function setUpMongoClient() { $client = new Client(); $this->database = $client->selectDatabase('yadm_test'); foreach ($this->database->listCollections() as $collectionInfo) { if ('system.indexes' == $collectionInfo->getName()) { continue; } $this->database->dropCollection($collectionInfo->getName()); } }
public function getCollections($databaseName) { /** @var Database $database */ $database = $this->client->selectDatabase($databaseName); $collections = $database->listCollections(); $result = []; /** @var CollectionInfo $item */ foreach ($collections as $item) { $result[] = ['name' => $item->getName(), 'cappedSize' => $item->getCappedSize(), 'cappedMax' => $item->getCappedMax()]; } return $result; }
public function testSelectDatabasePassesOptions() { $databaseOptions = ['readConcern' => new ReadConcern(ReadConcern::LOCAL), 'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), 'typeMap' => ['root' => 'array'], 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY)]; $client = new Client($this->getUri()); $database = $client->selectDatabase($this->getDatabaseName(), $databaseOptions); $debug = $database->__debugInfo(); $this->assertInstanceOf('MongoDB\\Driver\\ReadConcern', $debug['readConcern']); $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel()); $this->assertInstanceOf('MongoDB\\Driver\\ReadPreference', $debug['readPreference']); $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode()); $this->assertInternalType('array', $debug['typeMap']); $this->assertSame(['root' => 'array'], $debug['typeMap']); $this->assertInstanceOf('MongoDB\\Driver\\WriteConcern', $debug['writeConcern']); $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW()); }
/** * @param array $options */ public function __construct(array $options = array()) { if (isset($options['db']) && $options['db'] instanceof Database) { $this->_db = $options['db']; } else { if (!empty($options['client']) && $options['client'] instanceof Client) { $connection = $options['client']; } elseif (!empty($options['serverString'])) { $connection = new Client($options['serverString']); } else { $connection = new Client(); } $databaseName = !empty($options['dbName']) ? $options['dbName'] : 'jormakalevi'; $this->_db = $connection->selectDatabase($databaseName); } }
/** * Setup MongoDB connection * * $mongoDbConf must contain * - db: the name of mongo database to use * * and can contain * - uri * - uriOptions * - driverOptions * * @see \MongoDB\Client for $mongoConf * @param array $mongoDbConf * @return $this */ public function setupMongoDb(array $mongoDbConf) { $mongoDbConf += ['uri' => 'mongodb://localhost:27017', 'uriOptions' => [], 'driverOptions' => [], 'db' => '']; $client = new Client($mongoDbConf['uri'], $mongoDbConf['uriOptions'], $mongoDbConf['driverOptions']); $this->db = $client->selectDatabase($mongoDbConf['db']); return $this; }
/** * @return \MongoDB\Database */ protected function getCheckDatabase() { $client = new Client('mongodb://localhost', ['connect' => true]); return $client->selectDatabase('mongo-php-adapter'); }
/** * Driver constructor. * * @param MongoDBClient $connection * @param string $database */ public function __construct(MongoDBClient $connection, $database) { $this->connection = $connection; $this->database = $connection->selectDatabase($database); }
public function testCollectionReadPreferencesAreAppliedToDatabase() { /** @var PHPUnit_Framework_MockObject_MockObject|TripodTestConfig $mockConfig */ $mockConfig = $this->getMock('TripodTestConfig', array('getDatabase')); $mockConfig->loadConfig(json_decode(file_get_contents(dirname(__FILE__) . '/data/config.json'), true)); $mockConfig->expects($this->exactly(2))->method('getDatabase')->withConsecutive(array('tripod_php_testing', 'rs1', ReadPreference::RP_SECONDARY_PREFERRED), array('tripod_php_testing', 'rs1', ReadPreference::RP_NEAREST))->will($this->returnCallback(function () { $mongo = new Client(); return $mongo->selectDatabase('tripod_php_testing'); })); $mockConfig->getCollectionForCBD('tripod_php_testing', 'CBD_testing', ReadPreference::RP_SECONDARY_PREFERRED); $mockConfig->getCollectionForCBD('tripod_php_testing', 'CBD_testing', ReadPreference::RP_NEAREST); }
/** * Select database * * @param string $database */ public function selectDatabase($database) { $this->db = $this->connection->selectDatabase($database); }
/** * {@inheritdoc} */ protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $client = new MongoDB\Client($input->getOption('server')); $db = $client->selectDatabase($input->getArgument('database')); $output->writeln("<info>✓ Successfully established database connection</info>", $output::VERBOSITY_VERBOSE); $directories = $input->getArgument('migration-directories'); foreach ($directories as $directory) { if (!is_dir($directory)) { throw new Console\Exception\InvalidArgumentException("'{$directory}' is no valid directory"); } $output->writeln("<comment>Iterating '{$directory}' for potential migrations classes</comment>", $output::VERBOSITY_DEBUG); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory), \RecursiveIteratorIterator::LEAVES_ONLY); /** @var \SplFileInfo $file */ foreach ($iterator as $file) { if ($file->getBasename('.php') === $file->getBasename()) { continue; } require_once $file->getRealPath(); $output->writeln("<comment>Loaded potential migration '{$file->getRealPath()}'</comment>", $output::VERBOSITY_DEBUG); } } /** @var MongoDbMigrations\MigrationInterface[] $migrations */ $migrations = []; foreach (get_declared_classes() as $className) { $reflectionClass = new \ReflectionClass($className); if ($reflectionClass->implementsInterface(MongoDbMigrations\MigrationInterface::class)) { /** @var MongoDbMigrations\MigrationInterface $newInstance */ $newInstance = $reflectionClass->newInstance(); $id = md5($newInstance->getId()); if (isset($migrations[$id])) { $existingMigrationClass = get_class($migrations[$id]); throw new Console\Exception\RuntimeException("Found a non unique migration id '{$newInstance->getId()}' in '{$reflectionClass->getName()}', already defined by migration class '{$existingMigrationClass}'"); } $migrations[$id] = $newInstance; $output->writeln("<comment>Found valid migration class '{$reflectionClass->getName()}'</comment>", $output::VERBOSITY_DEBUG); } } $migrationClassesCount = count($migrations); $output->writeln("<info>✓ Found {$migrationClassesCount} valid migration classes</info>", $output::VERBOSITY_VERBOSE); uasort($migrations, function (MongoDbMigrations\MigrationInterface $a, MongoDbMigrations\MigrationInterface $b) { if ($a->getCreateDate() === $b->getCreateDate()) { return 0; } return $a->getCreateDate() < $b->getCreateDate() ? -1 : 1; }); $output->writeln("<info>✓ Reordered all migration classes according to their create date</info>", $output::VERBOSITY_VERBOSE); $databaseMigrationsLockCollection = $db->selectCollection('DATABASE_MIGRATIONS_LOCK'); $databaseMigrationsLockCollection->createIndex(['locked' => 1]); $currentLock = $databaseMigrationsLockCollection->findOneAndReplace(['locked' => ['$exists' => true]], ['locked' => true, 'last_locked_date' => new MongoDB\BSON\UTCDatetime((new \DateTime())->getTimestamp() * 1000)], ['upsert' => true]); if ($currentLock !== null && $currentLock->locked === true) { throw new Console\Exception\RuntimeException('Concurrent migrations are not allowed'); } try { $output->writeln("<info>✓ Successfully acquired migration lock</info>", $output::VERBOSITY_VERBOSE); $databaseMigrationsCollection = $db->selectCollection('DATABASE_MIGRATIONS'); $databaseMigrationsCollection->createIndex(['migration_id' => 1], ['unique' => true, 'background' => false]); $progress = new Console\Helper\ProgressBar($output, count($migrations)); switch ($output->getVerbosity()) { case $output::VERBOSITY_VERBOSE: $format = 'verbose'; break; case $output::VERBOSITY_VERY_VERBOSE: $format = 'very_verbose'; break; case $output::VERBOSITY_DEBUG: $format = 'debug'; break; default: $format = 'normal'; } $progress->setFormat($format); $progress->start(); $executedMigrations = 0; foreach ($migrations as $id => $migration) { $progress->advance(); if ($migration instanceof MongoDbMigrations\ContextualMigrationInterface && $input->getOption('contexts') !== []) { if (array_intersect($migration->getContexts(), $input->getOption('contexts')) === []) { continue; } } if (!$migration instanceof MongoDbMigrations\RunAlwaysMigrationInterface) { if ($databaseMigrationsCollection->count(['migration_id' => $id]) > 0) { continue; } } $migration->execute($db); $executedMigrations++; $migrationInfo = ['migration_id' => $id, 'migration_class' => get_class($migration), 'last_execution_date' => new MongoDB\BSON\UTCDatetime((new \DateTime())->getTimestamp() * 1000), 'run_always' => $migration instanceof MongoDbMigrations\RunAlwaysMigrationInterface]; if ($migration instanceof MongoDbMigrations\ContextualMigrationInterface) { $migrationInfo['contexts'] = $migration->getContexts(); } $databaseMigrationsCollection->updateOne(['migration_id' => $id], ['$set' => $migrationInfo], ['upsert' => true]); } $progress->finish(); $output->writeln(''); $output->writeln("<info>✓ Successfully executed {$executedMigrations} migrations</info>"); } catch (\Exception $e) { throw new Console\Exception\RuntimeException('Error while executing migrations', $e->getCode(), $e); } finally { $databaseMigrationsLockCollection->updateOne(['locked' => true], ['$set' => ['locked' => false]]); $output->writeln("<info>✓ Successfully released migration lock</info>", $output::VERBOSITY_VERBOSE); } }
/** * Add $triples about a given $subject to Mongo. Only $triples with subject matching $subject will be added, others will be ignored. * Make them quads with a $context * @param $subject * @param array $triples * @param string $storeName * @param string $podName * @param null $context * @param null $allowableTypes */ public function loadTriplesAbout($subject, array $triples, $storeName, $podName, $context = null, $allowableTypes = null) { $context = $context == null ? Config::getInstance()->getDefaultContextAlias() : $this->labeller->uri_to_alias($context); if (array_key_exists($podName, $this->collections)) { $collection = $this->collections[$podName]; } else { $m = new Client(Config::getInstance()->getConnStr($storeName), [], ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]); $collection = $m->selectDatabase($storeName)->selectCollection($podName); } $graph = new MongoGraph(); foreach ($triples as $triple) { $triple = rtrim($triple); $parts = preg_split("/\\s/", $triple); $subject = trim($parts[0], '><'); $predicate = trim($parts[1], '><'); $object = $this->extract_object($parts); if ($this->isUri($object)) { $graph->add_resource_triple($subject, $predicate, $object); } else { $graph->add_literal_triple($subject, $predicate, $object); } } if ($allowableTypes != null && is_array($allowableTypes)) { $types = $graph->get_resource_triple_values($subject, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); if ($types == null || empty($types)) { return; } else { foreach ($types as $type) { if (in_array($type, $allowableTypes)) { $this->saveCBD($subject, $graph, $collection, $context); return; } } return; } } $this->saveCBD($subject, $graph, $collection, $context); }
<?php namespace CASS\Application\Bundles\MongoDB; use function DI\object; use function DI\factory; use function DI\get; use DI\Container; use MongoDB\Database; use MongoDB\Client; return ['php-di' => [Database::class => factory(function (Container $container) { $env = $container->get('config.env'); $config = $container->get('config.mongodb'); $mongoClient = new Client($config['server'] ?? 'mongodb://127.0.0.1:27017', $config['options'] ?? ['connect' => true], $config['driver_options'] ?? []); return $mongoClient->selectDatabase(sprintf('%s_%s', $config['db_prefix'] ?? 'cass', $env)); })]];