can i avoid creation of a foreign key constraint for a one-to-one relationship? - foreign-keys

i want to use eclipselink to partition my database. for performance reasons i will have one table (entity A) replicated to all nodes and one table (entity B) that is hash partitioned over all nodes.
Since every A has a one-to-one relationship with a B entity eclipseLink creates a foreign key constraint on a column of the "A"-Table. because of the different partitioning mechanisms this contraint will fail for a lot of entries in A.
currently the properties of the entities can change dayly so i wouldn't want to miss ddl-generation for tests and development.
Is it possible to tell eclipse link not to create this specific foreign key? all foreign keys?
the current test database is an in memory hsqldb. is it possible to tell the db to ignore foreign key constraints?

You can use your own DDL script to create the tables, or just drop the constraint with your own script or native SQL query.
You can disable all constraints by subclassing your database platform class (and using "eclipselink.target-database" with your subclass).

If there is no foreign key there is no relationship.
Alternatively, you could mark the property b in class A as transient so it does not get managed by JPA. It means that you will have to retrieve the appropiate b value yourself.
Also, you could just try to make field b nullable (if JPA supports null=true for a One-to-One relationship, I am not sure) and check what happens.

Related

How to enforce database constraints between two foreign keys on a join table?

I am trying to enforce a constraint between two foreign keys on a join table, and I don't know whether I can do it using the database, or whether I should do it through my app, or my ORM.
Here are my tables:
Dataset
Tag
- Dataset: FK
- name: string (eg: "park", "church", etc)
Place
- Dataset: FK
- latitude
- longitude
PlaceTag (my join table)
- Tag: FK
- Place: FK
- note: string (eg: "this place is my favorite park")
I want to enforce the constraint that each PlaceTag has a Tag and a Place that belong to the same Dataset. Should I do this using the database, or my app? Or should I re-structure my models to enforce this constraint more easily?
FWIW, this is an open-source project, and my PR for creating these tables is up here: https://github.com/mapseed/api/pull/161/files The project is using Django, if that helps.
One way of "enforcing" (note the quotation marks) this in Django would be to override the PlaceTag's save() method. In there you can raise an exception whenever self.place.dataset != self.tag.dataset. Yet you should note that there are situations in which Django will not call the custom save() method of a model:
When calling the update() method on a queryset. This method is meant for bulk updates and hence, for performance reasons, proceeds with the update directly at a database level (reference).
Inside (data) migrations custom save() methods are not available.
In these two situations the approach I propose will not be useful to enforce the constraint (hence the quotation marks at the beginning). This is of course not the same and not as strong as enforcing this at a database level. Anyway I don't think there is a portable way (i.e. available in any or most SQL database engines) of enforcing such a condition since checking it will require a join on other tables, yet I may be wrong on this one.

Create table without checking foreign key on unexisting table

I'm adapting a really big query (MySQL to SQL) that creates lots of tables and relationships. The problem is that it always check if a table exists prior to adding a foreign key referencing to that table.
So I have to reorder the queries to avoid this problem, and my question is if there's a instruction that can turn that check off, so it'll create the tables and add references without stopping the query with every error it encounters.
I'm working with SQL in an Azure DB.
Thank you.
Easiest way is to create all tables first and then add constraints using ALTER TABLE.
For example:
CREATE TABLE a(id INT PRIMARY KEY IDENTITY(1,1), b_id INT, c CHAR(10));
CREATE TABLE b(id INT PRIMARY KEY IDENTITY(1,1), z INT);
ALTER TABLE a ADD CONSTRAINT FK_a_b_id_b FOREIGN KEY (b_id) REFERENCES b(id);
Rextester Demo

Cross-database relations using UUID for PK

It says here that foreignkeys across databases can't be done because of referential integrity: https://docs.djangoproject.com/en/1.9/topics/db/multi-db/#cross-database-relations
Could this be overcome by using UUID's for the primary key?
I'm guessing either I don't fully understand referential integrity, or I'm not the first to think of this and it can't be done for reasons I don't know yet.
A foreign key means "make sure a value in this column exists in another column". This doesn't work cross-database in PostgreSQL, as databases cannot "see" each other. It does work cross-schema though - use the fully qualified schema_name.table_name.
Why are you trying to refer to a column in another database?

Entity Framework Cascade Deleting, even though no CASCADE set up in database

I have a foreign key relationship between two tables UserProducts and Users in my database, with UserProducts having a UserID referencing the UserID in the Users table.
ALTER TABLE [dbo].[UserProducts] WITH CHECK ADD CONSTRAINT [FK_UserProducts_Users] FOREIGN KEY ([UserID])
REFERENCES [dbo].[Users] ([UserID])
GO
ALTER TABLE [dbo].[UserProducts] CHECK CONSTRAINT [FK_UserProducts_Users]
GO
The UserID column in the UserProducts table is part of a composite primary key with another column ProductID. There are also two additional DateTime columns, so Entity Framework does not treat UserProducts as a link table.
There is NO cascade delete on that foreign key above, nor did I set up anything to handle OnDelete on the Entity Framework foreign key association. Yet, when I delete a User entity from code, Entity Framework is taking the liberty of deleting the UserProducts associated with it by UserID. It is also generating a lot of SQL to do it: there is a separate DELETE per related record in the UserProducts table.
The code to perform the entity deletion is as follows:
using (var context = new LicensingRegistrationContext(_csb))
{
context.Database.Log = a => _logger.Trace(a);
var dbUser = GetUserDbSetWithIncludes(context)
.Where(a => a.UserID == user.Id).Single();
context.DbUsers.Remove(dbUser);
//TODO(MRL): Um...how are the dbUserProducts being removed???
context.SaveChanges();
}
How is this happening? In EF 4 I am pretty sure EF never took this liberty of doing this: you HAD to load and then delete all related entities manually in code.
Thanks
Entity framework by default has a
OneToManyCascadeDelete
convention. Here is the link http://msdn.microsoft.com/en-us/library/system.data.entity.modelconfiguration.conventions.onetomanycascadedeleteconvention(v=vs.113).aspx
So entity framework cascade deletes the one to many relationship by default.
You can disable this by disabling the convention or explicitly disabled it for this relationship via the fluent API.
I found this on MSDN and I believe this is what is happening:
When a primary key of the principal entity is also part of the primary key of the dependent entity, the relationship is an identifying relationship. In an identifying relationship the dependent entity cannot exist without the principal entity. This constraint causes the following behaviors in an identifying relationship: Deleting the principal object also deletes the dependent object. This is the same behavior as specifying OnDelete Action="Cascade" in the model for the relationship. Removing the relationship deletes the dependent object. Calling the Remove method on the EntityCollection marks both the relationship and the dependent object for deletion.
This is what is happening in my model where the UserComponent table has a composite primary key: UserID, ComponentID and the UserID column is a foreign key to the UserID in the User table.

Doctrine2: Uni-directional #OneToMany with foreign key?

I have a "Product" entity with many "Video" entities, and I only need a unidirectional #OneToMany with foreign key (one product, many videos). My Product-side "key" is not primary or unique, which is why I need it to be unidirectional (eg, "select * from videos where product_family = 2143")
I'm using Doctrine 2.1
Is there yet a way to do uni-directional #OneToMany with only a foreign-key in Doctrine 2.1? If not, soon?
UPDATE: I found a relevant quote from Roman Borschel on May 2010:
"this would need quite some special-case handling in many places. In the light that there are 2 reasonably good alternatives (mapping through a jointable or simply making the association bidirectional) we do not consider this something that really needs to be done."
Has this opinion by the Doctrine2 team changed?
OneToMany by design has the related ID on the "Many" side of the relationship. So to make the child table relate to the parent without an additional field in a join table is not possible.