Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #320 -- Changed save() code so that it doesn't rely on cursor.r…

…owcount. MySQLdb sets cursor.rowcount to 0 in an UPDATE statement even if the record already exists. Now save() does a SELECT query to find out whether a record with the primary key already exists.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@507 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 27986994eea82645fb99ad1a373b7d99110eb3c0 1 parent b5ed204
Adrian Holovaty authored August 15, 2005

Showing 1 changed file with 14 additions and 6 deletions. Show diff stats Hide diff stats

  1. 20  django/core/meta/__init__.py
20  django/core/meta/__init__.py
@@ -728,13 +728,21 @@ def method_save(opts, self):
728 728
     cursor = db.db.cursor()
729 729
 
730 730
     # First, try an UPDATE. If that doesn't update anything, do an INSERT.
731  
-    pk_set = bool(getattr(self, opts.pk.name))
  731
+    pk_val = getattr(self, opts.pk.name)
  732
+    pk_set = bool(pk_val)
  733
+    record_exists = True
732 734
     if pk_set:
733  
-        db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), False)) for f in non_pks]
734  
-        cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % (opts.db_table,
735  
-            ','.join(['%s=%%s' % f.name for f in non_pks]), opts.pk.name),
736  
-            db_values + [getattr(self, opts.pk.name)])
737  
-    if not pk_set or cursor.rowcount == 0:
  735
+        # Determine whether a record with the primary key already exists.
  736
+        cursor.execute("SELECT 1 FROM %s WHERE %s=%%s LIMIT 1" % (opts.db_table, opts.pk.name), [pk_val])
  737
+        # If it does already exist, do an UPDATE.
  738
+        if cursor.rowcount > 0:
  739
+            db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), False)) for f in non_pks]
  740
+            cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % (opts.db_table,
  741
+                ','.join(['%s=%%s' % f.name for f in non_pks]), opts.pk.name),
  742
+                db_values + [pk_val])
  743
+        else:
  744
+            record_exists = False
  745
+    if not pk_set or not record_exists:
738 746
         field_names = [f.name for f in opts.fields if not isinstance(f, AutoField)]
739 747
         placeholders = ['%s'] * len(field_names)
740 748
         db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), True)) for f in opts.fields if not isinstance(f, AutoField)]

0 notes on commit 2798699

Please sign in to comment.
Something went wrong with that request. Please try again.