[~BUG] Extbase (Persistence): The findByFooBar maps the property name to column name...
[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 * TRUE if automatic cache clearing in TCEMAIN should be done on insert/update/delete, FALSE otherwise.
61 *
62 * @var boolean
63 */
64 protected $automaticCacheClearing = FALSE;
65
66 /**
67 * Constructs this Storage Backend instance
68 *
69 * @param t3lib_db $databaseHandle The database handle
70 */
71 public function __construct($databaseHandle) {
72 $this->databaseHandle = $databaseHandle;
73 }
74
75 /**
76 * Injects the DataMapper to map nodes to objects
77 *
78 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
79 * @return void
80 */
81 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
82 $this->dataMapper = $dataMapper;
83 }
84
85 /**
86 * Set the automatic cache clearing flag.
87 * If TRUE, then inserted/updated/deleted records trigger a TCEMAIN cache clearing.
88 *
89 * @param $automaticCacheClearing boolean if TRUE, enables automatic cache clearing
90 * @return void
91
92 */
93 public function setAutomaticCacheClearing($automaticCacheClearing) {
94 $this->automaticCacheClearing = (boolean)$automaticCacheClearing;
95 }
96
97 /**
98 * Adds a row to the storage
99 *
100 * @param string $tableName The database table name
101 * @param array $row The row to be inserted
102 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
103 * @return int The uid of the inserted row
104 */
105 public function addRow($tableName, array $row, $isRelation = FALSE) {
106 $fields = array();
107 $values = array();
108 $parameters = array();
109 unset($row['uid']); // TODO Check if the offset exists
110 foreach ($row as $columnName => $value) {
111 $fields[] = $columnName;
112 $values[] = '?';
113 $parameters[] = $value;
114 }
115
116 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
117 $this->replacePlaceholders($sqlString, $parameters);
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 $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
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 $uid The uid of the row to be deleted
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, $uid, $isRelation = FALSE) {
167 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
168 $this->replacePlaceholders($sqlString, array((int)$uid));
169 if (!$isRelation) {
170 $this->clearPageCache($tableName, $uid, $isRelation);
171 }
172 $returnValue = $this->databaseHandle->sql_query($sqlString);
173 $this->checkSqlErrors();
174 return $returnValue;
175 }
176
177 /**
178 * Returns an array with tuples matching the query.
179 *
180 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
181 * @return array The matching tuples
182 */
183 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
184 $statement = $this->parseQuery($query);
185 $result = $this->databaseHandle->sql_query($statement);
186 $this->checkSqlErrors();
187 if ($result) {
188 $tuples = $this->getRowsFromResult($query->getSource(), $result);
189 }
190
191 return $tuples;
192 }
193
194 /**
195 * Returns an array with tuples matching the query.
196 *
197 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
198 * @return array The matching tuples
199 */
200 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
201 $statement = '';
202 $parameters = array();
203 $constraint = $query->getConstraint();
204 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) {
205 if ($constraint->getLanguage() === Tx_Extbase_Persistence_QOM_QueryObjectModelInterface::TYPO3_SQL_MYSQL) {
206 $statement = $constraint->getStatement();
207 $parameters= $query->getBoundVariableValues();
208 } else {
209 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
210 }
211 } else {
212 $sql = array();
213 $sql['tables'] = array();
214 $sql['fields'] = array();
215 $sql['where'] = array();
216 $sql['additionalWhereClause'] = array();
217 $sql['orderings'] = array();
218 $sql['limit'] = array();
219 $tuples = array();
220
221 $source = $query->getSource();
222 $this->parseSource($query, $source, $sql, $parameters);
223
224 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
225
226 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters, $query->getBoundVariableValues());
227
228 if (!empty($sql['where'])) {
229 $statement .= ' WHERE ' . implode('', $sql['where']);
230 if (!empty($sql['additionalWhereClause'])) {
231 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
232 }
233 } elseif (!empty($sql['additionalWhereClause'])) {
234 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
235 }
236
237 $this->parseOrderings($query->getOrderings(), $source, $sql, $parameters, $query->getBoundVariableValues());
238 if (!empty($sql['orderings'])) {
239 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
240 }
241
242 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
243 if (!empty($sql['limit'])) {
244 $statement .= ' LIMIT ' . $sql['limit'];
245 }
246 }
247
248 $this->replacePlaceholders($statement, $parameters);
249
250 return $statement;
251 }
252
253 /**
254 * Checks if a Value Object equal to the given Object exists in the data base
255 *
256 * @param array $properties The properties of the Value Object
257 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
258 * @return array The matching tuples
259 */
260 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap $dataMap) {
261 $fields = array();
262 $parameters = array();
263 foreach ($properties as $propertyName => $propertyValue) {
264 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
265 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
266 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
267 }
268 }
269
270 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode(' AND ', $fields);
271 $this->replacePlaceholders($sqlString, $parameters);
272 $res = $this->databaseHandle->sql_query($sqlString);
273 $this->checkSqlErrors();
274 $row = $this->databaseHandle->sql_fetch_assoc($res);
275 if ($row !== FALSE) {
276 return $row['uid'];
277 } else {
278 return FALSE;
279 }
280 }
281
282 /**
283 * Transforms a Query Source into SQL and parameter arrays
284 *
285 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
286 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
287 * @param array &$sql
288 * @param array &$parameters
289 * @return void
290 */
291 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
292 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
293 $tableName = $source->getSelectorName();
294 $sql['fields'][] = $tableName . '.*';
295 $sql['tables'][] = $tableName;
296 $querySettings = $query->getQuerySettings();
297 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
298 if ($querySettings->getRespectEnableFields()) {
299 $this->addEnableFieldsStatement($tableName, $sql);
300 }
301 if ($querySettings->getRespectStoragePage()) {
302 $this->addPageIdStatement($tableName, $sql);
303 }
304 }
305 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
306 $this->parseJoin($query, $source, $sql, $parameters);
307 }
308 }
309
310 /**
311 * Transforms a Join into SQL and parameter arrays
312 *
313 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
314 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
315 * @param array &$sql
316 * @param array &$parameters
317 * @return void
318 */
319 protected function parseJoin(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql, array &$parameters) {
320 $leftSource = $join->getLeft();
321 $leftTableName = $leftSource->getSelectorName();
322 $rightSource = $join->getRight();
323 $rightTableName = $rightSource->getSelectorName();
324
325 $sql['fields'][] = $leftTableName . '.*';
326 $sql['fields'][] = $rightTableName . '.*';
327
328 // TODO Implement support for different join types and nested joins
329 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
330
331 $joinCondition = $join->getJoinCondition();
332 // TODO Check the parsing of the join
333 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
334 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
335 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
336 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
337 }
338 // TODO Implement childtableWhere
339
340 $querySettings = $query->getQuerySettings();
341 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
342 if ($querySettings->getRespectEnableFields()) {
343 $this->addEnableFieldsStatement($leftTableName, $sql);
344 $this->addEnableFieldsStatement($rightTableName, $sql);
345 }
346 if ($querySettings->getRespectStoragePage()) {
347 $this->addPageIdStatement($leftTableName, $sql);
348 $this->addPageIdStatement($rightTableName, $sql);
349 }
350 }
351 }
352
353 /**
354 * Transforms a constraint into SQL and parameter arrays
355 *
356 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
357 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
358 * @param array &$sql
359 * @param array &$parameters
360 * @param array $boundVariableValues
361 * @return void
362 */
363 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
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 SQL query parts to add to
423 * @param array &$parameters
424 * @param string $valueFunction an aoptional 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, $sql, $parameters, 'LOWER');
430 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
431 $this->parseDynamicOperand($operand->getOperand(), $operator, $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 $queryPart 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 = "'" . $parameter . "'"; // TODO Discuss: Do we need quotation?
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 = substr($GLOBALS['TSFE']->sys_page->enableFields($tableName), 5);
531 } else { // TYPO3_MODE === 'BE'
532 $statement = substr(t3lib_BEfunc::BEenableFields($tableName), 5);
533 }
534 if(!empty($statement)) {
535 $sql['additionalWhereClause'][] = $statement;
536 }
537 }
538 }
539
540 /**
541 * Builds the page ID checking statement
542 *
543 * @param string $tableName The database table name
544 * @param array &$sql The query parts
545 * @return void
546 */
547 protected function addPageIdStatement($tableName, array &$sql) {
548 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
549 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
550 $extbaseSettings = Tx_Extbase_Dispatcher::getSettings();
551 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseSettings['storagePid'])) . ')';
552 }
553 }
554
555 /**
556 * Transforms orderings into SQL
557 *
558 * @param array $orderings
559 * @param array &$sql
560 * @param array &$parameters
561 * @param array $boundVariableValues
562 * @return void
563 */
564 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
565 foreach ($orderings as $ordering) {
566 $operand = $ordering->getOperand();
567 $order = $ordering->getOrder();
568 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
569 switch ($order) {
570 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
571 $order = 'ASC';
572 break;
573 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
574 $order = 'DESC';
575 break;
576 default:
577 throw new Tx_Extbase_Persistence_Exception('Unsupported order encountered.', 1242816074);
578 }
579 $columnName = $this->dataMapper->convertPropertyNameToColumnName($ordering->getOperand()->getPropertyName(), $source->getNodeTypeName());
580 $sql['orderings'][] = $columnName . ' ' . $order;
581 }
582 }
583 }
584
585 /**
586 * Transforms limit and offset into SQL
587 *
588 * @param int $limit
589 * @param int $offset
590 * @param array &$sql
591 * @return void
592 */
593 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
594 if ($limit !== NULL && $offset !== NULL) {
595 $sql['limit'] = $offset . ', ' . $limit;
596 } elseif ($limit !== NULL) {
597 $sql['limit'] = $limit;
598 }
599 }
600
601 /**
602 * Transforms a Resource from a database query to an array of rows. Performs the language and
603 * workspace overlay before.
604 *
605 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
606 *
607 * @return array The result as an array of rows (tuples)
608 */
609 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $res) {
610 $rows = array();
611 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
612 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
613 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
614 }
615 if (is_array($row)) {
616 // TODO Check if this is necessary, maybe the last line is enough
617 $arrayKeys = range(0,count($row));
618 array_fill_keys($arrayKeys, $row);
619 $rows[] = $row;
620 }
621 }
622 return $rows;
623 }
624
625 /**
626 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
627 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
628 *
629 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
630 * @param array $row The row array (as reference)
631 * @param string $languageUid The language id
632 * @param string $workspaceUidUid The workspace id
633 * @return void
634 */
635 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
636 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
637 if (TYPO3_MODE == 'FE') {
638 if (is_object($GLOBALS['TSFE'])) {
639 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
640 if ($languageUid === NULL) {
641 $languageUid = $GLOBALS['TSFE']->sys_language_content;
642 }
643 } else {
644 require_once(PATH_t3lib . 'class.t3lib_page.php');
645 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
646 if ($languageUid === NULL) {
647 $languageUid = intval(t3lib_div::_GP('L'));
648 }
649 }
650 if ($workspaceUid !== NULL) {
651 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
652 }
653 } else {
654 require_once(PATH_t3lib . 'class.t3lib_page.php');
655 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
656 //$this->pageSelectObject->versioningPreview = TRUE;
657 if ($workspaceUid === NULL) {
658 $workspaceUid = $GLOBALS['BE_USER']->workspace;
659 }
660 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
661 }
662 }
663
664 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
665 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
666 // TODO Skip if empty languageoverlay (languagevisibility)
667 return $row;
668 }
669
670 /**
671 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
672 *
673 * @return void
674 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
675 */
676 protected function checkSqlErrors() {
677 $error = $this->databaseHandle->sql_error();
678 if ($error !== '') {
679 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
680 }
681 }
682
683 /**
684 * Clear the TYPO3 page cache for the given record.
685 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
686 *
687 * @param $tableName Table name of the record
688 * @param $uid UID of the record
689 * @return void
690 */
691 protected function clearPageCache($tableName, $uid) {
692 if ($this->automaticCacheClearing !== TRUE) return;
693
694 $pageCache = $GLOBALS['typo3CacheManager']->getCache('cache_pages');
695 $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache('cache_pagesection');
696
697 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
698
699 $pageIdsToClear = array();
700 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
701 $storagePage = $row['pid'];
702 $pageIdsToClear[] = $storagePage;
703 }
704 if (!$storagePage) {
705 return;
706 }
707
708 $pageTSConfig = t3lib_BEfunc::getPagesTSconfig($storagePage);
709 if (isset($pageTSConfig['TCEMAIN.']['clearCacheCmd'])) {
710 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($pageTSConfig['TCEMAIN.']['clearCacheCmd']),1);
711 $clearCacheCommands = array_unique($clearCacheCommands);
712 foreach ($clearCacheCommands as $clearCacheCommand) {
713 if (t3lib_div::testInt($clearCacheCommand)) {
714 $pageIdsToClear[] = $clearCacheCommand;
715 }
716 }
717 }
718
719 foreach ($pageIdsToClear as $pageIdToClear) {
720 $pageCache->flushByTag('pageId_' . $pageIdToClear);
721 $pageSectionCache->flushByTag('pageId_' . $pageIdToClear);
722 }
723 }
724 }
725
726 ?>