connect 'jdbc:derby:workstyleDB;user=workstyle;password=hogehoge';
CREATE TABLE TASK_FILE_RELATION (
       RELATION_ID INT NOT NULL
     , TASK_ID INT NOT NULL
     , FILE_ID INT NOT NULL
     , PRIMARY KEY (RELATION_ID)
);

CREATE TABLE FILE (
       FILE_ID INT NOT NULL
     , NAME VARCHAR(256) NOT NULL
     , PATH VARCHAR(256)
     , PRIMARY KEY (FILE_ID)
);

INSERT INTO ID_TABLE (ID_TABLE_ID, TABLE_NAME, NEXT_ID, QUANTITY) VALUES (5, 'TASK_FILE_RELATION', 2001, 1);
INSERT INTO ID_TABLE (ID_TABLE_ID, TABLE_NAME, NEXT_ID, QUANTITY) VALUES (6, 'FILE', 2001, 1);

INSERT INTO TASK_FILE_RELATION (RELATION_ID, TASK_ID, FILE_ID)
SELECT FILE_ID, TASK_ID, FILE_ID
FROM ATTACHED_FILE;

INSERT INTO FILE(FILE_ID, NAME, PATH)
SELECT FILE_ID, NAME, PATH
FROM ATTACHED_FILE;

UPDATE ID_TABLE 
SET NEXT_ID = (
	SELECT CASE WHEN MAX(RELATION_ID) IS NULL THEN 2001 ELSE MAX(RELATION_ID)+1 END
	FROM TASK_FILE_RELATION
) WHERE ID_TABLE_ID = 5;

UPDATE ID_TABLE 
SET NEXT_ID = (
	SELECT CASE WHEN MAX(FILE_ID) IS NULL THEN 2001 ELSE MAX(FILE_ID)+1 END
	FROM FILE
) WHERE ID_TABLE_ID = 6;

ALTER TABLE TASK_FILE_RELATION
  ADD CONSTRAINT FK_TASK_FILE_RELATION_1
      FOREIGN KEY (TASK_ID)
      REFERENCES TASK (TASK_ID);

ALTER TABLE TASK_FILE_RELATION
  ADD CONSTRAINT FK_TASK_FILE_RELATION_2
      FOREIGN KEY (FILE_ID)
      REFERENCES FILE (FILE_ID);

DROP TABLE ATTACHED_FILE;

CREATE VIEW ATTACHED_FILE AS
SELECT F.FILE_ID, F.NAME, F.PATH, R.TASK_ID
FROM FILE F, TASK_FILE_RELATION R
WHERE F.FILE_ID = R.FILE_ID;