Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foreign Key Constraint Error When Inserting Related Tables (Supabase) #479

Open
juanmigdr opened this issue Feb 22, 2025 · 0 comments
Open

Comments

@juanmigdr
Copy link

Hello, thank you so so much for the library, it is amazing! 🚀

I just have one 'issue' that happens when dealing with two tables that depend on each other (using the Supabase plugin). Let's say you have exams and chapters. An exam can have multiple chapters, and upon exam creation, I ask the user how many chapters they want to add for that exam. When the number of chapters is submitted, the exam is created, and just after that, the chapters containing the FK to that exam are created.

The problem is that when I do this, I get errors when saving, since at the point of adding the chapter, it seems like the exam is still being created. I am solving it by having infinite retries, which fixes the issue, but it would be nice for LegendState to handle this in a better way by waiting for one insert to be completed before starting the next one.

Here is the saving code:

export const addExam = (numberOfChapters: number) => {
  if (numberOfChapters > 0) {
    batch(() => {
      const examId = generateId();
      exams$[examId].assign({
        id: examId,
      });

      for (let index = 0; index < numberOfChapters; index++) {
        const chapterId = generateId();
        chapters$[chapterId].assign({
          id: chapterId,
          exam_row_id: examId,
        });
      }
    });
  }
};

Error received:

[Error: insert or update on table "chapters" violates foreign key constraint "fk_exam"]

It seems like the batch operation does not ensure the order of execution when writing to the database, causing FK constraints to fail. Would it be possible to implement a way for LegendState to ensure that the exam insert completes before inserting dependent chapters?

Thank you again, this library rocks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant