Inversed FK with NOT NULL required - database

I am trying to model a database where I have 2 inverted foreign keys which both tables fields are required NOT NULL. How can I model that?
Here a small sample:
I have two tables called the first is a generic called "SystemObjects" and the second is called "Users". Each "SystemObject" is created by a "User" object and so require a 'CreatedBy' foreign key which cannot be null. In the same time, all users have also generic associated SystemObject entry and the table "Users" contains more info about those objects with specific type "User".
In OOP analogy, "User" inherits from "SystemObject" and has supplementary members. and so I need to keep track of that connection.
A summary to my problem:
"A" has a foreign key field to "B"
"B" has a foreign key field to "A"
Both are required (NOT NULL)
How to escape this trap? Any alternative Model that would solve my problem and allow me to have this vis-verca tracking?
Thank you!

Related

Database theory: best way to have a "flags" table which could apply to many entities?

I'm building a data model for a new project I'm developing. Part of this data model involves entities having "flags".
A flag is simply a boolean value - either an entity has the flag or it does not have the flag. To that end I have a table simply called "flags" that has an ID, a string name, and a description. (An example of a flag might be "is active" or "should be displayed" or "belongs to group".)
So for example, any user in my users table could have none, one, or many flags. So I create a userFlags bridge table with user ID and flag ID. If the table contains a row for the given flag ID and user ID, that user has that flag.
Ok, so now I add another entity - say "section". Each section can also have flags. So I create a sectionFlags table to accommodate this.
Now I have another entity - "content", so again, "contentFlags".
And so on.
My final data model has basically two tables per entity, one to hold the entity and one for flags.
While this certainly works, it seems like there may be a better way to design my model, so I don't have to have so many bridge tables. One idea I had was a master "hasFlags" table with flag ID, item ID and item type. The item type could be an enumerated field only accepting values corresponding to known entities. The only problem there is that my foreign key for the entity will not work because each "item ID" could refer to a different entity. (I have actually used this technique in other data models, and while it certainly works, you lose referential integrity as well as things like cascade updates.)
Or, perhaps my data model is fine as-is and that's just the nature of the beast.
Any more-advanced experienced DB devs care to chime in?
The many-to-many relationships are one way to do it (and possibly faster than what I'm about to suggest because they can use integer key indexes).
The other way to do this is with a polymorphic relationship.
Your entity-to-flag table needs 2 columns as well as the foreign key link to the flag table;
other_key integer not null
other_type varchar(...) not null
And in those fields you store the foreign key of the relation in the integer and the type of the relation in the varchar. Full-on ORMs that support this sometimes store the class name of the foreign relation in the type column, to aid with object loading.
The downside here is that the integer can't be a true foreign key as it will contain duplicates from many tables. It also makes your querying a bit more interesting per-join than the many-to-many tables, but it does allow you to generalise your join in code.

How do I define a one-to-one relationship over a one-to-many relationship in a relational database?

I'm creating a database schema with the following tables (sorry for the bad pseudocode):
User
====
user_id, PK
Collection
==========
collection_id, PK
user_id, FK(User->user_id)
Issue
=====
issue_id, PK
collection_id, FK(Collection->collection_id)
There is a one-to-many relationship from User to Collection, and also from Collection to Issue. So, a single user may maintain multiple collections, each with many issues.
The problem: I would like to designate a "default" collection to be displayed when the user first logs in to the application. For the record, I'm doing this in the Django framework, but I'm more interested in the elegant platform-independent solution. When I try to make a column in User that is a Foreign Key to Collection, it complains that Collection does not exist yet (I suppose because User is created first). I could add a "default" boolean column to Collection and enforce through my application that only one record per User be "true", but that seems inelegant. I could also have a separate table, say, User_Default_Collection, which has user_id as a Foreign, Unique Key, and a collection_id column which is a Foreign Key to Collection. But I'm certain this is also less than 3rd normal form. Any suggestions?
If you want to enforce that every user must and will always have his "default" collection, then because of the obvious cycle in the inclusion dependencies you are forced into either deferred constraint checking (if your DBMS allows the FK cycle to be declared in the first place) or application-enforced integrity.
If you can tolerate users not having any default collection at all, then create a separate table DFT_COLL(userid, dft_coll_id) with key userid and FK's to both USER and COLLECTION.
If it gives you trouble in cases when a user has no default collection, maybe this can still be addressed by having the system just pick one (e.g. the one with the lowest [or highest] id) and implement this with a UNION view (so that if you need the default then you read the UNION view and you're guaranteed (*) to get some result).
(*) If the user has a collection at all, that is. Note that requiring a default collection and requiring that to exist, implies requiring at least one collection per user. (And the corollary of this is that if it must be allowed for a user to have no collection at all, it is nonsensical and a contradiction to require him to have a default one.)
The most plausible solution i think would be:
Add nullable "default" field to Collection table
Create UNIQUE constraint for used_id and default
Keep "true"-s and NULLs (no false's) in "default" column.
This will not allow for multiple Collections associated with the same user_id to have the same "default" value other than null. You don't need to develop any application logic. However, this design would not force you to always have a default collection for a user.

how to check member type when having hierarchical inheritance

I have the following structure :
Person (abstract class) inherited by admin,staff and candidate. The candidate has two subclasses : admitted and retained.
So when a "person" sign in, I have to check if he's admin, staff or candidate, and if he is candidate I have to check if he's admitted,retained or just candidate, that means that I have to check 4 to 6 table each time someone sign in and in addition I will have to make a lot of if else in my program (to create the appropriate instance), I thought to go for a TPH but the problem is that some subclasses have relationships with other classes that some other don't have for example admin have a relation with "Processing result" (he's allowed to consult the processing results, and this will be logged in the database)
So what's the best solution to check member type in this case? is it possible to add a discriminator column in TPT ? can it be a foreign key (like putting all types in a table and put references to this types in the person and candidate table) ?
Thank you :)

Relational database design considering partly dependent information?

I strongly having the feeling, I don't see the wood for the trees, so I need your help.
Think of the following two tables:
create table Category (Category_ID integer,
Category_Desc nvarchar2(500));
create table Text (Text_Id integer,
Text nvarchar2(1000),
Category_Id integer references Category.Category_Id);
This code follows no proper syntax, it's just to get an idea of the problem.
Consider the idea to save text parts for certain categories to use them in an interface, like messages ("You can't do that!", "Do this!",...), but also to create notes for other objects, e. g. like orders ("Important customer! Prioritize this order!").
Now for my question. Some of this text bits bring some more information with them, like if you add the "Important customer" note to an order, also the Order.Prio_Flag is set.
Now this is a very special information, only considering text used by the category Order_Note. I don't want to add this to the Text table, since most of the entries are not affected by this and the table would get more and more crowded by special cases for only the least part of its content.
I get the feeling, the design is flawed, but I also don't want a table for every category and keep this as general as possible.
Keep in mind, this is a simplified view of the problem.
TL:DR: How do I add information to a table's content without adding new attributes, because the new attribute would only be filled for the least number of entries.
Subtyping and dependent attributes are easy to do in a relational database. For example, if some Texts are important and need to have a dependent attribute (e.g. DisplayColor), you could add the following table to your schema:
CREATE TABLE ImportantText (
Text_Id integer NOT NULL ,
Display_Color integer NOT NULL ,
PRIMARY KEY (Text_Id),
CONSTRAINT ImportantTextSubtypeOfText
FOREIGN KEY (Text_Id) REFERENCES Text (Text_Id)
ON DELETE CASCADE ON UPDATE CASCADE
);
Many people think foreign key constraints establish relationships between entities. That's not what they're for. They're CONSTRAINTS, i.e. they limit the values in a column to be a subset of another column. In this way, a subtyping relation is established which can record additional properties.
In the table above, any element of ImportantText must be an element of Text, and will have all the attributes of Text (since it must be recorded in the Text table), as well as the additional attributes of ImportantText.

can two primary keys be refer to the same attribute in another table

Can two primary keys refer to the same attribute in another table for example
customer id from table customer and user id from table user which refer to field id in table billing and i think i can differentiate between them by adding type field.
I see no reason why not but I also see your adding confusion for the next guy that has to work on this. Why not treat them separately with customer ID and User ID as different values? Good luck.
You can, but probably shouldn't. It is generally clearer to have linking tables instead; for example, if you have "customers", "users", and "billing" tables, have "customer_billing" and "user_billing" tables, rather than having a customer-or-user-id and type in the billing table.
A better solution is to have one supertype table containing the key for all users and customers. Reference the supertype table from your billing table.

Resources