0

I am creating a my sqlite Database tables following this link https://sqlmodel.tiangolo.com/tutorial/connect/create-connected-tables/ .

Now this creates two tables Team and Hero on start up of my FastAPI application. But on a special use-case I may need to create another new table.

I can certainly do that by following

def create_specific_table():
    conn = engine.connect()
    conn.execute(
        """ CREATE TABLE IF NOT EXISTS table2 ( 
            key TEXT PRIMARY KEY,  
            execution_id TEXT,
            )"""
          )

But I want to do it using the Model class . # models/table2.py

from sqlmodel import Column, SQLModel
class Table2(SQLModel, table=True):
    key: str = Field(default=None, foreign_key="table1.id")
    execution_id: str = Field(title="My Execution ID", index=False, default=None)

And then

def create_specific_table():
    import db.engine # Using the same engine
    SQLModel.metadata.create_all(engine) 

But its not creating Table2 .

I tried also passing the table to create_all table lists

def create_specific_table():
    import db.engine # Using the same engine
    SQLModel.metadata.create_all(engine, tables=[Table1, Table2])

But getting below error

Traceback (most recent call last):
  File "pydantic/validators.py", line 709, in pydantic.validators.find_validators
TypeError: issubclass() arg 1 must be a class



sqlmodel/main.py", line 277, in __new__
    new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
  File "pydantic/main.py", line 205, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 491, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 421, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 542, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 804, in pydantic.fields.ModelField.populate_validators
  File "pydantic/validators.py", line 718, in find_validators
RuntimeError: error checking inheritance of FieldInfo(extra={}) (type: FieldInfo)

The way I am triggering the db model creation in main.py is basically

@app.on_event("startup")
def on_startup():
    create_db_and_tables() # these are common
    create_specific_table() 
Dibshare
  • 95
  • 2
  • 13
  • `create_all` should work. If you enable logging, what output do you get? – snakecharmerb Sep 07 '22 at 07:54
  • I have updated my question. `on_startup` , `create_db_and_tables` is working fine but `create_specific_table` not even picking `SQLModel.metadata.create_all(engine)` for table2 – Dibshare Sep 07 '22 at 08:13
  • Not sure I feel , I have to register new table in `SQLModel.metadata.create_all(engine)` in `create_specific_table` – Dibshare Sep 07 '22 at 08:16

1 Answers1

0

Try:

    Table2.__table__.create(engine)

ref: How to use SQLModel with more than 1 database?

T Semple
  • 99
  • 1
  • 4