Index: modules/system/system.install
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/system.install,v
retrieving revision 1.48
diff -u -p -r1.48 system.install
--- modules/system/system.install	28 Nov 2006 14:37:44 -0000	1.48
+++ modules/system/system.install	29 Nov 2006 07:11:39 -0000
@@ -694,7 +694,7 @@ function system_install() {
       db_query("CREATE INDEX {node_comment_statistics}_node_comment_timestamp_idx ON {node_comment_statistics} (last_comment_timestamp)");
 
       db_query("CREATE TABLE {files} (
-        fid int_unsigned NOT NULL default 0,
+        fid serial CHECK (nid >= 0),
         nid int_unsigned NOT NULL default 0,
         filename varchar(255) NOT NULL default '',
         filepath varchar(255) NOT NULL default '',
@@ -3358,6 +3358,63 @@ function system_update_1016() {
   return $ret;
 }
 
+function system_update_1017() {
+  $ret = array();
+
+  switch ($GLOBALS['db_type']) {
+    case 'mysql':
+    case 'mysqli':
+      $ret[] = t('MySQL don\'t needed this update.');
+      break;
+    case 'pgsql':
+      // State tracker to determine whether we keep a backup of the files table or not.
+      $safe = TRUE;
+
+      // Backup the files table.
+      $ret[] = update_sql("CREATE TABLE {files_backup} AS SELECT * FROM {files}");
+
+      // Do some files table sanity checking and cleanup.
+      $ret[] = update_sql('DELETE FROM {files} WHERE fid = 0');
+      $ret[] = update_sql('DELETE FROM {file_revisions} WHERE fid = 0');
+
+      // Create a temporary table to build the new files tables from.
+      $ret[] = update_sql("CREATE TABLE {files_tmp} AS SELECT * FROM {files}");
+      $ret[] = update_sql('DROP TABLE {files}');
+      
+      // Create files table
+      $ret[] = update_sql("CREATE TABLE {files} (
+        fid serial CHECK (nid >= 0),
+        nid int_unsigned NOT NULL default 0,
+        filename varchar(255) NOT NULL default '',
+        filepath varchar(255) NOT NULL default '',
+        filemime varchar(255) NOT NULL default '',
+        filesize int_unsigned NOT NULL default 0,
+        PRIMARY KEY (fid)
+      )");
+      $result = update_sql("INSERT INTO {files} SELECT DISTINCT ON (fid) fid, nid, filename, filepath, filemime, filesize FROM {files_tmp}");
+      $ret[] = $result;
+      if ($result['success'] === FALSE) {
+        $safe = FALSE;
+      }
+
+      $ret[] = update_sql("SELECT setval('{files}_fid_seq', max(fid)) FROM {files}");
+
+      $ret[] = update_sql("DROP TABLE {files_tmp}");
+
+      // Remove original files table if all went well. Otherwise preserve it and notify user.
+      if ($safe) {
+        $ret[] = update_sql("DROP TABLE {files_backup}");
+      }
+      else {
+        drupal_set_message('Create new files table failed. A backup of the original table called {files_backup} remains in your database.');
+      }
+
+      break;
+  }
+
+  return $ret;
+}
+
 /**
  * @} End of "defgroup updates-4.7-to-5.0"
  */
