How to use @st.cache_resource with sqlalchemy.orm.declarative_base?

I’m trying to use streamlit connected to a database, and some ORM classes via SQLAlchemy.

@st.cache_resource
def get_declared_base() -> tuple[Any, Engine]:
    engine = create_engine('sqlite:////content/local_memory.db', echo=True)
    Base = declarative_base()
    Base.metadata.create_all(engine)
    return Base, engine

class Simulation(get_declared_base()[0]):
    __tablename__ = 'tb_simulation'
    id = Column(String, primary_key=True)
    name = Column(String)
    comment = Column(String)
    years = relationship("Year", back_populates="simulation", order_by="Year.year", cascade="all, delete-orphan")

class Year(get_declared_base()[0]):  # type: ignore
    __tablename__ = 'tb_year'
    id = Column(String, primary_key=True)
    is_reference = Column(Integer, default=0)
    year = Column(Integer)
    inflation = Column(Float, default=0)
    simulation_id = Column(String, ForeignKey('tb_simulation.id'))
    simulation = relationship("Simulation", back_populates="years")
    inputs = relationship("Input", back_populates="year", cascade="all, delete-orphan")

This code works as expected, but if I do any changes to the code and rerun, I got the following error:

InvalidRequestError: Table 'tb_simulation' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

Any tips on what I’m doing wrong?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.