Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/fixwarnings #306

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions FAnsi.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=DB/@EntryIndexedValue">DB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=FROM/@EntryIndexedValue">FROM</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SELECT/@EntryIndexedValue">SELECT</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SQL/@EntryIndexedValue">SQL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=WHERE/@EntryIndexedValue">WHERE</s:String></wpf:ResourceDictionary>
3 changes: 2 additions & 1 deletion FAnsiSql/DatabaseOperationArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ public DatabaseOperationArgs(IManagedTransaction transactionIfAny, int timeoutIn
/// <exception cref="OperationCanceledException"></exception>
public int ExecuteNonQuery(DbCommand cmd)
{
return Execute(cmd, ()=>cmd.ExecuteNonQueryAsync(CancellationToken));
return Execute(cmd, () => cmd.ExecuteNonQueryAsync(CancellationToken));
}

/// <summary>
/// Sets the timeout and cancellation on <paramref name="cmd"/> then runs <see cref="DbCommand.ExecuteScalar()"/> with the
/// <see cref="CancellationToken"/> (if any) and blocks till the call completes.
Expand Down
16 changes: 14 additions & 2 deletions FAnsiSql/Discovery/BulkCopy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,20 @@ protected void ConvertStringTypesToHardTypes(DataTable dt)

//if the DataColumn is part of the Primary Key of the DataTable (in memory)
//then we need to update the primary key to include the new column not the old one
if (dt.PrimaryKey != null && dt.PrimaryKey.Contains(dataColumn))
dt.PrimaryKey = dt.PrimaryKey.Except(new[] { dataColumn }).Union(new[] { newColumn }).ToArray();
if (dt.PrimaryKey != null)
{
var modified = false;
// Need to invoke the PrimaryKey setter to update the internal state of the DataTable, can't just modify existing array!
var newKey = Array.ConvertAll(dt.PrimaryKey, c =>
{
if (c != dataColumn) return c;

modified = true;
return newColumn;
});
if (modified)
dt.PrimaryKey = newKey;
}

var oldOrdinal = dataColumn.Ordinal;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,6 @@ public void AddOrUpdateKeyword(string keyword, string value, ConnectionStringKey
}

//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
5 changes: 3 additions & 2 deletions FAnsiSql/Discovery/DatabaseColumnRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public sealed class DatabaseColumnRequest(string columnName, DatabaseTypeRequest
/// </summary>
public string? Collation { get; set; }

public DatabaseColumnRequest(string columnName, string explicitDbType, bool allowNulls = true) : this(columnName, (DatabaseTypeRequest?)null, allowNulls)
public DatabaseColumnRequest(string columnName, string? explicitDbType, bool allowNulls = true) : this(columnName, (DatabaseTypeRequest?)null, allowNulls)
{
ExplicitDbType = explicitDbType;
}
Expand All @@ -69,7 +69,8 @@ public DatabaseColumnRequest(string columnName, string explicitDbType, bool allo
/// </summary>
/// <param name="typeTranslater"></param>
/// <returns></returns>
public string GetSQLDbType(ITypeTranslater typeTranslater) => ExplicitDbType??typeTranslater.GetSQLDBTypeForCSharpType(TypeRequested);
public string GetSQLDbType(ITypeTranslater typeTranslater) =>
ExplicitDbType ?? typeTranslater.GetSQLDBTypeForCSharpType(TypeRequested);

public string GetRuntimeName() => ColumnName;
}
20 changes: 7 additions & 13 deletions FAnsiSql/Discovery/DiscoveredColumn.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using FAnsi.Discovery.QuerySyntax;
using System;
using FAnsi.Discovery.QuerySyntax;
using FAnsi.Naming;
using TypeGuesser;

Expand Down Expand Up @@ -57,14 +58,13 @@ public sealed class DiscoveredColumn(DiscoveredTable table, string name, bool al
/// </summary>
public string? Format { get; set; }

private readonly string _name = name;
private readonly IQuerySyntaxHelper _querySyntaxHelper = table.Database.Server.GetQuerySyntaxHelper();

/// <summary>
/// The unqualified name of the column e.g. "MyCol"
/// </summary>
/// <returns></returns>
public string GetRuntimeName() => _querySyntaxHelper.GetRuntimeName(_name);
public string GetRuntimeName() => _querySyntaxHelper.GetRuntimeName(name);

/// <summary>
/// The fully qualified name of the column e.g. [MyDb].dbo.[MyTable].[MyCol] or `MyDb`.`MyCol`
Expand All @@ -86,7 +86,7 @@ public string GetFullyQualifiedName() => _querySyntaxHelper.EnsureFullyQualified
/// Returns the name of the column
/// </summary>
/// <returns></returns>
public override string ToString() => _name;
public override string ToString() => name;

/// <summary>
/// Generates a <see cref="Guesser"/> primed with the <see cref="DataType"/> of this column. This can be used to inspect new
Expand All @@ -100,7 +100,7 @@ public string GetFullyQualifiedName() => _querySyntaxHelper.EnsureFullyQualified
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
private bool Equals(DiscoveredColumn other) => string.Equals(_name, other._name) && Equals(Table, other.Table);
private bool Equals(DiscoveredColumn other) => string.Equals(name, other.ToString()) && Equals(Table, other.Table);

/// <summary>
/// Based on column name and Table
Expand All @@ -120,17 +120,11 @@ public override bool Equals(object? obj)
/// Based on column name and Table
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
return ((_name?.GetHashCode() ?? 0) * 397) ^ (Table?.GetHashCode() ?? 0);
}
}
public override int GetHashCode() => HashCode.Combine(name, Table);

/// <summary>
/// Returns the wrapped e.g. "[MyCol]" name of the column including escaping e.g. if you wanted to name a column "][nquisitor" (which would return "[]][nquisitor]"). Use <see cref="GetFullyQualifiedName()"/> to return the full name including table/database/schema.
/// </summary>
/// <returns></returns>
public string? GetWrappedName() => Table.GetQuerySyntaxHelper().EnsureWrapped(GetRuntimeName());
public string GetWrappedName() => Table.GetQuerySyntaxHelper().EnsureWrapped(GetRuntimeName());
}
6 changes: 3 additions & 3 deletions FAnsiSql/Discovery/DiscoveredDataType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public DiscoveredDataType(DbDataReader r, string sqlType, DiscoveredColumn? colu
public void Resize(int newSize, IManagedTransaction? managedTransaction = null)
{
var toReplace = GetLengthIfString();

if(newSize == toReplace)
return;

Expand Down Expand Up @@ -120,7 +120,7 @@ public void Resize(int numberOfDigitsBeforeDecimalPoint, int numberOfDigitsAfter
var newDataType = _column?.Table.GetQuerySyntaxHelper()
.TypeTranslater.GetSQLDBTypeForCSharpType(new DatabaseTypeRequest(typeof(decimal), null,
new DecimalSize(numberOfDigitsBeforeDecimalPoint, numberOfDigitsAfterDecimalPoint))) ??
throw new InvalidOperationException($"Failed to calculate new DB type");
throw new InvalidOperationException("Failed to calculate new DB type");

AlterTypeTo(newDataType, managedTransaction);
}
Expand Down Expand Up @@ -155,7 +155,7 @@ public void AlterTypeTo(string newType, IManagedTransaction? managedTransaction
}
}

SQLType = newType;
SQLType = newType;
}

/// <summary>
Expand Down
12 changes: 3 additions & 9 deletions FAnsiSql/Discovery/DiscoveredDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public IEnumerable<DiscoveredTableValuedFunction> DiscoverTableValuedFunctions(I
/// Returns the wrapped e.g. "[MyDatabase]" name of the database including escaping e.g. if you wanted to name a database "][nquisitor" (which would return "[]][nquisitor]").
/// </summary>
/// <returns></returns>
public string? GetWrappedName() => _querySyntaxHelper.EnsureWrapped(GetRuntimeName());
public string GetWrappedName() => _querySyntaxHelper.EnsureWrapped(GetRuntimeName());

/// <summary>
/// <para>Creates an expectation (See <see cref="IMightNotExist"/>) that there is a table with the given name in the database.
Expand Down Expand Up @@ -127,7 +127,7 @@ public DiscoveredTable ExpectTable(string tableName, string? schema = null, Tabl
/// <returns></returns>
public bool Exists(IManagedTransaction? transaction = null)
{
return Server.DiscoverDatabases().Any(db => db.GetRuntimeName()?.Equals(GetRuntimeName(), StringComparison.InvariantCultureIgnoreCase) == true);
return Server.DiscoverDatabases().Any(db => db.GetRuntimeName().Equals(GetRuntimeName(), StringComparison.InvariantCultureIgnoreCase));
}

/// <summary>
Expand Down Expand Up @@ -303,11 +303,5 @@ public override bool Equals(object? obj)
/// Based on Server and database name
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
return ((Server != null ? Server.GetHashCode() : 0) * 397) ^ (_database != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(_database) : 0);
}
}
public override int GetHashCode() => HashCode.Combine(Server, _database);
}
28 changes: 14 additions & 14 deletions FAnsiSql/Discovery/DiscoveredDatabaseHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ namespace FAnsi.Discovery;
/// DBMS specific implementation of all functionality that relates to interacting with existing databases (dropping databases, creating tables, finding stored procedures etc). For
/// database creation see <see cref="DiscoveredServerHelper"/>
/// </summary>
public abstract class DiscoveredDatabaseHelper:IDiscoveredDatabaseHelper
public abstract class DiscoveredDatabaseHelper : IDiscoveredDatabaseHelper
{
public abstract IEnumerable<DiscoveredTable> ListTables(DiscoveredDatabase parent, IQuerySyntaxHelper querySyntaxHelper, DbConnection connection,
string database, bool includeViews, DbTransaction? transaction = null);
Expand All @@ -41,7 +41,7 @@ public DiscoveredTable CreateTable(CreateTableArgs args)
? args.ExplicitColumnDefinitions.ToList()
: [];

if(args.DataTable != null)
if (args.DataTable != null)
{

ThrowIfObjectColumns(args.DataTable);
Expand All @@ -50,7 +50,7 @@ public DiscoveredTable CreateTable(CreateTableArgs args)
foreach (DataColumn column in args.DataTable.Columns)
{
//do we have an explicit overriding column definition?
var overriding = customRequests.SingleOrDefault(c => c.ColumnName.Equals(column.ColumnName,StringComparison.CurrentCultureIgnoreCase));
var overriding = customRequests.SingleOrDefault(c => c.ColumnName.Equals(column.ColumnName, StringComparison.CurrentCultureIgnoreCase));

//yes
if (overriding != null)
Expand Down Expand Up @@ -84,17 +84,17 @@ public DiscoveredTable CreateTable(CreateTableArgs args)
var guesser = GetGuesser(column);
guesser.Culture = args.Culture;

CopySettings(guesser,args);
CopySettings(guesser, args);

guesser.AdjustToCompensateForValues(column);

//if DoNotRetype is set on the column adjust the requested CSharpType to be the original type
if (column.GetDoNotReType())
guesser.Guess.CSharpType = column.DataType;

typeDictionary.Add(column.ColumnName,guesser);
typeDictionary.Add(column.ColumnName, guesser);

columns.Add(new DatabaseColumnRequest(column.ColumnName, guesser.Guess, column.AllowDBNull) { IsPrimaryKey = args.DataTable.PrimaryKey.Contains(column)});
columns.Add(new DatabaseColumnRequest(column.ColumnName, guesser.Guess, column.AllowDBNull) { IsPrimaryKey = args.DataTable.PrimaryKey.Contains(column) });
}
}
}
Expand Down Expand Up @@ -123,7 +123,7 @@ public DiscoveredTable CreateTable(CreateTableArgs args)
var tbl = args.Database.ExpectTable(args.TableName, args.Schema);

//unless we are being asked to create it empty then upload the DataTable to it
if(args.DataTable != null && !args.CreateEmpty)
if (args is { DataTable: not null, CreateEmpty: false })
{
using var bulk = tbl.BeginBulkInsert(args.Culture);
bulk.DateTimeDecider.Settings.ExplicitDateFormats = args.GuessSettings.ExplicitDateFormats;
Expand Down Expand Up @@ -153,7 +153,7 @@ public void ThrowIfObjectColumns(DataTable dt)
{
var objCol = dt.Columns.Cast<DataColumn>().FirstOrDefault(static c => c.DataType == typeof(object));

if(objCol != null)
if (objCol != null)
throw new NotSupportedException(
string.Format(
FAnsiStrings.DataTable_Column__0__was_of_DataType__1___this_is_not_allowed___Use_String_for_untyped_data,
Expand All @@ -174,7 +174,7 @@ public virtual string GetCreateTableSql(DiscoveredDatabase database, string tabl
bool cascadeDelete, string? schema)
{
if (string.IsNullOrWhiteSpace(tableName))
throw new ArgumentNullException(nameof(tableName),FAnsiStrings.DiscoveredDatabaseHelper_GetCreateTableSql_Table_name_cannot_be_null);
throw new ArgumentNullException(nameof(tableName), FAnsiStrings.DiscoveredDatabaseHelper_GetCreateTableSql_Table_name_cannot_be_null);

var bodySql = new StringBuilder();

Expand Down Expand Up @@ -204,7 +204,7 @@ public virtual string GetCreateTableSql(DiscoveredDatabase database, string tabl

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

if (foreignKeyPairs != null)
{
Expand All @@ -227,7 +227,7 @@ public virtual string GetCreateTableSql(DiscoveredDatabase database, string tabl
/// <param name="datatype"></param>
/// <param name="syntaxHelper"></param>
/// <returns></returns>
protected virtual string GetCreateTableSqlLineForColumn(DatabaseColumnRequest col, string datatype, IQuerySyntaxHelper syntaxHelper) => $"{syntaxHelper.EnsureWrapped(col.ColumnName)} {datatype} {(col.Default != MandatoryScalarFunctions.None ? $"default {syntaxHelper.GetScalarFunctionSql(col.Default)}" : "")} {(string.IsNullOrWhiteSpace(col.Collation) ? "" : $"COLLATE {col.Collation}")} {(col.AllowNulls && !col.IsPrimaryKey ? " NULL" : " NOT NULL")} {(col.IsAutoIncrement ? syntaxHelper.GetAutoIncrementKeywordIfAny() : "")}";
protected virtual string GetCreateTableSqlLineForColumn(DatabaseColumnRequest col, string datatype, IQuerySyntaxHelper syntaxHelper) => $"{syntaxHelper.EnsureWrapped(col.ColumnName)} {datatype} {(col.Default != MandatoryScalarFunctions.None ? $"default {syntaxHelper.GetScalarFunctionSql(col.Default)}" : "")} {(string.IsNullOrWhiteSpace(col.Collation) ? "" : $"COLLATE {col.Collation}")} {(col is { AllowNulls: true, IsPrimaryKey: false } ? " NULL" : " NOT NULL")} {(col.IsAutoIncrement ? syntaxHelper.GetAutoIncrementKeywordIfAny() : "")}";

public virtual string GetForeignKeyConstraintSql(string foreignTable, IQuerySyntaxHelper syntaxHelper,
Dictionary<IHasRuntimeName, DiscoveredColumn> foreignKeyPairs, bool cascadeDelete, string? constraintName)
Expand Down Expand Up @@ -273,7 +273,7 @@ public void ExecuteBatchNonQuery(string sql, DbConnection conn, DbTransaction? t
ExecuteBatchNonQuery(sql, conn, transaction, out _, timeout);
}

private static readonly string[] separator = ["\n", "\r"];
private static readonly string[] Separator = ["\n", "\r"];

/// <summary>
/// Executes the given SQL against the database + sends GO delimited statements as separate batches
Expand Down Expand Up @@ -306,11 +306,11 @@ public void ExecuteBatchNonQuery(string sql, DbConnection conn, DbTransaction? t
sql += "\nGO"; // make sure last batch is executed.
try
{
foreach (var line in sql.Split(separator, StringSplitOptions.RemoveEmptyEntries))
foreach (var line in sql.Split(Separator, StringSplitOptions.RemoveEmptyEntries))
{
lineNumber++;

if (line.Trim().Equals("GO",StringComparison.CurrentCultureIgnoreCase))
if (line.Trim().Equals("GO", StringComparison.CurrentCultureIgnoreCase))
{
var executeSql = sqlBatch.ToString();
if (string.IsNullOrWhiteSpace(executeSql))
Expand Down
10 changes: 3 additions & 7 deletions FAnsiSql/Discovery/DiscoveredServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -377,14 +377,10 @@ public DiscoveredDatabase CreateDatabase(string newDatabaseName)
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
private bool Equals(DiscoveredServer other)
{
if (Builder == null || other.Builder == null)
return Equals(Builder, other.Builder) && DatabaseType == other.DatabaseType;

private bool Equals(DiscoveredServer other) =>
//server is the same if they are pointed at the same server
return string.Equals(Builder.ConnectionString, other.Builder.ConnectionString, StringComparison.OrdinalIgnoreCase) && DatabaseType == other.DatabaseType;
}
DatabaseType == other.DatabaseType &&
string.Equals(Builder.ConnectionString, other.Builder.ConnectionString, StringComparison.OrdinalIgnoreCase);

/// <summary>
/// Equality based on Builder.ConnectionString and DatabaseType
Expand Down
Loading
Loading