
CREATE TABLE country (
    alpha2 TEXT    NOT NULL CHECK(LENGTH(alpha2) = 2),
    alpha3 TEXT    NOT NULL CHECK(LENGTH(alpha3) = 3),
    num    INTEGER NOT NULL CHECK(num >= 0),
    name   TEXT    NOT NULL,

    is_visible INTEGER NOT NULL CHECK(is_visible = TRUE OR is_visible = FALSE) DEFAULT TRUE,

    CONSTRAINT pk_country PRIMARY KEY (alpha2),
    CONSTRAINT sk_country_alpha3 UNIQUE (alpha3),
    CONSTRAINT sk_country_numeric UNIQUE (num),
    CONSTRAINT sk_country_name UNIQUE (name)
) STRICT;

CREATE TABLE AT_bundesland (
    id     INTEGER NOT NULL CHECK(id >= 0),
    short1 TEXT    NOT NULL,
    short2 TEXT,
    name   TEXT    NOT NULL,

    CONSTRAINT pk_AT_bundesland PRIMARY KEY (id),
    CONSTRAINT sk_AT_bundesland_short1 UNIQUE (short1),
    CONSTRAINT sk_AT_bundesland_short2 UNIQUE (short2),
    CONSTRAINT sk_AT_bundesland_name UNIQUE (name)
) STRICT;

CREATE TABLE AT_gemeinde (
    gkz     INTEGER NOT NULL CHECK(gkz >= 10000 AND gkz <= 99999),
    land_id INTEGER NOT NULL CHECK(land_id = gkz / 10000),
    name    TEXT    NOT NULL,

    CONSTRAINT pk_AT_gemeinde PRIMARY KEY (gkz),
    CONSTRAINT fk_AT_gemeinde_AT_bundesland FOREIGN KEY (land_id) REFERENCES AT_bundesland (id)
) STRICT;

CREATE TABLE AT_ort (
    okz  INTEGER NOT NULL CHECK(okz > 0),
    gkz  INTEGER NOT NULL,
    name TEXT    NOT NULL,

    CONSTRAINT pk_AT_ort PRIMARY KEY (okz),
    CONSTRAINT fk_AT_ort_AT_gemeinde FOREIGN KEY (gkz) REFERENCES AT_gemeinde (gkz)
) STRICT;

CREATE TABLE AT_plz (
    plz  INTEGER NOT NULL CHECK(plz >= 1000 AND plz <= 9999),
    okz  INTEGER NOT NULL,
    name TEXT    NOT NULL,

    CONSTRAINT pk_AT_plz PRIMARY KEY (plz, okz),
    CONSTRAINT fk_AT_plz_AT_ort FOREIGN KEY (okz) REFERENCES AT_ort (okz)
) STRICT;


INSERT INTO country VALUES
('AT', 'AUT',  40, 'Österreich',  TRUE),
('DE', 'DEU', 276, 'Deutschland', FALSE),
('CZ', 'CZE', 203, 'Tschechien',  FALSE),
('HU', 'HUN', 348, 'Ungarn',      FALSE),
('SK', 'SVK', 703, 'Slowakei',    FALSE);

INSERT INTO AT_bundesland VALUES
(1, 'B',  'Bgld.', 'Burgenland'),
(2, 'K',  'Ktn.',  'Kärnten'),
(3, 'N',  'NÖ',    'Niederösterreich'),
(4, 'O',  'OÖ',    'Oberösterreich'),
(5, 'S',  'Sbg.',  'Salzburg'),
(6, 'St', 'Stmk.', 'Steiermark'),
(7, 'T',   NULL,   'Tirol'),
(8, 'V',  'Vbg.',  'Vorarlberg'),
(9, 'W',   NULL,   'Wien');
