Skip to content

Commit

Permalink
Cleanup (#2794)
Browse files Browse the repository at this point in the history
  • Loading branch information
roji authored Jun 18, 2023
1 parent 459b27e commit 5784b52
Show file tree
Hide file tree
Showing 58 changed files with 193 additions and 232 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public override Expression GenerateCodeLiteral(object value)
{
var interval = (Interval)value;

return interval.HasStart && interval.HasEnd
return interval is { HasStart: true, HasEnd: true }
? Expression.New(
_constructor,
TimestampTzInstantMapping.GenerateCodeLiteral(interval.Start),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ private string GenerateLiteralCore(object value)

internal static Expression GenerateCodeLiteral(LocalDateTime dateTime)
{
if (dateTime.Second == 0 && dateTime.NanosecondOfSecond == 0)
if (dateTime is { Second: 0, NanosecondOfSecond: 0 })
{
return ConstantNew(ConstructorWithMinutes, dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute);
}
Expand Down
4 changes: 2 additions & 2 deletions src/EFCore.PG/Internal/IReadOnlyListExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ public static IReadOnlyList<T> Slice<T>(this IReadOnlyList<T> list, int start)

private sealed class IReadOnlyListSlice<T> : IReadOnlyList<T>
{
private IReadOnlyList<T> _underlying;
private int _start;
private readonly IReadOnlyList<T> _underlying;
private readonly int _start;

internal IReadOnlyListSlice(IReadOnlyList<T> underlying, int start)
{
Expand Down
1 change: 0 additions & 1 deletion src/EFCore.PG/Internal/NpgsqlSingletonOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ public virtual void Initialize(IDbContextOptions options)
public virtual void Validate(IDbContextOptions options)
{
var npgsqlOptions = options.FindExtension<NpgsqlOptionsExtension>() ?? new();
var coreOptions = options.FindExtension<CoreOptionsExtension>() ?? new();

if (PostgresVersion != npgsqlOptions.PostgresVersion)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ protected virtual void DiscoverPostgresExtensions(
/// </summary>
protected virtual void ProcessRowVersionProperty(IConventionProperty property, RelationalTypeMapping typeMapping)
{
if (property.ValueGenerated == ValueGenerated.OnAddOrUpdate
&& property.IsConcurrencyToken
if (property is { ValueGenerated: ValueGenerated.OnAddOrUpdate, IsConcurrencyToken: true }
&& typeMapping.StoreType == "xid")
{
property.Builder.HasColumnName("xmin");
Expand Down
3 changes: 1 addition & 2 deletions src/EFCore.PG/Metadata/Internal/NpgsqlAnnotationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ public override IEnumerable<IAnnotation> For(IColumn column, bool designTime)
var valueGenerationStrategy = valueGeneratedProperty.GetValueGenerationStrategy();
yield return new Annotation(NpgsqlAnnotationNames.ValueGenerationStrategy, valueGenerationStrategy);

if (valueGenerationStrategy == NpgsqlValueGenerationStrategy.IdentityByDefaultColumn ||
valueGenerationStrategy == NpgsqlValueGenerationStrategy.IdentityAlwaysColumn)
if (valueGenerationStrategy is NpgsqlValueGenerationStrategy.IdentityByDefaultColumn or NpgsqlValueGenerationStrategy.IdentityAlwaysColumn)
{
if (valueGeneratedProperty[NpgsqlAnnotationNames.IdentityOptions] is string identityOptions)
{
Expand Down
2 changes: 1 addition & 1 deletion src/EFCore.PG/Metadata/PostgresExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private static (string? Schema, string? Name, string? Version) Deserialize(IAnno
}

// TODO: Can't actually use schema and name...they might not be set when this is first called.
var schemaNameValue = value.Split(',').Select(x => x.Trim()).Select(x => x == "" || x == "''" ? null : x).ToArray();
var schemaNameValue = value.Split(',').Select(x => x.Trim()).Select(x => x is "" or "''" ? null : x).ToArray();
var schemaAndName = annotation.Name.Substring(NpgsqlAnnotationNames.PostgresExtensionPrefix.Length).Split('.');
switch (schemaAndName.Length)
{
Expand Down
12 changes: 6 additions & 6 deletions src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ protected override void Generate(

builder.Append("CREATE ");

if (operation[NpgsqlAnnotationNames.UnloggedTable] is bool unlogged && unlogged)
if (operation[NpgsqlAnnotationNames.UnloggedTable] is true)
{
builder.Append("UNLOGGED ");
}
Expand Down Expand Up @@ -312,8 +312,8 @@ protected override void Generate(AlterTableOperation operation, IModel? model, M
}

// Unlogged table (null is equivalent to false)
var oldUnlogged = operation.OldTable[NpgsqlAnnotationNames.UnloggedTable] is bool ou && ou;
var newUnlogged = operation[NpgsqlAnnotationNames.UnloggedTable] is bool nu && nu;
var oldUnlogged = operation.OldTable[NpgsqlAnnotationNames.UnloggedTable] is true;
var newUnlogged = operation[NpgsqlAnnotationNames.UnloggedTable] is true;

if (oldUnlogged != newUnlogged)
{
Expand Down Expand Up @@ -511,14 +511,14 @@ protected override void Generate(AlterColumnOperation operation, IModel? model,
builder.AppendLine(";");
}

if (operation.IsNullable && !operation.OldColumn.IsNullable)
if (operation is { IsNullable: true, OldColumn.IsNullable: false })
{
builder
.Append(alterBase)
.Append("DROP NOT NULL")
.AppendLine(";");
}
else if (!operation.IsNullable && operation.OldColumn.IsNullable)
else if (operation is { IsNullable: false, OldColumn.IsNullable: true })
{
// The column is being made non-nullable. Generate an update statement before doing that, to convert any existing null values to
// the default value (otherwise PostgreSQL fails).
Expand Down Expand Up @@ -2046,7 +2046,7 @@ private string IndexColumnList(IndexColumn[] columns, string? method)

// Of the built-in access methods, only btree (the default) supports
// sorting, thus we only want to emit sort options for btree indexes.
if (method is null || method == "btree")
if (method is null or "btree")
{
if (column.IsDescending)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class NpgsqlArrayMethodTranslator : IMethodCallTranslator
// ReSharper disable InconsistentNaming
private static readonly MethodInfo Array_IndexOf1 =
typeof(Array).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Single(m => m.Name == nameof(Array.IndexOf) && m.IsGenericMethod && m.GetParameters().Length == 2);
.Single(m => m is { Name: nameof(Array.IndexOf), IsGenericMethod: true } && m.GetParameters().Length == 2);

private static readonly MethodInfo Array_IndexOf2 =
typeof(Array).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public NpgsqlJsonDbFunctionsTranslator(
}

// The following are jsonb-only, not support on json
if (args.Any(a => a.TypeMapping is NpgsqlJsonTypeMapping jsonMapping && !jsonMapping.IsJsonb))
if (args.Any(a => a.TypeMapping is NpgsqlJsonTypeMapping { IsJsonb: false }))
{
throw new InvalidOperationException("JSON methods on EF.Functions only support the jsonb type, not json.");
}
Expand Down Expand Up @@ -109,8 +109,7 @@ SqlExpression Jsonb(SqlExpression e)

static SqlExpression RemoveConvert(SqlExpression e)
{
while (e is SqlUnaryExpression unary &&
(unary.OperatorType == ExpressionType.Convert || unary.OperatorType == ExpressionType.ConvertChecked))
while (e is SqlUnaryExpression { OperatorType: ExpressionType.Convert or ExpressionType.ConvertChecked } unary)
{
e = unary.Operand;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ public NpgsqlJsonDomTranslator(
}

if (member == RootElement &&
instance is ColumnExpression column &&
column.TypeMapping is NpgsqlJsonTypeMapping)
instance is ColumnExpression { TypeMapping: NpgsqlJsonTypeMapping } column)
{
// Simply get rid of the RootElement member access
return column;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,8 @@ public NpgsqlLikeTranslator(NpgsqlSqlExpressionFactory sqlExpressionFactory)

var (match, pattern) = (arguments[1], arguments[2]);

if (pattern is SqlConstantExpression constantPattern &&
constantPattern.Value is string patternValue &&
!patternValue.Contains("\\"))
if (pattern is SqlConstantExpression { Value: string patternValue }
&& !patternValue.Contains('\\'))
{
return sensitive
? _sqlExpressionFactory.Like(match, pattern)
Expand All @@ -89,4 +88,4 @@ constantPattern.Value is string patternValue &&
? _sqlExpressionFactory.Like(match, pattern, _sqlExpressionFactory.Constant(string.Empty))
: _sqlExpressionFactory.ILike(match, pattern, _sqlExpressionFactory.Constant(string.Empty));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public NpgsqlObjectToStringTranslator(IRelationalTypeMappingSource typeMappingSo

if (instance.Type == typeof(bool))
{
return instance is ColumnExpression columnExpression && columnExpression.IsNullable
return instance is ColumnExpression { IsNullable: true }
? _sqlExpressionFactory.Case(
new[]
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public NpgsqlRangeTranslator(
return null;
}

if (member.Name == nameof(NpgsqlRange<int>.LowerBound) || member.Name == nameof(NpgsqlRange<int>.UpperBound))
if (member.Name is nameof(NpgsqlRange<int>.LowerBound) or nameof(NpgsqlRange<int>.UpperBound))
{
var typeMapping = instance!.TypeMapping is NpgsqlRangeTypeMapping rangeMapping
? rangeMapping.SubtypeMapping
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public NpgsqlRowValueTranslator(NpgsqlSqlExpressionFactory sqlExpressionFactory)
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
// Translate ValueTuple.Create
if (method.DeclaringType == typeof(ValueTuple) && method.IsStatic && method.Name == nameof(ValueTuple.Create))
if (method.DeclaringType == typeof(ValueTuple) && method is { IsStatic: true, Name: nameof(ValueTuple.Create) })
{
return new PostgresRowValueExpression(arguments, method.ReturnType);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ private static readonly MethodInfo LastOrDefaultMethodInfoWithoutArgs
typeof(string).GetMethod(nameof(string.Join), new[] { typeof(char), typeof(string[]) })!;
private static readonly MethodInfo String_Join_generic1 =
typeof(string).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Single(m => m.Name == nameof(string.Join) && m.IsGenericMethod && m.GetParameters().Length == 2 && m.GetParameters()[0].ParameterType == typeof(string));
.Single(m => m is { Name: nameof(string.Join), IsGenericMethod: true } && m.GetParameters().Length == 2 && m.GetParameters()[0].ParameterType == typeof(string));
private static readonly MethodInfo String_Join_generic2 =
typeof(string).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Single(m => m.Name == nameof(string.Join) && m.IsGenericMethod && m.GetParameters().Length == 2 && m.GetParameters()[0].ParameterType == typeof(char));
.Single(m => m is { Name: nameof(string.Join), IsGenericMethod: true } && m.GetParameters().Length == 2 && m.GetParameters()[0].ParameterType == typeof(char));
// ReSharper restore InconsistentNaming

#endregion
Expand Down Expand Up @@ -501,7 +501,7 @@ private SqlExpression TranslateStartsEndsWith(SqlExpression instance, SqlExpress
: _sqlExpressionFactory.Equal(leftRight, castPattern);
}

private bool IsLikeWildChar(char c) => c == '%' || c == '_';
private bool IsLikeWildChar(char c) => c is '%' or '_';

private string EscapeLikePattern(string pattern)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,7 @@ protected override void Print(ExpressionPrinter expressionPrinter)

PostgresExpressionType.LTreeMatches
when Right.TypeMapping?.StoreType == "lquery" ||
Right.TypeMapping is NpgsqlArrayTypeMapping arrayMapping &&
arrayMapping.ElementTypeMapping.StoreType == "lquery"
=> "~",
Right.TypeMapping is NpgsqlArrayTypeMapping { ElementTypeMapping.StoreType: "lquery" } => "~",
PostgresExpressionType.LTreeMatches
when Right.TypeMapping?.StoreType == "ltxtquery"
=> "@",
Expand Down Expand Up @@ -156,7 +154,7 @@ Right.TypeMapping is NpgsqlArrayTypeMapping arrayMapping &&
expressionPrinter.Append(")");
}

static bool RequiresBrackets(SqlExpression expression) => expression is PostgresBinaryExpression || expression is LikeExpression;
static bool RequiresBrackets(SqlExpression expression) => expression is PostgresBinaryExpression or LikeExpression;
}

/// <inheritdoc />
Expand Down
10 changes: 3 additions & 7 deletions src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -464,13 +464,11 @@ protected virtual Expression VisitPostgresBinary(PostgresBinaryExpression binary
.Append(binaryExpression.OperatorType switch
{
PostgresExpressionType.Contains
when binaryExpression.Left.TypeMapping is NpgsqlInetTypeMapping ||
binaryExpression.Left.TypeMapping is NpgsqlCidrTypeMapping
when binaryExpression.Left.TypeMapping is NpgsqlInetTypeMapping or NpgsqlCidrTypeMapping
=> ">>",

PostgresExpressionType.ContainedBy
when binaryExpression.Left.TypeMapping is NpgsqlInetTypeMapping ||
binaryExpression.Left.TypeMapping is NpgsqlCidrTypeMapping
when binaryExpression.Left.TypeMapping is NpgsqlInetTypeMapping or NpgsqlCidrTypeMapping
=> "<<",

PostgresExpressionType.Contains => "@>",
Expand Down Expand Up @@ -500,9 +498,7 @@ binaryExpression.Left.TypeMapping is NpgsqlCidrTypeMapping

PostgresExpressionType.LTreeMatches
when binaryExpression.Right.TypeMapping.StoreType == "lquery" ||
binaryExpression.Right.TypeMapping is NpgsqlArrayTypeMapping arrayMapping &&
arrayMapping.ElementTypeMapping.StoreType == "lquery"
=> "~",
binaryExpression.Right.TypeMapping is NpgsqlArrayTypeMapping { ElementTypeMapping.StoreType: "lquery" } => "~",
PostgresExpressionType.LTreeMatches
when binaryExpression.Right.TypeMapping.StoreType == "ltxtquery"
=> "@",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,7 @@ protected virtual SqlExpression VisitUnknownBinary(

private static bool MayContainNulls(SqlExpression arrayExpression)
{
if (arrayExpression is SqlConstantExpression constantArrayExpression &&
constantArrayExpression.Value is Array constantArray)
if (arrayExpression is SqlConstantExpression { Value: Array constantArray })
{
for (var i = 0; i < constantArray.Length; i++)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,28 +284,24 @@ bool TryTranslateArguments(out SqlExpression[] sqlArguments)

private static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression)
if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression)
{
if (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked)
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}
var convertedType = unaryExpression.Type.UnwrapNullableType();

if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
innerType = Enum.GetUnderlyingType(innerType);
}
var convertedType = unaryExpression.Type.UnwrapNullableType();

if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}

Expand Down
9 changes: 2 additions & 7 deletions src/EFCore.PG/Query/NpgsqlSqlExpressionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -431,14 +431,9 @@ private SqlBinaryExpression ApplyTypeMappingOnSqlBinary(SqlBinaryExpression bina
|| leftType == typeof(TimeOnly)
)
|| rightType.FullName == "NodaTime.Period"
&& (
leftType.FullName == "NodaTime.LocalDateTime"
|| leftType.FullName == "NodaTime.LocalDate"
|| leftType.FullName == "NodaTime.LocalTime")
&& leftType.FullName is "NodaTime.LocalDateTime" or "NodaTime.LocalDate" or "NodaTime.LocalTime"
|| rightType.FullName == "NodaTime.Duration"
&& (
leftType.FullName == "NodaTime.Instant"
|| leftType.FullName == "NodaTime.ZonedDateTime"))
&& leftType.FullName is "NodaTime.Instant" or "NodaTime.ZonedDateTime")
{
var newLeft = ApplyTypeMapping(left, typeMapping);
var newRight = ApplyDefaultTypeMapping(right);
Expand Down
17 changes: 4 additions & 13 deletions src/EFCore.PG/Scaffolding/Internal/NpgsqlDatabaseModelFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1133,7 +1133,7 @@ FROM pg_collation coll
private static void AdjustDefaults(DatabaseColumn column, string systemTypeName)
{
var defaultValue = column.DefaultValueSql;
if (defaultValue is null || defaultValue == "(NULL)")
if (defaultValue is null or "(NULL)")
{
column.DefaultValueSql = null;
return;
Expand All @@ -1146,25 +1146,16 @@ private static void AdjustDefaults(DatabaseColumn column, string systemTypeName)

if (defaultValue == "0")
{
if (systemTypeName == "float4" ||
systemTypeName == "float8" ||
systemTypeName == "int2" ||
systemTypeName == "int4" ||
systemTypeName == "int8" ||
systemTypeName == "money" ||
systemTypeName == "numeric")
if (systemTypeName is "float4" or "float8" or "int2" or "int4" or "int8" or "money" or "numeric")
{
column.DefaultValueSql = null;
return;
}
}

if (defaultValue == "0.0" || defaultValue == "'0'::numeric")
if (defaultValue is "0.0" or "'0'::numeric")
{
if (systemTypeName == "numeric" ||
systemTypeName == "float4" ||
systemTypeName == "float8" ||
systemTypeName == "money")
if (systemTypeName is "numeric" or "float4" or "float8" or "money")
{
column.DefaultValueSql = null;
return;
Expand Down
Loading

0 comments on commit 5784b52

Please sign in to comment.