[+BUGFIX] Extbase (Persistence): Fixed typo in Exception class.
[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 * Constructs this Storage Backend instance
61 *
62 * @param t3lib_db $databaseHandle The database handle
63 */
64 public function __construct($databaseHandle) {
65 $this->databaseHandle = $databaseHandle;
66 }
67
68 /**
69 * Injects the DataMapper to map nodes to objects
70 *
71 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
72 * @return void
73 */
74 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
75 $this->dataMapper = $dataMapper;
76 }
77
78 /**
79 * Adds a row to the storage
80 *
81 * @param string $tableName The database table name
82 * @param array $row The row to be inserted
83 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
84 * @return int The uid of the inserted row
85 */
86 public function addRow($tableName, array $row, $isRelation = FALSE) {
87 $fields = array();
88 $values = array();
89 $parameters = array();
90 if (isset($row['uid'])) {
91 unset($row['uid']);
92 }
93 foreach ($row as $columnName => $value) {
94 $fields[] = $columnName;
95 $values[] = '?';
96 $parameters[] = $value;
97 }
98
99 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
100 $this->replacePlaceholders($sqlString, $parameters);
101 $this->databaseHandle->sql_query($sqlString);
102 $this->checkSqlErrors();
103 $uid = $this->databaseHandle->sql_insert_id();
104 if (!$isRelation) {
105 $this->clearPageCache($tableName, $uid);
106 }
107 return $uid;
108 }
109
110 /**
111 * Updates a row in the storage
112 *
113 * @param string $tableName The database table name
114 * @param array $row The row to be updated
115 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
116 * @return void
117 */
118 public function updateRow($tableName, array $row, $isRelation = FALSE) {
119 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
120 $uid = (int)$row['uid'];
121 unset($row['uid']);
122 $fields = array();
123 $parameters = array();
124 foreach ($row as $columnName => $value) {
125 $fields[] = $columnName . '=?';
126 $parameters[] = $value;
127 }
128 $parameters[] = $uid;
129
130 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
131 $this->replacePlaceholders($sqlString, $parameters);
132
133 $returnValue = $this->databaseHandle->sql_query($sqlString);
134 $this->checkSqlErrors();
135 if (!$isRelation) {
136 $this->clearPageCache($tableName, $uid);
137 }
138 return $returnValue;
139 }
140
141 /**
142 * Deletes a row in the storage
143 *
144 * @param string $tableName The database table name
145 * @param array $identifyer An array of identifyer array('fieldname' => value). This array will be transformed to a WHERE clause
146 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
147 * @return void
148 */
149 public function removeRow($tableName, array $identifyer, $isRelation = FALSE) {
150 $fieldNames = array_keys($identifyer);
151 $suffixedFieldNames = array();
152 foreach ($fieldNames as $fieldName) {
153 $suffixedFieldNames[] = $fieldName . '=?';
154 }
155 $parameters = array_values($identifyer);
156 $statement = 'DELETE FROM ' . $tableName;
157 $statement .= ' WHERE ' . implode(' AND ', $suffixedFieldNames);
158 $this->replacePlaceholders($statement, $parameters);
159 if (!$isRelation) {
160 $this->clearPageCache($tableName, $uid, $isRelation);
161 }
162 $returnValue = $this->databaseHandle->sql_query($statement);
163 $this->checkSqlErrors();
164 return $returnValue;
165 }
166
167 /**
168 * Returns an array with tuples matching the query.
169 *
170 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
171 * @return array The matching tuples
172 */
173 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
174 $statement = $this->parseQuery($query);
175 // debug($statement, -2); // FIXME remove debug code
176 $result = $this->databaseHandle->sql_query($statement);
177 $this->checkSqlErrors();
178 if ($result) {
179 $tuples = $this->getRowsFromResult($query->getSource(), $result);
180 }
181
182 return $tuples;
183 }
184
185 /**
186 * Returns an array with tuples matching the query.
187 *
188 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
189 * @return array The matching tuples
190 */
191 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
192 $statement = '';
193 $parameters = array();
194 $constraint = $query->getConstraint();
195 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) {
196 if ($constraint->getLanguage() === Tx_Extbase_Persistence_QOM_QueryObjectModelInterface::TYPO3_SQL_MYSQL) {
197 $statement = $constraint->getStatement();
198 $parameters= $query->getBoundVariableValues();
199 } else {
200 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
201 }
202 } else {
203 $sql = array();
204 $sql['tables'] = array();
205 $sql['fields'] = array();
206 $sql['where'] = array();
207 $sql['additionalWhereClause'] = array();
208 $sql['orderings'] = array();
209 $sql['limit'] = array();
210 $tuples = array();
211
212 $source = $query->getSource();
213 $this->parseSource($query, $source, $sql, $parameters);
214
215 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
216
217 $this->parseConstraint($constraint, $source, $sql, $parameters, $query->getBoundVariableValues());
218
219 if (!empty($sql['where'])) {
220 $statement .= ' WHERE ' . implode('', $sql['where']);
221 if (!empty($sql['additionalWhereClause'])) {
222 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
223 }
224 } elseif (!empty($sql['additionalWhereClause'])) {
225 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
226 }
227
228 $this->parseOrderings($query->getOrderings(), $source, $sql);
229 if (!empty($sql['orderings'])) {
230 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
231 }
232
233 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
234 if (!empty($sql['limit'])) {
235 $statement .= ' LIMIT ' . $sql['limit'];
236 }
237 }
238 $this->replacePlaceholders($statement, $parameters);
239 return $statement;
240 }
241
242 /**
243 * Checks if a Value Object equal to the given Object exists in the data base
244 *
245 * @param array $properties The properties of the Value Object
246 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
247 * @return array The matching uid
248 */
249 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap $dataMap) {
250 $fields = array();
251 $parameters = array();
252 foreach ($properties as $propertyName => $propertyValue) {
253 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
254 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
255 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
256 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
257 }
258 }
259 $sql = array();
260 $sql['additionalWhereClause'] = array();
261
262 $tableName = $dataMap->getTableName();
263 $this->addEnableFieldsStatement($tableName, $sql);
264
265 $statement = 'SELECT * FROM ' . $tableName;
266 $statement .= ' WHERE ' . implode(' AND ', $fields);
267 if (!empty($sql['additionalWhereClause'])) {
268 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
269 }
270 $this->replacePlaceholders($statement, $parameters);
271 $res = $this->databaseHandle->sql_query($statement);
272 $this->checkSqlErrors();
273 $row = $this->databaseHandle->sql_fetch_assoc($res);
274 if ($row !== FALSE) {
275 return $row['uid'];
276 } else {
277 return FALSE;
278 }
279 }
280
281 /**
282 * Transforms a Query Source into SQL and parameter arrays
283 *
284 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
285 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
286 * @param array &$sql
287 * @param array &$parameters
288 * @return void
289 */
290 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
291 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
292 $tableName = $source->getSelectorName();
293 $sql['fields'][] = $tableName . '.*';
294 $sql['tables'][] = $tableName;
295 $querySettings = $query->getQuerySettings();
296 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
297 if ($querySettings->getRespectEnableFields()) {
298 $this->addEnableFieldsStatement($tableName, $sql);
299 }
300 if ($querySettings->getRespectStoragePage()) {
301 $this->addPageIdStatement($tableName, $sql);
302 }
303 }
304 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
305 $this->parseJoin($query, $source, $sql);
306 }
307 }
308
309 /**
310 * Transforms a Join into SQL and parameter arrays
311 *
312 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
313 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
314 * @param array &$sql The query parts
315 * @return void
316 */
317 protected function parseJoin(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql) {
318 $leftSource = $join->getLeft();
319 $leftTableName = $leftSource->getSelectorName();
320 $rightSource = $join->getRight();
321 $rightTableName = $rightSource->getSelectorName();
322
323 $sql['fields'][] = $leftTableName . '.*';
324 $sql['fields'][] = $rightTableName . '.*';
325
326 // TODO Implement support for different join types and nested joins
327 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
328
329 $joinCondition = $join->getJoinCondition();
330 // TODO Check the parsing of the join
331 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
332 // TODO Discuss, if we should use $leftSource instead of $selector1Name
333 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
334 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
335 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
336 }
337 // TODO Implement childtableWhere
338
339 $querySettings = $query->getQuerySettings();
340 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
341 if ($querySettings->getRespectEnableFields()) {
342 $this->addEnableFieldsStatement($leftTableName, $sql);
343 $this->addEnableFieldsStatement($rightTableName, $sql);
344 }
345 if ($querySettings->getRespectStoragePage()) {
346 $this->addPageIdStatement($leftTableName, $sql);
347 $this->addPageIdStatement($rightTableName, $sql);
348 }
349 }
350 }
351
352 /**
353 * Transforms a constraint into SQL and parameter arrays
354 *
355 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
356 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
357 * @param array &$sql The query parts
358 * @param array &$parameters The parameters that will replace the markers
359 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
360 * @return void
361 */
362 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
363 if ($constraint === NULL) return;
364 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
365 $sql['where'][] = '(';
366 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
367 $sql['where'][] = ' AND ';
368 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
369 $sql['where'][] = ')';
370 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
371 $sql['where'][] = '(';
372 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
373 $sql['where'][] = ' OR ';
374 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
375 $sql['where'][] = ')';
376 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
377 $sql['where'][] = 'NOT (';
378 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters, $boundVariableValues);
379 $sql['where'][] = ')';
380 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
381 $this->parseComparison($constraint, $source, $sql, $parameters, $boundVariableValues);
382 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
383 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
384 }
385 }
386
387 /**
388 * Parse a Comparison into SQL and parameter arrays.
389 *
390 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
391 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
392 * @param array &$sql SQL query parts to add to
393 * @param array &$parameters Parameters to bind to the SQL
394 * @param array $boundVariableValues The bound variables in the query and their values
395 * @return void
396 */
397 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
398 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
399
400 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
401 $operator = $comparison->getOperator();
402 if ($value === NULL) {
403 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO) {
404 $operator = self::OPERATOR_EQUAL_TO_NULL;
405 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO) {
406 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
407 } else {
408 // TODO Throw exception
409 }
410 }
411 $parameters[] = $value;
412
413 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
414 }
415
416 /**
417 * Parse a DynamicOperand into SQL and parameter arrays.
418 *
419 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
420 * @param string $operator One of the JCR_OPERATOR_* constants
421 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
422 * @param array &$sql The query parts
423 * @param array &$parameters The parameters that will replace the markers
424 * @param string $valueFunction an optional SQL function to apply to the operand value
425 * @return void
426 */
427 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL) {
428 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
429 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
430 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
431 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
432 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
433 $tableName = $operand->getSelectorName();
434 // FIXME Discuss the translation from propertyName to columnName
435 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
436 $className = $source->getNodeTypeName();
437 } else {
438 $className = '';
439 }
440 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
441 $operator = $this->resolveOperator($operator);
442
443 if ($valueFunction === NULL) {
444 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
445 } else {
446 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
447 }
448
449 $sql['where'][] = $constraintSQL;
450 }
451 }
452
453 /**
454 * Returns the SQL operator for the given JCR operator type.
455 *
456 * @param string $operator One of the JCR_OPERATOR_* constants
457 * @return string an SQL operator
458 */
459 protected function resolveOperator($operator) {
460 switch ($operator) {
461 case self::OPERATOR_EQUAL_TO_NULL:
462 $operator = 'IS';
463 break;
464 case self::OPERATOR_NOT_EQUAL_TO_NULL:
465 $operator = 'IS NOT';
466 break;
467 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
468 $operator = '=';
469 break;
470 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
471 $operator = '!=';
472 break;
473 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
474 $operator = '<';
475 break;
476 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
477 $operator = '<=';
478 break;
479 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
480 $operator = '>';
481 break;
482 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
483 $operator = '>=';
484 break;
485 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
486 $operator = 'LIKE';
487 break;
488 default:
489 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
490 }
491
492 return $operator;
493 }
494
495 /**
496 * Replace query placeholders in a query part by the given
497 * parameters.
498 *
499 * @param string $sqlString The query part with placeholders
500 * @param array $parameters The parameters
501 * @return string The query part with replaced placeholders
502 */
503 protected function replacePlaceholders(&$sqlString, array $parameters) {
504 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);
505 $offset = 0;
506 foreach ($parameters as $parameter) {
507 $markPosition = strpos($sqlString, '?', $offset);
508 if ($markPosition !== FALSE) {
509 if ($parameter === NULL) {
510 $parameter = 'NULL';
511 } else {
512 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
513 }
514 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
515 }
516 $offset = $markPosition + strlen($parameter);
517 }
518 }
519
520 /**
521 * Builds the enable fields statement
522 *
523 * @param string $tableName The database table name
524 * @param array &$sql The query parts
525 * @return void
526 */
527 protected function addEnableFieldsStatement($tableName, array &$sql) {
528 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
529 if (TYPO3_MODE === 'FE') {
530 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
531 } else { // TYPO3_MODE === 'BE'
532 $statement = t3lib_BEfunc::deleteClause($tableName);
533 $statement .= t3lib_BEfunc::BEenableFields($tableName);
534 }
535 if(!empty($statement)) {
536 $statement = substr($statement, 5);
537 $sql['additionalWhereClause'][] = $statement;
538 }
539 }
540 }
541
542 /**
543 * Builds the page ID checking statement
544 *
545 * @param string $tableName The database table name
546 * @param array &$sql The query parts
547 * @return void
548 */
549 protected function addPageIdStatement($tableName, array &$sql) {
550 $columns = $this->databaseHandle->admin_get_fields($tableName);
551 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $columns)) {
552 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
553 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
554 }
555 }
556
557 /**
558 * Transforms orderings into SQL.
559 *
560 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
561 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
562 * @param array &$sql The query parts
563 * @return void
564 */
565 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
566 foreach ($orderings as $ordering) {
567 $operand = $ordering->getOperand();
568 $order = $ordering->getOrder();
569 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
570 switch ($order) {
571 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
572 $order = 'ASC';
573 break;
574 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
575 $order = 'DESC';
576 break;
577 default:
578 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
579 }
580 $tableName = $operand->getSelectorName();
581 $className = '';
582 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
583 $className = $source->getNodeTypeName();
584 }
585 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
586 if (strlen($tableName) > 0) {
587 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
588 } else {
589 $sql['orderings'][] = $columnName . ' ' . $order;
590 }
591 }
592 }
593 }
594
595 /**
596 * Transforms limit and offset into SQL
597 *
598 * @param int $limit
599 * @param int $offset
600 * @param array &$sql
601 * @return void
602 */
603 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
604 if ($limit !== NULL && $offset !== NULL) {
605 $sql['limit'] = $offset . ', ' . $limit;
606 } elseif ($limit !== NULL) {
607 $sql['limit'] = $limit;
608 }
609 }
610
611 /**
612 * Transforms a Resource from a database query to an array of rows. Performs the language and
613 * workspace overlay before.
614 *
615 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
616 * @param resource &$sql The resource
617 * @return array The result as an array of rows (tuples)
618 */
619 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $res) {
620 $rows = array();
621 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
622 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
623 // FIXME The overlay is only performed if we query a single table; no joins
624 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
625 }
626 if (is_array($row)) {
627 // TODO Check if this is necessary, maybe the last line is enough
628 $arrayKeys = range(0,count($row));
629 array_fill_keys($arrayKeys, $row);
630 $rows[] = $row;
631 }
632 }
633 return $rows;
634 }
635
636 /**
637 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
638 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
639 *
640 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
641 * @param array $row The row array (as reference)
642 * @param string $languageUid The language id
643 * @param string $workspaceUidUid The workspace id
644 * @return void
645 */
646 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
647 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
648 if (TYPO3_MODE == 'FE') {
649 if (is_object($GLOBALS['TSFE'])) {
650 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
651 if ($languageUid === NULL) {
652 $languageUid = $GLOBALS['TSFE']->sys_language_content;
653 }
654 } else {
655 require_once(PATH_t3lib . 'class.t3lib_page.php');
656 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
657 if ($languageUid === NULL) {
658 $languageUid = intval(t3lib_div::_GP('L'));
659 }
660 }
661 if ($workspaceUid !== NULL) {
662 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
663 }
664 } else {
665 require_once(PATH_t3lib . 'class.t3lib_page.php');
666 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
667 if ($workspaceUid === NULL) {
668 $workspaceUid = $GLOBALS['BE_USER']->workspace;
669 }
670 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
671 }
672 }
673
674 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
675 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
676 // TODO Skip if empty languageoverlay (languagevisibility)
677 return $row;
678 }
679
680 /**
681 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
682 *
683 * @return void
684 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
685 */
686 protected function checkSqlErrors() {
687 $error = $this->databaseHandle->sql_error();
688 if ($error !== '') {
689 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
690 }
691 }
692
693 /**
694 * Clear the TYPO3 page cache for the given record.
695 * If the record lies on a page, then we clear the cache of this page.
696 * If the record has no PID column, we clear the cache of the current page as best-effort.
697 *
698 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
699 *
700 * @param $tableName Table name of the record
701 * @param $uid UID of the record
702 * @return void
703 */
704 protected function clearPageCache($tableName, $uid) {
705 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
706 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
707 } else {
708 // if disabled, return
709 return;
710 }
711
712 $pageIdsToClear = array();
713 $storagePage = NULL;
714
715 $columns = $this->databaseHandle->admin_get_fields($tableName);
716 if (array_key_exists('pid', $columns)) {
717 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
718 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
719 $storagePage = $row['pid'];
720 $pageIdsToClear[] = $storagePage;
721 }
722 } elseif (isset($GLOBALS['TSFE'])) {
723 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
724 $storagePage = $GLOBALS['TSFE']->id;
725 $pageIdsToClear[] = $storagePage;
726 }
727
728
729 if ($storagePage === NULL) {
730 return;
731 }
732
733 $pageTSConfig = t3lib_BEfunc::getPagesTSconfig($storagePage);
734 if (isset($pageTSConfig['TCEMAIN.']['clearCacheCmd'])) {
735 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($pageTSConfig['TCEMAIN.']['clearCacheCmd']),1);
736 $clearCacheCommands = array_unique($clearCacheCommands);
737 foreach ($clearCacheCommands as $clearCacheCommand) {
738 if (t3lib_div::testInt($clearCacheCommand)) {
739 $pageIdsToClear[] = $clearCacheCommand;
740 }
741 }
742 }
743
744 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
745 }
746 }
747
748 ?>