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

Use Enum Member Values #4

Merged
merged 3 commits into from
Feb 18, 2025
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ on:

jobs:
build-ubuntu:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04

steps:
- uses: actions/checkout@v2
Expand Down
30 changes: 29 additions & 1 deletion src/Searchlight/Parsing/SyntaxParser.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Searchlight.Exceptions;
using Searchlight.Expressions;
using Searchlight.Nesting;
Expand Down Expand Up @@ -592,17 +594,43 @@ private static IExpressionValue ParseParameter(DataSource source, SyntaxTree syn
// Special case for enum types
if (column.EnumType != null || fieldType.IsEnum)
{
var fields = fieldType.GetFields(BindingFlags.Public | BindingFlags.Static);
var enumMembers = fields.Select(f =>
{
var attr = f.GetCustomAttribute<EnumMemberAttribute>();
if (attr != null && attr.Value != null)
{
return (f.Name, attr.Value);
}
return (null, null);
}).Where(e => e.Name != null).ToList();

var dictionary = enumMembers.ToDictionary(p => p.Value, p => p.Name);

try
{
if (dictionary.TryGetValue(valueToken, out var enumValueToken))
{
valueToken = enumValueToken;
}
var parsed = Enum.Parse(column.EnumType ?? fieldType, valueToken);
return ConstantValue.From(Convert.ChangeType(parsed, fieldType));
}
catch
{
var expectedTokens = Enum.GetNames(column.EnumType ?? fieldType);
var valueDictionary = enumMembers.ToDictionary(p => p.Name, p => p.Value);
for (var i = 0; i < expectedTokens.Length; i++)
{
if (valueDictionary.TryGetValue(expectedTokens[i], out var newToken))
{
expectedTokens[i] = newToken;
}
}
syntax.AddError(new InvalidToken
{
BadToken = valueToken,
ExpectedTokens = Enum.GetNames(column.EnumType ?? fieldType),
ExpectedTokens = expectedTokens,
OriginalFilter = tokens.OriginalText,
});
return null;
Expand Down
29 changes: 28 additions & 1 deletion tests/Searchlight.Tests/ParseModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Searchlight.Query;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Searchlight.Exceptions;
using Searchlight.Expressions;
Expand Down Expand Up @@ -509,13 +510,23 @@ public enum TestEnumValueCategory
Generic = 2,
}

public enum TestEnumAttributeValueCategory
{
[EnumMember(Value = "Not Anything")]
None = 0,
Special = 1,
Generic = 2,
}

[SearchlightModel(DefaultSort = "Name ascending")]
public class TestClassWithEnumValues
{
[SearchlightField(OriginalName = "field_name")]
public string Name { get; set; }
[SearchlightField(OriginalName = "field_category")]
public TestEnumValueCategory Category { get; set; }
[SearchlightField(OriginalName = "field_category_attribute")]
public TestEnumAttributeValueCategory AttributeCategory { get; set; }
}


Expand All @@ -524,11 +535,13 @@ public void TestValidEnumFilters()
{
var source = DataSource.Create(null, typeof(TestClassWithEnumValues), AttributeMode.Strict);
var columns = source.GetColumnDefinitions().ToArray();
Assert.AreEqual(2, columns.Length);
Assert.AreEqual(3, columns.Length);
Assert.AreEqual("Name", columns[0].FieldName);
Assert.AreEqual(typeof(string), columns[0].FieldType);
Assert.AreEqual("Category", columns[1].FieldName);
Assert.AreEqual(typeof(TestEnumValueCategory), columns[1].FieldType);
Assert.AreEqual("AttributeCategory", columns[2].FieldName);
Assert.AreEqual(typeof(TestEnumAttributeValueCategory), columns[2].FieldType);

// Query for a valid category
var syntax1 = source.ParseFilter("category = None");
Expand All @@ -537,12 +550,26 @@ public void TestValidEnumFilters()
// Query using the raw integer value, which is generally not advised but we accept it for historical reasons
var syntax2 = source.ParseFilter("category = 0");
Assert.IsNotNull(syntax2);

// Query attribute value
var syntax3 = source.ParseFilter("attributecategory = 'Not Anything'");
Assert.IsNotNull(syntax3);

// Query non attribute value in mixed enum
var syntax4 = source.ParseFilter("attributecategory = Special");
Assert.IsNotNull(syntax4);

// Query for a non-valid category
var ex2 = Assert.ThrowsException<InvalidToken>(() => source.ParseFilter("category = InvalidValue"));
Assert.AreEqual("InvalidValue", ex2.BadToken);
CollectionAssert.AreEqual(new string[] { "None", "Special", "Generic" }, ex2.ExpectedTokens);
Assert.AreEqual("The filter statement contained an unexpected token, 'InvalidValue'. Searchlight expects to find one of these next: None, Special, Generic", ex2.ErrorMessage);

// Query for a non-valid category in attribute enum
var ex3 = Assert.ThrowsException<InvalidToken>(() => source.ParseFilter("attributecategory = InvalidValue"));
Assert.AreEqual("InvalidValue", ex3.BadToken);
CollectionAssert.AreEqual(new string[] { "Not Anything", "Special", "Generic" }, ex3.ExpectedTokens);
Assert.AreEqual("The filter statement contained an unexpected token, 'InvalidValue'. Searchlight expects to find one of these next: Not Anything, Special, Generic", ex3.ErrorMessage);
}

[SearchlightModel(DefaultSort = nameof(Name))]
Expand Down
8 changes: 4 additions & 4 deletions tests/Searchlight.Tests/Searchlight.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
</PackageReference>
<PackageReference Include="MySql.Data" Version="8.1.0" />
<PackageReference Include="Npgsql" Version="7.0.4" />
<PackageReference Include="Testcontainers" Version="3.4.0" />
<PackageReference Include="Testcontainers.MsSql" Version="3.4.0" />
<PackageReference Include="Testcontainers.MySql" Version="3.4.0" />
<PackageReference Include="Testcontainers.PostgreSql" Version="3.4.0" />
<PackageReference Include="Testcontainers" Version="4.2.0" />
<PackageReference Include="Testcontainers.MsSql" Version="4.2.0" />
<PackageReference Include="Testcontainers.MySql" Version="4.2.0" />
amullan-sage marked this conversation as resolved.
Show resolved Hide resolved
<PackageReference Include="Testcontainers.PostgreSql" Version="4.2.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading