aboutsummaryrefslogtreecommitdiff
path: root/dropped/docker/crupest-api/CrupestApi/CrupestApi.Commons.Tests/Crud/SqlCompareHelper.cs
blob: 72b621890d600ab1f2093825bcc4cecde31ef49a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System.Text;

namespace CrupestApi.Commons.Crud.Tests;

public class SqlCompareHelper
{
    private static List<char> SymbolTokens = new List<char>() { '(', ')', ';' };

    public static List<string> SqlExtractWords(string? sql, bool toLower = true)
    {
        var result = new List<string>();

        if (string.IsNullOrEmpty(sql))
        {
            return result;
        }

        var current = 0;

        StringBuilder? wordBuilder = null;

        while (current < sql.Length)
        {
            if (char.IsWhiteSpace(sql[current]))
            {
                if (wordBuilder is not null)
                {
                    result.Add(wordBuilder.ToString());
                    wordBuilder = null;
                }
            }
            else if (SymbolTokens.Contains(sql[current]))
            {
                if (wordBuilder is not null)
                {
                    result.Add(wordBuilder.ToString());
                    wordBuilder = null;
                }
                result.Add(sql[current].ToString());
            }
            else
            {
                if (wordBuilder is not null)
                {
                    wordBuilder.Append(sql[current]);
                }
                else
                {
                    wordBuilder = new StringBuilder();
                    wordBuilder.Append(sql[current]);
                }
            }
            current++;
        }

        if (wordBuilder is not null)
        {
            result.Add(wordBuilder.ToString());
        }

        if (toLower)
        {
            for (int i = 0; i < result.Count; i++)
            {
                result[i] = result[i].ToLower();
            }
        }

        return result;
    }

    public static bool SqlEqual(string left, string right)
    {
        return SqlExtractWords(left) == SqlExtractWords(right);
    }

    [Fact]
    public void TestSqlExtractWords()
    {
        var sql = "SELECT * FROM TableName WHERE (id = @abcd);";
        var words = SqlExtractWords(sql);

        Assert.Equal(new List<string> { "select", "*", "from", "tablename", "where", "(", "id", "=", "@abcd", ")", ";" }, words);
    }
}