コード例 #1
0
 /**
  * @Named("conn=SqlLogger, logger=SqlLogger")
  */
 public function __construct(Connection $conn, LoggerInterface $logger = null)
 {
     $this->conn = $conn;
     if ($logger !== null) {
         $this->conn->getConfiguration()->setSQLLogger(new SqlLoggerPsr3Adapter($logger));
     }
 }
コード例 #2
0
ファイル: OptionWrapper.php プロジェクト: engelju/kexpgrabber
 public function deleteOption($key)
 {
     $stmt = $this->db->prepare("DELETE FROM options WHERE key IS :key");
     $stmt->bindParam("key", $key, \PDO::PARAM_STR);
     $stmt->execute();
     $this->db->commit();
 }
コード例 #3
0
 public function __construct(Connection $con, MethodPersister $methodPersister, PropertyPersister $propertyPersister, ConstantPersister $constantPersister)
 {
     $this->con = $con;
     $this->insertStmt = $con->prepare(self::INSERT_STMT);
     $this->methodPersister = $methodPersister;
     $this->propertyPersister = $propertyPersister;
     $this->constantPersister = $constantPersister;
 }
コード例 #4
0
 private function listenForEcho(Connection $db)
 {
     $readStatement = $db->prepare(sprintf(self::READ_HEARTBEAT_TOKEN_SQL, $this->heartbeatTable, $this->heartbeatTableColumn));
     $readStatement->execute(array($this->heartbeatToken));
     if ($readStatement->fetch() === false) {
         throw new DBALException("Error during listening for heartbeat echo");
     }
 }
コード例 #5
0
 /**
  * Writes the current session data to the database.
  *
  * @param FilterResponseEvent $event The event object
  */
 public function onKernelResponse(FilterResponseEvent $event)
 {
     if (!$this->hasUser() || !$this->isContaoMasterRequest($event)) {
         return;
     }
     $user = $this->getUserObject();
     $this->connection->prepare('UPDATE ' . $user->getTable() . ' SET session=? WHERE id=?')->execute([serialize($this->getSessionBag()->all()), $user->id]);
 }
コード例 #6
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws \Exception
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dump = file_get_contents($this->configPath . '/db.sql');
     $statement = $this->connection->prepare($dump);
     $statement->execute();
     if ($statement->errorCode() != 0) {
         throw new \Exception('Error while creating Database');
     }
     $output->writeln('<info>Database created successfully</info>');
 }
コード例 #7
0
 /**
  * @inheritDoc
  */
 public function persist(array $uncommittedEvents)
 {
     if (!method_exists($this->connection, 'insert')) {
         throw new \RuntimeException('The provided connection does not support inserting records using the "insert" method, please ' . 'choose a different connection type that does');
     }
     /** @var Stream\Event $event */
     foreach ($uncommittedEvents as $event) {
         $this->connection->insert($this->options[self::OPTION_TABLENAME], ['id' => (string) $event->id(), 'stream_id' => (string) $event->stream()->id(), 'sequence' => $event->sequence(), 'payload' => json_encode($event->payload()), 'emitted_at' => $event->emittedAt()->format('Y-m-d H:i:s')]);
     }
 }
コード例 #8
0
ファイル: RemoteAddressLookup.php プロジェクト: zource/zource
 public function lookup($remoteAddress)
 {
     return null;
     //
     $query = "SELECT * FROM `ip2location_db3` WHERE INET_ATON(:ip) <= ip_to LIMIT 1";
     $result = $this->connection->fetchAssoc($query, ['ip' => $remoteAddress]);
     if ($result) {
         return new RemoteAddressEntry($result['country_code'] === '-' ? null : $result['country_code'], $result['country_name'] === '-' ? null : $result['country_name'], $result['region_name'] === '-' ? null : $result['region_name'], $result['city_name'] === '-' ? null : $result['city_name']);
     }
     return null;
 }
コード例 #9
0
 /**
  * @throws \Doctrine\DBAL\DBALException
  */
 public function updateCount()
 {
     $sql = 'UPDATE tags
         SET tags.count = (
             SELECT COUNT(review_tag.tag_id)
             FROM review_tag
             WHERE review_tag.tag_id = tags.id
             GROUP BY review_tag.tag_id
         )';
     $this->connection->executeQuery($sql);
 }
コード例 #10
0
ファイル: Flipper.php プロジェクト: blackshawk/flipper
 /**
  * Execute a query and map it to your requested types. Returns an array of your rows.
  * @param string|array $requestedTypes
  * @param string|object|Statement $sql
  * @param array $params
  * @param string|array $split
  * @throws \InvalidArgumentException
  * @return array
  */
 public function query($requestedTypes, $sql, $params = [], $split = [])
 {
     if (is_null($requestedTypes) || empty($requestedTypes)) {
         throw new \InvalidArgumentException('You must specify at least one type to map your results against.');
     }
     if (!$sql instanceof Statement) {
         $sql = $this->connection->prepare($sql);
     }
     $sql->execute($params);
     $results = $sql->fetchAll();
     return $this->mapper->map($requestedTypes, $results, $split);
 }
コード例 #11
0
ファイル: DbDetector.php プロジェクト: dongww/web-monitor
 /**
  * @param ResourceInterface $resource
  *
  * @param  array            $options
  *
  * @return ResponseInterface
  */
 public function probe(ResourceInterface $resource = null, array $options = [])
 {
     $message = sprintf("\nDB DETECTOR:\n====================================\nconnected %s\n====================================\nDRIVER:%s\nDBNAME:%s\n", $this->connectionParams['host'], $this->connectionParams['driver'], $this->connectionParams['dbname']);
     $successful = false;
     try {
         if ($this->connection->ping()) {
             $successful = true;
         }
     } catch (\Exception $e) {
         $message = sprintf("\nDB DETECTOR:\n====================================\nCODE: %s\nERROR MESSAGE: %s\n", $e->getCode(), IconvHelper::convert($e->getMessage()));
     }
     return new DbDetectorResponse($successful, $message, $this->connectionParams);
 }
コード例 #12
0
ファイル: Connection.php プロジェクト: OmondiKevin/ADT_MTRH
 /**
  * rollbackSavePoint
  * releases given savepoint
  *
  * @param string $savepoint     name of a savepoint to rollback to
  * @return void
  */
 public function rollbackSavepoint($savepoint)
 {
     if (!$this->_platform->supportsSavepoints()) {
         throw ConnectionException::savepointsNotSupported();
     }
     $this->_conn->exec($this->_platform->rollbackSavePoint($savepoint));
 }
コード例 #13
0
ファイル: VideoWrapper.php プロジェクト: engelju/kexpgrabber
 public function deleteVideo(Video $video)
 {
     $stmt = $this->db->prepare("DELETE FROM videos WHERE id IS :id");
     $stmt->bindParam("id", $video->getId());
     $stmt->execute();
     $this->db->commit();
 }
コード例 #14
0
 protected function executeQueries(array $queries, \Closure $logger = null)
 {
     $this->conn->beginTransaction();
     try {
         foreach ($queries as $query) {
             if (null !== $logger) {
                 $logger($query);
             }
             $this->conn->query($query);
         }
         $this->conn->commit();
     } catch (\Exception $e) {
         $this->conn->rollback();
         throw $e;
     }
 }
コード例 #15
0
 /**
  * {@inheritDoc}
  */
 protected function batchInsertPendingVersions(array $pendingVersions)
 {
     if (count($pendingVersions) === 0) {
         return;
     }
     $versionTable = $this->getVersionTable();
     $insert = sprintf('INSERT INTO %s ', $versionTable);
     $columns = $this->getVersionColumns();
     $placeholders = sprintf('(%s)', implode(',', array_fill(0, count($columns), '?')));
     $multiplePlaceholders = array_fill(0, count($pendingVersions), $placeholders);
     $params = [];
     foreach ($pendingVersions as $pendingVersion) {
         $params = array_merge($params, $this->getSQLParamsFromVersion($pendingVersion));
     }
     $values = implode(',', $multiplePlaceholders);
     $query = sprintf('%s(%s) VALUES %s', $insert, implode(',', $columns), $values);
     $this->connection->executeQuery($query, $params);
 }
コード例 #16
0
 /**
  * {@inheritdoc}
  */
 public function rewind()
 {
     if ($this->statement) {
         throw new InvalidMethodCallException('Cannot rewind a PDOStatement');
     }
     $this->statement = $this->connection->prepare($this->query);
     $this->statement->execute($this->parameters);
     $this->next();
 }
コード例 #17
0
 /**
  * @return string
  */
 private function getCurrentVersion()
 {
     /** @var $result Statement */
     $result = $this->db->query('SELECT version FROM schema');
     $version = $result->fetchColumn();
     if (!$version) {
         $version = '0';
         $this->db->exec("INSERT INTO schema VALUES ('{$version}')");
     }
     return $version;
 }
コード例 #18
0
ファイル: Connection.php プロジェクト: Kevin-ZK/vaneDisk
 /**
  * Ping the server
  *
  * When the server is not available the method returns FALSE.
  * It is responsibility of the developer to handle this case
  * and abort the request or reconnect manually:
  *
  * @example
  *
  *   if ($conn->ping() === false) {
  *      $conn->close();
  *      $conn->connect();
  *   }
  *
  * It is undefined if the underlying driver attempts to reconnect
  * or disconnect when the connection is not available anymore
  * as long it returns TRUE when a reconnect succeeded and
  * FALSE when the connection was dropped.
  *
  * @return bool
  */
 public function ping()
 {
     $this->connect();
     if ($this->_conn instanceof PingableConnection) {
         return $this->_conn->ping();
     }
     try {
         $this->query($this->platform->getDummySelectSQL());
         return true;
     } catch (DBALException $e) {
         return false;
     }
 }
コード例 #19
0
    /**
     * @return Statement
     */
    private function prepareSelectStatement()
    {
        if ($this->selectStatement === null) {
            $sql = <<<EOQ
SELECT event_id, event_name, event_payload, aggregate_version, took_place_at, metadata
FROM {$this->tableName}
WHERE aggregate_id = :aggregate_id
ORDER BY aggregate_version ASC
EOQ;
            $this->selectStatement = $this->connection->prepare($sql);
        }
        return $this->selectStatement;
    }
コード例 #20
0
ファイル: 201.php プロジェクト: nlegoff/Phraseanet
 public function patch($version, \DOMDocument $domct, \DOMDocument $domth, Connection $connbas, \unicode $unicode)
 {
     if ($version == "2.0.1") {
         $th = $domth->documentElement;
         $ct = $domct->documentElement;
         $xp = new DOMXPath($domth);
         $te = $xp->query("/thesaurus//te");
         for ($i = 0; $i < $te->length; $i++) {
             $id = $te->item($i)->getAttribute("id");
             $nid = (int) $te->item($i)->getAttribute("nextid");
             for ($n = $te->item($i)->firstChild; $n; $n = $n->nextSibling) {
                 if ($n->nodeName == "sy") {
                     $n->setAttribute("id", $id . "." . $nid);
                     $te->item($i)->setAttribute("nextid", ++$nid);
                 }
             }
         }
         $sql = "UPDATE record SET status=status & ~2";
         $stmt = $connbas->prepare($sql);
         $stmt->execute();
         $stmt->closeCursor();
         $sql = "DELETE FROM thit";
         $stmt = $connbas->prepare($sql);
         $stmt->execute();
         $stmt->closeCursor();
         $domct = new DOMDocument();
         $domct->load(__DIR__ . "/../../../lib/conf.d/blank_cterms.xml");
         $ct = $domct->documentElement;
         $ct->setAttribute("creation_date", $now = date("YmdHis"));
         $ct->setAttribute("modification_date", $now);
         $ct->setAttribute("version", $version = "2.0.2");
         $th->setAttribute("version", $version = "2.0.2");
         $th->setAttribute("modification_date", date("YmdHis"));
         $version = "2.0.2";
     }
     return $version;
 }
コード例 #21
0
ファイル: Connection.php プロジェクト: skoop/symfony-sandbox
 /**
  * Cancel any database changes done during the current transaction.
  *
  * this method can be listened with onPreTransactionRollback and onTransactionRollback
  * eventlistener methods
  *
  * @throws ConnectionException If the rollback operation failed.
  */
 public function rollback()
 {
     if ($this->_transactionNestingLevel == 0) {
         throw ConnectionException::noActiveTransaction();
     }
     $this->connect();
     if ($this->_transactionNestingLevel == 1) {
         $this->_transactionNestingLevel = 0;
         $this->_conn->rollback();
         $this->_isRollbackOnly = false;
     } else {
         $this->_isRollbackOnly = true;
         --$this->_transactionNestingLevel;
     }
 }
コード例 #22
0
ファイル: 200.php プロジェクト: nlegoff/Phraseanet
 public function patch($version, \DOMDocument $domct, \DOMDocument $domth, Connection $connbas, \unicode $unicode)
 {
     if ($version == "2.0.0") {
         $th = $domth->documentElement;
         $ct = $domct->documentElement;
         $xp = new DOMXPath($domth);
         $te = $xp->query("/thesaurus//te");
         for ($i = 0; $i < $te->length; $i++) {
             $id = $te->item($i)->getAttribute("id");
             if ($id[0] >= "0" && $id[0] <= "9") {
                 $te->item($i)->setAttribute("id", "T" . $id);
             }
         }
         $ct->setAttribute("version", $version = "2.0.1");
         $th->setAttribute("version", $version = "2.0.1");
         $th->setAttribute("modification_date", date("YmdHis"));
         $sql = "UPDATE thit SET value=CONCAT('T',value) WHERE LEFT(value,1)>='0' AND LEFT(value,1)<='9'";
         $stmt = $connbas->prepare($sql);
         $stmt->execute();
         $stmt->closeCursor();
         $version = "2.0.1";
     }
     return $version;
 }
コード例 #23
0
ファイル: 202.php プロジェクト: nlegoff/Phraseanet
 public function patch($version, \DOMDocument $domct, \DOMDocument $domth, Connection $connbas, \unicode $unicode)
 {
     if ($version == "2.0.2") {
         $th = $domth->documentElement;
         $ct = $domct->documentElement;
         $sql = "ALTER TABLE `pref` ADD `cterms_moddate` DATETIME";
         $stmt = $connbas->prepare($sql);
         $stmt->execute();
         $stmt->closeCursor();
         $sql = "ALTER TABLE `pref` ADD `thesaurus_moddate` DATETIME";
         $stmt = $connbas->prepare($sql);
         $stmt->execute();
         $stmt->closeCursor();
         $sql = "UPDATE pref SET thesaurus_moddate = :date1, cterms_moddate = :date2";
         $stmt = $connbas->prepare($sql);
         $stmt->execute([':date1' => $th->getAttribute("modification_date"), ':date2' => $ct->getAttribute("modification_date")]);
         $stmt->closeCursor();
         $ct->setAttribute("version", $version = "2.0.3");
         $th->setAttribute("version", $version = "2.0.3");
         $th->setAttribute("modification_date", date("YmdHis"));
         $version = "2.0.3";
     }
     return $version;
 }
コード例 #24
0
 /**
  * Returns the languages which are currently in use.
  *
  * @return array The languages array
  */
 private function getLanguagesInUse()
 {
     // Get all languages in use (see #6013)
     $query = "\n            SELECT language FROM tl_member\n            UNION SELECT language FROM tl_user\n            UNION SELECT REPLACE(language, '-', '_') FROM tl_page\n            WHERE type='root'\n        ";
     $statement = $this->connection->prepare($query);
     $statement->execute();
     $languages = [];
     while ($language = $statement->fetch(\PDO::FETCH_OBJ)) {
         if ('' === $language->language) {
             continue;
         }
         $languages[] = $language->language;
         // Also cache "de" if "de-CH" is requested
         if (strlen($language->language) > 2) {
             $languages[] = substr($language->language, 0, 2);
         }
     }
     return array_unique($languages);
 }
コード例 #25
0
 /**
  * Link files to the Mongo product values.
  *
  * @param string $productTable
  */
 protected function migrateMediasOnProductValueMongo($productTable)
 {
     $db = $this->getMongoDatabase();
     $valueCollection = new MongoCollection($db, $productTable);
     $productsWithMedia = $valueCollection->find(['values.media' => ['$ne' => null]]);
     $stmt = $this->ormConnection->prepare('SELECT fi.id FROM akeneo_file_storage_file_info fi WHERE fi.old_file_key = ?');
     foreach ($productsWithMedia as $product) {
         foreach ($product['values'] as $index => $value) {
             if (isset($value['media'])) {
                 $stmt->bindValue(1, $value['media']['filename']);
                 $stmt->execute();
                 $fileInfo = $stmt->fetch();
                 /*
                 db.pim_catalog_product.update(
                      { _id: ObjectId("55ee950c48177e12588b5ccb"), "values._id": ObjectId("55ee950c48177e12588b5cd4") },
                      { $set: {"values.$.media": NumberLong(666)} }
                 )
                 */
                 $valueCollection->update(['_id' => new MongoId($product['_id']), 'values._id' => new MongoId($value['_id'])], ['$set' => ['values.$.media' => (int) $fileInfo['id']]]);
             }
         }
     }
 }
コード例 #26
0
ファイル: Install.php プロジェクト: luisbrito/Phraseanet
 private function getDBConn(InputInterface $input, OutputInterface $output, Connection $abConn, DialogHelper $dialog)
 {
     $dbConn = $template = $info = null;
     if (!$input->getOption('databox')) {
         do {
             $retry = false;
             $dbName = $dialog->ask($output, 'DataBox name, will not be created if empty : ', null);
             if ($dbName) {
                 try {
                     $info = ['host' => $abConn->getHost(), 'port' => $abConn->getPort(), 'user' => $abConn->getUsername(), 'password' => $abConn->getPassword(), 'dbname' => $dbName];
                     $dbConn = $this->container['dbal.provider']($info);
                     $dbConn->connect();
                     $output->writeln("\n\t<info>Data-Box : Connection successful !</info>\n");
                     do {
                         $template = $dialog->ask($output, 'Choose a language template for metadata structure, available are fr (french) and en (english) (en) : ', 'en');
                     } while (!in_array($template, ['en', 'fr']));
                     $output->writeln("\n\tLanguage selected is <info>'{$template}'</info>\n");
                 } catch (\Exception $e) {
                     $retry = true;
                 }
             } else {
                 $output->writeln("\n\tNo databox will be created\n");
             }
         } while ($retry);
     } else {
         $info = ['host' => $input->getOption('db-host'), 'port' => $input->getOption('db-port'), 'user' => $input->getOption('db-user'), 'password' => $input->getOption('db-password'), 'dbname' => $input->getOption('databox')];
         $dbConn = $this->container['dbal.provider']($info);
         $dbConn->connect();
         $output->writeln("\n\t<info>Data-Box : Connection successful !</info>\n");
         $template = $input->getOption('db-template') ?: 'en';
     }
     // add dbs.option & orm.options services to use orm.em later
     if ($dbConn && $info) {
         $this->container['dbs.options'] = array_merge($this->container['db.options.from_info']($info), $this->container['dbs.options']);
         $this->container['orm.ems.options'] = array_merge($this->container['orm.em.options.from_info']($info), $this->container['orm.ems.options']);
     }
     return [$dbConn, $template];
 }
コード例 #27
0
ファイル: DaoBase.php プロジェクト: ritalin/omelet
 protected function convertResults($results, DomainBase $domain, CaseSensor $sensor)
 {
     return $domain->convertResults($results, $this->conn->getDatabasePlatform(), $sensor);
 }
コード例 #28
0
ファイル: 204.php プロジェクト: nlegoff/Phraseanet
 public function fixIds(Connection $connbas, &$node)
 {
     if ($node->nodeType != XML_ELEMENT_NODE) {
         return;
     }
     if ($node->parentNode && $node->parentNode->nodeType == XML_ELEMENT_NODE) {
         $pid = $node->parentNode->getAttribute("id");
         if ($pid != "") {
             $id = $node->getAttribute("id");
             if (substr($id, 1, strlen($pid)) != substr($pid, "1") . ".") {
                 $nid = $node->parentNode->getAttribute("nextid");
                 $node->parentNode->setAttribute("nextid", $nid + 1);
                 $node->setAttribute("id", $newid = $pid . "." . $nid);
                 printf("// \tid '%s' (child of '%s') fixed to '%s'\n", $id, $pid, $newid);
                 $id = str_replace(".", "d", $id) . "d";
                 $newid = str_replace(".", "d", $newid) . "d";
                 $sql = "UPDATE thit SET value = :newid WHERE value = :oldid";
                 $stmt = $connbas->prepare($sql);
                 $stmt->execute([':newid' => $newid, ':oldid' => $id]);
                 $stmt->closeCursor();
             }
         }
     }
     for ($n = $node->firstChild; $n; $n = $n->nextSibling) {
         $this->fixIds($connbas, $n);
     }
 }
コード例 #29
0
ファイル: Thesaurus.php プロジェクト: nlegoff/Phraseanet
 private function doRejectBranch(Connection $connbas, \DOMElement $node)
 {
     if (strlen($oldid = $node->getAttribute("id")) > 1) {
         $node->setAttribute("id", $newid = "R" . substr($oldid, 1));
         $thit_oldid = str_replace(".", "d", $oldid) . "d";
         $thit_newid = str_replace(".", "d", $newid) . "d";
         $sql = "UPDATE thit SET value = :new_value WHERE value = :old_value";
         $stmt = $connbas->prepare($sql);
         $stmt->execute([':old_value' => $thit_oldid, ':new_value' => $thit_newid]);
         $stmt->closeCursor();
     }
     for ($n = $node->firstChild; $n; $n = $n->nextSibling) {
         if ($n->nodeType == XML_ELEMENT_NODE) {
             $this->doRejectBranch($connbas, $n);
         }
     }
 }
コード例 #30
0
ファイル: Installer.php プロジェクト: luisbrito/Phraseanet
 private function createConfigFile(Connection $abConn, $serverName, $binaryData, $dataPath)
 {
     $config = $this->app['configuration.store']->initialize()->getConfig();
     $config['main']['database']['host'] = $abConn->getHost();
     $config['main']['database']['port'] = $abConn->getPort();
     $config['main']['database']['user'] = $abConn->getUsername();
     $config['main']['database']['password'] = $abConn->getPassword();
     $config['main']['database']['dbname'] = $abConn->getDatabase();
     $config['main']['database']['driver'] = 'pdo_mysql';
     $config['main']['database']['charset'] = 'UTF8';
     $config['main']['binaries'] = $binaryData;
     $config['servername'] = $serverName;
     $config['main']['key'] = $this->app['random.medium']->generateString(16);
     if (null === ($dataPath = realpath($dataPath))) {
         throw new \InvalidArgumentException(sprintf('Path %s does not exist.', $dataPath));
     }
     $config['main']['storage']['subdefs'] = $dataPath;
     $config['main']['storage']['cache'] = realpath(__DIR__ . '/../../../../cache');
     $config['main']['storage']['log'] = realpath(__DIR__ . '/../../../../logs');
     $config['main']['storage']['download'] = realpath(__DIR__ . '/../../../../tmp/download');
     $config['main']['storage']['lazaret'] = realpath(__DIR__ . '/../../../../tmp/lazaret');
     $config['main']['storage']['caption'] = realpath(__DIR__ . '/../../../../tmp/caption');
     $config['registry'] = $this->app['registry.manipulator']->getRegistryData();
     $this->app['configuration.store']->setConfig($config);
 }