Just for anyone searching and finding this thread.  I started working
with the link given by Massimo and ended up with this.
It's very ugly and unsupported by me or anyone else.  However, it
converted my basic Firebird schema and it just might help save someone
else a little bit of time. I don't know about other DBs and I cannot
help anyone who gets stuck!


use like this
#auto.py schema.sql > modelcontroller.py

------------------ auto.py script -----------------
import re
import sys

regex_tables=re.compile("""^[\w]+\.define_table\(\s*[\'\"](?P<name>
[\w_]+)[\'\"]""",flags=re.M)

conversion={
'references':"'integer'",
'clob':"'text'",
'varchar':"'string'",
'char':"'string'",
'int':"'integer'",
'int4':"'integer'",
'bool':"'boolean'",
'float':"'double'",
'date':"'date'",
'datetime':"'datetime'",
'timestamp':"'datetime'",
'time':"'datetime'",  #populate doesn't accept time, needs fixing
'decimal':"'decimal(9,2)'",
'numeric':"'decimal(9,2)'",
'blob':"'text'",
'double':"'double'",
'defaultno':"'string', length=1, default='N'",  #ignore, personal
domain
'yesno':"'boolean'",   #ignore, personal domain
'amount':"'decimal(9,2)'",   #ignore, personal domain
'sys_id':"'integer'"   #ignore, personal domain
}

def convert(field):
    for k in conversion.iterkeys():
        field = field.lower()
        if field.find(k) >=0:
            outstr = conversion[k]
            if (outstr == "'string'") & (field.find('(')>=0) :
                lafield = field.split('(')
                lslen = re.search('(?P<group>[\d]+)',lafield[1])
                return outstr+', length='+lslen.group(0)
            else: return outstr
    return field

def auto(data):
    regex1=re.compile('\s*(?P<name>\S+\s+\S+).*')
    data = re.sub('[\f\n\r\t\v\[\]]', '', data).lower()
    data = re.sub(' id ', ' id_prev ', data)
    data = re.sub(' keys ', ' keyregister ', data)
    data = re.sub(' status ', ' stat ', data)
    tables={}
    output=''
    for item in re.compile('create\s+table\s+(?P<tablename>\S+)(?
P<fields>.*?\);)').findall(data):
        tablename=item[0]
        fields=item[1].lower()
        while (fields[0:1] == ' ') | (fields[0:1] == '(') :
fields=fields[1:]
        fields2=[regex1.match(i).group('name').split() for i in
fields.split(', ')]
        lastfieldtuple = fields2[-1:]
        if lastfieldtuple[0][0] == 'constraint' : fields2 = fields2
[:-1]

        sfields=''.join(["db.Field('%s',%s),\n    " % (k,convert(v))
for k,v in fields2 if not k.upper() in ['INDEX','CONSTRAINT']])
        output+="db.define_table('%s',\n    %smigrate='%s.mig')\n" %
(tablename, sfields, tablename)
        tables[tablename]=[k for k,v in fields2]
        labels=','.join(["'%s':T('%s')"%(f,f) for f in tables
[tablename]])
        output+='%s_labels={%s}\n\n' % (tablename,labels)
    tablenames=tables.keys()
    tablenames.sort()
    output += '\n\nfrom gluon.contrib.populate import populate\n'
    # populates the tables
    for tablename in tablenames:
        output += 'if not db(db.%(table)s.id).count(): populate(db.%
(table)s,5)\n'% dict(table=tablename)
    model = output

    # Returns a URL to link to in crud.selects.
    output = """
def mylink(field, type, ref):
    return URL(r=request, args=[field])
"""
    for tablename in tablenames:
        output += """

def %(table)s():
    # Maintain all the table_name records in the application
    # Manage, list, create and update projects.

    # SELECT if no args
    if len(request.args)<1:
        return dict(form=crud.select(db.%(table)s,linkto=mylink))

    # If 1 arg and it is 'create' then CREATE
    elif len(request.args)==1 and request.args[0]=='create':
        return dict(form=crud.create(db.%(table)s,next=URL
(request.application,request.controller,%(table)s)))

    # If 1 arg and its integer, EDIT it.
    elif len(request.args)==1:
        try:
            i=int(request.args[0])
        except:
            redirect(URL(r=request,f='index'))
        return dict(form=crud.update(db.%(table)s,i,next=URL
(request.application,request.controller,%(table)s)))
    else:
        redirect(URL(r=request,f='index'))

""" % dict(table=tablename,fields=tables[tablename])
    controller=output

    return '# MODEL\n'+model+'# CONTROLLER\n'+controller

if __name__=='__main__':
    print auto(open(sys.argv[1],'r').read())

--

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


Reply via email to