[+FEATURE] Extbase (Persistence): Implemented recursive starting point/storage page...
[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 const OPERATOR_IN = 'operatorIn';
40 const OPERATOR_NOT_IN = 'operatorNotIn';
41
42 /**
43 * The TYPO3 database object
44 *
45 * @var t3lib_db
46 */
47 protected $databaseHandle;
48
49 /**
50 * @var Tx_Extbase_Persistence_DataMapper
51 */
52 protected $dataMapper;
53
54 /**
55 * The TYPO3 page select object. Used for language and workspace overlay
56 *
57 * @var t3lib_pageSelect
58 */
59 protected $pageSelectObject;
60
61 /**
62 * A first-level TypoScript configuration cache
63 *
64 * @var array
65 */
66 protected $pageTSConfigCache = array();
67
68 /**
69 * Caches information about tables (esp. the existing column names)
70 *
71 * @var array
72 */
73 protected $tableInformationCache = array();
74
75 /**
76 * Constructs this Storage Backend instance
77 *
78 * @param t3lib_db $databaseHandle The database handle
79 */
80 public function __construct($databaseHandle) {
81 $this->databaseHandle = $databaseHandle;
82 }
83
84 /**
85 * Injects the DataMapper to map nodes to objects
86 *
87 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
88 * @return void
89 */
90 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
91 $this->dataMapper = $dataMapper;
92 }
93
94 /**
95 * Adds a row to the storage
96 *
97 * @param string $tableName The database table name
98 * @param array $row The row to be inserted
99 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
100 * @return int The uid of the inserted row
101 */
102 public function addRow($tableName, array $row, $isRelation = FALSE) {
103 $fields = array();
104 $values = array();
105 $parameters = array();
106 if (isset($row['uid'])) {
107 unset($row['uid']);
108 }
109 foreach ($row as $columnName => $value) {
110 $fields[] = $columnName;
111 $values[] = '?';
112 $parameters[] = $value;
113 }
114
115 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
116 $this->replacePlaceholders($sqlString, $parameters);
117 // debug($sqlString,-2);
118 $this->databaseHandle->sql_query($sqlString);
119 $this->checkSqlErrors();
120 $uid = $this->databaseHandle->sql_insert_id();
121 if (!$isRelation) {
122 $this->clearPageCache($tableName, $uid);
123 }
124 return (int)$uid;
125 }
126
127 /**
128 * Updates a row in the storage
129 *
130 * @param string $tableName The database table name
131 * @param array $row The row to be updated
132 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
133 * @return void
134 */
135 public function updateRow($tableName, array $row, $isRelation = FALSE) {
136 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
137 $uid = (int)$row['uid'];
138 unset($row['uid']);
139 $fields = array();
140 $parameters = array();
141 foreach ($row as $columnName => $value) {
142 $fields[] = $columnName . '=?';
143 $parameters[] = $value;
144 }
145 $parameters[] = $uid;
146
147 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
148 $this->replacePlaceholders($sqlString, $parameters);
149 // debug($sqlString,-2);
150 $returnValue = $this->databaseHandle->sql_query($sqlString);
151 $this->checkSqlErrors();
152 if (!$isRelation) {
153 $this->clearPageCache($tableName, $uid);
154 }
155 return $returnValue;
156 }
157
158 /**
159 * Deletes a row in the storage
160 *
161 * @param string $tableName The database table name
162 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
163 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
164 * @return void
165 */
166 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
167 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
168 $this->replacePlaceholders($statement, $identifier);
169 if (!$isRelation) {
170 $this->clearPageCache($tableName, $uid, $isRelation);
171 }
172 $returnValue = $this->databaseHandle->sql_query($statement);
173 $this->checkSqlErrors();
174 return $returnValue;
175 }
176
177 /**
178 * Fetches row data from the database
179 *
180 * @param string $identifier The Identifier of the row to fetch
181 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
182 * @return array|FALSE
183 */
184 public function getRowByIdentifier($tableName, array $identifier) {
185 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
186 $this->replacePlaceholders($statement, $identifier);
187 // debug($statement,-2);
188 $res = $this->databaseHandle->sql_query($statement);
189 $this->checkSqlErrors();
190 $row = $this->databaseHandle->sql_fetch_assoc($res);
191 if ($row !== FALSE) {
192 return $row;
193 } else {
194 return FALSE;
195 }
196 }
197
198 protected function parseIdentifier(array $identifier) {
199 $fieldNames = array_keys($identifier);
200 $suffixedFieldNames = array();
201 foreach ($fieldNames as $fieldName) {
202 $suffixedFieldNames[] = $fieldName . '=?';
203 }
204 return implode(' AND ', $suffixedFieldNames);
205 }
206
207 /**
208 * Returns an array with tuples matching the query.
209 *
210 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
211 * @return array The matching tuples
212 */
213 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
214 $constraint = $query->getConstraint();
215 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) {
216 if ($constraint->getLanguage() === Tx_Extbase_Persistence_QOM_QueryObjectModelInterface::TYPO3_SQL_MYSQL) {
217 $statement = $constraint->getStatement();
218 $parameters = $query->getBoundVariableValues();
219 } else {
220 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
221 }
222 } else {
223 $parameters = array();
224 $statement = $this->getStatement($query, $parameters);
225 }
226 $this->replacePlaceholders($statement, $parameters);
227 // debug($statement,-2);
228 $result = $this->databaseHandle->sql_query($statement);
229 $this->checkSqlErrors();
230 return $this->getRowsFromResult($query->getSource(), $result);
231 }
232
233 /**
234 * Returns the number of tuples matching the query.
235 *
236 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
237 * @return int The number of matching tuples
238 */
239 public function countRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
240 $constraint = $query->getConstraint();
241 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) throw new Tx_Extbase_Persistence_Storage_Exception_BadConstraint('Could not execute count on queries with a constraint of type Tx_Extbase_Persistence_QOM_StatementInterface', 1256661045);
242 $parameters = array();
243 $statementParts = $this->parseQuery($query, $parameters);
244 $statementParts['fields'] = array('COUNT(*)');
245 $statement = $this->buildStatement($statementParts, $parameters);
246 $this->replacePlaceholders($statement, $parameters);
247 $result = $this->databaseHandle->sql_query($statement);
248 $this->checkSqlErrors();
249 $tuples = $this->getRowsFromResult($query->getSource(), $result);
250 return current(current($tuples));
251 }
252
253 /**
254 * Returns the statement, ready to be executed.
255 *
256 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
257 * @return string The SQL statement
258 */
259 public function getStatement(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, array &$parameters) {
260 $statementParts = $this->parseQuery($query, $parameters);
261 $statement = $this->buildStatement($statementParts);
262 return $statement;
263 }
264
265 /**
266 * Parses the query and returns the SQL statement parts.
267 *
268 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
269 * @return array The SQL statement parts
270 */
271 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, array &$parameters) {
272 $sql = array();
273 $sql['tables'] = array();
274 $sql['fields'] = array();
275 $sql['where'] = array();
276 $sql['additionalWhereClause'] = array();
277 $sql['orderings'] = array();
278 $sql['limit'] = array();
279
280 $source = $query->getSource();
281
282 $this->parseSource($query, $source, $sql, $parameters);
283 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters, $query->getBoundVariableValues());
284 $this->parseOrderings($query->getOrderings(), $source, $sql);
285 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
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 buildStatement(array $sql) {
297 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
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[] = $dataMap->convertPropertyValueToFieldValue($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();
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_QueryObjectModel $query
364 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
365 * @param array &$sql
366 * @param array &$parameters
367 * @return void
368 */
369 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
370 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
371 $tableName = $source->getSelectorName();
372 $sql['fields'][] = $tableName . '.*';
373 $sql['tables'][] = $tableName;
374 $querySettings = $query->getQuerySettings();
375 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
376 if ($querySettings->getRespectEnableFields()) {
377 $this->addEnableFieldsStatement($tableName, $sql);
378 }
379 if ($querySettings->getRespectStoragePage()) {
380 $this->addPageIdStatement($tableName, $sql);
381 }
382 }
383 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
384 $this->parseJoin($query, $source, $sql);
385 }
386 }
387
388 /**
389 * Transforms a Join into SQL and parameter arrays
390 *
391 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
392 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
393 * @param array &$sql The query parts
394 * @return void
395 */
396 protected function parseJoin(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql) {
397 $leftSource = $join->getLeft();
398 $leftTableName = $leftSource->getSelectorName();
399 $rightSource = $join->getRight();
400 $rightTableName = $rightSource->getSelectorName();
401
402 $sql['fields'][] = $leftTableName . '.*';
403 $sql['fields'][] = $rightTableName . '.*';
404
405 // TODO Implement support for different join types and nested joins
406 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
407
408 $joinCondition = $join->getJoinCondition();
409 // TODO Check the parsing of the join
410 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
411 // TODO Discuss, if we should use $leftSource instead of $selector1Name
412 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
413 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
414 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
415 }
416 // TODO Implement childtableWhere
417
418 $querySettings = $query->getQuerySettings();
419 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
420 if ($querySettings->getRespectEnableFields()) {
421 $this->addEnableFieldsStatement($leftTableName, $sql);
422 $this->addEnableFieldsStatement($rightTableName, $sql);
423 }
424 if ($querySettings->getRespectStoragePage()) {
425 $this->addPageIdStatement($leftTableName, $sql);
426 $this->addPageIdStatement($rightTableName, $sql);
427 }
428 }
429 }
430
431 /**
432 * Transforms a constraint into SQL and parameter arrays
433 *
434 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
435 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
436 * @param array &$sql The query parts
437 * @param array &$parameters The parameters that will replace the markers
438 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
439 * @return void
440 */
441 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
442 if ($constraint === NULL) return;
443 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
444 $sql['where'][] = '(';
445 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
446 $sql['where'][] = ' AND ';
447 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
448 $sql['where'][] = ')';
449 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
450 $sql['where'][] = '(';
451 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
452 $sql['where'][] = ' OR ';
453 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
454 $sql['where'][] = ')';
455 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
456 $sql['where'][] = 'NOT (';
457 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters, $boundVariableValues);
458 $sql['where'][] = ')';
459 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
460 $this->parseComparison($constraint, $source, $sql, $parameters, $boundVariableValues);
461 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
462 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
463 }
464 }
465
466 /**
467 * Parse a Comparison into SQL and parameter arrays.
468 *
469 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
470 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
471 * @param array &$sql SQL query parts to add to
472 * @param array &$parameters Parameters to bind to the SQL
473 * @param array $boundVariableValues The bound variables in the query and their values
474 * @return void
475 */
476 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
477 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
478
479 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
480 $operator = $comparison->getOperator();
481 if ($value === NULL) {
482 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO) {
483 $operator = self::OPERATOR_EQUAL_TO_NULL;
484 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO) {
485 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
486 }
487 } elseif (is_array($value)) {
488 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO) {
489 $operator = self::OPERATOR_IN;
490 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO) {
491 $operator = self::OPERATOR_NOT_IN;
492 }
493 }
494 $parameters[] = $value;
495
496 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
497 }
498
499 /**
500 * Parse a DynamicOperand into SQL and parameter arrays.
501 *
502 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
503 * @param string $operator One of the JCR_OPERATOR_* constants
504 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
505 * @param array &$sql The query parts
506 * @param array &$parameters The parameters that will replace the markers
507 * @param string $valueFunction an optional SQL function to apply to the operand value
508 * @return void
509 */
510 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL) {
511 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
512 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
513 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
514 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
515 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
516 $tableName = $operand->getSelectorName();
517 // FIXME Discuss the translation from propertyName to columnName
518 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
519 $className = $source->getNodeTypeName();
520 } else {
521 $className = '';
522 }
523 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
524 $operator = $this->resolveOperator($operator);
525
526 if ($valueFunction === NULL) {
527 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
528 } else {
529 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
530 }
531
532 $sql['where'][] = $constraintSQL;
533 }
534 }
535
536 /**
537 * Returns the SQL operator for the given JCR operator type.
538 *
539 * @param string $operator One of the JCR_OPERATOR_* constants
540 * @return string an SQL operator
541 */
542 protected function resolveOperator($operator) {
543 switch ($operator) {
544 case self::OPERATOR_EQUAL_TO_NULL:
545 $operator = 'IS';
546 break;
547 case self::OPERATOR_NOT_EQUAL_TO_NULL:
548 $operator = 'IS NOT';
549 break;
550 case self::OPERATOR_IN:
551 $operator = 'IN';
552 break;
553 case self::OPERATOR_NOT_IN:
554 $operator = 'NOT IN';
555 break;
556 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
557 $operator = '=';
558 break;
559 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
560 $operator = '!=';
561 break;
562 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
563 $operator = '<';
564 break;
565 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
566 $operator = '<=';
567 break;
568 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
569 $operator = '>';
570 break;
571 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
572 $operator = '>=';
573 break;
574 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
575 $operator = 'LIKE';
576 break;
577 default:
578 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
579 }
580
581 return $operator;
582 }
583
584 /**
585 * Replace query placeholders in a query part by the given
586 * parameters.
587 *
588 * @param string $sqlString The query part with placeholders
589 * @param array $parameters The parameters
590 * @return string The query part with replaced placeholders
591 */
592 protected function replacePlaceholders(&$sqlString, array $parameters) {
593 // TODO profile this method again
594 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);
595 $offset = 0;
596 foreach ($parameters as $parameter) {
597 $markPosition = strpos($sqlString, '?', $offset);
598 if ($markPosition !== FALSE) {
599 if ($parameter === NULL) {
600 $parameter = 'NULL';
601 } elseif (is_array($parameter)) {
602 $items = array();
603 foreach ($parameter as $item) {
604 $items[] = $this->databaseHandle->fullQuoteStr($item, 'foo');
605 }
606 $parameter = '(' . implode(',', $items) . ')';
607 } else {
608 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
609 }
610 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
611 }
612 $offset = $markPosition + strlen($parameter);
613 }
614 }
615
616 /**
617 * Builds the enable fields statement
618 *
619 * @param string $tableName The database table name
620 * @param array &$sql The query parts
621 * @return void
622 */
623 protected function addEnableFieldsStatement($tableName, array &$sql) {
624 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
625 if (TYPO3_MODE === 'FE') {
626 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
627 } else { // TYPO3_MODE === 'BE'
628 $statement = t3lib_BEfunc::deleteClause($tableName);
629 $statement .= t3lib_BEfunc::BEenableFields($tableName);
630 }
631 if(!empty($statement)) {
632 $statement = substr($statement, 5);
633 $sql['additionalWhereClause'][] = $statement;
634 }
635 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] != '') {
636 $sql['additionalWhereClause'][] = $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1) ';
637 }
638 }
639 }
640
641 /**
642 * Builds the page ID checking statement
643 *
644 * @param string $tableName The database table name
645 * @param array &$sql The query parts
646 * @return void
647 */
648 protected function addPageIdStatement($tableName, array &$sql) {
649 if (empty($this->tableInformationCache[$tableName]['columnNames'])) {
650 $this->tableInformationCache[$tableName]['columnNames'] = $this->databaseHandle->admin_get_fields($tableName);
651 }
652 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache[$tableName]['columnNames'])) {
653 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
654 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
655 }
656 }
657
658 /**
659 * Transforms orderings into SQL.
660 *
661 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
662 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
663 * @param array &$sql The query parts
664 * @return void
665 */
666 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
667 foreach ($orderings as $ordering) {
668 $operand = $ordering->getOperand();
669 $order = $ordering->getOrder();
670 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
671 switch ($order) {
672 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
673 $order = 'ASC';
674 break;
675 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
676 $order = 'DESC';
677 break;
678 default:
679 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
680 }
681 $tableName = $operand->getSelectorName();
682 $className = '';
683 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
684 $className = $source->getNodeTypeName();
685 }
686 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
687 if (strlen($tableName) > 0) {
688 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
689 } else {
690 $sql['orderings'][] = $columnName . ' ' . $order;
691 }
692 }
693 }
694 }
695
696 /**
697 * Transforms limit and offset into SQL
698 *
699 * @param int $limit
700 * @param int $offset
701 * @param array &$sql
702 * @return void
703 */
704 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
705 if ($limit !== NULL && $offset !== NULL) {
706 $sql['limit'] = $offset . ', ' . $limit;
707 } elseif ($limit !== NULL) {
708 $sql['limit'] = $limit;
709 }
710 }
711
712 /**
713 * Transforms a Resource from a database query to an array of rows. Performs the language and
714 * workspace overlay before.
715 *
716 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
717 * @param resource $result The result
718 * @return array The result as an array of rows (tuples)
719 */
720 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $result) {
721 $rows = array();
722 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
723 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
724 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
725 } else if ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
726 $row = $this->doLanguageAndWorkspaceOverlay($source->getLeft()->getSelectorName(), $row);
727 }
728 if (is_array($row)) {
729 // TODO Check if this is necessary, maybe the last line is enough
730 $arrayKeys = range(0,count($row));
731 array_fill_keys($arrayKeys, $row);
732 $rows[] = $row;
733 }
734 }
735 return $rows;
736 }
737
738 /**
739 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
740 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
741 *
742 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
743 * @param array $row The row array (as reference)
744 * @param string $languageUid The language id
745 * @param string $workspaceUidUid The workspace id
746 * @return void
747 */
748 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
749 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
750 if (TYPO3_MODE == 'FE') {
751 if (is_object($GLOBALS['TSFE'])) {
752 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
753 } else {
754 require_once(PATH_t3lib . 'class.t3lib_page.php');
755 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
756 }
757 } else {
758 require_once(PATH_t3lib . 'class.t3lib_page.php');
759 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
760 }
761 }
762 if (is_object($GLOBALS['TSFE'])) {
763 if ($languageUid === NULL) {
764 $languageUid = $GLOBALS['TSFE']->sys_language_uid;
765 }
766 if ($workspaceUid !== NULL) {
767 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
768 }
769 } else {
770 if ($languageUid === NULL) {
771 $languageUid = intval(t3lib_div::_GP('L'));
772 }
773 if ($workspaceUid === NULL) {
774 $workspaceUid = $GLOBALS['BE_USER']->workspace;
775 }
776 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
777 }
778 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
779 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
780 // TODO Skip if empty languageoverlay (languagevisibility)
781 return $row;
782 }
783
784 /**
785 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
786 *
787 * @return void
788 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
789 */
790 protected function checkSqlErrors() {
791 $error = $this->databaseHandle->sql_error();
792 if ($error !== '') {
793 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
794 }
795 }
796
797 /**
798 * Clear the TYPO3 page cache for the given record.
799 * If the record lies on a page, then we clear the cache of this page.
800 * If the record has no PID column, we clear the cache of the current page as best-effort.
801 *
802 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
803 *
804 * @param $tableName Table name of the record
805 * @param $uid UID of the record
806 * @return void
807 */
808 protected function clearPageCache($tableName, $uid) {
809 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
810 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
811 } else {
812 // if disabled, return
813 return;
814 }
815
816 $pageIdsToClear = array();
817 $storagePage = NULL;
818
819 $columns = $this->databaseHandle->admin_get_fields($tableName);
820 if (array_key_exists('pid', $columns)) {
821 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
822 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
823 $storagePage = $row['pid'];
824 $pageIdsToClear[] = $storagePage;
825 }
826 } elseif (isset($GLOBALS['TSFE'])) {
827 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
828 $storagePage = $GLOBALS['TSFE']->id;
829 $pageIdsToClear[] = $storagePage;
830 }
831
832 if ($storagePage === NULL) {
833 return;
834 }
835 if (!isset($this->pageTSConfigCache[$storagePage])) {
836 $this->pageTSConfigCache[$storagePage] = t3lib_BEfunc::getPagesTSconfig($storagePage);
837 }
838 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
839 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
840 $clearCacheCommands = array_unique($clearCacheCommands);
841 foreach ($clearCacheCommands as $clearCacheCommand) {
842 if (t3lib_div::testInt($clearCacheCommand)) {
843 $pageIdsToClear[] = $clearCacheCommand;
844 }
845 }
846 }
847
848 // 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
849 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
850 }
851 }
852
853 ?>