Skip to content

Instantly share code, notes, and snippets.

@arielmagbanua
Created February 20, 2020 14:58
Show Gist options
  • Save arielmagbanua/d6b9ca5a36bb9de533cda27fc72afa38 to your computer and use it in GitHub Desktop.
Save arielmagbanua/d6b9ca5a36bb9de533cda27fc72afa38 to your computer and use it in GitHub Desktop.
IbsQueryBuilder Abstract Class that Mimics Laravel ORM for IBS Gateway Builder
using System;
using System.Text.RegularExpressions;
namespace ConsoleNancySelfHostedNetTest
{
public abstract class IbsQueryBuilder
{
private string _queryCriteria = "";
public virtual IbsQueryBuilder Where(string col, string arg1, string arg2 = null)
{
string op = "=";
string value = "";
if (!string.IsNullOrWhiteSpace(arg2))
{
op = arg1;
value = arg2;
}
else
{
// only 2 args is present then use = as default operator
value = arg1;
}
// format properly strings or characters
value = IsNumber(value) ? value : $"[{value}]";
if (string.IsNullOrWhiteSpace(_queryCriteria))
{
_queryCriteria = $"{col}{op}{value}";
}
else
{
_queryCriteria += $" and {col}{op}{value}";
}
return this;
}
public virtual IbsQueryBuilder OrWhere(string col, string arg1, string arg2 = null)
{
string op = "=";
string value = "";
if (!string.IsNullOrWhiteSpace(arg2))
{
op = arg1;
value = arg2;
}
else
{
// only 2 args is present then use = as default operator
value = arg1;
}
// format properly strings or characters
value = IsNumber(value) ? value : $"[{value}]";
if (string.IsNullOrWhiteSpace(_queryCriteria))
{
_queryCriteria = $"{col}{op}{value}";
}
else
{
_queryCriteria += $" or {col}{op}{value}";
}
return this;
}
public virtual IbsQueryBuilder WhereRaw(string criteria)
{
return SetRawCriteria("and", criteria);
}
public virtual IbsQueryBuilder OrWhereRaw(string criteria)
{
return SetRawCriteria("or", criteria);
}
private IbsQueryBuilder SetRawCriteria(string comparator, string criteria)
{
if (string.IsNullOrWhiteSpace(_queryCriteria))
{
_queryCriteria = criteria;
}
else
{
_queryCriteria += $" {comparator} {criteria}";
}
return this;
}
private Boolean IsNumber(string input)
{
return Regex.IsMatch(input, @"^\d+$");
}
public IbsQueryBuilder ClearQuery()
{
_queryCriteria = "";
return this;
}
public string ToQuery()
{
string temp = _queryCriteria;
// clear this property since at this point we already built the query
ClearQuery();
return temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment