Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bigtable: Read modify write row model #1334

Merged
81 changes: 81 additions & 0 deletions Bigtable/src/DataClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
use Google\ApiCore\Serializer;
use Google\Cloud\Bigtable\Exception\BigtableDataOperationException;
use Google\Cloud\Bigtable\Filter\FilterInterface;
use Google\Cloud\Bigtable\ReadModifyWriteRowRules;
use Google\Cloud\Bigtable\V2\BigtableClient as TableClient;
use Google\Cloud\Bigtable\V2\Row;
use Google\Cloud\Bigtable\V2\RowRange;
use Google\Cloud\Bigtable\V2\RowSet;
use Google\Cloud\Core\ArrayTrait;
Expand Down Expand Up @@ -322,4 +324,83 @@ public function readRow($rowKey, array $options = [])
->readAll()
->current();
}

/**
* Modifies a row atomically on the server. The method reads the latest
* existing timestamp and value from the specified columns and writes a new
* entry based on pre-defined read/modify/write rules. The new value for the
* timestamp is the greater of the existing timestamp or the current server
* time. The method returns the new contents of all modified cells.
*
* Example:
* ```
* use Google\Cloud\Bigtable\ReadModifyWriteRowRules;
*
* $rules = (new ReadModifyWriteRowRules)
* ->append('cf1', 'cq1', 'value12');
* $row = $dataClient->readModifyWriteRow('rk1', $rules);
*
* print_r($row);
* ```
*
* //Increments value

This comment was marked as spam.

* ```
* use Google\Cloud\Bigtable\DataUtil;
* use Google\Cloud\Bigtable\ReadModifyWriteRowRules;
* use Google\Cloud\Bigtable\RowMutation;
*
* $rowMutation = new RowMutation('rk1');
* $rowMutation->upsert('cf1', 'cq1', DataUtil::intToByteString(2));
*
* $dataClient->mutateRows([$rowMutation]);
*
* $rules = (new ReadModifyWriteRowRules)
* ->increment('cf1', 'cq1', 3);
* $row = $dataClient->readModifyWriteRow('rk1', $rules);
*
* print_r($row);
* ```
*
* @param string $rowKey The row key to read.
* @param ReadModifyWriteRowRules $rules Rules to apply on row.
* @param array $options [optional] Configuration options.
* @return array Returns array containing all column family keyed by family name.
* @throws ApiException if the remote call fails or operation fails
*/
public function readModifyWriteRow($rowKey, ReadModifyWriteRowRules $rules, array $options = [])
{
$readModifyWriteRowResponse = $this->bigtableClient->readModifyWriteRow(
$this->tableName,
$rowKey,
$rules->toProto(),
$options + $this->options
);
return $this->convertToArray($readModifyWriteRowResponse->getRow());
}

private function convertToArray(Row $row)
{
if ($row === null) {
return [];
}
$families = [];
foreach ($row->getFamilies() as $family) {
$qualifiers = [];
foreach ($family->getColumns() as $column) {
$values = [];
foreach ($column->getCells() as $cell) {
$values[] = [
'value' => $cell->getValue(),
'timeStamp' => $cell->getTimestampMicros(),
'labels' => ($cell->getLabels()->getIterator()->valid())
? implode(iterator_to_array($cell->getLabels()->getIterator()))
: ''
];
}
$qualifiers[$column->getQualifier()] = $values;
}
$families[$family->getName()] = $qualifiers;
}
return $families;
}
}
85 changes: 85 additions & 0 deletions Bigtable/src/DataUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
/**
* Copyright 2018, Google LLC All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Bigtable;

/**
* This class contains utility to convert integer to byte string and backward.
* This utility class is only supported on 64 bit machine with PHP version > 5.5.
*/
class DataUtil
{
private static $isLittleEndian;
private static $isSupported;

public static function isSystemLittleEndian()
dwsupplee marked this conversation as resolved.
Show resolved Hide resolved
{
if (self::$isLittleEndian === null) {
self::$isLittleEndian = (pack("P", 2) === pack("Q", 2));
}
return self::$isLittleEndian;
}

public static function isSupported()
{
if (self::$isSupported === null) {
self::$isSupported = PHP_VERSION_ID > 50500;

This comment was marked as spam.

}
return self::$isSupported;
}

/**
* Utility method to convert an integer to a 64-bit big-endian signed integer byte string.
*
* @param int $intValue Integer value to convert to.
* @return string Returns a string of bytes representing a 64-bit big-endian signed integer.
* @throws \InvalidArgumentException If value is not an integer.
*/
public static function intToByteString($intValue)
{
if (!self::isSupported()) {
throw new \ErrorException('This utility is only supported on 64 bit machine with PHP version > 5.5.');

This comment was marked as spam.

}
if (!is_int($intValue)) {
throw new \InvalidArgumentException(
sprintf(
'Expected argument to be of type int, instead got \'%s\'.',
gettype($intValue)
)
);
}
$bytes = pack("J", $intValue);
return $bytes;
}

/**
* Converts a 64-bit big-endian signed integer represented as a byte string to an integer.
*
* @param string $bytes String of bytes to convert.
* @return int Integer value of the string bytes.
*/
public static function byteStringToInt($bytes)
{
if (!self::isSupported()) {
throw new \ErrorException('This utility is only supported on 64 bit machine with PHP version > 5.5.');
}
if (self::isSystemLittleEndian()) {
$bytes = strrev($bytes);
}
return unpack("q", $bytes)[1];
}
}
85 changes: 85 additions & 0 deletions Bigtable/src/ReadModifyWriteRowRules.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
/**
* Copyright 2018, Google LLC All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Bigtable;

use Google\Cloud\Bigtable\V2\ReadModifyWriteRule;

/**
* This is a builder class which builds read/modify/write rules specifying how the specified rows contents
* are to be transformed into writes. Entries are applied in order, meaning that earlier rules will
* affect the results of later ones. This is intended to be used in combination with
* {@see Google\Cloud\Bigtable\DataClient::readModifyWriteRow()}.
*/
class ReadModifyWriteRowRules
{
/**
* @var ReadModifyWriteRule[]
*/
private $rules = [];

/**
* Appends the value to the existing value of the cell. If targeted cell is unset,
* it will be treated as containing the empty string.
*
* @param string $familyName Family name of the row.
* @param string $qualifier Column qualifier of the row.
* @param string $value Value of the Column qualifier.
*
* @return ReadModifyWriteRowRules returns current ReadModifyWriteRowRules object.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

*/
public function append($familyName, $qualifier, $value)
{
$this->rules[] = (new ReadModifyWriteRule)
->setFamilyName($familyName)
->setColumnQualifier($qualifier)
->setAppendValue($value);
return $this;
}

/**
* Adds `amount` to the existing value. If the targeted cell is unset, it will be treated
* as containing a zero. Otherwise, the targeted cell must containt an 8-byte value (interpreted
* as a 64-bit big-endian signed integer), or the entire request will fail.
*
* @param string $familyName Family name of the row.
* @param string $qualifier Column qualifier of the row.
* @param int $amount Amount to add to value of Column qualifier.

This comment was marked as spam.

*
* @return ReadModifyWriteRowRules returns current ReadModifyWriteRowRules object.
*/
public function increment($familyName, $qualifier, $amount)
{
$this->rules[] = (new ReadModifyWriteRule)
->setFamilyName($familyName)
->setColumnQualifier($qualifier)
->setIncrementAmount($amount);
return $this;
}

/**
* Returns proto representation of ReadModifyWriteRule.
*
* @internal
* @access private
* @return ReadModifyWriteRule[] Returns array of ReadModifyWriteRule rules.
*/
public function toProto()

This comment was marked as spam.

{
return $this->rules;
}
}
Loading