ZhiYeJianKang_PeiXun/cyqdata-master/SQL/SqlFormat.cs

574 lines
24 KiB
C#
Raw Normal View History

2025-02-20 15:41:53 +08:00
using CYQ.Data.Table;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Data;
namespace CYQ.Data.SQL
{
/// <summary>
/// Sql <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʽ<EFBFBD><CABD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֹ<EFBFBD><D6B9><EFBFBD>)
/// </summary>
internal class SqlFormat
{
/// <summary>
/// Sql<71>ؼ<EFBFBD><D8BC>ִ<EFBFBD><D6B4><EFBFBD>
/// </summary>
public static string Keyword(string name, DataBaseType dalType)
{
if (!string.IsNullOrEmpty(name))
{
name = name.Trim();
if (name.IndexOfAny(new char[] { ' ', '[', ']', '`', '"', '(', ')' }) == -1)
{
string pre = null;
int i = name.LastIndexOf('.');// <20><><EFBFBD>ӿ<EFBFBD><D3BF><EFBFBD>֧<EFBFBD>֣<EFBFBD>demo.dbo.users<72><73>
if (i > 0)
{
string[] items = name.Split('.');
pre = items[0];
name = items[items.Length - 1];
}
switch (dalType)
{
case DataBaseType.Access:
case DataBaseType.Excel:
return "[" + name + "]";
case DataBaseType.MsSql:
case DataBaseType.Sybase:
return (pre == null ? "" : pre + "..") + "[" + name + "]";
case DataBaseType.MySql:
return (pre == null ? "" : pre + ".") + "`" + name + "`";
case DataBaseType.Oracle:
if (AppConfig.DB.IsOracleUpper) { name = name.ToUpper(); if (pre != null) { pre = pre.ToUpper(); } }
return (pre == null ? "" : pre) + name;
case DataBaseType.DB2:
if (AppConfig.DB.IsDB2Upper) { name = name.ToUpper(); if (pre != null) { pre = pre.ToUpper(); } }
return (pre == null ? "" : pre) + name;
case DataBaseType.SQLite:
return "\"" + name + "\"";
case DataBaseType.FireBird:
if (AppConfig.DB.IsFireBirdUpper) { name = name.ToUpper(); if (pre != null) { pre = pre.ToUpper(); } }
return (pre == null ? "" : "\"" + pre + "\".") + "\"" + name + "\"";
case DataBaseType.DaMeng:
if (AppConfig.DB.IsDaMengUpper) { name = name.ToUpper(); if (pre != null) { pre = pre.ToUpper(); } }
return (pre == null ? "" : "\"" + pre + "\".") + "\"" + name + "\"";
case DataBaseType.KingBaseES:
if (AppConfig.DB.IsKingBaseESLower) { name = name.ToLower(); if (pre != null) { pre = pre.ToLower(); } }
return (pre == null ? "" : "\"" + pre + "\".") + "\"" + name + "\"";
case DataBaseType.PostgreSQL:
if (AppConfig.DB.IsPostgreLower) { name = name.ToLower(); }
return "\"" + name + "\"";
case DataBaseType.Txt:
case DataBaseType.Xml:
case DataBaseType.FoxPro:
return NotKeyword(name);
}
}
}
return name;
}
/// <summary>
/// ȥ<><C8A5><EFBFBD>ؼ<EFBFBD><D8BC>ַ<EFBFBD><D6B7><EFBFBD>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string NotKeyword(string name)
{
name = name.Trim();
if (name.IndexOfAny(new char[] { '(', ')' }) == -1 && name.Split(' ').Length == 1)
{
//string pre = string.Empty;
int i = name.LastIndexOf('.');// <20><><EFBFBD>ӿ<EFBFBD><D3BF><EFBFBD>֧<EFBFBD>֣<EFBFBD>demo.dbo.users<72><73>
if (i > 0)
{
// pre = name.Substring(0, i + 1);
name = name.Substring(i + 1);
}
name = name.Trim('[', ']', '`', '"');
}
return name;
}
/// <summary>
/// Sql<71><6C><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD><EFBFBD>ݺ<EFBFBD>Sqlע<6C><EFBFBD><EBB4A6>
/// </summary>
public static string Compatible(object where, DataBaseType dalType, bool isFilterInjection)
{
string text = GetIFieldSql(where);
if (isFilterInjection)
{
text = SqlInjection.Filter(text, dalType);
}
text = SqlCompatible.Format(text, dalType);
return RemoveWhereOneEqualsOne(text);
}
/// <summary>
/// <20>Ƴ<EFBFBD>"where 1=1"
/// </summary>
internal static string RemoveWhereOneEqualsOne(string sql)
{
try
{
sql = sql.Trim();
if (sql == "where 1=1")
{
return string.Empty;
}
if (sql.EndsWith(" and 1=1"))
{
return sql.Substring(0, sql.Length - 8);
}
int i = sql.IndexOf("where 1=1", StringComparison.OrdinalIgnoreCase);
//do
//{
if (i > 0)
{
if (i == sql.Length - 9)//<2F><>where 1=1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{
sql = sql.Substring(0, sql.Length - 10);
}
else if (sql.Substring(i + 10, 8).ToLower() == "order by")
{
sql = sql.Remove(i, 10);//<2F><><EFBFBD><EFBFBD><EFBFBD>ж<EFBFBD><D0B6><EFBFBD><EFBFBD><EFBFBD>
}
// i = sql.IndexOf("where 1=1", StringComparison.OrdinalIgnoreCase);
}
//}
//while (i > 0);
}
catch
{
}
return sql;
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>1=2<><32>SQL<51><4C><EFBFBD><EFBFBD>
/// </summary>
/// <param name="tableName"><3E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͼ<EFBFBD><CDBC><EFBFBD><EFBFBD></param>
/// <returns></returns>
internal static string BuildSqlWithWhereOneEqualsTow(string tableName)
{
tableName = tableName.Trim();
if (tableName[0] == '(' && tableName.IndexOf(')') > -1)
{
int end = tableName.LastIndexOf(')');
tableName = tableName.Substring(1, end - 1);//.Replace("\r\n", "\n").Replace('\n', ' '); <20><><EFBFBD><EFBFBD>ע<EFBFBD>͵Ļ<CDB5><C4BB>С<EFBFBD>
}
if (tableName.Contains(" "))
{
//<2F>ֳ<EFBFBD><D6B3><EFBFBD><EFBFBD><EFBFBD>
string partA = "", partB = "";//<2F>ֳ<EFBFBD><D6B3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD>˼<EFBFBD><CBBC><EFBFBD><EFBFBD>Ӳ<EFBFBD>ѯ<EFBFBD><D1AF><EFBFBD><EFBFBD>
int fromIndex = tableName.Replace("\n", " ").Replace("\r", " ").LastIndexOf(" from ", StringComparison.OrdinalIgnoreCase);
if (fromIndex > -1)
{
partA = tableName.Substring(0, fromIndex);
partB = tableName.Substring(fromIndex);
string[] keys = new string[] { " where ", "\nwhere ", "\nwhere\r", "\nwhere\n" };
if (partB.IndexOf("where", StringComparison.OrdinalIgnoreCase) > -1)
{
foreach (string key in keys)
{
if (partB.IndexOf(key, StringComparison.OrdinalIgnoreCase) > -1)
{
return partA + Regex.Replace(partB, key, " where 1=2 and ", RegexOptions.IgnoreCase);
}
}
}
else if (partA.IndexOf("where", StringComparison.OrdinalIgnoreCase) > -1)//<2F><><EFBFBD><EFBFBD>select * from a where id in(select distinct id from a) <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{
foreach (string key in keys)
{
if (partA.IndexOf(key, StringComparison.OrdinalIgnoreCase) > -1)
{
return Regex.Replace(partA, key, " where 1=2 and ", RegexOptions.IgnoreCase) + partB;
}
}
}
//<2F><><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD>group by
keys = new string[] { " group by", "\ngroup by" };
foreach (string key in keys)
{
if (partB.IndexOf(key, StringComparison.OrdinalIgnoreCase) > -1)
{
string newKey = key.Replace("group", "where 1=2 group");
return partA + Regex.Replace(partB, key, newKey, RegexOptions.IgnoreCase);
}
}
}
return tableName + " where 1=2";
}
return string.Format("select * from {0} where 1=2", tableName);
}
/// <summary>
/// Mysql Bit <20><><EFBFBD>Ͳ<EFBFBD><CDB2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>ֶ<EFBFBD>='0' <20><><EFBFBD><EFBFBD><EFBFBD>ԣ<EFBFBD>
/// </summary>
/// <param name="where"></param>
/// <param name="mdc"></param>
/// <returns></returns>
internal static string FormatMySqlBit(string where, MDataColumn mdc)
{
if (where.Contains("'0'"))
{
foreach (MCellStruct item in mdc)
{
DataGroupType group = DataType.GetGroup(item.SqlType);
if (group == DataGroupType.Number || group == DataGroupType.Bool)//<2F><>ͼģʽ<C4A3><CABD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>bit<69><74>bigint,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{
if (where.IndexOf(item.ColumnName, StringComparison.OrdinalIgnoreCase) > -1)
{
string pattern = @"\s?" + item.ColumnName + @"\s*=\s*'0'";
where = Regex.Replace(where, pattern, " " + item.ColumnName + "=0", RegexOptions.IgnoreCase);
}
}
}
}
return where;
}
internal static string FormatOracleDateTime(string where, MDataColumn mdc)
{
if (where.IndexOf(':') > -1 && where.IndexOfAny(new char[] { '>', '<', '-', '/' }) > -1)//<2F>ж<EFBFBD><D0B6>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD><DAB5>ж<EFBFBD>
{
foreach (MCellStruct item in mdc)
{
if (DataType.GetGroup(item.SqlType) == DataGroupType.Date && where.IndexOf(item.ColumnName, StringComparison.OrdinalIgnoreCase) > -1)
{
string pattern = @"(\s?" + item.ColumnName + @"\s*[><]{1}[=]?\s*)('.{19,23}')";
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
if (reg.IsMatch(where))
{
where = reg.Replace(where, delegate (Match match)
{
if (item.SqlType == SqlDbType.Timestamp)
{
return match.Groups[1].Value + "to_timestamp(" + match.Groups[2].Value + ",'yyyy-MM-dd HH24:MI:ss.ff')";
}
else
{
return match.Groups[1].Value + "to_date(" + match.Groups[2].Value + ",'yyyy-mm-dd hh24:mi:ss')";
}
});
}
}
}
}
return where;
}
internal static List<string> GetTableNamesFromSql(string sql)
{
List<string> nameList = new List<string>();
//<2F><>ȡԭʼ<D4AD><CABC><EFBFBD><EFBFBD>
string[] items = sql.Split(new char[] { ' ', ';', '(', ')', ',' });
if (items.Length == 1) { return nameList; }//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (items.Length > 3) // <20><><EFBFBD>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD>ո<EFBFBD><D5B8><EFBFBD>select * from xxx
{
bool isKeywork = false;
foreach (string item in items)
{
if (!string.IsNullOrEmpty(item))
{
string lowerItem = item.ToLower();
switch (lowerItem)
{
case "from":
case "update":
case "into":
case "join":
case "table":
isKeywork = true;
break;
default:
if (isKeywork)
{
if (item[0] == '(' || item.IndexOf('.') > -1) { isKeywork = false; }
else
{
isKeywork = false;
nameList.Add(NotKeyword(item));
}
}
break;
}
}
}
}
return nameList;
}
#region IField<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// <summary>
/// <20><>̬<EFBFBD>Ķ<EFBFBD>IField<6C>ӿڴ<D3BF><DAB4><EFBFBD>
/// </summary>
public static string GetIFieldSql(object whereObj)
{
//if (whereObj is IField)
//{
// IField filed = whereObj as IField;
// string where = filed.Sql;
// filed.Sql = "";
// return where;
//}
return Convert.ToString(whereObj);
}
#endregion
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݿ<EFBFBD>Ĭ<EFBFBD><C4AC>ֵ<EFBFBD><D6B5>ʽ<EFBFBD><CABD><EFBFBD>ɱ<EFBFBD>׼ֵ<D7BC><D6B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>׼ֵ<D7BC><D6B5>ԭ<EFBFBD>ɸ<EFBFBD><C9B8><EFBFBD><EFBFBD>ݿ<EFBFBD>Ĭ<EFBFBD><C4AC>ֵ
/// </summary>
/// <param name="flag">[0:ת<>ɱ<EFBFBD>׼ֵ],[1:ת<>ɸ<EFBFBD><C9B8><EFBFBD><EFBFBD>ݿ<EFBFBD>ֵ]</param>
/// <returns></returns>
public static string FormatDefaultValue(DataBaseType dalType, object value, int flag, SqlDbType sqlDbType)
{
string defaultValue = Convert.ToString(value).Trim().TrimEnd('\n');//oracle<6C><65><EFBFBD>Դ<EFBFBD>\n<><6E>β
if (dalType != DataBaseType.Access)
{
defaultValue = defaultValue.Replace("GenGUID()", string.Empty);
}
if (defaultValue.Length == 0)
{
return null;
}
DataGroupType group = DataType.GetGroup(sqlDbType);
if (flag == 0)
{
#region ת<EFBFBD><EFBFBD>׼ֵ - <EFBFBD><EFBFBD><EFBFBD><EFBFBD>˫<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>š<EFBFBD>
if (group == DataGroupType.Date)//<2F><><EFBFBD>ڵı<DAB5>׼ֵ
{
return SqlValue.GetDate;
}
else if (group == DataGroupType.Guid)
{
return SqlValue.Guid;
}
switch (dalType)
{
case DataBaseType.MySql://<2F><>ת\' \"<22><><EFBFBD><EFBFBD><EFBFBD>Բ<EFBFBD><D4B2><EFBFBD><EFBFBD><EFBFBD><E6BBBB>
defaultValue = defaultValue.Replace("\\\"", "\"").Replace("\\\'", "\'");
break;
case DataBaseType.Access:
case DataBaseType.SQLite:
defaultValue = defaultValue.Replace("\"\"", "<22><>");
break;
default:
defaultValue = defaultValue.Replace("''", "<22><>");
break;
}
switch (defaultValue.ToLower().Trim('(', ')'))
{
case "newid":
case "guid":
case "sys_guid":
case "genguid":
case "uuid":
return SqlValue.Guid;
}
#endregion
}
else
{
if (defaultValue == SqlValue.Guid)
{
switch (dalType)
{
case DataBaseType.MsSql:
case DataBaseType.Oracle:
case DataBaseType.Sybase:
case DataBaseType.PostgreSQL:
return SqlCompatible.FormatGUID(defaultValue, dalType);
default:
return "";
}
}
}
switch (dalType)
{
case DataBaseType.Access:
if (flag == 0)
{
if (defaultValue[0] == '"' && defaultValue[defaultValue.Length - 1] == '"')
{
defaultValue = defaultValue.Substring(1, defaultValue.Length - 2);
}
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "Now()").Replace("\"", "\"\"");
if (group == DataGroupType.Text)
{
defaultValue = "\"" + defaultValue + "\"";
}
}
break;
case DataBaseType.MsSql:
case DataBaseType.Sybase:
if (flag == 0)
{
if (defaultValue.StartsWith("(") && defaultValue.EndsWith(")"))//<2F><><EFBFBD><EFBFBD> (newid()) <20><>ȥ<EFBFBD><C8A5>()
{
defaultValue = defaultValue.Substring(1, defaultValue.Length - 2);
}
if (defaultValue.StartsWith("N'"))
{
defaultValue = defaultValue.TrimStart('N');
}
defaultValue = defaultValue.Trim('\'');//'(', ')',
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "getdate()").Replace("'", "''");
if (group == DataGroupType.Text)
{
defaultValue = "(N'" + defaultValue + "')";
}
}
break;
case DataBaseType.Oracle:
if (flag == 0)
{
defaultValue = defaultValue.Trim('\'');
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "sysdate").Replace("'", "''");
if (group == DataGroupType.Text)
{
defaultValue = "'" + defaultValue + "'";
}
}
break;
case DataBaseType.MySql:
if (flag == 0)
{
defaultValue = defaultValue.Replace("b'0", "0").Replace("b'1", "1").Trim(' ', '\'');
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "CURRENT_TIMESTAMP").Replace("'", "\\'").Replace("\"", "\\\"");
if (group == DataGroupType.Text)
{
defaultValue = "\"" + defaultValue + "\"";
}
}
break;
case DataBaseType.SQLite:
if (flag == 0)
{
defaultValue = defaultValue.Trim('"');
if (group > (int)DataGroupType.Text)//<2F><><EFBFBD><EFBFBD>һЩ<D2BB><D0A9><EFBFBD><EFBFBD><E6B7B6>д<EFBFBD><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>͵ļ<CDB5><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> '0'
{
defaultValue = defaultValue.Trim('\'');
}
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "CURRENT_TIMESTAMP").Replace("\"", "\"\"");
if (group == DataGroupType.Text)
{
defaultValue = "\"" + defaultValue + "\"";
}
}
break;
case DataBaseType.PostgreSQL:
if (flag == 0)
{
defaultValue = defaultValue.Trim('"');
if (group == DataGroupType.Text)
{
defaultValue = Regex.Split(defaultValue, "::", RegexOptions.IgnoreCase)[0];
}
if (group != DataGroupType.Text)//<2F><><EFBFBD><EFBFBD>һЩ<D2BB><D0A9><EFBFBD><EFBFBD><E6B7B6>д<EFBFBD><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>͵ļ<CDB5><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> '0'
{
defaultValue = defaultValue.Trim('\'');
}
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "now()").Replace("\"", "\"\"");
if (group == DataGroupType.Text)
{
defaultValue = Regex.Split(defaultValue, "::", RegexOptions.IgnoreCase)[0];
defaultValue = "'" + defaultValue.Trim('\'') + "'";
}
else if (group == DataGroupType.Bool) // bool
{
defaultValue = defaultValue.Replace("1", "true").Replace("0", "false");
}
}
break;
case DataBaseType.DB2:
if (flag == 0)
{
defaultValue = defaultValue.Trim(' ', '\'');
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "CURRENT TIMESTAMP");
if (group == DataGroupType.Text)
{
defaultValue = "'" + defaultValue.Replace("'", "''") + "'";
}
}
break;
case DataBaseType.FireBird:
if (flag == 0)
{
defaultValue = defaultValue.Replace("DEFAULT ", "").Trim(' ', '\'');
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "CURRENT_DATE");
if (group == DataGroupType.Text)
{
defaultValue = "'" + defaultValue.Replace("'", "''") + "'";
}
}
break;
case DataBaseType.DaMeng:
if (flag == 0)
{
defaultValue = defaultValue.Trim(' ', '\'');
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "GETDATE()");
if (group == DataGroupType.Text)
{
defaultValue = "'" + defaultValue.Replace("'", "''") + "'";
}
}
break;
case DataBaseType.KingBaseES:
if (flag == 0)
{
defaultValue = defaultValue.Trim(' ', '\'');
}
else
{
defaultValue = defaultValue.Replace(SqlValue.GetDate, "CURRENT_DATE");
if (group == DataGroupType.Text)
{
defaultValue = "'" + defaultValue.Replace("'", "''") + "'";
}
}
break;
}
if (flag == 0)
{
return defaultValue.Replace("<22><>", "\"").Replace("<22><>", "'");
}
return defaultValue;
}
}
}