expression example

$this->connection->query($query);
    if (isset($spec['initial_from_field'])) {
      if (isset($spec['initial'])) {
        $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
        $arguments = [':default_initial_value' => $spec['initial']];
      }
      else {
        $expression = $spec['initial_from_field'];
        $arguments = [];
      }
      $this->connection->update($table)
        ->expression($field$expression$arguments)
        ->execute();
    }
    elseif (isset($spec['initial'])) {
      $this->connection->update($table)
        ->fields([$field => $spec['initial']])
        ->execute();
    }
    if ($fixnull) {
      $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
    }
    if (isset($new_keys)) {
      
$this->assertSame('1', $num_matches, 'Updated fields successfully.');
  }

  /** * Tests UPDATE with expression values. */
  public function testUpdateExpression() {
    $before_age = $this->connection->query('SELECT [age] FROM {test} WHERE [name] = :name', [':name' => 'Ringo'])->fetchField();
    $num_updated = $this->connection->update('test')
      ->condition('name', 'Ringo')
      ->fields(['job' => 'Musician'])
      ->expression('age', '[age] + :age', [':age' => 4])
      ->execute();
    $this->assertSame(1, $num_updated, 'Updated 1 record.');

    $num_matches = $this->connection->query('SELECT COUNT(*) FROM {test} WHERE [job] = :job', [':job' => 'Musician'])->fetchField();
    $this->assertSame('1', $num_matches, 'Updated fields successfully.');

    $person = $this->connection->query('SELECT * FROM {test} WHERE [name] = :name', [':name' => 'Ringo'])->fetch();
    $this->assertEquals('Ringo', $person->name, 'Name set correctly.');
    $this->assertEquals($before_age + 4, $person->age, 'Age set correctly.');
    $this->assertEquals('Musician', $person->job, 'Job set correctly.');
  }

  

  public function add(FileInterface $file$module$type$id$count = 1) {
    $this->connection->merge($this->tableName)
      ->keys([
        'fid' => $file->id(),
        'module' => $module,
        'type' => $type,
        'id' => $id,
      ])
      ->fields(['count' => $count])
      ->expression('count', '[count] + :count', [':count' => $count])
      ->execute();

    parent::add($file$module$type$id$count);
  }

  /** * {@inheritdoc} */
  public function delete(FileInterface $file$module$type = NULL, $id = NULL, $count = 1) {
    // Delete rows that have an exact or less value to prevent empty rows.     $query = $this->connection->delete($this->tableName)
      
$this->connection->query($query);
    if (isset($spec['initial_from_field'])) {
      if (isset($spec['initial'])) {
        $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
        $arguments = [':default_initial_value' => $spec['initial']];
      }
      else {
        $expression = $spec['initial_from_field'];
        $arguments = [];
      }
      $this->connection->update($table)
        ->expression($field$expression$arguments)
        ->execute();
    }
    elseif (isset($spec['initial'])) {
      $this->connection->update($table)
        ->fields([$field => $spec['initial']])
        ->execute();
    }
    if ($fixnull) {
      $spec['not null'] = TRUE;
      $this->changeField($table$field$field$spec);
    }
  }
$this->connection = $connection;
  }

  /** * {@inheritdoc} */
  protected function doInvalidateTags(array $tags) {
    try {
      foreach ($tags as $tag) {
        $this->connection->merge('cachetags')
          ->insertFields(['invalidations' => 1])
          ->expression('invalidations', '[invalidations] + 1')
          ->key('tag', $tag)
          ->execute();
      }
    }
    catch (\Exception $e) {
      // Create the cache table, which will be empty. This fixes cases during       // core install where cache tags are invalidated before the table is       // created.       if (!$this->ensureTableExists()) {
        throw $e;
      }
    }
// If a word already exists in the database, its score gets increased         // appropriately. If not, we create a new record with the appropriate         // starting score.         $this->connection->merge('search_index')
          ->keys([
            'word' => $word,
            'sid' => $sid,
            'langcode' => $langcode,
            'type' => $type,
          ])
          ->fields(['score' => $score])
          ->expression('score', '[score] + :score', [':score' => $score])
          ->execute();
        $current_words[$word] = TRUE;
      }
    }
    catch (\Exception $e) {
      throw new SearchIndexException("Failed to insert dataset in index for type '$type', sid '$sid' and langcode '$langcode'", 0, $e);
    }
    finally {
      if ($update_weights) {
        $this->updateWordWeights($current_words);
      }
    }
$age_before = $this->connection->query('SELECT [age] FROM {test_people} WHERE [job] = :job', [':job' => 'Speaker'])->fetchField();

    // This is a very contrived example, as I have no idea why you'd want to     // change age this way, but that's beside the point.     // Note that we are also double-setting age here, once as a literal and     // once as an expression. This test will only pass if the expression wins,     // which is what is supposed to happen.     $this->connection->merge('test_people')
      ->key('job', 'Speaker')
      ->fields(['name' => 'Tiffany'])
      ->insertFields(['age' => 31])
      ->expression('age', '[age] + :age', [':age' => 4])
      ->execute();

    $num_records_after = $this->connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();
    $this->assertEquals($num_records_before$num_records_after, 'Merge updated properly.');

    $person = $this->connection->query('SELECT * FROM {test_people} WHERE [job] = :job', [':job' => 'Speaker'])->fetch();
    $this->assertEquals('Tiffany', $person->name, 'Name set correctly.');
    $this->assertEquals($age_before + 4, $person->age, 'Age updated correctly.');
    $this->assertEquals('Speaker', $person->job, 'Job set correctly.');
  }

  
throw $e;
        }
      }
    }

    if ($this->needsUpdate) {
      $update = $this->connection->update($this->table)
        ->fields($this->updateFields)
        ->condition($this->condition);
      if ($this->expressionFields) {
        foreach ($this->expressionFields as $field => $data) {
          $update->expression($field$data['expression']$data['arguments']);
        }
      }
      $update->execute();
      return self::STATUS_UPDATE;
    }
    return NULL;
  }

}
->execute();
  }

  /** * {@inheritdoc} */
  public function updateMovedChildren($bid$original$expressions$shift) {
    $query = $this->connection->update('book');
    $query->fields(['bid' => $bid]);

    foreach ($expressions as $expression) {
      $query->expression($expression[0]$expression[1]$expression[2]);
    }

    $query->expression('depth', '[depth] + :depth', [':depth' => $shift]);
    $query->condition('bid', $original['bid']);
    $p = 'p1';
    for ($i = 1; !empty($original[$p])$p = 'p' . ++$i) {
      $query->condition($p$original[$p]);
    }

    return $query->execute();
  }

  
$num_matches = $this->connection->query('SELECT COUNT(*) FROM {test} WHERE [job] = :job', [':job' => 'Musician'])->fetchField();
    $this->assertSame('1', $num_matches, 'Updated fields successfully.');
  }

  /** * Tests updating with expressions. */
  public function testExpressionUpdate() {
    // Ensure that expressions are handled properly. This should set every     // record's age to a square of itself.     $num_rows = $this->connection->update('test')
      ->expression('age', '[age] * [age]')
      ->execute();
    $this->assertSame(4, $num_rows, 'Updated 4 records.');

    $saved_name = $this->connection->query('SELECT [name] FROM {test} WHERE [age] = :age', [':age' => pow(26, 2)])->fetchField();
    $this->assertSame('Paul', $saved_name, 'Successfully updated values using an algebraic expression.');
  }

  /** * Tests return value on update. */
  public function testUpdateAffectedRows() {
    
// Apply the initial value if set.       if (isset($specification['initial_from_field'])) {
        if (isset($specification['initial'])) {
          $expression = 'COALESCE(' . $specification['initial_from_field'] . ', :default_initial_value)';
          $arguments = [':default_initial_value' => $specification['initial']];
        }
        else {
          $expression = $specification['initial_from_field'];
          $arguments = [];
        }
        $this->connection->update($table)
          ->expression($field$expression$arguments)
          ->execute();
      }
      elseif (isset($specification['initial'])) {
        $this->connection->update($table)
          ->fields([$field => $specification['initial']])
          ->execute();
      }
    }
    else {
      // We cannot add the field directly. Use the slower table alteration       // method, starting from the old schema.
$totalcount = $row->getDestinationProperty('totalcount');
    $timestamp = $row->getDestinationProperty('timestamp');

    $this->connection
      ->merge('node_counter')
      ->key('nid', $nid)
      ->fields([
        'daycount' => $daycount,
        'totalcount' => $totalcount,
        'timestamp' => $timestamp,
      ])
      ->expression('daycount', '[daycount] + :daycount', [':daycount' => $daycount])
      ->expression('totalcount', '[totalcount] + :totalcount', [':totalcount' => $totalcount])
      // Per Drupal policy: "A query may have any number of placeholders, but       // all must have unique names even if they have the same value."       // https://www.drupal.org/docs/8/api/database-api/static-queries#placeholders       ->expression('timestamp', 'CASE WHEN [timestamp] > :timestamp1 THEN [timestamp] ELSE :timestamp2 END', [':timestamp1' => $timestamp, ':timestamp2' => $timestamp])
      ->execute();

    return [$row->getDestinationProperty('nid')];
  }

}

  public function recordView($id) {
    return (bool) $this->connection
      ->merge('node_counter')
      ->key('nid', $id)
      ->fields([
        'daycount' => 1,
        'totalcount' => 1,
        'timestamp' => $this->getRequestTime(),
      ])
      ->expression('daycount', '[daycount] + 1')
      ->expression('totalcount', '[totalcount] + 1')
      ->execute();
  }

  /** * {@inheritdoc} */
  public function fetchViews($ids) {
    $views = $this->connection
      ->select('node_counter', 'nc')
      ->fields('nc', ['totalcount', 'daycount', 'timestamp'])
      


    $shift = $fields['depth'] - $original['depth'];
    if ($shift > 0) {
      // The order of expressions must be reversed so the new values don't       // overwrite the old ones before they can be used because "Single-table       // UPDATE assignments are generally evaluated from left to right".       // @see http://dev.mysql.com/doc/refman/5.0/en/update.html       $expressions = array_reverse($expressions);
    }
    foreach ($expressions as $expression) {
      $query->expression($expression[0]$expression[1]$expression[2]);
    }

    $query->expression('depth', '[depth] + :depth', [':depth' => $shift]);
    $query->condition('menu_name', $original['menu_name']);

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

    $query->execute();
  }

  
Home | Imprint | This part of the site doesn't use cookies.