Objection.js: Patch updates all columns in Typescript model that have a default parameter

Created on 26 Jun 2020  路  2Comments  路  Source: Vincit/objection.js

Problem

Patch is including more parameters in the SQL query than expected. I've isolated this down to happening on any Typescript model that has some parameters that have defaults. It appears that any parameters in a Typescript class that have default are automatically included.

Reproduction

Running the following on a Typescript model with defaults returns the provided response on a fresh project. Full reproduction code included below as well.

await Person.query()
        .where('id', 1)
        .patch({ first_name: 'Peter' })
        .debug()

`` { method: 'update', options: {}, timeout: false, cancelOnTimeout: false, bindings: [ true, false, 'Peter', 1 ], __knexQueryUid: '5e1ca920-b7bd-11ea-b4aa-53a8c3a6c359', sql: 'updatepersonssetis_tall= ?,has_family= ?,name= ? whereid` = ?' }

This issue appears to be related but never provided code to reproduce:
https://github.com/Vincit/objection.js/issues/1742


Full reproduction:
```typescript
import { Model } from 'objection'
const knex = require('knex')({
    client: 'mysql2',
    connection: { ... }
})
Model.knex(knex)


class Person extends Model {

    id: number
    first_name: string
    is_tall = true
    has_family = false

    static tableName = 'persons'
}

async function createSchema() {
    await knex.schema.dropTableIfExists('persons')

    await knex.schema
      .createTable('persons', table => {
        table.increments('id').primary()
        table.string('first_name')
        table.boolean('is_tall')
        table.boolean('has_family')
      })
}

async function main() {
    await createSchema()

    await Person.query()
        .where('id', 1)
        .patch({ first_name: 'Peter' })
        .debug()
}

main()
  .then(() => {
    console.log('success')
    return knex.destroy()
  })
  .catch(err => {
    console.error(err)
    return knex.destroy()
  })

Most helpful comment

This is a little confusing, and should definitely be mentioned in a documentation.

All 2 comments

Yep, that's by design. Don't use default values.

This is a little confusing, and should definitely be mentioned in a documentation.

Was this page helpful?
0 / 5 - 0 ratings