Skip to content

Commit

Permalink
Nullable fixups
Browse files Browse the repository at this point in the history
  • Loading branch information
jas88 committed Feb 1, 2024
1 parent 503677c commit 87c725a
Show file tree
Hide file tree
Showing 54 changed files with 252 additions and 255 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/dotnet-core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
- name: Setup .NET Core
uses: actions/setup-dotnet@v4
with:
dotnet-version: 7.0.x
dotnet-version: 8.0.x
- name: Install Sql Server
run: |
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
Expand Down
2 changes: 1 addition & 1 deletion FAnsiSql/Connections/IManagedConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public interface IManagedConnection : IDisposable
/// <summary>
/// Optional - DbTransaction being wrapped if one has been started or null
/// </summary>
DbTransaction Transaction { get; }
DbTransaction? Transaction { get; }

/// <summary>
/// Optional - transaction being run (See <see cref="DiscoveredServer.BeginNewTransactedConnection"/>. If this is not null then <see cref="Transaction"/> should also be not null.
Expand Down
2 changes: 1 addition & 1 deletion FAnsiSql/Connections/ManagedConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public sealed class ManagedConnection : IManagedConnection
public DbConnection Connection { get; }

/// <inheritdoc/>
public DbTransaction Transaction { get; }
public DbTransaction? Transaction { get; }

/// <inheritdoc/>
public IManagedTransaction ManagedTransaction { get; }
Expand Down
2 changes: 1 addition & 1 deletion FAnsiSql/DatabaseOperationArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public sealed class DatabaseOperationArgs
/// <summary>
/// If using an ongoing connection/transaction. Otherwise null.
/// </summary>
public IManagedTransaction TransactionIfAny{ get; set; }
public IManagedTransaction? TransactionIfAny { get; set; }

/// <summary>
/// Time to allow <see cref="DbCommand"/> to run before cancelling (this is db timeout and doesn't affect <see cref="CancellationToken"/>)
Expand Down
11 changes: 5 additions & 6 deletions FAnsiSql/Discovery/BulkCopy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public abstract class BulkCopy:IBulkCopy
public bool AllowUnmatchedInputColumns { get; private set; }

/// <inheritdoc/>
public DateTimeTypeDecider DateTimeDecider {get; protected set; }
public DateTimeTypeDecider DateTimeDecider { get; protected set; }

/// <summary>
/// Begins a new bulk copy operation in which one or more data tables are uploaded to the <paramref name="targetTable"/>. The API entrypoint for this is
Expand All @@ -50,7 +50,7 @@ public abstract class BulkCopy:IBulkCopy
/// <param name="targetTable"></param>
/// <param name="connection"></param>
/// <param name="culture">For parsing string date expressions etc</param>
protected BulkCopy(DiscoveredTable targetTable, IManagedConnection connection,CultureInfo culture)
protected BulkCopy(DiscoveredTable targetTable, IManagedConnection connection, CultureInfo culture)
{
Culture = culture;
TargetTable = targetTable;
Expand Down Expand Up @@ -121,11 +121,11 @@ protected void ConvertStringTypesToHardTypes(DataTable dt)
var newColumn = dt.Columns.Add($"{dataColumn.ColumnName}_{Guid.NewGuid()}",dataType);

//if it's a DateTime decider then guess DateTime culture based on values in the table
if(decider is DateTimeTypeDecider)
if (decider is DateTimeTypeDecider)
{
//also use this one in case the user has set up explicit stuff on it e.g. Culture/Settings
decider = DateTimeDecider;
DateTimeDecider.GuessDateFormat(dt.Rows.Cast<DataRow>().Take(500).Select(r=>r[dataColumn] as string));
DateTimeDecider.GuessDateFormat(dt.Rows.Cast<DataRow>().Take(500).Select(r => r[dataColumn] as string).OfType<string>());
}


Expand All @@ -134,9 +134,8 @@ protected void ConvertStringTypesToHardTypes(DataTable dt)
{
//parse the value
dr[newColumn] = decider.Parse(dr[dataColumn] as string)??DBNull.Value;

}
catch(Exception ex)
catch (Exception ex)
{
throw new Exception($"Failed to parse value '{dr[dataColumn]}' in column '{dataColumn}'",ex);
}

Check notice

Code scanning / CodeQL

Generic catch clause Note

Generic catch clause.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public void AddOrUpdateKeyword(string keyword, string value, ConnectionStringKey
/// <param name="keyword"></param>
/// <param name="value"></param>
/// <returns></returns>
private string GetCollisionWithKeyword(string keyword, string value)
private string? GetCollisionWithKeyword(string keyword, string value)
{
ArgumentNullException.ThrowIfNull(keyword);
ArgumentNullException.ThrowIfNull(value);
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 @@ -52,7 +52,7 @@ public sealed class DiscoveredRelationship(string fkName, DiscoveredTable pkTabl
/// <param name="primaryKeyCol"></param>
/// <param name="foreignKeyCol"></param>
/// <param name="transaction"></param>
public void AddKeys(string primaryKeyCol, string foreignKeyCol,IManagedTransaction transaction = null)
public void AddKeys(string primaryKeyCol, string foreignKeyCol,IManagedTransaction? transaction = null)
{
if (_pkColumns == null)
{
Expand Down
8 changes: 4 additions & 4 deletions FAnsiSql/Discovery/DatabaseColumnRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ namespace FAnsi.Discovery;
///
/// <para>Type specification is defined in the DatabaseTypeRequest but can also be specified explicitly (e.g. 'varchar(10)').</para>
/// </summary>
public sealed class DatabaseColumnRequest(string columnName, DatabaseTypeRequest typeRequested, bool allowNulls = true)
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.
///
/// <para>See also <see cref="GetSQLDbType"/></para>
/// </summary>
public string ExplicitDbType { get; set; }
public string? ExplicitDbType { get; set; }


public string ColumnName { get; set; } = columnName;
Expand All @@ -31,7 +31,7 @@ public sealed class DatabaseColumnRequest(string columnName, DatabaseTypeRequest
///
/// <para>See also <see cref="GetSQLDbType"/></para>
/// </summary>
public DatabaseTypeRequest TypeRequested { get; set; } = typeRequested;
public DatabaseTypeRequest? TypeRequested { get; set; } = typeRequested;

/// <summary>
/// True to create a column which is nullable
Expand Down 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 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,8 @@ namespace FAnsi.Discovery;
/// <param name="table"></param>
/// <param name="name"></param>
/// <param name="allowsNulls"></param>
public sealed 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 @@ -105,7 +106,7 @@ public sealed class DiscoveredColumn(DiscoveredTable table, string name, bool al
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
Expand Down
35 changes: 18 additions & 17 deletions FAnsiSql/Discovery/DiscoveredDataType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace FAnsi.Discovery;
/// </summary>
public sealed class DiscoveredDataType
{
private readonly DiscoveredColumn Column;
private readonly DiscoveredColumn? _column;

/// <summary>
/// The proprietary DBMS name for the datatype e.g. varchar2(100) for Oracle, datetime2 for Sql Server etc.
Expand All @@ -32,10 +32,10 @@ public sealed class DiscoveredDataType
/// <param name="r">All the values in r will be copied into the Dictionary property of this class called ProprietaryDatatype</param>
/// <param name="sqlType">Your inferred SQL data type for it e.g. varchar(50)</param>
/// <param name="column">The column it belongs to, can be null e.g. if your data type belongs to a DiscoveredParameter instead</param>
public DiscoveredDataType(DbDataReader r, string sqlType, DiscoveredColumn column)
public DiscoveredDataType(DbDataReader r, string sqlType, DiscoveredColumn? column)
{
SQLType = sqlType;
Column = column;
_column = column;

for (var i = 0; i < r.FieldCount; i++)
ProprietaryDatatype.Add(r.GetName(i), r.GetValue(i));
Expand All @@ -46,22 +46,22 @@ public DiscoveredDataType(DbDataReader r, string sqlType, DiscoveredColumn colum
/// <para>Returns <see cref="int.MaxValue"/> if the string type has no real limit e.g. "text"</para>
/// </summary>
/// <returns></returns>
public int GetLengthIfString() => Column.Table.Database.Server.Helper.GetQuerySyntaxHelper().TypeTranslater.GetLengthIfString(SQLType);
public int GetLengthIfString() => _column?.Table.Database.Server.Helper.GetQuerySyntaxHelper().TypeTranslater.GetLengthIfString(SQLType) ?? -1;

/// <summary>
/// <para>Returns the Scale/Precision of the data type. Only applies to decimal(x,y) types not basic types e.g. int.</para>
///
/// <para>Returns null if the datatype is not floating point</para>
/// </summary>
/// <returns></returns>
public DecimalSize GetDecimalSize() => Column.Table.Database.Server.Helper.GetQuerySyntaxHelper().TypeTranslater.GetDigitsBeforeAndAfterDecimalPointIfDecimal(SQLType);
public DecimalSize? GetDecimalSize() => _column?.Table.Database.Server.Helper.GetQuerySyntaxHelper().TypeTranslater.GetDigitsBeforeAndAfterDecimalPointIfDecimal(SQLType);

/// <summary>
/// Returns the System.Type that should be used to store values read out of columns of this data type (See <see cref="ITypeTranslater.GetCSharpTypeForSQLDBType"/>
/// </summary>
/// <returns></returns>
[return:DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties|DynamicallyAccessedMemberTypes.PublicFields)]
public Type GetCSharpDataType() => Column.Table.Database.Server.GetQuerySyntaxHelper().TypeTranslater.GetCSharpTypeForSQLDBType(SQLType);
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)]
public Type? GetCSharpDataType() => _column?.Table.Database.Server.GetQuerySyntaxHelper().TypeTranslater.GetCSharpTypeForSQLDBType(SQLType);

/// <summary>
/// Returns the <see cref="SQLType"/>
Expand All @@ -78,7 +78,7 @@ public DiscoveredDataType(DbDataReader r, string sqlType, DiscoveredColumn colum
/// <param name="managedTransaction"></param>
/// <exception cref="InvalidResizeException"></exception>
/// <exception cref="AlterFailedException"></exception>
public void Resize(int newSize, IManagedTransaction managedTransaction = null)
public void Resize(int newSize, IManagedTransaction? managedTransaction = null)
{
var toReplace = GetLengthIfString();

Expand All @@ -104,7 +104,7 @@ public void Resize(int newSize, IManagedTransaction managedTransaction = null)
/// <param name="managedTransaction"></param>
/// <exception cref="InvalidResizeException"></exception>
/// <exception cref="AlterFailedException"></exception>
public void Resize(int numberOfDigitsBeforeDecimalPoint, int numberOfDigitsAfterDecimalPoint, IManagedTransaction managedTransaction = null)
public void Resize(int numberOfDigitsBeforeDecimalPoint, int numberOfDigitsAfterDecimalPoint, IManagedTransaction? managedTransaction = null)
{
var toReplace = GetDecimalSize();

Expand All @@ -117,9 +117,10 @@ public void Resize(int numberOfDigitsBeforeDecimalPoint, int numberOfDigitsAfter
if (toReplace.NumbersAfterDecimalPlace> numberOfDigitsAfterDecimalPoint)
throw new InvalidResizeException(string.Format(FAnsiStrings.DiscoveredDataType_Resize_Cannot_shrink_column__number_of_digits_after_the_decimal_point_is_currently__0__and_you_asked_to_set_it_to__1___Current_SQLType_is__2__, toReplace.NumbersAfterDecimalPlace, numberOfDigitsAfterDecimalPoint, SQLType));

var newDataType = Column.Table.GetQuerySyntaxHelper()
.TypeTranslater.GetSQLDBTypeForCSharpType(new DatabaseTypeRequest(typeof (decimal), null,
new DecimalSize(numberOfDigitsBeforeDecimalPoint, numberOfDigitsAfterDecimalPoint)));
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");

AlterTypeTo(newDataType, managedTransaction);
}
Expand All @@ -133,15 +134,15 @@ public void Resize(int numberOfDigitsBeforeDecimalPoint, int numberOfDigitsAfter
/// <param name="managedTransaction"></param>
/// <param name="alterTimeoutInSeconds">The time to wait before giving up on the command (See <see cref="DbCommand.CommandTimeout"/></param>
/// <exception cref="AlterFailedException"></exception>
public void AlterTypeTo(string newType, IManagedTransaction managedTransaction = null,int alterTimeoutInSeconds = 500)
public void AlterTypeTo(string newType, IManagedTransaction? managedTransaction = null,int alterTimeoutInSeconds = 500)
{
if(Column == null)
if(_column == null)
throw new NotSupportedException(FAnsiStrings.DiscoveredDataType_AlterTypeTo_Cannot_resize_DataType_because_it_does_not_have_a_reference_to_a_Column_to_which_it_belongs);

var server = Column.Table.Database.Server;
var server = _column.Table.Database.Server;
using (var connection = server.GetManagedConnection(managedTransaction))
{
var sql = Column.Helper.GetAlterColumnToSql(Column, newType, Column.AllowNulls);
var sql = _column.Helper.GetAlterColumnToSql(_column, newType, _column.AllowNulls);
try
{
using var cmd = server.Helper.GetCommand(sql, connection.Connection, connection.Transaction);
Expand Down Expand Up @@ -174,7 +175,7 @@ public void AlterTypeTo(string newType, IManagedTransaction managedTransaction =
/// Equality based on <see cref="SQLType"/>
/// </summary>
/// <returns></returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
Expand Down
Loading

0 comments on commit 87c725a

Please sign in to comment.