Search code examples
pythonpython-elixir

Using multiple databases with Elixir


I would like to provide database for my program that uses elixir for ORM. Right now the database file (I am using SQLite) must be hardcoded in metadata, but I would like to be able to pass this in argv. Is there any way to do this nice?

The only thing I thought of is to:

from sys import argv

metadata.bind = argv[1]

Can I set this in the main script and it would be used in all modules, that define any Entities?


Solution

  • I have some code that does this in a slightly nicer fashion than just using argv

    from optparse import OptionParser
    
    parser = OptionParser()
    parser.add_option("-u", "--user", dest="user",
                      help="Database username")
    parser.add_option("-p", "--password", dest="password",
                      help="Database password")
    parser.add_option("-D", "--database", dest="database", default="myDatabase",
                      help="Database name")
    parser.add_option("-e", "--engine", dest="engine", default="mysql",
                      help="Database engine")
    parser.add_option("-H", "--host", dest="host", default="localhost",
                      help="Database host")
    
    (options, args) = parser.parse_args()
    
    def opt_hash(name):
        global options
        return getattr(options, name)
    
    options.__getitem__ = opt_hash
    
    metadata.bind = '%(engine)s://%(user)s:%(password)s@%(host)s/%(database)s' % options
    

    Note that the part using opt_hash is a bit of a hack. I use it because OptionParser doesn't return a normal hash, which is what is really needed for the niceness of the bind string I use in the last line.