Ticket #3615: t3615-r9725.diff

File t3615-r9725.diff, 12.3 KB (added by Ramiro Morales, 15 years ago)

Patch updated to trunk as of r9725

  • django/core/management/commands/loaddata.py

    diff -r 289df89a57e4 django/core/management/commands/loaddata.py
    a b  
    2727        from django.core import serializers
    2828        from django.db import connection, transaction
    2929        from django.conf import settings
     30
     31        def enable_constraint_checks():
     32            if not connection.features.can_defer_constraint_checks:
     33                connection.enable_forward_ref_checks()
    3034
    3135        self.style = no_style()
    3236
     
    5963            transaction.commit_unless_managed()
    6064            transaction.enter_transaction_management()
    6165            transaction.managed(True)
     66
     67        if not connection.features.can_defer_constraint_checks:
     68            connection.disable_forward_ref_checks()
    6269
    6370        class SingleZipReader(zipfile.ZipFile):
    6471            def __init__(self, *args, **kwargs):
     
    100107                if verbosity > 1:
    101108                    print "Loading '%s' fixtures..." % fixture_name
    102109            else:
     110                enable_constraint_checks()
    103111                sys.stderr.write(
    104112                    self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format." %
    105113                        (fixture_name, format)))
     
    119127                label_found = False
    120128                for format in formats:
    121129                    for compression_format in compression_formats:
    122                         if compression_format: 
    123                             file_name = '.'.join([fixture_name, format, 
     130                        if compression_format:
     131                            file_name = '.'.join([fixture_name, format,
    124132                                                  compression_format])
    125                         else: 
     133                        else:
    126134                            file_name = '.'.join([fixture_name, format])
    127                    
     135
    128136                        if verbosity > 1:
    129137                            print "Trying %s for %s fixture '%s'..." % \
    130138                                (humanize(fixture_dir), file_name, fixture_name)
    131139                        full_path = os.path.join(fixture_dir, file_name)
    132                         open_method = compression_types[compression_format]                               
    133                         try: 
     140                        open_method = compression_types[compression_format]
     141                        try:
    134142                            fixture = open_method(full_path, 'r')
    135143                            if label_found:
    136144                                fixture.close()
     145                                enable_constraint_checks()
    137146                                print self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting." %
    138147                                    (fixture_name, humanize(fixture_dir)))
    139148                                transaction.rollback()
     
    154163                                    object_count += objects_in_fixture
    155164                                    label_found = True
    156165                                except (SystemExit, KeyboardInterrupt):
     166                                    enable_constraint_checks()
    157167                                    raise
    158168                                except Exception:
    159169                                    import traceback
    160170                                    fixture.close()
     171                                    enable_constraint_checks()
    161172                                    transaction.rollback()
    162173                                    transaction.leave_transaction_management()
    163174                                    if show_traceback:
    164                                         import traceback
    165175                                        traceback.print_exc()
    166176                                    else:
    167177                                        sys.stderr.write(
     
    173183                                # If the fixture we loaded contains 0 objects, assume that an
    174184                                # error was encountered during fixture loading.
    175185                                if objects_in_fixture == 0:
     186                                    enable_constraint_checks()
    176187                                    sys.stderr.write(
    177188                                        self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)" %
    178189                                            (fixture_name)))
     
    184195                            if verbosity > 1:
    185196                                print "No %s fixture '%s' in %s." % \
    186197                                    (format, fixture_name, humanize(fixture_dir))
     198
     199        enable_constraint_checks()
    187200
    188201        # If we found even one object in a fixture, we need to reset the
    189202        # database sequences.
  • django/db/backends/__init__.py

    diff -r 289df89a57e4 django/db/backends/__init__.py
    a b  
    6161    def make_debug_cursor(self, cursor):
    6262        return util.CursorDebugWrapper(cursor, self)
    6363
     64    def disable_forward_ref_checks(self):
     65        pass
     66
     67    def enable_forward_ref_checks(self):
     68        pass
     69
    6470class BaseDatabaseFeatures(object):
    6571    # True if django.db.backend.utils.typecast_timestamp is used on values
    6672    # returned from dates() calls.
     
    7480    # If True, don't use integer foreign keys referring to, e.g., positive
    7581    # integer primary keys.
    7682    related_fields_match_type = False
     83    can_defer_constraint_checks = True
    7784
    7885class BaseDatabaseOperations(object):
    7986    """
  • django/db/backends/mysql/base.py

    diff -r 289df89a57e4 django/db/backends/mysql/base.py
    a b  
    111111    empty_fetchmany_value = ()
    112112    update_can_self_select = False
    113113    related_fields_match_type = True
     114    can_defer_constraint_checks = False
    114115
    115116class DatabaseOperations(BaseDatabaseOperations):
    116117    def date_extract_sql(self, lookup_type, field_name):
     
    288289                raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info())
    289290            self.server_version = tuple([int(x) for x in m.groups()])
    290291        return self.server_version
     292
     293    def disable_forward_ref_checks(self):
     294        self.cursor().execute('SET FOREIGN_KEY_CHECKS=0;')
     295
     296    def enable_forward_ref_checks(self):
     297        self.cursor().execute('SET FOREIGN_KEY_CHECKS=1;')
  • new file tests/modeltests/fixtures/fixtures/forward_references.json

    diff -r 289df89a57e4 tests/modeltests/fixtures/fixtures/forward_references.json
    - +  
     1[
     2    {
     3        "pk": 1,
     4        "model": "fixtures.store",
     5        "fields": {
     6            "book": 1,
     7            "name": "Amazon.com"
     8        }
     9    },
     10    {
     11        "pk": 2,
     12        "model": "fixtures.store",
     13        "fields": {
     14            "book": 3,
     15            "name": "Books.com"
     16        }
     17    },
     18    {
     19        "pk": 3,
     20        "model": "fixtures.store",
     21        "fields": {
     22            "book": 4,
     23            "name": "Mamma and Pappa's Books"
     24        }
     25    },
     26    {
     27        "pk": 1,
     28        "model": "fixtures.book",
     29        "fields": {
     30            "publisher": 1,
     31            "name": "The Definitive Guide to Django: Web Development Done Right",
     32            "authors": [1, 2]
     33        }
     34    },
     35    {
     36        "pk": 2,
     37        "model": "fixtures.book",
     38        "fields": {
     39            "publisher": 2,
     40            "name": "Sams Teach Yourself Django in 24 Hours",
     41            "authors": [3]
     42        }
     43    },
     44    {
     45        "pk": 3,
     46        "model": "fixtures.book",
     47        "fields": {
     48            "publisher": 1,
     49            "name": "Practical Django Projects",
     50            "authors": [4]
     51        }
     52    },
     53    {
     54        "pk": 4,
     55        "model": "fixtures.book",
     56        "fields": {
     57            "publisher": 3,
     58            "name": "Python Web Development with Django",
     59            "authors": [5, 6, 7]
     60        }
     61    },
     62    {
     63        "pk": 5,
     64        "model": "fixtures.book",
     65        "fields": {
     66            "publisher": 3,
     67            "name": "Artificial Intelligence: A Modern Approach",
     68            "authors": [8, 9]
     69        }
     70    },
     71    {
     72        "pk": 6,
     73        "model": "fixtures.book",
     74        "fields": {
     75            "publisher": 4,
     76            "name": "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
     77            "authors": [8]
     78        }
     79    },
     80    {
     81        "pk": 1,
     82        "model": "fixtures.author",
     83        "fields": {
     84            "friends": [2, 4],
     85            "name": "Adrian Holovaty"
     86        }
     87    },
     88    {
     89        "pk": 2,
     90        "model": "fixtures.author",
     91        "fields": {
     92            "friends": [1, 7],
     93            "name": "Jacob Kaplan-Moss"
     94        }
     95    },
     96    {
     97        "pk": 3,
     98        "model": "fixtures.author",
     99        "fields": {
     100            "friends": [],
     101            "name": "Brad Dayley"
     102        }
     103    },
     104    {
     105        "pk": 4,
     106        "model": "fixtures.author",
     107        "fields": {
     108            "friends": [1],
     109            "name": "James Bennett"
     110        }
     111    },
     112    {
     113        "pk": 5,
     114        "model": "fixtures.author",
     115        "fields": {
     116            "friends": [6, 7],
     117            "name": "Jeffrey Forcier"
     118        }
     119    },
     120    {
     121        "pk": 6,
     122        "model": "fixtures.author",
     123        "fields": {
     124            "friends": [5, 7],
     125            "name": "Paul Bissex"
     126        }
     127    },
     128    {
     129        "pk": 7,
     130        "model": "fixtures.author",
     131        "fields": {
     132            "friends": [2, 5, 6],
     133            "name": "Wesley J. Chun"
     134        }
     135    },
     136    {
     137        "pk": 8,
     138        "model": "fixtures.author",
     139        "fields": {
     140            "friends": [9],
     141            "name": "Peter Norvig"
     142        }
     143    },
     144    {
     145        "pk": 9,
     146        "model": "fixtures.author",
     147        "fields": {
     148            "friends": [8],
     149            "name": "Stuart Russell"
     150        }
     151    },
     152    {
     153        "pk": 1,
     154        "model": "fixtures.publisher",
     155        "fields": {
     156            "name": "Apress"
     157        }
     158    },
     159    {
     160        "pk": 2,
     161        "model": "fixtures.publisher",
     162        "fields": {
     163            "name": "Sams"
     164        }
     165    },
     166    {
     167        "pk": 3,
     168        "model": "fixtures.publisher",
     169        "fields": {
     170            "name": "Prentice Hall"
     171        }
     172    },
     173    {
     174        "pk": 4,
     175        "model": "fixtures.publisher",
     176        "fields": {
     177            "name": "Morgan Kaufmann"
     178        }
     179    }
     180]
  • tests/modeltests/fixtures/models.py

    diff -r 289df89a57e4 tests/modeltests/fixtures/models.py
    a b  
    2020
    2121    class Meta:
    2222        ordering = ('-pub_date', 'headline')
     23
     24class Author(models.Model):
     25   name = models.CharField(max_length=100)
     26   friends = models.ManyToManyField('self', blank=True)
     27
     28   def __unicode__(self):
     29      return self.name
     30
     31class Publisher(models.Model):
     32   name = models.CharField(max_length=300)
     33
     34   def __unicode__(self):
     35      return self.name
     36
     37class Book(models.Model):
     38   name = models.CharField(max_length=300)
     39   authors = models.ManyToManyField(Author)
     40   publisher = models.ForeignKey(Publisher)
     41
     42   def __unicode__(self):
     43      return self.name
     44
     45class Store(models.Model):
     46   name = models.CharField(max_length=300)
     47   book = models.ForeignKey(Book)
     48
     49   def __unicode__(self):
     50      return self.name
    2351
    2452__test__ = {'API_TESTS': """
    2553>>> from django.core import management
     
    5482# object list is unaffected
    5583>>> Article.objects.all()
    5684[<Article: XML identified as leading cause of cancer>, <Article: Django conquers world!>, <Article: Copyright is fine the way it is>, <Article: Poker on TV is great!>, <Article: Python program becomes self aware>]
     85
     86# Reset the database representation of this app.
     87# This will return the database to a clean initial state.
     88>>> management.call_command('flush', verbosity=0, interactive=False)
     89
     90# Load a fixture that contains forward references in various forms
     91>>> management.call_command('loaddata', 'forward_references', verbosity=0)
     92>>> Author.objects.count()
     939
    5794"""}
    5895
    5996# Database flushing does not work on MySQL with the default storage engine
Back to Top