Skip to content

Instantly share code, notes, and snippets.

@icanhasjonas
Last active March 6, 2019 23:59
Show Gist options
  • Save icanhasjonas/0a91ac4698bd6cc7c457cde7b4da2e9d to your computer and use it in GitHub Desktop.
Save icanhasjonas/0a91ac4698bd6cc7c457cde7b4da2e9d to your computer and use it in GitHub Desktop.
Self Formatting SQLish Filters... for the lazy
[AttributeUsage( AttributeTargets.Property )]
public class QueryFilterAttribute : Attribute {
public QueryFilterAttribute( string fieldName )
{
FieldName = fieldName;
}
public QueryFilterAttribute() { }
public string FieldName { get; }
public string Format( PropertyInfo pi, object instance )
{
var value = pi.GetValue( instance );
switch( value ) {
case bool b: return $"{FieldName ?? pi.Name} = {b.ToString().ToLowerInvariant()}";
case null: return null;
}
return null;
}
}
public static class QueryFilterFormatter<T> {
private static readonly (QueryFilterAttribute queryFilter, PropertyInfo pi)[] _info = typeof(T)
.GetProperties( BindingFlags.Instance | BindingFlags.Public )
.Select( x => (queryFilter: x.GetCustomAttribute<QueryFilterAttribute>(), pi: x) )
.Where( x => x.queryFilter != null )
.ToArray();
public static string Format( T instance ) =>
string.Join( " AND ", _info
.Select( x => x.queryFilter.Format( x.pi, instance ) )
.Where( x => x != null ) );
}
public class QueryParams
{
[QueryFilter("is_network_notification")]
public bool? IsNetworkNotification { get; set; }
[QueryFilter("is_published")]
public bool? IsPublished { get; set; }
[QueryFilter("is_test_account")]
public bool? IsTestAccount { get; set; }
public override string ToString() => QueryFilterFormatter<QueryParams>.Format(this);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment