You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Maybe after #344 we can support external extensions? By having for example typeorm-postgres-postgis module which will use declaration merging for ColumnPostgresType ? What do you think @19majkel94
Normal user would have type-safe for standard postgres functionality and if someone install 3rd party plugins to database, it can use customType option and provide his own type name.
But it has to have support in switch-case in typeorm or sth - I don't know how the support for column types works 😜
Where are we on that ? Despite point & other type being supported, Postgis itself is not. What amount of work would be required to make postgis and typeorm work together ?
Yes, adding new supported types in ColumnTypes and Postgres driver is quite easy. I managed rapidly to add the GEOMETRY(POINT, 4386) type.
However, working with Postgis means using Postgis sql functions quite often. To insert a new geographical point in a GEOMETRY(POINT, 4386) column for example : ST_SetSRID(ST_MakePoint(lat, long), 4326).
I talked on Gitter about this issue : the transformer option can solve the INSERT issue, as I discovered (after digging in the code) that it could take a function as a parameter, and in such case it will be considered as a SQL function.
So this works :
to(coordinates: ICoordinates): any {returnfunction(){return"ST_SetSRID(ST_MakePoint("+coordinates.lat+", "+coordinates.long+"), 4326)"}}
However, to fetch the data the transformer will only be applied after the rawsql query has been executed. Making it impossible to easily execute a function to fetch the data. I could definitely use a RAW SQL query, like I did before (ST_X(coordinates::geometry) AS longitude, ST_Y(coordinates::geometry) AS latitude), but I think that every type which need it should have an INSERT and SELECT sql_transform, used to create the SQL query. By creating this layer of abstraction we would have an easy to extend system, in which end-user / extension creators could create new types easily without modifying typeorm directly.
To give an example, I could create a PostGisPoint type/Interface in Typescript, with a longitude and latitude (with a column called coordinates).
Sorry I haven't worked with geo types and don't know all their specifics. Why can't we just select columns and have results, isn't postgres supposed to handle such logic on its own?
Nope, there are a lot of ways to work with geographic data with postgis, the system is really fast because it's optimizing everything (that's how you can get all the points of interest in a certain radius for example). So inserting and selecting geographic data always go through some postgis functions.
I may have some time during my weekends and late nights to work on this, if you want to clarify the abstraction layer / good way to make typeorm extensions (such as @typeorm/postgis) I could start something
Reacted by EreckGordon, Maia, Gustavo Henrique Ribeiro Dias, Wolfgang Rathgeb and Andrii Oriekhov
as I discovered (after digging in the code) that it could take a function as a parameter, and in such case it will be considered as a SQL function.
Can you point me to where you discovered this? I can't find it nor get it to work. I am trying to insert a point with the mysql driver. Making the to return a function like you suggest:
I have been digging quickly in Sequelize, and I see they have an abstraction layer allowing user to create types.
I did not use Sequelize recently, but that's more or less what I advised earlier. Example (you can see here the GEOGRAPHY type).
I'm wondering how hard this could be for TypeORM. Instead of using the type directly as a string, we would use a Class with a toSQL() method to create the SQL type string. This can already be done with transformer, but they are not a good solution for extending the framework.
Hello @RDeluxe, currently I'm busy at my main job and unfortunately I can't spend lot of time to TypeORM. I will proceed to this task as soon as I have free time. Meanwhile this task is opened for contributions.
Hey @RDeluxe - sorry for the delayed response. Didn't notice you had a question for me.
So, admittedly, I am not an expert on PostGIS but I have some experience with it and with OpenLayers and here are a couple of interesting things to notice:
The first approach is definitely wrong - it seems it just inserted it as a varchar (although... not quite because it added more precision :/).
I have POINTs working outside of typeorm in MySQL.
The datatype is POINT, it looks like this when I select * in Workbench:
And if I right click and open value in editor, I am able to see this when viewing it as text. Note that this is the same field that I am viewing as text or geojson that mysql lets me do because the datatype is POINT.
However, I have a whole other project where my geo_json field is simply TEXT and I transform it on the way in and out. The point that I am making is I think the data types are just sugar and it's all text underneath. But like I said, I am not close to an expert on this.
After spending a bit of time looking at this recently, it looks like there are 2 approaches. The less intrusive approach is to bypass the rudimentary spatial type support that exists for MySQL and MS SQL and use a ValueTransformer:
First, register geometry and geography to the list of supported data types (is there a way to do this from client code without patching the library?):
Then, register a column with a custom transformer that uses wkx to convert to/from WKB (well-known binary, e.g. 0101000020E610000000000000008046400000000000804640) / GeoJSON / WKT (well-known text, e.g. POINT(45 45)):
At this point, any code that works with entities will use GeoJSON to represent geometries. It doesn't enforce types, so you'll be able to switch between Point, LineString, Polygon, etc. without constraints.
The other, more intrusive, approach is to add geometry and geography types to the driver's spatialTypes and expand the special handling for SELECTs and INSERTs.
The existing implementation (AsText / GeomFromText for MySQL) uses WKT (well-known text) as the intermediate representation, which is perhaps less useful, as it still needs to be parsed into something to support easier manipulation and operation. If one were to go down that path, the equivalent PostGIS functions as ST_AsText and ST_GeomFromText (the ST prefix refers to "spatial type" in the SQL/MM Spatial standard. ST_AsGeoJSON and ST_GeomFromGeoJSON are the SQL/MM (read: PostGIS / MySQL / MariaDB) functions for conversion, which would obviate the need for a custom transformer (it would be treated as a json column instead and parsed/stringified as necessary).
An additional nicety would be to sniff to spatial columns in use (similar to checking for hstore, etc.) and attempt to register the postgis extension.
PostGIS types are a bit different than generalized types in that they're often parameterized. They work without parameters (geometry allows a column to store any type of geometry (point, line, polygon, geometry collection, etc.) without constraints on the SRID (spatial reference id; essentially the coordinate system in use--lat/lon is 4326 and is in degrees, web mercator (slippy maps around the web) is 3857 and units are "meters" (the length of a "meter" varies by latitude because earth is a spheroid; http://lyzidiamond.com/posts/4326-vs-3857 is a fantastic resource for understanding this and geographic coordinate systems in general better)). They can also restrict what's store in a column, e.g. geometry(POINT, 4326) will prevent non-points in coordinate systems other than lat/lon from being saved. typeorm doesn't look like it currently supports type parameterization, so this could be more of a long-term improvement that's not necessarily for immediate usefulness.
(geography is less commonly used in PostGIS, but has the benefit of allowing measurement calculations to occur in meters rather than degrees to produce human-readable output (what's the distance of 1º? it depends...))
As a relatively long-time JS and spatial dev, my preference would be to use GeoJSON as an internal representation rather than WKT (many other libraries, including Turf, support GeoJSON natively). This does represent a semver-major change though. I don't have time to put together a proper PR, but am happy to code review (just @ me on the PR).
Reacted by Adam Krupke, vanhumbeecka, Aljosa Sljuka, Dan, Alex Mantaut, Christian Wheeler, Alamo Saravali, Hyder Alamgir, hawkeng, Andrii Oriekhov and 3 more
Oh, I also wanted to mention that it's helpful to think of anything spatial as being generalized to existing within a coordinate system. Since we usually think of our Cartesian coordinate systems as (x, y), it makes sense (for anything machine-readable) to remain consistent when using lat/lon, which means (lon, lat) (which is(x, y).
I've solen all @mojodna's great work, added a (probably imperfect) ordering solution, and published it on npm as typeorm-spatial. I don't mean to maintain it as a permanent fork after a release includes PostGIS support.
@tomasoak sorry I didn't get it exactly, but geography and jsonb are different quite types on PostGIS. Ensure you have PostGIS installed with Postgresql first. Then, perhaps you should try migrating your data to geography type.
@lamuertepeluda thanks for answering and sorry by not being clear enough. I already have a Postgresql / Postgis database runny on.
This is what I have on database, a single-line jsonb object:
With de following value-structure (a FeatureCollection with several MultiPolygons): {"type": "FeatureCollection", "features": [{"id": "inputs.id_prod", "type": "Feature", "geometry": {"type": "MultiPolygon", "coordinates": [[[[-54.8, -1.4], [-54.8, -1.4], [-54.8, -1.4], [-54.8, -1.4], [-54.8, -1.4]]]]}, "properties": {"area_ha".......:
@tomasoak if you want to exploit PostGIS cool features such as indexes and manipulators for geography and geometry type, you should migrate your column type to "geography" type (or "geometry" type if your case fits, i.e. small areas or different SRID than 4326).
Then you can use @Coulmn('geography') without problem.
After spending a bit of time looking at this recently, it looks like there are 2 approaches. The less intrusive approach is to bypass the rudimentary spatial type support that exists for MySQL and MS SQL and use a ValueTransformer:
First, register geometry and geography to the list of supported data types (is there a way to do this from client code without patching the library?):
Then, register a column with a custom transformer that uses wkx to convert to/from WKB (well-known binary, e.g. 0101000020E610000000000000008046400000000000804640) / GeoJSON / WKT (well-known text, e.g. POINT(45 45)):
At this point, any code that works with entities will use GeoJSON to represent geometries. It doesn't enforce types, so you'll be able to switch between Point, LineString, Polygon, etc. without constraints.
The other, more intrusive, approach is to add geometry and geography types to the driver's spatialTypes and expand the special handling for SELECTs and INSERTs.
The existing implementation (AsText / GeomFromText for MySQL) uses WKT (well-known text) as the intermediate representation, which is perhaps less useful, as it still needs to be parsed into something to support easier manipulation and operation. If one were to go down that path, the equivalent PostGIS functions as ST_AsText and ST_GeomFromText (the ST prefix refers to "spatial type" in the SQL/MM Spatial standard. ST_AsGeoJSON and ST_GeomFromGeoJSON are the SQL/MM (read: PostGIS / MySQL / MariaDB) functions for conversion, which would obviate the need for a custom transformer (it would be treated as a json column instead and parsed/stringified as necessary).
An additional nicety would be to sniff to spatial columns in use (similar to checking for hstore, etc.) and attempt to register the postgis extension.
PostGIS types are a bit different than generalized types in that they're often parameterized. They work without parameters (geometry allows a column to store any type of geometry (point, line, polygon, geometry collection, etc.) without constraints on the SRID (spatial reference id; essentially the coordinate system in use--lat/lon is 4326 and is in degrees, web mercator (slippy maps around the web) is 3857 and units are "meters" (the length of a "meter" varies by latitude because earth is a spheroid; http://lyzidiamond.com/posts/4326-vs-3857 is a fantastic resource for understanding this and geographic coordinate systems in general better)). They can also restrict what's store in a column, e.g. geometry(POINT, 4326) will prevent non-points in coordinate systems other than lat/lon from being saved. typeorm doesn't look like it currently supports type parameterization, so this could be more of a long-term improvement that's not necessarily for immediate usefulness.
(geography is less commonly used in PostGIS, but has the benefit of allowing measurement calculations to occur in meters rather than degrees to produce human-readable output (what's the distance of 1º? it depends...))
As a relatively long-time JS and spatial dev, my preference would be to use GeoJSON as an internal representation rather than WKT (many other libraries, including Turf, support GeoJSON natively). This does represent a semver-major change though. I don't have time to put together a proper PR, but am happy to code review (just @ me on the PR).
I just want a simple example please:
how to insert lat-long point dataa into postgres, find distance between 2 points??
Activity
pleerock commentedon Mar 26, 2017
Maybe after #344 we can support external extensions? By having for example
typeorm-postgres-postgismodule which will use declaration merging forColumnPostgresType? What do you think @19majkel94MichalLytek commentedon Mar 26, 2017
If it's only about placing custom types in SQL DDL, you can do something like this:
Normal user would have type-safe for standard postgres functionality and if someone install 3rd party plugins to database, it can use
customTypeoption and provide his own type name.But it has to have support in switch-case in typeorm or sth - I don't know how the support for column types works 😜
pleerock commentedon Jun 17, 2017
Custom column data types are landed in
0.1.0-alpha.10. Now you can use any datatype postgres has. Feel free to test them!RDeluxe commentedon Feb 3, 2018
Where are we on that ? Despite point & other type being supported, Postgis itself is not. What amount of work would be required to make postgis and typeorm work together ?
pleerock commentedon Feb 5, 2018
Adding new types support is easy to implement feature.
RDeluxe commentedon Feb 5, 2018
Well, I'm not quite sure about that.
Yes, adding new supported types in ColumnTypes and Postgres driver is quite easy. I managed rapidly to add the
GEOMETRY(POINT, 4386)type.However, working with Postgis means using Postgis sql functions quite often. To insert a new geographical point in a
GEOMETRY(POINT, 4386)column for example :ST_SetSRID(ST_MakePoint(lat, long), 4326).I talked on Gitter about this issue : the
transformeroption can solve the INSERT issue, as I discovered (after digging in the code) that it could take a function as a parameter, and in such case it will be considered as a SQL function.So this works :
However, to fetch the data the transformer will only be applied after the rawsql query has been executed. Making it impossible to easily execute a function to fetch the data. I could definitely use a RAW SQL query, like I did before (
ST_X(coordinates::geometry) AS longitude, ST_Y(coordinates::geometry) AS latitude), but I think that every type which need it should have an INSERT and SELECT sql_transform, used to create the SQL query. By creating this layer of abstraction we would have an easy to extend system, in which end-user / extension creators could create new types easily without modifying typeorm directly.To give an example, I could create a PostGisPoint type/Interface in Typescript, with a longitude and latitude (with a column called coordinates).
This is really just some ideas, but as this lib grows, the more this abstraction layer will make sense
pleerock commentedon Feb 5, 2018
Sorry I haven't worked with geo types and don't know all their specifics. Why can't we just select columns and have results, isn't postgres supposed to handle such logic on its own?
RDeluxe commentedon Feb 5, 2018
Nope, there are a lot of ways to work with geographic data with postgis, the system is really fast because it's optimizing everything (that's how you can get all the points of interest in a certain radius for example). So inserting and selecting geographic data always go through some postgis functions.
RDeluxe commentedon Feb 5, 2018
I may have some time during my weekends and late nights to work on this, if you want to clarify the abstraction layer / good way to make typeorm extensions (such as
@typeorm/postgis) I could start somethingtheigor commentedon Feb 20, 2018
@RDeluxe , regarding
Can you point me to where you discovered this? I can't find it nor get it to work. I am trying to insert a point with the mysql driver. Making the
toreturn a function like you suggest:ends up with this sql sent to the db:
Same thing if I do
to: (v: Point) => () => `ST_GeomFromGeoJSON(${JSON.stringify(v)})`,- I get\'() => `ST_GeomFromGeoJSON(${JSON.stringify(v)})`\'If I do it without a function, like so:
I get this sent to mysql:
I think I just need some way to unescape the value for this column so the mysql function is treated as a function. Any ideas?
theigor commentedon Feb 20, 2018
Also, just for reference, I am able to get geometry out of mysql as geojson with this
fromtransformer:when I do
console.log(v)inside thefromfunction, I get an object like this:{ x: 42.3600825, y: -71.05888010000001 }RDeluxe commentedon Feb 22, 2018
Not quite sure, in the Postgres driver if I remember correctly. It may be line 386, in
escapeQueryWithParametersmethod.Btw, I think this issue should be re-opened, this is most definitely not solved from what I can see.
I repeat myself: but TypeORM needs some kind of abstraction layer to enable the possibility to extends it.
RDeluxe commentedon Feb 22, 2018
I have been digging quickly in Sequelize, and I see they have an abstraction layer allowing user to create types.
I did not use Sequelize recently, but that's more or less what I advised earlier.
Example (you can see here the GEOGRAPHY type).
I'm wondering how hard this could be for TypeORM. Instead of using the type directly as a string, we would use a Class with a toSQL() method to create the SQL type string. This can already be done with transformer, but they are not a good solution for extending the framework.
Pay attention to
This piece of code is what is missing right now in TypeORM, allowing users to use SQL functions while selecting
9 remaining items
AlexMesser commentedon May 24, 2018
Hello @RDeluxe, currently I'm busy at my main job and unfortunately I can't spend lot of time to TypeORM. I will proceed to this task as soon as I have free time. Meanwhile this task is opened for contributions.
theigor commentedon May 26, 2018
Hey @RDeluxe - sorry for the delayed response. Didn't notice you had a question for me.
So, admittedly, I am not an expert on PostGIS but I have some experience with it and with OpenLayers and here are a couple of interesting things to notice:
Not sure if that helps at all...
sethfitz commentedon Jun 22, 2018
After spending a bit of time looking at this recently, it looks like there are 2 approaches. The less intrusive approach is to bypass the rudimentary spatial type support that exists for MySQL and MS SQL and use a
ValueTransformer:First, register
geometryandgeographyto the list of supported data types (is there a way to do this from client code without patching the library?):typeorm/src/driver/postgres/PostgresDriver.ts
Lines 87 to 149 in 1fe884e
Then, register a column with a custom transformer that uses
wkxto convert to/from WKB (well-known binary, e.g.0101000020E610000000000000008046400000000000804640) / GeoJSON / WKT (well-known text, e.g.POINT(45 45)):At this point, any code that works with entities will use GeoJSON to represent geometries. It doesn't enforce types, so you'll be able to switch between
Point,LineString,Polygon, etc. without constraints.The other, more intrusive, approach is to add
geometryandgeographytypes to the driver'sspatialTypesand expand the special handling forSELECTs andINSERTs.The existing implementation (
AsText/GeomFromTextfor MySQL) uses WKT (well-known text) as the intermediate representation, which is perhaps less useful, as it still needs to be parsed into something to support easier manipulation and operation. If one were to go down that path, the equivalent PostGIS functions asST_AsTextandST_GeomFromText(theSTprefix refers to "spatial type" in the SQL/MM Spatial standard.ST_AsGeoJSONandST_GeomFromGeoJSONare the SQL/MM (read: PostGIS / MySQL / MariaDB) functions for conversion, which would obviate the need for a custom transformer (it would be treated as ajsoncolumn instead and parsed/stringified as necessary).An additional nicety would be to sniff to spatial columns in use (similar to checking for
hstore, etc.) and attempt to register thepostgisextension.PostGIS types are a bit different than generalized types in that they're often parameterized. They work without parameters (
geometryallows a column to store any type of geometry (point, line, polygon, geometry collection, etc.) without constraints on the SRID (spatial reference id; essentially the coordinate system in use--lat/lon is4326and is in degrees, web mercator (slippy maps around the web) is3857and units are "meters" (the length of a "meter" varies by latitude because earth is a spheroid; http://lyzidiamond.com/posts/4326-vs-3857 is a fantastic resource for understanding this and geographic coordinate systems in general better)). They can also restrict what's store in a column, e.g.geometry(POINT, 4326)will prevent non-points in coordinate systems other than lat/lon from being saved.typeormdoesn't look like it currently supports type parameterization, so this could be more of a long-term improvement that's not necessarily for immediate usefulness.(
geographyis less commonly used in PostGIS, but has the benefit of allowing measurement calculations to occur in meters rather than degrees to produce human-readable output (what's the distance of 1º? it depends...))As a relatively long-time JS and spatial dev, my preference would be to use GeoJSON as an internal representation rather than WKT (many other libraries, including Turf, support GeoJSON natively). This does represent a semver-major change though. I don't have time to put together a proper PR, but am happy to code review (just @ me on the PR).
sethfitz commentedon Jun 22, 2018
Oh, I also wanted to mention that it's helpful to think of anything spatial as being generalized to existing within a coordinate system. Since we usually think of our Cartesian coordinate systems as
(x, y), it makes sense (for anything machine-readable) to remain consistent when using lat/lon, which means(lon, lat)(which is(x, y).OKNoah commentedon Jun 30, 2018
I've solen all @mojodna's great work, added a (probably imperfect) ordering solution, and published it on npm as typeorm-spatial. I don't mean to maintain it as a permanent fork after a release includes PostGIS support.
As @mojodna also said elsewhere, this should work also:
tomasoak commentedon May 19, 2020
Hey guys. I read everything but I couldn't figure out how to solve this simple problem:
Any can help me?
I already have a GeoJson data, storage at PostgreSQL as jsonb.
I'm trying unsuccessfully this ways:
lamuertepeluda commentedon May 19, 2020
@tomasoak sorry I didn't get it exactly, but geography and jsonb are different quite types on PostGIS. Ensure you have PostGIS installed with Postgresql first. Then, perhaps you should try migrating your data to geography type.
tomasoak commentedon May 19, 2020
@lamuertepeluda thanks for answering and sorry by not being clear enough. I already have a Postgresql / Postgis database runny on.
This is what I have on database, a single-line jsonb object:

With de following value-structure (a FeatureCollection with several MultiPolygons):
{"type": "FeatureCollection", "features": [{"id": "inputs.id_prod", "type": "Feature", "geometry": {"type": "MultiPolygon", "coordinates": [[[[-54.8, -1.4], [-54.8, -1.4], [-54.8, -1.4], [-54.8, -1.4], [-54.8, -1.4]]]]}, "properties": {"area_ha".......:I just got right in this way:
lamuertepeluda commentedon May 20, 2020
@tomasoak if you want to exploit PostGIS cool features such as indexes and manipulators for geography and geometry type, you should migrate your column type to "geography" type (or "geometry" type if your case fits, i.e. small areas or different SRID than 4326).
Then you can use @Coulmn('geography') without problem.
Geography is a different type from json/jsonb and data can be converted to/from GeoJSON using operators such as https://postgis.net/docs/ST_AsGeoJSON.html
You can migrate to geography using https://postgis.net/docs/ST_GeomFromGeoJSON.html
Typeorm has a fair support for migrations of this type.
Of course you can stick to jsonb if this is your use case, but then your feature will behave just like a regular json object.
kukuandroid commentedon Aug 13, 2020
Hi, how to use query builder to query this type of column ?
kallol24 commentedon Oct 8, 2020
@kukuandroid
const query = connection.getRepository(Basic).createQueryBuilder('basic');
const response = await query.where('basic.verified2 @> :verified', {verified: {dob: false}}).getMany();
hussainwali74 commentedon May 9, 2021
I just want a simple example please:
how to insert lat-long point dataa into postgres, find distance between 2 points??
I have this column:
when I try to insert data:
"current_location": "{"type":"Point","coordinates":[39.807222,-76.984722]}",
it says ST_GeomFromGeoJSON is not defined. Please help
hussainwali74 commentedon May 9, 2021
@tomasoak sir ?
PradeepNooney commentedon May 16, 2021
@hussainwali74
https://stackoverflow.com/questions/67435650/storing-geojson-points-and-finding-points-within-a-given-distance-radius-nodej/67557083#67557083