Skip to content

API incompatibility regarding DECIMAL values #237

Closed

Description

@selaux

DECIMAL values are returned differently in node-mysql and node-mysql2. In node-mysql they are returned as type Number while in node-mysql2 they are returned as type String, which seems wrong to me.

Minimal test case:

var mysql = require('mysql'),
    mysql2 = require('mysql2'),
    connection;

connection = mysql.createConnection(JSON.parse(process.env.MYSQL_CONFIG));
connection2 = mysql2.createConnection(JSON.parse(process.env.MYSQL_CONFIG));

connection.query('CREATE TABLE decimal_table (d DECIMAL(4,2))', function() {
  connection.query('INSERT INTO decimal_table VALUES (0.1)', function() {
    var query = connection.query('SELECT * FROM decimal_table LIMIT 1');
    var query2 = connection2.query('SELECT * FROM decimal_table LIMIT 1');

    query.on('result', function(r) {
      console.log('node-mysql', r.d, typeof r.d);
      connection.end();
    });
    query2.on('result', function(r) {
      console.log('node-mysql2', r.d, typeof r.d);
      connection2.end();
    });
  });
});

On my machine (OS X, MySQL 5.7) this prints:

node-mysql2 0.10 string
node-mysql 0.1 number

Activity

  1. sidorares commented on Dec 15, 2015

    @sidorares
    Owner

    hi, this is intended ( but I'm open for discussion if that should be that way )

    DECIMAL values are stored and transmitted as strings, and often used where exact precision is required ( accounting etc ), so I assume in that case some precision arithmetic library would be used ( Bignumber, bn.js etc ) and data would be passed as string to that library

    Is this incompatibility causing any particular problems in your code?

  2. added
    mysqljs/mysql incompatibilities
    on Dec 15, 2015
  3. mlarcher commented on Sep 24, 2016

    @mlarcher

    Is there way to apply the same library transformation to all decimal fields before they reach the consuming code ?

  4. sushantdhiman commented on Sep 24, 2016

    @sushantdhiman
    Collaborator

    You can use typeCast option as used in test here

  5. mlarcher commented on Sep 24, 2016

    @mlarcher

    thanks, looks like precisely what we need :)

  6. jaredjenkins commented on Mar 31, 2017

    @jaredjenkins

    Related issue for Sequelize: sequelize/sequelize#7465

  7. sidorares commented on Mar 31, 2017

    @sidorares
    Owner

    @jaredjenkins if absolutely critical we could have decimalAsNumber flag to force conversion to number (at a cost of losing precision), but I'd rather avoid adding more flags

  8. jaredjenkins commented on Mar 31, 2017

    @jaredjenkins
  9. sidorares commented on Mar 31, 2017

    @sidorares
    Owner

    To me Decimal is very special, I'd suggest to update schema to use floats or ints depending on semantic if no real need for DECIMAL type

    I'm assuming this isn't the behavior for double or float?

    normal int/float types returned as JS Number

    return 'packet.parseLengthCodedIntNoBigCheck()';

    floats:

    Packet.prototype.parseFloat = function (len) {
    if (len === null) {
    return null;
    }
    var result = 0;
    var end = this.offset + len;
    var factor = 1;
    var pastDot = false;
    var charCode = 0;
    if (len === 0) {
    return 0; // TODO: assert? exception?
    }
    if (this.buffer[this.offset] == minus) {
    this.offset++;
    factor = -1;
    }
    if (this.buffer[this.offset] == plus) {
    this.offset++; // just ignore
    }
    while (this.offset < end) {
    charCode = this.buffer[this.offset];
    if (charCode == dot) {
    pastDot = true;
    this.offset++;
    } else if (charCode == exponent || charCode == exponentCapital) {
    this.offset++;
    var exponentValue = this.parseInt(end - this.offset);
    return (result / factor) * Math.pow(10, exponentValue);
    } else {
    result *= 10;
    result += this.buffer[this.offset] - 48;
    this.offset++;
    if (pastDot) {
    factor = factor * 10;
    }
    }
    }
    return result / factor;
    };

    ints:

    // The whole reason parse* function below exist
    // is because String creation is relatively expensive (at least with V8), and if we have
    // a buffer with "12345" content ideally we would like to bypass intermediate
    // "12345" string creation and directly build 12345 number out of
    // <Buffer 31 32 33 34 35> data.
    // In my benchmarks the difference is ~25M 8-digit numbers per second vs
    // 4.5 M using Number(packet.readLengthCodedString())
    // not used when size is close to max precision as series of *10 accumulate error
    // and approximate result mihgt be diffreent from (approximate as well) Number(bigNumStringValue))
    // In the futire node version if speed difference is smaller parse* functions might be removed
    // don't consider them as Packet public API
    var minus = '-'.charCodeAt(0);
    var plus = '+'.charCodeAt(0);
    Packet.prototype.parseInt = function (len, supportBigNumbers) {
    if (len === null) {
    return null;
    }
    if (len >= 14 && !supportBigNumbers) {
    var s = this.buffer.toString('ascii', this.offset, this.offset + len);
    this.offset += len;
    return Number(s);
    }
    var result = 0;
    var start = this.offset;
    var end = this.offset + len;
    var sign = 1;
    if (len === 0) {
    return 0; // TODO: assert? exception?
    }
    if (this.buffer[this.offset] == minus) {
    this.offset++;
    sign = -1;
    }
    // max precise int is 9007199254740992
    var str;
    var numDigits = end - this.offset;
    if (supportBigNumbers) {
    if (numDigits >= 15) {
    str = this.readString(end - this.offset, 'binary');
    result = parseInt(str, 10);
    if (result.toString() == str) {
    return sign * result;
    } else {
    return sign == -1 ? '-' + str : str;
    }
    } else if (numDigits > 16) {
    str = this.readString(end - this.offset);
    return sign == -1 ? '-' + str : str;
    }
    }
    if (this.buffer[this.offset] == plus) {
    this.offset++; // just ignore
    }
    while (this.offset < end) {
    result *= 10;
    result += this.buffer[this.offset] - 48;
    this.offset++;
    }
    var num = result * sign;
    if (!supportBigNumbers) {
    return num;
    }
    str = this.buffer.toString('ascii', start, end);
    if (num.toString() == str) {
    return num;
    } else {
    return str;
    }
    };
    // note that if value of inputNumberAsString is bigger than MAX_SAFE_INTEGER
    // ( or smaller than MIN_SAFE_INTEGER ) the parseIntNoBigCheck result might be
    // different from what you would get from Number(inputNumberAsString)
    // String(parseIntNoBigCheck) <> String(Number(inputNumberAsString)) <> inputNumberAsString
    Packet.prototype.parseIntNoBigCheck = function (len) {
    if (len === null) {
    return null;
    }
    var result = 0;
    var end = this.offset + len;
    var sign = 1;
    if (len === 0) {
    return 0; // TODO: assert? exception?
    }
    if (this.buffer[this.offset] == minus) {
    this.offset++;
    sign = -1;
    }
    if (this.buffer[this.offset] == plus) {
    this.offset++; // just ignore
    }
    while (this.offset < end) {
    result *= 10;
    result += this.buffer[this.offset] - 48;
    this.offset++;
    }
    return result * sign;
    };

  10. jaredjenkins commented on Mar 31, 2017

    @jaredjenkins

    Understood - I think we can comfortably move to a Float, but this is a breaking change from mysql -> mysql2 and Sequelize >= v4 won't work properly because of it. I am working on a PR with Sequelize. Can probably figure out how to make this configurable on their end.

  11. jaredjenkins commented on Mar 31, 2017

    @jaredjenkins

    So I take that back - we definitely want DECIMAL, but still think this is fine for the client (Sequelize) to resolve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    mysqljs/mysql incompatibilities

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions