DROP TABLE IF EXISTS notes;
DROP TABLE IF EXISTS note_relationships;
DROP TABLE IF EXISTS note_kasten_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,
    location INTEGER NOT NULL,
    FOREIGN KEY (id) REFERENCES notes (id) ON DELETE CASCADE
);

-- This table represents the forest of data relating a kasten 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 kasten.
--
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,
	CHECK (note_id <> parent_id)
);

-- This table represents the graph of data relating notes to kastens.
--
CREATE TABLE note_kasten_relationships (
    note_id TEXT NOT NULL,
    kasten_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 (kasten_id) REFERENCES notes (id) ON DELETE CASCADE,
	CHECK (note_id <> kasten_id)
);

