Skip to content

Commit d9d8386

Browse files
Upsert logging improvements (#492)
* Upsert logging improvements * case sensitive
1 parent a3b83a8 commit d9d8386

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/SqlAsyncCollector.cs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ private async Task UpsertRowsAsync(IEnumerable<T> rows, SqlAttribute attribute,
236236
batchCount++;
237237
GenerateDataQueryForMerge(tableInfo, batch, out string newDataQuery, out string rowData);
238238
command.CommandText = $"{newDataQuery} {tableInfo.Query};";
239+
this._logger.LogDebugWithThreadId($"UpsertRowsTransactionBatch - Query={command.CommandText}");
239240
par.Value = rowData;
240241
await command.ExecuteNonQueryAsync();
241242
}
@@ -265,7 +266,7 @@ private async Task UpsertRowsAsync(IEnumerable<T> rows, SqlAttribute attribute,
265266
string message2 = $"Encountered exception during upsert and rollback.";
266267
throw new AggregateException(message2, new List<Exception> { ex, ex2 });
267268
}
268-
throw;
269+
throw new InvalidOperationException($"Unexpected error upserting rows", ex);
269270
}
270271
}
271272
}
@@ -396,7 +397,6 @@ public class TableInformation
396397
public StringComparer Comparer { get; }
397398

398399
/// <summary>
399-
/// T-SQL merge statement generated from primary keys
400400
/// T-SQL merge or insert statement generated from primary keys
401401
/// and column names for a specific table.
402402
/// </summary>
@@ -540,9 +540,9 @@ WHEN NOT MATCHED THEN
540540
/// <param name="sqlConnection">An open connection with which to query SQL against</param>
541541
/// <param name="fullName">Full name of table, including schema (if exists).</param>
542542
/// <param name="logger">ILogger used to log any errors or warnings.</param>
543-
/// <param name="columnNames">Column names from the object</param>
543+
/// <param name="objectColumnNames">Column names from the object</param>
544544
/// <returns>TableInformation object containing primary keys, column types, etc.</returns>
545-
public static async Task<TableInformation> RetrieveTableInformationAsync(SqlConnection sqlConnection, string fullName, ILogger logger, IEnumerable<string> columnNames)
545+
public static async Task<TableInformation> RetrieveTableInformationAsync(SqlConnection sqlConnection, string fullName, ILogger logger, IEnumerable<string> objectColumnNames)
546546
{
547547
Dictionary<TelemetryPropertyName, string> sqlConnProps = sqlConnection.AsConnectionProps();
548548
TelemetryInstance.TrackEvent(TelemetryEventName.GetTableInfoStart, sqlConnProps);
@@ -560,13 +560,15 @@ public static async Task<TableInformation> RetrieveTableInformationAsync(SqlConn
560560
var cmdCollation = new SqlCommand(getDatabaseCollationQuery, sqlConnection);
561561
using (SqlDataReader rdr = await cmdCollation.ExecuteReaderAsync())
562562
{
563+
string collation = "";
563564
while (await rdr.ReadAsync())
564565
{
565-
caseSensitive = GetCaseSensitivityFromCollation(rdr[Collation].ToString());
566+
collation = rdr[Collation].ToString();
567+
caseSensitive = GetCaseSensitivityFromCollation(collation);
566568
}
567569
caseSensitiveSw.Stop();
568570
TelemetryInstance.TrackDuration(TelemetryEventName.GetCaseSensitivity, caseSensitiveSw.ElapsedMilliseconds, sqlConnProps);
569-
logger.LogDebugWithThreadId($"END GetCaseSensitivity Duration={caseSensitiveSw.ElapsedMilliseconds}ms");
571+
logger.LogDebugWithThreadId($"END GetCaseSensitivity Collation={collation} CaseSensitive={caseSensitive} Duration={caseSensitiveSw.ElapsedMilliseconds}ms");
570572
}
571573
}
572574
catch (Exception ex)
@@ -656,7 +658,7 @@ public static async Task<TableInformation> RetrieveTableInformationAsync(SqlConn
656658
// Match SQL Primary Key column names to POCO property objects. Ensure none are missing.
657659
StringComparison comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
658660
IEnumerable<PropertyInfo> primaryKeyProperties = typeof(T).GetProperties().Where(f => primaryKeys.Any(k => string.Equals(k.Name, f.Name, comparison)));
659-
IEnumerable<string> primaryKeysFromObject = columnNames.Where(f => primaryKeys.Any(k => string.Equals(k.Name, f, comparison)));
661+
IEnumerable<string> primaryKeysFromObject = objectColumnNames.Where(f => primaryKeys.Any(k => string.Equals(k.Name, f, comparison)));
660662
IEnumerable<PrimaryKey> missingPrimaryKeysFromItem = primaryKeys
661663
.Where(k => !primaryKeysFromObject.Contains(k.Name, comparer));
662664
bool hasIdentityColumnPrimaryKeys = primaryKeys.Any(k => k.IsIdentity);
@@ -674,7 +676,8 @@ public static async Task<TableInformation> RetrieveTableInformationAsync(SqlConn
674676
// If any identity columns or columns with default values aren't included in the object then we have to generate a basic insert since the merge statement expects all primary key
675677
// columns to exist. (the merge statement can handle nullable columns though if those exist)
676678
bool usingInsertQuery = (hasIdentityColumnPrimaryKeys || hasDefaultColumnPrimaryKeys) && missingPrimaryKeysFromItem.Any();
677-
IEnumerable<string> bracketedColumnNamesFromItem = columnNames
679+
680+
IEnumerable<string> bracketedColumnNamesFromItem = objectColumnNames
678681
.Where(prop => !primaryKeys.Any(k => k.IsIdentity && string.Equals(k.Name, prop, comparison))) // Skip any identity columns, those should never be updated
679682
.Select(prop => prop.AsBracketQuotedString());
680683
string query = usingInsertQuery ? GetInsertQuery(table, bracketedColumnNamesFromItem) : GetMergeQuery(primaryKeys, table, bracketedColumnNamesFromItem);
@@ -689,7 +692,7 @@ public static async Task<TableInformation> RetrieveTableInformationAsync(SqlConn
689692
sqlConnProps.Add(TelemetryPropertyName.QueryType, usingInsertQuery ? "insert" : "merge");
690693
sqlConnProps.Add(TelemetryPropertyName.HasIdentityColumn, hasIdentityColumnPrimaryKeys.ToString());
691694
TelemetryInstance.TrackDuration(TelemetryEventName.GetTableInfoEnd, tableInfoSw.ElapsedMilliseconds, sqlConnProps, durations);
692-
logger.LogDebugWithThreadId($"END RetrieveTableInformationAsync Duration={tableInfoSw.ElapsedMilliseconds}ms DB and Table: {sqlConnection.Database}.{fullName}. Primary keys: [{string.Join(",", primaryKeys.Select(pk => pk.Name))}]. SQL Column and Definitions: [{string.Join(",", columnDefinitionsFromSQL)}]");
695+
logger.LogDebugWithThreadId($"END RetrieveTableInformationAsync Duration={tableInfoSw.ElapsedMilliseconds}ms DB and Table: {sqlConnection.Database}.{fullName}. Primary keys: [{string.Join(",", primaryKeys.Select(pk => pk.Name))}]. SQL Column and Definitions: [{string.Join(",", columnDefinitionsFromSQL)}] Object columns: [{string.Join(",", objectColumnNames)}]");
693696
return new TableInformation(primaryKeyProperties, columnDefinitionsFromSQL, comparer, query, hasIdentityColumnPrimaryKeys);
694697
}
695698
}

0 commit comments

Comments
 (0)