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 $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
163 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
166 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
167 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
168 $this->replacePlaceholders($statement, $identifier);
170 $this->clearPageCache($tableName, $uid, $isRelation);
172 $returnValue = $this->databaseHandle
->sql_query($statement);
173 $this->checkSqlErrors();
178 * Fetches row data from the database
180 * @param string $identifier The Identifier of the row to fetch
181 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
182 * @return array|FALSE
184 public function getRowByIdentifier($tableName, array $identifier) {
185 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
186 $this->replacePlaceholders($statement, $identifier);
187 // debug($statement,-2);
188 $res = $this->databaseHandle
->sql_query($statement);
189 $this->checkSqlErrors();
190 $row = $this->databaseHandle
->sql_fetch_assoc($res);
191 if ($row !== FALSE) {
198 protected function parseIdentifier(array $identifier) {
199 $fieldNames = array_keys($identifier);
200 $suffixedFieldNames = array();
201 foreach ($fieldNames as $fieldName) {
202 $suffixedFieldNames[] = $fieldName . '=?';
204 return implode(' AND ', $suffixedFieldNames);
208 * Returns an array with tuples matching the query.
210 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
211 * @return array The matching tuples
213 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query) {
214 $constraint = $query->getConstraint();
215 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface
) {
216 if ($constraint->getLanguage() === Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
::TYPO3_SQL_MYSQL
) {
217 $statement = $constraint->getStatement();
218 $parameters = $query->getBoundVariableValues();
220 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
223 $parameters = array();
224 $statement = $this->getStatement($query, $parameters);
226 $this->replacePlaceholders($statement, $parameters);
227 // debug($statement,-2);
228 $result = $this->databaseHandle
->sql_query($statement);
229 $this->checkSqlErrors();
230 return $this->getRowsFromResult($query->getSource(), $result);
234 * Returns the number of tuples matching the query.
236 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
237 * @return int The number of matching tuples
239 public function countRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query) {
240 $constraint = $query->getConstraint();
241 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);
242 $parameters = array();
243 $statementParts = $this->parseQuery($query, $parameters);
244 $statementParts['fields'] = array('COUNT(*)');
245 $statement = $this->buildStatement($statementParts, $parameters);
246 $this->replacePlaceholders($statement, $parameters);
247 $result = $this->databaseHandle
->sql_query($statement);
248 $this->checkSqlErrors();
249 $tuples = $this->getRowsFromResult($query->getSource(), $result);
250 return current(current($tuples));
254 * Returns the statement, ready to be executed.
256 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
257 * @return string The SQL statement
259 public function getStatement(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, array &$parameters) {
260 $statementParts = $this->parseQuery($query, $parameters);
261 $statement = $this->buildStatement($statementParts);
266 * Parses the query and returns the SQL statement parts.
268 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
269 * @return array The SQL statement parts
271 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, array &$parameters) {
273 $sql['tables'] = array();
274 $sql['fields'] = array();
275 $sql['where'] = array();
276 $sql['additionalWhereClause'] = array();
277 $sql['orderings'] = array();
278 $sql['limit'] = array();
280 $source = $query->getSource();
282 $this->parseSource($query, $source, $sql, $parameters);
283 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters, $query->getBoundVariableValues());
284 $this->parseOrderings($query->getOrderings(), $source, $sql);
285 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
291 * Returns the statement, ready to be executed.
293 * @param array $sql The SQL statement parts
294 * @return string The SQL statement
296 public function buildStatement(array $sql) {
297 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
298 if (!empty($sql['where'])) {
299 $statement .= ' WHERE ' . implode('', $sql['where']);
300 if (!empty($sql['additionalWhereClause'])) {
301 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
303 } elseif (!empty($sql['additionalWhereClause'])) {
304 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
306 if (!empty($sql['orderings'])) {
307 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
309 if (!empty($sql['limit'])) {
310 $statement .= ' LIMIT ' . $sql['limit'];
316 * Checks if a Value Object equal to the given Object exists in the data base
318 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
319 * @return array The matching uid
321 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject
$object) {
323 $parameters = array();
324 $dataMap = $this->dataMapper
->getDataMap(get_class($object));
325 $properties = $object->_getProperties();
326 foreach ($properties as $propertyName => $propertyValue) {
327 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
328 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
329 if ($propertyValue === NULL) {
330 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
332 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
333 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
338 $sql['additionalWhereClause'] = array();
340 $tableName = $dataMap->getTableName();
341 $this->addEnableFieldsStatement($tableName, $sql);
343 $statement = 'SELECT * FROM ' . $tableName;
344 $statement .= ' WHERE ' . implode(' AND ', $fields);
345 if (!empty($sql['additionalWhereClause'])) {
346 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
348 $this->replacePlaceholders($statement, $parameters);
349 // debug($statement,-2);
350 $res = $this->databaseHandle
->sql_query($statement);
351 $this->checkSqlErrors();
352 $row = $this->databaseHandle
->sql_fetch_assoc($res);
353 if ($row !== FALSE) {
354 return (int)$row['uid'];
361 * Transforms a Query Source into SQL and parameter arrays
363 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
364 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
366 * @param array &$parameters
369 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters) {
370 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
371 $tableName = $source->getSelectorName();
372 $sql['fields'][] = $tableName . '.*';
373 $sql['tables'][] = $tableName;
374 $querySettings = $query->getQuerySettings();
375 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface
) {
376 if ($querySettings->getRespectEnableFields()) {
377 $this->addEnableFieldsStatement($tableName, $sql);
379 if ($querySettings->getRespectStoragePage()) {
380 $this->addPageIdStatement($tableName, $sql);
383 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
384 $this->parseJoin($query, $source, $sql);
389 * Transforms a Join into SQL and parameter arrays
391 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
392 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
393 * @param array &$sql The query parts
396 protected function parseJoin(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query, Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql) {
397 $leftSource = $join->getLeft();
398 $leftTableName = $leftSource->getSelectorName();
399 $rightSource = $join->getRight();
400 $rightTableName = $rightSource->getSelectorName();
402 $sql['fields'][] = $leftTableName . '.*';
403 $sql['fields'][] = $rightTableName . '.*';
405 // TODO Implement support for different join types and nested joins
406 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
408 $joinCondition = $join->getJoinCondition();
409 // TODO Check the parsing of the join
410 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
411 // TODO Discuss, if we should use $leftSource instead of $selector1Name
412 $column1Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
413 $column2Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
414 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
416 // TODO Implement childtableWhere
418 $querySettings = $query->getQuerySettings();
419 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface
) {
420 if ($querySettings->getRespectEnableFields()) {
421 $this->addEnableFieldsStatement($leftTableName, $sql);
422 $this->addEnableFieldsStatement($rightTableName, $sql);
424 if ($querySettings->getRespectStoragePage()) {
425 $this->addPageIdStatement($leftTableName, $sql);
426 $this->addPageIdStatement($rightTableName, $sql);
432 * Transforms a constraint into SQL and parameter arrays
434 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
435 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
436 * @param array &$sql The query parts
437 * @param array &$parameters The parameters that will replace the markers
438 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
441 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, array $boundVariableValues) {
442 if ($constraint === NULL) return;
443 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
444 $sql['where'][] = '(';
445 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
446 $sql['where'][] = ' AND ';
447 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
448 $sql['where'][] = ')';
449 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
450 $sql['where'][] = '(';
451 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
452 $sql['where'][] = ' OR ';
453 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
454 $sql['where'][] = ')';
455 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
456 $sql['where'][] = 'NOT (';
457 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters, $boundVariableValues);
458 $sql['where'][] = ')';
459 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
460 $this->parseComparison($constraint, $source, $sql, $parameters, $boundVariableValues);
461 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface
) {
462 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
467 * Parse a Comparison into SQL and parameter arrays.
469 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
470 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
471 * @param array &$sql SQL query parts to add to
472 * @param array &$parameters Parameters to bind to the SQL
473 * @param array $boundVariableValues The bound variables in the query and their values
476 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, array $boundVariableValues) {
477 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface
)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
479 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
480 $operator = $comparison->getOperator();
481 if ($value === NULL) {
482 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
) {
483 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
484 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
) {
485 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
487 } elseif (is_array($value)) {
488 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
) {
489 $operator = self
::OPERATOR_IN
;
490 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
) {
491 $operator = self
::OPERATOR_NOT_IN
;
494 $parameters[] = $value;
496 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
500 * Parse a DynamicOperand into SQL and parameter arrays.
502 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
503 * @param string $operator One of the JCR_OPERATOR_* constants
504 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
505 * @param array &$sql The query parts
506 * @param array &$parameters The parameters that will replace the markers
507 * @param string $valueFunction an optional SQL function to apply to the operand value
510 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql, array &$parameters, $valueFunction = NULL) {
511 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
512 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
513 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
514 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
515 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
516 $tableName = $operand->getSelectorName();
517 // FIXME Discuss the translation from propertyName to columnName
518 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
519 $className = $source->getNodeTypeName();
523 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
524 $operator = $this->resolveOperator($operator);
526 if ($valueFunction === NULL) {
527 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
529 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
532 $sql['where'][] = $constraintSQL;
537 * Returns the SQL operator for the given JCR operator type.
539 * @param string $operator One of the JCR_OPERATOR_* constants
540 * @return string an SQL operator
542 protected function resolveOperator($operator) {
544 case self
::OPERATOR_EQUAL_TO_NULL
:
547 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
548 $operator = 'IS NOT';
550 case self
::OPERATOR_IN
:
553 case self
::OPERATOR_NOT_IN
:
554 $operator = 'NOT IN';
556 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
:
559 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
:
562 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN
:
565 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO
:
568 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN
:
571 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
574 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LIKE
:
578 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
585 * Replace query placeholders in a query part by the given
588 * @param string $sqlString The query part with placeholders
589 * @param array $parameters The parameters
590 * @return string The query part with replaced placeholders
592 protected function replacePlaceholders(&$sqlString, array $parameters) {
593 // TODO profile this method again
594 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);
596 foreach ($parameters as $parameter) {
597 $markPosition = strpos($sqlString, '?', $offset);
598 if ($markPosition !== FALSE) {
599 if ($parameter === NULL) {
601 } elseif (is_array($parameter)) {
603 foreach ($parameter as $item) {
604 $items[] = $this->databaseHandle
->fullQuoteStr($item, 'foo');
606 $parameter = '(' . implode(',', $items) . ')';
608 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
610 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition +
1);
612 $offset = $markPosition +
strlen($parameter);
617 * Builds the enable fields statement
619 * @param string $tableName The database table name
620 * @param array &$sql The query parts
623 protected function addEnableFieldsStatement($tableName, array &$sql) {
624 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
625 if (TYPO3_MODE
=== 'FE') {
626 $statement = $GLOBALS['TSFE']->sys_page
->enableFields($tableName);
627 } else { // TYPO3_MODE === 'BE'
628 $statement = t3lib_BEfunc
::deleteClause($tableName);
629 $statement .= t3lib_BEfunc
::BEenableFields($tableName);
631 if(!empty($statement)) {
632 $statement = substr($statement, 5);
633 $sql['additionalWhereClause'][] = $statement;
639 * Builds the page ID checking statement
641 * @param string $tableName The database table name
642 * @param array &$sql The query parts
645 protected function addPageIdStatement($tableName, array &$sql) {
646 if (empty($this->tableInformationCache
[$tableName]['columnNames'])) {
647 $this->tableInformationCache
[$tableName]['columnNames'] = $this->databaseHandle
->admin_get_fields($tableName);
649 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache
[$tableName]['columnNames'])) {
650 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
651 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div
::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
656 * Transforms orderings into SQL.
658 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
659 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
660 * @param array &$sql The query parts
663 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface
$source, array &$sql) {
664 foreach ($orderings as $ordering) {
665 $operand = $ordering->getOperand();
666 $order = $ordering->getOrder();
667 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue
) {
669 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
672 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
676 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
678 $tableName = $operand->getSelectorName();
680 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
681 $className = $source->getNodeTypeName();
683 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
684 if (strlen($tableName) > 0) {
685 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
687 $sql['orderings'][] = $columnName . ' ' . $order;
694 * Transforms limit and offset into SQL
701 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
702 if ($limit !== NULL && $offset !== NULL) {
703 $sql['limit'] = $offset . ', ' . $limit;
704 } elseif ($limit !== NULL) {
705 $sql['limit'] = $limit;
710 * Transforms a Resource from a database query to an array of rows. Performs the language and
711 * workspace overlay before.
713 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
714 * @param resource $result The result
715 * @return array The result as an array of rows (tuples)
717 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface
$source, $result) {
719 while ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
720 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
721 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
722 } else if ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
723 $row = $this->doLanguageAndWorkspaceOverlay($source->getLeft()->getSelectorName(), $row);
725 if (is_array($row)) {
726 // TODO Check if this is necessary, maybe the last line is enough
727 $arrayKeys = range(0,count($row));
728 array_fill_keys($arrayKeys, $row);
736 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
737 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
739 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
740 * @param array $row The row array (as reference)
741 * @param string $languageUid The language id
742 * @param string $workspaceUidUid The workspace id
745 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
746 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
747 if (TYPO3_MODE
== 'FE') {
748 if (is_object($GLOBALS['TSFE'])) {
749 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
751 require_once(PATH_t3lib
. 'class.t3lib_page.php');
752 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
755 require_once(PATH_t3lib
. 'class.t3lib_page.php');
756 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
759 if (is_object($GLOBALS['TSFE'])) {
760 if ($languageUid === NULL) {
761 $languageUid = $GLOBALS['TSFE']->sys_language_uid
;
763 if ($workspaceUid !== NULL) {
764 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
767 if ($languageUid === NULL) {
768 $languageUid = intval(t3lib_div
::_GP('L'));
770 if ($workspaceUid === NULL) {
771 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
773 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
775 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
776 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
777 // TODO Skip if empty languageoverlay (languagevisibility)
782 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
785 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
787 protected function checkSqlErrors() {
788 $error = $this->databaseHandle
->sql_error();
790 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
795 * Clear the TYPO3 page cache for the given record.
796 * If the record lies on a page, then we clear the cache of this page.
797 * If the record has no PID column, we clear the cache of the current page as best-effort.
799 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
801 * @param $tableName Table name of the record
802 * @param $uid UID of the record
805 protected function clearPageCache($tableName, $uid) {
806 $extbaseSettings = Tx_Extbase_Dispatcher
::getExtbaseFrameworkConfiguration();
807 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
809 // if disabled, return
813 $pageIdsToClear = array();
816 $columns = $this->databaseHandle
->admin_get_fields($tableName);
817 if (array_key_exists('pid', $columns)) {
818 $result = $this->databaseHandle
->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
819 if ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
820 $storagePage = $row['pid'];
821 $pageIdsToClear[] = $storagePage;
823 } elseif (isset($GLOBALS['TSFE'])) {
824 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
825 $storagePage = $GLOBALS['TSFE']->id
;
826 $pageIdsToClear[] = $storagePage;
829 if ($storagePage === NULL) {
832 if (!isset($this->pageTSConfigCache
[$storagePage])) {
833 $this->pageTSConfigCache
[$storagePage] = t3lib_BEfunc
::getPagesTSconfig($storagePage);
835 if (isset($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
836 $clearCacheCommands = t3lib_div
::trimExplode(',',strtolower($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
837 $clearCacheCommands = array_unique($clearCacheCommands);
838 foreach ($clearCacheCommands as $clearCacheCommand) {
839 if (t3lib_div
::testInt($clearCacheCommand)) {
840 $pageIdsToClear[] = $clearCacheCommand;
845 // 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
846 Tx_Extbase_Utility_Cache
::clearPageCache($pageIdsToClear);