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