--- magnets

ALTER TABLE magnets
    RENAME TO magnets_old;

CREATE TABLE magnets
(
    id           INTEGER PRIMARY KEY NOT NULL,
    title        VARCHAR             NOT NULL,
    submitter    VARCHAR             NOT NULL,
    subreddit    VARCHAR             NOT NULL,
    link         VARCHAR             NOT NULL,
    published_at DATETIME            NOT NULL,
    imdb_id      VARCHAR
);

INSERT INTO magnets (id, title, submitter, subreddit, link, published_at, imdb_id)
SELECT id, title, submitter, subreddit, link, published_at, imdb_id
FROM magnets_old;

DROP TABLE magnets_old;

CREATE UNIQUE INDEX magnets_unique_link
    ON magnets (link);

--- bitmagnet_processed

ALTER TABLE bitmagnet_processed
    RENAME TO bitmagnet_processed_old;

CREATE TABLE bitmagnet_processed
(
    id           INTEGER PRIMARY KEY NOT NULL,
    magnet_id    INTEGER             NOT NULL,
    processed_at DATETIME            NOT NULL,
    FOREIGN KEY (magnet_id) REFERENCES magnets (id)
);

INSERT INTO bitmagnet_processed (id, magnet_id, processed_at)
SELECT id, magnet_id, processed_at
FROM bitmagnet_processed_old;

DROP TABLE bitmagnet_processed_old;

CREATE INDEX bitmagnet_processed_magnet_id ON bitmagnet_processed (magnet_id);

--- transmission_processed

ALTER TABLE transmission_processed
    RENAME TO transmission_processed_old;

CREATE TABLE transmission_processed
(
    id           INTEGER PRIMARY KEY NOT NULL,
    magnet_id    INTEGER             NOT NULL,
    processed_at DATETIME            NOT NULL,
    FOREIGN KEY (magnet_id) REFERENCES magnets (id)
);

INSERT INTO transmission_processed (id, magnet_id, processed_at)
SELECT id, magnet_id, processed_at
FROM transmission_processed_old;

DROP TABLE transmission_processed_old;

CREATE INDEX transmission_processed_magnet_id ON transmission_processed (magnet_id);