2

I am trying to create and fill a table in SQLite through SQLAlchemy using declarative_base()

Here is table declaration:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()


class Persons(Base):
    __tablename__ = 'persons'

    entry_id = Column(Integer, primary_key=True)
    age = Column(Integer)
    gender = Column(String(6))

Then engine and session:

engine = create_engine(r'sqlite:///persons.db')
db_session = scoped_session(sessionmaker(bind=engine))
session = db_session()

Table creation:

Base.metadata.create_all(engine)

It all works fine, until I try to do bulk mappings insert:

session.bulk_insert_mappings(table, bulk_rows)

If i use table = Persons for this, it all works fine and insert works as indented. But if I use table = Base.metadata.tables['persons'], which returns table object from Base, then it throws an error:

AttributeError: 'Table' object has no attribute 'mapper'

Why is that happening and can I somehow use Base.metadata.tables['persons'] table object for bulk inserts?

AlexFrost
  • 21
  • 3
  • `bulk_insert_mappings()` expects a mapped class (a model), not a `Table`. In other words it's for the ORM, not Core. – Ilja Everilä Dec 21 '19 at 15:22
  • @Ilja Everilä Thank you, is there any way to get this mapped class from `Base`? – AlexFrost Dec 21 '19 at 19:11
  • 1
    You could get it like this: https://stackoverflow.com/questions/11668355/sqlalchemy-get-model-from-table-name-this-may-imply-appending-some-function-to, but on the other hand you can perform bulk inserts using the Core `Table` just as well: https://docs.sqlalchemy.org/en/13/core/tutorial.html#executing-multiple-statements, https://stackoverflow.com/questions/18708050/bulk-insert-list-values-with-sqlalchemy-core, https://stackoverflow.com/questions/45484171/sqlalchemy-bulk-insert-is-slower-than-building-raw-sql – Ilja Everilä Dec 22 '19 at 07:55

0 Answers0