Updating the sqflite database if an item to the cart has already been added and creating if it is a new one in flutter - flutter

dbHelper.insert(
Cart(
id:null,
productId:snapshot.data[index].name,
productImage:snapshot.data[index].image)
.then(...)
I have created a DBHelper and have succesfully added them to my cart list but now I want to create data for my cart if it's a new item and if the item already exists in my cart list then I want to update the fields in my database.
So how can I query (sqflite) so that I create rows for new items and update for the previous ones through the id(primary) or through(productId which is also unique).

Not tested, but i think you can do custom SQL request like this:
INSERT INTO cart (product_id, ...)
VALUES ('145', ...)
ON CONFLICT(product_id) DO UPDATE SET quantity = quantity + 1;
To execute a custom SQL request with sqflite:
await db.rawQuery('SELECT * from mytable WHERE id = ?', [objectId]);

Related

How to bulk update SQLite table entries in Flutter

My Flutter app makes use of an SQLite database with multiple tables and Firebase authentication. Some time after publishing the app, I added a User ID column to each table, so that I could ensure that results could be filtered by users and they would only see their own data, should another user log into the app on the same device.
When I created the new column in each table though, for the entries that already existed, I allowed the data in the new column to be null to prevent an error with the database. The problem with that is that users who made the initial calculations where the User ID is null will now 'lose' that data, as it won't show up when I implement filtering with User ID.
What I want to do is bulk-update the null values in that column of each SQLite database table, if a null value exists in that table. The null values should be replaced by the current logged in User ID. I'm not sure of the best way to do this but my idea is something like this, with a database update function after it has been initialised:
Future _update(Database db, int oldVersion, int newVersion) async {
if (oldVersion < newVersion) {
Future<int> updateDB(String value) async {
final db = await instance.database;
return db.update(
values,
value.toJson(),
where: '${ValueFields.id} = ?',
whereArgs: [value.id],
);
}
}
}
Thing is, this doesn't seem to actually work and of course doesn't bulk update all rows in that particular column. Can someone advise on how I can build the bulk update function, to take all null User ID values in a particular table and change them to the current logged in user?
Thank you!
What you are doing is never updating anything if id is null. That is even if null were passed as the id via the whereargs, it would never update any rows as null is considered unique/distinct so will never be the same as another null. Instead you can use IS NULL. If the id is not null then it would not update rows where the id is null.
You can update all in one go if you use, (in SQL)
UPDATE the_table SET the_column = the_value WHERE the_column IS NULL
which I believe would be along the lines of:-
return db.update(
values,
value.toJson(),
where: '${ValueFields.id} IS NULL', /*<<<<< CHANGED WHERE CLAUSE */
whereArgs: [], /*<<<<< CHANGED NO WHERE ARGS*/
);

how to show list of CustomerId in dropdown list

i want to create Customer diary on the base of customerID that present in customer table.
In customerID field i want dropdown list having list of CustomerId's that are present in database
How can i do that ? can someone help me please
var _objAllCustomerIds = null;
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
_objAllCustomerIds = context.MyCustomers.Select(customer => customer.Id).ToList();
}
//where AdventureWorksEntities is your DBcontent containing all your entities
//MyCustomers is the entities representation of your customer table
if this is in your .aspx file
then in your .aspx.cs file (assuming you're using code behind) you'd get the list of customer IDs and then bind that list to this dropdown.
Does this answer from another question help?
How to bind the selected value of a DropDownList

Entity framework getting IDs for multiple insert in foreach

When we insert multiple rows at the same time with Entity framework it's good to add these objects one by one and then commit in the end, instead of adding and comitting each time.
So in that case, how do I get IDs for those insertions?
Example:
foreach (var item in list)
{
Subscription subscription = new Subscription();
subscription.Amount = item.ItemTotal;
this.ClientRepositories.LiveData.AddToSubscriptions(subscription);
// LiveData is db context via webservice proxy
// how to get IDS of these insertions if you do not commit each time?
int id = subscription.Id;
someOtherOperation(id); //i need to insert ID for each row that was inserted
}
this.ClientRepositories.LiveData.SaveChanges();
If I use commit inside for each time it adds new object I can easily get the latest inserted ID, but its not good to commit each time for multiple rows I heard.
I'm assuming that you are using auto incremented id's. I think your going to have to keep a list of your subscription objects outside of your loop. During each loop iteration, add the current subscription to the list. After your execute 'SaveChanges();' The subscription id's will be automatically added.
Would look like this:
List<Subscription> subList = new List<Subscription>();
foreach (var item in list)
{
Subscription subscription = new Subscription();
subscription.Amount = item.ItemTotal;
this.ClientRepositories.LiveData.AddToSubscriptions(subscription);
subList.add(subscription);
}
this.ClientRepositories.LiveData.SaveChanges();
/* At this point, each Subscription in your 'subList' should have an id */

How to fetch a list inside a list using LINQ to Entities

I have a requirement where i need to display a list in jquery DATATABLE. one of the column in a row will have multiple items (list).
So, in Busines Logic while fetching the DB details i'm trying to fetch a list which has another list in a row.
listTest =
(from TestA in context.Business
join Status in context.BStatus
on TestA. BStatus_Id equals Status.ID
join Prior in context.Priority
on TestA.Prior_ID equals Prior.ID into PriorityDetails
from PrtryDT in PriorityDetails.DefaultIfEmpty()
select new PModel
{
Id = TestA.ID,
Name = TestA.NM,
PriorityEvaluatedOnTS = TestA.PRI_EVAL_ON_TS,
//RequestPriority = i need to write a linq here to fetch a list for RequestPriority
}).ToList();

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);