Ticket #4747: mdb.patch
| File mdb.patch, 203.1 kB (added by ben <ben.fordnz@gmail.com>, 1 year ago) |
|---|
-
django/test/utils.py
old new 1 1 import sys, time 2 2 from django.conf import settings 3 from django.db import connection, backend, get_creation_module 3 from django.db import connection, transaction, backend, \ 4 connection_info, connections, get_creation_module 4 5 from django.core import management, mail 5 6 from django.core import management, mail 6 7 from django.dispatch import dispatcher … … 12 13 TEST_DATABASE_PREFIX = 'test_' 13 14 14 15 def instrumented_test_render(self, context): 15 """An instrumented Template render method, providing a signal16 that can be intercepted by the test system Client17 18 16 """ 17 An instrumented Template render method, providing a signal that can be 18 intercepted by the test system Client. 19 """ 19 20 dispatcher.send(signal=signals.template_rendered, sender=self, template=self, context=context) 20 21 return self.nodelist.render(context) 22 23 def instrumented_test_iter_render(self, context): 24 """ 25 An instrumented Template iter_render method, providing a signal that can be 26 intercepted by the test system Client. 27 """ 28 for chunk in self.nodelist.iter_render(context): 29 yield chunk 30 dispatcher.send(signal=signals.template_rendered, sender=self, template=self, context=context) 21 31 22 32 class TestSMTPConnection(object): 23 33 """A substitute SMTP connection for use during test sessions. … … 45 55 46 56 """ 47 57 Template.original_render = Template.render 58 Template.original_iter_render = Template.iter_render 48 59 Template.render = instrumented_test_render 60 Template.iter_render = instrumented_test_render 49 61 50 62 mail.original_SMTPConnection = mail.SMTPConnection 51 63 mail.SMTPConnection = TestSMTPConnection … … 60 72 61 73 """ 62 74 Template.render = Template.original_render 63 del Template.original_render 75 Template.iter_render = Template.original_iter_render 76 del Template.original_render, Template.original_iter_render 64 77 65 78 mail.SMTPConnection = mail.original_SMTPConnection 66 79 del mail.original_SMTPConnection … … 73 86 connection.connection.autocommit(True) 74 87 elif hasattr(connection.connection, "set_isolation_level"): 75 88 connection.connection.set_isolation_level(0) 76 89 77 90 def get_mysql_create_suffix(): 78 91 suffix = [] 79 92 if settings.TEST_DATABASE_CHARSET: … … 97 110 98 111 if verbosity >= 1: 99 112 print "Creating test database..." 113 100 114 # If we're using SQLite, it's more convenient to test against an 101 115 # in-memory database. 102 116 if settings.DATABASE_ENGINE == "sqlite3": 103 TEST_DATABASE_NAME = ":memory:" 117 TEST_DATABASE_NAME = "/home/ben/test.db" #":memory:" 118 if verbosity >= 2: 119 print "Using in-memory sqlite database for testing" 104 120 else: 105 121 suffix = { 106 122 'postgresql': get_postgresql_create_suffix, … … 112 128 TEST_DATABASE_NAME = settings.TEST_DATABASE_NAME 113 129 else: 114 130 TEST_DATABASE_NAME = TEST_DATABASE_PREFIX + settings.DATABASE_NAME 115 131 132 qn = backend.quote_name 116 133 # Create the test database and connect to it. We need to autocommit 117 134 # if the database supports it because PostgreSQL doesn't allow 118 135 # CREATE/DROP DATABASE statements within transactions. 119 136 cursor = connection.cursor() 120 137 _set_autocommit(connection) 121 138 try: 122 cursor.execute("CREATE DATABASE %s %s" % ( backend.quote_name(TEST_DATABASE_NAME), suffix))139 cursor.execute("CREATE DATABASE %s %s" % (qn(TEST_DATABASE_NAME), suffix)) 123 140 except Exception, e: 124 141 sys.stderr.write("Got an error creating the test database: %s\n" % e) 125 142 if not autoclobber: … … 128 145 try: 129 146 if verbosity >= 1: 130 147 print "Destroying old test database..." 131 cursor.execute("DROP DATABASE %s" % backend.quote_name(TEST_DATABASE_NAME))148 cursor.execute("DROP DATABASE %s" % qn(TEST_DATABASE_NAME)) 132 149 if verbosity >= 1: 133 150 print "Creating test database..." 134 cursor.execute("CREATE DATABASE %s %s" % ( backend.quote_name(TEST_DATABASE_NAME), suffix))151 cursor.execute("CREATE DATABASE %s %s" % (qn(TEST_DATABASE_NAME), suffix)) 135 152 except Exception, e: 136 153 sys.stderr.write("Got an error recreating the test database: %s\n" % e) 137 154 sys.exit(2) … … 148 165 # the side effect of initializing the test database. 149 166 cursor = connection.cursor() 150 167 151 def destroy_test_db(old_database_name, verbosity=1): 168 # Fill OTHER_DATABASES with the TEST_DATABASES settings, 169 # and connect each named connection to the test database. 170 test_databases = {} 171 for db_name in settings.TEST_DATABASES: 172 db_st = {'DATABASE_NAME': TEST_DATABASE_NAME} 173 if db_name in settings.TEST_DATABASE_MODELS: 174 db_st['MODELS'] = settings.TEST_DATABASE_MODELS.get(db_name, []) 175 test_databases[db_name] = db_st 176 settings.OTHER_DATABASES = test_databases 177 178 def destroy_test_db(old_database_name, old_databases, verbosity=1): 152 179 # If the database wants to drop the test DB itself, let it 153 180 creation_module = get_creation_module() 154 181 if hasattr(creation_module, "destroy_test_db"): 155 182 creation_module.destroy_test_db(settings, connection, backend, old_database_name, verbosity) 156 183 return 157 158 184 # Unless we're using SQLite, remove the test database to clean up after 159 185 # ourselves. Connect to the previous database (not the test database) 160 186 # to do so, because it's not allowed to delete a database while being 161 187 # connected to it. 162 188 if verbosity >= 1: 163 189 print "Destroying test database..." 190 164 191 connection.close() 192 for cnx in connections.keys(): 193 connections[cnx].close() 194 connections.reset() 195 165 196 TEST_DATABASE_NAME = settings.DATABASE_NAME 197 if verbosity >= 2: 198 print "Closed connections to %s" % TEST_DATABASE_NAME 166 199 settings.DATABASE_NAME = old_database_name 167 200 168 201 if settings.DATABASE_ENGINE != "sqlite3": 202 settings.OTHER_DATABASES = old_databases 203 for cnx in connections.keys(): 204 try: 205 connections[cnx].connection.cursor() 206 except (KeyboardInterrupt, SystemExit): 207 raise 208 except: 209 pass 169 210 cursor = connection.cursor() 170 211 _set_autocommit(connection) 171 212 time.sleep(1) # To avoid "database is being accessed by other users" errors. -
django/http/__init__.py
old new 224 224 content = ''.join(self._container) 225 225 if isinstance(content, unicode): 226 226 content = content.encode(self._charset) 227 228 # If self._container was an iterator, we have just exhausted it, so we 229 # need to save the results for anything else that needs access 230 if not self._is_string: 231 self._container = [content] 232 self._is_string = True 227 233 return content 228 234 229 235 def _set_content(self, value): … … 233 239 content = property(_get_content, _set_content) 234 240 235 241 def __iter__(self): 236 self._iterator = self._container.__iter__() 237 return self 242 for chunk in self._container: 243 if isinstance(chunk, unicode): 244 chunk = chunk.encode(self._charset) 245 yield chunk 238 246 239 def next(self):240 chunk = self._iterator.next()241 if isinstance(chunk, unicode):242 chunk = chunk.encode(self._charset)243 return chunk244 245 247 def close(self): 246 248 if hasattr(self._container, 'close'): 247 249 self._container.close() -
django/oldforms/__init__.py
old new 309 309 return data 310 310 html2python = staticmethod(html2python) 311 311 312 def iter_render(self, data): 313 # this even needed? 314 return (self.render(data),) 315 312 316 def render(self, data): 313 317 raise NotImplementedError 314 318 -
django/db/models/base.py
old new 6 6 from django.db.models.fields.related import OneToOneRel, ManyToOneRel 7 7 from django.db.models.query import delete_objects 8 8 from django.db.models.options import Options, AdminOptions 9 from django.db import connection, backend,transaction9 from django.db import transaction 10 10 from django.db.models import signals 11 11 from django.db.models.loading import register_models, get_model 12 12 from django.dispatch import dispatcher … … 22 22 "Metaclass for all models" 23 23 def __new__(cls, name, bases, attrs): 24 24 # If this isn't a subclass of Model, don't do anything special. 25 print "\n\n" + "*"*40 26 print "ModelBase Called with name: %s and attrs:" % name 27 print "\n".join(["%s => %s" % (k,v) for k, v in attrs.items()]) 25 28 try: 26 29 if not filter(lambda b: issubclass(b, Model), bases): 27 30 return super(ModelBase, cls).__new__(cls, name, bases, attrs) … … 201 204 def save(self): 202 205 dispatcher.send(signal=signals.pre_save, sender=self.__class__, instance=self) 203 206 207 db = self.__class__._default_manager.db 208 connection = db.connection 209 backend = db.backend 210 qn = backend.quote_name 204 211 non_pks = [f for f in self._meta.fields if not f.primary_key] 205 212 cursor = connection.cursor() 206 213 … … 211 218 if pk_set: 212 219 # Determine whether a record with the primary key already exists. 213 220 cursor.execute("SELECT COUNT(*) FROM %s WHERE %s=%%s" % \ 214 ( backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column)),221 (qn(self._meta.db_table), qn(self._meta.pk.column)), 215 222 self._meta.pk.get_db_prep_lookup('exact', pk_val)) 216 223 # If it does already exist, do an UPDATE. 217 224 if cursor.fetchone()[0] > 0: 218 225 db_values = [f.get_db_prep_save(f.pre_save(self, False)) for f in non_pks] 219 226 if db_values: 220 227 cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \ 221 ( backend.quote_name(self._meta.db_table),222 ','.join(['%s=%%s' % backend.quote_name(f.column) for f in non_pks]),223 backend.quote_name(self._meta.pk.column)),228 (qn(self._meta.db_table), 229 ','.join(['%s=%%s' % qn(f.column) for f in non_pks]), 230 qn(self._meta.pk.column)), 224 231 db_values + self._meta.pk.get_db_prep_lookup('exact', pk_val)) 225 232 else: 226 233 record_exists = False 227 234 if not pk_set or not record_exists: 228 field_names = [ backend.quote_name(f.column) for f in self._meta.fields if not isinstance(f, AutoField)]235 field_names = [qn(f.column) for f in self._meta.fields if not isinstance(f, AutoField)] 229 236 db_values = [f.get_db_prep_save(f.pre_save(self, True)) for f in self._meta.fields if not isinstance(f, AutoField)] 230 237 # If the PK has been manually set, respect that. 231 238 if pk_set: … … 233 240 db_values += [f.get_db_prep_save(f.pre_save(self, True)) for f in self._meta.fields if isinstance(f, AutoField)] 234 241 placeholders = ['%s'] * len(field_names) 235 242 if self._meta.order_with_respect_to: 236 field_names.append( backend.quote_name('_order'))243 field_names.append(qn('_order')) 237 244 # TODO: This assumes the database supports subqueries. 238 245 placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \ 239 ( backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.order_with_respect_to.column)))246 (qn(self._meta.db_table), qn(self._meta.order_with_respect_to.column))) 240 247 db_values.append(getattr(self, self._meta.order_with_respect_to.attname)) 241 248 if db_values: 242 249 cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \ 243 ( backend.quote_name(self._meta.db_table), ','.join(field_names),250 (qn(self._meta.db_table), ','.join(field_names), 244 251 ','.join(placeholders)), db_values) 245 252 else: 246 253 # Create a new record with defaults for everything. 247 254 cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % 248 ( backend.quote_name(self._meta.db_table),249 backend.quote_name(self._meta.pk.column),255 (qn(self._meta.db_table), 256 qn(self._meta.pk.column), 250 257 backend.get_pk_default_value())) 251 258 if self._meta.has_auto_field and not pk_set: 252 259 setattr(self, self._meta.pk.attname, backend.get_last_insert_id(cursor, self._meta.db_table, self._meta.pk.column)) 253 transaction.commit_unless_managed( )260 transaction.commit_unless_managed([connection]) 254 261 255 262 # Run any post-save hooks. 256 263 dispatcher.send(signal=signals.post_save, sender=self.__class__, instance=self) … … 321 328 return dict(field.choices).get(value, value) 322 329 323 330 def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): 331 qn = self._default_manager.db.backend.quote_name 324 332 op = is_next and '>' or '<' 325 333 where = '(%s %s %%s OR (%s = %%s AND %s.%s %s %%s))' % \ 326 ( backend.quote_name(field.column), op, backend.quote_name(field.column),327 backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column), op)334 (qn(field.column), op, qn(field.column), 335 qn(self._meta.db_table), qn(self._meta.pk.column), op) 328 336 param = str(getattr(self, field.attname)) 329 337 q = self.__class__._default_manager.filter(**kwargs).order_by((not is_next and '-' or '') + field.name, (not is_next and '-' or '') + self._meta.pk.name) 330 338 q._where.append(where) … … 335 343 raise self.DoesNotExist, "%s matching query does not exist." % self.__class__._meta.object_name 336 344 337 345 def _get_next_or_previous_in_order(self, is_next): 346 qn = self._default_manager.db.backend.quote_name 347 338 348 cachename = "__%s_order_cache" % is_next 339 349 if not hasattr(self, cachename): 340 350 op = is_next and '>' or '<' 341 351 order_field = self._meta.order_with_respect_to 342 352 where = ['%s %s (SELECT %s FROM %s WHERE %s=%%s)' % \ 343 ( backend.quote_name('_order'), op, backend.quote_name('_order'),344 backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column)),345 '%s=%%s' % backend.quote_name(order_field.column)]353 (qn('_order'), op, qn('_order'), 354 qn(self._meta.db_table), qn(self._meta.pk.column)), 355 '%s=%%s' % qn(order_field.column)] 346 356 params = [self._get_pk_val(), getattr(self, order_field.attname)] 347 357 obj = self._default_manager.order_by('_order').extra(where=where, params=params)[:1].get() 348 358 setattr(self, cachename, obj) … … 424 434 # ORDERING METHODS ######################### 425 435 426 436 def method_set_order(ordered_obj, self, id_list): 437 db = ordered_obj._default_manager.db 438 connection = db.connection 439 qn = db.backend.quote_name 427 440 cursor = connection.cursor() 428 441 # Example: "UPDATE poll_choices SET _order = %s WHERE poll_id = %s AND id = %s" 429 442 sql = "UPDATE %s SET %s = %%s WHERE %s = %%s AND %s = %%s" % \ 430 ( backend.quote_name(ordered_obj._meta.db_table), backend.quote_name('_order'),431 backend.quote_name(ordered_obj._meta.order_with_respect_to.column),432 backend.quote_name(ordered_obj._meta.pk.column))443 (qn(ordered_obj._meta.db_table), qn('_order'), 444 qn(ordered_obj._meta.order_with_respect_to.column), 445 qn(ordered_obj._meta.pk.column)) 433 446 rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) 434 447 cursor.executemany(sql, [(i, rel_val, j) for i, j in enumerate(id_list)]) 435 transaction.commit_unless_managed( )448 transaction.commit_unless_managed([connection]) 436 449 437 450 def method_get_order(ordered_obj, self): 451 db = ordered_obj._default_manager.db 452 connection = db.connection 453 qn = db.backend.quote_name 438 454 cursor = connection.cursor() 439 455 # Example: "SELECT id FROM poll_choices WHERE poll_id = %s ORDER BY _order" 440 456 sql = "SELECT %s FROM %s WHERE %s = %%s ORDER BY %s" % \ 441 ( backend.quote_name(ordered_obj._meta.pk.column),442 backend.quote_name(ordered_obj._meta.db_table),443 backend.quote_name(ordered_obj._meta.order_with_respect_to.column),444 backend.quote_name('_order'))457 (qn(ordered_obj._meta.pk.column), 458 qn(ordered_obj._meta.db_table), 459 qn(ordered_obj._meta.order_with_respect_to.column), 460 qn('_order')) 445 461 rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) 446 462 cursor.execute(sql, [rel_val]) 447 463 return [r[0] for r in cursor.fetchall()] -
django/db/models/manager.py
old new 1 from django.db import ConnectionInfoDescriptor 1 2 from django.db.models.query import QuerySet, EmptyQuerySet 2 3 from django.dispatch import dispatcher 3 from django.db.models import signals 4 from django.db.models import signals, get_apps, get_models 4 5 from django.db.models.fields import FieldDoesNotExist 5 6 7 try: 8 # Only exists in Python 2.4+ 9 from threading import local 10 except ImportError: 11 # Import copy of _thread_local.py from Python 2.4 12 from django.utils._threading_local import local 13 6 14 # Size of each "chunk" for get_iterator calls. 7 15 # Larger values are slightly faster at the expense of more storage space. 8 16 GET_ITERATOR_CHUNK_SIZE = 100 … … 17 25 except FieldDoesNotExist: 18 26 pass 19 27 cls.add_to_class('objects', Manager()) 20 28 elif cls._default_manager.model != cls: 29 # cls is an inherited model; don't want the parent manager 30 cls.add_to_class('objects', Manager()) 21 31 dispatcher.connect(ensure_default_manager, signal=signals.class_prepared) 22 32 33 34 23 35 class Manager(object): 24 36 # Tracks each time a Manager instance is created. Used to retain order. 25 37 creation_counter = 0 26 38 db = ConnectionInfoDescriptor() 39 27 40 def __init__(self): 28 41 super(Manager, self).__init__() 29 42 # Increase the creation counter, and save our local copy. … … 35 48 # TODO: Use weakref because of possible memory leak / circular reference. 36 49 self.model = model 37 50 setattr(model, name, ManagerDescriptor(self)) 38 if not hasattr(model, '_default_manager') or self.creation_counter < model._default_manager.creation_counter: 51 if not hasattr(model, '_default_manager') \ 52 or self.creation_counter < model._default_manager.creation_counter \ 53 or model._default_manager.model != model: 39 54 model._default_manager = self 40 55 41 56 ####################### 42 57 # PROXIES TO QUERYSET # 43 58 ####################### … … 105 120 def values(self, *args, **kwargs): 106 121 return self.get_query_set().values(*args, **kwargs) 107 122 123 ####################### 124 # SCHEMA MANIPULATION # 125 ####################### 126 127 def install(self, initial_data=False, pending=None): 128 """Install my model's table, indexes and (if requested) initial data. 129 130 Returns a dict of pending statements, keyed by the model that 131 needs to be created before the statements can be executed. 132 (Pending statements are those that could not yet be executed, 133 such as foreign key constraints for tables that don't exist at 134 install time.) 135 """ 136 if pending is None: 137 pending = {} 138 builder = self.db.get_creation_module().builder 139 run, pending = builder.get_create_table(self.model, pending=pending) 140 run += builder.get_create_indexes(self.model) 141 many_many = builder.get_create_many_to_many(self.model) 142 143 for statement in run: 144 statement.execute() 145 for klass, statements in many_many.items(): 146 if klass in builder.models_already_seen: 147 for statement in statements: 148 statement.execute() 149 else: 150 pending.setdefault(klass, []).extend(statements) 151 if initial_data: 152 self.load_initial_data() 153 return pending 154 155 def get_pending(self, rel_class, f): 156 """Get list pending statement relating my model to rel_class via 157 field f 158 """ 159 builder = self.db.get_creation_module().builder 160 return builder.get_ref_sql(self.model, rel_class, f) 161 162 def load_initial_data(self): 163 """Install initial data for model in db, Returns statements executed. 164 """ 165 builder = self.db.get_creation_module().builder 166 statements = builder.get_initialdata(self.model) 167 for statement in statements: 168 statement.execute() 169 return statements 170 171 def get_installed_models(self, table_list): 172 """Get list of models installed, given a list of tables. 173 """ 174 all_models = [] 175 for app in get_apps(): 176 for model in get_models(app): 177 all_models.append(model) 178 return set([m for m in all_models 179 if m._meta.db_table in table_list]) 180 181 def get_table_list(self): 182 """Get list of tables accessible via my model's connection. 183 """ 184 builder = self.db.get_creation_module().builder 185 return builder.get_table_list(self.db) 186 108 187 class ManagerDescriptor(object): 109 188 # This class ensures managers aren't accessible via model instances. 110 189 # For example, Poll.objects works, but poll_obj.objects raises AttributeError. … … 115 194 if instance != None: 116 195 raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__ 117 196 return self.manager 197 -
django/db/models/options.py
old new 1 1 from django.conf import settings 2 from django.db import connection_info, connections 2 3 from django.db.models.related import RelatedObject 3 4 from django.db.models.fields.related import ManyToManyRel 4 5 from django.db.models.fields import AutoField, FieldDoesNotExist … … 7 8 from django.db.models import Manager 8 9 from bisect import bisect 9 10 import re 11 import weakref 10 12 11 13 # Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces". 12 14 get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip() … … 79 81 self.db_table = truncate_name(self.db_table, 80 82 backend.get_max_name_length()) 81 83 84 # Keep a weakref to my model, for access to managers and such 85 self._model = weakref.ref(model) 86 82 87 def add_field(self, field): 83 88 # Insert the given field in the order in which it was created, using 84 89 # the "creation_counter" attribute of the field. … … 105 110 return f 106 111 raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name) 107 112 113 def get_default_manager(self): 114 model = self._model() 115 if model is None: 116 raise ReferenceError("Model no longer available in %s" % self) 117 return model._default_manager 118 108 119 def get_order_sql(self, table_prefix=''): 109 120 "Returns the full 'ORDER BY' clause for this object, according to self.ordering." 110 121 if not self.ordering: return '' -
django/db/models/loading.py
old new 12 12 _app_models = {} # Dictionary of models against app label 13 13 # Each value is a dictionary of model name: model class 14 14 # Applabel and Model entry exists in cache when individual model is loaded. 15 _app_model_order = {} # Dictionary of models against app label 16 # Each value is a list of model names, in the order in 17 # which the models were created 15 18 _app_errors = {} # Dictionary of errors that were experienced when loading the INSTALLED_APPS 16 19 # Key is the app_name of the model, value is the exception that was raised 17 20 # during model loading. … … 61 64 get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish. 62 65 return _app_errors 63 66 64 def get_models(app_mod=None ):67 def get_models(app_mod=None, creation_order=False): 65 68 """ 66 69 Given a module containing models, returns a list of the models. Otherwise 67 70 returns a list of all installed models. 68 71 """ 69 72 app_list = get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish. 70 73 if app_mod: 71 return _app_models.get(app_mod.__name__.split('.')[-2], {}).values() 74 app_label = app_mod.__name__.split('.')[-2] 75 app_models = _app_models.get(app_label, {}) 76 if creation_order: 77 return [ app_models[name] 78 for name in _app_model_order.get(app_label, []) ] 79 return app_models.values() 72 80 else: 73 81 model_list = [] 74 82 for app_mod in app_list: -
django/db/models/fields/__init__.py
old new 536 536 except ValueError: 537 537 raise validators.ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.') 538 538 539 def get_db_prep_save(self, value):540 # Casts dates into string format for entry into database.539 def pre_save(self, model_instance, add): 540 value = super(DateField, self).pre_save(model_instance, add) 541 541 if value is not None: 542 542 # MySQL will throw a warning if microseconds are given, because it 543 543 # doesn't support microseconds. 544 settings = model_instance._default_manager.db.connection.settings 544 545 if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): 545 546 value = value.replace(microsecond=0) 547 return value 548 549 def get_db_prep_save(self, value): 550 # Casts dates into string format for entry into database. 551 if value is not None: 546 552 value = str(value) 547 553 return Field.get_db_prep_save(self, value) 548 554 … … 909 915 if value is not None: 910 916 # MySQL will throw a warning if microseconds are given, because it 911 917 # doesn't support microseconds. 918 settings = model_instance._default_manager.db.connection.settings 912 919 if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): 913 920 value = value.replace(microsecond=0) 914 921 if settings.DATABASE_ENGINE == 'oracle': -
django/db/models/fields/related.py
old new 1 from django.db import backend,transaction1 from django.db import transaction 2 2 from django.db.models import signals, get_model 3 3 from django.db.models.fields import AutoField, Field, IntegerField, get_ul_class 4 4 from django.db.models.related import RelatedObject … … 318 318 # source_col_name: the PK colname in join_table for the source object 319 319 # target_col_name: the PK colname in join_table for the target object 320 320 # *objs - objects to add. Either object instances, or primary keys of object instances. 321 from django.db importconnection321 connection = self.model._default_manager.db.connection 322 322 323 323 # If there aren't any objects, there is nothing to do. 324 324 if objs: … … 343 343 cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \ 344 344 (self.join_table, source_col_name, target_col_name), 345 345 [self._pk_val, obj_id]) 346 transaction.commit_unless_managed()346 transaction.commit_unless_managed(connection) 347 347 348 348 def _remove_items(self, source_col_name, target_col_name, *objs): 349 349 # source_col_name: the PK colname in join_table for the source object 350 350 # target_col_name: the PK colname in join_table for the target object 351 351 # *objs - objects to remove 352 from django.db importconnection352 connection = self.model._default_manager.db.connection 353 353 354 354 # If there aren't any objects, there is nothing to do. 355 355 if objs: … … 366 366 (self.join_table, source_col_name, 367 367 target_col_name, ",".join(['%s'] * len(old_ids))), 368 368 [self._pk_val] + list(old_ids)) 369 transaction.commit_unless_managed()369 transaction.commit_unless_managed(connection) 370 370 371 371 def _clear_items(self, source_col_name): 372 372 # source_col_name: the PK colname in join_table for the source object 373 from django.db importconnection373 connection = self.model._default_manager.db.connection 374 374 cursor = connection.cursor() 375 375 cursor.execute("DELETE FROM %s WHERE %s = %%s" % \ 376 376 (self.join_table, source_col_name), 377 377 [self._pk_val]) 378 transaction.commit_unless_managed( )378 transaction.commit_unless_managed(connection) 379 379 380 380 return ManyRelatedManager 381 381 … … 399 399 superclass = rel_model._default_manager.__class__ 400 400 RelatedManager = create_many_related_manager(superclass) 401 401 402 qn = backend.quote_name402 qn = rel_model._default_manager.db.backend.quote_name 403 403 manager = RelatedManager( 404 404 model=rel_model, 405 405 core_filters={'%s__pk' % self.related.field.name: instance._get_pk_val()}, … … 440 440 superclass = rel_model._default_manager.__class__ 441 441 RelatedManager = create_many_related_manager(superclass) 442 442 443 qn = backend.quote_name443 qn = rel_model._default_manager.db.backend.quote_name 444 444 manager = RelatedManager( 445 445 model=rel_model, 446 446 core_filters={'%s__pk' % self.field.related_query_name(): instance._get_pk_val()}, -
django/db/models/query.py
old new 182 182 # self._select is a dictionary, and dictionaries' key order is 183 183 # undefined, so we convert it to a list of tuples. 184 184 extra_select = self._select.items() 185 186 cursor = connection.cursor() 185 cursor = self.model._default_manager.db.connection.cursor() 187 186 cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) 188 187 189 188 fill_cache = self._select_related … … 217 216 """ 218 217 if self._result_cache is not None: 219 218 return len(self._result_cache) 220 219 #from multi-db 220 db = self.model._default_manager.db 221 backend = db.backend 222 connection = db.connection 223 221 224 counter = self._clone() 222 225 counter._order_by = () 223 226 counter._select_related = False … … 304 307 Returns a dictionary mapping each of the given IDs to the object with 305 308 that ID. 306 309 """ 310 backend = self.model._default_manager.db.backend 307 311 assert self._limit is None and self._offset is None, \ 308 312 "Cannot use 'limit' or 'offset' with in_bulk" 309 313 assert isinstance(id_list, (tuple, list)), "in_bulk() must be provided with a list of IDs." … … 481 485 482 486 def _get_sql_clause(self): 483 487 opts = self.model._meta 484 488 backend = self.model._default_manager.db.backend 489 qn = backend.quote_name 485 490 # Construct the fundamental parts of the query: SELECT X FROM Y WHERE Z. 486 select = ["%s.%s" % (backend.quote_name(opts.db_table), backend.quote_name(f.column)) for f in opts.fields] 491 select = ["%s.%s" % (qn(opts.db_table), qn(f.column)) 492 for f in opts.fields] 487 493 tables = [quote_only_if_word(t) for t in self._tables] 488 494 joins = SortedDict() 489 495 where = self._where[:] … … 504 510 505 511 # Add any additional SELECTs. 506 512 if self._select: 507 select.extend(['(%s) AS %s' % (quote_only_if_word(s[1]), backend.quote_name(s[0])) for s in self._select.items()]) 513 select.extend(['(%s) AS %s' % (quote_only_if_word(s[1]), qn(s[0])) 514 for s in self._select.items()]) 508 515 509 516 # Start composing the body of the SQL statement. 510 sql = [" FROM", backend.quote_name(opts.db_table)]517 sql = [" FROM", qn(opts.db_table)] 511 518 512 519 # Compose the join dictionary into SQL describing the joins. 513 520 if joins: … … 540 547 order = "ASC" 541 548 if "." in col_name: 542 549 table_prefix, col_name = col_name.split('.', 1) 543 table_prefix = backend.quote_name(table_prefix) + '.'550 table_prefix = qn(table_prefix) + '.' 544 551 else: 545 552 # Use the database table as a column prefix if it wasn't given, 546 553 # and if the requested column isn't a custom SELECT. 547 554 if "." not in col_name and col_name not in (self._select or ()): 548 table_prefix = backend.quote_name(opts.db_table) + '.'555 table_prefix = qn(opts.db_table) + '.' 549 556 else: 550 557 table_prefix = '' 551 order_by.append('%s%s %s' % (table_prefix, backend.quote_name(orderfield2column(col_name, opts)), order))558 order_by.append('%s%s %s' % (table_prefix, qn(orderfield2column(col_name, opts)), order)) 552 559 if order_by: 553 560 sql.append("ORDER BY " + ", ".join(order_by)) 554 561 … … 597 604 598 605 columns = [f.column for f in fields] 599 606 select = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns] 607 608 #from multi-db 609 db = self.model._default_manager.db 610 backend = db.backend 611 qn = backend.quote_name 612 connection = db.connection 613 600 614 # Add any additional SELECTs. 601 615 if self._select: 602 616 select.extend(['(%s) AS %s' % (quote_only_if_word(s[1]), backend.quote_name(s[0])) for s in self._select.items()]) 603 617 604 618 cursor = connection.cursor() 619 select = ['%s.%s' % (qn(self.model._meta.db_table), qn(c)) 620 for c in columns] 605 621 cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) 606 622 607 623 has_resolve_columns = hasattr(self, 'resolve_columns') … … 623 639 def iterator(self): 624 640 from django.db.backends.util import typecast_timestamp 625 641 from django.db.models.fields import DateTimeField 642 db = self.model._default_manager.db 643 backend = db.backend 644 qn = backend.quote_name 645 connection = db.connection 646 626 647 self._order_by = () # Clear this because it'll mess things up otherwise. 627 648 if self._field.null: 628 649 self._where.append('%s.%s IS NOT NULL' % \ 629 (backend.quote_name(self.model._meta.db_table), backend.quote_name(self._field.column))) 650 (qn(self.model._meta.db_table), qn(self._field.column))) 651 630 652 try: 631 653 select, sql, params = self._get_sql_clause() 632 654 except EmptyResultSet: 633 655 raise StopIteration 634 656 635 table_name = backend.quote_name(self.model._meta.db_table)636 field_name = backend.quote_name(self._field.column)657 table_name = qn(self.model._meta.db_table) 658 field_name = qn(self._field.column) 637 659 638 660 if backend.allows_group_by_ordinal: 639 661 group_by = '1' … … 768 790 return SortedDict(), [], [] 769 791 return joins, where2, params 770 792 771 def get_where_clause(lookup_type, table_prefix, field_name, value): 793 def get_where_clause(opts, lookup_type, table_prefix, field_name, value): 794 backend = opts.get_default_manager().db.backend 795 qn = backend.quote_name 796 772 797 if table_prefix.endswith('.'): 773 table_prefix = backend.quote_name(table_prefix[:-1])+'.'774 field_name = backend.quote_name(field_name)798 table_prefix = qn(table_prefix[:-1])+'.' 799 field_name = qn(field_name) 775 800 if type(value) == datetime.datetime and backend.get_datetime_cast_sql(): 776 801 cast_sql = backend.get_datetime_cast_sql() 777 802 else: … … 832 857 Helper function that recursively populates the select, tables and where (in 833 858 place) for select_related queries. 834 859 """ 860 qn = opts.get_default_manager().db.backend.quote_name 835 861 836 862 # If we've got a max_depth set and we've exceeded that depth, bail now. 837 863 if max_depth and cur_depth > max_depth: 838 864 return None 839 865 840 qn = backend.quote_name841 866 for f in opts.fields: 842 867 if f.rel and not f.null: 843 868 db_table = f.rel.to._meta.db_table … … 935 960 return choices 936 961 937 962 def lookup_inner(path, lookup_type, value, opts, table, column): 938 qn = backend.quote_name939 963 joins, where, params = SortedDict(), [], [] 940 964 current_opts = opts 941 965 current_table = table 942 966 current_column = column 943 967 intermediate_table = None 944 968 join_required = False 969 db = current_opts.get_default_manager().db 970 backend = db.backend 971 connection = db.connection 972 qn = backend.quote_name 945 973 946 974 name = path.pop(0) 947 975 # Has the primary key been requested? If so, expand it out … … 1092 1120 # Last query term was a normal field. 1093 1121 column = field.column 1094 1122 1095 where.append(get_where_clause( lookup_type, current_table + '.', column, value))1123 where.append(get_where_clause(current_opts, lookup_type, current_table + '.', column, value)) 1096 1124 params.extend(field.get_db_prep_lookup(lookup_type, value)) 1097 1125 1098 1126 return joins, where, params 1099 1127 1100 1128 def delete_objects(seen_objs): 1101 1129 "Iterate through a list of seen classes, and remove any instances that are referred to" 1102 qn = backend.quote_name1103
