Postgresql Sqlalchemy dynamic table partition creation issue

676 Views Asked by At

I'm using postgresql and python sqllachmey for creating the partitioned table. Below is the example code.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Text
Base = declarative_base()
class Students(Base):
    __tablename__ = "Students"

    id = Column(Text, primary_key=True)
    name = Column(Text)
    type = Column(Text)
    desc = Column(Text)
    creation_time = Column(DateTime, default=func.now(), nullable=False, primary_key=True)
    __table_args__ = {
        'postgresql_partition_by': 'RANGE (creation_time)'
    }
table_list = [Students.__table__]
Base.metadata.create_all(self.engine, tables=table_list)

The above code creates a paritioned table and i'm creating the partitions using pg_partman extension.

Now, my need is that I want to use the class 'Students' for creating the student table under different databases, and some databases don't need the partitioned table. How can I make the above code dynamic so that I can take out 'postgresql_partition_by' from table_args?

According to the documents, it looks like, I have to use dictionary for table column definition but I'm not quite sure about it.

1

There are 1 best solutions below

2
ljmc On

The keyword arguemnts of Table (or __table_args__) are dialect specific, so your postgresql_partition_by will only be used with postgresql dialects, not sqlite or others.

class sqlalchemy.schema.Table(*args, **kw)

[...]

**kw – Additional keyword arguments not mentioned above are dialect specific, and passed in the form <dialectname>_<argname>. See the documentation regarding an individual dialect at Dialects for detail on documented arguments.