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