monkey patches django.db.models.sql.compiler.SQL*Compiler series
494307
def patch(self):
        
        from django.db.models.sql import compiler

        self._read_compilers = (
            compiler.SQLCompiler,
            compiler.SQLAggregateCompiler,
            compiler.SQLDateCompiler,
        )
        self._write_compilers = (
            compiler.SQLInsertCompiler,
            compiler.SQLDeleteCompiler,
            compiler.SQLUpdateCompiler,
        )
        if not self._patched:
            self._original = {}
            for reader in self._read_compilers:
                self._original[reader] = reader.execute_sql
                reader.execute_sql = self._monkey_select(reader.execute_sql)
            for updater in self._write_compilers:
                self._original[updater] = updater.execute_sql
                updater.execute_sql = self._monkey_write(updater.execute_sql)
            self._patched = True
            self.cache_backend.patch()
            self._handle_signals()
1039453
def emit_db_sequence_updates(engine):
    """"""

    if engine and engine.name == 'postgresql':
        # not implemented for other RDBMS; necessity unknown
        conn = engine.connect()
        qry = """SELECT 'SELECT last_value FROM ' || n.nspname ||
                         '.' || c.relname || ';' AS qry,
                        n.nspname || '.' || c.relname AS qual_name
                 FROM   pg_namespace n
                 JOIN   pg_class c ON (n.oid = c.relnamespace)
                 WHERE  c.relkind = 'S'"""
        for (qry, qual_name) in list(conn.execute(qry)):
            (lastval, ) = conn.execute(qry).first()
            nextval = int(lastval) + 1
            yield "ALTER SEQUENCE %s RESTART WITH %s;" % (qual_name, nextval)
617425
def patch(patch_inspect=True):
    
    PATCHED['collections.abc.Generator'] = _collections_abc.Generator = Generator
    PATCHED['collections.abc.Coroutine'] = _collections_abc.Coroutine = Coroutine
    PATCHED['collections.abc.Awaitable'] = _collections_abc.Awaitable = Awaitable

    if patch_inspect:
        import inspect
        PATCHED['inspect.isawaitable'] = inspect.isawaitable = isawaitable
165813
def generate_sql_changes(self):
        
        from_keys = set(self.from_sql_graph.nodes.keys())
        to_keys = set(self.to_sql_graph.nodes.keys())
        new_keys = to_keys - from_keys
        delete_keys = from_keys - to_keys
        changed_keys = set()
        dep_changed_keys = []

        for key in from_keys & to_keys:
            old_node = self.from_sql_graph.nodes[key]
            new_node = self.to_sql_graph.nodes[key]

            # identify SQL changes -- these will alter database.
            if not is_sql_equal(old_node.sql, new_node.sql):
                changed_keys.add(key)

            # identify dependencies change
            old_deps = self.from_sql_graph.dependencies[key]
            new_deps = self.to_sql_graph.dependencies[key]
            removed_deps = old_deps - new_deps
            added_deps = new_deps - old_deps
            if removed_deps or added_deps:
                dep_changed_keys.append((key, removed_deps, added_deps))

        # we do basic sort here and inject dependency keys here.
        # operations built using these keys will properly set operation dependencies which will
        # enforce django to build/keep a correct order of operations (stable_topological_sort).
        keys = self.assemble_changes(new_keys, changed_keys, self.to_sql_graph)
        delete_keys = self.assemble_changes(delete_keys, set(), self.from_sql_graph)

        self._sql_operations = {}
        self._generate_reversed_sql(keys, changed_keys)
        self._generate_sql(keys, changed_keys)
        self._generate_delete_sql(delete_keys)
        self._generate_altered_sql_dependencies(dep_changed_keys)
1075588
def _log_unicode_errors(logger, log_level):
    
    def log_debug_render(*args, **kwargs):
        try:
            return debug_variable_node_render(*args, **kwargs)
        except UnicodeDecodeError:
            logger.log(
                log_level,
                "UnicodeDecodeError in template rendering",
                exc_info=True)
        return ''

    def log_render(*args, **kwargs):
        try:
            return variable_node_render(*args, **kwargs)
        except UnicodeDecodeError:
            logger.log(
                log_level,
                "UnicodeDecodeError in template rendering",
                exc_info=True)
        return ''

    patch_base = patch.object(VariableNode, 'render', log_render)
    patch_all = patch_base
    if django.VERSION < (1, 9):
        from django.template.debug import DebugVariableNode
        patch_debug = patch.object(DebugVariableNode, 'render',
                                   log_debug_render)
        patch_all = _compose(patch_all, patch_debug)
    return lambda f: patch_all(f)
964940
function monkeypatch(content, next) {
        if (monkeyPatched(content)) return complete();

        _log('monkey patch %s', filePath);
        processor(content, next);
      }
745162
def patch_pymongo(config):
    

    # Nothing to change!
    if not config["print_mongodb"] and not config["trace_io"]:
        return

    from termcolor import cprint

    # Print because we are very early and log() may not be ready yet.
    cprint("Monkey-patching MongoDB methods...", "white")

    def gen_monkey_patch(base_object, method):
        base_method = getattr(base_object, method)

        def mrq_monkey_patched(self, *args, **kwargs):

            if config["trace_io"]:
                comment = "mrq"

                worker = get_current_worker()
                job = get_current_job()
                if job:
                    job.set_current_io({
                        "type": "mongodb.%s" % method,
                        "data": {
                            "collection": self.full_name
                        }
                        # Perf issue? All MongoDB data will get jsonified!
                        # "data": json.dumps(args)[0:300]
                    })
                    comment = {"job": job.id}
                elif worker:
                    comment = {"worker": worker.id}

                # Tag potentially expensive queries with their job id for easier debugging
                if method in ["find", "find_and_modify", "count", "update_many", "update", "delete_many"]:
                    if len(args) > 0 and isinstance(args[0], dict) and "$comment" not in args[0]:
                        query = copy.copy(args[0])
                        query["$comment"] = comment
                        args = (query, ) + args[1:]

            if config["print_mongodb"]:
                if self.full_name in config.get("print_mongodb_hidden_collections", []):
                    cprint("[MONGO] %s.%s%s %s" % (
                        self.full_name, method, "-hidden-", kwargs
                    ), "magenta")
                else:
                    cprint("[MONGO] %s.%s%s %s" % (
                        self.full_name, method, args, kwargs
                    ), "magenta")

            if config.get("mongodb_pre_hook"):
                config.get("mongodb_pre_hook")({
                    "collection": self.full_name,
                    "method": method,
                    "args": args,
                    "kwargs": kwargs,
                    "client": self.database.client,
                    "job": job
                })

            start_time = time.time()
            ret = False
            try:
                ret = base_method(self, *args, **kwargs)
            finally:
                stop_time = time.time()

                job = None

                if config["trace_io"]:
                    job = get_current_job()
                    if job:
                        job.set_current_io(None)

                if config.get("mongodb_post_hook"):
                    config.get("mongodb_post_hook")({
                        "collection": self.full_name,
                        "method": method,
                        "args": args,
                        "kwargs": kwargs,
                        "client": self.database.client,
                        "job": job,
                        "result": ret,
                        "time": stop_time - start_time
                    })

            return ret

        # Needed to avoid breaking mongokit
        mrq_monkey_patched.__doc__ = method.__doc__

        return mrq_monkey_patched

    from pymongo.collection import Collection
    pymongo_method_whitelist = (
        "bulk_write",
        "find", "find_one_and_delete", "find_one_and_replace", "find_one_and_update",
        "update", "update_one", "update_many",
        "drop",
        "count",
        "save",
        "insert", "insert_one", "insert_many",
        "replace_one",
        "remove", "delete_one", "delete_many",
        "find_and_modify",
        "parallel_scan",
        "options",
        "aggregate",
        "group", "distinct",
        "rename",
        "map_reduce", "inline_map_reduce",
        "create_indexes", "create_index", "ensure_index", "drop_index", "reindex", "list_indexes"
    )
    for method in pymongo_method_whitelist:
        if hasattr(Collection, method) and getattr(Collection, method).__name__ != "mrq_monkey_patched":
            setattr(Collection, method, gen_monkey_patch(Collection, method))
825876
def install_all_patches():
    
    from . import mysqldb
    from . import psycopg2
    from . import strict_redis
    from . import sqlalchemy
    from . import tornado_http
    from . import urllib
    from . import urllib2
    from . import requests

    mysqldb.install_patches()
    psycopg2.install_patches()
    strict_redis.install_patches()
    sqlalchemy.install_patches()
    tornado_http.install_patches()
    urllib.install_patches()
    urllib2.install_patches()
    requests.install_patches()
1248417
def patch(attrs, updates):
    """"""
    orig = {}
    for attr, value in updates:
        orig[attr] = attrs[attr]
        attrs[attr] = value
    return orig
462703
def compiled_orm_imports(self):
        """"""
        module = 'sqlalchemy.orm'
        labels = []
        if self.relationship_definitions:
            labels.append("relationship")
        return ALCHEMY_TEMPLATES.named_import.safe_substitute(module=module, labels=", ".join(labels))
525780
def compile(self):
        
        params = self.column_params + self.join_params + self.params
        if self.limit and self.limit >= 0:
            self.sql_limit = 'LIMIT ?'
            params += [self.limit]
        return (self.sql, params, self.keys)
272478
def apply_global_fixes(source, options, where='global', filename=''):
    
    if any(code_match(code, select=options.select, ignore=options.ignore)
           for code in ['E101', 'E111']):
        source = reindent(source,
                          indent_size=options.indent_size)

    for (code, function) in global_fixes():
        if code_match(code, select=options.select, ignore=options.ignore):
            if options.verbose:
                print('--->  Applying {0} fix for {1}'.format(where,
                                                              code.upper()),
                      file=sys.stderr)
            source = function(source,
                              aggressive=options.aggressive)

    source = fix_2to3(source,
                      aggressive=options.aggressive,
                      select=options.select,
                      ignore=options.ignore,
                      filename=filename)

    return source
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')
1152156
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_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')
1278866
def compile_update(self, query, values):
        
        table = self.wrap_table(query.from__)

        columns = self._compile_update_columns(values)

        from_ = self._compile_update_from(query)

        where = self._compile_update_wheres(query)

        return ("UPDATE %s SET %s%s %s" % (table, columns, from_, where)).strip()
1078018
def patches(self, dwn, install, comp_sum, uncomp_sum):
        
        dwnp, installp, comp_sump, uncomp_sump = ([] for i in range(4))
        for d, i, c, u in zip(dwn, install, comp_sum, uncomp_sum):
            if "_slack" + slack_ver() in i:
                dwnp.append(d)
                dwn.remove(d)
                installp.append(i)
                install.remove(i)
                comp_sump.append(c)
                comp_sum.remove(c)
                uncomp_sump.append(u)
                uncomp_sum.remove(u)
        if "--patches" in self.flag:
            return dwnp, installp, comp_sump, uncomp_sump
        return dwn, install, comp_sum, uncomp_sum
988194
def update(self, **kwargs):
        
        super(ModelQuerySet, self).update(_changed=True, **kwargs)