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