[+FEATURE] Extbase (Persistence): Implemented (still experimental) feature to be...
[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
231 // $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($sql,-2);
250 $result = $this->databaseHandle->sql_query($statement);
251 $this->checkSqlErrors();
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
260 * @return array The SQL statement parts
261 */
262 public function parseQuery(Tx_Extbase_Persistence_QueryInterface $query, array &$parameters) {
263 $sql = 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 DISTINCT ' . 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 . '.*';
371 $sql['tables'][] = $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 $leftTableName = $leftSource->getSelectorName();
387 $rightSource = $join->getRight();
388 $rightTableName = $rightSource->getSelectorName();
389
390 $sql['fields'][] = $leftTableName . '.*';
391 $sql['fields'][] = $rightTableName . '.*';
392
393 // TODO Implement support for different join types and nested joins
394 $sql['tables'][$leftTableName] = $leftTableName;
395 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
396
397 $joinCondition = $join->getJoinCondition();
398 // TODO Check the parsing of the join
399 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
400 // TODO Discuss, if we should use $leftSource instead of $selector1Name
401 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
402 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
403 $sql['unions'][$joinCondition->getSelector2Name()] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
404 }
405 // TODO Implement childtableWhere
406 }
407
408 /**
409 * Transforms a constraint into SQL and parameter arrays
410 *
411 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
412 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
413 * @param array &$sql The query parts
414 * @param array &$parameters The parameters that will replace the markers
415 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
416 * @return void
417 */
418 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
419 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
420 $sql['where'][] = '(';
421 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
422 $sql['where'][] = ' AND ';
423 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
424 $sql['where'][] = ')';
425 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
426 $sql['where'][] = '(';
427 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
428 $sql['where'][] = ' OR ';
429 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
430 $sql['where'][] = ')';
431 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
432 $sql['where'][] = 'NOT (';
433 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
434 $sql['where'][] = ')';
435 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
436 $this->parseComparison($constraint, $source, $sql, $parameters);
437 }
438 }
439
440 /**
441 * Parse a Comparison into SQL and parameter arrays.
442 *
443 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
444 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
445 * @param array &$sql SQL query parts to add to
446 * @param array &$parameters Parameters to bind to the SQL
447 * @param array $boundVariableValues The bound variables in the query and their values
448 * @return void
449 */
450 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
451 $operand1 = $comparison->getOperand1();
452 $operator = $comparison->getOperator();
453 $operand2 = $comparison->getOperand2();
454 if (($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO) && (is_array($operand2) || ($operand2 instanceof ArrayAccess) || ($operand2 instanceof Traversable))) {
455 // FIXME this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
456 $operator = Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN;
457 }
458
459 if ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN) {
460 $items = array();
461 $hasValue = FALSE;
462 foreach ($operand2 as $value) {
463 $value = $this->getPlainValue($value);
464 if ($value !== NULL) {
465 $items[] = $value;
466 $hasValue = TRUE;
467 }
468 }
469 if ($hasValue === FALSE) {
470 $sql['where'][] = '1<>1';
471 } else {
472 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
473 $items = array();
474 foreach ($operand2 as $value) {
475 $items[] = $this->getPlainValue($value);
476 }
477 $parameters[] = $items;
478 }
479 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_CONTAINS) {
480 if ($operand2 === NULL) {
481 $sql['where'][] = '1<>1';
482 } else {
483 $dataMap = $this->dataMapper->getDataMap($source->getNodeTypeName());
484 $columnMap = $dataMap->getColumnMap($operand1->getPropertyName());
485 $typeOfRelation = $columnMap->getTypeOfRelation();
486 $tableName = $operand1->getSelectorName();
487 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
488 $relationTableName = $columnMap->getRelationTableName();
489 $sql['where'][] = $tableName . '.uid IN (SELECT uid_local FROM ' . $relationTableName . ' WHERE uid_foreign=' . $this->getPlainValue($operand2) . ')';
490 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
491 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
492 if (isset($parentKeyFieldName)) {
493 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand1->getPropertyName(), $source->getNodeTypeName());
494 $childTableName = $columnMap->getChildTableName();
495 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
496 } else {
497 $statement = '(' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . ',%\'';
498 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . '\'';
499 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'' . $this->getPlainValue($operand2) . ',%\')';
500 $sql['where'][] = $statement;
501 }
502 } else {
503 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
504 }
505 }
506 } else {
507 if ($operand2 === NULL) {
508 if ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO) {
509 $operator = self::OPERATOR_EQUAL_TO_NULL;
510 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_NOT_EQUAL_TO) {
511 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
512 }
513 }
514 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
515 $parameters[] = $this->getPlainValue($operand2);
516 }
517 }
518
519 /**
520 * Returns a plain value, i.e. objects are flattened out if possible.
521 *
522 * @param mixed $input
523 * @return mixed
524 */
525 protected function getPlainValue($input) {
526 if ($input instanceof DateTime) {
527 return $input->format('U');
528 } elseif ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface) {
529 return $input->getUid();
530 } elseif (is_bool($input)) {
531 return $input === TRUE ? 1 : 0;
532 } else {
533 return $input;
534 }
535 }
536
537 /**
538 * Parse a DynamicOperand into SQL and parameter arrays.
539 *
540 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
541 * @param string $operator One of the JCR_OPERATOR_* constants
542 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
543 * @param array &$sql The query parts
544 * @param array &$parameters The parameters that will replace the markers
545 * @param string $valueFunction an optional SQL function to apply to the operand value
546 * @return void
547 */
548 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
549 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
550 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
551 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
552 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
553 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
554 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) { // FIXME Only necessary to differ from Join
555 $className = $source->getNodeTypeName();
556 }
557 $propertyName = $operand->getPropertyName();
558 while (strpos($propertyName, '.') !== FALSE) {
559 $this->addUnionStatement($className, $propertyName, $sql);
560 }
561 $tableName = $this->dataMapper->convertClassNameToTableName($className);
562 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
563 $operator = $this->resolveOperator($operator);
564 if ($valueFunction === NULL) {
565 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
566 } else {
567 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
568 }
569
570 $sql['where'][] = $constraintSQL;
571 }
572 }
573
574 protected function addUnionStatement(&$className, &$propertyPath, array &$sql) {
575 $explodedPropertyPath = explode('.', $propertyPath, 2);
576 $propertyName = $explodedPropertyPath[0];
577 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
578 $tableName = $this->dataMapper->convertClassNameToTableName($className);
579 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
580 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
581 $childTableName = $columnMap->getChildTableName();
582 if ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_ONE) {
583 if (isset($parentKeyFieldName)) {
584 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
585 } else {
586 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
587 }
588 $className = $columnMap->getChildClassName();
589 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
590 if (isset($parentKeyFieldName)) {
591 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
592 } else {
593 $onStatement = '(' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid,\',%\')';
594 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(\'%,\',' . $childTableName . '.uid)';
595 $onStatement .= ' OR ' . $tableName . '.' . $columnName . ' LIKE CONCAT(' . $childTableName . '.uid,\',%\'))';
596 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $onStatement;
597 }
598 $className = $this->dataMapper->getElementType($className, $propertyName);
599 } elseif ($columnMap->getTypeOfRelation() === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
600 $relationTableName = $columnMap->getRelationTableName();
601 $sql['unions'][$relationTableName] = 'INNER JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.uid_local';
602 $sql['unions'][$childTableName] = 'INNER JOIN ' . $childTableName . ' ON ' . $relationTableName . '.uid_foreign=' . $childTableName . '.uid';
603 $className = $this->dataMapper->getElementType($className, $propertyName);
604 } else {
605 throw new Tx_Extbase_Persistence_Exception('Could not determine type of relation.', 1252502725);
606 }
607 $propertyPath = $explodedPropertyPath[1];
608 }
609
610 /**
611 * Returns the SQL operator for the given JCR operator type.
612 *
613 * @param string $operator One of the JCR_OPERATOR_* constants
614 * @return string an SQL operator
615 */
616 protected function resolveOperator($operator) {
617 switch ($operator) {
618 case self::OPERATOR_EQUAL_TO_NULL:
619 $operator = 'IS';
620 break;
621 case self::OPERATOR_NOT_EQUAL_TO_NULL:
622 $operator = 'IS NOT';
623 break;
624 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN:
625 $operator = 'IN';
626 break;
627 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO:
628 $operator = '=';
629 break;
630 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_NOT_EQUAL_TO:
631 $operator = '!=';
632 break;
633 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LESS_THAN:
634 $operator = '<';
635 break;
636 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
637 $operator = '<=';
638 break;
639 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_GREATER_THAN:
640 $operator = '>';
641 break;
642 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
643 $operator = '>=';
644 break;
645 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LIKE:
646 $operator = 'LIKE';
647 break;
648 default:
649 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
650 }
651
652 return $operator;
653 }
654
655 /**
656 * Replace query placeholders in a query part by the given
657 * parameters.
658 *
659 * @param string $sqlString The query part with placeholders
660 * @param array $parameters The parameters
661 * @return string The query part with replaced placeholders
662 */
663 protected function replacePlaceholders(&$sqlString, array $parameters) {
664 // TODO profile this method again
665 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);
666 $offset = 0;
667 foreach ($parameters as $parameter) {
668 $markPosition = strpos($sqlString, '?', $offset);
669 if ($markPosition !== FALSE) {
670 if ($parameter === NULL) {
671 $parameter = 'NULL';
672 } elseif (is_array($parameter) || ($parameter instanceof ArrayAccess) || ($parameter instanceof Traversable)) {
673 $items = array();
674 foreach ($parameter as $item) {
675 $items[] = $this->databaseHandle->fullQuoteStr($item, 'foo');
676 }
677 $parameter = '(' . implode(',', $items) . ')';
678 } else {
679 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
680 }
681 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
682 }
683 $offset = $markPosition + strlen($parameter);
684 }
685 }
686
687 /**
688 * Adds additional WHERE statements according to the query settings.
689 *
690 * @param Tx_Extbase_Persistence_QuerySettingsInterface $querySettings The TYPO3 4.x specific query settings
691 * @param string $tableName The table name to add the additional where clause for
692 * @param string $sql
693 * @return void
694 */
695 protected function addAdditionalWhereClause(Tx_Extbase_Persistence_QuerySettingsInterface $querySettings, $tableName, &$sql) {
696 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettings) {
697 if ($querySettings->getRespectEnableFields()) {
698 $this->addEnableFieldsStatement($tableName, $sql);
699 }
700 if ($querySettings->getRespectSysLanguage()) {
701 $this->addSysLanguageStatement($tableName, $sql);
702 }
703 if ($querySettings->getRespectStoragePage()) {
704 $this->addPageIdStatement($tableName, $sql);
705 }
706 }
707 }
708
709 /**
710 * Builds the enable fields statement
711 *
712 * @param string $tableName The database table name
713 * @param array &$sql The query parts
714 * @return void
715 */
716 protected function addEnableFieldsStatement($tableName, array &$sql) {
717 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
718 if (TYPO3_MODE === 'FE') {
719 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
720 } else { // TYPO3_MODE === 'BE'
721 $statement = t3lib_BEfunc::deleteClause($tableName);
722 $statement .= t3lib_BEfunc::BEenableFields($tableName);
723 }
724 if(!empty($statement)) {
725 $statement = substr($statement, 5);
726 $sql['additionalWhereClause'][] = $statement;
727 }
728 }
729 }
730
731 /**
732 * Builds the language field statement
733 *
734 * @param string $tableName The database table name
735 * @param array &$sql The query parts
736 * @return void
737 */
738 protected function addSysLanguageStatement($tableName, array &$sql) {
739 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
740 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
741 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
742 }
743 }
744 }
745
746 /**
747 * Builds the page ID checking statement
748 *
749 * @param string $tableName The database table name
750 * @param array &$sql The query parts
751 * @return void
752 */
753 protected function addPageIdStatement($tableName, array &$sql) {
754 if (empty($this->tableInformationCache[$tableName]['columnNames'])) {
755 $this->tableInformationCache[$tableName]['columnNames'] = $this->databaseHandle->admin_get_fields($tableName);
756 }
757 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache[$tableName]['columnNames'])) {
758 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
759 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
760 }
761 }
762
763 /**
764 * Transforms orderings into SQL.
765 *
766 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
767 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
768 * @param array &$sql The query parts
769 * @return void
770 */
771 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
772 foreach ($orderings as $ordering) {
773 $operand = $ordering->getOperand();
774 $order = $ordering->getOrder();
775 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
776 switch ($order) {
777 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
778 $order = 'ASC';
779 break;
780 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
781 $order = 'DESC';
782 break;
783 default:
784 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
785 }
786 $tableName = $operand->getSelectorName();
787 $className = '';
788 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
789 $className = $source->getNodeTypeName();
790 }
791 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
792 if (strlen($tableName) > 0) {
793 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
794 } else {
795 $sql['orderings'][] = $columnName . ' ' . $order;
796 }
797 }
798 }
799 }
800
801 /**
802 * Transforms limit and offset into SQL
803 *
804 * @param int $limit
805 * @param int $offset
806 * @param array &$sql
807 * @return void
808 */
809 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
810 if ($limit !== NULL && $offset !== NULL) {
811 $sql['limit'] = $offset . ', ' . $limit;
812 } elseif ($limit !== NULL) {
813 $sql['limit'] = $limit;
814 }
815 }
816
817 /**
818 * Transforms a Resource from a database query to an array of rows.
819 *
820 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
821 * @param resource $result The result
822 * @return array The result as an array of rows (tuples)
823 */
824 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $result) {
825 $rows = array();
826 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
827 if (is_array($row)) {
828 // TODO Check if this is necessary, maybe the last line is enough
829 $arrayKeys = range(0, count($row));
830 array_fill_keys($arrayKeys, $row);
831 $rows[] = $row;
832 }
833 }
834 return $rows;
835 }
836
837 /**
838 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
839 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
840 *
841 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
842 * @param array $row The row array (as reference)
843 * @param string $languageUid The language id
844 * @param string $workspaceUidUid The workspace id
845 * @return void
846 */
847 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface $source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
848 $overlayedRows = array();
849 foreach ($rows as $row) {
850 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
851 if (TYPO3_MODE == 'FE') {
852 if (is_object($GLOBALS['TSFE'])) {
853 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
854 } else {
855 require_once(PATH_t3lib . 'class.t3lib_page.php');
856 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
857 }
858 } else {
859 require_once(PATH_t3lib . 'class.t3lib_page.php');
860 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
861 }
862 }
863 if (is_object($GLOBALS['TSFE'])) {
864 if ($languageUid === NULL) {
865 $languageUid = $GLOBALS['TSFE']->sys_language_uid;
866 }
867 if ($workspaceUid !== NULL) {
868 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
869 }
870 } else {
871 if ($languageUid === NULL) {
872 $languageUid = intval(t3lib_div::_GP('L'));
873 }
874 if ($workspaceUid === NULL) {
875 $workspaceUid = $GLOBALS['BE_USER']->workspace;
876 }
877 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
878 }
879 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
880 $tableName = $source->getSelectorName();
881 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
882 $tableName = $source->getLeft()->getSelectorName();
883 }
884 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
885 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
886 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
887 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid);
888 }
889 }
890 $overlayedRows[] = $row;
891 }
892 return $overlayedRows;
893 }
894
895 /**
896 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
897 *
898 * @return void
899 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
900 */
901 protected function checkSqlErrors() {
902 $error = $this->databaseHandle->sql_error();
903 if ($error !== '') {
904 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
905 }
906 }
907
908 /**
909 * Clear the TYPO3 page cache for the given record.
910 * If the record lies on a page, then we clear the cache of this page.
911 * If the record has no PID column, we clear the cache of the current page as best-effort.
912 *
913 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
914 *
915 * @param $tableName Table name of the record
916 * @param $uid UID of the record
917 * @return void
918 */
919 protected function clearPageCache($tableName, $uid) {
920 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
921 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
922 } else {
923 // if disabled, return
924 return;
925 }
926
927 $pageIdsToClear = array();
928 $storagePage = NULL;
929
930 $columns = $this->databaseHandle->admin_get_fields($tableName);
931 if (array_key_exists('pid', $columns)) {
932 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
933 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
934 $storagePage = $row['pid'];
935 $pageIdsToClear[] = $storagePage;
936 }
937 } elseif (isset($GLOBALS['TSFE'])) {
938 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
939 $storagePage = $GLOBALS['TSFE']->id;
940 $pageIdsToClear[] = $storagePage;
941 }
942
943 if ($storagePage === NULL) {
944 return;
945 }
946 if (!isset($this->pageTSConfigCache[$storagePage])) {
947 $this->pageTSConfigCache[$storagePage] = t3lib_BEfunc::getPagesTSconfig($storagePage);
948 }
949 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
950 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
951 $clearCacheCommands = array_unique($clearCacheCommands);
952 foreach ($clearCacheCommands as $clearCacheCommand) {
953 if (t3lib_div::testInt($clearCacheCommand)) {
954 $pageIdsToClear[] = $clearCacheCommand;
955 }
956 }
957 }
958
959 // 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
960 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
961 }
962 }
963
964 ?>