Search code examples
hsqldblibreoffice-base

Create field constraint based on another table field in LibreOffice Base


I have 3 tables, "Courses"(id, start_date), "Subscriptions"(id, assistant_id, course_id, date) and "Assistants"(id, registration_date).

Subscriptions reference Courses and Assistants with foreign keys as you see.

I need to add CHECK constraint that will prevent to create Subscription record if referenced Courses.start_date is older than referenced Assistants.registration_date. Is there a way to do this in Libre Base?

Table organization could not be changed.


Solution

  • Such a CHECK constraint cannot be created with the default engine. From the HSQLDB 1.8 documentation:

    ALTER TABLE <tablename> ADD [CONSTRAINT <constraintname>] CHECK (<search condition>);

    Adds a check constraint to the table. In the current version, a check constraint can reference only the row being inserted or updated.

    This means that commands like the following from TestSelfCheckConstraints.txt produce an error:

    /*e*/CREATE TABLE TC6(A CHAR, B CHAR, C CHAR, D INT, CHECK(A IN (SELECT A FROM TC5)));

    So, to perform such a check, you will have to verify it ahead of time (or afterwards) using a query. This could be done for a form by adding a macro in the Events tab. See this post for ideas: https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=21414.

    The default engine is rather old, so for such complex requirements it may be better to set up LibreOffice Base to use a different database engine. For example using MySQL, it is possible to set up a stored procedure trigger to do this kind of checking. See CHECK constraint in MySQL is not working.