Skip to content

Instantly share code, notes, and snippets.

@yawaramin
Created October 27, 2024 06:32
Show Gist options
  • Save yawaramin/d15d79515951ff6b2847cbab7466594b to your computer and use it in GitHub Desktop.
Save yawaramin/d15d79515951ff6b2847cbab7466594b to your computer and use it in GitHub Desktop.
SQLite database schema for a notes app with fulltext search and maintenance triggers
create table if not exists note (
id integer not null primary key autoincrement,
created_at timestamp not null default current_timestamp,
modified_at timestamp not null default current_timestamp,
starred_at timestamp,
title varchar(1024) not null,
content text not null default ''
);
create table if not exists note_tag (
note_id integer not null,
tag varchar(512) not null,
tagged_at timestamp not null default current_timestamp,
constraint fk_note_id foreign key(note_id) references note(id) on delete cascade,
constraint uk_note_id_tag unique(note_id, tag)
);
create table if not exists note_link (
from_note_id integer not null,
to_note_id integer not null check (from_note_id < to_note_id),
linked_at timestamp not null default current_timestamp,
constraint fk_from_note_id foreign key(from_note_id) references note(id) on delete cascade,
constraint fk_to_note_id foreign key(to_note_id) references note(id) on delete cascade,
constraint uk_note_link unique(from_note_id, to_note_id)
);
create virtual table if not exists note_search using fts5(
title,
content,
tokenize = 'porter unicode61 remove_diacritics 1',
content = 'note',
content_rowid = 'id',
columnsize = 0
);
create trigger if not exists note_search_ins after insert on note begin
insert into note_search (rowid, title, content)
values (new.id, new.title, new.content);
end;
create trigger if not exists note_search_del after delete on note begin
insert into note_search (note_search, rowid, title, content)
values ('delete', old.id, old.title, old.content);
end;
create trigger if not exists note_search_upd after update on note begin
insert into note_search (note_search, rowid, title, content)
values ('delete', old.id, old.title, old.content);
insert into note_search (rowid, title, content)
values (new.id, new.title, new.content);
end;
create trigger if not exists index_note_delete before delete on note when old.id = 1 begin
select raise(fail, 'cannot delete index note');
end;
create trigger if not exists index_note_update before update on note when old.id = 1 and new.id <> 1 begin
select raise(fail, 'cannot change index note ID');
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment