cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Phalcon\Mvc\Model attributes don't have any type

Open ogarbe opened this issue 13 years ago • 17 comments

Hi,

every data which comes from a DB in the model is typed as string which is (from my point of view) a bad behavior, even if php is not strictly typed.

Here is a changed i've done on the model due to this behavior, but i think typing data directly in the model should be done directly.

use Phalcon\Db\Column as Column;

abstract class Model extends \Phalcon\Mvc\Model
{
    public function toArray()
    {
        $array = parent::toArray();
        $metadata = $this->getDI()->get('modelsMetadata');
        $types = $metadata->getDataTypes($this);
        foreach ($types as $attribute => $type) {
            if (!is_null($array[$attribute])) {
                switch ($type) {
                    case Column::TYPE_INTEGER:
                        $array[$attribute] = (int) $array[$attribute];
                    break;
                    case Column::TYPE_DECIMAL:
                    case Column::TYPE_FLOAT:
                        $array[$attribute] = (float) $array[$attribute];
                    break;
                    case Column::TYPE_BOOLEAN:
                        $array[$attribute] = (bool) $array[$attribute];
                    break;
                }
            }
        }
        return $array;
    }
}

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

ogarbe avatar Oct 24 '13 20:10 ogarbe

This looks great but however there is one major drawback: not all types can be represented in PHP:

For example, 32 bit PHP will be unable to represent BIGINT as integer (the value will be (mod 2^32)), 64 bit PHP will be unable to represent BIGINT UNSIGNED. DECIMAL/NUMERIC types will probably lose their precision (ie, 1.01 in DECIMAL(1,2) will actually be 1.0099999997765 when cast to float).

This is the main reason why PDO returns all types as strings.

ghost avatar Oct 25 '13 11:10 ghost

Yes, but for int it's really better to have this and it's really more quick on mysql for example.

ogarbe avatar Oct 25 '13 14:10 ogarbe

Concerning decimal, my version is not really good, we should do a round(lenght,decimal) after

ogarbe avatar Oct 25 '13 14:10 ogarbe

Concerning decimal, my version is not really good, we should do a round(lenght,decimal) after

That won't work either :-) DECIMAL/NUMERIC types are used when you need to make sure you won't be affected by rounding errors because the decimal part often cannot be represented as the sum of negative powers of two — for example, when you have to deal with currency types (rounding errors = lost money) and that's why decimal types are represented (internally in DBMSes) either as strings or as two integers (MySQL does this).

I think that this code should probably go to the Incubator because it is too difficult to implement it properly in the core (and this implementation will affect all users of Phalcon).

@phalcon need your opinion.

ghost avatar Oct 26 '13 07:10 ghost

ok for datas which are not PK or FK, but for those, using string instead of int is a major drawback concerning performance, which is Phalcon main point.

At least, i'd like integer PK / FK to be represented as integers and used as integers in SQL requests.

ogarbe avatar Oct 28 '13 11:10 ogarbe

But why don't you pass PDO::PARAM_INT when binding such data? PDO internally handles everything as strings (that's why you see strings in the result sets even for numeric columns) and will use strings for integers unless the bind type is specified explicitly. Moreover, DBMS may also return data sets as strings (MySQL does this for example).

using string instead of int is a major drawback concerning performance

Mmm, where does this concern performance? As far as I can tell, Phalcon does no explicit data type conversion and what you see in the result set is what PDO driver returned.

ghost avatar Oct 28 '13 12:10 ghost

this concern performance in sql, doing a update

where id='134'

is really less quick than

where id=134

I could pass PDO::PARAM_INT when binding data, but if y use an ORM, it's because i don't want to do this kind of things otherwise i would use plain sql doing my own request myself... Why don't the ORM does this automatically ?

ogarbe avatar Oct 28 '13 13:10 ogarbe

Currently the ORM does pass any parameter using bound parameters so you would not see:

where id='134'
where id=134 //or this

but this:

where id = ?

ghost avatar Oct 30 '13 05:10 ghost

thanks @phalcon for your answer, but how this is passed to PDO after that ? do you bind "id" with PDO::PARAM_INT or you don't ? If not, that's the pb i'm talking about, don't do this will decrease perf on mysql / every other db due to string to int conversion in the Db engine.

ogarbe avatar Nov 04 '13 10:11 ogarbe

Yes, it automatically use PDO::PARAM_INT for integer columns.

You could implement something like this to see how parameters are passed to PDO:

http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements

ghost avatar Dec 19 '13 17:12 ghost

This issue is still present in 1.3.0. In my case it presents problems with loading model data into AngularJS app from a Phalcon backend via JSON, because all the numbers are returned as strings and are ignored as invalid for numeric input controls. The solution in the first post appears to work, however it does not get called when toArray() is called on a ResultSet.

integry avatar Mar 26 '14 10:03 integry

This is implemented in Phalcon 2.0.4:

<?php

namespace Some;

use Phalcon\DI,
    Phalcon\Db\Column,
    Phalcon\Mvc\Model,
    Phalcon\Events\Manager as EventsManager,
    Phalcon\Db\Adapter\Pdo\MySQL as Connection,
    Phalcon\Mvc\Model\Manager as ModelsManager,
    Phalcon\Mvc\Model\Metadata\Memory as ModelsMetaData;

$eventsManager = new EventsManager();

$di = new DI();

Model::setUp(["castOnHydrate" => true]);

$connection = new Connection(array(
    "host"          => "localhost",
    "username"      => "root",
    "password"      => "",
    "dbname"        => "phalcon_test",
));

$connection->setEventsManager($eventsManager);

$eventsManager->attach('db',
    function ($event, $connection) {
        switch ($event->getType()) {
            case 'beforeQuery':
                echo $connection->getSqlStatement(), "\n";
                print_r($connection->getSqlVariables());
                print_r($connection->getSqlBindTypes());
                break;
        }
    }
);

$modelsManager = new ModelsManager();
$modelsManager->setDi($di);

$modelsManager->registerNamespaceAlias('s', 'Some');

$di['db'] = $connection;
$di['modelsManager'] = $modelsManager;
$di['modelsMetadata'] = new ModelsMetadata();

class Robots extends Model
{-
}

$robots = $modelsManager->executeQuery(
    "SELECT * FROM [Some\Robots]"
);

foreach ($robots as $robot) {
    echo gettype($robot->code), PHP_EOL;
}

Outputs:

SELECT IF(COUNT(*) > 0, 1, 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME` = 'robots' AND `TABLE_SCHEMA` = DATABASE()
DESCRIBE `robots`
SELECT `robots`.`id`, `robots`.`name`, `robots`.`type`, `robots`.`year` FROM `robots`
Array
(
)
integer
integer
integer

andresgutierrez avatar Jun 19 '15 19:06 andresgutierrez

@andresgutierrez it seems there is a problem with findfirst and this new feature

I've tested the new version and this findfirst method doesn't work anymore :

$param = [
  'conditions' => "id_ville = ?0"
  'bind' => [10666]
  'cache' => [
    'key' => "akey"
   ]
];
$res = City::findFirst($param);

with phalcon.orm.cast_on_hydrate set to 0 => ok with phalcon.orm.cast_on_hydrate set to 1 => "ErrorException: Illegal offset type"

ogarbe avatar Jun 20 '15 09:06 ogarbe

same pb with this params

array(3) { 'conditions' => string(21) "id_ville = :id_ville:" 'bind' => array(1) { 'id_ville' => int(10666) } 'cache' => array(1) { 'key' => string(92) "Frontvpg\Models\Common\City-{"conditions":"id_ville = :id_ville:","bind":{"id_ville":10666}}" } }

ogarbe avatar Jun 20 '15 10:06 ogarbe

@ogarbe It's working fine to me, maybe you have to purge your cache?

<?php

namespace Some;

use Phalcon\DI,
    Phalcon\Db\Column,
    Phalcon\Db\RawValue,
    Phalcon\Mvc\Model,
    Phalcon\Events\Manager as EventsManager,
    Phalcon\Db\Dialect\MySQL as SqlDialect,
    Phalcon\Db\Adapter\Pdo\MySQL as Connection,
    Phalcon\Mvc\Model\Manager as ModelsManager,
    Phalcon\Mvc\Model\Metadata\Memory as ModelsMetaData,
    Phalcon\Cache\Backend\File as FilesCache,
    Phalcon\Cache\Frontend\Data as FrontendCache;

$eventsManager = new EventsManager();

$di = new DI();

$connection = new Connection(array(
    "host"     => "localhost",
    "username" => "root",
    "password" => "",
    "dbname"   => "phalcon_test",
));

$connection->setEventsManager($eventsManager);

$eventsManager->attach('db',
    function ($event, $connection) {
        switch ($event->getType()) {
            case 'beforeQuery':
                echo $connection->getSqlStatement(), "\n";
                print_r($connection->getSqlVariables());
                print_r($connection->getSqlBindTypes());
                break;
        }
    }
);

$modelsManager = new ModelsManager();
$modelsManager->setDi($di);
$di['db'] = $connection;
$di['modelsManager'] = $modelsManager;
$di['modelsMetadata'] = new ModelsMetadata();
$di['modelsCache'] = new FilesCache(
    new FrontendCache(array(
        "lifetime" => 86400
    )),
    ['cacheDir' => './']
);

Model::setup(['castOnHydrate' => true]);

class Robots extends Model
{

}

$param = [
  'conditions' => "id = ?0",
  'bind' => [1],
  'cache' => [
    'key' => "akey"
   ]
];
$robot = Robots::findFirst($param);

echo gettype($robot->id), PHP_EOL;

$robot = Robots::findFirst($param); // from the cache
echo gettype($robot->id), PHP_EOL;
SELECT IF(COUNT(*) > 0, 1, 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME` = 'robots' AND `TABLE_SCHEMA` = DATABASE()
DESCRIBE `robots`
SELECT `robots`.`id`, `robots`.`name`, `robots`.`type`, `robots`.`year`, `robots`.`datetime`, `robots`.`text` FROM `robots` WHERE `robots`.`id` = :0 LIMIT :AP0
Array
(
    [AP0] => 1
    [:0] => 1
)
Array
(
    [AP0] => 1
)
integer
integer

andresgutierrez avatar Jun 20 '15 15:06 andresgutierrez

@andresgutierrez - It's not an error, it's a notice :

please add this in your code

        set_error_handler(
            function ($errno, $errstr, $errfile, $errline) {
                throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
            },
            E_ALL
        );

ogarbe avatar Jun 22 '15 07:06 ogarbe

@andresgutierrez Just had time to dig more on this pb : the exception is raised here

https://github.com/phalcon/cphalcon/blob/c96782766cfe5852acb821af944140379125c1cb/phalcon/mvc/model.zep#L3530

attribute is not a string, it's an array containing two values which seems to be column name and column position

same pb here : https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model/resultset/simple.zep#L201

ogarbe avatar Jun 30 '15 09:06 ogarbe