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\Storage
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 * @var Tx_Extbase_Persistence_DataMapper
50 protected $dataMapper;
53 * The TYPO3 page select object. Used for language and workspace overlay
55 * @var t3lib_pageSelect
57 protected $pageSelectObject;
60 * A first-level TypoScript configuration cache
64 protected $pageTSConfigCache = array();
67 * Caches information about tables (esp. the existing column names)
71 protected $tableInformationCache = array();
74 * Constructs this Storage Backend instance
76 * @param t3lib_db $databaseHandle The database handle
78 public function __construct($databaseHandle) {
79 $this->databaseHandle
= $databaseHandle;
83 * Injects the DataMapper to map nodes to objects
85 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
88 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper
$dataMapper) {
89 $this->dataMapper
= $dataMapper;
93 * Adds a row to the storage
95 * @param string $tableName The database table name
96 * @param array $row The row to be inserted
97 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
98 * @return int The uid of the inserted row
100 public function addRow($tableName, array $row, $isRelation = FALSE) {
103 $parameters = array();
104 if (isset($row['uid'])) {
107 foreach ($row as $columnName => $value) {
108 $fields[] = $columnName;
110 $parameters[] = $value;
113 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
114 $this->replacePlaceholders($sqlString, $parameters);
115 // debug($sqlString,-2);
116 $this->databaseHandle
->sql_query($sqlString);
117 $this->checkSqlErrors();
118 $uid = $this->databaseHandle
->sql_insert_id();
120 $this->clearPageCache($tableName, $uid);
126 * Updates a row in the storage
128 * @param string $tableName The database table name
129 * @param array $row The row to be updated
130 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
133 public function updateRow($tableName, array $row, $isRelation = FALSE) {
134 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
135 $uid = (int)$row['uid'];
138 $parameters = array();
139 foreach ($row as $columnName => $value) {
140 $fields[] = $columnName . '=?';
141 $parameters[] = $value;
143 $parameters[] = $uid;
145 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
146 $this->replacePlaceholders($sqlString, $parameters);
147 // debug($sqlString,-2);
148 $returnValue = $this->databaseHandle
->sql_query($sqlString);
149 $this->checkSqlErrors();
151 $this->clearPageCache($tableName, $uid);
157 * Deletes a row in the storage
159 * @param string $tableName The database table name
160 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
161 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
164 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
165 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
166 $this->replacePlaceholders($statement, $identifier);
168 $this->clearPageCache($tableName, $uid, $isRelation);
170 $returnValue = $this->databaseHandle
->sql_query($statement);
171 $this->checkSqlErrors();
176 * Fetches row data from the database
178 * @param string $identifier The Identifier of the row to fetch
179 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
180 * @return array|FALSE
182 public function getRowByIdentifier($tableName, array $identifier) {
183 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
184 $this->replacePlaceholders($statement, $identifier);
185 // debug($statement,-2);
186 $res = $this->databaseHandle
->sql_query($statement);
187 $this->checkSqlErrors();
188 $row = $this->databaseHandle
->sql_fetch_assoc($res);
189 if ($row !== FALSE) {
196 protected function parseIdentifier(array $identifier) {
197 $fieldNames = array_keys($identifier);
198 $suffixedFieldNames = array();
199 foreach ($fieldNames as $fieldName) {
200 $suffixedFieldNames[] = $fieldName . '=?';
202 return implode(' AND ', $suffixedFieldNames);
206 * Returns the object data matching the $query.
208 * @param Tx_Extbase_Persistence_QueryInterface $query
210 * @author Karsten Dambekalns <karsten@typo3.org>
212 public function getObjectDataByQuery(Tx_Extbase_Persistence_QueryInterface
$query) {
213 $parameters = array();
215 $statement = $query->getStatement();
216 if($statement instanceof Tx_Extbase_Persistence_QOM_Statement
) {
217 $sql = $statement->getStatement();
218 $parameters = $statement->getBoundVariables();
220 $parameters = array();
221 $statementParts = $this->parseQuery($query, $parameters);
222 $sql = $this->buildQuery($statementParts, $parameters);
224 $this->replacePlaceholders($sql, $parameters);
226 $result = $this->databaseHandle
->sql_query($sql);
227 $this->checkSqlErrors();
228 $rows = $this->getRowsFromResult($query->getSource(), $result);
229 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows);
231 // $objectData = $this->processObjectRecords($statementHandle);
236 * Returns the number of tuples matching the query.
238 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
239 * @return int The number of matching tuples
241 public function getObjectCountByQuery(Tx_Extbase_Persistence_QueryInterface
$query) {
242 $constraint = $query->getConstraint();
243 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface
) throw new Tx_Extbase_Persistence_Storage_Exception_BadConstraint('Could not execute count on queries with a constraint of type Tx_Extbase_Persistence_QOM_StatementInterface', 1256661045);
244 $parameters = array();
245 $statementParts = $this->parseQuery($query, $parameters);
246 $statementParts['fields'] = array('COUNT(*)');
247 $statement = $this->buildQuery($statementParts, $parameters);
248 $this->replacePlaceholders($statement, $parameters);
250 $result = $this->databaseHandle
->sql_query($statement);
251 $this->checkSqlErrors();
252 $rows = $this->getRowsFromResult($query->getSource(), $result);
253 return current(current($rows));
257 * Parses the query and returns the SQL statement parts.
259 * @param Tx_Extbase_Persistence_QueryInterface $query
260 * @return array The SQL statement parts
262 public function parseQuery(Tx_Extbase_Persistence_QueryInterface
$query, array &$parameters) {
264 $sql['tables'] = array();
265 $sql['unions'] = array();
266 $sql['fields'] = array();
267 $sql['where'] = array();
268 $sql['additionalWhereClause'] = array();
269 $sql['orderings'] = array();
270 $sql['limit'] = array();
272 $source = $query->getSource();
274 $this->parseSource($source, $sql, $parameters);
275 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters);
276 $this->parseOrderings($query->getOrderings(), $source, $sql);
277 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
279 $tables = array_merge(array_keys($sql['tables']), array_keys($sql['unions']));
280 foreach ($tables as $tableName) {
281 if (is_string($tableName) && strlen($tableName) > 0) {
282 $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql);
290 * Returns the statement, ready to be executed.
292 * @param array $sql The SQL statement parts
293 * @return string The SQL statement
295 public function buildQuery(array $sql) {
296 $statement = 'SELECT DISTINCT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']) . ' '. implode(' ', $sql['unions']);
297 if (!empty($sql['where'])) {
298 $statement .= ' WHERE ' . implode('', $sql['where']);
299 if (!empty($sql['additionalWhereClause'])) {
300 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
302 } elseif (!empty($sql['additionalWhereClause'])) {
303 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
305 if (!empty($sql['orderings'])) {
306 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
308 if (!empty($sql['limit'])) {
309 $statement .= ' LIMIT ' . $sql['limit'];
315 * Checks if a Value Object equal to the given Object exists in the data base
317 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
318 * @return array The matching uid
320 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject
$object) {
322 $parameters = array();
323 $dataMap = $this->dataMapper
->getDataMap(get_class($object));
324 $properties = $object->_getProperties();
325 foreach ($properties as $propertyName => $propertyValue) {
326 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
327 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
328 if ($propertyValue === NULL) {
329 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
331 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
332 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
337 $sql['additionalWhereClause'] = array();
339 $tableName = $dataMap->getTableName();
340 $this->addEnableFieldsStatement($tableName, $sql);
342 $statement = 'SELECT * FROM ' . $tableName;
343 $statement .= ' WHERE ' . implode(' AND ', $fields);
344 if (!empty($sql['additionalWhereClause'])) {
345 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
347 $this->replacePlaceholders($statement, $parameters);
348 // debug($statement,-2);
349 $res = $this->databaseHandle
->sql_query($statement);
350 $this->checkSqlErrors();
351 $row = $this->databaseHandle
->sql_fetch_assoc($res);
352 if ($row !== FALSE) {
353 return (int)$row['uid'];
360 * Transforms a Query Source into SQL and parameter arrays
362 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
364 * @param array &$parameters
367 protected function parseSource(Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
368 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
369 $tableName = $source->getSelectorName();
370 $sql['fields'][] = $tableName . '.*';
371 $sql['tables'][] = $tableName;
372 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
373 $this->parseJoin($source, $sql);
378 * Transforms a Join into SQL and parameter arrays
380 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
381 * @param array &$sql The query parts
384 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql) {
385 $leftSource = $join->getLeft();
386 $leftTableName = $leftSource->getSelectorName();
387 $rightSource = $join->getRight();
388 $rightTableName = $rightSource->getSelectorName();
390 $sql['fields'][] = $leftTableName . '.*';
391 $sql['fields'][] = $rightTableName . '.*';
393 // TODO Implement support for different join types and nested joins
394 $sql['tables'][$leftTableName] = $leftTableName;
395 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
397 $joinCondition = $join->getJoinCondition();
398 // TODO Check the parsing of the join
399 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
400 // TODO Discuss, if we should use $leftSource instead of $selector1Name
401 $column1Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
402 $column2Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
403 $sql['unions'][$joinCondition->getSelector2Name()] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
405 // TODO Implement childtableWhere
409 * Transforms a constraint into SQL and parameter arrays
411 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
412 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
413 * @param array &$sql The query parts
414 * @param array &$parameters The parameters that will replace the markers
415 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
418 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
419 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
420 $sql['where'][] = '(';
421 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
422 $sql['where'][] = ' AND ';
423 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
424 $sql['where'][] = ')';
425 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
426 $sql['where'][] = '(';
427 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
428 $sql['where'][] = ' OR ';
429 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
430 $sql['where'][] = ')';
431 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
432 $sql['where'][] = 'NOT (';
433 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
434 $sql['where'][] = ')';
435 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
436 $this->parseComparison($constraint, $source, $sql, $parameters);
441 * Parse a Comparison into SQL and parameter arrays.
443 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
444 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
445 * @param array &$sql SQL query parts to add to
446 * @param array &$parameters Parameters to bind to the SQL
447 * @param array $boundVariableValues The bound variables in the query and their values
450 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
451 $operand1 = $comparison->getOperand1();
452 $operator = $comparison->getOperator();
453 $operand2 = $comparison->getOperand2();
454 if (($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) && (is_array($operand2) ||
($operand2 instanceof ArrayAccess
) ||
($operand2 instanceof Traversable
))) {
455 // FIXME this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
456 $operator = Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
;
459 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
) {
462 foreach ($operand2 as $value) {
463 $value = $this->getPlainValue($value);
464 if ($value !== NULL) {
469 if ($hasValue === FALSE) {
470 $sql['where'][] = '1<>1';
472 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
474 foreach ($operand2 as $value) {
475 $items[] = $this->getPlainValue($value);
477 $parameters[] = $items;
479 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_CONTAINS
) {
480 if ($operand2 === NULL) {
481 $sql['where'][] = '1<>1';
483 $dataMap = $this->dataMapper
->getDataMap($source->getNodeTypeName());
484 $columnMap = $dataMap->getColumnMap($operand1->getPropertyName());
485 $typeOfRelation = $columnMap->getTypeOfRelation();
486 $tableName = $operand1->getSelectorName();
487 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
488 $relationTableName = $columnMap->getRelationTableName();
489 $sql['where'][] = $tableName . '.uid IN (SELECT uid_local FROM ' . $relationTableName . ' WHERE uid_foreign=' . $this->getPlainValue($operand2) . ')';
490 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
491 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
492 if (isset($parentKeyFieldName)) {
493 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand1->getPropertyName(), $source->getNodeTypeName());
494 $childTableName = $columnMap->getChildTableName();
495 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
497 $statement = '(' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . ',%\'';
498 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . '\'';
499 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'' . $this->getPlainValue($operand2) . ',%\')';
500 $sql['where'][] = $statement;
503 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
507 if ($operand2 === NULL) {
508 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) {
509 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
510 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
) {
511 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
514 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
515 $parameters[] = $this->getPlainValue($operand2);
520 * Returns a plain value, i.e. objects are flattened out if possible.
522 * @param mixed $input
525 protected function getPlainValue($input) {
526 if ($input instanceof DateTime
) {
527 return $input->format('U');
528 } elseif ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface
) {
529 return $input->getUid();
530 } elseif (is_bool($input)) {
531 return $input === TRUE ?
1 : 0;
538 * Parse a DynamicOperand into SQL and parameter arrays.
540 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
541 * @param string $operator One of the JCR_OPERATOR_* constants
542 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
543 * @param array &$sql The query parts
544 * @param array &$parameters The parameters that will replace the markers
545 * @param string $valueFunction an optional SQL function to apply to the operand value
548 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
549 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
550 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
551 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
552 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
553 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
554 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) { // FIXME Only necessary to differ from Join
555 $className = $source->getNodeTypeName();
557 $propertyName = $operand->getPropertyName();
558 while (strpos($propertyName, '.') !== FALSE) {
559 $this->addUnionStatement($className, $propertyName, $sql);
561 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
562 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
563 $operator = $this->resolveOperator($operator);
564 if ($valueFunction === NULL) {
565 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
567 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
570 $sql['where'][] = $constraintSQL;
574 protected function addUnionStatement(&$className, &$propertyPath, array &$sql) {
575 $explodedPropertyPath = explode('.', $propertyPath, 2);
576 $propertyName = $explodedPropertyPath[0];
577 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
578 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
579 $columnMap = $this->dataMapper
->getDataMap($className)->getColumnMap($propertyName);
580 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
581 $childTableName = $columnMap->getChildTableName();
582 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_ONE
) {
583 if (isset($parentKeyFieldName)) {
584 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
586 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
588 $className = $columnMap->getChildClassName();
589 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
590 if (isset($parentKeyFieldName)) {
591 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
593 $onStatement = '(' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid,\',%\')';
594 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid)';
595 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(' . $childTableName . '.uid,\',%\'))';
596 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $onStatement;
598 $className = $this->dataMapper
->getElementType($className, $propertyName);
599 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
600 $relationTableName = $columnMap->getRelationTableName();
601 $sql['unions'][$relationTableName] = 'INNER JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.uid_local';
602 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $relationTableName . '.uid_foreign=' . $childTableName . '.uid';
603 $className = $this->dataMapper
->getElementType($className, $propertyName);
605 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
607 $propertyPath = $explodedPropertyPath[1];
611 * Returns the SQL operator for the given JCR operator type.
613 * @param string $operator One of the JCR_OPERATOR_* constants
614 * @return string an SQL operator
616 protected function resolveOperator($operator) {
618 case self
::OPERATOR_EQUAL_TO_NULL
:
621 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
622 $operator = 'IS NOT';
624 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
:
627 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
:
630 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
:
633 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN
:
636 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN_OR_EQUAL_TO
:
639 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN
:
642 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
645 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LIKE
:
649 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
656 * Replace query placeholders in a query part by the given
659 * @param string $sqlString The query part with placeholders
660 * @param array $parameters The parameters
661 * @return string The query part with replaced placeholders
663 protected function replacePlaceholders(&$sqlString, array $parameters) {
664 // TODO profile this method again
665 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);
667 foreach ($parameters as $parameter) {
668 $markPosition = strpos($sqlString, '?', $offset);
669 if ($markPosition !== FALSE) {
670 if ($parameter === NULL) {
672 } elseif (is_array($parameter) ||
($parameter instanceof ArrayAccess
) ||
($parameter instanceof Traversable
)) {
674 foreach ($parameter as $item) {
675 $items[] = $this->databaseHandle
->fullQuoteStr($item, 'foo');
677 $parameter = '(' . implode(',', $items) . ')';
679 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
681 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
683 $offset = $markPosition +
strlen($parameter);
688 * Adds additional WHERE statements according to the query settings.
690 * @param Tx_Extbase_Persistence_QuerySettingsInterface $querySettings The TYPO3 4.x specific query settings
691 * @param string $tableName The table name to add the additional where clause for
695 protected function addAdditionalWhereClause(Tx_Extbase_Persistence_QuerySettingsInterface
$querySettings, $tableName, &$sql) {
696 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettings
) {
697 if ($querySettings->getRespectEnableFields()) {
698 $this->addEnableFieldsStatement($tableName, $sql);
700 if ($querySettings->getRespectSysLanguage()) {
701 $this->addSysLanguageStatement($tableName, $sql);
703 if ($querySettings->getRespectStoragePage()) {
704 $this->addPageIdStatement($tableName, $sql);
710 * Builds the enable fields statement
712 * @param string $tableName The database table name
713 * @param array &$sql The query parts
716 protected function addEnableFieldsStatement($tableName, array &$sql) {
717 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
718 if (TYPO3_MODE
=== 'FE') {
719 $statement = $GLOBALS['TSFE']->sys_page
->enableFields($tableName);
720 } else { // TYPO3_MODE === 'BE'
721 $statement = t3lib_BEfunc
::deleteClause($tableName);
722 $statement .= t3lib_BEfunc
::BEenableFields($tableName);
724 if(!empty($statement)) {
725 $statement = substr($statement, 5);
726 $sql['additionalWhereClause'][] = $statement;
732 * Builds the language field statement
734 * @param string $tableName The database table name
735 * @param array &$sql The query parts
738 protected function addSysLanguageStatement($tableName, array &$sql) {
739 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
740 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
741 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
747 * Builds the page ID checking statement
749 * @param string $tableName The database table name
750 * @param array &$sql The query parts
753 protected function addPageIdStatement($tableName, array &$sql) {
754 if (empty($this->tableInformationCache
[$tableName]['columnNames'])) {
755 $this->tableInformationCache
[$tableName]['columnNames'] = $this->databaseHandle
->admin_get_fields($tableName);
757 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache
[$tableName]['columnNames'])) {
758 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
759 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div
::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
764 * Transforms orderings into SQL.
766 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
767 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
768 * @param array &$sql The query parts
771 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
772 foreach ($orderings as $ordering) {
773 $operand = $ordering->getOperand();
774 $order = $ordering->getOrder();
775 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue
) {
777 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
780 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
784 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
786 $tableName = $operand->getSelectorName();
788 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
789 $className = $source->getNodeTypeName();
791 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
792 if (strlen($tableName) > 0) {
793 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
795 $sql['orderings'][] = $columnName . ' ' . $order;
802 * Transforms limit and offset into SQL
809 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
810 if ($limit !== NULL && $offset !== NULL) {
811 $sql['limit'] = $offset . ', ' . $limit;
812 } elseif ($limit !== NULL) {
813 $sql['limit'] = $limit;
818 * Transforms a Resource from a database query to an array of rows.
820 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
821 * @param resource $result The result
822 * @return array The result as an array of rows (tuples)
824 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $result) {
826 while ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
827 if (is_array($row)) {
828 // TODO Check if this is necessary, maybe the last line is enough
829 $arrayKeys = range(0, count($row));
830 array_fill_keys($arrayKeys, $row);
838 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
839 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
841 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
842 * @param array $row The row array (as reference)
843 * @param string $languageUid The language id
844 * @param string $workspaceUidUid The workspace id
847 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface
$source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
848 $overlayedRows = array();
849 foreach ($rows as $row) {
850 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
851 if (TYPO3_MODE
== 'FE') {
852 if (is_object($GLOBALS['TSFE'])) {
853 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
855 require_once(PATH_t3lib
. 'class.t3lib_page.php');
856 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
859 require_once(PATH_t3lib
. 'class.t3lib_page.php');
860 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
863 if (is_object($GLOBALS['TSFE'])) {
864 if ($languageUid === NULL) {
865 $languageUid = $GLOBALS['TSFE']->sys_language_uid
;
867 if ($workspaceUid !== NULL) {
868 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
871 if ($languageUid === NULL) {
872 $languageUid = intval(t3lib_div
::_GP('L'));
874 if ($workspaceUid === NULL) {
875 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
877 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
879 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
880 $tableName = $source->getSelectorName();
881 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
882 $tableName = $source->getLeft()->getSelectorName();
884 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
885 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
886 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
887 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid);
890 $overlayedRows[] = $row;
892 return $overlayedRows;
896 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
899 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
901 protected function checkSqlErrors() {
902 $error = $this->databaseHandle
->sql_error();
904 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
909 * Clear the TYPO3 page cache for the given record.
910 * If the record lies on a page, then we clear the cache of this page.
911 * If the record has no PID column, we clear the cache of the current page as best-effort.
913 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
915 * @param $tableName Table name of the record
916 * @param $uid UID of the record
919 protected function clearPageCache($tableName, $uid) {
920 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
921 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
923 // if disabled, return
927 $pageIdsToClear = array();
930 $columns = $this->databaseHandle
->admin_get_fields($tableName);
931 if (array_key_exists('pid', $columns)) {
932 $result = $this->databaseHandle
->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
933 if ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
934 $storagePage = $row['pid'];
935 $pageIdsToClear[] = $storagePage;
937 } elseif (isset($GLOBALS['TSFE'])) {
938 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
939 $storagePage = $GLOBALS['TSFE']->id
;
940 $pageIdsToClear[] = $storagePage;
943 if ($storagePage === NULL) {
946 if (!isset($this->pageTSConfigCache
[$storagePage])) {
947 $this->pageTSConfigCache
[$storagePage] = t3lib_BEfunc
::getPagesTSconfig($storagePage);
949 if (isset($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
950 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
951 $clearCacheCommands = array_unique($clearCacheCommands);
952 foreach ($clearCacheCommands as $clearCacheCommand) {
953 if (t3lib_div
::testInt($clearCacheCommand)) {
954 $pageIdsToClear[] = $clearCacheCommand;
959 // TODO check if we can hand this over to the Dispatcher to clear the page only once, this will save around 10% time while inserting and updating
960 Tx_Extbase_Utility_Cache
::clearPageCache($pageIdsToClear);