cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Database query result keys are lowercase

Open roman-kulish opened this issue 13 years ago • 5 comments

The following ...

$db = new Phalcon\Db\Adapter\Pdo\Mysql(array(
    'username' => '*************',
    'password' => '*************',
    'dbname'   => '*************'
));

$result = $db->fetchOne('SELECT url_id AS ID, url AS LongURL FROM short_url', \Phalcon\Db::FETCH_ASSOC);
var_export($result);

... is expected to return

array(
    'ID' => '1',
    'LongUrl' => 'http://some/url'
)

At some stage keys are converted to lowercase and so actual result becomes ...

array(
    'id' => '1',
    'longurl' => 'http://some/url'
)

roman-kulish avatar Jan 26 '13 16:01 roman-kulish

This is not a bug, the database layer automatically sets the PDO option to PDO_CASE_LOWER to provide an unified way of returning the fields across different database systems.

You can set your own return case in this way:

$db->getInternalHandler()->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);

ghost avatar Jan 27 '13 01:01 ghost

Then it should be highlighted in documentation and/or API Docs. The following behaviour is not expected and may be harmful in the following cases:

  • When integrating with 3rd party apps which use StudlyCaps or camelCase for naming tables and / or columns
  • When using StudlyCaps or camelCase named class properties in ORM models

provide an unified way of returning the fields across different database systems

Honestly, do you jump between MySQL, Sqlite and PostgreSQL databases often? Normally people choose storage and they stick to it and switching to another storage requires more work than just changing the driver: fixing storage specific SQL language constraints, rewriting queries, removing or converting storage specific SQL extensions.

It may be TRUE only for ORM.

roman-kulish avatar Jan 28 '13 03:01 roman-kulish

One of the features than is expected in a ORM is that you can use multiple databases without change your code.

You can implement a column map to rename the columns and use the naming conventions you want: http://docs.phalconphp.com/en/latest/reference/models.html#independent-column-mapping

ghost avatar Jan 28 '13 09:01 ghost

I agree and I am not pushing you into changing the way it works. I am trying to make you consider that if ORM needs case folding it should happen in ORM only. Otherwise it becomes an unexpected behavior.

roman-kulish avatar Jan 28 '13 10:01 roman-kulish

You can set the column case with $db->getInternalHandler()->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); if you need to use the same column names case used in the database as I mentioned before. I going to add that in the docs.

ghost avatar Jan 29 '13 07:01 ghost