BEGIN TRANSACTION;
CREATE TABLE source_files (
	id		INTEGER PRIMARY KEY,
	filename	TEXT	UNIQUE NOT NULL,
	size		INTEGER NOT NULL,
	hash		TEXT,
	last_change	INTEGER NOT NULL DEFAULT (strftime('%s','now')),
	last_seen	INTEGER	NOT NULL DEFAULT (strftime('%s','now'))
);
CREATE TABLE destinations (
	id		INTEGER PRIMARY KEY,
	name		TEXT	UNIQUE NOT NULL
);
CREATE TABLE destination_files (
	id		INTEGER PRIMARY KEY,
	filename	TEXT,
	last_change	INTEGER	NOT NULL DEFAULT (strftime('%s','now')),
	source_file_id	INTEGER,
	destination_id	INTEGER,
	FOREIGN KEY	(source_file_id)	REFERENCES source_files(id),
	FOREIGN KEY	(destination_id)	REFERENCES destinations(id)
);

CREATE INDEX sourcefiles_by_name ON source_files (filename,id);

CREATE TRIGGER create_destinations AFTER INSERT ON source_files
BEGIN
	INSERT INTO destination_files (source_file_id,destination_id)
		SELECT source_files.id,destinations.id FROM source_files
	INNER JOIN destinations
		WHERE source_files.id=new.id;
END;
CREATE TRIGGER delete_destinations_files AFTER DELETE ON source_files
BEGIN
	UPDATE destination_files SET source_file_id=NULL WHERE source_file_id=old.id;
END;

COMMIT;
