Index: modules/system/system.install
===================================================================
RCS file: /cvs/drupal/drupal/modules/system/system.install,v
retrieving revision 1.47
diff -u -p -r1.47 system.install
--- modules/system/system.install	28 Nov 2006 03:32:03 -0000	1.47
+++ modules/system/system.install	28 Nov 2006 14:31:59 -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,61 @@ function system_update_1016() {
   return $ret;
 }
 
+function system_update_1017() {
+  $ret = array();
+  // State tracker to determine whether we keep a backup of the files table or not.
+  $safe = TRUE;
+
+  // PostgreSQL needs CREATE TABLE foobar _AS_ SELECT ...
+  $AS = ($GLOBALS['db_type'] == 'pgsql') ? 'AS' : '';
+
+  // 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}');
+
+  switch ($GLOBALS['db_type']) {
+    case 'pgsql':
+      // 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}");
+
+      break;
+  }
+
+  $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.');
+  }
+
+  return $ret;
+}
+
 /**
  * @} End of "defgroup updates-4.7-to-5.0"
  */
