Database design consideration on foreign-key both way between two tables - database

I have two class, User and Status, while a user will have a number of status, this is naturally Many-to-One relation and can be easily mapped to DB Tables.
However, the requirement also need User to maintain its “current” status, i.e., in the User Table, it need to have a foreign-key to the Status table. The result of this is having two foreign-keys between two tables in the opposite direction.
One obvious problem of this is once the records are inserted into the two tables, I can delete neither of them cause deleting from one table will violate the other table's foreign-key.
What is the best Design for this situation?

in your Status table , add a column that will determine whether this status record is "Current" or not.
** for performance issues , you can set only the "current" status records with '1' value and the rest with null value
you now don't have to use 2 foreign keys , only one - from Status to User.
if you are using hibernate as the post's tag :) you can create a view in the database that will select only the "Current" status records and will have the same structure as the Status table.
connect the view to the User entity using One-to-One relation,
I hope it helped you !

Do you have to keep the status in a separate table ? can it not be just represented by a java enum, and the User would have a status property. Something like this:
public enum UserStatus {
X, Y, Z;
}
public class User {
private UserStatus status;
...
}

Related

How to handle linked models?

I have two models, using Go 1.19:
type User struct {
Name string
ID int
}
type Order struct {
ID int
Name string
User *User
// or
UserID int
}
Of course, the database orders table has a foreign key to the users table via user_id.
Probably in different situations I have to use one of these models. When exactly?
Mb only user_id in DTO models, the user in responses from the server?
I will be glad for any information :)
It depends on your purpose. As usual, you have to use id when a table to include has meta info about your entity (often it's tables with a lot of rows and so heavy), therefore it will be better to use id, otherwise if it's table which describe some fields in initial table, you can use full entity.

Best approach for user status while building an API

Suppose I do have a users table in my application. I want to give that user status like active, inactive, blocked, approved, and verified. What should be the best approach for that?
Should I use multiple table columns like active = 1, inactive = 0, etc, or just a single column name 'status' and put that active, inactive, or block status as a value?
From a normalization perspective, you should keep 1-to-1 relationships within the same table.
You can also have a middle table where you store all of the available status values and use a foreign key to that table for each user record to set the status.

Insert foreign key records first to avoid racing condition?

I have 4 tables.
Table1 (primary)
Id
Table2 (foreign 1)
Id
Table1Id
Table3 (foreign 2)
Id
Table1Id
Etc
Table1 could have a record without table2,3 and 4 as well.
Now we have many records added to these tables and our application fetches to construct a response based on IDs in Table1.
You would normally add records in Table1 first then table 2 and 3 etc..
Our problem is that our polling (runs every 30seconds) application picks Ids from table1 but fails to get its linked records from Table2,3 and 4 because the application tries to fetch before linked records get saved in table 2,3 and 4 after saving a record in table1.
Is there a way of preventing this? Can we save foreign key records first? This way, the application won't see a record in table1 untill all linked records get saved in table2 and 3? Is it a common and safe practice?
Any advice would be great!
Thank you in advance
Depending on your system design you could always have this race condition. For example in a web application if you have a page that allows you to add a TableA, save it, then click a button to enter a related TableB, there is a period of time where a query on TableAs would receive an incomplete representation.
The solution is to either design the system or the data in a way that it can always be counted on to indicate that the data is in a complete state. For example, instead of designing it so that page-by-page entities in the relationship are saved independently, the user is given the ability to create the entire object graph. Entity Framework works with navigation properties for managing relationships, so if the client-side process walks through capturing the data for a Table A, then related Table B, and C etc. then passing all of those details in a structure to be persisted, you can have a single "Save" operation that creates the associated entities all in one go with one call to SaveChanges. This ensures all entities are committed together, or not at all. (if there is an exception) EF can take care of ensuring the tables are populated in the right order and assigning the FKs where needed. You don't need to "save" a TableA to get it's ID to populate in the TableB:
var tableA = new TableA
{
Name = viewModel.Name,
TableB = new TableB
{
Name = viewModel.BsName,
// ... or use biewModel.BDetails.Name, etc.
},
TableC = new TableC
{
// ....
}
};
context.TableAs.Add(tableA);
context.SaveChanges(); // Saves the A, B, and related C, etc.
If the data is rather large and complex and it doesn't make sense to try and capture everything at once, for instance if the data might be entered over a significant span of time given the user has to accumulate or check data etc. before the record state is considered complete enough to be queried on, then you can consider using something like a Status on your top level table. (TableA) This could be something like an enumeration. When you create your TableA record initially, the status would be defaulted to something like "InProgress". Any query reporting or such looking at TableAs would know only to query records with a Status of "Complete". As the user enters their Table B, C, etc. there would be either an automatic validation or manual assertion to determine if the TableA record can be marked off as "Complete", updating the status. From that point the report/summary query views would start seeing that row in results.

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.

One to two (1:2) relation between two tables

I'm working on some asp.net application, I got stuck in following business.
Suppose we have a person, and he can open both types of accounts and each account has some transaction history. Person table has some primary key say PPK, and customer table has some PK as PIN.
My question is how to solve/present this scenario in database, relation of person table to customer table is 1:2 as no person can have more than two account. and what about that transaction table? that holds all transaction history for some specific account? shall I make two transaction table (which is really a bad idea because as account type exceeds transaction tables exceeds).
Can I build their relation as 1:* (then I may need another table for that. it holds Fk of both table. )
or Can make pin as unique key and always open database for like checking limit of accounts (i.e. two).
I really need some suggestions.
All suggestions are welcome.
Thanks!
P.S: If you dont understand the question please ask me before reporting it away please!
You can either do something like this:
Or something like this:
The first model allows adding more accounts by just changing the CHECK (in case requirements change in the future), while the second would require adding another column in such case.
NOTE: The above assumes both account types are structurally identical, so they "fit" into same table. If that's not the case, you can use inheritance.
Ok you have a person table and an account table with a foreign key relationship between the two which is 1 person to many accounts. Then you have a transaction table that is related to the account id in the account table which is also 1 account to many transacations.
Now to enforce the limit of only two accounts being allowed, for that you want a trigger that checks when a record is being inserted or updated to amek sure the person currently has no more than one other record.

Resources