aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Commons.Tests/Crud/SqlCompareHelper.cs
blob: 8f3e5c666c035f8952404f29cf6b03e112fafd06 (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
using System.Text;

namespace CrupestApi.Commons.Crud.Tests;

public class SqlCompareHelper
{
    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 (sql[current] == ';')
            {
                if (wordBuilder is not null)
                {
                    result.Add(wordBuilder.ToString());
                    wordBuilder = null;
                }
                result.Add(";");
            }
            else
            {
                if (wordBuilder is not null)
                {
                    wordBuilder.Append(sql[current]);
                }
                else
                {
                    wordBuilder = new StringBuilder(sql[current]);
                }
            }
        }

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

        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(words, new List<string> { "select", "*", "from", "tablename", "where", "id", "=", "@abcd", ";" });
    }
}