Schema Inspect

3.1.1663587362 · maintenance · verified Fri Apr 17

Schema Inspect is a Python library for programmatically inspecting database schemas, with a strong focus on PostgreSQL. It integrates with SQLAlchemy to provide a structured representation of tables, columns, constraints, and other schema objects. The current version is 3.1.1663587362, which uses a unique timestamp-based versioning scheme, reflecting its last significant update in late 2022.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a database using a DSN (Data Source Name) and use `schemainspect` to retrieve and print the names of all tables and basic column details from the inspected schema. It uses an environment variable for the DSN for security.

from schemainspect import inspect
import os

# Example for PostgreSQL connection string
# Replace with your actual database URL or use an environment variable
dsn = os.environ.get("DATABASE_URL", "postgresql://user:password@localhost:5432/mydb")

# Inspect the database schema
print(f"Inspecting schema for: {dsn.split('@')[-1] if '@' in dsn else dsn}")
schema = inspect(dsn)

# Print all table names
print("\nTables found:")
if schema.tables:
    for table in schema.tables:
        print(f"  - {table.name}")
        # Optionally print columns for the first table as an example
        if table == list(schema.tables.values())[0]: # Get the first table
            for column in table.columns:
                print(f"    - Column: {column.name}, Type: {column.type}, Nullable: {column.nullable}")
else:
    print("  No tables found.")

# Access a specific table (replace 'your_table_name' with an actual table in your DB)
# if 'your_table_name' in schema.tables:
#     my_table = schema.tables['your_table_name']
#     print(f"\nDetails for table '{my_table.name}':")
#     for column in my_table.columns:
#         print(f"  Column: {column.name}, Type: {column.type}, Primary Key: {column.primary_key}")

view raw JSON →