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);
230 // TODO: implement $objectData = $this->processObjectRecords($statementHandle);
235 * Returns the number of tuples matching the query.
237 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
238 * @return int The number of matching tuples
240 public function getObjectCountByQuery(Tx_Extbase_Persistence_QueryInterface
$query) {
241 $constraint = $query->getConstraint();
242 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);
243 $parameters = array();
244 $statementParts = $this->parseQuery($query, $parameters);
245 $statementParts['fields'] = array('COUNT(*)');
246 $statement = $this->buildQuery($statementParts, $parameters);
247 $this->replacePlaceholders($statement, $parameters);
249 $result = $this->databaseHandle
->sql_query($statement);
250 $this->checkSqlErrors();
251 $rows = $this->getRowsFromResult($query->getSource(), $result);
252 return current(current($rows));
256 * Parses the query and returns the SQL statement parts.
258 * @param Tx_Extbase_Persistence_QueryInterface $query
259 * @return array The SQL statement parts
261 public function parseQuery(Tx_Extbase_Persistence_QueryInterface
$query, array &$parameters) {
263 $sql['keywords'] = array();
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 ' . implode(' ', $sql['keywords']) . ' '. 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] = $tableName . '.*';
371 $sql['tables'][$tableName] = $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 $leftClassName = $leftSource->getNodeTypeName();
387 $leftTableName = $leftSource->getSelectorName();
388 // $sql['fields'][$leftTableName] = $leftTableName . '.*';
389 $rightSource = $join->getRight();
390 if ($rightSource instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
391 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
392 $rightTableName = $rightSource->getLeft()->getSelectorName();
394 $rightClassName = $rightSource->getNodeTypeName();
395 $rightTableName = $rightSource->getSelectorName();
396 $sql['fields'][$leftTableName] = $rightTableName . '.*';
399 $sql['tables'][$leftTableName] = $leftTableName;
400 $sql['unions'][$rightTableName] = 'INNER JOIN ' . $rightTableName;
402 $joinCondition = $join->getJoinCondition();
403 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
404 $column1Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
405 $column2Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
406 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
408 if ($rightSource instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
409 $this->parseJoin($rightSource, $sql);
414 * Transforms a constraint into SQL and parameter arrays
416 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
417 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
418 * @param array &$sql The query parts
419 * @param array &$parameters The parameters that will replace the markers
420 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
423 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
424 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
425 $sql['where'][] = '(';
426 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
427 $sql['where'][] = ' AND ';
428 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
429 $sql['where'][] = ')';
430 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
431 $sql['where'][] = '(';
432 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
433 $sql['where'][] = ' OR ';
434 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
435 $sql['where'][] = ')';
436 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
437 $sql['where'][] = 'NOT (';
438 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
439 $sql['where'][] = ')';
440 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
441 $this->parseComparison($constraint, $source, $sql, $parameters);
446 * Parse a Comparison into SQL and parameter arrays.
448 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
449 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
450 * @param array &$sql SQL query parts to add to
451 * @param array &$parameters Parameters to bind to the SQL
452 * @param array $boundVariableValues The bound variables in the query and their values
455 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
456 $operand1 = $comparison->getOperand1();
457 $operator = $comparison->getOperator();
458 $operand2 = $comparison->getOperand2();
459 if (($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) && (is_array($operand2) ||
($operand2 instanceof ArrayAccess
) ||
($operand2 instanceof Traversable
))) {
460 // FIXME this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
461 $operator = Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
;
464 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
) {
467 foreach ($operand2 as $value) {
468 $value = $this->getPlainValue($value);
469 if ($value !== NULL) {
474 if ($hasValue === FALSE) {
475 $sql['where'][] = '1<>1';
477 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
479 foreach ($operand2 as $value) {
480 $items[] = $this->getPlainValue($value);
482 $parameters[] = $items;
484 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_CONTAINS
) {
485 if ($operand2 === NULL) {
486 $sql['where'][] = '1<>1';
488 $className = $source->getNodeTypeName();
489 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
490 $propertyName = $operand1->getPropertyName();
491 while (strpos($propertyName, '.') !== FALSE) {
492 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
494 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
495 $dataMap = $this->dataMapper
->getDataMap($className);
496 $columnMap = $dataMap->getColumnMap($propertyName);
497 $typeOfRelation = $columnMap->getTypeOfRelation();
498 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
499 $relationTableName = $columnMap->getRelationTableName();
500 $sql['where'][] = $tableName . '.uid IN (SELECT uid_local FROM ' . $relationTableName . ' WHERE uid_foreign=' . $this->getPlainValue($operand2) . ')';
501 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
502 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
503 if (isset($parentKeyFieldName)) {
504 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand1->getPropertyName(), $source->getNodeTypeName());
505 $childTableName = $columnMap->getChildTableName();
506 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
508 $statement = '(' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . ',%\'';
509 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . '\'';
510 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'' . $this->getPlainValue($operand2) . ',%\')';
511 $sql['where'][] = $statement;
514 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
518 if ($operand2 === NULL) {
519 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) {
520 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
521 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
) {
522 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
525 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
526 $parameters[] = $this->getPlainValue($operand2);
531 * Returns a plain value, i.e. objects are flattened out if possible.
533 * @param mixed $input
536 protected function getPlainValue($input) {
537 if ($input instanceof DateTime
) {
538 return $input->format('U');
539 } elseif ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface
) {
540 return $input->getUid();
541 } elseif (is_bool($input)) {
542 return $input === TRUE ?
1 : 0;
549 * Parse a DynamicOperand into SQL and parameter arrays.
551 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
552 * @param string $operator One of the JCR_OPERATOR_* constants
553 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
554 * @param array &$sql The query parts
555 * @param array &$parameters The parameters that will replace the markers
556 * @param string $valueFunction an optional SQL function to apply to the operand value
559 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
560 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
561 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
562 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
563 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
564 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
565 $propertyName = $operand->getPropertyName();
566 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) { // FIXME Only necessary to differ from Join
567 $className = $source->getNodeTypeName();
568 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
569 while (strpos($propertyName, '.') !== FALSE) {
570 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
572 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
573 $tableName = $source->getJoinCondition()->getSelector1Name();
575 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
576 $operator = $this->resolveOperator($operator);
577 if ($valueFunction === NULL) {
578 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
580 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
583 $sql['where'][] = $constraintSQL;
587 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
588 $explodedPropertyPath = explode('.', $propertyPath, 2);
589 $propertyName = $explodedPropertyPath[0];
590 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
591 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
592 $columnMap = $this->dataMapper
->getDataMap($className)->getColumnMap($propertyName);
593 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
594 $childTableName = $columnMap->getChildTableName();
595 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_ONE
) {
596 if (isset($parentKeyFieldName)) {
597 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
599 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
601 $className = $this->dataMapper
->getType($className, $propertyName);
602 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
603 if (isset($parentKeyFieldName)) {
604 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
606 $onStatement = '(' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid,\',%\')';
607 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid)';
608 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(' . $childTableName . '.uid,\',%\'))';
609 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $onStatement;
611 $className = $this->dataMapper
->getElementType($className, $propertyName);
612 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
613 $relationTableName = $columnMap->getRelationTableName();
614 $sql['unions'][$relationTableName] = 'INNER JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.uid_local';
615 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $relationTableName . '.uid_foreign=' . $childTableName . '.uid';
616 $className = $this->dataMapper
->getElementType($className, $propertyName);
618 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
620 // TODO check if there is another solution for this
621 $sql['keywords']['distinct'] = 'DISTINCT';
622 $propertyPath = $explodedPropertyPath[1];
623 $tableName = $childTableName;
627 * Returns the SQL operator for the given JCR operator type.
629 * @param string $operator One of the JCR_OPERATOR_* constants
630 * @return string an SQL operator
632 protected function resolveOperator($operator) {
634 case self
::OPERATOR_EQUAL_TO_NULL
:
637 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
638 $operator = 'IS NOT';
640 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
:
643 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
:
646 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
:
649 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN
:
652 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN_OR_EQUAL_TO
:
655 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN
:
658 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
661 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LIKE
:
665 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
672 * Replace query placeholders in a query part by the given
675 * @param string $sqlString The query part with placeholders
676 * @param array $parameters The parameters
677 * @return string The query part with replaced placeholders
679 protected function replacePlaceholders(&$sqlString, array $parameters) {
680 // TODO profile this method again
681 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);
683 foreach ($parameters as $parameter) {
684 $markPosition = strpos($sqlString, '?', $offset);
685 if ($markPosition !== FALSE) {
686 if ($parameter === NULL) {
688 } elseif (is_array($parameter) ||
($parameter instanceof ArrayAccess
) ||
($parameter instanceof Traversable
)) {
690 foreach ($parameter as $item) {
691 $items[] = $this->databaseHandle
->fullQuoteStr($item, 'foo');
693 $parameter = '(' . implode(',', $items) . ')';
695 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
697 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
699 $offset = $markPosition +
strlen($parameter);
704 * Adds additional WHERE statements according to the query settings.
706 * @param Tx_Extbase_Persistence_QuerySettingsInterface $querySettings The TYPO3 4.x specific query settings
707 * @param string $tableName The table name to add the additional where clause for
711 protected function addAdditionalWhereClause(Tx_Extbase_Persistence_QuerySettingsInterface
$querySettings, $tableName, &$sql) {
712 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettings
) {
713 if ($querySettings->getRespectEnableFields()) {
714 $this->addEnableFieldsStatement($tableName, $sql);
716 if ($querySettings->getRespectSysLanguage()) {
717 $this->addSysLanguageStatement($tableName, $sql);
719 if ($querySettings->getRespectStoragePage()) {
720 $this->addPageIdStatement($tableName, $sql);
726 * Builds the enable fields statement
728 * @param string $tableName The database table name
729 * @param array &$sql The query parts
732 protected function addEnableFieldsStatement($tableName, array &$sql) {
733 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
734 if (TYPO3_MODE
=== 'FE') {
735 $statement = $GLOBALS['TSFE']->sys_page
->enableFields($tableName);
736 } else { // TYPO3_MODE === 'BE'
737 $statement = t3lib_BEfunc
::deleteClause($tableName);
738 $statement .= t3lib_BEfunc
::BEenableFields($tableName);
740 if(!empty($statement)) {
741 $statement = substr($statement, 5);
742 $sql['additionalWhereClause'][] = $statement;
748 * Builds the language field statement
750 * @param string $tableName The database table name
751 * @param array &$sql The query parts
754 protected function addSysLanguageStatement($tableName, array &$sql) {
755 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
756 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
757 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
763 * Builds the page ID checking statement
765 * @param string $tableName The database table name
766 * @param array &$sql The query parts
769 protected function addPageIdStatement($tableName, array &$sql) {
770 if (empty($this->tableInformationCache
[$tableName]['columnNames'])) {
771 $this->tableInformationCache
[$tableName]['columnNames'] = $this->databaseHandle
->admin_get_fields($tableName);
773 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache
[$tableName]['columnNames'])) {
774 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
775 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div
::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
780 * Transforms orderings into SQL.
782 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
783 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
784 * @param array &$sql The query parts
787 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
788 foreach ($orderings as $propertyName => $order) {
789 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
790 $className = $source->getNodeTypeName();
791 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
792 while (strpos($propertyName, '.') !== FALSE) {
793 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
795 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
796 $tableName = $source->getLeft()->getSelectorName();
798 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
799 if (strlen($tableName) > 0) {
800 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
802 $sql['orderings'][] = $columnName . ' ' . $order;
808 * Transforms limit and offset into SQL
815 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
816 if ($limit !== NULL && $offset !== NULL) {
817 $sql['limit'] = $offset . ', ' . $limit;
818 } elseif ($limit !== NULL) {
819 $sql['limit'] = $limit;
824 * Transforms a Resource from a database query to an array of rows.
826 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
827 * @param resource $result The result
828 * @return array The result as an array of rows (tuples)
830 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $result) {
832 while ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
833 if (is_array($row)) {
834 // TODO Check if this is necessary, maybe the last line is enough
835 $arrayKeys = range(0, count($row));
836 array_fill_keys($arrayKeys, $row);
844 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
845 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
847 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
848 * @param array $row The row array (as reference)
849 * @param string $languageUid The language id
850 * @param string $workspaceUidUid The workspace id
853 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface
$source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
854 $overlayedRows = array();
855 foreach ($rows as $row) {
856 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
857 if (TYPO3_MODE
== 'FE') {
858 if (is_object($GLOBALS['TSFE'])) {
859 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
861 require_once(PATH_t3lib
. 'class.t3lib_page.php');
862 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
865 require_once(PATH_t3lib
. 'class.t3lib_page.php');
866 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
869 if (is_object($GLOBALS['TSFE'])) {
870 if ($languageUid === NULL) {
871 $languageUid = $GLOBALS['TSFE']->sys_language_uid
;
873 if ($workspaceUid !== NULL) {
874 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
877 if ($languageUid === NULL) {
878 $languageUid = intval(t3lib_div
::_GP('L'));
880 if ($workspaceUid === NULL) {
881 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
883 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
885 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
886 $tableName = $source->getSelectorName();
887 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
888 $tableName = $source->getLeft()->getSelectorName();
890 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
891 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
892 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
893 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid);
896 $overlayedRows[] = $row;
898 return $overlayedRows;
902 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
905 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
907 protected function checkSqlErrors() {
908 $error = $this->databaseHandle
->sql_error();
910 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
915 * Clear the TYPO3 page cache for the given record.
916 * If the record lies on a page, then we clear the cache of this page.
917 * If the record has no PID column, we clear the cache of the current page as best-effort.
919 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
921 * @param $tableName Table name of the record
922 * @param $uid UID of the record
925 protected function clearPageCache($tableName, $uid) {
926 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
927 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
929 // if disabled, return
933 $pageIdsToClear = array();
936 $columns = $this->databaseHandle
->admin_get_fields($tableName);
937 if (array_key_exists('pid', $columns)) {
938 $result = $this->databaseHandle
->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
939 if ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
940 $storagePage = $row['pid'];
941 $pageIdsToClear[] = $storagePage;
943 } elseif (isset($GLOBALS['TSFE'])) {
944 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
945 $storagePage = $GLOBALS['TSFE']->id
;
946 $pageIdsToClear[] = $storagePage;
949 if ($storagePage === NULL) {
952 if (!isset($this->pageTSConfigCache
[$storagePage])) {
953 $this->pageTSConfigCache
[$storagePage] = t3lib_BEfunc
::getPagesTSconfig($storagePage);
955 if (isset($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
956 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
957 $clearCacheCommands = array_unique($clearCacheCommands);
958 foreach ($clearCacheCommands as $clearCacheCommand) {
959 if (t3lib_div
::testInt($clearCacheCommand)) {
960 $pageIdsToClear[] = $clearCacheCommand;
965 // 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
966 Tx_Extbase_Utility_Cache
::clearPageCache($pageIdsToClear);