Skip to content

Commit

Permalink
Syntax and resharper cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
jas88 committed Dec 21, 2023
1 parent 1570991 commit 0507307
Show file tree
Hide file tree
Showing 110 changed files with 520 additions and 591 deletions.
16 changes: 7 additions & 9 deletions FAnsiSql/Connections/ManagedConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
namespace FAnsi.Connections;

/// <inheritdoc/>
public class ManagedConnection : IManagedConnection
public sealed class ManagedConnection : IManagedConnection
{
/// <inheritdoc/>
public DbConnection Connection { get; private set; }
Expand All @@ -29,13 +29,12 @@ internal ManagedConnection(DiscoveredServer discoveredServer, IManagedTransactio
ManagedTransaction = managedTransaction;
Transaction = managedTransaction?.Transaction;

//if there isn't a transaction then we opened a new connection so we had better remember to close it again
if(managedTransaction == null)
{
CloseOnDispose = true;
Debug.Assert(Connection.State == ConnectionState.Closed);
Connection.Open();
}
//if there isn't a transaction then we opened a new connection, so we had better remember to close it again
if (managedTransaction != null) return;

CloseOnDispose = true;
Debug.Assert(Connection.State == ConnectionState.Closed);
Connection.Open();
}

public ManagedConnection Clone()
Expand All @@ -48,7 +47,6 @@ public ManagedConnection Clone()
/// </summary>
public void Dispose()
{
System.GC.SuppressFinalize(this);
if (CloseOnDispose)
Connection.Dispose();
}
Expand Down
4 changes: 3 additions & 1 deletion FAnsiSql/Connections/ManagedTransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace FAnsi.Connections;

/// <inheritdoc/>
public class ManagedTransaction : IManagedTransaction
public sealed class ManagedTransaction : IManagedTransaction
{
/// <inheritdoc/>
public DbConnection Connection { get; private set; }
Expand All @@ -28,6 +28,7 @@ public void AbandonAndCloseConnection()
{
if(closed)
return;

closed = true;

try
Expand All @@ -52,6 +53,7 @@ public void CommitAndCloseConnection()
{
if(closed)
return;

closed = true;

try
Expand Down
5 changes: 4 additions & 1 deletion FAnsiSql/DatabaseOperationArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace FAnsi;
/// <summary>
/// Arguments for facilitating long running sql operations which the user/system might want to cancel mid way through.
/// </summary>
public class DatabaseOperationArgs
public sealed class DatabaseOperationArgs
{
/// <summary>
/// If using an ongoing connection/transaction. Otherwise null.
Expand Down Expand Up @@ -85,15 +85,18 @@ private T Execute<T>(DbCommand cmd, Func<Task<T>> method)
{
if (e.InnerExceptions.Count == 1)
throw e.InnerExceptions[0];

throw;
}

if (!t.IsCompleted)
cmd.Cancel();

if (t.Exception == null) return t.Result;

if (t.Exception.InnerExceptions.Count == 1)
throw t.Exception.InnerExceptions[0];

throw t.Exception;
}

Expand Down
2 changes: 1 addition & 1 deletion FAnsiSql/Discovery/ColumnMappingException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace FAnsi.Discovery;
/// Thrown when a given column requested could not be matched in the destination table e.g. when inserting data in a <see cref="DataTable"/>
/// into a <see cref="DiscoveredTable"/> during a <see cref="BulkCopy"/> operation
/// </summary>
public class ColumnMappingException : Exception
public sealed class ColumnMappingException : Exception
{
public ColumnMappingException(string msg):base(msg)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ private string GetCollisionWithKeyword(string keyword, string value)

//now iterate all the keys we had before and add those too, if the key count doesn't change for any of them we know it's a duplicate semantically
if (_builder.Keys == null) return null;

foreach (var current in _keywords)
{
var keysBefore = _builder.Keys.Count;
Expand Down
2 changes: 1 addition & 1 deletion FAnsiSql/Discovery/Constraints/DiscoveredRelationship.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace FAnsi.Discovery.Constraints;
/// <param name="pkTable"></param>
/// <param name="fkTable"></param>
/// <param name="deleteRule"></param>
public class DiscoveredRelationship(string fkName, DiscoveredTable pkTable, DiscoveredTable fkTable, CascadeRule deleteRule)
public sealed class DiscoveredRelationship(string fkName, DiscoveredTable pkTable, DiscoveredTable fkTable, CascadeRule deleteRule)
{
/// <summary>
/// The name of the foreign key constraint in the database e.g. FK_Table1_Table2
Expand Down
6 changes: 3 additions & 3 deletions FAnsiSql/Discovery/Constraints/RelationshipTopologicalSort.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace FAnsi.Discovery.Constraints;
/// <summary>
/// Helps resolve a dependency order between a collection of tables with interlinking foreign key constraints. Implements Khan's algorithm.
/// </summary>
public class RelationshipTopologicalSort
public sealed class RelationshipTopologicalSort
{
/// <summary>
/// The dependency order from least dependent (isolated tables and parent tables) to most (child tables then grandchild tables).
Expand All @@ -35,7 +35,7 @@ public RelationshipTopologicalSort(IEnumerable<DiscoveredTable> tables)

foreach (var relationship in nodes
.Select(table => table.DiscoverRelationships().Where(r => nodes.Contains(r.ForeignKeyTable)))
.SelectMany(relevantRelationships => relevantRelationships))
.SelectMany(static relevantRelationships => relevantRelationships))
edges.Add(Tuple.Create(relationship.PrimaryKeyTable, relationship.ForeignKeyTable));

_sortedList = TopologicalSort(nodes, edges);
Expand All @@ -49,7 +49,7 @@ public RelationshipTopologicalSort(IEnumerable<DiscoveredTable> tables)
/// <param name="nodes">All nodes of directed acyclic graph.</param>
/// <param name="edges">All edges of directed acyclic graph.</param>
/// <returns>Sorted node in topological order.</returns>
private List<T> TopologicalSort<T>(IEnumerable<T> nodes, HashSet<Tuple<T, T>> edges) where T : IEquatable<T>
private static List<T> TopologicalSort<T>(IEnumerable<T> nodes, HashSet<Tuple<T, T>> edges) where T : IEquatable<T>
{
// Empty list that will contain the sorted elements
var l = new List<T>();
Expand Down
22 changes: 7 additions & 15 deletions FAnsiSql/Discovery/DatabaseColumnRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ namespace FAnsi.Discovery;
///
/// <para>Type specification is defined in the DatabaseTypeRequest but can also be specified explicitly (e.g. 'varchar(10)').</para>
/// </summary>
public class DatabaseColumnRequest:ISupplementalColumnInformation,IHasRuntimeName
public sealed class DatabaseColumnRequest(string columnName, DatabaseTypeRequest typeRequested, bool allowNulls = true)
: ISupplementalColumnInformation, IHasRuntimeName
{
/// <summary>
/// The fixed string proprietary data type to use. This overrides <see cref="TypeRequested"/> if specified.
Expand All @@ -21,21 +22,21 @@ public class DatabaseColumnRequest:ISupplementalColumnInformation,IHasRuntimeNam
public string ExplicitDbType { get; set; }


public string ColumnName { get; set; }
public string ColumnName { get; set; } = columnName;

/// <summary>
/// The cross database platform type descriptior for the column e.g. 'able to store strings up to 18 in length'.
/// The cross database platform type descriptor for the column e.g. 'able to store strings up to 18 in length'.
///
/// <para>This is ignored if you have specified an <see cref="ExplicitDbType"/></para>
///
/// <para>See also <see cref="GetSQLDbType"/></para>
/// </summary>
public DatabaseTypeRequest TypeRequested { get; set; }
public DatabaseTypeRequest TypeRequested { get; set; } = typeRequested;

/// <summary>
/// True to create a column which is nullable
/// </summary>
public bool AllowNulls { get; set; }
public bool AllowNulls { get; set; } = allowNulls;

/// <summary>
/// True to include the column as part of the tables primary key
Expand All @@ -58,18 +59,9 @@ public class DatabaseColumnRequest:ISupplementalColumnInformation,IHasRuntimeNam
/// </summary>
public string Collation { get; set; }

public DatabaseColumnRequest(string columnName, DatabaseTypeRequest typeRequested, bool allowNulls = true)
{
ColumnName = columnName;
TypeRequested = typeRequested;
AllowNulls = allowNulls;
}

public DatabaseColumnRequest(string columnName, string explicitDbType, bool allowNulls = true)
public DatabaseColumnRequest(string columnName, string explicitDbType, bool allowNulls = true) : this(columnName, (DatabaseTypeRequest)null, allowNulls)
{
ExplicitDbType = explicitDbType;
ColumnName = columnName;
AllowNulls = allowNulls;
}

/// <summary>
Expand Down
5 changes: 3 additions & 2 deletions FAnsiSql/Discovery/DiscoveredColumn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace FAnsi.Discovery;
/// <param name="table"></param>
/// <param name="name"></param>
/// <param name="allowsNulls"></param>
public class DiscoveredColumn(DiscoveredTable table, string name, bool allowsNulls) : IHasFullyQualifiedNameToo,ISupplementalColumnInformation
public sealed class DiscoveredColumn(DiscoveredTable table, string name, bool allowsNulls) : IHasFullyQualifiedNameToo,ISupplementalColumnInformation
{
/// <summary>
/// The <see cref="DiscoveredTable"/> on which the <see cref="DiscoveredColumn"/> was found
Expand Down Expand Up @@ -113,7 +113,7 @@ public Guesser GetGuesser()
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected bool Equals(DiscoveredColumn other)
private bool Equals(DiscoveredColumn other)
{
return string.Equals(_name, other._name) && Equals(Table, other.Table);
}
Expand All @@ -127,6 +127,7 @@ public override bool Equals(object obj)
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;

return Equals((DiscoveredColumn)obj);
}

Expand Down
5 changes: 3 additions & 2 deletions FAnsiSql/Discovery/DiscoveredDataType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace FAnsi.Discovery;
/// <summary>
/// Cross database type reference to a Data Type string (e.g. varchar(30), varbinary(100) etc) of a Column in a Table
/// </summary>
public class DiscoveredDataType
public sealed class DiscoveredDataType
{
private readonly DiscoveredColumn Column;

Expand Down Expand Up @@ -174,7 +174,7 @@ public void AlterTypeTo(string newType, IManagedTransaction managedTransaction =
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected bool Equals(DiscoveredDataType other)
private bool Equals(DiscoveredDataType other)
{
return string.Equals(SQLType, other.SQLType);
}
Expand All @@ -197,6 +197,7 @@ public override bool Equals(object obj)
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;

return Equals((DiscoveredDataType)obj);
}

Expand Down
5 changes: 3 additions & 2 deletions FAnsiSql/Discovery/DiscoveredDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace FAnsi.Discovery;
/// <summary>
/// Cross database type reference to a specific database on a database server. Allows you to create tables, drop check existance etc.
/// </summary>
public class DiscoveredDatabase :IHasRuntimeName,IMightNotExist
public sealed class DiscoveredDatabase :IHasRuntimeName,IMightNotExist
{
private readonly string _database;
private readonly IQuerySyntaxHelper _querySyntaxHelper;
Expand Down Expand Up @@ -314,7 +314,7 @@ public void CreateBackup(string backupName)
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected bool Equals(DiscoveredDatabase other)
private bool Equals(DiscoveredDatabase other)
{
return Equals(Server, other.Server) && string.Equals(_database, other._database,StringComparison.OrdinalIgnoreCase);
}
Expand All @@ -329,6 +329,7 @@ public override bool Equals(object obj)
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;

return Equals((DiscoveredDatabase)obj);
}

Expand Down
24 changes: 11 additions & 13 deletions FAnsiSql/Discovery/DiscoveredDatabaseHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public DiscoveredTable CreateTable(CreateTableArgs args)
return tbl;
}

private void CopySettings(Guesser guesser, CreateTableArgs args)
private static void CopySettings(Guesser guesser, CreateTableArgs args)
{
//cannot change the instance so have to copy across the values. If this gets new properties that's a problem
//See tests GuessSettings_CopyProperties
Expand All @@ -152,7 +152,7 @@ private void CopySettings(Guesser guesser, CreateTableArgs args)
/// <param name="dt"></param>
public void ThrowIfObjectColumns(DataTable dt)
{
var objCol = dt.Columns.Cast<DataColumn>().FirstOrDefault(c => c.DataType == typeof(object));
var objCol = dt.Columns.Cast<DataColumn>().FirstOrDefault(static c => c.DataType == typeof(object));

if(objCol != null)
throw new NotSupportedException(
Expand Down Expand Up @@ -207,15 +207,15 @@ public virtual string GetCreateTableSql(DiscoveredDatabase database, string tabl
bodySql.AppendLine($"{GetCreateTableSqlLineForColumn(col, datatype, syntaxHelper)},");
}

var pks = columns.Where(c => c.IsPrimaryKey).ToArray();
var pks = columns.Where(static c => c.IsPrimaryKey).ToArray();
if (pks.Length != 0)
bodySql.Append(GetPrimaryKeyDeclarationSql(tableName, pks,syntaxHelper));

if (foreignKeyPairs != null)
{
bodySql.AppendLine();
bodySql.AppendLine(GetForeignKeyConstraintSql(tableName, syntaxHelper,
foreignKeyPairs.ToDictionary(static k => (IHasRuntimeName) k.Key, v => v.Value), cascadeDelete, null));
foreignKeyPairs.ToDictionary(static k => (IHasRuntimeName) k.Key, static v => v.Value), cascadeDelete, null));
}

var toReturn = bodySql.ToString().TrimEnd('\r', '\n', ',');
Expand All @@ -241,7 +241,7 @@ protected virtual string GetCreateTableSqlLineForColumn(DatabaseColumnRequest co
public virtual string GetForeignKeyConstraintSql(string foreignTable, IQuerySyntaxHelper syntaxHelper,
Dictionary<IHasRuntimeName, DiscoveredColumn> foreignKeyPairs, bool cascadeDelete, string constraintName)
{
var primaryKeyTable = foreignKeyPairs.Values.Select(v => v.Table).Distinct().Single();
var primaryKeyTable = foreignKeyPairs.Values.Select(static v => v.Table).Distinct().Single();

constraintName ??= GetForeignKeyConstraintNameFor(foreignTable, primaryKeyTable.GetRuntimeName());

Expand All @@ -257,27 +257,25 @@ public string GetForeignKeyConstraintNameFor(DiscoveredTable foreignTable, Disco
return GetForeignKeyConstraintNameFor(foreignTable.GetRuntimeName(), primaryTable.GetRuntimeName());
}

private string GetForeignKeyConstraintNameFor(string foreignTable, string primaryTable) =>
private static string GetForeignKeyConstraintNameFor(string foreignTable, string primaryTable) =>
MakeSensibleConstraintName("FK_", $"{foreignTable}_{primaryTable}");

public abstract DirectoryInfo Detach(DiscoveredDatabase database);

public abstract void CreateBackup(DiscoveredDatabase discoveredDatabase, string backupName);

private string GetPrimaryKeyDeclarationSql(string tableName, IEnumerable<DatabaseColumnRequest> pks,
private static string GetPrimaryKeyDeclarationSql(string tableName, IEnumerable<DatabaseColumnRequest> pks,
IQuerySyntaxHelper syntaxHelper) =>
$" CONSTRAINT {MakeSensibleConstraintName("PK_", tableName)} PRIMARY KEY ({string.Join(",", pks.Select(c => syntaxHelper.EnsureWrapped(c.ColumnName)))}),{Environment.NewLine}";

private string MakeSensibleConstraintName(string prefix, string tableName)
private static string MakeSensibleConstraintName(string prefix, string tableName)
{
var constraintName = QuerySyntaxHelper.MakeHeaderNameSensible(tableName);

if (string.IsNullOrWhiteSpace(constraintName))
{
var r = new Random();
constraintName = $"Constraint{r.Next(10000)}";
}
if (!string.IsNullOrWhiteSpace(constraintName)) return $"{prefix}{constraintName}";

var r = new Random();

Check warning

Code scanning / CodeQL

Useless assignment to local variable Warning

This assignment to
r
is useless, since its value is never read.
constraintName = $"Constraint{r.Next(10000)}";
return $"{prefix}{constraintName}";
}

Expand Down
2 changes: 1 addition & 1 deletion FAnsiSql/Discovery/DiscoveredParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/// <summary>
/// Cross database type reference to a Parameter (e.g. of a Table valued function / stored procedure).
/// </summary>
public class DiscoveredParameter(string parameterName)
public sealed class DiscoveredParameter(string parameterName)
{
/// <summary>
/// SQL name of parameter e.g. @bob for Sql Server
Expand Down
6 changes: 4 additions & 2 deletions FAnsiSql/Discovery/DiscoveredServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace FAnsi.Discovery;
/// <summary>
/// Cross database type reference to a database server. Allows you to get connections, create commands, list databases etc.
/// </summary>
public class DiscoveredServer : IMightNotExist
public sealed class DiscoveredServer : IMightNotExist
{
/// <summary>
/// Stores connection string State (which server the <see cref="DiscoveredServer"/> refers to.
Expand Down Expand Up @@ -214,6 +214,7 @@ public void TestConnection(int timeoutInMillis = 10000)
FAnsiStrings
.DiscoveredServer_TestConnection_Could_not_connect_to_server___0___after_timeout_of__1__milliseconds_,
Name, timeoutInMillis), e);

throw;
}
}
Expand Down Expand Up @@ -406,7 +407,7 @@ public Dictionary<string, string> DescribeServer()
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected bool Equals(DiscoveredServer other)
private bool Equals(DiscoveredServer other)
{
if (Builder == null || other.Builder == null)
return Equals(Builder, other.Builder) && DatabaseType == other.DatabaseType;
Expand All @@ -425,6 +426,7 @@ public override bool Equals(object obj)
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;

return Equals((DiscoveredServer)obj);
}

Expand Down
Loading

0 comments on commit 0507307

Please sign in to comment.