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