Frage

I have a database for saving various forms. I have a table of forms:

CREATE SEQUENCE seq_formtype;

CREATE TABLE formtype (
    id_ft integer NOT NULL DEFAULT nextval('seq_formtype'),
    name text
);

I have a table of different input fields in the form:

CREATE SEQUENCE seq_formstruct;

CREATE TABLE formstruct (
    id_fs integer NOT NULL DEFAULT nextval('seq_formstruct'),
    id_ft integer NOT NULL,
    name text,
    id_fstype text NOT NULL
);

And finally, I have a table in which I store the results from the form for each trial.

CREATE TABLE results (
    id_trial integer NOT NULL,
    id_fs integer NOT NULL,
    res_value text
);

When I add the result, I want to check whether all inputs from formstruct were inserted - that means that there will be for each entry in formstruct where formtype = typ_trialu (pseudocode) an entry in results.

Now I am not even sure how to check it or where to start. My idea was to create a trigger that would check the consistency after insertion to results (ie after insertion of all inputfield results).

War es hilfreich?

Lösung

It could be done with trigger(s) after insert statements.

CREATE TRIGGER check_form_types_trigger
    AFTER INSERT ON results
    FOR EACH STATEMENT
    EXECUTE PROCEDURE check_form_types_function();

And, in check_form_types_function (which should be plpgsql) you can raise an exception if your data (as a whole) are not consistent.

But, in the other hand, if you do this, you literally won't be able to insert partial data into results; you will be able to insert only whole data, with a single insert statement. And if you really care about consistency, you should do this check after each update & delete statements too.

Notes:

  • names like fs, ft, fstype are terrible, consider rename your columns.
  • consider using SERIALs (instead of just manually set up sequences)
  • consider using foreign keys
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top