Skip to content

Added GeoJSON support - #1854

Merged
YohDeadfall merged 2 commits into
npgsql:devfrom
YohDeadfall:GeoJSON
May 16, 2018
Merged

YohDeadfall merged 2 commits into
npgsql:devfrom
YohDeadfall:GeoJSON

Conversation

@YohDeadfall

@YohDeadfall YohDeadfall commented Mar 20, 2018 •

Copy link
Copy Markdown
Contributor

Features:

  • Supports same options as ST_AsGeoJSON.
  • Uses an spatial SRID to authority name map.
  • Allocates memory only for user defined coordinate spatial references.

Tests:

  • Basic geometry tests.
  • SRID to authority name tests.
  • Bounding box tests.

Fixes #1787

@roji

roji commented Mar 20, 2018

Copy link
Copy Markdown
Member

@YohDeadfall is it ready for reviewing?

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

Yes, it's ready.

Is there any way to get the exception details from Travis CI? Locally all tests pass.

@roji

roji commented Mar 20, 2018 •

Copy link
Copy Markdown
Member

OK, will try to review soon, although the next few days are busy with some non-Npgsql stuff.

For the build, you can click the "details" link on the Travis/Appveyor lines, it seems there's a StackOverflowException when running the plugin tests... Could that somehow be coming from your new tests?

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

Found and fixed. When a NUnit test fails with StackOverflowException, NUnit Adapter marks the test as successful and stops. If it's the last run test then the adapter thinks that everything is okay.

What is a problem with AppVeyor again?

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, check out my few minor comments. If you can also rebase and squash on your end I'll merge (if you have any difficulties I can do it).

Comment thread src/Npgsql.GeoJSON/CrsMap.WellKnown.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A link to some sort of reference documentation/explanation for all the codes below would be good.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's from the spatial_ref_sys table. A query to fetch that data can be found here.

Comment thread Npgsql.sln Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs to be done in Npgsql.all.sln as well

Comment thread src/Npgsql.GeoJSON/CrsMap.WellKnown.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also rename s_wellKnown to WellKnown to match static readonly naming convention.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please inverse order

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do.

Comment thread src/Npgsql.GeoJSON/GeoJsonHandler.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any particular benefit in wrapping the exception creation in static methods, especially for those which are only thrown from a single site? For the ones thrown from multiple site there's at least some value centralizing the string, even the more standard way is to put the strings in a a resx (although that would be overkill...)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about something like a throw helper without an additional class, but you're right. So will do. In future I think we should move all strings to resx files as continuation of #685.

Comment thread src/Npgsql.GeoJSON/CrsMap.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mutable structs are always dangerous (it's very easy to introduce errors by copying)... Since this is only used once, in the construction of the GeoJsonHandler, consider moving this logic into GeoJsonHandlerFactory?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so it's needed because it's designed only for the plugin with a few types inside. For large unobservable projects it would make sense, but not in that case.

Is it okay to use C# 7.2 and mark it as ref struct?

Comment thread src/Npgsql.GeoJSON/GeoJsonHandler.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe just do a switch? Would be faster (even if it's surely negligible)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did some perf measurements out of curiosity and got the following result:

[Config(typeof(Config))]
public class SwithcVsIf
{
    private EwkbGeometryType _type;

    [Params(
        (uint)(EwkbGeometryType.Point),
        (uint)(EwkbGeometryType.Point | EwkbGeometryType.HasZ),
        (uint)(EwkbGeometryType.Point | EwkbGeometryType.HasM),
        (uint)(EwkbGeometryType.Point | EwkbGeometryType.HasZ | EwkbGeometryType.HasM))]
    public uint Type
    {
        get => (uint)_type;
        set => _type = (EwkbGeometryType)value;
    }

    public const int Iterations = 1000000;

    [Benchmark(OperationsPerInvoke = Iterations)]
    public int UsingSwitch()
    {
        var total = 0;
        for (var i = 0; i < Iterations; i++)
            total += SizeOf(_type);
        return total;

        int SizeOf(EwkbGeometryType type)
        {
            switch (type & (EwkbGeometryType.HasZ | EwkbGeometryType.HasM))
            {
                case EwkbGeometryType.HasZ:
                case EwkbGeometryType.HasM:
                    return sizeof(double) * 3;

                case EwkbGeometryType.HasZ | EwkbGeometryType.HasM:
                    return sizeof(double) * 4;

                default:
                    return sizeof(double) * 2;
            }
        }
    }

    [Benchmark(OperationsPerInvoke = Iterations)]
    public int UsingIf()
    {
        var total = 0;
        for (var i = 0; i < Iterations; i++)
            total += SizeOf(_type);
        return total;

        int SizeOf(EwkbGeometryType type)
        {
            var size = sizeof(double) * 2;
            if (HasZ(type))
                size += sizeof(double);
            if (HasM(type))
                size += sizeof(double);
            return size;
        }
    }
BenchmarkDotNet=v0.10.12, OS=Windows 10.0.17133
Intel Xeon CPU E5-2687W 0 3.10GHz, 1 CPU, 16 logical cores and 16 physical cores
.NET Core SDK=2.1.4
  [Host]     : .NET Core 2.0.5 (Framework 4.6.26020.03), 64bit RyuJIT
  DefaultJob : .NET Core 2.0.5 (Framework 4.6.26020.03), 64bit RyuJIT
Method Type Mean Error StdDev Median Op/s
UsingSwitch 1 7.840 ns 0.1837 ns 0.4873 ns 7.765 ns 127,548,559.1
UsingIf 1 9.434 ns 0.1880 ns 0.5017 ns 9.484 ns 105,994,853.5
UsingSwitch 1073741825 7.214 ns 0.4103 ns 1.2097 ns 7.703 ns 138,619,873.1
UsingIf 1073741825 6.440 ns 0.5014 ns 1.4784 ns 7.073 ns 155,286,533.5
UsingSwitch 2147483649 7.086 ns 0.4545 ns 1.3402 ns 7.521 ns 141,114,206.3
UsingIf 2147483649 7.781 ns 0.4938 ns 1.4561 ns 8.360 ns 128,510,638.6
UsingSwitch 3221225473 8.803 ns 0.1749 ns 0.4576 ns 8.775 ns 113,593,669.6
UsingIf 3221225473 6.921 ns 0.1329 ns 0.2528 ns 6.928 ns 144,487,319.6

I think it's more readability choice because the difference is very small. It makes sense to leave it as it is.

Comment thread src/Npgsql.GeoJSON/GeoJsonHandler.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All callers of NotValid seems to throw AllOrNoneCoordiantesMustHaveZ if it returns true, so why not just throw it from inside the function? You could also rename from the somewhat confusing NotValid to, say, CheckZ.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ValidateAndGetLength(Polygon, ref NpgsqlLengthCache, NpgsqlParameter) method throws the exception in two places which are observable. It's more obvious.

Comment thread src/Npgsql.GeoJSON/GeoJsonHandler.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please unindent case to the same level as the switch

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do.

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

Rebased and squashed as you asked.

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

@roji Is there any way to cache authorities for pooled connection strings?

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

@roji Could you review it?

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for taking so long to do this @YohDeadfall.

I gave it a somewhat superficial review, since I'm not very knowledgeable in the actual spatial details etc. Every looks good apart from some small stuff, see below (especially the geography support).

Take a look at those and then feel free to merge, thanks!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any thoughts about supporting geography as well as geometry?

For the NTS plugin I added this in 8430f7a, it's trivial. The wire representation of geometry and geography is the same (WKB), the only difference is what happens when you run PostGIS functions on them; for example, ST_Distance() has an overload for geometry and another for geometry - but Npgsql doesn't to care about that.

So supporting geography in Npgsql is basically a matter of allowing users to specify NpgsqlDbType.Geography in order to send the geography type OID instead of the geometry one...

@YohDeadfall YohDeadfall May 14, 2018 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should swap CLR mappings and use geography as the default type? Or add an option to choose the default type?

public static INpgsqlTypeMapper UseGeoJsonForGeography(this INpgsqlTypeMapper mapper, GeoJSONOption option = GeoJSONOption.None, bool implicitMapping = true);
public static INpgsqlTypeMapper UseGeoJsonForGeometry(this INpgsqlTypeMapper mapper, GeoJSONOption option = GeoJSONOption.None, bool implicitMapping = false);
// or
public static INpgsqlTypeMapper UseGeoJsonForGeometry(this INpgsqlTypeMapper mapper, GeoJSONOption option = GeoJSONOption.None, bool geometryAsDefault = false);

I think that the first one is better because it registers only one factory which will fetch authorities when constructing a handler.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that geography definitely shouldn't be the default type... geography is much more limited in terms of operations you can execute (because it's much more complicated), all operations cost much more in terms of CPU (again, much more complicated :)), and it's only needed when working on a large or global scale (see these notes in the PostGIS docs). Npgsql has actually never supported geography with the legacy built-in types and very few people complained, I think it's pretty rare.

I guess a bool flag to UseGeoJSON() for using geography by default could be a good idea... By the way, if somebody wants to map everything to geography instead of geometry, it's pretty trivial to write some code in the models' OnModelConfiguring() which finds all spatial properties and sets their column type to geography. But if we can help out with a flag, why not.

If you add this flag, can you submit a PR doing the same for the NTS plugin?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, but what is about fetching authorities? Each factory (for geometry and geography) will request records from spatial_ref_sys when GeoJSONOptions.ShortCRS or GeoJSONOptions.LongCRS is specified. I can fix it, but it would be tricky (linked factories).

I think that type handling could be optimized by caching handlers, because now Ngpsql queries types every time connection gets open and allocates memory for their handlers. If someone wants to reload handlers and their data, then he will use ReloadTypes.

@roji roji May 15, 2018 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know much about the authority records... Wouldn't the flag only affect the (default) mapping for the CLR types? In other words, in the current NTS plugin, CLR Point is (by default) mapped to to the geometry mapping, not geography (i.e. an instance of NetTopologySuiteGeometryTypeMapping). If you make it mapped to the NetTopologySuiteGeographyTypeMapping instance instead (when the flag is specified), isn't that enough?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The flag isn't related to authorities.

Comment thread src/Npgsql.GeoJSON/GeoJSONHandler.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This SQL gets executed every time a physical connection is made. This isn't the end of the world (because it's per physical connection, not pooled), but you may still want to consider a cache based on the connection string to load it only once. Although I see that you load from database only if special options are specified, so it may not be worth it etc.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but there are a few thousand records. Fetching them each time will hurt performance.

Comment thread src/Npgsql.GeoJSON/GeoJSONHandler.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I usually indent case at the same level as the enclosing switch, i.e. like a goto label (which is what case labels really are). Similarly, I don't indent for curly braces and for the code (two levels of indentation), one is enough.

This reduces multiple levels of indentation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Visual Studio changed that. Will fix.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, there's place where you can configure that (or at least with Resharper)

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

I done some renames (for GeoJSONOptions and its values) and fixed tests. CRS map caching will be in an additional pull request.

@roji I'm waiting for your comment about geography support, and going to merge it after that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The flag isn't related to authorities.

Comment thread src/Npgsql.GeoJSON/GeoJSONHandler.cs Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is here. If I add mappings both for geometry and geography, then AddMapping will be called twice. This means that the Create method will be called twice too, and the query above will be executed twice.

There are two ways to fix the problem. The first one is hacky and works only for pooled connections, but it allows to register both mappings:

public static INpgsqlTypeMapper UseGeoJson(this INpgsqlTypeMapper mapper, GeoJSONOption option = GeoJSONOption.None, bool geographyAsDefault = false);
CrsMap GetCrsMap(NpgsqlConnection conn)
{
    if ((_options & (GeoJSONOptions.ShortCRS | GeoJSONOptions.LongCRS)) == GeoJSONOptions.None)
        return default;

    if (s_crsMaps.TryGetValue(conn.ConnectionString, out var crsMap))
        return crsMap;

    var connString = new NpgsqlConnectionStringBuilder(conn.ConnectionString);
    if (connString.Pooling)
    {
        var builder = new CrsMapBuilder();
        using (var cmd = new NpgsqlCommand(
                "SELECT min(srid), max(srid), auth_name " +
                "FROM(SELECT srid, auth_name, srid - rank() OVER(ORDER BY srid) AS range " +
                "FROM spatial_ref_sys) AS s GROUP BY range, auth_name ORDER BY 1;", conn))
        using (var reader = cmd.ExecuteReader())
            while (reader.Read())
            {
                builder.Add(new CrsMapEntry(
                    reader.GetInt32(0),
                    reader.GetInt32(1),
                    reader.GetString(2)));
            }

        crsMap = builder.Build();

        lock (s_crsMaps)
            s_crsMaps.Add(conn.ConnectionString, crsMap);
    }

    return crsMap;
}

The second way isn't tricky, but it allows only one type mapping. It's possible to support two mappings at the same time, but then the query will be executed twice. The advantage here is that an user is responsible for his own actions.

public static INpgsqlTypeMapper UseGeoJsonForGeography(this INpgsqlTypeMapper mapper, GeoJSONOption option = GeoJSONOption.None);
public static INpgsqlTypeMapper UseGeoJsonForGeometry(this INpgsqlTypeMapper mapper, GeoJSONOption option = GeoJSONOption.None);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The big problem with the 2nd way (if I understand it correctly) is that you can't mix both geometry and geography in the same application - we should support this...

The first way doesn't seem too hacky to me... And regardless of the geography/geometry problem, it helps in that you don't have to load the authorities every time a physical connection is opened - only once. One thing I don't understand is why pooling has to be turned on - why not cache the authorities regardless of pooling? And second, instead of taking a lock, why not just have a ConcurrentDictionary and use GetOrAdd() with a lambda that executes the query?

@YohDeadfall YohDeadfall May 16, 2018 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

One thing I don't understand is why pooling has to be turned on - why not cache the authorities regardless of pooling?

I don't like static caches when their lifetime should depend on an object. It would be better to cache handlers with their data in the connection or in the related pool. So, it was a way to limit the authority map cache.

And second, instead of taking a lock, why not just have a ConcurrentDictionary and use GetOrAdd() with a lambda that executes the query?

It was a sketch (:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh ok :)

The code as it is now looks really OK to me - a single static ConcurrentDictionary cache should really be OK. I'm OK for merging.

@YohDeadfall
YohDeadfall merged commit 693de09 into npgsql:dev May 16, 2018
@YohDeadfall
YohDeadfall deleted the GeoJSON branch May 16, 2018 11:44
@YohDeadfall YohDeadfall added this to the 4.0 milestone May 16, 2018
@roji

roji commented May 16, 2018

Copy link
Copy Markdown
Member

Thanks @YohDeadfall!

I've done a big documentation update everywhere, and have added a specific page for the GeoJSON plugin, you're welcome to go over it (or any other part) and propose changes.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants