Skip to content

Instantly share code, notes, and snippets.

@abhianair
Last active September 20, 2021 09:47
Show Gist options
  • Save abhianair/2dc0e63371dfa2c122cf06fd7d06c615 to your computer and use it in GitHub Desktop.
Save abhianair/2dc0e63371dfa2c122cf06fd7d06c615 to your computer and use it in GitHub Desktop.
Fask Create new schema and create tables to that schema using SQLAlchemy
import sqlalchemy
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from app import db
# engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
# if not engine.dialect.has_schema(engine, schema_name):
# engine.execute(sqlalchemy.schema.CreateSchema(schema_name))
# insp = sqlalchemy.inspect(engine)
# if engine.dialect.has_schema(engine, schema_name):
# # for table in db.Model.metadata.tables:
# for mapper in db.Model.registry.mappers:
# if not insp.has_table(mapper.class_, schema=schema_name):
# mapper.class_.__table__.schema = schema_name
# mapper.class_.__table__.create(engine)
db.session.execute('CREATE SCHEMA IF NOT EXISTS "{}";'.format(subdomain))
db.session.commit()
db.session.execute('SET search_path TO "{}";'.format(subdomain))
db.session.commit()
db.create_all(bind=None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment