2 /***************************************************************
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 team.
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.
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
32 * @subpackage Persistence\Storage
35 class Tx_Extbase_Persistence_Storage_Typo3DbBackend
implements Tx_Extbase_Persistence_Storage_BackendInterface
, t3lib_Singleton
{
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';
43 * The TYPO3 database object
47 protected $databaseHandle;
50 * @var Tx_Extbase_Persistence_DataMapper
52 protected $dataMapper;
55 * The TYPO3 page select object. Used for language and workspace overlay
57 * @var t3lib_pageSelect
59 protected $pageSelectObject;
62 * A first-level TypoScript configuration cache
66 protected $pageTSConfigCache = array();
69 * Caches information about tables (esp. the existing column names)
73 protected $tableInformationCache = array();
76 * Constructs this Storage Backend instance
78 * @param t3lib_db $databaseHandle The database handle
80 public function __construct($databaseHandle) {
81 $this->databaseHandle
= $databaseHandle;
85 * Injects the DataMapper to map nodes to objects
87 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
90 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper
$dataMapper) {
91 $this->dataMapper
= $dataMapper;
95 * Adds a row to the storage
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
102 public function addRow($tableName, array $row, $isRelation = FALSE) {
105 $parameters = array();
106 if (isset($row['uid'])) {
109 foreach ($row as $columnName => $value) {
110 $fields[] = $columnName;
112 $parameters[] = $value;
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();
122 $this->clearPageCache($tableName, $uid);
128 * Updates a row in the storage
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
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'];
140 $parameters = array();
141 foreach ($row as $columnName => $value) {
142 $fields[] = $columnName . '=?';
143 $parameters[] = $value;
145 $parameters[] = $uid;
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();
153 $this->clearPageCache($tableName, $uid);
159 * Deletes a row in the storage
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
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 . '=?';
172 $parameters = array_values($identifyer);
173 $statement = 'DELETE FROM ' . $tableName;
174 $statement .= ' WHERE ' . implode(' AND ', $suffixedFieldNames);
175 $this->replacePlaceholders($statement, $parameters);
177 $this->clearPageCache($tableName, $uid, $isRelation);
179 $returnValue = $this->databaseHandle
->sql_query($statement);
180 $this->checkSqlErrors();
185 * Fetches row data from the database
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
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) {
207 * Returns an array with tuples matching the query.
209 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
210 * @return array The matching tuples
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();
219 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
222 $parameters = array();
223 $statement = $this->getStatement($query, $parameters);
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);
233 * Returns the number of tuples matching the query.
235 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
236 * @return int The number of matching tuples
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));
253 * Returns the statement, ready to be executed.
255 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
256 * @return string The SQL statement
258 public function getStatement(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, array &$parameters) {
259 $statementParts = $this->parseQuery($query, $parameters);
260 $statement = $this->buildStatement($statementParts);
265 * Parses the query and returns the SQL statement parts.
267 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
268 * @return array The SQL statement parts
270 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, array &$parameters) {
272 $sql['tables'] = array();
273 $sql['fields'] = array();
274 $sql['where'] = array();
275 $sql['additionalWhereClause'] = array();
276 $sql['orderings'] = array();
277 $sql['limit'] = array();
279 $source = $query->getSource();
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);
290 * Returns the statement, ready to be executed.
292 * @param array $sql The SQL statement parts
293 * @return string The SQL statement
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']);
302 } elseif (!empty($sql['additionalWhereClause'])) {
303 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
305 if (!empty($sql['orderings'])) {
306 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
308 if (!empty($sql['limit'])) {
309 $statement .= ' LIMIT ' . $sql['limit'];
315 * Checks if a Value Object equal to the given Object exists in the data base
317 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
318 * @return array The matching uid
320 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject
$object) {
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);
333 $sql['additionalWhereClause'] = array();
335 $tableName = $dataMap->getTableName();
336 $this->addEnableFieldsStatement($tableName, $sql);
338 $statement = 'SELECT * FROM ' . $tableName;
339 $statement .= ' WHERE ' . implode(' AND ', $fields);
340 if (!empty($sql['additionalWhereClause'])) {
341 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
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'];
356 * Transforms a Query Source into SQL and parameter arrays
358 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
359 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
361 * @param array &$parameters
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);
374 if ($querySettings->getRespectStoragePage()) {
375 $this->addPageIdStatement($tableName, $sql);
378 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
379 $this->parseJoin($query, $source, $sql);
384 * Transforms a Join into SQL and parameter arrays
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
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();
397 $sql['fields'][] = $leftTableName . '.*';
398 $sql['fields'][] = $rightTableName . '.*';
400 // TODO Implement support for different join types and nested joins
401 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
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;
411 // TODO Implement childtableWhere
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);
419 if ($querySettings->getRespectStoragePage()) {
420 $this->addPageIdStatement($leftTableName, $sql);
421 $this->addPageIdStatement($rightTableName, $sql);
427 * Transforms a constraint into SQL and parameter arrays
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)
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);
462 * Parse a Comparison into SQL and parameter arrays.
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
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);
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
;
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
;
489 $parameters[] = $value;
491 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
495 * Parse a DynamicOperand into SQL and parameter arrays.
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
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();
518 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
519 $operator = $this->resolveOperator($operator);
521 if ($valueFunction === NULL) {
522 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
524 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
527 $sql['where'][] = $constraintSQL;
532 * Returns the SQL operator for the given JCR operator type.
534 * @param string $operator One of the JCR_OPERATOR_* constants
535 * @return string an SQL operator
537 protected function resolveOperator($operator) {
539 case self
::OPERATOR_EQUAL_TO_NULL
:
542 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
543 $operator = 'IS NOT';
545 case self
::OPERATOR_IN
:
548 case self
::OPERATOR_NOT_IN
:
549 $operator = 'NOT IN';
551 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
:
554 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
:
557 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN
:
560 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO
:
563 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN
:
566 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
569 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LIKE
:
573 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
580 * Replace query placeholders in a query part by the given
583 * @param string $sqlString The query part with placeholders
584 * @param array $parameters The parameters
585 * @return string The query part with replaced placeholders
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);
591 foreach ($parameters as $parameter) {
592 $markPosition = strpos($sqlString, '?', $offset);
593 if ($markPosition !== FALSE) {
594 if ($parameter === NULL) {
596 } elseif (is_array($parameter)) {
598 foreach ($parameter as $item) {
599 $items[] = $this->databaseHandle
->fullQuoteStr($item, 'foo');
601 $parameter = '(' . implode(',', $items) . ')';
603 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
605 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
607 $offset = $markPosition +
strlen($parameter);
612 * Builds the enable fields statement
614 * @param string $tableName The database table name
615 * @param array &$sql The query parts
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);
626 if(!empty($statement)) {
627 $statement = substr($statement, 5);
628 $sql['additionalWhereClause'][] = $statement;
634 * Builds the page ID checking statement
636 * @param string $tableName The database table name
637 * @param array &$sql The query parts
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);
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'])) . ')';
651 * Transforms orderings into SQL.
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
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
) {
664 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
667 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
671 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
673 $tableName = $operand->getSelectorName();
675 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
676 $className = $source->getNodeTypeName();
678 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
679 if (strlen($tableName) > 0) {
680 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
682 $sql['orderings'][] = $columnName . ' ' . $order;
689 * Transforms limit and offset into SQL
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;
705 * Transforms a Resource from a database query to an array of rows. Performs the language and
706 * workspace overlay before.
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)
712 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $result) {
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);
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);
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.
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
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
;
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'));
754 if ($workspaceUid !== NULL) {
755 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
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
;
763 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
767 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
768 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
769 // TODO Skip if empty languageoverlay (languagevisibility)
774 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
777 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
779 protected function checkSqlErrors() {
780 $error = $this->databaseHandle
->sql_error();
782 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
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.
791 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
793 * @param $tableName Table name of the record
794 * @param $uid UID of the record
797 protected function clearPageCache($tableName, $uid) {
798 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
799 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
801 // if disabled, return
805 $pageIdsToClear = array();
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;
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;
821 if ($storagePage === NULL) {
824 if (!isset($this->pageTSConfigCache
[$storagePage])) {
825 $this->pageTSConfigCache
[$storagePage] = t3lib_BEfunc
::getPagesTSconfig($storagePage);
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;
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);