How to update read model in CQRS pattern on schema change of write model database?

1.1k Views Asked by At

While using CQRS pattern with domain events to generate read model.

If we add new column in database with some default data or insert new row directly from sql query manually, in that case no events are generated so how to update the existing generated read model ?

2

There are 2 best solutions below

0
On BEST ANSWER

as their name says, domain events are something that represent a thing happened in your domain, and a good practice is to raise them as near as possible to the aggregate related to them. Actually, you should record those events inside the aggregate itself.

In your case, it seems that the action you are performing, is totally outside your domain, therefore you will have a problem, and that's why you don't know how to do it.

I suggest you to do something similar to this process:

  1. update your domain to have the new attribute (and so its mapping to DB) with a default value (if you need it), but nullable
  2. run a routine (or a script, or whatever can do this action) that internally calls a use case of your application that is responsible to update that field, and that will do this action for each one of your aggregates (the whole table)
  3. internally, each aggregate will record the related event and at some point of the execution the event is published, and then consumed to update your read model
  4. once all of your aggregates are updated, you can make that field not nullable (in your domain and in your database)

I strongly recommend you to avoid executing manual SQL query because your application won't be able to consistently react to those changes.

Hope this can help you!!

Goodbye and good luck!

0
On

In that case you just need to write a custom script for your Read Model. the Same as you do with you write model. And it would be better that you do it from your code not from SQL scripts.If you have event store DB you need to create event artificially and store.