-- @block
-- Create tables
-- Create 'sub' table
CREATE TABLE sub (
    adsh        VARCHAR(255) PRIMARY KEY,
    cik         BIGINT,
    name        VARCHAR(255),
    sic         DOUBLE PRECISION,
    countryba   VARCHAR(100),
    stprba      VARCHAR(100),
    cityba      VARCHAR(255),
    zipba       VARCHAR(50),
    bas1        VARCHAR(255),
    bas2        VARCHAR(255),
    baph        VARCHAR(255),
    countryma   VARCHAR(100),
    stprma      VARCHAR(100),
    cityma      VARCHAR(255),
    zipma       VARCHAR(50),
    mas1        VARCHAR(255),
    mas2        VARCHAR(255),
    countryinc  VARCHAR(100),
    stprinc     VARCHAR(100),
    ein         BIGINT,
    former      VARCHAR(255),
    changed     DOUBLE PRECISION,
    afs         VARCHAR(255),
    wksi        BIGINT,
    fye         DOUBLE PRECISION,
    form        VARCHAR(50),
    period      DOUBLE PRECISION,
    fy          DOUBLE PRECISION,
    fp          VARCHAR(50),
    filed       BIGINT,
    accepted    VARCHAR(255),
    prevrpt     BIGINT,
    detail      BIGINT,
    instance    VARCHAR(255),
    nciks       BIGINT,
    aciks       VARCHAR(255)
);

-- Create 'tag' table
CREATE TABLE tag (
    tag       VARCHAR(255),
    version   VARCHAR(255),
    custom    BIGINT,
    abstract  BIGINT,
    datatype  VARCHAR(255),
    iord      VARCHAR(50),
    crdr      VARCHAR(50),
    tlabel    VARCHAR(255),
    doc       TEXT,
    PRIMARY KEY (tag, version)
);

-- Create 'num' table
CREATE TABLE num (
    adsh      VARCHAR(255),
    tag       VARCHAR(255),
    version   VARCHAR(255),
    coreg     VARCHAR(255),
    ddate     BIGINT,
    qtrs      BIGINT,
    uom       VARCHAR(50),
    value     DOUBLE PRECISION,
    footnote  TEXT,
    PRIMARY KEY (adsh, tag, version, ddate),
    FOREIGN KEY (adsh) REFERENCES sub(adsh),
    FOREIGN KEY (tag, version) REFERENCES tag(tag, version)
);

-- Create 'pre' table
CREATE TABLE pre (
    adsh      VARCHAR(255),
    report    BIGINT,
    line      BIGINT,
    stmt      VARCHAR(255),
    inpth     BIGINT,
    rfile     VARCHAR(255),
    tag       VARCHAR(255),
    version   VARCHAR(255),
    plabel    VARCHAR(255),
    negating  BIGINT,
    PRIMARY KEY (adsh, report, line),
    FOREIGN KEY (adsh) REFERENCES sub(adsh),
    FOREIGN KEY (tag, version) REFERENCES tag(tag, version)
);
-- @end

-- @block
-- Reset db
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS num;
DROP TABLE IF EXISTS pre;
DROP TABLE IF EXISTS sub;
DROP TABLE IF EXISTS tag;
SET FOREIGN_KEY_CHECKS = 1;
-- @end