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 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
76 public function __construct() {
77 $this->databaseHandle
= $GLOBALS['TYPO3_DB'];
81 * Injects the DataMapper to map nodes to objects
83 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
86 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper
$dataMapper) {
87 $this->dataMapper
= $dataMapper;
91 * Adds a row to the storage
93 * @param string $tableName The database table name
94 * @param array $row The row to be inserted
95 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
96 * @return int The uid of the inserted row
98 public function addRow($tableName, array $row, $isRelation = FALSE) {
101 $parameters = array();
102 if (isset($row['uid'])) {
105 foreach ($row as $columnName => $value) {
106 $fields[] = $columnName;
108 $parameters[] = $value;
111 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
112 $this->replacePlaceholders($sqlString, $parameters);
113 // debug($sqlString,-2);
114 $this->databaseHandle
->sql_query($sqlString);
115 $this->checkSqlErrors($sqlString);
116 $uid = $this->databaseHandle
->sql_insert_id();
118 $this->clearPageCache($tableName, $uid);
124 * Updates a row in the storage
126 * @param string $tableName The database table name
127 * @param array $row The row to be updated
128 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
131 public function updateRow($tableName, array $row, $isRelation = FALSE) {
132 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
133 $uid = (int)$row['uid'];
136 $parameters = array();
137 foreach ($row as $columnName => $value) {
138 $fields[] = $columnName . '=?';
139 $parameters[] = $value;
141 $parameters[] = $uid;
143 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
144 $this->replacePlaceholders($sqlString, $parameters);
145 // debug($sqlString,-2);
146 $returnValue = $this->databaseHandle
->sql_query($sqlString);
147 $this->checkSqlErrors($sqlString);
149 $this->clearPageCache($tableName, $uid);
155 * Deletes a row in the storage
157 * @param string $tableName The database table name
158 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
159 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
162 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
163 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
164 $this->replacePlaceholders($statement, $identifier);
165 if (!$isRelation && isset($identifier['uid'])) {
166 $this->clearPageCache($tableName, $identifier['uid'], $isRelation);
168 // debug($statement, -2);
169 $returnValue = $this->databaseHandle
->sql_query($statement);
170 $this->checkSqlErrors($statement);
175 * Fetches row data from the database
177 * @param string $identifier The Identifier of the row to fetch
178 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
179 * @return array|FALSE
181 public function getRowByIdentifier($tableName, array $identifier) {
182 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
183 $this->replacePlaceholders($statement, $identifier);
184 // debug($statement,-2);
185 $res = $this->databaseHandle
->sql_query($statement);
186 $this->checkSqlErrors($statement);
187 $row = $this->databaseHandle
->sql_fetch_assoc($res);
188 if ($row !== FALSE) {
195 protected function parseIdentifier(array $identifier) {
196 $fieldNames = array_keys($identifier);
197 $suffixedFieldNames = array();
198 foreach ($fieldNames as $fieldName) {
199 $suffixedFieldNames[] = $fieldName . '=?';
201 return implode(' AND ', $suffixedFieldNames);
205 * Returns the object data matching the $query.
207 * @param Tx_Extbase_Persistence_QueryInterface $query
209 * @author Karsten Dambekalns <karsten@typo3.org>
211 public function getObjectDataByQuery(Tx_Extbase_Persistence_QueryInterface
$query) {
212 $parameters = array();
214 $statement = $query->getStatement();
215 if($statement instanceof Tx_Extbase_Persistence_QOM_Statement
) {
216 $sql = $statement->getStatement();
217 $parameters = $statement->getBoundVariables();
219 $parameters = array();
220 $statementParts = $this->parseQuery($query, $parameters);
221 $sql = $this->buildQuery($statementParts, $parameters);
223 $this->replacePlaceholders($sql, $parameters);
225 $result = $this->databaseHandle
->sql_query($sql);
226 $this->checkSqlErrors($sql);
227 $rows = $this->getRowsFromResult($query->getSource(), $result);
228 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows);
229 // TODO: implement $objectData = $this->processObjectRecords($statementHandle);
234 * Returns the number of tuples matching the query.
236 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
237 * @return int The number of matching tuples
239 public function getObjectCountByQuery(Tx_Extbase_Persistence_QueryInterface
$query) {
240 $constraint = $query->getConstraint();
241 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);
242 $parameters = array();
243 $statementParts = $this->parseQuery($query, $parameters);
244 $statementParts['fields'] = array('COUNT(*)');
245 $statement = $this->buildQuery($statementParts, $parameters);
246 $this->replacePlaceholders($statement, $parameters);
247 // debug($statement,-2);
248 $result = $this->databaseHandle
->sql_query($statement);
249 $this->checkSqlErrors($statement);
250 $rows = $this->getRowsFromResult($query->getSource(), $result);
251 return current(current($rows));
255 * Parses the query and returns the SQL statement parts.
257 * @param Tx_Extbase_Persistence_QueryInterface $query The query
258 * @return array The SQL statement parts
260 public function parseQuery(Tx_Extbase_Persistence_QueryInterface
$query, array &$parameters) {
262 $sql['keywords'] = array();
263 $sql['tables'] = array();
264 $sql['unions'] = array();
265 $sql['fields'] = array();
266 $sql['where'] = array();
267 $sql['additionalWhereClause'] = array();
268 $sql['orderings'] = array();
269 $sql['limit'] = array();
271 $source = $query->getSource();
273 $this->parseSource($source, $sql, $parameters);
274 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters);
275 $this->parseOrderings($query->getOrderings(), $source, $sql);
276 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
278 $tableNames = array_unique(array_keys($sql['tables'] +
$sql['unions']));
279 foreach ($tableNames as $tableName) {
280 if (is_string($tableName) && strlen($tableName) > 0) {
281 $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql);
289 * Returns the statement, ready to be executed.
291 * @param array $sql The SQL statement parts
292 * @return string The SQL statement
294 public function buildQuery(array $sql) {
295 $statement = 'SELECT ' . implode(' ', $sql['keywords']) . ' '. implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']) . ' '. implode(' ', $sql['unions']);
296 if (!empty($sql['where'])) {
297 $statement .= ' WHERE ' . implode('', $sql['where']);
298 if (!empty($sql['additionalWhereClause'])) {
299 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
301 } elseif (!empty($sql['additionalWhereClause'])) {
302 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
304 if (!empty($sql['orderings'])) {
305 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
307 if (!empty($sql['limit'])) {
308 $statement .= ' LIMIT ' . $sql['limit'];
314 * Checks if a Value Object equal to the given Object exists in the data base
316 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
317 * @return array The matching uid
319 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject
$object) {
321 $parameters = array();
322 $dataMap = $this->dataMapper
->getDataMap(get_class($object));
323 $properties = $object->_getProperties();
324 foreach ($properties as $propertyName => $propertyValue) {
325 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
326 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
327 if ($propertyValue === NULL) {
328 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
330 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
331 $parameters[] = $this->getPlainValue($propertyValue);
336 $sql['additionalWhereClause'] = array();
338 $tableName = $dataMap->getTableName();
339 $this->addEnableFieldsStatement($tableName, $sql);
341 $statement = 'SELECT * FROM ' . $tableName;
342 $statement .= ' WHERE ' . implode(' AND ', $fields);
343 if (!empty($sql['additionalWhereClause'])) {
344 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
346 $this->replacePlaceholders($statement, $parameters);
347 // debug($statement,-2);
348 $res = $this->databaseHandle
->sql_query($statement);
349 $this->checkSqlErrors($statement);
350 $row = $this->databaseHandle
->sql_fetch_assoc($res);
351 if ($row !== FALSE) {
352 return (int)$row['uid'];
359 * Transforms a Query Source into SQL and parameter arrays
361 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
363 * @param array &$parameters
366 protected function parseSource(Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
367 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
368 $className = $source->getNodeTypeName();
369 $tableName = $this->dataMapper
->getDataMap($className)->getTableName();
370 $this->addRecordTypeConstraint($className, $sql);
371 $sql['fields'][$tableName] = $tableName . '.*';
372 $sql['tables'][$tableName] = $tableName;
373 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
374 $this->parseJoin($source, $sql);
379 * Adda a constrint to ensure that the record type of the returned tuples is matching the data type of the repository.
381 * @param string $className The class name
382 * @param array &$sql The query parts
385 protected function addRecordTypeConstraint($className, &$sql) {
386 if ($className !== NULL) {
387 $dataMap = $this->dataMapper
->getDataMap($className);
388 if ($dataMap->getRecordTypeColumnName() !== NULL) {
389 $recordTypes = array();
390 if ($dataMap->getRecordType() !== NULL) {
391 $recordTypes[] = $dataMap->getRecordType();
393 foreach ($dataMap->getSubclasses() as $subclassName) {
394 $subclassDataMap = $this->dataMapper
->getDataMap($subclassName);
395 if ($subclassDataMap->getRecordType() !== NULL) {
396 $recordTypes[] = $subclassDataMap->getRecordType();
399 if (count($recordTypes) > 0) {
400 $recordTypeStatements = array();
401 foreach ($recordTypes as $recordType) {
402 $recordTypeStatements[] = $dataMap->getTableName() . '.' . $dataMap->getRecordTypeColumnName() . '=' . $this->databaseHandle
->fullQuoteStr($recordType, 'foo');
404 $sql['additionalWhereClause'][] = '(' . implode(' OR ', $recordTypeStatements) . ')';
411 * Transforms a Join into SQL and parameter arrays
413 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
414 * @param array &$sql The query parts
417 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql) {
418 $leftSource = $join->getLeft();
419 $leftClassName = $leftSource->getNodeTypeName();
420 $this->addRecordTypeConstraint($leftClassName, $sql);
421 $leftTableName = $leftSource->getSelectorName();
422 // $sql['fields'][$leftTableName] = $leftTableName . '.*';
423 $rightSource = $join->getRight();
424 if ($rightSource instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
425 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
426 $rightTableName = $rightSource->getLeft()->getSelectorName();
428 $rightClassName = $rightSource->getNodeTypeName();
429 $rightTableName = $rightSource->getSelectorName();
430 $sql['fields'][$leftTableName] = $rightTableName . '.*';
432 $this->addRecordTypeConstraint($rightClassName, $sql);
434 $sql['tables'][$leftTableName] = $leftTableName;
435 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
437 $joinCondition = $join->getJoinCondition();
438 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
439 $column1Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
440 $column2Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
441 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
443 if ($rightSource instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
444 $this->parseJoin($rightSource, $sql);
449 * Transforms a constraint into SQL and parameter arrays
451 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
452 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
453 * @param array &$sql The query parts
454 * @param array &$parameters The parameters that will replace the markers
455 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
458 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
459 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
460 $sql['where'][] = '(';
461 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
462 $sql['where'][] = ' AND ';
463 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
464 $sql['where'][] = ')';
465 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
466 $sql['where'][] = '(';
467 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
468 $sql['where'][] = ' OR ';
469 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
470 $sql['where'][] = ')';
471 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
472 $sql['where'][] = 'NOT (';
473 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
474 $sql['where'][] = ')';
475 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
476 $this->parseComparison($constraint, $source, $sql, $parameters);
481 * Parse a Comparison into SQL and parameter arrays.
483 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
484 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
485 * @param array &$sql SQL query parts to add to
486 * @param array &$parameters Parameters to bind to the SQL
487 * @param array $boundVariableValues The bound variables in the query and their values
490 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
491 $operand1 = $comparison->getOperand1();
492 $operator = $comparison->getOperator();
493 $operand2 = $comparison->getOperand2();
494 if (($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) && (is_array($operand2) ||
($operand2 instanceof ArrayAccess
) ||
($operand2 instanceof Traversable
))) {
495 // this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
496 $operator = Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
;
499 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
) {
502 foreach ($operand2 as $value) {
503 $value = $this->getPlainValue($value);
504 if ($value !== NULL) {
509 if ($hasValue === FALSE) {
510 $sql['where'][] = '1<>1';
512 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
513 $parameters[] = $items;
515 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_CONTAINS
) {
516 if ($operand2 === NULL) {
517 $sql['where'][] = '1<>1';
519 $className = $source->getNodeTypeName();
520 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
521 $propertyName = $operand1->getPropertyName();
522 while (strpos($propertyName, '.') !== FALSE) {
523 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
525 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
526 $dataMap = $this->dataMapper
->getDataMap($className);
527 $columnMap = $dataMap->getColumnMap($propertyName);
528 $typeOfRelation = $columnMap->getTypeOfRelation();
529 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
530 $relationTableName = $columnMap->getRelationTableName();
531 $sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=' . $this->getPlainValue($operand2) . ')';
532 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
533 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
534 if (isset($parentKeyFieldName)) {
535 $childTableName = $columnMap->getChildTableName();
536 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
538 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand1->getPropertyName(), $source->getNodeTypeName());
539 $statement = 'FIND_IN_SET(' . $this->getPlainValue($operand2) . ',' . $tableName . '.' . $columnName . ')';
540 $sql['where'][] = $statement;
543 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
547 if ($operand2 === NULL) {
548 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) {
549 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
550 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
) {
551 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
554 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
555 $parameters[] = $this->getPlainValue($operand2);
560 * Returns a plain value, i.e. objects are flattened out if possible.
562 * @param mixed $input
565 protected function getPlainValue($input) {
566 if (is_array($input)) {
567 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
569 if ($input instanceof DateTime
) {
570 return $input->format('U');
571 } elseif (is_object($input)) {
572 if ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface
) {
573 return $input->getUid();
575 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('An object of class "' . get_class($input) . '" could not be converted to a plain value.', 1274799934);
577 } elseif (is_bool($input)) {
578 return $input === TRUE ?
1 : 0;
585 * Parse a DynamicOperand into SQL and parameter arrays.
587 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
588 * @param string $operator One of the JCR_OPERATOR_* constants
589 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
590 * @param array &$sql The query parts
591 * @param array &$parameters The parameters that will replace the markers
592 * @param string $valueFunction an optional SQL function to apply to the operand value
595 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
596 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
597 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
598 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
599 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
600 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
601 $propertyName = $operand->getPropertyName();
602 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) { // FIXME Only necessary to differ from Join
603 $className = $source->getNodeTypeName();
604 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
605 while (strpos($propertyName, '.') !== FALSE) {
606 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
608 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
609 $tableName = $source->getJoinCondition()->getSelector1Name();
611 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
612 $operator = $this->resolveOperator($operator);
613 if ($valueFunction === NULL) {
614 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
616 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
619 $sql['where'][] = $constraintSQL;
623 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
624 $explodedPropertyPath = explode('.', $propertyPath, 2);
625 $propertyName = $explodedPropertyPath[0];
626 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
627 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
628 $columnMap = $this->dataMapper
->getDataMap($className)->getColumnMap($propertyName);
629 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
630 $childTableName = $columnMap->getChildTableName();
631 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_ONE
) {
632 if (isset($parentKeyFieldName)) {
633 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
635 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
637 $className = $this->dataMapper
->getType($className, $propertyName);
638 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
639 if (isset($parentKeyFieldName)) {
640 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
642 $onStatement = '(' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid,\',%\')';
643 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid)';
644 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(' . $childTableName . '.uid,\',%\'))';
645 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $onStatement;
647 $className = $this->dataMapper
->getType($className, $propertyName);
648 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
649 $relationTableName = $columnMap->getRelationTableName();
650 $sql['unions'][$relationTableName] = 'LEFT JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.uid_local';
651 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $relationTableName . '.uid_foreign=' . $childTableName . '.uid';
652 $className = $this->dataMapper
->getType($className, $propertyName);
654 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
656 // TODO check if there is another solution for this
657 $sql['keywords']['distinct'] = 'DISTINCT';
658 $propertyPath = $explodedPropertyPath[1];
659 $tableName = $childTableName;
663 * Returns the SQL operator for the given JCR operator type.
665 * @param string $operator One of the JCR_OPERATOR_* constants
666 * @return string an SQL operator
668 protected function resolveOperator($operator) {
670 case self
::OPERATOR_EQUAL_TO_NULL
:
673 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
674 $operator = 'IS NOT';
676 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
:
679 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
:
682 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
:
685 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN
:
688 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN_OR_EQUAL_TO
:
691 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN
:
694 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
697 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LIKE
:
701 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
708 * Replace query placeholders in a query part by the given
711 * @param string $sqlString The query part with placeholders
712 * @param array $parameters The parameters
713 * @return string The query part with replaced placeholders
715 protected function replacePlaceholders(&$sqlString, array $parameters) {
716 // TODO profile this method again
717 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);
719 foreach ($parameters as $parameter) {
720 $markPosition = strpos($sqlString, '?', $offset);
721 if ($markPosition !== FALSE) {
722 if ($parameter === NULL) {
724 } elseif (is_array($parameter) ||
($parameter instanceof ArrayAccess
) ||
($parameter instanceof Traversable
)) {
726 foreach ($parameter as $item) {
727 $items[] = $this->databaseHandle
->fullQuoteStr($item, 'foo');
729 $parameter = '(' . implode(',', $items) . ')';
731 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
733 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
735 $offset = $markPosition +
strlen($parameter);
740 * Adds additional WHERE statements according to the query settings.
742 * @param Tx_Extbase_Persistence_QuerySettingsInterface $querySettings The TYPO3 4.x specific query settings
743 * @param string $tableName The table name to add the additional where clause for
747 protected function addAdditionalWhereClause(Tx_Extbase_Persistence_QuerySettingsInterface
$querySettings, $tableName, &$sql) {
748 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettings
) {
749 if ($querySettings->getRespectEnableFields()) {
750 $this->addEnableFieldsStatement($tableName, $sql);
752 if ($querySettings->getRespectSysLanguage()) {
753 $this->addSysLanguageStatement($tableName, $sql);
755 if ($querySettings->getRespectStoragePage()) {
756 $this->addPageIdStatement($tableName, $sql);
762 * Builds the enable fields statement
764 * @param string $tableName The database table name
765 * @param array &$sql The query parts
768 protected function addEnableFieldsStatement($tableName, array &$sql) {
769 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
770 if (TYPO3_MODE
=== 'FE') {
771 $statement = $GLOBALS['TSFE']->sys_page
->enableFields($tableName);
772 } else { // TYPO3_MODE === 'BE'
773 $statement = t3lib_BEfunc
::deleteClause($tableName);
774 $statement .= t3lib_BEfunc
::BEenableFields($tableName);
776 if(!empty($statement)) {
777 $statement = substr($statement, 5);
778 $sql['additionalWhereClause'][] = $statement;
784 * Builds the language field statement
786 * @param string $tableName The database table name
787 * @param array &$sql The query parts
790 protected function addSysLanguageStatement($tableName, array &$sql) {
791 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
792 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
793 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
799 * Builds the page ID checking statement
801 * @param string $tableName The database table name
802 * @param array &$sql The query parts
805 protected function addPageIdStatement($tableName, array &$sql) {
806 if (empty($this->tableInformationCache
[$tableName]['columnNames'])) {
807 $this->tableInformationCache
[$tableName]['columnNames'] = $this->databaseHandle
->admin_get_fields($tableName);
809 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache
[$tableName]['columnNames'])) {
810 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
811 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div
::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
816 * Transforms orderings into SQL.
818 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
819 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
820 * @param array &$sql The query parts
823 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
824 foreach ($orderings as $propertyName => $order) {
826 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
: // Deprecated since Extbase 1.1
827 case Tx_Extbase_Persistence_QueryInterface
::ORDER_ASCENDING
:
830 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
: // Deprecated since Extbase 1.1
831 case Tx_Extbase_Persistence_QueryInterface
::ORDER_DESCENDING
:
835 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
837 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
838 $className = $source->getNodeTypeName();
839 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
840 while (strpos($propertyName, '.') !== FALSE) {
841 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
843 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
844 $tableName = $source->getLeft()->getSelectorName();
846 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
847 if (strlen($tableName) > 0) {
848 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
850 $sql['orderings'][] = $columnName . ' ' . $order;
856 * Transforms limit and offset into SQL
863 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
864 if ($limit !== NULL && $offset !== NULL) {
865 $sql['limit'] = $offset . ', ' . $limit;
866 } elseif ($limit !== NULL) {
867 $sql['limit'] = $limit;
872 * Transforms a Resource from a database query to an array of rows.
874 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
875 * @param resource $result The result
876 * @return array The result as an array of rows (tuples)
878 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $result) {
880 while ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
881 if (is_array($row)) {
882 // TODO Check if this is necessary, maybe the last line is enough
883 $arrayKeys = range(0, count($row));
884 array_fill_keys($arrayKeys, $row);
892 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
893 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
895 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
896 * @param array $row The row array (as reference)
897 * @param string $languageUid The language id
898 * @param string $workspaceUidUid The workspace id
901 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface
$source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
902 $overlayedRows = array();
903 foreach ($rows as $row) {
904 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
905 if (TYPO3_MODE
== 'FE') {
906 if (is_object($GLOBALS['TSFE'])) {
907 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
909 require_once(PATH_t3lib
. 'class.t3lib_page.php');
910 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
913 require_once(PATH_t3lib
. 'class.t3lib_page.php');
914 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
917 if (is_object($GLOBALS['TSFE'])) {
918 if ($languageUid === NULL) {
919 $languageUid = $GLOBALS['TSFE']->sys_language_uid
;
920 $languageMode = $GLOBALS['TSFE']->sys_language_mode
;
922 if ($workspaceUid !== NULL) {
923 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
926 if ($languageUid === NULL) {
927 $languageUid = intval(t3lib_div
::_GP('L'));
929 if ($workspaceUid === NULL) {
930 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
932 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
934 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
935 $tableName = $source->getSelectorName();
936 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
937 $tableName = $source->getRight()->getSelectorName();
939 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
940 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
941 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
942 $overlayMode = ($languageMode === 'strict') ?
'hideNonTranslated' : '';
943 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, $overlayMode);
947 $overlayedRows[] = $row;
950 return $overlayedRows;
954 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
957 * @param string $sql The SQL statement
958 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
960 protected function checkSqlErrors($sql='') {
961 $error = $this->databaseHandle
->sql_error();
963 $error .= $sql ?
': ' . $sql : '';
964 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
969 * Clear the TYPO3 page cache for the given record.
970 * If the record lies on a page, then we clear the cache of this page.
971 * If the record has no PID column, we clear the cache of the current page as best-effort.
973 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
975 * @param $tableName Table name of the record
976 * @param $uid UID of the record
979 protected function clearPageCache($tableName, $uid) {
980 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
981 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
983 // if disabled, return
987 $pageIdsToClear = array();
990 $columns = $this->databaseHandle
->admin_get_fields($tableName);
991 if (array_key_exists('pid', $columns)) {
992 $result = $this->databaseHandle
->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
993 if ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
994 $storagePage = $row['pid'];
995 $pageIdsToClear[] = $storagePage;
997 } elseif (isset($GLOBALS['TSFE'])) {
998 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
999 $storagePage = $GLOBALS['TSFE']->id
;
1000 $pageIdsToClear[] = $storagePage;
1003 if ($storagePage === NULL) {
1006 if (!isset($this->pageTSConfigCache
[$storagePage])) {
1007 $this->pageTSConfigCache
[$storagePage] = t3lib_BEfunc
::getPagesTSconfig($storagePage);
1009 if (isset($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
1010 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
1011 $clearCacheCommands = array_unique($clearCacheCommands);
1012 foreach ($clearCacheCommands as $clearCacheCommand) {
1013 if (t3lib_div
::testInt($clearCacheCommand)) {
1014 $pageIdsToClear[] = $clearCacheCommand;
1019 // 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
1020 Tx_Extbase_Utility_Cache
::clearPageCache($pageIdsToClear);