Trying to avoid a fact to fact relationship - domain-data-modelling

I am trying to avoid a fact to fact relationship but in this case it seems hard:
For several customers (DIM_Customer) we receive emails (FACT_email), Calls (FACT_CALL) etc. Now the emails and calls may have Surveys. Each Survey is unique for a Customer. As we know a survey consists of several questions.
So we have DIM_Survey (which basically is the survey type) and Dim_Questions And Fact_Survey (which contains the answers).
My question is how do I get the relationship between the email and the survey answers for that particular survey.

Related

How would one structure a mutual relationship between two users in Parse?

I am playing around with my own Parse server and would like to build a social media app just for fun. Just learning how to structure it and get everything developed.
One of the problems that I am having trouble wrapping my head around is how I would create a relationship structure between two users where the connection is mutual.
You would have to, on both ends, accept the relationship request.
I would also like to know how I would query for the friends list. Which would how would I query for the people the user has mutual connections with?
I hear that a friendship table relationship would be helpful for structuring a relationship with friends. But I would like to make it a mandatory mutual connection for people to be friends.
All you actually need is Request(person, friend) "PERSON asked to friend FRIEND", because requited and unrequited friendships can be extracted by query. You might prefer to keep those two relationships separately instead: Requited(person, friend) "PERSON asked to friend FRIEND and FRIEND asked to friend PERSON" & Unrequited(person, friend) "PERSON asked to friend FRIEND and FRIEND hasn't asked to friend PERSON". If a row (p, f) is in Requited then so is (f, p), and neither is in Unrequited. The two tables UNION to Request. But then you need to move rows between the tables when people friend or unfriend others. What is "best" logically depends on patterns of update & querying, and there will be likely be another "best" when implementation is included.
Database design is the identification of sufficient relationships/associations to describe any application situation. Each gets a table whose rows make a true statement from some characterizing statement template, aka predicate. Each query returns the rows that satisfy its own relationship/association, characterized by a predicate built from base predicates. Normalization helps with relationship/association/predicate/table choice, and so do information modeling methods. Pick a method (eg Object-Role Modeling) and learn it & how & why it leads to "good" designs while avoiding "bad" ones.
Create a new Object call "Relationships" and store both PFUser id's.

REST URL Design for One to Many and Many to Many Relationships

Your backend has two Models:
One Company to Many Employees.
You want to accomplish the following:
Get all Companies
Get a Company by ID
Get all Employees for a Company
Get all Employees
Get a Employee by ID
What is the best practice for handling the REST URLs when your models have 1:M relationships? This is what I have thought of so far:
/companies/
/companies/<company_id>/
/companies/<company_id>/employees/
/employees/
/employees/id/<employee_id>/
Now let's pretend One Company has Many Models. What is the best name to use for "Adding an employee to a Company" ? I can think of several alternatives:
Using GET:
/companies/<company_id>/add-employee/<employee_id>/
/employees/<employee_id/add-company/<company_id>/
Using POST:
/companies/add-employee/
/employees/add-company/
The URIs look fine to me, except maybe the last one, that does not need an additional "id" in the path. Also, I prefer singular forms of words, but that is just me perhaps:
/company/
/company/<company_id>/
/company/<company_id>/employee/
/employee/
/employee/<employee_id>/
The URIs do not matter that much actually, and can be changed at any point later in time when done properly. That is, all the URIs are linked to, instead of hardcoded into the client.
As far as adding an employee, I would perhaps use the same URIs defined above, and the PUT method:
PUT /employee/123
With some representation of an employee. I would prefer the PUT because it is idempotent. This means, if the operation seems to fail (timeout, network error occurs, whatever) the operation can be repeated without checking whether the previous one "really" failed on the server or not. The PUT requires some additional work on the server side, and some additional work to properly link to (such as forms), but offers a more robust design.
As an alternative you can use
POST /employee
With the employee representation as body. This does not offer any guarantees, but it is easier to implement.
Do not use GET to add an employee (or anything for that matter). This would go against the HTTP Specification for the GET method, which states that it should be a pure information retrieval method.

Dynamic representation of a REST resource

Lets assume I have an object that I expose as a REST resource in my application. This object has many fields and contains many other objects including associated collections. Something like this, but think MUCH bigger:
Customer
List<Order> orders
List<Address> shippingAddresses;
// other fields for name, etc.
Order
List<Product> products
// fields for total, tax, shipping, etc.
Product
// fields for name, UPC, description, etc.
I expose the customer in my api as /customer/{id}
Some of my clients will want all of the details for every product in each order. If I follow HATEOAS I could supply a link to get the product details. That would lead to n+1 calls to the service to populate the products within the orders for the customer. On the other hand, if I always populate it then many clients receive a bunch of information they don't need and I do a ton of database lookups that aren't needful.
How do I allow for a customer representation of my resource based on the needs of the client?
I see a few options.
Use Jackson's JsonView annotation to specify in advance what is used. The caller asks for a view appropriate to them. i.e. /customer/{id}?view=withProducts. This would require me to specify all available views at compile time and would not be all that flexible.
Allow the caller to ask for certain fields to be populated in the request, i.e. /customer/{id}?fields=orders,firstName,lastName. This would require me to have some handler that could parse the fields parameter and probably use reflection to populate stuff. Sounds super messy to me. The what do you do about sub-resources. Could I do fields=orders.products.upc and join into the collection that way? Sounds like I'm trying to write hibernate on top of REST or something.
Follow HATEOAS and require the client to make a million HTTP calls in order to populate what they need. This would work great for those that don't want to populate the item most of the time, but gets expensive for someone that is attempting to show a summary of order details or something like that.
Have separate resources for each view...
Other?
I would do something like this:
/customers/{id}/orders/?include=entities
Which is a kind of a more specific variation of your option 1.
You would also have the following options:
Specific order from a specific customer without list of products:
/customers/{id}/orders/{id}
Just the orders of a customer without products:
/customers/{id}/orders/
I tend to avoid singular resources, because most of the time or eventually someone always wants a list of things.
Option 2 (client specifies fields) is a filtering approach, and acts more like a query interface than a GETable resource. Your filter could be more expressive if you accept a partial template in a POST request that your service will populate. But that's complicated.
I'm willing to bet all you need is 2 simple representations of any complex entity. That should handle 99.9% of the cases in your domain. Given that, make a few more URIs, one for each "view" of things.
To handle the 0.1% case (for example, when you need the Products collection fully populated), provide query interfaces for the nested entities that allow you to filter. You can even provide hypermedia links to retrieve these collections as part of the simplified representations above.

RESTful design: when to use sub-resources? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
When designing resource hierarchies, when should one use sub-resources?
I used to believe that when a resource could not exist without another, it should be represented as its sub-resource. I recently ran across this counter-example:
An employee is uniquely identifiable across all companies.
An employee's access control and life-cycle depend on the company.
I modeled this as: /companies/{companyName}/employee/{employeeId}
Notice, I don't need to look up the company in order to locate the employee, so should I? If I do, I'm paying a price to look up information I don't need. If I don't, this URL mistakenly returns HTTP 200:
/companies/{nonExistingName}/employee/{existingId}
How should I represent the fact that a resource to belongs to another?
How should I represent the fact that a resource cannot be identified without another?
What relationships are sub-resources meant and not meant to model?
A year later, I ended with the following compromise (for database rows that contain a unique identifier):
Assign all resources a canonical URI at the root (e.g. /companies/{id} and /employees/{id}).
If a resource cannot exist without another, it should be represented as its sub-resource; however, treat the operation as a search engine query. Meaning, instead of carrying out the operation immediately, simply return HTTP 307 ("Temporary redirect") pointing at the canonical URI. This will cause clients to repeat the operation against the canonical URI.
Your specification document should only expose root resources that match your conceptual model (not dependent on implementation details). Implementation details might change (your rows might no longer be unique identifiable) but your conceptual model will remain intact. In the above example, you'd tell clients about /companies but not /employees.
This approach has the following benefits:
It eliminates the need to do unnecessary database look-ups.
It reduces the number of sanity-checks to one per request. At most, I have to check whether an employee belongs to a company, but I no longer have to do two validation checks for /companies/{companyId}/employees/{employeeId}/computers/{computerId}.
It has a mixed impact on database scalability. On the one hand you are reducing lock contention by locking less tables, for a shorter period of time. But on the other hand, you are increasing the possibility of deadlocks because each root resource must use a different locking order. I have no idea whether this is a net gain or loss but I take comfort in the fact that database deadlocks cannot be prevented anyway and the resulting locking rules are simpler to understand and implement. When in doubt, opt for simplicity.
Our conceptual model remains intact. By ensuring that the specification document only exposes our conceptual model, we are free to drop URIs containing implementation details in the future without breaking existing clients. Remember, nothing prevents you from exposing implementation details in intermediate URIs so long as your specification declares their structure as undefined.
This is problematic because it's no longer obvious that a user belongs
to a particular company.
Sometimes this may highlight a problem with your domain model. Why does a user belong to a company? If I change companies, am I whole new person? What if I work for two companies? Am I two different people?
If the answer is yes, then why not take some company-unique identifier to access a user?
e.g. username:
company/foo/user/bar
(where bar is my username that is unique within that specific company namespace)
If the answer is no, then why am I not a user (person) by myself, and the company/users collection merely points to me: <link rel="user" uri="/user/1" /> (note: employee seems to be more appropriate)
Now outside of your specific example, I think that resource-subresource relationships are more appropriate when it comes to use rather than ownership (and that's why you're struggling with the redundancy of identifying a company for a user that implicitly identifies a company).
What I mean by this is that users is actually a sub-resource of a company resource, because the use is to define the relationship between a company and its employees - another way of saying that is: you have to define a company before you can start hiring employees. Likewise, a user (person) has to be defined (born) before you can recruit them.
Your rule to decide if a resource should be modeled as sub resource is valid. Your problem does not arise from a wrong conceptual model but you let leak your database model into your REST model.
From a conceptual view an employee if it can only exist within a company relationship is modeled as a composition. The employee could be thus only identified via the company. Now databases come into play and all employee rows get a unique identifier.
My advice is don't let the database model leak in your conceptional model because you're exposing infrastructure concerns to your API. For example what happens when you decide to switch to a document oriented database like MongoDB where you could model your employees as part of the company document and no longer has this artificial unique id? Would you want to change your API?
To answer your extra questions
How should I represent the fact that a resource to belongs to another?
Composition via sub resources, other associations via URL links.
How should I represent the fact that a resource cannot be identified without another?
Use both id values in your resource URL and make sure not to let your database leak into your API by checking if the "combination" exists.
What relationships are sub-resources meant and not meant to model?
Sub resources are well suited for compositions but more generally spoken to model that a resource cannot exist without the parent resource and always belongs to one parent resource. Your rule when a resource could not exist without another, it should be represented as its sub-resource is a good guidance for this decision.
if a subresource is uniquely identifiable without its owning entity, it is no subresource and should have its own namespace (i.e. /users/{user} rather than /companies/{*}/users/{user}).
Most importantly: never ever ever everer uses your entity's database primary key as the resource identifier. that's the most common mistake where implementation details leak to the outside world. you should always have a natural business key (like username or company-number, rather than user-id or company-id). the uniqueness of such a key can be enforced by a unique constraint, if you wish, but the primary key of an entity should never ever everer leave the persistence-layer of your application, or at least it should never be an argument to any service method. If you go by this rule, you shouldn't have any trouble distinguishing between compositions (/companies/{company}/users/{user}) and associations (/users/{user}), because if your subresource doesn't have a natural business key, that identifies it in a global context, you can be very certain it really is a depending subresource (or you must first create a business key to make it globally identifiable).
This is one way you can resolve this situation:
/companies/{companyName}/employee/{employeeId} -> returns data about an employee, should also include the person's data
/person/{peopleId} -> returns data about the person
Talking about employee makes no sense without also talking about the company, but talking about the person does make sense even without a company and even if he's hired by multiple companies. A person's existence is independent of whether he's hired by any companies, but an employment's existence does depend on the company.
The issue seems to be when there is no specific company but an employee technically belongs to some company or organization otherwise they could be called bums or politicians. Being an employee implies a company/organization relationship somewhere but not a specific one. Also employees can work for more than one company/organization. When the specific company context is required then your original works /companies/{companyName}/users/{id}
Lets say you want to know the EmployerContribution for your ira/rsp/pension you'd use:
/companies/enron/users/fred/EmployerContribution
You get the specific amount contributed by enron (or $0).
What if you want the EmployerContributions from any or all companies fred works(ed) for? You don't need a concrete company for it to make sense. /companies/any/employee/fred/EmployerContribution
Where "any" is obviously an abstraction or placeholder when the employee's company doesn't matter but being an employee does. You need to intercept the 'company" handler to prevent a db lookup (although not sure why company wouldn't be cached? how many can there be?)
You can even change the abstraction to represent something like all companies for which Fred was employed over the last 10 years.
/companies/last10years/employee/fred/EmployerContribution

MVC:RESTful routing with nested urls, when entities are not really nested

I 'm really having a hard time with the RESTful paradigm + nested urls. I have asked a question that lead me to where I am right now here. My Domain is roughly this: there are schools, courses of a school and teachers of schools. Now schools, courses and teacher are not "nested" entities in the sense that you can refer to any of them with one Id. The site is a collection of "micro-sites" for each school showing each one's courses and teachers. A course or teacher can only exist in one school.
say we have a url like /schools/1/courses/10 . Course 10 of school 1. This works fine. Say that the user changes by hand 10 into 11, which happens to exist but is a course of school 2. Right now that leads to a mess, my site still "thinks" the user is in school 1 but shows course 3 as part of it.
Should I make detail-actions parametric to both the Id being asked for AND the "parent" entity (the school in this case) that it involved? Fetch from repositories not only by id but with a school constraint?
Or is there any better way to do this?
The way I would think about it is this; even though there may be a course 11 in your service, there is no resource that exists at the URI /schools/1/courses/11. Since there is no resource at this URI, I would return an HTTP 404 response to requests for the URI.
One way you may improve your service would be to replace the integer ID values with the names of the entities (this would require the names be unique). This would make your URIs more user friendly. An example would be /schools/Hogwarts/courses/Potions.
To further improve your service, you'll want to give users a way to navigate through the service to all of the different resources available. For example you'll probably want to allow them get a list of all courses offered by a certain school. To do that you'd expose a resource at /schools/Hogwarts/courses/ whose return type would be a list of all courses offered by the school. The representation of this list could be an XML document like the following snippet:
<courses>
<course uri="/schools/hogwarts/courses/defense+against+the+dark+arts">Defense against the dark arts</course>
<course uri="/schools/hogwarts/courses/potions">Potions</course>
</courses>
Should I make detail-actions
parametric to both the Id being asked
for AND the "parent" entity (the
school in this case) that it involved?
Fetch from repositories not only by id
but with a school constraint?
Yes.
Or is there any better way to do this?
Nothing wrong with what you described above.
You could do it with a catch-all route, and then parsing the url elements yourself.