Пример #1
0
def main():
    """ Main routine. """

    usage = '%prog [options] schema_file' + '\nVersion: %s' % VERSION
    parser = OptionParser(usage=usage)

    parser.add_option('-c', '--config-file',
                    dest='config_file',
                    help='Name of configuration file.')
    parser.add_option('-f', '--full-help',
                    action='store_true',
                    dest='full_help',
                    help=' '.join(['Print full help and exit.',
                        'Full help includes examples and notes.']),
                    )
    parser.add_option('-i', '--include-headers', action='store_true',
                    dest='headers',
                    help='Print table documentation headers.')
    parser.add_option('-s', '--ignore-signature', action='store_true',
                    dest='ignore_signature',
                    help='Do not print signature fields.')
    parser.add_option('-v', '--verbose', action='store_true',
                    dest='verbose',
                    help='Print messages to stdout',
                    )

    (options, args) = parser.parse_args()

    if options.verbose:
        # Add a stream handler to print messages to stderr.
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        LOG.addHandler(ch)

    if options.full_help:
        parser.print_help()
        print
        print usage_full()
        return

    if len(args) == 0:
        parser.print_help()
        exit(1)

    ignore_columns = []
    if options.ignore_signature:
        APP_ENV = env('shared', import_models=True)
        for field in ModelDb(APP_ENV).auth.signature.fields:
            if not field == 'id':
                ignore_columns.append(field)

    f = None
    if args[0] == '-':
        f = sys.stdin
    else:
        f = open(args[0], 'r')

    schema_file = SchemaFile(file_object=f)
    schema_file.parse()
    tables = []
    for line in schema_file.filter(['create', 'create_close', 'column']):
        LOG.debug('line: %s' % line.text)
        if line.type == 'create':
            create_line = CreateLine(text=line.text)
            create_line.parse()
            LOG.debug('create_line.table_name: %s'
                      % create_line.table_name)
            if create_line.table_name:
                table = MySQLTable(name=create_line.table_name)
                tables.append(table)
        if line.type == 'create_close':
            pass
        if line.type == 'column':
            if not len(tables) > 0:
                raise ValueError('Column without table: {text}'.format(
                        text=line.text))
            column_line = ColumnLine(text=line.text)
            column_line.parse()
            column = MySQLColumn(
                name=column_line.name,
                data_type=column_line.type,
                length=column_line.length,
                decimals=column_line.decimals,
                table=tables[-1],
                attributes=column_line.attributes,
                )
            if column.name not in ignore_columns:
                tables[-1].columns.append(column)
    f.close()

    # Set tables references
    # This step must be done after all MySQLTable objects are defined and
    # added to tables list since so the tables are available for columns that
    # reference it.
    for t in tables:
        for c in t.columns:
            c.set_referenced_table(tables=tables)
            if c.referenced_table:
                c.set_referenced_column()
                c.set_descriptor_column()

    defaults_set = None
    if options.config_file:
        defaults_set = FieldPropertyDefaultsSet()
        defaults_set.load(options.config_file)

    for t in tables:
        print ''
        if options.headers:
            print '"""'
            print t.documentation()
            print '"""'
        print define_table_code(t, defaults_set=defaults_set)

    first = True
    for t in sorted(tables, cmp=lambda x, y: cmp(x.name, y.name)):
        for c in sorted(t.columns, cmp=lambda x, y: cmp(x.name,
                        y.name)):
            if c.referenced_table:
                if first:
                    print ''
                first = False
                print c.requires_statement()
Пример #2
0
    def test__load(self):
        default_set = FieldPropertyDefaultsSet()

        tests = [{
            'label': 'empty file',
            'expect': 0,
            'by_name': {},
            'by_type': {},
            'text': '',
            }, {
            'label': 'fake section',
            'expect': 0,
            'by_name': {},
            'by_type': {},
            'text': """
[fake_section]
setting = value
""",
            }, {
            'label': 'by_name section',
            'expect': 7,
            'by_name': {'id': ['SKIP'], 'creation_date'
                        : ['writable=False'], 'modified_date'
                        : ['writable=False', 'update=request.now']},
            'by_type': {
                'string': ['requires=IS_NOT_EMPTY()'],
                'boolean': ['requires=IS_IN_SET[0,1]'],
                'date': ['IS_DATE()'],
                'time': ['IS_DATE()'],
                },
            'text'
                : """
[by_name]
id = SKIP
creation_date = writable=False
modified_date = writable=False
                update=request.now

[by_type]
string = requires=IS_NOT_EMPTY()
boolean = requires=IS_IN_SET[0,1]
date = IS_DATE()
time = IS_DATE()
""",
            }]

        f_text = '/tmp/web2py_sql_fieldpropertydefaults.txt'
        for t in tests:
            self._config_file_from_text(f_text, t['text'])
            default_set.load(f_text)
            self.assertEqual(len(default_set.field_property_defaults),
                             t['expect'])
            by_name = {}
            by_type = {}
            for fpd in default_set.field_property_defaults:
                if hasattr(fpd, 'column_name'):
                    by_name[fpd.column_name] = fpd.defaults
                if hasattr(fpd, 'column_type'):
                    by_type[fpd.column_type] = fpd.defaults
            if 'by_name' in t:
                self.assertEqual(by_name, t['by_name'])
            if 'by_type' in t:
                self.assertEqual(by_type, t['by_type'])
        os.unlink(f_text)
        return