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 the framework should add the "enable fields" (e.g. checking for hidden or deleted records)
59 protected $useEnableFields = TRUE;
62 * TRUE if automatic cache clearing in TCEMAIN should be done on insert/update/delete, FALSE otherwise.
66 protected $automaticCacheClearing = FALSE;
69 * Constructs this Storage Backend instance
71 * @param t3lib_db $databaseHandle The database handle
73 public function __construct($databaseHandle) {
74 $this->databaseHandle
= $databaseHandle;
78 * Set the automatic cache clearing flag.
79 * If TRUE, then inserted/updated/deleted records trigger a TCEMAIN cache clearing.
81 * @param $automaticCacheClearing boolean if TRUE, enables automatic cache clearing
85 public function setAutomaticCacheClearing($automaticCacheClearing) {
86 $this->automaticCacheClearing
= (boolean
)$automaticCacheClearing;
90 * Adds a row to the storage
92 * @param string $tableName The database table name
93 * @param array $row The row to be inserted
94 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
95 * @return int The uid of the inserted row
97 public function addRow($tableName, array $row, $isRelation = FALSE) {
100 $parameters = array();
101 unset($row['uid']); // TODO Check if the offset exists
102 foreach ($row as $columnName => $value) {
103 $fields[] = $columnName;
105 $parameters[] = $value;
108 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
109 $this->replacePlaceholders($sqlString, $parameters);
110 $this->databaseHandle
->sql_query($sqlString);
111 $this->checkSqlErrors();
112 $uid = $this->databaseHandle
->sql_insert_id();
114 $this->clearPageCache($tableName, $uid);
120 * Updates a row in the storage
122 * @param string $tableName The database table name
123 * @param array $row The row to be updated
124 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
127 public function updateRow($tableName, array $row, $isRelation = FALSE) {
128 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
129 $uid = (int)$row['uid'];
132 $parameters = array();
133 foreach ($row as $columnName => $value) {
134 $fields[] = $columnName . '=?';
135 $parameters[] = $value;
137 $parameters[] = $uid;
139 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
140 $this->replacePlaceholders($sqlString, $parameters);
142 $returnValue = $this->databaseHandle
->sql_query($sqlString);
143 $this->checkSqlErrors();
145 $this->clearPageCache($tableName, $uid);
151 * Deletes a row in the storage
153 * @param string $tableName The database table name
154 * @param array $uid The uid of the row to be deleted
155 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
158 public function removeRow($tableName, $uid, $isRelation = FALSE) {
159 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
160 $this->replacePlaceholders($sqlString, array((int)$uid));
162 $this->clearPageCache($tableName, $uid, $isRelation);
164 $returnValue = $this->databaseHandle
->sql_query($sqlString);
165 $this->checkSqlErrors();
170 * Returns an array with tuples matching the query.
172 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
173 * @return array The matching tuples
175 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query) {
177 $sql['tables'] = array();
178 $sql['fields'] = array();
179 $sql['where'] = array();
180 $sql['enableFields'] = array();
181 $sql['orderings'] = array();
182 $parameters = array();
185 $this->parseSource($query, $sql, $parameters);
186 $sqlString = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
188 $this->parseConstraint($query->getConstraint(), $sql, $parameters, $query->getBoundVariableValues());
189 if (!empty($sql['where'])) {
190 $sqlString .= ' WHERE ' . implode('', $sql['where']);
191 if (!empty($sql['enableFields'])) {
192 $sqlString .= ' AND ' . implode(' AND ', $sql['enableFields']);
194 } elseif (!empty($sql['enableFields'])) {
195 $sqlString .= ' WHERE ' . implode(' AND ', $sql['enableFields']);
198 $this->parseOrderings($query->getOrderings(), $sql, $parameters, $query->getBoundVariableValues());
199 if (!empty($sql['orderings'])) {
200 $sqlString .= ' ORDER BY ' . implode(', ', $sql['orderings']);
203 $this->replacePlaceholders($sqlString, $parameters);
205 $result = $this->databaseHandle
->sql_query($sqlString);
206 $this->checkSqlErrors();
208 // TODO Check for selector name
209 $tuples = $this->getRowsFromResult($query->getSelectorName(), $result);
216 * Checks if a Value Object equal to the given Object exists in the data base
218 * @param array $properties The properties of the Value Object
219 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
220 * @return array The matching tuples
222 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap
$dataMap) {
224 $parameters = array();
225 foreach ($properties as $propertyName => $propertyValue) {
226 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
227 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
228 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
232 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode('', $fields);
233 $this->replacePlaceholders($sqlString, $parameters);
234 $res = $this->databaseHandle
->sql_query($sqlString);
235 $this->checkSqlErrors();
236 $row = $this->databaseHandle
->sql_fetch_assoc($res);
237 if ($row !== FALSE) {
245 * Transforms a Query Source into SQL and parameter arrays
247 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
249 * @param array &$parameters
252 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModel
$query, array &$sql, array &$parameters) {
253 $source = $query->getSource();
254 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
255 $selectorName = $source->getSelectorName();
256 $sql['fields'][] = $selectorName . '.*';
257 $sql['tables'][] = $selectorName;
258 // TODO Should we make the usage of enableFields configurable? And how? Because the Query object and even the QOM should be abstracted from the storage backend.
259 if ($this->useEnableFields
=== TRUE) {
260 $this->addEnableFieldsStatement($selectorName, $sql);
262 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
263 $this->parseJoin($source, $sql, $parameters);
268 * Transforms a Join into SQL and parameter arrays
270 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
272 * @param array &$parameters
275 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql, array &$parameters) {
276 $leftSelectorName = $join->getLeft()->getSelectorName();
277 $rightSelectorName = $join->getRight()->getSelectorName();
279 $sql['fields'][] = $leftSelectorName . '.*';
280 $sql['fields'][] = $rightSelectorName . '.*';
282 // TODO Implement support for different join types and nested joins
283 $sql['tables'][] = $leftSelectorName . ' LEFT JOIN ' . $rightSelectorName;
285 $joinCondition = $join->getJoinCondition();
286 // TODO Check the parsing of the join
287 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
288 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $joinCondition->getProperty1Name() . ' = ' . $joinCondition->getSelector2Name() . '.' . $joinCondition->getProperty2Name();
290 // TODO Implement childtableWhere
292 $this->addEnableFieldsStatement($leftSelectorName, $sql);
293 $this->addEnableFieldsStatement($rightSelectorName, $sql);
297 * Transforms a constraint into SQL and parameter arrays
299 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
301 * @param array &$parameters
302 * @param array $boundVariableValues
305 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
306 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
307 $sql['where'][] = '(';
308 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
309 $sql['where'][] = ' AND ';
310 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
311 $sql['where'][] = ')';
312 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
313 $sql['where'][] = '(';
314 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
315 $sql['where'][] = ' OR ';
316 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
317 $sql['where'][] = ')';
318 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
319 $sql['where'][] = 'NOT (';
320 $this->parseConstraint($constraint->getConstraint(), $sql, $parameters, $boundVariableValues);
321 $sql['where'][] = ')';
322 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
323 $this->parseComparison($constraint, $sql, $parameters, $boundVariableValues);
324 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface
) {
325 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
330 * Parse a Comparison into SQL and parameter arrays.
332 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
333 * @param array &$sql SQL query parts to add to
334 * @param array &$parameters Parameters to bind to the SQL
335 * @param array $boundVariableValues The bound variables in the query and their values
338 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, array &$sql, array &$parameters, array $boundVariableValues) {
339 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface
)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
341 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
342 $operator = $comparison->getOperator();
343 if ($value === NULL) {
344 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
) {
345 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
346 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
) {
347 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
349 // TODO Throw exception
352 $parameters[] = $value;
354 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $sql, $parameters);
358 * Parse a DynamicOperand into SQL and parameter arrays.
360 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
361 * @param string $operator One of the JCR_OPERATOR_* constants
362 * @param array $boundVariableValues
363 * @param array &$parameters
364 * @param string $valueFunction an aoptional SQL function to apply to the operand value
367 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, array &$sql, array &$parameters, $valueFunction = NULL) {
368 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
369 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'LOWER');
370 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
371 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'UPPER');
372 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
373 $selectorName = $operand->getSelectorName();
374 $operator = $this->resolveOperator($operator);
376 if ($valueFunction === NULL) {
377 $constraintSQL .= (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
379 $constraintSQL .= $valueFunction . '(' . (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
382 $sql['where'][] = $constraintSQL;
387 * Returns the SQL operator for the given JCR operator type.
389 * @param string $operator One of the JCR_OPERATOR_* constants
390 * @return string an SQL operator
392 protected function resolveOperator($operator) {
394 case self
::OPERATOR_EQUAL_TO_NULL
:
397 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
398 $operator = 'IS NOT';
400 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
:
403 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
:
406 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN
:
409 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO
:
412 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN
:
415 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
418 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LIKE
:
422 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
429 * Replace query placeholders in a query part by the given
432 * @param string $queryPart The query part with placeholders
433 * @param array $parameters The parameters
434 * @return string The query part with replaced placeholders
436 protected function replacePlaceholders(&$sqlString, array $parameters) {
437 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);
438 foreach ($parameters as $parameter) {
439 $markPosition = strpos($sqlString, '?');
440 if ($markPosition !== FALSE) {
441 // TODO This is a bit hacky; improve the handling of $parameter === NULL
442 if ($parameter === NULL) {
445 $parameter = '"' . $parameter . '"';
447 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
453 * Builds the enable fields statement
455 * @param string $selectorName The selector name (= database table name)
456 * @param array &$sql The query parts
459 protected function addEnableFieldsStatement($selectorName, array &$sql) {
460 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
461 if (is_array($GLOBALS['TCA'][$selectorName]['ctrl'])) {
462 $statement = substr($GLOBALS['TSFE']->sys_page
->enableFields($selectorName), 4);
463 if(!empty($statement)) {
464 $sql['enableFields'][] = $statement;
470 * Transforms orderings into SQL
472 * @param array $orderings
474 * @param array &$parameters
475 * @param array $boundVariableValues
478 protected function parseOrderings(array $orderings, array &$sql, array &$parameters, array $boundVariableValues) {
479 foreach ($orderings as $ordering) {
480 $operand = $ordering->getOperand();
481 $order = $ordering->getOrder();
482 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue
) {
484 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
487 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
491 throw new Tx_Extbase_Persistence_Exception('Unsupported order encountered.', 1242816074);
494 $sql['orderings'][] = $ordering->getOperand()->getPropertyName() . ' ' . $order;
500 * Transforms a Resource from a database query to an array of rows. Performs the language and
501 * workspace overlay before.
503 * @return array The result as an array of rows (tuples)
505 protected function getRowsFromResult($tableName, $res) {
507 while ($row = $this->databaseHandle
->sql_fetch_assoc($res)) {
508 $row = $this->doLanguageAndWorkspaceOverlay($tableName, $row);
509 if (is_array($row)) {
510 // TODO Check if this is necessary, maybe the last line is enough
511 $arrayKeys = range(0,count($row));
512 array_fill_keys($arrayKeys, $row);
520 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
521 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
523 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
524 * @param array $row The row array (as reference)
525 * @param string $languageUid The language id
526 * @param string $workspaceUidUid The workspace id
529 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
530 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
531 if (TYPO3_MODE
== 'FE') {
532 if (is_object($GLOBALS['TSFE'])) {
533 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
534 if ($languageUid === NULL) {
535 $languageUid = $GLOBALS['TSFE']->sys_language_content
;
538 require_once(PATH_t3lib
. 'class.t3lib_page.php');
539 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
540 if ($languageUid === NULL) {
541 $languageUid = intval(t3lib_div
::_GP('L'));
544 if ($workspaceUid !== NULL) {
545 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
548 require_once(PATH_t3lib
. 'class.t3lib_page.php');
549 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
550 //$this->pageSelectObject->versioningPreview = TRUE;
551 if ($workspaceUid === NULL) {
552 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
554 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
558 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
559 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
560 // TODO Skip if empty languageoverlay (languagevisibility)
565 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
568 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
570 protected function checkSqlErrors() {
571 $error = $this->databaseHandle
->sql_error();
573 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
578 * Clear the TYPO3 page cache for the given record.
579 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
581 * @param $tableName Table name of the record
582 * @param $uid UID of the record
585 protected function clearPageCache($tableName, $uid) {
586 if ($this->automaticCacheClearing
!== TRUE) return;
588 $pageCache = $GLOBALS['typo3CacheManager']->getCache('cache_pages');
589 $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache('cache_pagesection');
591 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
593 $pageIdsToClear = array();
594 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
595 $storagePage = $row['pid'];
596 $pageIdsToClear[] = $storagePage;
602 $pageTSConfig = t3lib_BEfunc
::getPagesTSconfig($storagePage);
604 if ($pageTSConfig['clearCacheCmd']) {
605 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
606 $clearCacheCommands = array_unique($clearCacheCommands);
607 foreach ($clearCacheCommands as $clearCacheCommand) {
608 if (t3lib_div
::testInt($clearCacheCommand)) {
609 $pageIdsToClear[] = $clearCacheCommand;
614 foreach ($pageIdsToClear as $pageIdToClear) {
615 $pageCache->flushByTag('pageId_' . $pageIdToClear);
616 $pageSectionCache->flushByTag('pageId_' . $pageIdToClear);