DROP TRIGGER IF EXISTS on_delete_feed_trigger;
DROP TRIGGER IF EXISTS on_delete_category_trigger;

PRAGMA legacy_alter_table=ON;

ALTER TABLE feeds ADD sort_index INTEGER default NULL;
ALTER TABLE categories ADD sort_index INTEGER default NULL;
ALTER TABLE categories ADD parent_id TEXT NOT NULL default "NewsFlash.Toplevel";

DROP TABLE category_mapping;

ALTER TABLE feed_mapping RENAME TO _feed_mapping_old;

CREATE TABLE feed_mapping (
	feed_id TEXT NOT NULL REFERENCES feeds(feed_id),
	category_id TEXT NOT NULL REFERENCES categories(category_id),
	PRIMARY KEY (feed_id, category_id)
);

INSERT INTO feed_mapping (feed_id, category_id)
  SELECT feed_id, category_id FROM _feed_mapping_old;

DROP TABLE _feed_mapping_old;

PRAGMA legacy_alter_table=OFF;

CREATE TRIGGER on_delete_feed_trigger
	BEFORE DELETE ON feeds
	BEGIN
		DELETE FROM feed_mapping WHERE feed_mapping.feed_id=OLD.feed_id;
		DELETE FROM articles WHERE articles.feed_id=OLD.feed_id AND articles.marked=1;
		DELETE FROM fav_icons WHERE fav_icons.feed_id=OLD.feed_id;
	END;

CREATE TRIGGER on_delete_category_trigger
	BEFORE DELETE ON categories
	BEGIN
		DELETE FROM feed_mapping WHERE feed_mapping.category_id=OLD.category_id;
	END;