1#include "sql_string_helpers.h"
2
3#include <base/system.h>
4#include <cmath>
5
6void sqlstr::FuzzyString(char *pString, int Size)
7{
8 char *pNewString = new char[Size * 4 - 1];
9 int OutPos = 0;
10
11 for(int i = 0; i < Size; i++)
12 {
13 if(!pString[i])
14 break;
15
16 pNewString[OutPos++] = pString[i];
17 if(pString[i] != '\\' && str_utf8_isstart(c: pString[i + 1]))
18 pNewString[OutPos++] = '%';
19 }
20
21 pNewString[OutPos] = '\0';
22 str_copy(dst: pString, src: pNewString, dst_size: Size);
23 delete[] pNewString;
24}
25
26int sqlstr::EscapeLike(char *pDst, const char *pSrc, int DstSize)
27{
28 int Pos = 0;
29 int DstPos = 0;
30 while(DstPos + 2 < DstSize)
31 {
32 if(pSrc[Pos] == '\0')
33 break;
34 if(pSrc[Pos] == '\\' || pSrc[Pos] == '%' || pSrc[Pos] == '_' || pSrc[Pos] == '[')
35 pDst[DstPos++] = '\\';
36 pDst[DstPos++] = pSrc[Pos++];
37 }
38 pDst[DstPos++] = '\0';
39 return DstPos;
40}
41
42void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString, int Size)
43{
44 if(AgoTime <= 0)
45 {
46 str_copy(dst: pAgoString, src: "moments", dst_size: Size);
47 return;
48 }
49
50 char aBuf[20];
51 const int aTimes[7] =
52 {
53 60 * 60 * 24 * 365,
54 60 * 60 * 24 * 30,
55 60 * 60 * 24 * 7,
56 60 * 60 * 24,
57 60 * 60,
58 60,
59 1};
60 const char aaNames[7][6] =
61 {
62 "year",
63 "month",
64 "week",
65 "day",
66 "hour",
67 "min",
68 "sec"};
69
70 int Seconds = 0;
71 char aName[6];
72 int Count = 0;
73 int i = 0;
74
75 // finding biggest match
76 for(i = 0; i < 7; i++)
77 {
78 Seconds = aTimes[i];
79 str_copy(dst&: aName, src: aaNames[i]);
80
81 Count = std::floor(x: (float)AgoTime / (float)Seconds);
82 if(Count != 0)
83 {
84 break;
85 }
86 }
87
88 if(Count == 1)
89 {
90 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d %s", 1, aName);
91 }
92 else
93 {
94 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d %ss", Count, aName);
95 }
96 str_append(dst: pAgoString, src: aBuf, dst_size: Size);
97
98 if(i + 1 < 7)
99 {
100 // getting second piece now
101 int Seconds2 = aTimes[i + 1];
102 char aName2[6];
103 str_copy(dst&: aName2, src: aaNames[i + 1]);
104
105 // add second piece if it's greater than 0
106 int Count2 = std::floor(x: (float)(AgoTime - (Seconds * Count)) / (float)Seconds2);
107
108 if(Count2 != 0)
109 {
110 if(Count2 == 1)
111 {
112 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: " and %d %s", 1, aName2);
113 }
114 else
115 {
116 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: " and %d %ss", Count2, aName2);
117 }
118 str_append(dst: pAgoString, src: aBuf, dst_size: Size);
119 }
120 }
121}
122