dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

Datetime fields are returned as strings in MySQL #644

Open dialupnoises opened 9 years ago

dialupnoises commented 9 years ago

I'm using node-orm2 version 2.1.24 with MariaDB 10.0.10 and node 0.10.26 on Windows 8.1 64-bit. I'm using the MySQL driver with node-mysql at 2.7.0, since MariaDB is compatible with MySQL. I've created a model that includes a date property with time: true specified:

var Media = db.define('media', {
        ....
    last_updated: {type: 'date', time: true}
        ....
});

(There are more properties where I put the ellipsis, but I don't think they're relevant.)

I fetch all rows using Media.all. When I access the last_updated fields of the returned rows, it's a string like: 0000-00-00 00:00:00

For now I'm using a custom type:

function pad(n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

db.defineType('datetime', {
    datastoreType: function(prop) { return 'DATETIME'; },
    valueToProperty: function(value, prop) {
        if(value instanceof Date)
            return value;
        else
        {
            var matchResult = /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/.exec(value);
            if(!matchResult)
                return null;
            return new Date(
                parseInt(matchResult[1], 10),
                parseInt(matchResult[2], 10),
                parseInt(matchResult[3], 10),
                parseInt(matchResult[4], 10),
                parseInt(matchResult[5], 10),
                parseInt(matchResult[6], 10),
                0
            );
        }
    },
    propertyToValue: function(value, prop) {
        if(!value)
            return null;
        return (
            pad(value.getFullYear(), 4) + '-' +
            pad(value.getMonth() + 1, 2) + '-' +
            pad(value.getDate(), 2) + ' ' +
            pad(value.getHours(), 2) + ':' +
            pad(value.getMinutes(), 2) + ':' +
            pad(value.getSeconds(), 2)).toString();
    }
});
dxg commented 9 years ago

Curious. Could you create a PR with a failing test case? I'm wondering if this is standard behaviour for all drivers or only mysql.