CREATE TABLE `ACCOUNTS` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20),
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

CREATE TABLE `TRANSACTION` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `TDATE` date NOT NULL,
  `ACCOUNTID` integer NOT NULL,
  `MEMO` varchar(50) NOT NULL,
  `COUNTRY` char(2),
  `OUTFLOW` decimal(20,2),
  `INFLOW` decimal(12,2),
  `OWNERID` integer,
  `INSTALLMENT_NR` integer,
  `INSTALLMENT_TT` integer,
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

CREATE TABLE `PAYEE` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20),
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

CREATE TABLE `OWNER` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20),
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

CREATE TABLE `CATEGORY` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20),
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

CREATE TABLE `SUBCATEGORY` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `CATEGORYID` integer,
  `NAME` varchar(20),
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

CREATE TABLE `CATEGORIZED_TRANSACTIONS` (
  `ID` integer PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `ACCOUNTID` integer,
  `TRANSACTIONID` integer,
  `PAYEEID` integer,
  `CATEGORYID` integer,
  `SUBCATEGORYID` integer,
  `CREATED` datetime NOT NULL,
  `UPDATED` datetime
);

ALTER TABLE `ACCOUNTS` ADD FOREIGN KEY (`ID`) REFERENCES `TRANSACTION` (`ACCOUNTID`);

ALTER TABLE `OWNER` ADD FOREIGN KEY (`ID`) REFERENCES `TRANSACTION` (`OWNERID`);

ALTER TABLE `CATEGORY` ADD FOREIGN KEY (`ID`) REFERENCES `SUBCATEGORY` (`CATEGORYID`);

ALTER TABLE `TRANSACTION` ADD FOREIGN KEY (`ID`) REFERENCES `CATEGORIZED_TRANSACTIONS` (`TRANSACTIONID`);

ALTER TABLE `CATEGORY` ADD FOREIGN KEY (`ID`) REFERENCES `CATEGORIZED_TRANSACTIONS` (`CATEGORYID`);

ALTER TABLE `SUBCATEGORY` ADD FOREIGN KEY (`ID`) REFERENCES `CATEGORIZED_TRANSACTIONS` (`SUBCATEGORYID`);

ALTER TABLE `PAYEE` ADD FOREIGN KEY (`ID`) REFERENCES `CATEGORIZED_TRANSACTIONS` (`PAYEEID`);
