I’m trying to create a set of tables using SQL Alchemy 2.0
class Base(DeclarativeBase):
pass
class Attribute_Details(Base):
"""
"""
__tablename__ = "attribute_details"
id: Mapped[int] = mapped_column(primary_key=True)
description: Mapped[str] = mapped_column()
opened: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
closed: Mapped[datetime] = mapped_column()
report_attr: Mapped["Report_Attributes"] = relationship(back_populates="details")
def connect(self) -> bool:
"""
Establish connection to the database
"""
try:
self.engine = self.db.connect()
self.session_maker = sessionmaker(bind=self.engine)
self.meta = sqlalchemy.MetaData()
return True
except exc.SQLAlchemyError as e:
print(str(e))
return False
def create_tables(self):
"""
Create the corresponding tables for the Report template
"""
for table in self.tables:
if not self.engine.dialect.has_table(self.engine, table.__tablename__):
table_obj = [table.__table__]
Base.metadata.create_all(self.engine, tables=table_obj)
# CreateTable(table_obj).compile(dialect=postgresql.dialect())
self.logger.info("Created DB Table {}".format(table.__tablename__))
else:
self.logger.info("DB Table {} already exists".format(table.__tablename__))
tables: List[Base] = [Attribute_Details]
db = Database(config['db_con_test'])
db.connect():
db.create_tables()
Altough it reports “Created DB Table attribute_details”, the table is not created in the database. I tried the option with Base.metadata.create_all()
as well as CreateTable()
. I cannot spot the issue as the creation of tables with the new Declarative Mapping of SQL2.0 isn’t explained very well… at least for me.