2 /***************************************************************
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 team.
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
32 * @subpackage Persistence
35 class Tx_Extbase_Persistence_Storage_Typo3DbBackend
implements Tx_Extbase_Persistence_Storage_BackendInterface
, t3lib_Singleton
{
37 const OPERATOR_EQUAL_TO_NULL
= 'operatorEqualToNull';
38 const OPERATOR_NOT_EQUAL_TO_NULL
= 'operatorNotEqualToNull';
41 * The TYPO3 database object
45 protected $databaseHandle;
48 * The TYPO3 page select object. Used for language and workspace overlay
50 * @var t3lib_pageSelect
52 protected $pageSelectObject;
55 * TRUE if automatic cache clearing in TCEMAIN should be done on insert/update/delete, FALSE otherwise.
59 protected $automaticCacheClearing = FALSE;
62 * Constructs this Storage Backend instance
64 * @param t3lib_db $databaseHandle The database handle
66 public function __construct($databaseHandle) {
67 $this->databaseHandle
= $databaseHandle;
71 * Set the automatic cache clearing flag.
72 * If TRUE, then inserted/updated/deleted records trigger a TCEMAIN cache clearing.
74 * @param $automaticCacheClearing boolean if TRUE, enables automatic cache clearing
78 public function setAutomaticCacheClearing($automaticCacheClearing) {
79 $this->automaticCacheClearing
= (boolean
)$automaticCacheClearing;
83 * Adds a row to the storage
85 * @param string $tableName The database table name
86 * @param array $row The row to be inserted
87 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
88 * @return int The uid of the inserted row
90 public function addRow($tableName, array $row, $isRelation = FALSE) {
93 $parameters = array();
94 unset($row['uid']); // TODO Check if the offset exists
95 foreach ($row as $columnName => $value) {
96 $fields[] = $columnName;
98 $parameters[] = $value;
101 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
102 $this->replacePlaceholders($sqlString, $parameters);
103 $this->databaseHandle
->sql_query($sqlString);
104 $this->checkSqlErrors();
105 $uid = $this->databaseHandle
->sql_insert_id();
107 $this->clearPageCache($tableName, $uid);
113 * Updates a row in the storage
115 * @param string $tableName The database table name
116 * @param array $row The row to be updated
117 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
120 public function updateRow($tableName, array $row, $isRelation = FALSE) {
121 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
122 $uid = (int)$row['uid'];
125 $parameters = array();
126 foreach ($row as $columnName => $value) {
127 $fields[] = $columnName . '=?';
128 $parameters[] = $value;
130 $parameters[] = $uid;
132 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
133 $this->replacePlaceholders($sqlString, $parameters);
135 $returnValue = $this->databaseHandle
->sql_query($sqlString);
136 $this->checkSqlErrors();
138 $this->clearPageCache($tableName, $uid);
144 * Deletes a row in the storage
146 * @param string $tableName The database table name
147 * @param array $uid The uid of the row to be deleted
148 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
151 public function removeRow($tableName, $uid, $isRelation = FALSE) {
152 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
153 $this->replacePlaceholders($sqlString, array((int)$uid));
155 $this->clearPageCache($tableName, $uid, $isRelation);
157 $returnValue = $this->databaseHandle
->sql_query($sqlString);
158 $this->checkSqlErrors();
163 * Returns an array with tuples matching the query.
165 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
166 * @return array The matching tuples
168 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query) {
170 $sql['tables'] = array();
171 $sql['fields'] = array();
172 $sql['where'] = array();
173 $sql['enableFields'] = array();
174 $sql['orderings'] = array();
175 $sql['limit'] = array();
176 $parameters = array();
179 $this->parseSource($query, $sql, $parameters);
180 $sqlString = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
182 $this->parseConstraint($query->getConstraint(), $sql, $parameters, $query->getBoundVariableValues());
184 if (!empty($sql['where'])) {
185 $sqlString .= ' WHERE ' . implode('', $sql['where']);
186 if (!empty($sql['enableFields'])) {
187 $sqlString .= ' AND ' . implode(' AND ', $sql['enableFields']);
189 } elseif (!empty($sql['enableFields'])) {
190 $sqlString .= ' WHERE ' . implode(' AND ', $sql['enableFields']);
193 $this->parseOrderings($query->getOrderings(), $sql, $parameters, $query->getBoundVariableValues());
194 if (!empty($sql['orderings'])) {
195 $sqlString .= ' ORDER BY ' . implode(', ', $sql['orderings']);
198 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql, $parameters, $query->getBoundVariableValues());
199 if (!empty($sql['limit'])) {
200 $sqlString .= ' LIMIT ' . $sql['limit'];
203 $this->replacePlaceholders($sqlString, $parameters);
205 $result = $this->databaseHandle
->sql_query($sqlString);
206 $this->checkSqlErrors();
208 $tuples = $this->getRowsFromResult($query->getSource(), $result);
215 * Checks if a Value Object equal to the given Object exists in the data base
217 * @param array $properties The properties of the Value Object
218 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
219 * @return array The matching tuples
221 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap
$dataMap) {
223 $parameters = array();
224 foreach ($properties as $propertyName => $propertyValue) {
225 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
226 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
227 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
231 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode(' AND ', $fields);
232 $this->replacePlaceholders($sqlString, $parameters);
233 $res = $this->databaseHandle
->sql_query($sqlString);
234 $this->checkSqlErrors();
235 $row = $this->databaseHandle
->sql_fetch_assoc($res);
236 if ($row !== FALSE) {
244 * Transforms a Query Source into SQL and parameter arrays
246 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
248 * @param array &$parameters
251 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, array &$sql, array &$parameters) {
252 $source = $query->getSource();
253 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
254 $selectorName = $source->getSelectorName();
255 $sql['fields'][] = $selectorName . '.*';
256 $sql['tables'][] = $selectorName;
257 $extbaseSettings = Tx_Extbase_Dispatcher
::getSettings();
258 if ($query->getBackendSpecificQuerySettings()->enableFieldsEnabled()) {
259 $this->addEnableFieldsStatement($selectorName, $sql);
261 if ($query->getBackendSpecificQuerySettings()->storagePageEnabled()) {
262 $sql['enableFields'][] = $selectorName . '.pid=' . intval($extbaseSettings['storagePid']);
264 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
265 $this->parseJoin($source, $sql, $parameters);
270 * Transforms a Join into SQL and parameter arrays
272 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
274 * @param array &$parameters
277 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql, array &$parameters) {
278 $leftSelectorName = $join->getLeft()->getSelectorName();
279 $rightSelectorName = $join->getRight()->getSelectorName();
281 $sql['fields'][] = $leftSelectorName . '.*';
282 $sql['fields'][] = $rightSelectorName . '.*';
284 // TODO Implement support for different join types and nested joins
285 $sql['tables'][] = $leftSelectorName . ' LEFT JOIN ' . $rightSelectorName;
287 $joinCondition = $join->getJoinCondition();
288 // TODO Check the parsing of the join
289 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
290 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $joinCondition->getProperty1Name() . ' = ' . $joinCondition->getSelector2Name() . '.' . $joinCondition->getProperty2Name();
292 // TODO Implement childtableWhere
294 $this->addEnableFieldsStatement($leftSelectorName, $sql);
295 $this->addEnableFieldsStatement($rightSelectorName, $sql);
299 * Transforms a constraint into SQL and parameter arrays
301 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
303 * @param array &$parameters
304 * @param array $boundVariableValues
307 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
308 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
309 $sql['where'][] = '(';
310 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
311 $sql['where'][] = ' AND ';
312 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
313 $sql['where'][] = ')';
314 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
315 $sql['where'][] = '(';
316 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
317 $sql['where'][] = ' OR ';
318 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
319 $sql['where'][] = ')';
320 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
321 $sql['where'][] = 'NOT (';
322 $this->parseConstraint($constraint->getConstraint(), $sql, $parameters, $boundVariableValues);
323 $sql['where'][] = ')';
324 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
325 $this->parseComparison($constraint, $sql, $parameters, $boundVariableValues);
326 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface
) {
327 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
332 * Parse a Comparison into SQL and parameter arrays.
334 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
335 * @param array &$sql SQL query parts to add to
336 * @param array &$parameters Parameters to bind to the SQL
337 * @param array $boundVariableValues The bound variables in the query and their values
340 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, array &$sql, array &$parameters, array $boundVariableValues) {
341 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface
)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
343 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
344 $operator = $comparison->getOperator();
345 if ($value === NULL) {
346 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
) {
347 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
348 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
) {
349 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
351 // TODO Throw exception
354 $parameters[] = $value;
356 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $sql, $parameters);
360 * Parse a DynamicOperand into SQL and parameter arrays.
362 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
363 * @param string $operator One of the JCR_OPERATOR_* constants
364 * @param array $boundVariableValues
365 * @param array &$parameters
366 * @param string $valueFunction an aoptional SQL function to apply to the operand value
369 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, array &$sql, array &$parameters, $valueFunction = NULL) {
370 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
371 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'LOWER');
372 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
373 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'UPPER');
374 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
375 $selectorName = $operand->getSelectorName();
376 $operator = $this->resolveOperator($operator);
378 if ($valueFunction === NULL) {
379 $constraintSQL .= (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
381 $constraintSQL .= $valueFunction . '(' . (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
384 $sql['where'][] = $constraintSQL;
389 * Returns the SQL operator for the given JCR operator type.
391 * @param string $operator One of the JCR_OPERATOR_* constants
392 * @return string an SQL operator
394 protected function resolveOperator($operator) {
396 case self
::OPERATOR_EQUAL_TO_NULL
:
399 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
400 $operator = 'IS NOT';
402 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
:
405 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
:
408 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN
:
411 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO
:
414 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN
:
417 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
420 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LIKE
:
424 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
431 * Replace query placeholders in a query part by the given
434 * @param string $queryPart The query part with placeholders
435 * @param array $parameters The parameters
436 * @return string The query part with replaced placeholders
438 protected function replacePlaceholders(&$sqlString, array $parameters) {
439 if (substr_count($sqlString, '?') !== count($parameters)) throw new Tx_Extbase_Persistence_Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
441 foreach ($parameters as $parameter) {
442 $markPosition = strpos($sqlString, '?', $offset);
443 if ($markPosition !== FALSE) {
444 if ($parameter === NULL) {
447 $parameter = "'" . $parameter . "'"; // TODO Discuss: Do we need quotation?
449 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
451 $offset = $markPosition +
strlen($parameter);
456 * Builds the enable fields statement
458 * @param string $selectorName The selector name (= database table name)
459 * @param array &$sql The query parts
462 protected function addEnableFieldsStatement($selectorName, array &$sql) {
463 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
464 if (is_array($GLOBALS['TCA'][$selectorName]['ctrl'])) {
465 $statement = substr($GLOBALS['TSFE']->sys_page
->enableFields($selectorName), 5);
466 if(!empty($statement)) {
467 $sql['enableFields'][] = $statement;
473 * Transforms orderings into SQL
475 * @param array $orderings
477 * @param array &$parameters
478 * @param array $boundVariableValues
481 protected function parseOrderings(array $orderings, array &$sql, array &$parameters, array $boundVariableValues) {
482 foreach ($orderings as $ordering) {
483 $operand = $ordering->getOperand();
484 $order = $ordering->getOrder();
485 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue
) {
487 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
490 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
494 throw new Tx_Extbase_Persistence_Exception('Unsupported order encountered.', 1242816074);
497 $sql['orderings'][] = $ordering->getOperand()->getPropertyName() . ' ' . $order;
503 * Transforms limit and offset into SQL
510 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
511 if ($limit !== NULL && $offset !== NULL) {
512 $sql['limit'] = $offset . ', ' . $limit;
513 } elseif ($limit !== NULL) {
514 $sql['limit'] = $limit;
519 * Transforms a Resource from a database query to an array of rows. Performs the language and
520 * workspace overlay before.
522 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
524 * @return array The result as an array of rows (tuples)
526 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $res) {
528 while ($row = $this->databaseHandle
->sql_fetch_assoc($res)) {
529 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
530 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
532 if (is_array($row)) {
533 // TODO Check if this is necessary, maybe the last line is enough
534 $arrayKeys = range(0,count($row));
535 array_fill_keys($arrayKeys, $row);
543 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
544 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
546 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
547 * @param array $row The row array (as reference)
548 * @param string $languageUid The language id
549 * @param string $workspaceUidUid The workspace id
552 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
553 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
554 if (TYPO3_MODE
== 'FE') {
555 if (is_object($GLOBALS['TSFE'])) {
556 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
557 if ($languageUid === NULL) {
558 $languageUid = $GLOBALS['TSFE']->sys_language_content
;
561 require_once(PATH_t3lib
. 'class.t3lib_page.php');
562 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
563 if ($languageUid === NULL) {
564 $languageUid = intval(t3lib_div
::_GP('L'));
567 if ($workspaceUid !== NULL) {
568 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
571 require_once(PATH_t3lib
. 'class.t3lib_page.php');
572 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
573 //$this->pageSelectObject->versioningPreview = TRUE;
574 if ($workspaceUid === NULL) {
575 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
577 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
581 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
582 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
583 // TODO Skip if empty languageoverlay (languagevisibility)
588 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
591 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
593 protected function checkSqlErrors() {
594 $error = $this->databaseHandle
->sql_error();
596 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
601 * Clear the TYPO3 page cache for the given record.
602 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
604 * @param $tableName Table name of the record
605 * @param $uid UID of the record
608 protected function clearPageCache($tableName, $uid) {
609 if ($this->automaticCacheClearing
!== TRUE) return;
611 $pageCache = $GLOBALS['typo3CacheManager']->getCache('cache_pages');
612 $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache('cache_pagesection');
614 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
616 $pageIdsToClear = array();
617 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
618 $storagePage = $row['pid'];
619 $pageIdsToClear[] = $storagePage;
625 $pageTSConfig = t3lib_BEfunc
::getPagesTSconfig($storagePage);
626 if (isset($pageTSConfig['TCEMAIN.']['clearCacheCmd'])) {
627 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($pageTSConfig['TCEMAIN.']['clearCacheCmd']),1);
628 $clearCacheCommands = array_unique($clearCacheCommands);
629 foreach ($clearCacheCommands as $clearCacheCommand) {
630 if (t3lib_div
::testInt($clearCacheCommand)) {
631 $pageIdsToClear[] = $clearCacheCommand;
636 foreach ($pageIdsToClear as $pageIdToClear) {
637 $pageCache->flushByTag('pageId_' . $pageIdToClear);
638 $pageSectionCache->flushByTag('pageId_' . $pageIdToClear);