notesmachine/server/nm-store/src/store/sql/initialize_database.sql

59 lines
2.0 KiB
SQL

DROP TABLE IF EXISTS notes;
DROP TABLE IF EXISTS note_relationships;
DROP TABLE IF EXISTS note_page_relationships;
DROP TABLE IF EXISTS favorites;
CREATE TABLE notes (
id TEXT NOT NULL PRIMARY KEY,
content TEXT NOT NULL,
kind TEXT NOT NULL,
creation_date DATETIME NOT NULL,
updated_date DATETIME NOT NULL,
lastview_date DATETIME NOT NULL,
deleted_date DATETIME NULL
);
CREATE INDEX note_ids ON notes (id);
CREATE TABLE favorites (
id TEXT NOT NULL UNIQUE,
location INTEGER NOT NULL,
FOREIGN KEY (id) REFERENCES notes (id) ON DELETE CASCADE
);
-- This table represents the forest of data relating a page to its
-- collections of notes. The root is itself "a note," but the content
-- of that note will always be just the title of the page.
--
CREATE TABLE note_relationships (
note_id TEXT NOT NULL,
parent_id TEXT NOT NULL,
location INTEGER NOT NULL,
kind TEXT NOT NULL,
-- If either note disappears, we want all the edges to disappear as well.
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE CASCADE,
FOREIGN KEY (parent_id) REFERENCES notes (id) ON DELETE CASCADE,
UNIQUE (note_id, parent_id),
CHECK (note_id <> parent_id)
);
-- This table represents the graph of data relating notes to pages.
--
CREATE TABLE note_page_relationships (
note_id TEXT NOT NULL,
page_id TEXT NOT NULL,
kind TEXT NOT NULL,
-- If either note disappears, we want all the edges to disappear as well.
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE CASCADE,
FOREIGN KEY (page_id) REFERENCES notes (id) ON DELETE CASCADE,
UNIQUE (note_id, page_id),
CHECK (note_id <> page_id)
);
-- A fabulous constraint. This index prevents us from saying that
-- if a note points to a page, the page may not point to a
-- note. Now, it's absolutely required that a page_id point to
-- a PageType note; the content should be a title only.
CREATE UNIQUE INDEX note_page_unique_idx
ON note_page_relationships (MIN(note_id, page_id), MAX(note_id, page_id));