Sqlalchemy if table does not exist

后端 未结 4 650
南方客
南方客 2021-01-31 14:28

I wrote a module which is to create an empty database file

def create_database():
    engine = create_engine(\"sqlite:///myexample.db\", echo=True)
    metadata          


        
4条回答
  •  天涯浪人
    2021-01-31 15:18

    engine.dialect.has_table does not work for me on cx_oracle. I am getting AttributeError: 'OracleDialect_cx_oracle' object has no attribute 'default_schema_name'

    I wrote a workaround function:

    from sqlalchemy.engine.base import Engine  
    def orcl_tab_or_view_exists(in_engine: Engine, in_object: str,  in_object_name: str,)-> bool:
        """Checks if Oracle table exists in current in_engine connection
    
        in_object: 'table' | 'view'
    
        in_object_name: table_name | view_name
          """
        obj_query = """SELECT {o}_name FROM all_{o}s WHERE owner = SYS_CONTEXT ('userenv', 'current_schema') AND {o}_name = '{on}'
        """.format(o=in_object, on=in_object_name.upper())
        with in_engine.connect() as connection:
            result = connection.execute(obj_query)
        return len(list(result)) > 0
    

提交回复
热议问题