Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Use PDO as database abstraction layer instead of Creole

  • Loading branch information...
commit 2c2759fd85a622b08e3dcf667b2baa2c6dbd8692 1 parent 1e30f14
@integry authored
View
3  .gitmodules
@@ -1,3 +0,0 @@
-[submodule "creole"]
- path = creole
- url = git://github.com/integry/creole.git
View
2  ARLogger.php
@@ -103,7 +103,7 @@ private function addLogItem($msg, $logType)
private function createLogItemStr($itemArray)
{
$str = str_repeat(' ', ActiveRecord::$transactionLevel);
- $str .= $itemArray['msg']."\n";
+ //$str .= $itemArray['msg']."\n";
return $str;
}
View
105 ActiveRecord.php
@@ -66,7 +66,7 @@ function array_fill_keys($array, $values)
/**
* Database connection object
*
- * @var Creole
+ * @var PDO
*/
private static $dbConnection = null;
@@ -98,7 +98,7 @@ function array_fill_keys($array, $values)
* Database connection instance (refererences to self::$dbConnection)
*
* @see self::$dbConnection
- * @var Creole
+ * @var PDO
*/
private $db = null;
@@ -331,21 +331,37 @@ private function setupDBConnection()
/**
* Return a database connection object
*
- * @return Creole db object
+ * @return PDO db object
*/
public static function getDBConnection()
{
if (!self::$dbConnection)
{
- include_once(dirname(__file__) . DIRECTORY_SEPARATOR . "creole" . DIRECTORY_SEPARATOR . "Creole.php");
-
self::getLogger()->logQuery("Creating a database connection");
- self::$dbConnection = Creole::getConnection(self::$dsn);
- self::getLogger()->logQueryExecutionTime();
+ $dsn = parse_url(self::$dsn);
+
+ $params = array();
+ if ('mysql' == $dsn['scheme'])
+ {
+ $params = array(
+ PDO::MYSQL_ATTR_FOUND_ROWS => true,
+ PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\';' //@@session.sql_mode='';
+ );
+ }
+
+ try
+ {
+ self::$dbConnection = new PDO($dsn['scheme'] . ':dbname=' . substr($dsn['path'], 1) . ';host=' . $dsn['host'], $dsn['user'], !empty($dsn['password']) ? $dsn['password'] : '', $params);
+ self::$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+ }
+ catch (PDOException $e)
+ {
+ throw new SQLException($e->getMessage());
+ }
- self::$dbConnection->executeUpdate("SET NAMES 'utf8'");
- self::$dbConnection->executeUpdate("SET @@session.sql_mode=''");
+ self::getLogger()->logQueryExecutionTime();
}
+
return self::$dbConnection;
}
@@ -1003,7 +1019,7 @@ private static function extractSchemaData(ARSchema $schema, &$dataArray, $transf
{
foreach($schema->getArrayFieldList() as $name)
{
- $dataArray[$name] = is_string($dataArray[$name]) ? @unserialize($dataArray[$name]) : '';
+ $dataArray[$name] = is_string($dataArray[$name]) ? unserialize($dataArray[$name]) : '';
}
$recordData = array_intersect_key($dataArray, $schema->getFieldList());
@@ -1171,40 +1187,31 @@ public static function fetchDataFromDB(ARSelectQueryBuilder $query)
$db = self::getDBConnection();
$queryStr = $query->createString();
+
self::getLogger()->logQuery($queryStr);
- $resultSet = $query->getPreparedStatement($db)->executeQuery();
+ $statement = $query->getPreparedStatement($db);
+ $resultSet = $statement->execute();
self::getLogger()->logQueryExecutionTime();
- $dataArray = array();
- while ($resultSet->next())
- {
- $dataArray[] = $resultSet->getRow();
- }
-
- return $dataArray;
+ return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public static function getDataBySQL($sqlSelectQuery)
{
self::getLogger()->logQuery($sqlSelectQuery);
- if ($sqlSelectQuery instanceof PreparedStatementCommon)
+ if ($sqlSelectQuery instanceof PDOStatement)
{
- $resultSet = $sqlSelectQuery->executeQuery();
+ $sqlSelectQuery->execute();
+ $resultSet = $sqlSelectQuery->fetchAll(PDO::FETCH_ASSOC);
}
else
{
- $db = self::getDBConnection();
- $resultSet = $db->executeQuery($sqlSelectQuery);
+ $dataArray = self::getDBConnection()->query($sqlSelectQuery)->fetchAll(PDO::FETCH_ASSOC);
}
self::getLogger()->logQueryExecutionTime();
- $dataArray = array();
- while ($resultSet->next())
- {
- $dataArray[] = $resultSet->getRow();
- }
return $dataArray;
}
@@ -1237,8 +1244,15 @@ public static function executeUpdate($sql)
try
{
self::getLogger()->logQuery($sql);
- $res = self::getDBConnection()->executeQuery($sql);
+ $res = self::getDBConnection()->exec($sql);
+
+ if (false === $res)
+ {
+ throw new SQLException(self::getDBConnection()->errorInfo());
+ }
+
self::getLogger()->logQueryExecutionTime();
+
return $res;
}
catch (Exception $e)
@@ -1333,10 +1347,11 @@ public static function getRecordCount($className, ARSelectFilter $filter, $refer
self::getLogger()->logQuery($counterQuery);
- $counterResult = $query->getPreparedStatement($db)->executeQuery();
- $counterResult->next();
+ $statement = $query->getPreparedStatement($db);
+ $statement->execute();
- $resultData = $counterResult->getRow();
+ $resultData = $statement->fetch(PDO::FETCH_ASSOC);
+ $statement->closeCursor();
return $resultData['totalCount'];
}
@@ -1365,10 +1380,10 @@ public static function getRecordCountByQuery(ARSelectQueryBuilder $query)
self::getLogger()->logQuery($counterQuery);
$db = self::getDBConnection();
- $counterResult = $query->getPreparedStatement($db)->executeQuery();
- $counterResult->next();
-
- $resultData = $counterResult->getRow();
+ $statement = $query->getPreparedStatement($db);
+ $statement->execute();
+ $resultData = $statement->fetch(PDO::FETCH_ASSOC);
+ $statement->closeCursor();
return $resultData['totalCount'];
}
@@ -1500,7 +1515,7 @@ public static function deleteRecordSet($className, ARDeleteFilter $filter, $clea
}
self::getLogger()->logQuery($deleteQuery);
- $res = $db->executeUpdate($deleteQuery);
+ $res = self::executeUpdate($deleteQuery);
self::getLogger()->logQueryExecutionTime();
return $res;
}
@@ -1591,7 +1606,7 @@ public static function updateRecordSet($className, ARUpdateFilter $filter, $join
$sql = preg_replace('/^SELECT[ ]*FROM/', 'UPDATE', $query->createString());
self::getLogger()->logQuery($sql);
- return $db->executeUpdate($sql);
+ return self::executeUpdate($sql);
}
/**
@@ -1766,8 +1781,7 @@ protected function insert()
$PKField = $PKList[key($PKList)];
if (($PKField->getDataType() instanceof ARInteger) && !$this->getID())
{
- $IDG = $this->db->getIdGenerator();
- $this->setID($IDG->getId(), false);
+ $this->setID($this->db->lastInsertId(), false);
}
}
@@ -2378,8 +2392,7 @@ public static function beginTransaction()
self::$transactionLevel++;
if (1 == self::$transactionLevel)
{
- $db = self::getDBConnection();
- $db->setAutoCommit(false);
+ self::getDBConnection()->beginTransaction();
}
}
@@ -2393,13 +2406,13 @@ public static function commit()
if (self::$transactionLevel < 0)
{
self::$transactionLevel = 0;
+ return;
}
self::getLogger()->logAction("COMMIT transaction" . ((int)self::$transactionLevel + 1));
if (0 == self::$transactionLevel)
{
- $db = self::getDBConnection();
- $db->commit();
+ self::getDBConnection()->commit();
}
}
@@ -2411,8 +2424,7 @@ public static function rollback()
{
self::$transactionLevel = 0;
self::getLogger()->logAction("ROLLBACK transaction");
- $db = self::getDBConnection();
- $db->rollback();
+ self::getDBConnection()->rollback();
}
/**
@@ -2520,7 +2532,6 @@ public function unserialize($serialized)
$variables[$key] = $valueMapper instanceof ARValueMapper ? $valueMapper->get() : $valueMapper;
}
- //var_dump($variables);
$this->createDataAccessVariables($variables);
unset($array['data']);
@@ -2603,6 +2614,8 @@ public function __get($name)
}
}
+class SQLException extends Exception {}
+
register_shutdown_function(array('ActiveRecord', 'clearPool'));
?>
1  creole
@@ -1 +0,0 @@
-Subproject commit 328bb8235c9c70ddc472107f198e497e02fc13ad
View
38 query/ARSelectQueryBuilder.php
@@ -228,6 +228,7 @@ private function createStatementBody()
$joinListStr = implode(" ", $preparedJoinList);
}
+
return "SELECT ".$fieldListStr." FROM ".$tableListStr." ".$joinListStr;
}
@@ -243,40 +244,33 @@ public function createString()
return $sql;
}
- public function getPreparedStatement(ConnectionCommon $conn)
+ public function getPreparedStatement(PDO $conn)
{
$body = $this->createStatementBody();
- $values = array();
if (is_null($this->filter))
{
- return $conn->prepareStatement($body);
+ return $conn->prepare($body);
}
$prepared = $this->filter->createPreparedStatement();
+ $statement = $conn->prepare($body . $prepared['sql']);
- preg_match_all('/\?\?\?([a-z0-9]*)@@@/', $prepared['sql'], $matches);
- $values = $matches[1];
-
- $statement = $conn->prepareStatement($body . preg_replace('/\?\?\?([a-z0-9]*)@@@/', '?', $prepared['sql']));
-
- foreach ($values as $key => $id)
+ foreach ($prepared['values'] as $id => $value)
{
- $key++;
- $value = $prepared['values'][$id];
-
- if ('int' == $value['type'])
+ switch ($value['type'])
{
- $statement->setInt($key, $value['value']);
- }
- else if ('timestamp' == $value['type'])
- {
- $statement->setTimestamp($key, $value['value']);
- }
- else
- {
- $statement->setString($key, $value['value']);
+ case 'int':
+ $type = PDO::PARAM_INT;
+ break;
+
+ // @todo: timestamp, string, bool
+ default:
+ $type = null;
+ break;
}
+
+ $statement->bindValue($id, $value['value']);
}
return $statement;
View
5 query/filter/Condition.php
@@ -2,6 +2,7 @@
/**
* Abstract condition element used in WHERE clause
+ * Abstract condition element used in WHERE clause
*
* It allows programmer to create schema independent conditional statems and use it
* with a filter (ARFilter subclass) that is applied to a record set (deletion,
@@ -270,11 +271,11 @@ public function toPreparedStatement()
}
$value = $this->leftSide->prepareValue($this->rightSide);
- $id = md5($value);
+ $id = 'v' . md5($value);
$values[$id] = array('value' => $value,
'type' => $type);
- $condStr .= '???' . $id . '@@@';
+ $condStr .= ':' . $id;
}
return array('sql' => $condStr, 'values' => $values);
Please sign in to comment.
Something went wrong with that request. Please try again.