SQLAlchemy bulk insert auto-incremment

632 views Asked by At

Edit 2 :

class MethodCall(Base):
    __tablename__ = 'methodCall'
    id = Column(Integer, primary_key=True)
    name = Column(String( 255 ), unique = True)
    actions = relationship("Action")

def test_bulk_insert():
    ses = DBSession()
    mc = MethodCall()
    a1 = Action()
    a2 = Action()
    a1.lfn = getFile(ses, 'toto')
    a2.lfn = getFile(ses, 'toto')
    mc.actions.append(a1)
    mc.actions.append(a2)

Edit : Now i have two tables with a relationship :

class Action(Base):
    __tablename__ = 'action'
    id = Column(Integer, primary_key=True)
    file_id = Column(Integer, ForeignKey('file.id'))
    lfn = relationship("File")
    methodCall_id = Column(Integer, ForeignKey('methodCall.id'))

class File(Base):
    __tablename__ = 'file'
    id = Column(Integer, primary_key=True)
    name = Column(String( 255 ), unique = True)

When I insert two actions like this :

a1 = Action()
a2 = Action()
a1.lfn = getFile(ses, 'toto')
a2.lfn = getFile(ses, 'toto')
ses.bulk_save_objects([a1,a2])

def getFile(session,n):
    instance = session.query( File ).filter_by( name = n ).first()
    if not instance:
        instance = File( name=n )
        session.add( instance )
        session.commit()
    return instance

The file_id in table action is not set, it is null. How can I do ?

I have a little problem with SQLALchemy when inserting row.

I have a table file :

class File(Base): __tablename__ = 'file' id = Column(Integer, primary_key=True,autoincrement=True)

when I insert two files like this :

f1 = File( id = 1 )
f2 = File( id =2 )
session.add(f1)
session.add(f2)
session.commit()

It's a bulk insert :

2015-06-16 11:27:57,057 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-06-16 11:27:57,058 INFO sqlalchemy.engine.base.Engine INSERT INTO file (id) VALUES (%s)
2015-06-16 11:27:57,058 INFO sqlalchemy.engine.base.Engine ((1,), (2,))
2015-06-16 11:27:57,060 INFO sqlalchemy.engine.base.Engine COMMIT

but when I don't precise id, the insertion is one by one:

f1 = File(  )
f2 = File( )
session.add(f1)
session.add(f2)
session.commit()

2015-06-16 11:28:46,648 INFO sqlalchemy.engine.base.Engine INSERT INTO file () VALUES ()
2015-06-16 11:28:46,649 INFO sqlalchemy.engine.base.Engine ()
2015-06-16 11:28:46,654 INFO sqlalchemy.engine.base.Engine INSERT INTO file () VALUES ()
2015-06-16 11:28:46,654 INFO sqlalchemy.engine.base.Engine ()
2015-06-16 11:28:46,655 INFO sqlalchemy.engine.base.Engine COMMIT

Is there any way when I don't precise id to insert in bulk with auto-increment?

Thank you

0

There are 0 answers