jfgodoy / knex-postgis

postgis extension for knex
MIT License
183 stars 25 forks source link

Documentation/example needs improvement #27

Closed jmeyers91 closed 6 years ago

jmeyers91 commented 6 years ago

It's very difficult to understand what the functions in this module actually do. Some of the questions I have right after looking at the readme:

Why is there both a point and makePoint function? Why wouldn't the point function also take a z input? What does the transform function do? What are the return types of these functions?

It would be nice if the list of functions included some basic info. Alternatively, the example could be expanded. I had to find a stack overflow answer just to figure out how to make a point column, and I still haven't figured out how to insert a simple {longitude: 10, latitude: 10} object into my table (my first thought was to use point or makePoint but apparently it's not that simple).

jfgodoy commented 6 years ago

The functions in this module are helpers to create sql for postgis. Each function has the same name and parameters of its corresponding postgis function:

Why is there both a point and makePoint function?

because postgis have them: st_Point, st_MakePoint

Why wouldn't the point function also take a z input?

because postgis st_Point don't receive a z input

What does the transform function do?

https://postgis.net/docs/ST_Transform.html

What are the return types of these functions?

this function create a knex.raw instance.

To insert a point you should do something like this:

const knex = require('knex');
const knexPostgis = require('knex-postgis');

const db = knex({
  dialect: 'postgres',
   //... credentials
});

// install postgis functions in knex.postgis;
const st = knexPostgis(db);

const coord  = {longitude: 10, latitude: 10};

db.insert({
  id: 1,
  geom: st.makePoint(coord.longitude, coord.latitude)
}).into('mytable')
jmeyers91 commented 6 years ago

Ah that makes sense. I suppose most of my confusion has more to do with my lack of Postgis knowledge. If the purpose knex-postgis is to produce postgis function strings, why does it require a knex instance?

I tried using makePoint like you are to insert a point but I was getting an error because the column is created like this:

table.specificType('coordinates', 'geometry(point, 4326)').notNullable();

But makePoint doesn't accept an srid argument, so it gives me a mismatched srid error, so I ended up doing this in the insert:

postgis.geomFromText(`Point(${longitude} ${latitude})`, 4326);

This feels wrong because the whole reason I wanted a tool for this was to avoid stitching together parts of my queries.

jfgodoy commented 6 years ago

The purpose of this library is facilitate the use of postgis functions in knex queries, otherwise you would have to write a lot of knex.raw.

I just added setSRID function, so now you can create the point geometry as follows:

postgis.setSRID(postgis.point(long, lat), 4326)