Create and check schema on ORM

Issue #3982 duplicate
Dmitry Tyutryumov created an issue

Hi guys, i need you help.

How i can create a schema on ORM, for few tables,

  • MetaData doesn't work when schema doesn't exist.

  • event.listen(DeclBase.metadata, 'before_create', CreateSchema('schema')) i see an error if schema is exist, but i don't know how to check schema on ORM

Will be appreciate for help

Official response

  • Mike Bayer repo owner

    hello -

    you'd need to either run the appropriate SQL to detect if this schema exists (this is database dependent, see http://docs.sqlalchemy.org/en/latest/core/ddl.html#controlling-ddl-sequences for an example), or just emit the statement "CREATE SCHEMA IF NOT EXISTS <foobar>":

    from sqlalchemy import MetaData, Integer, Table, Column, event, create_engine
    from sqlalchemy.schema import CreateSchema
    from sqlalchemy import exc
    
    m = MetaData()
    
    t = Table(
        't', m, Column('x', Integer),
        schema="some_schema"
    )
    
    
    def should_create(ddl, target, connection, **kw):
        try:
            connection.execute(
                "SHOW CREATE SCHEMA %s" %
                ddl.element).scalar()
            return False
        except exc.DBAPIError:
            return True
    
    event.listen(
        m, "before_create",
        CreateSchema("some_schema").execute_if(
            callable_=should_create
        )
    )
    
    
    e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
    
    m.create_all(e)
    

Comments (3)

  1. Mike Bayer repo owner

    hello -

    you'd need to either run the appropriate SQL to detect if this schema exists (this is database dependent, see http://docs.sqlalchemy.org/en/latest/core/ddl.html#controlling-ddl-sequences for an example), or just emit the statement "CREATE SCHEMA IF NOT EXISTS <foobar>":

    from sqlalchemy import MetaData, Integer, Table, Column, event, create_engine
    from sqlalchemy.schema import CreateSchema
    from sqlalchemy import exc
    
    m = MetaData()
    
    t = Table(
        't', m, Column('x', Integer),
        schema="some_schema"
    )
    
    
    def should_create(ddl, target, connection, **kw):
        try:
            connection.execute(
                "SHOW CREATE SCHEMA %s" %
                ddl.element).scalar()
            return False
        except exc.DBAPIError:
            return True
    
    event.listen(
        m, "before_create",
        CreateSchema("some_schema").execute_if(
            callable_=should_create
        )
    )
    
    
    e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
    
    m.create_all(e)
    
  2. Log in to comment