What is returned from a "await db.Database.ExecuteSqlCommandAsync(sql, parameters)" - asp.net

I am trying to use this method to call a stored procedure.
var abc = await db.Database.ExecuteSqlCommandAsync(sql, parameters)
I see plenty of information on how to return data using parameters and that works okay. But I cannot find anything that tells me what is returned from the call?
Can someone tell me what will be put into abc and how can it be used?

As per
MSDN Database.ExecuteSqlCommandAsync Method (String, Object[])
it returns Task<int>. Here it is shown:
public Task<int> ExecuteSqlCommandAsync(
string sql,
params Object[] parameters
)
Return Value
Type: System.Threading.Tasks.Task<Int32>
A task that represents the asynchronous operation. The task result contains the result returned by the database after executing the command.
Now it depends on what you have in your sql query (sql param in your case). But for example, if you have a simple DELETE query like:
DELETE student WHERE papertype = 'science'
it will return the number of rows affected by the command. It's not a production level query so please ignore it's quality but you get the idea!

Related

AWS Java SDK DynamoDB, how to get attribute values from ExecuteStatementRequest response?

I'm using Java AWS SDK to query a DynamoDB table using ExecuteStatementRequest, but I'm don't know how to fetch the returned attribute values from the response.
Given I have the following query:
var response2 = client.executeStatement(ExecuteStatementRequest.builder()
.statement("""
UPDATE "my-table"
SET thresholdValue= thresholdValue + 12.5
WHERE assignmentId='item1#123#item2#456#item3#789'
RETURNING ALL NEW *
""")
.build());
System.out.println(response2.toString());
System.out.println(response2.getValueForField("Items", Collections.class)); // Doesn't cast to
This query executes fine and returns as part of the response attributes, however I can't find a way to get these values out of the response object using Java.
How can I do that?
I have found how to do that, however I'm not sure it this is the indicated way as the documentation doesn't provide any examples.
List items = response2.getValueForField("Items", List.class).get();
for (Object item : items) {
var values = (Map<String, AttributeValue>) item;
System.out.println(values.get("assignmentId").s());
System.out.println(values.get("thresholdValue").n());
}

If one of the multiple adds in a saveChangesAsync fails do the others get added?

I have this function in my application. If the insert of Phrase fails then can someone tell me if the Audit entry still gets added? If that's the case then is there a way that I can package these into a single transaction that could be rolled back.
Also if it fails can I catch this and then still have the procedure exit with an exception?
[Route("Post")]
[ValidateModel]
public async Task<IHttpActionResult> Post([FromBody]Phrase phrase)
{
phrase.StatusId = (int)EStatus.Saved;
UpdateHepburn(phrase);
db.Phrases.Add(phrase);
var audit = new Audit()
{
Entity = (int)EEntity.Phrase,
Action = (int)EAudit.Insert,
Note = phrase.English,
UserId = userId,
Date = DateTime.UtcNow,
Id = phrase.PhraseId
};
db.Audits.Add(audit);
await db.SaveChangesAsync();
return Ok(phrase);
}
I have this function in my application. If the insert of Phrase fails
then can someone tell me if the Audit entry still gets added?
You have written your code in a correct way by calling await db.SaveChangesAsync(); only one time after doing all your modifications on the DbContext.
The answer to your question is: No, the Audit will not be added if Phrase fails.
Because you are calling await db.SaveChangesAsync(); after doing all your things with your entities, Entity Framework wil generate all the required SQL Queries and put them in a single SQL transaction which makes the whole queries as an atomic operation to your database. If one of the generated query e.g. Auditgenerated query failed then the transaction will be rolled back. So every modification that have been done to your database will be removed and so Entity Framework will let your database in a coherent state.

Retrieve huge amount of data in Web API

I have a web api which allows the user to retrieve data real time and by batch. The problem however is that I have a data which has over 30 million of records which causes a bottleneck in a by batch request. I use paging in my get method which returns a default of 10 records per api request but still the 10 records take time in retrieving because of the bulk pull of data.
Here is the sample of my get method :
public async Task<IHttpActionResult> Get(int pageno = 1, int pagesize = 10)
{
int skip = (pageno - 1) * pagesize;
int total = db.webapi_customer_charges.Count();
var cc = await db.webapi_customer_charges
.OrderBy(c => c.hospital_number)
.Skip(skip)
.Take(pagesize)
.ToListAsync();
return Ok(new Paging<webapi_customer_charges>(cc, pageno, pagesize, total));
}
Is there a way or workaround or like best practice when it comes to retrieval of huge amount of data ? Thank you.
Not sure how you can do it with EF, since I assume it retrieves the whole set before you can skip or take, but I think it would be faster if you called a stored proc on Sql Server side and just pass in the min and max row numbers. That way you would only get the amount of data you need from the server on each call.
Here is a link to how you can call a stored proc with EF. If you don't find a better solution give it try it should be quite simple to make a select and use the ROW_NUMBER() in Sql to filter based on your input params.

How to get the table name in AWS dynamodb trigger function?

I am new with AWS and working on creating a lambda function on Python. The function will get the dynamodb table stream and write to a file in s3. Here the name of the file should be the name of the table.
Can someone please tell me how to get the table name if the trigger that is invoking the lambda function?
Thanks for help.
Since you mentioned you are new to AWS, I am going to answer descriptively.
I am assuming that you have set 'Stream enabled' setting for your DynamoDB table to 'Yes', and have set up this as an event source to your lambda function.
This is how I got the table name from the stream that invoked my lambda function -
def lambda_handler(event, context):
print(json.dumps(event, indent=2)) # Shows what's in the event object
for record in event['Records']:
ddbARN = record['eventSourceARN']
ddbTable = ddbARN.split(':')[5].split('/')[1]
print("DynamoDB table name: " + ddbTable)
return 'Successfully processed records.'
Basically, the event object that contains all the information about a particular DynamoDB stream that was responsible for that particular lambda function invoke, contains a parameter eventSourceARN. This eventSourceARN is the ARN (Amazon Resource Number) that uniquely identifies your DynamoDB table from which the event occurred.
This is a sample value for eventSourceARN -
arn:aws:dynamodb:us-east-1:111111111111:table/test/stream/2020-10-10T08:18:22.385
Notice the bold text above - test; this is the table name you are looking for.
In the line ddbTable = ddbARN.split(':')[5].split('/')[1] above, I have tried to split the entire ARN by ':' first, and then by '/' in order to get the value test. Once you have this value, you can call S3 APIs to write to a file in S3 with the same name.
Hope this helps.
Please note that eventSourceArn is not always provided. From my testing today, I didn't see eventSourceArn presented in record. You can also refer to the links:
Issue: https://github.com/aws/aws-sdk-js/issues/2226
API: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html
One way to do it will be via pattern matching in Scala using regex:
val ddbArnRegex: Regex = """arn:aws:dynamodb:(.+):(.+):table/(.+)/stream/(.+)""".r
def parseTableName(ddbARN: String): Option[String] = {
if (null == ddbARN) None
ddbARN match {
case ddbArnRegex(_, _, table, _) => Some(table)
case _ => None
}
}

node.js - determine when per-row asynchronous function is not called due to there being no rows

I'm trying to write code that will be executed if an SQLite query won't return results. However, the async nature of Node.js makes this difficult. I don't know if I can write code inside the callback function, because when I test with inputs that will cause empty results, nothing happens.
I'm doing
db.each("SELECT pid, collection , photo FROM photos WHERE collection = '"+collection_id+"' AND pid = '"+photo_id+"' ", function(err, row) {
console.log("PHOTO FOUND");
//code inside the callback function
});
//code I want
Specifically, I want to render something general, in case the user requests something that is not in the db
What should I do?
This is from the API documentation for the package you appear to be using (emphasis mine):
Database#each(sql, [param, ...], [callback], [complete])
Runs the SQL query with the specified parameters and calls the callback with for each result row. The function returns the Database object to allow for function chaining. The parameters are the same as the Database#run function, with the following differences:
The signature of the callback is function(err, row) {}. If the result set succeeds but is empty, the callback is never called. In all other cases, the callback is called once for every retrieved row. The order of calls correspond exactly to the order of rows in the result set.
After all row callbacks were called, the completion callback will be called if present. The first argument is an error object, and the second argument is the number of retrieved rows. If you specify only one function, it will be treated as row callback, if you specify two, the first (== second to last) function will be the row callback, the last function will be the completion callback.
If you know that a query only returns a very limited number of rows, it might be more convenient to use Database#all to retrieve all rows at once.
So, it would seem your code should look like this:
var sql = "SELECT pid, collection , photo FROM photos WHERE collection = '"+collection_id+"' AND pid = '"+photo_id+"' ";
db.each(sql, function(err, row) {
console.log("PHOTO FOUND");
//code inside the callback function
}, function(err, rows) {
if (rows == 0) {
//code I want
}
});

Resources