コード例 #1
0
ファイル: inspectdb_1_7.py プロジェクト: totalgood/pug-dj
    def handle_inspection(self, options):
        connection = connections[options.get('database')]
        # 'table_name_filter' is a stealth option
        table_name_filter = options.get('table_name_filter')

        table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
        strip_prefix = lambda s: s[1:] if s.startswith("u'") else s

        cursor = connection.cursor()
        yield "# This Django model module was generated by [pug](http://pypi.python.org/pypi/pug)."
        yield "# WARNING: This is pre-alpha software and is likely to break your code!"
        yield "# You'll have to do the following manually to clean this up:"
        yield "#   * Rearrange models' order"
        yield "#   * Make sure each model has one field with primary_key=True   <--- HOPEFULLY MORE ARE GUESSED FOR YOU NOW"  
        yield "#   * Remove `managed = False` lines for those models you wish to give write DB access"
        yield "# Feel free to rename the models, but don't rename db_table values or field names."
        yield "#"
        yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'"
        yield "# into your database."
        yield "from __future__ import unicode_literals"
        yield ''
        yield 'from %s import models' % self.db_module
        yield ''
        known_models = []
        for table_name in connection.introspection.table_names(cursor):
            if table_name_filter is not None and callable(table_name_filter):
                if not table_name_filter(table_name):
                    continue
            yield 'class %s(models.Model):' % table2model(table_name)
            known_models.append(table2model(table_name))
            try:
                relations = connection.introspection.get_relations(cursor, table_name)
            except NotImplementedError:
                relations = {}
            try:
                indexes = get_indexes(cursor, table_name)
            except NotImplementedError:
                indexes = {}
            print indexes
            indexes = {}
            used_column_names = []  # Holds column names used in the table so far
            for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)):
                comment_notes = []  # Holds Field notes, to be displayed in a Python comment.
                extra_params = OrderedDict()  # Holds Field parameters such as 'db_column'.
                column_name = row[0]
                is_relation = i in relations

                att_name, params, notes = self.normalize_col_name(
                    column_name, used_column_names, is_relation)
                extra_params.update(params)
                comment_notes.extend(notes)

                used_column_names.append(att_name)

                # Add primary_key and unique, if necessary.
                if column_name in indexes:
                    if indexes[column_name]['primary_key']:
                        extra_params['primary_key'] = True
                    elif indexes[column_name]['unique']:
                        extra_params['unique'] = True

                if is_relation:
                    rel_to = "self" if relations[i][1] == table_name else table2model(relations[i][1])
                    if rel_to in known_models:
                        field_type = 'ForeignKey(%s' % rel_to
                    else:
                        field_type = "ForeignKey('%s'" % rel_to
                else:
                    # Calling `get_field_type` to get the field type string and any
                    # additional paramters and notes.
                    field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
                    extra_params.update(field_params)
                    comment_notes.extend(field_notes)

                    field_type += '('

                # Don't output 'id = meta.AutoField(primary_key=True)', because
                # that's assumed if it doesn't exist.
                if att_name == 'id' and extra_params == {'primary_key': True}:
                    if field_type == 'AutoField(':
                        continue
                    elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield:
                        comment_notes.append('AutoField?')

                # Add 'null' and 'blank', if the 'null_ok' flag was present in the
                # table description.
                if row[6]:  # If it's NULL...
                    if field_type == 'BooleanField(':
                        field_type = 'NullBooleanField('
                    else:
                        extra_params['blank'] = True
                        if not field_type in ('TextField(', 'CharField('):
                            extra_params['null'] = True

                field_desc = '%s = %s%s' % (
                    att_name,
                    # Custom fields will have a dotted path
                    '' if '.' in field_type else 'models.',
                    field_type,
                )
                if extra_params:
                    if not field_desc.endswith('('):
                        field_desc += ', '
                    field_desc += ', '.join([
                        '%s=%s' % (k, strip_prefix(repr(v)))
                        for k, v in extra_params.items()])
                field_desc += ')'
                if comment_notes:
                    field_desc += ' # ' + ' '.join(comment_notes)
                yield '    %s' % field_desc
            for meta_line in self.get_meta(table_name):
                yield meta_line
コード例 #2
0
    def handle_inspection(self, options):
        verbosity = options.get('verbosity')
        app = options.get('app')

        connection = connections[options.get('database')]
        # use_extra = connections[options.get('extra')]

        # 'table_name_filter' is a stealth option -- callable that returns True if table name should be processed
        table_name_filter = options.get('table_name_filter')
        if table_name_filter is not None and isinstance(
                table_name_filter, basestring):
            callable_table_name_filter.filter_string = table_name_filter
            table_name_filter = callable_table_name_filter
            # because the parent method checks the stealth option
            options['table_name_filter'] = table_name_filter

        meta = db_meta(app=app,
                       table=table_name_filter,
                       verbosity=int(verbosity))

        if verbosity > 1:
            print meta
        # 'one_table_name' is a new NONstealth option -- string that indicates the one table (or model) that *should* be processed
        #one_table_name = options.get('table')

        table2model = lambda table_name: table_name.title().replace(
            '_', '').replace(' ', '').replace('-', '')
        strip_prefix = lambda s: s.startswith("u'") and s[1:] or s

        cursor = connection.cursor()
        yield "# This is an auto-generated Django model module."
        yield "# You'll have to do the following manually to clean this up:"
        yield "#     * Rearrange models' order"
        yield "#     * Make sure each model has one field with primary_key=True"
        yield "# Feel free to rename the models, but don't rename db_table values or field names."
        yield "#"
        yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'"
        yield "# into your database."
        yield "from __future__ import unicode_literals"
        yield ''
        yield 'from %s import models' % self.db_module
        yield ''
        known_models = []
        print meta.keys()
        print json.dumps(meta, indent=2)
        for table_name in connection.introspection.table_names(cursor):
            if table_name_filter is not None and callable(table_name_filter):
                if not table_name_filter(table_name):
                    continue
            # if one_table_name is not None and (table_name != one_table_name and table2model(table_name) != one_table_name):
            #     continue
            yield 'class %s(models.Model):' % table2model(table_name)
            known_models.append(table2model(table_name))
            try:
                relations = connection.introspection.get_relations(
                    cursor, table_name)
            except NotImplementedError:
                relations = {}
            try:
                indexes = connection.introspection.get_indexes(
                    cursor, table_name)
            except NotImplementedError:
                indexes = get_indexes(meta, table_name)
            used_column_names = [
            ]  # Holds column names used in the table so far
            table_columns = connection.introspection.get_table_description(
                cursor, table_name)
            table_meta = get_meta_tuples(cursor, table_name)
            for i, (row,
                    extra_meta) in enumerate(zip(table_columns, table_meta)):
                #print i
                #print row
                #print extra_meta
                comment_notes = [
                ]  # Holds Field notes, to be displayed in a Python comment.
                extra_params = {
                }  # Holds Field parameters such as 'db_column'.
                column_name = row[0]
                is_relation = i in relations

                att_name, params, notes = self.normalize_col_name(
                    column_name, used_column_names, is_relation)
                extra_params.update(params)
                comment_notes.extend(notes)

                used_column_names.append(att_name)

                # Add primary_key and unique, if necessary.
                if column_name in indexes:
                    if indexes[column_name]['primary_key']:
                        extra_params['primary_key'] = True
                    elif indexes[column_name]['unique']:
                        extra_params['unique'] = True

                if is_relation:
                    rel_to = relations[i][
                        1] == table_name and "'self'" or table2model(
                            relations[i][1])
                    if rel_to in known_models:
                        field_type = 'ForeignKey(%s' % rel_to
                    else:
                        field_type = "ForeignKey('%s'" % rel_to
                else:
                    # Calling `get_field_type` to get the field type string and any
                    # additional paramters and notes.
                    field_type, field_params, field_notes = self.get_field_type(
                        connection, table_name, row)
                    extra_params.update(field_params)
                    comment_notes.extend(field_notes)

                    field_type += '('

                # Don't output 'id = meta.AutoField(primary_key=True)', because
                # that's assumed if it doesn't exist.
                if att_name == 'id' and field_type == 'AutoField(' and extra_params == {
                        'primary_key': True
                }:
                    continue

                # Add 'null' and 'blank', if the 'null_ok' flag was present in the
                # table description.
                if row[6]:  # If it's NULL...
                    extra_params['blank'] = True
                    if not field_type in ('TextField(', 'CharField('):
                        extra_params['null'] = True

                field_desc = '%s = models.%s' % (att_name, field_type)
                if extra_params:
                    if not field_desc.endswith('('):
                        field_desc += ', '
                    field_desc += ', '.join([
                        '%s=%s' % (k, strip_prefix(repr(v)))
                        for k, v in extra_params.items()
                    ])
                field_desc += ')'
                if comment_notes:
                    field_desc += ' # ' + ' '.join(comment_notes)
                yield '    %s' % field_desc
            for meta_line in self.get_meta(table_name):
                yield meta_line
コード例 #3
0
ファイル: inspectdb_ms.py プロジェクト: MiddleFork/pug
    def handle_inspection(self, options):
        verbosity = options.get('verbosity')
        app = options.get('app')

        connection = connections[options.get('database')]
        # use_extra = connections[options.get('extra')]

        # 'table_name_filter' is a stealth option -- callable that returns True if table name should be processed
        table_name_filter = options.get('table_name_filter')
        if table_name_filter is not None and isinstance(table_name_filter, basestring):
            callable_table_name_filter.filter_string = table_name_filter 
            table_name_filter = callable_table_name_filter
            # because the parent method checks the stealth option
            options['table_name_filter'] = table_name_filter

        meta = db_meta(app=app, table=table_name_filter, verbosity=int(verbosity))

        if verbosity > 1:
            print meta
        # 'one_table_name' is a new NONstealth option -- string that indicates the one table (or model) that *should* be processed
        #one_table_name = options.get('table')

        table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
        strip_prefix = lambda s: s.startswith("u'") and s[1:] or s

        cursor = connection.cursor()
        yield "# This is an auto-generated Django model module."
        yield "# You'll have to do the following manually to clean this up:"
        yield "#     * Rearrange models' order"
        yield "#     * Make sure each model has one field with primary_key=True"
        yield "# Feel free to rename the models, but don't rename db_table values or field names."
        yield "#"
        yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'"
        yield "# into your database."
        yield "from __future__ import unicode_literals"
        yield ''
        yield 'from %s import models' % self.db_module
        yield ''
        known_models = []
        print meta.keys()
        print json.dumps(meta, indent=2)
        for table_name in connection.introspection.table_names(cursor):
            if table_name_filter is not None and callable(table_name_filter):
                if not table_name_filter(table_name):
                    continue
            # if one_table_name is not None and (table_name != one_table_name and table2model(table_name) != one_table_name):
            #     continue
            yield 'class %s(models.Model):' % table2model(table_name)
            known_models.append(table2model(table_name))
            try:
                relations = connection.introspection.get_relations(cursor, table_name)
            except NotImplementedError:
                relations = {}
            try:
                indexes = connection.introspection.get_indexes(cursor, table_name)
            except NotImplementedError:
                indexes = get_indexes(meta, table_name)
            used_column_names = [] # Holds column names used in the table so far
            table_columns = connection.introspection.get_table_description(cursor, table_name)
            table_meta = get_meta_tuples(cursor, table_name)
            for i, (row, extra_meta) in enumerate(zip(table_columns, table_meta)):
                #print i
                #print row
                #print extra_meta
                comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
                extra_params = {}  # Holds Field parameters such as 'db_column'.
                column_name = row[0]
                is_relation = i in relations

                att_name, params, notes = self.normalize_col_name(
                    column_name, used_column_names, is_relation)
                extra_params.update(params)
                comment_notes.extend(notes)

                used_column_names.append(att_name)

                # Add primary_key and unique, if necessary.
                if column_name in indexes:
                    if indexes[column_name]['primary_key']:
                        extra_params['primary_key'] = True
                    elif indexes[column_name]['unique']:
                        extra_params['unique'] = True

                if is_relation:
                    rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
                    if rel_to in known_models:
                        field_type = 'ForeignKey(%s' % rel_to
                    else:
                        field_type = "ForeignKey('%s'" % rel_to
                else:
                    # Calling `get_field_type` to get the field type string and any
                    # additional paramters and notes.
                    field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
                    extra_params.update(field_params)
                    comment_notes.extend(field_notes)

                    field_type += '('

                # Don't output 'id = meta.AutoField(primary_key=True)', because
                # that's assumed if it doesn't exist.
                if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}:
                    continue

                # Add 'null' and 'blank', if the 'null_ok' flag was present in the
                # table description.
                if row[6]: # If it's NULL...
                    extra_params['blank'] = True
                    if not field_type in ('TextField(', 'CharField('):
                        extra_params['null'] = True

                field_desc = '%s = models.%s' % (att_name, field_type)
                if extra_params:
                    if not field_desc.endswith('('):
                        field_desc += ', '
                    field_desc += ', '.join([
                        '%s=%s' % (k, strip_prefix(repr(v)))
                        for k, v in extra_params.items()])
                field_desc += ')'
                if comment_notes:
                    field_desc += ' # ' + ' '.join(comment_notes)
                yield '    %s' % field_desc
            for meta_line in self.get_meta(table_name):
                yield meta_line
コード例 #4
0
    def handle_inspection(self, options):
        connection = connections[options.get('database')]
        # 'table_name_filter' is a stealth option
        table_name_filter = options.get('table_name_filter')

        table2model = lambda table_name: table_name.title().replace(
            '_', '').replace(' ', '').replace('-', '')
        strip_prefix = lambda s: s[1:] if s.startswith("u'") else s

        cursor = connection.cursor()
        yield "# This Django model module was generated by [pug](pypi.python.org/pypi/pug)."
        yield "# WARNING: This is pre-alpha software and is likely to break your code!"
        yield "# You'll have to do the following manually to clean this up:"
        yield "#   * Rearrange models' order"
        yield "#   * Make sure each model has one field with primary_key=True   <--- HOPEFULLY MORE ARE GUESSED FOR YOU NOW"
        yield "#   * Remove `managed = False` lines for those models you wish to give write DB access"
        yield "# Feel free to rename the models, but don't rename db_table values or field names."
        yield "#"
        yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'"
        yield "# into your database."
        yield "from __future__ import unicode_literals"
        yield ''
        yield 'from %s import models' % self.db_module
        yield ''
        known_models = []
        for table_name in connection.introspection.table_names(cursor):
            if table_name_filter is not None and callable(table_name_filter):
                if not table_name_filter(table_name):
                    continue
            yield 'class %s(models.Model):' % table2model(table_name)
            known_models.append(table2model(table_name))
            try:
                relations = connection.introspection.get_relations(
                    cursor, table_name)
            except NotImplementedError:
                relations = {}
            try:
                indexes = get_indexes(cursor, table_name)
            except NotImplementedError:
                indexes = {}
            print indexes
            indexes = {}
            used_column_names = [
            ]  # Holds column names used in the table so far
            for i, row in enumerate(
                    connection.introspection.get_table_description(
                        cursor, table_name)):
                comment_notes = [
                ]  # Holds Field notes, to be displayed in a Python comment.
                extra_params = OrderedDict(
                )  # Holds Field parameters such as 'db_column'.
                column_name = row[0]
                is_relation = i in relations

                att_name, params, notes = self.normalize_col_name(
                    column_name, used_column_names, is_relation)
                extra_params.update(params)
                comment_notes.extend(notes)

                used_column_names.append(att_name)

                # Add primary_key and unique, if necessary.
                if column_name in indexes:
                    if indexes[column_name]['primary_key']:
                        extra_params['primary_key'] = True
                    elif indexes[column_name]['unique']:
                        extra_params['unique'] = True

                if is_relation:
                    rel_to = "self" if relations[i][
                        1] == table_name else table2model(relations[i][1])
                    if rel_to in known_models:
                        field_type = 'ForeignKey(%s' % rel_to
                    else:
                        field_type = "ForeignKey('%s'" % rel_to
                else:
                    # Calling `get_field_type` to get the field type string and any
                    # additional paramters and notes.
                    field_type, field_params, field_notes = self.get_field_type(
                        connection, table_name, row)
                    extra_params.update(field_params)
                    comment_notes.extend(field_notes)

                    field_type += '('

                # Don't output 'id = meta.AutoField(primary_key=True)', because
                # that's assumed if it doesn't exist.
                if att_name == 'id' and extra_params == {'primary_key': True}:
                    if field_type == 'AutoField(':
                        continue
                    elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield:
                        comment_notes.append('AutoField?')

                # Add 'null' and 'blank', if the 'null_ok' flag was present in the
                # table description.
                if row[6]:  # If it's NULL...
                    if field_type == 'BooleanField(':
                        field_type = 'NullBooleanField('
                    else:
                        extra_params['blank'] = True
                        if not field_type in ('TextField(', 'CharField('):
                            extra_params['null'] = True

                field_desc = '%s = %s%s' % (
                    att_name,
                    # Custom fields will have a dotted path
                    '' if '.' in field_type else 'models.',
                    field_type,
                )
                if extra_params:
                    if not field_desc.endswith('('):
                        field_desc += ', '
                    field_desc += ', '.join([
                        '%s=%s' % (k, strip_prefix(repr(v)))
                        for k, v in extra_params.items()
                    ])
                field_desc += ')'
                if comment_notes:
                    field_desc += ' # ' + ' '.join(comment_notes)
                yield '    %s' % field_desc
            for meta_line in self.get_meta(table_name):
                yield meta_line