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_QOM_QueryObjectModelInterface $query
260 * @return array The SQL statement parts
262 public function parseQuery(Tx_Extbase_Persistence_Query
$query, array &$parameters) {
264 $sql['tables'] = 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($query, $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);
282 * Returns the statement, ready to be executed.
284 * @param array $sql The SQL statement parts
285 * @return string The SQL statement
287 public function buildQuery(array $sql) {
288 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
289 if (!empty($sql['where'])) {
290 $statement .= ' WHERE ' . implode('', $sql['where']);
291 if (!empty($sql['additionalWhereClause'])) {
292 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
294 } elseif (!empty($sql['additionalWhereClause'])) {
295 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
297 if (!empty($sql['orderings'])) {
298 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
300 if (!empty($sql['limit'])) {
301 $statement .= ' LIMIT ' . $sql['limit'];
307 * Checks if a Value Object equal to the given Object exists in the data base
309 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
310 * @return array The matching uid
312 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject
$object) {
314 $parameters = array();
315 $dataMap = $this->dataMapper
->getDataMap(get_class($object));
316 $properties = $object->_getProperties();
317 foreach ($properties as $propertyName => $propertyValue) {
318 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
319 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
320 if ($propertyValue === NULL) {
321 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
323 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
324 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
329 $sql['additionalWhereClause'] = array();
331 $tableName = $dataMap->getTableName();
332 $this->addEnableFieldsStatement($tableName, $sql);
334 $statement = 'SELECT * FROM ' . $tableName;
335 $statement .= ' WHERE ' . implode(' AND ', $fields);
336 if (!empty($sql['additionalWhereClause'])) {
337 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
339 $this->replacePlaceholders($statement, $parameters);
340 // debug($statement,-2);
341 $res = $this->databaseHandle
->sql_query($statement);
342 $this->checkSqlErrors();
343 $row = $this->databaseHandle
->sql_fetch_assoc($res);
344 if ($row !== FALSE) {
345 return (int)$row['uid'];
352 * Transforms a Query Source into SQL and parameter arrays
354 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
355 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
357 * @param array &$parameters
360 protected function parseSource(Tx_Extbase_Persistence_Query
$query, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
361 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
362 $tableName = $source->getSelectorName();
363 $sql['fields'][] = $tableName . '.*';
364 $sql['tables'][] = $tableName;
365 $querySettings = $query->getQuerySettings();
366 if ($querySettings instanceof Tx_Extbase_Persistence_QuerySettingsInterface
) {
367 if ($querySettings->getRespectEnableFields()) {
368 $this->addEnableFieldsStatement($tableName, $sql);
370 if ($querySettings->getRespectSysLanguage()) {
371 $this->addSysLanguageStatement($tableName, $sql);
373 if ($querySettings->getRespectStoragePage()) {
374 $this->addPageIdStatement($tableName, $sql);
377 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
378 $this->parseJoin($query, $source, $sql);
383 * Transforms a Join into SQL and parameter arrays
385 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
386 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
387 * @param array &$sql The query parts
390 protected function parseJoin(Tx_Extbase_Persistence_QueryInterface
$query, Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql) {
391 $leftSource = $join->getLeft();
392 $leftTableName = $leftSource->getSelectorName();
393 $rightSource = $join->getRight();
394 $rightTableName = $rightSource->getSelectorName();
396 $sql['fields'][] = $leftTableName . '.*';
397 $sql['fields'][] = $rightTableName . '.*';
399 // TODO Implement support for different join types and nested joins
400 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
402 $joinCondition = $join->getJoinCondition();
403 // TODO Check the parsing of the join
404 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
405 // TODO Discuss, if we should use $leftSource instead of $selector1Name
406 $column1Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
407 $column2Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
408 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
410 // TODO Implement childtableWhere
412 $querySettings = $query->getQuerySettings();
413 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface
) {
414 if ($querySettings->getRespectEnableFields()) {
415 $this->addEnableFieldsStatement($leftTableName, $sql);
416 $this->addEnableFieldsStatement($rightTableName, $sql);
418 if ($querySettings->getRespectSysLanguage()) {
419 $this->addSysLanguageStatement($leftTableName, $sql);
420 $this->addSysLanguageStatement($rightTableName, $sql);
422 if ($querySettings->getRespectStoragePage()) {
423 $this->addPageIdStatement($leftTableName, $sql);
424 $this->addPageIdStatement($rightTableName, $sql);
430 * Transforms a constraint into SQL and parameter arrays
432 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
433 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
434 * @param array &$sql The query parts
435 * @param array &$parameters The parameters that will replace the markers
436 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
439 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
440 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
441 $sql['where'][] = '(';
442 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
443 $sql['where'][] = ' AND ';
444 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
445 $sql['where'][] = ')';
446 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
447 $sql['where'][] = '(';
448 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
449 $sql['where'][] = ' OR ';
450 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
451 $sql['where'][] = ')';
452 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
453 $sql['where'][] = 'NOT (';
454 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
455 $sql['where'][] = ')';
456 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
457 $this->parseComparison($constraint, $source, $sql, $parameters);
462 * Parse a Comparison into SQL and parameter arrays.
464 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
465 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
466 * @param array &$sql SQL query parts to add to
467 * @param array &$parameters Parameters to bind to the SQL
468 * @param array $boundVariableValues The bound variables in the query and their values
471 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
472 $operand1 = $comparison->getOperand1();
473 $operator = $comparison->getOperator();
474 $operand2 = $comparison->getOperand2();
475 if (($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) && (is_array($operand2) ||
($operand2 instanceof ArrayAccess
) ||
($operand2 instanceof Traversable
))) {
476 // FIXME this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
477 $operator = Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
;
480 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
) {
483 foreach ($operand2 as $value) {
484 $value = $this->getPlainValue($value);
485 if ($value !== NULL) {
490 if ($hasValue === FALSE) {
491 $sql['where'][] = '1<>1';
493 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
495 foreach ($operand2 as $value) {
496 $items[] = $this->getPlainValue($value);
498 $parameters[] = $items;
500 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_CONTAINS
) {
501 if ($operand2 === NULL) {
502 $sql['where'][] = '1<>1';
504 $dataMap = $this->dataMapper
->getDataMap($source->getNodeTypeName());
505 $columnMap = $dataMap->getColumnMap($operand1->getPropertyName());
506 $typeOfRelation = $columnMap->getTypeOfRelation();
507 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
508 $relationTableName = $columnMap->getRelationTableName();
509 $sql['where'][] = 'uid IN (SELECT uid_local FROM ' . $relationTableName . ' WHERE uid_foreign=' . $this->getPlainValue($operand2) . ')';
510 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap
::RELATION_HAS_MANY
) {
511 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
512 if (isset($parentKeyFieldName)) {
513 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand1->getPropertyName(), $source->getNodeTypeName());
514 $childTableName = $columnMap->getChildTableName();
515 $sql['where'][] = 'uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
517 $tableName = $operand1->getSelectorName();
518 $statement = '(' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . ',%\'';
519 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . '\'';
520 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'' . $this->getPlainValue($operand2) . ',%\')';
521 $sql['where'][] = $statement;
524 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
528 if ($operand2 === NULL) {
529 if ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
) {
530 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
531 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
) {
532 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
535 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
536 $parameters[] = $this->getPlainValue($operand2);
541 * Returns a plain value, i.e. objects are flattened out if possible.
543 * @param mixed $input
546 protected function getPlainValue($input) {
547 if ($input instanceof DateTime
) {
548 return $input->format('U');
549 } elseif ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface
) {
550 return $input->getUid();
551 } elseif (is_bool($input)) {
552 return $input === TRUE ?
1 : 0;
559 * Parse a DynamicOperand into SQL and parameter arrays.
561 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
562 * @param string $operator One of the JCR_OPERATOR_* constants
563 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
564 * @param array &$sql The query parts
565 * @param array &$parameters The parameters that will replace the markers
566 * @param string $valueFunction an optional SQL function to apply to the operand value
569 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
570 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
571 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
572 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
573 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
574 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
575 $tableName = $operand->getSelectorName();
576 // FIXME Discuss the translation from propertyName to columnName
577 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
578 $className = $source->getNodeTypeName();
582 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
583 $operator = $this->resolveOperator($operator);
584 if ($valueFunction === NULL) {
585 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
587 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
590 $sql['where'][] = $constraintSQL;
595 * Returns the SQL operator for the given JCR operator type.
597 * @param string $operator One of the JCR_OPERATOR_* constants
598 * @return string an SQL operator
600 protected function resolveOperator($operator) {
602 case self
::OPERATOR_EQUAL_TO_NULL
:
605 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
606 $operator = 'IS NOT';
608 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_IN
:
611 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_EQUAL_TO
:
614 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_NOT_EQUAL_TO
:
617 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN
:
620 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LESS_THAN_OR_EQUAL_TO
:
623 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN
:
626 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
629 case Tx_Extbase_Persistence_QueryInterface
::OPERATOR_LIKE
:
633 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
640 * Replace query placeholders in a query part by the given
643 * @param string $sqlString The query part with placeholders
644 * @param array $parameters The parameters
645 * @return string The query part with replaced placeholders
647 protected function replacePlaceholders(&$sqlString, array $parameters) {
648 // TODO profile this method again
649 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);
651 foreach ($parameters as $parameter) {
652 $markPosition = strpos($sqlString, '?', $offset);
653 if ($markPosition !== FALSE) {
654 if ($parameter === NULL) {
656 } elseif (is_array($parameter) ||
($parameter instanceof ArrayAccess
) ||
($parameter instanceof Traversable
)) {
658 foreach ($parameter as $item) {
659 $items[] = $this->databaseHandle
->fullQuoteStr($item, 'foo');
661 $parameter = '(' . implode(',', $items) . ')';
663 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
665 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
667 $offset = $markPosition +
strlen($parameter);
672 * Builds the enable fields statement
674 * @param string $tableName The database table name
675 * @param array &$sql The query parts
678 protected function addEnableFieldsStatement($tableName, array &$sql) {
679 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
680 if (TYPO3_MODE
=== 'FE') {
681 $statement = $GLOBALS['TSFE']->sys_page
->enableFields($tableName);
682 } else { // TYPO3_MODE === 'BE'
683 $statement = t3lib_BEfunc
::deleteClause($tableName);
684 $statement .= t3lib_BEfunc
::BEenableFields($tableName);
686 if(!empty($statement)) {
687 $statement = substr($statement, 5);
688 $sql['additionalWhereClause'][] = $statement;
694 * Builds the language field statement
696 * @param string $tableName The database table name
697 * @param array &$sql The query parts
700 protected function addSysLanguageStatement($tableName, array &$sql) {
701 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
702 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
703 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
709 * Builds the page ID checking statement
711 * @param string $tableName The database table name
712 * @param array &$sql The query parts
715 protected function addPageIdStatement($tableName, array &$sql) {
716 if (empty($this->tableInformationCache
[$tableName]['columnNames'])) {
717 $this->tableInformationCache
[$tableName]['columnNames'] = $this->databaseHandle
->admin_get_fields($tableName);
719 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache
[$tableName]['columnNames'])) {
720 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
721 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div
::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
726 * Transforms orderings into SQL.
728 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
729 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
730 * @param array &$sql The query parts
733 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
734 foreach ($orderings as $ordering) {
735 $operand = $ordering->getOperand();
736 $order = $ordering->getOrder();
737 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue
) {
739 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
742 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
746 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
748 $tableName = $operand->getSelectorName();
750 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
751 $className = $source->getNodeTypeName();
753 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
754 if (strlen($tableName) > 0) {
755 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
757 $sql['orderings'][] = $columnName . ' ' . $order;
764 * Transforms limit and offset into SQL
771 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
772 if ($limit !== NULL && $offset !== NULL) {
773 $sql['limit'] = $offset . ', ' . $limit;
774 } elseif ($limit !== NULL) {
775 $sql['limit'] = $limit;
780 * Transforms a Resource from a database query to an array of rows.
782 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
783 * @param resource $result The result
784 * @return array The result as an array of rows (tuples)
786 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $result) {
788 while ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
789 if (is_array($row)) {
790 // TODO Check if this is necessary, maybe the last line is enough
791 $arrayKeys = range(0, count($row));
792 array_fill_keys($arrayKeys, $row);
800 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
801 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
803 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
804 * @param array $row The row array (as reference)
805 * @param string $languageUid The language id
806 * @param string $workspaceUidUid The workspace id
809 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface
$source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
810 $overlayedRows = array();
811 foreach ($rows as $row) {
812 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
813 if (TYPO3_MODE
== 'FE') {
814 if (is_object($GLOBALS['TSFE'])) {
815 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
817 require_once(PATH_t3lib
. 'class.t3lib_page.php');
818 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
821 require_once(PATH_t3lib
. 'class.t3lib_page.php');
822 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
825 if (is_object($GLOBALS['TSFE'])) {
826 if ($languageUid === NULL) {
827 $languageUid = $GLOBALS['TSFE']->sys_language_uid
;
829 if ($workspaceUid !== NULL) {
830 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
833 if ($languageUid === NULL) {
834 $languageUid = intval(t3lib_div
::_GP('L'));
836 if ($workspaceUid === NULL) {
837 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
839 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
841 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
842 $tableName = $source->getSelectorName();
843 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
844 $tableName = $source->getLeft()->getSelectorName();
846 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
847 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
848 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
849 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid);
852 $overlayedRows[] = $row;
854 return $overlayedRows;
858 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
861 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
863 protected function checkSqlErrors() {
864 $error = $this->databaseHandle
->sql_error();
866 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
871 * Clear the TYPO3 page cache for the given record.
872 * If the record lies on a page, then we clear the cache of this page.
873 * If the record has no PID column, we clear the cache of the current page as best-effort.
875 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
877 * @param $tableName Table name of the record
878 * @param $uid UID of the record
881 protected function clearPageCache($tableName, $uid) {
882 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
883 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
885 // if disabled, return
889 $pageIdsToClear = array();
892 $columns = $this->databaseHandle
->admin_get_fields($tableName);
893 if (array_key_exists('pid', $columns)) {
894 $result = $this->databaseHandle
->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
895 if ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
896 $storagePage = $row['pid'];
897 $pageIdsToClear[] = $storagePage;
899 } elseif (isset($GLOBALS['TSFE'])) {
900 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
901 $storagePage = $GLOBALS['TSFE']->id
;
902 $pageIdsToClear[] = $storagePage;
905 if ($storagePage === NULL) {
908 if (!isset($this->pageTSConfigCache
[$storagePage])) {
909 $this->pageTSConfigCache
[$storagePage] = t3lib_BEfunc
::getPagesTSconfig($storagePage);
911 if (isset($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
912 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
913 $clearCacheCommands = array_unique($clearCacheCommands);
914 foreach ($clearCacheCommands as $clearCacheCommand) {
915 if (t3lib_div
::testInt($clearCacheCommand)) {
916 $pageIdsToClear[] = $clearCacheCommand;
921 // 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
922 Tx_Extbase_Utility_Cache
::clearPageCache($pageIdsToClear);