sqlalchemy.exc.InvalidRequestError: Table 'anothernewtable' is already defined for this MetaData instance. Specify 'extend_existing=True'

Viewed 22

On one of my GET call, I call the following functions in this order:

get_custom_db()

get_computers_both()

Where:

async def get_custom_db(db_name: str, table_name: str):
    DATABASE_URL = "postgresql://username:password@localhost/"+db_name
    database = databases.Database(DATABASE_URL)
    metadata = sqlalchemy.MetaData()
    computers = sqlalchemy.Table(
        table_name,
        metadata,
        sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
        sqlalchemy.Column("computername", sqlalchemy.String),
        extend_existing=True
    )
    engine = sqlalchemy.create_engine(
        DATABASE_URL
    )    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
        

And:

async def get_computers_both(db: Session, table_name: str, q: str = "", skip: int = 0, limit: str = "100"):

    class Computer(Base):
        __tablename__ = table_name
        extend_existing = True
        id = Column(Integer, primary_key=True, index=True)
        computername = Column(String)

    limit = str(limit)
    return db.query(Computer).filter(
        or_(
            Computer.computername.contains(q),
        )
    ).limit(limit).all()

And eventhough I have defined extend_existing = True for both SqlAlchemy Table declaration and the Computer class, I still get this error:

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

[EDIT]

Sorry I forgot to mention that before doing this calls, I perform a POST request that call this function:

@app.post("/computers/", response_model=Computer)
async def create_computer(computer: ComputerIn):

    # CREATION dynamique de la base
    DATABASE_URL = "postgresql://username:password@localhost/"+computer.database_name
    database = databases.Database(DATABASE_URL)

    metadata = sqlalchemy.MetaData()
    computers = sqlalchemy.Table(
        computer.table_name,
        metadata,
        sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
        sqlalchemy.Column("computername", sqlalchemy.String),
        extend_existing=True
    )
    engine = sqlalchemy.create_engine(
        DATABASE_URL
    )
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    # Dependency
    def get_db():
        db = SessionLocal()
        try:
            yield db
        finally:
            db.close()
            

    metadata.create_all(engine)

    await database.connect()
    ...............
0 Answers
Related