Skip to content

Support for PostGIS data types #370

Closed

Description

@smitalm

Do you plan to support PostGIS geography data types?

Activity

  1. pleerock commented on Mar 26, 2017

    @pleerock
    Member

    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

  2. MichalLytek commented on Mar 26, 2017

    @MichalLytek
    Contributor

    If it's only about placing custom types in SQL DDL, you can do something like this:

    interface ColumnOptions {
        primary?: boolean;
    }
    type columnType = "number"|"text";
    
    function DecoratorTest(type: columnType, options?: ColumnOptions);
    function DecoratorTest(type: string, options: ColumnOptions & { customType: true });
    function DecoratorTest(type: string, options?: ColumnOptions) {
         return function (object: Object, propertyName: string) {
         }
    }
    
    class Test {
    
        @DecoratorTest("long_number", { customType: true }
        customTypeProperty: number;
    
        @DecoratorTest("text")
        normalProperty: string;
    
    }

    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 😜

  3. pleerock commented on Jun 17, 2017

    @pleerock
    Member

    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!

  4. RDeluxe commented on Feb 3, 2018

    @RDeluxe

    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 ?

  5. pleerock commented on Feb 5, 2018

    @pleerock
    Member

    Adding new types support is easy to implement feature.

  6. RDeluxe commented on Feb 5, 2018

    @RDeluxe

    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 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 {
        return function () { 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).

    SQLTransformer.insert(point : PostGisPoint ) : function {
     return function () { return "ST_SetSRID(ST_MakePoint(" + point.lat + ", " + point.long + "), 4326)" }
    }
    
    SQLTransformer.select(columnAlias: any) : function {
      return function () { return "
        'coordinates', json_build_object(
            'latitude', ST_Y(${columnAlias}::geometry),
            'longitude', ST_X(${columnAlias}::geometry)
         )"
      }
    }

    This is really just some ideas, but as this lib grows, the more this abstraction layer will make sense

  7. pleerock commented on Feb 5, 2018

    @pleerock
    Member

    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?

  8. RDeluxe commented on Feb 5, 2018

    @RDeluxe

    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.

  9. RDeluxe commented on Feb 5, 2018

    @RDeluxe

    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

  10. theigor commented on Feb 20, 2018

    @theigor

    @RDeluxe , regarding

    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:

      import { Point } from 'geojson';
      ...
    
      @Column("blob", {
        transformer: {
          to: (v: Point) => {
            return function () { return `ST_GeomFromGeoJSON(${JSON.stringify(v)})` }
          }
        }
      })
      location: Point;

    ends up with this sql sent to the db:

      sql: 'INSERT INTO `table`(`location`) VALUES (\'function () { return `ST_GeomFromGeoJSON(${JSON.stringify(v)})`; }\')
    

    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:

      @Column("blob", {
        transformer: {
          to: (v: Point) => `ST_GeomFromGeoJSON(${JSON.stringify(v)})`
        }
      })
      location: Point;

    I get this sent to mysql:

      sql: 'INSERT INTO `table`(`location`) VALUES (\'ST_GeomFromGeoJSON({\\"type\\":\\"Point\\",\\"coordinates\\":[42.3600825,-71.05888010000001]})\')
    

    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?

  11. theigor commented on Feb 20, 2018

    @theigor

    Also, just for reference, I am able to get geometry out of mysql as geojson with this from transformer:

    @Column("blob", {
        transformer: {
          to: (v: Point) => eval(`ST_GeomFromGeoJSON(${JSON.stringify(v)})`),
          from: (v: any) => { return {type: "Point", coordinates: [ v.x, v.y ] } as Point }
        }
      })
      location: Point;

    when I do console.log(v) inside the from function, I get an object like this:

    { x: 42.3600825, y: -71.05888010000001 }
  12. RDeluxe commented on Feb 22, 2018

    @RDeluxe

    Not quite sure, in the Postgres driver if I remember correctly. It may be line 386, in escapeQueryWithParameters method.

    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.

  13. RDeluxe commented on Feb 22, 2018

    @RDeluxe

    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

     GEOGRAPHY.prototype._stringify = function _stringify(value, options) {
        return 'ST_GeomFromGeoJSON(' + options.escape(JSON.stringify(value)) + ')';
      };

    This piece of code is what is missing right now in TypeORM, allowing users to use SQL functions while selecting

  14. 9 remaining items

  15. AlexMesser commented on May 24, 2018

    @AlexMesser
    Collaborator

    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.

  16. theigor commented on May 26, 2018

    @theigor

    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:

    1. While we typically think of lat and long in that order, OpenLayers actually uses long, lat. Here's the explanation - https://openlayers.org/en/latest/doc/faq.html#why-is-the-order-of-a-coordinate-lon-lat-and-not-lat-lon-. Because of this, there seems to be some validity to the second approach above.
    2. The first approach is definitely wrong - it seems it just inserted it as a varchar (although... not quite because it added more precision :/).
    3. I have POINTs working outside of typeorm in MySQL.
      • The datatype is POINT, it looks like this when I select * in Workbench:
        image
      • 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.
        image
        image
    4. 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.

    Not sure if that helps at all...

  17. sethfitz commented on Jun 22, 2018

    @sethfitz
    Contributor

    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?):

    supportedDataTypes: ColumnType[] = [
    "int",
    "int2",
    "int4",
    "int8",
    "smallint",
    "integer",
    "bigint",
    "decimal",
    "numeric",
    "real",
    "float",
    "float4",
    "float8",
    "double precision",
    "money",
    "character varying",
    "varchar",
    "character",
    "char",
    "text",
    "citext",
    "hstore",
    "bytea",
    "bit",
    "varbit",
    "bit varying",
    "timetz",
    "timestamptz",
    "timestamp",
    "timestamp without time zone",
    "timestamp with time zone",
    "date",
    "time",
    "time without time zone",
    "time with time zone",
    "interval",
    "bool",
    "boolean",
    "enum",
    "point",
    "line",
    "lseg",
    "box",
    "path",
    "polygon",
    "circle",
    "cidr",
    "inet",
    "macaddr",
    "tsvector",
    "tsquery",
    "uuid",
    "xml",
    "json",
    "jsonb",
    "int4range",
    "int8range",
    "numrange",
    "tsrange",
    "tstzrange",
    "daterange"
    ];

    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)):

    import { Geometry } from "geojson";
    import {
      Column,
      Entity,
      PrimaryGeneratedColumn
    } from "typeorm";
    import { ValueTransformer } from "typeorm/decorator/options/ValueTransformer";
    import * as wkx from "wkx";
    
    class GeometryTransformer implements ValueTransformer {
      to(geojson: Geometry) {
        return wkx.Geometry.parseGeoJSON(geojson).toWkt();
      }
    
      from(wkb: any) {
        return wkx.Geometry.parse(new Buffer(wkb, "hex")).toGeoJSON();
      }
    }
    
    @Entity()
    class GeocodedThing {
      @PrimaryGeneratedColumn() id: number;
    
      @Column("geometry", {
        transformer: new GeometryTransformer()
      })
      geom: Geometry;
    }

    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).

  18. sethfitz commented on Jun 22, 2018

    @sethfitz
    Contributor

    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).

  19. OKNoah commented on Jun 30, 2018

    @OKNoah
    Contributor

    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.

    .orderBy({"place.location": {
              distance: {
                type: "Point",
                coordinates: [lon, lat]
              },
              order: 'ASC',
              nulls: 'NULLS LAST'
          }})

    As @mojodna also said elsewhere, this should work also:

    .orderBy("ST_Distance(post.geom, ST_GeomFromGeoJSON(:origin))", "DESC")
        .setParameters({ origin: JSON.stringify(origin) })
  20. tomasoak commented on May 19, 2020

    @tomasoak

    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:

    image

  21. lamuertepeluda commented on May 19, 2020

    @lamuertepeluda

    @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.

  22. tomasoak commented on May 19, 2020

    @tomasoak

    @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:
    image
    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:

    @Field(() => GraphQLJSON)
      @PrimaryColumn('jsonb')
      geojson: FeatureCollection;
    
  23. lamuertepeluda commented on May 20, 2020

    @lamuertepeluda

    @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.

  24. kukuandroid commented on Aug 13, 2020

    @kukuandroid

    Hi, how to use query builder to query this type of column ?

  25. kallol24 commented on Oct 8, 2020

    @kallol24

    @kukuandroid

    const query = connection.getRepository(Basic).createQueryBuilder('basic');

    const response = await query.where('basic.verified2 @> :verified', {verified: {dob: false}}).getMany();

  26. hussainwali74 commented on May 9, 2021

    @hussainwali74

    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?):

    supportedDataTypes: ColumnType[] = [
    "int",
    "int2",
    "int4",
    "int8",
    "smallint",
    "integer",
    "bigint",
    "decimal",
    "numeric",
    "real",
    "float",
    "float4",
    "float8",
    "double precision",
    "money",
    "character varying",
    "varchar",
    "character",
    "char",
    "text",
    "citext",
    "hstore",
    "bytea",
    "bit",
    "varbit",
    "bit varying",
    "timetz",
    "timestamptz",
    "timestamp",
    "timestamp without time zone",
    "timestamp with time zone",
    "date",
    "time",
    "time without time zone",
    "time with time zone",
    "interval",
    "bool",
    "boolean",
    "enum",
    "point",
    "line",
    "lseg",
    "box",
    "path",
    "polygon",
    "circle",
    "cidr",
    "inet",
    "macaddr",
    "tsvector",
    "tsquery",
    "uuid",
    "xml",
    "json",
    "jsonb",
    "int4range",
    "int8range",
    "numrange",
    "tsrange",
    "tstzrange",
    "daterange"
    ];

    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)):

    import { Geometry } from "geojson";
    import {
      Column,
      Entity,
      PrimaryGeneratedColumn
    } from "typeorm";
    import { ValueTransformer } from "typeorm/decorator/options/ValueTransformer";
    import * as wkx from "wkx";
    
    class GeometryTransformer implements ValueTransformer {
      to(geojson: Geometry) {
        return wkx.Geometry.parseGeoJSON(geojson).toWkt();
      }
    
      from(wkb: any) {
        return wkx.Geometry.parse(new Buffer(wkb, "hex")).toGeoJSON();
      }
    }
    
    @Entity()
    class GeocodedThing {
      @PrimaryGeneratedColumn() id: number;
    
      @Column("geometry", {
        transformer: new GeometryTransformer()
      })
      geom: Geometry;
    }

    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??

    I have this column:

    @Index({ spatial: true })
     @Column({
       type: 'geometry',
       srid: 4326,
       nullable: true,
       spatialFeatureType: 'Point',
       transformer: {
         to: (v: Point) => {
           console.log(v);
           console.log(JSON.stringify(v));
           return eval(
             `ST_GeomFromGeoJSON('{"type":"Point","coordinates":[39.807222,-76.984722]}')`,
           );
         },
         from: (v: any) => {
           return v;
         },
       },
     })
     current_location: string;
    
    
    

    when I try to insert data:
    "current_location": "{"type":"Point","coordinates":[39.807222,-76.984722]}",

    it says ST_GeomFromGeoJSON is not defined. Please help

  27. hussainwali74 commented on May 9, 2021

    @hussainwali74

    Hi, how to use query builder to query this type of column ?

    @tomasoak sir ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions