[+BUGFIX] Extbase (Persistence): Fixed using the correct columnname for contains...
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Storage / Typo3DbBackend.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 team.
10 *
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.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 *
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.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * A Storage backend
30 *
31 * @package Extbase
32 * @subpackage Persistence\Storage
33 * @version $Id$
34 */
35 class Tx_Extbase_Persistence_Storage_Typo3DbBackend implements Tx_Extbase_Persistence_Storage_BackendInterface, t3lib_Singleton {
36
37 const OPERATOR_EQUAL_TO_NULL = 'operatorEqualToNull';
38 const OPERATOR_NOT_EQUAL_TO_NULL = 'operatorNotEqualToNull';
39
40 /**
41 * The TYPO3 database object
42 *
43 * @var t3lib_db
44 */
45 protected $databaseHandle;
46
47 /**
48 * @var Tx_Extbase_Persistence_DataMapper
49 */
50 protected $dataMapper;
51
52 /**
53 * The TYPO3 page select object. Used for language and workspace overlay
54 *
55 * @var t3lib_pageSelect
56 */
57 protected $pageSelectObject;
58
59 /**
60 * A first-level TypoScript configuration cache
61 *
62 * @var array
63 */
64 protected $pageTSConfigCache = array();
65
66 /**
67 * Caches information about tables (esp. the existing column names)
68 *
69 * @var array
70 */
71 protected $tableInformationCache = array();
72
73 /**
74 * @var Tx_Extbase_Configuration_ConfigurationManagerInterface
75 */
76 protected $configurationManager;
77
78 /**
79 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
80 */
81 public function __construct() {
82 $this->databaseHandle = $GLOBALS['TYPO3_DB'];
83 }
84
85 /**
86 * @param Tx_Extbase_Configuration_ConfigurationManagerInterface $configurationManager
87 * @return void
88 */
89 public function injectConfigurationManager(Tx_Extbase_Configuration_ConfigurationManagerInterface $configurationManager) {
90 $this->configurationManager = $configurationManager;
91 }
92
93 /**
94 * Injects the DataMapper to map nodes to objects
95 *
96 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
97 * @return void
98 */
99 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
100 $this->dataMapper = $dataMapper;
101 }
102
103 /**
104 * Adds a row to the storage
105 *
106 * @param string $tableName The database table name
107 * @param array $row The row to be inserted
108 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
109 * @return int The uid of the inserted row
110 */
111 public function addRow($tableName, array $row, $isRelation = FALSE) {
112 $fields = array();
113 $values = array();
114 $parameters = array();
115 if (isset($row['uid'])) {
116 unset($row['uid']);
117 }
118 foreach ($row as $columnName => $value) {
119 $fields[] = $columnName;
120 $values[] = '?';
121 $parameters[] = $value;
122 }
123
124 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
125 $this->replacePlaceholders($sqlString, $parameters);
126 // debug($sqlString,-2);
127 $this->databaseHandle->sql_query($sqlString);
128 $this->checkSqlErrors($sqlString);
129 $uid = $this->databaseHandle->sql_insert_id();
130 if (!$isRelation) {
131 $this->clearPageCache($tableName, $uid);
132 }
133 return (int)$uid;
134 }
135
136 /**
137 * Updates a row in the storage
138 *
139 * @param string $tableName The database table name
140 * @param array $row The row to be updated
141 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
142 * @return void
143 */
144 public function updateRow($tableName, array $row, $isRelation = FALSE) {
145 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
146 $uid = (int)$row['uid'];
147 unset($row['uid']);
148 $fields = array();
149 $parameters = array();
150 foreach ($row as $columnName => $value) {
151 $fields[] = $columnName . '=?';
152 $parameters[] = $value;
153 }
154 $parameters[] = $uid;
155
156 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
157 $this->replacePlaceholders($sqlString, $parameters);
158 // debug($sqlString,-2);
159 $returnValue = $this->databaseHandle->sql_query($sqlString);
160 $this->checkSqlErrors($sqlString);
161 if (!$isRelation) {
162 $this->clearPageCache($tableName, $uid);
163 }
164 return $returnValue;
165 }
166
167 /**
168 * Deletes a row in the storage
169 *
170 * @param string $tableName The database table name
171 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
172 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
173 * @return void
174 */
175 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
176 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
177 $this->replacePlaceholders($statement, $identifier);
178 if (!$isRelation && isset($identifier['uid'])) {
179 $this->clearPageCache($tableName, $identifier['uid'], $isRelation);
180 }
181 // debug($statement, -2);
182 $returnValue = $this->databaseHandle->sql_query($statement);
183 $this->checkSqlErrors($statement);
184 return $returnValue;
185 }
186
187 /**
188 * Fetches row data from the database
189 *
190 * @param string $identifier The Identifier of the row to fetch
191 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
192 * @return array|FALSE
193 */
194 public function getRowByIdentifier($tableName, array $identifier) {
195 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
196 $this->replacePlaceholders($statement, $identifier);
197 // debug($statement,-2);
198 $res = $this->databaseHandle->sql_query($statement);
199 $this->checkSqlErrors($statement);
200 $row = $this->databaseHandle->sql_fetch_assoc($res);
201 if ($row !== FALSE) {
202 return $row;
203 } else {
204 return FALSE;
205 }
206 }
207
208 protected function parseIdentifier(array $identifier) {
209 $fieldNames = array_keys($identifier);
210 $suffixedFieldNames = array();
211 foreach ($fieldNames as $fieldName) {
212 $suffixedFieldNames[] = $fieldName . '=?';
213 }
214 return implode(' AND ', $suffixedFieldNames);
215 }
216
217 /**
218 * Returns the object data matching the $query.
219 *
220 * @param Tx_Extbase_Persistence_QueryInterface $query
221 * @return array
222 * @author Karsten Dambekalns <karsten@typo3.org>
223 */
224 public function getObjectDataByQuery(Tx_Extbase_Persistence_QueryInterface $query) {
225 $parameters = array();
226
227 $statement = $query->getStatement();
228 if($statement instanceof Tx_Extbase_Persistence_QOM_Statement) {
229 $sql = $statement->getStatement();
230 $parameters = $statement->getBoundVariables();
231 } else {
232 $parameters = array();
233 $statementParts = $this->parseQuery($query, $parameters);
234 $sql = $this->buildQuery($statementParts, $parameters);
235 }
236 $this->replacePlaceholders($sql, $parameters);
237 // debug($sql,-2);
238 $result = $this->databaseHandle->sql_query($sql);
239 $this->checkSqlErrors($sql);
240 $rows = $this->getRowsFromResult($query->getSource(), $result);
241 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows);
242 // TODO: implement $objectData = $this->processObjectRecords($statementHandle);
243 return $rows;
244 }
245
246 /**
247 * Returns the number of tuples matching the query.
248 *
249 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
250 * @return integer The number of matching tuples
251 */
252 public function getObjectCountByQuery(Tx_Extbase_Persistence_QueryInterface $query) {
253 $constraint = $query->getConstraint();
254 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) {
255 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);
256 }
257 $parameters = array();
258 $statementParts = $this->parseQuery($query, $parameters);
259 // if limit is set, we need to count the rows "manually" as COUNT(*) ignores LIMIT constraints
260 if (!empty($statementParts['limit'])) {
261 $statement = $this->buildQuery($statementParts, $parameters);
262 $this->replacePlaceholders($statement, $parameters);
263 $result = $this->databaseHandle->sql_query($statement);
264 $this->checkSqlErrors($statement);
265 return $this->databaseHandle->sql_num_rows($result);
266 } else {
267 $statementParts['fields'] = array('COUNT(*)');
268 $statement = $this->buildQuery($statementParts, $parameters);
269 $this->replacePlaceholders($statement, $parameters);
270 $result = $this->databaseHandle->sql_query($statement);
271 $this->checkSqlErrors($statement);
272 $rows = $this->getRowsFromResult($query->getSource(), $result);
273 return current(current($rows));
274 }
275 }
276
277 /**
278 * Parses the query and returns the SQL statement parts.
279 *
280 * @param Tx_Extbase_Persistence_QueryInterface $query The query
281 * @return array The SQL statement parts
282 */
283 public function parseQuery(Tx_Extbase_Persistence_QueryInterface $query, array &$parameters) {
284 $sql = array();
285 $sql['keywords'] = array();
286 $sql['tables'] = array();
287 $sql['unions'] = array();
288 $sql['fields'] = array();
289 $sql['where'] = array();
290 $sql['additionalWhereClause'] = array();
291 $sql['orderings'] = array();
292 $sql['limit'] = array();
293
294 $source = $query->getSource();
295
296 $this->parseSource($source, $sql, $parameters);
297 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters);
298 $this->parseOrderings($query->getOrderings(), $source, $sql);
299 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
300
301 $tableNames = array_unique(array_keys($sql['tables'] + $sql['unions']));
302 foreach ($tableNames as $tableName) {
303 if (is_string($tableName) && strlen($tableName) > 0) {
304 $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql);
305 }
306 }
307
308 return $sql;
309 }
310
311 /**
312 * Returns the statement, ready to be executed.
313 *
314 * @param array $sql The SQL statement parts
315 * @return string The SQL statement
316 */
317 public function buildQuery(array $sql) {
318 $statement = 'SELECT ' . implode(' ', $sql['keywords']) . ' '. implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']) . ' '. implode(' ', $sql['unions']);
319 if (!empty($sql['where'])) {
320 $statement .= ' WHERE ' . implode('', $sql['where']);
321 if (!empty($sql['additionalWhereClause'])) {
322 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
323 }
324 } elseif (!empty($sql['additionalWhereClause'])) {
325 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
326 }
327 if (!empty($sql['orderings'])) {
328 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
329 }
330 if (!empty($sql['limit'])) {
331 $statement .= ' LIMIT ' . $sql['limit'];
332 }
333 return $statement;
334 }
335
336 /**
337 * Checks if a Value Object equal to the given Object exists in the data base
338 *
339 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
340 * @return array The matching uid
341 */
342 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject $object) {
343 $fields = array();
344 $parameters = array();
345 $dataMap = $this->dataMapper->getDataMap(get_class($object));
346 $properties = $object->_getProperties();
347 foreach ($properties as $propertyName => $propertyValue) {
348 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
349 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
350 if ($propertyValue === NULL) {
351 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
352 } else {
353 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
354 $parameters[] = $this->getPlainValue($propertyValue);
355 }
356 }
357 }
358 $sql = array();
359 $sql['additionalWhereClause'] = array();
360
361 $tableName = $dataMap->getTableName();
362 $this->addEnableFieldsStatement($tableName, $sql);
363
364 $statement = 'SELECT * FROM ' . $tableName;
365 $statement .= ' WHERE ' . implode(' AND ', $fields);
366 if (!empty($sql['additionalWhereClause'])) {
367 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
368 }
369 $this->replacePlaceholders($statement, $parameters);
370 // debug($statement,-2);
371 $res = $this->databaseHandle->sql_query($statement);
372 $this->checkSqlErrors($statement);
373 $row = $this->databaseHandle->sql_fetch_assoc($res);
374 if ($row !== FALSE) {
375 return (int)$row['uid'];
376 } else {
377 return FALSE;
378 }
379 }
380
381 /**
382 * Transforms a Query Source into SQL and parameter arrays
383 *
384 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
385 * @param array &$sql
386 * @param array &$parameters
387 * @return void
388 */
389 protected function parseSource(Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
390 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
391 $className = $source->getNodeTypeName();
392 $tableName = $this->dataMapper->getDataMap($className)->getTableName();
393 $this->addRecordTypeConstraint($className, $sql);
394 $sql['fields'][$tableName] = $tableName . '.*';
395 $sql['tables'][$tableName] = $tableName;
396 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
397 $this->parseJoin($source, $sql);
398 }
399 }
400
401 /**
402 * Adda a constrint to ensure that the record type of the returned tuples is matching the data type of the repository.
403 *
404 * @param string $className The class name
405 * @param array &$sql The query parts
406 * @return void
407 */
408 protected function addRecordTypeConstraint($className, &$sql) {
409 if ($className !== NULL) {
410 $dataMap = $this->dataMapper->getDataMap($className);
411 if ($dataMap->getRecordTypeColumnName() !== NULL) {
412 $recordTypes = array();
413 if ($dataMap->getRecordType() !== NULL) {
414 $recordTypes[] = $dataMap->getRecordType();
415 }
416 foreach ($dataMap->getSubclasses() as $subclassName) {
417 $subclassDataMap = $this->dataMapper->getDataMap($subclassName);
418 if ($subclassDataMap->getRecordType() !== NULL) {
419 $recordTypes[] = $subclassDataMap->getRecordType();
420 }
421 }
422 if (count($recordTypes) > 0) {
423 $recordTypeStatements = array();
424 foreach ($recordTypes as $recordType) {
425 $recordTypeStatements[] = $dataMap->getTableName() . '.' . $dataMap->getRecordTypeColumnName() . '=' . $this->databaseHandle->fullQuoteStr($recordType, 'foo');
426 }
427 $sql['additionalWhereClause'][] = '(' . implode(' OR ', $recordTypeStatements) . ')';
428 }
429 }
430 }
431 }
432
433 /**
434 * Transforms a Join into SQL and parameter arrays
435 *
436 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
437 * @param array &$sql The query parts
438 * @return void
439 */
440 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql) {
441 $leftSource = $join->getLeft();
442 $leftClassName = $leftSource->getNodeTypeName();
443 $this->addRecordTypeConstraint($leftClassName, $sql);
444 $leftTableName = $leftSource->getSelectorName();
445 // $sql['fields'][$leftTableName] = $leftTableName . '.*';
446 $rightSource = $join->getRight();
447 if ($rightSource instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
448 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
449 $rightTableName = $rightSource->getLeft()->getSelectorName();
450 } else {
451 $rightClassName = $rightSource->getNodeTypeName();
452 $rightTableName = $rightSource->getSelectorName();
453 $sql['fields'][$leftTableName] = $rightTableName . '.*';
454 }
455 $this->addRecordTypeConstraint($rightClassName, $sql);
456
457 $sql['tables'][$leftTableName] = $leftTableName;
458 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
459
460 $joinCondition = $join->getJoinCondition();
461 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
462 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
463 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
464 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
465 }
466 if ($rightSource instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
467 $this->parseJoin($rightSource, $sql);
468 }
469 }
470
471 /**
472 * Transforms a constraint into SQL and parameter arrays
473 *
474 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
475 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
476 * @param array &$sql The query parts
477 * @param array &$parameters The parameters that will replace the markers
478 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
479 * @return void
480 */
481 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
482 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
483 $sql['where'][] = '(';
484 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
485 $sql['where'][] = ' AND ';
486 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
487 $sql['where'][] = ')';
488 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
489 $sql['where'][] = '(';
490 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
491 $sql['where'][] = ' OR ';
492 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
493 $sql['where'][] = ')';
494 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
495 $sql['where'][] = 'NOT (';
496 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
497 $sql['where'][] = ')';
498 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
499 $this->parseComparison($constraint, $source, $sql, $parameters);
500 }
501 }
502
503 /**
504 * Parse a Comparison into SQL and parameter arrays.
505 *
506 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
507 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
508 * @param array &$sql SQL query parts to add to
509 * @param array &$parameters Parameters to bind to the SQL
510 * @param array $boundVariableValues The bound variables in the query and their values
511 * @return void
512 */
513 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
514 $operand1 = $comparison->getOperand1();
515 $operator = $comparison->getOperator();
516 $operand2 = $comparison->getOperand2();
517 if (($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO) && (is_array($operand2) || ($operand2 instanceof ArrayAccess) || ($operand2 instanceof Traversable))) {
518 // this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
519 $operator = Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN;
520 }
521
522 if ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN) {
523 $items = array();
524 $hasValue = FALSE;
525 foreach ($operand2 as $value) {
526 $value = $this->getPlainValue($value);
527 if ($value !== NULL) {
528 $items[] = $value;
529 $hasValue = TRUE;
530 }
531 }
532 if ($hasValue === FALSE) {
533 $sql['where'][] = '1<>1';
534 } else {
535 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
536 $parameters[] = $items;
537 }
538 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_CONTAINS) {
539 if ($operand2 === NULL) {
540 $sql['where'][] = '1<>1';
541 } else {
542 $className = $source->getNodeTypeName();
543 $tableName = $this->dataMapper->convertClassNameToTableName($className);
544 $propertyName = $operand1->getPropertyName();
545 while (strpos($propertyName, '.') !== FALSE) {
546 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
547 }
548 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
549 $dataMap = $this->dataMapper->getDataMap($className);
550 $columnMap = $dataMap->getColumnMap($propertyName);
551 $typeOfRelation = $columnMap->getTypeOfRelation();
552 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
553 $relationTableName = $columnMap->getRelationTableName();
554 $sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=' . $this->getPlainValue($operand2) . ')';
555 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
556 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
557 if (isset($parentKeyFieldName)) {
558 $childTableName = $columnMap->getChildTableName();
559 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
560 } else {
561 $statement = 'FIND_IN_SET(' . $this->getPlainValue($operand2) . ',' . $tableName . '.' . $columnName . ')';
562 $sql['where'][] = $statement;
563 }
564 } else {
565 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
566 }
567 }
568 } else {
569 if ($operand2 === NULL) {
570 if ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO) {
571 $operator = self::OPERATOR_EQUAL_TO_NULL;
572 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_NOT_EQUAL_TO) {
573 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
574 }
575 }
576 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
577 $parameters[] = $this->getPlainValue($operand2);
578 }
579 }
580
581 /**
582 * Returns a plain value, i.e. objects are flattened out if possible.
583 *
584 * @param mixed $input
585 * @return mixed
586 */
587 protected function getPlainValue($input) {
588 if (is_array($input)) {
589 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
590 }
591 if ($input instanceof DateTime) {
592 return $input->format('U');
593 } elseif (is_object($input)) {
594 if ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface) {
595 return $input->getUid();
596 } else {
597 throw new Tx_Extbase_Persistence_Exception_UnexpectedTypeException('An object of class "' . get_class($input) . '" could not be converted to a plain value.', 1274799934);
598 }
599 } elseif (is_bool($input)) {
600 return $input === TRUE ? 1 : 0;
601 } else {
602 return $input;
603 }
604 }
605
606 /**
607 * Parse a DynamicOperand into SQL and parameter arrays.
608 *
609 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
610 * @param string $operator One of the JCR_OPERATOR_* constants
611 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
612 * @param array &$sql The query parts
613 * @param array &$parameters The parameters that will replace the markers
614 * @param string $valueFunction an optional SQL function to apply to the operand value
615 * @return void
616 */
617 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
618 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
619 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
620 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
621 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
622 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
623 $propertyName = $operand->getPropertyName();
624 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) { // FIXME Only necessary to differ from Join
625 $className = $source->getNodeTypeName();
626 $tableName = $this->dataMapper->convertClassNameToTableName($className);
627 while (strpos($propertyName, '.') !== FALSE) {
628 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
629 }
630 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
631 $tableName = $source->getJoinCondition()->getSelector1Name();
632 }
633 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
634 $operator = $this->resolveOperator($operator);
635 if ($valueFunction === NULL) {
636 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
637 } else {
638 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ') ' . $operator . ' ?';
639 }
640
641 $sql['where'][] = $constraintSQL;
642 }
643 }
644
645 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
646 $explodedPropertyPath = explode('.', $propertyPath, 2);
647 $propertyName = $explodedPropertyPath[0];
648 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
649 $tableName = $this->dataMapper->convertClassNameToTableName($className);
650 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
651 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
652 $childTableName = $columnMap->getChildTableName();
653 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
654 if (isset($parentKeyFieldName)) {
655 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
656 } else {
657 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
658 }
659 $className = $this->dataMapper->getType($className, $propertyName);
660 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
661 if (isset($parentKeyFieldName)) {
662 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
663 } else {
664 $onStatement = '(' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid,\',%\')';
665 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid)';
666 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(' . $childTableName . '.uid,\',%\'))';
667 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $onStatement;
668 }
669 $className = $this->dataMapper->getType($className, $propertyName);
670 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
671 $relationTableName = $columnMap->getRelationTableName();
672 $sql['unions'][$relationTableName] = 'LEFT JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.uid_local';
673 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $relationTableName . '.uid_foreign=' . $childTableName . '.uid';
674 $className = $this->dataMapper->getType($className, $propertyName);
675 } else {
676 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
677 }
678 // TODO check if there is another solution for this
679 $sql['keywords']['distinct'] = 'DISTINCT';
680 $propertyPath = $explodedPropertyPath[1];
681 $tableName = $childTableName;
682 }
683
684 /**
685 * Returns the SQL operator for the given JCR operator type.
686 *
687 * @param string $operator One of the JCR_OPERATOR_* constants
688 * @return string an SQL operator
689 */
690 protected function resolveOperator($operator) {
691 switch ($operator) {
692 case self::OPERATOR_EQUAL_TO_NULL:
693 $operator = 'IS';
694 break;
695 case self::OPERATOR_NOT_EQUAL_TO_NULL:
696 $operator = 'IS NOT';
697 break;
698 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN:
699 $operator = 'IN';
700 break;
701 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO:
702 $operator = '=';
703 break;
704 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_NOT_EQUAL_TO:
705 $operator = '!=';
706 break;
707 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LESS_THAN:
708 $operator = '<';
709 break;
710 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
711 $operator = '<=';
712 break;
713 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_GREATER_THAN:
714 $operator = '>';
715 break;
716 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
717 $operator = '>=';
718 break;
719 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LIKE:
720 $operator = 'LIKE';
721 break;
722 default:
723 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
724 }
725
726 return $operator;
727 }
728
729 /**
730 * Replace query placeholders in a query part by the given
731 * parameters.
732 *
733 * @param string $sqlString The query part with placeholders
734 * @param array $parameters The parameters
735 * @return string The query part with replaced placeholders
736 */
737 protected function replacePlaceholders(&$sqlString, array $parameters) {
738 // TODO profile this method again
739 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);
740 $offset = 0;
741 foreach ($parameters as $parameter) {
742 $markPosition = strpos($sqlString, '?', $offset);
743 if ($markPosition !== FALSE) {
744 if ($parameter === NULL) {
745 $parameter = 'NULL';
746 } elseif (is_array($parameter) || ($parameter instanceof ArrayAccess) || ($parameter instanceof Traversable)) {
747 $items = array();
748 foreach ($parameter as $item) {
749 $items[] = $this->databaseHandle->fullQuoteStr($item, 'foo');
750 }
751 $parameter = '(' . implode(',', $items) . ')';
752 } else {
753 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
754 }
755 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
756 }
757 $offset = $markPosition + strlen($parameter);
758 }
759 }
760
761 /**
762 * Adds additional WHERE statements according to the query settings.
763 *
764 * @param Tx_Extbase_Persistence_QuerySettingsInterface $querySettings The TYPO3 4.x specific query settings
765 * @param string $tableName The table name to add the additional where clause for
766 * @param string $sql
767 * @return void
768 */
769 protected function addAdditionalWhereClause(Tx_Extbase_Persistence_QuerySettingsInterface $querySettings, $tableName, &$sql) {
770 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettings) {
771 if ($querySettings->getRespectEnableFields()) {
772 $this->addEnableFieldsStatement($tableName, $sql);
773 }
774 if ($querySettings->getRespectSysLanguage()) {
775 $this->addSysLanguageStatement($tableName, $sql);
776 }
777 if ($querySettings->getRespectStoragePage()) {
778 $this->addPageIdStatement($tableName, $sql, $querySettings->getStoragePageIds());
779 }
780 }
781 }
782
783 /**
784 * Builds the enable fields statement
785 *
786 * @param string $tableName The database table name
787 * @param array &$sql The query parts
788 * @return void
789 */
790 protected function addEnableFieldsStatement($tableName, array &$sql) {
791 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
792 if (TYPO3_MODE === 'FE') {
793 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
794 } else { // TYPO3_MODE === 'BE'
795 $statement = t3lib_BEfunc::deleteClause($tableName);
796 $statement .= t3lib_BEfunc::BEenableFields($tableName);
797 }
798 if(!empty($statement)) {
799 $statement = substr($statement, 5);
800 $sql['additionalWhereClause'][] = $statement;
801 }
802 }
803 }
804
805 /**
806 * Builds the language field statement
807 *
808 * @param string $tableName The database table name
809 * @param array &$sql The query parts
810 * @return void
811 */
812 protected function addSysLanguageStatement($tableName, array &$sql) {
813 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
814 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
815 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
816 }
817 }
818 }
819
820 /**
821 * Builds the page ID checking statement
822 *
823 * @param string $tableName The database table name
824 * @param array &$sql The query parts
825 * @param array $storagePageIds list of storage page ids
826 * @return void
827 */
828 protected function addPageIdStatement($tableName, array &$sql, array $storagePageIds) {
829 if (empty($this->tableInformationCache[$tableName]['columnNames'])) {
830 $this->tableInformationCache[$tableName]['columnNames'] = $this->databaseHandle->admin_get_fields($tableName);
831 }
832 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache[$tableName]['columnNames'])) {
833 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', $storagePageIds) . ')';
834 }
835 }
836
837 /**
838 * Transforms orderings into SQL.
839 *
840 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
841 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
842 * @param array &$sql The query parts
843 * @return void
844 */
845 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
846 foreach ($orderings as $propertyName => $order) {
847 switch ($order) {
848 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING: // Deprecated since Extbase 1.1
849 case Tx_Extbase_Persistence_QueryInterface::ORDER_ASCENDING:
850 $order = 'ASC';
851 break;
852 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING: // Deprecated since Extbase 1.1
853 case Tx_Extbase_Persistence_QueryInterface::ORDER_DESCENDING:
854 $order = 'DESC';
855 break;
856 default:
857 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
858 }
859 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
860 $className = $source->getNodeTypeName();
861 $tableName = $this->dataMapper->convertClassNameToTableName($className);
862 while (strpos($propertyName, '.') !== FALSE) {
863 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
864 }
865 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
866 $tableName = $source->getLeft()->getSelectorName();
867 }
868 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
869 if (strlen($tableName) > 0) {
870 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
871 } else {
872 $sql['orderings'][] = $columnName . ' ' . $order;
873 }
874 }
875 }
876
877 /**
878 * Transforms limit and offset into SQL
879 *
880 * @param int $limit
881 * @param int $offset
882 * @param array &$sql
883 * @return void
884 */
885 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
886 if ($limit !== NULL && $offset !== NULL) {
887 $sql['limit'] = $offset . ', ' . $limit;
888 } elseif ($limit !== NULL) {
889 $sql['limit'] = $limit;
890 }
891 }
892
893 /**
894 * Transforms a Resource from a database query to an array of rows.
895 *
896 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
897 * @param resource $result The result
898 * @return array The result as an array of rows (tuples)
899 */
900 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $result) {
901 $rows = array();
902 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
903 if (is_array($row)) {
904 // TODO Check if this is necessary, maybe the last line is enough
905 $arrayKeys = range(0, count($row));
906 array_fill_keys($arrayKeys, $row);
907 $rows[] = $row;
908 }
909 }
910 return $rows;
911 }
912
913 /**
914 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
915 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
916 *
917 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
918 * @param array $row The row array (as reference)
919 * @param string $languageUid The language id
920 * @param string $workspaceUidUid The workspace id
921 * @return void
922 */
923 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface $source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
924 $overlayedRows = array();
925 foreach ($rows as $row) {
926 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
927 if (TYPO3_MODE == 'FE') {
928 if (is_object($GLOBALS['TSFE'])) {
929 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
930 } else {
931 require_once(PATH_t3lib . 'class.t3lib_page.php');
932 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
933 }
934 } else {
935 require_once(PATH_t3lib . 'class.t3lib_page.php');
936 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
937 }
938 }
939 if (is_object($GLOBALS['TSFE'])) {
940 if ($languageUid === NULL) {
941 $languageUid = $GLOBALS['TSFE']->sys_language_uid;
942 $languageMode = $GLOBALS['TSFE']->sys_language_mode;
943 }
944 if ($workspaceUid !== NULL) {
945 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
946 }
947 } else {
948 if ($languageUid === NULL) {
949 $languageUid = intval(t3lib_div::_GP('L'));
950 }
951 if ($workspaceUid === NULL) {
952 $workspaceUid = $GLOBALS['BE_USER']->workspace;
953 }
954 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
955 }
956 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
957 $tableName = $source->getSelectorName();
958 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
959 $tableName = $source->getRight()->getSelectorName();
960 }
961 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
962 if($tableName == 'pages') {
963 $row = $this->pageSelectObject->getPageOverlay($row, $languageUid);
964 } elseif(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
965 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
966 $overlayMode = ($languageMode === 'strict') ? 'hideNonTranslated' : '';
967 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, $overlayMode);
968 }
969 }
970 if ($row !== NULL && is_array($row)) {
971 $overlayedRows[] = $row;
972 }
973 }
974 return $overlayedRows;
975 }
976
977 /**
978 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
979 *
980 * @return void
981 * @param string $sql The SQL statement
982 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
983 */
984 protected function checkSqlErrors($sql='') {
985 $error = $this->databaseHandle->sql_error();
986 if ($error !== '') {
987 $error .= $sql ? ': ' . $sql : '';
988 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
989 }
990 }
991
992 /**
993 * Clear the TYPO3 page cache for the given record.
994 * If the record lies on a page, then we clear the cache of this page.
995 * If the record has no PID column, we clear the cache of the current page as best-effort.
996 *
997 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
998 *
999 * @param $tableName Table name of the record
1000 * @param $uid UID of the record
1001 * @return void
1002 */
1003 protected function clearPageCache($tableName, $uid) {
1004 $frameworkConfiguration = $this->configurationManager->getConfiguration(Tx_Extbase_Configuration_ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
1005 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
1006 } else {
1007 // if disabled, return
1008 return;
1009 }
1010
1011 $pageIdsToClear = array();
1012 $storagePage = NULL;
1013
1014 $columns = $this->databaseHandle->admin_get_fields($tableName);
1015 if (array_key_exists('pid', $columns)) {
1016 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
1017 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
1018 $storagePage = $row['pid'];
1019 $pageIdsToClear[] = $storagePage;
1020 }
1021 } elseif (isset($GLOBALS['TSFE'])) {
1022 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
1023 $storagePage = $GLOBALS['TSFE']->id;
1024 $pageIdsToClear[] = $storagePage;
1025 }
1026
1027 if ($storagePage === NULL) {
1028 return;
1029 }
1030 if (!isset($this->pageTSConfigCache[$storagePage])) {
1031 $this->pageTSConfigCache[$storagePage] = t3lib_BEfunc::getPagesTSconfig($storagePage);
1032 }
1033 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
1034 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
1035 $clearCacheCommands = array_unique($clearCacheCommands);
1036 foreach ($clearCacheCommands as $clearCacheCommand) {
1037 if (t3lib_div::testInt($clearCacheCommand)) {
1038 $pageIdsToClear[] = $clearCacheCommand;
1039 }
1040 }
1041 }
1042
1043 // 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
1044 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
1045 }
1046 }
1047
1048 ?>