Retrieving and using last inserted row ID in sqlite - c++

I am aware how to retrieve the last inserted row id in sqlite (by LAST_INSERT_ROWID()).
Assume there is a business logic class Customer with a string name and an int id field.
Consider this piece of pseudo code/MWE:
Customer newCust = Customer();
newCust.setName("Mr. Happy");
createNewCustomer(newCust);
print(newCust.id); // would print "3"
void createNewCustomer(Customer& cust) {
insertNewCustomer(cust.name); // [pseudo code] inserts a new row in DB; id automatically assigned
int id = sqlite3::LAST_INSERT_ROWID(); // [pseudo code] retrieve last inserted row id
cust.id = id;
return;
}
The Customer object is passed by reference, so that its id field can be updated after the query and used in the rest of the program.
Should I wrap the two steps (inserting and retrieving the last id) in a transaction in order to guarantee the last retrieved id is really the one from the query before (think about a scenario with multiple connections accessing in WAL mode for instance).
Is this even a sophisticated approach?

Related

Using C++ and MariaDB to operate on database records

I am trying to use the data records present in my database (MariaDB) by connecting with C++ and using mysql_query to executeSQL query in C++, my goal is to use the data present in the database to my C++ code and perform operations and again push the operated data which is stored in the variable back to the database.
I am facing the problem of
Segmentation error
Query out of sync
I think this is happening because I am using a loop to take the data from the database and then update the records back to the database, and while updating the records I can update static data but I am not able to update the variable data which stores the operating values.
con = mysql_connection_setup(mysqlD); // connection using database id
resultRecord = mysql_execute_query(con, "SELECT Date FROM tableData LIMIT 1000;");
//take data from database into C++ code
cout << "Displaying 10 Database Records: \n"
for (int i = 0; i < 10; i++) // operation on first 10 values
{
databaseTable = mysql_fetch_row(resultRecord); // Fetch the particular data from database
char *DatePtr[i] = {databaseTable[0]}; // Date Column
string dateString = *DatePtr; // function uses string
cout << "Operated Date: ";
DateOperator(dateString); // Function for date operation which returns the operated date.
updateRecord = mysql_execute_query(con, "UPDATE tableData SET DataAge = (#variable value) WHERE Id < 0 ");
}
mysql_free_result(resultRecord); //Free Up the Query
mysql_close(con);
This is my first question on Stack Overflow so please let me know if any update is required in the question. Please help me out of this problem.
Thank you for your time and response.

How to query a Dynamo DB table using only not null values

I am using AWS Dynamo DB and am facing an issue.
I have a table which has multiple columns (e.g. firstname, lastname and others). The primary key is an integer.
My requirement is that user can send in one or more search condition and I have fetch data based on this.
e.g. say a Table t1 which has columns Id, firstname, lastname
I am unable to search when user sends in only one search condition.
Below is code:
Table table = dynamoDB.getTable("t1");
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":firstname", "aa");
expressionAttributeValues.put(":lastname", "bb");
ItemCollection<ScanOutcome> items = table.scan
("(firstname = :firstname) AND " +
"(lastname = :lastname)", // FilterExpression
null, // ProjectionExpression
null, // No ExpressionAttributeNames
expressionAttributeValues);
When I send both firstname and lastname as input then the above code works fine.
However if I send in only firstname then the code fails as the lastname input is not being sent.
One crude way to solve this if I make the FilterExpression programatically. I want to know if dynamodb query has inbuilt support for such scenario.
I searched a lot but could not find anything useful.

What does DynamoDB scan return if item with Exclusive Start Key does not exist in the table?

I'm trying to implement pagination for my API. I have a DynamoDB table with a simple primary key.
Since the ExclusiveStartKey in a DynamoDB scan() operation is nothing but the primary key of the last item fetched in the scan operation before, I was wondering what would DynamoDB return if I perform a scan() with an ExclusiveStartKey that does not exist in the table?
# Here response contains the same list of items for the same
# primary key passed to the scan operation
response = table.scan(ExclusiveStartKey=NonExistentPrimaryKey)
I expected DynamoDB to return no items (correct me if this assumption of mine is what's wrong), i.e the scanning should resume from the ExclusiveStartKey, if it exists in the table. If not, it should return no items.
But what I do see happening is, the scan() still returns items. When I give the same non-existent primary key, it keeps returning me a list starting from the same item.
Does DynamoDB simply apply the hash function on the ExclusiveStartKey and from the result of this hash decide from which partition it has to start returning items or something?
# My theory as to what DynamoDB does in a paginated scan operation
partitionId = dynamodbHashFunction(NonExistentPrimaryKey)
return fetchItemsFromPartition(partitionId)
My end goal is that when an invalid ExclusiveStartKey is provided by the user (i.e a non-existent primary key), I want to return nothing or even better, return a message that the ExclusiveStartKey is invalid.
Looks like you want to return items based on a value. If that value does not exist, then you want to have an empty result set. This is possible with the
Java V2 DynamoDbTable object's scan method:
https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/DynamoDbTable.html
For this solution, one way is to scan an AmazonDB table and return a result set based on the value of specific column (including the key). You can use an Expression object. This lets you set the value that you want to return in a result set.
For example, here is Java logic that returns all items where a date column is 2013-11-15. If there are no items that meet this condition, then no items are returned. There is no need for a pre-check, etc. You need to setup the ScanEnhancedRequest properly.
public static void scanIndex(DynamoDbClient ddb, String tableName, String indexName) {
System.out.println("\n***********************************************************\n");
System.out.print("Select items for "+tableName +" where createDate is 2013-11-15!");
try {
// Create a DynamoDbEnhancedClient and use the DynamoDbClient object.
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
// Create a DynamoDbTable object based on Issues.
DynamoDbTable<Issues> table = enhancedClient.table("Issues", TableSchema.fromBean(Issues.class));
// Setup the scan based on the index.
if (indexName == "CreateDateIndex") {
System.out.println("Issues filed on 2013-11-15");
AttributeValue attVal = AttributeValue.builder()
.s("2013-11-15")
.build();
// Get only items in the Issues table for 2013-11-15.
Map<String, AttributeValue> myMap = new HashMap<>();
myMap.put(":val1", attVal);
Map<String, String> myExMap = new HashMap<>();
myExMap.put("#createDate", "createDate");
Expression expression = Expression.builder()
.expressionValues(myMap)
.expressionNames(myExMap)
.expression("#createDate = :val1")
.build();
ScanEnhancedRequest enhancedRequest = ScanEnhancedRequest.builder()
.filterExpression(expression)
.limit(15)
.build();
// Get items in the Issues table.
Iterator<Issues> results = table.scan(enhancedRequest).items().iterator();
while (results.hasNext()) {
Issues issue = results.next();
System.out.println("The record description is " + issue.getDescription());
System.out.println("The record title is " + issue.getTitle());
}
}
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}

How to perform getitem or query to retrieve last updated record in DynamoDB without using primary key

I've recently started learning DynamoDB and created a table 'Communication' with the following attributes (along with the DynamoDB type):
Primary Key Communication ID (randomly generated seq # or UUID): String
Sort Key User ID: String
Attributes/Columns:
Communication_Mode: String
Communication_Channel: String
Communication_Preference: String (possible values Y/N)
DateTime: Number
Use case: User can choose not to be communicated (Communication_Preference: N) and after a month user may opt for it (Communication_Preference: Y); meaning for the same User ID there can be more than 1 record as PartitionKey is randomly generated number
If I have to query above table and retrieve last inserted record for a specific userid do I need to create Global Secondary Index on DateTime.
Can someone correct me if my understanding is wrong or propose me the best option to meet above requirement. Thanks!

How to fetch last inserted record for particular id?

Apologies, I am completely new to Django. My question is that I have 20 records in my database table and suppose 10 record is of same ID and I want to fetch last inserted record for that id I have date column in my table. How can I do that?
last_obj = YourModel.objects.last()
But generally, you can't create > 1 objects with same id, if you didn't specified your own id field to replace built-in. And even then, it's a bad idea.