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