SQLite Forum

Main Topic and Non Main Topics (Was: Topic and subtopic)
Login
Ah, ok.  That makes more sense.  So lets have tables that look like this:

```
create table Topic
(
  id     integer primary key,
  name   text collate nocase unique
);
create table Data
(
  id          integer primary key,
  MainTopicID integer not null references Topic(id)
);
create index DataTopic on Data(mainTopicID);
create table AdditionalTopics
(
  DataID     integer not null references Data(id),
  SubTopicID integer not null references Topic(id),
  PRIMARY KEY (DataID, SubTopicID),
  UNIQUE (SubTopicID, DataID)
) WITHOUT ROWID;
```

All these enforce the basics.  You need to make sure foreign key enforcement is turned on for every connection by issuing the command `pragma foreign_keys=1` to each and every connection without fail.  If you do not do this, then your foreign key constraints will not be enforced and you can "muck up" your referential integrity (or you can compile your application with foreign keys turned on by default).

Then you need an "insert trigger" to stop you from inserting bad data, and update triggers to stop you from updating bad data, and delete triggers to stop you from creating inconsistencies.

```
create trigger ATI before insert on AdditionalTopics
begin
  select raise(ABORT, 'Cannot set MainTopic as SubTopic')
   where new.SubTopicID == (
                            select MainTopicID 
                              from Data 
                             where id == new.DataID
                           );
end;
create trigger ATU before update on AdditionalTopics
begin
  select raise(ABORT, 'Cannot set MainTopic as SubTopic')
   where new.SubTopicID == (
                            select MainTopicID 
                              from Data 
                             where id == new.DataID
                           );
end;
create trigger TD before delete on Topic
begin
  select raise(ABORT, 'Cannot Delete Topic that is in Use')
    where exists (
                  select 1
                    from AdditionalTopics
                   where SubTopicID == old.id
                 );
end;
create trigger TU before update of id on Topic
begin
  select raise(ABORT, 'Cannot Renumber Topic that is in Use')
    where exists (
                  select 1
                    from AdditionalTopics
                   where SubTopicID == old.id
                 );
end;
```

** Edited to fix typographic errors **  
** Edited again because the update trigger should fire always **