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
36 class Tx_Extbase_Persistence_Storage_Typo3DbBackend
implements Tx_Extbase_Persistence_Storage_BackendInterface
, t3lib_Singleton
{
39 * The TYPO3 database object
43 protected $databaseHandle;
46 * The TYPO3 page select object. Used for language and workspace overlay
48 * @var t3lib_pageSelect
50 protected $pageSelectObject;
53 * Constructs this Storage Backend instance
55 public function __construct() {
56 $this->databaseHandle
= $GLOBALS['TYPO3_DB'];
60 * Adds a row to the storage
62 * @param string $tableName The database table name
63 * @param array $row The row to be inserted
64 * @return int The uid of the inserted row
66 public function addRow($tableName, array $row) {
69 $parameters = array();
70 unset($row['uid']); // TODO Check if the offset exists
71 foreach ($row as $columnName => $value) {
72 $fields[] = $columnName;
74 $parameters[] = $value;
77 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
78 $this->replacePlaceholders($sqlString, $parameters);
80 $this->databaseHandle
->sql_query($sqlString);
81 return $this->databaseHandle
->sql_insert_id();
85 * Updates a row in the storage
87 * @param string $tableName The database table name
88 * @param array $row The row to be updated
91 public function updateRow($tableName, array $row) {
92 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
93 $uid = (int)$row['uid'];
96 $parameters = array();
97 foreach ($row as $columnName => $value) {
98 $fields[] = $columnName . '=?';
99 $parameters[] = $value;
101 $parameters[] = $uid;
103 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
104 $this->replacePlaceholders($sqlString, $parameters);
106 return $this->databaseHandle
->sql_query($sqlString);
110 * Deletes a row in the storage
112 * @param string $tableName The database table name
113 * @param array $uid The uid of the row to be deleted
116 public function removeRow($tableName, $uid) {
117 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
118 $this->replacePlaceholders($sqlString, array((int)$uid));
119 return $this->databaseHandle
->sql_query($sqlString);
123 * Returns an array with tuples matching the query.
125 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
126 * @return array The matching tuples
128 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface
$query) {
130 $parameters = array();
133 $this->parseSource($query, $sql, $parameters);
134 $sqlString = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
136 $this->parseConstraint($query->getConstraint(), $sql, $parameters, $query->getBoundVariableValues());
137 if (!empty($sql['where'])) {
138 $sqlString .= ' WHERE ' . implode('', $sql['where']) . ' AND ' . implode(' AND ', $sql['enableFields']);
140 $sqlString .= ' WHERE ' . implode(' AND ', $sql['enableFields']);
143 $this->parseOrderings($query->getOrderings(), $sql, $parameters, $query->getBoundVariableValues());
144 if (!empty($sql['orderings'])) {
145 $sqlString .= ' ORDER BY ' . implode(', ', $sql['orderings']);
148 $this->replacePlaceholders($sqlString, $parameters);
150 $result = $this->databaseHandle
->sql_query($sqlString);
152 // TODO Check for selector name
153 $tuples = $this->getRowsFromResult($query->getSelectorName(), $result);
160 * Checks if a Value Object equal to the given Object exists in the data base
162 * @param array $properties The properties of the Value Object
163 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
164 * @return array The matching tuples
166 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap
$dataMap) {
168 $parameters = array();
169 foreach ($properties as $propertyName => $propertyValue) {
170 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
171 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
172 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
176 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode('', $fields);
177 $this->replacePlaceholders($sqlString, $parameters);
178 $res = $this->databaseHandle
->sql_query($sqlString);
179 $row = $this->databaseHandle
->sql_fetch_assoc($res);
180 if ($row !== FALSE) {
188 * Transforms a Query Source into SQL and parameter arrays
190 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
192 * @param array &$parameters
195 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModel
$query, array &$sql, array &$parameters) {
196 $source = $query->getSource();
197 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface
) {
198 $selectorName = $source->getSelectorName();
199 $sql['fields'][] = $selectorName . '.*';
200 $sql['tables'][] = $selectorName;
201 // TODO Should we make the usage of enableFields configurable? And how? Because the Query object and even the QOM should be abstracted from the storage backend.
202 $this->addEnableFieldsStatement($selectorName, $sql);
203 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface
) {
204 $this->parseJoin($source, $sql, $parameters);
209 * Transforms a Join into SQL and parameter arrays
211 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
213 * @param array &$parameters
216 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface
$join, array &$sql, array &$parameters) {
217 $leftSelectorName = $join->getLeft()->getSelectorName();
218 $rightSelectorName = $join->getRight()->getSelectorName();
220 $sql['fields'][] = $leftSelectorName . '.*';
221 $sql['fields'][] = $rightSelectorName . '.*';
223 // TODO Implement support for different join types and nested joins
224 $sql['tables'][] = $leftSelectorName . ' LEFT JOIN ' . $rightSelectorName;
226 $joinCondition = $join->getJoinCondition();
227 // TODO Check the parsing of the join
228 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition
) {
229 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $joinCondition->getProperty1Name() . ' = ' . $joinCondition->getSelector2Name() . '.' . $joinCondition->getProperty2Name();
231 // TODO Implement childtableWhere
233 $this->addEnableFieldsStatement($leftSelectorName, $sql);
234 $this->addEnableFieldsStatement($rightSelectorName, $sql);
238 * Transforms a constraint into SQL and parameter arrays
240 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
242 * @param array &$parameters
243 * @param array $boundVariableValues
246 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface
$constraint = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
247 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface
) {
248 $sql['where'][] = '(';
249 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
250 $sql['where'][] = ' AND ';
251 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
252 $sql['where'][] = ')';
253 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface
) {
254 $sql['where'][] = '(';
255 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
256 $sql['where'][] = ' OR ';
257 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
258 $sql['where'][] = ')';
259 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface
) {
260 $sql['where'][] = '(NOT ';
261 $this->parseConstraint($constraint->getConstraint(), $sql, $parameters, $boundVariableValues);
262 $sql['where'][] = ')';
263 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface
) {
264 $this->parseComparison($constraint, $sql, $parameters, $boundVariableValues);
265 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface
) {
266 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
271 * Parse a Comparison into SQL and parameter arrays.
273 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
274 * @param array &$sql SQL query parts to add to
275 * @param array &$parameters Parameters to bind to the SQL
276 * @param array $boundVariableValues The bound variables in the query and their values
279 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface
$comparison, array &$sql, array &$parameters, array $boundVariableValues) {
280 $this->parseDynamicOperand($comparison->getOperand1(), $comparison->getOperator(), $sql, $parameters);
282 if ($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface
) {
283 $parameters[] = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
288 * Parse a DynamicOperand into SQL and parameter arrays.
290 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
291 * @param string $operator One of the JCR_OPERATOR_* constants
292 * @param array $boundVariableValues
293 * @param array &$parameters
294 * @param string $valueFunction an aoptional SQL function to apply to the operand value
297 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface
$operand, $operator, array &$sql, array &$parameters, $valueFunction = NULL) {
298 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface
) {
299 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'LOWER');
300 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface
) {
301 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'UPPER');
302 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface
) {
303 $selectorName = $operand->getSelectorName();
304 $operator = $this->resolveOperator($operator);
306 $constraintSQL = '(';
307 if ($valueFunction === NULL) {
308 $constraintSQL .= (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
310 $constraintSQL .= $valueFunction . '(' . (!empty($selectorName) ?
$selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
312 $constraintSQL .= ') ';
314 $sql['where'][] = $constraintSQL;
319 * Returns the SQL operator for the given JCR operator type.
321 * @param string $operator One of the JCR_OPERATOR_* constants
322 * @return string an SQL operator
324 protected function resolveOperator($operator) {
326 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_EQUAL_TO
:
329 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_NOT_EQUAL_TO
:
332 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN
:
335 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO
:
338 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN
:
341 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
344 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface
::JCR_OPERATOR_LIKE
:
348 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
355 * Replace query placeholders in a query part by the given
358 * @param string $queryPart The query part with placeholders
359 * @param array $parameters The parameters
360 * @return string The query part with replaced placeholders
362 protected function replacePlaceholders(&$sqlString, array $parameters) {
363 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);
364 foreach ($parameters as $parameter) {
365 $markPosition = strpos($sqlString, '?');
366 if ($markPosition !== FALSE) {
367 $sqlString = substr($sqlString, 0, $markPosition) . '"' . $parameter . '"' . substr($sqlString, $markPosition +
1);
373 * Builds the enable fields statement
375 * @param string $selectorName The selector name (= database table name)
376 * @param array &$sql The query parts
379 protected function addEnableFieldsStatement($selectorName, array &$sql) {
380 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
381 if (is_array($GLOBALS['TCA'][$selectorName]['ctrl'])) {
382 $statement = substr($GLOBALS['TSFE']->sys_page
->enableFields($selectorName), 4);
383 if(!empty($statement)) {
384 $sql['enableFields'][] = $statement;
390 * Transforms orderings into SQL
392 * @param array $orderings
394 * @param array &$parameters
395 * @param array $boundVariableValues
398 protected function parseOrderings(array $orderings = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
399 if (is_array($orderings)) {
400 foreach ($orderings as $propertyName => $ordering) {
407 * Transforms a Resource from a database query to an array of rows. Performs the language and
408 * workspace overlay before.
410 * @return array The result as an array of rows (tuples)
412 protected function getRowsFromResult($tableName, $res) {
414 while ($row = $this->databaseHandle
->sql_fetch_assoc($res)) {
415 $row = $this->doLanguageAndWorkspaceOverlay($tableName, $row);
416 if (is_array($row)) {
417 // TODO Check if this is necessary, maybe the last line is enough
418 $arrayKeys = range(0,count($row));
419 array_fill_keys($arrayKeys, $row);
427 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
428 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
430 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
431 * @param array $row The row array (as reference)
432 * @param string $languageUid The language id
433 * @param string $workspaceUidUid The workspace id
436 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
437 if (!($this->pageSelectObject
instanceof t3lib_pageSelect
)) {
438 if (TYPO3_MODE
== 'FE') {
439 if (is_object($GLOBALS['TSFE'])) {
440 $this->pageSelectObject
= $GLOBALS['TSFE']->sys_page
;
441 if ($languageUid === NULL) {
442 $languageUid = $GLOBALS['TSFE']->sys_language_content
;
445 require_once(PATH_t3lib
. 'class.t3lib_page.php');
446 $this->pageSelectObject
= t3lib_div
::makeInstance('t3lib_pageSelect');
447 if ($languageUid === NULL) {
448 $languageUid = intval(t3lib_div
::_GP('L'));
451 if ($workspaceUid !== NULL) {
452 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
455 require_once(PATH_t3lib
. 'class.t3lib_page.php');
456 $this->pageSelectObject
= t3lib_div
::makeInstance( 't3lib_pageSelect' );
457 //$this->pageSelectObject->versioningPreview = TRUE;
458 if ($workspaceUid === NULL) {
459 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
461 $this->pageSelectObject
->versioningWorkspaceId
= $workspaceUid;
465 $this->pageSelectObject
->versionOL($tableName, $row, TRUE);
466 $row = $this->pageSelectObject
->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
467 // TODO Skip if empty languageoverlay (languagevisibility)