Created
February 26, 2023 14:36
-
-
Save Corvan/33b9247f433a3bf44ee179cdac0064ee to your computer and use it in GitHub Desktop.
Using sqlalchemy to inspect a postgres database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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