-
-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
sqlalchemy2ormar - failed to create ormar class #1
Comments
Yeah I had the same problem seems that automap is far from being perfect as it tries to create column and relation with the same name, which fails. You can use also models generated with |
How did u convert the sqlalchemy to ormar Class ? |
I used |
would u mine to share the code please |
I saved the db with sqlacodegen into # parser.py
import sqlalchemy
from databases import Database
from sqlalchemy_to_ormar import sqlalchemy_to_ormar
import models # this is the file saved by sqlacodegen
import sys, inspect
ormar_models = []
metadata = sqlalchemy.MetaData()
database = Database("sqlite:///")
def parse_classes():
for name, obj in inspect.getmembers(sys.modules["models"]):
if inspect.isclass(obj):
if (isinstance(obj, sqlalchemy.ext.declarative.api.DeclarativeMeta)
and obj.__name__ != "Base"):
print(obj)
ormar_models.append(
sqlalchemy_to_ormar(obj, metadata=metadata, database=database))
parse_classes() Note that it will explode (recurrsion error) if you have circles in code or self-referencing modules as it's not supported yet. |
sqlacodegen + conversion to ormar - great feature ! It could be also interesting to have assign default assignment automatically (be set of rules of course). |
Yes I want to add automap/autodiscovery with sqlacodegen (as automap from sqlalchemy is not really helpful in most of my cases). As for auto assignment if you mean register a class in a module so you can access it by name you can modify the example as: import sqlalchemy
from databases import Database
from sqlalchemy_to_ormar import sqlalchemy_to_ormar
import models
import sys, inspect
metadata = sqlalchemy.MetaData()
database = Database("sqlite:///")
def parse_classes():
for name, obj in inspect.getmembers(sys.modules["models"]):
if inspect.isclass(obj):
if (isinstance(obj, sqlalchemy.ext.declarative.api.DeclarativeMeta)
and obj.__name__ != "Base"):
print(obj)
ormar_class = sqlalchemy_to_ormar(obj, metadata=metadata, database=database)
# register in current module
setattr(sys.modules[__name__], ormar_class.__name__, ormar_class)
parse_classes()
# should be available
print(<YOUR_MODEL_NAME>) If You can also save to file, there is a #when you have list of ormar models
with open("ormar.model.py", "w") as file:
for model in ormar_models:
file.write(ormar_model_str_repr(model)) I don't remember the new lines so you might have to add new lines ("\n") writes to the loop between models. |
Trying to add the auto discovery via fastapi, I have doubt if this should be the recommended approach , WARNING: WatchGodReload detected file change in '['/app/auto_discovery/db_schemas.py']'. Reloading...
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: ASGI 'lifespan' protocol appears unsupported.
INFO: Application shutdown complete Q: is there more elegant way to do it? code: @audo_discovery_router.post("/auto_discovery/", response_model=DbConfigAndSetup,tags=["auto_discovery"])
async def auto_discovery(dbConfigandsetup: DbConfigAndSetup):
module = importlib.import_module('databases_config.db')
# enum class - translate the friendly name for db_name --> BaseMeta
# So dbConfigandsetup.db_name.name holds the chosen related BaseMeta
choosen_basemeta_class = getattr(module, dbConfigandsetup.db_name.name)
## User prvoide table_list (or None)
tables_file = sqlacodegen_get_tables(choosen_basemeta_class.database,dbConfigandsetup.tables)
return {"Message": "done"}
def sqlacodegen_get_tables(BaseMeta ,table_list ):
#extracting the url for sqlacodegen
url = str(BaseMeta.database.url)
metadata = BaseMeta.metadata
database = BaseMeta.database
if not table_list is None:
table_list = ",".join(table_list)
sqlacodegen_cmd ="sqlacodegen --outfile auto_discovery/db_schemas.py --tables (" + table_list + ") " + url
else:
sqlacodegen_cmd ="sqlacodegen --outfile auto_discovery/db_schemas.py " + url
#exeucting sqlacodegen with cmd
os.system(sqlacodegen_cmd)
# getting an error as file hasn't finish written so import failed
#don't like the idea anyway
from . import db_schemas
#converting to ormar
for name, obj in inspect.getmembers(sys.modules["db_schemas"]):
if inspect.isclass(obj):
if (isinstance(obj, sqlalchemy.ext.declarative.api.DeclarativeMeta)
and obj.__name__ != "Base"):
ormar_models.append(
sqlalchemy_to_ormar(obj, metadata=metadata, database=database))
with open("auto_discovery/models.py", "w") as file:
for model in ormar_models:
file.write(ormar_model_str_repr(model)) |
Fastapi reloads cause you probably run it with And if you run this behind a server like gunicorn etc. without reload there might be problems with picking up the new python files. So if you want to do this dynamically on fastapi request you shouldn't write it to files. Why do you want to write to files through fastapi? Reflecting a database and creating models from this might be quite expensive operation depending on number of tables, so you can easily hit timouts along the way if you go through web request. |
Describe the bug
I create tables where tables actually define as ormar class in program ,.
once tables created - verified them in DB.
Also manage to fetch/insert data with the models,
Tried pull the ormar class using the sqlalchemy2ormar:
getting:
To Reproduce
Create tables in DB:
Expected behavior
Expect to get ormar Class
Versions (please complete the following information):
Python version 3.8
ormar 0.10.5
sqlalchemy-to-ormar 0.0.1
Additional context
I double check with other tool there's no DB issue ,
the tool provide the sqlalchemy our of DB :
Would appreciate an instruction how run the tool on specific list ,
The text was updated successfully, but these errors were encountered: