Skip to content

Commit

Permalink
fix issue with reader generation and column names
Browse files Browse the repository at this point in the history
  • Loading branch information
pwelter34 committed Aug 9, 2024
1 parent 6f27712 commit ca6a123
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 26 deletions.
54 changes: 52 additions & 2 deletions src/FluentCommand.Generators/DataReaderFactoryGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Immutable;
using System.Reflection;
using System.Xml.Linq;

using FluentCommand.Generators.Internal;
using FluentCommand.Generators.Models;
Expand Down Expand Up @@ -171,7 +172,15 @@ private static EntityProperty CreateProperty(IPropertySymbol propertySymbol, str
// look for custom field converter
var attributes = propertySymbol.GetAttributes();
if (attributes == null || attributes.Length == 0)
return new EntityProperty(propertyName, propertyType, parameterName);
{
return new EntityProperty(
propertyName,
propertyName,
propertyType,
parameterName);
}

var columnName = GetColumnName(attributes) ?? propertyName;

var converter = attributes
.FirstOrDefault(a => a.AttributeClass is
Expand All @@ -181,14 +190,21 @@ private static EntityProperty CreateProperty(IPropertySymbol propertySymbol, str
});

if (converter == null)
return new EntityProperty(propertyName, propertyType, parameterName);
{
return new EntityProperty(
propertyName,
columnName,
propertyType,
parameterName);
}

// attribute contructor
var converterType = converter.ConstructorArguments.FirstOrDefault();
if (converterType.Value is INamedTypeSymbol converterSymbol)
{
return new EntityProperty(
propertyName,
columnName,
propertyType,
parameterName,
converterSymbol.ToDisplayString());
Expand All @@ -205,13 +221,15 @@ private static EntityProperty CreateProperty(IPropertySymbol propertySymbol, str

return new EntityProperty(
propertyName,
columnName,
propertyType,
parameterName,
converterString);
}

return new EntityProperty(
propertyName,
columnName,
propertyType,
parameterName);
}
Expand Down Expand Up @@ -243,4 +261,36 @@ private static bool IsIncluded(IPropertySymbol propertySymbol)

return !propertySymbol.IsIndexer && !propertySymbol.IsAbstract && propertySymbol.DeclaredAccessibility == Accessibility.Public;
}

private static string GetColumnName(ImmutableArray<AttributeData> attributes)
{
var columnAttribute = attributes
.FirstOrDefault(a => a.AttributeClass is
{
Name: "ColumnAttribute",
ContainingNamespace:
{
Name: "Schema",
ContainingNamespace:
{
Name: "DataAnnotations",
ContainingNamespace:
{
Name: "ComponentModel",
ContainingNamespace.Name: "System"
}
}
}
});

if (columnAttribute == null)
return null;

// attribute contructor [Column("Name")]
var converterType = columnAttribute.ConstructorArguments.FirstOrDefault();
if (converterType.Value is string stringValue)
return stringValue;

return null;
}
}
10 changes: 3 additions & 7 deletions src/FluentCommand.Generators/DataReaderFactoryWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -364,13 +364,9 @@ private static void WriteEntityFactory(IndentedStringBuilder codeBuilder, Entity
var fieldName = CamelCase(entityProperty.PropertyName);

codeBuilder
.Append("case nameof(")
.Append(entity.EntityNamespace)
.Append(".")
.Append(entity.EntityName)
.Append(".")
.Append(entityProperty.PropertyName)
.AppendLine("):");
.Append("case \"")
.Append(entityProperty.ColumnName)
.AppendLine("\":");

if (string.IsNullOrEmpty(entityProperty.ConverterName))
{
Expand Down
4 changes: 4 additions & 0 deletions src/FluentCommand.Generators/Models/EntityProperty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@ public sealed class EntityProperty : IEquatable<EntityProperty>
{
public EntityProperty(
string propertyName,
string columnName,
string propertyType,
string parameterName = null,
string converterName = null)
{
PropertyName = propertyName;
ColumnName = columnName;
PropertyType = propertyType;
ParameterName = parameterName;
ConverterName = converterName;
}

public string PropertyName { get; }

public string ColumnName { get; }

public string PropertyType { get; }

public string ParameterName { get; }
Expand Down
8 changes: 1 addition & 7 deletions src/FluentCommand/Extensions/DataRecordExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -450,13 +450,7 @@ public static object GetValue(this IDataRecord dataRecord, string name)
public static T GetValue<T>(this IDataRecord dataRecord, string name)
{
int ordinal = dataRecord.GetOrdinal(name);
if (dataRecord.IsDBNull(ordinal))
return default;

if (dataRecord is DbDataReader dataReader)
return dataReader.GetFieldValue<T>(ordinal);

return (T)dataRecord.GetValue(ordinal);
return dataRecord.GetValue<T>(ordinal);
}

/// <summary>
Expand Down
31 changes: 31 additions & 0 deletions test/FluentCommand.Entities/TableTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace FluentCommand.Entities;

[Table("Table1 $ Test", Schema = "dbo")]
public class TableTest
{
private const string BlahColumn = "Blah #";

[Key]
[Column("Test$")]
public string Test { get; set; } = null!;

[Column(BlahColumn)]
public string Blah { get; set; }

[Column("Table Example ID")]
public int? TableExampleID { get; set; }

public int? TableExampleObject { get; set; }

[Column("1stNumber")]
public string FirstNumber { get; set; }

[Column("123Street")]
public string Street { get; set; }

[Column("123 Test 123")]
public string Test123 { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ public async Task Generate()
"Status",
new EntityProperty[]
{
new("Id", typeof(int).FullName),
new("Name", typeof(string).FullName),
new("IsActive", typeof(bool).FullName),
new("Updated", typeof(DateTimeOffset).FullName),
new("RowVersion", typeof(byte[]).FullName),
new("Id", "Id", typeof(int).FullName),
new("Name", "Name", typeof(string).FullName),
new("IsActive", "IsActive", typeof(bool).FullName),
new("Updated", "Updated", typeof(DateTimeOffset).FullName),
new("RowVersion", "RowVersion", typeof(byte[]).FullName),
}.ToImmutableArray()
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,19 +112,19 @@ namespace FluentCommand.Entities
var __name = dataRecord.GetName(__index);
switch (__name)
{
case nameof(FluentCommand.Entities.Status.Id):
case "Id":
v_id = dataRecord.GetInt32(__index);
break;
case nameof(FluentCommand.Entities.Status.Name):
case "Name":
v_name = dataRecord.GetString(__index);
break;
case nameof(FluentCommand.Entities.Status.IsActive):
case "IsActive":
v_isActive = dataRecord.GetBoolean(__index);
break;
case nameof(FluentCommand.Entities.Status.Updated):
case "Updated":
v_updated = dataRecord.GetDateTimeOffset(__index);
break;
case nameof(FluentCommand.Entities.Status.RowVersion):
case "RowVersion":
v_rowVersion = dataRecord.GetBytes(__index);
break;
}
Expand Down
14 changes: 14 additions & 0 deletions test/FluentCommand.SqlServer.Tests/DataQueryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -454,4 +454,18 @@ public async System.Threading.Tasks.Task SqlQueryDataTypeAsync()
results.Should().NotBeNull();
}

[Fact]
public async System.Threading.Tasks.Task SqlQueryTableTestAsync()
{
await using var session = Services.GetRequiredService<IDataSession>();
session.Should().NotBeNull();

var results = await session
.Sql(builder => builder
.Select<TableTest>()
)
.QueryAsync<TableTest>();

results.Should().NotBeNull();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,18 @@ CREATE TABLE [dbo].[DataType] (
CONSTRAINT [PK_DataType] PRIMARY KEY ([Id])
);

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Table1 $ Test]') AND type in (N'U'))
CREATE TABLE [dbo].[Table1 $ Test] (
[Test$] char(10) NOT NULL,
[Blah #] char(10) NULL,
[Table Example ID] int NULL,
[TableExampleObject] int NULL,
[1stNumber] nvarchar(50) NULL,
[123Street] nvarchar(50) NULL,
[123 Test 123] nvarchar(50) NULL,
CONSTRAINT [PK_Table1 $ Test] PRIMARY KEY ([Test$])
);

-- Types
CREATE TYPE [dbo].[UserImportType] AS TABLE
(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,22 @@ WHEN NOT MATCHED BY TARGET THEN
WHEN MATCHED THEN
UPDATE SET t.[Name] = s.[Name], t.[Boolean] = s.[Boolean], t.[Short] = s.[Short], t.[Long] = s.[Long], t.[Float] = s.[Float], t.[Double] = s.[Double], t.[Decimal] = s.[Decimal], t.[DateTime] = s.[DateTime], t.[DateTimeOffset] = s.[DateTimeOffset], t.[Guid] = s.[Guid], t.[TimeSpan] = s.[TimeSpan], t.[DateOnly] = s.[DateOnly], t.[TimeOnly] = s.[TimeOnly], t.[BooleanNull] = s.[BooleanNull], t.[ShortNull] = s.[ShortNull], t.[LongNull] = s.[LongNull], t.[FloatNull] = s.[FloatNull], t.[DoubleNull] = s.[DoubleNull], t.[DecimalNull] = s.[DecimalNull], t.[DateTimeNull] = s.[DateTimeNull], t.[DateTimeOffsetNull] = s.[DateTimeOffsetNull], t.[GuidNull] = s.[GuidNull], t.[TimeSpanNull] = s.[TimeSpanNull], t.[DateOnlyNull] = s.[DateOnlyNull], t.[TimeOnlyNull] = s.[TimeOnlyNull]
OUTPUT $action as MergeAction;

/* Table [dbo].[Table1 $ Test] data */

MERGE INTO [dbo].[Table1 $ Test] AS t
USING
(
VALUES
(N'testing ', N'value ', 123, 456, N'123 Main', N'City, MN', N'55555')
)
AS s
([Test$], [Blah #], [Table Example ID], [TableExampleObject], [1stNumber], [123Street], [123 Test 123])
ON (t.[Test$] = s.[Test$])
WHEN NOT MATCHED BY TARGET THEN
INSERT ([Test$], [Blah #], [Table Example ID], [TableExampleObject], [1stNumber], [123Street], [123 Test 123])
VALUES (s.[Test$], s.[Blah #], s.[Table Example ID], s.[TableExampleObject], s.[1stNumber], s.[123Street], s.[123 Test 123])
WHEN MATCHED THEN
UPDATE SET t.[Blah #] = s.[Blah #], t.[Table Example ID] = s.[Table Example ID], t.[TableExampleObject] = s.[TableExampleObject], t.[1stNumber] = s.[1stNumber], t.[123Street] = s.[123Street], t.[123 Test 123] = s.[123 Test 123]
OUTPUT $action as MergeAction;

0 comments on commit ca6a123

Please sign in to comment.