Skip to content

Instantly share code, notes, and snippets.

@Corvan
Created February 26, 2023 14:36
Show Gist options
  • Save Corvan/33b9247f433a3bf44ee179cdac0064ee to your computer and use it in GitHub Desktop.
Save Corvan/33b9247f433a3bf44ee179cdac0064ee to your computer and use it in GitHub Desktop.
Using sqlalchemy to inspect a postgres database
import sqlalchemy
engine = sqlalchemy.create_engine("postgresql+psycopg2:///lars")
meta = sqlalchemy.schema.MetaData()
meta.reflect(bind=engine)
inspector = sqlalchemy.inspect(engine)
default_schema_name = inspector.default_schema_name
schema_names = inspector.get_schema_names()
def create_tables(if_exists: bool = False) -> str:
return "\n".join(
[
str(
sqlalchemy.schema.CreateTable(table, if_not_exists=if_exists).compile(
engine
)
)
for table in meta.sorted_tables
]
)
print(create_tables())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment