-- to load the geoip data:
-- psql -U postgres -d jam -f GeoIP-20140304.sql
-- psql -U postgres -d jam -f supplement.sql

DELETE FROM jamcompany;
ALTER SEQUENCE jamcompany_coid_seq RESTART WITH 1;
INSERT INTO jamcompany (company) SELECT DISTINCT company FROM geoipisp ORDER BY company;

DELETE FROM jamisp;
INSERT INTO jamisp (beginip, endip, coid) SELECT x.beginip, x.endip, y.coid FROM geoipisp x, jamcompany y WHERE x.company = y.company;

ALTER TABLE geoiplocations DROP COLUMN geog;
ALTER TABLE geoiplocations ADD COLUMN geog geography(point, 4326);
UPDATE geoiplocations SET geog = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)::geography;
CREATE INDEX geoiplocations_geog_gix ON geoiplocations USING GIST (geog);

ALTER TABLE geoipblocks DROP COLUMN geom;
ALTER TABLE geoipblocks ADD COLUMN geom geometry(polygon);
-- DROP INDEX geoipblocks_geom_gix;
UPDATE geoipblocks SET geom = ST_MakeEnvelope(beginip, -1, endip, 1);
CREATE INDEX geoipblocks_geom_gix ON geoipblocks USING GIST (geom);

ALTER TABLE jamisp DROP COLUMN geom;
ALTER TABLE jamisp ADD COLUMN geom geometry(polygon);
UPDATE jamisp SET geom = ST_MakeEnvelope(beginip, -1, endip, 1);
CREATE INDEX jamisp_geom_gix ON jamisp USING GIST (geom);

DELETE FROM cities;
INSERT INTO cities (city, region, countrycode) SELECT DISTINCT city, region, countrycode FROM geoiplocations WHERE length(city) > 0 AND length(countrycode) > 0;
DELETE FROM regions;
INSERT INTO regions (region, countrycode) SELECT DISTINCT region, countrycode FROM cities;
DELETE FROM countries;
INSERT INTO countries (countrycode) SELECT DISTINCT countrycode FROM regions;


VACUUM ANALYSE;
