/** * Start transaction */ public function testBeginTransactionBasic() { $obj_request = new \google\appengine\datastore\v4\BeginTransactionRequest(); $obj_response = new \google\appengine\datastore\v4\BeginTransactionResponse(); $obj_response->setTransaction('test-txn-ref-123'); $this->apiProxyMock->expectCall('datastore_v4', 'BeginTransaction', $obj_request, $obj_response); $_SERVER['APPLICATION_ID'] = 'DatasetTest'; $obj_gateway = $this->getMockBuilder('\\GDS\\Gateway\\ProtoBuf')->setMethods(['withTransaction', 'fetchById'])->getMock(); $obj_gateway->expects($this->once())->method('withTransaction')->with($this->equalTo('test-txn-ref-123'))->willReturn($obj_gateway); $obj_store = new GDS\Store('Book', $obj_gateway); $obj_store->beginTransaction(); $obj_store->fetchById('123456'); $this->apiProxyMock->verify(); }
/** * Test Failure on cross-group transactions * * @expectedException Exception * @expectedExceptionMessage Cross group transactions not supported over JSON API */ public function testFailCrossGroup() { $obj_gateway = new GDS\Gateway\GoogleAPIClient($this->setupTestClient(), 'Dataset'); $obj_store = new \GDS\Store('Film', $obj_gateway); $obj_store->beginTransaction(TRUE); }
<?php /** * Create a single record in GDS * * @author Tom Walder <*****@*****.**> */ require_once 'boilerplate.php'; $obj_store = new GDS\Store($obj_gateway, 'Friend'); // So now create a simple Model object $obj_charlie = new GDS\Entity(); $obj_charlie->name = 'Charlie'; $obj_charlie->age = 26; $obj_charlie->height = 120; $obj_store->upsert($obj_charlie); echo "Created: ", $obj_charlie->getKeyId(), PHP_EOL; // So now create a simple Model object $obj_max = new GDS\Entity(); $obj_max->name = 'Max'; $obj_max->age = 26; $obj_max->height = 122; $obj_store->upsert($obj_max); echo "Created: ", $obj_max->getKeyId(), PHP_EOL; echo "Query 1:", PHP_EOL; foreach ($obj_store->fetchAll("SELECT * FROM Friend WHERE age = 26") as $obj_result) { echo "Got: ", $obj_result->getKeyId(), ' ', $obj_result->name, PHP_EOL; } echo "Query 2:", PHP_EOL; foreach ($obj_store->fetchAll("SELECT * FROM Friend WHERE age = 26 AND height = 122") as $obj_result) { echo "Got: ", $obj_result->getKeyId(), ' ', $obj_result->name, PHP_EOL; }
/** * Run a complex GQL Query */ public function testGqlQueryParams() { $obj_http = $this->initTestHttpClient('https://datastore.googleapis.com/v1/projects/DatasetTest:runQuery', ['json' => (object) ['gqlQuery' => (object) ['allowLiterals' => true, 'queryString' => 'SELECT * FROM Test WHERE booly = @booly AND stringy = @stringy AND inty = @inty AND floaty = @floaty AND datey = @datey AND somekey = @somekey LIMIT 1', 'namedBindings' => (object) ['booly' => (object) ['value' => (object) ['booleanValue' => true]], 'stringy' => (object) ['value' => (object) ['stringValue' => 'test']], 'inty' => (object) ['value' => (object) ['integerValue' => 123]], 'floaty' => (object) ['value' => (object) ['doubleValue' => 4.56]], 'datey' => (object) ['value' => (object) ['timestampValue' => '1955-11-10T01:02:03.000000Z']], 'somekey' => (object) ['value' => (object) ['keyValue' => (object) ['path' => [(object) ['kind' => 'Test', 'name' => 'my-first-key-name']], 'partitionId' => (object) ['projectId' => self::TEST_PROJECT]]]]]], 'partitionId' => (object) ['projectId' => self::TEST_PROJECT]]], ['batch' => (object) ['entityResultType' => 'FULL', 'entityResults' => []]]); $obj_gateway = $this->initTestGateway()->setHttpClient($obj_http); $obj_store = new \GDS\Store('Test', $obj_gateway); $obj_key_entity = $obj_store->createEntity()->setKeyName('my-first-key-name'); $obj_store->fetchOne("SELECT * FROM Test WHERE booly = @booly AND stringy = @stringy AND inty = @inty AND floaty = @floaty AND datey = @datey AND somekey = @somekey", ['booly' => true, 'stringy' => 'test', 'inty' => 123, 'floaty' => 4.56, 'datey' => new DateTime('1955-11-10 01:02:03'), 'somekey' => $obj_key_entity]); $this->validateHttpClient($obj_http); }
/** * Fetch Page with cursor offset from historical value, using 'default query' */ public function testFetchPageHistoricalCursor() { $obj_request = $this->getBasicFetchRequest(); $obj_gql_query = $obj_request->mutableGqlQuery(); $obj_gql_query->setAllowLiteral(TRUE); $obj_gql_query->setQueryString("SELECT * FROM `Person` ORDER BY __key__ ASC LIMIT @intPageSize OFFSET @startCursor"); $obj_arg = $obj_gql_query->addNameArg(); $obj_arg->setName('intPageSize'); $obj_arg->mutableValue()->setIntegerValue(11); $obj_arg_offset = $obj_gql_query->addNameArg(); $obj_arg_offset->setName('startCursor'); $obj_arg_offset->setCursor('some-historical-cursor'); $this->apiProxyMock->expectCall('datastore_v4', 'RunQuery', $obj_request, new \google\appengine\datastore\v4\RunQueryResponse()); $obj_gateway = new GDS\Gateway\ProtoBuf('Dataset'); $obj_schema = (new \GDS\Schema('Person'))->addString('name')->addInteger('age'); $obj_store = new GDS\Store($obj_schema, $obj_gateway); $obj_store->setCursor('some-historical-cursor'); $arr_result = $obj_store->fetchPage(11); $this->assertEquals($arr_result, []); $this->apiProxyMock->verify(); }
<?php /** * Read data based on Ancestor Keys * * @author Tom Walder <*****@*****.**> */ require_once 'boilerplate.php'; $obj_person_schema = (new GDS\Schema('Person'))->addString('name')->addString('description'); $obj_store = new GDS\Store($obj_person_schema, $obj_gateway); // Load the parent (run 'ancestor_keys.php' if needed to create it) $obj_stored_parent = $obj_store->fetchOne("SELECT * FROM Person WHERE __key__ = KEY(Person, '*****@*****.**')"); // All "Person" entities in the group (INCLUDING the root) $arr = $obj_store->fetchAll("SELECT * FROM Person WHERE __key__ HAS ANCESTOR @person", ['person' => $obj_stored_parent]); print_r($arr); // Now just load one (which is a nested entity) print_r($obj_store->fetchAll("SELECT * FROM Person WHERE __key__ = @person", ['person' => $arr[1]]));
<?php /** * GDS Example - Create one record, with no Schema * * @author Tom Walder <*****@*****.**> */ require_once '../_includes.php'; // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine $obj_store = new \GDS\Store('Book'); // Alternative Gateway (remote JSON API) // Download your service JSON file from the Google Developer Console // $obj_gateway = new \GDS\Gateway\RESTv1('your-app-id'); // $obj_store = new \GDS\Store('Book', $obj_gateway); // Create a simple Entity object $obj_book = new GDS\Entity(); $obj_book->title = 'Romeo and Juliet'; $obj_book->author = 'William Shakespeare'; $obj_book->isbn = '1840224339'; // Insert into the Datastore $obj_store->upsert($obj_book); // Show the key echo "Created: ", $obj_book->getKeyId(), PHP_EOL;
<?php /** * Create a hierarchy of records in GDS * * @author Tom Walder <*****@*****.**> */ require_once 'boilerplate.php'; $obj_person_schema = (new GDS\Schema('Person'))->addString('name')->addString('description'); $obj_store = new GDS\Store($obj_person_schema, $obj_gateway); // Create the parent $obj_john = $obj_store->createEntity(); $obj_john->name = 'John Smiths'; $obj_john->description = 'A parent'; $obj_store->upsert($obj_john); // Create a child $obj_jane = $obj_store->createEntity(); $obj_jane->name = 'Jane Smiths'; $obj_jane->description = 'A child'; $obj_jane->setAncestry($obj_john); $obj_store->upsert($obj_jane); // Create a grand child $obj_jo = $obj_store->createEntity(); $obj_jo->name = 'Jo Smiths'; $obj_jo->description = 'A child'; $obj_jo->setAncestry($obj_jane); $obj_store->upsert($obj_jo); // Now fetch and display the Entity Group print_r($obj_store->fetchEntityGroup($obj_john));
<?php /** * GDS Example - Create one record (using the array syntax), with no Schema * * @author Tom Walder <*****@*****.**> */ require_once '../_includes.php'; // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine $obj_store = new \GDS\Store('Book'); // Alternative Gateway (remote JSON API) // Download your service JSON file from the Google Developer Console // $obj_client = \GDS\Gateway\GoogleAPIClient::createClientFromJson('/path/to/your/service.json'); // $obj_gateway = new \GDS\Gateway\GoogleAPIClient($obj_client, 'your-app-id'); // $obj_store = new \GDS\Store('Book', $obj_gateway); // Create a simple Entity object $obj_book = $obj_store->createEntity(['title' => 'Romeo and Juliet', 'author' => 'William Shakespeare', 'isbn' => '1840224339']); // Insert into the Datastore $obj_store->upsert($obj_book); // Show the key echo "Created: ", $obj_book->getKeyId(), PHP_EOL;
/** * Fetch with custom entity class */ public function testFetchByIdWithResult() { $obj_request = new \google\appengine\datastore\v4\LookupRequest(); $obj_request->mutableReadOptions(); $obj_key = $obj_request->addKey(); $obj_partition = $obj_key->mutablePartitionId(); $obj_partition->setDatasetId('Dataset'); $obj_kpe = $obj_key->addPathElement(); $obj_kpe->setKind('Book'); $obj_kpe->setId(123456789); $obj_response = new \google\appengine\datastore\v4\LookupResponse(); $obj_found = $obj_response->addFound(); $obj_entity = $obj_found->mutableEntity(); $obj_result_key = $obj_entity->mutableKey(); $obj_result_kpe = $obj_result_key->addPathElement(); $obj_result_kpe->setKind('Book'); $obj_result_kpe->setId(123456789); $obj_result_property = $obj_entity->addProperty(); $obj_result_property->setName('author'); $obj_val = $obj_result_property->mutableValue(); // addDeprecatedValue(); $obj_val->setStringValue('William Shakespeare'); $this->apiProxyMock->expectCall('datastore_v4', 'Lookup', $obj_request, $obj_response); $obj_gateway = new \GDS\Gateway\ProtoBuf('Dataset'); $obj_store = new \GDS\Store('Book', $obj_gateway); $obj_store->setEntityClass('Book'); $obj_result = $obj_store->fetchById(123456789); $this->assertInstanceOf('\\GDS\\Entity', $obj_result); $this->assertInstanceOf('\\Book', $obj_result); $this->assertEquals(1, count($obj_result->getData())); $this->assertEquals('Book', $obj_result->getKind()); $this->assertEquals(123456789, $obj_result->getKeyId()); $this->assertEquals($obj_result->author, 'William Shakespeare'); $this->apiProxyMock->verify(); }
public function testMixedOverlappingQuotedParamFallback() { $obj_deny_proxy = new DenyGQLProxyMock(); $obj_deny_proxy->init($this); $obj_request = new \google\appengine\datastore\v4\RunQueryRequest(); $obj_request->setSuggestedBatchSize(1000); $obj_request->mutableReadOptions(); $obj_partition = $obj_request->mutablePartitionId(); $obj_partition->setDatasetId('Dataset'); $obj_query = $obj_request->mutableQuery(); $obj_query->addKind()->setName('Book and "stuff"'); $obj_comp_filter = $obj_query->mutableFilter()->mutableCompositeFilter()->setOperator(\google\appengine\datastore\v4\CompositeFilter\Operator::AND_); $obj_prop_filter1 = $obj_comp_filter->addFilter()->mutablePropertyFilter()->setOperator(\google\appengine\datastore\v4\PropertyFilter\Operator::EQUAL); $obj_prop_filter1->mutableProperty()->setName('author'); $obj_prop_filter1->mutableValue()->setStringValue('William "Will" Shakespeare'); $obj_prop_filter2 = $obj_comp_filter->addFilter()->mutablePropertyFilter()->setOperator(\google\appengine\datastore\v4\PropertyFilter\Operator::EQUAL); $obj_prop_filter2->mutableProperty()->setName('isbn'); $obj_prop_filter2->mutableValue()->setStringValue("1234'5'6789"); $obj_deny_proxy->expectCall('datastore_v4', 'RunQuery', $obj_request, new \google\appengine\datastore\v4\RunQueryResponse()); $obj_gateway = new GDS\Gateway\ProtoBuf('Dataset'); $obj_store = new GDS\Store('Book', $obj_gateway); $obj_store->fetchAll('SELECT * FROM `Book and "stuff"` WHERE author = \'William "Will" Shakespeare\' AND isbn = "1234\'5\'6789"'); $obj_deny_proxy->verify(); }
/** * Test delete with namespace */ public function testDeleteWithNamespace() { $str_ns = 'TestNameSpace'; $obj_http = $this->initTestHttpClient('https://datastore.googleapis.com/v1/projects/DatasetTest:commit', ['json' => (object) ['mode' => 'NON_TRANSACTIONAL', 'mutations' => [(object) ['delete' => (object) ['path' => [(object) ['kind' => 'Test', 'id' => '123456789']], 'partitionId' => (object) ['projectId' => self::TEST_PROJECT, 'namespaceId' => $str_ns]]]]]]); $obj_gateway = $this->initTestGateway($str_ns)->setHttpClient($obj_http); $obj_store = new \GDS\Store('Test', $obj_gateway); $obj_entity = (new GDS\Entity())->setKeyId('123456789'); $obj_store->delete([$obj_entity]); $this->validateHttpClient($obj_http); }
<?php /** * GDS Example - Create several records in one upsert, with no Schema * * @author Tom Walder <*****@*****.**> */ require_once '../_includes.php'; // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine $obj_store = new \GDS\Store('Book'); // Alternative Gateway (remote JSON API) // Download your service JSON file from the Google Developer Console // $obj_gateway = new \GDS\Gateway\RESTv1('your-app-id'); // $obj_store = new \GDS\Store('Book', $obj_gateway); // Create some Entity objects $obj_romeo = $obj_store->createEntity(['title' => 'Romeo and Juliet', 'author' => 'William Shakespeare', 'isbn' => '1840224339']); $obj_midsummer = $obj_store->createEntity(['title' => "A Midsummer Night's Dream", 'author' => 'William Shakespeare', 'isbn' => '1853260304']); // Insert multiple into the Datastore $arr_books = [$obj_romeo, $obj_midsummer]; $obj_store->upsert($arr_books); // Show their keys foreach ($arr_books as $obj_book) { echo "Created: ", $obj_book->getKeyId(), PHP_EOL; }
<?php /** * Move data between name spaces * * @author Tom Walder <*****@*****.**> */ require_once '../_includes.php'; // Define our Book Schema $obj_schema = (new GDS\Schema('Book'))->addString('title', FALSE)->addString('author')->addString('isbn')->addDatetime('published', FALSE)->addInteger('pages', FALSE); // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine // BUT, this time With a namespace defined ("ns1") $obj_gateway_ns1 = new GDS\Gateway\ProtoBuf(null, 'ns1'); $obj_store_ns1 = new \GDS\Store($obj_schema, $obj_gateway_ns1); // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine // BUT, this time With a namespace defined ("ns2") $obj_gateway_ns2 = new GDS\Gateway\ProtoBuf(null, 'ns2'); $obj_store_ns2 = new \GDS\Store($obj_schema, $obj_gateway_ns2); // Fetch a record from the first namespace $obj_book = $obj_store_ns1->fetchOne(); // ========= // IMPORTANT // ========= // The book inserted to ns2 here will have the SAME keyId or keyName // BUT will be in a different namespace, so will still be uniquely addressable // As the "fully qualified" key of an Entity in GDS includes the namespace // Insert into the second namesapce $obj_store_ns2->upsert($obj_book);
<?php /** * Simplest GDS example - no schema, Kind only * * @author Tom Walder <*****@*****.**> */ require_once '../vendor/autoload.php'; require_once 'config/setup.php'; // We'll need a Google_Client, use our convenience method $obj_client = GDS\Gateway\GoogleAPIClient::createGoogleClient(GDS_APP_NAME, GDS_SERVICE_ACCOUNT_NAME, GDS_KEY_FILE_PATH); // Gateway requires a Google_Client and Dataset ID $obj_gateway = new GDS\Gateway\GoogleAPIClient($obj_client, GDS_DATASET_ID); // Store requires a Gateway and Kind $obj_book_store = new GDS\Store($obj_gateway, 'Book'); // Fetch a record $obj_book = $obj_book_store->fetchOne(); // Dump the result print_r($obj_book);
<?php /** * Query parameter examples - datetime bindings * * @author Tom Walder <*****@*****.**> */ require_once 'boilerplate.php'; // Schema with datetime $obj_task_schema = (new GDS\Schema('Task'))->addString('title')->addDatetime('due', TRUE); // Store requires a Gateway and Schema $obj_task_store = new GDS\Store($obj_gateway, $obj_task_schema); // Insert some data, with datetime binding $obj_task_1 = $obj_task_store->createEntity(['title' => 'My first task', 'due' => new DateTime('+1 day')]); $obj_task_store->upsert($obj_task_1); // Insert some data, with "normal" string format $obj_task_2 = $obj_task_store->createEntity(['title' => 'My first task', 'due' => date('Y-m-d H:10:00')]); $obj_task_store->upsert($obj_task_2); // Fetch with datetime binding $arr_results = $obj_task_store->fetchAll("SELECT * FROM Task WHERE due < @dtm", ['dtm' => new DateTime('+6 hours')]); describeResult($arr_results, TRUE); /** * Helper function to simplify results display * * @param $mix_result * @param bool $bol_recurse */ function describeResult($mix_result, $bol_recurse = FALSE) { if ($mix_result instanceof GDS\Entity) { $str_class = get_class($mix_result);
<?php /** * Create or some records in GDS * with an indexed string field * * * @author Tom Walder <*****@*****.**> */ require_once '../vendor/autoload.php'; require_once 'config/setup.php'; // We'll need a Google_Client, use our convenience method $obj_google_client = GDS\Gateway\GoogleAPIClient::createGoogleClient(GDS_APP_NAME, GDS_SERVICE_ACCOUNT_NAME, GDS_KEY_FILE_PATH); $obj_gateway = new GDS\Gateway\GoogleAPIClient($obj_google_client, GDS_DATASET_ID); // Optionally, namespace // Define the model on-the-fly $obj_contact_schema = (new GDS\Schema('Contact'))->addString('first_name')->addString('last_name')->addStringList('tags', TRUE); // Configure the Store $obj_store = new GDS\Store($obj_gateway, $obj_contact_schema); // Create 1 $obj_contact1 = $obj_store->createEntity(['first_name' => 'Tom', 'last_name' => 'Walder', 'tags' => ["customer", "newsletter"]]); $obj_contact1->setKeyName('*****@*****.**'); // Create 2 $obj_contact2 = $obj_store->createEntity(['first_name' => 'Thomas', 'last_name' => 'Walder', 'tags' => ["newsletter", "api"]]); $obj_contact2->setKeyName('*****@*****.**'); // Upsert $obj_store->upsert([$obj_contact1, $obj_contact2]);
/** * Fetch with string list */ public function testFetchWithStringListResult() { $obj_response = new \google\appengine\datastore\v4\LookupResponse(); $obj_found = $obj_response->addFound(); $obj_entity = $obj_found->mutableEntity(); $obj_result_key = $obj_entity->mutableKey(); $obj_result_kpe = $obj_result_key->addPathElement(); $obj_result_kpe->setKind('Book'); $obj_result_kpe->setId(123456789); $obj_result_property = $obj_entity->addProperty(); $obj_result_property->setName('director'); $obj_val = $obj_result_property->mutableValue(); $obj_val->setStringValue('Robert Zemeckis'); $obj_result_property2 = $obj_entity->addProperty(); $obj_result_property2->setName('dedications'); $obj_val2 = $obj_result_property2->mutableValue(); $obj_val2->addListValue()->setStringValue('Marty McFly'); $obj_val2->addListValue()->setStringValue('Emmett Brown'); $this->apiProxyMock->expectCall('datastore_v4', 'Lookup', $this->getBasicBookByIdRequest(), $obj_response); $obj_gateway = new GDS\Gateway\ProtoBuf('Dataset'); $obj_store = new GDS\Store('Book', $obj_gateway); $obj_result = $obj_store->fetchById(123456789); $this->assertInstanceOf('\\GDS\\Entity', $obj_result); $this->assertEquals(2, count($obj_result->getData())); $this->assertEquals('Book', $obj_result->getKind()); $this->assertEquals(123456789, $obj_result->getKeyId()); $this->assertEquals('Robert Zemeckis', $obj_result->director); $this->assertEquals(['Marty McFly', 'Emmett Brown'], $obj_result->dedications); $this->apiProxyMock->verify(); }
<?php /** * Name-spaced CREATE examples for GDS * * @author Tom Walder <*****@*****.**> */ require_once '../_includes.php'; // Define our Book Schema $obj_schema = (new GDS\Schema('Book'))->addString('title', FALSE)->addString('author')->addString('isbn')->addDatetime('published', FALSE)->addInteger('pages', FALSE); // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine // BUT, this time With a namespace defined ("ns1") $obj_gateway_ns1 = new GDS\Gateway\ProtoBuf(null, 'ns1'); $obj_store_ns1 = new \GDS\Store($obj_schema, $obj_gateway_ns1); // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine // BUT, this time With a namespace defined ("ns2") $obj_gateway_ns2 = new GDS\Gateway\ProtoBuf(null, 'ns2'); $obj_store_ns2 = new \GDS\Store($obj_schema, $obj_gateway_ns2); // Create a Book in the first namespace $obj_book1 = $obj_store_ns1->createEntity(['title' => 'Romeo and Juliet', 'author' => 'William Shakespeare', 'isbn' => '1840224339']); $obj_store_ns1->upsert($obj_book1); // Create a Book in the second namespace $obj_book2 = $obj_store_ns2->createEntity(['title' => 'Hamlet', 'author' => 'William Shakespeare', 'isbn' => '1853260096']); $obj_store_ns2->upsert($obj_book2);
/** * Name-spaced FETCH examples for GDS * * @author Tom Walder <*****@*****.**> */ require_once '../_includes.php'; // Define our Book Schema $obj_schema = (new GDS\Schema('Book'))->addString('title', FALSE)->addString('author')->addString('isbn')->addDatetime('published', FALSE)->addInteger('pages', FALSE); // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine // BUT, this time With a namespace defined ("ns1") $obj_gateway_ns1 = new GDS\Gateway\ProtoBuf(null, 'ns1'); $obj_store_ns1 = new \GDS\Store($obj_schema, $obj_gateway_ns1); // This Store uses the default Protocol Buffer Gateway - for App Engine local development or live App Engine // BUT, this time With a namespace defined ("ns2") $obj_gateway_ns2 = new GDS\Gateway\ProtoBuf(null, 'ns2'); $obj_store_ns2 = new \GDS\Store($obj_schema, $obj_gateway_ns2); // Fetch all (client 1) echo "From ns1", PHP_EOL; $arr_books1 = $obj_store_ns1->fetchAll("SELECT * FROM Book"); echo "Query client 1 found ", count($arr_books1), " records", PHP_EOL; foreach ($arr_books1 as $obj_book) { echo " Title: {$obj_book->title}, ISBN: {$obj_book->isbn}", PHP_EOL; } // Fetch all (client 2) echo "From ns2", PHP_EOL; $arr_books2 = $obj_store_ns2->fetchAll("SELECT * FROM Book"); echo "Query client 2 found ", count($arr_books2), " records", PHP_EOL; foreach ($arr_books2 as $obj_book) { echo " Title: {$obj_book->title}, ISBN: {$obj_book->isbn}", PHP_EOL; }
describeResult($obj_book); // Fetch all $arr_books = $obj_book_store->fetchAll("SELECT * FROM Book"); describeResult($arr_books); // Fetch paginated $obj_book_store->query('SELECT * FROM Book'); while ($arr_page = $obj_book_store->fetchPage(50)) { describeResult($arr_page); } // Retrieve multiple rows by ID echo "Multi fetch:", PHP_EOL; $arr_books = $obj_book_store->fetchByIds(['5692592335355904', '5149586599444480']); foreach ($arr_books as $obj_book) { describeResult($obj_book); } $obj_store = new GDS\Store('Contact', $obj_gateway); $arr_contacts = $obj_store->fetchByNames(['*****@*****.**', '*****@*****.**']); foreach ($arr_contacts as $obj_contact) { echo " Found: {$obj_contact->first_name}, {$obj_contact->last_name}", PHP_EOL; } /** * Helper function to simplify results display * * @param $mix_result * @param bool $bol_recurse */ function describeResult($mix_result, $bol_recurse = FALSE) { if ($mix_result instanceof GDS\Entity) { $str_class = get_class($mix_result); echo "Found single result: [{$str_class}] {$mix_result->getKeyId()}, {$mix_result->title}, {$mix_result->isbn}, {$mix_result->author}", PHP_EOL;
<?php /** * Create, update and retrieve a series of Entities to test retrieval and mapping of Auto-insert IDs * * @author Tom Walder <*****@*****.**> */ require_once 'boilerplate.php'; $obj_store = new GDS\Store('Temperatures', $obj_gateway); // Delete ALL // $obj_store->delete($obj_store->fetchAll()); // Create some new records with random temperatures $arr_new_records = []; $int_new_records = mt_rand(10, 20); for ($int = 1; $int <= $int_new_records; $int++) { $obj_new_entity = $obj_store->createEntity(['temp' => mt_rand(1, 9999)]); $arr_new_records[] = $obj_new_entity; } $obj_store->upsert($arr_new_records); // Now keep a record of the mapping (POST upsert) $arr_temp_id_map = []; foreach ($arr_new_records as $obj_temp) { $arr_temp_id_map[$obj_temp->getKeyId()] = $obj_temp->temp; } // Get all records from the Datastore and compare $arr_all_temps = $obj_store->fetchAll(); foreach ($arr_all_temps as $obj_stored_temp) { echo $obj_stored_temp->getKeyID() . " has temp " . $obj_stored_temp->temp; if (isset($arr_temp_id_map[$obj_stored_temp->getKeyID()])) { if ($arr_temp_id_map[$obj_stored_temp->getKeyID()] == $obj_stored_temp->temp) { echo ", match OK";
/** * Insert One WITH result */ public function testUpsertOneAutoIdWithResult() { $obj_request = new \google\appengine\datastore\v4\CommitRequest(); $obj_request->setMode(\google\appengine\datastore\v4\CommitRequest\Mode::NON_TRANSACTIONAL); $obj_mutation = $obj_request->mutableDeprecatedMutation(); $obj_entity = $obj_mutation->addInsertAutoId(); $obj_key = $obj_entity->mutableKey(); $obj_partition = $obj_key->mutablePartitionId(); $obj_partition->setDatasetId('Dataset'); $obj_kpe = $obj_key->addPathElement(); $obj_kpe->setKind('Film'); $obj_property = $obj_entity->addProperty(); $obj_property->setName('title'); $obj_val = $obj_property->mutableValue(); $obj_val->setIndexed(TRUE); $obj_val->setStringValue('Back to the Future'); $obj_response = new \google\appengine\datastore\v4\CommitResponse(); $obj_mutation_result = $obj_response->mutableDeprecatedMutationResult(); $obj_ai_key = $obj_mutation_result->addInsertAutoIdKey(); $obj_ai_kpe = $obj_ai_key->addPathElement(); $obj_ai_kpe->setKind('Film')->setId(499190400); $this->apiProxyMock->expectCall('datastore_v4', 'Commit', $obj_request, $obj_response); $obj_gateway = new GDS\Gateway\ProtoBuf('Dataset'); $obj_store = new GDS\Store('Film', $obj_gateway); $obj_book = $obj_store->createEntity(['title' => 'Back to the Future']); $obj_store->upsert($obj_book); $this->assertEquals(499190400, $obj_book->getKeyId()); $this->apiProxyMock->verify(); }
/** * Fetch data from GDS * with an indexed string field * * * @author Tom Walder <*****@*****.**> */ require_once '../vendor/autoload.php'; require_once 'config/setup.php'; // We'll need a Google_Client, use our convenience method $obj_google_client = GDS\Gateway\GoogleAPIClient::createGoogleClient(GDS_APP_NAME, GDS_SERVICE_ACCOUNT_NAME, GDS_KEY_FILE_PATH); $obj_gateway = new GDS\Gateway\GoogleAPIClient($obj_google_client, GDS_DATASET_ID); // Optionally, namespace // Define the model on-the-fly $obj_contact_schema = (new GDS\Schema('Contact'))->addString('first_name')->addString('last_name')->addStringList('tags', TRUE); // Configure the Store $obj_store = new GDS\Store($obj_contact_schema, $obj_gateway); // A couple of tests show($obj_store->fetchAll("SELECT * FROM Contact_v1 WHERE tags = 'newsletter' AND tags = 'customer'")); show($obj_store->fetchAll("SELECT * FROM Contact_v1 WHERE tags = 'api'")); show($obj_store->fetchAll("SELECT * FROM Contact_v1 WHERE tags = 'newsletter'")); /** * Show result data * * @param $arr */ function show($arr) { echo PHP_EOL, "Query found ", count($arr), " records", PHP_EOL; foreach ($arr as $obj_model) { echo " Email: {$obj_model->getKeyName()}, Name: {$obj_model->first_name}", PHP_EOL; }
<?php /** * Create a single record in GDS * * @author Tom Walder <*****@*****.**> */ require_once 'boilerplate.php'; $obj_person_schema = (new GDS\Schema('Person'))->addString('name')->addString('description'); $obj_store = new GDS\Store($obj_person_schema, $obj_gateway); // Create the parent $obj_john = new \GDS\Entity(); $obj_john->name = 'John Smiths'; $obj_john->description = 'A parent'; $obj_john->setKeyName('*****@*****.**'); $obj_store->upsert($obj_john); $obj_stored_parent = $obj_store->fetchOne("SELECT * FROM Person WHERE __key__ = KEY(Person, '*****@*****.**')"); // Create a child $obj_jane = new \GDS\Entity(); $obj_jane->name = 'Jane Smiths'; $obj_jane->description = 'A child'; $obj_jane->setKeyName('*****@*****.**'); $obj_jane->setAncestry($obj_stored_parent); $obj_store->upsert($obj_jane);