You can define ClickHouse tables using either the SQLAlchemy Declarative style (via get_declarative_base) or the Constructor style (using Table).
- Declarative style: Uses a class inheriting from a base. By default, table names follow a lowercase underscore convention, but you can override this using the
__tablename__ attribute. - Constructor style: Uses the
Table object directly with MetaData.
from sqlalchemy import create_engine, Column, MetaData, literal
from clickhouse_sqlalchemy import (
Table, make_session, get_declarative_base, types, engines
)
uri = 'clickhouse://default:@localhost/test'
engine = create_engine(uri)
session = make_session(engine)
metadata = MetaData(bind=engine)
# Declarative style
Base = get_declarative_base(metadata=metadata)
class Rate(Base):
day = Column(types.Date, primary_key=True)
value = Column(types.Int32, comment='Rate value')
other_value = Column(types.DateTime)
__table_args__ = (
engines.Memory(),
{'comment': 'Store rates'}
)
# Constructor style
another_table = Table('another_rate', metadata,
Column('day', types.Date, primary_key=True),
Column('value', types.Int32, server_default=literal(1)),
engines.Memory()
)