Contact: fumanchu@aminus.org

Log in as guest/dejavu to create tickets

Here's a little script I've used to create a model.py file from an existing Postgres DB that uses multiple schemas. It's also handy for keeping it updated when the DB changes underneath me; I just re-discover it and then diff the changes.

import re
import os, sys
localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))

from dejavu.storage import db


def automodel(root, outfile=None):
    linesep = os.linesep
    
    if outfile is None:
        outfile = os.path.join(localDir, "model.py")
    
    f = open(outfile, "wb")
    try:
        f.write('''
import datetime
import decimal
Decimal = decimal.Decimal

from dejavu import Unit, UnitProperty, UnitSequencer


def register_classes(sm):
    classes = globals().copy()
    classes.pop('Unit')
    sm.register_all(classes)

schemas = []


''')
        
        schemanames = root.db.discover_schemas()
        schemanames.sort()
        for schema in schemanames:
            modeler = db.Modeler(schema)
            # Ignore tsearch2 tables
            modeler.ignore.extend(['tokentype', 'tokenout',
                                   'statinfo', 'tsdebug'])
            source = modeler.all_source()
            
            if source:
                f.write("""
# ---------------------------- Schema: %s ---------------------------- #

schemas.append(%r)


""" % (schema.name, schema.name))
                for block in source:
                    block = block.replace('\n', linesep)
                    f.write(block)
                    f.write(linesep + '    _dbschema_name = "%s"' % schema.name)
                    f.write(linesep + linesep + linesep)
    finally:
        f.close()


if __name__ == "__main__":
    args = sys.argv[:]
    scriptname = args.pop(0)
    
    defaultdb = "master"
    dbname = raw_input("Database to discover [%s]:" % defaultdb) or defaultdb
    import getpass
    pw = getpass.getpass("Password for the 'postgres' account:")
    opts = {'connections.Connect':
            "host=localhost dbname=%s user=postgres password=%s" % (dbname, pw)}
    
    from dejavu import storage
    root = storage.resolve("pypgsql", opts)
    print root.version()
    
    try:
        automodel(root, *tuple(args))
    finally:
        root.shutdown()