[DBAL-863] [GH-564] [DBAL-630] Incorrect PostgreSQL boolean handling Created: 04/Apr/14  Updated: 07/Apr/14

Status: Awaiting Feedback
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Critical
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: boolean, dbal, orm, postgresql


 Description   

This issue is created automatically through a Github pull request on behalf of davividal:

Url: https://github.com/doctrine/dbal/pull/564

Message:

Working on PostgreSQL incorrect boolean handling when emulating prepared statements



 Comments   
Comment by Davi Koscianski Vidal [ 04/Apr/14 ]

This PR is related to http://www.doctrine-project.org/jira/browse/DBAL-630

Comment by Davi Koscianski Vidal [ 04/Apr/14 ]

The only issue with this PR is that it breaks Doctrine2 ORM. I already have a patch for that too, but I'm not sure on how to proceed.

Comment by Davi Koscianski Vidal [ 04/Apr/14 ]

I'm not breaking ORM anymore.





[DBAL-859] OraclePlatform: rownum should not be used directly in WHERE clausule Created: 12/Feb/14  Updated: 01/Apr/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Critical
Reporter: Mariusz Jaskółka Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Oracle, All OSes.


Attachments: File OraclePlatform.php     File OraclePlatform_bugfix.php    

 Description   

At 90% of cases when we use ROWNUM in WHERE clause it will work correctly, but sometimes not. I noticed that that is why Doctrine sometimes works incorrect.
Source:
http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html

Quote:
"That is why a query in the following form is almost certainly an error:

select *
from emp
where ROWNUM <= 5
order by sal desc;
"

I prepared modified OraclePlatform.php with solution (attachment) - rownum is being compared after all operations.



 Comments   
Comment by Steve Müller [ 01/Apr/14 ]

Mariusz Jaskółka can you please provide an example where the current implementation fails? We have functional tests LIMIT queries in DBAL but they run fine on Oracle. I need more information to be able to reproduce this problem.





[DBAL-630] Incorrect PostgreSQL boolean handling Created: 14/Oct/13  Updated: 04/Apr/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Critical
Reporter: Stan Imbt Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This is a follow-up to issue #457 ("Use int values instead of strings for PostgreSQL booleans"), which is still not fixed. Int values are no solution at all. In fact the root cause lies deeper, outside the PostgreSQL platform class.

1. The patch to fix #457 does not change the default behaviour of the PostgreSQL platform class (method convertBooleans() returns strings 'true'/'false'). When the PostgreSQL PDO driver is configured to emulate prepared statements, it still results in unexpected failures, storing boolean false entity values as true in the database.

2. The new alternative boolean conversion mode activated by PostgreSqlPlatform::setUseBooleanTrueFalseStrings(false) is of no use as it prevents execution of DQL queries with boolean conditions, because integers 0 and 1 are not valid boolean literals in PostgreSQL.

The root cause is the notion of a PHP value being convertible to a database value. Because in fact there are two different types of "database values":

  • Literals used directly in SQL statements
  • Values passed as parameters to prepared statements

To make this absolutely clear:

Prerequisites
$pdo = new PDO(...);
$pdo->exec('CREATE TABLE my_table(bool_col BOOLEAN NOT NULL)');
$stmt = $pdo->prepare('INSERT INTO my_table(bool_col) VALUES(?)');
Using string 'false'
$value = 'false';

// This works, using the SQL literal false
$pdo->exec('INSERT INTO my_table(bool_col) VALUES(' . $value . ')');

// This works, too. But it's remarkable that Postgres accepts the string 'false'
// as a boolean value. Compare this to the string 'NULL' in an SQL statement vs.
// 'NULL' as a prepared statement param (instead of PHP null).
$stmt->bindValue(1, $value, PDO::PARAM_BOOL);
$stmt->execute();

// Sets bool_col to true! The PostgreSQL PDO driver correctly expects a boolean
// and (string)'false' yields true.
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$stmt->bindValue(1, $value, PDO::PARAM_BOOL);
$stmt->execute();
Using boolean false
$value = false;

// This will obviously fail, because false is cast to an empty string, resulting
// in "... VALUES()".
$pdo->exec('INSERT INTO my_table(bool_col) VALUES(' . $value . ')');

// Works
$stmt->bindValue(1, $value, PDO::PARAM_BOOL);
$stmt->execute();

// Works, too
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$stmt->bindValue(1, $value, PDO::PARAM_BOOL);
$stmt->execute();
Using integer 0
$value = 0;

// Causes 'ERROR: column "bool_col" is of type boolean but expression is of type integer'
$pdo->exec('INSERT INTO my_table(bool_col) VALUES(' . $value . ')');

// Works
$stmt->bindValue(1, $value, PDO::PARAM_BOOL);
$stmt->execute();

// Works, because of implicit PHP type cast 0 -> false
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$stmt->bindValue(1, $value, PDO::PARAM_BOOL);
$stmt->execute();

There are two locations in DBAL and ORM where AbstractPlatform::convertBooleans() is called to build SQL literals:

DoctrineDBALPlatformsAbstractPlatform::getDefaultValueDeclarationSQL()
$default = " DEFAULT '" . $this->convertBooleans($field['default']) . "'";

Wow, this is even being enclosed in single quotes!? But then the whole method is buggy anyway, e.g. using an unescaped string value for a string literal (scenarios for SQL injection unlikely but possible).

DoctrineORMQuerySqlWalker::walkLiteral()
case AST\Literal::BOOLEAN:
	$bool = strtolower($literal->value) == 'true' ? true : false;
	$boolVal = $this->conn->getDatabasePlatform()->convertBooleans($bool);
	return $boolVal;

...and the result is later used as a boolean literal in an SQL query.

To solve this we need something like AbstractPlatform::convertBoolToSqlLiteral() (returning strings true and false for the Postgres platform) and AbstractPlatform::convertBoolToDbValue() (converting to integer 0 or 1 for platforms without a native bool type).

Note 1: The docs currently suggest to call $conn->getDatabasePlatform()->setUseBooleanTrueFalseStrings($flag). This is bad OO design, because getDatabasePlatform() returns an AbstracPlattform instance which does not have a contract for the method.

Note 2: What makes this problem so nasty is the fact that switching to emulated prepares makes an application fail in a non-obvious way. There will be no traceable errors but simply all boolean false values in ORM entities stored as boolean true. When integration tests use a different database (e.g. an SQLite in-memory DB to minimize test execution time) the problem will even escape the tests. And the distance between cause and effect also makes the problem very hard to find. Who would expect a database driver setting to cause booleans in the DB to be the opposite of what they're supposed to be? Especially as this only becomes apparent after later re-hydrating stored entities.

Note 3: Why emulated prepared statements matter: When PostgreSQL processes a prepared statement, its query planner works out a query plan and uses it for all subsequent executions of this query. This way it has to make a rather crude guess at the number of affected rows from each table in a join. When a non-prepared query is executed, the query planner can take into account the given values (mostly the ones in the "WHERE" part of the query) and make a much more specific guess at which plan will perform best.
In our case, we decided to switch to emulated prepares after we found out that a complex query in our application would run five times faster with emulated prepares.

Note 4: Is there a reason for AbstractPlatform::convertBooleans() accepting either a single bool value or an array of bool values? I didn't find client code calling it with an array. This makes the method less obvious, is currently implemented with code duplication and at least for the PostgreSQL plattform class, the "array of bool" functionality is not even tested.



 Comments   
Comment by Benjamin Eberlei [ 01/Jan/14 ]

PDO::ATTR_EMULATE_PREPARES finally explains why I was unable to reproduce this before. This is obviously a very critical error. Increasing priority.

Comment by Benjamin Eberlei [ 01/Jan/14 ]

Stan Imbt I cannot really reproduce the ATTR_EMULATE_PREPARES issue, see https://github.com/doctrine/dbal/commit/f29f0fae8479955911928888ebab07ccd4e8ab0c

I agree that we need two methods on the Platform for casting values to SqlLiterals and to Params, as they are in two different contexts.

Comment by Benjamin Eberlei [ 01/Jan/14 ]

We have a reproduce-case, it fails on Travis: https://travis-ci.org/doctrine/dbal/jobs/16217622

Comment by Stan Imbt [ 02/Jan/14 ]

Thanks for looking into this, Benjamin.
We could reproduce the problem with different PHP 5.4 builds on both Linux and Windows (Postgres version shouldn't matter as emulated prepares are handled in the Postgres PDO driver). Travis runs the tests on PHP 5.3 and also fails as expected. Are you using PHP 5.5? If so, I assume the PHP folks have recently changed the PG PDO driver's behaviour, making it act more like PG itself (i.e. converting a bool param with string value 'false' to boolean false).

Comment by Davi Koscianski Vidal [ 31/Mar/14 ]

I'm using PHP 5.5.3 + PostgreSQL 9.3.3 and I confirm that this is not working.

But it looks like it won't work for anyone because PHP: https://bugs.php.net/bug.php?id=57157.

Comment by Stan Imbt [ 01/Apr/14 ]

Davi, I can reproduce the referenced PHP bug, both with and without emulated prepares, but it is not related to this Doctrine bug.

Doctrine calls PDOStatement::bindValue(), specifying the data type PDO::PARAM_BOOL in case of bool fields. The PHP bug only occurs when the param data type is not provided, apparently converting the param value to string ((string)false === '') and passing that on to the DBMS.

Comment by Davi Koscianski Vidal [ 01/Apr/14 ]

Stan, almost the same 'test case' as PHP bug:

<?php

/*
CREATE TABLE "booleantest" (
  "persistence_object_identifier" serial NOT NULL,
  "hidden" boolean NOT NULL
);
 */

$handle = new PDO('pgsql:host=127.0.0.1 dbname=postgres', 'postgres', 'postgres');
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$handle->setAttribute(PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT, true);

$statement = $handle->prepare('INSERT INTO booleantest (hidden) VALUES (?)');

// works as expected
$statement->execute(array(true));
echo 'TRUE has been inserted' . PHP_EOL;

$statement->bindValue(1, "true", PDO::PARAM_BOOL);
echo 'TRUE has been inserted' . PHP_EOL;

// dies with
// PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type boolean: ""
// $statement->execute(array(FALSE));

$statement->bindValue(1, "false", PDO::PARAM_BOOL);
$statement->debugDumpParams();
$statement->execute();
echo 'FALSE has been inserted' . PHP_EOL;

When PDO::ATTR_EMULATE_PREPARES is set to true, $stmt->debugDumpParams() outputs:

SQL: [43] INSERT INTO booleantest (hidden) VALUES (?)
Params:  1
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=2

But when it is disabled, it outputs:

SQL: [43] INSERT INTO booleantest (hidden) VALUES (?)
Params:  1
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=5

This is exactly the same output from tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php (after adding debugDumpParam() to DBAL\Driver\PDOStatement.php, obviously). param_type = 2 when type = PDO::PARAM_STR.
For debugging purposes, I changed DBAL\Driver\PDOStatement.php line 67 from return parent::bindValue($param, $value, $type); to parent::bindValue(1, "false", \PDO::PARAM_BOOL); (so I will always store a boolean false on database), but debugDumpParam() keeps telling me that param_type is 2 if I'm using emulated prepares.

Comment by Davi Koscianski Vidal [ 01/Apr/14 ]

Using $stmt->bindValue(1, 'false', \PDO::PARAM_STR); works as expected. Maybe a dirty workaround?

Comment by Davi Koscianski Vidal [ 03/Apr/14 ]

This same test case passes with PHP 5.3.18, but fails with 5.5.3 and 5.5.11.

$ phpenv shell 5.5.11

$ php --version
PHP 5.5.11 (cli) (built: Apr  3 2014 09:52:27) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

$ vendor/bin/phpunit -c postgres.phpunit.xml tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php 
PHPUnit 3.7.34 by Sebastian Bergmann.

Configuration read from.postgres.phpunit.xml

..F

Time: 3.91 seconds, Memory: 4.25Mb

There was 1 failure:

1) Doctrine\Tests\DBAL\Functional\Ticket\DBAL630Test::testBooleanConversionBoolParamEmulatedPrepares
Failed asserting that true is false.

./tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php:79

FAILURES!
Tests: 3, Assertions: 6, Failures: 1.

$ phpenv shell system 

$ php --version
PHP 5.5.3-1ubuntu2.2 (cli) (built: Feb 28 2014 20:06:05) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies

$ vendor/bin/phpunit -c postgres.phpunit.xml tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php 
PHPUnit 3.7.34 by Sebastian Bergmann.

Configuration read from ./postgres.phpunit.xml

..F

Time: 1.59 seconds, Memory: 4.25Mb

There was 1 failure:

1) Doctrine\Tests\DBAL\Functional\Ticket\DBAL630Test::testBooleanConversionBoolParamEmulatedPrepares
Failed asserting that true is false.

./tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php:79

FAILURES!
Tests: 3, Assertions: 6, Failures: 1.

$ phpenv shell 5.3.18 

$ php --version
PHP 5.3.18 (cli) (built: Apr  2 2014 16:47:04) 
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies

$ vendor/bin/phpunit -c postgres.phpunit.xml tests/Doctrine/Tests/DBAL/Functional/Ticket/DBAL630Test.php 
PHPUnit 3.7.34 by Sebastian Bergmann.

Configuration read from ./postgres.phpunit.xml

...

Time: 1.06 seconds, Memory: 6.50Mb

OK (3 tests, 6 assertions)
Comment by Davi Koscianski Vidal [ 04/Apr/14 ]

I think I messed something when creating the PR. The bot automatically created this ticket: http://www.doctrine-project.org/jira/browse/DBAL-863

I'm sorry.





[DBAL-833] [GH-542] [DBAL-825] Drop default constraints before altering column type on SQL Server Created: 07/Mar/14  Updated: 07/Mar/14

Status: In Progress
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: sqlserver, sqlsrv

Issue Links:
Duplicate
duplicates DBAL-825 ALTER COLUMN on mssql is failing if d... In Progress
duplicates DBAL-826 [GH-536] [WIP] unit test for DBAL-825 Resolved

 Description   

This issue is created automatically through a Github pull request on behalf of deeky666:

Url: https://github.com/doctrine/dbal/pull/542

Message:

SQL Server implements column default values as constraints and therefore requires them to be dropped before a column type change.
This PR implements the recreation of default constraints on column type alterations.
Additionally some code in `SQLServerPlatform::getAlterTableSQL()` has been refactored to avoid code duplication and unnecessary SQL generation.
Please note that due to the issue's tests the PostgreSQL platform had to be altered to fulfill the same behaviour. PostgreSQL returned some strange default value like `666:smallint` when reverse engineering a column type change with a default value of `666` from type `smallint` to `integer`. So I think this PR fixes a bug in this platform, too. Additionally I had to change the deprecated default value retrieval SQL in PostgreSQL in order to work flawlessly. See the [documentation](http://www.postgresql.org/docs/9.3/static/catalog-pg-attrdef.html) at the very end.

I would also like to note that this PR is definitely not the end of the line concerning default values and column alterations. Some weird errors were revealed on other platforms while fixing this issue. MySQL for example denies default values on BLOB/TEXT type columns, DB2 just throws non-understandable syntax errors around and Oracle seems to map decimal/numeric types without a defined scale to integer when reverse engineering (not really related to this issue but it came up while testing).

Otherwise the tests pass on all platforms.



 Comments   
Comment by Doctrine Bot [ 07/Mar/14 ]

A related Github Pull-Request [GH-536] was closed:
https://github.com/doctrine/dbal/pull/536





[DBAL-834] SQLServer modifyLimitQuery does not work with aggregate functions in ORDER BY Created: 10/Mar/14  Updated: 21/Mar/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Francesco Montefoschi Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: paginator
Environment:

SQL Server 2008 SP3



 Description   

Starting with Doctrine 2.4, the `modifyLimitQuery` method does not work anymore with query using ORDER BY MAX(...)
See this example:

$sql = "SELECT MAX(heading_id) aliased, code
	FROM operator_model_operator
	GROUP BY code
	ORDER BY MAX(heading_id) DESC
";
$sql = $this->em->getConnection()->getDatabasePlatform()->modifyLimitQuery(
	$sql, 1, 0
);

Doctrine generates this SQL, which is invalid:

SELECT * FROM (SELECT MAX(heading_id) aliased, code
, ROW_NUMBER() OVER (ORDER BY MAX(heading_id) AS doctrine_rownum FROM operator_model_operator GROUP BY code) DESC
) AS doctrine_tbl WHERE doctrine_rownum BETWEEN 1 AND 1

The ORDER BY in moved into the OVER(), but the `preg_replace` in SQLServerPlatform.php stops to replace at the closing ")".



 Comments   
Comment by Francesco Montefoschi [ 10/Mar/14 ]

It is not possible to write `ORDER BY aliased` because it leads to a syntax error in SQL Server.

Comment by Steve Müller [ 10/Mar/14 ]

Francesco Montefoschi There have been some modifications to the modifyLimitQuery() method in SQL Server lately for 2.5 which address some problems with subqueries and aggregate functions. Not sure if that might already solve your issue. Can you please check if the problem also exists in the current master branch of DBAL?
See commit: https://github.com/doctrine/dbal/commit/9f3cb437c0f491599de4e1bd847235965f98ffd4

Comment by Francesco Montefoschi [ 11/Mar/14 ]
  - Removing doctrine/common (v2.4.1)
  - Installing doctrine/common (2.4.x-dev 9a7e20e)
    Cloning 9a7e20e779360f3b8a02c27a89d47d5a6fdce8d1

  - Removing doctrine/dbal (v2.4.2)
  - Installing doctrine/dbal (dev-master c61361d)
    Cloning c61361d8fcf65a977d8610ba78eb542a1d2f44b4

  - Removing doctrine/orm (v2.4.2)
  - Installing doctrine/orm (2.4.x-dev a949e87)
    Cloning a949e87ca88299cde368d2b574740753526b62c9

Same issue.

Comment by Flip [ 14/Mar/14 ]

on this line here https://github.com/doctrine/dbal/blob/9f3cb437c0f491599de4e1bd847235965f98ffd4/lib/Doctrine/DBAL/Platforms/SQLServerPlatform.php#L1164

try the following stuffs:

Puts "DESC" in a second capturing group (closer to the original regex, but not sure why you want to do this)
/ORDER\s+BY\s+([^)(]*(?:\(\w+\))?)(.*)/

Includes "DESC" in the first capturing group
/ORDER\s+BY\s+([^)(]*(?:\(\w+\))?.*)/

Same as last one, except this one stops capturing when it hits a ")" after "DESC"
/ORDER\s+BY\s+([^)(]*(?:\(\w+\))?[^)]*)/
Comment by M.K. [ 21/Mar/14 ]

This not only affects Queries with aggregate functions, but every Query that uses a limit and order by an entity-field alias.

Try this Testcase:

$query = $this->em->createQuery("
	SELECT a.id AS test
	FROM prim\\entity\\Article a
	ORDER BY test ASC
");
$query->setMaxResults(10);
echo "<h3>DQL</h3>";
var_dump($query->getDQL());
echo "<br><h3>SQL</h3>";
var_dump($query->getSQL());
echo "<br><h3>Result</h3>";
var_dump($query->getResult());
Comment by Flip [ 21/Mar/14 ]

The test case is incomplete as we don't have `kare\\entity
Article`. Please try the 3 proposed solutions and show the results from those adjustments.

Comment by M.K. [ 21/Mar/14 ]

This is just a sample Query for illustration. Replace it with whatever Entity you like.





[DBAL-830] [GH-539] unit test added for altering a column's default where the column name is... Created: 04/Mar/14  Updated: 05/Mar/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: sqlsrv


 Description   

This issue is created automatically through a Github pull request on behalf of DeepDiver1975:

Url: https://github.com/doctrine/dbal/pull/539

Message:

... a keyword - fails on mssql:

Exception : [Doctrine\DBAL\DBALException] An exception occurred while executing 'ALTER TABLE column_keyword_test DROP CONSTRAINT DF_D3D4D2F1_4BF2EAC0':

SQLSTATE [42000, 3728]: [Microsoft][SQL Server Native Client 11.0][SQL Server]'DF_D3D4D2F1_4BF2EAC0' is not a constraint.
SQLSTATE [42000, 3727]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Could not drop constraint. See previous errors.

With queries:
5. SQL: 'ALTER TABLE column_keyword_test DROP CONSTRAINT DF_D3D4D2F1_4BF2EAC0' Params: 
4. SQL: 'SELECT    col.name,
                          type.name AS type,
                          col.max_length AS length,
                          ~col.is_nullable AS notnull,
                          def.definition AS [default],
                          col.scale,
                          col.precision,
                          col.is_identity AS autoincrement,
                          col.collation_name AS collation,
                          CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
                FROM      sys.columns AS col
                JOIN      sys.types AS type
                ON        col.user_type_id = type.user_type_id
                JOIN      sys.objects AS obj
                ON        col.object_id = obj.object_id
                JOIN      sys.schemas AS scm
                ON        obj.schema_id = scm.schema_id
                LEFT JOIN sys.default_constraints def
                ON        col.default_object_id = def.object_id
                AND       col.object_id = def.parent_object_id
                LEFT JOIN sys.extended_properties AS prop
                ON        obj.object_id = prop.major_id
                AND       col.column_id = prop.minor_id
                AND       prop.name = 'MS_Description'
                WHERE     obj.type = 'U'
                AND       (obj.name = 'column_keyword_test' AND scm.name = SCHEMA_NAME())' Params: 
3. SQL: 'ALTER TABLE column_keyword_test ADD CONSTRAINT DF_D3D4D2F1_ACF51D19 DEFAULT 23 FOR [select]' Params: 
2. SQL: 'CREATE TABLE column_keyword_test ([select] INT NOT NULL)' Params: 

Trace:
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Connection.php:988
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Schema\AbstractSchemaManager.php:971
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Schema\AbstractSchemaManager.php:612
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Schema\SQLServerSchemaManager.php:232
C:\projects\doctrine\dbal\tests\Doctrine\Tests\DBAL\Functional\Schema\SchemaManagerFunctionalTestCase.php:619
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php:976
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php:831
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestResult.php:648
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php:776
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php:775
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php:745
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\TextUI\TestRunner.php:349
C:\Program Files (x86)\PHP\v5.3\pear\PHPUnit\TextUI\Command.php:176
C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php:268
C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php:506

#0 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php(946): Doctrine\Tests\DbalFunctionalTestCase->onNotSuccessfulTest(Object(Doctrine\DBAL\DBALException))
#1 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestResult.php(648): PHPUnit_Framework_TestCase->runBare()
#2 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php(776): PHPUnit_Framework_TestResult->run(Object(Doctrine\Tests\DBAL\Functional\Schema\SQLServerSchemaManagerTest))
#3 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php(775): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#4 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php(745): PHPUnit_Framework_TestSuite->runTest(Object(Doctrine\Tests\DBAL\Functional\Schema\SQLServerSchemaManagerTest), Object(PHPUnit_Framework_TestResult))
#5 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\TextUI\TestRunner.php(349): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#6 C:\Program Files (x86)\PHP\v5.3\pear\PHPUnit\TextUI\Command.php(176): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#7 C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php(268): PHPUnit_TextUI_Command->run(Array, true)
#8 C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php(506): IDE_Base_PHPUnit_TextUI_Command::main()
#9 {main}





[DBAL-825] ALTER COLUMN on mssql is failing if default constraint is attached Created: 03/Mar/14  Updated: 07/Mar/14

Status: In Progress
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Thomas Müller Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: None
Environment:

MSSQL


Issue Links:
Duplicate
is duplicated by DBAL-833 [GH-542] [DBAL-825] Drop default cons... In Progress
is duplicated by DBAL-826 [GH-536] [WIP] unit test for DBAL-825 Resolved

 Description   

Here is the unit test - implemented in class SchemaManagerFunctionalTestCase

 
    public function testChangeColumnsTypeWithDefault()
    {
        $table = new \Doctrine\DBAL\Schema\Table('column_change_type_test');
        $table->addColumn('id', 'integer', array('default' => 5));

        $this->_sm->createTable($table);

        $columns = $this->_sm->listTableColumns("column_change_type_test");
        $this->assertEquals(1, count($columns));
        $this->assertInstanceOf('Doctrine\DBAL\Types\IntegerType', $columns['id']->getType());

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff('column_change_type_test');
        $tableDiff->changedColumns['id'] = new \Doctrine\DBAL\Schema\ColumnDiff(
            'id', new \Doctrine\DBAL\Schema\Column(
                'id', \Doctrine\DBAL\Types\Type::getType('smallint'), array('default' => 5)
            ),
            array('type'),
            new \Doctrine\DBAL\Schema\Column(
                'id', \Doctrine\DBAL\Types\Type::getType('integer'), array('default' => '5')
            )
        );

        $this->_sm->alterTable($tableDiff);

        $columns = $this->_sm->listTableColumns("column_change_type_test");
        $this->assertEquals(1, count($columns));
        $this->assertInstanceOf('Doctrine\DBAL\Types\SmallIntType', $columns['id']->getType());
        $this->assertSame('', $columns['id']->getDefault());
    }

Causes following result

 
Exception : [Doctrine\DBAL\DBALException] An exception occurred while executing 'ALTER TABLE column_change_type_test ALTER COLUMN id SMALLINT NOT NULL':

SQLSTATE [42000, 5074]: [Microsoft][SQL Server Native Client 11.0][SQL Server]The object 'DF_A74995E2_BF396750' is dependent on column 'id'.
SQLSTATE [42000, 4922]: [Microsoft][SQL Server Native Client 11.0][SQL Server]ALTER TABLE ALTER COLUMN id failed because one or more objects access this column.

With queries:
5. SQL: 'ALTER TABLE column_change_type_test ALTER COLUMN id SMALLINT NOT NULL' Params: 
4. SQL: 'SELECT    col.name,
                          type.name AS type,
                          col.max_length AS length,
                          ~col.is_nullable AS notnull,
                          def.definition AS [default],
                          col.scale,
                          col.precision,
                          col.is_identity AS autoincrement,
                          col.collation_name AS collation,
                          CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
                FROM      sys.columns AS col
                JOIN      sys.types AS type
                ON        col.user_type_id = type.user_type_id
                JOIN      sys.objects AS obj
                ON        col.object_id = obj.object_id
                JOIN      sys.schemas AS scm
                ON        obj.schema_id = scm.schema_id
                LEFT JOIN sys.default_constraints def
                ON        col.default_object_id = def.object_id
                AND       col.object_id = def.parent_object_id
                LEFT JOIN sys.extended_properties AS prop
                ON        obj.object_id = prop.major_id
                AND       col.column_id = prop.minor_id
                AND       prop.name = 'MS_Description'
                WHERE     obj.type = 'U'
                AND       (obj.name = 'column_change_type_test' AND scm.name = SCHEMA_NAME())' Params: 
3. SQL: 'ALTER TABLE column_change_type_test ADD CONSTRAINT DF_A74995E2_BF396750 DEFAULT 5 FOR id' Params: 
2. SQL: 'CREATE TABLE column_change_type_test (id INT NOT NULL)' Params: 

Trace:
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Connection.php:988
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Schema\AbstractSchemaManager.php:971
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Schema\AbstractSchemaManager.php:612
C:\projects\doctrine\dbal\lib\Doctrine\DBAL\Schema\SQLServerSchemaManager.php:232
C:\projects\doctrine\dbal\tests\Doctrine\Tests\DBAL\Functional\Schema\SchemaManagerFunctionalTestCase.php:621
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php:976
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php:831
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestResult.php:648
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php:776
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php:775
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php:745
C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\TextUI\TestRunner.php:349
C:\Program Files (x86)\PHP\v5.3\pear\PHPUnit\TextUI\Command.php:176
C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php:268
C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php:506

#0 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php(946): Doctrine\Tests\DbalFunctionalTestCase->onNotSuccessfulTest(Object(Doctrine\DBAL\DBALException))
#1 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestResult.php(648): PHPUnit_Framework_TestCase->runBare()
#2 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestCase.php(776): PHPUnit_Framework_TestResult->run(Object(Doctrine\Tests\DBAL\Functional\Schema\SQLServerSchemaManagerTest))
#3 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php(775): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#4 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\Framework\TestSuite.php(745): PHPUnit_Framework_TestSuite->runTest(Object(Doctrine\Tests\DBAL\Functional\Schema\SQLServerSchemaManagerTest), Object(PHPUnit_Framework_TestResult))
#5 C:\projects\doctrine\dbal\vendor\phpunit\phpunit\PHPUnit\TextUI\TestRunner.php(349): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#6 C:\Program Files (x86)\PHP\v5.3\pear\PHPUnit\TextUI\Command.php(176): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#7 C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php(268): PHPUnit_TextUI_Command->run(Array, true)
#8 C:\Users\deepdiver\AppData\Local\Temp\ide-phpunit.php(506): IDE_Base_PHPUnit_TextUI_Command::main()
#9 {main}



 Comments   
Comment by Thomas Müller [ 03/Mar/14 ]

Possible solution: http://www.select-sql.com/mssql/how-to-alter-column-with-default-constraint-in-mssql.html

Comment by Thomas Müller [ 03/Mar/14 ]

Here is the unit test: https://github.com/DeepDiver1975/dbal/commit/53238301f7e124d31232e9b3eab774c32c9e04c4

Comment by Steve Müller [ 03/Mar/14 ]

Thomas Müller Thanks for reporting. Which version of SQL Server is affected by this?

Comment by Thomas Müller [ 03/Mar/14 ]

SQL Server 2012 Express Edition





[DBAL-819] Schema-tools does not work on multiple Oracle's schemas Created: 21/Feb/14  Updated: 22/Feb/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms, Schema Managers
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Antoine Descamps Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: Cli, oracle, orm, schematool
Environment:

DB: Oracle 11g



 Description   

The schema-tools, used via the CLI, is not able to detect schema's changes when working on multiple schemas.

For instance, the ORM is configured with a "global" Oracle's user, having permissions on every schemas. To specify which entities belong to which schema, I've prefixed the table name with the corresponding schema.

When trying to do the following command:

orm:schema-tool:update --dump-sql

Doctrine returns me the following message:

Nothing to update - your database is already in sync with the current entity metadata.

If, instead of using the "global" user in the Doctrine's configuration, I set the user of the specific schema I'm trying to generate a table on based from an entity, it works.



 Comments   
Comment by Steve Müller [ 21/Feb/14 ]

Moved this to DBAL for now. It seems to be related to schema prefixed table names not being evaluated in the platforms when generating the SQL for reverse engineering the database schema.

Comment by Steve Müller [ 22/Feb/14 ]

Antoine Descamps Okay after having investigated on this in detail and thinking about the possibilities we have to find a solution for this, I came to the following conclusion:
ORM's schema tool and DBAL's schema introspection are designed to be bound to what Doctrine defines as "database" for each platform. This is the scope of the whole operation. In case of Oracle it is the "user". You cannot break out of this scope in any way as the current DBAL implementation is not designed for a "complete" schema introspection and therefore does not allow it at some points. Fully understanding your concern I am afraid we cannot find a reasonable solution for your use case at this point in development (2.x). Furthermore there is a good reason for limiting the schema introspection to a certain layer. If the schema tool would introspect the "complete" schema without regard to the database it is connected to, it would suggest a lot of schema changes from other databases that do not belong to the context of the entity manager / database. This behaviour would even cause a lot more annoyance to users as it is the default use case that users are only interested in one database per entity manager.
Also this problem is completely independant from your mapping definitions. So it doesn't matter whether you prefix your table names or not. When running the "update" operation on the schema tool, it is the online schema introspection part that is preventing the schema tool from behaving as you would wish.
Changing the schema introspection behaviour in DBAL would completely break BC and is at some places in the code not even possible without changing the API.
I am sorry that I have to disappoint you with this conclusion but we I am afraid we cannot do anything about your issue until we start developing 3.x. We might reevaluate your use case their and see what we can do.





[DBAL-807] Index renaming in postgresql does not work when index relates to table inside namespace Created: 08/Feb/14  Updated: 22/Feb/14

Status: In Progress
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.5
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Artur Eshenbrener Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: None

Issue Links:
Reference
is referenced by DBAL-821 [GH-532] DBAL-807 [DBAL-807] - Added ... Open
is referenced by DBAL-822 [GH-533] [DBAL-807] Respect schema wh... Open

 Description   
CREATE SCHEMA test;
CREATE TABLE test.table_name (id INT);
CREATE INDEX idx_1 ON test.table_name (id);

If index would be renamed, generated sql is:

ALTER INDEX idx_1 RENAME TO new_index_name;

But valid sql code should be:

ALTER INDEX test.idx_1 RENAME TO new_index_name;


 Comments   
Comment by Steve Müller [ 21/Feb/14 ]

Artur Eshenbrener Can you please provide more details about your use case so that we can reproduce it better. How do you get the wrong SQL?

Comment by Artur Eshenbrener [ 22/Feb/14 ]

I've pushed failing test, reproduces this problem.
https://github.com/doctrine/dbal/pull/532

Comment by Doctrine Bot [ 22/Feb/14 ]

A related Github Pull-Request [GH-532] was closed:
https://github.com/doctrine/dbal/pull/532

Comment by Steve Müller [ 22/Feb/14 ]

Patch supplied in PR: https://github.com/doctrine/dbal/pull/533





[DBAL-802] Tablename quoting not working for ALTER TABLE Created: 06/Feb/14  Updated: 06/Feb/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.3.4, 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Dennis Birkholz Assignee: Steve Müller
Resolution: Unresolved Votes: 0
Labels: Quoting, TableDiff, mysql


 Description   

I use the orm:schema-tool:update to update the database schema of my model which contains a table with the name "Character".
Quoting for this table name works without the need to add backticks in foreign key definitions (references `Character`) but "ALTER Character" misses the quotes.
The reason is that the getAlterTableSQL method of the MySqlPlatform class uses the name property of the supplied TableDiff which does not contain a quoted name.
The original Table information that contained the quoting information is not available from the TableDiff.

A quick fix is to just force a name quoting with "$this->quoteIdentifier($diff->name)" in the getAlterTableSQL but this does ignore all quoting-decision-functionality of doctrine.



 Comments   
Comment by Dennis Birkholz [ 06/Feb/14 ]

Just checked on v2.4.2: the issue is still present there but the TableDiff now contains the original table information object so the fix may be a lot less hacky.

Comment by Steve Müller [ 06/Feb/14 ]

Dennis Birkholz This issue should have been fixed in 2.5, commit: https://github.com/doctrine/dbal/commit/75d35f5809095b37cb7085a9289eca4aa9c6df68
See here: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php#L600

Please check again with the current master.





[DBAL-788] ORDER BY with function COUNT() fails Created: 08/Jan/14  Updated: 14/Mar/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Flip Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

mssql 2008 R2



 Description   

This:
ORDER BY ad.name ASC, count(filter.value) DESC

Fails with:
Error: Expected end of string, got '('



 Comments   
Comment by M.K. [ 15/Jan/14 ]

I have the same problem using SUM() in ORDER BY. I think the doctrine documentation says, that you have to use an alias in ORDER BY. This works fine with MySQL, but fails in MSSQL, because MSSQL doesn't allow aliases in ORDER BY.
I think using aliases in DQL should be fine, so it's rather a problem in SQLServerPlatform class. Aggregate functions in ORDER BY are pretty basic stuff.

Issue should be moved to DBAL.

Comment by Steve Müller [ 15/Jan/14 ]

Is using aggregate functions in ORDER BY even possible in SQL Server? It's not clear from the documentation. However it looks like ORDER BY SQL generation might have to be delegated to the specific platform just like LIMIT/OFFSET clauses. This would be another big mess for SQL Server

Comment by M.K. [ 15/Jan/14 ]

I use MSSQL 2008 R2 as well and it seems MSSQL is fine with using aliases in ORDER BY after all. If i run a DQL-Query like that:

SELECT t.id, SUM(pos.price) AS amount
FROM Project\Entity\Task t
LEFT JOIN Project\Entity\Position pos WITH t.id = pos.tid
GROUP BY t.id
ORDER BY amount ASC

... everything is fine. SQL looks like this:

SELECT t0_.id AS id0, SUM(p0_.price) AS sclr1
FROM task t0_ WITH (NOLOCK)
LEFT JOIN position p0_ ON (t0_.id = p0_.tid)
GROUP BY t0_.id
ORDER BY sclr1 ASC

MSSQL seems to be okay with the alias. But if apply a limit on the DQL-Query, SQL looks like this:

SELECT *
FROM (
	SELECT t0_.id AS id0, SUM(p0_.price) AS sclr1, ROW_NUMBER() OVER (ORDER BY sclr1 ASC) AS doctrine_rownum
	FROM task t0_ WITH (NOLOCK)
	LEFT JOIN position p0_ ON (t0_.id = p0_.tid)
	GROUP BY p0_.id
) AS doctrine_tbl
WHERE doctrine_rownum BETWEEN 1 AND 50

Execution fails with Error: "Invalid column name 'sclr1'"

I'm not really familiar with MSSQL which is why i decided to use Doctrine after all. But i hope this helps.

Comment by Steve Müller [ 15/Jan/14 ]

M.K. Thanks for the detailed information. The fact that you are using a limit here was missing. SQL Server does not support referring to expressions or column aliases from the select list in OVER() clause.
See here: http://msdn.microsoft.com/en-us/library/ms189461.aspx
Could you please test if it possible to specify the SUM() expression directly in the OVER() clause? Like the following:

SELECT *
FROM (
	SELECT t0_.id AS id0, SUM(p0_.price) AS sclr1, ROW_NUMBER() OVER (ORDER BY SUM(p0_.price) ASC) AS doctrine_rownum
	FROM task t0_ WITH (NOLOCK)
	LEFT JOIN position p0_ ON (t0_.id = p0_.tid)
	GROUP BY p0_.id
) AS doctrine_tbl
WHERE doctrine_rownum BETWEEN 1 AND 50

If that works we might be able to rewrite the SQLServerPlatform::modifyLimitQuery() to respect that. Otherwise I really don't know what to do about it.

Comment by M.K. [ 15/Jan/14 ]

Yup, using the SUM() expression in the OVER() clause works just fine.

Comment by Steve Müller [ 15/Jan/14 ]

M.K. Thank you for investigating. I would like to move this ticket to DBAL because it is a DBAL issue. But I guess that makes two issues now because if I understand correctly, Flip did not use a limit/offset query modification but did not use an alias in the ORDER BY clause either but instead directly specified a COUNT() expression...

Comment by Flip [ 24/Jan/14 ]

I can confirm it works when using an alias. Issue can be closed.

Comment by M.K. [ 14/Mar/14 ]

This issue refers to the same problem:
http://www.doctrine-project.org/jira/browse/DBAL-834





[DBAL-669] Postgresql platform schema creation fails if it already exists Created: 18/Nov/13  Updated: 02/Apr/14

Status: Awaiting Feedback
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4, 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Chris Ramakers Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Postgresql 8.3.14 on CentOS6
Also happens on Postgresql 9.2 on the same box



 Description   

This patch (https://github.com/doctrine/dbal/commit/fabe3c346b24dcb70eba0cb3936998ec6cc152f0) introduced a bug where the schemaNeedsCreation method always returns true if the schema name isn't 'default' or 'public'.

We heavily use schema's in our application and whenever an insert query is queued, it fails because the schema in question already exists but the platform adapter fails to detect that and continues with a "CREATE SCHEMA" query which fails.

The easy fix is to add the 'IF NOT EXISTS' clause to the 'CREATE SCHEMA' query but that will only function on Postgresql 9.3 and upward since 'IF NOT EXISTS' wasn't possible in earlier versions for schema creation.

Beter would be to load the existing schema's and compare them to those. I would create a pull request but i'm not sure how to obtain a database connection in the Platform (if at all possible) to pull a list of already known schema's?



 Comments   
Comment by Marco Pivetta [ 13/Dec/13 ]

Chris Ramakers I'm trying to look into it. The method

schemaNeedsCreation

seems indeed to be wrong.

Comment by Marco Pivetta [ 13/Dec/13 ]

Provided a fix for this at https://github.com/doctrine/dbal/pull/444

We won't fix the schema creation command, since it is supposed to fail on already existing conflicting elements (tables/etc)

Comment by Chris Ramakers [ 02/Apr/14 ]

Any news on this? The bug keeps causing problems every time we deploy a new version. We are practically required to edit the vendor files for doctrine in our project so this bug doesn't cause issues.





[DBAL-642] Generated IDs are not guaranteed to be unique over the table's lifetime in SQLite Created: 27/Oct/13  Updated: 01/Jan/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: flack Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

In

http://docs.doctrine-project.org/en/2.0.x/reference/basic-mapping.html#identifier-generation-strategies

it says that MySQL and SQLite use AUTO_INCREMENT by default. The generated SQL for creating an ID field with GENERATOR_TYPE_AUTO looks like this (abbreviated
for readability):

CREATE_TABLE_TEST (id INTEGER DEFAULT 0 NOT NULL, PRIMARY KEY(id))

http://www.sqlite.org/faq.html#q1 states:

If you declare a column of a table to be INTEGER PRIMARY KEY, then whenever you insert a NULL into that column of the table, the NULL is automatically converted into an integer which is one greater than the largest value of that column over all other rows in the table, or 1 if the table is empty. [...] Note that the integer key is one greater than the largest key that was in the table just prior to the insert. The new key will be unique over all keys currently in the table, but it might overlap with keys that have been previously deleted from the table.

So in other words, if you remove an entity and then create a new one, the new one will have the same id as the previously deleted one. If you do both operations on the same entitymanager, id references (in proxies f.x.) will suddenly get confused and point to something else (at least that's my current theory..)

The point is: SQLite doesn't act like MySQL as the documentation implies, and IMHO SQLite's current behaviour makes it useless for more complex scenarios. I've found some reference to this problem here:

https://github.com/doctrine/dbal/pull/66

Unfortunately, it doesn't mention any solution. The problem is that you can't override the columnDefinition, because it would have to be "INTEGER PRIMARY KEY AUTOINCREMENT", but then, you get an exception, because the Platform appends ", PRIMARY KEY(id)", so it's defined twice



 Comments   
Comment by Steve Müller [ 25/Nov/13 ]

As far as I understand there is a conflict in SQLite between having an autoincrement primary key and having a composite primary because you can only choose either way. The PR you referenced removed the autoincrement behaviour in favour of having the opportunity to define composite primary keys. So what would you expect to be the solution here?

Comment by flack [ 25/Nov/13 ]

Well, from a user's point of view, it would be nice if the SQLite Platform implementation would make full use of the possibilities of SQLite. That is to say: If someone uses composite primary, they get the behaviour Doctrine has right now, and those that use the simple case (which is recommended all over the documentation), get the behaviour previous to the pull request, i.e. autoincrement that works like in MySQL (which the documentation implies). As far as I understood the discussion in the pull request, the author was looking for a solution to implement this, but then the PR was merged before the issue was solved.

Comment by flack [ 25/Nov/13 ]

I guess what is bothering me is that the current behaviour breaks assumptions that I think many applications using Doctrine make. At least I know that in my own code, I never planned for the possibility of a database primary key being re-used for a different object, especially not during the same request. And like I wrote above, I suspect that Doctrine itself is not totally prepared for that situation either (also mentioned here: https://github.com/doctrine/dbal/pull/66#discussion_r173623). So IMHO the IDENTIY generator strategy for SQLite seems broken, or at least is behaving unexpectedly. The documentation says

AUTO (default): Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite and MsSQL and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability.

I don't really see how the current behaviour can be said to provide full portability (at least with MySQL, which supposedly uses the same preferred strategy)

Comment by Steve Müller [ 25/Nov/13 ]

Yeah I get your point. But it's always hard and error prone to work around the vendors lack of common features. A possibility COULD be to implement a trigger in columns declared as autoincrement which simulates the behaviour of an auotincrement column on inserts. Oracle uses a similar workaround with a trigger and a sequence to simulate autoincrement columns. But this is just an idea and has to evaluated for usability first.

Comment by Steve Müller [ 25/Nov/13 ]

Yes that's true. The documentation is misleading here. I guess that it was written before the issue came up and then was not updated. Unfortunately SQLite does not support native sequences which would make life a lot easier. But I will keep that in mind and investigate a solution for this.

Comment by Benjamin Eberlei [ 13/Dec/13 ]

I think there is no fix for this, this is just how SQLite works, and we cannot really keep the last ids somewhere. IMHO its a documentation issue.

Comment by flack [ 13/Dec/13 ]

Well, you cannot fix it for cases with multiple id columns (but the Doctrine documentation already suggests that they should be avoided where possible), but for single integer columns (which is the normal case, as suggested by documentation), SQLite provides all the necessary functionality, as long as you create the column with INTEGER PRIMARY KEY AUTOINCREMENT. So IMHO the best solution would be if support for this could be implemented somehow in the SQL Platform driver.

Comment by flack [ 14/Dec/13 ]

Case in point: I implemented exactly this in a Doctrine adapter I'm working on:

https://github.com/flack/midgard-portable/blob/master/src/midgard/portable/storage/subscriber.php#L136

Granted, this is a very ugly workaround that only works because I know all my ID columns are actually called 'id' (and will never change), but I'm fairly sure that a more general solution could be built with reasonable effort.

Comment by Benjamin Eberlei [ 01/Jan/14 ]

flack We removed the Sqlite AUTOINCREMENT for some weird reason. I am inclined to add this again, however I need to find out what the reasons for removing this have been.

Comment by Steve Müller [ 01/Jan/14 ]

Benjamin Eberlei I checked that lately and I came to the same conclusion. The reason why it was removed is to support composite primary keys which was not possible before somehow. We could add autoincrement if only a single column integer primary key is given I think...





[DBAL-550] Complete/non-overridable event dispatching in DDL methods of AbstractPlatform Created: 22/Jun/13  Updated: 23/Dec/13

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Stéphane Klein Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: migrations, schematool


 Description   

The default implementation provided by the AbstractPlatform class dispatches several events related to schema modifications (create table, change column and so on) and offers the ability to prevent the default behaviour by setting a flag on the dispatched event. However, it appears that some DDL operations aren't covered by this mechanism (foreign keys creation, for example, doesn't seem to be observable). Furthermore, the concrete platforms can override any of these methods, potentially leading to inconsistancies in components that expect those events to be dispatched.

I'm working on a large modular application build on top of Symfony, in which each bundle must have its own migration classes (i.e. migrations on a per bundle basis, not at the application level), possibly with references to other parts of the schema. I used to write those classes manually using the dbal api, but this is tiedous and error-prone, and I'd like to take advantage of the mapping-based schema generation. I found that using the event system and "filtering" ddl operations to keep only the operations related to a given bundle is a clean and easy way to achieve this goal, but the issues I mentionned prevent me to complete the implementation.

I'd be glad to hear your opinion on that topic and, providing you're interested in it, contribute in a way or another to improve the existing code.



 Comments   
Comment by Benjamin Eberlei [ 22/Jun/13 ]

This is not a blocker

Comment by Benjamin Eberlei [ 22/Jun/13 ]

The DBAL event system is not in its best shape and definately could use some improvement. Your easiest way however would be to hook the process of generating the whole schema, and then dropping tables from those two to only contain the ones you are interested in.

Comment by Stéphane Klein [ 23/Jun/13 ]

That's indeed the simplest solution. Thanks a lot for your answer.

Comment by Steve Müller [ 23/Dec/13 ]

Benjamin Eberlei Is there anything to do here? Should the missing events be added or is that not necessary?





[DBAL-477] Just doublequote all schema names and field names in PostgreSQL sql command generation, and the same for MySQL Created: 28/Mar/13  Updated: 24/Dec/13

Status: Open
Project: Doctrine DBAL
Component/s: Platforms, Schema Managers
Affects Version/s: 2.3.2
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: jos de witte Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mysql, postgresql
Environment:

Any PostgreSQL environment


Issue Links:
Reference
is referenced by DBAL-96 Make approach towards identifier quot... Open

 Description   

Generation of any SQL command to the database (From entities or migration versions) does not quote all the reserved keywords (For example a fieldname `right`.

Simple fix that always works: double-quote dbname, schemaname and fieldname

e.g "dbsecurity"."userschema"."users" or "tblusers"

MySQL : use the ` sign.

e.g `security`.`users` or `tblusers` (No support for schemas since I last checked some time ago)



 Comments   
Comment by Steve Müller [ 24/Jun/13 ]

If those are reserved keywords, they should be added to the "PostgreSQLKeywords" class and they will be quoted by Doctrine. As far as I can see those keywords mentioned are not present in this class. Maybe there is something missing?





[DBAL-444] OraclePlatform getSequenceNextValSQL not handling case/quoting properly on 11g Created: 10/Feb/13  Updated: 03/Jan/14

Status: In Progress
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.3.2
Fix Version/s: 2.5
Security Level: All

Type: Bug Priority: Major
Reporter: Max Milaney Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: oci8, oracle, sequence
Environment:

PHP version 5.4.11
Oracle 11g Instant Client version 11.2.0.3.0
Oracle Database 11g Enterprise Edition version 11.2.0.3.0 (x64)
OCI8 DBAL driver


Attachments: File example.php    

 Description   

I have an installer script that uses ORM SchemaTool to create the entities in the DB and then populates with basic data using basic EM->persist calls via ORM.

Sequence objects are created, and when using the 10g Instant Client everything worked correctly, however, upon upgrade to latest version of the Instant Client Oracle seems to be expecting consistent case for these schema objects. It appears as if they are being created with a quoted name as they are created in lowercase. OraclePlatform::getSequenceNextValSQL, however, generates "SELECT entity_id_seq.nextval FROM DUAL" and this fails with error "General error: 2289 OCIStmtExecute: ORA-02289: sequence does not exist".

Executing "SELECT "entity_id_seq".nextval FROM DUAL" directly on the DB returns the correct value.

I believe this may also impact the code in http://www.doctrine-project.org/jira/browse/DBAL-278



 Comments   
Comment by Max Milaney [ 10/Mar/13 ]

Hi there,
Wondering if there is any update on this? I'm having to use a workaround in my applications.
Cheers,
Max

Comment by Benjamin Eberlei [ 14/Mar/13 ]

Can you maybe show an entity definition with its sequence mapping?

Comment by Max Milaney [ 17/Mar/13 ]

Here you are mate. Please see attachment.

Comment by Benjamin Eberlei [ 04/Apr/13 ]

I cant seem to find the problem, in DBAL "lib/Doctrine/DBAL/Platforms/OraclePlatform.php" on line 171, the sequence statement is created with $sequence->getQuotedName($platform), but this only works if quoting is requrested for the sequence.

How do you actually create the sequence? Your entity doesnt have @GeneratedValue.

What does the create schema command say with "--dump-sql" flag? Is the SQL quoted?

Comment by Steve Müller [ 03/Jan/14 ]

Max Milaney Can you please test if this still exists in the current master branch? If so, can you please provide the information requested by Benjamin Eberlei ? Otherwise hunting this down is rather hard... Thank you!





[DBAL-357] Missing way to set types for CAST declaration Created: 04/Oct/12  Updated: 04/Oct/12

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.2, 2.3
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Pete Sisson Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

For a query such as

x = CASE WHEN id=$1 THEN CAST($2 AS int)

there doesn't seem to be a way to correctly assign the type across multiple platforms. E.g. Postgres required "int" but mysql just requires "unsigned". Attempting to use "int" here with mysql will fail.

The method Doctrine\DBAL\Platforms method getIntegerTypeDeclarationSQL will return something like "INT unsigned" for sql, which also fails.






[DBAL-96] Make approach towards identifier quoting consistent Created: 26/Feb/11  Updated: 24/Dec/13

Status: Open
Project: Doctrine DBAL
Component/s: Platforms, Schema Managers
Affects Version/s: None
Fix Version/s: 2.5

Type: Improvement Priority: Major
Reporter: Benjamin Eberlei Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None

Issue Links:
Duplicate
is duplicated by DBAL-120 MySql platform getAlterTableSQL does ... Resolved
Reference
relates to DBAL-45 Add CLI tool that checks for Reserved... Resolved
relates to DBAL-477 Just doublequote all schema names and... Open
is referenced by DBAL-40 Transparent table&column names escaping Open

 Description   
  • Make the use of `` a general approach for explicit quoting of identifiers
  • introduce AbstractPlatform::getRegularSQLIdentifierCase($identifier)
  • Introduce AbstractPlatform::isRegularIdentifier($identifier)
  • Fix Schema Assets not to lower-case, but to check for explicit quoting before.
  • Filter values of identifiers passed to all platform functions when they are used in information schema queries according to `` explicit quoting rules.

Problem: Schema is independent of a vendor, this means we have to pick a behavior, i propose SQL-92

This means:

  • strtoupper() ALL tables, column, index, foreign key names that are not quoted by ``
  • For any Quoted identifiers by `` the case is kept.
  • We can introduce a validator to detect a schema that cannot be implemented with a given vendor platform.

In conjunction with the SQL reserved keywords tickets we can then improve the DatabaseDriver considerably to detect identifier casings



 Comments   
Comment by Steve Müller [ 24/Dec/13 ]

Benjamin Eberlei this is an interesting approach and I like it. But I have some complaints about it.
1. I doubt users will be happy about forced default casing rules (ALL upper or ALL lower). Therefore we should think about adding a simple configuration option in DBAL allowing to override the default casing behaviour to the user's preference.
2. Using a consistent default casing means we ALWAYS have to quote identifiers as otherwise the underlying database could silently change the case again (don't know if this is an issue).
3. Introducing this approach in 2.x branch is a BC break as it breaks users' mixed-case identifier mappings.

For 2.x we should maybe at least make use of Identifier class throughout the platforms where necessary.





[DBAL-40] Transparent table&column names escaping Created: 05/Aug/10  Updated: 26/Sep/13

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.3, 2.4, 2.4.1
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Jan Tichý Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 12
Labels: None

Issue Links:
Reference
relates to DBAL-96 Make approach towards identifier quot... Open

 Description   

Hello, I would like to re-open the discussion about automatic transparent escaping of all table/column names sent from DBAL to database. It was already discussed in http://www.doctrine-project.org/jira/browse/DDC-88 without any satisfactory result.

Why do I have to quote any reserved word used in table or column name? Why Doctrine doesn't do this automatically for all table and column
names used in generated SQL queries?

Before you start to explain how complicated it is and what problems you will be faced with, try to look at excellent DIBI database layer - how it acts in this way - it's behaviour is very cool. Unfortunally at the moment the full documentation is in czech only, but here is a brief automatic google-translation to english - http://dibiphp.com/en/quick-start.

My suggestion to Doctrine 2 ORM/DBAL solution is:

1. Developer should never care about any escaping or avoiding any reserved words - it is not his business, the DBAL shoult solve it transparently and safely.

2. So there should be no need and even no possibility to add any quotation chars in @column or @table annotations as well as in DQL queries. ORM layer has nothing to do with escaping, it is all a business of the DBAL layer. Current possibility for manual escaping the names in mentioned annotations is totally wrong and should be discontinued.

3. DBAL should escape ALL table and column names transparently and automatically. There should be ne option to enable or disable the escaping, there is no reason for disabling it.

4. The escaping should be performed just in the final translation of DBAL queries to native SQL query, not earlier. This is the right place to do that.

So what do you think about that?



 Comments   
Comment by Roman S. Borschel [ 05/Aug/10 ]

My point of view (and the reason for the current implementation) is as follows:

  • Using reserved words is bad practice.
  • Quoting everything is like hitting all the SQL with a huge big hammer just to hit the 1% of reserved words (which are again, bad practice), thus overkill.
  • Quoting everything bloats the generated SQL (just to hit the 1% of reserved words which are bad practice to begin with)
  • Quoting everything automatically is like hiding the fact from developers that they use reserved words, thus hiding a bad practice and silently encouraging usage of reserved words in new database schemas. This is not desirable.
  • Quoting reserved words has more effects than simply making the database "accept" that identifier. It affects the case-sensitivity and that in a very inconsistent way across databases and operating systems (See http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html , especially the conclusion). You say there is no reason for disabling it but in fact there are a lot of reasons to do so, so many that it is disabled by default in MDB2 and discouraged to enable it.

So, supporting selective quoting in the name of a (slightly) better interoperability with legacy schemas looked (and still looks) like the best solution for us. The support is limited, explicit, does not require much implementation or overhead and does not unnecessarily bloat the SQL.

There is only one solution for reserved words: not using them. Quoting is a workaround, not a solution and especially not a good one.

ps: I really wish quoting reserved words would not be available in SQL It's not available in most programming languages and noone cares, people just don't use reserved words, because they simply can't.

Comment by Jan Tichý [ 05/Aug/10 ]

Hi Roman, thank you very much for your response! I storngly disagree with most of your points .

There is no doubt that using reserved words is bad practice - FROM THE VIEW OF DATABASE SYSTEM.

But we are discussing about ORM and DBAL. One of the biggest goals of ORM/DBAL is to provide transparent usage of the storage behind the scene. No matter if it is MySQL or PostgreSQL or even maybe something completely diferent.

The ORM/DBAL layer should prevent me from any specifics of particular storage as much as possible. I don't want to remember (and I never should to) that I cannot create entity Order because "order" is reserved word in some weird technology far away from me as ORM programmer.

It is strictly consistent with what you have written above in your PS - "It's not available in most programming languages and noone cares, people just don't use reserved words, because they simply can't" - just consider Doctrine 2 to be another programming language - and there is no real systematic reason in Doctrine 2 itself to prevent developers create entities named "Order".

Here is an analogy - It is the same as if you would say that you cannot use associative arrays in PHP because C-language or Assembler behind PHP doesn't support associative arrays. Yes, they don't support them but it is the responsibility of PHP to provide them. In the same way I don't want to respect this weird limitations of particular RDBMS behind Doctrine 2. This is Doctrine's responsibility to transparently cover the limitation.

Moreover, when list of registered keywords is different from one to the other RDBMS, so the naming of entities is strongly dependent on current database server.

Moreover, when I realize that I have used a registered keyword as lately as an error returns from database engine, not earlier.

I suppose here is probably no risk of SQL injection, but I feel the current Doctrine 2 acting to be "vulnerable" in very similar way, on principle. Simply - you are sending an unescaped piece of SQL query to the database without any warranty what it is. And sometimes it fails, sometimes not. From this view I don't consider overall escaping to be overkill at all, I consider it to be a necessity.

I am strongly convinced that developer working upon DBAL or even ORM layer should never think about such naming limitations and he even shouldn't know anything about reserved words in his particular DBMS.

Now to mentioned problems with case sensitivity. Resulting from the fact that Doctrine 2 entity names are case insensitive I belive that all table definitions and SQL queries comming from Doctrine 2 to database should act as case insensitive too. And that the only practicable way is to normalize (lowercase) all table and column names just on DBAL side before it is passed as SQL query to database.

Jan

Comment by Benjamin Eberlei [ 05/Aug/10 ]

There is actually a very good reason for not quoting. Oracle columns behave differently in their internal structure when escaped.

for example:

/**
  * @column(type="integer")
 */
private $foo;

With quoting it would lead to a column "foo" being lower-cased IN the database and even returned so from resultsets. Without casing it would be a column "FOO". We would essentially need to implement lots of glue code just to get this annoying Oracle feature to work and i think Postgres has the same with lower-cased columns.

Comment by Roman S. Borschel [ 05/Aug/10 ]

@"Hi Roman, thank you very much for your response! I storngly disagree with most of your points"

I guess we can agree to disagree then

@"But we are discussing about ORM and DBAL. One of the biggest goals of ORM/DBAL is to provide transparent usage of the storage behind the scene. No matter if it is MySQL or PostgreSQL or even maybe something completely diferent."

Actually, no, "hiding" the storage completely from the developer is not the goal just as it is not the goal to "hide" SQL. There is an object model on one side and a relational database on the other side. The goal is to provide a mapping between them which is not the same as "hiding" one from the other. In order to create good applications that use ORM technology you need to know both very well, OOP and relational databases. The goal is not to make relational database knowledge "unnecessary". This only results in inefficient use of the databases. The goal is to give people who know both sides equally well a tool to map between the two. Not even "portability" between different relational database vendors is a main goal of an ORM technology, it is just obvious to provide assistance with that as part of the mapping.

@"and there is no real systematic reason in Doctrine 2 itself to prevent developers create entities named "Order".

Noone prevents you from naming domain classes anything you want. Class naming is different from table naming. That the table name defaults to the class name is just that, a default, that can and should be changed if necessary.

@"Moreover, when list of registered keywords is different from one to the other RDBMS, so the naming of entities is strongly dependent on current database server."

Correct, and if you want to create a portable application that works, and will be deployed on, a different set of vendors, you need to have some knowledge of these databases and consider their characteristics. An ORM/DBAL technology does not give you any guarantee for complete and transparent portability between vendors and especially not that it will perform equally well on all of them. The ORM/DBAL technology helps you for the most part in a lot of cases with portability issues but it is no free ticket.

@"I suppose here is probably no risk of SQL injection, but I feel the current Doctrine 2 acting to be "vulnerable" in very similar way, on principle. Simply - you are sending an unescaped piece of SQL query to the database without any warranty what it is. And sometimes it fails, sometimes not. From this view I don't consider overall escaping to be overkill at all, I consider it to be a necessity."

Do not confuse identifier quoting with quoting/escaping of special characters as it is used for security reasons on input. Identifier quoting is absolutely not a necessity, it is a workaround for using otherwise reserved words as schema element names. Speaking of goals, it is neither a "goal" of ORM/DBAL technology to completely remove the possibilities of SQL injections. You can't. It'll always be possible with wrong usage.

@"I am strongly convinced that developer working upon DBAL or even ORM layer should never think about such naming limitations and he even shouldn't know anything about reserved words in his particular DBMS."

And I am strongly convinced that a developer working with a DBAL/ORM should know the underlying databases pretty well.

I think you're really not aware of all the consequences it has across different database vendors to quote every identifier. If not for developers using Doctrine, you cause at least any developer or application pain that does not access the database through Doctrine and is thus feels the full pain of case-sensitivity and mandatory quoting you enforced on the whole schema. Ubiquitious access to the data is actually a strong point of a relational database and it is far from uncommon that the same database is accessed by many parties.

I think the approach taken by DIBI is a bad idea and even worse if there is no way to turn this behavior off. Do they have Oracle or DB2 users? I'm wondering what the sysadmins behind these databases might think if they see this quoting nightmare since to my knowledge this is considered bad practice among them as well.

Yes, we're disagreeing on many points but if you really think identifier quoting is a good idea then you're ignoring a whole lot of prior experience (not only mine).

Comment by Lukas Kahwe [ 05/Aug/10 ]

I was one of the lead developers of MDB2 and we just ran into tons of issues when we overly aggressively did identifier quoting by default. even the option caused lots of headaches. furthermore I agree that the ORM is not about turning an RDBMS into an Object Database, but instead to make a mapping possible. In this vain using reserved words or making all identifiers case sensitive will be a big pain for the people that do work one level lower aka the DBA's. heck even as a developer I frequently work on the DB's command line.

Now as for helping people prevent issues with reserved words. Back then I added some reserved word checking into MDB2_Schema. Obviously its hard to really keep track of all of the different reserved words for all RDBMS. Maybe its possible to work with this guy for this: http://www.petefreitag.com/item/290.cfm This way it could be possible to validate if the names chosen in the models will not cause issues with a certain list of RDBMS.

Comment by Benjamin Eberlei [ 07/Aug/10 ]

Reserved words checking sounds to be a fair compromise!

Comment by Jan Tichý [ 30/Aug/10 ]

Hello, thank you all for your responses.

This helped me understand much about Doctrine 2 basic objectives - especially that it is designed mainly to "make a mapping possible" only, not to be as much as possible transparent layer between database and application. And even if I don't like this conception (because I personally think ORM should provide all such features - like automatic reserved keywords escaping - to make the particular database as transparent as possible), at the same time I fully understand all metioned arguments for doing things in such way. Thank you again.

Comment by Damian Boune [ 17/Jan/11 ]

I would like to state an agreement with the OP.

I understand where there are difficulties in handling reserved words and backtick/quoting, and certainly one should always avoid the use of reserved words in their own schema designs. This is a given when one is able to exert control.

At present I am working on a project in which I am dealing with an outside database where I have no control over the schema, nor am I able to push the remote into making the most sensible changes to their schema. I must live with what they provide.

DBAL presents me with a set of invaluable tools that can not be used as-is, because it lacks the ability to handle quoting when generating schema sql. I'm sure there are some other places where I will find this lacking as well. This is disappointing.

Regardless of what we as developers should do when designing our own schema, we still need to be able to work and play with others who may not follow the same common sense conventions.

Edit:
My temporary quick solution to just "make it work", was to modify AbstractAsset::getQuotedName and force the use of $platform->quoteIdentifier. It did the trick for now until a more suitable solution presents itself.

Comment by Francesco Montefoschi [ 03/Feb/11 ]

"its hard to really keep track of all of the different reserved words for all RDBMS"

That's the main point for me.

Comment by Adrian Rudnik [ 26/Apr/11 ]

@Damian thanks for the hint. I just ran into a similar situation.

Not every project is a startup. I tried to use doctrine2 on a customers database for a small web ui. Well I told them to rename their `iso3166-1` table and `alpha-2` field, then we had a good laugh. We made the mapping possible but i'll remember the one thing i learned: doctrine did not help, guide, prevent or cared at all. It did not even hesitate to spew invalid sql snippets when asked to dump. Its okay for me, but i've expected something more resilient from a DBAL.

Comment by Robert (Jamie) Munro [ 02/Feb/13 ]

What do you mean by "Quoting everything is like hitting all the SQL with a huge big hammer"? Is there a performance hit?

I have always quoted all names when working with PostGres. Not quoting them has always felt like not quoting strings in PHP (e.g. $foo[bar] instead of $foo['bar'] because unless the string is keyword or defined as a constant somewhere, you don't need to (although you will get a "Use of undefined constant" warning). In the early days of PHP, not quoting array keys was common example practise.

Comment by Marco Pivetta [ 02/Feb/13 ]

If you want quoting by default on everything we have a quoting strategy (in ORM) that you can use. I don't think quoting everything by default is a viable solution. Back in `Zend_Db` times this was eating up a lot of performance for no real reason. Users having a clean schema without horrors like columns called `order` or `group` should not be penalized because of users not using valid naming schemes.

Comment by Steve Müller [ 24/Jun/13 ]

Hello, if I understand correctly, the issue of quoting reserved keywords automatically is solved in https://github.com/doctrine/dbal/pull/302. Besides reserved keywords you can still decide quoting or not quoting identifier manually by passing quotes to the identifier or not.

Comment by Arthur Bodera [ 26/Sep/13 ]

It's still broken in 2.4.

PR 302 only selectively fixes indexes, PK and FK, but ALTER and all CRUD will still fail (and schema tool will produce invalid sql).

There is no performance hit, as all operations already hit `DefaultQuoteStrategy`.

Currently you have the following workarounds:

  • selectively add `quoted=true` to table and column names (ugh)
  • replace `DefaultQuoteStrategy` with strategy that quotes all identifiers.

Here is a class you can use: https://gist.github.com/Thinkscape/6713196

Comment by Arthur Bodera [ 26/Sep/13 ]

QuoteStrategies are not used for ALTER queries. This means that using the EagerQuoteStrategy mentioned above won't fix invalid ALTER queries generated by schema tool.

For ALTER to work, we need this merged:

https://github.com/doctrine/dbal/pull/379

Comment by Doctrine Bot [ 26/Sep/13 ]

A related Github Pull-Request [GH-379] was closed:
https://github.com/doctrine/dbal/pull/379





[DBAL-801] add SECOND, MINUTE, WEEK into DATE_SUB, DATE_ADD Created: 04/Feb/14  Updated: 04/Feb/14

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: gondo Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

currently only HOUR, MONTH, YEAR options are implemented
would be nice to have all of them but for now at least the major one would be fine, so to complete the list, i would like to see:
SECOND, MINUTE, WEEK to be implemented

im not sure if all the platforms are capable of this, so if anyone can verify that would be great.
after that, implementation is simple copy/paste of existing code with very minor changes.






[DBAL-422] Wrong VARCHAR default length in SQLServerPlatform Created: 24/Jan/13  Updated: 27/Dec/13

Status: Open
Project: Doctrine DBAL
Component/s: Platforms
Affects Version/s: 2.3.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Minor
Reporter: Steve Müller Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: platform, sqlserver, sqlsrv, varchar


 Description   

In SQLServerPlatform the default length for a VARCHAR declaration is set to "255". But according to the SQLServer documentation from Microsoft the default length is "1", if omitted in the declaration.
See remarks: http://msdn.microsoft.com/en-us/library/ms186939.aspx
Also the default length is hardcoded in the "getVarcharTypeDeclarationSQLSnippet" method which in my opinion should be evaluated through "getVarcharDefaultLength".

I don't exactly know if the current implementation is intended, otherwise it should be fixed. I would then create an PR if desired.



 Comments   
Comment by Steve Müller [ 27/Dec/13 ]

The implementation is inconsistent on other platforms, too and can first be addressed in 3.0 I think. Otherwise this would be a BC break.





[DBAL-858] oracle IN statement with more than 1000 values Created: 11/Jan/13  Updated: 01/Apr/14

Status: Open
Project: Doctrine DBAL
Component/s: Drivers, Platforms
Affects Version/s: 2.2.2
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Minor
Reporter: Marc Drolet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

If I have a query with a IN statement with more tahn 1000 values I get an sql error.

I've try IN with implode:
select * from test where id IN(' . implode(',', $values) . ')
and I've also try with executeQuery:
select * from test where id IN(:test)
executeQuery($sql, array($values), array(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY))



 Comments   
Comment by Marc Drolet [ 11/Jan/13 ]

Here is the way I've implement the solution on my side: (for oracle)

into Doctrine/DBAL/Statement.php, I've add this method:

/**
     * Binds a parameter value to the statement.
     * This is implemented this way for oracle only. Other drivers are redirected to bindValue method.
     *
     * The value will be bound with to the type provided (that required to be a table type).
     *
     * @param String $name The name or position of the parameter.
     * @param Array $value The value of the parameter.
     * @param String $type The name of the type to use to bind.
     * @return boolean TRUE on success, FALSE on failure.
     */
    public function bindList($name, Array $value, $type)
    {
        if ('oracle' !== $this->platform->getName())
        {
            $this->bindValue($name, $value, $type);
        }
        else
        {
            return $this->stmt->bindList($name, $value, $type);
        }
    }

into Doctrine/DBAL/Driver/Statement.php I've add:

/**
     * @TODO: docs
     */
    function bindList($param, Array $values, $type);

into Doctrine/DBAL/Driver/OCI8/OCI8Statement.php I've add this method:

/**
     * {@inheritdoc}
     */
    public function bindList($param, Array $value, $type)
    {
        if (!($list = oci_new_collection($this->_dbh, $type)))
        {
            //throw new OCI8Exception::fromErrorInfo($this->errorInfo());
        }

        foreach ($value as $entry)
        {
            $list->append($entry);
        }
        if (!oci_bind_by_name($this->_sth, $param, $list, -1, OCI_B_NTY))
        {
            //throw new OCI8Exception::fromErrorInfo($this->errorInfo());
        }
    }

// NOTE: we should probably add the bindList to all driver Statement object.

into your code you can use it this way:

$sql = "
    SELECT *
    FROM test
    WHERE id IN
    (
        SELECT *
        FROM
        (
            CAST (: p_ids AS list_int_type)
        )
    )
";
$stmt = connection->prepare($sql);
$stmt->bindList(': p_ids', $ids, 'list_int_type');
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);

NOTE:
list_int_type need to be a valid oracle data type. You can create one with the name you want.
example:
you can have 2 type of accepted array of values: integer and string
let's say we create one for string named: list_str_type and one for integer list_int_type

create or replace type list_str_type as table of varchar2(4000);
create or replace type list_int_type as table of number;

Comment by Benjamin Eberlei [ 01/Apr/13 ]

Hey Marc Drolet

thanks for the feedback and the solution, however i would like to have something generic that is working independent of the database driver. This code is very specific.

Can you point me to some documentation why oci collection works with more than 1000 elements and how it works in PHP?

Comment by Marc Drolet [ 02/Apr/13 ]

Hi Benjamin,

The limitation is not from the oci driver, it's an oracle limitation. There are a couple of possible solution/implementation that can be done but the one I've provide is the one that perform better for the test I've done and from what I can found over the blogs I've read.

I can't find the exact documentation of oracle. oracle doc is so poor.
Here is the best description link I can provide that describe some possible implementation.
http://vsadilovskiy.wordpress.com/substituting-a-collection-for-in-list-performance-study/

I don't know if there is similar limitation with other database. With the implementation I've provided, It will be possible to implement the proper solution depending on the database limitation you face otherwise it will execute the generic IN. What's bad, we need to create the type into the database.

NOTE: In my case, I can not perform a sub-query, I get the my collection from a web service call.





[DBAL-175] Table comments in Doctrine\DBAL\Schema\Table Object Created: 06/Oct/11  Updated: 17/Oct/11

Status: Open
Project: Doctrine DBAL
Component/s: Platforms, Schema Managers
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Minor
Reporter: Asmir Mustafic Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Should be useful discover the table comments from database schema.

This feature is already available for column comments, but not for table comments






[DBAL-167] Schema comparator doesn't work properly with columnDefinition's Created: 17/Sep/11  Updated: 16/Jul/12

Status: Open
Project: Doctrine DBAL
Component/s: Drivers, Platforms, Schema Managers
Affects Version/s: 2.0.8, 2.1, 2.1.1, 2.1.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Minor
Reporter: Dmitry Strygin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None


 Description   

Schema comparator will mostly always return changed properties on columns for entities defined with columnDefinition even they are identical in the DB. This is due to weak low-lever compatibility of SchemaTool#getCreateSchemaSql() and SchemaTool#getSchemaFromMetadata() – the first one doesn't reconstruct columnDefinition, and the other one never supports 'fixed', 'default', cannot determine, whether it is boolean or integer (ex. TINYINT in the DB), etc...

All this results in extremely annoying unnecessary alter-table-change-columns surrounded by dropping and after that re-enabling constrains dependent on those columns.

I mean stuff like this:

symfony2#app/console doctrine:schema:update --dump-sql
...
ALTER TABLE es_hotels DROP FOREIGN KEY FK_527F88EE584598A3F92F3E70;
ALTER TABLE es_hotels DROP FOREIGN KEY FK_527F88EE584598A37A3ABE5D;
ALTER TABLE es_hotels DROP FOREIGN KEY FK_527F88EE584598A3EE551564;
ALTER TABLE es_hotels CHANGE is_active is_active TINYINT(1) NOT NULL DEFAULT '1', CHANGE checksum checksum CHAR(32) DEFAULT NULL;
ALTER TABLE es_hotels ADD CONSTRAINT FK_527F88EE584598A3F92F3E70 FOREIGN KEY (operator_id, country_id) REFERENCES es_countries(operator_id, id) ON DELETE CASCADE;
ALTER TABLE es_hotels ADD CONSTRAINT FK_527F88EE584598A37A3ABE5D FOREIGN KEY (operator_id, resort_id) REFERENCES es_resorts(operator_id, id) ON DELETE CASCADE;
ALTER TABLE es_hotels ADD CONSTRAINT FK_527F88EE584598A3EE551564 FOREIGN KEY (operator_id, subresort_id) REFERENCES es_subresorts(operator_id, id) ON DELETE CASCADE;
...

The simple solution would be to fix schema comparator not to signal any changes on columns with columnDefinition properties.
But would be much and much better to add some code to all *SchemaManager#getPortableTableColumnDefinition so they would reconstuct columnDefinition and they would be matched in the schema comparator.

I can do this



 Comments   
Comment by Roderick Schaefer | We handle IT [ 16/Oct/11 ]

I'm having the same issue on my production webserver, but not on the development webserver. I find that odd. It tries to drop all foreign keys and create them again, although without the CHANGE statement you are referring to, Dmitry.

Comment by Benjamin Eberlei [ 09/Jan/12 ]

This maybe fixable by making a hash out of the column definition and saving it into a database comment.

The Foreign Key problem maybe because of an old MySQL version 5.0.x

Comment by Joe Cai [ 16/Jul/12 ]

@beberlei, sounds good to me. any plan of implementing this?





Generated at Mon Apr 21 07:28:38 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.