If installed this causes Django's queries to be captured.
322949
def install_sql_hook():
    """"""
    try:
        from django.db.backends.utils import CursorWrapper
    except ImportError:
        from django.db.backends.util import CursorWrapper

    try:
        real_execute = CursorWrapper.execute
        real_executemany = CursorWrapper.executemany
    except AttributeError:
        # XXX(mitsuhiko): On some very old django versions (<1.6) this
        # trickery would have to look different but I can't be bothered.
        return

    def record_sql(vendor, alias, start, duration, sql, params):
        def processor(data):
            real_sql, real_params = format_sql(sql, params)
            if real_params:
                real_sql = real_sql % tuple(real_params)
            # maybe category to 'django.%s.%s' % (vendor, alias or
            #   'default') ?
            data.update({
                'message': real_sql,
                'category': 'query',
            })
        breadcrumbs.record(processor=processor)

    def record_many_sql(vendor, alias, start, sql, param_list):
        duration = time.time() - start
        for params in param_list:
            record_sql(vendor, alias, start, duration, sql, params)

    def execute(self, sql, params=None):
        start = time.time()
        try:
            return real_execute(self, sql, params)
        finally:
            record_sql(self.db.vendor, getattr(self.db, 'alias', None),
                       start, time.time() - start, sql, params)

    def executemany(self, sql, param_list):
        start = time.time()
        try:
            return real_executemany(self, sql, param_list)
        finally:
            record_many_sql(self.db.vendor, getattr(self.db, 'alias', None),
                            start, sql, param_list)

    CursorWrapper.execute = execute
    CursorWrapper.executemany = executemany
    breadcrumbs.ignore_logger('django.db.backends')
467641
def autodiscover():
    
    import copy
    from django.conf import settings
    from django.utils.importlib import import_module

    for app in settings.INSTALLED_APPS:
        # Attempt to import the app's gargoyle module.
        before_import_registry = copy.copy(gargoyle._registry)
        try:
            import_module('%s.gargoyle' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            gargoyle._registry = before_import_registry

    # load builtins
    __import__('gargoyle.builtins')
415199
def autodiscover_modules():
    
    import imp
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        try:
            __import__(app)
            app_path = sys.modules[app].__path__
        except AttributeError:
            continue
        try:
            imp.find_module('permissions', app_path)
        except ImportError:
            continue
        __import__("%s.permissions" % app)
        app_path = sys.modules["%s.permissions" % app]
    LOADING = False
1024614
def _build_models_query(self, query):
        
        registered_models_ct = self.build_models_list()
        if registered_models_ct:
            restrictions = [xapian.Query('%s%s' % (TERM_PREFIXES[DJANGO_CT], model_ct))
                            for model_ct in registered_models_ct]
            limit_query = xapian.Query(xapian.Query.OP_OR, restrictions)

            query = xapian.Query(xapian.Query.OP_AND, query, limit_query)

        return query
18172
def _import_plugins(self):
        
        if self.detected:
            return

        # In some cases, plugin scanning may start during a request.
        # Make sure there is only one thread scanning for plugins.
        self.scanLock.acquire()
        if self.detected:
            return  # previous threaded released + completed

        try:
            import_apps_submodule("content_plugins")
            self.detected = True
        finally:
            self.scanLock.release()
461541
def extract_queries(self, args, kwargs):
        '''
            
        '''
        return super(POSTGRESExtPillar, self).extract_queries(args, kwargs)
1200384
def query(self):
        
        output = Query()
        for column, op, plugin, editor in self._plugins:
            query = Query(column)
            if plugin.setupQuery(query, op, editor):
                output &= query
        return output
922517
def queryset(self, request):
        
        qs = super(MultilingualInlineAdmin, self).queryset(request)
        # Don't now what the hell I was thinking here, but this code breaks stuff:
        #
        # checkfield = self.get_fill_check_field()
        # if checkfield is not None:
        #     kwargs = {str('%s_%s__isnull' % (checkfield, GLL.language_code)): False}
        #     from django.db.models.fields import CharField
        #     if isinstance(self.model._meta.translation_model._meta.get_field_by_name(checkfield)[0], CharField):
        #         kwargs[str('%s_%s__gt' % (checkfield, GLL.language_code))] = ''
        #     return qs.filter(**kwargs)
        return qs.filter(translations__language_code=GLL.language_code).distinct()
1362589
def filter(self, *query_filter):
        '''
        '''
        for query in query_filter:
            self.query.append(query)
        return self
1206022
def patch_db_connections():
    

    global __already_patched

    if not __already_patched:
        from django.db import connections

        connections._connections = local(connections._connections)
        __already_patched = True
1357387
public void logInsertQueriesForCurrentThread() {
		List<String> queries = getInsertQueriesForCurrentThread()
			.stream()
			.map(CircularQueueCaptureQueriesListener::formatQueryAsSql)
			.collect(Collectors.toList());
		ourLog.info("Insert Queries:\n{}", String.join("\n", queries));
	}
1122293
def add_constraints(self):
        
        if self._constraints:
            self._query.where(self._foreign_key, "=", self.get_parent_key())
1105332
public void logInsertQueries() {
		List<String> queries = getInsertQueries()
			.stream()
			.map(CircularQueueCaptureQueriesListener::formatQueryAsSql)
			.collect(Collectors.toList());
		ourLog.info("Insert Queries:\n{}", String.join("\n", queries));
	}
880085
def add_filter(self, filter_expr, connector=AND, negate=False, trim=False,
            can_reuse=None, process_extras=True, force_having=False):
        
        if force_having:
            import warnings
            warnings.warn("multilingual-ng doesn't support force_having (see Django ticket #11293)")
        arg, value = filter_expr
        parts = arg.split(LOOKUP_SEP)
        if not parts:
            raise FieldError("Cannot parse keyword query %r" % arg)

        # Work out the lookup type and remove it from 'parts', if necessary.
        if len(parts) == 1 or parts[-1] not in self.query_terms:
            lookup_type = 'exact'
        else:
            lookup_type = parts.pop()

        # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
        # uses of None as a query value.
        if value is None:
            if lookup_type != 'exact':
                raise ValueError("Cannot use None as a query value")
            lookup_type = 'isnull'
            value = True
        elif (value == '' and lookup_type == 'exact' and
              self.get_compiler(DEFAULT_DB_ALIAS).connection.features.interprets_empty_strings_as_nulls):
            lookup_type = 'isnull'
            value = True
        elif callable(value):
            value = value()

        opts = self.get_meta()
        alias = self.get_initial_alias()
        allow_many = trim or not negate

        try:
            field, target, opts, join_list, last, extra_filters = self.setup_joins(
                    parts, opts, alias, True, allow_many, can_reuse=can_reuse,
                    negate=negate, process_extras=process_extras)
        except MultiJoin, e:
            self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
                    can_reuse)
            return

        #=======================================================================
        # Django Mulitlingual NG Specific Code START
        #=======================================================================
        if hasattr(opts, 'translation_model'):
            field_name = parts[-1]
            if field_name == 'pk':
                field_name = opts.pk.name
            translation_opts = opts.translation_model._meta
            if field_name in translation_opts.translated_fields.keys():
                field, model, direct, m2m = opts.get_field_by_name(field_name)
                if model == opts.translation_model:
                    language_code = translation_opts.translated_fields[field_name][1]
                    if language_code is None:
                        language_code = get_default_language()
                    master_table_name = opts.db_table
                    trans_table_alias = get_translation_table_alias(
                        model._meta.db_table, language_code)
                    new_table = (master_table_name + "__" + trans_table_alias)
                    self.where.add(constraint_tuple(new_table, field.column, field, lookup_type, value), connector)
                    return
        #=======================================================================
        # Django Mulitlingual NG Specific Code END
        #=======================================================================
        final = len(join_list)
        penultimate = last.pop()
        if penultimate == final:
            penultimate = last.pop()
        if trim and len(join_list) > 1:
            extra = join_list[penultimate:]
            join_list = join_list[:penultimate]
            final = penultimate
            penultimate = last.pop()
            col = self.alias_map[extra[0]][LHS_JOIN_COL]
            for alias in extra:
                self.unref_alias(alias)
        else:
            col = target.column
        alias = join_list[-1]

        while final > 1:
            # An optimization: if the final join is against the same column as
            # we are comparing against, we can go back one step in the join
            # chain and compare against the lhs of the join instead (and then
            # repeat the optimization). The result, potentially, involves less
            # table joins.
            join = self.alias_map[alias]
            if col != join[RHS_JOIN_COL]:
                break
            self.unref_alias(alias)
            alias = join[LHS_ALIAS]
            col = join[LHS_JOIN_COL]
            join_list = join_list[:-1]
            final -= 1
            if final == penultimate:
                penultimate = last.pop()

        if (lookup_type == 'isnull' and value is True and not negate and
                final > 1):
            # If the comparison is against NULL, we need to use a left outer
            # join when connecting to the previous model. We make that
            # adjustment here. We don't do this unless needed as it's less
            # efficient at the database level.
            self.promote_alias(join_list[penultimate])

        if connector == OR:
            # Some joins may need to be promoted when adding a new filter to a
            # disjunction. We walk the list of new joins and where it diverges
            # from any previous joins (ref count is 1 in the table list), we
            # make the new additions (and any existing ones not used in the new
            # join list) an outer join.
            join_it = iter(join_list)
            table_it = iter(self.tables)
            join_it.next(), table_it.next()
            table_promote = False
            join_promote = False
            for join in join_it:
                table = table_it.next()
                if join == table and self.alias_refcount[join] > 1:
                    continue
                join_promote = self.promote_alias(join)
                if table != join:
                    table_promote = self.promote_alias(table)
                break
            self.promote_alias_chain(join_it, join_promote)
            self.promote_alias_chain(table_it, table_promote)

        self.where.add(constraint_tuple(alias, col, field, lookup_type, value), connector)

        if negate:
            self.promote_alias_chain(join_list)
            if lookup_type != 'isnull':
                if final > 1:
                    for alias in join_list:
                        if self.alias_map[alias][JOIN_TYPE] == self.LOUTER:
                            j_col = self.alias_map[alias][RHS_JOIN_COL]
                            entry = self.where_class()
                            entry.add(constraint_tuple(alias, j_col, None, 'isnull', True), AND)
                            entry.negate()
                            self.where.add(entry, AND)
                            break
                elif not (lookup_type == 'in' and not value) and field.null:
                    # Leaky abstraction artifact: We have to specifically
                    # exclude the "foo__in=[]" case from this handling, because
                    # it's short-circuited in the Where class.
                    entry = self.where_class()
                    entry.add(constraint_tuple(alias, col, None, 'isnull', True), AND)
                    entry.negate()
                    self.where.add(entry, AND)

        if can_reuse is not None:
            can_reuse.update(join_list)
        if process_extras:
            for filter in extra_filters:
                self.add_filter(filter, negate=negate, can_reuse=can_reuse,
                        process_extras=False)
125632
def check_db_connection():
    '''
    
    '''
    # mysql is lazily connected to in django.
    # connection.connection is None means
    # you have not connected to mysql before
    if connection.connection and not connection.is_usable():
        # destroy the default mysql connection
        # after this line, when you use ORM methods
        # django will reconnect to the default mysql
        logger.debug('deleted default connection')
        del connections._connections.default
42031
public static void checkQuery(Query<?> query, InjectionManager manager) {
        checkQuery(query, null, null, manager);
    }
586814
def include(self, *fields, **kwargs):
        
        clone = self._clone()

        # Preserve the stickiness of related querysets
        # NOTE: by default _clone will clear this attribute
        # .include does not modify the actual query, so we
        # should not clear `filter_is_sticky`
        if self.query.filter_is_sticky:
            clone.query.filter_is_sticky = True

        clone._include_limit = kwargs.pop('limit_includes', None)
        assert not kwargs, '"limit_includes" is the only accepted kwargs. Eat your heart out 2.7'

        # Copy the behavior of .select_related(None)
        if fields == (None, ):
            for field in clone._includes.keys():
                clone.query._annotations.pop('__{}'.format(field.name), None)
            clone._includes.clear()
            return clone

        # Parse everything the way django handles joins/select related
        # Including multiple child fields ie .include(field1__field2, field1__field3)
        # turns into {field1: {field2: {}, field3: {}}
        for name in fields:
            ctx, model = clone._includes, clone.model
            for spl in name.split('__'):
                field = model._meta.get_field(spl)
                if isinstance(field, ForeignObjectRel) and field.is_hidden():
                    raise ValueError('Hidden field "{!r}" has no descriptor and therefore cannot be included'.format(field))
                model = field.related_model
                ctx = ctx.setdefault(field, OrderedDict())

        for field in clone._includes.keys():
            clone._include(field)

        return clone