QueryBuilder

mail@pastecode.io avatar
unknown
csharp
a year ago
2.1 kB
1
Indexable
Never
using System;
using System.Collections.Generic;
using System.Text;

namespace ThreadBasket.Api.Functions.Models.Shared;

public class QueryBuilder
{
    private StringBuilder _queryBuilder = new();
    private string _tableName = "";
    private int _whereCount = 0;

    private readonly Dictionary<SqlOperator, string> _operatorDictionary = new()
    {
        { SqlOperator.Equal, "=" },
        { SqlOperator.NotEqual, "<>" },
        { SqlOperator.GreaterThan, ">" },
        { SqlOperator.GreaterThanOrEqual, ">=" },
        { SqlOperator.LessThan, "<" },
        { SqlOperator.LessThanOrEqual, "<=" }
    };

    public void AddSelect(string[] fields)
    {
        _queryBuilder.Append($"SELECT {string.Join(",", fields)} ");
    }

    public void AddSelectAll()
    {
        _queryBuilder.Append("SELECT * ");
    }

    public void AddFrom(string tableName)
    {
        _tableName = tableName;
        _queryBuilder.Append($"FROM {tableName} ");
    }

    public void AddWhere(string field, SqlOperator sqlOperator, string value)
    {
        if (_whereCount > 0)
        {
            _queryBuilder.Append($"&& {_tableName}.{field} {_operatorDictionary.GetValueOrDefault(sqlOperator)} '{value}' ");
        }
        else
        {
            _queryBuilder.Append($"WHERE {_tableName}.{field} {_operatorDictionary.GetValueOrDefault(sqlOperator)} '{value}' ");
        }

        _whereCount++;
    }


    public void AddOrderBy(string field, SqlOrderType orderType)
    {
        var orderBy = orderType switch
        {
            SqlOrderType.Ascending => "ASC",
            SqlOrderType.Descending => "DESC",
            _ => throw new ArgumentOutOfRangeException(nameof(orderType), orderType, null)
        };

        _queryBuilder.Append($"ORDER BY {_tableName}.{field} {orderBy} ");
    }

    public void AddOffset(int offset)
    {
        _queryBuilder.Append($"OFFSET {offset} ");
    }

    public void AddLimit(int limit)
    {
        _queryBuilder.Append($"LIMIT {limit} ");
    }

    public string Build()
    {
        return _queryBuilder.ToString();
    }
}