Skip to content

Instantly share code, notes, and snippets.

@hilam
Created July 1, 2022 21:13
Show Gist options
  • Save hilam/9c93765d8bc333c033d4992193028eef to your computer and use it in GitHub Desktop.
Save hilam/9c93765d8bc333c033d4992193028eef to your computer and use it in GitHub Desktop.
from sqlalchemy import Table, MetaData, create_engine
from sqlalchemy.engine import reflection
# Configurações de conexão abstraídas em variáveis de ambiente setadas num arquivo .env
DB_USER = os.getenv('DB_USER')
DB_PASS = os.getenv('DB_PASS')
DB_HOST = os.getenv('DB_HOST')
DB_NAME = os.getenv('DB_NAME')
SQLALCHEMY_DATABASE_URL = f"postgresql+psycopg2://{DB_USER}:{DB_PASS}@{DB_HOST}:5432/{DB_NAME}"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
def get_equivalent(typename):
# tipo do Postgres: tipo do SQLAlchemy
types = {
'VARCHAR': 'String',
'TIMESTAMP': 'DateTime',
'BIGINT': 'Integer',
'NUMERIC': 'Float'
}
return types.get(typename, typename.title())
def create_class_source(class_name, table_name):
meta = MetaData()
table_text = """class {}(Base):\n""".format(class_name.title().replace("_",""))
table_text += """ __tablename__ = '{}' \n\n""".format(table_name)
table = Table(table_name, meta, autoload_with=engine)
for column in table.columns:
col_text = """ {name} = Column({type}, {{extras}})\n""".format(
name=column.name,
type=get_equivalent(
repr(column.type).strip('()')
),
)
extras = ""
# neste ponto inspecionar os atributos de column em que estiver interessado
# e montar a string extras com alguns 'if' -
# ex.: ( column.foreign_keys, column.primary_key)
table_text += col_text.format(extras=extras)
return table_text + "\n\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment