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