fetchField example


class UpsertTest extends DatabaseTestBase {

  /** * Confirms that we can upsert (update-or-insert) records successfully. */
  public function testUpsert() {
    $connection = Database::getConnection();
    $num_records_before = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();

    $upsert = $connection->upsert('test_people')
      ->key('job')
      ->fields(['job', 'age', 'name']);

    // Add a new row.     $upsert->values([
      'job' => 'Presenter',
      'age' => 31,
      'name' => 'Tiffany',
    ]);

    
public function testDbNextIdClosedConnection() {
    // Create an additional connection to test closing the connection.     $connection_info = Database::getConnectionInfo();
    Database::addConnectionInfo('default', 'next_id', $connection_info['default']);

    // Get a few IDs to ensure there the clean up needs to run and there is more     // than one row.     Database::getConnection('next_id')->nextId();
    Database::getConnection('next_id')->nextId();

    // At this point the sequences table should contain unnecessary rows.     $count = $this->connection->select('sequences')->countQuery()->execute()->fetchField();
    $this->assertGreaterThan(1, $count);

    // Close the connection.     Database::closeConnection('next_id');

    // Test that \Drupal\mysql\Driver\Database\mysql\Connection::__destruct()     // successfully trims the sequences table if the connection is closed.     $count = $this->connection->select('sequences')->countQuery()->execute()->fetchField();
    $this->assertEquals(1, $count);
  }

}
public function isAllowed($name$threshold$window = 3600, $identifier = NULL) {
    if (!isset($identifier)) {
      $identifier = $this->requestStack->getCurrentRequest()->getClientIp();
    }
    try {
      $number = $this->connection->select(static::TABLE_NAME, 'f')
        ->condition('event', $name)
        ->condition('identifier', $identifier)
        ->condition('timestamp', REQUEST_TIME - $window, '>')
        ->countQuery()
        ->execute()
        ->fetchField();
      return ($number < $threshold);
    }
    catch (\Exception $e) {
      $this->catchException($e);
      return TRUE;
    }
  }

  /** * {@inheritdoc} */
  
'id' => 2,
        'count' => 3,
      ])
      ->execute();

    // Normal decrement.     $file_usage->delete($file, 'testing', 'bar', 2);
    $count = $connection->select('file_usage', 'f')
      ->fields('f', ['count'])
      ->condition('f.fid', $file->id())
      ->execute()
      ->fetchField();
    $this->assertEquals(2, $count, 'The count was decremented correctly.');

    // Multiple decrement and removal.     $file_usage->delete($file, 'testing', 'bar', 2, 2);
    $count = $connection->select('file_usage', 'f')
      ->fields('f', ['count'])
      ->condition('f.fid', $file->id())
      ->execute()
      ->fetchField();
    $this->assertFalse($count, 'The count was removed entirely when empty.');

    
->fields(['reindex' => $old])
      ->condition('reindex', $current, '>=')
      ->execute();

    // Save the node again. Verify that the request time on it is not updated.     $this->searchableNodes[1]->save();
    $result = $connection->select('search_dataset', 'd')
      ->fields('d', ['reindex'])
      ->condition('type', 'node_search')
      ->condition('sid', $this->searchableNodes[1]->id())
      ->execute()
      ->fetchField();
    $this->assertEquals($old$result, 'Reindex time was not updated if node was already marked');

    // Add a bogus entry to the search index table using a different search     // type. This will not appear in the index status, because it is not     // managed by a plugin.     $search_index->index('foo', $this->searchableNodes[0]->id(), 'en', 'some text');
    $this->assertIndexCounts(1, 8, 'after adding a different index item');

    // Mark just this "foo" index for reindexing.     $search_index->markForReindex('foo');
    $this->assertIndexCounts(1, 8, 'after reindexing the other search type');

    

class DeleteTruncateTest extends DatabaseTestBase {

  /** * Confirms that we can use a subselect in a delete successfully. */
  public function testSubselectDelete() {
    $num_records_before = $this->connection->query('SELECT COUNT(*) FROM {test_task}')->fetchField();
    $pid_to_delete = $this->connection->query("SELECT * FROM {test_task} WHERE [task] = 'sleep' ORDER BY [tid]")->fetchField();

    $subquery = $this->connection->select('test', 't')
      ->fields('t', ['id'])
      ->condition('t.id', [$pid_to_delete], 'IN');
    $delete = $this->connection->delete('test_task')
      ->condition('task', 'sleep')
      ->condition('pid', $subquery, 'IN');

    $num_deleted = $delete->execute();
    $this->assertEquals(1, $num_deleted, 'Deleted 1 record.');

    
    // hook_query_alter() gets access to the extended object.     if (!$this->preExecute($this)) {
      return NULL;
    }

    // A NULL limit is the "kill switch" for pager queries.     if (empty($this->limit)) {
      return;
    }
    $this->ensureElement();

    $total_items = $this->getCountQuery()->execute()->fetchField();
    $pager = $this->connection->getPagerManager()->createPager($total_items$this->limit, $this->element);
    $this->range($pager->getCurrentPage() * $this->limit, $this->limit);

    // Now that we've added our pager-based range instructions, run the query normally.     return $this->query->execute();
  }

  /** * Ensure that there is an element associated with this query. * * After running this method, access $this->element to get the element for this * query. */

class ContactSettings extends Variable {

  /** * {@inheritdoc} */
  protected function initializeIterator() {
    $default_category = $this->select('contact', 'c')
      ->fields('c', ['cid'])
      ->condition('c.selected', 1)
      ->execute()
      ->fetchField();
    return new \ArrayIterator([$this->values() + ['default_category' => $default_category]]);
  }

}
foreach ($conditions as $field => $value) {
      // Cast scalars to array so we can consistently use an IN condition.       $query->condition('l.' . $field(array) $value, 'IN');
    }
    return $query->execute()->fetchAll();
  }

  /** * {@inheritdoc} */
  public function countStrings() {
    return $this->dbExecute("SELECT COUNT(*) FROM {locales_source}")->fetchField();
  }

  /** * {@inheritdoc} */
  public function countTranslations() {
    return $this->dbExecute("SELECT t.language, COUNT(*) AS translated FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid GROUP BY t.language")->fetchAllKeyed();
  }

  /** * {@inheritdoc} */
/** * Gets the number of rows in the test cache bin database table. * * @return int * The number of rows in the test cache bin database table. */
  protected function getNumRows() {
    $table = 'cache_' . $this->testBin;
    $connection = $this->container->get('database');
    $query = $connection->select($table);
    $query->addExpression('COUNT([cid])', 'cid');
    return (int) $query->execute()->fetchField();
  }

  /** * Test that the service "cache_tags.invalidator.checksum" is backend overridable. */
  public function testCacheTagsInvalidatorChecksumIsBackendOverridable() {
    $definition = $this->container->getDefinition('cache_tags.invalidator.checksum');
    $this->assertTrue($definition->hasTag('backend_overridable'));
  }

  /** * Test that the service "cache.backend.database" is backend overridable. */


    // The import should have created 6 strings.     $this->assertSession()->pageTextContains("One translation file imported. 6 translations were added, 0 translations were updated and 0 translations were removed.");

    // The database should now contain 6 customized strings (two imported     // strings are not translated).     $count = Database::getConnection()->select('locales_target')
      ->condition('customized', 1)
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertEquals(6, $count, 'Customized translations successfully imported.');

    // Try importing a .po file with overriding strings, and ensure existing     // customized strings are kept.     $this->importPoFile($this->getCustomOverwritePoFile()[
      'langcode' => 'fr',
      'overwrite_options[not_customized]' => TRUE,
      'overwrite_options[customized]' => FALSE,
    ]);

    // The import should have created 1 string.

  public function markForReindex() {
    // All NodeSearch pages share a common search index "type" equal to     // the plugin ID.     $this->searchIndex->markForReindex($this->getPluginId());
  }

  /** * {@inheritdoc} */
  public function indexStatus() {
    $total = $this->database->query('SELECT COUNT(*) FROM {node}')->fetchField();
    $remaining = $this->database->query("SELECT COUNT(DISTINCT [n].[nid]) FROM {node} [n] LEFT JOIN {search_dataset} [sd] ON [sd].[sid] = [n].[nid] AND [sd].[type] = :type WHERE [sd].[sid] IS NULL OR [sd].[reindex] <> 0", [':type' => $this->getPluginId()])->fetchField();

    return ['remaining' => $remaining, 'total' => $total];
  }

  /** * {@inheritdoc} */
  public function searchFormAlter(array &$form, FormStateInterface $form_state) {
    $parameters = $this->getParameters();
    $keys = $this->getKeywords();
    
->execute();
    return (bool) $deleted;
  }

  /** * {@inheritdoc} */
  public function getAssignedToUser($account) {
    $query = $this->connection->select('shortcut_set_users', 'ssu');
    $query->fields('ssu', ['set_name']);
    $query->condition('ssu.uid', $account->id());
    return $query->execute()->fetchField();
  }

  /** * {@inheritdoc} */
  public function countAssignedUsers(ShortcutSetInterface $shortcut_set) {
    return Database::getConnection()->query('SELECT COUNT(*) FROM {shortcut_set_users} WHERE [set_name] = :name', [':name' => $shortcut_set->id()])->fetchField();
  }

  /** * {@inheritdoc} */
protected function doFindChildrenRelativeDepth(array $original) {
    $query = $this->connection->select($this->table, NULL, $this->options);
    $query->addField($this->table, 'depth');
    $query->condition('menu_name', $original['menu_name']);
    $query->orderBy('depth', 'DESC');
    $query->range(0, 1);

    for ($i = 1; $i <= static::MAX_DEPTH && $original["p$i"]$i++) {
      $query->condition("p$i", $original["p$i"]);
    }

    $max_depth = $this->safeExecuteSelect($query)->fetchField();

    return ($max_depth > $original['depth']) ? $max_depth - $original['depth'] : 0;
  }

  /** * Sets the materialized path field values based on the parent. * * @param array $fields * The menu link. * @param array|false $parent * The parent menu link. * @param array $original * The original menu link. */


use Drupal\Core\Database\Database;

$connection = Database::getConnection();
// Ensure any tables with a serial column with a value of 0 are created as // expected. if ($connection->databaseType() === 'mysql') {
  $sql_mode = $connection->query("SELECT @@sql_mode;")->fetchField();
  $connection->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
}

$connection->schema()->createTable('accesslog', array(
  'fields' => array(
    'aid' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'size' => 'normal',
    ),
    'sid' => array(
      
Home | Imprint | This part of the site doesn't use cookies.