MariaDB / Sequelize SQL syntax error when syncing - mariadb

const User = sequelize.define('User', {
Points: {
type: DataTypes.NUMBER,
defaultValue: 0,
allowNull: false
},
UserId: {
type: DataTypes.STRING,
allowNull: true
}
},
{
sequelize,
modelName: 'User',
tableName: 'Points'
});
User.sync()
This code chucks out a MariaDB error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'NOT NULL DEFAULT 0, `UserId` VARCHAR(255) DEFAULT '', `createdAt` DATETIME NO...' at line 1
Could someone help please? I am quite new to this sort of thing so I wouldn't really know. Thanks!

Related

Next-auth JWT user missing values after logging in

I ran into some issues regarding the JWT user being null after a succesfull login.
Did some debugging in the callbacks and saw the following:
2 {
token: {
token: {
name: null,
email: null,
picture: null,
sub: 'e1d4c887-0257-4543-be37-c9b297e2cce6'
},
user: {
id: 'e1d4c887-0257-4543-be37-c9b297e2cce6',
emailVerified: '2022-09-06T09:54:24.163Z',
name: null,
email: null,
image: null
},
account: {
providerAccountId: 'test#test.com',
type: 'email',
provider: 'email'
},
isNewUser: false,
iat: 1662458064,
exp: 1665050064,
jti: '521054a5-7ead-43fc-94f4-f5eb7fffde43'
}
}
I read through the docs and noticed that the correct callback flow would be: signin -> JWT -> Session.
It is possible to return the user object found within the signIn callback, but this is not getting passed into the JWT callback.
Due to the fact that some properties like isNewUser are filled in correctly, could the missing user info be related to a DB issue?
What are some things I could further check in the hopes of solving this issue?

Dynamoose: The Model object doesn't allow config as a parameter

I have created a model that was working when I had my backend functions running on my local machine, but when it uses AWS I get and authentication problem when the table is being queried:
2022-02-18T08:54:58.149Z 31785a81-ea8c-434b-832f-6dcff583c01c ERROR Unhandled Promise Rejection
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "AccessDeniedException: User: arn:aws:sts::xxxxxxxxx:assumed-role/dev-production-history-role/ppc-backend-functions-dev-queryProductionHistoryItems is not authorized to perform: dynamodb:CreateTable on resource: arn:aws:dynamodb:eu-west-1:xxxxxxxxxxxx:table/dev-production-history-table",
"trace": [
"Runtime.UnhandledPromiseRejection: AccessDeniedException: User: arn:aws:sts::xxxxxxxxx:assumed-role/dev-production-history-role/ppc-backend-functions-dev-queryProductionHistoryItems is not authorized to perform: dynamodb:CreateTable on resource: arn:aws:dynamodb:eu-west-1:xxxxxxxxx:table/dev-production-history-table",
" at process.<anonymous> (/var/runtime/index.js:35:15)",
" at process.emit (events.js:400:28)",
" at processPromiseRejections (internal/process/promises.js:245:33)",
" at processTicksAndRejections (internal/process/task_queues.js:96:32)"
]
}
This is how my model is defined:
const model = dynamoose.model<ProductionHistory>(DatabaseTableNames.productionHistoryTable, {schema});
From looking at possible solutions, it seems that adding {“create”: false} to the parameters might solve the issue, but in version 3 of Dynamoose you cannot add three parameters, so this will not work:
const model = dynamoose.model<ProductionHistory>(DatabaseTableNames.productionHistoryTable,
schema, {“create”: false});
Does anyone know how to overcome this problem so that it works with Dynamoose version 3?
I have made the changes that Charlie Fish suggested and I am now getting the following error:
2022-02-18T16:39:39.211Z b00a36b8-c612-4886-b9fc-da7084527bf0 INFO AccessDeniedException: User: arn:aws:sts::874124979428:assumed-role/dev-production-history-role/ppc-backend-functions-dev-queryProductionHistoryItems is not authorized to perform: dynamodb:Query on resource: arn:aws:dynamodb:eu-west-1:874124979428:table/dev-production-history-table
at deserializeAws_json1_0QueryCommandError (/var/task/node_modules/dynamoose/node_modules/#aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:2984:41)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async /var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-serde/dist-cjs/deserializerMiddleware.js:7:24
at async /var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-signing/dist-cjs/middleware.js:11:20
at async StandardRetryStrategy.retry (/var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-retry/dist-cjs/StandardRetryStrategy.js:51:46)
at async /var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-logger/dist-cjs/loggerMiddleware.js:6:22
at async main (/var/task/node_modules/dynamoose/dist/aws/ddb/internal.js:6:20)
at async /var/task/node_modules/dynamoose/dist/ItemRetriever.js:105:32
at async Object.queryByDate (/var/task/functions/production-history/query.js:1:1723)
at async Runtime.l [as handler] (/var/task/functions/production-history/query.js:1:1974) {
__type: 'com.amazon.coral.service#AccessDeniedException',
'$fault': 'client',
'$metadata': {
httpStatusCode: 400,
requestId: 'DCB6SNOH9O2NTRAS9LL3OJGEU7VV4KQNSO5AEMVJF66Q9ASUAAJG',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
'$response': HttpResponse {
statusCode: 400,
headers: {
server: 'Server',
date: 'Fri, 18 Feb 2022 16:39:39 GMT',
'content-type': 'application/x-amz-json-1.0',
'content-length': '331',
connection: 'keep-alive',
'x-amzn-requestid': 'DCB6SNOH9O2NTRAS9LL3OJGEU7VV4KQNSO5AEMVJF66Q9ASUAAJG',
'x-amz-crc32': '2950006190'
},
body: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
socket: null,
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [ClientRequest],
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
}
}
}
This is my code now:
const model = dynamoose.model<ProductionHistory>(DatabaseTableNames.productionHistoryTable, schema);
const Table = new dynamoose.Table(DatabaseTableNames.productionHistoryTable, [model], {"create": false, "waitForActive": false});
Any ideas?
Disclaimer: this answer is based on Dynamoose v3.0.0 beta 1. Answers based on beta versions can become outdated quickly, so be sure to check for any updated details for your version of Dynamoose.
In Dynamoose v3, a new class was introduced called Table. This represents a single DynamoDB Table. In previous versions of Dynamoose, a Model represented a single DynamoDB Table, but based on the API also kinda represented a specific entity or model in your data structure (ex. Movie, Order, User, etc). This lead to complications and confusion when it comes to single table design structures especially.
In terms of code, what this means is the following.
// If you have the following code in v2:
const User = dynamoose.model("User", {"id": String});
// It will be converted to this in v3:
const User = dynamoose.model("User", {"id": String});
const DBTable = new dynamoose.Table("DBTable", [User]);
So basically you create a new Table instance based on your Model. In v3 if you try to use your Model without created a Table instance based on it, it will throw an error.
Once you do that, the 3rd parameter of your Table constructor, you can pass in settings. Once of which being create. So you can set that to false as that parameter.
Your code specifically would look something like:
const model = dynamoose.model<ProductionHistory(DatabaseTableNames.productionHistoryTable, schema);
const DBTable = new dynamoose.Table(DatabaseTableNames.productionHistoryTable, [model], {"create": false});

Meteor server validated method doesn't display validation error on client

I have this server side validated method imports/api/Shops/server/methods.js:
export const shopGeocodeAddress = new ValidatedMethod({
name: 'shops.geocodeAddress',
validate: new SimpleSchema({
streetName: { type: String },
houseNumber: { type: Number },
city: { type: String },
state: { type: String },
country: { type: String },
zip: { type: String, optional: true },
}).validator(),
run({ streetName, houseNumber, city, state, country, zip }) {
...
...
...
...
return location;
},
});
To test validation error message on the client, I'm sending houseNumber as string which will get the method to fail, as it expects houseNumber as Number. So far so good. I'm getting a validation error on the server console like this:
I20190418-10:55:28.605(-3)? Exception while invoking method 'shops.geocodeAddress' { ClientError: House number must be of type Number
...
...
I20190418-10:55:28.608(-3)? errorType: 'ClientError',
I20190418-10:55:28.608(-3)? name: 'ClientError',
I20190418-10:55:28.608(-3)? error: 'validation-error',
I20190418-10:55:28.609(-3)? details:
I20190418-10:55:28.609(-3)? [ { name: 'houseNumber',
I20190418-10:55:28.609(-3)? value: NaN,
I20190418-10:55:28.609(-3)? type: 'expectedType',
I20190418-10:55:28.609(-3)? dataType: 'Number',
I20190418-10:55:28.609(-3)? message: 'House number debe ser del tipo Number' } ] }
But on the client I get only an internal server error like this:
details: undefined
error: 500
errorType: "Meteor.Error"
isClientSafe: true
message: "Internal server error [500]"
reason: "Internal server error"
Thus I can't indicate the client which type of error is, or which field must be changed in order for the method to be run correctly.
Is there a way to catch validation error on server methods and send them to the client?
Thanks in advise!
You can surround the s
schema.validator with a try/catch and throw a custom Meteor.Error that contains better understandable information.
You can do the same with the code inside run.
If you want to do this for every validated method, you may create a simple generator function:
const createMethod = options => new ValidatedMethod({
name: options.name,
validate(...args) {
try {
new SimpleSchema(options.schema).validate(...args)
} catch (e) {
throw new Meteor.Error('validationError', e.reason)
}
},
run(...args) {
try {
return options.run.call(this, ...args)
} catch (e) {
throw new Meteor.Error('methodError', e.reason)
}
}
})
Note that you may use e.reason || e.message
2 things:
A) You can write
city: String,
state: String,
zip: { type: String, optional: true }
...
B) You say "server side validated method". Your method needs to be in the common space reachable by both Server and Client. In the method you enclose everything into Server. You call the method from the client (and reach it) but run it on the Server:
export const shopGeocodeAddress = new ValidatedMethod({
name: 'shops.geocodeAddress',
validate: new SimpleSchema({
streetName: String,
houseNumber: Number,
city: String,
state: String,
country: String,
zip: { type: String, optional: true },
}).validator(),
run({ streetName, houseNumber, city, state, country, zip }) {
if (Meteor.isServer) {
...
...
...
...
return location;
}
},
});
Finally I used this answer on Meteor Forums https://forums.meteor.com/t/server-validated-method-doesnt-display-validation-error-on-client/48635/2?u=razor7
Basically I needed to create a new file to be run in server startup to route validation errors to client
import SimpleSchema from 'simpl-schema';
SimpleSchema.defineValidationErrorTransform((error) => {
const ddpError = new Meteor.Error(error.message);
ddpError.error = 'validation-error';
ddpError.details = error.details;
ddpError.reason = error.message;
return ddpError;
});

Getting 'query in command must target a single shard'

I have a CosmosDB setup using the Mongo API. I have a collection with a hashed shard on one of the field of the document. When I run commands like db.collection.remove or db.collection.deleteMany I get the following error.
Command deleteMany failed: query in command must target a single shard key.: {"message":"Command deleteMany failed: query in command must target a single shard key."}
I'm not sure how can I mention a shard key as part of the query considering I want the query to run across all the shards.
You need to provide shard key when you want to run commands like db.collection.remove or db.collection.deleteMany.
For example :
My data source as below:
[
{
"id" : "2",
"name" : "b"
},
{
"id" : "1",
"name" : "a"
}
]
And my shared key is "/name". Use db.coll.deleteMany({"name":"a"}) to delete specific shard.
Hope it helps you.
It should be ShardKey which you have chosen when you created cosmosDb collection.
FilterDefinition<Product> filter = Builders<Product>.Filter.Eq("id", 2);
=== 2 is my shardKey
await this._dbContext.GetProducts.DeleteOneAsync(filter);
return RedirectToAction("Index");
Kindly refer an image below , how does it look like in CosmosDB
Shard Key(Partition Key) has to be provided during specification of schema model in the code. Once its provided, we can perform regular operation like save, update and delete as usual.
Example:
const mySchema = new Schema({
requestId: { type: String, required: true },
data: String,
documents: [{ docId: String, name: String, attachedBy: String }],
updatedBy: {
type: {
name: { type: String, required: true },
email: { type: String, required: true },
}, required: true
},
createdDate: { type: Date, required: true },
updatedDate: { type: Date },
}, { shardKey: { requestId: 1 } }
);
In the above code we specified requestId as Shard Key, now we can perform any mongo operations
Example:
let request:any = await myModel.findById(requestId);
request.data ="New Data";
await request.save();
Hope that helps.
This works with all Mongo operations

DynamoDb documentClient.update or delete StringSet throws ValidationException

I successfully update and delete an item from a StringSet in a dynamoDb table when called from my test app running on localhost.
I then upload the app to LightSail but now when I call the same function to update or delete an item it throws a ValidationException!:
{
"message": "Invalid UpdateExpression: Incorrect operand type for operator or
function; operator: DELETE, operand type: MAP",
"code": "ValidationException",
"time": "2018-01-03T13:20:14.919Z",
"requestId": "9HCQMH5RAUBRK1K7BNESNBUD5BVV4KQNSO5AEMVJF66Q9ASUAAJG",
"statusCode": 400,
"retryable": false,
"retryDelay": 10.381373865940402
}
Why? I have not made any changes to my code so why does this happen and how to solve it?
Here's the relevant code:
var documentClient = getDocumentClient();
var paramsSET = {
ExpressionAttributeNames:
{
"#StringSet": "Packages"
},
ExpressionAttributeValues:
{
":value": documentClient.createSet(['filler as SET cannot be empty',
app.packageName
])
},
Key:
{
"EmailAddress": app.emailAddress
},
ReturnValues: "ALL_NEW",
TableName: "Developers",
UpdateExpression: "ADD #StringSet :value"
// UpdateExpression: "DELETE #StringSet :value" ------ to delete value
};
// adds packagename to Packages SET in developers table - creates set if not exist
documentClient.update(paramsSET, function (err, data){}
I could not get it to work using the documentclient api.
finally used the old api and got it to work using dynamodb.updateItem see docs here
still have no idea why it works on localhost (accessing the same dynamodb tables) and not when live on LightSail!

Resources