简体   繁体   中英

Generate schema SQL with SQLAlchemy

How does one generate the SQL/Migrate Code/Whatever with SQLAlchemy when using the Declarative Base?

from sqlalchemy import *
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mysql://root:password@localhost/mydb_dev', echo=True)
metadata = MetaData(bind=engine)


class User(Base):
    __table__ = Table("users", metadata, autoload=True)

    id = Column(Integer, primary_key=True)
    display_name = Column(String)
    email = Column(String)
    password = Column(String)

    def __repr__(self):
        return "<User(id='{}', display_name='{}', email='{}')>".format(self.id, self.display_name, self.email)


class Site(Base):
    __table__ = Table("sites", metadata, autoload=True)

    id = Column(Integer, primary_key=True)
    name = Column(String)
    urls = relationship("URL")

    def __repr__(self):
        return "<Site(id='{}', name='{}')>".format(self.id, self.name)

I have this so far, I'd like to see what SQLAlchemy would generate as a schema.

Or, does SQLAlchemy do this at all? Is this a case where I create and manage the database and it's schema separately, and I just update my entities to reflect it?

Do understand that I am used to Doctrine2, and im very new to SQLAlchemy

Thanks!

You can create the db models by calling:

metadata.create_all()

http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.MetaData.create_all

Note that this only works for the creation of previously non-existent models, and doesn't handle updates or downgrades. Check out alembic for even finer control:

http://alembic.zzzcomputing.com/en/latest/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM