node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Determining geometry type ID

Open asindl opened this issue 2 years ago • 2 comments

I am running several SELECT * requests on database with some geospatial data. Geometry fields are returned as WKB (e.g. "0101000020E6100000F6E0795A1CEB53C0F118BC73D99A4040"). I know, there is libs to parse the WKB into something more usable (even though the best solution would be to already receive the data e.g. in geoJSON), but first of all, I need to determine, that a certain field is a geometry type. How would I best do that using the library?

asindl avatar Feb 22 '24 17:02 asindl

Relying the OID might not be the best approach. The OID of the geometry type can be different in every database (restoring a database dump can change it too).

You can query the OID on the current connection with something like this: SELECT oid FROM pg_type WHERE typname = 'geometry'.

What you do with it depends on your setup. If you only have the single database, and you can ensure that the OID won't change over time, you can set the parser on the global pg-types instance: require('pg').types.setTypeParser(geometryOID, parseWKB).

If you have multiple databases, you will want to pass a separate pg-types instance for each query: https://node-postgres.com/apis/client#queryconfig.

If you can't be sure, that the OID won't change between connections (eg. horizontally scaled read replicas), you might have to query the OID for each new connection.


Alternatively you could just use the WKB parser based on column name or column index after you get your data back from the library. This way you don't need to depend on the OID.

boromisp avatar Feb 22 '24 19:02 boromisp

Thanks a lot @boromisp! I use wkx for the parsing now. Your proposed function looks like that then:

var wkx = require('wkx');
function parseWKB(wkb){
  var wkbBuffer = Buffer.from(wkb, 'hex');
  return wkx.Geometry.parse(wkbBuffer).toGeoJSON();
}

asindl avatar Feb 23 '24 08:02 asindl