mardi 12 mars 2019

Issue about huge query constructing huge object?

I am working on a company's legacy project. There's a huge object which is constructed by a super long query. The query somehow looks like this.

SELECT *
FROM item i 
JOIN item_product prod on prod.item = i.id
LEFT JOIN product_shippingaddress ps on pa.product = prod.id
LEFT JOIN product_packageinfo pp on pp.product = prod.id
.
.
.
(80 lines of query)
WHERE item.id = @itemId

Which is a very long query involves many information about this product.

It constructs a huge object 'Item' which provides all kind of information of the item. Taking the below example of how things works currently

int itemId = createItem(); //creates a record in item table
associateAddressToItem(item); // Add a shipping address to item
for(int productId in productsToAdd){
     addProduct(itemId); // insert info into item_product table
}
Item item = getItem(item); // This function invokes the huge query to collect information of a single item
for(Product product in item.products){
     UpdateItemPrice(product.Id,itemId);
     if (product.shippable()) 
     {
         addItemTax(itemId, product.Id); // add tax based on address and product attribute
     }
}
item = getItem(itemId); // calls the query to update information of the object
charge(item); //charge based on item's price and tax

This case invokes the function getItem twice. I don't think this is efficient at all, as long as it runs a huge query twice. However, I think it is needed currently because it needs to fetch information stored in database to update the object.

Is there a better way to handle this kind of situation? I feel it is not optimized but I can come up with a way to improve it.

Aucun commentaire:

Enregistrer un commentaire