2

I have a app perpetuating data in Postgresql/Express/Knex/Objection. I am looking for. way t track changes in my models, so that I can manage and revert versions similar to paper_trail in rails or this port for sequelize: https://github.com/nielsgl/sequelize-paper-trail

Is there something I could use for this in Knex/Objection or at the db level to track changes

Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70
user2799827
  • 1,077
  • 3
  • 18
  • 54
  • Are you using version control (Eg: Git?)? Have you tried tracking with `knex_migrations` table in your Postgres db? It's the table Knex uses to track migrations. – technogeek1995 Apr 17 '20 at 17:42
  • I am using git, but I am not talking about version control in code. I am trying to track changes in individual records within the models. e.g if i changed the title of a document, then I would now I have 2 versions of that document in the db. Then I go back and change the body of the document 2 days later, no I have 3 versions. I want to generate a changeset, such that I can see what edits were made at each stage and potentially revert to a previous version. – user2799827 Apr 18 '20 at 02:01
  • I'm not aware of this functionality out of the box with Knex/Objection. However, you should be able to implement what you're looking for by using Objection's Model's static methods [docs](https://vincit.github.io/objection.js/api/model/static-methods.html). You can subscribe to a given update/create query to automatically edit a document version column on the model (and thus stored in the database). Is that helpful? – technogeek1995 Apr 18 '20 at 02:29
  • Yes, thanks, I'll check out Objection's docs. – user2799827 Apr 18 '20 at 07:50
  • After i saw your comment, Yes, you can use ```triggers``` to trigger! an action when a record changes or etc. But it seems more like ```database journaling``` what is you talk about, hmmm. – Vahid Alimohamadi Apr 19 '20 at 13:08

1 Answers1

1

Answer: There is not any generic way to do it in Objection nor knex.

Random rambling:

You need to design what kind of changes you like to track and write some code for example to Model hooks in objection how to track the changes.

One way to implement it would be for example by adding a separate table where all the tracked changes are written for example in JSONB object where updated fields or old values are stored and indexed or something like that. I'm pretty sure you don't want to add tracking of all the data in the database, since it will blow up the DB size very fast.

Anyways implementation depends what it is actually why you like or need to track the data and what are actual use cases that you need to support.

Also this might work for you: https://wiki.postgresql.org/wiki/Audit_trigger

Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70