On Nov 13, 2007 5:14 AM, Simon Pamies <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I'm very pleased to announce the release of SQLAutocode 0.4.1 and
> 0.5. This tool enables SQLAlchemy users to automagically generate
> python code from an existing database layout and even has the
>

Hey Simon, I found your code today and started to hack on it to do db
migrations.  Since it is out of the scope of your project, I'll
probably just write my own.   But before I came to that conclusion, I
did some cleaning up of the autocode.py.  Feel free to accept it if
you want.  Here's the overview of the changes in the attached diff:

 * Remove import * - I know SA does this all over the place, but when
you have various projects that you are doing this with (ie both
autocode and SA) it makes it difficult to know what came from where.
Especially if you are an outside developer

 * added a _main() function

 * changed getopt to optparse

 * added newlines after "else:"

 * changed "if foo is True:" to "if foo:"

cheers,

matt

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

=== modified file 'autocode.py'
--- autocode.py 2007-11-13 22:18:59 +0000
+++ autocode.py 2007-11-13 23:34:54 +0000
@@ -1,104 +1,93 @@
-
 import sys
-import sqlalchemy
-if sqlalchemy.__version__ != 'svn':
-    if sqlalchemy.__version__.split('.')[1] != '4':
+import os
+import optparse
+
+
+import sqlalchemy as sa
+if sa.__version__ != 'svn':
+    if sa.__version__.split('.')[1] != '4':
         print 'Not compatible with this version of SQLAlchemy! Only works for 
the 0.4.x line!'
         sys.exit(7)
 
-del sqlalchemy
-
-
-from sqlalchemy import engine, MetaData
-
 import constants
-from loader import *
-from formatter import *
-
-if __name__ == '__main__':
-
-    import sys, getopt, os
-    
-    args, longargs = ('hu:o:s:t:i3e', ['help', 'url=', 'output=', 'schema=', 
'tables=', 'noindex', 'z3c', 'example'])
-
-    try:
-        optlist, args = getopt.getopt(sys.argv[1:], args, longargs)
-    except getopt.GetoptError:
-        print >>sys.stderr, 'Error: Unknown arguments.'
-        print >>sys.stderr, constants.USAGE
-        sys.exit(255)
-    
-    if len(optlist)==0:
-        print >>sys.stderr, 'Error: No arguments passed.'
-        print >>sys.stderr, constants.USAGE
-        sys.exit(0)
-
-    url, output, schema, tables, \
-            filehandle, noindex, \
-            example, z3c = (None, None, None, None, None, None, False, False)
-    for opt, arg in optlist:
-        if opt in ['-h', '--help']:
-            print >>sys.stderr, constants.USAGE
-            sys.exit(0)
-            
-        if opt in ['-u', '--url']:
-            url = arg
-
-        if opt in ['-i', '--noindex']:
-            noindex = True
-
-        if opt in ['-e', '--example']:
-            example = True
-
-        if opt in ['-3', '--z3c']:
-            z3c = True
-            constants.TAB = 26*' '
-            
-        if opt in ['-o', '--output']:
-            output = arg
-
-            if os.path.exists(output):
-                print >>sys.stderr, 'Output file exists - it will be 
overwritten!'
-                resp = raw_input('Overwrite (Y/N): ')
-                if resp.strip().lower() != 'y':
-                    print "Aborted."
-                    sys.exit(0)
-
-                else: os.unlink(output)
-
-            filehandle = open(output, 'wU')
-            
-        if opt in ['-s', '--schema']:
-            schema = arg.strip()
-            
-        if opt in ['-t', '--tables']:
-            tables = arg.split(',')
+import loader
+import formatter
+
+def _main(prog_args=None):
+    if prog_args is None:
+        prog_args = sys.argv
+
+    parser = optparse.OptionParser("""Generates python code for a given 
database schema.""")
+    
+    parser.add_option("-u", "--url",
+                      help="Database url (e.g.: postgres://postgres:[EMAIL 
PROTECTED]/Database)",
+                      action="store", dest="url", default=None)
+    parser.add_option("-o", "--output",
+                      help="Where to put the output (default is stdout)",
+                      action="store", dest="output", default=None)
+    parser.add_option("-s", "--schema",
+                      help="Name of the schema to output (default is 
'default')",
+                      action="store", dest="schema", default=None)
+    parser.add_option("-t", "--tables",
+                      help="""Name of tables to inspect (default is 'all').  
Support globbing character to select more tables.  ex.: -t Download* will 
generate a model for all tables starting with Download""",
+                      action="store", dest="tables", default=None)
+    parser.add_option("-i", "--noindex",
+                      help="Do not generate index information",
+                      action="store_true", dest="noindex")
+    parser.add_option("-e", "--example",
+                      help="Generate code with examples how to access data",
+                      action="store_true", dest="example")
+    parser.add_option("-3", "--z3c",
+                      help="Generate code for use with z3c.sqlalchemy",
+                      action="store_true", dest="z3c")
+    opt, args = parser.parse_args(prog_args)
+
+    if opt.z3c:
+        constants.TAB = 26*' '
+
+    filehandle=None
+    if opt.output:
+        if os.path.exists(opt.output):
+            print >>sys.stderr, 'Output file exists - it will be overwritten!'
+            resp = raw_input('Overwrite (Y/N): ')
+            if resp.strip().lower() != 'y':
+                print "Aborted."
+                sys.exit(0)
+            else:
+                os.unlink(opt.output)
+        filehandle = open(opt.output, 'wU')
+        
+    if opt.tables:
+        opt.tables.split(",")
+    
 
     print >>sys.stderr, 'Starting...'
-    dburl = engine.url.make_url(url)
-    db = create_engine(url)
+    dburl = sa.engine.url.make_url(opt.url)
+    db = sa.create_engine(opt.url)
 
-    metadata = MetaData(db)
+    metadata = sa.MetaData(db)
     connection = db.connect()
 
     # some header with imports 
-    if z3c is True:
-        printout(constants.HEADER_Z3C, filehandle)
-    else: printout(constants.HEADER, filehandle)
+    if opt.z3c:
+        formatter.printout(constants.HEADER_Z3C, filehandle)
+    else:
+        formatter.printout(constants.HEADER, filehandle)
     
-    if schema == None:
+    if not opt.schema:
         try:
-            schema = db.dialect.get_default_schema_name(connection)
-        except NotImplementedError: schema = None
+            opt.schema = db.dialect.get_default_schema_name(connection)
+        except NotImplementedError:
+            opt.schema = None
 
-    tablenames = db.dialect.table_names(connection, schema)
+    tablenames = db.dialect.table_names(connection, opt.schema)
 
     # support user defined tables
-    if tables != None:
+    if opt.tables:
 
         # first check if tables are available
         tablenames = []
-        for tn in tables:
+        for tn in opt.tables:
             tname = tn.strip()
 
             if tname[-1] != '*':
@@ -110,51 +99,58 @@
                     if t2name.startswith(tname[:-1]):
                         tablenames.append(t2name)
 
+        
     # do the hard work
     for tname in tablenames:
         tname = tname.encode( 'utf-8')
         print >>sys.stderr, "Generating python model for table %s" % tname
 
-        table = Table(tname, metadata, schema=schema, autoload=True)
+        table = sa.Table(tname, metadata, schema=opt.schema, autoload=True)
 
         INC = '\n\n'
-        if z3c is True:
+        if opt.z3c:
             INC = INC + 4*' '
 
-        printout(INC+'%s %s %s' % (tname, '=', repr(table)), filehandle)
+        formatter.printout(INC+'%s %s %s' % (tname, '=', repr(table)), 
filehandle)
 
-        if z3c is True:
-            printout(INC + \
+        if opt.z3c:
+            formatter.printout(INC + \
                     'class %(tn)sObject(MappedClassBase): pass\n    
mapper(%(tn)sObject, %(tn)s)' \
                     % {'tn':tname}, filehandle)
 
         # directly print indices after table def
-        if noindex != True:
+        if opt.noindex != True:
             indexes = []
             if table.indexes == set([]):
                 # for certain dialects we need to include index support
                 if hasattr(db.dialect, 'indexloader'):
                     indexes = db.dialect.indexloader(db).indexes(table)
 
-                else: print >>sys.stderr, 'It seems that this dialect does not 
support indexes!'
-            else: indexes = list(table.indexes)
+                else:
+                    print >>sys.stderr, 'It seems that this dialect does not 
support indexes!'
+            else:
+                indexes = list(table.indexes)
 
             pindexes = '\n'.join(repr_index(index, tname)
                                         for index in indexes )
             if pindexes: 
                 for index in pindexes:
-                    printout(index, filehandle)
+                    formatter.printout(index, filehandle)
 
-    if z3c is True:
-        printout('\n' + constants.FOOTER_Z3C, filehandle)
+    if opt.z3c:
+        formatter.printout('\n' + constants.FOOTER_Z3C, filehandle)
     
     # print some example
-    if example is True:
-        printout('\n' + constants.FOOTER_EXAMPLE % {'url' : url, 'tablename' : 
tablenames[0]}, filehandle)
+    if opt.example:
+        formatter.printout('\n' + constants.FOOTER_EXAMPLE % {'url' : url, 
'tablename' : tablenames[0]}, filehandle)
     
-    if filehandle != None: 
-        printout("\n", filehandle)
+    if filehandle:
+        formatter.printout("\n", filehandle)
         filehandle.close()
         print >>sys.stderr, "Output written to %s" % output
 
+    
+if __name__ == '__main__':
+    _main()
+
 # vim:ts=4:sw=4:expandtab

Reply via email to