Skip to content

Commit

Permalink
Generate GEOMETRY (POINT) columns
Browse files Browse the repository at this point in the history
We previously generated PostgreSQL GEOMETRY (or GEOGRAPHY) columns, not
taking into account the CLR type. We now include that as a constraint on
the column.

Note that SRID support still needs to be done (npgsql#717).

Fixes npgsql#719
  • Loading branch information
roji committed Nov 29, 2018
1 parent ad4e0d6 commit 2174ba7
Show file tree
Hide file tree
Showing 2 changed files with 157 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using GeoAPI.Geometries;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Storage;
Expand All @@ -11,6 +13,19 @@ namespace Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal
{
public class NpgsqlNetTopologySuiteTypeMappingSourcePlugin : IRelationalTypeMappingSourcePlugin
{
static readonly Dictionary<string, Type> _storeTypeMappings
= new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase)
{
{ "GEOMETRY", typeof(IGeometry) },
{ "GEOMETRYCOLLECTION", typeof(IGeometryCollection) },
{ "LINESTRING", typeof(ILineString) },
{ "MULTILINESTRING", typeof(IMultiLineString) },
{ "MULTIPOINT", typeof(IMultiPoint) },
{ "MULTIPOLYGON", typeof(IMultiPolygon) },
{ "POINT", typeof(IPoint) },
{ "POLYGON", typeof(IPolygon) }
};

// Note: we reference the options rather than copying IsGeographyDefault out, because that field is initialized
// rather late by SingletonOptionsInitializer
readonly INpgsqlNetTopologySuiteOptions _options;
Expand All @@ -21,17 +36,96 @@ public NpgsqlNetTopologySuiteTypeMappingSourcePlugin([NotNull] INpgsqlNetTopolog
public virtual RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
{
var clrType = mappingInfo.ClrType;
var storeTypeName = mappingInfo.StoreTypeName;
var storeType = mappingInfo.StoreTypeName;

// TODO: Array
return clrType != null && typeof(IGeometry).IsAssignableFrom(clrType) ||
storeTypeName != null && (
storeTypeName.Equals("geometry", StringComparison.OrdinalIgnoreCase) ||
storeTypeName.Equals("geography", StringComparison.OrdinalIgnoreCase))
? (RelationalTypeMapping)Activator.CreateInstance(
typeof(NpgsqlGeometryTypeMapping<>).MakeGenericType(clrType ?? typeof(IGeometry)),
storeTypeName ?? (_options.IsGeographyDefault ? "geography" : "geometry"))
: null;
// TODO: SRID (https://github.com/aspnet/EntityFrameworkCore/issues/14000)

if (clrType != null)
{
if (typeof(IGeometry).IsAssignableFrom(clrType) &&
(storeType != null || TryGetStoreType(clrType, _options.IsGeographyDefault, null, out storeType)))
{
return (RelationalTypeMapping)Activator.CreateInstance(
typeof(NpgsqlGeometryTypeMapping<>).MakeGenericType(clrType),
storeType);
}
}
else if (storeType != null)
{
var x = ParseGeometryStoreType(storeType);
if (!x.HasValue)
return null;

if (!_storeTypeMappings.TryGetValue(x.Value.SpatialType ?? "geometry", out clrType))
return null;

return (RelationalTypeMapping)Activator.CreateInstance(
typeof(NpgsqlGeometryTypeMapping<>).MakeGenericType(clrType),
storeType);
}

return null;
}

static readonly Regex _storeTypeRegex = new Regex(@"^(GEOMETRY|GEOGRAPHY)\s*(\((\w+)(,(\d+))?\))?$", RegexOptions.IgnoreCase);

/// <summary>
/// Given a PostgreSQL store type, attempts to parse it down to its components.
/// </summary>
/// <param name="storeType">A PostgreSQL store type string representation (e.g. GEOMETRY (POINT,4269))</param>
/// <returns>The different components of the store type, or null if <paramref name="storeType"/> isn't a spatial type.</returns>
public static (bool IsGeography, string SpatialType, int? Srid)? ParseGeometryStoreType(string storeType)
{
var m = _storeTypeRegex.Match(storeType);
if (!m.Success)
return null;

return (
string.Equals(m.Groups[1].Value, "GEOGRAPHY", StringComparison.OrdinalIgnoreCase),
m.Groups[3].Success ? m.Groups[3].Value : null,
m.Groups[5].Success ? (int?)int.Parse(m.Groups[5].Value) : null);
}

static bool TryGetStoreType(Type clrType, bool isGeography, int? srid, out string storeType)
{
var sb = new StringBuilder(isGeography ? "GEOGRAPHY" : "GEOMETRY");
if (typeof(ILineString).IsAssignableFrom(clrType))
sb.Append(" (LINESTRING");
else if (typeof(IMultiLineString).IsAssignableFrom(clrType))
sb.Append(" (MULTILINESTRING");
else if (typeof(IMultiPoint).IsAssignableFrom(clrType))
sb.Append(" (MULTIPOINT");
else if (typeof(IMultiPolygon).IsAssignableFrom(clrType))
sb.Append(" (MULTIPOLYGON");
else if (typeof(IPoint).IsAssignableFrom(clrType))
sb.Append(" (POINT");
else if (typeof(IPolygon).IsAssignableFrom(clrType))
sb.Append(" (POLYGON");
else if (typeof(IGeometryCollection).IsAssignableFrom(clrType))
sb.Append(" (GEOMETRYCOLLECTION");
else if (typeof(IGeometry).IsAssignableFrom(clrType))
{
if (!srid.HasValue)
{
storeType = sb.ToString();
return true;
}

sb.Append(" (GEOMETRY");
}
else
{
storeType = null;
return false;
}

if (srid.HasValue)
sb.Append(',').Append(srid.Value);
sb.Append(')');

storeType = sb.ToString();
return true;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
using Microsoft.EntityFrameworkCore.Storage;
using Npgsql.EntityFrameworkCore.PostgreSQL.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal;
using Xunit;

namespace Npgsql.EntityFrameworkCore.PostgreSQL.Storage
{
public class NpgsqlNetTopologySuiteTypeMappingSourcePluginTest
{
[Theory]
[InlineData(typeof(IPoint), "GEOMETRY (POINT)")]
[InlineData(typeof(IGeometry), "GEOMETRY")]
[InlineData(typeof(string), null)]
public void Geom_by_ClrType(Type clrType, string storeType)
=> Assert.Equal(storeType, _geomPlugin.FindMapping(new RelationalTypeMappingInfo(clrType))?.StoreType);

[Theory]
[InlineData(typeof(IPoint), "GEOGRAPHY (POINT)")]
[InlineData(typeof(IGeometry), "GEOGRAPHY")]
[InlineData(typeof(string), null)]
public void Geog_by_ClrType(Type clrType, string storeType)
=> Assert.Equal(storeType, _geogPlugin.FindMapping(new RelationalTypeMappingInfo(clrType))?.StoreType);

[Theory]
[InlineData("GEOMETRY (POINT)", typeof(IPoint))]
[InlineData("GEOGRAPHY (POINT)", typeof(IPoint))]
[InlineData("GEOMETRY", typeof(IGeometry))]
[InlineData("text", null)]
public void By_StoreType(string storeType, Type clrType)
=> Assert.Equal(clrType, _geomPlugin.FindMapping(new RelationalTypeMappingInfo(storeType))?.ClrType);

[Theory]
[MemberData(nameof(GetParseData))]
public void ParseGeometryStoreType(string storeType, (bool IsGeography, string SpatialType, int? Srid)? expected)
=> Assert.Equal(expected, NpgsqlNetTopologySuiteTypeMappingSourcePlugin.ParseGeometryStoreType(storeType));

static IEnumerable<object[]> GetParseData() => new[]
{
new object[] { "geography (point,123)", (ValueTuple<bool, string, int?>)(true, "point", 123) },
new object[] { "GEOGRAPHY (point)", (ValueTuple<bool, string, int?>)(true, "point", null) },
new object[] { "geometry", (ValueTuple<bool, string, int?>)(false, null, null) },
new object[] { "geometry (geometry)", (ValueTuple<bool, string, int?>)(false, "geometry", null) },
new object[] { "text", null }
};

readonly NpgsqlNetTopologySuiteTypeMappingSourcePlugin _geomPlugin =
new NpgsqlNetTopologySuiteTypeMappingSourcePlugin(new NpgsqlNetTopologySuiteOptions());
readonly NpgsqlNetTopologySuiteTypeMappingSourcePlugin _geogPlugin =
new NpgsqlNetTopologySuiteTypeMappingSourcePlugin(new NpgsqlNetTopologySuiteOptions() { IsGeographyDefault = true });
}
}

0 comments on commit 2174ba7

Please sign in to comment.