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