-
Notifications
You must be signed in to change notification settings - Fork 598
/
AutoSelectHelper.cs
33 lines (28 loc) · 1.36 KB
/
AutoSelectHelper.cs
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
using System.Linq;
using System.Text.RegularExpressions;
using PetaPoco.Core;
namespace PetaPoco.Internal
{
internal static class AutoSelectHelper
{
private static Regex rxSelect = new Regex(@"\A\s*(SELECT|EXECUTE|CALL|WITH|SET|DECLARE)\s",
RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);
private static Regex rxFrom = new Regex(@"\A\s*FROM\s", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);
public static string AddSelectClause<T>(IProvider provider, string sql, IMapper defaultMapper)
{
if (sql.StartsWith(";"))
return sql.Substring(1);
if (!rxSelect.IsMatch(sql))
{
var pd = PocoData.ForType(typeof(T), defaultMapper);
var tableName = provider.EscapeTableName(pd.TableInfo.TableName);
string cols = pd.Columns.Count != 0 ? string.Join(", ", (from c in pd.QueryColumns select tableName + "." + provider.EscapeSqlIdentifier(c)).ToArray()) : "NULL";
if (!rxFrom.IsMatch(sql))
sql = string.Format("SELECT {0} FROM {1} {2}", cols, tableName, sql);
else
sql = string.Format("SELECT {0} {1}", cols, sql);
}
return sql;
}
}
}