diff options
Diffstat (limited to 'framework/DataAccess')
-rw-r--r-- | framework/DataAccess/TAdodb.php | 256 | ||||
-rw-r--r-- | framework/DataAccess/TDatabaseProvider.php | 150 |
2 files changed, 336 insertions, 70 deletions
diff --git a/framework/DataAccess/TAdodb.php b/framework/DataAccess/TAdodb.php index f6b486e4..c7005c76 100644 --- a/framework/DataAccess/TAdodb.php +++ b/framework/DataAccess/TAdodb.php @@ -1,17 +1,100 @@ <?php
+/**
+ * TAdodb and TAdodbConnection class file.
+ *
+ * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
+ * @link http://www.pradosoft.com/
+ * @copyright Copyright © 2005 PradoSoft
+ * @license http://www.pradosoft.com/license/
+ * @version $Revision: $ $Date: $
+ * @package System.DataAccess
+ */
+/**
+ * Include the database provider base class.
+ */
Prado::using('System.DataAccess.TDatabaseProvider');
/**
- * Adbodb data access module.
+ * TAdodb database connection module.
+ *
+ * The TAdodb module class allows the database connection details to be
+ * specified in the application.xml or config.xml, the later are directory level
+ * configurations.
+ * <code>
+ * ...
+ * <modules>
+ * ...
+ * <module id="my_db1"
+ * class="TAdodb"
+ * ConnectionString="mysql://username:password@localhost/mydatabase" />
+ * ...
+ * </modules>
+ * ...
+ * </code>
+ * Where <tt>mysql</tt> is the driver name, <tt>username</tt> and
+ * <tt>password</tt> are the required credentials to connection to the database,
+ * <tt>localhost</tt> is the database resource and <tt>mydatabase</tt> is the
+ * name of database to connect to.
+ *
+ * The Adodb library supports many database drivers. The drivers included are
+ * # <tt>mysql</tt> MySQL without transactions.
+ * # <tt>mysqlt</tt> MySQL 3.23 or later with transaction support.
+ * # <tt>mysqli</tt> MySQLi extension, does not support transactions.
+ * # <tt>pdo_mysql</tt> PDO driver for MysSQL.
+ *
+ * # <tt>oracle</tt> Oracle 7.
+ * # <tt>oci8po</tt> Portable version of oci8 driver.
+ * # <tt>oci8</tt> Oracle (oci8).
+ * # <tt>oci805</tt> Oracle 8.0.5 driver.
+ * # <tt>pdo_oci</tt> PDO driver for Oracle.
+ * # <tt>odbc_oracle</tt> Oracle support via ODBC.
*
- * Usage:
+ * # <tt>postgres7</tt> Postgres 7, 8.
+ * # <tt>pdo_pgsql</tt> PDO driver for postgres.
+ * # <tt>postgres64</tt> Postgress 6.4.
+ *
+ * # <tt>pdo_mssql</tt> PDO driver for MSSQL.
+ * # <tt>odbc_mssql</tt> MSSQL support via ODBC.
+ * # <tt>mssqlpo</tt> Portable MSSQL Driver that supports || instead of +.
+ * # <tt>ado_mssql</tt> Microsoft SQL Server ADO data driver.
+ * # <tt>mssql</tt> Native mssql driver.
+ *
+ * # <tt>ldap</tt> LDAP.
+ * # <tt>sqlite</tt> SQLite database.
+ *
+ * For other database drivers and detail documentation regarding indiviual
+ * drivers visit {@link http://adodb.sourceforge. net/}
+ *
+ * When using an sqlite database it is easier to specify the {@link setDriver
+ * Driver} as "sqlite" and {@link setHost Host} as the path to the sqlite
+ * database file. For example:
* <code>
- * $provider = new TAdodb;
- * $provider->setConnectionString($dsn); $
- * connection = $provider->getConnection();
- * $resultSet = $connection->execute('....');
+ * <module id="my_db1"
+ * class="TAdodb"
+ * Driver="sqlite"
+ * Host="Application.pages.my_db" />
+ * </code>
+ * Note that the database file should not contain <b>no dots</b>. The path can
+ * be use namespace or a fullpath (but no dots).
+ *
+ * To access the database from a TPage or other TApplicationComponent classes
+ * use the {@link TApplication::getModule getModule} method of TApplication.
+ * <code>
+ * $db = $this->getApplication()->getModule('my_db1');
+ * //similarly
+ * $db = $this->Application->Modules['my_db1'];
* </code>
+ *
+ * For classes that are not instance of TApplicationComponent (such as
+ * TUserManager) use the static {@link PradoBase::getApplication getApplication}
+ * method first.
+ * <code>
+ * $db = Prado::getApplication()->getModule('my_db1');
+ * </code>
+ *
+ * If you wish to use a Adodb connections without module configuration, see the
+ * TAdodbConnection class.
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Revision: $ $Date: $
@@ -20,44 +103,113 @@ Prado::using('System.DataAccess.TDatabaseProvider'); */
class TAdodb extends TDatabaseProvider
{
+ /**
+ * @var string Adodb associative fetch mode.
+ */
const FETCH_ASSOCIATIVE='associative';
+ /**
+ * @var string Adodb numeric fetch mode.
+ */
const FETCH_NUMERIC='numeric';
+ /**
+ * @var string Adodb fetch mode using both associative and numeric.
+ */
const FETCH_BOTH='both';
+ /**
+ * @var string Adodb default fetch mode.
+ */
const FETCH_DEFAULT='default';
+ /**
+ * @var TAdodbConnection database connection.
+ */
private $_connection = null;
+ /**
+ * @var string Adodb record set cache directory.
+ */
private $_cachedir='';
+ /**
+ * @var string current fetch mode.
+ */
private $_fetchMode = 'associative';
+ /**
+ * @var boolean whether to enable the active recors.
+ */
+ private $_enableActiveRecords = false;
+ /**
+ * @return TAdodbConnection connects to the database and returns the
+ * connection resource.
+ */
public function getConnection()
{
- $this->initialize();
return $this->_connection;
}
-
- public function initialize()
+
+ /**
+ * Initialize the module configurations.
+ */
+ public function init($config)
{
+ parent::init($config);
if(!class_exists('ADOConnection', false))
$this->importAdodbLibrary();
if(is_null($this->_connection))
- $this->_connection = new TAdodbConnection($this);
+ {
+ if($config instanceof TAdodbConnection)
+ $this->_connection = $config;
+ else
+ $this->_connection = new TAdodbConnection($this);
+ if($this->getEnableActiveRecords())
+ $this->initializeActiveRecords();
+ }
}
- public function enableActiveRecords()
+ /**
+ * Enabling Adodb to retrieve results as active records, and active record
+ * object to save changes. Once set to true and the connection is
+ * initialized, setting <tt>EnableActiveRecords</tt> to false has no effect.
+ * @param boolean true to allow active records.
+ */
+ public function setEnableActiveRecords($value)
+ {
+ $this->_enableActiveRecords = TPropertyValue::ensureBoolean($value);
+ }
+
+ /**
+ * @param boolean whether to enable active records.
+ */
+ public function getEnableActiveRecords()
{
- $conn = $this->getConnection();
- if(is_null($conn->getInternalConnection()) && $conn->open())
+ return $this->_enableActiveRecords;
+ }
+
+ /**
+ * Initialize the active records by setting the active records database
+ * adpater to the current database connection.
+ */
+ public function initializeActiveRecords()
+ {
+ $conn = $this->_connection;
+ if(!is_null($conn->getInternalConnection()) || $conn->open())
{
Prado::using('System.DataAccess.TActiveRecord');
TActiveRecord::setDatabaseAdapter($conn->getInternalConnection());
+ $this->_enableActiveRecords = true;
}
}
+ /**
+ * @return string the adodb library path.
+ */
protected function getAdodbLibrary()
{
return Prado::getPathOfNamespace('System.3rdParty.adodb');
}
+ /**
+ * Import the necessary adodb library files.
+ */
protected function importAdodbLibrary()
{
$path = $this->getAdodbLibrary();
@@ -66,7 +218,7 @@ class TAdodb extends TDatabaseProvider }
/**
- * @return string the cache directory for adodb module
+ * @return string the cache directory for Adodb to save cached queries.
*/
public function getCacheDir()
{
@@ -74,17 +226,17 @@ class TAdodb extends TDatabaseProvider }
/**
- * Sets the cache directory for ADODB (in adodb it is
- * called to $ADODB_CACHE_DIR)
+ * The cache directory for Adodb to save cached queries. The path can be
+ * specified using a namespace or the fullpath.
* @param string the cache directory for adodb module
*/
public function setCacheDir($value)
{
- $this->_cachedir=$value;
+ $this->_cachedir=Prado::getPathOfNamespace($value);
}
/**
- * @return string fetch mode of query data
+ * @return string fetch mode of queried data
*/
public function getFetchMode()
{
@@ -92,7 +244,9 @@ class TAdodb extends TDatabaseProvider }
/**
- * Sets the fetch mode of query data: Associative, Numeric, Both, Default (default)
+ * Sets the fetch mode of query data, valid modes are <tt>Associative</tt>,
+ * <tt>Numeric</tt>, <tt>Both</tt> or <tt>Default</tt>. The mode names are
+ * case insensitive.
* @param string the fetch mode of query data
*/
public function setFetchMode($value)
@@ -104,16 +258,23 @@ class TAdodb extends TDatabaseProvider else
$this->_fetchMode=self::FETCH_DEFAULT;
}
-
}
/**
- * TAdodbConnection is a wrapper class of the ADODB ADOConnection class.
- * For more information about the ADODB library, see {@link http://adodb.sourceforge.net/}.
+ * TAdodbConnection provides access to the ADODB ADOConnection class. For detail
+ * documentation regarding indiviual drivers visit {@link http://adodb.sourceforge.net/}
*
* You can call any method implemented in ADOConnection class via TAdodbConnection,
* such as TAdodbConnection::FetchRow(), and so on. The method calls
- * will be passed to ADOConnection class.
+ * will be passed an ADOConnection instance.
+ *
+ * To use TAdodbConnection without the TAdodb database connection provider pass
+ * a DSN style connection string to the TAdodbConnection constructor.
+ * <code>
+ * $dsn = "mysql://username:password@localhost/mydb";
+ * $db = new TAdodbConnection($dsn);
+ * $resultSet = $db->execute('...');
+ * </code>
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Revision: $ $Date: $
@@ -122,10 +283,14 @@ class TAdodb extends TDatabaseProvider */
class TAdodbConnection extends TDbConnection
{
+ /**
+ * @var ADOConnection database connection.
+ */
private $_connection;
/**
- * Gets the internal connection.
+ * Gets the internal connection. Should only be used by framework
+ * developers.
*/
public function getInternalConnection()
{
@@ -190,16 +355,38 @@ class TAdodbConnection extends TDbConnection return call_user_func_array(array($this->_connection,$method),$params);
}
+ /**
+ * @return boolean true if the database is connected.
+ */
public function getIsClosed()
{
return is_null($this->_connection) || !$this->_connection->IsConnected();
}
+ /**
+ * Prepares (compiles) an SQL query for repeated execution. Bind parameters
+ * are denoted by ?, except for the oci8 driver, which uses the traditional
+ * Oracle :varname convention. If there is an error, or we are emulating
+ * Prepare( ), we return the original $sql string.
+ *
+ * Prepare( ) cannot be used with functions that use SQL query rewriting
+ * techniques, e.g. PageExecute( ) and SelectLimit( ).
+ *
+ * @param string sql statement.
+ * @return array an array containing the original sql statement in the first
+ * array element;
+ */
public function prepare($statement)
{
return $this->_connection->prepare($statement);
}
+ /**
+ * Execute SQL statement $sql and return derived class of ADORecordSet if
+ * successful. Note that a record set is always returned on success, even if
+ * we are executing an insert or update statement. You can also pass in $sql
+ * a statement prepared in {@link prepare}.
+ */
public function execute($sql, $parameters=array())
{
return $this->_connection->execute($sql, $parameters);
@@ -221,13 +408,21 @@ class TAdodbConnection extends TDbConnection return $this->connection->CompleteTrans();
}
-
+ /**
+ * End a transaction successfully.
+ * @return true if successful. If the database does not support
+ * transactions, will return true also as data is always committed.
+ */
public function commit()
{
return $this->connection->CommitTrans();
}
-
+ /**
+ * End a transaction, rollback all changes.
+ * @return true if successful. If the database does not support
+ * transactions, will return false as data is never rollbacked.
+ */
public function rollback()
{
return $this->connection->RollbackTrans();
@@ -242,7 +437,7 @@ class TAdodbConnection extends TDbConnection if($this->getIsClosed())
{
$provider = $this->getProvider();
- $provider->initialize();
+ $provider->init($this);
if(strlen($provider->getConnectionString()) < 1)
{
if(strlen($provider->getDriver()) < 1)
@@ -259,13 +454,13 @@ class TAdodbConnection extends TDbConnection }
/**
- * Complete the database connection.
+ * Creates the database connection using host, username, password and
+ * database name properties.
*/
protected function initConnection()
{
$provider = $this->getProvider();
-
- if($provider->getUsePersistentConnection())
+ if(is_int(strpos($provider->getConnectionOptions(), 'persist')))
{
$this->_connection->PConnect($provider->getHost(),
$provider->getUsername(),$provider->getPassword(),
@@ -328,7 +523,6 @@ class TAdodbConnection extends TDbConnection {
return $this->_connection->qstr($string, $magic_quotes);
}
-
}
?>
\ No newline at end of file diff --git a/framework/DataAccess/TDatabaseProvider.php b/framework/DataAccess/TDatabaseProvider.php index 2a62c03a..a39213f1 100644 --- a/framework/DataAccess/TDatabaseProvider.php +++ b/framework/DataAccess/TDatabaseProvider.php @@ -1,25 +1,77 @@ <?php
-
/**
- * Database access module.
+ * TDatabaseProvider and TDbConnection class and IDbConnection interface file.
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
+ * @link http://www.pradosoft.com/
+ * @copyright Copyright © 2005 PradoSoft
+ * @license http://www.pradosoft.com/license/
+ * @version $Revision: $ $Date: $
+ * @package System.DataAccess
+ */
+
+/**
+ * Database provider or adapter base class.
+ *
+ * All database providers should extend this base class to provide a uniform
+ * configuration to the database. Database providers should allow the database
+ * connection to be set via the {@link setConnectionString ConnectionString}
+ * property using a DSN string. The DSN format is
+ * <code>
+ * $driver://$username:$password@host/$database?options[=value]
+ * </code>
+ * Alternatively the database connections details can be set via the {@link
+ * setDriver Driver}, {@link setUsername Username}, {@link setPassword
+ * Password}, {@link setHost Host} and {@link setDatabase Database} properties.
+ * Additional options for individual database driver may be added via the {@link
+ * setConnectionOptions ConnectionOptions} property.
+ *
+ * Database provider implementation must implement the {@link getConnection
+ * Connection} property that returns a database connection or client. A
+ * DSN connection string the represents the available connection properties can
+ * be obtained from the protected method {@link buildConnectionString} method.
+ *
+ * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Revision: $ $Date: $
* @package System.DataAccess
* @since 3.0
*/
abstract class TDatabaseProvider extends TModule
{
+ /**
+ * @var string DSN connection string.
+ */
private $_connectionString = '';
+ /**
+ * @var string database name.
+ */
private $_database='';
+ /**
+ * @var string database driver name.
+ */
private $_driver='';
+ /**
+ * @var string database host name.
+ */
private $_host='';
+ /**
+ * @var string database connection username credentail.
+ */
private $_username='';
+ /**
+ * @var string database connection password credential.
+ */
private $_password='';
- private $_persistent=true;
+ /**
+ * @var string additional connection options.
+ */
+ private $_options='';
+
/**
- * @param string used to open the connection
+ * DSN connection string of the form
+ * <tt>$driver://$username:$password@host/$database?options[=value]</tt>
+ * @param string DSN style connection string.
*/
public function setConnectionString($value)
{
@@ -27,7 +79,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * @return string used to open the connection
+ * @return string DSN connection string
*/
public function getConnectionString()
{
@@ -35,7 +87,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * @return string the DB driver (mysql, sqlite, etc.)
+ * @return string database driver name (mysql, sqlite, etc.)
*/
public function getDriver()
{
@@ -43,8 +95,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * Sets the DB driver (mysql, sqlite, etc.)
- * @param string the DB driver
+ * @param string database driver name.
*/
public function setDriver($value)
{
@@ -53,8 +104,10 @@ abstract class TDatabaseProvider extends TModule /**
* If the driver is <tt>sqlite</tt>, the host must be dot path to the sqlite
- * file.
- * @return string the DB host name/IP (and port number) in the format "host[:port]"
+ * file. E.g. "<tt>Application.pages.my_db</tt>". The database filename
+ * should not contain any dots.
+ * @return string database host name/IP (and port number) in the format
+ * "host[:port]"
*/
public function getHost()
{
@@ -65,7 +118,8 @@ abstract class TDatabaseProvider extends TModule }
/**
- * Sets the DB host name/IP (and port number) in the format "host[:port]"
+ * Sets the database host name/IP or resource (and port number) in the
+ * format "host [: port]"
* @param string the DB host
*/
public function setHost($value)
@@ -74,7 +128,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * @return string the DB username
+ * @return string database connection username credential.
*/
public function getUsername()
{
@@ -82,8 +136,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * Sets the DB username
- * @param string the DB username
+ * @param string database connection username credential.
*/
public function setUsername($value)
{
@@ -91,7 +144,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * @return string the DB password
+ * @return string database connection password
*/
public function getPassword()
{
@@ -99,8 +152,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * Sets the DB password
- * @param string the DB password
+ * @param string database connection password.
*/
public function setPassword($value)
{
@@ -108,7 +160,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * @return string the database name
+ * @return string default database name to connect.
*/
public function getDatabase()
{
@@ -116,8 +168,7 @@ abstract class TDatabaseProvider extends TModule }
/**
- * Sets the database name
- * @param string the database name
+ * @param string default database name to connect to.
*/
public function setDatabase($value)
{
@@ -125,23 +176,27 @@ abstract class TDatabaseProvider extends TModule }
/**
- * @return boolean whether the DB connection is persistent
+ * @return string additional connection options.
*/
- public function getUsePersistentConnection()
+ public function getConnectionOptions()
{
- return $this->_persistent;
+ return $this->_options;
}
/**
- * Sets whether the DB connection should be persistent
- * @param boolean whether the DB connection should be persistent
+ * @param string additional connection options for each individual database
+ * driver.
*/
- public function setUsePersistentConnection($value)
+ public function setConnectionOptions($value)
{
- $this->_persistent=$value;
+ $this->_options=$value;
}
- protected function buildDsn()
+ /**
+ * @return string the DSN connection string build from individual connection
+ * properties.
+ */
+ protected function buildConnectionString()
{
$driver = $this->getDriver().'://';
$user = $this->getUsername();
@@ -154,9 +209,9 @@ abstract class TDatabaseProvider extends TModule $host = '@'.$host;
$db = $this->getDatabase();
$db = strlen($db) > 0 ? '/'.$db : $db;
- $persist = $this->getUsePersistentConnection() ? '': '?persit';
+ $options = $this->getConnectionOptions();
- return $driver.$user.$pass.$host.$persist;
+ return $driver.$user.$pass.$host.$options;
}
/**
@@ -187,7 +242,7 @@ interface IDbConnection public function getIsClosed();
/**
- * Opens a database connection with settings provided in the ConnectionString.
+ * Opens a database connection using settings of a TDatabaseProvider.
*/
public function open();
@@ -207,24 +262,26 @@ interface IDbConnection public function execute($sql, $parameters=array());
/**
- * Start a transaction on this connection.
+ * Start a transaction on this connection. Not all database will support
+ * transactions.
*/
public function beginTransaction();
/**
- * Finish and cleanup transactions.
+ * Finish and cleanup transactions. Not all database will support
+ * transactions.
*/
public function completeTransaction();
/**
* Makes all changes made since the previous commit/rollback permanent and
- * releases any database locks.
+ * releases any database locks. Not all database will support transactions.
*/
public function commit();
/**
* Undoes all changes made in the current transaction and releases any
- * database locks
+ * database locks. Not all database will support transactions.
*/
public function rollback();
@@ -240,7 +297,7 @@ interface IDbConnection /**
* Performs the connection to the database using a TDatabaseProvider,
- * executes SQL statements.
+ * and provides an interface for executing SQL statements and transactions.
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Revision: $ $Date: $
@@ -249,24 +306,39 @@ interface IDbConnection */
abstract class TDbConnection extends TComponent implements IDbConnection
{
+ /**
+ * @string TDatabaseProvider database provider containing connection
+ * details.
+ */
private $_provider;
- public function __construct($provider)
+ /**
+ * Creates a new database connection context.
+ */
+ public function __construct(TDatabaseProvider $provider)
{
- if($provider instanceof TDatabaseProvider)
- $this->setProvider($provider);
+ $this->setProvider($provider);
}
+ /**
+ * @param TDatabaseProvider sets the connection details.
+ */
public function setProvider($provider)
{
$this->_provider = $provider;
}
+ /**
+ * @param TDatabaseProvider gets the database connection details.
+ */
public function getProvider()
{
return $this->_provider;
}
+ /**
+ * Automatically closes the database connection.
+ */
public function __destruct()
{
$this->close();
|