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