How to create only one table with SQLAlchemy?
Above, the declarative_base() callable returns a new base class from which all mapped classes should inherit. When the class definition is completed, a new Table and mapper() will have been generated.
The resulting table and mapper are accessible via
__table__
and__mapper__
attributes
(From here)
Therefore:
def build_daily_history_table(ticket):
classname = ticket + "_HistoricDay"
ticket = type(classname, (Base, HistoricDay), {'__tablename__' : ticket+"_daily_history"})
ticket.__repr__ = build_daily_history_table_repr
return ticket
build_daily_history_table("test").__table__.create(bind = engine)
Output:
2013-10-04 22:36:53,263 INFO sqlalchemy.engine.base.Engine
CREATE TABLE test_daily_history (
id INTEGER NOT NULL,
date DATE,
open FLOAT,
high FLOAT,
low FLOAT,
close FLOAT,
volume BIGINT,
"adjClose" FLOAT,
PRIMARY KEY (id)
)
2013-10-04 22:36:53,263 INFO sqlalchemy.engine.base.Engine ()
2013-10-04 22:36:53,263 INFO sqlalchemy.engine.base.Engine COMMIT
Credit goes to javex's comment/correction or I might have suggested something akin to:
Base.metadata.tables["ticket_daily_history"].create(bind = engine)
Advise:
The approach used in build_daily_history_table
could be one of the least elegant ways of doing things, primarily for the reason that it is polluting/cluttering the namespace.
To create specific tables, giving tables
parameter to create_all()
method is enough.
Base.metadata.create_all(engine, tables=table_objects)
table_objects equals to:
table_objects = [HistoricDay.__table__]
or
table_objects = [Base.metadata.tables["historicday"]]
I showed one table here. You can increase the number of the tables as you wish.
Reference: http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.create_all
Create all not exists tables with one line. It will check whether the table exists first by default.
Base.metadata.create_all(db_engine, Base.metadata.tables.values(),checkfirst=True)
Create one target table with table_name
.
Base.metadata.create_all(db_engine, Base.metadata.tables[table_name],checkfirst=True)
It works perfectly with declarative_base
.
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
TABLE_PREFIX = "decision_"
class Stock(Base):
__tablename__ = '{}stocks'.format(TABLE_PREFIX)
id = Column(Integer, primary_key=True)
name = Column(String)
class StagePerformance(Base):
__tablename__ = '{}stage_performance'.format(TABLE_PREFIX)
id = Column(Integer, primary_key=True)
date = Column(DateTime)
stock = relationship("Stock", back_populates="stage_performances")
period = Column(Integer )
open = Column(Float)
high = Column(Float)
low = Column(Float)
close = Column(Float)
change_ratio = Column(Float)
turnover = Column(Float)
volume = Column(Float)