ALTER TABLE parkings_secondary NO INHERIT parkings;
ALTER TABLE parkings ADD COLUMN "tariff_id" VARCHAR(50) NULL;
ALTER TABLE parkings_secondary ADD COLUMN "tariff_id" VARCHAR(50) NULL;
ALTER TABLE parkings_secondary INHERIT parkings;
ALTER TABLE parking_machines ADD COLUMN "tariff_id" VARCHAR(255) NULL;

UPDATE parkings SET tariff_id = ppt.tariff_id
FROM parking_tariffs_relation ppt
WHERE parkings.id = ppt.parking_id;

UPDATE parking_machines SET tariff_id = ppt.tariff_id
FROM parking_tariffs_relation ppt
WHERE parking_machines.id = ppt.parking_id;

DROP TABLE parking_tariffs_relation;

DROP VIEW v_parkings_filtered;
CREATE VIEW v_parkings_filtered AS
WITH parkings_loc AS (
    SELECT
        p.id AS id,
        pl.sanitized_locations AS location
    FROM
        ONLY parkings p
    INNER JOIN parkings_location pl
        ON p.source = pl.source AND p.source_id = pl.source_id
    WHERE
        p.source IN (
            SELECT
                source
            FROM
                parking_sources ps
            WHERE
                ps.api_v3_allowed
        )
)
SELECT
    *
FROM
    ONLY parkings p
UNION ALL
SELECT
    *
FROM
    ONLY parkings_secondary ps
WHERE
    ps.id NOT IN (
        SELECT
            DISTINCT ps.id
        FROM
            parkings_loc plo
        INNER JOIN parkings_secondary ps
           ON ST_Intersects(plo.location, ps.sanitized_location)
    );

drop view v_parking_machines_filtered;
create view v_parking_machines_filtered as
with parking_machines_primary as (
    select * from parking_machines where source != 'osm'
), parking_machines_secondary as (
    select * from parking_machines where source = 'osm'
)
select * from parking_machines_primary p1
union all
select * from parking_machines_secondary p2
where p2.id not in (
    select distinct p2.id
    from parking_machines_primary p1
    inner join parking_machines_secondary p2 ON ST_Distance(p1.location::geography, p2.location::geography) < 15
);
