本文整理汇总了PHP中Drupal\Core\Database\Connection类的典型用法代码示例。如果您正苦于以下问题:PHP Connection类的具体用法?PHP Connection怎么用?PHP Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: log
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
{
// Remove any backtraces since they may contain an unserializable variable.
unset($context['backtrace']);
// Convert PSR3-style messages to SafeMarkup::format() style, so they can be
// translated too in runtime.
$message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
try {
$this->connection->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => Unicode::substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => $context['link'], 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => Unicode::substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute();
} catch (\Exception $e) {
// When running Drupal on MySQL or MariaDB you can run into several errors
// that corrupt the database connection. Some examples for these kind of
// errors on the database layer are "1100 - Table 'xyz' was not locked
// with LOCK TABLES" and "1153 - Got a packet bigger than
// 'max_allowed_packet' bytes". If such an error happens, the MySQL server
// invalidates the connection and answers all further requests in this
// connection with "2006 - MySQL server had gone away". In that case the
// insert statement above results in a database exception. To ensure that
// the causal error is written to the log we try once to open a dedicated
// connection and write again.
if (($e instanceof DatabaseException || $e instanceof \PDOException) && $this->connection->getTarget() != self::DEDICATED_DBLOG_CONNECTION_TARGET) {
// Open a dedicated connection for logging.
$key = $this->connection->getKey();
$info = Database::getConnectionInfo($key);
Database::addConnectionInfo($key, self::DEDICATED_DBLOG_CONNECTION_TARGET, $info['default']);
$this->connection = Database::getConnection(self::DEDICATED_DBLOG_CONNECTION_TARGET, $key);
// Now try once to log the error again.
$this->log($level, $message, $context);
} else {
throw $e;
}
}
}
示例2: collect
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = NULL)
{
$connections = [];
foreach (Database::getAllConnectionInfo() as $key => $info) {
$database = Database::getConnection('default', $key);
$connections[$key] = $database->getLogger()->get('webprofiler');
}
$this->data['connections'] = array_keys($connections);
$data = [];
foreach ($connections as $key => $queries) {
foreach ($queries as $query) {
// Remove caller args.
unset($query['caller']['args']);
// Remove query args element if empty.
if (empty($query['args'])) {
unset($query['args']);
}
// Save time in milliseconds.
$query['time'] = $query['time'] * 1000;
$query['database'] = $key;
$data[] = $query;
}
}
$querySort = $this->configFactory->get('webprofiler.config')->get('query_sort');
if ('duration' === $querySort) {
usort($data, ["Drupal\\webprofiler\\DataCollector\\DatabaseDataCollector", "orderQueryByTime"]);
}
$this->data['queries'] = $data;
$options = $this->database->getConnectionOptions();
// Remove password for security.
unset($options['password']);
$this->data['database'] = $options;
}
示例3: dropTables
/**
* Drop the tables used for the sample data.
*
* @param \Drupal\Core\Database\Connection $connection
* The connection to use to drop the tables.
*/
public function dropTables(Connection $connection)
{
$tables = $this->routingTableDefinition();
$schema = $connection->schema();
foreach ($tables as $name => $table) {
$schema->dropTable($name);
}
}
示例4: __construct
/**
* Constructs a Query object.
*
* @param \Drupal\Core\Database\Connection $connection
* Database connection object.
* @param array $options
* Array of query options.
*/
public function __construct(Connection $connection, $options)
{
$this->uniqueIdentifier = uniqid('', TRUE);
$this->connection = $connection;
$this->connectionKey = $this->connection->getKey();
$this->connectionTarget = $this->connection->getTarget();
$this->queryOptions = $options;
}
示例5: doTestEntry
/**
* Checks whether the expected logging entry got written.
*
* @param \Drupal\Core\Database\Connection $connection
* The database collection.
*/
protected function doTestEntry(Connection $connection)
{
$result = $connection->select('watchdog')->fields('watchdog')->execute()->fetchAll();
$this->assertEqual(1, count($result));
$this->assertEqual(WATCHDOG_INFO, $result[0]->severity);
$this->assertEqual('system', $result[0]->type);
$this->assertEqual('Hello world @key', $result[0]->message);
$this->assertEqual(array('@key' => 'value'), unserialize($result[0]->variables));
}
示例6: setUp
/**
* Sets up required mocks and the CommentStatistics service under test.
*/
protected function setUp()
{
$this->statement = $this->getMockBuilder('Drupal\\Core\\Database\\Driver\\sqlite\\Statement')->disableOriginalConstructor()->getMock();
$this->statement->expects($this->any())->method('fetchObject')->will($this->returnCallback(array($this, 'fetchObjectCallback')));
$this->select = $this->getMockBuilder('Drupal\\Core\\Database\\Query\\Select')->disableOriginalConstructor()->getMock();
$this->select->expects($this->any())->method('fields')->will($this->returnSelf());
$this->select->expects($this->any())->method('condition')->will($this->returnSelf());
$this->select->expects($this->any())->method('execute')->will($this->returnValue($this->statement));
$this->database = $this->getMockBuilder('Drupal\\Core\\Database\\Connection')->disableOriginalConstructor()->getMock();
$this->database->expects($this->once())->method('select')->will($this->returnValue($this->select));
$this->commentStatistics = new CommentStatistics($this->database, $this->getMock('Drupal\\Core\\Session\\AccountInterface'), $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'), $this->getMock('Drupal\\Core\\State\\StateInterface'));
}
示例7: testEntitySchemaUpdate
/**
* Tests that entity schema responds to changes in the entity type definition.
*/
public function testEntitySchemaUpdate()
{
$this->installModule('entity_schema_test');
$storage_definitions = $this->entityManager->getFieldStorageDefinitions('entity_test');
$this->entityManager->onFieldStorageDefinitionCreate($storage_definitions['custom_base_field']);
$this->entityManager->onFieldStorageDefinitionCreate($storage_definitions['custom_bundle_field']);
$schema_handler = $this->database->schema();
$tables = array('entity_test', 'entity_test_revision', 'entity_test_field_data', 'entity_test_field_revision');
$dedicated_tables = array('entity_test__custom_bundle_field', 'entity_test_revision__custom_bundle_field');
// Initially only the base table and the dedicated field data table should
// exist.
foreach ($tables as $index => $table) {
$this->assertEqual($schema_handler->tableExists($table), !$index, SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
}
$this->assertTrue($schema_handler->tableExists($dedicated_tables[0]), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
// Update the entity type definition and check that the entity schema now
// supports translations and revisions.
$this->updateEntityType(TRUE);
foreach ($tables as $table) {
$this->assertTrue($schema_handler->tableExists($table), SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
}
foreach ($dedicated_tables as $table) {
$this->assertTrue($schema_handler->tableExists($table), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
}
// Revert changes and check that the entity schema now does not support
// neither translations nor revisions.
$this->updateEntityType(FALSE);
foreach ($tables as $index => $table) {
$this->assertEqual($schema_handler->tableExists($table), !$index, SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
}
$this->assertTrue($schema_handler->tableExists($dedicated_tables[0]), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
}
示例8: findMatchingRedirect
/**
* Gets a redirect for given path, query and language.
*
* @param string $source_path
* The redirect source path.
* @param array $query
* The redirect source path query.
* @param $language
* The language for which is the redirect.
*
* @return \Drupal\redirect\Entity\Redirect
* The matched redirect entity.
*
* @throws \Drupal\redirect\Exception\RedirectLoopException
*/
public function findMatchingRedirect($source_path, array $query = [], $language = Language::LANGCODE_NOT_SPECIFIED)
{
$hashes = [Redirect::generateHash($source_path, $query, $language)];
if ($language != Language::LANGCODE_NOT_SPECIFIED) {
$hashes[] = Redirect::generateHash($source_path, $query, Language::LANGCODE_NOT_SPECIFIED);
}
// Add a hash without the query string if using passthrough querystrings.
if (!empty($query) && $this->config->get('passthrough_querystring')) {
$hashes[] = Redirect::generateHash($source_path, [], $language);
if ($language != Language::LANGCODE_NOT_SPECIFIED) {
$hashes[] = Redirect::generateHash($source_path, [], Language::LANGCODE_NOT_SPECIFIED);
}
}
// Load redirects by hash. A direct query is used to improve performance.
$rid = $this->connection->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])->fetchField();
if (!empty($rid)) {
// Check if this is a loop.
if (in_array($rid, $this->foundRedirects)) {
throw new RedirectLoopException('/' . $source_path, $rid);
}
$this->foundRedirects[] = $rid;
$redirect = $this->load($rid);
// Find chained redirects.
if ($recursive = $this->findByRedirect($redirect, $language)) {
// Reset found redirects.
$this->foundRedirects = [];
return $recursive;
}
return $redirect;
}
return NULL;
}
示例9: preRender
public function preRender(&$values)
{
$uids = array();
$this->items = array();
foreach ($values as $result) {
$uids[] = $this->getValue($result);
}
if ($uids) {
$roles = user_roles();
$result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles)));
foreach ($result as $role) {
$this->items[$role->uid][$role->rid]['role'] = $roles[$role->rid]->label();
$this->items[$role->uid][$role->rid]['rid'] = $role->rid;
}
// Sort the roles for each user by role weight.
$ordered_roles = array_flip(array_keys($roles));
foreach ($this->items as &$user_roles) {
// Create an array of rids that the user has in the role weight order.
$sorted_keys = array_intersect_key($ordered_roles, $user_roles);
// Merge with the unsorted array of role information which has the
// effect of sorting it.
$user_roles = array_merge($sorted_keys, $user_roles);
}
}
}
示例10: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$_SESSION['dblog_overview_filter'] = array();
$this->connection->delete('watchdog')->execute();
drupal_set_message($this->t('Database log cleared.'));
$form_state->setRedirectUrl($this->getCancelUrl());
}
示例11: overview
/**
* Displays a listing of migration messages.
*
* Messages are truncated at 56 chars.
*
* @return array
* A render array as expected by drupal_render().
*/
public function overview($migration_group, $migration)
{
$rows = [];
$classes = static::getLogLevelClassMap();
/** @var MigrationInterface $migration */
$migration = Migration::load($migration);
$source_id_field_names = array_keys($migration->getSourcePlugin()->getIds());
$column_number = 1;
foreach ($source_id_field_names as $source_id_field_name) {
$header[] = ['data' => $source_id_field_name, 'field' => 'sourceid' . $column_number++, 'class' => [RESPONSIVE_PRIORITY_MEDIUM]];
}
$header[] = ['data' => $this->t('Severity level'), 'field' => 'level', 'class' => [RESPONSIVE_PRIORITY_LOW]];
$header[] = ['data' => $this->t('Message'), 'field' => 'message'];
$message_table = $migration->getIdMap()->messageTableName();
$query = $this->database->select($message_table, 'm')->extend('\\Drupal\\Core\\Database\\Query\\PagerSelectExtender')->extend('\\Drupal\\Core\\Database\\Query\\TableSortExtender');
$query->fields('m');
$result = $query->limit(50)->orderByHeader($header)->execute();
foreach ($result as $message_row) {
$column_number = 1;
foreach ($source_id_field_names as $source_id_field_name) {
$column_name = 'sourceid' . $column_number++;
$row[$column_name] = $message_row->{$column_name};
}
$row['level'] = $message_row->level;
$row['message'] = $message_row->message;
$row['class'] = [Html::getClass('migrate-message-' . $message_row->level), $classes[$message_row->level]];
$rows[] = $row;
}
$build['message_table'] = ['#type' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => ['id' => $message_table, 'class' => [$message_table]], '#empty' => $this->t('No messages for this migration.')];
$build['message_pager'] = ['#type' => 'pager'];
return $build;
}
示例12: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, array &$form_state)
{
$_SESSION['dblog_overview_filter'] = array();
$this->connection->delete('watchdog')->execute();
drupal_set_message($this->t('Database log cleared.'));
$form_state['redirect_route'] = $this->getCancelRoute();
}
示例13: clearEvents
/**
* @param DrupalStyle $io
* @param $eventType
* @param $eventSeverity
* @param $userId
* @return bool
*/
protected function clearEvents(DrupalStyle $io, $eventType, $eventSeverity, $userId)
{
$severity = RfcLogLevel::getLevels();
$query = $this->database->delete('watchdog');
if ($eventType) {
$query->condition('type', $eventType);
}
if ($eventSeverity) {
if (!in_array($eventSeverity, $severity)) {
$io->error(sprintf($this->trans('commands.database.log.clear.messages.invalid-severity'), $eventSeverity));
return false;
}
$query->condition('severity', array_search($eventSeverity, $severity));
}
if ($userId) {
$query->condition('uid', $userId);
}
$result = $query->execute();
if (!$result) {
$io->error($this->trans('commands.database.log.clear.messages.clear-error'));
return false;
}
$io->success($this->trans('commands.database.log.clear.messages.clear-sucess'));
return true;
}
示例14: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$uid = $input->getArgument('user');
$user = User::load($uid);
if (!$user) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
return 1;
}
$password = $input->getArgument('password');
if (!$password) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
return 1;
}
try {
$user->setPassword($password);
$user->save();
$schema = $this->database->schema();
$flood = $schema->findTables('flood');
if ($flood) {
$this - $this->chainQueue->addCommand('user:login:clear:attempts', ['uid' => $uid]);
}
} catch (\Exception $e) {
$io->error($e->getMessage());
return 1;
}
$io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
}
示例15: createTable
/**
* Create a new table from a Drupal table definition if it doesn't exist.
*
* @param string $name
* The name of the table to create.
* @param array $table
* A Schema API table definition array.
*/
protected function createTable($name, array $table)
{
// This must be on the database connection to be shared among classes.
if (empty($this->database->migrateTables[$name])) {
$this->database->migrateTables[$name] = TRUE;
$this->database->schema()->createTable($name, $table);
}
}