Objection.js: Updating array properties result in malformed query when jsonSchema is present

Created on 14 Dec 2015  路  2Comments  路  Source: Vincit/objection.js

When an array type is defined for a property in the jsonSchema an update results in a malformed query.

Running the following

class Movie extends Model {

  static get tableName() {
    return 'movie';
  }

  static get jsonSchema() {
    return {
      type: 'object',
      properties: {
        tags: {type: 'array'}
      }
    }
  }
}
    Movie.query().patch({'tags': ['test']}).where('id', 1);

results in:

{ [error: update "movie" set "tags" = $1 where "id" = $2 - malformed array literal: "["test"]"]
  name: 'error',
  length: 144,
  severity: 'ERROR',
  code: '22P02',
  detail: '"[" must introduce explicitly-specified array dimensions.',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'arrayfuncs.c',
  line: '242',
  routine: 'array_in' }

  error: update "movie" set "tags" = $1 where "id" = $2 - malformed array literal: "["test"]"
      at Connection.parseE (/.../node_modules/pg/lib/connection.js:539:11)
      at Connection.parseMessage (/.../node_modules/pg/lib/connection.js:366:17)
      at Socket.<anonymous> (/.../node_modules/pg/lib/connection.js:105:22)
      at emitOne (events.js:77:13)
      at Socket.emit (events.js:169:7)
      at readableAddChunk (_stream_readable.js:146:16)
      at Socket.Readable.push (_stream_readable.js:110:10)
      at TCP.onread (net.js:523:20)


Without the jsonSchema the query works as expected, I am assuming some sort of transformation or escaping happens that turns ["test"] into "["test"]" due to it being an array.

Leaving objection out completely and running the update via knex works as expected as well.

Most helpful comment

So the type of the tags column is a postgres array and _not_ json/jsonb? Objection maps object and array properties into strings so that they can be stored into json/jsonb columns. You can override the properties that are mapped by setting the jsonAttributes property of the model. So in your case you will probably want to set an empty array to signal that no properties should be mapped into JSON strings:

static get jsonAttributes() {
  return [];
}

All 2 comments

So the type of the tags column is a postgres array and _not_ json/jsonb? Objection maps object and array properties into strings so that they can be stored into json/jsonb columns. You can override the properties that are mapped by setting the jsonAttributes property of the model. So in your case you will probably want to set an empty array to signal that no properties should be mapped into JSON strings:

static get jsonAttributes() {
  return [];
}

Ah, wasn't aware of that, thank you

Was this page helpful?
0 / 5 - 0 ratings