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