Update only the given column value with appsync api and datasource as posgresql - postgresql

I have created appsync api with postgresql as datasource. Now it's very straight to create , update and delete any record with graphql. But i want something like, whenever any update takes places , i can update value of that particular column only. Eg
lets we have user table with 3 fields:
user_id
name
city
now when we update city for user than only city should update:
mutation update{
updateUser(input:{user_id:"xxxxx",city:"xyz"}){
user_id
name
city
}}
user update input:
input updateUserInput{
user_id!
name
city
}
Is there any way to do this in vtx template or we have to use lambda as datasource and then do this.

I figured it out how we can achieve it:
you can do like this:
#set ($updates = "")
#foreach( $item in $ctx.args.input.keySet())
#if($item)
#set ($updates = "$updates, $item = '$ctx.args.input.get($item)'")
#end
#end
--------used cognito as authentication , so user id will come in indentity
#set($user_id = ($ctx.identity.username))
#set($updates = "$updates, updated_at = '$util.time.nowFormatted('yyyy-MM-dd HH:mm:ssZ')'")
{
"version": "2018-05-29",
"statements": [
$util.toJson("update public.tableName SET $updates.substring(1) WHERE user_id = '$user_id'"),
$util.toJson("select * from public.tableName WHERE user_id = '$user_id'")
]
}
I hope it will help someone.

Related

How to model custom relationships involving multiple fields in Hasura?

I am using Hasura with Postgres database. I have 2 tables:
LithicTransaction
id: uuid
LedgerItem
id: uuid
type: text
referenceId: uuid
Their relationship:
A LithicTransaction may have 0 or 1 LedgerItem.
A LedgerItem may have 0 or 1 LithicTransaction.
I would like to model these 2 relationships. I know the underlying SQL statements, but I do not know if it is possible to set these as relationships in Hasura.
Problem 1:
Add LithicTransaction.ledgerItem, which resolves to 0 or 1 LedgerItem object.
The goal is to be able to write GraphQL query such as:
query {
lithicTransactions {
id
ledgerItem {
id
}
}
}
Possible SQL implementation:
-- getLedgerItem(lithicTransaction.id)
SELECT * FROM LedgerItem
WHERE type = 'LITHIC_TRANSACTION' AND referenceID = $1
LIMIT 1;
$1 = a specific LithicTransaction.id
Problem 2:
Add LedgerItem.lithicTransaction, which resolves to 0 or 1 LithicTransaction object.
The goal is to be able to write GraphQL query such as:
query {
ledgerItems {
id
lithicTransaction {
id
}
}
}
Possible SQL implementation:
-- getLithicTransaction(ledgerItem.referenceId, ledgerItem.type)
SELECT * FROM LithicTransaction
WHERE id = $1 AND 'LITHIC_TRANSACTION' = $2
LIMIT 1;
$1 = a specific LedgerItem.referenceId
$2 = a specific LedgerItem.type
Please let me know if this is possible with Hasura, or any recommended workarounds. Thank you.
So if I understood correctly:
desired relationship is object relationship
LedgerItem.type must be equal 'LITHIC_TRANSACTION'
Hasura now don't support equations as field = constant.
But an easy workaround exists:
1. Create a view with type='LITHIC_TRANSACTION'
CREATE VIEW LedgerItemLythic
AS
SELECT * FROM LedgerItem
WHERE
WHERE type = 'LITHIC_TRANSACTION'
2.Register this view (LedgerItemLythic) in hasura
3.Open relationships for this view (LedgerItemLythic) and create manually object relationship
Define object relationship LedgerItemLythic.reference_id = LithicTransaction.id
4.Open relationships for LithicTransaction and create manually object relationship
Define object relationship LithicTransaction.id = LedgerItemLythic.reference_id
Mission accomplished.

I am having trouble with my postgresql query

I have a query in mysql works well, but when I go to postgresql does not update me, I want to know where is my error.
I leave my php file the query update does not work
<?php
require_once "Controllers/conexion.php";
session_start();
$resultado=pg_query("SELECT nextval('user_id_seq') as key");
$row=pg_fetch_array($resultado, 0);
$key=$row['key'];
try {
$resultado = pg_query($conexion,"select * from encuesta_respuesta where id_user = '".$_SESSION['user']."' and id_encuesta = '".$_POST['id_encuesta']."'");
while( $row = pg_fetch_assoc($resultado)){
$data = $row;
}
if ($data['estado']=='F') {
header("Location: Inicio.php");
}
foreach($_POST['pregunta'] as $id_pregunta=>$valor){
$query="insert into encuesta_respuesta_opcion values (".$key.",".$_POST['id_encuesta'].",".$id_pregunta.",".$valor.")";
$resultado = pg_query($conexion,$query);
}
$query="update encuesta_respuesta set estado='F' where id_user=".$_SESSION['user']." and id_encuesta = ".$_POST['id_encuesta'];
$resultado = pg_query($conexion,$query);
$resp['error']=false;
} catch (Exception $e) {
$resp['error']=true;
}
header("Location: Inicio.php");
?>
Directly try to update data in your database, check this query works or not. If it works, then you have to change your query building procedure in your application. For example:
postgres=# create table test (id_user VARCHAR (50) PRIMARY KEY, id_encuesta VARCHAR (50), estado VARCHAR (10));
postgres=# insert into test values ('anower','engg.','A');
postgres=# update test set estado='F' where id_user='anower' and id_encuesta='engg.';
The query should work the same in MySql and postgres.
If you are getting different results during updates then your survey tables arent the same.
Most liked id_user and id_encuesta are autoincrement fields. So they dont necesary have the same values.
Try using a Select to see if they have same survey information.
SELECT *
FROM survey
where id_user=".$_SESSION['user']."
and id_encuesta = ".$_POST['id_encuesta'];

Magento2 DOB Customer attribute Save

While customer creation , i need to store dob attribute for customer.which is not saving. facing issue like,
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer_entity.value_id' in 'field list', query was: SELECT customer_entity.value_id FROM customer_entity WHERE (attribute_id='11' AND entity_id='199')
meanwhile,if i added custom date attribute in customer entity it get saved.
Any one have any idea about it.
Thanks in advance.
I am storing custom attributes as given below,
$data = []; //Array of attributes with key as attribute code
$customer = $this->customerModel->load($customerId);
$customerData = $customer->getDataModel();
$customerResource = $this->customerAttrFactory->create();
foreach ($data as $attrCode => $attrValue):
$customerData->setCustomAttribute($attrCode, $attrValue);
$customer->updateData($customerData);
$customerResource->saveAttribute($customer, $attrCode);
endforeach;
No need to save dob as an attribute.
Customer entity table has dob field so we can set it through customer model as given below.
$websiteId = $this->storeManager->getWebsite()->getWebsiteId();
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$data['dob'] = $formData['dob'];
$customer->setData($data);
$customer->save();

MotorEngine - How to represent the equivalent of the foreign key in model?

In MongoDB I have a document that represents a Balance which has an Stakeholder's ID as a field.
I need to relate these two classes, Balance and Stakeholder, but I don't know what's the proper way. I've seen there's a field that could be appropiate but I still don't understand it: EmbeddedDocumentField()
class Balance(Document):
id = UUIDField()
creation_date = DateTimeField(auto_now_on_insert=True)
gross_balance = FloatField(required=True, min_value=0, default=0)
balances_description = StringField(required=True, max_length=255)
stake_holder = #FK to Stakeholder
class Stakeholder(Document):
...
Any idea?
If Stakeholder represents document from other collection and stake_holder is ObjectId, you should use ReferenceField()
stake_holder = ReferenceField(reference_document_type=Stakeholder)

Is there a way to update a database field based on a list?

Using JPA, I have a list of entries from my database :
User(id, firstname, lastname, email)
That I get by doing:
List<User> users = User.find("lastname = ?", "smith");
And I'd like to update all in one request, by doing something like this :
"UPDATE USER SET email = null IN :list"
and then set the parameter "list" to users
Is it possible? if so, how?
Thanks for your help :)
Well, you could embed the query that you used to obtain list in the where clause of the update.
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName = :?)
By doing this you'd be doing the query to search the list and the update in single update query.
How do you like that? Do you think this could work?
-EDIT-
Since you want to use the original list of items instead of a list just retrieved from the database, you can still ensure you build the original list like this
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName IN(:originalList))
Then when you invoke it, you can do something like this:
Collection<String> originalList = Arrays.asList("Kenobi", "Skywalker", "Windu");
query.setParameter("originalList", originalList);
By this, you can still ensure the query will only contain items in your original list and not any possible new item from the database, provided that that last name is a candidate key in the database, otherwise I would recommend that you use the ID for the subquery instend of the last name.
if you have jpa+hibernate you can use entityManager.createQuery() for creating hql query
like that:
String hql = "UPDATE Supplier SET name = :newName WHERE name IN :name";
entityManager.createQuery(hql);