CQRS aggregated view - cqrs

There is a common recommendation to have single table (or SQL view) per ViewModel. I can't really understand how to achieve this in the scenario then I need to show an aggregated model on the view and a list of children. Example:
Topic title
Topic description.
Comment 1
Comment 2
Comment 3
There is an aggregated Topic model that is supposed to be a root model and represented by the 1st SQL view and a number of child models - Comment linked to Topic with a foreign key. So we have 2 tables or views and join to show them on the screen.
And the questions are:
Is it okay to have more than one joined tables for the single
ViewModel?
Is it possible to flatten the example above to keep it in the single SQL view? If so then how the ViewModel class should look like?
What to do if we have more than 1 linked models?
Programming language doesn't really matter.

A document oriented database better fits for Read model. You can store document per ViewModel, and there is no needs in joins, etc. But your ViewModel is not obligatory referred to only one document. In your example, if you load more comments by ajax, you can store comment in another document/collection/table. If you use search queries for comments, you also can store it in another document/collection/table. If you load all comments together with topic you can store it in one document (topic and comments together). Later, if you decide to load comments by ajax or allow user query comment, you can split this document or store comments in another collection/table additionally.

The recommendation is to store your data in a format that suits your needs. Joinless queries are preferred, not mandatory. A practical alternative would be to store your views as documents in a document database.

Related

Lagom persistent read side and model evolution

To learn lagom i created a simple application with some simple persistent entities and a persistent read side (as per the official documentation, using cassandra)
The official doc contains a section about model evolution, describing how to change the model. However, there is no mention of evolution when it comes to the read side.
Assuming i have an entity called Item, with an ID and a name, and the read side creates a table like CREATE TABLE IF NOT EXISTS items (id TEXT, name TEXT, PRIMARY KEY (id))
I now want to change the item to include a description. This is trivial for the persistent entity, but the read side has to be changed as well.
I can see several approaches to (maybe) achieve that:
use a model evolution tool like liquibase or play evolutions to change the read side tables.
somehow include update table statements in createTables that migrate the model
create additional tables containing the additional information, and keep the old tables without modifications
Which approach would be the most fitting? Is there something better?
Creating a new table and dropping the old table is an option too IMHO.
It is simple as modifying your "create table" command ("create table mytable_v2 ..." and "drop table mytable...") and changing the offset name and modifying your event handlers.
override def buildHandler( ): ReadSideProcessor.ReadSideHandler[MyEvent] = {
readSide.builder[MyEvent]("myOffset") // change it to "myOffset_v2"
...
}
This results in all events to be replayed and your read side table to be reconstructed from the scratch. This may not be an option if the current table is really huge as the recostruction may last very long time.
Regarding what #erip says I see perfectly normal adding a new column to your read side table. Suppose there are lots of records in this table with list of all entities and you want to retrieve a list of entities based on some criteria so you need some columns to be included in the where clause. Retrieving list of all entities and asking each of them if it complies with the criteria is not an option at all - it could be very unefficient as it needs more time, memory and network usage.
The point of a read-side is to materialize views from entity state changes from your service's event stream in your service. In this respect, you as the service controller can decide what is important for your subscribers to know about. This is handled by creating read-sides with an anti-corruption layer (or ACL).
Typically your subscribers will subscribe to API events which should experience no evolution. Your internal events (or impl events) will likely need to evolve; because of this, there should be a transformation from the impl to the API.
This is why it's very important to consider your domain very carefully before design: you really need to nail down what subscribers will need to know about. In the case of a description, it strikes me as unlikely that subscribers will need (or want!) to know about that.

In a nosql database like MongoDB or Couchbase how to model many to many relationship?

Consider a scenario of an application where I have users and projects and the requirement is users shall be assigned to projects. One user can be assigned to multiple projects. This is a many to many relationship. So what is the best way to model such a requirement.
I will like to discuss few approaches to model such a requirement :
- Embeded data model
In this approach I will embedd the user documents inside projects document.
Advantages : you get all the required data in one API call OR by fetching one single document.
Disadvantages : Data duplicacy which is OK
Real problem is if you update user information for eg user mobile no or name from users screen then this updated information should also be reflected under all embedded user documents. For this some bulk update query should be fired.
But is this the right way ???
- Embedding object references instead of objects (which is normalised)
In this case if we embedd user id's instead of user objects then the problem mentioned above wont be there but then we will have to make multiple network calls to get required data or make a seperate relation kond of document as we do in SQL.
Is this the best way ??
We have a same scenario, so i embed objectId. and for fill data for clients, populate users data in find function.
contract.find({}).populate('user').then(function(){});
There are few hard and fast rules, but usually with many-to-many relationships you would prefer references over embedding. This doesn't mean your data is totally flat/normalized.
For example, you could have a user document with an array of project ids. You could have the reverse for projects.
Think about your queries and how you will structure them. That can give you other hints about how to structure your documents.

Mutual dependency MongoDB

Let's say I'm making a social app with MongoDB database, and I want users to be able befriend each other. Of course friendship is a mutual relation and user ids are integers. What would be the best approach?
Every user has a list of friend ids. Every time a bond is created/severed, both users' lists have to be updated.
Create join table 'friendship' containing IDs of 2 users. Every time bond is created I have to create two entries. 1->2 and 2->1
As no. 2, but always create only 1 bond with rule: lower_usr_id -> higher_usr_id. Assuming there are a lot of people and friendships. Wouldn't it save a lot of space and time?
It sounds like you're rather unclear about how MongoDB works. Joins aren't something that appears in MongoDB, and if you're trying to use MongoDB like a relational database you're doing it wrong.
I'm no expert on MongoDB, but I believe there are two common methods of modelling a one-to-many relationship:
Embedding one document inside another
Using references
Embedding a document inside another makes sense where the parent document in some sense "owns" the child document. For instance, in the context of a blogging application, a comment is owned by a post, so it might make sense to embed the comment inside the post.
For your use case, I don't believe that would be appropriate since the relationship is between objects of the same type. It would therefore make sense to record friendships as a reference to another object in the same collection.
Check out this link for further details.

classes and data presentation

I hope someone can give me some guidance in how to best approach this situation.
I am using dbcontext, wpf and sql server.
I am having situations were the presentation of the data requires other data than just what is coming from a single table. For example, if I had a person table but wanted to show also how many books they had read from related data, say fields would be name, address, NoOfBooks.
I currently create a new class, called say PersonBookPM, that I fill up with data from a linq query which combines the two tables which includes the above three fields.I create an observablecollection of that and make that the itemssource of the grid/listbox.
When I am then adding data to that I then need to use the selecteditem, convert that back to the single entity of person, and attach it back in to the context.
It seems like the classes have already been defined by the code gen and I am repeating the process only slightly differently.
Am I going round the houses here?
Thanks Scott

DB Design: more tables vs less tables

Say I want to design a database for a community site with blogs, photos, forums etc., one way to do this is to single out the concept of a "post", as a blog entry, a blog comment, a photo, a photo comment, a forum post all can be thought as a post. So, I could potentially have one table named Post [PostID, PostType, Title, Body .... ], the PostType will tell what type of post it is.
Or I could design this whole thing with more tables, BlogPost, PhotoPost, ForumPost, and I'll leave Comment just it's own table with a CommentType column.
Or have a Post table for all types of post, but have a separate Comment table.
To be complete I'm using ADO.NET Entity Framework to implement my DAL.
Now the question what are some of the implications if I go with any route described above that will influence on my DB performance and manageability, middle tier design and code cleaness, EF performance etc.?
Thank you very much!
Ray.
Let me ask you this:
What happens if two years from now you decide to add a 'music post' as a blog type? Do you have to create a new table for MusicPost, and then re-code your application to integrate it? Or would you rather log on to your blog admin panel, add a blog type in a drop-down box called 'Music', and be on your merry way?
In this case, less tables!
Generally, life will be easier if you can have all the posts in one table:
less joins to perform
less tables to maintain
common attributes are not repeated between tables
code more generic
However, you could run into some issues:
if each subtype has a lot of its own attributes, you could end up with many columns - maybe too many for your DBMS
if a subtype has an attribute (e.g. a stored picture) that is expensive for your DBMS to maintain even when unused, you might not want that column in all rows
Should you run unto such an issue, you can create a new table just for the specific attributes of that post subtype - for example:
create table posts (post_id number primary key,
post_date date,
post_title ...); /* All the common attributes */
create table photo_post (post_id references posts, photograph ...);
In many cases, no such issues arise and a single table for all will suffice.
I can't think of any merit in creating a distinct table for every subtype.
The problem is similar to the question of how deep your hierarchy should be in an OO design.
A simple approach in OO terms would be to have a base class Post and children for BlogPost, ForumPost and so on. Comment could either be a child of Post or its own hierarchy, depending on your requirements.
Then how this is going to be mapped to DB tables is an entirely different question. This classical essay by Scott Ambler deals with the different mapping strategies and explains their advantages and disadvantages in a rather detailed way.