[FIXED] SQLite variable CHECK constraint

Issue

I have table with chromosomes (objects that have length) and table with regions (for example genes) on the chromosomes (objects that have range defined as two integers - position start and position end). I would like to forbid inserting into database regions with coordinates greater than length of particular chromosome.

Is it possible in SQLite? If not is it possible in any other SQL system (preferably free)?

DROP TABLE IF EXISTS chromosomes;
CREATE TABLE chromosomes
  (
     chromosome_id INTEGER UNIQUE NOT NULL CHECK(TYPEOF(chromosome_id) = 'integer'),
     name          VARCHAR UNIQUE NOT NULL CHECK(TYPEOF(name) = 'text'),
     length        INTEGER NOT NULL CHECK(TYPEOF(length) = 'integer' AND length > 0),
     PRIMARY KEY (chromosome_id)
  );


DROP TABLE IF EXISTS genes;
CREATE TABLE genes
  (
     gene_id           INTEGER UNIQUE NOT NULL CHECK(TYPEOF(gene_id) = 'integer'),
     symbol            VARCHAR NOT NULL CHECK(TYPEOF(symbol) = 'text'),
     refseq_id         VARCHAR NOT NULL CHECK(TYPEOF(refseq_id) = 'text'),
     chromosome_id     INTEGER NOT NULL CHECK(TYPEOF(chromosome_id) = 'integer'),
     start             INTEGER NOT NULL CHECK(TYPEOF(start) = 'integer' AND start > 0 AND start < end),
     end               INTEGER NOT NULL CHECK(TYPEOF(end) = 'integer' AND end > 0 AND end > start),
     external_db_link  VARCHAR NOT NULL CHECK(TYPEOF(external_db_link) = 'text'),
     PRIMARY KEY (gene_id)                   
     FOREIGN KEY (chromosome_id) REFERENCES chromosomes(chromosome_id)
  );

Solution

This type of constraint is not easily available in any database. In general, this would be handled using a trigger. The problem is that it is a constraint between two tables, but it does not use equality.

Triggers are available in SQLite as well as other databases.

One work-around is a check constraint using a user-defined function. The function can do the lookup into the chromosomes table and be used in a check constraint. SQLite doesn't really have user-defined functions. One database that supports this is Postgres.

Another option is to wrap all data modifications in stored procedures (this tends to be the way that I design systems). Then the stored procedure can do all the checks that are needed.



Answered By - Gordon Linoff
Answer Checked By - Robin (sql.easybugfix Admin)

Related Posts

Post a Comment