Skip to content

Instantly share code, notes, and snippets.

@mmulich
Last active November 3, 2020 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmulich/3c38f9cf0aeca15dd96a5cda5838fc94 to your computer and use it in GitHub Desktop.
Save mmulich/3c38f9cf0aeca15dd96a5cda5838fc94 to your computer and use it in GitHub Desktop.
"""
SQLAlchemy with Postgres schemas reflection
This experiment creates some tables across schemas and asks sqlalchemy to reflect those tables.
The tables are not connected with constraints as that would allow reflection to *just* work.
"""
import os
from pprint import pprint
import sqlalchemy as sa
# Create the connection engine
# export DB_URL="postgresql://test:test@db/experiment"
engine = sa.create_engine(os.environ['DB_URL'])
# Create an inspector instance for getting the schema names
inspector = sa.inspect(engine)
# Create some tables by handle
with engine.connect() as conn:
conn.execute("""\
create schema foo;
create schema bar;
create table tableau (id serial primary key, num integer);
create table foo.tableau (id serial primary key, word text);
create table bar.other (id serial primary key, word text);
insert into tableau (num) values (1), (2), (3);
insert into foo.tableau (word) values ('four'), ('five'), ('six');
insert into bar.other (word) values ('seven'), ('eight'), ('nine');
""")
# Reflect the tables
metadata = sa.MetaData()
metadata.reflect(bind=engine)
# Reflect the tables in the individual schemas
for schema in inspector.get_schema_names():
# Ignore the internal informational schema and default public schema
if schema in ['information_schema', 'public']:
continue
metadata.reflect(bind=engine, schema=schema)
# Print out the table names
print("Tables: " + ', '.join(metadata.tables.keys()))
print('-'*80)
pprint(metadata.tables)
sqlalchemy
psycopg2-binary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment