GAE PHP Datastore Query - php

For a project I am using Google App Engine's Datastore with PHP, which does not have official documentation.
I used the following guide to successfully be able to add new entities to the datastore, but now I am struggling to get queries working so that I can retrieve data and display it on my web page.
https://gae-php-tips.appspot.com/2013/12/23/getting-started-with-the-cloud-datastore-on-php-app-engine/
Here is my current code:
try {
// test the config and connectivity by creating a test entity, building
// a commit request for that entity, and creating/updating it in the datastore
// $req = createRequest();
// $service_dataset->commit($dataset_id, $req, []);
$req = createQuery();
// printQueryResults($req);
}
catch (Google_Exception $ex) {
syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
echo "There was an issue -- check the logs.";
return;
}
function createQuery()
{
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString("SELECT * FROM 'Notes' WHERE name = 'test1'");
$gql_query->setAllowLiteral(true);
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $req;
}
I want to be able to query my datastore and get all the entities that have a matching name.

I tested successfully this following code adapted, i assume that you are using DatastoreService.php from the guide you mentioned. There must be different ways to parse the query result but here is one ;)
config.php : replace with your credentials
<?php
$google_api_config = [
'application-id' => 'xxxxxxxxxxxxxxx',
'service-account-name' => 'xxxxx#developer.gserviceaccount.com',
'private-key' => file_get_contents('xxxxxxx.p12'),
'dataset-id' => 'xxxxxxxxxxxx'
];
your code adapted
require_once 'config.php';
require_once 'DatastoreService.php';
try {
$req = createQuery();
}
catch (Google_Exception $ex) {
syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
echo "There was an issue -- check the logs.";
return;
}
// from config.php
$options = $google_api_config;
$datastoreService = new DatastoreService($options);
$result = $datastoreService->runQuery($req, $optParams = []);
$results = $result->getBatch()->getEntityResults();
$items = array();
foreach ($results as $item) {
$item = $item->getEntity()->getProperties();
$items[] = $item['name']['stringValue'];
}
echo '<plaintext>' . print_r($items, true);
function createQuery()
{
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString($query = "SELECT * FROM Notes WHERE name = 'test1'");
$gql_query->setAllowLiteral(true);
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $req;
}

Include google/cloud-datastore library via composer as below.
$ composer require google/cloud-datastore
and you can use Query mothod as Example below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Datastore\DatastoreClient;
$datastore = new DatastoreClient([
'projectId' => 'my_project'
]);
$query = $datastore->query();
$query->kind('Notes');
$query->filter('name ', '=', 'test1');
$res = $datastore->runQuery($query);
foreach ($res as $notes) {
echo $notes['name']; // test1
}
Or it can be build using query object
<?php
$query = $datastore->query([
'query' => [
'kind' => [
[
'name' => 'Notes'
]
],
'filter' => [
'propertyFilter' => [
'op' => 'EQUAL',
'property' => [
'name' => 'name'
],
'value' => [
'stringValue' => 'test1'
]
]
]
]
]);

Related

Google Task API PHP: Setting the TaskList ID & "Invalid task list ID" error

I'm trying to loop through task lists in order to generate a list of tasks using the Google Task PHP library.
I have:
Done all the credential stuff & can call the API
I can get task lists
A list of tasks for the respective task list output correctly using the ids generated from the point above & the tasklist parameter in Task API explorer
Where I'm stuck:
I'm not sure if I'm calling the 1) wrong method or 2) passing the wrong parameter to get a list of tasks for a respective tasklist id.
My code:
function getGcalTasks(){
$client = $this->getGcalTaskClient();
try {
$service = new Google_Service_Tasks($client);
$optParamLists = array(
'maxResults' => 10,
);
$result_lists = $service->tasklists->listTasklists($optParamLists);
if (
is_array($result_lists->getItems())
&& count($result_lists->getItems())
) {
foreach ($result_lists->getItems() as $tasklist) {
$taskListId = trim($tasklist->getId());
$taskListTitle = trim($tasklist->getTitle());
if(
$taskListId
){
$optParamsTasks = array(
// I've tried all of the below and still get: "Invalid task list ID",
'id' => $taskListId,
'kind' => 'tasks#taskList',
'title' => $taskListTitle,
//'tasklist' => $taskListId,
//'taskList' => $taskListId,
//'tasklistId' => $taskListId,
//'listName' => $taskListTitle,
);
$result_tasks = $service->tasks->listTasks($optParamsTasks);
}
}
}
} catch (Exception $e) {
log_message('error',$e->getMessage());
}
}
Welp, I took a look a few minutes later and realized that listTasks() only accepts one parameter, the id. The code below is working for me:
function getGcalTasks(){
$client = $this->getGcalTaskClient();
$tasks = array();
try {
$service = new Google_Service_Tasks($client);
$optParamLists = array(
'maxResults' => 10,
);
$result_lists = $service->tasklists->listTasklists($optParamLists);
if (
is_array($result_lists->getItems())
&& count($result_lists->getItems())
) {
foreach ($result_lists->getItems() as $tasklist) {
$taskListId = trim($tasklist->getId());
$taskListTitle = trim($tasklist->getTitle());
if(
$taskListId
){
$optParamsTasks = array(
'tasklist' => $taskListId,
);
$result_tasks = $service->tasks->listTasks($taskListId);
$tasks[] = $result_tasks->getItems();
}
}
return $tasks;
}
} catch (Exception $e) {
log_message('error',$e->getMessage());
}
}

Laravel + Shopify inventoryBulkAdjustQuantityAtLocation

I'm using following package : 'osiset/Basic-Shopify-API' and need bulk update products by location.
It's only possible with GraphQL. This function should work :
inventoryBulkAdjustQuantityAtLocation Shopify documentation
$shop = 'example.myshopify.com';
$token = 'shppa_admin_api_token';
/ Create options for the API
$options = new Options();
$options->setVersion('2020-04');
// Create the client and session
$api = new BasicShopifyAPI($options);
$api->setSession(new Session($shop, $token));
$products[0]['inventoryItemId'] = '33125243617303';
$products[0]['availableDelta'] = 2000;
$result = $api->graph(
'mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: InventoryAdjustItemInput!,$locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $InventoryAdjustItemInput, locationId: $locationId) {userErrors {field message } inventoryLevels { id }}}',
['inventoryItemAdjustments' =>
$products
],
);
But I don't understand how to use it. Could anyone help me ?
Now it works. It's a challenge to understand GraphQL queries if you never used them before.
Here are some more information :
https://www.shopify.com/partners/blog/multi-location_and_graphql
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments1['locationId'] = $locationId;
$inventoryItemAdjustments1['inventoryItemAdjustments']['inventoryItemId'] = 'gid://shopify/InventoryItem/1';
$inventoryItemAdjustments1['inventoryItemAdjustments']['availableDelta'] = 500;
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$inventoryItemAdjustments1
);
Not so good examples (hardcoded values, aliases - not real life examples) ... graphql variables should be used and they should match mutation requirements ('root' parameters), in this case locationId and inventoryItemAdjustments (array of objects).
You can test this mutation in graphiql/playground using 'query variables' defined like this:
{
locationId: "gid://shopify/Location/1",
inventoryItemAdjustments: [
{
'inventoryItemId': 'gid://shopify/InventoryItem/1',
'availableDelta': 500
},
{
'inventoryItemId': 'gid://shopify/InventoryItem/2',
'availableDelta': 100
}
]
}
... so using php (associative arrays are encoded to json as objects - explicitely declared for readability) it should look more like this:
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments = [];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/1',
'availableDelta'] => 500;
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/2',
'availableDelta'] => 100;
];
$variables = (object)[
'locationId' => $locationId;
'inventoryItemAdjustments' => $inventoryItemAdjustments
];
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$variables
);
I would like to show another library that uses this and expand on the last example.
I am using a slightly different library for graphql:
https://github.com/Shopify/shopify-php-api/
Updating the inventory like it was posted here shows a [statusCode:GuzzleHttp\Psr7\Response:private] => 200
So it seems to work but does not reflect in updated inventory. :(
Checking at /admin/products/inventory?location_id=62241177806&query=F11_27781195
would not show the new inventory.
I am using the inventoryid correctly (not product or variantid).
$inventoryItemAdjustments = array();
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435235534',
'availableDelta' => 500
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435268302',
'availableDelta' => 500
];
$variables = array(
'locationId' => ConfigClass::$locationId,
'inventoryItemAdjustments' => $inventoryItemAdjustments
);
$graphqlquery='mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}';
$response = $client->query(['query' => $graphqlquery, 'variables' => $variables]);
Deleting a product works (and is a good test if the library is initialized well):
$query = <<<QUERY
mutation {
productDelete(input: {id: "gid://shopify/Product/6975310463182"})
{
deletedProductId
}
}
QUERY;
$response = $client->query(["query" => $query]);
print_r($response);
die;

How can I delete rows from Google Sheet with PHP?

I use Google Api PHP Library.
I want to delete rows.
I found it, but how can I use it? https://github.com/google/google-api-php-client-services/blob/master/src/Google/Service/Sheets/DeleteDimensionRequest.php
For example, I use it for adding rows:
// Build the CellData array
$values = array();
foreach( $ary_values AS $d ) {
$cellData = new Google_Service_Sheets_CellData();
$value = new Google_Service_Sheets_ExtendedValue();
$value->setStringValue($d);
$cellData->setUserEnteredValue($value);
$values[] = $cellData;
}
// Build the RowData
$rowData = new Google_Service_Sheets_RowData();
$rowData->setValues($values);
// Prepare the request
$append_request = new Google_Service_Sheets_AppendCellsRequest();
$append_request->setSheetId(0);
$append_request->setRows($rowData);
$append_request->setFields('userEnteredValue');
// Set the request
$request = new Google_Service_Sheets_Request();
$request->setAppendCells($append_request);
// Add the request to the requests array
$requests = array();
$requests[] = $request;
// Prepare the update
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => $requests
));
try {
// Execute the request
$response = $sheet_service->spreadsheets->batchUpdate($fileId, $batchUpdateRequest);
if( $response->valid() ) {
// Success, the row has been added
return true;
}
} catch (Exception $e) {
// Something went wrong
error_log($e->getMessage());
print_r($e->getMessage());
}
return false;
Please Try this works for me
$spid = '1lIUtn8WmN1Yhgxv68dt4rylm6rO77o8UX8uZu9PIu2o'; // <=== Remember to update this to your workbook to be updated
$deleteOperation = array(
'range' => array(
'sheetId' => 0, // <======= This mean the very first sheet on worksheet
'dimension' => 'ROWS',
'startIndex'=> 2, //Identify the starting point,
'endIndex' => (3) //Identify where to stop when deleting
)
);
$deletable_row[] = new Google_Service_Sheets_Request(
array('deleteDimension' => $deleteOperation)
);
Then Send the query to google to update your worksheet
$delete_body = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => $deletable_row
)
);
//var_dump($delete_body);
$result = $service->spreadsheets->batchUpdate($spid, $delete_body);
you check here. This assists me when trying to solve google sheet deleting operation.
I hope this helps you. Thanks and keep in touch

Not able to update mongo document with following code

Im using following code to update a mongo document. But its not working when I use $inc in order to increment a counter. It works well if no inc is used.
$arrWhere = array('epa_id' => $objData->request->memo->epa_id);
$arrSet = array(
'pa_response'=>$objData,
'response_status'=>'N',
'modified_datetime'=> getServerTimeStamp(),
array('$inc'=>array('revision_id'=>1)),
);
$arrResult = $objPriorAuth->updatePA($arrWhere, $arrSet);
public function updatePA($arrWhere,$arrSet)
{
global $medDB;
$strCollection = EPA_MASTER;
$dbCollection = $medDB->$strCollection;
$arrReturn = array();
//dump($arrSet);
try
{
$dbCollection->update(
$arrWhere,
array('$set' =>$arrSet),
array('multiple' => true)
);
dump($medDB->lastError());
}
catch(MongoCursorException $mce)
{
$arrReturn['error'] = $mce->getMessage();
logError($mce->getMessage(),DB_ERROR_LOG_FILE_PATH);
}
return $arrReturn;
}
It's wrong syntax, you can't use inc inside set. Try out the following code:
Change options:
$arrSet = array(
'pa_response'=>$objData,
'response_status'=>'N',
'modified_datetime'=> getServerTimeStamp()
);
$arrInc = array('$inc'=>array('revision_id'=>1));
Change update query:
array('$set' => $arrSet, '$inc' => $arrInc);

Rename mongo database

I am doing project using mongodb and php. so here I tried to rename existing database using php. so I did following way to rename database.
first I create new database( user new database name)
read all records from old db and insert to new db
then I drop old db
this is my code.
$conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
$exist_dbs = $conn->listDBs();
foreach ($exist_dbs["databases"] as $databse) {
if ($databse['name'] == $new_name) {
$new_name_is_exist = true;
}
}
if (!$new_name_is_exist) {
$db = new \MongoDB($conn, $old_name);
//create new database
$db_new = new \MongoDB($conn, $new_name);
$collections = $db->getCollectionNames();
foreach ($collections as $collection) {
//create collection
$new_collection = new \MongoCollection($db_new, $collection);
$mongo_collection = $db->$collection;
$objects = $mongo_collection->find();
while ($document = $objects->getNext()) {
//add records
$new_collection->insert($document);
}
}
$db->drop();
$msg = 'database renamed';
} else {
$msg = 'given database name already exist';
}
$conn->close();
it works fine. but I would like to know is there any better way to rename mongo database using php?
Copy db (php + mongodb):
<?php
$rename = 'oldname';
$name = 'newname';
$mongo = (new MongoClient());
$db = $mongo->admin;
$response = $db->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => $rename,
'todb' => $name
));
print_r($response);
Drop db (php + mongodb):
<?php
$name = 'oldname';
$mongo = (new MongoClient());
$db = $mongo->$name;
$response = $db->command(array(
'dropDatabase' => 1
));
print_r($response);
$db=new new Mongo();
Copy old_db to new_db
$responseCopy = $db->admin->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => 'old_db',
'todb' =>'new_db'
));
Now drop old_db
if($responseCopy['ok']==1){
$responseDrop=$db->old_db->command(array('dropDatabase' => 1));
//OR
$responseDrop =$db->old_db->drop();
}
Show Output
print_r($responseCopy);
print_r($responseDrop);
Output will be something like this
Array ( [ok] => 1 )
Array ( [dropped] => old_db [ok] => 1 )
you can use this
$mongo = new MongoClient('_MONGODB_HOST_URL_');
$query = array("renameCollection" => "Database.OldName", "to" => "Database.NewName", "dropTarget" => "true");
$mongo->admin->command($query);

Categories