diff --git a/database/database.pgsql b/database/database.pgsql
index 58251fb0d01e8bd105a96c70e19dff4893fd4b56..339549516ea46c30e423fb50562fe17546f9c003 100644
--- a/database/database.pgsql
+++ b/database/database.pgsql
@@ -80,7 +80,7 @@ CREATE TABLE boxes (
   title varchar(64) NOT NULL default '',
   body text default '',
   info varchar(128) NOT NULL default '',
-  type smallint NOT NULL default '0',
+  format smallint NOT NULL default '0',
   PRIMARY KEY  (bid),
   UNIQUE (info),
   UNIQUE (title)
@@ -145,7 +145,7 @@ CREATE TABLE aggregator_feed (
 --
 
 CREATE TABLE aggregator_item (
-  iid integer NOT NULL auto_increment,
+  iid SERIAL,
   fid integer NOT NULL default '0',
   title varchar(255) NOT NULL default '',
   link varchar(255) NOT NULL default '',
@@ -162,7 +162,7 @@ CREATE TABLE aggregator_item (
 
 CREATE TABLE cache (
   cid varchar(255) NOT NULL default '',
-  data text default '',
+  data bytea default '',
   expire integer NOT NULL default '0',
   created integer NOT NULL default '0',
   headers text default '',
@@ -181,6 +181,7 @@ CREATE TABLE comments (
   subject varchar(64) NOT NULL default '',
   comment text NOT NULL default '',
   hostname varchar(128) NOT NULL default '',
+  format smallint NOT NULL default '0',
   timestamp integer NOT NULL default '0',
   score integer NOT NULL default '0',
   status smallint  NOT NULL default '0',
@@ -213,26 +214,41 @@ CREATE TABLE directory (
 --
 
 CREATE TABLE files (
-  fid int(10) unsigned NOT NULL default '0',
-  nid int(10) unsigned NOT NULL default '0',
+  fid serial,
+  nid integer NOT NULL default '0',
   filename varchar(255) NOT NULL default '',
   filepath varchar(255) NOT NULL default '',
   filemime varchar(255) NOT NULL default '',
-  filesize int(10) unsigned NOT NULL default '0',
-  list tinyint(1) unsigned NOT NULL default '0',
+  filesize integer NOT NULL default '0',
+  list smallint NOT NULL default '0',
   PRIMARY KEY  (fid)
 );
 
+--
+-- Table structure for table 'filter_formats'
+--
+
+CREATE TABLE filter_formats (
+  format SERIAL,
+  name varchar(255) NOT NULL default '',
+  roles varchar(255) NOT NULL default '',
+  cache smallint NOT NULL default '0',
+  PRIMARY KEY (format)
+);
+
 --
 -- Table structure for table 'filters'
 --
 
 CREATE TABLE filters (
-  module varchar(64) NOT NULL default '',
-  weight smallint DEFAULT '0' NOT NULL,
-  PRIMARY KEY (module)
+  format integer NOT NULL DEFAULT '0',
+  module varchar(64) NOT NULL DEFAULT '',
+  delta smallint NOT NULL DEFAULT 1,
+  weight smallint DEFAULT '0' NOT NULL
 );
 
+CREATE INDEX filters_module_idx ON filters(module);
+
 --
 -- Table structure for table 'forum'
 --
@@ -274,10 +290,9 @@ CREATE TABLE locales_meta (
 -- Table structure for locales_source
 --
 
-CREATE sequence locales_source_lid_seq;
 
 CREATE TABLE locales_source (
-lid integer DEFAULT nextval('locales_source_lid_seq'::text) NOT NULL,
+lid serial,
   location varchar(128) NOT NULL default '',
   source text NOT NULL,
   PRIMARY KEY  (lid)
@@ -289,7 +304,7 @@ lid integer DEFAULT nextval('locales_source_lid_seq'::text) NOT NULL,
 
 CREATE TABLE locales_target (
   lid int4 NOT NULL default '0',
-  translation text NOT NULL,
+  translation text DEFAULT '' NOT NULL,
   locale varchar(12) NOT NULL default '',
   plid int4 NOT NULL default '0',
   plural int4 NOT NULL default '0',
@@ -303,8 +318,9 @@ CREATE TABLE locales_target (
 -- Table structure for table 'menu'
 --
 
+
 CREATE TABLE menu (
-  mid integer NOT NULL default '0',
+  mid serial,
   pid integer NOT NULL default '0',
   path varchar(255) NOT NULL default '',
   title varchar(255) NOT NULL default '',
@@ -313,7 +329,6 @@ CREATE TABLE menu (
   type smallint NOT NULL default '0',
   PRIMARY KEY  (mid)
 );
-
 --
 -- Table structure for table 'moderation_filters'
 --
@@ -370,6 +385,7 @@ CREATE TABLE node (
   changed integer NOT NULL default '0',
   revisions text NOT NULL default '',
   sticky integer NOT NULL default '0',
+  format smallint NOT NULL default '0',
   PRIMARY KEY  (nid)
 );
 CREATE INDEX node_type_idx ON node(type);
@@ -439,6 +455,7 @@ CREATE TABLE profile_fields (
   weight smallint DEFAULT '0' NOT NULL,
   required smallint DEFAULT '0' NOT NULL,
   visibility smallint DEFAULT '0' NOT NULL,
+  overview smallint DEFAULT '0' NOT NULL,
   options text,
   UNIQUE (name),
   PRIMARY KEY (fid)
@@ -725,22 +742,20 @@ INSERT INTO variable(name,value) VALUES('theme_default','s:10:"bluemarine";');
 INSERT INTO users(uid,name,mail) VALUES(0,'','');
 INSERT INTO users_roles(uid,rid) VALUES(0, 1);
 
-INSERT INTO role (rid, name) VALUES (1, 'anonymous user');
+INSERT INTO role (name) VALUES ('anonymous user');
 INSERT INTO permission VALUES (1,'access content',0);
 
-INSERT INTO role (rid, name) VALUES (2, 'authenticated user');
+INSERT INTO role (name) VALUES ('authenticated user');
 INSERT INTO permission VALUES (2,'access comments, access content, post comments, post comments without approval',0);
 
 INSERT INTO blocks(module,delta,status) VALUES('user', '0', '1');
 INSERT INTO blocks(module,delta,status) VALUES('user', '1', '1');
 
-INSERT INTO sequences (name, id) VALUES ('menu_mid', 1);
-
 INSERT INTO node_access VALUES (0, 0, 'all', 1, 0, 0);
 
-INSERT INTO filter_formats VALUES (1,'Filtered HTML',',1,2,',1);
-INSERT INTO filter_formats VALUES (2,'PHP code','',0);
-INSERT INTO filter_formats VALUES (3,'Full HTML','',1));
+INSERT INTO filter_formats (name, roles, cache) VALUES ('Filtered HTML',',1,2,',1);
+INSERT INTO filter_formats (name, roles, cache) VALUES ('PHP code','',0);
+INSERT INTO filter_formats (name, roles, cache) VALUES ('Full HTML','',1);
 INSERT INTO filters VALUES (1,'filter',0,0);
 INSERT INTO filters VALUES (1,'filter',3,1);
 INSERT INTO filters VALUES (2,'filter',1,0);
@@ -749,6 +764,12 @@ INSERT INTO variable (name,value) VALUES ('filter_html_1','i:1;');
 
 INSERT INTO locales_meta(locale, name, enabled, isdefault) VALUES('en', 'English', '1', '1');
 
+---
+--- Alter some sequences
+---
+ALTER SEQUENCE menu_mid_seq RESTART 2;
+
+
 ---
 --- Functions
 ---
diff --git a/database/updates.inc b/database/updates.inc
index 5b6ebb7824c4fb8d532b26500b21b9c7c77ee152..4466dc9ba8c4c74814f65453794393df579722fe 100644
--- a/database/updates.inc
+++ b/database/updates.inc
@@ -795,17 +795,30 @@ function update_79() {
 }
 
 function update_80() {
+  if ($GLOBALS['db_type'] == 'mysql') {
+    // Add a 'created' field to the users table:
+    $ret[] = update_sql('ALTER TABLE {users} ADD created INT(11) NOT NULL');
+    $ret[] = update_sql('ALTER TABLE {users} CHANGE timestamp changed INT(11) NOT NULL');
 
-  // Add a 'created' field to the users table:
-  $ret[] = update_sql('ALTER TABLE {users} ADD created INT(11) NOT NULL');
-  $ret[] = update_sql('ALTER TABLE {users} CHANGE timestamp changed INT(11) NOT NULL');
+    // Add some indices to speed up the update process:
+    $ret[] = update_sql('ALTER TABLE {comments} ADD index (timestamp)');
+    $ret[] = update_sql('ALTER TABLE {node} ADD index (created)');
 
-  // Add some indices to speed up the update process:
-  $ret[] = update_sql('ALTER TABLE {comments} ADD index (timestamp)');
-  $ret[] = update_sql('ALTER TABLE {node} ADD index (created)');
+    // Assign everyone a created timestamp to begin with:
+    $ret[] = update_sql("UPDATE {users} SET created = changed WHERE created = ''");
 
-  // Assign everyone a created timestamp to begin with:
-  $ret[] = update_sql("UPDATE {users} SET created = changed WHERE created = ''");
+  }
+  else {
+    // Add a 'created' field to the users table:
+    $ret[] = update_sql('ALTER TABLE {users} ADD created INTEGER');
+    $ret[] = update_sql("ALTER TABLE {users} ALTER COLUMN created SET DEFAULT '0'");
+    $ret[] = update_sql("UPDATE {users} SET created = 0");
+    $ret[] = update_sql("ALTER TABLE {users} ALTER COLUMN created SET NOT NULL");
+
+    $ret[] = update_sql('ALTER TABLE {users} RENAME timestamp TO changed');
+
+    $ret[] = update_sql("UPDATE {users} SET created = changed WHERE created = 0");
+  }
 
   // Print a status message:"
   print '<p>Note: this might take a while ...</p>';
@@ -830,29 +843,63 @@ function update_80() {
     db_query('UPDATE {users} SET created = %d WHERE created > %d AND uid <= %d', $timestamp, $timestamp, $account->uid);
   }
 
-  // Add profile module related tables:
-  $ret[] = update_sql("CREATE TABLE {profile_fields} (
-    fid int(10) NOT NULL auto_increment,
-    title varchar(255) default NULL,
-    name varchar(128) default NULL,
-    explanation TEXT default NULL,
-    category varchar(255) default NULL,
-    type varchar(128) default NULL,
-    weight tinyint(1) DEFAULT '0' NOT NULL,
-    overview tinyint(1) DEFAULT '0' NOT NULL,
-    options text,
-    KEY category (category),
-    UNIQUE KEY name (name),
-    PRIMARY KEY (fid)
-   );");
-
-  $ret[] = update_sql("CREATE TABLE {profile_values} (
-    fid int(11) unsigned default '0',
-    uid int(11) unsigned default '0',
-    value text,
-    KEY uid (uid),
-    KEY fid (fid)
-   );");
+  if ($GLOBALS['db_type'] == 'mysql') {
+    // Add profile module related tables:
+    $ret[] = update_sql("CREATE TABLE {profile_fields} (
+      fid int(10) NOT NULL auto_increment,
+      title varchar(255) default NULL,
+      name varchar(128) default NULL,
+      explanation TEXT default NULL,
+      category varchar(255) default NULL,
+      type varchar(128) default NULL,
+      weight tinyint(1) DEFAULT '0' NOT NULL,
+      overview tinyint(1) DEFAULT '0' NOT NULL,
+      options text,
+      KEY category (category),
+      UNIQUE KEY name (name),
+      PRIMARY KEY (fid)
+     );");
+
+    $ret[] = update_sql("CREATE TABLE {profile_values} (
+      fid int(11) unsigned default '0',
+      uid int(11) unsigned default '0',
+      value text,
+      KEY uid (uid),
+      KEY fid (fid)
+     );");
+    $ret[] = update_sql("ALTER TABLE {users} ADD picture varchar(255) NOT NULL DEFAULT ''");
+  }
+  else {
+
+    $ret[] = update_sql("CREATE TABLE profile_fields (
+      fid serial,
+      title varchar(255) default NULL,
+      name varchar(128) default NULL,
+      explanation TEXT default NULL,
+      category varchar(255) default NULL,
+      type varchar(128) default NULL,
+      weight smallint DEFAULT '0' NOT NULL,
+      overview smallint DEFAULT '0' NOT NULL,
+      options text,
+      UNIQUE (name),
+      PRIMARY KEY (fid)
+    )");
+    $ret[] = update_sql("CREATE INDEX profile_fields_category ON profile_fields (category)");
+
+    $ret[] = update_sql("CREATE TABLE profile_values (
+      fid integer default '0',
+      uid integer default '0',
+      value text
+    )");
+    $ret[] = update_sql("CREATE INDEX profile_values_uid ON profile_values (uid)");
+    $ret[] = update_sql("CREATE INDEX profile_values_fid ON profile_values (fid)");
+
+    $ret[] = update_sql("ALTER TABLE {users} ADD picture varchar(255)");
+    $ret[] = update_sql("ALTER TABLE {users} ALTER COLUMN picture SET DEFAULT ''");
+    $ret[] = update_sql("UPDATE {users} SET picture = ''");
+    $ret[] = update_sql("ALTER TABLE {users} ALTER COLUMN picture SET NOT NULL");
+
+  }
 
   // Migrate the old profile data to the new scheme:
   $fields = array(
@@ -882,7 +929,6 @@ function update_80() {
   foreach ($fields as $field) {
     db_query("INSERT INTO {profile_fields} (title, name, type, category, options, overview) VALUES ('%s', '%s', '%s', 'Personal information', '%s', %d)", $field[0], $field[1], $field[2], $field[3], $field[4]);
   }
-  db_query("ALTER TABLE {users} ADD picture varchar(255) NOT NULL DEFAULT ''");
 
   $result = db_query("SELECT uid FROM {users} WHERE uid > 0");
   while ($account = db_fetch_object($result)) {
@@ -965,7 +1011,7 @@ function update_83() {
   }
   else {
     $ret[] = update_sql("CREATE TABLE {menu} (
-  mid integer NOT NULL default '0',
+  mid serial,
   pid integer NOT NULL default '0',
   path varchar(255) NOT NULL default '',
   title varchar(255) NOT NULL default '',
@@ -1239,6 +1285,9 @@ function update_96() {
 }
 
 function update_97() {
+  /**
+   * Works for both PostgreSQL and MySQL
+   */
   $convert = array('node/view/' => 'node/', 'book/view/' => 'book/', 'user/view/' => 'user/');
   foreach ($convert as $from => $to) {
     $result = db_query("SELECT pid, src FROM {url_alias} WHERE src LIKE '%s%%'", $from);
@@ -1251,6 +1300,9 @@ function update_97() {
 }
 
 function update_98() {
+  /**
+   * Works for both PostgreSQL and MySQL
+   */
   $result = db_query("SELECT pid, src FROM {url_alias} WHERE src LIKE 'taxonomy/%%'", $from);
   while ($alias = db_fetch_object($result)) {
     list(, $page, $op, $terms) = explode('/', $alias->src);
@@ -1319,9 +1371,55 @@ function update_99() {
     $ret[] = update_sql("ALTER TABLE {page} DROP format");
   }
   else if ($GLOBALS['db_type'] == 'pgsql') {
-    // TODO: add pgsql equivalent. Whoever does this should pay attention that
-    // the keys/indices for the 'filters' table are correct. There was some
-    // inconsistency between the MySQL and PGSQL version before.
+    $result = db_query("SELECT * FROM {filters}");
+    if ($result) {
+      while ($obj = db_fetch_object($result)) {
+        $filters[] = $obj;
+      }
+    }
+
+    $ret[] = update_sql("DROP TABLE {filters}");
+
+    $ret[] = update_sql("CREATE TABLE {filters} (
+      format integer NOT NULL DEFAULT '0',
+      module varchar(64) NOT NULL DEFAULT '',
+      delta smallint NOT NULL DEFAULT 1,
+      weight smallint DEFAULT '0' NOT NULL
+    )");
+
+    $ret[] = update_sql("CREATE INDEX filters_module_idx ON filters(module)");
+    if (is_array($filters)) {
+      foreach ($filters as $filter) {
+        db_query("INSERT INTO {filters} VALUES (%d, '%s', %d, %d)", $filter->format ? $filter->format : 0, $filter->module, $filter->delta ? $filter->delta : 1, $filter->weight);
+      }
+    }
+
+    $ret[] = update_sql("CREATE TABLE {filter_formats} (
+      format SERIAL,
+      name varchar(255) NOT NULL default '',
+      roles varchar(255) NOT NULL default '',
+      cache smallint NOT NULL default '0',
+      PRIMARY KEY (format)
+    )");
+
+    $ret[] = update_sql("ALTER TABLE {boxes} RENAME type TO format");
+
+    $ret[] = update_sql("ALTER TABLE {comments} ADD format smallint");
+    $ret[] = update_sql("ALTER TABLE {comments} ALTER COLUMN format SET DEFAULT '0'");
+    $ret[] = update_sql("UPDATE {comments} SET format = '0'");
+    $ret[] = update_sql("ALTER TABLE {comments} ALTER COLUMN format SET NOT NULL");
+
+    $ret[] = update_sql("ALTER TABLE {node} ADD format smallint");
+    $ret[] = update_sql("ALTER TABLE {node} ALTER COLUMN format SET DEFAULT '0'");
+    $ret[] = update_sql("UPDATE {node} SET format = '0'");
+    $ret[] = update_sql("ALTER TABLE {node} ALTER COLUMN format SET NOT NULL");
+
+
+    /* Postgres usually can't drop columns
+    $ret[] = update_sql("ALTER TABLE {book} DROP format");
+    $ret[] = update_sql("ALTER TABLE {page} DROP format");
+    */
+
   }
 
   // Initialize all nodes and comments to the legacy format (see below)
@@ -1370,7 +1468,7 @@ function update_99() {
   }
   // Make sure the legacy format is accessible to all roles
   $all_roles = array_keys(user_roles());
-  $ret[] = update_sql("INSERT INTO {filter_formats} VALUES (1,'$default',',". implode(',', $all_roles) .",',1)");
+  $ret[] = update_sql("INSERT INTO {filter_formats} VALUES (". db_next_id("{filter_formats}_format") .",'$default',',". implode(',', $all_roles) .",',1)");
 
   // Determine which roles have the old 'create php content' permission.
   $res = db_query("SELECT rid FROM {permission} WHERE perm LIKE '%create php content%'");
@@ -1378,10 +1476,11 @@ function update_99() {
   while ($role = db_fetch_object($res)) {
     $php_roles[] = $role->rid;
   }
-  $ret[] = update_sql("INSERT INTO {filter_formats} VALUES (2,'PHP code','". implode(',', $php_roles) .",',0)");
+
+  $ret[] = update_sql("INSERT INTO {filter_formats} VALUES (". db_next_id("{filter_formats}_format") .",'PHP code','". implode(',', $php_roles) .",',0)");
 
   // This is a 'Full HTML' format which allows all HTML without restrictions.
-  $ret[] = update_sql("INSERT INTO {filter_formats} VALUES (3,'Full HTML','',1)");
+  $ret[] = update_sql("INSERT INTO {filter_formats} VALUES (". db_next_id("{filter_formats}_format") .",'Full HTML','',1)");
 
   // Set the default format to the legacy format
   variable_set('filter_default_format', 1);
@@ -1448,16 +1547,46 @@ function update_100() {
       KEY plid (plid),
       KEY plural (plural)
     )");
-    $ret[] = update_sql("INSERT INTO {locales_meta} (locale, name, enabled, isdefault) VALUES ('en', 'English', '1', '1')");
     $ret[] = update_sql("ALTER TABLE {users} CHANGE language language varchar(12) NOT NULL default ''");
   }
-  else { // TODO: pgsql support (see database.pgsql for suggestions)
+  else {
+    $ret[] = update_sql("CREATE TABLE {locales_target} (
+      lid int4 NOT NULL default '0',
+      translation text DEFAULT '' NOT NULL,
+      locale varchar(12) NOT NULL default '',
+      plid int4 NOT NULL default '0',
+      plural int4 NOT NULL default '0'
+    )");
+    $ret[] = update_sql("CREATE INDEX {locales_target}_lid ON {locales_target}(lid)");
+    $ret[] = update_sql("CREATE INDEX {locales_target}_locale ON {locales_target}(locale)");
+    $ret[] = update_sql("CREATE INDEX {locales_target}_plid ON {locales_target}(plid)");
+    $ret[] = update_sql("CREATE INDEX {locales_target}_plural ON {locales_target}(plural)");
+
+    $ret[] = update_sql("CREATE SEQUENCE {locales_source}_lid INCREMENT 1 START 0 MINVALUE 0");
+    $ret[] = update_sql("CREATE TABLE {locales_source} (
+      lid serial,
+      location varchar(128) NOT NULL default '',
+      source text NOT NULL,
+      PRIMARY KEY  (lid)
+    )");
+
+    $ret[] = update_sql("ALTER TABLE {users} rename language to lang_archive");
+    $ret[] = update_sql("ALTER TABLE {users} add language varchar(12)");
+    $ret[] = update_sql("ALTER TABLE {users} ALTER language SET DEFAULT ''");
+    $ret[] = update_sql("UPDATE {users} SET language = ''");
+    $ret[] = update_sql("ALTER TABLE {users} ALTER language SET NOT NULL");
+    $ret[] = update_sql("update {users} set language = lang_archive");
+
   }
+  $ret[] = update_sql("INSERT INTO {locales_meta} (locale, name, enabled, isdefault) VALUES ('en', 'English', '1', '1')");
 
   return $ret;
 }
 
 function update_101() {
+  /**
+   * Works for both PostgreSQL and MySQL
+   */
   include_once 'includes/locale.inc';
   // get the language columns
   $result = db_query('SELECT * FROM {locales} LIMIT 1');
@@ -1516,25 +1645,45 @@ function update_101() {
 }
 
 function update_102() {
+  /**
+   * Works for both PostgreSQL and MySQL
+   */
   return array(update_sql("INSERT INTO {system} (filename, name, type, description, status, throttle, bootstrap) VALUES ('modules/legacy.module', 'legacy', 'module', '', 1, 0, 0)"));
 }
 
 function update_103() {
   $ret = array();
-  $ret[] = update_sql("CREATE TABLE {files} (
-    fid int(10) unsigned NOT NULL default '0',
-    nid int(10) 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(10) unsigned NOT NULL default '0',
-    list tinyint(1) unsigned NOT NULL default '0',
-    PRIMARY KEY  (fid)
-  )");
+  if ($GLOBALS['db_type'] == 'mysql') {
+    $ret[] = update_sql("CREATE TABLE {files} (
+      fid int(10) unsigned NOT NULL default '0',
+      nid int(10) 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(10) unsigned NOT NULL default '0',
+      list tinyint(1) unsigned NOT NULL default '0',
+      PRIMARY KEY  (fid)
+    )");
+  }
+  else {
+    $ret[] = update_sql("CREATE TABLE {files} (
+      fid serial,
+      nid integer NOT NULL default '0',
+      filename varchar(255) NOT NULL default '',
+      filepath varchar(255) NOT NULL default '',
+      filemime varchar(255) NOT NULL default '',
+      filesize integer NOT NULL default '0',
+      list smallint NOT NULL default '0',
+      PRIMARY KEY  (fid)
+    )");
+  }
   return $ret;
 }
 
 function update_104() {
+  /**
+   * Works for both PostgreSQL and MySQL
+   */
   $ret = array();
   if (variable_get('theme_default', 'xtemplate') == 'chameleon') {
     $ret[] = update_sql("DELETE FROM {system} WHERE name = 'chameleon'");
@@ -1562,6 +1711,7 @@ function update_104() {
   return $ret;
 }
 
+
 function update_sql($sql) {
   $edit = $_POST["edit"];
   $result = db_query($sql);
diff --git a/includes/bootstrap.inc b/includes/bootstrap.inc
index 94c1b077f86eec5cc707169266a6efcbed289905..7bfcaa91f13e883d561af1737c0e9071f30bbc20 100644
--- a/includes/bootstrap.inc
+++ b/includes/bootstrap.inc
@@ -121,10 +121,12 @@ function cache_get($key) {
  *   A string containing HTTP header information for cached pages.
  */
 function cache_set($cid, $data, $expire = 0, $headers = NULL) {
-  db_query("UPDATE {cache} SET data = '%s', created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, time(), $expire, $headers, $cid);
+  $data = db_encode_blob($data);
+
+  db_query("UPDATE {cache} SET data = '$data', created = " . time() . ", expire = $expire, headers = '$headers' WHERE cid = '$cid'");
   if (!db_affected_rows()) {
-    db_query("INSERT INTO {cache} (cid, data, created, expire, headers) VALUES('%s', '%s', %d, %d, '%s')", $cid, $data, time(), $expire, $headers);
-  }
+   db_query("INSERT INTO {cache} (cid, data, created, expire, headers) VALUES('$cid', '$data', " . time() . ", $expire, '$headers')");
+ }
 }
 
 /**
@@ -250,7 +252,7 @@ function drupal_page_header() {
         header($header);
       }
 
-      print $cache->data;
+      print db_decode_blob($cache->data);
 
       // Call all init() and exit() hooks without including all modules.
       // Only use those hooks for critical operations.
diff --git a/includes/database.inc b/includes/database.inc
index b0e98fcdf9af6c0edf042dec9ecbc95e3f73ec89..ddfaf5d4c54ebb7c80d3be55393283e785acdde2 100644
--- a/includes/database.inc
+++ b/includes/database.inc
@@ -108,7 +108,7 @@ function db_set_active($name = 'default') {
       include_once 'includes/database.mysql.inc';
     }
     else {
-      include_once 'includes/database.pear.inc';
+      include_once 'includes/database.pgsql.inc';
     }
 
     $db_conns[$name] = db_connect($connect_url);
diff --git a/includes/database.mysql.inc b/includes/database.mysql.inc
index 698ec1ce3e2013bddee2d1c3a749acb0441ab96d..ff0919fdcc9549fce72339e7ba65158205d79d87 100644
--- a/includes/database.mysql.inc
+++ b/includes/database.mysql.inc
@@ -261,6 +261,30 @@ function db_query_range($query) {
   return _db_query($query);
 }
 
+/**
+ * Returns a properly formatted Binary Large OBject value.
+ *
+ * @param $data
+ *   Data to encode.
+ * @return
+ *  Encoded data.
+ */
+function db_encode_blob($data) {
+  return $data;
+}
+
+/**
+ * Returns text from a Binary Large OBject value.
+ *
+ * @param $data
+ *   Data to decode.
+ * @return
+ *  Decoded data.
+ */
+function db_decode_blob($data) {
+  return $data;
+}
+
 /**
  * @} end of addtogroup database
  */
diff --git a/includes/database.pgsql.inc b/includes/database.pgsql.inc
new file mode 100644
index 0000000000000000000000000000000000000000..9ea863d5161788d6b02d6cdeab82f913c3c3ce42
--- /dev/null
+++ b/includes/database.pgsql.inc
@@ -0,0 +1,285 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Database interface code for postgresql database servers.
+ */
+
+/**
+ * @addtogroup database
+ * @{
+ */
+
+/**
+ * Initialize a database connection.
+ *
+ * Note that you can change the pg_connect() call to pg_pconnect() if you
+ * want to use persistent connections. This is not recommended on shared hosts,
+ * and might require additional database/webserver tuning. It can increase
+ * performance, however, when the overhead to connect to your database is high
+ * (e.g. your database and web server live on different machines).
+ */
+function db_connect($url) {
+  $url = parse_url($url);
+
+  $conn_string = ' user='. $url['user'] .' dbname='. substr($url['path'], 1) .' password='. $url['pass'];
+  $connection = pg_connect($conn_string) or die(pg_last_error());
+
+  return $connection;
+}
+
+/**
+ * Runs a basic query in the active database.
+ *
+ * User-supplied arguments to the query should be passed in as separate parameters
+ * so that they can be properly escaped to avoid SQL injection attacks.
+ *
+ * @param $query
+ *   A string containing an SQL query.
+ * @param ...
+ *   A variable number of arguments which are substituted into the query using
+ *   printf() syntax.
+ * @return
+ *   A database query result resource, or FALSE if the query was not executed
+ *   correctly.
+ */
+function db_query($query) {
+  $args = func_get_args();
+
+  $query = db_prefix_tables($query);
+  if (count($args) > 1) {
+    if(is_array($args[1])){
+      $args1 = array_map('check_query', $args[1]);
+      $nargs = array_merge(array($query), $args1);
+    }
+    else {
+      $nargs = array_map('check_query', $args);
+      $nargs[0] = $query;
+    }
+    return _db_query(call_user_func_array('sprintf', $nargs));
+  }
+  else {
+    return _db_query($query);
+  }
+}
+
+/**
+ * Debugging version of db_query().
+ *
+ * Echoes the query to the browser.
+ */
+function db_queryd($query) {
+  $args = func_get_args();
+  $query = db_prefix_tables($query);
+  if (count($args) > 1) {
+    if(is_array($args[1])){
+      $args1 = array_map('check_query', $args[1]);
+      $nargs = array_merge(array($query), $args1);
+    }
+    else {
+      $nargs = array_map('check_query', $args);
+      $nargs[0] = $query;
+    }
+    return _db_query(call_user_func_array('sprintf', $nargs), 1);
+  }
+  else {
+    return _db_query($query, 1);
+  }
+}
+
+/**
+ * Helper function for db_query().
+ */
+function _db_query($query, $debug = 0) {
+  global $active_db, $last_result;
+  global $queries;
+
+  if (variable_get('dev_query', 0)) {
+    list($usec, $sec) = explode(' ', microtime());
+    $timer = (float)$usec + (float)$sec;
+  }
+
+  $last_result = pg_query($active_db, $query);
+
+  if (variable_get('dev_query', 0)) {
+    list($usec, $sec) = explode(' ', microtime());
+    $stop = (float)$usec + (float)$sec;
+    $diff = $stop - $timer;
+    $queries[] = array($query, $diff);
+  }
+
+  if ($debug) {
+    print '<p>query: '. $query .'<br />error:'. pg_last_error() .'</p>';
+  }
+
+  if ($last_result !== FALSE) {
+    return $last_result;
+  }
+  else {
+    trigger_error(pg_last_error() ."\nquery: ". htmlspecialchars($query), E_USER_ERROR);
+  }
+}
+
+/**
+ * Fetch one result row from the previous query as an object.
+ *
+ * @param $result
+ *   A database query result resource, as returned from db_query().
+ * @return
+ *   An object representing the next row of the result. The attributes of this
+ *   object are the table fields selected by the query.
+ */
+function db_fetch_object($result) {
+  if ($result) {
+    return pg_fetch_object($result);
+  }
+}
+
+/**
+ * Fetch one result row from the previous query as an array.
+ *
+ * @param $result
+ *   A database query result resource, as returned from db_query().
+ * @return
+ *   An associative array representing the next row of the result. The keys of
+ *   this object are the names of the table fields selected by the query, and
+ *   the values are the field values for this result row.
+ */
+function db_fetch_array($result) {
+  if ($result) {
+    return pg_fetch_assoc($result);
+  }
+}
+
+/**
+ * Determine how many result rows were found by the preceding query.
+ *
+ * @param $result
+ *   A database query result resource, as returned from db_query().
+ * @return
+ *   The number of result rows.
+ */
+function db_num_rows($result) {
+  if ($result) {
+    return pg_num_rows($result);
+  }
+}
+
+/**
+ * Return an individual result field from the previous query.
+ *
+ * Only use this function if exactly one field is being selected; otherwise,
+ * use db_fetch_object() or db_fetch_array().
+ *
+ * @param $result
+ *   A database query result resource, as returned from db_query().
+ * @param $row
+ *   The index of the row whose result is needed.
+ * @return
+ *   The resulting field.
+ */
+function db_result($result, $row = 0) {
+  if ($result && pg_num_rows($result) > $row) {
+    $res = pg_fetch_row($result, $row);
+
+    return $res[0];
+  }
+}
+
+/**
+ * Determine whether the previous query caused an error.
+ */
+function db_error() {
+  return pg_last_error();
+}
+
+/**
+ * Return a new unique ID in the given sequence.
+ *
+ * For compatibility reasons, Drupal does not use auto-numbered fields in its
+ * database tables. Instead, this function is used to return a new unique ID
+ * of the type requested. If necessary, a new sequence with the given name
+ * will be created.
+ */
+function db_next_id($name) {
+  $id = db_result(db_query("SELECT nextval('public.%s_seq')", db_prefix_tables($name)));
+  return $id;
+}
+
+/**
+ * Determine the number of rows changed by the preceding query.
+ */
+function db_affected_rows() {
+  global $last_result;
+  return pg_affected_rows($last_result);
+}
+
+/**
+ * Runs a limited-range query in the active database.
+ *
+ * Use this as a substitute for db_query() when a subset of the query is to be
+ * returned.
+ * User-supplied arguments to the query should be passed in as separate parameters
+ * so that they can be properly escaped to avoid SQL injection attacks.
+ *
+ * @param $query
+ *   A string containing an SQL query.
+ * @param ...
+ *   A variable number of arguments which are substituted into the query using
+ *   printf() syntax.
+ * @param $from
+ *   The first result row to return.
+ * @param $count
+ *   The maximum number of result rows to return.
+ * @return
+ *   A database query result resource, or FALSE if the query was not executed
+ *   correctly.
+ */
+function db_query_range($query) {
+  $args = func_get_args();
+  $count = array_pop($args);
+  $from = array_pop($args);
+  if (count(func_get_args()) > 3) {
+    $args = array_map('check_query', $args);
+    $query = db_prefix_tables($query);
+    $args[0] = $query;
+    $query = call_user_func_array('sprintf', $args);
+  }
+  else {
+    $query = func_get_arg(0);
+    $query = db_prefix_tables($query);
+  }
+  $query .= ' LIMIT '. $count .' OFFSET '. $from;
+  return _db_query($query);
+}
+
+/**
+ * Returns a properly formatted Binary Large OBject value.
+ *
+ * @param $data
+ *   Data to encode.
+ * @return
+ *  Encoded data.
+ */
+function db_encode_blob($data) {
+  return pg_escape_bytea($data);
+}
+
+/**
+ * Returns text from a Binary Large OBject value.
+ *
+ * @param $data
+ *   Data to decode.
+ * @return
+ *  Decoded data.
+ */
+function db_decode_blob($data) {
+  return stripcslashes($data);
+}
+
+/**
+ * @} end of addtogroup database
+ */
+
+?>
diff --git a/includes/locale.inc b/includes/locale.inc
index 4bc4b4af2709bf79669facd541b00fabcd59d451..8b9aa5c20fe229e7333723165d75bf19c82b7d65 100644
--- a/includes/locale.inc
+++ b/includes/locale.inc
@@ -123,7 +123,7 @@ function _locale_import_po($file, $lang, $mode) {
   // If not in 'safe mode', increase the maximum execution time:
   if (!ini_get('safe_mode')) {
     set_time_limit(240);
-  }  
+  }
 
   // Check if we have the language already in the database
   if (!db_fetch_object(db_query("SELECT locale FROM {locales_meta} WHERE locale = '%s'", $lang))) {
diff --git a/modules/archive.module b/modules/archive.module
index 57bea34199e3fc7e2bff85f8858158826ad09290..abc8148ad5444b9345dde47706bedaa36279f05f 100644
--- a/modules/archive.module
+++ b/modules/archive.module
@@ -253,7 +253,7 @@ function archive_page($year = 0, $month = 0, $day = 0) {
 
   if ($year && $month && $day) {
     // Fetch nodes for the selected date, if one was specified.
-    $result = db_query_range('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() .' WHERE n.status = 1 AND n.created > %d AND n.created < %d AND '. node_access_where_sql() .' ORDER BY n.created', $date, $date_end, 0, 20);
+    $result = db_query_range('SELECT DISTINCT(n.nid), n.created FROM {node} n '. node_access_join_sql() .' WHERE n.status = 1 AND n.created > %d AND n.created < %d AND '. node_access_where_sql() .' ORDER BY n.created', $date, $date_end, 0, 20);
 
     while ($nid = db_fetch_object($result)) {
       $output .= node_view(node_load(array('nid' => $nid->nid)), 1);
diff --git a/modules/archive/archive.module b/modules/archive/archive.module
index 57bea34199e3fc7e2bff85f8858158826ad09290..abc8148ad5444b9345dde47706bedaa36279f05f 100644
--- a/modules/archive/archive.module
+++ b/modules/archive/archive.module
@@ -253,7 +253,7 @@ function archive_page($year = 0, $month = 0, $day = 0) {
 
   if ($year && $month && $day) {
     // Fetch nodes for the selected date, if one was specified.
-    $result = db_query_range('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() .' WHERE n.status = 1 AND n.created > %d AND n.created < %d AND '. node_access_where_sql() .' ORDER BY n.created', $date, $date_end, 0, 20);
+    $result = db_query_range('SELECT DISTINCT(n.nid), n.created FROM {node} n '. node_access_join_sql() .' WHERE n.status = 1 AND n.created > %d AND n.created < %d AND '. node_access_where_sql() .' ORDER BY n.created', $date, $date_end, 0, 20);
 
     while ($nid = db_fetch_object($result)) {
       $output .= node_view(node_load(array('nid' => $nid->nid)), 1);
diff --git a/modules/block.module b/modules/block.module
index df0a6761842c130a72665d70e03df5c027a565ef..9011c79845726e4b0d7592467e54478c859ad22a 100644
--- a/modules/block.module
+++ b/modules/block.module
@@ -366,7 +366,7 @@ function block_list($region) {
         */
         if (!($block['throttle'] && (module_invoke('throttle', 'status') > 4))) {
           $array = module_invoke($block['module'], 'block', 'view', $block['delta']);
-          if (is_array($array)) { 
+          if (is_array($array)) {
             $block = array_merge($block, $array);
           }
         }
diff --git a/modules/block/block.module b/modules/block/block.module
index df0a6761842c130a72665d70e03df5c027a565ef..9011c79845726e4b0d7592467e54478c859ad22a 100644
--- a/modules/block/block.module
+++ b/modules/block/block.module
@@ -366,7 +366,7 @@ function block_list($region) {
         */
         if (!($block['throttle'] && (module_invoke('throttle', 'status') > 4))) {
           $array = module_invoke($block['module'], 'block', 'view', $block['delta']);
-          if (is_array($array)) { 
+          if (is_array($array)) {
             $block = array_merge($block, $array);
           }
         }
diff --git a/modules/blog.module b/modules/blog.module
index 5711bd7b5be80856c962f11829cab4ac8ef5d05d..d1a97da32348c65c36f9baa40eb62d18df02263a 100644
--- a/modules/blog.module
+++ b/modules/blog.module
@@ -141,7 +141,7 @@ function blog_page_user($uid) {
   $title = t("%name's blog", array('%name' => $account->name));
   $output = '';
 
-  $result = pager_query('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() ." WHERE type = 'blog' AND n.uid = %d AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.sticky DESC, n.created DESC', variable_get('default_nodes_main', 10), 0, NULL, $account->uid);
+  $result = pager_query('SELECT DISTINCT(n.nid), n.sticky, n.created FROM {node} n '. node_access_join_sql() ." WHERE type = 'blog' AND n.uid = %d AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.sticky DESC, n.created DESC', variable_get('default_nodes_main', 10), 0, NULL, $account->uid);
   while ($node = db_fetch_object($result)) {
     $output .= node_view(node_load(array('nid' => $node->nid)), 1);
   }
@@ -160,7 +160,7 @@ function blog_page_last() {
 
   $output = '';
 
-  $result = pager_query('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', variable_get('default_nodes_main', 10));
+  $result = pager_query('SELECT DISTINCT(n.nid), n.created FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', variable_get('default_nodes_main', 10));
 
   while ($node = db_fetch_object($result)) {
     $output .= node_view(node_load(array('nid' => $node->nid)), 1);
@@ -292,7 +292,7 @@ function blog_block($op = 'list', $delta = 0) {
   }
   else {
     if (user_access('access content')) {
-      $block['content'] = node_title_list(db_query_range('SELECT DISTINCT(n.nid), n.title FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', 0, 10));
+      $block['content'] = node_title_list(db_query_range('SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', 0, 10));
       $block['content'] .= '<div class="more-link">'. l(t('more'), 'blog', array('title' => t('Read the latest blog entries.'))) .'</div>';
       $block['subject'] = t('Recent blog posts');
     }
diff --git a/modules/blog/blog.module b/modules/blog/blog.module
index 5711bd7b5be80856c962f11829cab4ac8ef5d05d..d1a97da32348c65c36f9baa40eb62d18df02263a 100644
--- a/modules/blog/blog.module
+++ b/modules/blog/blog.module
@@ -141,7 +141,7 @@ function blog_page_user($uid) {
   $title = t("%name's blog", array('%name' => $account->name));
   $output = '';
 
-  $result = pager_query('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() ." WHERE type = 'blog' AND n.uid = %d AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.sticky DESC, n.created DESC', variable_get('default_nodes_main', 10), 0, NULL, $account->uid);
+  $result = pager_query('SELECT DISTINCT(n.nid), n.sticky, n.created FROM {node} n '. node_access_join_sql() ." WHERE type = 'blog' AND n.uid = %d AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.sticky DESC, n.created DESC', variable_get('default_nodes_main', 10), 0, NULL, $account->uid);
   while ($node = db_fetch_object($result)) {
     $output .= node_view(node_load(array('nid' => $node->nid)), 1);
   }
@@ -160,7 +160,7 @@ function blog_page_last() {
 
   $output = '';
 
-  $result = pager_query('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', variable_get('default_nodes_main', 10));
+  $result = pager_query('SELECT DISTINCT(n.nid), n.created FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', variable_get('default_nodes_main', 10));
 
   while ($node = db_fetch_object($result)) {
     $output .= node_view(node_load(array('nid' => $node->nid)), 1);
@@ -292,7 +292,7 @@ function blog_block($op = 'list', $delta = 0) {
   }
   else {
     if (user_access('access content')) {
-      $block['content'] = node_title_list(db_query_range('SELECT DISTINCT(n.nid), n.title FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', 0, 10));
+      $block['content'] = node_title_list(db_query_range('SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n '. node_access_join_sql() ." WHERE n.type = 'blog' AND n.status = 1 AND ". node_access_where_sql() .' ORDER BY n.created DESC', 0, 10));
       $block['content'] .= '<div class="more-link">'. l(t('more'), 'blog', array('title' => t('Read the latest blog entries.'))) .'</div>';
       $block['subject'] = t('Recent blog posts');
     }
diff --git a/modules/book.module b/modules/book.module
index fe21ba011612584e9defed42198507a34ba9c63d..f4a8475154567b846b5171a969d20cff70120954 100644
--- a/modules/book.module
+++ b/modules/book.module
@@ -358,7 +358,7 @@ function book_prev($node) {
  */
 function book_next($node) {
   // get first direct child
-  $child = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') ORDER BY b.weight ASC, n.title ASC", $node->nid));
+  $child = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') ORDER BY b.weight ASC, n.title ASC", $node->nid));
   if ($child) {
     return $child;
   }
@@ -367,7 +367,7 @@ function book_next($node) {
   array_push($path = book_location($node), $node); // Path to top-level node including this one.
 
   while (($leaf = array_pop($path)) && count($path)) {
-    $next = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') AND (b.weight > %d OR (b.weight = %d AND n.title > '%s')) ORDER BY b.weight ASC, n.title ASC", $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
+    $next = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') AND (b.weight > %d OR (b.weight = %d AND n.title > '%s')) ORDER BY b.weight ASC, n.title ASC", $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
     if ($next) {
       return $next;
     }
@@ -508,7 +508,7 @@ function book_toc_recurse($nid, $indent, $toc, $children, $exclude) {
 }
 
 function book_toc($exclude = 0) {
-  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' ORDER BY b.weight, n.title');
+  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent, b.weight FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' ORDER BY b.weight, n.title');
 
   while ($node = db_fetch_object($result)) {
     if (!$children[$node->parent]) {
@@ -561,7 +561,7 @@ function book_tree_recurse($nid, $depth, $children, $unfold = array()) {
 }
 
 function book_tree($parent = 0, $depth = 3, $unfold = array()) {
-  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.moderate = 0 ORDER BY b.weight, n.title');
+  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent, b.weight FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.moderate = 0 ORDER BY b.weight, n.title');
 
   while ($node = db_fetch_object($result)) {
     $list = $children[$node->parent] ? $children[$node->parent] : array();
@@ -604,7 +604,7 @@ function book_render() {
  */
 function book_print($nid = 0, $depth = 1) {
   global $base_url;
-  $result = db_query('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.nid = %d AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title', $nid);
+  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.nid = %d AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title', $nid);
 
   while ($page = db_fetch_object($result)) {
     // load the node:
@@ -634,7 +634,7 @@ function book_print($nid = 0, $depth = 1) {
 }
 
 function book_print_recurse($parent = '', $depth = 1) {
-  $result = db_query("SELECT DISTINCT(n.nid) FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND ". node_access_where_sql() ." AND b.parent = '$parent' AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title");
+  $result = db_query("SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND ". node_access_where_sql() ." AND b.parent = '$parent' AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title");
 
   while ($page = db_fetch_object($result)) {
     // Load the node:
diff --git a/modules/book/book.module b/modules/book/book.module
index fe21ba011612584e9defed42198507a34ba9c63d..f4a8475154567b846b5171a969d20cff70120954 100644
--- a/modules/book/book.module
+++ b/modules/book/book.module
@@ -358,7 +358,7 @@ function book_prev($node) {
  */
 function book_next($node) {
   // get first direct child
-  $child = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') ORDER BY b.weight ASC, n.title ASC", $node->nid));
+  $child = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') ORDER BY b.weight ASC, n.title ASC", $node->nid));
   if ($child) {
     return $child;
   }
@@ -367,7 +367,7 @@ function book_next($node) {
   array_push($path = book_location($node), $node); // Path to top-level node including this one.
 
   while (($leaf = array_pop($path)) && count($path)) {
-    $next = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') AND (b.weight > %d OR (b.weight = %d AND n.title > '%s')) ORDER BY b.weight ASC, n.title ASC", $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
+    $next = db_fetch_object(db_query("SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE b.parent = %d AND n.status = 1 AND ". node_access_where_sql() ." AND (n.moderate = 0 OR n.revisions != '') AND (b.weight > %d OR (b.weight = %d AND n.title > '%s')) ORDER BY b.weight ASC, n.title ASC", $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
     if ($next) {
       return $next;
     }
@@ -508,7 +508,7 @@ function book_toc_recurse($nid, $indent, $toc, $children, $exclude) {
 }
 
 function book_toc($exclude = 0) {
-  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' ORDER BY b.weight, n.title');
+  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent, b.weight FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' ORDER BY b.weight, n.title');
 
   while ($node = db_fetch_object($result)) {
     if (!$children[$node->parent]) {
@@ -561,7 +561,7 @@ function book_tree_recurse($nid, $depth, $children, $unfold = array()) {
 }
 
 function book_tree($parent = 0, $depth = 3, $unfold = array()) {
-  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.moderate = 0 ORDER BY b.weight, n.title');
+  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.parent, b.weight FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.moderate = 0 ORDER BY b.weight, n.title');
 
   while ($node = db_fetch_object($result)) {
     $list = $children[$node->parent] ? $children[$node->parent] : array();
@@ -604,7 +604,7 @@ function book_render() {
  */
 function book_print($nid = 0, $depth = 1) {
   global $base_url;
-  $result = db_query('SELECT DISTINCT(n.nid) FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.nid = %d AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title', $nid);
+  $result = db_query('SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n '. node_access_join_sql() .' INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND '. node_access_where_sql() .' AND n.nid = %d AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title', $nid);
 
   while ($page = db_fetch_object($result)) {
     // load the node:
@@ -634,7 +634,7 @@ function book_print($nid = 0, $depth = 1) {
 }
 
 function book_print_recurse($parent = '', $depth = 1) {
-  $result = db_query("SELECT DISTINCT(n.nid) FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND ". node_access_where_sql() ." AND b.parent = '$parent' AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title");
+  $result = db_query("SELECT DISTINCT(n.nid), n.title, b.weight FROM {node} n ". node_access_join_sql() ." INNER JOIN {book} b ON n.nid = b.nid WHERE n.status = 1 AND ". node_access_where_sql() ." AND b.parent = '$parent' AND (n.moderate = 0 OR n.revisions IS NOT NULL) ORDER BY b.weight, n.title");
 
   while ($page = db_fetch_object($result)) {
     // Load the node:
diff --git a/modules/poll.module b/modules/poll.module
index 34209894d6c7a631a5b7fa591ce72b6123d95efe..e3973501143dad0c256c77c6b6624a1e49204588 100644
--- a/modules/poll.module
+++ b/modules/poll.module
@@ -272,7 +272,7 @@ function poll_node_name($node) {
 
 function poll_page() {
   // List all polls
-  $result = pager_query("SELECT DISTINCT(n.nid), n.title, p.active, SUM(c.chvotes) AS votes FROM {node} n ". node_access_join_sql() ." INNER JOIN {poll} p ON n.nid=p.nid INNER JOIN {poll_choices} c ON n.nid=c.nid WHERE type = 'poll' AND status = 1 AND ". node_access_where_sql() ." AND moderate = 0 GROUP BY n.nid, n.title, p.active, n.created ORDER BY n.created DESC", 15);
+  $result = pager_query("SELECT DISTINCT(n.nid), n.title, p.active, n.created, SUM(c.chvotes) AS votes FROM {node} n ". node_access_join_sql() ." INNER JOIN {poll} p ON n.nid=p.nid INNER JOIN {poll_choices} c ON n.nid=c.nid WHERE type = 'poll' AND status = 1 AND ". node_access_where_sql() ." AND moderate = 0 GROUP BY n.nid, n.title, p.active, n.created ORDER BY n.created DESC", 15);
   $output = '<ul>';
   while ($node = db_fetch_object($result)) {
     $output .= '<li>'. l($node->title, "node/$node->nid") .' - '. format_plural($node->votes, '1 vote', '%count votes') .' - '. ($node->active ? t('open') : t('closed')) .'</li>';
diff --git a/modules/poll/poll.module b/modules/poll/poll.module
index 34209894d6c7a631a5b7fa591ce72b6123d95efe..e3973501143dad0c256c77c6b6624a1e49204588 100644
--- a/modules/poll/poll.module
+++ b/modules/poll/poll.module
@@ -272,7 +272,7 @@ function poll_node_name($node) {
 
 function poll_page() {
   // List all polls
-  $result = pager_query("SELECT DISTINCT(n.nid), n.title, p.active, SUM(c.chvotes) AS votes FROM {node} n ". node_access_join_sql() ." INNER JOIN {poll} p ON n.nid=p.nid INNER JOIN {poll_choices} c ON n.nid=c.nid WHERE type = 'poll' AND status = 1 AND ". node_access_where_sql() ." AND moderate = 0 GROUP BY n.nid, n.title, p.active, n.created ORDER BY n.created DESC", 15);
+  $result = pager_query("SELECT DISTINCT(n.nid), n.title, p.active, n.created, SUM(c.chvotes) AS votes FROM {node} n ". node_access_join_sql() ." INNER JOIN {poll} p ON n.nid=p.nid INNER JOIN {poll_choices} c ON n.nid=c.nid WHERE type = 'poll' AND status = 1 AND ". node_access_where_sql() ." AND moderate = 0 GROUP BY n.nid, n.title, p.active, n.created ORDER BY n.created DESC", 15);
   $output = '<ul>';
   while ($node = db_fetch_object($result)) {
     $output .= '<li>'. l($node->title, "node/$node->nid") .' - '. format_plural($node->votes, '1 vote', '%count votes') .' - '. ($node->active ? t('open') : t('closed')) .'</li>';
diff --git a/modules/taxonomy.module b/modules/taxonomy.module
index a358814f0dbdc8469f917d9f48471e94c163ec83..5ed419e3a1b631854c29630a81b1d7429905abc2 100644
--- a/modules/taxonomy.module
+++ b/modules/taxonomy.module
@@ -77,7 +77,7 @@ function taxonomy_block($op = 'list', $delta = 0) {
     return $blocks;
   }
   else if (user_access('access content')) {
-    $result = db_query("SELECT d.tid, d.name, MAX(n.created) AS updated, COUNT(*) AS count FROM {term_data} d INNER JOIN {term_node} USING (tid) INNER JOIN {node} n USING (nid) WHERE n.status = 1 GROUP BY d.tid ORDER BY updated DESC, d.name");
+    $result = db_query("SELECT d.tid, d.name, MAX(n.created) AS updated, COUNT(*) AS count FROM {term_data} d INNER JOIN {term_node} USING (tid) INNER JOIN {node} n USING (nid) WHERE n.status = 1 GROUP BY d.tid, d.name ORDER BY updated DESC, d.name");
     $items = array();
     while ($category = db_fetch_object($result)) {
       $items[] = l("$category->name ($category->count)", 'taxonomy/term/'. $category->tid) .'<br />'. format_interval(time() - $category->updated) .' '. t('ago');
diff --git a/modules/taxonomy/taxonomy.module b/modules/taxonomy/taxonomy.module
index a358814f0dbdc8469f917d9f48471e94c163ec83..5ed419e3a1b631854c29630a81b1d7429905abc2 100644
--- a/modules/taxonomy/taxonomy.module
+++ b/modules/taxonomy/taxonomy.module
@@ -77,7 +77,7 @@ function taxonomy_block($op = 'list', $delta = 0) {
     return $blocks;
   }
   else if (user_access('access content')) {
-    $result = db_query("SELECT d.tid, d.name, MAX(n.created) AS updated, COUNT(*) AS count FROM {term_data} d INNER JOIN {term_node} USING (tid) INNER JOIN {node} n USING (nid) WHERE n.status = 1 GROUP BY d.tid ORDER BY updated DESC, d.name");
+    $result = db_query("SELECT d.tid, d.name, MAX(n.created) AS updated, COUNT(*) AS count FROM {term_data} d INNER JOIN {term_node} USING (tid) INNER JOIN {node} n USING (nid) WHERE n.status = 1 GROUP BY d.tid, d.name ORDER BY updated DESC, d.name");
     $items = array();
     while ($category = db_fetch_object($result)) {
       $items[] = l("$category->name ($category->count)", 'taxonomy/term/'. $category->tid) .'<br />'. format_interval(time() - $category->updated) .' '. t('ago');