Flask-SQLAlchemy creating schema before creating tables


I am trying to configure a MySQL schema using Flask-SQLAlchemy. I have a schema called testdb and some tables. I will list one table, User.
This code, so far, creates all of the tables needed but only when testdb already exists. Is there a way to check and create testdb before I connect?

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/testdb'
db = SQLAlchemy(app)

class User(db.Model):
    userid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(16), unique=True, nullable=False)
    password = db.Column(db.String(16), unique=False, nullable=False)
    email = db.Column(db.String(80), unique=True, nullable=False)
    createdDate = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    lastUpdated = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)


Desired command:

Asked By: Help Me Nothing



I solved this thanks to @hygorxaraujo
See the code below:

import sqlachemy

engine = sqlalchemy.create_engine('mysql://root:password@localhost') # connect to server
engine.execute("CREATE SCHEMA IF NOT EXISTS `testdb`;") #create db
engine.execute("USE testdb;") # select new db

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mypassword@localhost/testdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #Turn off annoying message
db = SQLAlchemy(app)
Answered By: Help Me Nothing

Here is a way to do it automatically for all schemas defined on models:

class User(db.Model)
    __tablename__ = 'user'
    __table_args__ = { 'schema': 'user' }

    user_id = db.Column(db.BigInteger, primary_key=True)

def _create_all_schemas():
    # get all the tables defined in your models
    tables = db.Model.metadata.tables.values()

    # group the tables by schema
    schemas = {}
    for table in tables:
        schema_name = table.schema
        if schema_name not in schemas:
            schemas[schema_name] = []

    # create the schemas
    with db.engine.connect() as conn:
        for schema_name, tables in schemas.items():
            if not conn.dialect.has_schema(conn, schema_name):


# Sync
Answered By: Ron S.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.