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 * @return int The uid of the inserted row
96 public function addRow($tableName, array $row) {
99 $parameters = array();
100 unset($row['uid']); // TODO Check if the offset exists
101 foreach ($row as $columnName => $value) {
102 $fields[] = $columnName;
104 $parameters[] = $value;
107 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
108 $this->replacePlaceholders($sqlString, $parameters);
110 $this->databaseHandle
->sql_query($sqlString);
111 $uid = $this->databaseHandle
->sql_insert_id();
112 $this->clearPageCache($tableName, $uid);
117 * Updates a row in the storage
119 * @param string $tableName The database table name
120 * @param array $row The row to be updated
123 public function updateRow($tableName, array $row) {
124 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
125 $uid = (int)$row['uid'];
128 $parameters = array();
129 foreach ($row as $columnName => $value) {
130 $fields[] = $columnName . '=?';
131 $parameters[] = $value;
133 $parameters[] = $uid;
135 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
136 $this->replacePlaceholders($sqlString, $parameters);
138 $returnValue = $this->databaseHandle
->sql_query($sqlString);
139 $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
150 public function removeRow($tableName, $uid) {
151 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
152 $this->replacePlaceholders($sqlString, array((int)$uid));
153 $this->clearPageCache($tableName, $uid);
154 $returnValue = $this->databaseHandle
->sql_query($sqlString);
159 * Returns an array with tuples matching the query.
161 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
162 * @return array The matching tuples
164 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query) {
166 $sql['tables'] = array();
167 $sql['fields'] = array();
168 $sql['where'] = array();
169 $sql['enableFields'] = array();
170 $sql['orderings'] = array();
171 $parameters = array();
174 $this->parseSource($query, $sql, $parameters);
175 $sqlString = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
177 $this->parseConstraint($query->getConstraint(), $sql, $parameters, $query->getBoundVariableValues());
178 if (!empty($sql['where'])) {
179 $sqlString .= ' WHERE ' . implode('', $sql['where']);
180 if (!empty($sql['enableFields'])) {
181 $sqlString .= ' AND ' . implode(' AND ', $sql['enableFields']);
183 } elseif (!empty($sql['enableFields'])) {
184 $sqlString .= ' WHERE ' . implode(' AND ', $sql['enableFields']);
187 $this->parseOrderings($query->getOrderings(), $sql, $parameters, $query->getBoundVariableValues());
188 if (!empty($sql['orderings'])) {
189 $sqlString .= ' ORDER BY ' . implode(', ', $sql['orderings']);
192 $this->replacePlaceholders($sqlString, $parameters);
194 $result = $this->databaseHandle
->sql_query($sqlString);
196 // TODO Check for selector name
197 $tuples = $this->getRowsFromResult($query->getSelectorName(), $result);
204 * Checks if a Value Object equal to the given Object exists in the data base
206 * @param array $properties The properties of the Value Object
207 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
208 * @return array The matching tuples
210 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap
$dataMap) {
212 $parameters = array();
213 foreach ($properties as $propertyName => $propertyValue) {
214 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
215 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
216 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
220 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode('', $fields);
221 $this->replacePlaceholders($sqlString, $parameters);
222 $res = $this->databaseHandle
->sql_query($sqlString);
223 $row = $this->databaseHandle
->sql_fetch_assoc($res);
224 if ($row !== FALSE) {
232 * Transforms a Query Source into SQL and parameter arrays
234 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
236 * @param array &$parameters
239 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModel
$query, array &$sql, array &$parameters) {
240 $source = $query->getSource();
241 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
242 $selectorName = $source->getSelectorName();
243 $sql['fields'][] = $selectorName . '.*';
244 $sql['tables'][] = $selectorName;
245 // 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.
246 if ($this->useEnableFields
=== TRUE) {
247 $this->addEnableFieldsStatement($selectorName, $sql);
249 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
250 $this->parseJoin($source, $sql, $parameters);
255 * Transforms a Join into SQL and parameter arrays
257 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
259 * @param array &$parameters
262 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql, array &$parameters) {
263 $leftSelectorName = $join->getLeft()->getSelectorName();
264 $rightSelectorName = $join->getRight()->getSelectorName();
266 $sql['fields'][] = $leftSelectorName . '.*';
267 $sql['fields'][] = $rightSelectorName . '.*';
269 // TODO Implement support for different join types and nested joins
270 $sql['tables'][] = $leftSelectorName . ' LEFT JOIN ' . $rightSelectorName;
272 $joinCondition = $join->getJoinCondition();
273 // TODO Check the parsing of the join
274 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
275 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $joinCondition->getProperty1Name() . ' = ' . $joinCondition->getSelector2Name() . '.' . $joinCondition->getProperty2Name();
277 // TODO Implement childtableWhere
279 $this->addEnableFieldsStatement($leftSelectorName, $sql);
280 $this->addEnableFieldsStatement($rightSelectorName, $sql);
284 * Transforms a constraint into SQL and parameter arrays
286 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
288 * @param array &$parameters
289 * @param array $boundVariableValues
292 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
293 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
294 $sql['where'][] = '(';
295 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
296 $sql['where'][] = ' AND ';
297 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
298 $sql['where'][] = ')';
299 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
300 $sql['where'][] = '(';
301 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
302 $sql['where'][] = ' OR ';
303 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
304 $sql['where'][] = ')';
305 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
306 $sql['where'][] = 'NOT (';
307 $this->parseConstraint($constraint->getConstraint(), $sql, $parameters, $boundVariableValues);
308 $sql['where'][] = ')';
309 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
310 $this->parseComparison($constraint, $sql, $parameters, $boundVariableValues);
311 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface
) {
312 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
317 * Parse a Comparison into SQL and parameter arrays.
319 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
320 * @param array &$sql SQL query parts to add to
321 * @param array &$parameters Parameters to bind to the SQL
322 * @param array $boundVariableValues The bound variables in the query and their values
325 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, array &$sql, array &$parameters, array $boundVariableValues) {
326 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface
)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
328 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
329 $operator = $comparison->getOperator();
330 if ($value === NULL) {
331 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
) {
332 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
333 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
) {
334 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
336 // TODO Throw exception
339 $parameters[] = $value;
341 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $sql, $parameters);
345 * Parse a DynamicOperand into SQL and parameter arrays.
347 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
348 * @param string $operator One of the JCR_OPERATOR_* constants
349 * @param array $boundVariableValues
350 * @param array &$parameters
351 * @param string $valueFunction an aoptional SQL function to apply to the operand value
354 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, array &$sql, array &$parameters, $valueFunction = NULL) {
355 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
356 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'LOWER');
357 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
358 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'UPPER');
359 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
360 $selectorName = $operand->getSelectorName();
361 $operator = $this->resolveOperator($operator);
363 if ($valueFunction === NULL) {
364 $constraintSQL .= (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
366 $constraintSQL .= $valueFunction . '(' . (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
369 $sql['where'][] = $constraintSQL;
374 * Returns the SQL operator for the given JCR operator type.
376 * @param string $operator One of the JCR_OPERATOR_* constants
377 * @return string an SQL operator
379 protected function resolveOperator($operator) {
381 case self
::OPERATOR_EQUAL_TO_NULL
:
384 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
385 $operator = 'IS NOT';
387 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
:
390 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
:
393 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN
:
396 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO
:
399 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN
:
402 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
405 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LIKE
:
409 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
416 * Replace query placeholders in a query part by the given
419 * @param string $queryPart The query part with placeholders
420 * @param array $parameters The parameters
421 * @return string The query part with replaced placeholders
423 protected function replacePlaceholders(&$sqlString, array $parameters) {
424 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);
425 foreach ($parameters as $parameter) {
426 $markPosition = strpos($sqlString, '?');
427 if ($markPosition !== FALSE) {
428 // TODO This is a bit hacky; improve the handling of $parameter === NULL
429 if ($parameter === NULL) {
432 $parameter = '"' . $parameter . '"';
434 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
440 * Builds the enable fields statement
442 * @param string $selectorName The selector name (= database table name)
443 * @param array &$sql The query parts
446 protected function addEnableFieldsStatement($selectorName, array &$sql) {
447 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
448 if (is_array($GLOBALS['TCA'][$selectorName]['ctrl'])) {
449 $statement = substr($GLOBALS['TSFE']->sys_page
->enableFields($selectorName), 4);
450 if(!empty($statement)) {
451 $sql['enableFields'][] = $statement;
457 * Transforms orderings into SQL
459 * @param array $orderings
461 * @param array &$parameters
462 * @param array $boundVariableValues
465 protected function parseOrderings(array $orderings = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
466 if (is_array($orderings)) {
467 foreach ($orderings as $propertyName => $ordering) {
474 * Transforms a Resource from a database query to an array of rows. Performs the language and
475 * workspace overlay before.
477 * @return array The result as an array of rows (tuples)
479 protected function getRowsFromResult($tableName, $res) {
481 while ($row = $this->databaseHandle
->sql_fetch_assoc($res)) {
482 $row = $this->doLanguageAndWorkspaceOverlay($tableName, $row);
483 if (is_array($row)) {
484 // TODO Check if this is necessary, maybe the last line is enough
485 $arrayKeys = range(0,count($row));
486 array_fill_keys($arrayKeys, $row);
494 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
495 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
497 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
498 * @param array $row The row array (as reference)
499 * @param string $languageUid The language id
500 * @param string $workspaceUidUid The workspace id
503 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
504 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
505 if (TYPO3_MODE
== 'FE') {
506 if (is_object($GLOBALS['TSFE'])) {
507 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
508 if ($languageUid === NULL) {
509 $languageUid = $GLOBALS['TSFE']->sys_language_content
;
512 require_once(PATH_t3lib
. 'class.t3lib_page.php');
513 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
514 if ($languageUid === NULL) {
515 $languageUid = intval(t3lib_div
::_GP('L'));
518 if ($workspaceUid !== NULL) {
519 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
522 require_once(PATH_t3lib
. 'class.t3lib_page.php');
523 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
524 //$this->pageSelectObject->versioningPreview = TRUE;
525 if ($workspaceUid === NULL) {
526 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
528 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
532 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
533 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
534 // TODO Skip if empty languageoverlay (languagevisibility)
539 * Clear the TYPO3 page cache for the given record.
540 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
542 * @param $tableName Table name of the record
543 * @param $uid UID of the record
546 protected function clearPageCache($tableName, $uid) {
547 if ($this->automaticCacheClearing
!== TRUE) return;
549 $pageCache = $GLOBALS['typo3CacheManager']->getCache('cache_pages');
550 $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache('cache_pagesection');
552 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
554 $pageIdsToClear = array();
555 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
556 $storagePage = $row['pid'];
557 $pageIdsToClear[] = $storagePage;
563 $pageTSConfig = t3lib_BEfunc
::getPagesTSconfig($storagePage);
565 if ($pageTSConfig['clearCacheCmd']) {
566 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
567 $clearCacheCommands = array_unique($clearCacheCommands);
568 foreach ($clearCacheCommands as $clearCacheCommand) {
569 if (t3lib_div
::testInt($clearCacheCommand)) {
570 $pageIdsToClear[] = $clearCacheCommand;
575 foreach ($pageIdsToClear as $pageIdToClear) {
576 $pageCache->flushByTag('pageId_' . $pageIdToClear);
577 $pageSectionCache->flushByTag('pageId_' . $pageIdToClear);