Created
October 2, 2012 19:48
-
-
Save gsakkis/3822855 to your computer and use it in GitHub Desktop.
SQLAlchemy identity map order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from sqlalchemy import Column, ForeignKey, Integer, String, create_engine | |
from sqlalchemy.exc import IntegrityError | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.orm import sessionmaker | |
Base = declarative_base() | |
class Author(Base): | |
__tablename__ = 'author' | |
author_id = Column(Integer, primary_key=True) | |
name = Column(String(50)) | |
def __repr__(self): | |
return 'Author(%r)' % self.name | |
class Book(Base): | |
__tablename__ = 'book' | |
book_id = Column(Integer, primary_key=True) | |
title = Column(String(60)) | |
author_id = Column(Integer, ForeignKey(Author.author_id)) | |
def __repr__(self): | |
return 'Book(%r)' % self.title | |
def test_insert(object_lists, session): | |
for objects in object_lists: | |
session.add_all(objects) | |
try: | |
session.commit() | |
except IntegrityError as ex: | |
print "Error: %s" % ex | |
return False | |
return True | |
if __name__ == "__main__": | |
engine = create_engine('mysql://localhost/test') | |
session = sessionmaker(bind=engine)() | |
Base.metadata.create_all(engine) | |
authors = [Author(author_id=i, name='A%d' % i) | |
for i in xrange(1, 5)] | |
books = [Book(author_id=random.randrange(1, 5), title='B%d' % i) | |
for i in xrange(1, 10)] | |
# succeeds | |
#object_lists = [authors, books] | |
# may fail | |
#object_lists = [authors + books] | |
# may fail | |
object_lists = [authors + books]; random.shuffle(object_lists) | |
try: | |
assert test_insert(object_lists, session) | |
finally: | |
Base.metadata.drop_all(engine) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment