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