=== modified file 'includes/database/database.inc'
--- includes/database/database.inc	2008-12-06 09:01:58 +0000
+++ includes/database/database.inc	2008-12-07 05:20:52 +0000
@@ -117,7 +117,6 @@
  * DELETE queries have a similar pattern.
  */
 
-
 /**
  * Base Database API class.
  *
@@ -166,6 +165,24 @@
   protected $preparedStatements = array();
 
   /**
+   * Track the number of "layers" of transactions currently active.
+   *
+   * On many databases transactions cannot nest.  Instead, we track
+   * nested calls to transactions and collapse them into a single
+   * transaction.
+   *
+   * @var int
+   */
+  protected $transactionLayers = 0;
+
+  /**
+   * Whether or not the active transaction (if any) will be rolled back.
+   *
+   * @var boolean
+   */
+  protected $willRollBack;
+
+  /**
    * The name of the Select class for this connection.
    *
    * Normally this and the following class names would be static variables,
@@ -225,6 +242,14 @@
   protected $transactionSupport = TRUE;
 
   /**
+   * Whether this database connection supports transactional DDL.
+   * Set to FALSE by default because few databases support this feature.
+   *
+   * @var bool
+   */
+  protected $transactionalDDLSupport = FALSE;
+
+  /**
    * The schema object for this connection.
    *
    * @var object
@@ -649,6 +674,16 @@
   }
 
   /**
+   * Determine if there is an active transaction open.
+   *
+   * @return
+   *   TRUE if we're currently in a transaction, FALSE otherwise.
+   */
+  public function inTransaction() {
+    return ($this->transactionLayers > 0);
+  }
+
+  /**
    * Returns a new DatabaseTransaction object on this connection.
    *
    * @param $required
@@ -657,7 +692,7 @@
    *   this method will throw an exception and the operation will not be possible.
    * @see DatabaseTransaction
    */
-  public function startTransaction($required = FALSE) {
+  public function beginTransaction($required = FALSE) {
     if ($required && !$this->supportsTransactions()) {
       throw new TransactionsNotSupportedException();
     }
@@ -672,6 +707,78 @@
   }
 
   /**
+   * Schedule the current transaction for rollback. Throws an exception if no
+   * transaction is active.
+   */
+  public function rollBack() {
+    if ($this->transactionLayers == 0) {
+      throw new NoActiveTransactionException();
+    }
+
+    $this->willRollBack = TRUE;
+  }
+
+  /**
+   * Determine if this transaction will roll back. Use this function to skip
+   * further operations if the current transaction is already scheduled to
+   * roll back. Throws an exception if no transaction is active.
+   *
+   * @return
+   *   TRUE if the transaction will roll back, FALSE otherwise.
+   */
+  public function willRollBack() {
+    if ($this->transactionLayers == 0) {
+      throw new NoActiveTransactionException();
+    }
+
+    return $this->willRollBack;
+  }
+
+  /**
+   * Increases the depth of transaction nesting, beginning a transaction if one
+   * is not already active.
+   *
+   * @see DatabaseTransaction
+   */
+  public function pushTransaction() {
+    ++$this->transactionLayers;
+
+    if ($this->transactionLayers == 1) {
+      if ($this->supportsTransactions()) {
+        parent::beginTransaction();
+      }
+
+      // Reset any scheduled rollback
+      $this->willRollBack = FALSE;
+    }
+  }
+
+  /**
+   * Decreases the depth of transaction nesting, committing or rolling back a
+   * transaction if we are on the outermost layer of transactions. Throws a
+   * NoActiveTransactionException exception if no transaction is active.
+   *
+   * @see DatabaseTransaction
+   */
+  public function popTransaction() {
+    if ($this->transactionLayers == 0) {
+      throw new NoActiveTransactionException();
+    }
+
+    --$this->transactionLayers;
+
+    if ($this->transactionLayers == 0 && $this->supportsTransactions()) {
+      if ($this->willRollBack) {
+        parent::rollBack();
+      }
+      else {
+        parent::commit();
+      }
+    }
+    //return new $class_type($this);
+  }
+
+  /**
    * Runs a limited-range query on this database object.
    *
    * Use this as a substitute for ->query() when a subset of the query is to be
@@ -735,9 +842,24 @@
 
   /**
    * Determine if this driver supports transactions.
+   *
+   * @return
+   *   TRUE if this connection supports transactions, FALSE otherwise.
    */
   public function supportsTransactions() {
-   return $this->transactionSupport;
+    return $this->transactionSupport;
+  }
+
+  /**
+   * Determine if this driver supports transactional DDL.
+   *
+   * DDL queries are those that change the schema, such as ALTER queries.
+   *
+   * @return
+   *   TRUE if this connection supports transactions for DDL queries, FALSE otherwise.
+   */
+  public function supportsTransactionalDDL() {
+    return $this->transactionalDDLSupport;
   }
 
   /**
@@ -761,6 +883,20 @@
    *   The extra handling directives for the specified operator, or NULL.
    */
   abstract public function mapConditionOperator($operator);
+
+  /**
+   * Throws an exception to deny direct access to transaction commits.
+   *
+   * We do not want to allow users to commit transactions at any time, only
+   * by destroying the transaction object or allowing it to go out of scope.
+   * A direct commit bypasses all of the safety checks we've built on top of
+   * PDO's transaction routines.
+   *
+   * @see DatabaseTransaction
+   */
+  public function commit() {
+    throw new ExplicitTransactionsNotSupportedException();
+  }
 }
 
 /**
@@ -1121,7 +1257,20 @@
 class TransactionsNotSupportedException extends PDOException { }
 
 /**
- * A wrapper class for creating and managing database transactions.
+ * Exception to throw when popTransaction() is called when no transaction is active.
+ */
+class NoActiveTransactionException extends PDOException { }
+
+/**
+ * Exception to deny attempts to explicitly manage transactions.
+ *
+ * This exception will be thrown when the PDO connection commit() is called.
+ * Code should never call this method directly.
+ */
+class ExplicitTransactionsNotSupportedException extends PDOException { }
+
+/**
+ * A wrapper class for managing database transaction nesting and lifetime.
  *
  * Not all databases or database configurations support transactions.  For
  * example, MySQL MyISAM tables do not.  It is also easy to begin a transaction
@@ -1130,107 +1279,29 @@
  *
  * This class acts as a wrapper for transactions.  To begin a transaction,
  * simply instantiate it.  When the object goes out of scope and is destroyed
- * it will automatically commit.  It also will check to see if the specified
- * connection supports transactions.  If not, it will simply skip any transaction
- * commands, allowing user-space code to proceed normally.  The only difference
- * is that rollbacks won't actually do anything.
+ * it will automatically commit or roll back.
  *
  * In the vast majority of cases, you should not instantiate this class directly.
- * Instead, call ->startTransaction() from the appropriate connection object.
+ * Instead, call $connection->beginTransaction(), where $connection is a
+ * DatabaseConnection object.
  */
 class DatabaseTransaction {
 
   /**
-   * The connection object for this transaction.
+   * A reference to the connection object for this transaction.
    *
    * @var DatabaseConnection
    */
   protected $connection;
 
-  /**
-   * Whether or not this connection supports transactions.
-   *
-   * This can be derived from the connection itself with a method call,
-   * but is cached here for performance.
-   *
-   * @var boolean
-   */
-  protected $supportsTransactions;
-
-  /**
-   * Whether or not this transaction has been rolled back.
-   *
-   * @var boolean
-   */
-  protected $hasRolledBack = FALSE;
-
-  /**
-   * Whether or not this transaction has been committed.
-   *
-   * @var boolean
-   */
-  protected $hasCommitted = FALSE;
-
-  /**
-   * Track the number of "layers" of transactions currently active.
-   *
-   * On many databases transactions cannot nest.  Instead, we track
-   * nested calls to transactions and collapse them into a single
-   * transaction.
-   *
-   * @var int
-   */
-  protected static $layers = 0;
-
-  public function __construct(DatabaseConnection $connection) {
-    $this->connection = $connection;
-    $this->supportsTransactions = $connection->supportsTransactions();
-
-    if (self::$layers == 0 && $this->supportsTransactions) {
-      $connection->beginTransaction();
-    }
-
-    ++self::$layers;
-  }
-
-  /**
-   * Commit this transaction.
-   */
-  public function commit() {
-    --self::$layers;
-    if (self::$layers == 0 && $this->supportsTransactions) {
-      $this->connection->commit();
-      $this->hasCommitted = TRUE;
-    }
-  }
-
-  /**
-   * Roll back this transaction.
-   */
-  public function rollBack() {
-    if ($this->supportsTransactions) {
-      $this->connection->rollBack();
-      $this->hasRolledBack = TRUE;
-    }
-  }
-
-  /**
-   * Determine if this transaction has already been rolled back.
-   *
-   * @return
-   *   TRUE if the transaction has been rolled back, FALSE otherwise.
-   */
-  public function hasRolledBack() {
-    return $this->hasRolledBack;
+  public function __construct(DatabaseConnection &$connection) {
+    $this->connection = &$connection;
+    $this->connection->pushTransaction();
   }
 
   public function __destruct() {
-    --self::$layers;
-    if (self::$layers == 0 && $this->supportsTransactions && !$this->hasRolledBack && !$this->hasCommitted) {
-      $this->connection->commit();
-    }
+    $this->connection->popTransaction();
   }
-
 }
 
 /**
@@ -1703,6 +1774,26 @@
 }
 
 /**
+ * Returns a new transaction object for the active database.
+ *
+ * @param $required
+ *   TRUE if the calling code will not function properly without transaction
+ *   support.  If set to TRUE and the active database does not support transactions
+ *   a TransactionsNotSupportedException exception will be thrown.
+ * @param $options
+ *   An array of options to control how the transaction operates.  Only the
+ *   target key has any meaning in this case.
+ * @return
+ *   A new DatabaseTransaction object for this connection.
+ */
+function db_transaction($required = FALSE, Array $options = array()) {
+  if (empty($options['target'])) {
+    $options['target'] = 'default';
+  }
+  return Database::getActiveConnection($options['target'])->beginTransaction($required);
+}
+
+/**
  * Sets a new active database.
  *
  * @param $key

=== modified file 'includes/database/mysql/database.inc'
--- includes/database/mysql/database.inc	2008-12-06 09:01:58 +0000
+++ includes/database/mysql/database.inc	2008-12-07 05:19:36 +0000
@@ -16,6 +16,9 @@
   public function __construct(Array $connection_options = array()) {
     // This driver defaults to non transaction support.
     $this->transactionSupport = !empty($connection_option['transactions']);
+    
+    // MySQL never supports transactional DDL.
+    $this->transactionalDDLSupport = FALSE;
 
     // Default to TCP connection on port 3306.
     if (empty($connection_options['port'])) {

=== modified file 'includes/database/pgsql/database.inc'
--- includes/database/pgsql/database.inc	2008-12-06 09:01:58 +0000
+++ includes/database/pgsql/database.inc	2008-12-07 05:20:18 +0000
@@ -16,6 +16,10 @@
   public function __construct(Array $connection_options = array()) {
     // This driver defaults to transaction support, except if explicitly passed FALSE.
     $this->transactionSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] === FALSE;
+    
+    // Transactional DDL is always available in PostgreSQL,
+    // but we'll only enable it if standard transactions are.
+    $this->transactionalDDLSupport = $this->transactionSupport;
 
     // Default to TCP connection on port 5432.
     if (empty($connection_options['port'])) {

=== modified file 'modules/simpletest/tests/database_test.test'
--- modules/simpletest/tests/database_test.test	2008-12-06 09:01:58 +0000
+++ modules/simpletest/tests/database_test.test	2008-12-07 04:21:08 +0000
@@ -2030,3 +2030,175 @@
     $this->assertFalse(db_table_exists('temporary'), t('The temporary table is, indeed, temporary.'));
   }
 }
+
+/**
+ * Test transaction support.
+ */
+class DatabaseTransactionTestCase extends DatabaseTestCase {
+
+  function getInfo() {
+    return array(
+      'name' => t('Transaction tests'),
+      'description' => t('Test the transaction abstraction system.'),
+      'group' => t('Database'),
+    );
+  }
+
+  /**
+   * Helper method for transaction unit test.
+   *
+   * @param $suffix
+   *   Suffix to add to field values to differentiate tests.
+   * @param $rollback
+   *   Whether or not to try rolling back the transaction when we're done.
+   */
+  protected function transactionOuterLayer($suffix, $rollback = FALSE) {
+    $connection = Database::getActiveConnection();
+    $txn = db_transaction();
+
+    db_insert('test')
+      ->fields(array(
+        'name' => 'David' . $suffix,
+        'age' => '24',
+      ))
+      ->execute();
+
+    $this->assertTrue($connection->inTransaction(), t('In transaction before calling nested transaction.'));
+
+    $this->transactionInnerLayer($suffix, $rollback);
+
+    $this->assertTrue($connection->inTransaction(), t('In transaction after calling nested transaction.'));
+  }
+
+  /**
+   * Helper method for transaction unit tests.
+   *
+   * @param $suffix
+   *   Suffix to add to field values to differentiate tests.
+   * @param $rollback
+   *   Whether or not to try rolling back the transaction when we're done.
+   */
+  protected function transactionInnerLayer($suffix, $rollback = FALSE) {
+    $connection = Database::getActiveConnection();
+    $txn = db_transaction();
+
+    db_insert('test')
+      ->fields(array(
+        'name' => 'Daniel' . $suffix,
+        'age' => '19',
+      ))
+      ->execute();
+
+    $this->assertTrue($connection->inTransaction(), t('In transaction inside nested transaction.'));
+
+    if ($rollback) {
+      $connection->rollBack();
+      $this->assertTrue($connection->willRollBack(), t('Transaction is scheduled to roll back after calling rollBack().'));
+    }
+  }
+
+  /**
+   * Test that a database that claims to support transactions will return a transaction object.
+   *
+   * If the active connection does not support transactions, this test does nothing.
+   */
+  function testTransactionsSupported() {
+    try {
+      $connection = Database::getActiveConnection();
+      if ($connection->supportsTransactions()) {
+        $txn = db_transaction(TRUE);
+      }
+      $this->pass('Transaction started successfully.');
+    }
+    catch (TransactionsNotSupportedException $e) {
+      $this->fail("Exception thrown when it shouldn't have been.");
+    }
+  }
+
+  /**
+   * Test that a database that doesn't support transactions fails correctly.
+   *
+   * If the active connection supports transactions, this test does nothing.
+   */
+  function testTransactionsNotSupported() {
+    try {
+      $connection = Database::getActiveConnection();
+      if (!$connection->supportsTransactions()) {
+        $txn = db_transaction(TRUE);
+      }
+      $this->fail('No transaction failure registered.');
+    }
+    catch (TransactionsNotSupportedException $e) {
+      $this->pass("Exception thrown for unsupported transactions.");
+    }
+  }
+
+  /**
+   * Test transaction rollback on a database that supports transactions.
+   *
+   * If the active connection does not support transactions, this test does nothing.
+   */
+  function testTransactionRollBackSupported() {
+    // This test won't work right if transactions are not supported.
+    if (!Database::getActiveConnection()->supportsTransactions()) {
+      return;
+    }
+    try {
+      $this->transactionOuterLayer('B', TRUE);
+
+      $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'DavidB'))->fetchField();
+      $this->assertNotIdentical($saved_age, '24', t('Cannot retrieve DavidB row after commit.'));
+
+      $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'DanielB'))->fetchField();
+      $this->assertNotIdentical($saved_age, '19', t('Cannot retrieve DanielB row after commit.'));
+    }
+    catch(Exception $e) {
+      $this->fail($e->getMessage());
+    }
+  }
+
+  /**
+   * Test transaction rollback on a database that does not support transactions.
+   *
+   * If the active driver supports transactions, this test does nothing.
+   */
+  function testTransactionRollBackNotSupported() {
+    // This test won't work right if transactions are supported.
+    if (Database::getActiveConnection()->supportsTransactions()) {
+      return;
+    }
+    try {
+      $this->transactionOuterLayer('B', TRUE);
+
+      $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'DavidB'))->fetchField();
+      $this->assertIdentical($saved_age, '24', t('DavidB not rolled back, since transactions are not supported.'));
+
+      $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'DanielB'))->fetchField();
+      $this->assertIdentical($saved_age, '19', t('DanielB not rolled back, since transactions are not supported.'));
+    }
+    catch(Exception $e) {
+      $this->fail($e->getMessage());
+    }
+  }
+
+  /**
+   * Test committed transaction.
+   *
+   * The behavior of this test should be identical for connections that support
+   * transactions and those that do not.
+   */
+  function testCommittedTransaction() {
+    try {
+      $this->transactionOuterLayer('A');
+
+      $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'DavidA'))->fetchField();
+      $this->assertIdentical($saved_age, '24', t('Can retrieve DavidA row after commit.'));
+
+      $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'DanielA'))->fetchField();
+      $this->assertIdentical($saved_age, '19', t('Can retrieve DanielA row after commit.'));
+    }
+    catch(Exception $e) {
+      $this->fail($e->getMessage());
+    }
+  }
+}

