Using SQLAlchemy-Utils for Database Table and Column Reflection

  • Share this:

Code introduction


This function demonstrates the use of reflection in SQLAlchemy-Utils to inspect a database's tables and columns, returning a dictionary that contains table names and column information.


Technology Stack : SQLAlchemy-Utils, SQLAlchemy

Code Type : Function

Code Difficulty : Intermediate


                
                    
def table_reflection(database, session):
    # This function demonstrates the use of reflection in SQLAlchemy-Utils to inspect a database's tables and columns.
    
    # Create a reflection object for the database
    reflect = sa.engine_reflect.ReflectEngine(database.engine)
    
    # Reflect all tables in the database
    reflected_tables = reflect.tables
    
    # Create a dictionary to store table information
    tables_info = {}
    
    # Iterate over each table and collect information
    for table in reflected_tables:
        # Get the full schema and table name
        full_name = '.'.join([table.schema, table.name])
        
        # Get the columns for the table
        columns = session.query(table.c).with_columns(
            sa.func.count().label('count')
        ).group_by(table.c.name).all()
        
        # Store the column information
        columns_info = [column._props for column in columns]
        tables_info[full_name] = {
            'columns': columns_info
        }
    
    return tables_info