Repository navigation
Added GeoJSON support - #1854
Conversation
|
@YohDeadfall is it ready for reviewing? |
|
Yes, it's ready. Is there any way to get the exception details from Travis CI? Locally all tests pass. |
|
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? |
|
Found and fixed. When a NUnit test fails with What is a problem with AppVeyor again? |
roji
left a comment
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
A link to some sort of reference documentation/explanation for all the codes below would be good.
There was a problem hiding this comment.
It's from the spatial_ref_sys table. A query to fetch that data can be found here.
There was a problem hiding this comment.
Needs to be done in Npgsql.all.sln as well
There was a problem hiding this comment.
Also rename s_wellKnown to WellKnown to match static readonly naming convention.
There was a problem hiding this comment.
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...)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Maybe just do a switch? Would be faster (even if it's surely negligible)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
The ValidateAndGetLength(Polygon, ref NpgsqlLengthCache, NpgsqlParameter) method throws the exception in two places which are observable. It's more obvious.
There was a problem hiding this comment.
Please unindent case to the same level as the switch
|
Rebased and squashed as you asked. |
|
@roji Is there any way to cache authorities for pooled connection strings? |
|
@roji Could you review it? |
roji
left a comment
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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...
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
The flag isn't related to authorities.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Yes, but there are a few thousand records. Fetching them each time will hurt performance.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Visual Studio changed that. Will fix.
There was a problem hiding this comment.
Yeah, there's place where you can configure that (or at least with Resharper)
|
I done some renames (for @roji I'm waiting for your comment about |
There was a problem hiding this comment.
The flag isn't related to authorities.
There was a problem hiding this comment.
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);There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 (:
There was a problem hiding this comment.
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.
|
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. |
Features:
ST_AsGeoJSON.Tests:
Fixes #1787