Home > Net >  FASTAPI SQLAlchemy Creating a table during run time based on user input
FASTAPI SQLAlchemy Creating a table during run time based on user input

Time:10-21

The user will be providing some information such as table_x with column_x. And I'd like to create these tables in an existing database or a new database based on the user's value.

These values will be provided during run-time therefore I cannot create the Model beforehand.

If anyone could provide some help, let me know!

CodePudding user response:

I've managed to figure out what I intended to do. I used engine.dialect.has_table(engine, Variable_tableName) to check if the database has the table inside. IF it doesn't, then it will proceed to create a table in the database.

Sample code:

engine = create_engine("sqlite:///myexample.db") 
if not engine.dialect.has_table(engine, "Variable_tableName")
    metadata = MetaData(engine)

    # Create a table with the appropriate Columns
    Table("Variable_tableName", metadata,
          Column('Id', Integer, primary_key=True, nullable=False), 
          Column('Date', Date), Column('Country', String),
          Column('Brand', String), Column('Price', Float))
    
    # Implement the creation
    metadata.create_all()
  • Related