Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // reproduce datastore 409 error: too much contention on these datastore entities
- // 1. run: php datastore409.php
- // 2. run: php datastore409.php update
- // 3. you will see error:
- // Fatal error: Uncaught exception 'Google\Cloud\Core\Exception\ConflictException' with message '{
- // "error": {
- // "code": 409,
- // "message": "too much contention on these datastore entities. please try again.",
- // "status": "ABORTED"
- // }
- // }
- // Includes the autoloader for libraries installed with composer
- require __DIR__ . '/vendor/autoload.php';
- // Imports the Google Cloud client library
- use Google\Cloud\Datastore\DatastoreClient;
- // Instantiates a client
- $datastore = new DatastoreClient([
- 'keyFilePath' => __DIR__ . '/config/gcloud_key.json',
- 'namespaceId' => 'test',
- ]);
- if (count($argv) == 1) {
- // The kind for the new entity
- $kind = 'Task';
- // The name/ID for the new entity
- $name = 'sampleTask';
- // The Cloud Datastore key for the new entity
- $taskKey = $datastore->key($kind, $name);
- // Prepares the new entity
- $task = $datastore->entity($taskKey, ['description' => 'Buy milk']);
- // Saves the entity
- $datastore->upsert($task);
- echo 'Saved ' . $task->key() . ': ' . $task['description'] . PHP_EOL;
- $transaction = $datastore->transaction();
- $key = $datastore->key('Task', 'sampleTask');
- $task = $transaction->lookup($key);
- var_dump($task);
- echo 'now you should open another terminal and run: ' . "\n\n";
- echo ' php datastore409.php update' . "\n\n";
- echo 'then come back here to see result:' . "\n";
- sleep(10);
- $task['priority'] = 'slow' . time();
- try {
- $transaction->upsert($task);
- $transaction->commit();
- } catch (Google\Cloud\Core\Exception\ConflictException $e) {
- echo $e->getMessage() . "\n";
- $task_in_datastore = $datastore->lookup($key);
- echo 'datastore entity version: ' . $task_in_datastore->baseVersion() . "\n";
- echo 'php entity version: ' . $task->baseVersion() . "\n";
- echo 'your data version is older than datastore, so 409 error happened' . "\n";
- }
- } elseif (!empty($argv[1]) && $argv[1] == 'update') {
- $transaction = $datastore->transaction();
- $key = $datastore->key('Task', 'sampleTask');
- $task = $transaction->lookup($key);
- $task['priority'] = 'fast' . time();
- $transaction->upsert($task);
- $transaction->commit();
- echo 'I have updated the entity before you.' . "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement