Ticket #14098: inspect-skip.diff

File inspect-skip.diff, 9.5 KB (added by Adam Vandenberg, 14 years ago)
  • django/core/management/commands/inspectdb.py

    diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py
    index e45f22c..f606b41 100644
    a b class Command(NoArgsCommand):  
    1111        make_option('--database', action='store', dest='database',
    1212            default=DEFAULT_DB_ALIAS, help='Nominates a database to '
    1313                'introspect.  Defaults to using the "default" database.'),
     14
     15        make_option('--skip', action='store_true', dest='skip',
     16            default=False, help='Skips tables that cannot be read instead of erroring out.'),
    1417    )
    1518
    1619    requires_model_validation = False
    class Command(NoArgsCommand):  
    4447        for table_name in connection.introspection.get_table_list(cursor):
    4548            yield 'class %s(models.Model):' % table2model(table_name)
    4649            try:
    47                 relations = connection.introspection.get_relations(cursor, table_name)
    48             except NotImplementedError:
    49                 relations = {}
    50             try:
    51                 indexes = connection.introspection.get_indexes(cursor, table_name)
    52             except NotImplementedError:
    53                 indexes = {}
    54             for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)):
    55                 column_name = row[0]
    56                 att_name = column_name.lower()
    57                 comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
    58                 extra_params = {}  # Holds Field parameters such as 'db_column'.
    59 
    60                 # If the column name can't be used verbatim as a Python
    61                 # attribute, set the "db_column" for this Field.
    62                 if ' ' in att_name or '-' in att_name or keyword.iskeyword(att_name) or column_name != att_name:
    63                     extra_params['db_column'] = column_name
    64 
    65                 # Modify the field name to make it Python-compatible.
    66                 if ' ' in att_name:
    67                     att_name = att_name.replace(' ', '_')
    68                     comment_notes.append('Field renamed to remove spaces.')
    69                 if '-' in att_name:
    70                     att_name = att_name.replace('-', '_')
    71                     comment_notes.append('Field renamed to remove dashes.')
    72                 if keyword.iskeyword(att_name):
    73                     att_name += '_field'
    74                     comment_notes.append('Field renamed because it was a Python reserved word.')
    75                 if column_name != att_name:
    76                     comment_notes.append('Field name made lowercase.')
    77 
    78                 if i in relations:
    79                     rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
    80                     field_type = 'ForeignKey(%s' % rel_to
    81                     if att_name.endswith('_id'):
    82                         att_name = att_name[:-3]
    83                     else:
     50                try:
     51                    relations = connection.introspection.get_relations(cursor, table_name)
     52                except NotImplementedError:
     53                    relations = {}
     54                try:
     55                    indexes = connection.introspection.get_indexes(cursor, table_name)
     56                except NotImplementedError:
     57                    indexes = {}
     58                for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)):
     59                    column_name = row[0]
     60                    att_name = column_name.lower()
     61                    comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
     62                    extra_params = {}  # Holds Field parameters such as 'db_column'.
     63
     64                    # If the column name can't be used verbatim as a Python
     65                    # attribute, set the "db_column" for this Field.
     66                    if ' ' in att_name or '-' in att_name or keyword.iskeyword(att_name) or column_name != att_name:
    8467                        extra_params['db_column'] = column_name
     68
     69                    # Modify the field name to make it Python-compatible.
     70                    if ' ' in att_name:
     71                        att_name = att_name.replace(' ', '_')
     72                        comment_notes.append('Field renamed to remove spaces.')
     73                    if '-' in att_name:
     74                        att_name = att_name.replace('-', '_')
     75                        comment_notes.append('Field renamed to remove dashes.')
     76                    if keyword.iskeyword(att_name):
     77                        att_name += '_field'
     78                        comment_notes.append('Field renamed because it was a Python reserved word.')
     79                    if column_name != att_name:
     80                        comment_notes.append('Field name made lowercase.')
     81
     82                    if i in relations:
     83                        rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
     84                        field_type = 'ForeignKey(%s' % rel_to
     85                        if att_name.endswith('_id'):
     86                            att_name = att_name[:-3]
     87                        else:
     88                            extra_params['db_column'] = column_name
     89                    else:
     90                        # Calling `get_field_type` to get the field type string and any
     91                        # additional paramters and notes.
     92                        field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
     93                        extra_params.update(field_params)
     94                        comment_notes.extend(field_notes)
     95
     96                        # Add primary_key and unique, if necessary.
     97                        if column_name in indexes:
     98                            if indexes[column_name]['primary_key']:
     99                                extra_params['primary_key'] = True
     100                            elif indexes[column_name]['unique']:
     101                                extra_params['unique'] = True
     102
     103                        field_type += '('
     104
     105                    # Don't output 'id = meta.AutoField(primary_key=True)', because
     106                    # that's assumed if it doesn't exist.
     107                    if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}:
     108                        continue
     109
     110                    # Add 'null' and 'blank', if the 'null_ok' flag was present in the
     111                    # table description.
     112                    if row[6]: # If it's NULL...
     113                        extra_params['blank'] = True
     114                        if not field_type in ('TextField(', 'CharField('):
     115                            extra_params['null'] = True
     116
     117                    field_desc = '%s = models.%s' % (att_name, field_type)
     118                    if extra_params:
     119                        if not field_desc.endswith('('):
     120                            field_desc += ', '
     121                        field_desc += ', '.join(['%s=%r' % (k, v) for k, v in extra_params.items()])
     122                    field_desc += ')'
     123                    if comment_notes:
     124                        field_desc += ' # ' + ' '.join(comment_notes)
     125                    yield '    %s' % field_desc
     126                for meta_line in self.get_meta(table_name):
     127                    yield meta_line
     128
     129            except:
     130                if options.get('skip'):
     131                    yield "    # Error reading this table"
     132                    yield "    pass"
     133                    yield
    85134                else:
    86                     # Calling `get_field_type` to get the field type string and any
    87                     # additional paramters and notes.
    88                     field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
    89                     extra_params.update(field_params)
    90                     comment_notes.extend(field_notes)
    91 
    92                     # Add primary_key and unique, if necessary.
    93                     if column_name in indexes:
    94                         if indexes[column_name]['primary_key']:
    95                             extra_params['primary_key'] = True
    96                         elif indexes[column_name]['unique']:
    97                             extra_params['unique'] = True
    98 
    99                     field_type += '('
    100 
    101                 # Don't output 'id = meta.AutoField(primary_key=True)', because
    102                 # that's assumed if it doesn't exist.
    103                 if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}:
    104                     continue
    105 
    106                 # Add 'null' and 'blank', if the 'null_ok' flag was present in the
    107                 # table description.
    108                 if row[6]: # If it's NULL...
    109                     extra_params['blank'] = True
    110                     if not field_type in ('TextField(', 'CharField('):
    111                         extra_params['null'] = True
    112 
    113                 field_desc = '%s = models.%s' % (att_name, field_type)
    114                 if extra_params:
    115                     if not field_desc.endswith('('):
    116                         field_desc += ', '
    117                     field_desc += ', '.join(['%s=%r' % (k, v) for k, v in extra_params.items()])
    118                 field_desc += ')'
    119                 if comment_notes:
    120                     field_desc += ' # ' + ' '.join(comment_notes)
    121                 yield '    %s' % field_desc
    122             for meta_line in self.get_meta(table_name):
    123                 yield meta_line
     135                    raise
    124136
    125137    def get_field_type(self, connection, table_name, row):
    126138        """
Back to Top