What I have found, after fighting for some weeks, is that the error comes because it has not been considered the case when one already has bought shares from a company. So, in the code must be considered that shares should be added and the transactions table must be updated instead of inserting a new raw.