Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidRequestError: Object '' is already attached to session

I'm getting:

sqlalchemy.exc.InvalidRequestError: Object '<DBEdge at 0x103c4a190>' is already attached to session '1' (this is '2')

in this line

session.add(edge)

When I'm trying to run this:

  def findOrCreateEdge(self,user1,user2): #user1 is followed by user2
    if user1.id>user2.id:
      user1, user2 = user2, user1
      kind = 2
    else:
      kind = 1
    edge = self.findEdge(user1,user2)
    if edge:
      if edge.kind==1 and kind==2:
        edge.kind = 3
      if edge.kind==2 and kind==1:
        edge.kind = 3
      return edge
    else:
      edge = DBEdge(user1,user2)
      edge.kind = kind
      user1.edge_count = user1.edge_count + 1
      user2.edge_count = user2.edge_count + 1
      #session.save(edge) # we don't flush edges here, because it gives us a huge speedup to do a bunch at once then flush.
      try:
        session.add(edge)
        session.commit()
      except:
        session = Session()
        session.add(edge)
        session.commit()
      return edge
like image 232
Filipe Ferminiano Avatar asked Mar 01 '14 05:03

Filipe Ferminiano


1 Answers

The problem lies with adding the edge twice, once to the first session and then, on an exception, to the second session. I don't know what exactly you are trying to achieve here, but instead of brutally stuffing the edge into a new session, it would be better if you investigated the error and fixed the problem. Alternatively, you may want to roll the previous session back and restart it, then adding the edge to it.

Creating a new session when you already have one is almost always a mistake (except when the context itself changed, but that doesn't seem to be the case here).

like image 192
javex Avatar answered Oct 11 '22 17:10

javex