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