diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index f74e9880b..faabb04f8 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -8,7 +8,7 @@ jobs: strategy: matrix: - php-version: ['8.0', '8.1'] + php-version: ['8.1'] fail-fast: false diff --git a/composer.json b/composer.json index 6216bd7be..2b3672c64 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "generator/lib" ], "require": { - "php": "^8.0", + "php": "^8.1", "ext-dom": "*", "ext-iconv": "*", "ext-json": "*", diff --git a/generator/default.properties b/generator/default.properties index 9c313c7e7..b2353d1e1 100644 --- a/generator/default.properties +++ b/generator/default.properties @@ -104,8 +104,8 @@ propel.disableIdentifierQuoting = false # it is nice to change the defaults. propel.defaultTimeStampFormat = Y-m-d H:i:s -propel.defaultTimeFormat = %X -propel.defaultDateFormat = %x +propel.defaultTimeFormat = H:i:s +propel.defaultDateFormat = Y-m-d propel.defaultKeyType = phpName diff --git a/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php b/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php index a9bc26535..8a9ed76ca 100644 --- a/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php +++ b/generator/lib/behavior/nestedset/NestedSetBehaviorObjectBuilderModifier.php @@ -1495,10 +1495,8 @@ protected function addGetIterator(&$script) $script .= " /** * Returns a pre-order iterator for this node and its children. - * - * @return RecursiveIterator */ -public function getIterator() +public function getIterator(): NestedSetRecursiveIterator { return new NestedSetRecursiveIterator(\$this); } diff --git a/generator/lib/behavior/sluggable/SluggableBehavior.php b/generator/lib/behavior/sluggable/SluggableBehavior.php index eb0df5f7f..946e5724e 100644 --- a/generator/lib/behavior/sluggable/SluggableBehavior.php +++ b/generator/lib/behavior/sluggable/SluggableBehavior.php @@ -229,6 +229,8 @@ public function addCleanupSlugPart(&$script) */ protected static function cleanupSlugPart(\$slug, \$replacement = '" . $this->getParameter('replacement') . "') { + \$slug = (string) \$slug; + // transliterate \$slug = iconv('utf-8', 'us-ascii//TRANSLIT', \$slug); @@ -317,18 +319,8 @@ protected function makeSlugUnique(\$slug, \$separator = '" . $this->getParameter \$query = " . $this->builder->getStubQueryBuilder()->getClassname() . "::create('q') "; - $platform = $this->getTable()->getDatabase()->getPlatform(); - if ($platform instanceof PgsqlPlatform) { - $script .= "->where('q." . $this->getColumnForParameter('slug_column')->getPhpName() . " ' . (\$alreadyExists ? '~*' : '=') . ' ?', \$alreadyExists ? '^' . \$slug2 . '[0-9]+$' : \$slug2)"; - } elseif ($platform instanceof MssqlPlatform) { - $script .= "->where('q." . $this->getColumnForParameter('slug_column')->getPhpName() . " ' . (\$alreadyExists ? 'like' : '=') . ' ?', \$alreadyExists ? '^' . \$slug2 . '[0-9]+$' : \$slug2)"; - } elseif ($platform instanceof OraclePlatform) { - $script .= "->where((\$alreadyExists ? 'REGEXP_LIKE(' : '') . 'q." . $this->getColumnForParameter('slug_column')->getPhpName() . " ' . (\$alreadyExists ? ',' : '=') . ' ?' . (\$alreadyExists ? ')' : ''), \$alreadyExists ? '^' . \$slug2 . '[0-9]+$' : \$slug2)"; - } else { - $script .= "->where('q." . $this->getColumnForParameter('slug_column')->getPhpName() . " ' . (\$alreadyExists ? 'REGEXP' : '=') . ' ?', \$alreadyExists ? '^' . \$slug2 . '[0-9]+$' : \$slug2)"; - } - - $script .="->prune(\$this)"; + $script .= "->where('q." . $this->getColumnForParameter('slug_column')->getPhpName() . " ' . (\$alreadyExists ? 'REGEXP' : '=') . ' ?', \$alreadyExists ? '^' . \$slug2 . '[0-9]+$' : \$slug2)"; + $script .= "->prune(\$this)"; if ($this->getParameter('scope_column')) { $scopeGetter = 'get' . $this->getColumnForParameter('scope_column')->getPhpName(); diff --git a/generator/lib/builder/om/ExtensionQueryBuilder.php b/generator/lib/builder/om/ExtensionQueryBuilder.php index 560b6118c..6b30a237a 100644 --- a/generator/lib/builder/om/ExtensionQueryBuilder.php +++ b/generator/lib/builder/om/ExtensionQueryBuilder.php @@ -66,7 +66,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php b/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php index f25962818..a3c866fa5 100644 --- a/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php +++ b/generator/lib/builder/om/ExtensionQueryInheritanceBuilder.php @@ -110,7 +110,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php b/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php index d01dea6d1..f0fc4cc08 100644 --- a/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php +++ b/generator/lib/builder/om/PHP5ExtensionNodeBuilder.php @@ -65,7 +65,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php b/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php index 11856a9a4..44d0c27c4 100644 --- a/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php +++ b/generator/lib/builder/om/PHP5ExtensionNodePeerBuilder.php @@ -65,7 +65,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php b/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php index 2287d0fd8..6d91330c9 100644 --- a/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php +++ b/generator/lib/builder/om/PHP5ExtensionObjectBuilder.php @@ -88,7 +88,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php b/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php index b688dcc94..5fb5fd421 100644 --- a/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php +++ b/generator/lib/builder/om/PHP5ExtensionPeerBuilder.php @@ -88,7 +88,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5InterfaceBuilder.php b/generator/lib/builder/om/PHP5InterfaceBuilder.php index c762f1492..701af7a37 100644 --- a/generator/lib/builder/om/PHP5InterfaceBuilder.php +++ b/generator/lib/builder/om/PHP5InterfaceBuilder.php @@ -61,7 +61,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php b/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php index dd7970a8c..47f3610dc 100644 --- a/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php +++ b/generator/lib/builder/om/PHP5MultiExtendObjectBuilder.php @@ -147,7 +147,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5NestedSetBuilder.php b/generator/lib/builder/om/PHP5NestedSetBuilder.php index 1fd51df70..bebd0aa81 100644 --- a/generator/lib/builder/om/PHP5NestedSetBuilder.php +++ b/generator/lib/builder/om/PHP5NestedSetBuilder.php @@ -72,7 +72,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * @@ -236,10 +236,8 @@ protected function addGetIterator(&$script) $script .= " /** * Returns a pre-order iterator for this node and its children. - * - * @return NodeIterator */ - public function getIterator() + public function getIterator(): NestedSetRecursiveIterator { return new NestedSetRecursiveIterator(\$this); } diff --git a/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php b/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php index 02e5c2477..84bc09dc5 100644 --- a/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php +++ b/generator/lib/builder/om/PHP5NestedSetPeerBuilder.php @@ -72,7 +72,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5NodeBuilder.php b/generator/lib/builder/om/PHP5NodeBuilder.php index 18ccb2bea..b45335102 100644 --- a/generator/lib/builder/om/PHP5NodeBuilder.php +++ b/generator/lib/builder/om/PHP5NodeBuilder.php @@ -69,7 +69,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5NodePeerBuilder.php b/generator/lib/builder/om/PHP5NodePeerBuilder.php index b3c0a87c2..a46f4d1f8 100644 --- a/generator/lib/builder/om/PHP5NodePeerBuilder.php +++ b/generator/lib/builder/om/PHP5NodePeerBuilder.php @@ -68,7 +68,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5ObjectBuilder.php b/generator/lib/builder/om/PHP5ObjectBuilder.php index 948763190..e19948fc3 100644 --- a/generator/lib/builder/om/PHP5ObjectBuilder.php +++ b/generator/lib/builder/om/PHP5ObjectBuilder.php @@ -222,7 +222,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * @@ -855,7 +855,7 @@ public function addTemporalAccessorComment(&$script, Column $col) } $script .= " * - * @param string \$format The date/time format string (either date()-style or strftime()-style). + * @param string \$format The date/time format string (date()-style). * If format is null, then the raw " . ($useDateTime ? 'DateTime object' : 'unix timestamp integer') . ' will be returned.'; if ($useDateTime) { $script .= " @@ -1022,10 +1022,6 @@ protected function addTemporalAccessorBody(&$script, Column $col) $script .= " } - if (strpos(\$format, '%') !== false) { - return strftime(\$format, \$dt->format('U')); - } - return \$dt->format(\$format); "; } @@ -1397,32 +1393,15 @@ protected function addLazyLoaderBody(&$script, Column $col) $platform = $this->getPlatform(); $clo = strtolower($col->getName()); - // pdo_sqlsrv driver requires the use of PDOStatement::bindColumn() or a hex string will be returned - if ($col->getType() === PropelTypes::BLOB && $platform instanceof SqlsrvPlatform) { - $script .= " - \$c = \$this->buildPkeyCriteria(); - \$c->addSelectColumn(" . $this->getColumnConstant($col) . "); - try { - \$row = [0 => null]; - \$stmt = " . $this->getPeerClassname() . "::doSelectStmt(\$c, \$con); - \$stmt->bindColumn(1, \$row[0], PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); - \$stmt->fetch(PDO::FETCH_BOUND); - \$stmt->closeCursor();"; - } else { - $script .= " + $script .= " \$c = \$this->buildPkeyCriteria(); \$c->addSelectColumn(" . $this->getColumnConstant($col) . "); try { \$stmt = " . $this->getPeerClassname() . "::doSelectStmt(\$c, \$con); \$row = \$stmt->fetch(PDO::FETCH_NUM); \$stmt->closeCursor();"; - } - if ($col->getType() === PropelTypes::CLOB && $platform instanceof OraclePlatform) { - // PDO_OCI returns a stream for CLOB objects, while other PDO adapters return a string... - $script .= " - \$this->$clo = stream_get_contents(\$row[0]);"; - } elseif ($col->isLobType() && !$platform->hasStreamBlobImpl()) { + if ($col->isLobType() && !$platform->hasStreamBlobImpl()) { $script .= " if (\$row && \$row[0] !== null) { \$this->$clo = fopen('php://memory', 'r+'); @@ -2179,11 +2158,7 @@ protected function addHydrateBody(&$script) foreach ($table->getColumns() as $col) { if (!$col->isLazyLoad()) { $clo = strtolower($col->getName()); - if ($col->getType() === PropelTypes::CLOB_EMU && $this->getPlatform() instanceof OraclePlatform) { - // PDO_OCI returns a stream for CLOB objects, while other PDO adapters return a string... - $script .= " - \$this->$clo = stream_get_contents(\$row[\$startcol + $n]);"; - } elseif ($col->isLobType() && !$platform->hasStreamBlobImpl()) { + if ($col->isLobType() && !$platform->hasStreamBlobImpl()) { $script .= " if (\$row[\$startcol + $n] !== null) { \$this->$clo = fopen('php://memory', 'r+'); @@ -3614,7 +3589,6 @@ protected function addRefFKGetJoinMethods(&$script, ForeignKey $refFK) $tblFK = $refFK->getTable(); $join_behavior = $this->getGeneratorConfig()->getBuildProperty('useLeftJoinsInDoJoinMethods') ? 'Criteria::LEFT_JOIN' : 'Criteria::INNER_JOIN'; - $peerClassname = $this->getStubPeerBuilder()->getClassname(); $fkQueryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); $collName = $this->getRefFKCollVarName($refFK); @@ -3916,7 +3890,6 @@ protected function addRefFKCount(&$script, ForeignKey $refFK) $table = $this->getTable(); $tblFK = $refFK->getTable(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); $fkQueryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); @@ -3971,7 +3944,6 @@ protected function addRefFKGet(&$script, ForeignKey $refFK) $table = $this->getTable(); $tblFK = $refFK->getTable(); - $peerClassname = $this->getStubPeerBuilder()->getClassname(); $fkQueryClassname = $this->getNewStubQueryBuilder($refFK->getTable())->getClassname(); $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true); @@ -4889,21 +4861,7 @@ protected function addDoInsert() */ protected function doInsert(PropelPDO \$con) {"; - if ($this->getPlatform() instanceof MssqlPlatform) { - if ($table->hasAutoIncrementPrimaryKey()) { - $script .= " - \$this->modifiedColumns[] = " . $this->getColumnConstant($table->getAutoIncrementPrimaryKey()) . ';'; - } - $script .= " - \$criteria = \$this->buildCriteria();"; - if ($this->getTable()->getIdMethod() != IDMethod::NO_ID_METHOD) { - $script .= $this->addDoInsertBodyWithIdMethod(); - } else { - $script .= $this->addDoInsertBodyStandard(); - } - } else { - $script .= $this->addDoInsertBodyRaw(); - } + $script .= $this->addDoInsertBodyRaw(); $script .= " \$this->setNew(false); } @@ -4921,8 +4879,6 @@ protected function addDoInsertBodyStandard() protected function addDoInsertBodyWithIdMethod() { $table = $this->getTable(); - $reloadOnInsert = $table->isReloadOnInsert(); - $basePeerClassname = $this->getNewPeerBuilder($table)->getBasePeerClassname(); $script = ''; foreach ($table->getPrimaryKey() as $col) { if (!$col->isAutoIncrement()) { @@ -4975,7 +4931,6 @@ protected function addDoInsertBodyRaw() { $this->declareClasses('Propel', 'PDO'); $table = $this->getTable(); - $peerClassname = $this->getPeerClassname(); $platform = $this->getPlatform(); $primaryKeyMethodInfo = ''; if ($table->getIdMethodParameters()) { diff --git a/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php b/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php index a6c54ea6b..289be9a38 100644 --- a/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php +++ b/generator/lib/builder/om/PHP5ObjectNoCollectionBuilder.php @@ -112,11 +112,7 @@ protected function addLazyLoaderBody(&$script, Column $col) \$row = \$stmt->fetch(PDO::FETCH_NUM); \$stmt->closeCursor();"; - if ($col->getType() === PropelTypes::CLOB && $this->getPlatform() instanceof OraclePlatform) { - // PDO_OCI returns a stream for CLOB objects, while other PDO adapters return a string... - $script .= " - \$this->$clo = stream_get_contents(\$row[0]);"; - } elseif ($col->isLobType() && !$platform->hasStreamBlobImpl()) { + if ($col->isLobType() && !$platform->hasStreamBlobImpl()) { $script .= " if (\$row[0] !== null) { \$this->$clo = fopen('php://memory', 'r+'); diff --git a/generator/lib/builder/om/PHP5PeerBuilder.php b/generator/lib/builder/om/PHP5PeerBuilder.php index 02155e145..d5d265b49 100644 --- a/generator/lib/builder/om/PHP5PeerBuilder.php +++ b/generator/lib/builder/om/PHP5PeerBuilder.php @@ -111,7 +111,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/PHP5TableMapBuilder.php b/generator/lib/builder/om/PHP5TableMapBuilder.php index 8187e805a..04a447cf1 100644 --- a/generator/lib/builder/om/PHP5TableMapBuilder.php +++ b/generator/lib/builder/om/PHP5TableMapBuilder.php @@ -73,7 +73,7 @@ protected function addClassOpen(&$script) * *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/om/QueryBuilder.php b/generator/lib/builder/om/QueryBuilder.php index 238fba1fd..45696b449 100644 --- a/generator/lib/builder/om/QueryBuilder.php +++ b/generator/lib/builder/om/QueryBuilder.php @@ -84,7 +84,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * @@ -928,7 +928,7 @@ public function filterBy$colPhpName(\$$variableName = null, \$comparison = null) }"; } elseif ($col->isTextType()) { $script .= " - if (null === \$comparison) { + if (null === \$comparison && null !== \$$variableName) { if (is_array(\$$variableName)) { \$comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', \$$variableName)) { diff --git a/generator/lib/builder/om/QueryInheritanceBuilder.php b/generator/lib/builder/om/QueryInheritanceBuilder.php index d8bb8a0c6..fe1b26f27 100644 --- a/generator/lib/builder/om/QueryInheritanceBuilder.php +++ b/generator/lib/builder/om/QueryInheritanceBuilder.php @@ -141,7 +141,7 @@ protected function addClassOpen(&$script) * $tableDesc *"; if ($this->getBuildProperty('addTimeStamp')) { - $now = strftime('%c'); + $now = date('F j, Y, g:i a'); $script .= ' * This class was autogenerated by Propel ' . $this->getBuildProperty('version') . " on: * diff --git a/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php b/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php deleted file mode 100644 index 2a468bbf0..000000000 --- a/generator/lib/builder/sql/mssql/MssqlDataSQLBuilder.php +++ /dev/null @@ -1,36 +0,0 @@ - - * @package propel.generator.builder.sql.mssql - */ -class MssqlDataSQLBuilder extends DataSQLBuilder -{ - - /** - * - * @param mixed $blob Blob object or string containing data. - * - * @return string - */ - protected function getBlobSql($blob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($blob)) { - $blob = $blob->__toString(); - } - $data = unpack('H*hex', $blob); - - return '0x' . $data['hex']; // no surrounding quotes! - } -} diff --git a/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php b/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php deleted file mode 100644 index 52860f201..000000000 --- a/generator/lib/builder/sql/oracle/OracleDataSQLBuilder.php +++ /dev/null @@ -1,20 +0,0 @@ - - * @package propel.generator.builder.sql.oracle - */ -class OracleDataSQLBuilder extends DataSQLBuilder -{ - -} diff --git a/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php b/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php deleted file mode 100644 index 8ca367acf..000000000 --- a/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php +++ /dev/null @@ -1,107 +0,0 @@ - - * @package propel.generator.builder.sql.pgsql - */ -class PgsqlDataSQLBuilder extends DataSQLBuilder -{ - - /** - * The largest serial value encountered this far. - * - * @var int - */ - private $maxSeqVal; - - /** - * Construct a new PgsqlDataSQLBuilder object. - * - * @param Table $table - */ - public function __construct(Table $table) - { - parent::__construct($table); - } - - /** - * The main method in this class, returns the SQL for INSERTing data into a row. - * - * @param DataRow $row The row to process. - * - * @return string - */ - public function buildRowSql(DataRow $row) - { - $sql = parent::buildRowSql($row); - - $table = $this->getTable(); - - if ($table->hasAutoIncrementPrimaryKey() && $table->getIdMethod() == IDMethod::NATIVE) { - foreach ($row->getColumnValues() as $colValue) { - if ($colValue->getColumn()->isAutoIncrement()) { - if ($colValue->getValue() > $this->maxSeqVal) { - $this->maxSeqVal = $colValue->getValue(); - } - } - } - } - - return $sql; - } - - public function getTableEndSql() - { - $table = $this->getTable(); - $sql = ''; - if ($table->hasAutoIncrementPrimaryKey() && $table->getIdMethod() == IDMethod::NATIVE) { - $seqname = $this->getPlatform()->getSequenceName($table); - $sql .= "SELECT pg_catalog.setval('$seqname', " . ((int) $this->maxSeqVal) . '); -'; - } - - return $sql; - } - - /** - * Get SQL value to insert for Postgres BOOLEAN column. - * - * @param boolean $value - * - * @return string The representation of boolean for Postgres ('t' or 'f'). - */ - protected function getBooleanSql($value) - { - if ($value === 'f' || $value === 'false' || $value === '0') { - $value = false; - } - - return ($value ? "'t'" : "'f'"); - } - - /** - * - * @param mixed $blob Blob object or string containing data. - * - * @return string - */ - protected function getBlobSql($blob) - { - // they took magic __toString() out of PHP5.0.0; this sucks - if (is_object($blob)) { - $blob = $blob->__toString(); - } - - return "'" . pg_escape_bytea($blob) . "'"; - } -} diff --git a/generator/lib/builder/sql/sqlsrv/SqlsrvDataSQLBuilder.php b/generator/lib/builder/sql/sqlsrv/SqlsrvDataSQLBuilder.php deleted file mode 100644 index 09c2278ba..000000000 --- a/generator/lib/builder/sql/sqlsrv/SqlsrvDataSQLBuilder.php +++ /dev/null @@ -1,20 +0,0 @@ - 3 && ctype_alpha($file[0]) && substr($file, 1, 1) === ':' diff --git a/generator/lib/config/GeneratorConfig.php b/generator/lib/config/GeneratorConfig.php index 1357f912f..785b3e12e 100644 --- a/generator/lib/config/GeneratorConfig.php +++ b/generator/lib/config/GeneratorConfig.php @@ -269,7 +269,7 @@ public function getBuildConnections() // probably using the command line, which doesn't accept whitespace // therefore base64 encoded $this->parseBuildConnections(base64_decode($buildTimeConfigString)); - } elseif (file_exists($buildTimeConfigPath)) { + } elseif ($buildTimeConfigPath && file_exists($buildTimeConfigPath)) { // configuration stored in a buildtime-conf.xml file $this->parseBuildConnections(file_get_contents($buildTimeConfigPath)); } else { diff --git a/generator/lib/model/Column.php b/generator/lib/model/Column.php index 579a7dda1..53e9447ca 100644 --- a/generator/lib/model/Column.php +++ b/generator/lib/model/Column.php @@ -29,7 +29,7 @@ class Column extends XMLElement const DEFAULT_VISIBILITY = 'public'; public static $valid_visibilities = ['public', 'protected', 'private']; - private $name; + private ?string $name; private $description; private $phpName = null; private $phpNamingMethod; @@ -141,17 +141,17 @@ protected function setupObject() if ($dom) { $this->getDomain()->copy($this->getTable()->getDatabase()->getDomain($dom)); } else { - $type = strtoupper($this->getAttribute('type')); + $type = strtoupper((string) $this->getAttribute('type')); if ($type) { if ($platform = $this->getPlatform()) { - $this->getDomain()->copy($this->getPlatform()->getDomainForType($type)); + $this->getDomain()->copy($platform->getDomainForType($type)); } else { // no platform - probably during tests $this->setDomain(new Domain($type)); } } else { if ($platform = $this->getPlatform()) { - $this->getDomain()->copy($this->getPlatform()->getDomainForType(self::DEFAULT_TYPE)); + $this->getDomain()->copy($platform->getDomainForType(self::DEFAULT_TYPE)); } else { // no platform - probably during tests $this->setDomain(new Domain(self::DEFAULT_TYPE)); @@ -289,7 +289,7 @@ public function getFullyQualifiedName() /** * Get the name of the column */ - public function getName() + public function getName(): ?string { return $this->name; } @@ -980,9 +980,9 @@ public function isEnumType() /** * Sets the list of possible values for an ENUM column * - * @param array + * @param array $valueSet */ - public function setValueSet($valueSet) + public function setValueSet($valueSet): void { $this->valueSet = $valueSet; } diff --git a/generator/lib/model/Database.php b/generator/lib/model/Database.php index 41a755aa3..939a23557 100644 --- a/generator/lib/model/Database.php +++ b/generator/lib/model/Database.php @@ -421,9 +421,9 @@ public function addTable($data) } $this->tableList[] = $tbl; $this->tablesByName[$tbl->getName()] = $tbl; - $this->tablesByLowercaseName[strtolower($tbl->getName())] = $tbl; + $this->tablesByLowercaseName[strtolower((string) $tbl->getName())] = $tbl; $this->tablesByPhpName[$tbl->getPhpName()] = $tbl; - if (strpos($tbl->getNamespace(), '\\') === 0) { + if (str_starts_with((string) $tbl->getNamespace(), '\\')) { $tbl->setNamespace(substr($tbl->getNamespace(), 1)); } elseif ($namespace = $this->getNamespace()) { if ($tbl->getNamespace() === null) { diff --git a/generator/lib/model/Domain.php b/generator/lib/model/Domain.php index 9180358d1..b045da1d8 100644 --- a/generator/lib/model/Domain.php +++ b/generator/lib/model/Domain.php @@ -46,7 +46,7 @@ class Domain extends XMLElement private $propelType; /** - * @var string The SQL type to use for this column + * @var string|null The SQL type to use for this column */ private $sqlType; @@ -314,9 +314,9 @@ public function replaceDefaultValue(ColumnDefaultValue $value = null) } /** - * @return string Returns the sqlType. + * @return string|null Returns the sqlType. */ - public function getSqlType() + public function getSqlType(): ?string { return $this->sqlType; } @@ -324,7 +324,7 @@ public function getSqlType() /** * @param string $sqlType The sqlType to set. */ - public function setSqlType($sqlType) + public function setSqlType($sqlType): void { $this->sqlType = $sqlType; } diff --git a/generator/lib/model/ForeignKey.php b/generator/lib/model/ForeignKey.php index 671a942b9..834b79e80 100644 --- a/generator/lib/model/ForeignKey.php +++ b/generator/lib/model/ForeignKey.php @@ -266,9 +266,9 @@ public function setDefaultJoin($defaultJoin) /** * Get the foreignTableName of the FK * - * @return string foreign table qualified name + * @return string|null foreign table qualified name */ - public function getForeignTableName() + public function getForeignTableName(): ?string { if ($this->foreignSchemaName && $this->getTable()->getDatabase()->getPlatform()->supportsSchemas()) { return $this->foreignSchemaName . '.' . $this->foreignTableCommonName; @@ -340,7 +340,7 @@ public function getTable() /** * Returns the Name of the table the foreign key is in */ - public function getTableName() + public function getTableName(): ?string { return $this->parentTable->getName(); } diff --git a/generator/lib/model/PhpNameGenerator.php b/generator/lib/model/PhpNameGenerator.php index 738471dc2..9d9def3f4 100644 --- a/generator/lib/model/PhpNameGenerator.php +++ b/generator/lib/model/PhpNameGenerator.php @@ -97,7 +97,7 @@ public function generateName($inputs) protected function underscoreMethod($schemaName) { $name = ''; - $tok = strtok($schemaName, self::STD_SEPARATOR_CHAR); + $tok = strtok((string) $schemaName, self::STD_SEPARATOR_CHAR); while ($tok !== false) { $name .= ucfirst(strtolower($tok)); $tok = strtok(self::STD_SEPARATOR_CHAR); diff --git a/generator/lib/model/PropelTypes.php b/generator/lib/model/PropelTypes.php index 3ad2909de..6e2b5bdcc 100644 --- a/generator/lib/model/PropelTypes.php +++ b/generator/lib/model/PropelTypes.php @@ -386,12 +386,12 @@ public static function isPhpObjectType($phpType) /** * Convenience method to indicate whether a passed-in PHP type is an array. * - * @param string $phpType The PHP type to check + * @param string|null $phpType The PHP type to check * * @return boolean */ - public static function isPhpArrayType($phpType) + public static function isPhpArrayType($phpType): bool { - return strtoupper($phpType) === self::PHP_ARRAY; + return null !== $phpType && strtoupper($phpType) === self::PHP_ARRAY; } } diff --git a/generator/lib/model/ScopedElement.php b/generator/lib/model/ScopedElement.php index 7c1ec25a3..be6ab55e9 100644 --- a/generator/lib/model/ScopedElement.php +++ b/generator/lib/model/ScopedElement.php @@ -34,7 +34,7 @@ abstract class ScopedElement extends XMLElement /** * Namespace for the generated OM. * - * @var string + * @var string|null */ protected $namespace; @@ -66,10 +66,8 @@ protected function setupObject() /** * Get the value of the namespace. - * - * @return value of namespace. */ - public function getNamespace() + public function getNamespace(): ?string { return $this->namespace; } @@ -77,7 +75,7 @@ public function getNamespace() /** * Set the value of the namespace. * - * @param $v Value to assign to namespace. + * @param string $v Value to assign to namespace. */ public function setNamespace($v) { diff --git a/generator/lib/model/Table.php b/generator/lib/model/Table.php index 1b363a479..d3a8cec66 100644 --- a/generator/lib/model/Table.php +++ b/generator/lib/model/Table.php @@ -727,7 +727,7 @@ public function addColumn($data) } $this->columnList[] = $col; $this->columnsByName[$col->getName()] = $col; - $this->columnsByLowercaseName[strtolower($col->getName())] = $col; + $this->columnsByLowercaseName[strtolower((string) $col->getName())] = $col; $this->columnsByPhpName[$col->getPhpName()] = $col; $col->setPosition(count($this->columnList)); $this->needsTransactionInPostgres |= $col->requiresTransactionInPostgres(); @@ -1233,20 +1233,23 @@ public function hasAdditionalBuilders() */ public function getAdditionalBuilders() { - $additionalBuilders = array(); + $additionalBuilders = []; + foreach ($this->getBehaviors() as $behavior) { - $additionalBuilders = array_merge($additionalBuilders, $behavior->getAdditionalBuilders()); + $additionalBuilders[] = $behavior->getAdditionalBuilders(); } - return $additionalBuilders; + return array_merge([], ...$additionalBuilders); } /** * Get the name of the Table */ - public function getName() + public function getName(): ?string { - if ($this->schema && $this->getDatabase() && $this->getDatabase()->getPlatform() && $this->getDatabase()->getPlatform()->supportsSchemas()) { + $database = $this->getDatabase(); + + if ($this->schema && $database && $database->getPlatform() && $database->getPlatform()->supportsSchemas()) { return $this->schema . '.' . $this->commonName; } @@ -1755,7 +1758,7 @@ public function setDatabase(Database $db) /** * Get the database that contains this table. * - * @return Database + * @return Database|null */ public function getDatabase() { diff --git a/generator/lib/model/XMLElement.php b/generator/lib/model/XMLElement.php index 077a86828..a40ec69e7 100644 --- a/generator/lib/model/XMLElement.php +++ b/generator/lib/model/XMLElement.php @@ -74,8 +74,6 @@ public function getAttribute($name, $defaultValue = null) $name = strtolower($name); return $this->attributes[$name] ?? $defaultValue; - - return $defaultValue; } /** @@ -86,16 +84,20 @@ public function getAttribute($name, $defaultValue = null) */ protected function booleanValue($val) { + if (null === $val) { + return false; + } + if (is_numeric($val)) { return (bool) $val; } - return (in_array(strtolower($val), ['true', 't', 'y', 'yes'], true) ? true : false); + return in_array(strtolower($val), ['true', 't', 'y', 'yes'], true); } protected function getDefaultValueForArray($stringValue) { - $stringValue = trim($stringValue); + $stringValue = trim((string) $stringValue); if (empty($stringValue)) { return null; diff --git a/generator/lib/model/diff/PropelColumnComparator.php b/generator/lib/model/diff/PropelColumnComparator.php index fb36bdae0..fad05c977 100644 --- a/generator/lib/model/diff/PropelColumnComparator.php +++ b/generator/lib/model/diff/PropelColumnComparator.php @@ -62,7 +62,7 @@ public static function compareColumns(Column $fromColumn, Column $toColumn) if ($fromDomain->getSize() != $toDomain->getSize()) { $changedProperties['size'] = [$fromDomain->getSize(), $toDomain->getSize()]; } - if (strtoupper($fromDomain->getSqlType()) != strtoupper($toDomain->getSqlType())) { + if (strtoupper((string) $fromDomain->getSqlType()) !== strtoupper((string) $toDomain->getSqlType())) { $changedProperties['sqlType'] = [$fromDomain->getSqlType(), $toDomain->getSqlType()]; } if ($fromColumn->isNotNull() != $toColumn->isNotNull()) { diff --git a/generator/lib/model/diff/PropelDatabaseDiff.php b/generator/lib/model/diff/PropelDatabaseDiff.php index 07325a80c..efac39835 100644 --- a/generator/lib/model/diff/PropelDatabaseDiff.php +++ b/generator/lib/model/diff/PropelDatabaseDiff.php @@ -18,15 +18,19 @@ */ class PropelDatabaseDiff { + /** @var array */ protected $addedTables = []; + /** @var array */ protected $removedTables = []; + /** @var array */ protected $modifiedTables = []; + /** @var array */ protected $renamedTables = []; /** * Setter for the addedTables property * - * @param array $addedTables + * @param array $addedTables */ public function setAddedTables($addedTables) { @@ -57,7 +61,7 @@ public function removeAddedTable($tableName) /** * Getter for the addedTables property * - * @return array + * @return array */ public function getAddedTables() { @@ -79,7 +83,7 @@ public function countAddedTables() * * @param string $tableName * - * @param Table + * @return Table */ public function getAddedTable($tableName) { @@ -89,7 +93,7 @@ public function getAddedTable($tableName) /** * Setter for the removedTables property * - * @param array $removedTables + * @param array $removedTables */ public function setRemovedTables($removedTables) { @@ -120,7 +124,7 @@ public function removeRemovedTable($tableName) /** * Getter for the removedTables property * - * @return array + * @return array */ public function getRemovedTables() { @@ -142,7 +146,7 @@ public function countRemovedTables() * * @param string $tableName * - * @param Table + * @return Table */ public function getRemovedTable($tableName) { @@ -152,7 +156,7 @@ public function getRemovedTable($tableName) /** * Setter for the modifiedTables property * - * @param array $modifiedTables + * @param array $modifiedTables */ public function setModifiedTables($modifiedTables) { @@ -183,7 +187,7 @@ public function countModifiedTables() /** * Getter for the modifiedTables property * - * @return array + * @return array */ public function getModifiedTables() { @@ -193,7 +197,7 @@ public function getModifiedTables() /** * Setter for the renamedTables property * - * @param array $renamedTables + * @param array $renamedTables */ public function setRenamedTables($renamedTables) { @@ -214,7 +218,7 @@ public function addRenamedTable($fromName, $toName) /** * Getter for the renamedTables property * - * @return array + * @return array */ public function getRenamedTables() { diff --git a/generator/lib/model/diff/PropelForeignKeyComparator.php b/generator/lib/model/diff/PropelForeignKeyComparator.php index 44be886c5..279aa491b 100644 --- a/generator/lib/model/diff/PropelForeignKeyComparator.php +++ b/generator/lib/model/diff/PropelForeignKeyComparator.php @@ -33,13 +33,13 @@ public static function computeDiff(ForeignKey $fromFk, ForeignKey $toFk, $caseIn { // Check for differences in local and remote table $test = $caseInsensitive ? - strtolower($fromFk->getTableName()) != strtolower($toFk->getTableName()) : + strtolower((string) $fromFk->getTableName()) != strtolower((string) $toFk->getTableName()) : $fromFk->getTableName() != $toFk->getTableName(); if ($test) { return true; } $test = $caseInsensitive ? - strtolower($fromFk->getForeignTableName()) != strtolower($toFk->getForeignTableName()) : + strtolower((string) $fromFk->getForeignTableName()) != strtolower((string) $toFk->getForeignTableName()) : $fromFk->getForeignTableName() != $toFk->getForeignTableName(); if ($test) { return true; diff --git a/generator/lib/model/diff/PropelTableDiff.php b/generator/lib/model/diff/PropelTableDiff.php index bc1e16c5a..605c008b9 100644 --- a/generator/lib/model/diff/PropelTableDiff.php +++ b/generator/lib/model/diff/PropelTableDiff.php @@ -21,8 +21,11 @@ class PropelTableDiff protected $fromTable; protected $toTable; + /** @var array */ protected $addedColumns = []; + /** @var array */ protected $removedColumns = []; + /** @var array */ protected $modifiedColumns = []; protected $renamedColumns = []; @@ -124,7 +127,7 @@ public function getAddedColumns() * * @param string $columnName * - * @param Column + * @return Column */ public function getAddedColumn($columnName) { @@ -177,7 +180,7 @@ public function getRemovedColumns() * * @param string $columnName * - * @param Column + * @return Column */ public function getRemovedColumn($columnName) { diff --git a/generator/lib/platform/MssqlPlatform.php b/generator/lib/platform/MssqlPlatform.php deleted file mode 100644 index 285a4f7d1..000000000 --- a/generator/lib/platform/MssqlPlatform.php +++ /dev/null @@ -1,184 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @version $Revision$ - * @package propel.generator.platform - */ -class MssqlPlatform extends DefaultPlatform -{ - protected static $dropCount = 0; - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->setSchemaDomainMapping(new Domain(PropelTypes::INTEGER, 'INT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, 'INT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, 'FLOAT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, 'VARCHAR(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, 'VARCHAR(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, 'DATETIME')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BU_DATE, 'DATETIME')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIME, 'DATETIME')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, 'DATETIME')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BU_TIMESTAMP, 'DATETIME')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, 'BINARY(7132)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, 'VARBINARY(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, 'VARBINARY(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, 'VARBINARY(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::OBJECT, 'VARCHAR(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::PHP_ARRAY, 'VARCHAR(MAX)')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::ENUM, 'TINYINT')); - } - - public function getMaxColumnNameLength() - { - return 128; - } - - public function getNullString($notNull) - { - return ($notNull ? 'NOT NULL' : 'NULL'); - } - - public function supportsNativeDeleteTrigger() - { - return true; - } - - public function supportsInsertNullPk() - { - return false; - } - - public function getDropTableDDL(Table $table) - { - $ret = ''; - foreach ($table->getForeignKeys() as $fk) { - $ret .= " -IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='" . $fk->getName() . "') - ALTER TABLE " . $this->quoteIdentifier($table->getName()) . ' DROP CONSTRAINT ' . $this->quoteIdentifier($fk->getName()) . '; -'; - } - - self::$dropCount++; - - $ret .= " -IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = '" . $table->getName() . "') -BEGIN - DECLARE @reftable_" . self::$dropCount . ' nvarchar(60), @constraintname_' . self::$dropCount . " nvarchar(60) - DECLARE refcursor CURSOR FOR - select reftables.name tablename, cons.name constraintname - from sysobjects tables, - sysobjects reftables, - sysobjects cons, - sysreferences ref - where tables.id = ref.rkeyid - and cons.id = ref.constid - and reftables.id = ref.fkeyid - and tables.name = '" . $table->getName() . "' - OPEN refcursor - FETCH NEXT from refcursor into @reftable_" . self::$dropCount . ', @constraintname_' . self::$dropCount . " - while @@FETCH_STATUS = 0 - BEGIN - exec ('alter table '+@reftable_" . self::$dropCount . "+' drop constraint '+@constraintname_" . self::$dropCount . ') - FETCH NEXT from refcursor into @reftable_' . self::$dropCount . ', @constraintname_' . self::$dropCount . ' - END - CLOSE refcursor - DEALLOCATE refcursor - DROP TABLE ' . $this->quoteIdentifier($table->getName()) . ' -END -'; - - return $ret; - } - - public function getPrimaryKeyDDL(Table $table) - { - if ($table->hasPrimaryKey()) { - $pattern = 'CONSTRAINT %s PRIMARY KEY (%s)'; - - return sprintf($pattern, - $this->quoteIdentifier($this->getPrimaryKeyName($table)), - $this->getColumnListDDL($table->getPrimaryKey()) - ); - } - } - - public function getAddForeignKeyDDL(ForeignKey $fk) - { - if ($fk->isSkipSql()) { - return; - } - $pattern = ' -BEGIN -ALTER TABLE %s ADD %s -END -; -'; - - return sprintf($pattern, - $this->quoteIdentifier($fk->getTable()->getName()), - $this->getForeignKeyDDL($fk) - ); - } - - public function getForeignKeyDDL(ForeignKey $fk) - { - if ($fk->isSkipSql()) { - return; - } - $pattern = 'CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)'; - $script = sprintf($pattern, - $this->quoteIdentifier($fk->getName()), - $this->getColumnListDDL($fk->getLocalColumns()), - $this->quoteIdentifier($fk->getForeignTableName()), - $this->getColumnListDDL($fk->getForeignColumns()) - ); - if ($fk->hasOnUpdate() && $fk->getOnUpdate() != ForeignKey::SETNULL) { - $script .= ' ON UPDATE ' . $fk->getOnUpdate(); - } - if ($fk->hasOnDelete() && $fk->getOnDelete() != ForeignKey::SETNULL) { - $script .= ' ON DELETE ' . $fk->getOnDelete(); - } - - return $script; - } - - /** - * @see Platform::supportsSchemas() - */ - public function supportsSchemas() - { - return true; - } - - public function hasSize($sqlType) - { - return !('INT' == $sqlType || 'TEXT' == $sqlType); - } - - public function quoteIdentifier($text) - { - return $this->isIdentifierQuotingEnabled ? '[' . strtr($text, ['.' => '].[']) . ']' : $text; - } - - public function getTimestampFormatter() - { - return 'Y-m-d H:i:s'; - } -} diff --git a/generator/lib/platform/OraclePlatform.php b/generator/lib/platform/OraclePlatform.php deleted file mode 100644 index acd7a815f..000000000 --- a/generator/lib/platform/OraclePlatform.php +++ /dev/null @@ -1,397 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @author Denis Dalmais - * @version $Revision$ - * @package propel.generator.platform - */ -class OraclePlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->schemaDomainMap[PropelTypes::BOOLEAN] = new Domain(PropelTypes::BOOLEAN_EMU, 'NUMBER', '1', '0'); - $this->schemaDomainMap[PropelTypes::CLOB] = new Domain(PropelTypes::CLOB_EMU, 'CLOB'); - $this->schemaDomainMap[PropelTypes::CLOB_EMU] = $this->schemaDomainMap[PropelTypes::CLOB]; - $this->setSchemaDomainMapping(new Domain(PropelTypes::TINYINT, 'NUMBER', '3', '0')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::SMALLINT, 'NUMBER', '5', '0')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::INTEGER, 'NUMBER')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BIGINT, 'NUMBER', '20', '0')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::REAL, 'NUMBER')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, 'FLOAT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DECIMAL, 'NUMBER')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::NUMERIC, 'NUMBER')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARCHAR, 'NVARCHAR2')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, 'NVARCHAR2', '2000')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIME, 'DATE')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, 'DATE')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, 'TIMESTAMP')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, 'LONG RAW')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, 'BLOB')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, 'LONG RAW')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::OBJECT, 'NVARCHAR2', '2000')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::PHP_ARRAY, 'NVARCHAR2', '2000')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::ENUM, 'NUMBER', '3', '0')); - } - - public function getMaxColumnNameLength() - { - return 30; - } - - public function getNativeIdMethod() - { - return PropelPlatformInterface::SEQUENCE; - } - - public function getAutoIncrement() - { - return ''; - } - - public function supportsNativeDeleteTrigger() - { - return true; - } - - public function getBeginDDL() - { - return " -ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'; -ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'; -"; - } - - public function getAddTablesDDL(Database $database) - { - $ret = $this->getBeginDDL(); - foreach ($database->getTablesForSql() as $table) { - $ret .= $this->getCommentBlockDDL($table->getName()); - $ret .= $this->getDropTableDDL($table); - $ret .= $this->getAddTableDDL($table); - $ret .= $this->getAddIndicesDDL($table); - } - $ret2 = ''; - foreach ($database->getTablesForSql() as $table) { - $ret2 .= $this->getAddForeignKeysDDL($table); - } - if ($ret2) { - $ret .= $this->getCommentBlockDDL('Foreign Keys') . $ret2; - } - $ret .= $this->getEndDDL(); - - return $ret; - } - - public function getAddTableDDL(Table $table) - { - $tableDescription = $table->hasDescription() ? $this->getCommentLineDDL($table->getDescription()) : ''; - - $lines = []; - - foreach ($table->getColumns() as $column) { - $lines[] = $this->getColumnDDL($column); - } - - foreach ($table->getUnices() as $unique) { - $lines[] = $this->getUniqueDDL($unique); - } - - $sep = ', - '; - - $pattern = ' -%sCREATE TABLE %s -( - %s -)%s; -'; - $ret = sprintf($pattern, - $tableDescription, - $this->quoteIdentifier($table->getName()), - implode($sep, $lines), - $this->generateBlockStorage($table) - ); - - $ret .= $this->getAddPrimaryKeyDDL($table); - $ret .= $this->getAddSequencesDDL($table); - - return $ret; - } - - public function getAddPrimaryKeyDDL(Table $table) - { - if (is_array($table->getPrimaryKey()) && count($table->getPrimaryKey())) { - return parent::getAddPrimaryKeyDDL($table); - } - } - - public function getAddSequencesDDL(Table $table) - { - if ($table->getIdMethod() == 'native') { - $pattern = ' -CREATE SEQUENCE %s - INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE NOCACHE ORDER; -'; - - return sprintf($pattern, - $this->quoteIdentifier($this->getSequenceName($table)) - ); - } - } - - public function getDropTableDDL(Table $table) - { - $ret = ' -DROP TABLE ' . $this->quoteIdentifier($table->getName()) . ' CASCADE CONSTRAINTS; -'; - if ($table->getIdMethod() == IDMethod::NATIVE) { - $ret .= ' -DROP SEQUENCE ' . $this->quoteIdentifier($this->getSequenceName($table)) . '; -'; - } - - return $ret; - } - - public function getPrimaryKeyName(Table $table) - { - $tableName = $table->getName(); - // pk constraint name must be 30 chars at most - $tableName = substr($tableName, 0, min(27, strlen($tableName))); - - return $tableName . '_PK'; - } - - public function getPrimaryKeyDDL(Table $table) - { - if ($table->hasPrimaryKey()) { - $pattern = 'CONSTRAINT %s PRIMARY KEY (%s)%s'; - - return sprintf($pattern, - $this->quoteIdentifier($this->getPrimaryKeyName($table)), - $this->getColumnListDDL($table->getPrimaryKey()), - $this->generateBlockStorage($table, true) - ); - } - } - - public function getUniqueDDL(Unique $unique) - { - return sprintf('CONSTRAINT %s UNIQUE (%s)', - $this->quoteIdentifier($unique->getName()), - $this->getColumnListDDL($unique->getColumns()) - ); - } - - public function getForeignKeyDDL(ForeignKey $fk) - { - if ($fk->isSkipSql()) { - return; - } - $pattern = 'CONSTRAINT %s - FOREIGN KEY (%s) REFERENCES %s (%s)'; - $script = sprintf($pattern, - $this->quoteIdentifier($fk->getName()), - $this->getColumnListDDL($fk->getLocalColumns()), - $this->quoteIdentifier($fk->getForeignTableName()), - $this->getColumnListDDL($fk->getForeignColumns()) - ); - if ($fk->hasOnDelete()) { - $script .= ' - ON DELETE ' . $fk->getOnDelete(); - } - - return $script; - } - - /** - * Whether the underlying PDO driver for this platform returns BLOB columns as streams (instead of strings). - * - * @return boolean - */ - public function hasStreamBlobImpl() - { - return true; - } - - public function quoteIdentifier($text) - { - return $text; - } - - public function getTimestampFormatter() - { - return 'Y-m-d H:i:s'; - } - - /** - * @note While Oracle supports schemas, they're user-based and - * are really only good for creating a database layout in - * one fell swoop. - * @see Platform::supportsSchemas() - */ - public function supportsSchemas() - { - return false; - } - - /** - * Generate oracle block storage - * - * @param Table|Index $object object with vendor parameters - * @param bool $isPrimaryKey is a primary key vendor part - * - * @return string oracle vendor sql part - */ - public function generateBlockStorage($object, $isPrimaryKey = false) - { - $vendorSpecific = $object->getVendorInfoForType('oracle'); - if ($vendorSpecific->isEmpty()) { - return ''; - } - - if ($isPrimaryKey) { - $physicalParameters = ' -USING INDEX -'; - $prefix = 'PK'; - } else { - $physicalParameters = "\n"; - $prefix = ''; - } - - if ($vendorSpecific->hasParameter($prefix . 'PCTFree')) { - $physicalParameters .= 'PCTFREE ' . $vendorSpecific->getParameter($prefix . 'PCTFree') . ' -'; - } - if ($vendorSpecific->hasParameter($prefix . 'InitTrans')) { - $physicalParameters .= 'INITRANS ' . $vendorSpecific->getParameter($prefix . 'InitTrans') . ' -'; - } - if ($vendorSpecific->hasParameter($prefix . 'MinExtents') || $vendorSpecific->hasParameter($prefix . 'MaxExtents') || $vendorSpecific->hasParameter($prefix . 'PCTIncrease')) { - $physicalParameters .= 'STORAGE -( -'; - if ($vendorSpecific->hasParameter($prefix . 'MinExtents')) { - $physicalParameters .= ' MINEXTENTS ' . $vendorSpecific->getParameter($prefix . 'MinExtents') . ' -'; - } - if ($vendorSpecific->hasParameter($prefix . 'MaxExtents')) { - $physicalParameters .= ' MAXEXTENTS ' . $vendorSpecific->getParameter($prefix . 'MaxExtents') . ' -'; - } - if ($vendorSpecific->hasParameter($prefix . 'PCTIncrease')) { - $physicalParameters .= ' PCTINCREASE ' . $vendorSpecific->getParameter($prefix . 'PCTIncrease') . ' -'; - } - $physicalParameters .= ') -'; - } - if ($vendorSpecific->hasParameter($prefix . 'Tablespace')) { - $physicalParameters .= 'TABLESPACE ' . $vendorSpecific->getParameter($prefix . 'Tablespace'); - } - - return $physicalParameters; - } - - /** - * Builds the DDL SQL to add an Index. - * - * @param Index $index - * - * @return string - */ - public function getAddIndexDDL(Index $index) - { - // don't create index form primary key - if ($this->getPrimaryKeyName($index->getTable()) == $this->quoteIdentifier($index->getName())) { - return ''; - } - - $pattern = ' -CREATE %sINDEX %s ON %s (%s)%s; -'; - - return sprintf($pattern, - $index->getIsUnique() ? 'UNIQUE ' : '', - $this->quoteIdentifier($index->getName()), - $this->quoteIdentifier($index->getTable()->getName()), - $this->getColumnListDDL($index->getColumns()), - $this->generateBlockStorage($index) - ); - } - - /** - * Get the PHP snippet for binding a value to a column. - * Warning: duplicates logic from DBOracle::bindValue(). - * Any code modification here must be ported there. - */ - public function getColumnBindingPHP($column, $identifier, $columnValueAccessor, $tab = ' ') - { - if ($column->getPDOType() == PropelTypes::CLOB_EMU) { - return sprintf( - "%s\$stmt->bindParam(%s, %s, %s, strlen(%s)); -", - $tab, - $identifier, - $columnValueAccessor, - PropelTypes::getPdoTypeString($column->getType()), - $columnValueAccessor - ); - } - - return parent::getColumnBindingPHP($column, $identifier, $columnValueAccessor, $tab); - } - - /** - * Get the PHP snippet for getting a Pk from the database. - * Warning: duplicates logic from DBOracle::getId(). - * Any code modification here must be ported there. - */ - public function getIdentifierPhp($columnValueMutator, $connectionVariableName = '$con', $sequenceName = '', $tab = ' ' - ) - { - if (!$sequenceName) { - throw new EngineException('Oracle needs a sequence name to fetch primary keys'); - } - $snippet = " -\$stmt = %s->query('SELECT %s.nextval FROM dual'); -\$row = \$stmt->fetch(PDO::FETCH_NUM); -%s = \$row[0];"; - $script = sprintf($snippet, - $connectionVariableName, - $sequenceName, - $columnValueMutator - ); - - return preg_replace('/^/m', $tab, $script); - } - - public function getDefaultFKOnDeleteBehavior() - { - return ForeignKey::NOACTION; - } - - public function getDefaultFKOnUpdateBehavior() - { - return ForeignKey::NOACTION; - } -} diff --git a/generator/lib/platform/PgsqlPlatform.php b/generator/lib/platform/PgsqlPlatform.php deleted file mode 100644 index b0cfa7a87..000000000 --- a/generator/lib/platform/PgsqlPlatform.php +++ /dev/null @@ -1,508 +0,0 @@ - (Propel) - * @author Martin Poeschl (Torque) - * @author Niklas Närhinen - * @version $Revision$ - * @package propel.generator.platform - */ -class PgsqlPlatform extends DefaultPlatform -{ - - /** - * Initializes db specific domain mapping. - */ - protected function initialize() - { - parent::initialize(); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, 'BOOLEAN')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::TINYINT, 'INT2')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::SMALLINT, 'INT2')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BIGINT, 'INT8')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::REAL, 'FLOAT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, 'DOUBLE PRECISION')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::FLOAT, 'DOUBLE PRECISION')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, 'TEXT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, 'BYTEA')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, 'BYTEA')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, 'BYTEA')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, 'BYTEA')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, 'TEXT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::OBJECT, 'TEXT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::PHP_ARRAY, 'TEXT')); - $this->setSchemaDomainMapping(new Domain(PropelTypes::ENUM, 'INT2')); - } - - public function getNativeIdMethod() - { - return PropelPlatformInterface::SERIAL; - } - - public function getAutoIncrement() - { - return ''; - } - - public function getMaxColumnNameLength() - { - return 32; - } - - /** - * Escape the string for RDBMS. - * - * @param string $text - * - * @return string - */ - public function disconnectedEscapeText($text) - { - if (function_exists('pg_escape_string')) { - return pg_escape_string($text); - } - - return parent::disconnectedEscapeText($text); - } - - public function getBooleanString($b) - { - // parent method does the checking to allow string - // representations & returns integer - $b = parent::getBooleanString($b); - - return ($b ? "'t'" : "'f'"); - } - - public function supportsNativeDeleteTrigger() - { - return true; - } - - /** - * Override to provide sequence names that conform to postgres' standard when - * no id-method-parameter specified. - * - * @param Table $table - * - * @return string - */ - public function getSequenceName(Table $table) - { - static $longNamesMap = []; - $result = null; - if ($table->getIdMethod() == IDMethod::NATIVE) { - $idMethodParams = $table->getIdMethodParameters(); - if (empty($idMethodParams)) { - $result = null; - // We're going to ignore a check for max length (mainly - // because I'm not sure how Postgres would handle this w/ SERIAL anyway) - foreach ($table->getColumns() as $col) { - if ($col->isAutoIncrement()) { - $result = $table->getName() . '_' . $col->getName() . '_seq'; - break; // there's only one auto-increment column allowed - } - } - } else { - $result = $idMethodParams[0]->getValue(); - } - } - - return $result; - } - - protected function getAddSequenceDDL(Table $table) - { - if ($table->getIdMethod() == IDMethod::NATIVE && $table->getIdMethodParameters() != null) { - $pattern = ' -CREATE SEQUENCE %s; -'; - - return sprintf($pattern, - $this->quoteIdentifier(strtolower($this->getSequenceName($table))) - ); - } - } - - protected function getDropSequenceDDL(Table $table) - { - if ($table->getIdMethod() == IDMethod::NATIVE && $table->getIdMethodParameters() != null) { - $pattern = ' -DROP SEQUENCE %s; -'; - - return sprintf($pattern, - $this->quoteIdentifier(strtolower($this->getSequenceName($table))) - ); - } - } - - public function getAddSchemasDDL(Database $database) - { - $ret = ''; - $schemas = []; - foreach ($database->getTables() as $table) { - $vi = $table->getVendorInfoForType('pgsql'); - if ($vi->hasParameter('schema') && !isset($schemas[$vi->getParameter('schema')])) { - $schemas[$vi->getParameter('schema')] = true; - $ret .= $this->getAddSchemaDDL($table); - } - } - - return $ret; - } - - public function getAddSchemaDDL(Table $table) - { - $vi = $table->getVendorInfoForType('pgsql'); - if ($vi->hasParameter('schema')) { - $pattern = ' -CREATE SCHEMA %s; -'; - - return sprintf($pattern, $this->quoteIdentifier($vi->getParameter('schema'))); - } - } - - public function getUseSchemaDDL(Table $table) - { - $vi = $table->getVendorInfoForType('pgsql'); - if ($vi->hasParameter('schema')) { - $pattern = ' -SET search_path TO %s; -'; - - return sprintf($pattern, $this->quoteIdentifier($vi->getParameter('schema'))); - } - } - - public function getResetSchemaDDL(Table $table) - { - $vi = $table->getVendorInfoForType('pgsql'); - if ($vi->hasParameter('schema')) { - return ' -SET search_path TO public; -'; - } - } - - public function getAddTablesDDL(Database $database) - { - $ret = $this->getBeginDDL(); - $ret .= $this->getAddSchemasDDL($database); - foreach ($database->getTablesForSql() as $table) { - $ret .= $this->getCommentBlockDDL($table->getName()); - $ret .= $this->getDropTableDDL($table); - $ret .= $this->getAddTableDDL($table); - $ret .= $this->getAddIndicesDDL($table); - } - foreach ($database->getTablesForSql() as $table) { - $ret .= $this->getAddForeignKeysDDL($table); - } - $ret .= $this->getEndDDL(); - - return $ret; - } - - public function getAddTableDDL(Table $table) - { - $ret = ''; - $ret .= $this->getUseSchemaDDL($table); - $ret .= $this->getAddSequenceDDL($table); - - $lines = []; - - foreach ($table->getColumns() as $column) { - $lines[] = $this->getColumnDDL($column); - } - - if ($table->hasPrimaryKey()) { - $lines[] = $this->getPrimaryKeyDDL($table); - } - - foreach ($table->getUnices() as $unique) { - $lines[] = $this->getUniqueDDL($unique); - } - - $sep = ', - '; - $pattern = ' -CREATE TABLE %s -( - %s -); -'; - $ret .= sprintf($pattern, - $this->quoteIdentifier($table->getName()), - implode($sep, $lines) - ); - - if ($table->hasDescription()) { - $pattern = ' -COMMENT ON TABLE %s IS %s; -'; - $ret .= sprintf($pattern, - $this->quoteIdentifier($table->getName()), - $this->quote($table->getDescription()) - ); - } - - $ret .= $this->getAddColumnsComments($table); - $ret .= $this->getResetSchemaDDL($table); - - return $ret; - } - - protected function getAddColumnsComments(Table $table) - { - $ret = ''; - foreach ($table->getColumns() as $column) { - $ret .= $this->getAddColumnComment($column); - } - - return $ret; - } - - protected function getAddColumnComment(Column $column) - { - $pattern = ' -COMMENT ON COLUMN %s.%s IS %s; -'; - if ($description = $column->getDescription()) { - return sprintf($pattern, - $this->quoteIdentifier($column->getTable()->getName()), - $this->quoteIdentifier($column->getName()), - $this->quote($description) - ); - } - } - - public function getDropTableDDL(Table $table) - { - $ret = ''; - $ret .= $this->getUseSchemaDDL($table); - $pattern = ' -DROP TABLE IF EXISTS %s CASCADE; -'; - $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName())); - $ret .= $this->getDropSequenceDDL($table); - $ret .= $this->getResetSchemaDDL($table); - - return $ret; - } - - public function getPrimaryKeyName(Table $table) - { - $tableName = $table->getName(); - - return $tableName . '_pkey'; - } - - public function getColumnDDL(Column $col) - { - $domain = $col->getDomain(); - - $ddl = [$this->quoteIdentifier($col->getName())]; - $sqlType = $domain->getSqlType(); - $table = $col->getTable(); - if ($col->isAutoIncrement() && $table && $table->getIdMethodParameters() == null) { - $sqlType = $col->getType() === PropelTypes::BIGINT ? 'bigserial' : 'serial'; - } - if ($this->hasSize($sqlType) && $col->isDefaultSqlType($this)) { - $ddl[] = $sqlType . $domain->printSize(); - } else { - $ddl[] = $sqlType; - } - if ($default = $this->getColumnDefaultValueDDL($col)) { - $ddl[] = $default; - } - if ($notNull = $this->getNullString($col->isNotNull())) { - $ddl[] = $notNull; - } - if ($autoIncrement = $col->getAutoIncrementString()) { - $ddl[] = $autoIncrement; - } - - return implode(' ', $ddl); - } - - public function getUniqueDDL(Unique $unique) - { - return sprintf('CONSTRAINT %s UNIQUE (%s)', - $this->quoteIdentifier($unique->getName()), - $this->getColumnListDDL($unique->getColumns()) - ); - } - - /** - * @see Platform::supportsSchemas() - */ - public function supportsSchemas() - { - return true; - } - - public function hasSize($sqlType) - { - return !('BYTEA' == $sqlType || 'TEXT' == $sqlType || 'DOUBLE PRECISION' == $sqlType); - } - - public function hasStreamBlobImpl() - { - return true; - } - - public function supportsVarcharWithoutSize() - { - return true; - } - - /** - * Overrides the implementation from DefaultPlatform - * - * @author Niklas Närhinen - * @return string - * @see DefaultPlatform::getModifyColumnDDL - */ - public function getModifyColumnDDL(PropelColumnDiff $columnDiff) - { - $ret = ''; - $changedProperties = $columnDiff->getChangedProperties(); - - $toColumn = $columnDiff->getToColumn(); - - $table = $toColumn->getTable(); - - $colName = $this->quoteIdentifier($toColumn->getName()); - - $pattern = ' -ALTER TABLE %s ALTER COLUMN %s; -'; - foreach ($changedProperties as $key => $property) { - switch ($key) { - case 'defaultValueType': - continue 2; - case 'size': - case 'type': - case 'scale': - $sqlType = $toColumn->getDomain()->getSqlType(); - if ($toColumn->isAutoIncrement() && $table && $table->getIdMethodParameters() == null) { - $sqlType = $toColumn->getType() === PropelTypes::BIGINT ? 'bigserial' : 'serial'; - } - if ($this->hasSize($sqlType)) { - $sqlType .= $toColumn->getDomain()->printSize(); - } - $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . ' TYPE ' . $sqlType); - break; - case 'defaultValueValue': - if ($property[0] !== null && $property[1] === null) { - $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . ' DROP DEFAULT'); - } else { - $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . ' SET ' . $this->getColumnDefaultValueDDL($toColumn)); - } - break; - case 'notNull': - $notNull = ' DROP NOT NULL'; - if ($property[1]) { - $notNull = ' SET NOT NULL'; - } - $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . $notNull); - break; - } - } - - return $ret; - } - - /** - * Overrides the implementation from DefaultPlatform - * - * @author Niklas Närhinen - * @return string - * @see DefaultPlatform::getModifyColumnsDDL - */ - public function getModifyColumnsDDL($columnDiffs) - { - $ret = ''; - foreach ($columnDiffs as $columnDiff) { - $ret .= $this->getModifyColumnDDL($columnDiff); - } - - return $ret; - } - - /** - * Overrides the implementation from DefaultPlatform - * - * @author Niklas Närhinen - * @return string - * @see DefaultPlatform::getAddColumnsDLL - */ - public function getAddColumnsDDL($columns) - { - $ret = ''; - foreach ($columns as $column) { - $ret .= $this->getAddColumnDDL($column); - } - - return $ret; - } - - /** - * Overrides the implementation from DefaultPlatform - * - * @author Niklas Närhinen - * @return string - * @see DefaultPlatform::getDropIndexDDL - */ - public function getDropIndexDDL(Index $index) - { - if ($index instanceof Unique) { - $pattern = ' - ALTER TABLE %s DROP CONSTRAINT %s; - '; - - return sprintf($pattern, - $this->quoteIdentifier($index->getTable()->getName()), - $this->quoteIdentifier($index->getName()) - ); - } - - return parent::getDropIndexDDL($index); - } - - /** - * Get the PHP snippet for getting a Pk from the database. - * Warning: duplicates logic from DBPostgres::getId(). - * Any code modification here must be ported there. - */ - public function getIdentifierPhp($columnValueMutator, $connectionVariableName = '$con', $sequenceName = '', $tab = ' ' - ) - { - if (!$sequenceName) { - throw new EngineException('PostgreSQL needs a sequence name to fetch primary keys'); - } - $snippet = " -\$stmt = %s->query(\"SELECT nextval('%s')\"); -\$row = \$stmt->fetch(PDO::FETCH_NUM); -%s = \$row[0];"; - $script = sprintf($snippet, - $connectionVariableName, - $sequenceName, - $columnValueMutator - ); - - return preg_replace('/^/m', $tab, $script); - } -} diff --git a/generator/lib/platform/SqlsrvPlatform.php b/generator/lib/platform/SqlsrvPlatform.php deleted file mode 100644 index ec4ebd788..000000000 --- a/generator/lib/platform/SqlsrvPlatform.php +++ /dev/null @@ -1,28 +0,0 @@ - - * @version $Revision$ - * @package propel.generator.reverse.mssql - */ -class MssqlSchemaParser extends BaseSchemaParser -{ - - /** - * Map MSSQL native types to Propel types. - * - * @var array - */ - private static $mssqlTypeMap = [ - 'binary' => PropelTypes::BINARY, - 'bit' => PropelTypes::BOOLEAN, - 'char' => PropelTypes::CHAR, - 'datetime' => PropelTypes::TIMESTAMP, - 'decimal() identity' => PropelTypes::DECIMAL, - 'decimal' => PropelTypes::DECIMAL, - 'image' => PropelTypes::LONGVARBINARY, - 'int' => PropelTypes::INTEGER, - 'int identity' => PropelTypes::INTEGER, - 'integer' => PropelTypes::INTEGER, - 'money' => PropelTypes::DECIMAL, - 'nchar' => PropelTypes::CHAR, - 'ntext' => PropelTypes::LONGVARCHAR, - 'numeric() identity' => PropelTypes::NUMERIC, - 'numeric' => PropelTypes::NUMERIC, - 'nvarchar' => PropelTypes::VARCHAR, - 'real' => PropelTypes::REAL, - 'float' => PropelTypes::FLOAT, - 'smalldatetime' => PropelTypes::TIMESTAMP, - 'smallint' => PropelTypes::SMALLINT, - 'smallint identity' => PropelTypes::SMALLINT, - 'smallmoney' => PropelTypes::DECIMAL, - 'sysname' => PropelTypes::VARCHAR, - 'text' => PropelTypes::LONGVARCHAR, - 'timestamp' => PropelTypes::BINARY, - 'tinyint identity' => PropelTypes::TINYINT, - 'tinyint' => PropelTypes::TINYINT, - 'uniqueidentifier' => PropelTypes::CHAR, - 'varbinary' => PropelTypes::VARBINARY, - 'varbinary(max)' => PropelTypes::CLOB, - 'varchar' => PropelTypes::VARCHAR, - 'varchar(max)' => PropelTypes::CLOB, - // SQL Server 2000 only - 'bigint identity' => PropelTypes::BIGINT, - 'bigint' => PropelTypes::BIGINT, - 'sql_variant' => PropelTypes::VARCHAR, - ]; - - /** - * @see BaseSchemaParser::getTypeMapping() - */ - protected function getTypeMapping() - { - return self::$mssqlTypeMap; - } - - /** - * - */ - public function parse(Database $database, Task $task = null) - { - $stmt = $this->dbh->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME <> 'dtproperties'"); - - // First load the tables (important that this happen before filling out details of tables) - $tables = []; - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $name = $this->cleanDelimitedIdentifiers($row[0]); - if ($name == $this->getMigrationTable()) { - continue; - } - $table = new Table($name); - $table->setIdMethod($database->getDefaultIdMethod()); - $database->addTable($table); - $tables[] = $table; - } - - // Now populate only columns. - foreach ($tables as $table) { - $this->addColumns($table); - } - - // Now add indexes and constraints. - foreach ($tables as $table) { - $this->addForeignKeys($table); - $this->addIndexes($table); - $this->addPrimaryKey($table); - } - - return count($tables); - } - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addColumns(Table $table) - { - $stmt = $this->dbh->query("sp_columns '" . $table->getName() . "'"); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $this->cleanDelimitedIdentifiers($row['COLUMN_NAME']); - $type = $row['TYPE_NAME']; - $size = $row['LENGTH']; - $is_nullable = $row['NULLABLE']; - $default = $row['COLUMN_DEF']; - $precision = $row['PRECISION']; - $scale = $row['SCALE']; - $autoincrement = false; - if (strtolower($type) == 'int identity') { - $autoincrement = true; - } - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn( - 'Column [' . $table->getName() . '.' . $name . '] has a column type (' . $type . ') that Propel does not support.' - ); - } - - $column = new Column($name); - $column->setTable($table); - $column->setDomainForType($propelType); - // We may want to provide an option to include this: - // $column->getDomain()->replaceSqlType($type); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE)); - } - $column->setAutoIncrement($autoincrement); - $column->setNotNull(!$is_nullable); - - $table->addColumn($column); - } - } - - /** - * Load foreign keys for this table. - */ - protected function addForeignKeys(Table $table) - { - $database = $table->getDatabase(); - - $stmt = $this->dbh->query("SELECT ccu1.TABLE_NAME, ccu1.COLUMN_NAME, ccu2.TABLE_NAME AS FK_TABLE_NAME, ccu2.COLUMN_NAME AS FK_COLUMN_NAME - FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu1 INNER JOIN - INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc1 ON tc1.CONSTRAINT_NAME = ccu1.CONSTRAINT_NAME AND - CONSTRAINT_TYPE = 'Foreign Key' INNER JOIN - INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1 ON rc1.CONSTRAINT_NAME = tc1.CONSTRAINT_NAME INNER JOIN - INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu2 ON ccu2.CONSTRAINT_NAME = rc1.UNIQUE_CONSTRAINT_NAME - WHERE (ccu1.table_name = '" . $table->getName() . "')"); - - $foreignKeys = []; // local store to avoid duplicates - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $lcol = $this->cleanDelimitedIdentifiers($row['COLUMN_NAME']); - $ftbl = $this->cleanDelimitedIdentifiers($row['FK_TABLE_NAME']); - $fcol = $this->cleanDelimitedIdentifiers($row['FK_COLUMN_NAME']); - - $foreignTable = $database->getTable($ftbl); - $foreignColumn = $foreignTable->getColumn($fcol); - $localColumn = $table->getColumn($lcol); - - if (!isset($foreignKeys[$name])) { - $fk = new ForeignKey($name); - $fk->setForeignTableCommonName($foreignTable->getCommonName()); - $fk->setForeignSchemaName($foreignTable->getSchema()); - //$fk->setOnDelete($fkactions['ON DELETE']); - //$fk->setOnUpdate($fkactions['ON UPDATE']); - $table->addForeignKey($fk); - $foreignKeys[$name] = $fk; - } - $foreignKeys[$name]->addReference($localColumn, $foreignColumn); - } - } - - /** - * Load indexes for this table - */ - protected function addIndexes(Table $table) - { - $stmt = $this->dbh->query("sp_indexes_rowset '" . $table->getName() . "'"); - - $indexes = []; - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $colName = $this->cleanDelimitedIdentifiers($row['COLUMN_NAME']); - $name = $this->cleanDelimitedIdentifiers($row['INDEX_NAME']); - - // FIXME -- Add UNIQUE support - if (!isset($indexes[$name])) { - $indexes[$name] = new Index($name); - $table->addIndex($indexes[$name]); - } - - $indexes[$name]->addColumn($table->getColumn($colName)); - } - } - - /** - * Loads the primary key for this table. - */ - protected function addPrimaryKey(Table $table) - { - $stmt = $this->dbh->query("SELECT COLUMN_NAME - FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS - INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ON - INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE.constraint_name - WHERE (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'PRIMARY KEY') AND - (INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_NAME = '" . $table->getName() . "')"); - - // Loop through the returned results, grouping the same key_name together - // adding each column for that key. - while ($row = $stmt->fetch(PDO::FETCH_NUM)) { - $name = $this->cleanDelimitedIdentifiers($row[0]); - $table->getColumn($name)->setPrimaryKey(true); - } - } - - /** - * according to the identifier definition, we have to clean simple quote (') around the identifier name - * returns by mssql - * - * @see http://msdn.microsoft.com/library/ms175874.aspx - * - * @param string $identifier - * - * @return string - */ - protected function cleanDelimitedIdentifiers($identifier) - { - return preg_replace('/^\'(.*)\'$/U', '$1', $identifier); - } -} diff --git a/generator/lib/reverse/oracle/OracleSchemaParser.php b/generator/lib/reverse/oracle/OracleSchemaParser.php deleted file mode 100644 index 2eccdf1ee..000000000 --- a/generator/lib/reverse/oracle/OracleSchemaParser.php +++ /dev/null @@ -1,287 +0,0 @@ - - * @author Guillermo Gutierrez (Adaptation) - * @version $Revision$ - * @package propel.generator.reverse.oracle - */ -class OracleSchemaParser extends BaseSchemaParser -{ - - /** - * Map Oracle native types to Propel types. - * - * There really aren't any Oracle native types, so we're just - * using the MySQL ones here. - * - * Left as unsupported: - * BFILE, - * RAW, - * ROWID - * - * Supported but non existant as a specific type in Oracle: - * DECIMAL (NUMBER with scale), - * DOUBLE (FLOAT with precision = 126) - * - * @var array - */ - private static $oracleTypeMap = [ - 'BLOB' => PropelTypes::BLOB, - 'CHAR' => PropelTypes::CHAR, - 'CLOB' => PropelTypes::CLOB, - 'DATE' => PropelTypes::TIMESTAMP, - 'BIGINT' => PropelTypes::BIGINT, - 'DECIMAL' => PropelTypes::DECIMAL, - 'DOUBLE' => PropelTypes::DOUBLE, - 'FLOAT' => PropelTypes::FLOAT, - 'LONG' => PropelTypes::LONGVARCHAR, - 'NCHAR' => PropelTypes::CHAR, - 'NCLOB' => PropelTypes::CLOB, - 'NUMBER' => PropelTypes::INTEGER, - 'NVARCHAR2' => PropelTypes::VARCHAR, - 'TIMESTAMP' => PropelTypes::TIMESTAMP, - 'VARCHAR2' => PropelTypes::VARCHAR, - ]; - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$oracleTypeMap; - } - - /** - * Searches for tables in the database. Maybe we want to search also the views. - * - * @param Database $database The Database model class to add tables to. - * @param Task $task - * - * @return int - */ - public function parse(Database $database, Task $task = null) - { - $tables = []; - $stmt = $this->dbh->query("SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE = 'TABLE'"); - - $seqPattern = $this->getGeneratorConfig()->getBuildProperty('oracleAutoincrementSequencePattern'); - - if ($task) { - $task->log('Reverse Engineering Table Structures', Project::MSG_VERBOSE); - } - // First load the tables (important that this happen before filling out details of tables) - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if (strpos($row['OBJECT_NAME'], '$') !== false) { - // this is an Oracle internal table or materialized view - prune - continue; - } - if (strtoupper($row['OBJECT_NAME']) == strtoupper($this->getMigrationTable())) { - continue; - } - $table = new Table($row['OBJECT_NAME']); - $table->setIdMethod($database->getDefaultIdMethod()); - if ($task) { - $task->log("Adding table '" . $table->getName() . "'", Project::MSG_VERBOSE); - } - $database->addTable($table); - // Add columns, primary keys and indexes. - $this->addColumns($table); - $this->addPrimaryKey($table); - $this->addIndexes($table); - - $pkColumns = $table->getPrimaryKey(); - if (count($pkColumns) == 1 && $seqPattern) { - $seqName = str_replace('${table}', $table->getName(), $seqPattern); - $seqName = strtoupper($seqName); - - $stmt2 = $this->dbh->query("SELECT * FROM USER_SEQUENCES WHERE SEQUENCE_NAME = '" . $seqName . "'"); - $hasSeq = $stmt2->fetch(PDO::FETCH_ASSOC); - - if ($hasSeq) { - $pkColumns[0]->setAutoIncrement(true); - $idMethodParameter = new IdMethodParameter(); - $idMethodParameter->setValue($seqName); - $table->addIdMethodParameter($idMethodParameter); - } - } - - $tables[] = $table; - } - - if ($task) { - $task->log('Reverse Engineering Foreign Keys', Project::MSG_VERBOSE); - } - - foreach ($tables as $table) { - if ($task) { - $task->log("Adding foreign keys for table '" . $table->getName() . "'", Project::MSG_VERBOSE); - } - $this->addForeignKeys($table); - } - - return count($tables); - } - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addColumns(Table $table) - { - $stmt = $this->dbh->query("SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, DATA_DEFAULT FROM USER_TAB_COLS WHERE TABLE_NAME = '" . $table->getName() . "'"); - /* @var stmt PDOStatement */ - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if (strpos($row['COLUMN_NAME'], '$') !== false) { - // this is an Oracle internal column - prune - continue; - } - $size = $row["DATA_PRECISION"] ?: $row["DATA_LENGTH"]; - $scale = $row['DATA_SCALE']; - $default = $row['DATA_DEFAULT']; - $type = $row['DATA_TYPE']; - $isNullable = ($row['NULLABLE'] == 'Y'); - if ($type == 'NUMBER' && $row['DATA_SCALE'] > 0) { - $type = 'DECIMAL'; - } - if ($type == 'NUMBER' && $size > 9) { - $type = 'BIGINT'; - } - if ($type == 'FLOAT' && $row['DATA_PRECISION'] == 126) { - $type = 'DOUBLE'; - } - if (strpos($type, 'TIMESTAMP(') !== false) { - $type = substr($type, 0, strpos($type, '(')); - $default = '0000-00-00 00:00:00'; - $size = null; - $scale = null; - } - if ($type == 'DATE') { - $default = '0000-00-00'; - $size = null; - $scale = null; - } - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn( - 'Column [' . $table->getName() . '.' . $row['COLUMN_NAME'] . '] has a column type (' . $row['DATA_TYPE'] . ') that Propel does not support.' - ); - } - - $column = new Column($row['COLUMN_NAME']); - $column->setPhpName(); // Prevent problems with strange col names - $column->setTable($table); - $column->setDomainForType($propelType); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE)); - } - $column->setAutoIncrement(false); // This flag sets in self::parse() - $column->setNotNull(!$isNullable); - $table->addColumn($column); - } - } // addColumn() - - /** - * Adds Indexes to the specified table. - * - * @param Table $table The Table model class to add columns to. - */ - protected function addIndexes(Table $table) - { - $stmt = $this->dbh->query("SELECT COLUMN_NAME, INDEX_NAME FROM USER_IND_COLUMNS WHERE TABLE_NAME = '" . $table->getName() . "' ORDER BY COLUMN_NAME"); - $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); - - $indices = []; - foreach ($rows as $row) { - $indices[$row['INDEX_NAME']][] = $row['COLUMN_NAME']; - } - - foreach ($indices as $indexName => $columnNames) { - $index = new Index($indexName); - foreach ($columnNames AS $columnName) { - // Oracle deals with complex indices using an internal reference, so... - // let's ignore this kind of index - if ($table->hasColumn($columnName)) { - $index->addColumn($table->getColumn($columnName)); - } - } - // since some of the columns are pruned above, we must only add an index if it has columns - if ($index->hasColumns()) { - $table->addIndex($index); - } - } - } - - /** - * Load foreign keys for this table. - * - * @param Table $table The Table model class to add FKs to - */ - protected function addForeignKeys(Table $table) - { - // local store to avoid duplicates - $foreignKeys = []; - - $stmt = $this->dbh->query("SELECT CONSTRAINT_NAME, DELETE_RULE, R_CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'R' AND TABLE_NAME = '" . $table->getName() . "'"); - /* @var stmt PDOStatement */ - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - // Local reference - $stmt2 = $this->dbh->query("SELECT COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = '" . $row['CONSTRAINT_NAME'] . "' AND TABLE_NAME = '" . $table->getName() . "'"); - /* @var stmt2 PDOStatement */ - $localReferenceInfo = $stmt2->fetch(PDO::FETCH_ASSOC); - - // Foreign reference - $stmt2 = $this->dbh->query("SELECT TABLE_NAME, COLUMN_NAME FROM USER_CONS_COLUMNS WHERE CONSTRAINT_NAME = '" . $row['R_CONSTRAINT_NAME'] . "'"); - $foreignReferenceInfo = $stmt2->fetch(PDO::FETCH_ASSOC); - - if (!isset($foreignKeys[$row['CONSTRAINT_NAME']])) { - $fk = new ForeignKey($row['CONSTRAINT_NAME']); - $fk->setForeignTableCommonName($foreignReferenceInfo['TABLE_NAME']); - $fk->setOnDelete($row['DELETE_RULE']); - $fk->setOnUpdate($row['DELETE_RULE']); - $fk->addReference( - ['local' => $localReferenceInfo['COLUMN_NAME'], 'foreign' => $foreignReferenceInfo['COLUMN_NAME']] - ); - $table->addForeignKey($fk); - $foreignKeys[$row['CONSTRAINT_NAME']] = $fk; - } - } - } - - /** - * Loads the primary key for this table. - * - * @param Table $table The Table model class to add PK to. - */ - protected function addPrimaryKey(Table $table) - { - $stmt = $this->dbh->query("SELECT COLS.COLUMN_NAME FROM USER_CONSTRAINTS CONS, USER_CONS_COLUMNS COLS WHERE CONS.CONSTRAINT_NAME = COLS.CONSTRAINT_NAME AND CONS.TABLE_NAME = '" . $table->getName() . "' AND CONS.CONSTRAINT_TYPE = 'P'"); - /* @var stmt PDOStatement */ - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - // This fixes a strange behavior by PDO. Sometimes the - // row values are inside an index 0 of an array - if (array_key_exists(0, $row)) { - $row = $row[0]; - } - $table->getColumn($row['COLUMN_NAME'])->setPrimaryKey(true); - } - } -} diff --git a/generator/lib/reverse/pgsql/PgsqlSchemaParser.php b/generator/lib/reverse/pgsql/PgsqlSchemaParser.php deleted file mode 100644 index 91f07fabc..000000000 --- a/generator/lib/reverse/pgsql/PgsqlSchemaParser.php +++ /dev/null @@ -1,584 +0,0 @@ - - * @version $Revision$ - * @package propel.generator.reverse.pgsql - */ -class PgsqlSchemaParser extends BaseSchemaParser -{ - - /** - * Map PostgreSQL native types to Propel types. - * @var array - */ - /** Map MySQL native types to Propel (JDBC) types. */ - private static $pgsqlTypeMap = [ - 'bool' => PropelTypes::BOOLEAN, - 'boolean' => PropelTypes::BOOLEAN, - 'tinyint' => PropelTypes::TINYINT, - 'smallint' => PropelTypes::SMALLINT, - 'mediumint' => PropelTypes::SMALLINT, - 'int2' => PropelTypes::SMALLINT, - 'int' => PropelTypes::INTEGER, - 'int4' => PropelTypes::INTEGER, - 'serial4' => PropelTypes::INTEGER, - 'integer' => PropelTypes::INTEGER, - 'int8' => PropelTypes::BIGINT, - 'bigint' => PropelTypes::BIGINT, - 'bigserial' => PropelTypes::BIGINT, - 'serial8' => PropelTypes::BIGINT, - 'int24' => PropelTypes::BIGINT, - 'real' => PropelTypes::REAL, - 'float' => PropelTypes::FLOAT, - 'float4' => PropelTypes::FLOAT, - 'decimal' => PropelTypes::DECIMAL, - 'numeric' => PropelTypes::DECIMAL, - 'double' => PropelTypes::DOUBLE, - 'float8' => PropelTypes::DOUBLE, - 'char' => PropelTypes::CHAR, - 'character' => PropelTypes::CHAR, - 'varchar' => PropelTypes::VARCHAR, - 'date' => PropelTypes::DATE, - 'time' => PropelTypes::TIME, - 'timetz' => PropelTypes::TIME, - //'year' => PropelTypes::YEAR, PropelTypes::YEAR does not exist... does this need to be mapped to a different propel type? - 'datetime' => PropelTypes::TIMESTAMP, - 'timestamp' => PropelTypes::TIMESTAMP, - 'timestamptz' => PropelTypes::TIMESTAMP, - 'bytea' => PropelTypes::BLOB, - 'text' => PropelTypes::LONGVARCHAR, - ]; - - /** - * Gets a type mapping from native types to Propel types - * - * @return array - */ - protected function getTypeMapping() - { - return self::$pgsqlTypeMap; - } - - /** - * - */ - public function parse(Database $database, Task $task = null) - { - $stmt = $this->dbh->query('SELECT version() as ver'); - $nativeVersion = $stmt->fetchColumn(); - - if (!$nativeVersion) { - throw new EngineException('Failed to get database version'); - } - - $arrVersion = sscanf($nativeVersion, '%*s %d.%d'); - $version = sprintf('%d.%d', $arrVersion[0], $arrVersion[1]); - - // Clean up - $stmt = null; - - $stmt = $this->dbh->query("SELECT c.oid, - c.relname, n.nspname - FROM pg_class c join pg_namespace n on (c.relnamespace=n.oid) - WHERE c.relkind = 'r' - AND n.nspname NOT IN ('information_schema','pg_catalog') - AND n.nspname NOT LIKE 'pg_temp%' - AND n.nspname NOT LIKE 'pg_toast%' - ORDER BY relname"); - - $tableWraps = []; - - // First load the tables (important that this happen before filling out details of tables) - if ($task) { - $task->log('Reverse Engineering Tables', Project::MSG_VERBOSE); - } - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $name = $row['relname']; - $namespacename = $row['nspname']; - if ($name == $this->getMigrationTable()) { - continue; - } - if ($task) { - $task->log(" Adding table '" . $name . "' in schema '" . $namespacename . "'", Project::MSG_VERBOSE); - } - $oid = $row['oid']; - $table = new Table($name); - if ($namespacename != 'public') { - $table->setSchema($namespacename); - } - $table->setIdMethod($database->getDefaultIdMethod()); - $database->addTable($table); - - // Create a wrapper to hold these tables and their associated OID - $wrap = new stdClass; - $wrap->table = $table; - $wrap->oid = $oid; - $tableWraps[] = $wrap; - } - - // Now populate only columns. - if ($task) { - $task->log('Reverse Engineering Columns', Project::MSG_VERBOSE); - } - foreach ($tableWraps as $wrap) { - if ($task) { - $task->log(" Adding columns for table '" . $wrap->table->getName() . "'", Project::MSG_VERBOSE); - } - $this->addColumns($wrap->table, $wrap->oid, $version); - } - - // Now add indexes and constraints. - if ($task) { - $task->log('Reverse Engineering Indices And Constraints', Project::MSG_VERBOSE); - } - foreach ($tableWraps as $wrap) { - if ($task) { - $task->log(" Adding indices and constraints for table '" . $wrap->table->getName() . "'", Project::MSG_VERBOSE); - } - $this->addForeignKeys($wrap->table, $wrap->oid, $version); - $this->addIndexes($wrap->table, $wrap->oid, $version); - $this->addPrimaryKey($wrap->table, $wrap->oid, $version); - } - - // TODO - Handle Sequences ... - return count($tableWraps); - } - - /** - * Adds Columns to the specified table. - * - * @param Table $table The Table model class to add columns to. - * @param int $oid The table OID - * @param string $version The database version. - * - * @throws EngineException - */ - protected function addColumns(Table $table, $oid, $version) - { - // Get the columns, types, etc. - // Based on code from pgAdmin3 (http://www.pgadmin.org/) - $stmt = $this->dbh->prepare("SELECT - att.attname, - att.atttypmod, - att.atthasdef, - att.attnotnull, - def.adsrc, - CASE WHEN att.attndims > 0 THEN 1 ELSE 0 END AS isarray, - CASE - WHEN ty.typname = 'bpchar' - THEN 'char' - WHEN ty.typname = '_bpchar' - THEN '_char' - ELSE - ty.typname - END AS typname, - ty.typtype - FROM pg_attribute att - JOIN pg_type ty ON ty.oid=att.atttypid - LEFT OUTER JOIN pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum - WHERE att.attrelid = ? AND att.attnum > 0 - AND att.attisdropped IS FALSE - ORDER BY att.attnum"); - - $stmt->bindValue(1, $oid, PDO::PARAM_INT); - $stmt->execute(); - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $size = null; - $precision = null; - $scale = null; - - // Check to ensure that this column isn't an array data type - if (((int) $row['isarray']) === 1) { - throw new EngineException (sprintf('Array datatypes are not currently supported [%s.%s]', $this->name, $row['attname'])); - } // if (((int) $row['isarray']) === 1) - - $name = $row['attname']; - - // If they type is a domain, Process it - if (strtolower($row['typtype']) == 'd') { - $arrDomain = $this->processDomain($row['typname']); - $type = $arrDomain['type']; - $size = $arrDomain['length']; - $precision = $size; - $scale = $arrDomain['scale']; - $boolHasDefault = ('' !== trim($row['atthasdef'])) ? $row['atthasdef'] : $arrDomain['hasdefault']; - $default = ('' !== trim($row['adsrc'])) ? $row['adsrc'] : $arrDomain['default']; - $is_nullable = ('' !== trim($row['attnotnull'])) ? $row['attnotnull'] : $arrDomain['notnull']; - $is_nullable = (($is_nullable == 't') ? false : true); - } else { - $type = $row['typname']; - $arrLengthPrecision = $this->processLengthScale($row['atttypmod'], $type); - $size = $arrLengthPrecision['length']; - $precision = $size; - $scale = $arrLengthPrecision['scale']; - $boolHasDefault = $row['atthasdef']; - $default = $row['adsrc']; - $is_nullable = (($row['attnotnull'] == 't') ? false : true); - } // else (strtolower ($row['typtype']) == 'd') - - $autoincrement = null; - - // if column has a default - if (($boolHasDefault == 't') && ('' !== trim($default))) { - if (!preg_match('/^nextval\(/', $default)) { - $strDefault = preg_replace('/::\W*/', '', $default); - $default = str_replace("'", '', $strDefault); - } else { - $autoincrement = true; - $default = null; - } - } else { - $default = null; - } - - $propelType = $this->getMappedPropelType($type); - if (!$propelType) { - $propelType = Column::DEFAULT_TYPE; - $this->warn( - 'Column [' . $table->getName() . '.' . $name . '] has a column type (' . $type . ') that Propel does not support.' - ); - } - - $column = new Column($name); - $column->setTable($table); - $column->setDomainForType($propelType); - // We may want to provide an option to include this: - // $column->getDomain()->replaceSqlType($type); - $column->getDomain()->replaceSize($size); - $column->getDomain()->replaceScale($scale); - if ($default !== null) { - if ($default == 'now()') { - $type = ColumnDefaultValue::TYPE_EXPR; - } else { - $type = ColumnDefaultValue::TYPE_VALUE; - } - $column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, $type)); - } - $column->setAutoIncrement($autoincrement); - $column->setNotNull(!$is_nullable); - - $table->addColumn($column); - } - } // addColumn() - - private function processLengthScale($intTypmod, $strName) - { - // Define the return array - $arrRetVal = ['length' => null, 'scale' => null]; - - // Some datatypes don't have a Typmod - if ($intTypmod == -1) { - return $arrRetVal; - } // if ($intTypmod == -1) - - // Decimal Datatype? - if ($strName == $this->getMappedNativeType(PropelTypes::DECIMAL)) { - $intLen = ($intTypmod - 4) >> 16; - $intPrec = ($intTypmod - 4) & 0xffff; - $intLen = sprintf('%ld', $intLen); - if ($intPrec) { - $intPrec = sprintf('%ld', $intPrec); - } // if ($intPrec) - $arrRetVal['length'] = $intLen; - $arrRetVal['scale'] = $intPrec; - } // if ($strName == $this->getMappedNativeType(PropelTypes::NUMERIC)) - elseif ($strName == $this->getMappedNativeType(PropelTypes::TIME) || $strName == 'timetz' || $strName == $this->getMappedNativeType(PropelTypes::TIMESTAMP) || $strName == 'timestamptz' || $strName == 'interval' || $strName == 'bit') { - $arrRetVal['length'] = sprintf('%ld', $intTypmod); - } // elseif (TIME, TIMESTAMP, INTERVAL, BIT) - else { - $arrRetVal['length'] = sprintf('%ld', ($intTypmod - 4)); - } // else - - return $arrRetVal; - } // private function processLengthScale ($intTypmod, $strName) - - private function processDomain($strDomain) - { - if ('' === trim($strDomain)) { - throw new EngineException ('Invalid domain name [' . $strDomain . ']'); - } - - $stmt = $this->dbh->prepare("SELECT - d.typname as domname, - b.typname as basetype, - d.typlen, - d.typtypmod, - d.typnotnull, - d.typdefault - FROM pg_type d - INNER JOIN pg_type b ON b.oid = CASE WHEN d.typndims > 0 then d.typelem ELSE d.typbasetype END - WHERE - d.typtype = 'd' - AND d.typname = ? - ORDER BY d.typname"); - $stmt->bindValue(1, $strDomain); - $stmt->execute(); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$row) { - throw new EngineException ('Domain [' . $strDomain . '] not found.'); - } - - $arrDomain = []; - $arrDomain['type'] = $row['basetype']; - $arrLengthPrecision = $this->processLengthScale($row['typtypmod'], $row['basetype']); - $arrDomain['length'] = $arrLengthPrecision['length']; - $arrDomain['scale'] = $arrLengthPrecision['scale']; - $arrDomain['notnull'] = $row['typnotnull']; - $arrDomain['default'] = $row['typdefault']; - $arrDomain['hasdefault'] = ('' !== trim($row['typdefault'])) ? 't' : 'f'; - - $stmt = null; // cleanup - - return $arrDomain; - } // private function processDomain($strDomain) - - /** - * Load foreign keys for this table. - */ - protected function addForeignKeys(Table $table, $oid, $version) - { - $database = $table->getDatabase(); - $stmt = $this->dbh->prepare("SELECT - conname, - confupdtype, - confdeltype, - CASE nl.nspname WHEN 'public' THEN cl.relname ELSE nl.nspname||'.'||cl.relname END as fktab, - array_agg(DISTINCT a2.attname) AS fkcols, - CASE nr.nspname WHEN 'public' THEN cr.relname ELSE nr.nspname||'.'||cr.relname END as reftab, - array_agg(DISTINCT a1.attname) AS refcols - FROM pg_constraint ct - JOIN pg_class cl ON cl.oid=conrelid - JOIN pg_class cr ON cr.oid=confrelid - JOIN pg_namespace nl ON nl.oid = cl.relnamespace - JOIN pg_namespace nr ON nr.oid = cr.relnamespace - LEFT JOIN pg_catalog.pg_attribute a1 ON a1.attrelid = ct.confrelid - LEFT JOIN pg_catalog.pg_attribute a2 ON a2.attrelid = ct.conrelid - WHERE - contype='f' - AND conrelid = ? - AND a2.attnum = ANY (ct.conkey) - AND a1.attnum = ANY (ct.confkey) - GROUP BY conname, confupdtype, confdeltype, fktab, reftab - ORDER BY conname"); - $stmt->bindValue(1, $oid); - $stmt->execute(); - - $foreignKeys = []; // local store to avoid duplicates - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $name = $row['conname']; - $local_table = $row['fktab']; - $local_columns = explode(',', trim($row['fkcols'], '{}')); - $foreign_table = $row['reftab']; - $foreign_columns = explode(',', trim($row['refcols'], '{}')); - - // On Update - switch ($row['confupdtype']) { - case 'c': - $onupdate = ForeignKey::CASCADE; - break; - case 'd': - $onupdate = ForeignKey::SETDEFAULT; - break; - case 'n': - $onupdate = ForeignKey::SETNULL; - break; - case 'r': - $onupdate = ForeignKey::RESTRICT; - break; - default: - case 'a': - //NOACTION is the postgresql default - $onupdate = ForeignKey::NONE; - break; - } - // On Delete - switch ($row['confdeltype']) { - case 'c': - $ondelete = ForeignKey::CASCADE; - break; - case 'd': - $ondelete = ForeignKey::SETDEFAULT; - break; - case 'n': - $ondelete = ForeignKey::SETNULL; - break; - case 'r': - $ondelete = ForeignKey::RESTRICT; - break; - default: - case 'a': - //NOACTION is the postgresql default - $ondelete = ForeignKey::NONE; - break; - } - - $foreignTable = $database->getTable($foreign_table); - $localTable = $database->getTable($local_table); - - if (!isset($foreignKeys[$name])) { - $fk = new ForeignKey($name); - $fk->setForeignTableCommonName($foreignTable->getCommonName()); - $fk->setForeignSchemaName($foreignTable->getSchema()); - $fk->setOnDelete($ondelete); - $fk->setOnUpdate($onupdate); - $table->addForeignKey($fk); - $foreignKeys[$name] = $fk; - } - - for ($i = 0, $iMax = count($local_columns); $i < $iMax; $i++) { - $foreignKeys[$name]->addReference( - $localTable->getColumn($local_columns[$i]), - $foreignTable->getColumn($foreign_columns[$i]) - ); - } - } - } - - /** - * Load indexes for this table - */ - protected function addIndexes(Table $table, $oid, $version) - { - $stmt = $this->dbh->prepare( - 'SELECT - DISTINCT ON(cls.relname) - cls.relname as idxname, - indkey, - indisunique - FROM pg_index idx - JOIN pg_class cls ON cls.oid=indexrelid - WHERE indrelid = ? AND NOT indisprimary - ORDER BY cls.relname' - ); - - $stmt->bindValue(1, $oid); - $stmt->execute(); - - $stmt2 = $this->dbh->prepare( - 'SELECT a.attname - FROM pg_catalog.pg_class c JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid - WHERE c.oid = ? AND a.attnum = ? AND NOT a.attisdropped - ORDER BY a.attnum' - ); - - $indexes = []; - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $name = $row['idxname']; - $unique = ($row['indisunique'] == 't') ? true : false; - if (!isset($indexes[$name])) { - if ($unique) { - $indexes[$name] = new Unique($name); - } else { - $indexes[$name] = new Index($name); - } - $table->addIndex($indexes[$name]); - } - - $arrColumns = explode(' ', $row['indkey']); - foreach ($arrColumns as $intColNum) { - $stmt2->bindValue(1, $oid); - $stmt2->bindValue(2, $intColNum); - $stmt2->execute(); - - $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); - - $indexes[$name]->addColumn($table->getColumn($row2['attname'])); - } // foreach ($arrColumns as $intColNum) - - } - } - - /** - * Loads the primary key for this table. - */ - protected function addPrimaryKey(Table $table, $oid, $version) - { - - $stmt = $this->dbh->prepare( - 'SELECT - DISTINCT ON(cls.relname) - cls.relname as idxname, - indkey, - indisunique - FROM pg_index idx - JOIN pg_class cls ON cls.oid=indexrelid - WHERE indrelid = ? AND indisprimary - ORDER BY cls.relname' - ); - $stmt->bindValue(1, $oid); - $stmt->execute(); - - // Loop through the returned results, grouping the same key_name together - // adding each column for that key. - - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $arrColumns = explode(' ', $row['indkey']); - foreach ($arrColumns as $intColNum) { - $stmt2 = $this->dbh->prepare( - 'SELECT a.attname - FROM pg_catalog.pg_class c JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid - WHERE c.oid = ? AND a.attnum = ? AND NOT a.attisdropped - ORDER BY a.attnum' - ); - $stmt2->bindValue(1, $oid); - $stmt2->bindValue(2, $intColNum); - $stmt2->execute(); - - $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); - $table->getColumn($row2['attname'])->setPrimaryKey(true); - } // foreach ($arrColumns as $intColNum) - } - } - - /** - * Adds the sequences for this database. - * - * @return void - * @throws SQLException - */ - protected function addSequences(Database $database) - { - /* - -- WE DON'T HAVE ANY USE FOR THESE YET IN REVERSE ENGINEERING ... - $this->sequences = array(); - $result = pg_query($this->conn->getResource(), "SELECT c.oid, - case when n.nspname='public' then c.relname else n.nspname||'.'||c.relname end as relname - FROM pg_class c join pg_namespace n on (c.relnamespace=n.oid) - WHERE c.relkind = 'S' - AND n.nspname NOT IN ('information_schema','pg_catalog') - AND n.nspname NOT LIKE 'pg_temp%' - AND n.nspname NOT LIKE 'pg_toast%' - ORDER BY relname"); - - if (!$result) { - throw new SQLException("Could not list sequences", pg_last_error($this->dblink)); - } - - while ($row = pg_fetch_assoc($result)) { - // FIXME -- decide what info we need for sequences & then create a SequenceInfo object (if needed) - $obj = new stdClass; - $obj->name = $row['relname']; - $obj->oid = $row['oid']; - $this->sequences[strtoupper($row['relname'])] = $obj; - } - */ - } -} diff --git a/generator/lib/reverse/sqlsrv/SqlsrvSchemaParser.php b/generator/lib/reverse/sqlsrv/SqlsrvSchemaParser.php deleted file mode 100644 index 4d94c647a..000000000 --- a/generator/lib/reverse/sqlsrv/SqlsrvSchemaParser.php +++ /dev/null @@ -1,20 +0,0 @@ - - * @version $Revision$ - * @package propel.generator.reverse.sqlsrv - */ -class SqlsrvSchemaParser extends MssqlSchemaParser -{ -} diff --git a/generator/lib/task/PropelConvertConfTask.php b/generator/lib/task/PropelConvertConfTask.php index 9a4aeb4a7..c9bfcab2c 100644 --- a/generator/lib/task/PropelConvertConfTask.php +++ b/generator/lib/task/PropelConvertConfTask.php @@ -119,9 +119,8 @@ public function main() // Write resulting PHP data to output file $outfile = new PhingFile($this->outputDirectory, $this->outputFile); $output = "getGeneratorConfig()->getBuildProperty('addTimestamp') ? ' on ' . strftime( - '%c' - ) : '') . "\n"; + $output .= '// This file generated by Propel ' . $phpconf['generator_version'] . ' convert-conf target' . ($this->getGeneratorConfig()->getBuildProperty('addTimestamp') ? ' on ' . + date('F j, Y, g:i a') : '') . "\n"; $output .= '// from XML runtime conf file ' . $this->xmlConfFile->getPath() . "\n"; $output .= "\$conf = "; $output .= var_export($phpconf, true); @@ -149,9 +148,8 @@ public function main() $phpconfClassmap = $this->getClassMap(); $outfile = new PhingFile($this->outputDirectory, $this->outputClassmapFile); $output = '<' . '?' . "php\n"; - $output .= '// This file generated by Propel ' . $phpconf['generator_version'] . ' convert-conf target' . ($this->getGeneratorConfig()->getBuildProperty('addTimestamp') ? ' on ' . strftime( - '%c' - ) : '') . "\n"; + $output .= '// This file generated by Propel ' . $phpconf['generator_version'] . ' convert-conf target' . ($this->getGeneratorConfig()->getBuildProperty('addTimestamp') ? ' on ' . + date('F j, Y, g:i a') : '') . "\n"; $output .= 'return '; $output .= var_export($phpconfClassmap, true); $output .= ';'; diff --git a/generator/lib/task/PropelSQLTask.php b/generator/lib/task/PropelSQLTask.php index 9fb0f6148..449f99a5a 100644 --- a/generator/lib/task/PropelSQLTask.php +++ b/generator/lib/task/PropelSQLTask.php @@ -173,48 +173,14 @@ public function main() } // main() - public function getWarnings(Database $database, PropelPLatformInterface $platform) + public function getWarnings(Database $database, PropelPlatformInterface $platform): void { - foreach ($database->getTablesForSql() as $table) { - foreach ($table->getForeignKeys() as $fk) { - - if ($platform instanceof MssqlPlatform && $fk->hasOnUpdate() && $fk->getOnUpdate() == ForeignKey::SETNULL) { - // there may be others that also won't work - // we have to skip this because it's unsupported. - $this->log(sprintf( - 'Ignoring the "ON UPDATE SET NULL" option for "%s" fk on "%s" table (unsupported by MSSQL).', - $fk->getLocalColumnNames(), - $table->getName() - ), Project::MSG_WARN); - } - - if ($platform instanceof MssqlPlatform && $fk->hasOnDelete() && $fk->getOnDelete() == ForeignKey::SETNULL) { - // there may be others that also won't work - // we have to skip this because it's unsupported. - $this->log(sprintf( - 'Ignoring the "ON DELETE SET NULL" option for "%s" fk on "%s" table (unsupported by MSSQL).', - $fk->getLocalColumnNames(), - $table->getName() - ), Project::MSG_WARN); - } - - if ($platform instanceof OraclePlatform && $fk->hasOnUpdate()) { - // there may be others that also won't work - // we have to skip this because it's unsupported. - $this->log(sprintf( - 'Ignoring the "ON UPDATE" option for "%s" fk on "%s" table (unsupported by current Oracle adapter).', - $fk->getLocalColumnNames(), - $table->getName() - ), Project::MSG_WARN); - } - } - } } /** * Packages the datamodels to one datamodel per package * - * This applies only when the the packageObjectModel option is set. We need to + * This applies only when the packageObjectModel option is set. We need to * re-package the datamodels to allow the database package attribute to control * which tables go into which SQL file. * diff --git a/phpunit.xml.dist b/phpunit.xml.dist index de2a7b215..a95eff381 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,22 +1,10 @@ - - - - - - ./runtime/lib/ diff --git a/psalm-baseline.xml b/psalm-baseline.xml index cbb5d2bf3..e0c50254e 100644 --- a/psalm-baseline.xml +++ b/psalm-baseline.xml @@ -1,5 +1,5 @@ - + $script @@ -155,6 +155,15 @@ objectMethods postSave + + $table->getName() + $this->getTable()->getName() + $this->getTable()->getName() + + + getTablePrefix + getTablePrefix + @@ -197,6 +206,9 @@ preUpdateQuery queryMethods + + getTable + @@ -259,9 +271,6 @@ Column - - $table->getNamespace() - $builder $builder @@ -285,8 +294,10 @@ modifyDatabase modifyTable - - $table->getNamespace() + + hasTable + + $this->getArchiveTable() @@ -404,6 +415,9 @@ postDelete preSave + + getTablePrefix + 'PHP5ObjectBuilder' 'PHP5PeerBuilder' @@ -444,9 +458,6 @@ - - $table->getNamespace() - $string @@ -476,9 +487,12 @@ relateI18nTableToMainTable replaceTokens - - $table->getNamespace() - + + $table->getName() + + + hasTable + @@ -1040,6 +1054,9 @@ modifyTable useScope + + $this->getTable()->getName() + @@ -1108,6 +1125,10 @@ preUpdate setBuilder + + $this->behavior->getTable()->getColumn($scope)->getName() + $this->behavior->getTable()->getColumn($scope)->getName() + $builder $objectClassname @@ -1268,14 +1289,14 @@ objectMethods preDelete + + getTable + !$fk->isComposite() - - $table->getNamespace() - $versionTable @@ -1299,9 +1320,9 @@ modifyDatabase modifyTable - - $table->getNamespace() - + + hasTable + new VersionableBehaviorPeerBuilderModifier($this) @@ -1487,9 +1508,13 @@ QueryBuilder QueryBuilder - + + $this->getTable()->getDatabase() null + + getPlatform + $dataSqlBuilder $generatorConfig @@ -1514,11 +1539,10 @@ $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'datasql') - + $this->getGeneratorConfig() $this->getTable() $this->getTable() - $this->getTable()->getDatabase() isset($this->dataSqlBuilder) @@ -1603,13 +1627,14 @@ $col === null $pkg - + + string + + $class $pkg - $this->getTable()->getNamespace() - - string + string string @@ -1641,6 +1666,16 @@ isAddIncludes validateModel + + $this->getTable()->getNamespace() + + + $col->getName() + $fk->getForeignTableName() + + + getTable + $this->getTable()->getPackage() @@ -2373,9 +2408,61 @@ $fmt - - $table->getAutoIncrementPrimaryKey() + + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $column->getName() + $column->getName() + $column->getName() + $column->getName() + $column->getName() + $table->getName() + + getTable + getTable + getTable + $mysqlInvalidDateString $mysqlInvalidDateString @@ -2442,6 +2529,22 @@ addRefFKInit addReload + + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $col->getName() + $column->getName() + $column->getName() + $column->getName() + $lcol->getName() + $localColumn->getName() + $localColumn->getName() + $localColumn->getName() + $localColumn->getName() + $localColumn->getName() + PHP5ObjectNoCollectionBuilder PHP5ObjectNoCollectionBuilder @@ -2543,6 +2646,43 @@ $php + + $col->getName() + $col->getName() + $col->getName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $fk->getForeignTableName() + $subfk->getForeignTableName() + $subfk->getForeignTableName() + $subfk->getForeignTableName() + $subfk->getForeignTableName() + + + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + getTable + $pk @@ -2623,6 +2763,9 @@ applyBehaviorModifier getBehaviorContent + + $col->getName() + PeerBuilder PeerBuilder @@ -2751,6 +2894,17 @@ applyBehaviorModifier getBehaviorContent + + $column->getName() + $column->getName() + $table->getName() + + + getName + getTable + getTable + getTable + QueryBuilder QueryBuilder @@ -2827,6 +2981,9 @@ reset + + $this->getTable()->getName() + (float) $value (float) $value @@ -2834,61 +2991,18 @@ (int) $value - - - MssqlDataSQLBuilder - MssqlDataSQLBuilder - - MysqlDataSQLBuilder MysqlDataSQLBuilder - - - OracleDataSQLBuilder - OracleDataSQLBuilder - - - - - $value === '0' - $value === '0' - $value === 'f' - $value === 'f' - $value === 'f' || $value === 'false' - $value === 'false' - $value === 'false' - - - string - - - $maxSeqVal - PgsqlDataSQLBuilder - PgsqlDataSQLBuilder - - - (int) $this->maxSeqVal - - - getSequenceName - - SqliteDataSQLBuilder SqliteDataSQLBuilder - - - SqlsrvDataSQLBuilder - SqlsrvDataSQLBuilder - - ready @@ -2931,9 +3045,6 @@ $attributes['package'] $attributes['referenceOnly'] - - public function endElement($parser, $name) - $localName $rawName @@ -2942,12 +3053,10 @@ AppData - + $file $filePath $name - $name - $parser $parser $parser $tag @@ -2970,9 +3079,8 @@ $encoding $isForReferenceOnly - + _throwInvalidTagException - endElement isAbsolutePath isAlreadyParsed isExternalSchema @@ -3023,7 +3131,8 @@ $attributes - + + $table->getName() $this->currBuilder = null null @@ -3103,9 +3212,7 @@ $classpath - - $buildTimeConfigPath - $buildTimeConfigPath + $con @@ -3163,9 +3270,6 @@ $pos - - require_once __DIR__ . '/../builder/om/' . $class . '.php' - @@ -3206,6 +3310,14 @@ setName setPlatform + + null + + + $addTable->getName() + $addTable->getName() + $namespace + getNamespace @@ -3272,11 +3384,10 @@ - + $this->domain === null false null === $this->domain - null === $this->domain->getSqlType() $this->domain ? $this->domain->getSize() : false @@ -3284,9 +3395,6 @@ $inhdata - - public function setValueSet($valueSet) - $dflt $this->domain ? $this->domain->getSize() : false @@ -3301,7 +3409,7 @@ $domain->getSize() $newSize - + $def $name $name @@ -3320,9 +3428,8 @@ $tsk $typeName $value - $valueSet - + $accessorVisibility $defaultValue $description @@ -3341,7 +3448,6 @@ $isTreeScopeKey $isUnique $mutatorVisibility - $name $namePrefix $needsTransactionInPostgres $nodeKeySep @@ -3352,7 +3458,7 @@ $size $valid_visibilities - + addReferrer appendXml clearInheritanceList @@ -3362,7 +3468,6 @@ getConstantColumnName getDescription getFullyQualifiedName - getName getNodeKeySep getPropelType getReferrers @@ -3411,14 +3516,20 @@ setType setTypeFromString setUnique - setValueSet setupObject - + + $col + $domain->getSqlType() + $this->getName() + $this->name + $this->name + $this->name $valueSet - + createElement + getDefaultPhpNamingMethod $domain @@ -3466,26 +3577,19 @@ - + !$table->isReadOnly() - $tbl->getNamespace() === null $tbl->getPackage() === null $tbl->getSchema() === null - + $data - $tbl->getNamespace() - $tbl->getNamespace() Behavior Table Table - - $namespace - $tbl->getNamespace() - new $class() @@ -3535,21 +3639,26 @@ $key + + $tbl->getName() + $tbl->getNamespace() + + + $this->tablesByName + createElement - + $dbParent $defaultStringFormat Database Database - Database (bool) $v - - $namespace = $this->getNamespace() + $this->getAppData() @@ -3585,7 +3694,7 @@ $this->scale $this->size - + appendXml copy replaceDefaultValue @@ -3599,13 +3708,12 @@ setName setScale setSize - setSqlType setType setupObject - - $sqlType ?? $type - + + $this->sqlType + createElement @@ -3682,7 +3790,7 @@ $phpName $refPhpName - + addReference appendXml clearReferences @@ -3696,7 +3804,6 @@ getName getSchemaName getTable - getTableName hasOnDelete hasOnUpdate normalizeFKey @@ -3716,6 +3823,9 @@ $m[$foreign] ?? null $m[$local] ?? null + + $foreignPKCols + createElement @@ -3768,8 +3878,9 @@ numeric - + $this->indexColumnSizes + $this->indexColumns $name @@ -3804,6 +3915,9 @@ $this->indexName + + $this->indexColumnSizes + createElement @@ -3851,6 +3965,11 @@ getAlgorithm + + + (string) $schemaName + + $type @@ -3893,18 +4012,15 @@ - - $this->namespace + $this->pkg $this->schema - - value + value value - - $v + $v $v @@ -3918,8 +4034,7 @@ setSchema setupObject - - value + value value @@ -3969,7 +4084,8 @@ $this->needsTransactionInPostgres - + + $this->foreignTableNames $this->needsTransactionInPostgres |= $col->requiresTransactionInPostgres() @@ -4022,7 +4138,7 @@ $v $v - + addExtraIndices addForeignKey addIdMethodParameter @@ -4044,7 +4160,6 @@ getFirstPrimaryKeyColumn getForeignTableNames getIdMethodParameters - getName getNumColumns getNumLazyLoadColumns getReferrers @@ -4086,14 +4201,46 @@ strrpos($foreignKey->getName(), 'FK_') + + $col + $col + $col->getName() + $col->getName() + $col->getName() + $foreignKey->getForeignTableName() + $foreignKey->getForeignTableName() + $foreignTable->getName() + $this->getName() + $this->getName() + $this->getName() + $this->getName() + $this->getName() + + + $this->columnsByName + $this->columnsByName + $name $name - + createElement + getAppData + getBaseClass + getBasePeer + getBuildProperty + getDefaultIdMethod + getDefaultPhpNamingMethod + getDefaultStringFormat + getDefaultStringFormat + getPlatform + getPlatform + getTable + getTablePrefix + isHeavyIndexing - + $abstractValue $alias $allowPkInsert @@ -4119,14 +4266,14 @@ $treeMode Table Table - Table (bool) $isCrossRef (bool) $v (bool) $v - + + $database->getPlatform() $foreignColumn !== null $foreignTable !== null $localColumn !== null @@ -4136,14 +4283,9 @@ $this->basePeer !== null $this->description !== null $this->forReferenceOnly !== null - $this->getDatabase() - $this->getDatabase() - $this->getDatabase() - $this->getDatabase()->getPlatform() $this->getSchema() !== null $this->idMethod !== null $this->interface !== null - $this->namespace !== null $this->phpName !== null $this->pkg !== null $this->readOnly !== null @@ -4182,6 +4324,9 @@ + + string + $column $table @@ -4194,8 +4339,12 @@ setTranslate setupObject - + + $this->column->getName() + + createElement + getDefaultTranslateMethod $this->translate !== null @@ -4281,27 +4430,11 @@ - - public function getAddedTable($tableName) - public function getRemovedTable($tableName) - - - $tableName - $tableName - - - $addedTables - $modifiedTables - $removedTables - $renamedTables - - + addAddedTable addModifiedTable addRemovedTable addRenamedTable - getAddedTable - getRemovedTable removeAddedTable removeRemovedTable setAddedTables @@ -4322,34 +4455,35 @@ setFromTable setToTable + + $column->getName() + $column->getName() + $column->getName() + $column->getName() + $column->getName() + $column->getName() + $fromColumn->getName() + $fromColumn->getName() + - - public function getAddedColumn($columnName) - public function getRemovedColumn($columnName) - - + $addedFks $addedIndices $addedPkColumns - $columnName - $columnName $modifiedIndices $removedFks $removedIndices $removedPkColumns $renamedPkColumns - - $addedColumns + $addedFks $addedIndices $addedPkColumns $fromTable - $modifiedColumns $modifiedFks $modifiedIndices - $removedColumns $removedFks $removedIndices $removedPkColumns @@ -4357,7 +4491,7 @@ $renamedPkColumns $toTable - + addAddedColumn addAddedFk addAddedIndex @@ -4371,9 +4505,7 @@ addRemovedPkColumn addRenamedColumn addRenamedPkColumn - getAddedColumn getModifiedIndices - getRemovedColumn removeAddedColumn removeAddedFk removeAddedPkColumn @@ -4396,6 +4528,9 @@ setRenamedPkColumns setToTable + + $this->getFromTable()->getName() + @@ -4473,6 +4608,24 @@ array_search($defaultValue->getValue(), $col->getValueSet()) + + $col->getName() + $column + $column->getName() + $fk->getForeignTableName() + $sqlType + $table->getName() + $table->getName() + $table->getName() + $table->getName() + $table->getName() + $table->getName() + + + $longNamesMap + $longNamesMap + $longNamesMap + $con @@ -4490,32 +4643,13 @@ $this->generatorConfig - - - getAddForeignKeyDDL - getForeignKeyDDL - getPrimaryKeyDDL - - - $notNull - - - $dropCount - - - initialize - - - MssqlPlatform - - - - - getIsUnique - - - getDropForeignKeyDDL - string + + + getIsUnique + + + getDropForeignKeyDDL + string 'AUTO_INCREMENT' @@ -4562,6 +4696,17 @@ $generatorConfig + + $col->getName() + $column->getName() + $sqlType + $table->getName() + $table->getName() + $table->getName() + + + getVendorInfoForType + MysqlPlatform @@ -4575,84 +4720,6 @@ $vendorInfo - - - getIsUnique - - - getAddPrimaryKeyDDL - getForeignKeyDDL - getPrimaryKeyDDL - - - '' - - - getAutoIncrement - - - $column - $columnValueAccessor - $columnValueMutator - $connectionVariableName - $identifier - $sequenceName - $tab - $tab - - - getAddSequencesDDL - getColumnBindingPHP - getDefaultFKOnDeleteBehavior - getDefaultFKOnUpdateBehavior - getIdentifierPhp - initialize - - - OraclePlatform - - - is_array($table->getPrimaryKey()) - - - - - '' - - - getAutoIncrement - - - $b - $columnDiffs - $columnValueMutator - $columns - $connectionVariableName - $sequenceName - $tab - - - getAddColumnComment - getAddColumnsComments - getAddSchemaDDL - getAddSchemasDDL - getAddSequenceDDL - getDropSequenceDDL - getIdentifierPhp - getResetSchemaDDL - getUseSchemaDDL - initialize - - - $result - - - $b - - - PgsqlPlatform - - $delim @@ -4680,15 +4747,15 @@ initialize + + $fk->getForeignTableName() + $table->getName() + $table->getName() + SqlitePlatform - - - SqlsrvPlatform - - $this->nativeToPropelTypeMap === null @@ -4731,39 +4798,6 @@ setGeneratorConfig - - - $default - $row['COLUMN_NAME'] - $row['COLUMN_NAME'] - $row['COLUMN_NAME'] - $row['FK_COLUMN_NAME'] - $row['FK_TABLE_NAME'] - $row['INDEX_NAME'] - $row[0] - $row[0] - $scale - $size - $type - $type - - - addColumns - addForeignKeys - addIndexes - addPrimaryKey - - - MssqlSchemaParser - MssqlSchemaParser - MssqlSchemaParser - - - $name - $name - $name - - $indexes[$name] @@ -4805,6 +4839,9 @@ $indexes $indexes + + getTable + MysqlSchemaParser MysqlSchemaParser @@ -4815,134 +4852,6 @@ is_array($result) - - - $foreignKeys[$row['CONSTRAINT_NAME']] - - - $default - $row['COLUMN_NAME'] - $row['COLUMN_NAME'] - $row['COLUMN_NAME'] - $row['CONSTRAINT_NAME'] - $row['OBJECT_NAME'] - $row['OBJECT_NAME'] - $row['OBJECT_NAME'] - $scale - $size - $type - $type - $type - $type - - - addColumns - addForeignKeys - addIndexes - addPrimaryKey - - - strpos($type, '(') - - - $foreignReferenceInfo['COLUMN_NAME'] - $foreignReferenceInfo['TABLE_NAME'] - $localReferenceInfo['COLUMN_NAME'] - $row['COLUMN_NAME'] - - - $row['COLUMN_NAME'] - - - $foreignKeys - - - OracleSchemaParser - OracleSchemaParser - OracleSchemaParser - - - - - $foreignKeys[$name] - $indexes[$name] - - - $default - $default - $default - $foreign_table - $local_table - $name - $name - $name - $name - $name - $row2['attname'] - $row2['attname'] - $row['adsrc'] - $row['atthasdef'] - $row['attname'] - $row['attnotnull'] - $row['fkcols'] - $row['indkey'] - $row['indkey'] - $row['refcols'] - $row['typdefault'] - $row['typtype'] - - - $intTypmod - $oid - $oid - $oid - $strDomain - $strName - $version - $version - $version - - - $pgsqlTypeMap - - - addColumns - addForeignKeys - addIndexes - addPrimaryKey - processDomain - processLengthScale - - - $row2['attname'] - $row2['attname'] - - - $arrVersion[0] - $arrVersion[1] - $type - - - $arrVersion[0] - $arrVersion[1] - - - $foreignKeys - $indexes - $indexes - - - PgsqlSchemaParser - PgsqlSchemaParser - PgsqlSchemaParser - - - SQLException - - - $this->name - - $colname @@ -4970,13 +4879,6 @@ SqliteSchemaParser - - - SqlsrvSchemaParser - SqlsrvSchemaParser - SqlsrvSchemaParser - - !$this->mapperElement @@ -5218,6 +5120,12 @@ setDatabaseUrl setDatabaseUser + + $tbl->getName() + + + $row + $this->getDataModels() $this->getDataModels() @@ -5310,6 +5218,9 @@ main setTargetPlatform + + $builder->getTable()->getName() + $dataModels @@ -5406,9 +5317,6 @@ $dmMap $platform - - PropelPLatformInterface - $sqldbmap @@ -5418,10 +5326,9 @@ $database - + cloneDatabase createSqlDbMap - getWarnings main setDatabase setSqlDbMap @@ -5479,6 +5386,9 @@ setOutputFile setSamePhpName + + $this->validators + (bool) $v (bool) $v @@ -5498,6 +5408,15 @@ main + + + $column->getName() + $column->getName() + $table->getName() + $table->getName() + $table->getName() + + new $adapterClass() @@ -5635,11 +5554,6 @@ - - $namespaces[$table->getNamespace()] - $namespaces[$table->getNamespace()] - $namespaces[$table->getNamespace()] - $errors @@ -5648,9 +5562,21 @@ validateTableAttributes validateTableColumns - - $table->getNamespace() - + + $column->getName() + $foreignTableName + $table->getName() + $table->getName() + $table->getName() + $table->getName() + $table->getName() + $table->getName() + + + $fkTables + $namespaces + $namespaces + @@ -5820,25 +5746,6 @@ DBAdapter - - - !is_numeric($limit) - !is_numeric($offset) - - - cleanupSQL - setCharset - - - $seed - - - $orders - - - $orderArr - - applyLimit @@ -5872,82 +5779,6 @@ $seed - - - $row[0] - - - integer - - - applyLimit - initConnection - - - $seed - - - $params - - - $row[0] - - - strpos($sql, 'FROM') - - - $row[0] - - - $criteria - - - $dbMap - $params - - - - - useQuoteIdentifier - useQuoteIdentifier - - - $row[0] - - - integer - - - applyLimit - - - $seed - - - $row[0] - - - $row[0] - - - $dbMap - $params - - - - - cleanupSQL - initConnection - setCharset - - - PDO::SQLSRV_ATTR_ENCODING - PDO::SQLSRV_ATTR_ENCODING - PDO::SQLSRV_ENCODING_BINARY - PDO::SQLSRV_ENCODING_SYSTEM - PDO::SQLSRV_ENCODING_UTF8 - - applyLimit @@ -5957,41 +5788,6 @@ $seed - - - MssqlDebugPDO - MssqlDebugPDO - MssqlDebugPDO - MssqlDebugPDO - - - - - integer - integer - integer - integer - integer - - - $return - $return - $return - $return - - - integer - integer - integer - integer - - - MssqlPropelPDO - MssqlPropelPDO - MssqlPropelPDO - MssqlPropelPDO - - $this->getModel() @@ -6036,14 +5832,11 @@ Propel::getConnection($databaseName, $type) - + $formatter $formatter $formatter $formatter - $iterator - $iterator - $iterator $key @@ -6059,16 +5852,9 @@ PropelPDO - - null - (string) $this->exportTo(constant($this->getPeerClass() . '::DEFAULT_STRING_FORMAT')) - - $this->getIterator() - $this->iterator - fromArray @@ -6078,17 +5864,9 @@ $this->getModel() $this->getModel() - new $class() - - $element - $element - $key - $obj - $obj - delete fromArray @@ -6103,8 +5881,7 @@ $iterator - - fromArray + initIterator @@ -6120,9 +5897,6 @@ $currentKey $currentRow - - closeCursor - $formatter @@ -6160,23 +5934,14 @@ - - $input_parameters - - - $input_parameters - - - $input_parameters ?: [] - + + $maxLength + null === $this->configuration - - void - integer @@ -6685,13 +6450,6 @@ - - $this->curNode - implode('.', $key) - - - key - $node @@ -6885,10 +6643,10 @@ '' '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw) '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar) + (float) str_replace(',', '', $scalar) + (int) self::parseScalar(substr($scalar, 2)) -log(0) - floatval(str_replace(',', '', $scalar)) - intval(self::parseScalar(substr($scalar, 2))) - is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'$value'" : $value) + is_infinite($value) ? str_ireplace('INF', '.Inf', (string) $value) : (is_string($value) ? "'$value'" : $value) is_string($value) ? "'$value'" : (int) $value log(0) strtotime($scalar) @@ -6918,9 +6676,6 @@ (string) $raw (string) $scalar - - (string) substr($scalar, 5) - @@ -7100,6 +6855,10 @@ hashCode init + + $column + $column + $type @@ -7231,9 +6990,6 @@ $this->getCriterionForClause($clause, $value, $bindingType) - - public function setWith($with) - $affectedRows $this->tableMap @@ -7252,7 +7008,7 @@ $this->add($this->getRealColumnName($column), $value, $comparison) $this->addUsingOperator($this->getAliasedColName($column), $value, $operator) - + $affectedRows $affectedRows $arguments @@ -7260,7 +7016,6 @@ $forceIndividualSaves $name $values - $with $currentAlias @@ -7280,7 +7035,7 @@ $useAliasInSQL $with - + basePostUpdate basePreUpdate configureSelectColumns @@ -7289,16 +7044,12 @@ preUpdate setPreviousJoin setPrimaryCriteria - setWith ModelCriteria ModelCriteria ModelCriteria - - null - strrpos($colName, '.') @@ -7689,11 +7440,6 @@ $value - - - $str !== null - - $value diff --git a/runtime/lib/Propel.php b/runtime/lib/Propel.php index f5364bb62..862e1657d 100644 --- a/runtime/lib/Propel.php +++ b/runtime/lib/Propel.php @@ -162,18 +162,9 @@ class Propel protected static $autoloadMap = [ 'DBAdapter' => 'adapter/DBAdapter.php', - 'DBMSSQL' => 'adapter/DBMSSQL.php', - 'MssqlPropelPDO' => 'adapter/MSSQL/MssqlPropelPDO.php', - 'MssqlDebugPDO' => 'adapter/MSSQL/MssqlDebugPDO.php', - 'MssqlDateTime' => 'adapter/MSSQL/MssqlDateTime.class.php', 'DBMySQL' => 'adapter/DBMySQL.php', - 'DBMySQLi' => 'adapter/DBMySQLi.php', 'DBNone' => 'adapter/DBNone.php', - 'DBOracle' => 'adapter/DBOracle.php', - 'DBPostgres' => 'adapter/DBPostgres.php', 'DBSQLite' => 'adapter/DBSQLite.php', - 'DBSybase' => 'adapter/DBSybase.php', - 'DBSQLSRV' => 'adapter/DBSQLSRV.php', 'PropelArrayCollection' => 'collection/PropelArrayCollection.php', 'PropelCollection' => 'collection/PropelCollection.php', diff --git a/runtime/lib/adapter/DBAdapter.php b/runtime/lib/adapter/DBAdapter.php index dbf1bf667..3cf0fd548 100644 --- a/runtime/lib/adapter/DBAdapter.php +++ b/runtime/lib/adapter/DBAdapter.php @@ -43,12 +43,6 @@ abstract class DBAdapter */ private static $adapters = [ 'mysql' => 'DBMySQL', - 'mysqli' => 'DBMySQLi', - 'mssql' => 'DBMSSQL', - 'sqlsrv' => 'DBSQLSRV', - 'oracle' => 'DBOracle', - 'oci' => 'DBOracle', - 'pgsql' => 'DBPostgres', 'sqlite' => 'DBSQLite', '' => 'DBNone', ]; diff --git a/runtime/lib/adapter/DBMSSQL.php b/runtime/lib/adapter/DBMSSQL.php deleted file mode 100644 index ec684d5bb..000000000 --- a/runtime/lib/adapter/DBMSSQL.php +++ /dev/null @@ -1,333 +0,0 @@ - (Propel) - * @version $Revision$ - * @package propel.runtime.adapter - */ -class DBMSSQL extends DBAdapter -{ - /** - * MS SQL Server does not support SET NAMES - * - * @see DBAdapter::setCharset() - * - * @param PDO $con - * @param string $charset - */ - public function setCharset(PDO $con, $charset) - { - } - - /** - * This method is used to ignore case. - * - * @param string $in The string to transform to upper case. - * - * @return string The upper case string. - */ - public function toUpperCase($in) - { - return $this->ignoreCase($in); - } - - /** - * This method is used to ignore case. - * - * @param string $in The string whose case to ignore. - * - * @return string The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string $s1 String to concatenate. - * @param string $s2 String to append. - * - * @return string - */ - public function concatString($s1, $s2) - { - return '(' . $s1 . ' + ' . $s2 . ')'; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string $s String to extract from. - * @param integer $pos Offset to start from. - * @param integer $len Number of characters to extract. - * - * @return string - */ - public function subString($s, $pos, $len) - { - return 'SUBSTRING(' . $s . ', ' . $pos . ', ' . $len . ')'; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string $s String to calculate length of. - * - * @return string - */ - public function strLength($s) - { - return 'LEN(' . $s . ')'; - } - - /** - * @see DBAdapter::quoteIdentifier() - * - * @param string $text - * - * @return string - */ - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } - - /** - * @see DBAdapter::quoteIdentifierTable() - * - * @param string $table - * - * @return string - */ - public function quoteIdentifierTable($table) - { - // e.g. 'database.table alias' should be escaped as '[database].[table] [alias]' - return '[' . strtr($table, ['.' => '].[', ' ' => '] [']) . ']'; - } - - /** - * @see DBAdapter::random() - * - * @param string $seed - * - * @return string - */ - public function random($seed = null) - { - return 'RAND(' . ((int) $seed) . ')'; - } - - /** - * Simulated Limit/Offset - * - * This rewrites the $sql query to apply the offset and limit. - * some of the ORDER BY logic borrowed from Doctrine MsSqlPlatform - * - * @see DBAdapter::applyLimit() - * @author Benjamin Runnels - * - * @param string $sql - * @param integer $offset - * @param integer $limit - * - * @return void - * - * @throws PropelException - * @throws Exception - */ - public function applyLimit(&$sql, $offset, $limit) - { - // make sure offset and limit are numeric - if (!is_numeric($offset) || !is_numeric($limit)) { - throw new PropelException('DBMSSQL::applyLimit() expects a number for argument 2 and 3'); - } - - //split the select and from clauses out of the original query - $selectSegment = []; - - $selectText = 'SELECT '; - - preg_match('/\Aselect(.*)from(.*)/si', $sql, $selectSegment); - if (count($selectSegment) == 3) { - $selectStatement = trim($selectSegment[1]); - $fromStatement = trim($selectSegment[2]); - } else { - throw new Exception('DBMSSQL::applyLimit() could not locate the select statement at the start of the query.'); - } - - if (preg_match('/\Aselect(\s+)distinct/i', $sql)) { - $selectText .= 'DISTINCT '; - $selectStatement = str_ireplace('distinct ', '', $selectStatement); - } - - // if we're starting at offset 0 then theres no need to simulate LIMIT, - // just grab the top $limit number of rows - if ($offset == 0) { - $sql = $selectText . 'TOP ' . $limit . ' ' . $selectStatement . ' FROM ' . $fromStatement; - - return; - } - - //get the ORDER BY clause if present - $orderStatement = stristr($fromStatement, 'ORDER BY'); - $orders = ''; - - if ($orderStatement !== false) { - //remove order statement from the FROM statement - $fromStatement = trim(str_replace($orderStatement, '', $fromStatement)); - - $order = str_ireplace('ORDER BY', '', $orderStatement); - $orders = array_map('trim', explode(',', $order)); - - foreach ($orders as $i => $iValue) { - $orderArr[trim(preg_replace('/\s+(ASC|DESC)$/i', '', $orders[$i]))] = [ - 'sort' => (stripos($iValue, ' DESC') !== false) ? 'DESC' : 'ASC', - 'key' => $i - ]; - } - } - - //setup inner and outer select selects - $innerSelect = ''; - $outerSelect = ''; - foreach (explode(', ', $selectStatement) as $selCol) { - $selColArr = explode(' ', $selCol); - $selColCount = count($selColArr) - 1; - - //make sure the current column isn't * or an aggregate - if ($selColArr[0] != '*' && false === strpos($selColArr[0], '(') && strtoupper($selColArr[0]) !== 'CASE') { - - // Aliases can be used in ORDER BY clauses on a SELECT, - // but aliases are not valid in the ORDER BY clause of ROW_NUMBER() OVER (...), - // so if we notice that part of $order is actually an alias, - // we replace it with the original Table.Column designation. - if ($selColCount) { - // column with alias - foreach ([' ASC', ' DESC'] as $sort) { - $index = array_search($selColArr[2] . $sort, $orders); - if ($index !== false) { - // replace alias with "Table.Column ASC/DESC" - $orders[$index] = $selColArr[0] . $sort; - break; - } - } - } - - if (isset($orderArr[$selColArr[0]])) { - $orders[$orderArr[$selColArr[0]]['key']] = $selColArr[0] . ' ' . $orderArr[$selColArr[0]]['sort']; - } - - //use the alias if one was present otherwise use the column name - $alias = (false === stripos($selCol, ' AS ')) ? $selColArr[0] : $selColArr[$selColCount]; - //don't quote the identifier if it is already quoted - if ($alias[0] != '[') { - $alias = $this->quoteIdentifier($alias); - } - - //save the first non-aggregate column for use in ROW_NUMBER() if required - if (!isset($firstColumnOrderStatement)) { - $firstColumnOrderStatement = 'ORDER BY ' . $selColArr[0]; - } - - //add an alias to the inner select so all columns will be unique - $innerSelect .= $selColArr[0] . ' AS ' . $alias . ', '; - $outerSelect .= $alias . ', '; - } else { - //aggregate columns must always have an alias clause - if (false === stripos($selCol, ' AS ')) { - throw new Exception('DBMSSQL::applyLimit() requires aggregate columns to have an Alias clause'); - } - - //aggregate column alias can't be used as the count column you must use the entire aggregate statement - if (isset($orderArr[$selColArr[$selColCount]])) { - $orders[$orderArr[$selColArr[$selColCount]]['key']] = str_replace($selColArr[$selColCount - 1] . ' ' . $selColArr[$selColCount], '', $selCol) . $orderArr[$selColArr[$selColCount]]['sort']; - } - - //quote the alias - $alias = $selColArr[$selColCount]; - //don't quote the identifier if it is already quoted - if ($alias[0] != '[') { - $alias = $this->quoteIdentifier($alias); - } - $innerSelect .= str_replace($selColArr[$selColCount], $alias, $selCol) . ', '; - $outerSelect .= $alias . ', '; - } - } - - if (is_array($orders)) { - $orderStatement = 'ORDER BY ' . implode(', ', $orders); - } else { - //use the first non aggregate column in our select statement if no ORDER BY clause present - if (isset($firstColumnOrderStatement)) { - $orderStatement = $firstColumnOrderStatement; - } else { - throw new Exception('DBMSSQL::applyLimit() unable to find column to use with ROW_NUMBER()'); - } - } - - //substring the select strings to get rid of the last comma and add our FROM and SELECT clauses - $innerSelect = $selectText . 'ROW_NUMBER() OVER(' . $orderStatement . ') AS [RowNumber], ' . substr($innerSelect, 0, -2) . ' FROM'; - //outer select can't use * because of the RowNumber column - $outerSelect = 'SELECT ' . substr($outerSelect, 0, -2) . ' FROM'; - - //ROW_NUMBER() starts at 1 not 0 - $sql = $outerSelect . ' (' . $innerSelect . ' ' . $fromStatement . ') AS derivedb WHERE RowNumber BETWEEN ' . ($offset + 1) . ' AND ' . ($limit + $offset); - } - - /** - * @see parent::cleanupSQL() - * - * @param string $sql - * @param array $params - * @param Criteria $values - * @param DatabaseMap $dbMap - */ - public function cleanupSQL(&$sql, array &$params, Criteria $values, DatabaseMap $dbMap) - { - $i = 1; - $paramCols = []; - foreach ($params as $param) { - if (null !== $param['table']) { - $column = $dbMap->getTable($param['table'])->getColumn($param['column']); - /* MSSQL pdo_dblib and pdo_mssql blob values must be converted to hex and then the hex added - * to the query string directly. If it goes through PDOStatement::bindValue quotes will cause - * an error with the insert or update. - */ - if (is_resource($param['value']) && $column->isLob()) { - // we always need to make sure that the stream is rewound, otherwise nothing will - // get written to database. - rewind($param['value']); - $hexArr = unpack('H*hex', stream_get_contents($param['value'])); - $sql = str_replace(":p$i", '0x' . $hexArr['hex'], $sql); - unset($hexArr); - fclose($param['value']); - } else { - $paramCols[] = $param; - } - } - $i++; - } - - //if we made changes re-number the params - if ($params != $paramCols) { - $params = $paramCols; - unset($paramCols); - preg_match_all('/:p\d/', $sql, $matches); - foreach ($matches[0] as $key => $match) { - $sql = str_replace($match, ':p' . ($key + 1), $sql); - } - } - } -} diff --git a/runtime/lib/adapter/DBOracle.php b/runtime/lib/adapter/DBOracle.php deleted file mode 100644 index 86e8a8e5b..000000000 --- a/runtime/lib/adapter/DBOracle.php +++ /dev/null @@ -1,309 +0,0 @@ - (Propel) - * @author Hans Lellelid (Propel) - * @author Jon S. Stevens (Torque) - * @author Brett McLaughlin (Torque) - * @author Bill Schneider (Torque) - * @author Daniel Rall (Torque) - * @version $Revision$ - * @package propel.runtime.adapter - */ -class DBOracle extends DBAdapter -{ - /** - * This method is called after a connection was created to run necessary - * post-initialization queries or code. - * Removes the charset query and adds the date queries - * - * @see parent::initConnection() - * - * @param PDO $con - * @param array $settings A $PDO PDO connection instance - */ - public function initConnection(PDO $con, array $settings) - { - $con->exec("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'"); - $con->exec("ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'"); - if (isset($settings['queries']) && is_array($settings['queries'])) { - foreach ($settings['queries'] as $queries) { - foreach ((array) $queries as $query) { - $con->exec($query); - } - } - } - } - - /** - * This method is used to ignore case. - * - * @param string $in The string to transform to upper case. - * - * @return string The upper case string. - */ - public function toUpperCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * This method is used to ignore case. - * - * @param string $in The string whose case to ignore. - * - * @return string The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string $s1 String to concatenate. - * @param string $s2 String to append. - * - * @return string - */ - public function concatString($s1, $s2) - { - return "CONCAT($s1, $s2)"; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string $s String to extract from. - * @param integer $pos Offset to start from. - * @param integer $len Number of characters to extract. - * - * @return string - */ - public function subString($s, $pos, $len) - { - return "SUBSTR($s, $pos, $len)"; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string $s String to calculate length of. - * - * @return string - */ - public function strLength($s) - { - return "LENGTH($s)"; - } - - /** - * @see DBAdapter::applyLimit() - * - * @param string $sql - * @param integer $offset - * @param integer $limit - * @param null|Criteria $criteria - */ - public function applyLimit(&$sql, $offset, $limit, $criteria = null) - { - if (BasePeer::needsSelectAliases($criteria)) { - $crit = clone $criteria; - $selectSql = $this->createSelectSqlPart($crit, $params, true); - $sql = $selectSql . substr($sql, strpos($sql, 'FROM') - 1); - } - $sql = 'SELECT B.* FROM (' - . 'SELECT A.*, rownum AS PROPEL_ROWNUM FROM (' . $sql . ') A ' - . ') B WHERE '; - - if ($offset > 0) { - $sql .= ' B.PROPEL_ROWNUM > ' . $offset; - if ($limit > 0) { - $sql .= ' AND B.PROPEL_ROWNUM <= ' . ($offset + $limit); - } - } else { - $sql .= ' B.PROPEL_ROWNUM <= ' . $limit; - } - } - - /** - * @return int - */ - protected function getIdMethod() - { - return DBAdapter::ID_METHOD_SEQUENCE; - } - - /** - * @param PDO $con - * @param string $name - * - * @throws PropelException - * @return integer - */ - public function getId(PDO $con, $name = null) - { - if ($name === null) { - throw new PropelException('Unable to fetch next sequence ID without sequence name.'); - } - - $stmt = $con->query('SELECT ' . $name . '.nextval FROM dual'); - $row = $stmt->fetch(PDO::FETCH_NUM); - - return $row[0]; - } - - /** - * @param string $seed - * - * @return string - */ - public function random($seed = null) - { - return 'dbms_random.value'; - } - - /** - * Ensures uniqueness of select column names by turning them all into aliases - * This is necessary for queries on more than one table when the tables share a column name - * - * @see http://propel.phpdb.org/trac/ticket/795 - * - * @param Criteria $criteria - * - * @return Criteria The input, with Select columns replaced by aliases - */ - public function turnSelectColumnsToAliases(Criteria $criteria) - { - $selectColumns = $criteria->getSelectColumns(); - // clearSelectColumns also clears the aliases, so get them too - $asColumns = $criteria->getAsColumns(); - $criteria->clearSelectColumns(); - $columnAliases = $asColumns; - // add the select columns back - foreach ($selectColumns as $id => $clause) { - // Generate a unique alias - $baseAlias = 'ORA_COL_ALIAS_' . $id; - $alias = $baseAlias; - // If it already exists, add a unique suffix - $i = 0; - while (isset($columnAliases[$alias])) { - $i++; - $alias = $baseAlias . '_' . $i; - } - // Add it as an alias - $criteria->addAsColumn($alias, $clause); - $columnAliases[$alias] = $clause; - } - // Add the aliases back, don't modify them - foreach ($asColumns as $name => $clause) { - $criteria->addAsColumn($name, $clause); - } - - return $criteria; - } - - /** - * @see DBAdapter::bindValue() - * Warning: duplicates logic from OraclePlatform::getColumnBindingPHP(). - * Any code modification here must be ported there. - * - * @param PDOStatement $stmt - * @param string $parameter - * @param mixed $value - * @param ColumnMap $cMap - * @param null|integer $position - * - * @return boolean - */ - public function bindValue(PDOStatement $stmt, $parameter, $value, ColumnMap $cMap, $position = null) - { - if ($cMap->isTemporal()) { - $value = $this->formatTemporalValue($value, $cMap); - } elseif ($cMap->getType() == PropelColumnTypes::CLOB_EMU) { - return $stmt->bindParam(':p' . $position, $value, $cMap->getPdoType(), strlen($value)); - } elseif (is_resource($value) && $cMap->isLob()) { - // we always need to make sure that the stream is rewound, otherwise nothing will - // get written to database. - rewind($value); - } - - return $stmt->bindValue($parameter, $value, $cMap->getPdoType()); - } - - /** - * Do Explain Plan for query object or query string - * - * @param PropelPDO $con propel connection - * @param ModelCriteria|string $query query the criteria or the query string - * - * @throws PropelException - * @return PDOStatement A PDO statement executed using the connection, ready to be fetched - */ - public function doExplainPlan(PropelPDO $con, $query) - { - $con->beginTransaction(); - if ($query instanceof ModelCriteria) { - $params = []; - $dbMap = Propel::getDatabaseMap($query->getDbName()); - $sql = BasePeer::createSelectSql($query, $params); - } else { - $sql = $query; - } - // unique id for the query string - $uniqueId = uniqid('Propel', true); - - $stmt = $con->prepare($this->getExplainPlanQuery($sql, $uniqueId)); - - if ($query instanceof ModelCriteria) { - $this->bindValues($stmt, $params, $dbMap); - } - - $stmt->execute(); - // explain plan is save in a table, data must be commit - $con->commit(); - - $stmt = $con->prepare($this->getExplainPlanReadQuery($uniqueId)); - $stmt->execute(); - - return $stmt; - } - - /** - * Explain Plan compute query getter - * - * @param string $query query to explain - * @param string $uniqueId query unique id - * - * @return string - */ - public function getExplainPlanQuery($query, $uniqueId) - { - return sprintf('EXPLAIN PLAN SET STATEMENT_ID = \'%s\' FOR %s', $uniqueId, $query); - } - - /** - * Explain Plan read query - * - * @param string $uniqueId - * - * @return string query unique id - */ - public function getExplainPlanReadQuery($uniqueId) - { - return sprintf('SELECT LEVEL, OPERATION, OPTIONS, COST, CARDINALITY, BYTES -FROM PLAN_TABLE CONNECT BY PRIOR ID = PARENT_ID AND PRIOR STATEMENT_ID = STATEMENT_ID -START WITH ID = 0 AND STATEMENT_ID = \'%s\' ORDER BY ID', $uniqueId); - } -} diff --git a/runtime/lib/adapter/DBPostgres.php b/runtime/lib/adapter/DBPostgres.php deleted file mode 100644 index df56b826d..000000000 --- a/runtime/lib/adapter/DBPostgres.php +++ /dev/null @@ -1,252 +0,0 @@ -http://www.pgsql.org - * - * @author Hans Lellelid (Propel) - * @author Hakan Tandogan (Torque) - * @version $Revision$ - * @package propel.runtime.adapter - */ -class DBPostgres extends DBAdapter -{ - - /** - * This method is used to ignore case. - * - * @param string $in The string to transform to upper case. - * - * @return string The upper case string. - */ - public function toUpperCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * This method is used to ignore case. - * - * @param string $in The string whose case to ignore. - * - * @return string The string in a case that can be ignored. - */ - public function ignoreCase($in) - { - return 'UPPER(' . $in . ')'; - } - - /** - * Returns SQL which concatenates the second string to the first. - * - * @param string $s1 String to concatenate. - * @param string $s2 String to append. - * - * @return string - */ - public function concatString($s1, $s2) - { - return "($s1 || $s2)"; - } - - /** - * Returns SQL which extracts a substring. - * - * @param string $s String to extract from. - * @param integer $pos Offset to start from. - * @param integer $len Number of characters to extract. - * - * @return string - */ - public function subString($s, $pos, $len) - { - return "substring($s from $pos" . ($len > -1 ? "for $len" : '') . ')'; - } - - /** - * Returns SQL which calculates the length (in chars) of a string. - * - * @param string $s String to calculate length of. - * - * @return string - */ - public function strLength($s) - { - return "char_length($s)"; - } - - /** - * @see DBAdapter::getIdMethod() - * - * @return integer - */ - protected function getIdMethod() - { - return DBAdapter::ID_METHOD_SEQUENCE; - } - - /** - * Gets ID for specified sequence name. - * Warning: duplicates logic from PgsqlPlatform::getIdentifierPhp(). - * Any code modification here must be ported there. - * - * @param PDO $con - * @param string $name - * - * @return integer - * - * @throws PropelException - */ - public function getId(PDO $con, $name = null) - { - if ($name === null) { - throw new PropelException('Unable to fetch next sequence ID without sequence name.'); - } - $stmt = $con->query('SELECT nextval(' . $con->quote($name) . ')'); - $row = $stmt->fetch(PDO::FETCH_NUM); - - return $row[0]; - } - - /** - * Returns timestamp formatter string for use in date() function. - * - * @return string - */ - public function getTimestampFormatter() - { - return 'Y-m-d H:i:s O'; - } - - /** - * Returns timestamp formatter string for use in date() function. - * - * @return string - */ - public function getTimeFormatter() - { - return 'H:i:s O'; - } - - /** - * @see DBAdapter::applyLimit() - * - * @param string $sql - * @param integer $offset - * @param integer $limit - */ - public function applyLimit(&$sql, $offset, $limit) - { - if ($limit > 0) { - $sql .= ' LIMIT ' . $limit; - } - if ($offset > 0) { - $sql .= ' OFFSET ' . $offset; - } - } - - /** - * @see DBAdapter::random() - * - * @param string $seed - * - * @return string - */ - public function random($seed = null) - { - return 'random()'; - } - - /** - * @see DBAdapter::getDeleteFromClause() - * - * @param Criteria $criteria - * @param string $tableName - * - * @return string - */ - public function getDeleteFromClause($criteria, $tableName) - { - $sql = 'DELETE '; - if ($queryComment = $criteria->getComment()) { - $sql .= '/* ' . $queryComment . ' */ '; - } - if ($realTableName = $criteria->getTableForAlias($tableName)) { - if ($this->useQuoteIdentifier()) { - $realTableName = $this->quoteIdentifierTable($realTableName); - } - $sql .= 'FROM ' . $realTableName . ' AS ' . $tableName; - } else { - if ($this->useQuoteIdentifier()) { - $tableName = $this->quoteIdentifierTable($tableName); - } - $sql .= 'FROM ' . $tableName; - } - - return $sql; - } - - /** - * @see DBAdapter::quoteIdentifierTable() - * - * @param string $table - * - * @return string - */ - public function quoteIdentifierTable($table) - { - // e.g. 'database.table alias' should be escaped as '"database"."table" "alias"' - return '"' . strtr($table, ['.' => '"."', ' ' => '" "']) . '"'; - } - - /** - * Do Explain Plan for query object or query string - * - * @param PropelPDO $con propel connection - * @param ModelCriteria|string $query query the criteria or the query string - * - * @throws PropelException - * @return PDOStatement A PDO statement executed using the connection, ready to be fetched - */ - public function doExplainPlan(PropelPDO $con, $query) - { - if ($query instanceof ModelCriteria) { - $params = []; - $dbMap = Propel::getDatabaseMap($query->getDbName()); - $sql = BasePeer::createSelectSql($query, $params); - } else { - $sql = $query; - } - - $stmt = $con->prepare($this->getExplainPlanQuery($sql)); - - if ($query instanceof ModelCriteria) { - $this->bindValues($stmt, $params, $dbMap); - } - - $stmt->execute(); - - return $stmt; - } - - /** - * Explain Plan compute query getter - * - * @param string $query query to explain - * - * @return string - */ - public function getExplainPlanQuery($query) - { - return 'EXPLAIN ' . $query; - } -} diff --git a/runtime/lib/adapter/DBSQLSRV.php b/runtime/lib/adapter/DBSQLSRV.php deleted file mode 100644 index 240ba0256..000000000 --- a/runtime/lib/adapter/DBSQLSRV.php +++ /dev/null @@ -1,115 +0,0 @@ -setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $con->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false); - - parent::initConnection($con, $settings); - } - - /** - * @see parent::setCharset() - * - * @param PDO $con - * @param string $charset - * - * @throws PropelException - */ - public function setCharset(PDO $con, $charset) - { - switch (strtolower($charset)) { - case 'utf-8': - $con->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_UTF8); - break; - case 'system': - $con->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_SYSTEM); - break; - default: - throw new PropelException('only utf-8 or system encoding are supported by the pdo_sqlsrv driver'); - } - } - - /** - * @see parent::cleanupSQL() - * - * @param string $sql - * @param array $params - * @param Criteria $values - * @param DatabaseMap $dbMap - */ - public function cleanupSQL(&$sql, array &$params, Criteria $values, DatabaseMap $dbMap) - { - $i = 1; - foreach ($params as $param) { - $tableName = $param['table']; - $columnName = $param['column']; - $value = $param['value']; - - // this is to workaround for a bug with pdo_sqlsrv inserting or updating blobs with null values - // http://social.msdn.microsoft.com/Forums/en-US/sqldriverforphp/thread/5a755bdd-41e9-45cb-9166-c9da4475bb94 - if (null !== $tableName) { - $cMap = $dbMap->getTable($tableName)->getColumn($columnName); - if ($value === null && $cMap->isLob()) { - $sql = str_replace(":p$i", "CONVERT(VARBINARY(MAX), :p$i)", $sql); - } - } - $i++; - } - } - - /** - * @see DBAdapter::bindValue() - * - * @param PDOStatement $stmt - * @param string $parameter - * @param mixed $value - * @param ColumnMap $cMap - * @param null|integer $position - * - * @return boolean - */ - public function bindValue(PDOStatement $stmt, $parameter, $value, ColumnMap $cMap, $position = null) - { - if ($cMap->isTemporal()) { - $value = $this->formatTemporalValue($value, $cMap); - } elseif (is_resource($value) && $cMap->isLob()) { - // we always need to make sure that the stream is rewound, otherwise nothing will - // get written to database. - rewind($value); - // pdo_sqlsrv must have bind binaries using bindParam so that the PDO::SQLSRV_ENCODING_BINARY - // driver option can be utilized. This requires a unique blob parameter because the bindParam - // value is passed by reference and if we didn't do this then the referenced parameter value - // would change on the next loop - $blob = 'blob' . $position; - $$blob = $value; - - return $stmt->bindParam($parameter, ${$blob}, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY); - } - - return $stmt->bindValue($parameter, $value, $cMap->getPdoType()); - } -} diff --git a/runtime/lib/adapter/MSSQL/MssqlDebugPDO.php b/runtime/lib/adapter/MSSQL/MssqlDebugPDO.php deleted file mode 100644 index 3265b43bc..000000000 --- a/runtime/lib/adapter/MSSQL/MssqlDebugPDO.php +++ /dev/null @@ -1,19 +0,0 @@ -getNestedTransactionCount(); - if ($opcount === 0) { - $return = self::exec('BEGIN TRANSACTION'); - if ($this->useDebug) { - $this->log('Begin transaction', null, __METHOD__); - } - $this->isUncommitable = false; - } - $this->nestedTransactionCount++; - - return $return; - } - - /** - * Commit a transaction. - * - * It is necessary to override the abstract PDO transaction functions here, as - * the PDO driver for MSSQL does not support transactions. - * - * @return integer - * - * @throws PropelException - */ - public function commit() - { - $return = true; - $opcount = $this->getNestedTransactionCount(); - if ($opcount > 0) { - if ($opcount === 1) { - if ($this->isUncommitable) { - throw new PropelException('Cannot commit because a nested transaction was rolled back'); - } - - $return = self::exec('COMMIT TRANSACTION'); - if ($this->useDebug) { - $this->log('Commit transaction', null, __METHOD__); - } - } - $this->nestedTransactionCount--; - } - - return $return; - } - - /** - * Roll-back a transaction. - * - * It is necessary to override the abstract PDO transaction functions here, as - * the PDO driver for MSSQL does not support transactions. - * - * @return integer - */ - public function rollBack() - { - $return = true; - $opcount = $this->getNestedTransactionCount(); - if ($opcount > 0) { - if ($opcount === 1) { - $return = self::exec('ROLLBACK TRANSACTION'); - if ($this->useDebug) { - $this->log('Rollback transaction', null, __METHOD__); - } - } else { - $this->isUncommitable = true; - } - $this->nestedTransactionCount--; - } - - return $return; - } - - /** - * Rollback the whole transaction, even if this is a nested rollback - * and reset the nested transaction count to 0. - * - * It is necessary to override the abstract PDO transaction functions here, as - * the PDO driver for MSSQL does not support transactions. - * - * @return integer - */ - public function forceRollBack() - { - $return = true; - $opcount = $this->getNestedTransactionCount(); - if ($opcount > 0) { - // If we're in a transaction, always roll it back - // regardless of nesting level. - $return = self::exec('ROLLBACK TRANSACTION'); - - // reset nested transaction count to 0 so that we don't - // try to commit (or rollback) the transaction outside this scope. - $this->nestedTransactionCount = 0; - - if ($this->useDebug) { - $this->log('Rollback transaction', null, __METHOD__); - } - } - - return $return; - } - - /** - * @param string $seqname - * - * @return integer - */ - public function lastInsertId($seqname = null) - { - $result = self::query('SELECT SCOPE_IDENTITY()'); - - return (int) $result->fetchColumn(); - } - - /** - * @param string $text - * - * @return string - */ - public function quoteIdentifier($text) - { - return '[' . $text . ']'; - } - - /** - * @return boolean - */ - public function useQuoteIdentifier() - { - return true; - } -} diff --git a/runtime/lib/collection/PropelArrayCollection.php b/runtime/lib/collection/PropelArrayCollection.php index 6d9a6dfe5..20581a994 100644 --- a/runtime/lib/collection/PropelArrayCollection.php +++ b/runtime/lib/collection/PropelArrayCollection.php @@ -164,7 +164,7 @@ public function toArray($keyColumn = null, $usePrefix = false, $keyType = BasePe * * @return array */ - public function getArrayCopy($keyColumn = null, $usePrefix = false) + public function getArrayCopy($keyColumn = null, $usePrefix = false): array { if (null === $keyColumn && false === $usePrefix) { return parent::getArrayCopy(); diff --git a/runtime/lib/collection/PropelCollection.php b/runtime/lib/collection/PropelCollection.php index 652935146..8aa3005ed 100644 --- a/runtime/lib/collection/PropelCollection.php +++ b/runtime/lib/collection/PropelCollection.php @@ -28,17 +28,17 @@ class PropelCollection extends ArrayObject implements Serializable { /** - * @var string + * @var class-string|string */ protected $model = ''; /** - * @var ArrayIterator + * @var ArrayIterator|null */ protected $iterator; /** - * @var PropelFormatter + * @var PropelFormatter */ protected $formatter; @@ -362,29 +362,28 @@ public function diff(PropelCollection $collection) // Serializable interface - /** - * @return string - */ - public function serialize() + public function serialize(): string { - $repr = [ + return serialize($this->__serialize()); + } + + public function __serialize(): array + { + return [ 'data' => $this->getArrayCopy(), 'model' => $this->model, ]; + } - return serialize($repr); + public function unserialize(string $data): void + { + $this->__unserialize(unserialize($data)); } - /** - * @param string $data - * - * @return void - */ - public function unserialize($data) + public function __unserialize(array $data): void { - $repr = unserialize($data); - $this->exchangeArray($repr['data']); - $this->model = $repr['model']; + $this->exchangeArray($data['data']); + $this->model = $data['model']; } // IteratorAggregate method @@ -395,17 +394,14 @@ public function unserialize($data) * * @return ArrayIterator */ - public function getIterator() + public function getIterator(): Iterator { $this->iterator = new ArrayIterator($this); return $this->iterator; } - /** - * @return ArrayIterator - */ - public function getInternalIterator() + public function getInternalIterator(): ArrayIterator { return $this->iterator ?? $this->getIterator(); } @@ -437,7 +433,7 @@ public function setModel($model) /** * Get the model of the elements in the collection * - * @return string Name of the Propel object class stored in the collection + * @return class-string|string Name of the Propel object class stored in the collection */ public function getModel() { diff --git a/runtime/lib/collection/PropelObjectCollection.php b/runtime/lib/collection/PropelObjectCollection.php index fad119201..2fa3ee415 100644 --- a/runtime/lib/collection/PropelObjectCollection.php +++ b/runtime/lib/collection/PropelObjectCollection.php @@ -33,7 +33,7 @@ public function save($con = null) } $con->beginTransaction(); try { - /** @var $element BaseObject */ + /** @var BaseObject $element */ foreach ($this as $element) { $element->save($con); } @@ -61,7 +61,7 @@ public function delete($con = null) } $con->beginTransaction(); try { - /** @var $element BaseObject */ + /** @var BaseObject $element */ foreach ($this as $element) { $element->delete($con); } @@ -83,9 +83,10 @@ public function getPrimaryKeys($usePrefix = true) { $ret = []; - /** @var $obj BaseObject */ + /** @var BaseObject $obj */ foreach ($this as $key => $obj) { $key = $usePrefix ? ($this->getModel() . '_' . $key) : $key; + /** @psalm-suppress UndefinedMagicMethod */ $ret[$key] = $obj->getPrimaryKey(); } @@ -103,8 +104,9 @@ public function fromArray($arr) { $class = $this->getModel(); foreach ($arr as $element) { - /** @var $obj BaseObject */ + /** @var BaseObject $obj */ $obj = new $class(); + /** @psalm-suppress UndefinedMagicMethod */ $obj->fromArray($element); $this->append($obj); } @@ -113,9 +115,9 @@ public function fromArray($arr) /** * Get an array representation of the collection * - * @param string $keyColumn If null, the returned array uses an incremental index. + * @param string $keyColumn If null, the returned array uses an incremental index. * Otherwise, the array is indexed using the specified column - * @param boolean $usePrefix If true, the returned array prefixes keys + * @param boolean $usePrefix If true, the returned array prefixes keys * with the model class name ('Article_0', 'Article_1', etc). * * @@ -138,7 +140,7 @@ public function fromArray($arr) * * @return array */ - public function getArrayCopy($keyColumn = null, $usePrefix = false) + public function getArrayCopy($keyColumn = null, $usePrefix = false): array { if (null === $keyColumn && false === $usePrefix) { return parent::getArrayCopy(); diff --git a/runtime/lib/collection/PropelOnDemandCollection.php b/runtime/lib/collection/PropelOnDemandCollection.php index 4fb342936..a1e7a1672 100644 --- a/runtime/lib/collection/PropelOnDemandCollection.php +++ b/runtime/lib/collection/PropelOnDemandCollection.php @@ -17,7 +17,7 @@ class PropelOnDemandCollection extends PropelCollection { /** - * @var PropelOnDemandIterator + * @var PropelOnDemandIterator */ protected $iterator; @@ -39,7 +39,7 @@ public function initIterator(PropelFormatter $formatter, PDOStatement $stmt) * * @throws PropelException */ - public function fromArray($arr) + public function fromArray($arr): void { throw new PropelException('The On Demand Collection is read only'); } @@ -49,7 +49,7 @@ public function fromArray($arr) /** * @return PropelOnDemandIterator */ - public function getIterator() + public function getIterator(): Iterator { return $this->iterator; } @@ -58,12 +58,8 @@ public function getIterator() /** * @throws PropelException - * - * @param integer $offset - * - * @return boolean */ - public function offsetExists($offset) + public function offsetExists(mixed $key): bool { throw new PropelException('The On Demand Collection does not allow access by offset'); } @@ -71,11 +67,11 @@ public function offsetExists($offset) /** * @throws PropelException * - * @param integer $offset + * @param integer $key * * @return mixed */ - public function offsetGet($offset) + public function offsetGet(mixed $key): mixed { throw new PropelException('The On Demand Collection does not allow access by offset'); } @@ -83,10 +79,10 @@ public function offsetGet($offset) /** * @throws PropelException * - * @param integer $offset + * @param integer $key * @param mixed $value */ - public function offsetSet($offset, $value) + public function offsetSet(mixed $key, mixed $value): void { throw new PropelException('The On Demand Collection is read only'); } @@ -94,9 +90,9 @@ public function offsetSet($offset, $value) /** * @throws PropelException * - * @param integer $offset + * @param integer $key */ - public function offsetUnset($offset) + public function offsetUnset(mixed $key): void { throw new PropelException('The On Demand Collection is read only'); } @@ -106,19 +102,31 @@ public function offsetUnset($offset) /** * @throws PropelException */ - public function serialize() + public function serialize(): string + { + throw new PropelException('The On Demand Collection cannot be serialized'); + } + + /** + * @throws PropelException + */ + public function __serialize(): array + { + throw new PropelException('The On Demand Collection cannot be serialized'); + } + + /** + * @throws PropelException + */ + public function unserialize(string $data): void { throw new PropelException('The On Demand Collection cannot be serialized'); } /** * @throws PropelException - * - * @param string $data - * - * @return void */ - public function unserialize($data) + public function __unserialize(array $data): void { throw new PropelException('The On Demand Collection cannot be serialized'); } @@ -131,77 +139,115 @@ public function unserialize($data) * * @return integer Number of results */ - public function count() + public function count(): int { return $this->iterator->count(); } // ArrayObject methods - public function append($value) + /** + * @throws PropelException + */ + public function append(mixed $value): void { throw new PropelException('The On Demand Collection is read only'); } - public function prepend($value) + /** + * @throws PropelException + */ + public function prepend(mixed $value): void { throw new PropelException('The On Demand Collection is read only'); } - public function asort(int $flags = SORT_REGULAR) + /** + * @throws PropelException + */ + public function asort(int $flags = SORT_REGULAR): bool { throw new PropelException('The On Demand Collection is read only'); } - public function exchangeArray($input) + /** + * @throws PropelException + */ + public function exchangeArray(object|array $array): array { throw new PropelException('The On Demand Collection is read only'); } - public function getArrayCopy() + /** + * @throws PropelException + */ + public function getArrayCopy(): array { throw new PropelException('The On Demand Collection does not allow access by offset'); } - public function getFlags() + /** + * @throws PropelException + */ + public function getFlags(): int { throw new PropelException('The On Demand Collection does not allow access by offset'); } - public function ksort(int $flags = SORT_REGULAR) + /** + * @throws PropelException + */ + public function ksort(int $flags = SORT_REGULAR): bool { throw new PropelException('The On Demand Collection is read only'); } - public function natcasesort() + /** + * @throws PropelException + */ + public function natcasesort(): bool { throw new PropelException('The On Demand Collection is read only'); } - public function natsort() + /** + * @throws PropelException + */ + public function natsort(): bool { throw new PropelException('The On Demand Collection is read only'); } - public function setFlags($flags) + /** + * @throws PropelException + */ + public function setFlags(int $flags): void { throw new PropelException('The On Demand Collection does not allow acces by offset'); } - public function uasort($cmp_function) + /** + * @throws PropelException + */ + public function uasort(callable $callback): bool { throw new PropelException('The On Demand Collection is read only'); } - public function uksort($cmp_function) + /** + * @throws PropelException + */ + public function uksort(callable $callback): bool { throw new PropelException('The On Demand Collection is read only'); } /** - * {@inheritdoc} + * @inheritDoc + * + * @throws PropelException */ - public function exportTo($parser, $usePrefix = true, $includeLazyLoadColumns = true) + public function exportTo($parser, $usePrefix = true, $includeLazyLoadColumns = true): string { throw new PropelException('A PropelOnDemandCollection cannot be exported.'); } diff --git a/runtime/lib/collection/PropelOnDemandIterator.php b/runtime/lib/collection/PropelOnDemandIterator.php index 09da34e2b..d21a5c221 100644 --- a/runtime/lib/collection/PropelOnDemandIterator.php +++ b/runtime/lib/collection/PropelOnDemandIterator.php @@ -50,7 +50,7 @@ public function __construct(PropelFormatter $formatter, PDOStatement $stmt) $this->stmt = $stmt; } - public function closeCursor() + public function closeCursor(): void { $this->stmt->closeCursor(); } @@ -61,7 +61,7 @@ public function closeCursor() * * @return integer Number of results */ - public function count() + public function count(): int { return $this->stmt->rowCount(); } @@ -74,17 +74,15 @@ public function count() * * @return BaseObject */ - public function current() + public function current(): BaseObject { return $this->formatter->getAllObjectsFromRow($this->currentRow); } /** * Gets the current key in the iterator - * - * @return string */ - public function key() + public function key(): string|int { return $this->currentKey; } @@ -93,7 +91,7 @@ public function key() * Advances the cursor in the statement * Closes the cursor if the end of the statement is reached */ - public function next() + public function next(): void { if (null === $this->currentRow) { $this->enableInstancePoolingOnFinish = Propel::disableInstancePooling(); @@ -113,7 +111,7 @@ public function next() * Initializes the iterator by advancing to the first position * This method can only be called once (this is a NoRewindIterator) */ - public function rewind() + public function rewind(): void { // check that the hydration can begin if (null === $this->formatter) { @@ -133,7 +131,7 @@ public function rewind() /** * @return boolean */ - public function valid() + public function valid(): bool { return (bool) $this->isValid; } diff --git a/runtime/lib/config/PropelConfiguration.php b/runtime/lib/config/PropelConfiguration.php index e513bb994..aa5c5ba32 100644 --- a/runtime/lib/config/PropelConfiguration.php +++ b/runtime/lib/config/PropelConfiguration.php @@ -47,7 +47,7 @@ public function __construct(array $parameters = []) * * @return boolean */ - public function offsetExists($offset) + public function offsetExists(mixed $offset): bool { return array_key_exists($offset, $this->parameters); } @@ -58,7 +58,7 @@ public function offsetExists($offset) * @param integer $offset * @param mixed $value */ - public function offsetSet($offset, $value) + public function offsetSet(mixed $offset, mixed $value): void { $this->parameters[$offset] = $value; $this->isFlattened = false; @@ -71,7 +71,7 @@ public function offsetSet($offset, $value) * * @return array */ - public function offsetGet($offset) + public function offsetGet(mixed $offset): mixed { return $this->parameters[$offset]; } @@ -81,7 +81,7 @@ public function offsetGet($offset) * * @param integer $offset */ - public function offsetUnset($offset) + public function offsetUnset(mixed $offset): void { unset($this->parameters[$offset]); $this->isFlattened = false; diff --git a/runtime/lib/config/PropelConfigurationIterator.php b/runtime/lib/config/PropelConfigurationIterator.php index d2bcf3ba3..53a2d6209 100644 --- a/runtime/lib/config/PropelConfigurationIterator.php +++ b/runtime/lib/config/PropelConfigurationIterator.php @@ -47,7 +47,7 @@ class PropelConfigurationIterator extends RecursiveIteratorIterator * * @return string */ - public function getNamespace() + public function getNamespace(): string { return implode('.', $this->namespaceStack); } @@ -61,7 +61,7 @@ public function getNamespace() * - self::NODE_PARENT * - self::NODE_ITEM */ - public function getNodeType() + public function getNodeType(): ?int { return $this->nodeType; } @@ -72,7 +72,7 @@ public function getNodeType() * @see http://www.php.net/RecursiveIteratorIterator * @return mixed */ - public function current() + public function current(): mixed { $current = parent::current(); if (is_array($current)) { @@ -90,7 +90,7 @@ public function current() * * @see http://www.php.net/RecursiveIteratorIterator */ - public function endChildren() + public function endChildren(): void { if ($this->namespaceStack) { array_pop($this->namespaceStack); diff --git a/runtime/lib/connection/DebugPDOStatement.php b/runtime/lib/connection/DebugPDOStatement.php index e7c4eafb1..86b581864 100644 --- a/runtime/lib/connection/DebugPDOStatement.php +++ b/runtime/lib/connection/DebugPDOStatement.php @@ -52,8 +52,6 @@ class DebugPDOStatement extends PDOStatement * which this instance was created. * * @param PropelPDO $pdo Reference to the parent PDO instance. - * - * @return DebugPDOStatement */ protected function __construct(PropelPDO $pdo) { @@ -65,7 +63,7 @@ protected function __construct(PropelPDO $pdo) * * @return string */ - public function getExecutedQueryString(array $values = []) + public function getExecutedQueryString(array $values = []): string { $sql = $this->queryString; $boundValues = empty($values) ? $this->boundValues : $values; @@ -91,17 +89,13 @@ public function getExecutedQueryString(array $values = []) /** * Executes a prepared statement. Returns a boolean value indicating success. * Overridden for query counting and logging. - * - * @param string $input_parameters - * - * @return boolean */ - public function execute($input_parameters = null) + public function execute(?array $params = null): bool { $debug = $this->pdo->getDebugSnapshot(); - $return = parent::execute($input_parameters); + $return = parent::execute($params); - $sql = $this->getExecutedQueryString($input_parameters ?: []); + $sql = $this->getExecutedQueryString($params ?: []); $this->pdo->log($sql, null, __METHOD__, $debug); $this->pdo->setLastExecutedQuery($sql); $this->pdo->incrementQueryCount(); @@ -113,21 +107,21 @@ public function execute($input_parameters = null) * Binds a value to a corresponding named or question mark placeholder in the SQL statement * that was use to prepare the statement. Returns a boolean value indicating success. * - * @param int|string $pos Parameter identifier (for determining what to replace in the query). + * @param int|string $param Parameter identifier (for determining what to replace in the query). * @param mixed $value The value to bind to the parameter. * @param int $type Explicit data type for the parameter using the PDO::PARAM_* constants. Defaults to PDO::PARAM_STR. * * @return bool */ - public function bindValue($pos, $value, $type = PDO::PARAM_STR) + public function bindValue(int|string $param, mixed $value, int $type = PDO::PARAM_STR): bool { $debug = $this->pdo->getDebugSnapshot(); $typestr = self::$typeMap[$type] ?? '(default)'; - $return = parent::bindValue($pos, $value, $type); + $return = parent::bindValue($param, $value, $type); $valuestr = $type == PDO::PARAM_LOB ? '[LOB value]' : var_export($value, true); - $msg = sprintf('Binding %s at position %s w/ PDO type %s', $valuestr, $pos, $typestr); + $msg = sprintf('Binding %s at position %s w/ PDO type %s', $valuestr, $param, $typestr); - $this->boundValues[$pos] = $value; + $this->boundValues[$param] = $value; $this->pdo->log($msg, null, __METHOD__, $debug); @@ -136,28 +130,31 @@ public function bindValue($pos, $value, $type = PDO::PARAM_STR) /** * Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement - * that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound + * that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound * as a reference and will only be evaluated at the time that PDOStatement::execute() is called. * Returns a boolean value indicating success. * - * @param int|string $pos Parameter identifier (for determining what to replace in the query). - * @param mixed $value The value to bind to the parameter. - * @param int $type Explicit data type for the parameter using the PDO::PARAM_* constants. Defaults to PDO::PARAM_STR. - * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length. - * @param mixed $driver_options - * - * @return bool + * @param int|string $param Parameter identifier (for determining what to replace in the query). + * @param mixed $var The value to bind to the parameter. + * @param int $type Explicit data type for the parameter using the PDO::PARAM_* constants. Defaults to PDO::PARAM_STR. + * @param int|null $maxLength Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length. + * @param mixed $driverOptions */ - public function bindParam($pos, &$value, $type = PDO::PARAM_STR, $length = 0, $driver_options = null) - { - $originalValue = $value; + public function bindParam( + int|string $param, + mixed &$var, + int $type = PDO::PARAM_STR, + int $maxLength = null, + mixed $driverOptions = null + ): bool { + $originalValue = $var; $debug = $this->pdo->getDebugSnapshot(); $typestr = self::$typeMap[$type] ?? '(default)'; - $return = parent::bindParam($pos, $value, $type, $length, $driver_options); - $valuestr = $length > 100 ? '[Large value]' : var_export($value, true); - $msg = sprintf('Binding %s at position %s w/ PDO type %s', $valuestr, $pos, $typestr); + $return = parent::bindParam($param, $var, $type, $maxLength ?: 0, $driverOptions); + $varstr = $maxLength > 100 ? '[Large value]' : var_export($var, true); + $msg = sprintf('Binding %s at position %s w/ PDO type %s', $varstr, $param, $typestr); - $this->boundValues[$pos] = $originalValue; + $this->boundValues[$param] = $originalValue; $this->pdo->log($msg, null, __METHOD__, $debug); diff --git a/runtime/lib/connection/PropelPDO.php b/runtime/lib/connection/PropelPDO.php index 34836e35b..74c418a8f 100644 --- a/runtime/lib/connection/PropelPDO.php +++ b/runtime/lib/connection/PropelPDO.php @@ -208,7 +208,7 @@ protected function setNestedTransactionCount($v) * * @return boolean */ - public function isInTransaction() + public function isInTransaction(): bool { return ($this->getNestedTransactionCount() > 0); } @@ -219,7 +219,7 @@ public function isInTransaction() * * @return boolean True if the connection is in a committable transaction */ - public function isCommitable() + public function isCommitable(): bool { return $this->isInTransaction() && !$this->isUncommitable; } @@ -229,7 +229,7 @@ public function isCommitable() * * @return boolean */ - public function beginTransaction() + public function beginTransaction(): bool { $return = true; if (!$this->nestedTransactionCount) { @@ -252,7 +252,7 @@ public function beginTransaction() * * @throws PropelException */ - public function commit() + public function commit(): bool { $return = true; $opcount = $this->nestedTransactionCount; @@ -281,7 +281,7 @@ public function commit() * * @return boolean Whether operation was successful. */ - public function rollBack() + public function rollBack(): bool { $return = true; $opcount = $this->nestedTransactionCount; @@ -336,10 +336,8 @@ public function forceRollBack() * * @param integer $attribute The attribute to set (e.g. PropelPDO::PROPEL_ATTR_CACHE_PREPARES). * @param mixed $value The attribute value. - * - * @return void */ - public function setAttribute($attribute, $value) + public function setAttribute(int $attribute, mixed $value): bool { switch ($attribute) { case self::PROPEL_ATTR_CACHE_PREPARES: @@ -349,8 +347,10 @@ public function setAttribute($attribute, $value) $this->connectionName = $value; break; default: - parent::setAttribute($attribute, $value); + return parent::setAttribute($attribute, $value); } + + return true; } /** @@ -362,7 +362,7 @@ public function setAttribute($attribute, $value) * * @return mixed */ - public function getAttribute($attribute) + public function getAttribute(int $attribute): mixed { switch ($attribute) { case self::PROPEL_ATTR_CACHE_PREPARES: @@ -381,31 +381,29 @@ public function getAttribute($attribute) * - Add logging and query counting if logging is true. * - Add query caching support if the PropelPDO::PROPEL_ATTR_CACHE_PREPARES was set to true. * - * @param string $sql This must be a valid SQL statement for the target database server. - * @param array $driver_options One $array or more key => value pairs to set attribute values + * @param string $query This must be a valid SQL statement for the target database server. + * @param array $options One $array or more key => value pairs to set attribute values * for the PDOStatement object that this method returns. - * - * @return PDOStatement */ - public function prepare($sql, $driver_options = []) + public function prepare(string $query, array $options = []): PDOStatement { if ($this->useDebug) { $debug = $this->getDebugSnapshot(); } if ($this->cachePreparedStatements) { - if (!isset($this->preparedStatements[$sql])) { - $return = parent::prepare($sql, $driver_options); - $this->preparedStatements[$sql] = $return; + if (!isset($this->preparedStatements[$query])) { + $return = parent::prepare($query, $options); + $this->preparedStatements[$query] = $return; } else { - $return = $this->preparedStatements[$sql]; + $return = $this->preparedStatements[$query]; } } else { - $return = parent::prepare($sql, $driver_options); + $return = parent::prepare($query, $options); } if ($this->useDebug) { - $this->log($sql, null, __METHOD__, $debug); + $this->log($query, null, __METHOD__, $debug); } return $return; @@ -414,22 +412,18 @@ public function prepare($sql, $driver_options = []) /** * Execute an SQL statement and return the number of affected rows. * Overrides PDO::exec() to log queries when required - * - * @param string $sql - * - * @return integer */ - public function exec($sql) + public function exec(string $statement): int|false { if ($this->useDebug) { $debug = $this->getDebugSnapshot(); } - $return = parent::exec($sql); + $return = parent::exec($statement); if ($this->useDebug) { - $this->log($sql, null, __METHOD__, $debug); - $this->setLastExecutedQuery($sql); + $this->log($statement, null, __METHOD__, $debug); + $this->setLastExecutedQuery($statement); $this->incrementQueryCount(); } @@ -447,10 +441,8 @@ public function exec($sql) * @param string $statement * @param int $mode * @param mixed $fetch_mode_args - * - * @return PDOStatement */ - public function query($statement, $mode = PDO::ATTR_DEFAULT_FETCH_MODE, ...$fetch_mode_args) + public function query($statement, $mode = PDO::ATTR_DEFAULT_FETCH_MODE, ...$fetch_mode_args): PDOStatement { if ($this->useDebug) { $debug = $this->getDebugSnapshot(); diff --git a/runtime/lib/om/NestedSetRecursiveIterator.php b/runtime/lib/om/NestedSetRecursiveIterator.php index b73d2e63a..3d2323cb0 100644 --- a/runtime/lib/om/NestedSetRecursiveIterator.php +++ b/runtime/lib/om/NestedSetRecursiveIterator.php @@ -27,22 +27,22 @@ public function __construct($node) $this->curNode = $node; } - public function rewind() + public function rewind(): void { $this->curNode = $this->topNode; } - public function valid() + public function valid(): bool { return ($this->curNode !== null); } - public function current() + public function current(): mixed { return $this->curNode; } - public function key() + public function key(): string { $method = method_exists($this->curNode, 'getPath') ? 'getPath' : 'getAncestors'; $key = []; @@ -53,7 +53,7 @@ public function key() return implode('.', $key); } - public function next() + public function next(): void { $nextNode = null; $method = method_exists($this->curNode, 'retrieveNextSibling') ? 'retrieveNextSibling' : 'getNextSibling'; @@ -71,16 +71,14 @@ public function next() } $this->curNode = $nextNode; } - - return $this->curNode; } - public function hasChildren() + public function hasChildren(): bool { return $this->curNode->hasChildren(); } - public function getChildren() + public function getChildren(): NestedSetRecursiveIterator { $method = method_exists($this->curNode, 'retrieveFirstChild') ? 'retrieveFirstChild' : 'getFirstChild'; diff --git a/runtime/lib/parser/PropelXMLParser.php b/runtime/lib/parser/PropelXMLParser.php index 9249c11dd..94e82bdd7 100644 --- a/runtime/lib/parser/PropelXMLParser.php +++ b/runtime/lib/parser/PropelXMLParser.php @@ -116,7 +116,7 @@ protected function arrayToDOM($array, $rootElement, $charset = null, $removeNumb $child = $element->ownerDocument->createCDATASection($value); $element->appendChild($child); } else { - $child = $element->ownerDocument->createTextNode($value); + $child = $element->ownerDocument->createTextNode((string) $value); $element->appendChild($child); } $rootElement->appendChild($element); diff --git a/runtime/lib/parser/yaml/sfYamlInline.php b/runtime/lib/parser/yaml/sfYamlInline.php index 7ad73706c..8c81fa795 100644 --- a/runtime/lib/parser/yaml/sfYamlInline.php +++ b/runtime/lib/parser/yaml/sfYamlInline.php @@ -90,11 +90,11 @@ public static function dump($value) return 'true'; case false === $value: return 'false'; - case ctype_digit($value): + case ctype_digit((string) $value): return is_string($value) ? "'$value'" : (int) $value; case is_numeric($value): - return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'$value'" : $value); - case false !== strpos($value, "\n") || false !== strpos($value, "\r"): + return is_infinite($value) ? str_ireplace('INF', '.Inf', (string) $value) : (is_string($value) ? "'$value'" : $value); + case str_contains($value, "\n") || str_contains($value, "\r"): return sprintf('"%s"', str_replace(['"', "\n", "\r"], ['\\"', '\n', '\r'], $value)); case preg_match('/[ \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): return sprintf("'%s'", str_replace('\'', '\'\'', $value)); @@ -354,15 +354,15 @@ protected static function evaluateScalar($scalar) case '' == $scalar: case '~' == $scalar: return null; - case 0 === strpos($scalar, '!str'): - return (string) substr($scalar, 5); - case 0 === strpos($scalar, '! '): - return intval(self::parseScalar(substr($scalar, 2))); - case 0 === strpos($scalar, '!!php/object:'): + case str_starts_with($scalar, '!str'): + return substr($scalar, 5); + case str_starts_with($scalar, '! '): + return (int) self::parseScalar(substr($scalar, 2)); + case str_starts_with($scalar, '!!php/object:'): return unserialize(substr($scalar, 13)); case ctype_digit($scalar): $raw = $scalar; - $cast = intval($scalar); + $cast = (int) $scalar; return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); case in_array(strtolower($scalar), $trueValues): @@ -377,7 +377,7 @@ protected static function evaluateScalar($scalar) case 0 == strcasecmp($scalar, '-.inf'): return log(0); case preg_match('/^(-|\+)?[\d,]+(\.\d+)?$/', $scalar): - return floatval(str_replace(',', '', $scalar)); + return (float) str_replace(',', '', $scalar); case preg_match(self::getTimestampRegex(), $scalar): return strtotime($scalar); default: diff --git a/runtime/lib/query/Criteria.php b/runtime/lib/query/Criteria.php index bc5966ebb..eacc5fbf2 100644 --- a/runtime/lib/query/Criteria.php +++ b/runtime/lib/query/Criteria.php @@ -279,7 +279,7 @@ public function __construct($dbName = null) * Implementing SPL IteratorAggregate interface. This allows * you to foreach () over a Criteria object. */ - public function getIterator() + public function getIterator(): CriterionIterator { return new CriterionIterator($this); } diff --git a/runtime/lib/query/Criterion.php b/runtime/lib/query/Criterion.php index 0f752ade4..9c24a2dd9 100644 --- a/runtime/lib/query/Criterion.php +++ b/runtime/lib/query/Criterion.php @@ -71,17 +71,17 @@ class Criterion /** * Create a new instance. * - * @param Criteria $outer The outer class (this is an "inner" class). - * @param string $column TABLE.COLUMN format. - * @param mixed $value - * @param string $comparison - * @param string $type + * @param Criteria $outer The outer class (this is an "inner" class). + * @param string|null $column TABLE.COLUMN format. + * @param mixed $value + * @param string|null $comparison + * @param string $type */ public function __construct(Criteria $outer, $column, $value, $comparison = null, $type = null) { $this->value = $value; - $dotPos = strrpos($column, '.'); - if ($dotPos === false || $comparison == Criteria::RAW) { + $dotPos = $column ? strrpos($column, '.') : false; + if ($dotPos === false || $comparison === Criteria::RAW) { // no dot => aliased column $this->table = null; $this->column = $column; @@ -396,27 +396,19 @@ protected function appendLikeToPs(&$sb, array &$params) { $field = ($this->table === null) ? $this->column : $this->table . '.' . $this->column; $db = $this->getDb(); - // If selection is case insensitive use ILIKE for PostgreSQL or SQL + // If selection is case-insensitive use ILIKE for PostgreSQL or SQL // UPPER() function on column name for other databases. if ($this->ignoreStringCase) { - if ($db instanceof DBPostgres) { - if ($this->comparison === Criteria::LIKE) { - $this->comparison = Criteria::ILIKE; - } elseif ($this->comparison === Criteria::NOT_LIKE) { - $this->comparison = Criteria::NOT_ILIKE; - } - } else { - $field = $db->ignoreCase($field); - } + $field = $db->ignoreCase($field); } $params[] = ['table' => $this->realtable, 'column' => $this->column, 'value' => $this->value]; $sb .= $field . $this->comparison; - // If selection is case insensitive use SQL UPPER() function + // If selection is case-insensitive use SQL UPPER() function // on criteria or, if Postgres we are using ILIKE, so not necessary. - if ($this->ignoreStringCase && !($db instanceof DBPostgres)) { + if ($this->ignoreStringCase) { $sb .= $db->ignoreCase(':p' . count($params)); } else { $sb .= ':p' . count($params); diff --git a/runtime/lib/query/CriterionIterator.php b/runtime/lib/query/CriterionIterator.php index 82dc058f3..69c2dd583 100644 --- a/runtime/lib/query/CriterionIterator.php +++ b/runtime/lib/query/CriterionIterator.php @@ -32,27 +32,27 @@ public function __construct(Criteria $criteria) $this->criteriaSize = count($this->criteriaKeys); } - public function rewind() + public function rewind(): void { $this->idx = 0; } - public function valid() + public function valid(): bool { return $this->idx < $this->criteriaSize; } - public function key() + public function key(): string|int { return $this->criteriaKeys[$this->idx]; } - public function current() + public function current(): Criterion { return $this->criteria->getCriterion($this->criteriaKeys[$this->idx]); } - public function next() + public function next(): void { $this->idx++; } diff --git a/runtime/lib/query/ModelCriteria.php b/runtime/lib/query/ModelCriteria.php index 00dd6426e..48867c928 100644 --- a/runtime/lib/query/ModelCriteria.php +++ b/runtime/lib/query/ModelCriteria.php @@ -896,7 +896,7 @@ public function getWith() * Sets the array of ModelWith specifying which objects must be hydrated * together with the main object. * - * @param array + * @param array $with * * @return ModelCriteria The current object, for fluid interface */ diff --git a/runtime/lib/query/ModelCriterion.php b/runtime/lib/query/ModelCriterion.php index 51aa1a955..596bc4a87 100644 --- a/runtime/lib/query/ModelCriterion.php +++ b/runtime/lib/query/ModelCriterion.php @@ -140,11 +140,6 @@ public function appendModelClauseToPs(&$sb, array &$params) */ public function appendModelClauseLikeToPs(&$sb, array &$params) { - // LIKE is case insensitive in mySQL and SQLite, but not in PostGres - // If the column is case insensitive, use ILIKE / NOT ILIKE instead of LIKE / NOT LIKE - if ($this->ignoreStringCase && $this->getDb() instanceof DBPostgres) { - $this->clause = preg_replace('/LIKE \?$/i', 'ILIKE ?', $this->clause); - } $this->appendModelClauseToPs($sb, $params); } diff --git a/runtime/lib/util/PropelDateTime.php b/runtime/lib/util/PropelDateTime.php index 6f412147c..a5ef51ad6 100644 --- a/runtime/lib/util/PropelDateTime.php +++ b/runtime/lib/util/PropelDateTime.php @@ -119,7 +119,7 @@ public function __sleep() * PHP "magic" function called when object is restored from serialized state. * Calls DateTime constructor with previously stored string value of date. */ - public function __wakeup() + public function __wakeup(): void { parent::__construct($this->dateString, new DateTimeZone($this->tzString)); } diff --git a/runtime/lib/util/PropelModelPager.php b/runtime/lib/util/PropelModelPager.php index 05f01de64..173d83f05 100644 --- a/runtime/lib/util/PropelModelPager.php +++ b/runtime/lib/util/PropelModelPager.php @@ -392,7 +392,7 @@ public function isEven() return $this->getResults()->isEven(); } - public function getIterator() + public function getIterator(): Iterator { return $this->getResults()->getIterator(); } @@ -403,7 +403,7 @@ public function getIterator() * @see Countable * @return int */ - public function count() + public function count(): int { return $this->getNbResults(); } diff --git a/runtime/lib/util/PropelPager.php b/runtime/lib/util/PropelPager.php index 8dadf77ae..500184b9f 100644 --- a/runtime/lib/util/PropelPager.php +++ b/runtime/lib/util/PropelPager.php @@ -560,7 +560,7 @@ public function setMax($v) * * @return int */ - public function count() + public function count(): int { return count($this->getResult()); } @@ -570,7 +570,7 @@ public function count() * * @return mixed */ - public function current() + public function current(): mixed { if (!isset($this->rs)) { $this->doRs(); @@ -584,7 +584,7 @@ public function current() * * @return int */ - public function key() + public function key(): int { return $this->currentKey; } @@ -594,7 +594,7 @@ public function key() * * @return void */ - public function next() + public function next(): void { $this->currentKey++; } @@ -604,7 +604,7 @@ public function next() * * @return void */ - public function rewind() + public function rewind(): void { $this->currentKey = 0; } @@ -614,7 +614,7 @@ public function rewind() * * @return boolean */ - public function valid() + public function valid(): bool { if (!isset($this->rs)) { $this->doRs(); diff --git a/runtime/lib/validator/BasicValidator.php b/runtime/lib/validator/BasicValidator.php index a88d21591..79aea6f14 100644 --- a/runtime/lib/validator/BasicValidator.php +++ b/runtime/lib/validator/BasicValidator.php @@ -25,7 +25,7 @@ interface BasicValidator * Determine whether a value meets the criteria specified * * @param ValidatorMap $map A column map object for the column to be validated. - * @param string $str a String to be tested + * @param string|null $str a String to be tested * * @return mixed TRUE if valid, error message otherwise */ diff --git a/runtime/lib/validator/MatchValidator.php b/runtime/lib/validator/MatchValidator.php index 350632196..065ee2a71 100644 --- a/runtime/lib/validator/MatchValidator.php +++ b/runtime/lib/validator/MatchValidator.php @@ -61,13 +61,10 @@ private function prepareRegexp($exp) /** * Whether the passed string matches regular expression. * - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { - return (preg_match($this->prepareRegexp($map->getValue()), $str) != 0); + return (preg_match($this->prepareRegexp($map->getValue()), (string) $str) != 0); } } diff --git a/runtime/lib/validator/MaxLengthValidator.php b/runtime/lib/validator/MaxLengthValidator.php index 4e1f0f3c4..efbf04ca7 100644 --- a/runtime/lib/validator/MaxLengthValidator.php +++ b/runtime/lib/validator/MaxLengthValidator.php @@ -32,15 +32,10 @@ class MaxLengthValidator implements BasicValidator { /** - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { - $len = function_exists('mb_strlen') ? mb_strlen($str) : strlen($str); - - return $len <= intval($map->getValue()); + return mb_strlen((string) $str) <= (int) $map->getValue(); } } diff --git a/runtime/lib/validator/MaxValueValidator.php b/runtime/lib/validator/MaxValueValidator.php index 82a86ffac..4658d4b39 100644 --- a/runtime/lib/validator/MaxValueValidator.php +++ b/runtime/lib/validator/MaxValueValidator.php @@ -29,17 +29,12 @@ class MaxValueValidator implements BasicValidator { /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param mixed $value - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $value) { - if (is_null($value) == false && is_numeric($value) == true) { - return intval($value) <= intval($map->getValue()); + if (is_numeric($value) == true) { + return (int) $value <= (int) $map->getValue(); } return false; diff --git a/runtime/lib/validator/MinLengthValidator.php b/runtime/lib/validator/MinLengthValidator.php index 57875f33c..59a87baee 100644 --- a/runtime/lib/validator/MinLengthValidator.php +++ b/runtime/lib/validator/MinLengthValidator.php @@ -26,17 +26,10 @@ class MinLengthValidator implements BasicValidator { /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { - $len = function_exists('mb_strlen') ? mb_strlen($str) : strlen($str); - - return $len >= intval($map->getValue()); + return mb_strlen((string) $str) >= (int) $map->getValue(); } } diff --git a/runtime/lib/validator/MinValueValidator.php b/runtime/lib/validator/MinValueValidator.php index bd73e69b5..4a624a985 100644 --- a/runtime/lib/validator/MinValueValidator.php +++ b/runtime/lib/validator/MinValueValidator.php @@ -29,17 +29,12 @@ class MinValueValidator implements BasicValidator { /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param mixed $value - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $value) { - if (is_null($value) == false && is_numeric($value)) { - return intval($value) >= intval($map->getValue()); + if (is_numeric($value)) { + return (int) $value >= (int) $map->getValue(); } return false; diff --git a/runtime/lib/validator/NotMatchValidator.php b/runtime/lib/validator/NotMatchValidator.php index e488fa4a3..a3eb91318 100644 --- a/runtime/lib/validator/NotMatchValidator.php +++ b/runtime/lib/validator/NotMatchValidator.php @@ -57,15 +57,10 @@ private function prepareRegexp($exp) } /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { - return (preg_match($this->prepareRegexp($map->getValue()), $str) == 0); + return (preg_match($this->prepareRegexp($map->getValue()), (string) $str) == 0); } } diff --git a/runtime/lib/validator/RequiredValidator.php b/runtime/lib/validator/RequiredValidator.php index 68eaebb63..f58d3dae6 100644 --- a/runtime/lib/validator/RequiredValidator.php +++ b/runtime/lib/validator/RequiredValidator.php @@ -28,15 +28,10 @@ class RequiredValidator implements BasicValidator { /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { - return ($str !== null && $str !== ''); + return $str !== null && $str !== ''; } } diff --git a/runtime/lib/validator/TypeValidator.php b/runtime/lib/validator/TypeValidator.php index 78ec52d5c..a3f86f473 100644 --- a/runtime/lib/validator/TypeValidator.php +++ b/runtime/lib/validator/TypeValidator.php @@ -37,31 +37,18 @@ class TypeValidator implements BasicValidator */ public function isValid(ValidatorMap $map, $value) { - switch ($map->getValue()) { - case 'array': - return is_array($value); - case 'bool': - case 'boolean': - return is_bool($value); - case 'float': - return is_float($value); - case 'int': - case 'integer': - return is_int($value); - case 'numeric': - return is_numeric($value); - case 'object': - return is_object($value); - case 'resource': - return is_resource($value); - case 'scalar': - return is_scalar($value); - case 'string': - return is_string($value); - case 'function': - return function_exists($value); - default: - throw new PropelException('Unknown type ' . $map->getValue()); - } + return match ($map->getValue()) { + 'array' => is_array($value), + 'bool', 'boolean' => is_bool($value), + 'float' => is_float($value), + 'int', 'integer' => is_int($value), + 'numeric' => is_numeric($value), + 'object' => is_object($value), + 'resource' => is_resource($value), + 'scalar' => is_scalar($value), + 'string' => is_string($value), + 'function' => function_exists($value), + default => throw new PropelException('Unknown type ' . $map->getValue()), + }; } } diff --git a/runtime/lib/validator/UniqueValidator.php b/runtime/lib/validator/UniqueValidator.php index 13083ce37..6d698672c 100644 --- a/runtime/lib/validator/UniqueValidator.php +++ b/runtime/lib/validator/UniqueValidator.php @@ -26,12 +26,7 @@ class UniqueValidator implements BasicValidator { /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { diff --git a/runtime/lib/validator/ValidValuesValidator.php b/runtime/lib/validator/ValidValuesValidator.php index cd5098609..2275c2d28 100644 --- a/runtime/lib/validator/ValidValuesValidator.php +++ b/runtime/lib/validator/ValidValuesValidator.php @@ -26,12 +26,7 @@ class ValidValuesValidator implements BasicValidator { /** - * @see BasicValidator::isValid() - * - * @param ValidatorMap $map - * @param string $str - * - * @return boolean + * @inheritDoc */ public function isValid(ValidatorMap $map, $str) { diff --git a/test/fixtures/reverse/pgsql/runtime-conf.xml b/test/fixtures/reverse/pgsql/runtime-conf.xml deleted file mode 100644 index 4e2b972bd..000000000 --- a/test/fixtures/reverse/pgsql/runtime-conf.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - pgsql - - DebugPDO - pgsql:host=127.0.0.1;dbname=reverse_bookstore - - - - - - - - - utf8 - - - - - - - diff --git a/test/testsuite/generator/model/diff/PropelForeignKeyComparatorTest.php b/test/testsuite/generator/model/diff/PropelForeignKeyComparatorTest.php index f54e4974c..7697b7a20 100644 --- a/test/testsuite/generator/model/diff/PropelForeignKeyComparatorTest.php +++ b/test/testsuite/generator/model/diff/PropelForeignKeyComparatorTest.php @@ -18,7 +18,7 @@ * * @package generator.model.diff */ -class PropelForeignComparatorTest extends TestCase +class PropelForeignKeyComparatorTest extends TestCase { public function testCompareNoDifference(): void { diff --git a/test/testsuite/generator/platform/MssqlPlatformTest.php b/test/testsuite/generator/platform/MssqlPlatformTest.php deleted file mode 100644 index 0bedd6c29..000000000 --- a/test/testsuite/generator/platform/MssqlPlatformTest.php +++ /dev/null @@ -1,640 +0,0 @@ -setIdMethod(IDMethod::NATIVE); - $expected = 'foo_SEQ'; - $this->assertSame($expected, $this->getPlatform()->getSequenceName($table)); - } - - public function testGetSequenceNameCustom(): void - { - $table = new Table('foo'); - $table->setIdMethod(IDMethod::NATIVE); - $idMethodParameter = new IdMethodParameter(); - $idMethodParameter->setValue('foo_sequence'); - $table->addIdMethodParameter($idMethodParameter); - $table->setIdMethod(IDMethod::NATIVE); - $expected = 'foo_sequence'; - $this->assertSame($expected, $this->getPlatform()->getSequenceName($table)); - } - - /** - * @dataProvider providerForTestGetAddTablesDDL - */ - public function testGetAddTablesDDL($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertSame($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTablesDDLSchema - */ - public function testGetAddTablesDDLSchemas($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertSame($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTablesSkipSQLDDL - */ - public function testGetAddTablesSkipSQLDDL($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = ''; - $this->assertSame($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSimplePK - */ - public function testGetAddTableDDLSimplePK($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = ' --- This is foo table -CREATE TABLE [foo] -( - [id] INT NOT NULL IDENTITY, - [bar] VARCHAR(255) NOT NULL, - CONSTRAINT [foo_PK] PRIMARY KEY ([id]) -); -'; - $this->assertSame($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLCompositePK - */ - public function testGetAddTableDDLCompositePK($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = ' -CREATE TABLE [foo] -( - [foo] INT NOT NULL, - [bar] INT NOT NULL, - [baz] VARCHAR(255) NOT NULL, - CONSTRAINT [foo_PK] PRIMARY KEY ([foo],[bar]) -); -'; - $this->assertSame($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLUniqueIndex - */ - public function testGetAddTableDDLUniqueIndex($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = ' -CREATE TABLE [foo] -( - [id] INT NOT NULL IDENTITY, - [bar] INT NULL, - CONSTRAINT [foo_PK] PRIMARY KEY ([id]), - UNIQUE ([bar]) -); -'; - $this->assertSame($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSchema - */ - public function testGetAddTableDDLSchema($schema): void - { - $table = $this->getTableFromSchema($schema, 'Woopah.foo'); - $expected = ' -CREATE TABLE [Woopah].[foo] -( - [id] INT NOT NULL IDENTITY, - [bar] INT NULL, - CONSTRAINT [foo_PK] PRIMARY KEY ([id]) -); -'; - $this->assertSame($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - public function testGetDropTableDDL(): void - { - $table = new Table('foo'); - $expected = " -IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = 'foo') -BEGIN - DECLARE @reftable_6 nvarchar(60), @constraintname_6 nvarchar(60) - DECLARE refcursor CURSOR FOR - select reftables.name tablename, cons.name constraintname - from sysobjects tables, - sysobjects reftables, - sysobjects cons, - sysreferences ref - where tables.id = ref.rkeyid - and cons.id = ref.constid - and reftables.id = ref.fkeyid - and tables.name = 'foo' - OPEN refcursor - FETCH NEXT from refcursor into @reftable_6, @constraintname_6 - while @@FETCH_STATUS = 0 - BEGIN - exec ('alter table '+@reftable_6+' drop constraint '+@constraintname_6) - FETCH NEXT from refcursor into @reftable_6, @constraintname_6 - END - CLOSE refcursor - DEALLOCATE refcursor - DROP TABLE [foo] -END -"; - $this->assertSame($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSchema - */ - public function testGetDropTableDDLSchema($schema): void - { - $table = $this->getTableFromSchema($schema, 'Woopah.foo'); - $expected = " -IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = 'Woopah.foo') -BEGIN - DECLARE @reftable_7 nvarchar(60), @constraintname_7 nvarchar(60) - DECLARE refcursor CURSOR FOR - select reftables.name tablename, cons.name constraintname - from sysobjects tables, - sysobjects reftables, - sysobjects cons, - sysreferences ref - where tables.id = ref.rkeyid - and cons.id = ref.constid - and reftables.id = ref.fkeyid - and tables.name = 'Woopah.foo' - OPEN refcursor - FETCH NEXT from refcursor into @reftable_7, @constraintname_7 - while @@FETCH_STATUS = 0 - BEGIN - exec ('alter table '+@reftable_7+' drop constraint '+@constraintname_7) - FETCH NEXT from refcursor into @reftable_7, @constraintname_7 - END - CLOSE refcursor - DEALLOCATE refcursor - DROP TABLE [Woopah].[foo] -END -"; - $this->assertSame($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - public function testGetColumnDDLCustomSqlType(): void - { - $column = new Column('foo'); - $column->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE')); - $column->getDomain()->replaceScale(2); - $column->getDomain()->replaceSize(3); - $column->setNotNull(true); - $column->getDomain()->setDefaultValue(new ColumnDefaultValue(123, ColumnDefaultValue::TYPE_VALUE)); - $column->getDomain()->replaceSqlType('DECIMAL(5,6)'); - - $expected = '[foo] DECIMAL(5,6) DEFAULT 123 NOT NULL'; - $this->assertSame($expected, $this->getPlatform()->getColumnDDL($column)); - } - - public function testGetPrimaryKeyDDLSimpleKey(): void - { - $table = new Table('foo'); - $column = new Column('bar'); - $column->setPrimaryKey(true); - $table->addColumn($column); - - $expected = 'CONSTRAINT [foo_PK] PRIMARY KEY ([bar])'; - $this->assertSame($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - public function testGetPrimaryKeyDDLCompositeKey(): void - { - $table = new Table('foo'); - $column1 = new Column('bar1'); - $column1->setPrimaryKey(true); - $table->addColumn($column1); - $column2 = new Column('bar2'); - $column2->setPrimaryKey(true); - $table->addColumn($column2); - - $expected = 'CONSTRAINT [foo_PK] PRIMARY KEY ([bar1],[bar2])'; - $this->assertSame($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetDropPrimaryKeyDDL($table): void - { - $expected = ' -ALTER TABLE [foo] DROP CONSTRAINT [foo_PK]; -'; - $this->assertSame($expected, $this->getPlatform()->getDropPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetAddPrimaryKeyDDL($table): void - { - $expected = ' -ALTER TABLE [foo] ADD CONSTRAINT [foo_PK] PRIMARY KEY ([bar]); -'; - $this->assertSame($expected, $this->getPlatform()->getAddPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestGetIndicesDDL - */ - public function testAddIndicesDDL($table): void - { - $expected = ' -CREATE INDEX [babar] ON [foo] ([bar1],[bar2]); - -CREATE INDEX [foo_index] ON [foo] ([bar1]); -'; - $this->assertSame($expected, $this->getPLatform()->getAddIndicesDDL($table)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testAddIndexDDL($index): void - { - $expected = ' -CREATE INDEX [babar] ON [foo] ([bar1],[bar2]); -'; - $this->assertSame($expected, $this->getPLatform()->getAddIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testDropIndexDDL($index): void - { - $expected = ' -DROP INDEX [babar]; -'; - $this->assertSame($expected, $this->getPLatform()->getDropIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testGetIndexDDL($index): void - { - $expected = 'INDEX [babar] ([bar1],[bar2])'; - $this->assertSame($expected, $this->getPLatform()->getIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetUniqueDDL - */ - public function testGetUniqueDDL($index): void - { - $expected = 'UNIQUE ([bar1],[bar2])'; - $this->assertSame($expected, $this->getPLatform()->getUniqueDDL($index)); - } - - /** - * @dataProvider providerForTestGetForeignKeysDDL - */ - public function testGetAddForeignKeysDDL($table): void - { - $expected = ' -BEGIN -ALTER TABLE [foo] ADD CONSTRAINT [foo_bar_FK] FOREIGN KEY ([bar_id]) REFERENCES [bar] ([id]) ON DELETE CASCADE -END -; - -BEGIN -ALTER TABLE [foo] ADD CONSTRAINT [foo_baz_FK] FOREIGN KEY ([baz_id]) REFERENCES [baz] ([id]) -END -; -'; - $this->assertSame($expected, $this->getPLatform()->getAddForeignKeysDDL($table)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetAddForeignKeyDDL($fk): void - { - $expected = ' -BEGIN -ALTER TABLE [foo] ADD CONSTRAINT [foo_bar_FK] FOREIGN KEY ([bar_id]) REFERENCES [bar] ([id]) ON DELETE CASCADE -END -; -'; - $this->assertSame($expected, $this->getPLatform()->getAddForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetAddForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetDropForeignKeyDDL($fk): void - { - $expected = ' -ALTER TABLE [foo] DROP CONSTRAINT [foo_bar_FK]; -'; - $this->assertEquals($expected, $this->getPLatform()->getDropForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetDropForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getDropForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetForeignKeyDDL($fk): void - { - $expected = 'CONSTRAINT [foo_bar_FK] FOREIGN KEY ([bar_id]) REFERENCES [bar] ([id]) ON DELETE CASCADE'; - $this->assertSame($expected, $this->getPLatform()->getForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getForeignKeyDDL($fk)); - } - - public function testGetCommentBlockDDL(): void - { - $expected = ' ------------------------------------------------------------------------ --- foo bar ------------------------------------------------------------------------ -'; - $this->assertSame($expected, $this->getPLatform()->getCommentBlockDDL('foo bar')); - } -} diff --git a/test/testsuite/generator/platform/OraclePlatformMigrationTest.php b/test/testsuite/generator/platform/OraclePlatformMigrationTest.php deleted file mode 100644 index a8cf6a6ec..000000000 --- a/test/testsuite/generator/platform/OraclePlatformMigrationTest.php +++ /dev/null @@ -1,454 +0,0 @@ -assertSame($expected, $this->getPlatform()->getModifyDatabaseDDL($databaseDiff)); - } - - /** - * @dataProvider providerForTestGetRenameTableDDL - */ - public function testGetRenameTableDDL($fromName, $toName) - { - $expected = ' -ALTER TABLE foo1 RENAME TO foo2; -'; - $this->assertSame($expected, $this->getPlatform()->getRenameTableDDL($fromName, $toName)); - } - - /** - * @dataProvider providerForTestGetModifyTableDDL - */ - public function testGetModifyTableDDL($tableDiff): void - { - $expected = ' -ALTER TABLE foo DROP CONSTRAINT foo1_FK_2; - -ALTER TABLE foo DROP CONSTRAINT foo1_FK_1; - -DROP INDEX bar_baz_FK; - -DROP INDEX bar_FK; - -ALTER TABLE foo RENAME COLUMN bar TO bar1; - -ALTER TABLE foo MODIFY -( - baz NVARCHAR2(12) -); - -ALTER TABLE foo ADD -( - baz3 NVARCHAR2(2000) -); - -CREATE INDEX bar_FK ON foo (bar1); - -CREATE INDEX baz_FK ON foo (baz3); - -ALTER TABLE foo ADD CONSTRAINT foo1_FK_1 - FOREIGN KEY (bar1) REFERENCES foo2 (bar); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTableDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableColumnsDDL - */ - public function testGetModifyTableColumnsDDL($tableDiff): void - { - $expected = ' -ALTER TABLE foo RENAME COLUMN bar TO bar1; - -ALTER TABLE foo MODIFY -( - baz NVARCHAR2(12) -); - -ALTER TABLE foo ADD -( - baz3 NVARCHAR2(2000) -); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTableColumnsDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTablePrimaryKeysDDL - */ - public function testGetModifyTablePrimaryKeysDDL($tableDiff): void - { - $expected = ' -ALTER TABLE foo DROP CONSTRAINT foo_PK; - -ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY (id,bar); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTablePrimaryKeyDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableIndicesDDL - */ - public function testGetModifyTableIndicesDDL($tableDiff): void - { - $expected = ' -DROP INDEX bar_FK; - -CREATE INDEX baz_FK ON foo (baz); - -DROP INDEX bar_baz_FK; - -CREATE INDEX bar_baz_FK ON foo (id,bar,baz); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTableIndicesDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysDDL - */ - public function testGetModifyTableForeignKeysDDL($tableDiff): void - { - $expected = ' -ALTER TABLE foo1 DROP CONSTRAINT foo1_FK_1; - -ALTER TABLE foo1 ADD CONSTRAINT foo1_FK_5 - FOREIGN KEY (baz) REFERENCES foo2 (baz); - -ALTER TABLE foo1 DROP CONSTRAINT foo1_FK_2; - -ALTER TABLE foo1 ADD CONSTRAINT foo1_FK_2 - FOREIGN KEY (bar,id) REFERENCES foo2 (bar,id); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysSkipSqlDDL - */ - public function testGetModifyTableForeignKeysSkipSqlDDL($tableDiff): void - { - $expected = ' -ALTER TABLE foo1 DROP CONSTRAINT foo1_FK_1; -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff)); - $expected = ' -ALTER TABLE foo1 ADD CONSTRAINT foo1_FK_1 - FOREIGN KEY (bar) REFERENCES foo2 (bar); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff->getReverseDiff())); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql2DDL - */ - public function testGetModifyTableForeignKeysSkipSql2DDL($tableDiff) - { - $expected = ''; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff)); - $expected = ''; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff->getReverseDiff())); - } - - /** - * @dataProvider providerForTestGetRemoveColumnDDL - */ - public function testGetRemoveColumnDDL($column): void - { - $expected = ' -ALTER TABLE foo DROP COLUMN bar; -'; - $this->assertSame($expected, $this->getPlatform()->getRemoveColumnDDL($column)); - } - - /** - * @dataProvider providerForTestGetRenameColumnDDL - */ - public function testGetRenameColumnDDL($fromColumn, $toColumn) - { - $expected = ' -ALTER TABLE foo RENAME COLUMN bar1 TO bar2; -'; - $this->assertSame($expected, $this->getPlatform()->getRenameColumnDDL($fromColumn, $toColumn)); - } - - /** - * @dataProvider providerForTestGetModifyColumnDDL - */ - public function testGetModifyColumnDDL($columnDiff): void - { - $expected = ' -ALTER TABLE foo MODIFY bar FLOAT(3); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyColumnDDL($columnDiff)); - } - - /** - * @dataProvider providerForTestGetModifyColumnsDDL - */ - public function testGetModifyColumnsDDL($columnDiffs): void - { - $expected = ' -ALTER TABLE foo MODIFY -( - bar1 FLOAT(3), - bar2 INTEGER NOT NULL -); -'; - $this->assertSame($expected, $this->getPlatform()->getModifyColumnsDDL($columnDiffs)); - } - - /** - * @dataProvider providerForTestGetAddColumnDDL - */ - public function testGetAddColumnDDL($column): void - { - $expected = ' -ALTER TABLE foo ADD bar NUMBER; -'; - $this->assertSame($expected, $this->getPlatform()->getAddColumnDDL($column)); - } - - /** - * @dataProvider providerForTestGetAddColumnsDDL - */ - public function testGetAddColumnsDDL($columns): void - { - $expected = ' -ALTER TABLE foo ADD -( - bar1 NUMBER, - bar2 FLOAT(3,2) DEFAULT -1 NOT NULL -); -'; - $this->assertSame($expected, $this->getPlatform()->getAddColumnsDDL($columns)); - } - - public function testGetModifyDatabaseWithBlockStorageDDL(): void - { - $schema1 = << - - - -
- - - - -
- - - -
- -EOF; - $schema2 = << - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -EOF; - $d1 = $this->getDatabaseFromSchema($schema1); - $d2 = $this->getDatabaseFromSchema($schema2); - $databaseDiff = PropelDatabaseComparator::computeDiff($d1, $d2); - $expected = " -ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'; -ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'; - -DROP TABLE foo1 CASCADE CONSTRAINTS; - -DROP SEQUENCE foo1_SEQ; - -ALTER TABLE foo3 RENAME TO foo4; - -CREATE TABLE foo5 -( - id NUMBER NOT NULL, - lkdjfsh NUMBER, - dfgdsgf CLOB -) -PCTFREE 20 -INITRANS 4 -STORAGE -( - MINEXTENTS 1 - MAXEXTENTS 99 - PCTINCREASE 0 -) -TABLESPACE L_128K; - -ALTER TABLE foo5 ADD CONSTRAINT foo5_PK PRIMARY KEY (id) -USING INDEX -PCTFREE 20 -INITRANS 4 -STORAGE -( - MINEXTENTS 1 - MAXEXTENTS 99 - PCTINCREASE 0 -) -TABLESPACE IL_128K; - -CREATE SEQUENCE foo5_SEQ - INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE NOCACHE ORDER; - -CREATE INDEX lkdjfsh_IDX ON foo5 (lkdjfsh) -PCTFREE 20 -INITRANS 4 -STORAGE -( - MINEXTENTS 1 - MAXEXTENTS 99 - PCTINCREASE 0 -) -TABLESPACE L_128K; - -ALTER TABLE foo2 RENAME COLUMN bar TO bar1; - -ALTER TABLE foo2 MODIFY -( - baz NVARCHAR2(12) -); - -ALTER TABLE foo2 ADD -( - baz3 CLOB -); -"; - // ignore tab/space indentation comparison - $this->assertSame($expected, str_replace("\t", ' ', $this->getPlatform()->getModifyDatabaseDDL($databaseDiff))); - } - -} diff --git a/test/testsuite/generator/platform/OraclePlatformTest.php b/test/testsuite/generator/platform/OraclePlatformTest.php deleted file mode 100644 index e427a8b02..000000000 --- a/test/testsuite/generator/platform/OraclePlatformTest.php +++ /dev/null @@ -1,589 +0,0 @@ -setIdMethod(IDMethod::NATIVE); - $expected = 'foo_SEQ'; - $this->assertEquals($expected, $this->getPlatform()->getSequenceName($table)); - } - - public function testGetSequenceNameCustom(): void - { - $table = new Table('foo'); - $table->setIdMethod(IDMethod::NATIVE); - $idMethodParameter = new IdMethodParameter(); - $idMethodParameter->setValue('foo_sequence'); - $table->addIdMethodParameter($idMethodParameter); - $table->setIdMethod(IDMethod::NATIVE); - $expected = 'foo_sequence'; - $this->assertEquals($expected, $this->getPlatform()->getSequenceName($table)); - } - - /** - * @dataProvider providerForTestGetAddTablesDDL - */ - public function testGetAddTablesDDL($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTablesSkipSQLDDL - */ - public function testGetAddTablesSkipSQLDDL($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = " -ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'; -ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'; -"; - $this->assertEquals($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSimplePK - */ - public function testGetAddTableDDLSimplePK($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = ' --- This is foo table -CREATE TABLE foo -( - id NUMBER NOT NULL, - bar NVARCHAR2(255) NOT NULL -); - -ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY (id); - -CREATE SEQUENCE foo_SEQ - INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE NOCACHE ORDER; -'; - $this->assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLCompositePK - */ - public function testGetAddTableDDLCompositePK($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = ' -CREATE TABLE foo -( - foo NUMBER NOT NULL, - bar NUMBER NOT NULL, - baz NVARCHAR2(255) NOT NULL -); - -ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY (foo,bar); -'; - $this->assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLUniqueIndex - */ - public function testGetAddTableDDLUniqueIndex($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = ' -CREATE TABLE foo -( - id NUMBER NOT NULL, - bar NUMBER, - CONSTRAINT foo_U_1 UNIQUE (bar) -); - -ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY (id); - -CREATE SEQUENCE foo_SEQ - INCREMENT BY 1 START WITH 1 NOMAXVALUE NOCYCLE NOCACHE ORDER; -'; - $this->assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - public function testGetDropTableDDL(): void - { - $table = new Table('foo'); - $expected = ' -DROP TABLE foo CASCADE CONSTRAINTS; -'; - $this->assertEquals($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - public function testGetDropTableWithSequenceDDL(): void - { - $table = new Table('foo'); - $idMethodParameter = new IdMethodParameter(); - $idMethodParameter->setValue('foo_sequence'); - $table->addIdMethodParameter($idMethodParameter); - $table->setIdMethod(IDMethod::NATIVE); - $expected = ' -DROP TABLE foo CASCADE CONSTRAINTS; - -DROP SEQUENCE foo_sequence; -'; - $this->assertEquals($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - public function testGetColumnDDLCustomSqlType(): void - { - $column = new Column('foo'); - $column->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE')); - $column->getDomain()->replaceScale(2); - $column->getDomain()->replaceSize(3); - $column->setNotNull(true); - $column->getDomain()->setDefaultValue(new ColumnDefaultValue(123, ColumnDefaultValue::TYPE_VALUE)); - $column->getDomain()->replaceSqlType('DECIMAL(5,6)'); - $expected = 'foo DECIMAL(5,6) DEFAULT 123 NOT NULL'; - $this->assertEquals($expected, $this->getPlatform()->getColumnDDL($column)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetPrimaryKeyDDLSimpleKey($table): void - { - $expected ='CONSTRAINT foo_PK PRIMARY KEY (bar)'; - $this->assertEquals($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - public function testGetPrimaryKeyDDLLongTableName(): void - { - $table = new Table('this_table_has_a_very_long_name'); - $column = new Column('bar'); - $column->setPrimaryKey(true); - $table->addColumn($column); - $expected = 'CONSTRAINT this_table_has_a_very_long__PK PRIMARY KEY (bar)'; - $this->assertEquals($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - public function testGetPrimaryKeyDDLCompositeKey(): void - { - $table = new Table('foo'); - $column1 = new Column('bar1'); - $column1->setPrimaryKey(true); - $table->addColumn($column1); - $column2 = new Column('bar2'); - $column2->setPrimaryKey(true); - $table->addColumn($column2); - $expected = 'CONSTRAINT foo_PK PRIMARY KEY (bar1,bar2)'; - $this->assertEquals($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetDropPrimaryKeyDDL($table): void - { - $expected = ' -ALTER TABLE foo DROP CONSTRAINT foo_PK; -'; - $this->assertEquals($expected, $this->getPlatform()->getDropPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetAddPrimaryKeyDDL($table): void - { - $expected = ' -ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY (bar); -'; - $this->assertEquals($expected, $this->getPlatform()->getAddPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestGetIndicesDDL - */ - public function testAddIndicesDDL($table): void - { - $expected = ' -CREATE INDEX babar ON foo (bar1,bar2); - -CREATE INDEX foo_index ON foo (bar1); -'; - $this->assertEquals($expected, $this->getPLatform()->getAddIndicesDDL($table)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testAddIndexDDL($index): void - { - $expected = ' -CREATE INDEX babar ON foo (bar1,bar2); -'; - $this->assertEquals($expected, $this->getPLatform()->getAddIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testDropIndexDDL($index): void - { - $expected = ' -DROP INDEX babar; -'; - $this->assertEquals($expected, $this->getPLatform()->getDropIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testGetIndexDDL($index): void - { - $expected = 'INDEX babar (bar1,bar2)'; - $this->assertEquals($expected, $this->getPLatform()->getIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetUniqueDDL - */ - public function testGetUniqueDDL($index): void - { - $expected = 'CONSTRAINT babar UNIQUE (bar1,bar2)'; - $this->assertEquals($expected, $this->getPlatform()->getUniqueDDL($index)); - } - - /** - * @dataProvider providerForTestGetForeignKeysDDL - */ - public function testGetAddForeignKeysDDL($table): void - { - $expected = ' -ALTER TABLE foo ADD CONSTRAINT foo_bar_FK - FOREIGN KEY (bar_id) REFERENCES bar (id) - ON DELETE CASCADE; - -ALTER TABLE foo ADD CONSTRAINT foo_baz_FK - FOREIGN KEY (baz_id) REFERENCES baz (id) - ON DELETE SET NULL; -'; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeysDDL($table)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetAddForeignKeyDDL($fk): void - { - $expected = ' -ALTER TABLE foo ADD CONSTRAINT foo_bar_FK - FOREIGN KEY (bar_id) REFERENCES bar (id) - ON DELETE CASCADE; -'; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetAddForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetDropForeignKeyDDL($fk): void - { - $expected = ' -ALTER TABLE foo DROP CONSTRAINT foo_bar_FK; -'; - $this->assertEquals($expected, $this->getPLatform()->getDropForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetDropForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getDropForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetForeignKeyDDL($fk): void - { - $expected = 'CONSTRAINT foo_bar_FK - FOREIGN KEY (bar_id) REFERENCES bar (id) - ON DELETE CASCADE'; - $this->assertEquals($expected, $this->getPLatform()->getForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getForeignKeyDDL($fk)); - } - - public function testGetCommentBlockDDL(): void - { - $expected = ' ------------------------------------------------------------------------ --- foo bar ------------------------------------------------------------------------ -'; - $this->assertEquals($expected, $this->getPLatform()->getCommentBlockDDL('foo bar')); - } - - public function testGetOracleBlockStorageDDL(): void - { - $schema = << - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - -
- -EOF; - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertEquals($expected, str_replace("\t", ' ', $this->getPlatform()->getAddTablesDDL($database))); - } -} diff --git a/test/testsuite/generator/platform/PgsqlPlatformMigrationTest.php b/test/testsuite/generator/platform/PgsqlPlatformMigrationTest.php deleted file mode 100644 index 4359077c4..000000000 --- a/test/testsuite/generator/platform/PgsqlPlatformMigrationTest.php +++ /dev/null @@ -1,394 +0,0 @@ -assertSame($expected, $this->getPlatform()->getModifyDatabaseDDL($databaseDiff)); - } - - /** - * @dataProvider providerForTestGetRenameTableDDL - */ - public function testGetRenameTableDDL($fromName, $toName) - { - $expected = ' -ALTER TABLE "foo1" RENAME TO "foo2"; -'; - $this->assertSame($expected, $this->getPlatform()->getRenameTableDDL($fromName, $toName)); - } - - /** - * @dataProvider providerForTestGetModifyTableDDL - */ - public function testGetModifyTableDDL($tableDiff): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTableDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableColumnsDDL - */ - public function testGetModifyTableColumnsDDL($tableDiff): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTableColumnsDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTablePrimaryKeysDDL - */ - public function testGetModifyTablePrimaryKeysDDL($tableDiff): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTablePrimaryKeyDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableIndicesDDL - */ - public function testGetModifyTableIndicesDDL($tableDiff): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTableIndicesDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysDDL - */ - public function testGetModifyTableForeignKeysDDL($tableDiff): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff)); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysSkipSqlDDL - */ - public function testGetModifyTableForeignKeysSkipSqlDDL($tableDiff): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff)); - $expected = <<assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff->getReverseDiff())); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql2DDL - */ - public function testGetModifyTableForeignKeysSkipSql2DDL($tableDiff) - { - $expected = ''; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff)); - $expected = ''; - $this->assertSame($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff->getReverseDiff())); - } - - /** - * @dataProvider providerForTestGetRemoveColumnDDL - */ - public function testGetRemoveColumnDDL($column): void - { - $expected = ' -ALTER TABLE "foo" DROP COLUMN "bar"; -'; - $this->assertSame($expected, $this->getPlatform()->getRemoveColumnDDL($column)); - } - - /** - * @dataProvider providerForTestGetRenameColumnDDL - */ - public function testGetRenameColumnDDL($fromColumn, $toColumn) - { - $expected = ' -ALTER TABLE "foo" RENAME COLUMN "bar1" TO "bar2"; -'; - $this->assertSame($expected, $this->getPlatform()->getRenameColumnDDL($fromColumn, $toColumn)); - } - - /** - * @dataProvider providerForTestGetModifyColumnDDL - */ - public function testGetModifyColumnDDL($columnDiff): void - { - $expected = ' -ALTER TABLE "foo" ALTER COLUMN "bar" TYPE DOUBLE PRECISION; -'; - $this->assertSame($expected, $this->getPlatform()->getModifyColumnDDL($columnDiff)); - } - - public function testGetModifyColumnDDLWithChangedTypeAndDefault(): void - { - $t1 = new Table('foo'); - $c1 = new Column('bar'); - $c1->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE')); - $c1->getDomain()->replaceSize(2); - $t1->addColumn($c1); - $t2 = new Table('foo'); - $c2 = new Column('bar'); - $c2->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE')); - $c2->getDomain()->replaceSize(3); - $c2->getDomain()->setDefaultValue(new ColumnDefaultValue(-100, ColumnDefaultValue::TYPE_VALUE)); - $t2->addColumn($c2); - $columnDiff = PropelColumnComparator::computeDiff($c1, $c2); - $expected = <<assertSame($expected, $this->getPlatform()->getModifyColumnDDL($columnDiff)); - } - - /** - * @dataProvider providerForTestGetModifyColumnsDDL - */ - public function testGetModifyColumnsDDL($columnDiffs): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyColumnsDDL($columnDiffs)); - } - - /** - * @dataProvider providerForTestGetAddColumnDDL - */ - public function testGetAddColumnDDL($column): void - { - $expected = ' -ALTER TABLE "foo" ADD "bar" INTEGER; -'; - $this->assertSame($expected, $this->getPlatform()->getAddColumnDDL($column)); - } - - /** - * @dataProvider providerForTestGetAddColumnsDDL - */ - public function testGetAddColumnsDDL($columns): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getAddColumnsDDL($columns)); - } - - public function testGetModifyColumnDDLWithVarcharWithoutSize(): void - { - $t1 = new Table('foo'); - $c1 = new Column('bar'); - $c1->setTable($t1); - $c1->getDomain()->copy($this->getPlatform()->getDomainForType('VARCHAR')); - $c1->getDomain()->replaceSize(null); - $c1->getDomain()->replaceScale(null); - $t1->addColumn($c1); - - $schema = << - - - -
- -EOF; - - $table = $this->getDatabaseFromSchema($schema)->getTable('foo'); - $c2 = $table->getColumn('bar'); - $columnDiff = PropelColumnComparator::computeDiff($c1, $c2); - $expected = false; - $this->assertSame($expected, $columnDiff); - } - -public function testGetModifyColumnDDLWithVarcharWithoutSizeAndPlatform(): void - { - $t1 = new Table('foo'); - $c1 = new Column('bar'); - $c1->setTable($t1); - $c1->getDomain()->copy($this->getPlatform()->getDomainForType('VARCHAR')); - $c1->getDomain()->replaceSize(null); - $c1->getDomain()->replaceScale(null); - $t1->addColumn($c1); - - $schema = << - - - -
- -EOF; - - $xtad = new XmlToAppData(null); - $appData = $xtad->parseString($schema); - $db = $appData->getDatabase(); - $table = $db->getTable('foo'); - $c2 = $table->getColumn('bar'); - $columnDiff = PropelColumnComparator::computeDiff($c1, $c2); - $expected = false; - $this->assertSame($expected, $columnDiff); - } - - /** - * @dataProvider providerForTestGetModifyColumnRemoveDefaultValueDDL - */ - public function testGetModifyColumnRemoveDefaultValueDDL($columnDiffs): void - { - $expected = <<assertSame($expected, $this->getPlatform()->getModifyColumnDDL($columnDiffs)); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql3DDL - */ - public function testGetModifyTableForeignKeysSkipSql3DDL($databaseDiff) - { - $this->assertFalse($databaseDiff); - } - - /** - * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql4DDL - */ - public function testGetModifyTableForeignKeysSkipSql4DDL($databaseDiff) - { - $this->assertFalse($databaseDiff); - } - -} diff --git a/test/testsuite/generator/platform/PgsqlPlatformTest.php b/test/testsuite/generator/platform/PgsqlPlatformTest.php deleted file mode 100644 index aaf080f4e..000000000 --- a/test/testsuite/generator/platform/PgsqlPlatformTest.php +++ /dev/null @@ -1,727 +0,0 @@ -setIdMethod(IDMethod::NATIVE); - $col = new Column('bar'); - $col->getDomain()->copy($this->getPlatform()->getDomainForType('INTEGER')); - $col->setAutoIncrement(true); - $table->addColumn($col); - $expected = 'foo_bar_seq'; - $this->assertEquals($expected, $this->getPlatform()->getSequenceName($table)); - } - - public function testGetSequenceNameCustom(): void - { - $table = new Table('foo'); - $table->setIdMethod(IDMethod::NATIVE); - $idMethodParameter = new IdMethodParameter(); - $idMethodParameter->setValue('foo_sequence'); - $table->addIdMethodParameter($idMethodParameter); - $table->setIdMethod(IDMethod::NATIVE); - $col = new Column('bar'); - $col->getDomain()->copy($this->getPlatform()->getDomainForType('INTEGER')); - $col->setAutoIncrement(true); - $table->addColumn($col); - $expected = 'foo_sequence'; - $this->assertEquals($expected, $this->getPlatform()->getSequenceName($table)); - } - - /** - * @dataProvider providerForTestGetAddTablesDDL - */ - public function testGetAddTablesDDL($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTablesSkipSQLDDL - */ - public function testGetAddTablesDDLSkipSQL($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = ''; - $this->assertEquals($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - public function testGetAddTablesDDLSchemasVendor(): void - { - $schema = << - - - - - -
- - -
- - - - - -
- -EOF; - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTablesDDLSchema - */ - public function testGetAddTablesDDLSchemas($schema): void - { - $database = $this->getDatabaseFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTablesDDL($database)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSimplePK - */ - public function testGetAddTableDDLSimplePK($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLCompositePK - */ - public function testGetAddTableDDLCompositePK($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLUniqueIndex - */ - public function testGetAddTableDDLUniqueIndex($schema): void - { - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - public function testGetAddTableDDLSchemaVendor(): void - { - $schema = << - - - - - -
- -EOF; - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSchema - */ - public function testGetAddTableDDLSchema($schema): void - { - $table = $this->getTableFromSchema($schema, 'Woopah.foo'); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - public function testGetAddTableDDLSequence(): void - { - $schema = << - - - -
- -EOF; - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - public function testGetAddTableDDLColumnComments(): void - { - $schema = << - - - -
- -EOF; - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getAddTableDDL($table)); - } - - public function testGetDropTableDDL(): void - { - $table = new Table('foo'); - $expected = ' -DROP TABLE IF EXISTS "foo" CASCADE; -'; - $this->assertEquals($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - public function testGetDropTableDDLSchemaVendor(): void - { - $schema = << - - - - - -
- -EOF; - $table = $this->getTableFromSchema($schema); - $expected = <<assertEquals($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - /** - * @dataProvider providerForTestGetAddTableDDLSchema - */ - public function testGetDropTableDDLSchema($schema): void - { - $table = $this->getTableFromSchema($schema, 'Woopah.foo'); - $expected = <<assertEquals($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - public function testGetDropTableWithSequenceDDL(): void - { - $table = new Table('foo'); - $idMethodParameter = new IdMethodParameter(); - $idMethodParameter->setValue('foo_sequence'); - $table->addIdMethodParameter($idMethodParameter); - $table->setIdMethod(IDMethod::NATIVE); - $expected = ' -DROP TABLE IF EXISTS "foo" CASCADE; - -DROP SEQUENCE "foo_sequence"; -'; - $this->assertEquals($expected, $this->getPlatform()->getDropTableDDL($table)); - } - - public function testGetColumnDDL(): void - { - $c = new Column('foo'); - $c->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE')); - $c->getDomain()->replaceScale(2); - $c->getDomain()->replaceSize(3); - $c->setNotNull(true); - $c->getDomain()->setDefaultValue(new ColumnDefaultValue(123, ColumnDefaultValue::TYPE_VALUE)); - - $expected = '"foo" DOUBLE PRECISION DEFAULT 123 NOT NULL'; - $this->assertEquals($expected, $this->getPlatform()->getColumnDDL($c)); - } - - public function testGetColumnDDLAutoIncrement(): void - { - $database = new Database(); - $database->setPlatform($this->getPlatform()); - $table = new Table('foo_table'); - $table->setIdMethod(IDMethod::NATIVE); - $database->addTable($table); - $column = new Column('foo'); - $column->getDomain()->copy($this->getPlatform()->getDomainForType(PropelTypes::BIGINT)); - $column->setAutoIncrement(true); - $table->addColumn($column); - - $expected = '"foo" bigserial'; - $this->assertEquals($expected, $this->getPlatform()->getColumnDDL($column)); - } - - public function testGetColumnDDLCustomSqlType(): void - { - $column = new Column('foo'); - $column->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE')); - $column->getDomain()->replaceScale(2); - $column->getDomain()->replaceSize(3); - $column->setNotNull(true); - $column->getDomain()->setDefaultValue(new ColumnDefaultValue(123, ColumnDefaultValue::TYPE_VALUE)); - $column->getDomain()->replaceSqlType('DECIMAL(5,6)'); - - $expected = '"foo" DECIMAL(5,6) DEFAULT 123 NOT NULL'; - $this->assertEquals($expected, $this->getPlatform()->getColumnDDL($column)); - } - - public function testGetPrimaryKeyDDLSimpleKey(): void - { - $table = new Table('foo'); - $column = new Column('bar'); - $column->setPrimaryKey(true); - $table->addColumn($column); - - $expected = 'PRIMARY KEY ("bar")'; - $this->assertEquals($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - public function testGetPrimaryKeyDDLCompositeKey(): void - { - $table = new Table('foo'); - $column1 = new Column('bar1'); - $column1->setPrimaryKey(true); - $table->addColumn($column1); - $column2 = new Column('bar2'); - $column2->setPrimaryKey(true); - $table->addColumn($column2); - - $expected = 'PRIMARY KEY ("bar1","bar2")'; - $this->assertEquals($expected, $this->getPlatform()->getPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetDropPrimaryKeyDDL($table): void - { - $expected = ' -ALTER TABLE "foo" DROP CONSTRAINT "foo_pkey"; -'; - $this->assertEquals($expected, $this->getPlatform()->getDropPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestPrimaryKeyDDL - */ - public function testGetAddPrimaryKeyDDL($table): void - { - $expected = ' -ALTER TABLE "foo" ADD PRIMARY KEY ("bar"); -'; - $this->assertEquals($expected, $this->getPlatform()->getAddPrimaryKeyDDL($table)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testAddIndexDDL($index): void - { - $expected = ' -CREATE INDEX "babar" ON "foo" ("bar1","bar2"); -'; - $this->assertEquals($expected, $this->getPLatform()->getAddIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetIndicesDDL - */ - public function testAddIndicesDDL($table): void - { - $expected = ' -CREATE INDEX "babar" ON "foo" ("bar1","bar2"); - -CREATE INDEX "foo_index" ON "foo" ("bar1"); -'; - $this->assertEquals($expected, $this->getPLatform()->getAddIndicesDDL($table)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testDropIndexDDL($index): void - { - $expected = ' -DROP INDEX "babar"; -'; - $this->assertEquals($expected, $this->getPLatform()->getDropIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetIndexDDL - */ - public function testGetIndexDDL($index): void - { - $expected = 'INDEX "babar" ("bar1","bar2")'; - $this->assertEquals($expected, $this->getPLatform()->getIndexDDL($index)); - } - - /** - * @dataProvider providerForTestGetUniqueDDL - */ - public function testGetUniqueDDL($index): void - { - $expected = 'CONSTRAINT "babar" UNIQUE ("bar1","bar2")'; - $this->assertEquals($expected, $this->getPlatform()->getUniqueDDL($index)); - } - - /** - * @dataProvider providerForTestGetForeignKeysDDL - */ - public function testGetAddForeignKeysDDL($table): void - { - $expected = ' -ALTER TABLE "foo" ADD CONSTRAINT "foo_bar_FK" - FOREIGN KEY ("bar_id") - REFERENCES "bar" ("id") - ON DELETE CASCADE; - -ALTER TABLE "foo" ADD CONSTRAINT "foo_baz_FK" - FOREIGN KEY ("baz_id") - REFERENCES "baz" ("id") - ON DELETE SET NULL; -'; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeysDDL($table)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetAddForeignKeyDDL($fk): void - { - $expected = ' -ALTER TABLE "foo" ADD CONSTRAINT "foo_bar_FK" - FOREIGN KEY ("bar_id") - REFERENCES "bar" ("id") - ON DELETE CASCADE; -'; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetAddForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getAddForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetDropForeignKeyDDL($fk): void - { - $expected = ' -ALTER TABLE "foo" DROP CONSTRAINT "foo_bar_FK"; -'; - $this->assertEquals($expected, $this->getPLatform()->getDropForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetDropForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getDropForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeyDDL - */ - public function testGetForeignKeyDDL($fk): void - { - $expected = 'CONSTRAINT "foo_bar_FK" - FOREIGN KEY ("bar_id") - REFERENCES "bar" ("id") - ON DELETE CASCADE'; - $this->assertEquals($expected, $this->getPLatform()->getForeignKeyDDL($fk)); - } - - /** - * @dataProvider providerForTestGetForeignKeySkipSqlDDL - */ - public function testGetForeignKeySkipSqlDDL($fk): void - { - $expected = ''; - $this->assertEquals($expected, $this->getPLatform()->getForeignKeyDDL($fk)); - } - - public function testGetCommentBlockDDL(): void - { - $expected = ' ------------------------------------------------------------------------ --- foo bar ------------------------------------------------------------------------ -'; - $this->assertEquals($expected, $this->getPLatform()->getCommentBlockDDL('foo bar')); - } - -} diff --git a/test/testsuite/generator/reverse/mssql/MssqlSchemaParserTest.php b/test/testsuite/generator/reverse/mssql/MssqlSchemaParserTest.php deleted file mode 100644 index eeb957cdc..000000000 --- a/test/testsuite/generator/reverse/mssql/MssqlSchemaParserTest.php +++ /dev/null @@ -1,71 +0,0 @@ -cleanDelimitedIdentifiers('\''.$expected.'\''); - $this->assertSame($expected, $tested); - - $tested = $parser->cleanDelimitedIdentifiers('\''.$expected); - $this->assertSame('\''.$expected, $tested); - - $tested = $parser->cleanDelimitedIdentifiers($expected.'\''); - $this->assertSame($expected.'\'', $tested); - - $expected = 'this is a tabl\'ename'; - - $tested = $parser->cleanDelimitedIdentifiers('\''.$expected.'\''); - $this->assertSame($expected, $tested); - - $tested = $parser->cleanDelimitedIdentifiers('\''.$expected); - $this->assertSame('\''.$expected, $tested); - - $tested = $parser->cleanDelimitedIdentifiers($expected.'\''); - $this->assertSame($expected.'\'', $tested); - - $expected = 'this is a\'tabl\'ename'; - - $tested = $parser->cleanDelimitedIdentifiers('\''.$expected.'\''); - $this->assertSame($expected, $tested); - - $tested = $parser->cleanDelimitedIdentifiers('\''.$expected); - $this->assertSame('\''.$expected, $tested); - - $tested = $parser->cleanDelimitedIdentifiers($expected.'\''); - $this->assertSame($expected.'\'', $tested); - - } -} - -class TestableMssqlSchemaParser extends MssqlSchemaParser -{ - public function cleanDelimitedIdentifiers($identifier) - { - return parent::cleanDelimitedIdentifiers($identifier); - } -} diff --git a/test/testsuite/generator/reverse/pgsql/PgsqlSchemaParserTest.php b/test/testsuite/generator/reverse/pgsql/PgsqlSchemaParserTest.php deleted file mode 100644 index 36adb4d38..000000000 --- a/test/testsuite/generator/reverse/pgsql/PgsqlSchemaParserTest.php +++ /dev/null @@ -1,108 +0,0 @@ -markTestSkipped('PGSQL unit test'); - - parent::setUp(); - - $xmlDom = new DOMDocument(); - $xmlDom->load(__DIR__ . '/../../../../fixtures/reverse/pgsql/runtime-conf.xml'); - $xml = simplexml_load_string($xmlDom->saveXML()); - $phpconf = TestablePropelConvertConfTask::simpleXmlToArray($xml); - - Propel::setConfiguration($phpconf); - Propel::initialize(); - - $this->con = Propel::getConnection('reverse-bookstore'); - $this->con->beginTransaction(); - } - - protected function tearDown(): void - { - if ($this->con) { - $this->con->rollback(); - } - - parent::tearDown(); - Propel::init(__DIR__ . '/../../../../fixtures/bookstore/build/conf/bookstore-conf.php'); - } - - public function parseDataProvider() - { - return [ - // columnDDL, expectedColumnPhpName, expectedColumnDefaultType, expectedColumnDefaultValue, expectedSize, expectedScale - ['my_column varchar(20) default null', 'MyColumn', ColumnDefaultValue::TYPE_VALUE, 'NULL', 20, null], - ["my_column varchar(20) default ''", 'MyColumn', ColumnDefaultValue::TYPE_VALUE, '', 20, null], - ['my_column numeric(11,0) default 0', 'MyColumn', ColumnDefaultValue::TYPE_VALUE, 0, 11, 0], - ['my_column numeric(55,8) default 0', 'MyColumn', ColumnDefaultValue::TYPE_VALUE, 0, 55, 8], - ]; - } - - /** - * @dataProvider parseDataProvider - */ - public function testParse($columnDDL, $expectedColumnPhpName, $expectedColumnDefaultType, $expectedColumnDefaultValue, $expectedSize, $expectedScale) - { - $this->con->query("create table foo ( {$columnDDL} );"); - $parser = new PgsqlSchemaParser($this->con); - $parser->setGeneratorConfig(new QuickGeneratorConfig()); - - $database = new Database(); - $database->setPlatform(new DefaultPlatform()); - - // make sure our DDL insert produced exactly the SQL we inserted - $this->assertSame(1, $parser->parse($database), 'One table and one view defined should return one as we exclude views'); - $tables = $database->getTables(); - $this->assertCount(1, $tables); - $table = $tables[0]; - $columns = $table->getColumns(); - $this->assertCount(1, $columns); - - // check out our rev-eng column info - $defaultValue = $columns[0]->getDefaultValue(); - $this->assertEquals($expectedColumnPhpName, $columns[0]->getPhpName()); - $this->assertEquals($expectedColumnDefaultType, $defaultValue->getType()); - $this->assertEquals($expectedColumnDefaultValue, $defaultValue->getValue()); - $this->assertEquals($expectedSize, $columns[0]->getSize()); - $this->assertEquals($expectedScale, $columns[0]->getScale()); - } -} - -class TestablePropelConvertConfTask extends PropelConvertConfTask -{ - public static function simpleXmlToArray($xml) - { - return parent::simpleXmlToArray($xml); - } -} diff --git a/test/testsuite/runtime/adapter/DBMSSQLTest.php b/test/testsuite/runtime/adapter/DBMSSQLTest.php deleted file mode 100644 index 8445dec7b..000000000 --- a/test/testsuite/runtime/adapter/DBMSSQLTest.php +++ /dev/null @@ -1,43 +0,0 @@ - - * @package runtime.adapter - */ -class DBMSSQLTest extends DBAdapterTestAbstract -{ - public function testSelectJoinOrderAlias(): void - { - $adapter = new DBMSSQL(); - $sql = 'SELECT Field, Related.Field AS [RelatedField] FROM Record LEFT JOIN Related ON Record.RelatedID = Related.ID ORDER BY [RelatedField] ASC'; - $adapter->applyLimit($sql, 10, 5); - $this->assertSame('SELECT [Field], [RelatedField] FROM (SELECT ROW_NUMBER() OVER(ORDER BY Related.Field ASC) AS [RowNumber], Field AS [Field], Related.Field AS [RelatedField] FROM Record LEFT JOIN Related ON Record.RelatedID = Related.ID) AS derivedb WHERE RowNumber BETWEEN 11 AND 15', $sql); - } - - public function testQuotingIdentifiers(): void - { - $db = new DBMSSQL(); - $this->assertSame('[Book ISBN]', $db->quoteIdentifier('Book ISBN')); - } - - public function testCaseQuery(): void - { - $adapter = new DBMSSQL(); - $sql = "SELECT Field1, CASE WHEN Field2 = 'non-relevant' THEN 0 ELSE 1 END AS [Relevant] FROM Record ORDER BY [Relevant] ASC"; - $adapter->applyLimit($sql, 10, 5); - $this->assertSame("SELECT [Field1], [Relevant] FROM (SELECT ROW_NUMBER() OVER(ORDER BY CASE WHEN Field2 = 'non-relevant' THEN 0 ELSE 1 END ASC) AS [RowNumber], Field1 AS [Field1], CASE WHEN Field2 = 'non-relevant' THEN 0 ELSE 1 END AS [Relevant] FROM Record) AS derivedb WHERE RowNumber BETWEEN 11 AND 15", $sql); - } -} diff --git a/test/testsuite/runtime/adapter/DBOracleTest.php b/test/testsuite/runtime/adapter/DBOracleTest.php deleted file mode 100644 index e0df1fc43..000000000 --- a/test/testsuite/runtime/adapter/DBOracleTest.php +++ /dev/null @@ -1,90 +0,0 @@ -setDbName('oracle'); - BookPeer::addSelectColumns($c); - $c->setLimit(1); - $params = []; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertSame('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with the original column names by default'); - } - - public function testApplyLimitDuplicateColumnName(): void - { - $db = new DBOracle(); - Propel::setDb('oracle', $db); - $c = new Criteria(); - $c->setDbName('oracle'); - BookPeer::addSelectColumns($c); - AuthorPeer::addSelectColumns($c); - $c->setLimit(1); - $params = []; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertSame('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_0').', book.title AS '.$db->quoteIdentifier('ORA_COL_ALIAS_1').', book.isbn AS '.$db->quoteIdentifier('ORA_COL_ALIAS_2').', book.price AS '.$db->quoteIdentifier('ORA_COL_ALIAS_3').', book.publisher_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_4').', book.author_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_5').', author.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_6').', author.first_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_7').', author.last_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_8').', author.email AS '.$db->quoteIdentifier('ORA_COL_ALIAS_9').', author.age AS '.$db->quoteIdentifier('ORA_COL_ALIAS_10').' FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with aliased column names when a duplicate column name is found'); - } - - public function testApplyLimitDuplicateColumnNameWithColumn(): void - { - $db = new DBOracle(); - Propel::setDb('oracle', $db); - $c = new Criteria(); - $c->setDbName('oracle'); - BookPeer::addSelectColumns($c); - AuthorPeer::addSelectColumns($c); - $c->addAsColumn('BOOK_PRICE', BookPeer::PRICE); - $c->setLimit(1); - $params = []; - $asColumns = $c->getAsColumns(); - $sql = BasePeer::createSelectSql($c, $params); - $this->assertSame('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_0').', book.title AS '.$db->quoteIdentifier('ORA_COL_ALIAS_1').', book.isbn AS '.$db->quoteIdentifier('ORA_COL_ALIAS_2').', book.price AS '.$db->quoteIdentifier('ORA_COL_ALIAS_3').', book.publisher_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_4').', book.author_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_5').', author.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_6').', author.first_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_7').', author.last_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_8').', author.email AS '.$db->quoteIdentifier('ORA_COL_ALIAS_9').', author.age AS '.$db->quoteIdentifier('ORA_COL_ALIAS_10').', book.price AS '.$db->quoteIdentifier('BOOK_PRICE').' FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with aliased column names when a duplicate column name is found'); - $this->assertEquals($asColumns, $c->getAsColumns(), 'createSelectSql supplementary add alias column'); - } - - public function testCreateSelectSqlPart(): void - { - Propel::setDb('oracle', new DBOracle()); - $db = Propel::getDB(); - $c = new Criteria(); - $c->addSelectColumn(BookPeer::ID); - $c->addAsColumn('book_ID', BookPeer::ID); - $fromClause = []; - $selectSql = $db->createSelectSqlPart($c, $fromClause); - $this->assertSame('SELECT book.id, book.id AS '.$db->quoteIdentifier('book_ID'), $selectSql, 'createSelectSqlPart() returns a SQL SELECT clause with both select and as columns'); - $this->assertEquals(['book'], $fromClause, 'createSelectSqlPart() adds the tables from the select columns to the from clause'); - } - - public function testGetExplainPlanQuery(): void - { - $db = new DBOracle(); - $explainQuery = $db->getExplainPlanQuery('SELECT B.* FROM (SELECT A.*, rownum AS '.$db->quoteIdentifier('PROPEL_ROWNUM').' FROM (SELECT book.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_0').', book.title AS '.$db->quoteIdentifier('ORA_COL_ALIAS_1').', book.isbn AS '.$db->quoteIdentifier('ORA_COL_ALIAS_2').', book.price AS '.$db->quoteIdentifier('ORA_COL_ALIAS_3').', book.publisher_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_4').', book.author_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_5').', author.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_6').', author.first_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_7').', author.last_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_8').', author.email AS '.$db->quoteIdentifier('ORA_COL_ALIAS_9').', author.age AS '.$db->quoteIdentifier('ORA_COL_ALIAS_10').', book.price AS '.$db->quoteIdentifier('BOOK_PRICE').' FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', 'iuyiuyiu'); - $this->assertSame('EXPLAIN PLAN SET STATEMENT_ID = \'iuyiuyiu\' FOR SELECT B.* FROM (SELECT A.*, rownum AS '.$db->quoteIdentifier('PROPEL_ROWNUM').' FROM (SELECT book.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_0').', book.title AS '.$db->quoteIdentifier('ORA_COL_ALIAS_1').', book.isbn AS '.$db->quoteIdentifier('ORA_COL_ALIAS_2').', book.price AS '.$db->quoteIdentifier('ORA_COL_ALIAS_3').', book.publisher_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_4').', book.author_id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_5').', author.id AS '.$db->quoteIdentifier('ORA_COL_ALIAS_6').', author.first_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_7').', author.last_name AS '.$db->quoteIdentifier('ORA_COL_ALIAS_8').', author.email AS '.$db->quoteIdentifier('ORA_COL_ALIAS_9').', author.age AS '.$db->quoteIdentifier('ORA_COL_ALIAS_10').', book.price AS '.$db->quoteIdentifier('BOOK_PRICE').' FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $explainQuery, 'getExplainPlanQuery() returns a SQL Explain query'); - } - - public function testQuotingIdentifiers(): void - { - $db = new DBOracle(); - $this->assertSame('"Book ISBN"', $db->quoteIdentifier('Book ISBN')); - } -} diff --git a/test/testsuite/runtime/adapter/DBPostgresTest.php b/test/testsuite/runtime/adapter/DBPostgresTest.php deleted file mode 100644 index adad17c87..000000000 --- a/test/testsuite/runtime/adapter/DBPostgresTest.php +++ /dev/null @@ -1,37 +0,0 @@ - - * @package runtime.adapter - */ -class DBPostgresTest extends DBAdapterTestAbstract -{ - public function testGetExplainPlanQuery(): void - { - $db = new DBPostgres(); - $query = 'SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID AS ORA_COL_ALIAS_0, book.TITLE AS ORA_COL_ALIAS_1, book.ISBN AS ORA_COL_ALIAS_2, book.PRICE AS ORA_COL_ALIAS_3, book.PUBLISHER_ID AS ORA_COL_ALIAS_4, book.AUTHOR_ID AS ORA_COL_ALIAS_5, author.ID AS ORA_COL_ALIAS_6, author.FIRST_NAME AS ORA_COL_ALIAS_7, author.LAST_NAME AS ORA_COL_ALIAS_8, author.EMAIL AS ORA_COL_ALIAS_9, author.AGE AS ORA_COL_ALIAS_10, book.PRICE AS BOOK_PRICE FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1'; - - $this->assertSame('EXPLAIN SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID AS ORA_COL_ALIAS_0, book.TITLE AS ORA_COL_ALIAS_1, book.ISBN AS ORA_COL_ALIAS_2, book.PRICE AS ORA_COL_ALIAS_3, book.PUBLISHER_ID AS ORA_COL_ALIAS_4, book.AUTHOR_ID AS ORA_COL_ALIAS_5, author.ID AS ORA_COL_ALIAS_6, author.FIRST_NAME AS ORA_COL_ALIAS_7, author.LAST_NAME AS ORA_COL_ALIAS_8, author.EMAIL AS ORA_COL_ALIAS_9, author.AGE AS ORA_COL_ALIAS_10, book.PRICE AS BOOK_PRICE FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $db->getExplainPlanQuery($query), 'getExplainPlanQuery() returns a SQL Explain query'); - } - - public function testQuotingIdentifiers(): void - { - $db = new DBPostgres(); - $this->assertSame('"Book ISBN"', $db->quoteIdentifier('Book ISBN')); - } -} diff --git a/test/testsuite/runtime/query/CriteriaTest.php b/test/testsuite/runtime/query/CriteriaTest.php index 0c19b4fe8..f0be0a0eb 100644 --- a/test/testsuite/runtime/query/CriteriaTest.php +++ b/test/testsuite/runtime/query/CriteriaTest.php @@ -304,8 +304,8 @@ public function testAddOrEmptyCriteria(): void public function testCriterionIgnoreCase(): void { $originalDB = Propel::getDB(); - $adapters = [new DBMySQL(), new DBPostgres()]; - $expectedIgnore = ['UPPER(TABLE.COLUMN) LIKE UPPER(:p1)', 'TABLE.COLUMN ILIKE :p1']; + $adapters = [new DBMySQL()]; + $expectedIgnore = ['UPPER(TABLE.COLUMN) LIKE UPPER(:p1)']; $i =0; foreach ($adapters as $adapter) { diff --git a/test/testsuite/runtime/query/ExplainPlanTest.php b/test/testsuite/runtime/query/ExplainPlanTest.php index 046cf7806..550774a3b 100644 --- a/test/testsuite/runtime/query/ExplainPlanTest.php +++ b/test/testsuite/runtime/query/ExplainPlanTest.php @@ -46,8 +46,6 @@ public function testExplainPlanFromObject(): void $this->assertArrayHasKey('table',$explain[1], 'Line 2, table key exist'); $this->assertArrayHasKey('type',$explain[1], 'Line 2, type key exist'); $this->assertArrayHasKey('possible_keys',$explain[1], 'Line 2, possible_keys key exist'); - } elseif ($db instanceof DBOracle) { - $this->assertGreaterThan(2, count($explain), 'Explain plan return more than 2 lines'); } else { $this->markTestSkipped('Cannot test explain plan on adapter ' . get_class($db)); } @@ -77,8 +75,6 @@ public function testExplainPlanFromString(): void $this->assertArrayHasKey('table',$explain[1], 'Line 2, table key exist'); $this->assertArrayHasKey('type',$explain[1], 'Line 2, type key exist'); $this->assertArrayHasKey('possible_keys',$explain[1], 'Line 2, possible_keys key exist'); - } elseif ($db instanceof DBOracle) { - $this->assertGreaterThan(2, count($explain), 'Explain plan return more than 2 lines'); } else { $this->markTestSkipped('Cannot test explain plan on adapter ' . get_class($db)); } diff --git a/test/testsuite/runtime/util/BasePeerTest.php b/test/testsuite/runtime/util/BasePeerTest.php index 2497fe1f5..2240a99ed 100644 --- a/test/testsuite/runtime/util/BasePeerTest.php +++ b/test/testsuite/runtime/util/BasePeerTest.php @@ -129,103 +129,6 @@ public function testMixedJoinOrder(): void $this->assertEquals($expectedSql, $sql); } - public function testMssqlApplyLimitNoOffset(): void - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if (! ($db instanceof DBMSSQL)) { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID)'); - - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - - $c->setOffset(0); - $c->setLimit(20); - - $params = []; - $sql = BasePeer::createSelectSql($c, $params); - - $expectedSql = 'SELECT TOP 20 book.id, book.title, publisher.NAME, (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID) AS PublisherName FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.id)'; - $this->assertSame($expectedSql, $sql); - } - - public function testMssqlApplyLimitWithOffset(): void - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if (! ($db instanceof DBMSSQL)) { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID)'); - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->setOffset(20); - $c->setLimit(20); - - $params = []; - - $expectedSql = 'SELECT [book.id], [book.title], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY book.id) AS [RowNumber], book.id AS [book.id], book.title AS [book.title], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.id)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40'; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertSame($expectedSql, $sql); - } - - public function testMssqlApplyLimitWithOffsetOrderByAggregate(): void - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if (! ($db instanceof DBMSSQL)) { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID)'); - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->addDescendingOrderByColumn('PublisherName'); - $c->setOffset(20); - $c->setLimit(20); - - $params = []; - - $expectedSql = 'SELECT [book.id], [book.title], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID) DESC) AS [RowNumber], book.id AS [book.id], book.title AS [book.title], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.id)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40'; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertSame($expectedSql, $sql); - } - - public function testMssqlApplyLimitWithOffsetMultipleOrderBy(): void - { - $db = Propel::getDB(BookPeer::DATABASE_NAME); - if (! ($db instanceof DBMSSQL)) { - $this->markTestSkipped(); - } - - $c = new Criteria(BookPeer::DATABASE_NAME); - $c->addSelectColumn(BookPeer::ID); - $c->addSelectColumn(BookPeer::TITLE); - $c->addSelectColumn(PublisherPeer::NAME); - $c->addAsColumn('PublisherName','(SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID)'); - $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::LEFT_JOIN); - $c->addDescendingOrderByColumn('PublisherName'); - $c->addAscendingOrderByColumn(BookPeer::TITLE); - $c->setOffset(20); - $c->setLimit(20); - - $params = []; - - $expectedSql = 'SELECT [book.id], [book.title], [publisher.NAME], [PublisherName] FROM (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID) DESC, book.title ASC) AS [RowNumber], book.id AS [book.id], book.title AS [book.title], publisher.NAME AS [publisher.NAME], (SELECT MAX(publisher.NAME) FROM publisher WHERE publisher.id = book.PUBLISHER_ID) AS [PublisherName] FROM book LEFT JOIN publisher ON (book.PUBLISHER_ID=publisher.id)) AS derivedb WHERE RowNumber BETWEEN 21 AND 40'; - $sql = BasePeer::createSelectSql($c, $params); - $this->assertSame($expectedSql, $sql); - } - public function testDoDeleteNoCondition(): void { $this->expectException(PropelException::class); diff --git a/test/tools/helpers/bookstore/validator/ISBNValidator.php b/test/tools/helpers/bookstore/validator/ISBNValidator.php index c92413ca6..ba5679197 100644 --- a/test/tools/helpers/bookstore/validator/ISBNValidator.php +++ b/test/tools/helpers/bookstore/validator/ISBNValidator.php @@ -24,6 +24,6 @@ class ISBNValidator implements BasicValidator */ public function isValid(ValidatorMap $map, $str) { - return !(preg_match(self::NOT_ISBN_REGEXP, $str)); + return !(preg_match(self::NOT_ISBN_REGEXP, (string) $str)); } }