Ticket #1763: db_fix.patch

File db_fix.patch, 21.6 KB (added by crankycoder@…, 18 years ago)

Updated the patch sync with django svn head at revision 3046

  • django/db/models/base.py

     
    77from django.db.models.related import RelatedObject
    88from django.db.models.query import orderlist2sql, delete_objects
    99from django.db.models.options import Options, AdminOptions
    10 from django.db import connection, backend, transaction
     10from django.db import backend, transaction
     11import django.db
    1112from django.db.models import signals
    1213from django.db.models.loading import register_models
    1314from django.dispatch import dispatcher
     
    149150        dispatcher.send(signal=signals.pre_save, sender=self.__class__, instance=self)
    150151
    151152        non_pks = [f for f in self._meta.fields if not f.primary_key]
    152         cursor = connection.cursor()
     153        cursor = django.db.connection.cursor()
    153154
    154155        # First, try an UPDATE. If that doesn't update anything, do an INSERT.
    155156        pk_val = self._get_pk_val()
     
    361362        rel = rel_field.rel.to
    362363        m2m_table = rel_field.m2m_db_table()
    363364        this_id = self._get_pk_val()
    364         cursor = connection.cursor()
     365        cursor = django.db.connection.cursor()
    365366        cursor.execute("DELETE FROM %s WHERE %s = %%s" % \
    366367            (backend.quote_name(m2m_table),
    367368            backend.quote_name(rel_field.m2m_column_name())), [this_id])
     
    379380# ORDERING METHODS #########################
    380381
    381382def method_set_order(ordered_obj, self, id_list):
    382     cursor = connection.cursor()
     383    cursor = django.db.connection.cursor()
    383384    # Example: "UPDATE poll_choices SET _order = %s WHERE poll_id = %s AND id = %s"
    384385    sql = "UPDATE %s SET %s = %%s WHERE %s = %%s AND %s = %%s" % \
    385386        (backend.quote_name(ordered_obj.db_table), backend.quote_name('_order'),
     
    390391    transaction.commit_unless_managed()
    391392
    392393def method_get_order(ordered_obj, self):
    393     cursor = connection.cursor()
     394    cursor = django.db.connection.cursor()
    394395    # Example: "SELECT id FROM poll_choices WHERE poll_id = %s ORDER BY _order"
    395396    sql = "SELECT %s FROM %s WHERE %s = %%s ORDER BY %s" % \
    396397        (backend.quote_name(ordered_obj._meta.pk.column),
  • django/db/models/manager.py

     
    11from django.utils.functional import curry
    2 from django.db import backend, connection
     2from django.db import backend
    33from django.db.models.query import QuerySet
    44from django.dispatch import dispatcher
    55from django.db.models import signals
  • django/db/models/fields/related.py

     
    1 from django.db import backend, connection, transaction
     1from django.db import backend, transaction
    22from django.db.models import signals
    33from django.db.models.fields import AutoField, Field, IntegerField, get_ul_class
    44from django.db.models.related import RelatedObject
     
    77from django.core import validators
    88from django import forms
    99from django.dispatch import dispatcher
     10import django.db
    1011
    1112# For Python 2.3
    1213if not hasattr(__builtins__, 'set'):
     
    282283            # source_col_name: the PK colname in join_table for the source object
    283284            # target_col_name: the PK colname in join_table for the target object
    284285            # *objs - objects to add
    285             from django.db import connection
    286286
    287287            # Add the newly created or already existing objects to the join table.
    288288            # First find out which items are already added, to avoid adding them twice
    289289            new_ids = set([obj._get_pk_val() for obj in objs])
    290             cursor = connection.cursor()
     290            cursor = django.db.connection.cursor()
    291291            cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \
    292292                (target_col_name, self.join_table, source_col_name,
    293293                target_col_name, ",".join(['%s'] * len(new_ids))),
     
    308308            # source_col_name: the PK colname in join_table for the source object
    309309            # target_col_name: the PK colname in join_table for the target object
    310310            # *objs - objects to remove
    311             from django.db import connection
    312311
    313312            for obj in objs:
    314313                if not isinstance(obj, self.model):
    315314                    raise ValueError, "objects to remove() must be %s instances" % self.model._meta.object_name
    316315            # Remove the specified objects from the join table
    317             cursor = connection.cursor()
     316            cursor = django.db.connection.cursor()
    318317            for obj in objs:
    319318                cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s = %%s" % \
    320319                    (self.join_table, source_col_name, target_col_name),
     
    323322
    324323        def _clear_items(self, source_col_name):
    325324            # source_col_name: the PK colname in join_table for the source object
    326             from django.db import connection
    327             cursor = connection.cursor()
     325            cursor = django.db.connection.cursor()
    328326            cursor.execute("DELETE FROM %s WHERE %s = %%s" % \
    329327                (self.join_table, source_col_name),
    330328                [self._pk_val])
  • django/db/models/__init__.py

     
    11from django.conf import settings
    22from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
    33from django.core import validators
    4 from django.db import backend, connection
     4from django.db import backend
    55from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
    66from django.db.models.query import Q
    77from django.db.models.manager import Manager
  • django/db/models/query.py

     
    1 from django.db import backend, connection, transaction
     1from django.db import backend, transaction
     2import django.db
    23from django.db.models.fields import DateField, FieldDoesNotExist
    34from django.db.models import signals
    45from django.dispatch import dispatcher
     
    158159        # undefined, so we convert it to a list of tuples.
    159160        extra_select = self._select.items()
    160161
    161         cursor = connection.cursor()
     162        cursor = django.db.connection.cursor()
    162163        select, sql, params = self._get_sql_clause()
    163164        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
    164165        fill_cache = self._select_related
     
    184185        counter._limit = None
    185186        counter._select_related = False
    186187        select, sql, params = counter._get_sql_clause()
    187         cursor = connection.cursor()
     188        cursor = django.db.connection.cursor()
    188189        if self._distinct:
    189190            id_col = "%s.%s" % (backend.quote_name(self.model._meta.db_table),
    190191                    backend.quote_name(self.model._meta.pk.column))
     
    488489            columns = [f.column for f in self.model._meta.fields]
    489490            field_names = [f.attname for f in self.model._meta.fields]
    490491
    491         cursor = connection.cursor()
     492        cursor = django.db.connection.cursor()
    492493        select, sql, params = self._get_sql_clause()
    493494        select = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns]
    494495        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
     
    515516        sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1 %s' % \
    516517            (backend.get_date_trunc_sql(self._kind, '%s.%s' % (backend.quote_name(self.model._meta.db_table),
    517518            backend.quote_name(self._field.column))), sql, self._order)
    518         cursor = connection.cursor()
     519        cursor = django.db.connection.cursor()
    519520        cursor.execute(sql, params)
    520521        # We have to manually run typecast_timestamp(str()) on the results, because
    521522        # MySQL doesn't automatically cast the result of date functions as datetime
     
    863864    ordered_classes = seen_objs.keys()
    864865    ordered_classes.reverse()
    865866
    866     cursor = connection.cursor()
     867    cursor = django.db.connection.cursor()
    867868
    868869    for cls in ordered_classes:
    869870        seen_objs[cls] = seen_objs[cls].items()
  • django/db/transaction.py

     
    1616    import thread
    1717except ImportError:
    1818    import dummy_thread as thread
    19 from django.db import connection
     19import django.db
    2020from django.conf import settings
    2121
    2222class TransactionManagementError(Exception):
     
    123123    if top:
    124124        top[-1] = flag
    125125        if not flag and is_dirty():
    126             connection._commit()
     126            django.db.connection._commit()
    127127            set_clean()
    128128    else:
    129129        raise TransactionManagementError("This code isn't under transaction management")
     
    133133    Commits changes if the system is not in managed transaction mode.
    134134    """
    135135    if not is_managed():
    136         connection._commit()
     136        django.db.connection._commit()
    137137    else:
    138138        set_dirty()
    139139
     
    142142    Rolls back changes if the system is not in managed transaction mode.
    143143    """
    144144    if not is_managed():
    145         connection._rollback()
     145        django.db.connection._rollback()
    146146    else:
    147147        set_dirty()
    148148
     
    150150    """
    151151    Does the commit itself and resets the dirty flag.
    152152    """
    153     connection._commit()
     153    django.db.connection._commit()
    154154    set_clean()
    155155
    156156def rollback():
    157157    """
    158158    This function does the rollback itself and resets the dirty flag.
    159159    """
    160     connection._rollback()
     160    django.db.connection._rollback()
    161161    set_clean()
    162162
    163163##############
  • django/core/context_processors.py

     
    2525    context_extras = {}
    2626    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
    2727        context_extras['debug'] = True
    28         from django.db import connection
    29         context_extras['sql_queries'] = connection.queries
     28        import django.db
     29        context_extras['sql_queries'] = django.db.connection.queries
    3030    return context_extras
    3131
    3232def i18n(request):
  • django/core/cache/backends/db.py

     
    11"Database cache backend."
    22
    33from django.core.cache.backends.base import BaseCache
    4 from django.db import connection, transaction
     4from django.db import transaction
    55import base64, time
    66from datetime import datetime
    77try:
     
    2525            self._cull_frequency = 3
    2626
    2727    def get(self, key, default=None):
    28         cursor = connection.cursor()
     28        cursor = django.db.connection.cursor()
    2929        cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % self._table, [key])
    3030        row = cursor.fetchone()
    3131        if row is None:
     
    4040    def set(self, key, value, timeout=None):
    4141        if timeout is None:
    4242            timeout = self.default_timeout
    43         cursor = connection.cursor()
     43        cursor = django.db.connection.cursor()
    4444        cursor.execute("SELECT COUNT(*) FROM %s" % self._table)
    4545        num = cursor.fetchone()[0]
    4646        now = datetime.now().replace(microsecond=0)
     
    6161            transaction.commit_unless_managed()
    6262
    6363    def delete(self, key):
    64         cursor = connection.cursor()
     64        cursor = django.db.connection.cursor()
    6565        cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key])
    6666        transaction.commit_unless_managed()
    6767
    6868    def has_key(self, key):
    69         cursor = connection.cursor()
     69        cursor = django.db.connection.cursor()
    7070        cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key])
    7171        return cursor.fetchone() is not None
    7272
  • django/core/management.py

     
    6363
    6464def _get_table_list():
    6565    "Gets a list of all db tables that are physically installed."
    66     from django.db import connection, get_introspection_module
    67     cursor = connection.cursor()
     66    from django.db import get_introspection_module
     67    cursor = django.db.connection.cursor()
    6868    return get_introspection_module().get_table_list(cursor)
    6969
    7070# If the foreign key points to an AutoField, a PositiveIntegerField or a
     
    244244
    245245def get_sql_delete(app):
    246246    "Returns a list of the DROP TABLE SQL statements for the given app."
    247     from django.db import backend, connection, models, get_introspection_module
     247    from django.db import backend, models, get_introspection_module
    248248    introspection = get_introspection_module()
    249249
    250250    # This should work even if a connecton isn't available
    251251    try:
    252         cursor = connection.cursor()
     252        cursor = django.db.connection.cursor()
    253253    except:
    254254        cursor = None
    255255
     
    308308    # directly into a database client, to avoid locking issues.
    309309    if cursor:
    310310        cursor.close()
    311         connection.close()
     311        django.db.connection.close()
    312312
    313313    return output[::-1] # Reverse it, to deal with table dependencies.
    314314get_sql_delete.help_doc = "Prints the DROP TABLE SQL statements for the given app name(s)."
     
    419419
    420420def syncdb():
    421421    "Creates the database tables for all apps in INSTALLED_APPS whose tables haven't already been created."
    422     from django.db import connection, transaction, models, get_creation_module
     422    from django.db import transaction, models, get_creation_module
    423423    from django.db.models import signals
    424424    from django.conf import settings
    425425    from django.dispatch import dispatcher
     
    439439
    440440    data_types = get_creation_module().DATA_TYPES
    441441
    442     cursor = connection.cursor()
     442    cursor = django.db.connection.cursor()
    443443
    444444    # Get a list of all existing database tables,
    445445    # so we know what needs to be added.
     
    554554
    555555def install(app):
    556556    "Executes the equivalent of 'get_sql_all' in the current database."
    557     from django.db import connection, transaction
     557    from django.db import transaction
    558558
    559559    app_name = app.__name__.split('.')[-2]
    560560
     
    566566    sql_list = get_sql_all(app)
    567567
    568568    try:
    569         cursor = connection.cursor()
     569        cursor = django.db.connection.cursor()
    570570        for sql in sql_list:
    571571            cursor.execute(sql)
    572572    except Exception, e:
     
    584584
    585585def reset(app):
    586586    "Executes the equivalent of 'get_sql_reset' in the current database."
    587     from django.db import connection, transaction
     587    from django.db import transaction
    588588    from cStringIO import StringIO
    589589    app_name = app.__name__.split('.')[-2]
    590590
     
    602602Type 'yes' to continue, or 'no' to cancel: """)
    603603    if confirm == 'yes':
    604604        try:
    605             cursor = connection.cursor()
     605            cursor = django.db.connection.cursor()
    606606            for sql in sql_list:
    607607                cursor.execute(sql)
    608608        except Exception, e:
     
    684684
    685685def inspectdb():
    686686    "Generator that introspects the tables in the given database name and returns a Django model, one line at a time."
    687     from django.db import connection, get_introspection_module
     687    from django.db import get_introspection_module
    688688    from django.conf import settings
    689689    import keyword
    690690
     
    694694        object_name = table_name.title().replace('_', '')
    695695        return object_name.endswith('s') and object_name[:-1] or object_name
    696696
    697     cursor = connection.cursor()
     697    cursor = django.db.connection.cursor()
    698698    yield "# This is an auto-generated Django model module."
    699699    yield "# You'll have to do the following manually to clean this up:"
    700700    yield "#     * Rearrange models' order"
     
    10141014
    10151015def createcachetable(tablename):
    10161016    "Creates the table needed to use the SQL cache backend"
    1017     from django.db import backend, connection, transaction, get_creation_module, models
     1017    from django.db import backend, transaction, get_creation_module, models
    10181018    data_types = get_creation_module().DATA_TYPES
    10191019    fields = (
    10201020        # "key" is a reserved word in MySQL, so use "cache_key" instead.
     
    10411041    for i, line in enumerate(table_output):
    10421042        full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
    10431043    full_statement.append(');')
    1044     curs = connection.cursor()
     1044    curs = django.db.connection.cursor()
    10451045    curs.execute("\n".join(full_statement))
    10461046    for statement in index_output:
    10471047        curs.execute(statement)
  • django/contrib/auth/models.py

     
    11from django.core import validators
    2 from django.db import backend, connection, models
     2from django.db import backend, models
     3import django.db
    34from django.contrib.contenttypes.models import ContentType
    45from django.utils.translation import gettext_lazy as _
    56import datetime
     
    130131        "Returns a list of permission strings that this user has through his/her groups."
    131132        if not hasattr(self, '_group_perm_cache'):
    132133            import sets
    133             cursor = connection.cursor()
     134            cursor = django.db.connection.cursor()
    134135            # The SQL below works out to the following, after DB quoting:
    135136            # cursor.execute("""
    136137            #     SELECT ct."app_label", p."codename"
  • django/bin/daily_cleanup.py

     
    11"Daily cleanup file"
    22
    3 from django.db import backend, connection, transaction
     3from django.db import backend, transaction
     4import django.db
    45
    56DOCUMENTATION_DIRECTORY = '/home/html/documentation/'
    67
    78def clean_up():
    89    # Clean up old database records
    9     cursor = connection.cursor()
     10    cursor = django.db.connection.cursor()
    1011    cursor.execute("DELETE FROM %s WHERE %s < NOW()" % \
    1112        (backend.quote_name('core_sessions'), backend.quote_name('expire_date')))
    1213    cursor.execute("DELETE FROM %s WHERE %s < NOW() - INTERVAL '1 week'" % \
  • tests/modeltests/custom_methods/models.py

     
    2525        Verbose version of get_articles_from_same_day_1, which does a custom
    2626        database query for the sake of demonstration.
    2727        """
    28         from django.db import connection
    29         cursor = connection.cursor()
     28        import django.db
     29        cursor = django.db.connection.cursor()
    3030        cursor.execute("""
    3131            SELECT id, headline, pub_date
    3232            FROM custom_methods_article
  • tests/runtests.py

     
    9494        # Manually set DEBUG = False.
    9595        settings.DEBUG = False
    9696
    97         from django.db import connection
     97        import django.db
    9898        from django.core import management
    9999        import django.db.models
    100100
     
    128128            # Create the test database and connect to it. We need to autocommit
    129129            # if the database supports it because PostgreSQL doesn't allow
    130130            # CREATE/DROP DATABASE statements within transactions.
    131             cursor = connection.cursor()
    132             self._set_autocommit(connection)
     131            cursor = django.db.connection.cursor()
     132            self._set_autocommit(django.db.connection)
    133133            self.output(1, "Creating test database")
    134134            try:
    135135                cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
     
    142142                else:
    143143                    print "Tests cancelled."
    144144                    return
    145         connection.close()
     145        django.db.connection.close()
    146146        old_database_name = settings.DATABASE_NAME
    147147        settings.DATABASE_NAME = TEST_DATABASE_NAME
    148148
    149149        # Initialize the test database.
    150         cursor = connection.cursor()
     150        cursor = django.db.connection.cursor()
    151151
    152152        # Run the tests for each test model.
    153153        self.output(1, "Running app tests")
     
    228228        # to do so, because it's not allowed to delete a database while being
    229229        # connected to it.
    230230        if settings.DATABASE_ENGINE != "sqlite3":
    231             connection.close()
     231            django.db.connection.close()
    232232            settings.DATABASE_NAME = old_database_name
    233             cursor = connection.cursor()
     233            cursor = django.db.connection.cursor()
    234234            self.output(1, "Deleting test database")
    235             self._set_autocommit(connection)
     235            self._set_autocommit(django.db.connection)
    236236            time.sleep(1) # To avoid "database is being accessed by other users" errors.
    237237            cursor.execute("DROP DATABASE %s" % TEST_DATABASE_NAME)
    238238
Back to Top