Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Postgres JSON type doesn't like buffer values #600

Open
twolfson opened this issue Jan 9, 2015 · 1 comment
Open

Postgres JSON type doesn't like buffer values #600

twolfson opened this issue Jan 9, 2015 · 1 comment

Comments

@twolfson
Copy link

twolfson commented Jan 9, 2015

I am trying to get orm setup on an existing database that leverages JSON columns. It looks like the object type is saving to hexadecimal values. However, Postgres 9.3 doesn't like this. Can we remove this buffer escaping (prob not since we have #378) or add a new type called json which doesn't encode into hex (a la #381)?

$ createdb buffer-test
$ psql buffer-test 
psql (9.3.5)
Type "help" for help.

buffer-test=# CREATE TABLE items (item json);
CREATE TABLE
buffer-test=# INSERT INTO items (item) VALUES ('{}');
INSERT 0 1
buffer-test=# INSERT INTO items (item) VALUES ('\x7b7d');
ERROR:  invalid input syntax for type json
LINE 1: INSERT INTO items (item) VALUES ('\x7b7d');
                                         ^
DETAIL:  Token "\" is invalid.
CONTEXT:  JSON data, line 1: \...
@twolfson
Copy link
Author

twolfson commented Jan 9, 2015

I have added the datatype via defineType and it looks like it's working great:

// Add in the JSON data type (`object` works with binary/string columns)
// https://github.com/dresende/node-orm2/wiki/Model-Properties#custom-types
db.defineType('json', {
  datastoreType: function (prop) {
    return 'JSON';
  },

  // https://github.com/dresende/node-orm2/blob/v2.1.20/lib/Drivers/DML/postgres.js#L247-L256
  valueToProperty: function (value, prop) {
    if (typeof value !== 'object') {
      try {
        value = JSON.parse(value);
      } catch (err) {
        value = null;
      }
    }
    return value;
  },

  // https://github.com/dresende/node-orm2/blob/v2.1.20/lib/Drivers/DML/postgres.js#L317-L321
  propertyToValue: function (value, prop) {
    if (value !== null) {
      value = JSON.stringify(value);
    }
    return value;
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant