OSM2psql is a handy tool for importing OSM data into a PostgreSQL database. Though, the created database cannot be converted back to a PBF file. For example, to use a routing algorithm (e.g., Graphhopper) with a custom weighting, the PBF format is needed. For this, I used Osmosis.
For the task of editing a PBF file and re-creating a new PBF file I used the following process:
For Mac, Homebrew can be used:
brew install postgresql
brew install postgis
brew install osmosis
brew services start postgresql@14
createdb myOsmDB #(in command line - not psql shell!)
Geofabrik provides a great free download service for OSM PBF files.
The following steps are also described in the Osmosis PostGIS Setup description
4. Download osmosis setup script
psql -d myOsmDB 'CREATE EXTENSION postgis; CREATE EXTENSION hstore;'
psql -d myOsmDB -f osmosis-0.48.3/script/pgsnapshot_schema_0.6.sql
osmosis --read-pbf YOUR_PBF_FILE_NAME.osm.pbf --log-progress --write-pgsql database=myOsmDB
Using SQL (for example via a user interface like Dbeaver), edit the database as needed.
All OSM tags are stored in a single column 'tags' using the hstore
datatype.
-- create a new custom attribute
alter table ways
add column myNewAttribute numeric;
-- set attribute values as needed
-- store attribute in the osm hstore tag list
update ways
set tags = tags || hstore('myNewAttribute', myNewAttribute::text)
where tags -> 'highway' <> ''; -- for example, update all ways that are highways,
-- i.e., the tag highway is not empty
-- drop custom column afterwards, as it is not needed anymore
alter table ways
drop column myNewAttribute;
osmosis --read-pgsql database=myOsmDB --dataset-dump --write-pbf file=YOUR_CUSTOM_PBF_FILE_NAME.osm.pbf