Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting SQLAlchemy to issue CREATE SCHEMA on create_all

I have a SqlAlchemy model with a schema argument like so:

Base = declarative_base()  class Road(Base):   __tablename__ = "roads"   __table_args__ = {'schema': 'my_schema'}   id = Column(Integer, primary_key=True) 

When I use Base.metadata.create_all(engine) it correctly issues a CREATE TABLE with the schema name on the front like so CREATE TABLE my_schema.roads ( but Postgresql rightly complains that the schema doesn't exist.

Am I missing a step to get SqlAlchemy to issue the CREATE SCHEMA my_schema or do I have to call this manually?

like image 355
Rory Hart Avatar asked Dec 03 '12 05:12

Rory Hart


People also ask

How do I create a schema in SQLAlchemy?

You can also import the method as such: from sqlalchemy. schema import CreateSchema . And use it directly with engine. execute(CreateSchema(schema_name)) .

What does DB Create_all () do?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student. db.


1 Answers

I have done it manually on my db init script like so:

from sqlalchemy.schema import CreateSchema engine.execute(CreateSchema('my_schema')) 

But this seems less magical than I was expecting.

like image 59
Rory Hart Avatar answered Oct 03 '22 16:10

Rory Hart