diff --git a/src/EFCore.PG.NTS/Infrastructure/Internal/NetTopologySuiteDataSourceConfigurationPlugin.cs b/src/EFCore.PG.NTS/Infrastructure/Internal/NetTopologySuiteDataSourceConfigurationPlugin.cs index d258c2889..e8b06a835 100644 --- a/src/EFCore.PG.NTS/Infrastructure/Internal/NetTopologySuiteDataSourceConfigurationPlugin.cs +++ b/src/EFCore.PG.NTS/Infrastructure/Internal/NetTopologySuiteDataSourceConfigurationPlugin.cs @@ -1,5 +1,3 @@ -using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; - namespace Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal; /// diff --git a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs index c3a57fffa..86de97978 100644 --- a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs +++ b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs @@ -28,10 +28,10 @@ public NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin( throw new ArgumentException($"Must be an {nameof(NpgsqlSqlExpressionFactory)}", nameof(sqlExpressionFactory)); } - Translators = new IAggregateMethodCallTranslator[] - { + Translators = + [ new NpgsqlNetTopologySuiteAggregateMethodTranslator(npgsqlSqlExpressionFactory, typeMappingSource) - }; + ]; } /// @@ -103,19 +103,18 @@ public NpgsqlNetTopologySuiteAggregateMethodTranslator( // https://postgis.net/docs/ST_ConvexHull.html return _sqlExpressionFactory.Function( "ST_ConvexHull", - new[] - { + [ _sqlExpressionFactory.AggregateFunction( "ST_Collect", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, - argumentsPropagateNullability: new[] { false }, + argumentsPropagateNullability: [false], typeof(Geometry), GetMapping()) - }, + ], nullable: true, - argumentsPropagateNullability: new[] { true }, + argumentsPropagateNullability: [true], typeof(Geometry), GetMapping()); } @@ -127,10 +126,10 @@ public NpgsqlNetTopologySuiteAggregateMethodTranslator( return _sqlExpressionFactory.Convert( _sqlExpressionFactory.AggregateFunction( "ST_Extent", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, - argumentsPropagateNullability: new[] { false }, + argumentsPropagateNullability: [false], typeof(Geometry), GetMapping()), typeof(Geometry), GetMapping()); @@ -140,10 +139,10 @@ public NpgsqlNetTopologySuiteAggregateMethodTranslator( { return _sqlExpressionFactory.AggregateFunction( method == UnionMethod ? "ST_Union" : "ST_Collect", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, - argumentsPropagateNullability: new[] { false }, + argumentsPropagateNullability: [false], typeof(Geometry), GetMapping()); } diff --git a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMemberTranslatorPlugin.cs b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMemberTranslatorPlugin.cs index 0bbeb6e0c..e9fb5ac9f 100644 --- a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMemberTranslatorPlugin.cs +++ b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMemberTranslatorPlugin.cs @@ -20,7 +20,7 @@ public NpgsqlNetTopologySuiteMemberTranslatorPlugin( IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sqlExpressionFactory) { - Translators = new IMemberTranslator[] { new NpgsqlGeometryMemberTranslator(sqlExpressionFactory, typeMappingSource), }; + Translators = [new NpgsqlGeometryMemberTranslator(sqlExpressionFactory, typeMappingSource)]; } /// diff --git a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMethodCallTranslatorPlugin.cs b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMethodCallTranslatorPlugin.cs index 0b5afb739..896589719 100644 --- a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMethodCallTranslatorPlugin.cs +++ b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteMethodCallTranslatorPlugin.cs @@ -27,7 +27,7 @@ public NpgsqlNetTopologySuiteMethodCallTranslatorPlugin( throw new ArgumentException($"Must be an {nameof(NpgsqlSqlExpressionFactory)}", nameof(sqlExpressionFactory)); } - Translators = new IMethodCallTranslator[] { new NpgsqlGeometryMethodTranslator(npgsqlSqlExpressionFactory, typeMappingSource), }; + Translators = [new NpgsqlGeometryMethodTranslator(npgsqlSqlExpressionFactory, typeMappingSource)]; } /// @@ -90,7 +90,7 @@ public NpgsqlGeometryMethodTranslator( { nameof(NpgsqlNetTopologySuiteDbFunctionsExtensions.Transform) => _sqlExpressionFactory.Function( "ST_Transform", - new[] { arguments[1], arguments[2] }, + [arguments[1], arguments[2]], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType, @@ -98,7 +98,7 @@ public NpgsqlGeometryMethodTranslator( nameof(NpgsqlNetTopologySuiteDbFunctionsExtensions.Force2D) => _sqlExpressionFactory.Function( "ST_Force2D", - new[] { arguments[1] }, + [arguments[1]], nullable: true, TrueArrays[1], method.ReturnType, @@ -110,9 +110,9 @@ public NpgsqlGeometryMethodTranslator( arguments[2]), nameof(NpgsqlNetTopologySuiteDbFunctionsExtensions.Distance) => - TranslateGeometryMethod(arguments[1], method, new[] { arguments[2], arguments[3] }), + TranslateGeometryMethod(arguments[1], method, [arguments[2], arguments[3]]), nameof(NpgsqlNetTopologySuiteDbFunctionsExtensions.IsWithinDistance) => - TranslateGeometryMethod(arguments[1], method, new[] { arguments[2], arguments[3], arguments[4] }), + TranslateGeometryMethod(arguments[1], method, [arguments[2], arguments[3], arguments[4]]), _ => null }; @@ -147,7 +147,7 @@ public NpgsqlGeometryMethodTranslator( { return _sqlExpressionFactory.Function( "ST_GeometryN", - new[] { instance, OneBased(arguments[0]) }, + [instance, OneBased(arguments[0])], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType, diff --git a/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeAggregateMethodCallTranslatorPlugin.cs b/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeAggregateMethodCallTranslatorPlugin.cs index f4b7da247..32139bda9 100644 --- a/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeAggregateMethodCallTranslatorPlugin.cs +++ b/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeAggregateMethodCallTranslatorPlugin.cs @@ -25,10 +25,10 @@ public NpgsqlNodaTimeAggregateMethodCallTranslatorPlugin( throw new ArgumentException($"Must be an {nameof(NpgsqlSqlExpressionFactory)}", nameof(sqlExpressionFactory)); } - Translators = new IAggregateMethodCallTranslator[] - { + Translators = + [ new NpgsqlNodaTimeAggregateMethodTranslator(npgsqlSqlExpressionFactory, typeMappingSource) - }; + ]; } /// @@ -87,19 +87,19 @@ public NpgsqlNodaTimeAggregateMethodTranslator( return method.Name switch { nameof(NpgsqlNodaTimeDbFunctionsExtensions.Sum) => _sqlExpressionFactory.AggregateFunction( - "sum", new[] { sqlExpression }, source, nullable: true, argumentsPropagateNullability: FalseArrays[1], + "sum", [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], returnType: sqlExpression.Type, sqlExpression.TypeMapping), nameof(NpgsqlNodaTimeDbFunctionsExtensions.Average) => _sqlExpressionFactory.AggregateFunction( - "avg", new[] { sqlExpression }, source, nullable: true, argumentsPropagateNullability: FalseArrays[1], + "avg", [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], returnType: sqlExpression.Type, sqlExpression.TypeMapping), nameof(NpgsqlNodaTimeDbFunctionsExtensions.RangeAgg) => _sqlExpressionFactory.AggregateFunction( - "range_agg", new[] { sqlExpression }, source, nullable: true, argumentsPropagateNullability: FalseArrays[1], + "range_agg", [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], returnType: method.ReturnType, _typeMappingSource.FindMapping(method.ReturnType)), nameof(NpgsqlNodaTimeDbFunctionsExtensions.RangeIntersectAgg) => _sqlExpressionFactory.AggregateFunction( - "range_intersect_agg", new[] { sqlExpression }, source, nullable: true, argumentsPropagateNullability: FalseArrays[1], + "range_intersect_agg", [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], returnType: sqlExpression.Type, sqlExpression.TypeMapping), _ => null diff --git a/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMemberTranslatorPlugin.cs b/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMemberTranslatorPlugin.cs index e96117583..cda280630 100644 --- a/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMemberTranslatorPlugin.cs +++ b/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMemberTranslatorPlugin.cs @@ -21,10 +21,10 @@ public NpgsqlNodaTimeMemberTranslatorPlugin( IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sqlExpressionFactory) { - Translators = new IMemberTranslator[] - { - new NpgsqlNodaTimeMemberTranslator(typeMappingSource, (NpgsqlSqlExpressionFactory)sqlExpressionFactory), - }; + Translators = + [ + new NpgsqlNodaTimeMemberTranslator(typeMappingSource, (NpgsqlSqlExpressionFactory)sqlExpressionFactory) + ]; } /// @@ -196,7 +196,7 @@ SqlExpression TranslateDurationTotalMember(SqlExpression instance, double diviso return _sqlExpressionFactory.Not( _sqlExpressionFactory.Function( "lower_inf", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(bool))); @@ -207,7 +207,7 @@ SqlExpression TranslateDurationTotalMember(SqlExpression instance, double diviso return _sqlExpressionFactory.Not( _sqlExpressionFactory.Function( "upper_inf", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(bool))); @@ -223,7 +223,7 @@ SqlExpression TranslateDurationTotalMember(SqlExpression instance, double diviso SqlExpression Lower() => _sqlExpressionFactory.Function( "lower", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(Interval), @@ -232,7 +232,7 @@ SqlExpression Lower() SqlExpression Upper() => _sqlExpressionFactory.Function( "upper", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(Interval), @@ -270,7 +270,7 @@ SqlExpression Upper() SqlExpression Lower() => _sqlExpressionFactory.Function( "lower", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(LocalDate), @@ -279,7 +279,7 @@ SqlExpression Lower() SqlExpression Upper() => _sqlExpressionFactory.Function( "upper", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(LocalDate), @@ -304,7 +304,7 @@ SqlExpression Upper() "DayOfWeek" when GetDatePartExpression(instance, "dow", true) is var getValueExpression => _sqlExpressionFactory.Case( getValueExpression, - new[] { new CaseWhenClause(_sqlExpressionFactory.Constant(0), _sqlExpressionFactory.Constant(7)) }, + [new CaseWhenClause(_sqlExpressionFactory.Constant(0), _sqlExpressionFactory.Constant(7))], getValueExpression), // PG allows converting a timestamp directly to date, truncating the time; but given a timestamptz, it performs a time zone @@ -350,7 +350,7 @@ private SqlExpression GetDatePartExpressionDouble( { var result = _sqlExpressionFactory.Function( "date_part", - new[] { _sqlExpressionFactory.Constant(partName), instance }, + [_sqlExpressionFactory.Constant(partName), instance], nullable: true, argumentsPropagateNullability: TrueArrays[2], typeof(double)); @@ -359,7 +359,7 @@ private SqlExpression GetDatePartExpressionDouble( { result = _sqlExpressionFactory.Function( "floor", - new[] { result }, + [result], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(double)); diff --git a/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMethodCallTranslatorPlugin.cs b/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMethodCallTranslatorPlugin.cs index 1a3a9d7c7..2fac8c08e 100644 --- a/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMethodCallTranslatorPlugin.cs +++ b/src/EFCore.PG.NodaTime/Query/Internal/NpgsqlNodaTimeMethodCallTranslatorPlugin.cs @@ -23,10 +23,10 @@ public NpgsqlNodaTimeMethodCallTranslatorPlugin( IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sqlExpressionFactory) { - Translators = new IMethodCallTranslator[] - { - new NpgsqlNodaTimeMethodCallTranslator(typeMappingSource, (NpgsqlSqlExpressionFactory)sqlExpressionFactory), - }; + Translators = + [ + new NpgsqlNodaTimeMethodCallTranslator(typeMappingSource, (NpgsqlSqlExpressionFactory)sqlExpressionFactory) + ]; } /// @@ -336,8 +336,8 @@ public NpgsqlNodaTimeMethodCallTranslator( static PgFunctionExpression IntervalPart(string datePart, SqlExpression parameter) => PgFunctionExpression.CreateWithNamedArguments( "make_interval", - new[] { parameter }, - new[] { datePart }, + [parameter], + [datePart], nullable: true, argumentsPropagateNullability: TrueArrays[1], builtIn: true, diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/IntervalRangeMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/IntervalRangeMapping.cs index 6d0e08d12..e98372ccb 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/IntervalRangeMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/IntervalRangeMapping.cs @@ -1,7 +1,8 @@ -// ReSharper disable once CheckNamespace + using System.Text; using NodaTime.Text; +// ReSharper disable once CheckNamespace using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; // ReSharper disable once CheckNamespace diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/LegacyTimestampInstantMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/LegacyTimestampInstantMapping.cs index d2b6b7116..c31a179ec 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/LegacyTimestampInstantMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/LegacyTimestampInstantMapping.cs @@ -88,7 +88,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{GenerateLiteralCore(value)}"""; + => $""" + "{GenerateLiteralCore(value)}" + """; private string GenerateLiteralCore(object value) { diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/PeriodIntervalMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/PeriodIntervalMapping.cs index bd001d58a..99eba05e1 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/PeriodIntervalMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/PeriodIntervalMapping.cs @@ -94,7 +94,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{GenerateLiteralCore(value)}"""; + => $""" + "{GenerateLiteralCore(value)}" + """; private string GenerateLiteralCore(object value) => PeriodPattern.NormalizingIso.Format((Period)value); diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/TimeTzMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/TimeTzMapping.cs index 4cf64a6d8..7ffeb3116 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/TimeTzMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/TimeTzMapping.cs @@ -111,7 +111,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{Pattern.Format((OffsetTime)value)}"""; + => $""" + "{Pattern.Format((OffsetTime)value)}" + """; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampLocalDateTimeMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampLocalDateTimeMapping.cs index d9d069e0a..a3b2b47f5 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampLocalDateTimeMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampLocalDateTimeMapping.cs @@ -97,7 +97,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{Format((LocalDateTime)value)}"""; + => $""" + "{Format((LocalDateTime)value)}" + """; private static string Format(LocalDateTime localDateTime) { diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzInstantMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzInstantMapping.cs index 52da44391..bf6f741b2 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzInstantMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzInstantMapping.cs @@ -1,4 +1,3 @@ -using System.Globalization; using System.Text.Json; using Microsoft.EntityFrameworkCore.Storage.Json; using NodaTime.Text; @@ -88,7 +87,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{Format((Instant)value)}"""; + => $""" + "{Format((Instant)value)}" + """; private static string Format(Instant instant) { diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzOffsetDateTimeMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzOffsetDateTimeMapping.cs index 3fba21afe..8d54d819b 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzOffsetDateTimeMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzOffsetDateTimeMapping.cs @@ -97,7 +97,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{Format((OffsetDateTime)value)}"""; + => $""" + "{Format((OffsetDateTime)value)}" + """; private static string Format(OffsetDateTime offsetDateTime) => OffsetDateTimePattern.ExtendedIso.Format(offsetDateTime); diff --git a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzZonedDateTimeMapping.cs b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzZonedDateTimeMapping.cs index 03456b358..8ed3c499f 100644 --- a/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzZonedDateTimeMapping.cs +++ b/src/EFCore.PG.NodaTime/Storage/Internal/TimestampTzZonedDateTimeMapping.cs @@ -93,7 +93,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{Pattern.Format((ZonedDateTime)value)}"""; + => $""" + "{Pattern.Format((ZonedDateTime)value)}" + """; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.PG/Extensions/ExpressionVisitorExtensions.cs b/src/EFCore.PG/Extensions/ExpressionVisitorExtensions.cs index 25f9921f5..1007adc98 100644 --- a/src/EFCore.PG/Extensions/ExpressionVisitorExtensions.cs +++ b/src/EFCore.PG/Extensions/ExpressionVisitorExtensions.cs @@ -3,8 +3,6 @@ // ReSharper disable once CheckNamespace namespace System.Linq.Expressions; -#nullable enable - [DebuggerStepThrough] internal static class ExpressionVisitorExtensions { diff --git a/src/EFCore.PG/Extensions/MetadataExtensions/NpgsqlPropertyExtensions.cs b/src/EFCore.PG/Extensions/MetadataExtensions/NpgsqlPropertyExtensions.cs index af88adbf5..ce01fb60e 100644 --- a/src/EFCore.PG/Extensions/MetadataExtensions/NpgsqlPropertyExtensions.cs +++ b/src/EFCore.PG/Extensions/MetadataExtensions/NpgsqlPropertyExtensions.cs @@ -1,4 +1,3 @@ -using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal; diff --git a/src/EFCore.PG/Infrastructure/Internal/INpgsqlSingletonOptions.cs b/src/EFCore.PG/Infrastructure/Internal/INpgsqlSingletonOptions.cs index 97910f632..0f08a215f 100644 --- a/src/EFCore.PG/Infrastructure/Internal/INpgsqlSingletonOptions.cs +++ b/src/EFCore.PG/Infrastructure/Internal/INpgsqlSingletonOptions.cs @@ -1,7 +1,4 @@ -using System.Data.Common; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; - -namespace Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal; +namespace Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal; /// /// Represents options for Npgsql that can only be set at the singleton level. diff --git a/src/EFCore.PG/Infrastructure/Internal/NpgsqlOptionsExtension.cs b/src/EFCore.PG/Infrastructure/Internal/NpgsqlOptionsExtension.cs index 60c5cb59a..285ed2989 100644 --- a/src/EFCore.PG/Infrastructure/Internal/NpgsqlOptionsExtension.cs +++ b/src/EFCore.PG/Infrastructure/Internal/NpgsqlOptionsExtension.cs @@ -2,8 +2,6 @@ using System.Globalization; using System.Net.Security; using System.Text; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; namespace Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal; diff --git a/src/EFCore.PG/Internal/NpgsqlSingletonOptions.cs b/src/EFCore.PG/Internal/NpgsqlSingletonOptions.cs index 46c9f9a7c..5adba7a0c 100644 --- a/src/EFCore.PG/Internal/NpgsqlSingletonOptions.cs +++ b/src/EFCore.PG/Internal/NpgsqlSingletonOptions.cs @@ -1,7 +1,5 @@ -using System.Data.Common; -using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; +using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; namespace Npgsql.EntityFrameworkCore.PostgreSQL.Internal; diff --git a/src/EFCore.PG/Metadata/Conventions/NpgsqlConventionSetBuilder.cs b/src/EFCore.PG/Metadata/Conventions/NpgsqlConventionSetBuilder.cs index 6b296e878..1e1d22ae9 100644 --- a/src/EFCore.PG/Metadata/Conventions/NpgsqlConventionSetBuilder.cs +++ b/src/EFCore.PG/Metadata/Conventions/NpgsqlConventionSetBuilder.cs @@ -1,5 +1,4 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; namespace Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Conventions; diff --git a/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs b/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs index 5fadf3eba..78fde2980 100644 --- a/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs +++ b/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs @@ -146,10 +146,12 @@ public override string GetCreateIfNotExistsScript() /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public override string GetBeginIfNotExistsScript(string migrationId) - => $@" + => $""" + DO $EF$ BEGIN - IF NOT EXISTS(SELECT 1 FROM {SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema)} WHERE ""{MigrationIdColumnName}"" = '{migrationId}') THEN"; + IF NOT EXISTS(SELECT 1 FROM {SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema)} WHERE "{MigrationIdColumnName}" = '{migrationId}') THEN +"""; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -176,14 +178,6 @@ public override string GetEndIfScript() END $EF$; """; - private RelationalCommandParameterObject CreateRelationalCommandParameters() - => new( - Dependencies.Connection, - null, - null, - Dependencies.CurrentContext.Context, - Dependencies.CommandLogger, CommandSource.Migrations); - private sealed class DummyDisposable : IDisposable, IAsyncDisposable { public void Dispose() diff --git a/src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs b/src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs index 0d0969390..800941791 100644 --- a/src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs +++ b/src/EFCore.PG/Migrations/NpgsqlMigrationsSqlGenerator.cs @@ -84,7 +84,7 @@ void AddSequenceBumpingForSeeding() NpgsqlValueGenerationStrategy.IdentityByDefaultColumn or NpgsqlValueGenerationStrategy.IdentityAlwaysColumn or NpgsqlValueGenerationStrategy.SerialColumn)) - ?? Enumerable.Empty()) + ?? []) .Distinct() .ToArray(); @@ -116,12 +116,14 @@ or NpgsqlValueGenerationStrategy.IdentityAlwaysColumn // e.g. negative values seeded) builder .AppendLine( - @$"{selectOrPerform} setval( + $""" +{selectOrPerform} setval( pg_get_serial_sequence('{table}', '{unquotedColumn}'), GREATEST( (SELECT MAX({column}) FROM {table}) + 1, nextval(pg_get_serial_sequence('{table}', '{unquotedColumn}'))), - false);"); + false); +"""); } builder.EndCommand(); @@ -2194,11 +2196,11 @@ private string ColumnsToTsVector( "json" => string.Join( " || ", columnGroup.Select( c => - $@"json_to_tsvector({tsVectorConfigLiteral}, {JsonColumn(c)}, '""all""')")), + $"""json_to_tsvector({tsVectorConfigLiteral}, {JsonColumn(c)}, '"all"')""")), "jsonb" => string.Join( " || ", columnGroup.Select( c => - $@"jsonb_to_tsvector({tsVectorConfigLiteral}, {JsonColumn(c)}, '""all""')")), + $"""jsonb_to_tsvector({tsVectorConfigLiteral}, {JsonColumn(c)}, '"all"')""")), "null" => throw new InvalidOperationException( $"Column or index {columnOrIndexName} refers to unknown column in tsvector definition"), _ => throw new ArgumentOutOfRangeException() diff --git a/src/EFCore.PG/Properties/NpgsqlStrings.Designer.cs b/src/EFCore.PG/Properties/NpgsqlStrings.Designer.cs index 3bcd31e53..6e39cfd0e 100644 --- a/src/EFCore.PG/Properties/NpgsqlStrings.Designer.cs +++ b/src/EFCore.PG/Properties/NpgsqlStrings.Designer.cs @@ -1,11 +1,11 @@ // +#nullable enable + using System.Resources; using Microsoft.EntityFrameworkCore.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Diagnostics.Internal; -#nullable enable - namespace Npgsql.EntityFrameworkCore.PostgreSQL.Internal { /// diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlAggregateMethodCallTranslatorProvider.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlAggregateMethodCallTranslatorProvider.cs index 27574ff2b..7f8daed18 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlAggregateMethodCallTranslatorProvider.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlAggregateMethodCallTranslatorProvider.cs @@ -23,11 +23,10 @@ public NpgsqlAggregateMethodCallTranslatorProvider( var typeMappingSource = dependencies.RelationalTypeMappingSource; AddTranslators( - new IAggregateMethodCallTranslator[] - { - new NpgsqlQueryableAggregateMethodTranslator(sqlExpressionFactory, typeMappingSource), + [ + new NpgsqlQueryableAggregateMethodTranslator(sqlExpressionFactory, typeMappingSource), new NpgsqlStatisticsAggregateMethodTranslator(sqlExpressionFactory, typeMappingSource), new NpgsqlMiscAggregateMethodTranslator(sqlExpressionFactory, typeMappingSource, model) - }); + ]); } } diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlArrayMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlArrayMethodTranslator.cs index 286c87646..e128dacea 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlArrayMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlArrayMethodTranslator.cs @@ -84,7 +84,7 @@ public NpgsqlArrayMethodTranslator(NpgsqlSqlExpressionFactory sqlExpressionFacto { return _sqlExpressionFactory.Function( "get_byte", - new[] { arguments[0], arguments[1] }, + [arguments[0], arguments[1]], nullable: true, argumentsPropagateNullability: TrueArrays[2], typeof(byte)); @@ -159,7 +159,7 @@ static bool IsMappedToNonArray(SqlExpression arrayOrList) _sqlExpressionFactory.Subtract( _sqlExpressionFactory.Function( "array_position", - new[] { array, item, startIndex }, + [array, item, startIndex], nullable: true, TrueArrays[3], arrayOrList.Type), @@ -175,7 +175,7 @@ static bool IsMappedToNonArray(SqlExpression arrayOrList) return _sqlExpressionFactory.Function( "array_append", - new[] { array, item }, + [array, item], nullable: true, TrueArrays[2], arrayOrList.Type, @@ -188,11 +188,10 @@ static bool IsMappedToNonArray(SqlExpression arrayOrList) return _sqlExpressionFactory.Function( "array_cat", - new[] - { + [ _sqlExpressionFactory.ApplyTypeMapping(arrayOrList, inferredMapping), _sqlExpressionFactory.ApplyTypeMapping(arguments[0], inferredMapping) - }, + ], nullable: true, TrueArrays[2], arrayOrList.Type, diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlByteArrayMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlByteArrayMethodTranslator.cs index 3a9dc4a24..4a6a22659 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlByteArrayMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlByteArrayMethodTranslator.cs @@ -52,16 +52,15 @@ public NpgsqlByteArrayMethodTranslator(ISqlExpressionFactory sqlExpressionFactor // We have a byte value, but we need a bytea for PostgreSQL POSITION. var value = arguments[1] is SqlConstantExpression constantValue - ? (SqlExpression)_sqlExpressionFactory.Constant(new[] { (byte)constantValue.Value! }, typeMapping) + ? _sqlExpressionFactory.Constant(new[] { (byte)constantValue.Value! }, typeMapping) // Create bytea from non-constant byte: SELECT set_byte('\x00', 0, 8::smallint); : _sqlExpressionFactory.Function( "set_byte", - new[] - { + [ _sqlExpressionFactory.Constant(new[] { (byte)0 }, typeMapping), _sqlExpressionFactory.Constant(0), arguments[1] - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[3], typeof(byte[]), @@ -70,8 +69,8 @@ public NpgsqlByteArrayMethodTranslator(ISqlExpressionFactory sqlExpressionFactor return _sqlExpressionFactory.GreaterThan( PgFunctionExpression.CreateWithArgumentSeparators( "position", - new[] { value, source }, - new[] { "IN" }, // POSITION(x IN y) + [value, source], + ["IN"], // POSITION(x IN y) nullable: true, argumentsPropagateNullability: TrueArrays[2], builtIn: true, @@ -85,7 +84,7 @@ public NpgsqlByteArrayMethodTranslator(ISqlExpressionFactory sqlExpressionFactor return _sqlExpressionFactory.Convert( _sqlExpressionFactory.Function( "get_byte", - new[] { arguments[0], _sqlExpressionFactory.Constant(0) }, + [arguments[0], _sqlExpressionFactory.Constant(0)], nullable: true, argumentsPropagateNullability: TrueArrays[2], typeof(byte)), diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlDateTimeMemberTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlDateTimeMemberTranslator.cs index 73c2b578f..2cbac35b8 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlDateTimeMemberTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlDateTimeMemberTranslator.cs @@ -70,7 +70,7 @@ public NpgsqlDateTimeMemberTranslator(IRelationalTypeMappingSource typeMappingSo case { } when NpgsqlTypeMappingSource.LegacyTimestampBehavior: return _sqlExpressionFactory.Function( "date_trunc", - new[] { _sqlExpressionFactory.Constant("day"), instance }, + [_sqlExpressionFactory.Constant("day"), instance], nullable: true, argumentsPropagateNullability: TrueArrays[2], returnType, @@ -79,7 +79,7 @@ public NpgsqlDateTimeMemberTranslator(IRelationalTypeMappingSource typeMappingSo case { TypeMapping: NpgsqlTimestampTzTypeMapping }: return _sqlExpressionFactory.Function( "date_trunc", - new[] { _sqlExpressionFactory.Constant("day"), instance, _sqlExpressionFactory.Constant("UTC") }, + [_sqlExpressionFactory.Constant("day"), instance, _sqlExpressionFactory.Constant("UTC")], nullable: true, argumentsPropagateNullability: TrueArrays[3], returnType, @@ -112,7 +112,7 @@ public NpgsqlDateTimeMemberTranslator(IRelationalTypeMappingSource typeMappingSo nameof(DateTime.Today) => _sqlExpressionFactory.Function( "date_trunc", - new[] { _sqlExpressionFactory.Constant("day"), LocalNow() }, + [_sqlExpressionFactory.Constant("day"), LocalNow()], nullable: false, argumentsPropagateNullability: FalseArrays[2], typeof(DateTime), @@ -172,7 +172,7 @@ SqlExpression LocalNow() var result = _sqlExpressionFactory.Function( "date_part", - new[] { _sqlExpressionFactory.Constant(partName), instance }, + [_sqlExpressionFactory.Constant(partName), instance], nullable: true, argumentsPropagateNullability: TrueArrays[2], typeof(double)); @@ -181,7 +181,7 @@ SqlExpression LocalNow() { result = _sqlExpressionFactory.Function( "floor", - new[] { result }, + [result], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(double)); @@ -217,7 +217,7 @@ SqlExpression LocalNow() nameof(DateTimeOffset.Date) => _sqlExpressionFactory.Function( "date_trunc", - new SqlExpression[] { _sqlExpressionFactory.Constant("day"), _sqlExpressionFactory.AtUtc(instance) }, + [_sqlExpressionFactory.Constant("day"), _sqlExpressionFactory.AtUtc(instance)], nullable: true, argumentsPropagateNullability: TrueArrays[2], typeof(DateTime), diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlFullTextSearchMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlFullTextSearchMethodTranslator.cs index 7dc27b21c..e4db8fba8 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlFullTextSearchMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlFullTextSearchMethodTranslator.cs @@ -111,12 +111,11 @@ public NpgsqlFullTextSearchMethodTranslator( 3 => _sqlExpressionFactory.Function( rankFunctionName, - new[] - { + [ arguments[1].Type == typeof(float[]) ? arguments[1] : arguments[0], arguments[1].Type == typeof(float[]) ? arguments[0] : arguments[1], arguments[2] - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[3], typeof(float), @@ -124,7 +123,7 @@ public NpgsqlFullTextSearchMethodTranslator( 4 => _sqlExpressionFactory.Function( rankFunctionName, - new[] { arguments[1], arguments[0], arguments[2], arguments[3] }, + [arguments[1], arguments[0], arguments[2], arguments[3]], nullable: true, argumentsPropagateNullability: TrueArrays[4], method.ReturnType, @@ -181,7 +180,7 @@ public NpgsqlFullTextSearchMethodTranslator( arguments[1].Type == typeof(string) ? _sqlExpressionFactory.Function( "plainto_tsquery", - new[] { arguments[1] }, + [arguments[1]], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(NpgsqlTsQuery), @@ -211,7 +210,7 @@ public NpgsqlFullTextSearchMethodTranslator( nameof(NpgsqlFullTextSearchLinqExtensions.GetResultHeadline) when arguments.Count == 2 => _sqlExpressionFactory.Function( "ts_headline", - new[] { arguments[1], arguments[0] }, + [arguments[1], arguments[0]], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType), @@ -219,7 +218,7 @@ public NpgsqlFullTextSearchMethodTranslator( nameof(NpgsqlFullTextSearchLinqExtensions.GetResultHeadline) when arguments.Count == 3 => _sqlExpressionFactory.Function( "ts_headline", - new[] { arguments[1], arguments[0], arguments[2] }, + [arguments[1], arguments[0], arguments[2]], nullable: true, argumentsPropagateNullability: TrueArrays[3], method.ReturnType), @@ -227,8 +226,7 @@ public NpgsqlFullTextSearchMethodTranslator( nameof(NpgsqlFullTextSearchLinqExtensions.GetResultHeadline) when arguments.Count == 4 => _sqlExpressionFactory.Function( "ts_headline", - new[] - { + [ // For the regconfig parameter, if a constant string was provided, just pass it as a string - regconfig-accepting functions // will implicitly cast to regconfig. For (string!) parameters, we add an explicit cast, since regconfig actually is an OID // behind the scenes, and for parameter binary transfer no type coercion occurs. @@ -238,7 +236,7 @@ arguments[1] is SqlConstantExpression constant arguments[2], arguments[0], arguments[3] - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[4], method.ReturnType), @@ -310,8 +308,7 @@ arguments[1] is SqlConstantExpression constant SqlExpression ConfigAccepting(string functionName) => _sqlExpressionFactory.Function( - functionName, new[] - { + functionName, [ // For the regconfig parameter, if a constant string was provided, just pass it as a string - regconfig-accepting functions // will implicitly cast to regconfig. For (string!) parameters, we add an explicit cast, since regconfig actually is an OID // behind the scenes, and for parameter binary transfer no type coercion occurs. @@ -319,7 +316,7 @@ arguments[1] is SqlConstantExpression constant ? _sqlExpressionFactory.ApplyDefaultTypeMapping(constant) : _sqlExpressionFactory.Convert(arguments[1], typeof(string), _regconfigMapping), arguments[2] - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType, @@ -327,8 +324,7 @@ arguments[1] is SqlConstantExpression constant SqlExpression DictionaryAccepting(string functionName) => _sqlExpressionFactory.Function( - functionName, new[] - { + functionName, [ // For the regdictionary parameter, if a constant string was provided, just pass it as a string - regdictionary-accepting functions // will implicitly cast to regdictionary. For (string!) parameters, we add an explicit cast, since regdictionary actually is an OID // behind the scenes, and for parameter binary transfer no type coercion occurs. @@ -336,7 +332,7 @@ arguments[1] is SqlConstantExpression constant ? _sqlExpressionFactory.ApplyDefaultTypeMapping(constant) : _sqlExpressionFactory.Convert(arguments[1], typeof(string), _regdictionaryMapping), arguments[2] - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType, @@ -345,7 +341,7 @@ arguments[1] is SqlConstantExpression constant SqlExpression NonConfigAccepting(string functionName) => _sqlExpressionFactory.Function( functionName, - new[] { arguments[1] }, + [arguments[1]], nullable: true, argumentsPropagateNullability: TrueArrays[1], method.ReturnType, diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDbFunctionsTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDbFunctionsTranslator.cs index b1ee9e709..122b3e0c5 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDbFunctionsTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDbFunctionsTranslator.cs @@ -72,7 +72,7 @@ public NpgsqlJsonDbFunctionsTranslator( { return _sqlExpressionFactory.Function( ((NpgsqlJsonTypeMapping)args[0].TypeMapping!).IsJsonb ? "jsonb_typeof" : "json_typeof", - new[] { args[0] }, + [args[0]], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(string)); diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDomTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDomTranslator.cs index c314b5926..7a94102cb 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDomTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonDomTranslator.cs @@ -139,7 +139,7 @@ public NpgsqlJsonDomTranslator( { return _sqlExpressionFactory.Function( mapping.IsJsonb ? "jsonb_array_length" : "json_array_length", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(int)); diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonPocoTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonPocoTranslator.cs index 3a8118599..61a0946c3 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonPocoTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlJsonPocoTranslator.cs @@ -105,7 +105,7 @@ public NpgsqlJsonPocoTranslator( => ConvertFromText( _sqlExpressionFactory.JsonTraversal( columnExpression, - new[] { member }, + [member], returnsText: true, typeof(string), _stringTypeMapping), @@ -132,7 +132,7 @@ PgJsonTraversalExpression prevPathTraversal case ColumnExpression { TypeMapping: NpgsqlJsonTypeMapping mapping }: return _sqlExpressionFactory.Function( mapping.IsJsonb ? "jsonb_array_length" : "json_array_length", - new[] { expression }, + [expression], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(int)); @@ -150,7 +150,7 @@ PgJsonTraversalExpression prevPathTraversal var jsonMapping = (NpgsqlJsonTypeMapping)traversal.Expression.TypeMapping!; return _sqlExpressionFactory.Function( jsonMapping.IsJsonb ? "jsonb_array_length" : "json_array_length", - new[] { newTraversal }, + [newTraversal], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(int)); diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlLTreeTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlLTreeTranslator.cs index 270797f14..4875c2275 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlLTreeTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlLTreeTranslator.cs @@ -82,7 +82,7 @@ public NpgsqlLTreeTranslator( nameof(LTree.Subtree) => _sqlExpressionFactory.Function( "subltree", - new[] { instance!, arguments[0], arguments[1] }, + [instance!, arguments[0], arguments[1]], nullable: true, TrueArrays[3], typeof(LTree), @@ -112,7 +112,7 @@ public NpgsqlLTreeTranslator( nameof(LTree.LongestCommonAncestor) => _sqlExpressionFactory.Function( "lca", - new[] { arguments[0] }, + [arguments[0]], nullable: true, TrueArrays[1], typeof(LTree), @@ -139,7 +139,7 @@ public NpgsqlLTreeTranslator( => member.DeclaringType == typeof(LTree) && member.Name == nameof(LTree.NLevel) ? _sqlExpressionFactory.Function( "nlevel", - new[] { instance! }, + [instance!], nullable: true, TrueArrays[1], typeof(int)) diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMathTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMathTranslator.cs index 9568ba113..07919734b 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMathTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMathTranslator.cs @@ -83,22 +83,22 @@ public class NpgsqlMathTranslator : IMethodCallTranslator { typeof(BigInteger).GetRuntimeMethod(nameof(BigInteger.Min), [typeof(BigInteger), typeof(BigInteger)])!, "LEAST" }, }; - private static readonly IEnumerable TruncateMethodInfos = new[] - { + private static readonly IEnumerable TruncateMethodInfos = + [ typeof(Math).GetRequiredRuntimeMethod(nameof(Math.Truncate), typeof(decimal)), typeof(Math).GetRequiredRuntimeMethod(nameof(Math.Truncate), typeof(double)), typeof(MathF).GetRequiredRuntimeMethod(nameof(MathF.Truncate), typeof(float)) - }; + ]; - private static readonly IEnumerable RoundMethodInfos = new[] - { + private static readonly IEnumerable RoundMethodInfos = + [ typeof(Math).GetRequiredRuntimeMethod(nameof(Math.Round), typeof(decimal)), typeof(Math).GetRequiredRuntimeMethod(nameof(Math.Round), typeof(double)), typeof(MathF).GetRequiredRuntimeMethod(nameof(MathF.Round), typeof(float)) - }; + ]; - private static readonly IEnumerable SignMethodInfos = new[] - { + private static readonly IEnumerable SignMethodInfos = + [ typeof(Math).GetRuntimeMethod(nameof(Math.Sign), [typeof(decimal)])!, typeof(Math).GetRuntimeMethod(nameof(Math.Sign), [typeof(double)])!, typeof(Math).GetRuntimeMethod(nameof(Math.Sign), [typeof(float)])!, @@ -106,8 +106,8 @@ public class NpgsqlMathTranslator : IMethodCallTranslator typeof(Math).GetRuntimeMethod(nameof(Math.Sign), [typeof(long)])!, typeof(Math).GetRuntimeMethod(nameof(Math.Sign), [typeof(sbyte)])!, typeof(Math).GetRuntimeMethod(nameof(Math.Sign), [typeof(short)])!, - typeof(MathF).GetRuntimeMethod(nameof(MathF.Sign), [typeof(float)])!, - }; + typeof(MathF).GetRuntimeMethod(nameof(MathF.Sign), [typeof(float)])! + ]; private static readonly MethodInfo RoundDecimalTwoParams = typeof(Math).GetRuntimeMethod(nameof(Math.Round), [typeof(decimal), typeof(int)])!; @@ -188,9 +188,9 @@ public NpgsqlMathTranslator( // C# has Round over decimal/double/float only so our argument will be one of those types (compiler puts convert node) // In database result will be same type except for float which returns double which we need to cast back to float. - var result = (SqlExpression)_sqlExpressionFactory.Function( + var result = _sqlExpressionFactory.Function( "trunc", - new[] { argument }, + [argument], nullable: true, argumentsPropagateNullability: TrueArrays[1], argument.Type == typeof(float) ? typeof(double) : argument.Type); @@ -209,9 +209,9 @@ public NpgsqlMathTranslator( // C# has Round over decimal/double/float only so our argument will be one of those types (compiler puts convert node) // In database result will be same type except for float which returns double which we need to cast back to float. - var result = (SqlExpression)_sqlExpressionFactory.Function( + var result = _sqlExpressionFactory.Function( "round", - new[] { argument }, + [argument], nullable: true, argumentsPropagateNullability: TrueArrays[1], argument.Type == typeof(float) ? typeof(double) : argument.Type); @@ -244,11 +244,10 @@ public NpgsqlMathTranslator( { return _sqlExpressionFactory.Function( "round", - new[] - { + [ _sqlExpressionFactory.ApplyDefaultTypeMapping(arguments[0]), _sqlExpressionFactory.ApplyDefaultTypeMapping(arguments[1]) - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType, diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMemberTranslatorProvider.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMemberTranslatorProvider.cs index 18db4afb2..28ab9785a 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMemberTranslatorProvider.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMemberTranslatorProvider.cs @@ -35,16 +35,15 @@ public NpgsqlMemberTranslatorProvider( JsonPocoTranslator = new NpgsqlJsonPocoTranslator(typeMappingSource, sqlExpressionFactory, model); AddTranslators( - new IMemberTranslator[] - { - new NpgsqlBigIntegerMemberTranslator(sqlExpressionFactory), + [ + new NpgsqlBigIntegerMemberTranslator(sqlExpressionFactory), new NpgsqlDateTimeMemberTranslator(typeMappingSource, sqlExpressionFactory), new NpgsqlJsonDomTranslator(typeMappingSource, sqlExpressionFactory, model), new NpgsqlLTreeTranslator(typeMappingSource, sqlExpressionFactory, model), JsonPocoTranslator, new NpgsqlRangeTranslator(typeMappingSource, sqlExpressionFactory, model, supportsMultiranges), new NpgsqlStringMemberTranslator(sqlExpressionFactory), - new NpgsqlTimeSpanMemberTranslator(sqlExpressionFactory), - }); + new NpgsqlTimeSpanMemberTranslator(sqlExpressionFactory) + ]); } } diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMethodCallTranslatorProvider.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMethodCallTranslatorProvider.cs index 46a19b4b5..63843eab3 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMethodCallTranslatorProvider.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMethodCallTranslatorProvider.cs @@ -40,9 +40,8 @@ public NpgsqlMethodCallTranslatorProvider( LTreeTranslator = new NpgsqlLTreeTranslator(typeMappingSource, sqlExpressionFactory, model); AddTranslators( - new IMethodCallTranslator[] - { - new NpgsqlArrayMethodTranslator(sqlExpressionFactory, jsonTranslator), + [ + new NpgsqlArrayMethodTranslator(sqlExpressionFactory, jsonTranslator), new NpgsqlByteArrayMethodTranslator(sqlExpressionFactory), new NpgsqlConvertTranslator(sqlExpressionFactory), new NpgsqlDateTimeMethodTranslator(typeMappingSource, sqlExpressionFactory), @@ -62,7 +61,7 @@ public NpgsqlMethodCallTranslatorProvider( new NpgsqlRegexIsMatchTranslator(sqlExpressionFactory), new NpgsqlRowValueTranslator(sqlExpressionFactory), new NpgsqlStringMethodTranslator(typeMappingSource, sqlExpressionFactory), - new NpgsqlTrigramsMethodTranslator(typeMappingSource, sqlExpressionFactory, model), - }); + new NpgsqlTrigramsMethodTranslator(typeMappingSource, sqlExpressionFactory, model) + ]); } } diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMiscAggregateMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMiscAggregateMethodTranslator.cs index 1b972d54f..b938ecb96 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMiscAggregateMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlMiscAggregateMethodTranslator.cs @@ -71,11 +71,10 @@ public NpgsqlMiscAggregateMethodTranslator( return _sqlExpressionFactory.Coalesce( _sqlExpressionFactory.AggregateFunction( "string_agg", - new[] - { + [ sqlExpression, method == StringJoin ? arguments[0] : _sqlExpressionFactory.Constant(string.Empty, typeof(string)) - }, + ], source, nullable: true, // string_agg can return nulls regardless of the nullability of its arguments, since if there's an aggregate predicate @@ -93,7 +92,7 @@ public NpgsqlMiscAggregateMethodTranslator( case nameof(NpgsqlAggregateDbFunctionsExtensions.ArrayAgg): return _sqlExpressionFactory.AggregateFunction( "array_agg", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -105,7 +104,7 @@ public NpgsqlMiscAggregateMethodTranslator( case nameof(NpgsqlAggregateDbFunctionsExtensions.JsonAgg): return _sqlExpressionFactory.AggregateFunction( "json_agg", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -115,7 +114,7 @@ public NpgsqlMiscAggregateMethodTranslator( case nameof(NpgsqlAggregateDbFunctionsExtensions.JsonbAgg): return _sqlExpressionFactory.AggregateFunction( "jsonb_agg", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -125,7 +124,7 @@ public NpgsqlMiscAggregateMethodTranslator( case nameof(NpgsqlAggregateDbFunctionsExtensions.Sum): return _sqlExpressionFactory.AggregateFunction( "sum", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -135,7 +134,7 @@ public NpgsqlMiscAggregateMethodTranslator( case nameof(NpgsqlAggregateDbFunctionsExtensions.Average): return _sqlExpressionFactory.AggregateFunction( "avg", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -158,7 +157,7 @@ public NpgsqlMiscAggregateMethodTranslator( return _sqlExpressionFactory.AggregateFunction( isJsonb ? "jsonb_object_agg" : "json_object_agg", - new[] { keys, values }, + [keys, values], source, nullable: true, argumentsPropagateNullability: FalseArrays[2], @@ -176,7 +175,7 @@ public NpgsqlMiscAggregateMethodTranslator( return _sqlExpressionFactory.AggregateFunction( "range_agg", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -186,7 +185,7 @@ public NpgsqlMiscAggregateMethodTranslator( case nameof(NpgsqlRangeDbFunctionsExtensions.RangeIntersectAgg): return _sqlExpressionFactory.AggregateFunction( "range_intersect_agg", - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlObjectToStringTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlObjectToStringTranslator.cs index eddefd322..2a98b58ae 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlObjectToStringTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlObjectToStringTranslator.cs @@ -73,25 +73,23 @@ public NpgsqlObjectToStringTranslator(IRelationalTypeMappingSource typeMappingSo { return _sqlExpressionFactory.Case( instance, - new[] - { + [ new CaseWhenClause( _sqlExpressionFactory.Constant(false), _sqlExpressionFactory.Constant(false.ToString())), new CaseWhenClause( _sqlExpressionFactory.Constant(true), _sqlExpressionFactory.Constant(true.ToString())) - }, + ], _sqlExpressionFactory.Constant(string.Empty)); } return _sqlExpressionFactory.Case( - new[] - { + [ new CaseWhenClause( instance, _sqlExpressionFactory.Constant(true.ToString())) - }, + ], _sqlExpressionFactory.Constant(false.ToString())); } } diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlQueryableAggregateMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlQueryableAggregateMethodTranslator.cs index b1d8fae15..1cffc45fe 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlQueryableAggregateMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlQueryableAggregateMethodTranslator.cs @@ -62,7 +62,7 @@ public NpgsqlQueryableAggregateMethodTranslator( ? _sqlExpressionFactory.Convert( _sqlExpressionFactory.AggregateFunction( "avg", - new[] { averageSqlExpression }, + [averageSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -71,7 +71,7 @@ public NpgsqlQueryableAggregateMethodTranslator( averageSqlExpression.TypeMapping) : _sqlExpressionFactory.AggregateFunction( "avg", - new[] { averageSqlExpression }, + [averageSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -86,7 +86,7 @@ public NpgsqlQueryableAggregateMethodTranslator( return _sqlExpressionFactory.Convert( _sqlExpressionFactory.AggregateFunction( "count", - new[] { countSqlExpression }, + [countSqlExpression], source, nullable: false, argumentsPropagateNullability: FalseArrays[1], @@ -100,7 +100,7 @@ public NpgsqlQueryableAggregateMethodTranslator( var longCountSqlExpression = (source.Selector as SqlExpression) ?? _sqlExpressionFactory.Fragment("*"); return _sqlExpressionFactory.AggregateFunction( "count", - new[] { longCountSqlExpression }, + [longCountSqlExpression], source, nullable: false, argumentsPropagateNullability: FalseArrays[1], @@ -112,7 +112,7 @@ public NpgsqlQueryableAggregateMethodTranslator( && source.Selector is SqlExpression maxSqlExpression: return _sqlExpressionFactory.AggregateFunction( "max", - new[] { maxSqlExpression }, + [maxSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -125,7 +125,7 @@ public NpgsqlQueryableAggregateMethodTranslator( && source.Selector is SqlExpression minSqlExpression: return _sqlExpressionFactory.AggregateFunction( "min", - new[] { minSqlExpression }, + [minSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -147,7 +147,7 @@ public NpgsqlQueryableAggregateMethodTranslator( return _sqlExpressionFactory.Convert( _sqlExpressionFactory.AggregateFunction( "sum", - new[] { sumSqlExpression }, + [sumSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -161,7 +161,7 @@ public NpgsqlQueryableAggregateMethodTranslator( return _sqlExpressionFactory.Convert( _sqlExpressionFactory.AggregateFunction( "sum", - new[] { sumSqlExpression }, + [sumSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -172,7 +172,7 @@ public NpgsqlQueryableAggregateMethodTranslator( return _sqlExpressionFactory.AggregateFunction( "sum", - new[] { sumSqlExpression }, + [sumSqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlRangeTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlRangeTranslator.cs index 9e0bb9113..2b6747fdf 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlRangeTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlRangeTranslator.cs @@ -56,7 +56,7 @@ public NpgsqlRangeTranslator( return _sqlExpressionFactory.Not( _sqlExpressionFactory.Function( "isempty", - new[] { arguments[0] }, + [arguments[0]], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(bool))); @@ -76,11 +76,10 @@ public NpgsqlRangeTranslator( return _sqlExpressionFactory.Function( "range_merge", - new[] - { + [ _sqlExpressionFactory.ApplyTypeMapping(arguments[0], inferredMapping), _sqlExpressionFactory.ApplyTypeMapping(arguments[1], inferredMapping) - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType, @@ -95,7 +94,7 @@ public NpgsqlRangeTranslator( return _sqlExpressionFactory.Function( "range_merge", - new[] { arguments[0] }, + [arguments[0]], nullable: true, argumentsPropagateNullability: TrueArrays[1], method.ReturnType, @@ -153,7 +152,7 @@ public NpgsqlRangeTranslator( return _sqlExpressionFactory.Function( member.Name == nameof(NpgsqlRange.LowerBound) ? "lower" : "upper", - new[] { instance }, + [instance], nullable: true, argumentsPropagateNullability: TrueArrays[1], returnType, @@ -174,7 +173,7 @@ public NpgsqlRangeTranslator( SqlExpression SingleArgBoolFunction(string name, SqlExpression argument) => _sqlExpressionFactory.Function( name, - new[] { argument }, + [argument], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(bool)); diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStatisticsAggregateMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStatisticsAggregateMethodTranslator.cs index f902412b5..1bb84be83 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStatisticsAggregateMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStatisticsAggregateMethodTranslator.cs @@ -63,7 +63,7 @@ public NpgsqlStatisticsAggregateMethodTranslator( { return _sqlExpressionFactory.AggregateFunction( functionName, - new[] { sqlExpression }, + [sqlExpression], source, nullable: true, argumentsPropagateNullability: FalseArrays[1], @@ -101,7 +101,7 @@ public NpgsqlStatisticsAggregateMethodTranslator( return method.Name == nameof(NpgsqlAggregateDbFunctionsExtensions.RegrCount) ? _sqlExpressionFactory.AggregateFunction( functionName, - new[] { y, x }, + [y, x], source, nullable: true, argumentsPropagateNullability: FalseArrays[2], @@ -109,7 +109,7 @@ public NpgsqlStatisticsAggregateMethodTranslator( _longTypeMapping) : _sqlExpressionFactory.AggregateFunction( functionName, - new[] { y, x }, + [y, x], source, nullable: true, argumentsPropagateNullability: FalseArrays[2], diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMemberTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMemberTranslator.cs index d56c7a9d3..a64f931b1 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMemberTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMemberTranslator.cs @@ -35,7 +35,7 @@ public NpgsqlStringMemberTranslator(ISqlExpressionFactory sqlExpressionFactory) ? _sqlExpressionFactory.Convert( _sqlExpressionFactory.Function( "length", - new[] { instance! }, + [instance!], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(long)), diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMethodTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMethodTranslator.cs index dbd1c13be..d56f63380 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMethodTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlStringMethodTranslator.cs @@ -169,7 +169,7 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I var argument = arguments[0]; return _sqlExpressionFactory.Function( "substr", - new[] { argument, _sqlExpressionFactory.Constant(1), _sqlExpressionFactory.Constant(1) }, + [argument, _sqlExpressionFactory.Constant(1), _sqlExpressionFactory.Constant(1)], nullable: true, argumentsPropagateNullability: TrueArrays[3], method.ReturnType); @@ -180,17 +180,16 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I var argument = arguments[0]; return _sqlExpressionFactory.Function( "substr", - new[] - { + [ argument, _sqlExpressionFactory.Function( "length", - new[] { argument }, + [argument], nullable: true, - argumentsPropagateNullability: new[] { true }, + argumentsPropagateNullability: [true], typeof(int)), _sqlExpressionFactory.Constant(1) - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[3], method.ReturnType); @@ -209,11 +208,10 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I return _sqlExpressionFactory.Subtract( _sqlExpressionFactory.Function( "strpos", - new[] - { + [ _sqlExpressionFactory.ApplyTypeMapping(instance!, stringTypeMapping), _sqlExpressionFactory.ApplyTypeMapping(argument, stringTypeMapping) - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[2], method.ReturnType), @@ -228,12 +226,11 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I return _sqlExpressionFactory.Function( "replace", - new[] - { + [ _sqlExpressionFactory.ApplyTypeMapping(instance!, stringTypeMapping), _sqlExpressionFactory.ApplyTypeMapping(oldValue, stringTypeMapping), _sqlExpressionFactory.ApplyTypeMapping(newValue, stringTypeMapping) - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[3], method.ReturnType, @@ -244,7 +241,7 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I { return _sqlExpressionFactory.Function( method == ToLower ? "lower" : "upper", - new[] { instance! }, + [instance!], nullable: true, argumentsPropagateNullability: TrueArrays[1], method.ReturnType, @@ -275,7 +272,7 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I _sqlExpressionFactory.Equal( _sqlExpressionFactory.Function( "btrim", - new[] { argument, _whitespace }, + [argument, _whitespace], nullable: true, argumentsPropagateNullability: TrueArrays[2], argument.Type, @@ -310,13 +307,12 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I return _sqlExpressionFactory.Function( isTrimStart ? "ltrim" : isTrimEnd ? "rtrim" : "btrim", - new[] - { + [ instance!, trimChars is null || trimChars.Length == 0 ? _whitespace : _sqlExpressionFactory.Constant(new string(trimChars)) - }, + ], nullable: true, argumentsPropagateNullability: TrueArrays[2], instance!.Type, @@ -385,7 +381,7 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I return _sqlExpressionFactory.Function( "array_to_string", - new[] { arguments[1], arguments[0], _sqlExpressionFactory.Constant("") }, + [arguments[1], arguments[0], _sqlExpressionFactory.Constant("")], nullable: true, argumentsPropagateNullability: TrueArrays[3], typeof(string)); @@ -400,7 +396,7 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I { return _sqlExpressionFactory.Function( "reverse", - new[] { arguments[1] }, + [arguments[1]], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(string), @@ -412,9 +408,9 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I // Note that string_to_array always returns text[], regardless of the input type return _sqlExpressionFactory.Function( "string_to_array", - new[] { arguments[1], arguments[2] }, + [arguments[1], arguments[2]], nullable: true, - argumentsPropagateNullability: new[] { true, false }, + argumentsPropagateNullability: [true, false], typeof(string[]), _typeMappingSource.FindMapping(typeof(string[]))); } @@ -424,9 +420,9 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I // Note that string_to_array always returns text[], regardless of the input type return _sqlExpressionFactory.Function( "string_to_array", - new[] { arguments[1], arguments[2], arguments[3] }, + [arguments[1], arguments[2], arguments[3]], nullable: true, - argumentsPropagateNullability: new[] { true, false, false }, + argumentsPropagateNullability: [true, false, false], typeof(string[]), _typeMappingSource.FindMapping(typeof(string[]))); } @@ -435,9 +431,9 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I { return _sqlExpressionFactory.Function( "to_date", - new[] { arguments[1], arguments[2] }, + [arguments[1], arguments[2]], nullable: true, - argumentsPropagateNullability: new[] { true, true }, + argumentsPropagateNullability: [true, true], typeof(DateOnly), _typeMappingSource.FindMapping(typeof(DateOnly)) ); @@ -447,9 +443,9 @@ public NpgsqlStringMethodTranslator(NpgsqlTypeMappingSource typeMappingSource, I { return _sqlExpressionFactory.Function( "to_timestamp", - new[] { arguments[1], arguments[2] }, + [arguments[1], arguments[2]], nullable: true, - argumentsPropagateNullability: new[] { true, true }, + argumentsPropagateNullability: [true, true], typeof(DateTime), _typeMappingSource.FindMapping(typeof(DateTime)) ); diff --git a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlTimeSpanMemberTranslator.cs b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlTimeSpanMemberTranslator.cs index b4b59966b..a191699f2 100644 --- a/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlTimeSpanMemberTranslator.cs +++ b/src/EFCore.PG/Query/ExpressionTranslators/Internal/NpgsqlTimeSpanMemberTranslator.cs @@ -68,7 +68,7 @@ SqlExpression Floor(SqlExpression value) => _sqlExpressionFactory.Convert( _sqlExpressionFactory.Function( "floor", - new[] { value }, + [value], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(double)), @@ -76,7 +76,7 @@ SqlExpression Floor(SqlExpression value) SqlExpression DatePart(string part, SqlExpression value) => _sqlExpressionFactory.Function( - "date_part", new[] { _sqlExpressionFactory.Constant(part), value }, + "date_part", [_sqlExpressionFactory.Constant(part), value], nullable: true, argumentsPropagateNullability: FalseTrueArray, returnType); diff --git a/src/EFCore.PG/Query/Expressions/Internal/PgUnnestExpression.cs b/src/EFCore.PG/Query/Expressions/Internal/PgUnnestExpression.cs index d55fd4b8d..5d1a6b31a 100644 --- a/src/EFCore.PG/Query/Expressions/Internal/PgUnnestExpression.cs +++ b/src/EFCore.PG/Query/Expressions/Internal/PgUnnestExpression.cs @@ -59,7 +59,7 @@ public PgUnnestExpression(string alias, SqlExpression array, string columnName, } private PgUnnestExpression(string alias, SqlExpression array, ColumnInfo? columnInfo, bool withOrdinality = true) - : base(alias, "unnest", new[] { array }, columnInfo is null ? null : [columnInfo.Value], withOrdinality) + : base(alias, "unnest", [array], columnInfo is null ? null : [columnInfo.Value], withOrdinality) { } diff --git a/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs b/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs index a6d4a6871..40bbb33e8 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs @@ -1,7 +1,6 @@ using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.NetworkInformation; -using System.Text.Json; using System.Text.RegularExpressions; using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions; using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal; diff --git a/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs index 2224b09a2..9453c824b 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs @@ -125,7 +125,7 @@ protected override QueryableMethodTranslatingExpressionVisitor CreateSubqueryVis { // TODO: For geometry collection support (not yet supported), see #2850. selectExpression = new SelectExpression( - [new TableValuedFunctionExpression(tableAlias, "ST_Dump", new[] { sqlExpression })], + [new TableValuedFunctionExpression(tableAlias, "ST_Dump", [sqlExpression])], new ColumnExpression("geom", tableAlias, elementClrType.UnwrapNullableType(), elementTypeMapping, isElementNullable), identifier: [], // TODO _queryCompilationContext.SqlAliasManager); @@ -240,7 +240,7 @@ protected override ShapedQueryExpression TransformJsonQueryToTable(JsonQueryExpr // Construct the json_to_recordset around the JsonScalarExpression, and wrap it in a SelectExpression var jsonToRecordSetExpression = new PgTableValuedFunctionExpression( - tableAlias, functionName, new[] { jsonScalarExpression }, columnInfos, withOrdinality: true); + tableAlias, functionName, [jsonScalarExpression], columnInfos, withOrdinality: true); #pragma warning disable EF1001 // SelectExpression constructors are currently internal var selectExpression = CreateSelect( @@ -367,7 +367,7 @@ static IEnumerable GetAllNavigationsInHierarchy(IEntityType entityT _sqlExpressionFactory.GreaterThan( _sqlExpressionFactory.Function( "cardinality", - new[] { array }, + [array], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(int)), @@ -603,7 +603,7 @@ static IEnumerable GetAllNavigationsInHierarchy(IEntityType entityT _sqlExpressionFactory.IsNotNull( _sqlExpressionFactory.Function( "array_position", - new[] { array, translatedItem }, + [array, translatedItem], nullable: true, argumentsPropagateNullability: FalseArrays[2], typeof(int)))); @@ -613,7 +613,7 @@ static IEnumerable GetAllNavigationsInHierarchy(IEntityType entityT source, _sqlExpressionFactory.Contains( array, - _sqlExpressionFactory.NewArrayOrConstant(new[] { translatedItem }, array.Type, array.TypeMapping))); + _sqlExpressionFactory.NewArrayOrConstant([translatedItem], array.Type, array.TypeMapping))); // For constant arrays (new[] { 1, 2, 3 }) or inline arrays (new[] { 1, param, 3 }), don't do anything PG-specific for since // the general EF Core mechanism is fine for that case: item IN (1, 2, 3). @@ -658,7 +658,7 @@ static IEnumerable GetAllNavigationsInHierarchy(IEntityType entityT { var translation = _sqlExpressionFactory.Function( "cardinality", - new[] { array }, + [array], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(int)); diff --git a/src/EFCore.PG/Query/Internal/NpgsqlSqlNullabilityProcessor.cs b/src/EFCore.PG/Query/Internal/NpgsqlSqlNullabilityProcessor.cs index 215219f19..6424f37e5 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlSqlNullabilityProcessor.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlSqlNullabilityProcessor.cs @@ -288,7 +288,7 @@ protected virtual SqlExpression VisitAny(PgAnyExpression anyExpression, bool all _sqlExpressionFactory.IsNotNull( _sqlExpressionFactory.Function( "array_position", - new[] { array, _sqlExpressionFactory.Constant(null, item.Type, item.TypeMapping) }, + [array, _sqlExpressionFactory.Constant(null, item.Type, item.TypeMapping)], nullable: true, argumentsPropagateNullability: FalseArrays[2], typeof(int))))); diff --git a/src/EFCore.PG/Query/Internal/NpgsqlSqlTranslatingExpressionVisitor.cs b/src/EFCore.PG/Query/Internal/NpgsqlSqlTranslatingExpressionVisitor.cs index 9c4029c40..9ce217f02 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlSqlTranslatingExpressionVisitor.cs @@ -100,7 +100,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) { return _sqlExpressionFactory.Function( "length", - new[] { sqlOperand }, + [sqlOperand], nullable: true, argumentsPropagateNullability: TrueArrays[1], typeof(int)); @@ -195,8 +195,8 @@ when binaryExpression.Left.Type.UnwrapNullableType().FullName == "NodaTime.Local return PgFunctionExpression.CreateWithNamedArguments( "make_interval", - new[] { subtraction }, - new[] { "days" }, + [subtraction], + ["days"], nullable: true, argumentsPropagateNullability: TrueArrays[1], builtIn: true, @@ -477,13 +477,12 @@ when patternParameter.Name.StartsWith(QueryCompilationContext.QueryParameterPref translation = _sqlExpressionFactory.Function( methodType is StartsEndsWithContains.StartsWith ? "left" : "right", - new[] - { + [ translatedInstance, _sqlExpressionFactory.Function( - "length", new[] { translatedPattern }, nullable: true, - argumentsPropagateNullability: new[] { true }, typeof(int)) - }, nullable: true, argumentsPropagateNullability: new[] { true, true }, typeof(string), + "length", [translatedPattern], nullable: true, + argumentsPropagateNullability: [true], typeof(int)) + ], nullable: true, argumentsPropagateNullability: [true, true], typeof(string), stringTypeMapping); // LEFT/RIGHT of a citext return a text, so for non-default text mappings we apply an explicit cast. @@ -513,8 +512,8 @@ when patternParameter.Name.StartsWith(QueryCompilationContext.QueryParameterPref _sqlExpressionFactory.IsNotNull(translatedPattern), _sqlExpressionFactory.GreaterThan( _sqlExpressionFactory.Function( - "strpos", new[] { translatedInstance, translatedPattern }, nullable: true, - argumentsPropagateNullability: new[] { true, true }, typeof(int)), + "strpos", [translatedInstance, translatedPattern], nullable: true, + argumentsPropagateNullability: [true, true], typeof(int)), _sqlExpressionFactory.Constant(0)))); break; diff --git a/src/EFCore.PG/Scaffolding/Internal/NpgsqlDatabaseModelFactory.cs b/src/EFCore.PG/Scaffolding/Internal/NpgsqlDatabaseModelFactory.cs index 823a273a1..4af78bfc7 100644 --- a/src/EFCore.PG/Scaffolding/Internal/NpgsqlDatabaseModelFactory.cs +++ b/src/EFCore.PG/Scaffolding/Internal/NpgsqlDatabaseModelFactory.cs @@ -19,7 +19,7 @@ public class NpgsqlDatabaseModelFactory : DatabaseModelFactory { #region Fields - private const string NamePartRegex = @"(?:(?:""(?(?:(?:"""")|[^""])+)"")|(?[^\.\[""]+))"; + private const string NamePartRegex = """(?:(?:"(?(?:(?:"")|[^"])+)")|(?[^\.\["]+))"""; private static readonly Regex SchemaTableNameExtractor = new( diff --git a/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlIntervalTypeMapping.cs b/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlIntervalTypeMapping.cs index c5846088d..7bf603944 100644 --- a/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlIntervalTypeMapping.cs +++ b/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlIntervalTypeMapping.cs @@ -79,7 +79,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{FormatTimeSpanAsInterval((TimeSpan)value)}"""; + => $""" + "{FormatTimeSpanAsInterval((TimeSpan)value)}" + """; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTypeMapping.cs b/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTypeMapping.cs index c1e4ac41f..21e3fccf0 100644 --- a/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTypeMapping.cs +++ b/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTypeMapping.cs @@ -76,7 +76,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => $@"""{GenerateLiteralCore(value)}"""; + => $""" + "{GenerateLiteralCore(value)}" + """; private string GenerateLiteralCore(object value) => FormatDateTime((DateTime)value); diff --git a/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTzTypeMapping.cs b/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTzTypeMapping.cs index 0cba8cfe3..ef1ace200 100644 --- a/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTzTypeMapping.cs +++ b/src/EFCore.PG/Storage/Internal/Mapping/NpgsqlTimestampTzTypeMapping.cs @@ -84,7 +84,9 @@ protected override string GenerateNonNullSqlLiteral(object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected override string GenerateEmbeddedNonNullSqlLiteral(object value) - => @$"""{Format(value)}"""; + => $""" + "{Format(value)}" + """; private static string Format(object value) => value switch diff --git a/src/EFCore.PG/Storage/Internal/NpgsqlDatabaseCreator.cs b/src/EFCore.PG/Storage/Internal/NpgsqlDatabaseCreator.cs index b4fc8190a..72f8e6c5f 100644 --- a/src/EFCore.PG/Storage/Internal/NpgsqlDatabaseCreator.cs +++ b/src/EFCore.PG/Storage/Internal/NpgsqlDatabaseCreator.cs @@ -170,16 +170,15 @@ private IReadOnlyList CreateCreateOperations() var designTimeModel = Dependencies.CurrentContext.Context.GetService().Model; return Dependencies.MigrationsSqlGenerator.Generate( - new[] - { - new NpgsqlCreateDatabaseOperation + [ + new NpgsqlCreateDatabaseOperation { Name = _connection.DbConnection.Database, Template = designTimeModel.GetDatabaseTemplate(), Collation = designTimeModel.GetCollation(), Tablespace = designTimeModel.GetTablespace() } - }); + ]); } /// diff --git a/src/EFCore.PG/Storage/ValueConversion/NpgsqlArrayConverter.cs b/src/EFCore.PG/Storage/ValueConversion/NpgsqlArrayConverter.cs index c27fb5a87..f04221b5a 100644 --- a/src/EFCore.PG/Storage/ValueConversion/NpgsqlArrayConverter.cs +++ b/src/EFCore.PG/Storage/ValueConversion/NpgsqlArrayConverter.cs @@ -153,9 +153,8 @@ private static Expression> ArrayConversionExpression>( // First, check if the given array value is null and return null immediately if so @@ -213,7 +212,7 @@ private static Expression ForLoop( var initAssign = Assign(loopVar, initValue); var breakLabel = Label("LoopBreak"); var loop = Block( - new[] { loopVar }, + [loopVar], initAssign, Loop( IfThenElse( diff --git a/src/Shared/NonCapturingLazyInitializer.cs b/src/Shared/NonCapturingLazyInitializer.cs index a8d623031..ece9b1944 100644 --- a/src/Shared/NonCapturingLazyInitializer.cs +++ b/src/Shared/NonCapturingLazyInitializer.cs @@ -1,7 +1,5 @@ using System.Diagnostics.CodeAnalysis; -#nullable enable - namespace Microsoft.EntityFrameworkCore.Internal; internal static class NonCapturingLazyInitializer diff --git a/src/Shared/SharedTypeExtensions.cs b/src/Shared/SharedTypeExtensions.cs index ae06d69f7..6965d22cb 100644 --- a/src/Shared/SharedTypeExtensions.cs +++ b/src/Shared/SharedTypeExtensions.cs @@ -1,8 +1,6 @@ using System.Runtime.CompilerServices; using System.Text; -#nullable enable - // ReSharper disable once CheckNamespace namespace System; diff --git a/test/EFCore.PG.FunctionalTests/BuiltInDataTypesNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/BuiltInDataTypesNpgsqlTest.cs index 62ba84946..a873c85b4 100644 --- a/test/EFCore.PG.FunctionalTests/BuiltInDataTypesNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/BuiltInDataTypesNpgsqlTest.cs @@ -1,7 +1,6 @@ using System.Collections.Immutable; using System.ComponentModel.DataAnnotations.Schema; using System.Net.NetworkInformation; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities; namespace Npgsql.EntityFrameworkCore.PostgreSQL; @@ -101,8 +100,8 @@ public virtual void Can_query_using_any_mapped_data_type() EnumAsVarchar = StringEnumU16.Value4, PhysicalAddressAsMacaddr = PhysicalAddress.Parse("08-00-2B-01-02-03"), NpgsqlPointAsPoint = new NpgsqlPoint(5.2, 3.3), - StringAsJsonb = @"{""a"": ""b""}", - StringAsJson = @"{""a"": ""b""}", + StringAsJsonb = """{"a": "b"}""", + StringAsJson = """{"a": "b"}""", DictionaryAsHstore = new Dictionary { { "a", "b" } }, ImmutableDictionaryAsHstore = ImmutableDictionary.Empty.Add("c", "d"), NpgsqlRangeAsRange = new NpgsqlRange(4, true, 8, false), @@ -238,7 +237,7 @@ public virtual void Can_query_using_any_mapped_data_type() // Assert.Same(entity, context.Set().Single(e => e.Int == 999 && e.Point == param29)); // ReSharper disable once ConvertToConstant.Local - var param30 = @"{""a"": ""b""}"; + var param30 = """{"a": "b"}"""; Assert.Same(entity, context.Set().Single(e => e.Int == 999 && e.StringAsJsonb == param30)); // operator does not exist: json = json (https://stackoverflow.com/questions/32843213/operator-does-not-exist-json-json) @@ -467,7 +466,8 @@ public virtual void Can_insert_and_read_back_all_mapped_data_types() var parameters = DumpParameters(); Assert.Equal( - @"@p0='77' + """ +@p0='77' @p1='True' @p2='80' (DbType = Int16) @p3='0x56' (Nullable = false) @@ -500,8 +500,8 @@ public virtual void Can_insert_and_read_back_all_mapped_data_types() @p28=''a' & 'b'' (Nullable = false) (DbType = Object) @p29=''a' 'b'' (Nullable = false) (DbType = Object) @p30='79' -@p31='{""a"": ""b""}' (Nullable = false) (DbType = Object) -@p32='{""a"": ""b""}' (Nullable = false) (DbType = Object) +@p31='{"a": "b"}' (Nullable = false) (DbType = Object) +@p32='{"a": "b"}' (Nullable = false) (DbType = Object) @p33='Gumball Rules!' (Nullable = false) @p34='Gumball Rules OK' (Nullable = false) @p35='11:15:12' (DbType = Object) @@ -511,7 +511,8 @@ public virtual void Can_insert_and_read_back_all_mapped_data_types() @p39='4294967295' @p40='-1' @p41='2147483648' (DbType = Object) -@p42='-1'", +@p42='-1' +""", parameters, ignoreLineEndingDifferences: true); } @@ -564,8 +565,8 @@ private static void AssertMappedDataTypes(MappedDataTypes entity, int id) Assert.Equal(PhysicalAddress.Parse("08-00-2B-01-02-03"), entity.PhysicalAddressAsMacaddr); Assert.Equal(new NpgsqlPoint(5.2, 3.3), entity.NpgsqlPointAsPoint); - Assert.Equal(@"{""a"": ""b""}", entity.StringAsJsonb); - Assert.Equal(@"{""a"": ""b""}", entity.StringAsJson); + Assert.Equal("""{"a": "b"}""", entity.StringAsJsonb); + Assert.Equal("""{"a": "b"}""", entity.StringAsJson); Assert.Equal(new Dictionary { { "a", "b" } }, entity.DictionaryAsHstore); Assert.Equal(new NpgsqlRange(4, true, 8, false), entity.NpgsqlRangeAsRange); @@ -619,8 +620,8 @@ private static MappedDataTypes CreateMappedDataTypes(int id) EnumAsVarchar = StringEnumU16.Value4, PhysicalAddressAsMacaddr = PhysicalAddress.Parse("08-00-2B-01-02-03"), NpgsqlPointAsPoint = new NpgsqlPoint(5.2, 3.3), - StringAsJsonb = @"{""a"": ""b""}", - StringAsJson = @"{""a"": ""b""}", + StringAsJsonb = """{"a": "b"}""", + StringAsJson = """{"a": "b"}""", DictionaryAsHstore = new Dictionary { { "a", "b" } }, NpgsqlRangeAsRange = new NpgsqlRange(4, true, 8, false), IntArrayAsIntArray = [2, 3], diff --git a/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHFiltersInheritanceBulkUpdatesNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHFiltersInheritanceBulkUpdatesNpgsqlTest.cs index ecab1b210..4b8c44424 100644 --- a/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHFiltersInheritanceBulkUpdatesNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHFiltersInheritanceBulkUpdatesNpgsqlTest.cs @@ -2,16 +2,12 @@ namespace Npgsql.EntityFrameworkCore.PostgreSQL.BulkUpdates; -public class TPHFiltersInheritanceBulkUpdatesNpgsqlTest : FiltersInheritanceBulkUpdatesRelationalTestBase< - TPHFiltersInheritanceBulkUpdatesNpgsqlFixture> +public class TPHFiltersInheritanceBulkUpdatesNpgsqlTest( + TPHFiltersInheritanceBulkUpdatesNpgsqlFixture fixture, + ITestOutputHelper testOutputHelper) + : FiltersInheritanceBulkUpdatesRelationalTestBase< + TPHFiltersInheritanceBulkUpdatesNpgsqlFixture>(fixture, testOutputHelper) { - public TPHFiltersInheritanceBulkUpdatesNpgsqlTest( - TPHFiltersInheritanceBulkUpdatesNpgsqlFixture fixture, - ITestOutputHelper testOutputHelper) - : base(fixture, testOutputHelper) - { - } - public override async Task Delete_where_hierarchy(bool async) { await base.Delete_where_hierarchy(async); diff --git a/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHInheritanceBulkUpdatesNpgsqlFixture.cs b/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHInheritanceBulkUpdatesNpgsqlFixture.cs index dd076dd8f..dee6e67aa 100644 --- a/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHInheritanceBulkUpdatesNpgsqlFixture.cs +++ b/test/EFCore.PG.FunctionalTests/BulkUpdates/TPHInheritanceBulkUpdatesNpgsqlFixture.cs @@ -13,6 +13,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con { base.OnModelCreating(modelBuilder, context); - modelBuilder.Entity().HasNoKey().ToSqlQuery(@"SELECT * FROM ""Animals"""); + modelBuilder.Entity().HasNoKey().ToSqlQuery(""" + SELECT * FROM "Animals" + """); } } diff --git a/test/EFCore.PG.FunctionalTests/ComputedColumnTest.cs b/test/EFCore.PG.FunctionalTests/ComputedColumnTest.cs index 2cc8f767c..0e1b399c3 100644 --- a/test/EFCore.PG.FunctionalTests/ComputedColumnTest.cs +++ b/test/EFCore.PG.FunctionalTests/ComputedColumnTest.cs @@ -63,11 +63,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .Property(e => e.P4) - .HasComputedColumnSql(@"""P1"" + ""P2""", stored: true); + .HasComputedColumnSql(""" + "P1" + "P2" + """, stored: true); modelBuilder.Entity() .Property(e => e.P5) - .HasComputedColumnSql(@"""P1"" + ""P3""", stored: true); + .HasComputedColumnSql(""" + "P1" + "P3" + """, stored: true); } } @@ -109,7 +113,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() .Property(entity => entity.CalculatedFlagEnum) - .HasComputedColumnSql(@"""FlagEnum"" | ""OptionalFlagEnum""", stored: true); + .HasComputedColumnSql(""" + "FlagEnum" | "OptionalFlagEnum" + """, stored: true); } [ConditionalFact] diff --git a/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorDisabledNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorDisabledNpgsqlTest.cs index d8c24046a..d31212647 100644 --- a/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorDisabledNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorDisabledNpgsqlTest.cs @@ -14,8 +14,12 @@ public ConcurrencyDetectorDisabledNpgsqlTest(ConcurrencyDetectorNpgsqlFixture fi public override Task FromSql(bool async) => ConcurrencyDetectorTest( async c => async - ? await c.Products.FromSqlRaw(@"select * from ""Products""").ToListAsync() - : c.Products.FromSqlRaw(@"select * from ""Products""").ToList()); + ? await c.Products.FromSqlRaw(""" + select * from "Products" + """).ToListAsync() + : c.Products.FromSqlRaw(""" + select * from "Products" + """).ToList()); protected override async Task ConcurrencyDetectorTest(Func> test) { diff --git a/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorEnabledNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorEnabledNpgsqlTest.cs index 8a0f4d5ff..6cb940edd 100644 --- a/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorEnabledNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/ConcurrencyDetectorEnabledNpgsqlTest.cs @@ -14,8 +14,12 @@ public ConcurrencyDetectorEnabledNpgsqlTest(ConcurrencyDetectorNpgsqlFixture fix public override Task FromSql(bool async) => ConcurrencyDetectorTest( async c => async - ? await c.Products.FromSqlRaw(@"select * from ""Products""").ToListAsync() - : c.Products.FromSqlRaw(@"select * from ""Products""").ToList()); + ? await c.Products.FromSqlRaw(""" + select * from "Products" + """).ToListAsync() + : c.Products.FromSqlRaw(""" + select * from "Products" + """).ToList()); protected override async Task ConcurrencyDetectorTest(Func> test) { diff --git a/test/EFCore.PG.FunctionalTests/ExecutionStrategyTest.cs b/test/EFCore.PG.FunctionalTests/ExecutionStrategyTest.cs index 640b3c356..f488081c6 100644 --- a/test/EFCore.PG.FunctionalTests/ExecutionStrategyTest.cs +++ b/test/EFCore.PG.FunctionalTests/ExecutionStrategyTest.cs @@ -80,7 +80,7 @@ private void Test_commit_failure(bool realFailure, Action(); - connection.CommitFailures.Enqueue(new bool?[] { realFailure }); + connection.CommitFailures.Enqueue([realFailure]); Fixture.TestSqlLoggerFactory.Clear(); context.Products.Add(new Product()); @@ -194,7 +194,7 @@ private async Task Test_commit_failure_async( { var connection = (TestNpgsqlConnection)context.GetService(); - connection.CommitFailures.Enqueue(new bool?[] { realFailure }); + connection.CommitFailures.Enqueue([realFailure]); Fixture.TestSqlLoggerFactory.Clear(); context.Products.Add(new Product()); @@ -236,7 +236,7 @@ public void Handles_commit_failure_multiple_SaveChanges(bool realFailure) using (var context2 = CreateContext()) { - connection.CommitFailures.Enqueue(new bool?[] { realFailure }); + connection.CommitFailures.Enqueue([realFailure]); context1.Products.Add(new Product()); context2.Products.Add(new Product()); @@ -276,7 +276,7 @@ public async Task Retries_SaveChanges_on_execution_failure( { var connection = (TestNpgsqlConnection)context.GetService(); - connection.ExecutionFailures.Enqueue(new bool?[] { null, realFailure }); + connection.ExecutionFailures.Enqueue([null, realFailure]); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); @@ -385,7 +385,7 @@ public async Task Retries_query_on_execution_failure(bool externalStrategy, bool { var connection = (TestNpgsqlConnection)context.GetService(); - connection.ExecutionFailures.Enqueue(new bool?[] { true }); + connection.ExecutionFailures.Enqueue([true]); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); @@ -441,7 +441,7 @@ public async Task Retries_FromSqlRaw_on_execution_failure(bool externalStrategy, { var connection = (TestNpgsqlConnection)context.GetService(); - connection.ExecutionFailures.Enqueue(new bool?[] { true }); + connection.ExecutionFailures.Enqueue([true]); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); @@ -453,14 +453,16 @@ public async Task Retries_FromSqlRaw_on_execution_failure(bool externalStrategy, list = await new TestNpgsqlRetryingExecutionStrategy(context) .ExecuteAsync( context, (c, ct) => c.Set().FromSqlRaw( - @"SELECT ""Id"", ""Name"" - FROM ""Products""").ToListAsync(ct), null); + """ + SELECT "Id", "Name" FROM "Products" + """).ToListAsync(ct), null); } else { list = await context.Set().FromSqlRaw( - @"SELECT ""Id"", ""Name"" - FROM ""Products""").ToListAsync(); + """ + SELECT "Id", "Name" FROM "Products" + """).ToListAsync(); } } else @@ -470,14 +472,17 @@ public async Task Retries_FromSqlRaw_on_execution_failure(bool externalStrategy, list = new TestNpgsqlRetryingExecutionStrategy(context) .Execute( context, c => c.Set().FromSqlRaw( - @"SELECT ""Id"", ""Name"" - FROM ""Products""").ToList(), null); + """ + SELECT "Id", "Name" + FROM "Products" + """).ToList(), null); } else { list = context.Set().FromSqlRaw( - @"SELECT ""Id"", ""Name"" - FROM ""Products""").ToList(); + """ + SELECT "Id", "Name" FROM "Products" + """).ToList(); } } @@ -496,7 +501,7 @@ public async Task Retries_OpenConnection_on_execution_failure(bool externalStrat await using var context = CreateContext(); var connection = (TestNpgsqlConnection)context.GetService(); - connection.OpenFailures.Enqueue(new bool?[] { true }); + connection.OpenFailures.Enqueue([true]); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); @@ -549,7 +554,7 @@ public async Task Retries_BeginTransaction_on_execution_failure(bool async) await using var context = CreateContext(); var connection = (TestNpgsqlConnection)context.GetService(); - connection.OpenFailures.Enqueue(new bool?[] { true }); + connection.OpenFailures.Enqueue([true]); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); @@ -584,8 +589,8 @@ public void Verification_is_retried_using_same_retry_limit() { var connection = (TestNpgsqlConnection)context.GetService(); - connection.ExecutionFailures.Enqueue(new bool?[] { true, null, true, true }); - connection.CommitFailures.Enqueue(new bool?[] { true, true, true, true }); + connection.ExecutionFailures.Enqueue([true, null, true, true]); + connection.CommitFailures.Enqueue([true, true, true, true]); context.Products.Add(new Product()); Assert.Throws( diff --git a/test/EFCore.PG.FunctionalTests/ExistingConnectionTest.cs b/test/EFCore.PG.FunctionalTests/ExistingConnectionTest.cs index f155b67ba..abbe8f3f5 100644 --- a/test/EFCore.PG.FunctionalTests/ExistingConnectionTest.cs +++ b/test/EFCore.PG.FunctionalTests/ExistingConnectionTest.cs @@ -85,7 +85,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) b => { b.HasKey(c => c.CustomerId); - RelationalEntityTypeBuilderExtensions.ToTable((EntityTypeBuilder)b, "Customers"); + ((EntityTypeBuilder)b).ToTable("Customers"); }); } diff --git a/test/EFCore.PG.FunctionalTests/JsonTypesNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/JsonTypesNpgsqlTest.cs index 6806f8fa0..575433a57 100644 --- a/test/EFCore.PG.FunctionalTests/JsonTypesNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/JsonTypesNpgsqlTest.cs @@ -1,7 +1,6 @@ #nullable enable using System.Collections; - using System.Globalization; using System.Numerics; using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; diff --git a/test/EFCore.PG.FunctionalTests/MaterializationInterceptionNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/MaterializationInterceptionNpgsqlTest.cs index 31735e9ff..1e44c27db 100644 --- a/test/EFCore.PG.FunctionalTests/MaterializationInterceptionNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/MaterializationInterceptionNpgsqlTest.cs @@ -1,7 +1,5 @@ #nullable enable -using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; -using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities; namespace Npgsql.EntityFrameworkCore.PostgreSQL; diff --git a/test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs index 1f11df6bf..38743f56e 100644 --- a/test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Migrations/MigrationsNpgsqlTest.cs @@ -62,7 +62,7 @@ IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'dbo2') THEN COMMENT ON COLUMN dbo2."People"."EmployerId" IS 'Employer ID comment'; """, // - @"CREATE INDEX ""IX_People_EmployerId"" ON dbo2.""People"" (""EmployerId"");"); + """CREATE INDEX "IX_People_EmployerId" ON dbo2."People" ("EmployerId");"""); } public override async Task Create_table_no_key() @@ -531,7 +531,7 @@ IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'TestTableSchema') THEN END $EF$; """, // - @"ALTER TABLE ""TestTable"" SET SCHEMA ""TestTableSchema"";"); + """ALTER TABLE "TestTable" SET SCHEMA "TestTableSchema";"""); } #endregion @@ -1194,7 +1194,9 @@ await Test( e.Property("Y"); }), builder => builder.Entity("People").Property("Sum") - .HasComputedColumnSql(@"""X"" + ""Y""", stored: true), + .HasComputedColumnSql(""" + "X" + "Y" + """, stored: true), builder => builder.Entity("People").Property("Sum"), model => { @@ -1740,7 +1742,9 @@ await Test( "People", b => { b.Property("Name"); - b.Property("Name2").HasComputedColumnSql(@"""Name""", stored: true); + b.Property("Name2").HasComputedColumnSql(""" + "Name" + """, stored: true); }), _ => { }, builder => builder.Entity("People").Property("Name2") @@ -1748,7 +1752,9 @@ await Test( model => { var computedColumn = Assert.Single(Assert.Single(model.Tables).Columns, c => c.Name == "Name2"); - Assert.Equal(@"""Name""", computedColumn.ComputedColumnSql); + Assert.Equal(""" + "Name" + """, computedColumn.ComputedColumnSql); Assert.Equal(NonDefaultCollation, computedColumn.Collation); }); @@ -2031,12 +2037,14 @@ await Test( _ => { }, builder => builder.Entity("People").HasIndex("Name") .IncludeProperties("FirstName", "LastName") - .HasFilter(@"""Name"" IS NOT NULL"), + .HasFilter(""" + "Name" IS NOT NULL + """), model => { var table = Assert.Single(model.Tables); var index = Assert.Single(table.Indexes); - Assert.Equal(@"(""Name"" IS NOT NULL)", index.Filter); + Assert.Equal("""("Name" IS NOT NULL)""", index.Filter); Assert.Single(index.Columns); Assert.Contains(table.Columns.Single(c => c.Name == "Name"), index.Columns); @@ -2122,13 +2130,15 @@ await Test( builder => builder.Entity("People").HasIndex("Name") .IsUnique() .IncludeProperties("FirstName", "LastName") - .HasFilter(@"""Name"" IS NOT NULL"), + .HasFilter(""" + "Name" IS NOT NULL + """), model => { var table = Assert.Single(model.Tables); var index = Assert.Single(table.Indexes); Assert.True(index.IsUnique); - Assert.Equal(@"(""Name"" IS NOT NULL)", index.Filter); + Assert.Equal("""("Name" IS NOT NULL)""", index.Filter); Assert.Single(index.Columns); Assert.Contains(table.Columns.Single(c => c.Name == "Name"), index.Columns); @@ -2858,12 +2868,14 @@ await Test( }); AssertSql( - @"DO $EF$ -BEGIN - IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'some_schema') THEN - CREATE SCHEMA some_schema; - END IF; -END $EF$;", + """ + DO $EF$ + BEGIN + IF NOT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'some_schema') THEN + CREATE SCHEMA some_schema; + END IF; + END $EF$; + """, // @"CREATE EXTENSION IF NOT EXISTS citext SCHEMA some_schema;"); } @@ -3176,7 +3188,7 @@ await Test( var column = Assert.Single(table.Columns, c => c.Name == "TsVector"); Assert.Equal("tsvector", column.StoreType); Assert.Equal( - @"to_tsvector('english'::regconfig, ((""Title"" || ' '::text) || COALESCE(""Description"", ''::text)))", + """to_tsvector('english'::regconfig, (("Title" || ' '::text) || COALESCE("Description", ''::text)))""", column.ComputedColumnSql); }); diff --git a/test/EFCore.PG.FunctionalTests/Migrations/NpgsqlMigrationsSqlGeneratorTest.cs b/test/EFCore.PG.FunctionalTests/Migrations/NpgsqlMigrationsSqlGeneratorTest.cs index ac5fec041..0b3dc8292 100644 --- a/test/EFCore.PG.FunctionalTests/Migrations/NpgsqlMigrationsSqlGeneratorTest.cs +++ b/test/EFCore.PG.FunctionalTests/Migrations/NpgsqlMigrationsSqlGeneratorTest.cs @@ -23,8 +23,10 @@ public virtual void CreateDatabaseOperation() Generate(new NpgsqlCreateDatabaseOperation { Name = "Northwind" }); AssertSql( - @"CREATE DATABASE ""Northwind""; -"); + """ +CREATE DATABASE "Northwind"; + +"""); } [ConditionalFact] diff --git a/test/EFCore.PG.FunctionalTests/ModelBuilding/NpgsqlModelBuilderTestBase.cs b/test/EFCore.PG.FunctionalTests/ModelBuilding/NpgsqlModelBuilderTestBase.cs index 95f42a658..afce39d7a 100644 --- a/test/EFCore.PG.FunctionalTests/ModelBuilding/NpgsqlModelBuilderTestBase.cs +++ b/test/EFCore.PG.FunctionalTests/ModelBuilding/NpgsqlModelBuilderTestBase.cs @@ -1,9 +1,8 @@ +#nullable enable + using Microsoft.EntityFrameworkCore.ModelBuilding; -using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities; -#nullable enable - namespace Npgsql.EntityFrameworkCore.PostgreSQL.ModelBuilding; public class NpgsqlModelBuilderTestBase : RelationalModelBuilderTest diff --git a/test/EFCore.PG.FunctionalTests/NpgsqlDatabaseCreatorTest.cs b/test/EFCore.PG.FunctionalTests/NpgsqlDatabaseCreatorTest.cs index 2c7bc8061..edf3087bd 100644 --- a/test/EFCore.PG.FunctionalTests/NpgsqlDatabaseCreatorTest.cs +++ b/test/EFCore.PG.FunctionalTests/NpgsqlDatabaseCreatorTest.cs @@ -452,37 +452,37 @@ public void GenerateCreateScript_works() using var context = new BloggingContext("Data Source=foo"); var script = context.Database.GenerateCreateScript(); Assert.Equal( - @"CREATE TABLE ""Blogs"" (" + """CREATE TABLE "Blogs" (""" + _eol - + @" ""Key1"" text NOT NULL," + + """ "Key1" text NOT NULL,""" + _eol - + @" ""Key2"" bytea NOT NULL," + + """ "Key2" bytea NOT NULL,""" + _eol - + @" ""Cheese"" text," + + """ "Cheese" text,""" + _eol - + @" ""ErMilan"" integer NOT NULL," + + """ "ErMilan" integer NOT NULL,""" + _eol - + @" ""George"" boolean NOT NULL," + + """ "George" boolean NOT NULL,""" + _eol - + @" ""TheGu"" uuid NOT NULL," + + """ "TheGu" uuid NOT NULL,""" + _eol - + @" ""NotFigTime"" timestamp with time zone NOT NULL," + + """ "NotFigTime" timestamp with time zone NOT NULL,""" + _eol - + @" ""ToEat"" smallint NOT NULL," + + """ "ToEat" smallint NOT NULL,""" + _eol - + @" ""OrNothing"" double precision NOT NULL," + + """ "OrNothing" double precision NOT NULL,""" + _eol - + @" ""Fuse"" smallint NOT NULL," + + """ "Fuse" smallint NOT NULL,""" + _eol - + @" ""WayRound"" bigint NOT NULL," + + """ "WayRound" bigint NOT NULL,""" + _eol - + @" ""On"" real NOT NULL," + + """ "On" real NOT NULL,""" + _eol - + @" ""AndChew"" bytea," + + """ "AndChew" bytea,""" + _eol - + @" ""AndRow"" bytea," + + """ "AndRow" bytea,""" + _eol - + @" CONSTRAINT ""PK_Blogs"" PRIMARY KEY (""Key1"", ""Key2"")" + + """ CONSTRAINT "PK_Blogs" PRIMARY KEY ("Key1", "Key2")""" + _eol + ");" + _eol diff --git a/test/EFCore.PG.FunctionalTests/Query/FuzzyStringMatchQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/FuzzyStringMatchQueryNpgsqlTest.cs index bf18e9670..fd76749d3 100644 --- a/test/EFCore.PG.FunctionalTests/Query/FuzzyStringMatchQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/FuzzyStringMatchQueryNpgsqlTest.cs @@ -31,7 +31,7 @@ public void FuzzyStringMatchSoundex() .Select(x => EF.Functions.FuzzyStringMatchSoundex(x.Text)) .ToArray(); - AssertContainsSql(@"soundex(f.""Text"")"); + AssertContainsSql("""soundex(f."Text")"""); } [Fact] @@ -42,7 +42,7 @@ public void FuzzyStringMatchDifference() .Select(x => EF.Functions.FuzzyStringMatchDifference(x.Text, "target")) .ToArray(); - AssertContainsSql(@"difference(f.""Text"", 'target')"); + AssertContainsSql("""difference(f."Text", 'target')"""); } [Fact] @@ -53,7 +53,7 @@ public void FuzzyStringMatchLevenshtein() .Select(x => EF.Functions.FuzzyStringMatchLevenshtein(x.Text, "target")) .ToArray(); - AssertContainsSql(@"levenshtein(f.""Text"", 'target')"); + AssertContainsSql("""levenshtein(f."Text", 'target')"""); } [Fact] @@ -64,7 +64,7 @@ public void FuzzyStringMatchLevenshtein_With_Costs() .Select(x => EF.Functions.FuzzyStringMatchLevenshtein(x.Text, "target", 1, 2, 3)) .ToArray(); - AssertContainsSql(@"levenshtein(f.""Text"", 'target', 1, 2, 3)"); + AssertContainsSql("""levenshtein(f."Text", 'target', 1, 2, 3)"""); } [Fact] @@ -75,7 +75,7 @@ public void FuzzyStringMatchLevenshteinLessEqual() .Select(x => EF.Functions.FuzzyStringMatchLevenshteinLessEqual(x.Text, "target", 5)) .ToArray(); - AssertContainsSql(@"levenshtein_less_equal(f.""Text"", 'target', 5)"); + AssertContainsSql("""levenshtein_less_equal(f."Text", 'target', 5)"""); } [Fact] @@ -86,7 +86,7 @@ public void FuzzyStringMatchLevenshteinLessEqual_With_Costs() .Select(x => EF.Functions.FuzzyStringMatchLevenshteinLessEqual(x.Text, "target", 1, 2, 3, 5)) .ToArray(); - AssertContainsSql(@"levenshtein_less_equal(f.""Text"", 'target', 1, 2, 3, 5)"); + AssertContainsSql("""levenshtein_less_equal(f."Text", 'target', 1, 2, 3, 5)"""); } [Fact] @@ -97,7 +97,7 @@ public void FuzzyStringMatchMetaphone() .Select(x => EF.Functions.FuzzyStringMatchMetaphone(x.Text, 6)) .ToArray(); - AssertContainsSql(@"metaphone(f.""Text"", 6)"); + AssertContainsSql("""metaphone(f."Text", 6)"""); } [Fact] @@ -108,7 +108,7 @@ public void FuzzyStringMatchDoubleMetaphone() .Select(x => EF.Functions.FuzzyStringMatchDoubleMetaphone(x.Text)) .ToArray(); - AssertContainsSql(@"dmetaphone(f.""Text"")"); + AssertContainsSql("""dmetaphone(f."Text")"""); } [Fact] @@ -119,7 +119,7 @@ public void FuzzyStringMatchDoubleMetaphoneAlt() .Select(x => EF.Functions.FuzzyStringMatchDoubleMetaphoneAlt(x.Text)) .ToArray(); - AssertContainsSql(@"dmetaphone_alt(f.""Text"")"); + AssertContainsSql("""dmetaphone_alt(f."Text")"""); } #endregion diff --git a/test/EFCore.PG.FunctionalTests/Query/GearsOfWarFromSqlQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/GearsOfWarFromSqlQueryNpgsqlTest.cs index 59e8a92b2..b8a140c27 100644 --- a/test/EFCore.PG.FunctionalTests/Query/GearsOfWarFromSqlQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/GearsOfWarFromSqlQueryNpgsqlTest.cs @@ -14,7 +14,9 @@ public override void From_sql_queryable_simple_columns_out_of_order() base.From_sql_queryable_simple_columns_out_of_order(); Assert.Equal( - @"SELECT ""Id"", ""Name"", ""IsAutomatic"", ""AmmunitionType"", ""OwnerFullName"", ""SynergyWithId"" FROM ""Weapons"" ORDER BY ""Name""", + """ +SELECT "Id", "Name", "IsAutomatic", "AmmunitionType", "OwnerFullName", "SynergyWithId" FROM "Weapons" ORDER BY "Name" +""", Sql); } diff --git a/test/EFCore.PG.FunctionalTests/Query/JsonDomQueryTest.cs b/test/EFCore.PG.FunctionalTests/Query/JsonDomQueryTest.cs index 3e26de810..a46fd3c96 100644 --- a/test/EFCore.PG.FunctionalTests/Query/JsonDomQueryTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/JsonDomQueryTest.cs @@ -55,8 +55,10 @@ public void Literal_document() ctx.JsonbEntities.Where( e => e.CustomerDocument == JsonDocument.Parse( - @" -{ ""Name"": ""Test customer"", ""Age"": 80 }", default))); + """ + + { "Name": "Test customer", "Age": 80 } + """, default))); AssertSql( """ @@ -428,7 +430,7 @@ LIMIT 2 public void JsonContains_with_json_element() { using var ctx = CreateContext(); - var element = JsonDocument.Parse(@"{""Name"": ""Joe"", ""Age"": 25}").RootElement; + var element = JsonDocument.Parse("""{"Name": "Joe", "Age": 25}""").RootElement; var count = ctx.JsonbEntities.Count( e => EF.Functions.JsonContains(e.CustomerElement, element)); @@ -450,7 +452,7 @@ public void JsonContains_with_string() using var ctx = CreateContext(); var count = ctx.JsonbEntities.Count( e => - EF.Functions.JsonContains(e.CustomerElement, @"{""Name"": ""Joe"", ""Age"": 25}")); + EF.Functions.JsonContains(e.CustomerElement, """{"Name": "Joe", "Age": 25}""")); Assert.Equal(1, count); AssertSql( @@ -465,7 +467,7 @@ SELECT count(*)::int public void JsonContained_with_json_element() { using var ctx = CreateContext(); - var element = JsonDocument.Parse(@"{""Name"": ""Joe"", ""Age"": 25}").RootElement; + var element = JsonDocument.Parse("""{"Name": "Joe", "Age": 25}""").RootElement; var count = ctx.JsonbEntities.Count( e => EF.Functions.JsonContained(element, e.CustomerElement)); @@ -487,7 +489,7 @@ public void JsonContained_with_string() using var ctx = CreateContext(); var count = ctx.JsonbEntities.Count( e => - EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.CustomerElement)); + EF.Functions.JsonContained("""{"Name": "Joe", "Age": 25}""", e.CustomerElement)); // Assert.Equal(1, count); AssertSql( @@ -732,7 +734,9 @@ static JsonDocument CreateCustomer2() """); static JsonDocument CreateCustomer3() - => JsonDocument.Parse(@"""foo"""); + => JsonDocument.Parse(""" + "foo" + """); } } diff --git a/test/EFCore.PG.FunctionalTests/Query/JsonPocoQueryTest.cs b/test/EFCore.PG.FunctionalTests/Query/JsonPocoQueryTest.cs index 55668f31f..bb108fc6e 100644 --- a/test/EFCore.PG.FunctionalTests/Query/JsonPocoQueryTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/JsonPocoQueryTest.cs @@ -499,7 +499,7 @@ LIMIT 2 public void JsonContains_with_json_element() { using var ctx = CreateContext(); - var element = JsonDocument.Parse(@"{""Name"": ""Joe"", ""Age"": 25}").RootElement; + var element = JsonDocument.Parse("""{"Name": "Joe", "Age": 25}""").RootElement; var count = ctx.JsonbEntities.Count( e => EF.Functions.JsonContains(e.Customer, element)); @@ -521,7 +521,7 @@ public void JsonContains_with_string_literal() using var ctx = CreateContext(); var count = ctx.JsonbEntities.Count( e => - EF.Functions.JsonContains(e.Customer, @"{""Name"": ""Joe"", ""Age"": 25}")); + EF.Functions.JsonContains(e.Customer, """{"Name": "Joe", "Age": 25}""")); Assert.Equal(1, count); AssertSql( @@ -536,7 +536,7 @@ SELECT count(*)::int public void JsonContains_with_string_parameter() { using var ctx = CreateContext(); - var someJson = @"{""Name"": ""Joe"", ""Age"": 25}"; + var someJson = """{"Name": "Joe", "Age": 25}"""; var count = ctx.JsonbEntities.Count( e => EF.Functions.JsonContains(e.Customer, someJson)); @@ -556,7 +556,7 @@ WHERE j."Customer" @> @__someJson_1 public void JsonContained_with_json_element() { using var ctx = CreateContext(); - var element = JsonDocument.Parse(@"{""Name"": ""Joe"", ""Age"": 25}").RootElement; + var element = JsonDocument.Parse("""{"Name": "Joe", "Age": 25}""").RootElement; var count = ctx.JsonbEntities.Count( e => EF.Functions.JsonContained(element, e.Customer)); @@ -578,7 +578,7 @@ public void JsonContained_with_string_literal() using var ctx = CreateContext(); var count = ctx.JsonbEntities.Count( e => - EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.Customer)); + EF.Functions.JsonContained("""{"Name": "Joe", "Age": 25}""", e.Customer)); Assert.Equal(1, count); AssertSql( @@ -593,7 +593,7 @@ SELECT count(*)::int public void JsonContained_with_string_parameter() { using var ctx = CreateContext(); - var someJson = @"{""Name"": ""Joe"", ""Age"": 25}"; + var someJson = """{"Name": "Joe", "Age": 25}"""; var count = ctx.JsonbEntities.Count( e => EF.Functions.JsonContained(someJson, e.Customer)); diff --git a/test/EFCore.PG.FunctionalTests/Query/JsonStringQueryTest.cs b/test/EFCore.PG.FunctionalTests/Query/JsonStringQueryTest.cs index 5504d001c..3608a7dfd 100644 --- a/test/EFCore.PG.FunctionalTests/Query/JsonStringQueryTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/JsonStringQueryTest.cs @@ -52,7 +52,7 @@ public void Literal() Assert.Empty( ctx.JsonEntities.Where( - e => e.CustomerJsonb == @"{""Name"":""Test customer"",""Age"":80,""IsVip"":false,""Statistics"":null,""Orders"":null}")); + e => e.CustomerJsonb == """{"Name":"Test customer","Age":80,"IsVip":false,"Statistics":null,"Orders":null}""")); AssertSql( """ @@ -99,7 +99,7 @@ public void JsonContains_with_json_element() { using var ctx = CreateContext(); - var element = JsonDocument.Parse(@"{""Name"": ""Joe"", ""Age"": 25}").RootElement; + var element = JsonDocument.Parse("""{"Name": "Joe", "Age": 25}""").RootElement; var count = ctx.JsonEntities.Count(e => EF.Functions.JsonContains(e.CustomerJsonb, element)); Assert.Equal(1, count); @@ -119,7 +119,7 @@ public void JsonContains_with_string() { using var ctx = CreateContext(); - var count = ctx.JsonEntities.Count(e => EF.Functions.JsonContains(e.CustomerJsonb, @"{""Name"": ""Joe"", ""Age"": 25}")); + var count = ctx.JsonEntities.Count(e => EF.Functions.JsonContains(e.CustomerJsonb, """{"Name": "Joe", "Age": 25}""")); Assert.Equal(1, count); @@ -137,7 +137,11 @@ public void JsonContains_with_string_column() using var ctx = CreateContext(); var count = ctx.JsonEntities.Count( - e => EF.Functions.JsonContains(e.CustomerJsonb, @"{""Name"": """ + e.SomeString + @""", ""Age"": 25}")); + e => EF.Functions.JsonContains(e.CustomerJsonb, """ + {"Name": " + """ + e.SomeString + """ + ", "Age": 25} + """)); Assert.Equal(1, count); @@ -154,7 +158,7 @@ public void JsonContained_with_json_element() { using var ctx = CreateContext(); - var element = JsonDocument.Parse(@"{""Name"": ""Joe"", ""Age"": 25}").RootElement; + var element = JsonDocument.Parse("""{"Name": "Joe", "Age": 25}""").RootElement; var count = ctx.JsonEntities.Count(e => EF.Functions.JsonContained(element, e.CustomerJsonb)); Assert.Equal(1, count); @@ -174,7 +178,7 @@ public void JsonContained_with_string() { using var ctx = CreateContext(); - var count = ctx.JsonEntities.Count(e => EF.Functions.JsonContained(@"{""Name"": ""Joe"", ""Age"": 25}", e.CustomerJsonb)); + var count = ctx.JsonEntities.Count(e => EF.Functions.JsonContained("""{"Name": "Joe", "Age": 25}""", e.CustomerJsonb)); Assert.Equal(1, count); @@ -253,60 +257,64 @@ public class JsonStringQueryContext(DbContextOptions options) : PoolableDbContex public static async Task SeedAsync(JsonStringQueryContext context) { - const string customer1 = @" + const string customer1 = """ + { - ""Name"": ""Joe"", - ""Age"": 25, - ""IsVip"": false, - ""Statistics"": + "Name": "Joe", + "Age": 25, + "IsVip": false, + "Statistics": { - ""Visits"": 4, - ""Purchases"": 3, - ""Nested"": + "Visits": 4, + "Purchases": 3, + "Nested": { - ""SomeProperty"": 10, - ""IntArray"": [3, 4] + "SomeProperty": 10, + "IntArray": [3, 4] } }, - ""Orders"": + "Orders": [ { - ""Price"": 99.5, - ""ShippingAddress"": ""Some address 1"", - ""ShippingDate"": ""2019-10-01"" + "Price": 99.5, + "ShippingAddress": "Some address 1", + "ShippingDate": "2019-10-01" }, { - ""Price"": 23, - ""ShippingAddress"": ""Some address 2"", - ""ShippingDate"": ""2019-10-10"" + "Price": 23, + "ShippingAddress": "Some address 2", + "ShippingDate": "2019-10-10" } ] - }"; + } +"""; + + const string customer2 = """ - const string customer2 = @" { - ""Name"": ""Moe"", - ""Age"": 35, - ""IsVip"": true, - ""Statistics"": + "Name": "Moe", + "Age": 35, + "IsVip": true, + "Statistics": { - ""Visits"": 20, - ""Purchases"": 25, - ""Nested"": + "Visits": 20, + "Purchases": 25, + "Nested": { - ""SomeProperty"": 20, - ""IntArray"": [5, 6] + "SomeProperty": 20, + "IntArray": [5, 6] } }, - ""Orders"": + "Orders": [ { - ""Price"": 5, - ""ShippingAddress"": ""Moe's address"", - ""ShippingDate"": ""2019-11-03"" + "Price": 5, + "ShippingAddress": "Moe's address", + "ShippingDate": "2019-11-03" } ] - }"; + } +"""; const string array = "[1, 2, 3]"; diff --git a/test/EFCore.PG.FunctionalTests/Query/LegacyNpgsqlNodaTimeTypeMappingTest.cs b/test/EFCore.PG.FunctionalTests/Query/LegacyNpgsqlNodaTimeTypeMappingTest.cs index 1d1d41641..e2a5bb1f0 100644 --- a/test/EFCore.PG.FunctionalTests/Query/LegacyNpgsqlNodaTimeTypeMappingTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/LegacyNpgsqlNodaTimeTypeMappingTest.cs @@ -55,7 +55,7 @@ public void GenerateSqlLiteral_returns_instant_range_in_legacy_mode() var value = new NpgsqlRange( new LocalDateTime(2020, 1, 1, 12, 0, 0).InUtc().ToInstant(), new LocalDateTime(2020, 1, 2, 12, 0, 0).InUtc().ToInstant()); - Assert.Equal(@"'[""2020-01-01T12:00:00Z"",""2020-01-02T12:00:00Z""]'::tsrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00Z","2020-01-02T12:00:00Z"]'::tsrange""", mapping.GenerateSqlLiteral(value)); } #region Support @@ -66,11 +66,10 @@ public void GenerateSqlLiteral_returns_instant_range_in_legacy_mode() new JsonValueReaderWriterSource(new JsonValueReaderWriterSourceDependencies()), []), new RelationalTypeMappingSourceDependencies( - new IRelationalTypeMappingSourcePlugin[] - { - new NpgsqlNodaTimeTypeMappingSourcePlugin( + [ + new NpgsqlNodaTimeTypeMappingSourcePlugin( new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies())) - }), + ]), new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()), new NpgsqlSingletonOptions() ); diff --git a/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs index 399c8cd84..b4ffa354e 100644 --- a/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/NonSharedPrimitiveCollectionsQueryNpgsqlTest.cs @@ -1,5 +1,4 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; -using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities; namespace Npgsql.EntityFrameworkCore.PostgreSQL.Query; diff --git a/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs index 48f0fa784..c8fd85fe5 100644 --- a/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs @@ -534,7 +534,7 @@ public virtual async Task GroupBy_JsonObjectAgg(bool async) var london = results.Single(r => r.City == "London"); Assert.Equal( - @"{ ""Around the Horn"" : ""Thomas Hardy"", ""B's Beverages"" : ""Victoria Ashworth"", ""Consolidated Holdings"" : ""Elizabeth Brown"", ""Eastern Connection"" : ""Ann Devon"", ""North/South"" : ""Simon Crowther"", ""Seven Seas Imports"" : ""Hari Kumar"" }", + """{ "Around the Horn" : "Thomas Hardy", "B's Beverages" : "Victoria Ashworth", "Consolidated Holdings" : "Elizabeth Brown", "Eastern Connection" : "Ann Devon", "North/South" : "Simon Crowther", "Seven Seas Imports" : "Hari Kumar" }""", london.Companies); AssertSql( diff --git a/test/EFCore.PG.FunctionalTests/Query/NorthwindMiscellaneousQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/NorthwindMiscellaneousQueryNpgsqlTest.cs index d6db7b54d..cc8aa9153 100644 --- a/test/EFCore.PG.FunctionalTests/Query/NorthwindMiscellaneousQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/NorthwindMiscellaneousQueryNpgsqlTest.cs @@ -298,9 +298,8 @@ public async Task Array_Any_Like(bool async) var result = async ? await query.ToListAsync() : query.ToList(); Assert.Equal( - new[] - { - "ANATR", + [ + "ANATR", "BERGS", "BOLID", "CACTU", @@ -322,7 +321,7 @@ public async Task Array_Any_Like(bool async) "TORTU", "TRADH", "WANDK" - }, result.Select(e => e.CustomerID)); + ], result.Select(e => e.CustomerID)); AssertSql( """ @@ -367,9 +366,8 @@ public async Task Array_Any_ILike(bool async) var result = async ? await query.ToListAsync() : query.ToList(); Assert.Equal( - new[] - { - "ANATR", + [ + "ANATR", "BERGS", "BOLID", "CACTU", @@ -391,7 +389,7 @@ public async Task Array_Any_ILike(bool async) "TORTU", "TRADH", "WANDK" - }, result.Select(e => e.CustomerID)); + ], result.Select(e => e.CustomerID)); AssertSql( """ diff --git a/test/EFCore.PG.FunctionalTests/Query/SpatialQueryNpgsqlGeographyTest.cs b/test/EFCore.PG.FunctionalTests/Query/SpatialQueryNpgsqlGeographyTest.cs index 20d115583..8508607b7 100644 --- a/test/EFCore.PG.FunctionalTests/Query/SpatialQueryNpgsqlGeographyTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/SpatialQueryNpgsqlGeographyTest.cs @@ -22,10 +22,10 @@ public SpatialQueryNpgsqlGeographyTest(SpatialQueryNpgsqlGeographyFixture fixtur protected override bool AssertDistances => false; - public static IEnumerable IsAsyncDataAndUseSpheroid = new[] - { - [false, false], [false, true], [true, false], new object[] { true, true } - }; + public static IEnumerable IsAsyncDataAndUseSpheroid = + [ + [false, false], [false, true], [true, false], [true, true] + ]; public override async Task Area(bool async) { diff --git a/test/EFCore.PG.FunctionalTests/Query/SqlExecutorNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/SqlExecutorNpgsqlTest.cs index 2c10adc6f..d761b5586 100644 --- a/test/EFCore.PG.FunctionalTests/Query/SqlExecutorNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/SqlExecutorNpgsqlTest.cs @@ -15,11 +15,11 @@ protected override DbParameter CreateDbParameter(string name, object value) => new NpgsqlParameter { ParameterName = name, Value = value }; protected override string TenMostExpensiveProductsSproc - => @"SELECT * FROM ""Ten Most Expensive Products""()"; + => """SELECT * FROM "Ten Most Expensive Products"()"""; protected override string CustomerOrderHistorySproc - => @"SELECT * FROM ""CustOrderHist""(@CustomerID)"; + => """SELECT * FROM "CustOrderHist"(@CustomerID)"""; protected override string CustomerOrderHistoryWithGeneratedParameterSproc - => @"SELECT * FROM ""CustOrderHist""({0})"; + => """SELECT * FROM "CustOrderHist"({0})"""; } diff --git a/test/EFCore.PG.FunctionalTests/Query/TPHInheritanceQueryNpgsqlFixture.cs b/test/EFCore.PG.FunctionalTests/Query/TPHInheritanceQueryNpgsqlFixture.cs index 7957eb5a1..eedc4427e 100644 --- a/test/EFCore.PG.FunctionalTests/Query/TPHInheritanceQueryNpgsqlFixture.cs +++ b/test/EFCore.PG.FunctionalTests/Query/TPHInheritanceQueryNpgsqlFixture.cs @@ -12,6 +12,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con { base.OnModelCreating(modelBuilder, context); - modelBuilder.Entity().HasNoKey().ToSqlQuery(@"SELECT * FROM ""Animals"""); + modelBuilder.Entity().HasNoKey().ToSqlQuery(""" + SELECT * FROM "Animals" + """); } } diff --git a/test/EFCore.PG.FunctionalTests/Query/TrigramsQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/TrigramsQueryNpgsqlTest.cs index c78819df2..12f3668e0 100644 --- a/test/EFCore.PG.FunctionalTests/Query/TrigramsQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/TrigramsQueryNpgsqlTest.cs @@ -31,7 +31,7 @@ public void TrigramsShow() .Select(x => EF.Functions.TrigramsShow(x.Text)) .ToArray(); - AssertContainsSql(@"show_trgm(t.""Text"")"); + AssertContainsSql("""show_trgm(t."Text")"""); } [Fact] @@ -42,7 +42,7 @@ public void TrigramsSimilarity() .Select(x => EF.Functions.TrigramsSimilarity(x.Text, "target")) .ToArray(); - AssertContainsSql(@"similarity(t.""Text"", 'target')"); + AssertContainsSql("""similarity(t."Text", 'target')"""); } [Fact] @@ -53,7 +53,7 @@ public void TrigramsWordSimilarity() .Select(x => EF.Functions.TrigramsWordSimilarity(x.Text, "target")) .ToArray(); - AssertContainsSql(@"word_similarity(t.""Text"", 'target')"); + AssertContainsSql("""word_similarity(t."Text", 'target')"""); } [ConditionalFact] @@ -65,7 +65,7 @@ public void TrigramsStrictWordSimilarity() .Select(x => EF.Functions.TrigramsStrictWordSimilarity(x.Text, "target")) .ToArray(); - AssertContainsSql(@"strict_word_similarity(t.""Text"", 'target')"); + AssertContainsSql("""strict_word_similarity(t."Text", 'target')"""); } [Fact] @@ -76,7 +76,7 @@ public void TrigramsAreSimilar() .Select(x => EF.Functions.TrigramsAreSimilar(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" % 'target'"); + AssertContainsSql("""t."Text" % 'target'"""); } [Fact] @@ -87,7 +87,7 @@ public void TrigramsAreWordSimilar() .Select(x => EF.Functions.TrigramsAreWordSimilar(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <% 'target'"); + AssertContainsSql("""t."Text" <% 'target'"""); } [Fact] @@ -98,7 +98,7 @@ public void TrigramsAreNotWordSimilar() .Select(x => EF.Functions.TrigramsAreNotWordSimilar(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" %> 'target'"); + AssertContainsSql("""t."Text" %> 'target'"""); } [ConditionalFact] @@ -110,7 +110,7 @@ public void TrigramsAreStrictWordSimilar() .Select(x => EF.Functions.TrigramsAreStrictWordSimilar(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <<% 'target'"); + AssertContainsSql("""t."Text" <<% 'target'"""); } [ConditionalFact] @@ -122,7 +122,7 @@ public void TrigramsAreNotStrictWordSimilar() .Select(x => EF.Functions.TrigramsAreNotStrictWordSimilar(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" %>> 'target'"); + AssertContainsSql("""t."Text" %>> 'target'"""); } [Fact] @@ -133,7 +133,7 @@ public void TrigramsSimilarityDistance() .Select(x => EF.Functions.TrigramsSimilarityDistance(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <-> 'target'"); + AssertContainsSql("""t."Text" <-> 'target'"""); } [Fact] @@ -144,7 +144,7 @@ public void TrigramsWordSimilarityDistance() .Select(x => EF.Functions.TrigramsWordSimilarityDistance(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <<-> 'target'"); + AssertContainsSql("""t."Text" <<-> 'target'"""); } [Fact] @@ -155,7 +155,7 @@ public void TrigramsWordSimilarityDistanceInverted() .Select(x => EF.Functions.TrigramsWordSimilarityDistanceInverted(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <->> 'target'"); + AssertContainsSql("""t."Text" <->> 'target'"""); } [ConditionalFact] @@ -167,7 +167,7 @@ public void TrigramsStrictWordSimilarityDistance() .Select(x => EF.Functions.TrigramsStrictWordSimilarityDistance(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <<<-> 'target'"); + AssertContainsSql("""t."Text" <<<-> 'target'"""); } [ConditionalFact] @@ -179,7 +179,7 @@ public void TrigramsStrictWordSimilarityDistanceInverted() .Select(x => EF.Functions.TrigramsStrictWordSimilarityDistanceInverted(x.Text, "target")) .ToArray(); - AssertContainsSql(@"t.""Text"" <->>> 'target'"); + AssertContainsSql("""t."Text" <->>> 'target'"""); } [Fact] // #1659 diff --git a/test/EFCore.PG.FunctionalTests/Scaffolding/NpgsqlDatabaseModelFactoryTest.cs b/test/EFCore.PG.FunctionalTests/Scaffolding/NpgsqlDatabaseModelFactoryTest.cs index 5696d082b..eb0179a68 100644 --- a/test/EFCore.PG.FunctionalTests/Scaffolding/NpgsqlDatabaseModelFactoryTest.cs +++ b/test/EFCore.PG.FunctionalTests/Scaffolding/NpgsqlDatabaseModelFactoryTest.cs @@ -42,8 +42,8 @@ MAXVALUE 8 MINVALUE -3 CYCLE; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var defaultSequence = dbModel.Sequences.First(ds => ds.Name == "DefaultFacetsSequence"); @@ -81,8 +81,8 @@ public void Sequence_min_max_start_values_are_null_if_default() CREATE SEQUENCE "IntSequence" AS int; CREATE SEQUENCE "BigIntSequence" AS bigint; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { Assert.All( @@ -107,8 +107,8 @@ public void Filter_sequences_based_on_schema() CREATE SEQUENCE "Sequence"; CREATE SEQUENCE db2."Sequence" """, - Enumerable.Empty(), - new[] { "db2" }, + [], + ["db2"], dbModel => { var sequence = Assert.Single(dbModel.Sequences); @@ -130,8 +130,8 @@ CREATE SEQUENCE db2."Sequence" public void Set_default_schema() => Test( "SELECT 1", - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { Assert.Equal("public", dbModel.DefaultSchema); @@ -145,8 +145,8 @@ public void Create_tables() CREATE TABLE "Everest" (id int); CREATE TABLE "Denali" (id int); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { Assert.Collection( @@ -178,8 +178,8 @@ public void Filter_schemas() CREATE TABLE db2."K2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "Kilimanjaro" (Id int, B varchar, UNIQUE (B)); """, - Enumerable.Empty(), - new[] { "db2" }, + [], + ["db2"], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -201,8 +201,8 @@ public void Filter_tables() CREATE TABLE "K2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "Kilimanjaro" (Id int, B varchar, UNIQUE (B), FOREIGN KEY (B) REFERENCES "K2" (A)); """, - new[] { "K2" }, - Enumerable.Empty(), + ["K2"], + [], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -224,8 +224,10 @@ public void Filter_tables_with_qualified_name() CREATE TABLE "K.2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "Kilimanjaro" (Id int, B varchar, UNIQUE (B)); """, - new[] { @"""K.2""" }, - Enumerable.Empty(), + [""" + "K.2" + """], + [], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -248,8 +250,8 @@ public void Filter_tables_with_schema_qualified_name1() CREATE TABLE db2."K2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "Kilimanjaro" (Id int, B varchar, UNIQUE (B)); """, - new[] { "public.K2" }, - Enumerable.Empty(), + ["public.K2"], + [], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -273,8 +275,10 @@ public void Filter_tables_with_schema_qualified_name2() CREATE TABLE "db.2"."K.2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "db.2"."Kilimanjaro" (Id int, B varchar, UNIQUE (B)); """, - new[] { @"""db.2"".""K.2""" }, - Enumerable.Empty(), + [""" + "db.2"."K.2" + """], + [], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -298,8 +302,10 @@ public void Filter_tables_with_schema_qualified_name3() CREATE TABLE "db2"."K.2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "Kilimanjaro" (Id int, B varchar, UNIQUE (B)); """, - new[] { @"public.""K.2""" }, - Enumerable.Empty(), + [""" + public."K.2" + """], + [], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -323,8 +329,10 @@ public void Filter_tables_with_schema_qualified_name4() CREATE TABLE "db.2"."K2" (Id int, A varchar, UNIQUE (A)); CREATE TABLE "db.2"."Kilimanjaro" (Id int, B varchar, UNIQUE (B)); """, - new[] { @"""db.2"".K2" }, - Enumerable.Empty(), + [""" + "db.2".K2 + """], + [], dbModel => { var table = Assert.Single(dbModel.Tables); @@ -380,15 +388,24 @@ public void Complex_filtering_validation() FOREIGN KEY ("ForeignKeyId1", "ForeignKeyId2") REFERENCES "db2"."PrincipalTable"("UC1", "UC2") ON DELETE CASCADE ); """, - new[] - { - @"""db.2"".""QuotedTableName""", - @"""db.2"".SimpleTableName", - @"public.""Table.With.Dot""", - @"public.""SimpleTableName""", - @"""JustTableName""" - }, - new[] { "db2" }, + [ + """ + "db.2"."QuotedTableName" + """, + """ + "db.2".SimpleTableName + """, + """ + public."Table.With.Dot" + """, + """ + public."SimpleTableName" + """, + """ + "JustTableName" + """ + ], + ["db2"], dbModel => { var sequence = Assert.Single(dbModel.Sequences); @@ -455,8 +472,8 @@ public void Create_columns() "Name" text NOT NULL ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -472,7 +489,9 @@ public void Create_columns() Assert.Single(table.Columns.Where(c => c.Name == "Id")); Assert.Single(table.Columns.Where(c => c.Name == "Name")); }, - @"DROP TABLE ""Blogs"""); + """ + DROP TABLE "Blogs" + """); [Fact] public void Create_view_columns() @@ -480,8 +499,8 @@ public void Create_view_columns() """ CREATE VIEW "BlogsView" AS SELECT 100::int AS "Id", ''::text AS "Name"; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = Assert.IsType(dbModel.Tables.Single()); @@ -498,7 +517,7 @@ public void Create_view_columns() Assert.Single(table.Columns.Where(c => c.Name == "Id")); Assert.Single(table.Columns.Where(c => c.Name == "Name")); }, - @"DROP VIEW ""BlogsView"";"); + """DROP VIEW "BlogsView";"""); [Fact] public void Create_materialized_view_columns() @@ -506,8 +525,8 @@ public void Create_materialized_view_columns() """ CREATE MATERIALIZED VIEW "BlogsView" AS SELECT 100::int AS "Id", ''::text AS "Name"; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -524,7 +543,7 @@ public void Create_materialized_view_columns() Assert.Single(table.Columns.Where(c => c.Name == "Id")); Assert.Single(table.Columns.Where(c => c.Name == "Name")); }, - @"DROP MATERIALIZED VIEW ""BlogsView"";"); + """DROP MATERIALIZED VIEW "BlogsView";"""); [Fact] public void Create_primary_key() @@ -532,8 +551,8 @@ public void Create_primary_key() """ CREATE TABLE "PrimaryKeyTable" ("Id" int PRIMARY KEY); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; @@ -543,7 +562,9 @@ public void Create_primary_key() Assert.StartsWith("PrimaryKeyTable_pkey", pk.Name); Assert.Equal(["Id"], pk.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""PrimaryKeyTable"""); + """ + DROP TABLE "PrimaryKeyTable" + """); [Fact] public void Create_unique_constraints() @@ -560,8 +581,8 @@ public void Create_unique_constraints() CREATE INDEX "IX_INDEX" on "UniqueConstraint" ("IndexProperty"); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -578,7 +599,9 @@ public void Create_unique_constraints() Assert.Equal("UniqueConstraint", secondConstraint.Table.Name); Assert.Equal(["Unq1", "Unq2"], secondConstraint.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""UniqueConstraint"""); + """ + DROP TABLE "UniqueConstraint" + """); [Fact] public void Create_indexes() @@ -595,8 +618,8 @@ public void Create_indexes() CREATE INDEX "IX_NAME" on "IndexTable" ("Name"); CREATE INDEX "IX_INDEX" on "IndexTable" ("IndexProperty"); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -613,7 +636,9 @@ public void Create_indexes() Assert.Single(table.Indexes.Where(c => c.Name == "IX_NAME")); Assert.Single(table.Indexes.Where(c => c.Name == "IX_INDEX")); }, - @"DROP TABLE ""IndexTable"""); + """ + DROP TABLE "IndexTable" + """); [Fact] public void Create_foreign_keys() @@ -634,8 +659,8 @@ FOREIGN KEY ("ForeignKeyId") REFERENCES "PrincipalTable"("Id") ON DELETE CASCADE FOREIGN KEY ("Id") REFERENCES "PrincipalTable"("Id") ON DELETE NO ACTION ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var firstFk = Assert.Single(dbModel.Tables.Single(t => t.Name == "FirstDependent").ForeignKeys); @@ -688,8 +713,8 @@ CREATE TABLE domains ( char_domain public.char_domain NULL ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var textDomainColumn = Assert.Single(dbModel.Tables.Single().Columns.Where(c => c.Name == "text_domain")); @@ -721,8 +746,8 @@ public void Decimal_numeric_types_have_precision_scale() "numeric18Column" numeric(18) NOT NULL ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -731,7 +756,9 @@ public void Decimal_numeric_types_have_precision_scale() Assert.Equal("numeric(15,2)", columns.Single(c => c.Name == "numeric152Column").StoreType); Assert.Equal("numeric(18,0)", columns.Single(c => c.Name == "numeric18Column").StoreType); }, - @"DROP TABLE ""NumericColumns"""); + """ + DROP TABLE "NumericColumns" + """); [Fact] public void Specific_max_length_are_add_to_store_type() @@ -747,8 +774,8 @@ public void Specific_max_length_are_add_to_store_type() "varbit123ArrayColumn" varbit(123)[] NULL ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -760,7 +787,9 @@ public void Specific_max_length_are_add_to_store_type() Assert.Equal("character varying(66)[]", columns.Single(c => c.Name == "varchar66ArrayColumn").StoreType); Assert.Equal("bit varying(123)[]", columns.Single(c => c.Name == "varbit123ArrayColumn").StoreType); }, - @"DROP TABLE ""LengthColumns"""); + """ + DROP TABLE "LengthColumns" + """); [Fact] public void Datetime_types_have_precision_if_non_null_scale() @@ -775,8 +804,8 @@ public void Datetime_types_have_precision_if_non_null_scale() "interval5Column" interval(5) NULL ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -787,7 +816,9 @@ public void Datetime_types_have_precision_if_non_null_scale() Assert.Equal("timestamp(4) with time zone", columns.Single(c => c.Name == "timestamptz4Column").StoreType); Assert.Equal("interval(5)", columns.Single(c => c.Name == "interval5Column").StoreType); }, - @"DROP TABLE ""LengthColumns"""); + """ + DROP TABLE "LengthColumns" + """); [Fact] public void Store_types_without_any_facets() @@ -820,8 +851,8 @@ public void Store_types_without_any_facets() "textArrayColumn" text[] ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single(t => t.Name == "NoFacetTypes").Columns; @@ -849,7 +880,9 @@ public void Store_types_without_any_facets() Assert.Equal("xid", columns.Single(c => c.Name == "xidColumn").StoreType); Assert.Equal("text[]", columns.Single(c => c.Name == "textArrayColumn").StoreType); }, - @"DROP TABLE ""NoFacetTypes"""); + """ + DROP TABLE "NoFacetTypes" + """); [Fact] public void Default_values_are_stored() @@ -860,8 +893,8 @@ public void Default_values_are_stored() "FixedDefaultValue" timestamp NOT NULL DEFAULT ('1999-01-08') ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -869,7 +902,9 @@ public void Default_values_are_stored() "'1999-01-08 00:00:00'::timestamp without time zone", columns.Single(c => c.Name == "FixedDefaultValue").DefaultValueSql); }, - @"DROP TABLE ""DefaultValues"""); + """ + DROP TABLE "DefaultValues" + """); [ConditionalFact] [MinimumPostgresVersion(12, 0)] @@ -883,8 +918,8 @@ public void Computed_values_are_stored() "SumOfAAndB" int GENERATED ALWAYS AS ("A" + "B") STORED ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -893,10 +928,12 @@ public void Computed_values_are_stored() // columns. var column = columns.Single(c => c.Name == "SumOfAAndB"); Assert.Null(column.DefaultValueSql); - Assert.Equal(@"(""A"" + ""B"")", column.ComputedColumnSql); + Assert.Equal("""("A" + "B")""", column.ComputedColumnSql); Assert.True(column.IsStored); }, - @"DROP TABLE ""ComputedValues"""); + """ + DROP TABLE "ComputedValues" + """); [Fact] public void Default_value_matching_clr_default_is_not_stored() @@ -927,8 +964,8 @@ public void Default_value_matching_clr_default_is_not_stored() "IgnoredDefault34" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000' ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -952,8 +989,8 @@ public void ValueGenerated_is_set_for_default_and_serial_column() "FixedDefaultValue" timestamp NOT NULL DEFAULT ('1999-01-08') ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -962,7 +999,9 @@ public void ValueGenerated_is_set_for_default_and_serial_column() Assert.Null(columns.Single(c => c.Name == "NoValueGenerationColumn").ValueGenerated); Assert.Null(columns.Single(c => c.Name == "FixedDefaultValue").ValueGenerated); }, - @"DROP TABLE ""ValueGeneratedProperties"""); + """ + DROP TABLE "ValueGeneratedProperties" + """); [ConditionalFact] [MinimumPostgresVersion(10, 0)] @@ -974,8 +1013,8 @@ public void ValueGenerated_is_set_for_identity_column() "Id2" INT GENERATED BY DEFAULT AS IDENTITY ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -983,7 +1022,9 @@ public void ValueGenerated_is_set_for_identity_column() Assert.Equal(ValueGenerated.OnAdd, columns.Single(c => c.Name == "Id1").ValueGenerated); Assert.Equal(ValueGenerated.OnAdd, columns.Single(c => c.Name == "Id2").ValueGenerated); }, - @"DROP TABLE ""ValueGeneratedProperties"""); + """ + DROP TABLE "ValueGeneratedProperties" + """); [ConditionalFact] [MinimumPostgresVersion(12, 0)] @@ -997,15 +1038,17 @@ public void ValueGenerated_is_set_for_computed_column() "SumOfAAndB" int GENERATED ALWAYS AS ("A" + "B") STORED ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; Assert.Null(columns.Single(c => c.Name == "SumOfAAndB").ValueGenerated); }, - @"DROP TABLE ""ValueGeneratedProperties"""); + """ + DROP TABLE "ValueGeneratedProperties" + """); [Fact] public void Column_nullability_is_set() @@ -1017,8 +1060,8 @@ public void Column_nullability_is_set() "NonNullableInt" int NOT NULL ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -1026,7 +1069,9 @@ public void Column_nullability_is_set() Assert.True(columns.Single(c => c.Name == "NullableInt").IsNullable); Assert.False(columns.Single(c => c.Name == "NonNullableInt").IsNullable); }, - @"DROP TABLE ""NullableColumns"""); + """ + DROP TABLE "NullableColumns" + """); [Fact] public void Column_nullability_is_set_with_domain() @@ -1040,8 +1085,8 @@ public void Column_nullability_is_set_with_domain() "NonNullString" non_nullable_int NOT NULL ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -1063,10 +1108,12 @@ CREATE TABLE "SystemColumnsTable" "Id" int NOT NULL PRIMARY KEY ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => Assert.Single(dbModel.Tables.Single().Columns), - @"DROP TABLE ""SystemColumnsTable"""); + """ + DROP TABLE "SystemColumnsTable" + """); #endregion @@ -1082,8 +1129,8 @@ public void Create_composite_primary_key() PRIMARY KEY ("Id2", "Id1") ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; @@ -1092,7 +1139,9 @@ PRIMARY KEY ("Id2", "Id1") Assert.Equal("CompositePrimaryKeyTable", pk.Table.Name); Assert.Equal(["Id2", "Id1"], pk.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""CompositePrimaryKeyTable"""); + """ + DROP TABLE "CompositePrimaryKeyTable" + """); [Fact] public void Set_primary_key_name_from_index() @@ -1104,8 +1153,8 @@ public void Set_primary_key_name_from_index() CONSTRAINT "MyPK" PRIMARY KEY ( "Id2" ) ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; @@ -1115,7 +1164,9 @@ public void Set_primary_key_name_from_index() Assert.StartsWith("MyPK", pk.Name); Assert.Equal(["Id2"], pk.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""PrimaryKeyName"""); + """ + DROP TABLE "PrimaryKeyName" + """); #endregion @@ -1131,8 +1182,8 @@ public void Create_composite_unique_constraint() CONSTRAINT "UX" UNIQUE ("Id2", "Id1") ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var uniqueConstraint = Assert.Single(dbModel.Tables.Single().UniqueConstraints); @@ -1143,7 +1194,9 @@ public void Create_composite_unique_constraint() Assert.Equal("UX", uniqueConstraint.Name); Assert.Equal(["Id2", "Id1"], uniqueConstraint.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""CompositeUniqueConstraintTable"""); + """ + DROP TABLE "CompositeUniqueConstraintTable" + """); [Fact] public void Set_unique_constraint_name_from_index() @@ -1155,8 +1208,8 @@ public void Set_unique_constraint_name_from_index() CONSTRAINT "MyUC" UNIQUE ( "Id2" ) ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1169,7 +1222,9 @@ public void Set_unique_constraint_name_from_index() Assert.Equal(["Id2"], uniqueConstraint.Columns.Select(ic => ic.Name).ToList()); Assert.Empty(table.Indexes); }, - @"DROP TABLE ""UniqueConstraintName"""); + """ + DROP TABLE "UniqueConstraintName" + """); #endregion @@ -1186,8 +1241,8 @@ public void Create_composite_index() CREATE INDEX "IX_COMPOSITE" ON "CompositeIndexTable" ( "Id2", "Id1" ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); @@ -1198,7 +1253,9 @@ public void Create_composite_index() Assert.Equal("IX_COMPOSITE", index.Name); Assert.Equal(["Id2", "Id1"], index.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""CompositeIndexTable"""); + """ + DROP TABLE "CompositeIndexTable" + """); [Fact] public void Set_unique_true_for_unique_index() @@ -1211,8 +1268,8 @@ public void Set_unique_true_for_unique_index() CREATE UNIQUE INDEX "IX_UNIQUE" ON "UniqueIndexTable" ( "Id2" ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); @@ -1225,7 +1282,9 @@ public void Set_unique_true_for_unique_index() Assert.Null(index.Filter); Assert.Equal(["Id2"], index.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""UniqueIndexTable"""); + """ + DROP TABLE "UniqueIndexTable" + """); [Fact] public void Set_filter_for_filtered_index() @@ -1238,8 +1297,8 @@ public void Set_filter_for_filtered_index() CREATE UNIQUE INDEX "IX_UNIQUE" ON "FilteredIndexTable" ( "Id2" ) WHERE "Id2" > 10; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); @@ -1248,10 +1307,12 @@ public void Set_filter_for_filtered_index() Assert.Equal("public", index.Table.Schema); Assert.Equal("FilteredIndexTable", index.Table.Name); Assert.Equal("IX_UNIQUE", index.Name); - Assert.Equal(@"(""Id2"" > 10)", index.Filter); + Assert.Equal("""("Id2" > 10)""", index.Filter); Assert.Equal(["Id2"], index.Columns.Select(ic => ic.Name).ToList()); }, - @"DROP TABLE ""FilteredIndexTable"""); + """ + DROP TABLE "FilteredIndexTable" + """); #endregion @@ -1274,8 +1335,8 @@ PRIMARY KEY ("Id1", "Id2") FOREIGN KEY ("ForeignKeyId1", "ForeignKeyId2") REFERENCES "PrincipalTable"("Id1", "Id2") ON DELETE CASCADE ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); @@ -1314,8 +1375,8 @@ FOREIGN KEY ("ForeignKeyId1") REFERENCES "PrincipalTable"("Id") ON DELETE CASCAD FOREIGN KEY ("ForeignKeyId2") REFERENCES "AnotherPrincipalTable"("Id") ON DELETE CASCADE ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var foreignKeys = dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys; @@ -1365,8 +1426,8 @@ public void Create_foreign_key_referencing_unique_constraint() FOREIGN KEY ("ForeignKeyId") REFERENCES "PrincipalTable"("Id2") ON DELETE CASCADE ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); @@ -1399,8 +1460,8 @@ public void Set_name_for_foreign_key() CONSTRAINT "MYFK" FOREIGN KEY ("ForeignKeyId") REFERENCES "PrincipalTable"("Id") ON DELETE CASCADE ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); @@ -1443,8 +1504,8 @@ FOREIGN KEY ("ForeignKeyRestrictId") REFERENCES "PrincipalTable"("Id") ON DELETE FOREIGN KEY ("ForeignKeySetDefaultId") REFERENCES "PrincipalTable"("Id") ON DELETE SET DEFAULT ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(t => t.Name == "DependentTable"); @@ -1487,8 +1548,8 @@ public void Warn_missing_schema() """ CREATE TABLE "Blank" ("Id" int) """, - Enumerable.Empty(), - new[] { "MySchema" }, + [], + ["MySchema"], dbModel => { Assert.Empty(dbModel.Tables); @@ -1499,7 +1560,9 @@ public void Warn_missing_schema() Assert.Equal( NpgsqlResources.LogMissingSchema(new TestLogger()).GenerateMessage("MySchema"), Message); }, - @"DROP TABLE ""Blank"""); + """ + DROP TABLE "Blank" + """); [Fact] public void Warn_missing_table() @@ -1507,8 +1570,8 @@ public void Warn_missing_table() """ CREATE TABLE "Blank" ("Id" int) """, - new[] { "MyTable" }, - Enumerable.Empty(), + ["MyTable"], + [], dbModel => { Assert.Empty(dbModel.Tables); @@ -1519,7 +1582,9 @@ public void Warn_missing_table() Assert.Equal( NpgsqlResources.LogMissingTable(new TestLogger()).GenerateMessage("MyTable"), Message); }, - @"DROP TABLE ""Blank"""); + """ + DROP TABLE "Blank" + """); [Fact] public void Warn_missing_principal_table_for_foreign_key() @@ -1535,8 +1600,8 @@ public void Warn_missing_principal_table_for_foreign_key() CONSTRAINT "MYFK" FOREIGN KEY ("ForeignKeyId") REFERENCES "PrincipalTable"("Id") ON DELETE CASCADE ); """, - new[] { "DependentTable" }, - Enumerable.Empty(), + ["DependentTable"], + [], _ => { var (_, Id, Message, _, _) = Assert.Single(Fixture.ListLoggerFactory.Log.Where(t => t.Level == LogLevel.Warning)); @@ -1565,8 +1630,8 @@ public void SequenceSerial() CREATE TABLE my_schema.serial_sequence_in_schema (Id serial PRIMARY KEY); CREATE TABLE my_schema."SerialSequenceInSchema" ("Id" serial PRIMARY KEY); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { // Sequences which belong to a serial column should not get reverse engineered as separate sequences @@ -1595,12 +1660,12 @@ public void SequenceNonSerial() CREATE SEQUENCE "SomeSequence"; CREATE TABLE "NonSerialSequence" ("Id" integer PRIMARY KEY DEFAULT nextval('"SomeSequence"')) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var column = dbModel.Tables.Single().Columns.Single(); - Assert.Equal(@"nextval('""SomeSequence""'::regclass)", column.DefaultValueSql); + Assert.Equal("""nextval('"SomeSequence"'::regclass)""", column.DefaultValueSql); // Npgsql has special detection for serial columns (scaffolding them with ValueGenerated.OnAdd // and removing the default), but not for non-serial sequence-driven columns, which are scaffolded // with a DefaultValue. This is consistent with the SqlServer scaffolding behavior. @@ -1624,8 +1689,8 @@ CREATE TABLE identity ( b int GENERATED BY DEFAULT AS IDENTITY ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var idIdentityAlways = dbModel.Tables.Single().Columns.Single(c => c.Name == "id"); @@ -1663,8 +1728,8 @@ with_options int GENERATED BY DEFAULT AS IDENTITY (START WITH 5 INCREMENT BY 2 M smallint_without_options smallint GENERATED BY DEFAULT AS IDENTITY ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var withOptions = dbModel.Tables.Single().Columns.Single(c => c.Name == "with_options"); @@ -1715,8 +1780,8 @@ CREATE TABLE columns_with_collation ( non_default_collation TEXT COLLATE "POSIX" ); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var columns = dbModel.Tables.Single().Columns; @@ -1730,8 +1795,8 @@ non_default_collation TEXT COLLATE "POSIX" public void Default_database_collation_is_not_scaffolded() => Test( @"-- Empty database", - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => Assert.Null(dbModel.Collation), @""); @@ -1743,8 +1808,8 @@ public void Index_method() CREATE INDEX ix_a ON "IndexMethod" USING hash (a); CREATE INDEX ix_b ON "IndexMethod" (b); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1762,7 +1827,9 @@ public void Index_method() Assert.Null(noMethodIndex.FindAnnotation(NpgsqlAnnotationNames.IndexMethod)); //Assert.Equal("btree", noMethodIndex.FindAnnotation(NpgsqlAnnotationNames.IndexMethod).Value); }, - @"DROP TABLE ""IndexMethod"""); + """ + DROP TABLE "IndexMethod" + """); [Fact] public void Index_operators() @@ -1772,8 +1839,8 @@ public void Index_operators() CREATE INDEX ix_with ON "IndexOperators" (a, b varchar_pattern_ops); CREATE INDEX ix_without ON "IndexOperators" (a, b); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1784,7 +1851,9 @@ public void Index_operators() var indexWithout = table.Indexes.Single(i => i.Name == "ix_without"); Assert.Null(indexWithout.FindAnnotation(NpgsqlAnnotationNames.IndexOperators)); }, - @"DROP TABLE ""IndexOperators"""); + """ + DROP TABLE "IndexOperators" + """); [Fact] public void Index_collation() @@ -1794,8 +1863,8 @@ public void Index_collation() CREATE INDEX ix_with ON "IndexCollation" (a, b COLLATE "POSIX"); CREATE INDEX ix_without ON "IndexCollation" (a, b); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1806,7 +1875,9 @@ public void Index_collation() var indexWithout = table.Indexes.Single(i => i.Name == "ix_without"); Assert.Null(indexWithout.FindAnnotation(RelationalAnnotationNames.Collation)); }, - @"DROP TABLE ""IndexCollation"""); + """ + DROP TABLE "IndexCollation" + """); [Theory] [InlineData("gin", new bool[0])] @@ -1825,8 +1896,8 @@ public void Index_IsDescending(string method, bool[] expected) CREATE INDEX ix_btree ON "IndexSortOrder" USING btree (a ASC, b DESC); CREATE INDEX ix_without ON "IndexSortOrder" (a, b); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1836,9 +1907,11 @@ public void Index_IsDescending(string method, bool[] expected) Assert.Equal(expected, indexWith.IsDescending); var indexWithout = table.Indexes.Single(i => i.Name == "ix_without"); - Assert.Equal(new[] { false, false }, indexWithout.IsDescending); + Assert.Equal([false, false], indexWithout.IsDescending); }, - @"DROP TABLE ""IndexSortOrder"""); + """ + DROP TABLE "IndexSortOrder" + """); [Fact] public void Index_null_sort_order() @@ -1848,8 +1921,8 @@ public void Index_null_sort_order() CREATE INDEX ix_with ON "IndexNullSortOrder" (a NULLS FIRST, b DESC NULLS LAST); CREATE INDEX ix_without ON "IndexNullSortOrder" (a, b); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1862,7 +1935,9 @@ public void Index_null_sort_order() var indexWithout = table.Indexes.Single(i => i.Name == "ix_without"); Assert.Null(indexWithout.FindAnnotation(NpgsqlAnnotationNames.IndexNullSortOrder)); }, - @"DROP TABLE ""IndexNullSortOrder"""); + """ + DROP TABLE "IndexNullSortOrder" + """); [ConditionalFact] [MinimumPostgresVersion(11, 0)] @@ -1873,8 +1948,8 @@ public void Index_covering() CREATE INDEX ix_with ON "IndexCovering" (a) INCLUDE (b, c); CREATE INDEX ix_without ON "IndexCovering" (a, b, c); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1889,7 +1964,9 @@ public void Index_covering() Assert.Equal(new[] { "a", "b", "c" }, indexWithout.Columns.Select(i => i.Name).ToArray()); Assert.Null(indexWithout.FindAnnotation(NpgsqlAnnotationNames.IndexInclude)); }, - @"DROP TABLE ""IndexCovering"""); + """ + DROP TABLE "IndexCovering" + """); [ConditionalFact] [MinimumPostgresVersion(15, 0)] @@ -1900,8 +1977,8 @@ public void Index_are_nulls_distinct() CREATE INDEX "IX_NullsDistinct" ON "IndexNullsDistinct" (a); CREATE INDEX "IX_NullsNotDistinct" ON "IndexNullsDistinct" (a) NULLS NOT DISTINCT; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1913,7 +1990,9 @@ public void Index_are_nulls_distinct() false, Assert.Single(table.Indexes, i => i.Name == "IX_NullsNotDistinct")[NpgsqlAnnotationNames.NullsDistinct]); }, - @"DROP TABLE ""IndexNullsDistinct"""); + """ + DROP TABLE "IndexNullsDistinct" + """); [Fact] public void Comments() @@ -1923,8 +2002,8 @@ public void Comments() COMMENT ON TABLE comment IS 'table comment'; COMMENT ON COLUMN comment.a IS 'column comment' """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var table = dbModel.Tables.Single(); @@ -1942,8 +2021,8 @@ public void Sequence_types() CREATE SEQUENCE "IntSequence" AS int; CREATE SEQUENCE "BigIntSequence" AS bigint; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var smallSequence = dbModel.Sequences.Single(s => s.Name == "SmallIntSequence"); @@ -1967,8 +2046,8 @@ public void Dropped_columns() ALTER TABLE foo DROP COLUMN id; ALTER TABLE foo ADD COLUMN id2 int PRIMARY KEY; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { Assert.Single(dbModel.Tables.Single().Columns); @@ -1983,8 +2062,8 @@ public void Postgres_extensions() CREATE EXTENSION hstore; CREATE EXTENSION pgcrypto SCHEMA db2; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var extensions = dbModel.GetPostgresExtensions(); @@ -2011,8 +2090,8 @@ public void Enums() CREATE TYPE db2.mood AS ENUM ('excited', 'depressed'); CREATE TABLE foo (mood mood UNIQUE); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var enums = dbModel.GetPostgresEnums(); @@ -2020,11 +2099,11 @@ public void Enums() var mood = enums.Single(e => e.Schema is null); Assert.Equal("mood", mood.Name); - Assert.Equal(new[] { "happy", "sad" }, mood.Labels); + Assert.Equal(["happy", "sad"], mood.Labels); var mood2 = enums.Single(e => e.Schema == "db2"); Assert.Equal("mood", mood2.Name); - Assert.Equal(new[] { "excited", "depressed" }, mood2.Labels); + Assert.Equal(["excited", "depressed"], mood2.Labels); var table = Assert.Single(dbModel.Tables); Assert.NotNull(table); @@ -2049,8 +2128,8 @@ public void Bug453() CREATE TABLE foo (mood mood, some_num int UNIQUE); CREATE TABLE bar (foreign_key int REFERENCES foo(some_num)); """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], // Enum columns are left out of the model for now (a warning is logged). dbModel => Assert.Single(dbModel.Tables.Single(t => t.Name == "foo").Columns), """ @@ -2093,8 +2172,8 @@ CREATE TABLE column_types ( line line ) """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => { var options = new NpgsqlSingletonOptions(); @@ -2129,8 +2208,8 @@ public void System_tables_are_ignored() DROP EXTENSION IF EXISTS postgis; CREATE EXTENSION postgis; """, - Enumerable.Empty(), - Enumerable.Empty(), + [], + [], dbModel => Assert.Empty(dbModel.Tables), "DROP EXTENSION postgis"); @@ -2184,7 +2263,9 @@ public override async Task InitializeAsync() { await base.InitializeAsync(); await TestStore.ExecuteNonQueryAsync("CREATE SCHEMA IF NOT EXISTS db2"); - await TestStore.ExecuteNonQueryAsync(@"CREATE SCHEMA IF NOT EXISTS ""db.2"""); + await TestStore.ExecuteNonQueryAsync(""" + CREATE SCHEMA IF NOT EXISTS "db.2" + """); } protected override bool ShouldLogCategory(string logCategory) diff --git a/test/EFCore.PG.FunctionalTests/TestModels/Array/ArrayQueryData.cs b/test/EFCore.PG.FunctionalTests/TestModels/Array/ArrayQueryData.cs index 55f9f0bd9..32e5a6c3a 100644 --- a/test/EFCore.PG.FunctionalTests/TestModels/Array/ArrayQueryData.cs +++ b/test/EFCore.PG.FunctionalTests/TestModels/Array/ArrayQueryData.cs @@ -22,8 +22,8 @@ public IQueryable Set() } public static IReadOnlyList CreateArrayEntities() - => new ArrayEntity[] - { + => + [ new() { Id = 1, @@ -49,7 +49,7 @@ public static IReadOnlyList CreateArrayEntities() ValueConvertedListOfEnum = [SomeEnum.Eight, SomeEnum.Nine], ArrayOfStringConvertedToDelimitedString = ["3", "4"], ListOfStringConvertedToDelimitedString = ["3", "4"], - IList = new[] { 8, 9 }, + IList = [8, 9], Byte = 10 }, new() @@ -77,11 +77,11 @@ public static IReadOnlyList CreateArrayEntities() ValueConvertedListOfEnum = [SomeEnum.Nine, SomeEnum.Ten], ArrayOfStringConvertedToDelimitedString = ["5", "6", "7", "8"], ListOfStringConvertedToDelimitedString = ["5", "6", "7", "8"], - IList = new[] { 9, 10 }, + IList = [9, 10], Byte = 20 } - }; + ]; public static IReadOnlyList CreateContainerEntities() - => new[] { new ArrayContainerEntity { Id = 1, ArrayEntities = CreateArrayEntities().ToList() } }; + => [new ArrayContainerEntity { Id = 1, ArrayEntities = CreateArrayEntities().ToList() }]; } diff --git a/test/EFCore.PG.FunctionalTests/TestUtilities/NpgsqlDatabaseCleaner.cs b/test/EFCore.PG.FunctionalTests/TestUtilities/NpgsqlDatabaseCleaner.cs index d75de6be2..5698435e0 100644 --- a/test/EFCore.PG.FunctionalTests/TestUtilities/NpgsqlDatabaseCleaner.cs +++ b/test/EFCore.PG.FunctionalTests/TestUtilities/NpgsqlDatabaseCleaner.cs @@ -53,8 +53,7 @@ public override void Clean(DatabaseFacade facade) private void DropExtensions(NpgsqlConnection conn) { - const string getExtensions = @" -SELECT name FROM pg_available_extensions WHERE installed_version IS NOT NULL AND name <> 'plpgsql'"; + const string getExtensions = "SELECT name FROM pg_available_extensions WHERE installed_version IS NOT NULL AND name <> 'plpgsql'"; List extensions; using (var cmd = new NpgsqlCommand(getExtensions, conn)) @@ -76,11 +75,12 @@ private void DropExtensions(NpgsqlConnection conn) /// private void DropTypes(NpgsqlConnection conn) { - const string getUserDefinedRangesEnums = @" + const string getUserDefinedRangesEnums = """ SELECT ns.nspname, typname FROM pg_type JOIN pg_namespace AS ns ON ns.oid = pg_type.typnamespace -WHERE typtype IN ('r', 'e') AND nspname <> 'pg_catalog'"; +WHERE typtype IN ('r', 'e') AND nspname <> 'pg_catalog' +"""; (string Schema, string Name)[] userDefinedTypes; using (var cmd = new NpgsqlCommand(getUserDefinedRangesEnums, conn)) @@ -91,7 +91,7 @@ FROM pg_type if (userDefinedTypes.Any()) { - var dropTypes = string.Concat(userDefinedTypes.Select(t => $@"DROP TYPE ""{t.Schema}"".""{t.Name}"" CASCADE;")); + var dropTypes = string.Concat(userDefinedTypes.Select(t => $"""DROP TYPE "{t.Schema}"."{t.Name}" CASCADE;""")); using var cmd = new NpgsqlCommand(dropTypes, conn); cmd.ExecuteNonQuery(); } @@ -102,8 +102,8 @@ FROM pg_type /// private void DropFunctions(NpgsqlConnection conn) { - const string getUserDefinedFunctions = @" -SELECT 'DROP ROUTINE ""' || nspname || '"".""' || proname || '""(' || oidvectortypes(proargtypes) || ');' FROM pg_proc + const string getUserDefinedFunctions = """ +SELECT 'DROP ROUTINE "' || nspname || '"."' || proname || '"(' || oidvectortypes(proargtypes) || ');' FROM pg_proc JOIN pg_namespace AS ns ON ns.oid = pg_proc.pronamespace WHERE nspname NOT IN ('pg_catalog', 'information_schema') AND @@ -111,7 +111,8 @@ NOT EXISTS ( SELECT * FROM pg_depend AS dep WHERE dep.classid = (SELECT oid FROM pg_class WHERE relname = 'pg_proc') AND dep.objid = pg_proc.oid AND - deptype = 'e');"; + deptype = 'e'); +"""; string dropSql; using (var cmd = new NpgsqlCommand(getUserDefinedFunctions, conn)) @@ -151,7 +152,7 @@ FROM pg_collation coll if (userDefinedTypes.Any()) { - var dropTypes = string.Concat(userDefinedTypes.Select(t => $@"DROP COLLATION ""{t.Schema}"".""{t.Name}"" CASCADE;")); + var dropTypes = string.Concat(userDefinedTypes.Select(t => $"""DROP COLLATION "{t.Schema}"."{t.Name}" CASCADE;""")); using var cmd = new NpgsqlCommand(dropTypes, conn); cmd.ExecuteNonQuery(); } diff --git a/test/EFCore.PG.FunctionalTests/UpdatesNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/UpdatesNpgsqlTest.cs index 0c4b0fc3c..b44952233 100644 --- a/test/EFCore.PG.FunctionalTests/UpdatesNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/UpdatesNpgsqlTest.cs @@ -69,7 +69,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity() .Property(p => p.Id).HasDefaultValueSql("uuid_generate_v4()"); - modelBuilder.Entity().HasIndex(p => new { p.Name, p.Price }).IsUnique().HasFilter(@"""Name"" IS NOT NULL"); + modelBuilder.Entity().HasIndex(p => new { p.Name, p.Price }).IsUnique().HasFilter(""" + "Name" IS NOT NULL + """); modelBuilder.Entity().Property(r => r.Concurrency).HasColumnType("timestamp without time zone"); } diff --git a/test/EFCore.PG.FunctionalTests/WithConstructorsNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/WithConstructorsNpgsqlTest.cs index e1337b284..14ce4b0b4 100644 --- a/test/EFCore.PG.FunctionalTests/WithConstructorsNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/WithConstructorsNpgsqlTest.cs @@ -17,7 +17,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con { base.OnModelCreating(modelBuilder, context); - modelBuilder.Entity().HasNoKey().ToSqlQuery(@"SELECT * FROM ""Blog"""); + modelBuilder.Entity().HasNoKey().ToSqlQuery(""" + SELECT * FROM "Blog" + """); } } } diff --git a/test/EFCore.PG.Tests/Metadata/NpgsqlMetadataBuilderExtensionsTest.cs b/test/EFCore.PG.Tests/Metadata/NpgsqlMetadataBuilderExtensionsTest.cs index 78e23abfb..91aa83076 100644 --- a/test/EFCore.PG.Tests/Metadata/NpgsqlMetadataBuilderExtensionsTest.cs +++ b/test/EFCore.PG.Tests/Metadata/NpgsqlMetadataBuilderExtensionsTest.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.Internal; namespace Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; @@ -81,7 +80,7 @@ public void Can_access_index() var modelBuilder = CreateBuilder(); var entityTypeBuilder = modelBuilder.Entity(typeof(Splot)); var idProperty = entityTypeBuilder.Property(typeof(int), "Id").Metadata; - var indexBuilder = entityTypeBuilder.HasIndex(new[] { idProperty }); + var indexBuilder = entityTypeBuilder.HasIndex([idProperty]); Assert.NotNull(indexBuilder.HasMethod("gin")); Assert.Equal("gin", indexBuilder.Metadata.GetMethod()); @@ -103,7 +102,7 @@ public void Can_access_relationship() var modelBuilder = CreateBuilder(); var entityTypeBuilder = modelBuilder.Entity(typeof(Splot)); var idProperty = entityTypeBuilder.Property(typeof(int), "Id").Metadata; - var key = entityTypeBuilder.HasKey(new[] { idProperty }).Metadata; + var key = entityTypeBuilder.HasKey([idProperty]).Metadata; var relationshipBuilder = entityTypeBuilder.HasRelationship(entityTypeBuilder.Metadata, key); Assert.NotNull(relationshipBuilder.HasConstraintName("Splew")); diff --git a/test/EFCore.PG.Tests/NpgsqlRelationalConnectionTest.cs b/test/EFCore.PG.Tests/NpgsqlRelationalConnectionTest.cs index e5ce3d183..8b72df045 100644 --- a/test/EFCore.PG.Tests/NpgsqlRelationalConnectionTest.cs +++ b/test/EFCore.PG.Tests/NpgsqlRelationalConnectionTest.cs @@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore.Infrastructure.Internal; using Microsoft.EntityFrameworkCore.Storage.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Diagnostics.Internal; -using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities; diff --git a/test/EFCore.PG.Tests/Scaffolding/NpgsqlCodeGeneratorTest.cs b/test/EFCore.PG.Tests/Scaffolding/NpgsqlCodeGeneratorTest.cs index 5b2d1348b..1405216a8 100644 --- a/test/EFCore.PG.Tests/Scaffolding/NpgsqlCodeGeneratorTest.cs +++ b/test/EFCore.PG.Tests/Scaffolding/NpgsqlCodeGeneratorTest.cs @@ -12,7 +12,7 @@ public virtual void Use_provider_method_is_generated_correctly() { var codeGenerator = new NpgsqlCodeGenerator( new ProviderCodeGeneratorDependencies( - Enumerable.Empty())); + [])); var result = codeGenerator.GenerateUseProvider("Server=test;Username=test;Password=test;Database=test", providerOptions: null); @@ -28,7 +28,7 @@ public virtual void Use_provider_method_is_generated_correctly_with_options() { var codeGenerator = new NpgsqlCodeGenerator( new ProviderCodeGeneratorDependencies( - Enumerable.Empty())); + [])); var providerOptions = new MethodCallCodeFragment(_setProviderOptionMethodInfo); @@ -53,7 +53,7 @@ public virtual void Use_provider_method_is_generated_correctly_with_NetTopologyS { var codeGenerator = new NpgsqlCodeGenerator( new ProviderCodeGeneratorDependencies( - new[] { new NpgsqlNetTopologySuiteCodeGeneratorPlugin() })); + [new NpgsqlNetTopologySuiteCodeGeneratorPlugin()])); var result = ((IProviderConfigurationCodeGenerator)codeGenerator).GenerateUseProvider("Data Source=Test"); @@ -76,7 +76,7 @@ public virtual void Use_provider_method_is_generated_correctly_with_NodaTime() { var codeGenerator = new NpgsqlCodeGenerator( new ProviderCodeGeneratorDependencies( - new[] { new NpgsqlNodaTimeCodeGeneratorPlugin() })); + [new NpgsqlNodaTimeCodeGeneratorPlugin()])); var result = ((IProviderConfigurationCodeGenerator)codeGenerator).GenerateUseProvider("Data Source=Test"); diff --git a/test/EFCore.PG.Tests/Storage/NpgsqlNodaTimeTypeMappingTest.cs b/test/EFCore.PG.Tests/Storage/NpgsqlNodaTimeTypeMappingTest.cs index 4fe8cc00a..1545c1348 100644 --- a/test/EFCore.PG.Tests/Storage/NpgsqlNodaTimeTypeMappingTest.cs +++ b/test/EFCore.PG.Tests/Storage/NpgsqlNodaTimeTypeMappingTest.cs @@ -105,7 +105,7 @@ public void GenerateSqlLiteral_returns_tsrange_literal() Assert.Equal("timestamp without time zone", mapping.SubtypeMapping.StoreType); var value = new NpgsqlRange(new LocalDateTime(2020, 1, 1, 12, 0, 0), new LocalDateTime(2020, 1, 2, 12, 0, 0)); - Assert.Equal(@"'[""2020-01-01T12:00:00"",""2020-01-02T12:00:00""]'::tsrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00","2020-01-02T12:00:00"]'::tsrange""", mapping.GenerateSqlLiteral(value)); } [Fact] @@ -170,7 +170,7 @@ public void GenerateCodeLiteral_returns_ZonedDateTime_literal() var zonedDateTime = (new LocalDateTime(2018, 4, 20, 10, 31, 33, 666) + Period.FromTicks(6660)) .InZone(DateTimeZone.ForOffset(Offset.FromHours(2)), Resolvers.LenientResolver); Assert.Equal( - @"new NodaTime.ZonedDateTime(NodaTime.Instant.FromUnixTimeTicks(15242130936666660L), NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.ForId(""UTC+02""))", + """new NodaTime.ZonedDateTime(NodaTime.Instant.FromUnixTimeTicks(15242130936666660L), NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.ForId("UTC+02"))""", CodeLiteral(zonedDateTime)); } @@ -369,7 +369,7 @@ public void GenerateSqlLiteral_returns_tstzrange_Instant_literal() var value = new NpgsqlRange( new LocalDateTime(2020, 1, 1, 12, 0, 0).InUtc().ToInstant(), new LocalDateTime(2020, 1, 2, 12, 0, 0).InUtc().ToInstant()); - Assert.Equal(@"'[""2020-01-01T12:00:00Z"",""2020-01-02T12:00:00Z""]'::tstzrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00Z","2020-01-02T12:00:00Z"]'::tstzrange""", mapping.GenerateSqlLiteral(value)); } [Fact] @@ -382,7 +382,7 @@ public void GenerateSqlLiteral_returns_tstzrange_ZonedDateTime_literal() var value = new NpgsqlRange( new LocalDateTime(2020, 1, 1, 12, 0, 0).InUtc(), new LocalDateTime(2020, 1, 2, 12, 0, 0).InUtc()); - Assert.Equal(@"'[""2020-01-01T12:00:00Z"",""2020-01-02T12:00:00Z""]'::tstzrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00Z","2020-01-02T12:00:00Z"]'::tstzrange""", mapping.GenerateSqlLiteral(value)); } [Fact] @@ -395,7 +395,7 @@ public void GenerateSqlLiteral_returns_tstzrange_OffsetDateTime_literal() var value = new NpgsqlRange( new LocalDateTime(2020, 1, 1, 12, 0, 0).WithOffset(Offset.Zero), new LocalDateTime(2020, 1, 2, 12, 0, 0).WithOffset(Offset.Zero)); - Assert.Equal(@"'[""2020-01-01T12:00:00Z"",""2020-01-02T12:00:00Z""]'::tstzrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00Z","2020-01-02T12:00:00Z"]'::tstzrange""", mapping.GenerateSqlLiteral(value)); } [Fact] @@ -688,7 +688,7 @@ public void OffsetTime_json(string timeString, string json) [Fact] public void Duration_is_properly_mapped() => Assert.All( - new[] { GetMapping(typeof(Duration)), GetMapping(typeof(Duration), "interval") }, + [GetMapping(typeof(Duration)), GetMapping(typeof(Duration), "interval")], m => { Assert.Equal("interval", m.StoreType); @@ -698,7 +698,7 @@ public void Duration_is_properly_mapped() [Fact] public void Period_is_properly_mapped() => Assert.All( - new[] { GetMapping(typeof(Period)), GetMapping(typeof(Period), "interval") }, + [GetMapping(typeof(Period)), GetMapping(typeof(Period), "interval")], m => { Assert.Equal("interval", m.StoreType); @@ -841,11 +841,10 @@ public void GenerateCodeLiteral_returns_DateTimezone_literal() new JsonValueReaderWriterSource(new JsonValueReaderWriterSourceDependencies()), []), new RelationalTypeMappingSourceDependencies( - new IRelationalTypeMappingSourcePlugin[] - { - new NpgsqlNodaTimeTypeMappingSourcePlugin( + [ + new NpgsqlNodaTimeTypeMappingSourcePlugin( new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies())) - }), + ]), new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()), new NpgsqlSingletonOptions() ); diff --git a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs index c735a165c..e95bbdd19 100644 --- a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs +++ b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingSourceTest.cs @@ -310,11 +310,10 @@ private NpgsqlTypeMappingSource CreateTypeMappingSource(Version postgresVersion new JsonValueReaderWriterSource(new JsonValueReaderWriterSourceDependencies()), []), new RelationalTypeMappingSourceDependencies( - new IRelationalTypeMappingSourcePlugin[] - { - new NpgsqlNetTopologySuiteTypeMappingSourcePlugin(new NpgsqlNetTopologySuiteSingletonOptions()), + [ + new NpgsqlNetTopologySuiteTypeMappingSourcePlugin(new NpgsqlNetTopologySuiteSingletonOptions()), new DummyTypeMappingSourcePlugin() - }), + ]), new NpgsqlSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies()), options); } diff --git a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingTest.cs b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingTest.cs index c2d90bd2a..ea8f3663a 100644 --- a/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingTest.cs +++ b/test/EFCore.PG.Tests/Storage/NpgsqlTypeMappingTest.cs @@ -9,7 +9,6 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal; using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping; -using Npgsql.NameTranslation; namespace Npgsql.EntityFrameworkCore.PostgreSQL.Storage; @@ -259,7 +258,7 @@ public void GenerateSqlLiteral_returns_macaddr_literal() [Fact] public void GenerateCodeLiteral_returns_macaddr_literal() => Assert.Equal( - @"System.Net.NetworkInformation.PhysicalAddress.Parse(""001122334455"")", + """System.Net.NetworkInformation.PhysicalAddress.Parse("001122334455")""", CodeLiteral(PhysicalAddress.Parse("00-11-22-33-44-55"))); [Fact] @@ -270,7 +269,7 @@ public void GenerateSqlLiteral_returns_macaddr8_literal() [Fact] public void GenerateCodeLiteral_returns_macaddr8_literal() => Assert.Equal( - @"System.Net.NetworkInformation.PhysicalAddress.Parse(""0011223344556677"")", + """System.Net.NetworkInformation.PhysicalAddress.Parse("0011223344556677")""", CodeLiteral(PhysicalAddress.Parse("00-11-22-33-44-55-66-77"))); [Fact] @@ -279,7 +278,7 @@ public void GenerateSqlLiteral_returns_inet_literal() [Fact] public void GenerateCodeLiteral_returns_inet_literal() - => Assert.Equal(@"System.Net.IPAddress.Parse(""192.168.1.1"")", CodeLiteral(IPAddress.Parse("192.168.1.1"))); + => Assert.Equal("""System.Net.IPAddress.Parse("192.168.1.1")""", CodeLiteral(IPAddress.Parse("192.168.1.1"))); [Fact] public void GenerateSqlLiteral_returns_cidr_literal() @@ -288,7 +287,7 @@ public void GenerateSqlLiteral_returns_cidr_literal() [Fact] public void GenerateCodeLiteral_returns_cidr_literal() => Assert.Equal( - @"new NpgsqlTypes.NpgsqlCidr(System.Net.IPAddress.Parse(""192.168.1.0""), (byte)24)", + """new NpgsqlTypes.NpgsqlCidr(System.Net.IPAddress.Parse("192.168.1.0"), (byte)24)""", CodeLiteral(new NpgsqlCidr(IPAddress.Parse("192.168.1.0"), 24))); #endregion Networking @@ -402,19 +401,19 @@ public void GenerateSqlLiteral_returns_bool_literal() [Fact] public void GenerateSqlLiteral_returns_varbit_literal() - => Assert.Equal("B'10'", GetMapping("varbit").GenerateSqlLiteral(new BitArray(new[] { true, false }))); + => Assert.Equal("B'10'", GetMapping("varbit").GenerateSqlLiteral(new BitArray([true, false]))); [Fact] public void GenerateCodeLiteral_returns_varbit_literal() - => Assert.Equal("new System.Collections.BitArray(new bool[] { true, false })", CodeLiteral(new BitArray(new[] { true, false }))); + => Assert.Equal("new System.Collections.BitArray(new bool[] { true, false })", CodeLiteral(new BitArray([true, false]))); [Fact] public void GenerateSqlLiteral_returns_bit_literal() - => Assert.Equal("B'10'", GetMapping("bit").GenerateSqlLiteral(new BitArray(new[] { true, false }))); + => Assert.Equal("B'10'", GetMapping("bit").GenerateSqlLiteral(new BitArray([true, false]))); [Fact] public void GenerateCodeLiteral_returns_bit_literal() - => Assert.Equal("new System.Collections.BitArray(new bool[] { true, false })", CodeLiteral(new BitArray(new[] { true, false }))); + => Assert.Equal("new System.Collections.BitArray(new bool[] { true, false })", CodeLiteral(new BitArray([true, false]))); [Fact(Skip = "https://github.com/dotnet/efcore/pull/30939")] public void ValueComparer_hstore_array() @@ -438,7 +437,7 @@ public void GenerateSqlLiteral_returns_bytea_literal() [Fact] public void GenerateSqlLiteral_returns_hstore_literal() => Assert.Equal( - @"HSTORE '""k1""=>""v1"",""k2""=>""v2""'", + """HSTORE '"k1"=>"v1","k2"=>"v2"'""", GetMapping("hstore").GenerateSqlLiteral(new Dictionary { { "k1", "v1" }, { "k2", "v2" } })); [Fact] @@ -454,7 +453,7 @@ public void GenerateSqlLiteral_returns_BigInteger_literal() [Fact] public void GenerateCodeLiteral_returns_BigInteger_literal() => Assert.Equal( - @"BigInteger.Parse(""18446744073709551615"", NumberFormatInfo.InvariantInfo)", + """BigInteger.Parse("18446744073709551615", NumberFormatInfo.InvariantInfo)""", CodeLiteral(new BigInteger(ulong.MaxValue))); [Fact] @@ -501,13 +500,17 @@ public void GenerateSqlLiteral_returns_enum_literal() [Fact] public void GenerateSqlLiteral_returns_enum_uppercase_literal() { - var mapping = new NpgsqlEnumTypeMapping(@"""DummyEnum""", "DummyEnum", typeof(DummyEnum), new Dictionary + var mapping = new NpgsqlEnumTypeMapping(""" + "DummyEnum" + """, "DummyEnum", typeof(DummyEnum), new Dictionary { [DummyEnum.Happy] = "happy", [DummyEnum.Sad] = "sad" }); - Assert.Equal(@"'sad'::""DummyEnum""", mapping.GenerateSqlLiteral(DummyEnum.Sad)); + Assert.Equal(""" + 'sad'::"DummyEnum" + """, mapping.GenerateSqlLiteral(DummyEnum.Sad)); } private enum DummyEnum @@ -713,7 +716,7 @@ public void GenerateSqlLiteral_returns_tsrange_literal() Assert.Equal("timestamp without time zone", mapping.SubtypeMapping.StoreType); var value = new NpgsqlRange(new DateTime(2020, 1, 1, 12, 0, 0), new DateTime(2020, 1, 2, 12, 0, 0)); - Assert.Equal(@"'[""2020-01-01T12:00:00"",""2020-01-02T12:00:00""]'::tsrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00","2020-01-02T12:00:00"]'::tsrange""", mapping.GenerateSqlLiteral(value)); } [Fact] @@ -724,7 +727,7 @@ public void GenerateSqlLiteral_returns_tstzrange_literal() var value = new NpgsqlRange( new DateTime(2020, 1, 1, 12, 0, 0, DateTimeKind.Utc), new DateTime(2020, 1, 2, 12, 0, 0, DateTimeKind.Utc)); - Assert.Equal(@"'[""2020-01-01T12:00:00Z"",""2020-01-02T12:00:00Z""]'::tstzrange", mapping.GenerateSqlLiteral(value)); + Assert.Equal("""'["2020-01-01T12:00:00Z","2020-01-02T12:00:00Z"]'::tstzrange""", mapping.GenerateSqlLiteral(value)); } [Fact] @@ -908,12 +911,12 @@ public void GenerateSqlLiteral_returns_json_element_literal() public void GenerateCodeLiteral_returns_json_document_literal() => Assert.Equal( """System.Text.Json.JsonDocument.Parse("{\"Name\":\"Joe\",\"Age\":25}", new System.Text.Json.JsonDocumentOptions())""", - CodeLiteral(JsonDocument.Parse(@"{""Name"":""Joe"",""Age"":25}"))); + CodeLiteral(JsonDocument.Parse("""{"Name":"Joe","Age":25}"""))); [Fact] public void GenerateCodeLiteral_returns_json_element_literal() // TODO: https://github.com/dotnet/efcore/issues/32192 - => Assert.Throws(() => CodeLiteral(JsonDocument.Parse(@"{""Name"":""Joe"",""Age"":25}").RootElement)); + => Assert.Throws(() => CodeLiteral(JsonDocument.Parse("""{"Name":"Joe","Age":25}""").RootElement)); // Assert.Equal( // """System.Text.Json.JsonDocument.Parse("{\"Name\":\"Joe\",\"Age\":25}", new System.Text.Json.JsonDocumentOptions()).RootElement""",