I have a little problem regarding “arranging of code, which depends on each other” when setting an sqlalchemy mapping to a sqlite database in python.
The goal is to write a script, whcih satisfies the following conditions:
- Gets a
filenameparameter as command line argument. - Based on the
filenameit should create an absolute path to the SQLite database. - It should connect to the database and create an
engine - It shall reflect the tables in this databases.
- It should
monkey patchthe columnidin the tablemytableas a primary key column, since the table doesn’t habe a primary key and sqlalchemy requires one.
So I came up with this:
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
def create_path(file_name):
# generate absolute path to file_name
path_to_file = create_path("my_file_name.sqlite")
engine = create_engine('sqlite:///{path}'.format(path=path_to_file), echo=False)
Base = declarative_base()
Base.metadata.create_all(engine)
class MyTable(Base):
__tablename__ = 'my_table'
__table_args__ = {'autoload': True}
id = Column(Integer, primary_key=True) # Monkey patching the id column as primary key.
def main(argv):
# parse file_name here from argv
Session = sessionmaker(bind=engine)
session = Session()
for row in session.query(MyTable).all():
print row
return "Stop!"
if __name__ == '__main__':
sys.exit(main())
But this is a doomed construction and I don’t see how I could rearrange my code without breaking the dependencies.
- To be able to create
MyClassI needBaseto be defined beforeMyClass. - To be able to create
BaseI needengineto be defined beforeBase. - To be able to create
engineI needpath_to_fileto be defined beforeengine. - To be able to create
path_to_fileoutside ofmain()I needcreate_file()to be defined beforepath_to_file. - And so on…
Hopefully you see where I am stuck…
Any suggestions?
Edit: By the way, the code works, but only with a hardcoded filename in the top of the script.
I do not see why you could not use the
declarativemapping still complety. I think the key to the proper dependencies is to know what to put in the module and what in the script/function. With python, you can easily define the class inside therun_scriptfunction.