ALTER TABLE tiles RENAME COLUMN zoom_level TO tile_zoom;

ALTER TABLE tiles ADD COLUMN tile_x INT;
ALTER TABLE tiles ADD COLUMN tile_y INT;

UPDATE tiles SET
    tile_x = FLOOR((longitude + 180.0) / 360.0 * POWER(2, tile_zoom))::INT,
    tile_y = FLOOR((1.0 - LN(TAN(RADIANS(latitude)) + 1.0 / COS(RADIANS(latitude))) / PI()) / 2.0 * POWER(2, tile_zoom))::INT;

ALTER TABLE tiles ALTER COLUMN tile_x SET NOT NULL;
ALTER TABLE tiles ALTER COLUMN tile_y SET NOT NULL;

DROP INDEX IF EXISTS idx_tiles_zoom;
DROP INDEX IF EXISTS idx_tiles_unique_location;

CREATE INDEX idx_tiles_zoom ON tiles(tile_zoom);
CREATE UNIQUE INDEX idx_tiles_unique_location ON tiles(latitude, longitude, tile_zoom, tile_size_meters, version);
CREATE INDEX idx_tiles_coordinates ON tiles(tile_zoom, tile_x, tile_y, version);
