DBFlow icon indicating copy to clipboard operation
DBFlow copied to clipboard

FOREIGN KEY constraint failed (code 787)

Open boxlady opened this issue 11 years ago • 8 comments

First of here is the class that I think is causing the problem, this is the base class to rafeling (there is no other columns etc in rafeling (All other classes are able to save). I have tried a combination of saving order saveForeignKeyModel = false and @Unique(onUniqueConflict = ConflictAction.REPLACE) for primary keys. Not sure if the fault is mine or not but I’ve been banging my head for days now and any help would be greatly appreciated.

 @ModelContainer
@Table(databaseName = Database.NAME)
public class Damages extends BaseModel {
protected Paint paint;
Ernstklasse ernstklasse;
@Column
@PrimaryKey(autoincrement = true)
 public long idDamage;
@Column
 String mText;
@Column
@ForeignKey(references = {@ForeignKeyReference(columnName = "IDShape", columnType = Long.class, foreignColumnName = "IDShape")}, saveForeignKeyModel = true)
Shape shape;
@Column
@ForeignKey(references = {@ForeignKeyReference(columnName = "Lane", columnType = Long.class, foreignColumnName = "IDLane")}, saveForeignKeyModel = true)
Lane lane; 

Edited - 08-26 10:20:29.893 19347-19347/? E/SQLiteLog﹕ (787) abort at 14 in [INSERT INTO Rafeling (IDShape, MTEXT, Lane) VALUES (?, ?, ?)]: FOREIGN KEY constraint failed

Caused by: android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787) at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method) at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782) at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788) at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86) at com.raizlabs.android.dbflow.sql.SqlUtils.insert(SqlUtils.java:314) at com.raizlabs.android.dbflow.sql.SqlUtils.save(SqlUtils.java:268) at com.raizlabs.android.dbflow.structure.ModelAdapter.save(ModelAdapter.java:54) at com.raizlabs.android.dbflow.structure.BaseModel.save(BaseModel.java:50) at com.wab.detailinspection.database.Lane.saveDames(Lane.java:173)

boxlady avatar Aug 25 '15 09:08 boxlady

@boxlady does the foreign key Shape or Lane point to a valid object? according to the sqlite doc (https://www.sqlite.org/foreignkeys.html): This example table here:

CREATE TABLE track(
  trackid     INTEGER, 
  trackname   TEXT, 
  trackartist INTEGER,
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);

"This way, the constraint is enforced by SQLite. Attempting to insert a row into the track table that does not correspond to any row in the artist table will fail, as will attempting to delete a row from the artist table when there exist dependent rows in the track table There is one exception: if the foreign key column in the track table is NULL, then no corresponding entry in the artist table is required."

So if those objects exist in the Damages model as non-null, but actually aren't saved in their corresponding tables beforehand, it'll throw an exception.

agrosner avatar Aug 26 '15 23:08 agrosner

Here is the shape class Lane class, and a example of one of the inherited classes from damages.

ModelContainer
@Table(databaseName = Database.NAME)
public class Shape extends BaseModel {
@Column
@PrimaryKey(autoincrement = true)
public int IDShape;
@Column
public float CenterPointX;
@Column
public float CenterPointY;
@Column
public float StartPointX;
@Column
public float StartPointY;
@Column
public float EndPointX;
@Column
public float EndPointY;
@Column
public float MidPointX;
@Column
public float MidPointY;



@ModelContainer
@Table(databaseName = Database.NAME)
public class Lane extends BaseModel {
@Column
@PrimaryKey(autoincrement = true)
public int IDLane;
@Column
@ForeignKey(references = {@ForeignKeyReference(columnName = "IDSection", columnType = Long.class, foreignColumnName = "IDSection")}, saveForeignKeyModel = false)
Section section;
@Column
String Name;
@Column
int NumberOfDamages;



@ModelContainer
@Table(databaseName = Database.NAME)
public class Rafeling extends Damages {

    public Rafeling() {
        super();

    }

First they are not marked as non-null. They can be null but they are not. The weird thing about it is. That when using shape and Lane as foreign keys it fails to save the damage class itself while the other two are saved. I tired just about everything to get it to work but it doesn’t seem to matter. I have a few inherited classes like rectangle which inherits from shape and some damages classes that inherit from Damages. I tried with just one of the foreign keys separately it still failed, I tried with another class that doesn’t have inheritance and it was fine. But I don’t see how that can matter though… grrr

boxlady avatar Aug 27 '15 09:08 boxlady

I’ve made a simple test for this with some of the classes (drawing parts were removed for simplicity) and posted it up on GitHub (link below) so you can see what I mean and test it for yourself.

https://github.com/boxlady/Errortest

I’ve gone through it step by step. With just the shape class as a foreign key it saves the shape, comes back and tried to save itself but fails here

long id = insertStatement.executeInsert();

In the SqlUtils.class Method

    public static <ModelClass extends Model, TableClass extends Model, AdapterClass extends     RetrievalAdapter & InternalAdapter> void insert(TableClass model, AdapterClass adapter, ModelAdapter<ModelClass> modelAdapter) {
        SQLiteStatement insertStatement = modelAdapter.getInsertStatement();
        ((InternalAdapter)adapter).bindToStatement(insertStatement, model);
        long id = insertStatement.executeInsert();
        ((InternalAdapter)adapter).updateAutoIncrement(model, id);
        notifyModelChanged(model, adapter, modelAdapter, Action.INSERT);
    }

I really don't know what I'm doing wrong....

boxlady avatar Aug 27 '15 11:08 boxlady

hey! just a stupid question, you first save Lane and Shape and then finally Damages like @agrosner asked? I mean your fks pointing to existing values in your db right? make sure the relation exists. Btw curious thing, your fkreference use Long.class so why don't you put your pk as Long?

OptimistNot avatar Aug 27 '15 15:08 OptimistNot

@OptimistNot Yes I made sure that they were saved first. I changed it to int to see if it fixed the error and then forgot to change it back...

boxlady avatar Aug 28 '15 10:08 boxlady

Your table name is Rafeling? :/ why don't you give same name as Model name?

OptimistNot avatar Aug 28 '15 10:08 OptimistNot

Yes its a Dutch name for what it is... and It inherits from damages since its a damage.

On Fri, Aug 28, 2015 at 12:43 PM, OptimistNot [email protected] wrote:

Your table name is Rafeling? :/ why don't you give same name as Model name?

— Reply to this email directly or view it on GitHub https://github.com/Raizlabs/DBFlow/issues/368#issuecomment-135735322.

Julie Buurman

boxlady avatar Aug 28 '15 10:08 boxlady

@agrosner I found the problem and I think its a bug.

I have a superclass Shape and another Superclass Damages which each have subclasses. Each damages has its own shape (rectangle circle etc.) For the Damages superclass I have Shape Shape but each damage superclass casts it to what it needs like rectangle (shape = new rectangle). This causes the error. If I move the foreign key to each subclass and change it from the generic shape to say rectangle foreign key there is no error, change it back to Shape shape - error. There is no difference between Shape and rectangle except in implication and drawing but no columns etc. change… so there shouldn't be a problem

boxlady avatar Aug 29 '15 08:08 boxlady