I am trying to update my RDS Aurora database with simple information.
import * as AWS from 'aws-sdk';
import { BatchExecuteStatementRequest } from 'aws-sdk/clients/rdsdataservice';
const RDS = new AWS.RDSDataService();
export const create = async (event: any) => {
try {
const params: BatchExecuteStatementRequest = {
secretArn: 'arn:aws:secretsmanager:XXXXXXXXXXXXXXXXXXX',
resourceArn: 'arn:aws:rds:XXXXXXXXXXXXXXXXXXXXX',
schema: 'PUBLIC',
database: 'test_db',
parameterSets: [
[
{
name: 'FirstName',
value: {
stringValue: 'Joe',
}
},
{
name: 'LastName',
value: {
stringValue: 'Doe'
}
}
],
[
{
name: 'FirstName',
value: {
stringValue: 'Joyer',
}
},
{
name: 'LastName',
value: {
stringValue: 'Doyer'
}
}
]
],
sql: 'INSERT INTO test_table (FirstName, LastName) VALUES (:FirstName, :LastName)'
};
const res = await RDS.batchExecuteStatement(params).promise();
console.log({ result: res, params });
return {
statusCode: 200,
body: JSON.stringify(res)
};
} catch (err) {
console.error(err);
return {
statusCode: err.statusCode || 500,
headers: { 'Content-Type': 'text/plain' },
body: 'Could not create the note.'
};
}
};
This will generate an error:
{ BadRequestException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ’(’Joyer’, ‘Doyer’)' at line 1 }
The weird part is, it's working if I only add ONE person in parameterSets, so the error occur when I try to have more than one array.
I created my db in AWS console, this is the query for that:
CREATE DATABASE IF NOT EXISTS test_db;
USE test_db;
CREATE TABLE IF NOT EXISTS test_table (
Id int NOT NULL AUTO_INCREMENT,
FirstName varchar(255),
LastName varchar(255),
PRIMARY KEY (Id)
);
I found the problem while I was writing the question, thought I will share it here anyway.
You can NOT have AUTO_INCREMENT!
This was the error, just remove it and everything works.
This was a couple of fun hours.....
Related
I have created a plugin in the adminstration and I want to insert the manyToMany products with vehicles into Shopware 6 database. From the code below I am trying to insert '92961afbc50e4380b3af86b257630ade' into the 'product_id' column of the 'vehicles_product' table :
import template from './sw-vehicles-import.html.twig';
const { Component, Mixin } = Shopware;
Component.register('sw-vehicles-import', {
template,
inject: ['importExport', 'repositoryFactory', 'feature'],
mixins: [
Mixin.getByName('notification'),
],
metaInfo() {
return {
title: this.$createTitle()
};
},
data() {
return {
importFile: null,
repository: null,
entity: undefined,
};
},
computed: {
},
created() {
this.repository = this.repositoryFactory.create('vehicles');
},
methods: {
onStartProcess() {
this.entity = this.repository.create(Shopware.Context.api);
this.entity.categoryFilter = 'CategoryName';
this.entity.featureFilter = 'FeatureName';
this.entity.products.productId = '92961afbc50e4380b3af86b257630ade';
this.repository.save(this.entity, Shopware.Context.api);
}
}
});
The build process doesn't work, what am I doing wrong? Could you help me please ?
You need to create a new entity collection for the association if it doesn't exist yet.
const { EntityCollection } = Shopware.Data;
if (!this.entity.products) {
this.entity.products = new EntityCollection(
'/product',
'product',
Shopware.Context.api
);
}
const product = await this.repositoryFactory.create('product').get('92961afbc50e4380b3af86b257630ade', Shopware.Context.api);
this.entity.products.add(product);
this.repository.save(this.entity, Shopware.Context.api);
when I create feed in Screen A,
I add and in order to apply this change to screen directly I change cache like below.
in this Screen A, I use seeAllFeeds query.
So I add this added feed to seeAllFeeds.
const updateUploadPhoto = (cache, result) => {
const {
data: { createFeed },
} = result;
if (createFeed.id) {
cache.modify({
id: "ROOT_QUERY",
fields: {
seeAllFeeds(prev) {
return [createFeed, ...prev];
},
},
});
}
}
So it works well.
But problem is I use seeCertainUserFeedpoem query in Screen B.
And here, I also need to add this added feed info.
However this screen is not applied unless I refresh the screen.
(Due to flatlist, I can't refresh because if so, scroll goes to top.)
So I add this cache.modify once again below.
I also match the data with seeCertainUserFeedpoem manually and update.
const updateUploadPhoto = (cache, result) => {
const {
data: { createFeed },
} = result;
const FeedpomeId = `Feedpoem:${createFeed.id}`;
const FeedpoemFragment = {
caption: createFeed.caption,
commentNumber: createFeed.commentNumber,
createdAt: createFeed.createdAt,
id: createFeed.id,
isLiked: createFeed.isLiked,
isMine: createFeed.isMine,
likeNumber: createFeed.likeNumber,
photos: createFeed.photos,
poemCaption: null,
poemCommentNumber: 0,
poemLikeNumber: 0,
poemTitle: null,
updatedAt: createFeed.updatedAt,
};
if (createFeed.id) {
cache.modify({
id: "ROOT_QUERY",
fields: {
seeAllFeeds(prev) {
return [createFeed, ...prev];
},
},
});
cache.modify({
id: FeedpomeId,
data: FeedpoemFragment,
});
navigation.navigate("Tabs", { screen: "일상" });
}
};
So I also try this way, not cache.modify but client.writeFragment.
const updateUploadPhoto = (cache, result) => {
const {
data: { createFeed },
} = result;
const FeedpomeId = `Feedpoem:${createFeed.id}`;
const FeedpoemFragment = {
caption: createFeed.caption,
commentNumber: createFeed.commentNumber,
createdAt: createFeed.createdAt,
id: createFeed.id,
isLiked: createFeed.isLiked,
isMine: createFeed.isMine,
likeNumber: createFeed.likeNumber,
photos: createFeed.photos,
poemCaption: null,
poemCommentNumber: 0,
poemLikeNumber: 0,
poemTitle: null,
updatedAt: createFeed.updatedAt,
};
if (createFeed.id) {
cache.modify({
id: "ROOT_QUERY",
fields: {
seeAllFeeds(prev) {
return [createFeed, ...prev];
},
},
});
client.writeFragment({
id: FeedpomeId,
data: FeedpoemFragment,
});
navigation.navigate("Tabs", { screen: "일상" });
}
};
But both dont' work.
And 2nd way throws me this error.
LogBox.js:173 Possible Unhandled Promise Rejection (id: 0): Error:
Cannot read properties of undefined (reading 'definitions') Error:
Cannot read properties of undefined (reading 'definitions')
what is the problem here?
I can edit / delete with cache.
Because I understand that first find the exact cache by id.
However creating is hard.
I want to share my cache as well.
But this is too long.
chat is also welcome, please help me.
I have a query:
createNotification: async (_, args, {req, res}) => {
const followedBy = await prisma.user.updateMany({
where: {
following: {
some: {
id: req.userId
},
},
},
data: {
notifications: {
create: {
message: args.message,
watched: false,
},
},
},
})
And User and Notification models:
model User {
id Int #id #default(autoincrement())
email String #unique
name String
user_name String #unique
password String
movies Movie[]
notifications Notification[]
followedBy User[] #relation("UserFollows", references: [id])
following User[] #relation("UserFollows", references: [id])
}
model Notification {
id Int #id #default(autoincrement())
link String?
movie_id Int?
message String
icon String?
thumbnail String?
user User #relation(fields: [userId], references: [id])
userId Int
watched Boolean
}
When I run my query I get an error:
Unknown arg `notifications` in data.notifications for type UserUpdateManyMutationInput. Did you mean `email`? Available args:
type UserUpdateManyMutationInput {
email?: String | StringFieldUpdateOperationsInput
name?: String | StringFieldUpdateOperationsInput
user_name?: String | StringFieldUpdateOperationsInput
password?: String | StringFieldUpdateOperationsInput
}
The strange thing is that this works:
const followedBy = await prisma.user.findUnique({
where: {id: req.userId},
include: {
followedBy: true,
},
});
followedBy.followedBy.map(async(user) => {
await prisma.user.update({
where: {id: user.id},
data: {
notifications: {
create: {
message: args.message,
watched: false,
},
},
},
});
});
But this isn't making the best of what Prisma offers.
As of September 2021, Prisma does not support mutating nested relations in a top-level updateMany query. This is what the typescript error is trying to tell you, that you can only access email, name, user_name and password fields inside data. There's an open feature request for this which you could follow if you're interested.
For the schema that you have provided, here's a possible workaround that's slightly less readable but more optimized than your current solution.
createNotification: async (_, args, {req, res}) => {
// get the followers array of req.userId
const followedBy = await prisma.user.findUnique({
where: { id: req.userId },
include: {
followedBy: true,
},
});
// array of notification objects to be created, one for each follower of req.userId
let messageDataArray = followedBy.followedBy.map((user) => {
return {
userId: user.id,
message: args.message,
watched: false,
};
});
// do a bulk createMany.
// Since it's one query, it should be more optimized than running an update for each user in a loop.
await prisma.notification.createMany({
data: messageDataArray,
});
};
If you're interested, here's the docs reference for the kinds of nested updates that are possible.
How do I update my database using Postman?
I'm trying to learn Express using Postman to test different types of requests, but I can't figure out how to update my data set. This is the structure of the data set I'm using.
var DB = [
{ category: 'Pets',
products: [
{ name: 'banjo',
color: 'grey',
mean: true,
description: "meows"
},
{ name: 'rigby',
color: 'black and white',
mean: false,
description: 'barks'
}]}]
Lets say I want to add another pet into the pets category so in products
{name: frank, color: orange, : mean: false: description: glubs}
I cant figure out how to add it correctly in Postman so that itll update. My code for the update is as follow:
app.post("/product/add", (req, res) => {
var category = req.body.category;
const { name, color, mean, description } = req.body;
var product = { name:name, color:color, mean:mean, description:description }; console.log(product);
var index = DB.findIndex(x => x.category == category);
if(index !== -1){
var indexProduct = DB[index].products.findIndex(x => x.name == product.name); if(indexProduct !== -1){
DB[index].products.push(product);
res.status(200).send(DB);
} else {
res.status(200).send(`Product already added to category.`);
};
} else {
res.status(200).send(`Category not found.`);
} });
Thanks in advance! Also sorry for the format.
There are a lot of repetitions, destructured variables that are not needed and syntactic errors in your code. Start by breaking down your problem into smaller chunks that are more manageable and then, test your endpoint with postman.
Let's start with your data and how it is structured:
var DB = [{
category: 'Pets',
products: [{
name: 'banjo',
color: 'grey',
mean: true,
description: "meows"
},
{
name: 'rigby',
color: 'black and white',
mean: false,
description: 'barks'
}
]
}]
// Lets say you want to add another pet into the pets category so in products
const obj = {
name: "frank",
color: "orange",
mean: false,
description: "glubs"
}
This is one of the things you could do to check if the object is not found and if not, you add it to your db.
DB.forEach((val) => {
if (val.products.name !== obj.name) {
DB[0].products.push(obj);
}
})
console.log(DB[0].products)
/**
*[{
name: 'banjo',
color: 'grey',
mean: true,
description: 'meows'
},
{
name: 'rigby',
color: 'black and white',
mean: false,
description: 'barks'
},
{
name: 'frank',
color: 'orange',
mean: false,
description: 'glubs'
}
]
*/
You postman request could look like this:
app.post("/product/add", (req, res) => {
// extract just what you need e.g name or ID if you have one...
const { name } = req.body;
// NOT efficient, best if you use a unique ID to look up
DB.forEach(value => {
if (value.products.name !== name) {
DB[0].products.push(req.body);
return res.status(200).send(JSON.stringify(DB));
}
else
return res.status(404).send("Not found or whatever");
});
});
OR using Array.prototype.findIndex you could do:
app.post("/product/add", (req, res) => {
const { name } = req.body;
const index = DB.forIndex(value => value === name);
if (index === -1) {
DB[0].products.push(req.body);
return res.status(200).send(JSON.stringify(DB));
}
else
return res.status(404).send("Not found or whatever");
}
});
Note: if your object name is the same than another one, your new object won't be pushed to the DB array. This would suggest you need to index your object with a unique identifier.
So I'm trying to make dynamic command handling for my bot, but it just doesn't work. Everything works without dynamic command handling.
So this is there error i get when i type in command !work:
UniqueConstraintError [SequelizeUniqueConstraintError]: Validation error
at Query.formatError (C:\Users\mmede\Desktop\Discord Bot\node_modules\sequelize\lib\dialects\sqlite\query.js:409:16)
at Query._handleQueryResponse (C:\Users\mmede\Desktop\Discord Bot\node_modules\sequelize\lib\dialects\sqlite\query.js:72:18)
at Statement.afterExecute (C:\Users\mmede\Desktop\Discord Bot\node_modules\sequelize\lib\dialects\sqlite\query.js:246:27)
at Statement.callbackTrampoline (internal/async_hooks.js:129:14) {
errors: [
ValidationErrorItem {
message: 'user_id must be unique',
type: 'unique violation',
path: 'user_id',
value: '485384232131100693',
origin: 'DB',
instance: [users],
validatorKey: 'not_unique',
validatorName: null,
validatorArgs: []
}
],
fields: [ 'user_id' ],
parent: [Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: users.user_id] {
errno: 19,
code: 'SQLITE_CONSTRAINT',
sql: 'INSERT INTO `users` (`user_id`,`balance`) VALUES ($1,$2);'
},
original: [Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: users.user_id] {
errno: 19,
code: 'SQLITE_CONSTRAINT',
sql: 'INSERT INTO `users` (`user_id`,`balance`) VALUES ($1,$2);'
},
sql: 'INSERT INTO `users` (`user_id`,`balance`) VALUES ($1,$2);'
}
and this is my work script:
const Discord = require('discord.js');
const { Users, CurrencyShop } = require('../dbObjects');
const currency = new Discord.Collection();
Reflect.defineProperty(currency, 'add', {
//eslint-disable-next-line func-name-matching
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
} else {
try {
const newUser = await Users.create({ user_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
} catch (err) {
// print the error details
console.log(err);
}
}
},
});
module.exports = {
name: 'work',
description: 'balancas',
execute(message, async) {
message.channel.send('You hacked someones computer and you gained 1million vbucks')
currency.add(message.author.id, 1000000);
}
}
If anyone would like to help me I would really appreciate it. I'm new to sql so that would be great if you explained where I made the mistake.
The problem is that you're trying to insert an entry (user) into the users table with a user_id that already exists.
Since the users table has a UNIQUE constraint, that column is a primary key for the table and there can be no duplicate user_ids i.e. no two users can have the same user_id.
If you want to edit a particular user, try the update command.