Advertisement
AlexVhr

SQLA data loss

Jan 7th, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import sessionmaker, relationship
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy import Column, Integer, Text, ForeignKey
  5.  
  6. sa_engine = create_engine("sqlite:///:memory:")
  7. Session = sessionmaker(bind=sa_engine)
  8. session = Session()
  9. Base = declarative_base()
  10.  
  11. class Parent(Base):
  12.     __tablename__ = 'parent'
  13.     id = Column(Integer, primary_key=True)
  14.     name = Column(Text)
  15.     children = relationship('Child', backref='parent')
  16.  
  17.     def __repr__(self):
  18.         return self.name
  19.  
  20. class Child(Base):
  21.     __tablename__ = 'child'
  22.     id = Column(Integer, primary_key=True)
  23.     name = Column(Text)
  24.     parent_id = Column(Integer, ForeignKey('parent.id'))
  25.  
  26.     def __repr__(self):
  27.         return self.name
  28.  
  29. Base.metadata.create_all(sa_engine)
  30.  
  31. p = Parent(name='Thomas')
  32. session.add(p)
  33.  
  34. c1 = Child(name="Mary")
  35. c2 = Child(name="John")
  36. c3 = Child(name="Kenny")
  37.  
  38. p.children.append(c1)
  39. p.children.append(c2)
  40. p.children.append(c3)
  41. session.commit()
  42.  
  43. p = session.query(Parent).get(1)
  44. print(p.children) #prints [Mary, John, Kenny]
  45.  
  46. temp1 = p.children[1]
  47. temp2 = p.children[2]
  48.  
  49. p.children[2] = temp1
  50. p.children[1] = temp2
  51.  
  52. print(p.children) #prints [Mary, Kenny, John]
  53.  
  54. session.commit()
  55. print(p.children) #prints [Mary, John]. Oh my God! They killed Kenny!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement