2

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!

RedactedProfile
  • 2,748
  • 6
  • 32
  • 51

1 Answers1

2

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/

dizzyf
  • 3,263
  • 19
  • 29