Skip to content
Permalink
Browse files

Minor cleanup all around

With Rider solution-wide analysis
  • Loading branch information...
roji committed Sep 1, 2019
1 parent d4e73b4 commit e59da52c45f4e556aae7ec7eec1fa3e07d9b85c0
Showing with 212 additions and 251 deletions.
  1. +1 −0 .editorconfig
  2. +4 −0 Npgsql.sln.DotSettings
  3. +1 −0 src/Npgsql.GeoJSON/NpgsqlGeoJSONExtensions.cs
  4. +1 −1 src/Npgsql.Json.NET/JsonHandler.cs
  5. +0 −2 src/Npgsql.Json.NET/JsonbHandler.cs
  6. +9 −9 src/Npgsql.NetTopologySuite/NetTopologySuiteHandler.cs
  7. +1 −0 src/Npgsql.NetTopologySuite/NpgsqlNetTopologySuiteExtensions.cs
  8. +1 −1 src/Npgsql.RawPostgis/NpgsqlRawPostgisExtensions.cs
  9. +1 −1 src/Npgsql.RawPostgis/PostgisRawHandler.cs
  10. +1 −3 src/Npgsql/BackendMessages/AuthenticationMessages.cs
  11. +0 −1 src/Npgsql/BackendMessages/RowDescriptionMessage.cs
  12. +0 −3 src/Npgsql/Common.cs
  13. +6 −4 src/Npgsql/Counters.cs
  14. +0 −1 src/Npgsql/Logging/NpgsqlLogManager.cs
  15. +1 −1 src/Npgsql/NpgsqlBinaryExporter.cs
  16. +1 −1 src/Npgsql/NpgsqlBinaryImporter.cs
  17. +10 −8 src/Npgsql/NpgsqlCommand.cs
  18. +7 −10 src/Npgsql/NpgsqlConnector.Auth.cs
  19. +5 −10 src/Npgsql/NpgsqlConnector.cs
  20. +23 −41 src/Npgsql/NpgsqlDataReader.cs
  21. +19 −19 src/Npgsql/NpgsqlDatabaseInfo.cs
  22. +9 −9 src/Npgsql/NpgsqlLargeObjectManager.cs
  23. +10 −11 src/Npgsql/NpgsqlLargeObjectStream.cs
  24. +0 −1 src/Npgsql/NpgsqlParameter.cs
  25. +0 −1 src/Npgsql/NpgsqlParameter`.cs
  26. +26 −25 src/Npgsql/NpgsqlReadBuffer.Stream.cs
  27. +1 −1 src/Npgsql/NpgsqlSchema.cs
  28. +0 −1 src/Npgsql/NpgsqlTransaction.cs
  29. +3 −3 src/Npgsql/NpgsqlTypes/NpgsqlTimeSpan.cs
  30. +18 −22 src/Npgsql/NpgsqlTypes/NpgsqlTsVector.cs
  31. +1 −0 src/Npgsql/NpgsqlTypes/NpgsqlTypes.cs
  32. +1 −0 src/Npgsql/NpgsqlTypes/NpgsqlUserTypes.cs
  33. +2 −2 src/Npgsql/NpgsqlWriteBuffer.Stream.cs
  34. +4 −4 src/Npgsql/PoolManager.cs
  35. +1 −4 src/Npgsql/PostgresMinimalDatabaseInfo.cs
  36. +0 −1 src/Npgsql/PregeneratedMessages.cs
  37. +3 −0 src/Npgsql/SqlQueryParser.cs
  38. +2 −2 src/Npgsql/TypeHandlers/ArrayHandler.cs
  39. +1 −0 src/Npgsql/TypeHandlers/BitStringHandler.cs
  40. +0 −1 src/Npgsql/TypeHandlers/JsonHandler.cs
  41. +1 −1 src/Npgsql/TypeHandlers/NumericHandlers/MoneyHandler.cs
  42. +1 −1 src/Npgsql/TypeHandlers/TextHandler.cs
  43. +4 −4 src/Npgsql/TypeHandlers/UnmappedEnumHandler.cs
  44. +1 −1 src/Npgsql/TypeHandling/NpgsqlSimpleTypeHandler.cs
  45. +1 −1 src/Npgsql/TypeHandling/NpgsqlTypeHandler`.cs
  46. +0 −2 src/Npgsql/TypeMapping/ConnectorTypeMapper.cs
  47. +1 −0 src/Npgsql/TypeMapping/EntityFrameworkCoreCompat.cs
  48. +0 −1 src/Npgsql/TypeMapping/TypeMapperBase.cs
  49. +20 −20 src/Npgsql/Util/CodeAnalysis.cs
  50. +2 −2 src/Npgsql/Util/DbDataReaderExtensions.cs
  51. +5 −13 src/Npgsql/Util/VersionExtensions.cs
  52. +1 −0 src/Npgsql/VolatileResourceManager.cs
  53. +1 −1 src/Npgsql/WindowsUsernameProvider.cs
@@ -37,3 +37,4 @@ csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
csharp_indent_case_contents_when_block = false
@@ -6,6 +6,7 @@
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ArgumentsStyleStringLiteral/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=MemberCanBePrivate_002EGlobal/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=MemberCanBeProtected_002EGlobal/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/UsageCheckingInspectionLevel/@EntryValue">InternalsOnly</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/ARGUMENTS_LITERAL/@EntryValue">Positional</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/ARGUMENTS_NAMED/@EntryValue">Positional</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/DEFAULT_INTERNAL_MODIFIER/@EntryValue">Implicit</s:String>
@@ -14,8 +15,10 @@
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AFTER_TYPECAST_PARENTHESES/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_WITHIN_SINGLE_LINE_ARRAY_INITIALIZER_BRACES/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CRS/@EntryIndexedValue">CRS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GIS/@EntryIndexedValue">GIS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GSS/@EntryIndexedValue">GSS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=HMAC/@EntryIndexedValue">HMAC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MD/@EntryIndexedValue">MD</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OID/@EntryIndexedValue">OID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SASL/@EntryIndexedValue">SASL</s:String>
@@ -88,6 +91,7 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=Npgsql/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Npgsql_0027s/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=PGTZ/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Postgis/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Postgre/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pregenerated/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=P_0020keepaliv/@EntryIndexedValue">True</s:Boolean>
@@ -6,6 +6,7 @@
using Npgsql.TypeMapping;
using NpgsqlTypes;

// ReSharper disable once CheckNamespace
namespace Npgsql
{
/// <summary>
@@ -20,7 +20,7 @@ public override NpgsqlTypeHandler<string> Create(PostgresType postgresType, Npgs
=> new JsonHandler(postgresType, conn, _settings);
}

class JsonHandler : Npgsql.TypeHandlers.TextHandler
class JsonHandler : TypeHandlers.TextHandler
{
readonly JsonSerializerSettings _settings;

@@ -1,6 +1,4 @@
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Npgsql.BackendMessages;
@@ -135,30 +135,30 @@ public override void Write(byte[] buffer, int offset, int count)
#region Write

public override Task Write(Geometry value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<Point>.Write(Point value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<LineString>.Write(LineString value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<Polygon>.Write(Polygon value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<MultiPoint>.Write(MultiPoint value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<MultiLineString>.Write(MultiLineString value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<MultiPolygon>.Write(MultiPolygon value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task INpgsqlTypeHandler<GeometryCollection>.Write(GeometryCollection value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
=> WriteCore(value, buf, lengthCache, parameter, async);
=> WriteCore(value, buf);

Task WriteCore(Geometry value, NpgsqlWriteBuffer buf, NpgsqlLengthCache? lengthCache, NpgsqlParameter? parameter, bool async)
Task WriteCore(Geometry value, NpgsqlWriteBuffer buf)
{
_writer.Write(value, buf.GetStream());
return Task.CompletedTask;
@@ -7,6 +7,7 @@
using Npgsql.TypeMapping;
using NpgsqlTypes;

// ReSharper disable once CheckNamespace
namespace Npgsql
{
/// <summary>
@@ -1,4 +1,4 @@
using Npgsql.LegacyPostgis;
using Npgsql.RawPostgis;
using Npgsql.TypeMapping;
using NpgsqlTypes;

@@ -4,7 +4,7 @@

#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

namespace Npgsql.LegacyPostgis
namespace Npgsql.RawPostgis
{
public class PostgisRawHandlerFactory : NpgsqlTypeHandlerFactory<byte[]>
{
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections.Generic;
using Npgsql.Logging;
using Npgsql.Util;

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using Npgsql.PostgresTypes;
using Npgsql.TypeHandlers;
@@ -1,6 +1,3 @@
using System.Diagnostics;
using System.Threading.Tasks;

namespace Npgsql
{
/// <summary>
@@ -1,8 +1,10 @@
using System;
using Npgsql.Logging;

#if NET461
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Npgsql.Logging;
#endif

namespace Npgsql
{
@@ -191,7 +193,7 @@ static string GetInstanceName()

var pid = Process.GetCurrentProcess().Id;

result = string.Format((IFormatProvider?)null, "{0}[{1}]", instanceName, pid);
result = string.Format(null, "{0}[{1}]", instanceName, pid);
result = result.Replace('(', '[').Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_');

if (result.Length > CounterInstanceNameMaxLength)
@@ -209,7 +211,7 @@ static string GetInstanceName()
result.Substring(result.Length - lastPartLength, lastPartLength));

Debug.Assert(result.Length == CounterInstanceNameMaxLength,
string.Format((IFormatProvider?)null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length));
string.Format(null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length));
}

return result;
@@ -1,5 +1,4 @@
using System;
using System.Diagnostics;

namespace Npgsql.Logging
{
@@ -16,7 +16,7 @@ namespace Npgsql
/// Provides an API for a binary COPY TO operation, a high-performance data export mechanism from
/// a PostgreSQL table. Initiated by <see cref="NpgsqlConnection.BeginBinaryExport"/>
/// </summary>
public sealed class NpgsqlBinaryExporter : ICancelable, IDisposable, IAsyncDisposable
public sealed class NpgsqlBinaryExporter : ICancelable, IAsyncDisposable
{
#region Fields and Properties

@@ -17,7 +17,7 @@ namespace Npgsql
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public sealed class NpgsqlBinaryImporter : ICancelable, IDisposable, IAsyncDisposable
public sealed class NpgsqlBinaryImporter : ICancelable, IAsyncDisposable
{
#region Fields and Properties

@@ -462,8 +462,7 @@ void DeriveParametersForFunction()
case 'v':
throw new NotImplementedException("Cannot derive function parameter of type VARIADIC");
default:
throw new ArgumentOutOfRangeException("proargmode", modes[i],
"Unknown code in proargmodes while deriving: " + modes[i]);
throw new ArgumentOutOfRangeException("Unknown code in proargmodes while deriving: " + modes[i]);
}
}

@@ -601,6 +600,7 @@ async Task PrepareLong()
// Loop over statements, skipping those that are already prepared (because they were persisted)
var isFirst = true;
foreach (var statement in _statements)
{
if (statement.PreparedStatement?.State == PreparedState.BeingPrepared)
{
var pStatement = statement.PreparedStatement;
@@ -629,17 +629,19 @@ async Task PrepareLong()
default:
throw connector.UnexpectedMessageReceived(msg.Code);
}

pStatement.CompletePrepare();
isFirst = false;
}
}

Expect<ReadyForQueryMessage>(await connector.ReadMessage(async), connector);
Expect<ReadyForQueryMessage>(await connector.ReadMessage(async), connector);

if (async)
await sendTask;
else
sendTask.GetAwaiter().GetResult();
}
if (async)
await sendTask;
else
sendTask.GetAwaiter().GetResult();
}
}
}

@@ -76,9 +76,6 @@ async Task AuthenticateSASL(List<string> mechanisms, string username, bool async
var passwd = GetPassword(username) ??
throw new NpgsqlException($"No password has been provided but the backend requires one (in SASL/{mechanism})");

const string ClientKey = "Client Key";
const string ServerKey = "Server Key";

// Assumption: the write buffer is big enough to contain all our outgoing messages
var clientNonce = GetNonce();

@@ -95,7 +92,7 @@ async Task AuthenticateSASL(List<string> mechanisms, string username, bool async
var saltBytes = Convert.FromBase64String(firstServerMsg.Salt);
var saltedPassword = Hi(passwd.Normalize(NormalizationForm.FormKC), saltBytes, firstServerMsg.Iteration);

var clientKey = HMAC(saltedPassword, ClientKey);
var clientKey = HMAC(saltedPassword, "Client Key");
byte[] storedKey;
using (var sha256 = SHA256.Create())
storedKey = sha256.ComputeHash(clientKey);
@@ -107,10 +104,10 @@ async Task AuthenticateSASL(List<string> mechanisms, string username, bool async
var authMessage = $"{clientFirstMessageBare},{serverFirstMessage},{clientFinalMessageWithoutProof}";

var clientSignature = HMAC(storedKey, authMessage);
var clientProofBytes = XOR(clientKey, clientSignature);
var clientProofBytes = Xor(clientKey, clientSignature);
var clientProof = Convert.ToBase64String(clientProofBytes);

var serverKey = HMAC(saltedPassword, ServerKey);
var serverKey = HMAC(saltedPassword, "Server Key");
var serverSignature = HMAC(serverKey, authMessage);

var messageStr = $"{clientFinalMessageWithoutProof},p={clientProof}";
@@ -148,22 +145,22 @@ static byte[] Hi(string str, byte[] salt, int count)
byte[] hi, u1;

Buffer.BlockCopy(salt, 0, salt1, 0, salt.Length);
salt1[salt1.Length - 1] = (byte)1;
salt1[salt1.Length - 1] = 1;

hi = u1 = hmac.ComputeHash(salt1);

for (var i = 1; i < count; i++)
{
var u2 = hmac.ComputeHash(u1);
XOR(hi, u2);
Xor(hi, u2);
u1 = u2;
}

return hi;
}
}

static byte[] XOR(byte[] buffer1, byte[] buffer2)
static byte[] Xor(byte[] buffer1, byte[] buffer2)
{
for (var i = 0; i < buffer1.Length; i++)
buffer1[i] ^= buffer2[i];
@@ -392,7 +389,7 @@ class AuthenticationCompleteException : Exception { }
throw new NpgsqlException($"Obtaining password using {nameof(NpgsqlConnection)}.{nameof(ProvidePasswordCallback)} delegate failed", e);
}
}

return null;
}
}
@@ -13,7 +13,6 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Npgsql.BackendMessages;
using Npgsql.Logging;
using Npgsql.TypeMapping;
@@ -179,7 +178,6 @@ int ReceiveTimeout
/// </summary>
internal object CancelLock { get; }

readonly int _keepAlive;
readonly bool _isKeepAliveEnabled;
readonly Timer? _keepAliveTimer;

@@ -276,7 +274,6 @@ internal NpgsqlConnector(NpgsqlConnection connection)
_isKeepAliveEnabled = Settings.KeepAlive > 0;
if (_isKeepAliveEnabled)
{
_keepAlive = Settings.KeepAlive * 1000;
_userLock = new SemaphoreSlim(1, 1);
_keepAliveTimer = new Timer(PerformKeepAlive, null, Timeout.Infinite, Timeout.Infinite);
}
@@ -798,8 +795,8 @@ internal void PrependInternalMessage(byte[] rawMessage, int responseMessageCount
{
_pendingPrependedResponses += responseMessageCount;

var t = WritePregenerated(rawMessage, false);
Debug.Assert(t.IsCompleted, $"Could not fully write pregenerated message into the buffer");
var t = WritePregenerated(rawMessage);
Debug.Assert(t.IsCompleted, "Could not fully write pregenerated message into the buffer");
}

#endregion
@@ -836,15 +833,15 @@ internal ValueTask<IBackendMessage> ReadMessage(bool async, DataRowLoadingMode d
case BackendMessageCode.ParameterStatus:
case BackendMessageCode.ErrorResponse:
ReadBuffer.ReadPosition--;
return ReadMessageLong(dataRowLoadingMode, readingNotifications);
return ReadMessageLong(dataRowLoadingMode, readingNotifications2: false);
}

PGUtil.ValidateBackendMessageCode(messageCode);
var len = ReadBuffer.ReadInt32() - 4; // Transmitted length includes itself
if (len > ReadBuffer.ReadBytesLeft)
{
ReadBuffer.ReadPosition -= 5;
return ReadMessageLong(dataRowLoadingMode, readingNotifications);
return ReadMessageLong(dataRowLoadingMode, readingNotifications2: false);
}

return new ValueTask<IBackendMessage?>(ParseServerMessage(ReadBuffer, messageCode, len, false));
@@ -1230,7 +1227,7 @@ internal void CloseOngoingOperations()
// therefore vulnerable to the race condition in #615.
if (currentCopyOperation is NpgsqlBinaryImporter ||
currentCopyOperation is NpgsqlCopyTextWriter ||
(currentCopyOperation is NpgsqlRawCopyStream rawCopyStream && rawCopyStream.CanWrite))
currentCopyOperation is NpgsqlRawCopyStream rawCopyStream && rawCopyStream.CanWrite)
{
try
{
@@ -1890,8 +1887,6 @@ async Task DoWaitAsync(CancellationToken cancellationToken)
/// </summary>
internal string Timezone { get; private set; } = default!;

bool IsRedshift => Settings.ServerCompatibilityMode == ServerCompatibilityMode.Redshift;

#endregion Supported features and PostgreSQL settings

#region Execute internal command

0 comments on commit e59da52

Please sign in to comment.
You can’t perform that action at this time.