TDSQLForPGODBC同步TDSQL修改

This commit is contained in:
guoshun.du 2025-05-06 10:34:06 +08:00
parent 842e69b733
commit 1bf233b4c8
7 changed files with 255 additions and 63 deletions

View File

@ -8,6 +8,7 @@ namespace SqlSugar.TDSQLForPGODBC
{
public override string GetDbTypeName(string csharpTypeName)
{
csharpTypeName = GetValidCsharpTypeName(csharpTypeName);
if (csharpTypeName == UtilConstants.ByteArrayType.Name)
return "bytea";
if (csharpTypeName.ToLower() == "int32")
@ -26,9 +27,28 @@ namespace SqlSugar.TDSQLForPGODBC
else
return "varchar";
}
private string GetValidCsharpTypeName(string csharpTypeName)
{
if (csharpTypeName?.StartsWith("ora") == true && this.Context.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.Vastbase)
{
csharpTypeName = csharpTypeName.Replace("ora", "");
}
else if (csharpTypeName?.StartsWith("mssql_") == true && this.Context.CurrentConnectionConfig?.MoreSettings?.DatabaseModel == DbType.Vastbase)
{
csharpTypeName = csharpTypeName.Replace("mssql_", "");
}
else if (csharpTypeName?.StartsWith("sys.") == true)
{
csharpTypeName = csharpTypeName.Replace("sys.", "");
}
return csharpTypeName;
}
public override string GetPropertyTypeName(string dbTypeName)
{
dbTypeName = dbTypeName.ToLower();
dbTypeName = GetValidCsharpTypeName(dbTypeName);
var propertyTypes = MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName || it.Key.ToLower() == dbTypeName);
if (propertyTypes == null)
{
@ -37,7 +57,8 @@ namespace SqlSugar.TDSQLForPGODBC
else if (dbTypeName == "xml" || dbTypeName == "string" || dbTypeName == "jsonb" || dbTypeName == "json")
{
return "string";
}else if (dbTypeName == "bpchar")//数据库char datatype 查询出来的时候是 bpchar
}
else if (dbTypeName == "bpchar")//数据库char datatype 查询出来的时候是 bpchar
{
return "char";
}
@ -52,6 +73,10 @@ namespace SqlSugar.TDSQLForPGODBC
var dbTypeName2 = dbTypeName.TrimStart('_');
return MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName2 || it.Key.ToLower() == dbTypeName2).Select(it => it.Value + "[]").First();
}
else if (dbTypeName.EndsWith("geometry") || dbTypeName.EndsWith("geography"))
{
return CSharpDataType.@string.ToString();
}
Check.ThrowNotSupportedException(string.Format(" \"{0}\" Type NotSupported, DbBindProvider.GetPropertyTypeName error.", dbTypeName));
return null;
}
@ -146,7 +171,16 @@ namespace SqlSugar.TDSQLForPGODBC
new KeyValuePair<string, CSharpDataType>("time",CSharpDataType.TimeSpan),
new KeyValuePair<string, CSharpDataType>("public.geometry",CSharpDataType.@object),
new KeyValuePair<string, CSharpDataType>("public.geography",CSharpDataType.@object),
new KeyValuePair<string, CSharpDataType>("inet",CSharpDataType.@object)
new KeyValuePair<string, CSharpDataType>("inet",CSharpDataType.@object),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@int),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@float),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@short),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@byte),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@double),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@long),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@bool),
new KeyValuePair<string, CSharpDataType>("number",CSharpDataType.@decimal),
};
public override List<string> StringThrow
{

View File

@ -30,8 +30,11 @@ namespace SqlSugar.TDSQLForPGODBC
col_description(pclass.oid, pcolumn.ordinal_position) as ColumnDescription,
case when pkey.colname = pcolumn.column_name
then true else false end as IsPrimaryKey,
case when pcolumn.column_default like 'nextval%'
then true else false end as IsIdentity,
CASE
WHEN (current_setting('server_version_num')::INT >= 100000 AND pcolumn.is_identity = 'YES') THEN true
WHEN pcolumn.column_default LIKE 'nextval%' THEN true
ELSE false
END AS IsIdentity,
case when pcolumn.is_nullable = 'YES'
then true else false end as IsNullable
from (select * from pg_tables where upper(tablename) = upper('{0}') and schemaname='" + schema + @"') ptables inner join pg_class pclass
@ -247,6 +250,18 @@ namespace SqlSugar.TDSQLForPGODBC
#endregion
#region Methods
public override bool IsAnyTable(string tableName, bool isCache = true)
{
if (isCache == false)
{
var sql = $" SELECT 1 FROM pg_catalog.pg_tables \r\n WHERE schemaname = '" + GetSchema() + "' \r\n AND Lower(tablename) = '" + tableName.ToLower() + "' ";
return this.Context.Ado.GetInt(sql) > 0;
}
else
{
return base.IsAnyTable(tableName, isCache);
}
}
public override List<string> GetDbTypes()
{
var result = this.Context.Ado.SqlQuery<string>(@"SELECT DISTINCT data_type
@ -382,7 +397,16 @@ WHERE tgrelid = '"+tableName+"'::regclass");
}
var oldDatabaseName = this.Context.Ado.Connection.Database;
var connection = this.Context.CurrentConnectionConfig.ConnectionString;
if (Regex.Matches(connection, oldDatabaseName).Count > 1)
{
var builder = new Npgsql.NpgsqlConnectionStringBuilder(connection);
builder.Database = "postgres";
connection = builder.ConnectionString;
}
else
{
connection = connection.Replace(oldDatabaseName, "postgres");
}
var newDb = new SqlSugarClient(new ConnectionConfig()
{
DbType = this.Context.CurrentConnectionConfig.DbType,
@ -579,6 +603,28 @@ WHERE tgrelid = '"+tableName+"'::regclass");
private string GetSchema()
{
var schema = "public";
var pgSqlIsAutoToLowerSchema = this.Context?.CurrentConnectionConfig?.MoreSettings?.PgSqlIsAutoToLowerSchema == false;
if (pgSqlIsAutoToLowerSchema)
{
if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString, "searchpath=", RegexOptions.IgnoreCase))
{
var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString, @"searchpath\=(\w+)").Groups[1].Value;
if (regValue.HasValue())
{
schema = regValue;
}
}
else if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString, "search path=", RegexOptions.IgnoreCase))
{
var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"search path\=(\w+)").Groups[1].Value;
if (regValue.HasValue())
{
schema = regValue;
}
}
}
else
{
if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), "searchpath="))
{
var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"searchpath\=(\w+)").Groups[1].Value;
@ -595,7 +641,7 @@ WHERE tgrelid = '"+tableName+"'::regclass");
schema = regValue;
}
}
}
return schema;
}
private static void ConvertCreateColumnInfo(DbColumnInfo x)

View File

@ -244,6 +244,12 @@ namespace SqlSugar.TDSQLForPGODBC
{
var parameter = model.Args[0];
var parameter2 = model.Args[1];
var parameter2Info = model.Parameters?.FirstOrDefault(it => it.ParameterName.EqualCase(parameter2.MemberName + ""));
if (parameter2Info != null && parameter2.MemberName?.ToString()?.StartsWith("@MethodConst") == true)
{
parameter2Info.Value = parameter2.MemberValue + "%";
return string.Format(" ({0} like {1} ) ", parameter.MemberName, parameter2.MemberName);
}
return string.Format(" ({0} like concat({1},'%')) ", parameter.MemberName, parameter2.MemberName);
}
@ -251,6 +257,12 @@ namespace SqlSugar.TDSQLForPGODBC
{
var parameter = model.Args[0];
var parameter2 = model.Args[1];
var parameter2Info = model.Parameters?.FirstOrDefault(it => it.ParameterName.EqualCase(parameter2.MemberName + ""));
if (parameter2Info != null && parameter2.MemberName?.ToString()?.StartsWith("@MethodConst") == true)
{
parameter2Info.Value = "%" + parameter2.MemberValue;
return string.Format(" ({0} like {1} ) ", parameter.MemberName, parameter2.MemberName);
}
return string.Format(" ({0} like concat('%',{1}))", parameter.MemberName, parameter2.MemberName);
}
@ -482,6 +494,15 @@ namespace SqlSugar.TDSQLForPGODBC
return $" {model.Args[0].MemberName}::jsonb @> '[\"{model.Args[1].MemberValue}\"]'::jsonb ";
}
}
public override string GetStringJoinSelector(string result, string separator)
{
if (result?.ToLower()?.Contains("distinct") == true)
{
return $"string_agg({result},'{separator}') ";
}
return $"string_agg(({result})::text,'{separator}') ";
}
public override string JsonListObjectAny(MethodCallExpressionModel model)
{
if (UtilMethods.IsNumber(model.Args[2].MemberValue.GetType().Name))

View File

@ -242,6 +242,10 @@ namespace SqlSugar.TDSQLForPGODBC
{
return v.ToString(CultureInfo.InvariantCulture);
}
else if (value is double dou)
{
return dou.ToString(CultureInfo.InvariantCulture);
}
else
{
return N + "'" + value.ToString() + "'";

View File

@ -91,6 +91,10 @@ namespace SqlSugar.TDSQLForPGODBC
{
return v.ToString(CultureInfo.InvariantCulture);
}
else if (value is double dou)
{
return dou.ToString(CultureInfo.InvariantCulture);
}
else
{
return "'" + value.ToString() + "'";
@ -285,3 +289,4 @@ namespace SqlSugar.TDSQLForPGODBC
}
}
}
}

View File

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace SqlSugar.TDSQLForPGODBC
{
@ -11,9 +12,10 @@ namespace SqlSugar.TDSQLForPGODBC
public const char DotChar = '.';
internal const string Space = " ";
internal const char SpaceChar = ' ';
internal const string AssemblyName = "SqlSugar";
internal const string AssemblyName = "SqlSugar.TDSQLForPGODBC";
internal static string ReplaceKey = "{" + Guid.NewGuid() + "}";
internal const string ReplaceCommaKey = "{112A689B-17A1-4A06-9D27-A39EAB8BC3D5}";
internal const string GroupReplaceKey = "{GroupReplaceKey_l33asdysaas1231s}";
internal static Type UShortType = typeof(ushort);
internal static Type ULongType = typeof(ulong);
@ -62,7 +64,7 @@ namespace SqlSugar.TDSQLForPGODBC
typeof(short),
typeof(ushort),
};
//internal static CultureInfo EnCultureInfo = new CultureInfo("en");
internal static string[] DateTypeStringList = new string[]
{
@ -75,5 +77,8 @@ namespace SqlSugar.TDSQLForPGODBC
"Millisecond",
"Date"
};
public static ConstantExpression ExpTrue = Expression.Constant(true);
public static ConstantExpression ExpFalse = Expression.Constant(false);
}
}

View File

@ -18,6 +18,66 @@ namespace SqlSugar.TDSQLForPGODBC
{
public class UtilMethods
{
public static string EscapeLikeValue(ISqlSugarClient db, string value, char wildcard = '%')
{
var dbType = db.CurrentConnectionConfig.DbType;
if (db.CurrentConnectionConfig?.MoreSettings?.DatabaseModel != null)
{
dbType = db.CurrentConnectionConfig.MoreSettings.DatabaseModel.Value;
}
if (string.IsNullOrEmpty(value))
return value;
string wildcardStr = wildcard.ToString();
switch (dbType)
{
// 支持标准 SQL LIKE 转义,通常使用中括号 [] 或反斜杠 \ 进行转义
case DbType.SqlServer:
case DbType.Access:
case DbType.Odbc:
case DbType.TDSQLForPGODBC:
// SQL Server 使用中括号转义 %, _ 等
value = value.Replace("[", "[[]")
.Replace("]", "[]]")
.Replace(wildcardStr, $"[{wildcard}]");
break;
// PostgreSQL 风格数据库,使用反斜杠进行 LIKE 转义
case DbType.PostgreSQL:
case DbType.OpenGauss:
case DbType.TDSQL:
case DbType.GaussDB:
case DbType.GaussDBNative:
// MySQL 和兼容库,使用反斜杠进行转义
case DbType.MySql:
case DbType.MySqlConnector:
case DbType.Tidb:
case DbType.PolarDB:
case DbType.OceanBase:
case DbType.Oracle:
case DbType.OceanBaseForOracle:
case DbType.HG:
case DbType.Dm:
case DbType.GBase:
case DbType.DB2:
case DbType.HANA:
case DbType.GoldenDB:
case DbType.Sqlite:
case DbType.DuckDB:
case DbType.QuestDB:
case DbType.Doris:
case DbType.Xugu:
case DbType.Vastbase:
default:
value = value
.Replace(wildcardStr, "\\\\" + wildcard);
break;
}
return value;
}
public static List<SugarParameter> CopySugarParameters(List<SugarParameter> pars)
{
@ -193,6 +253,14 @@ namespace SqlSugar.TDSQLForPGODBC
var p = ParameterConverter.Invoke(obj, new object[] { value, 100 + index }) as SugarParameter;
return p;
}
internal static object QueryConverter(int index, ISqlSugarClient db, IDataReader dataReader, EntityInfo entity, EntityColumnInfo columnInfo)
{
var type = columnInfo.SqlParameterDbType as Type;
var ParameterConverter = type.GetMethod("QueryConverter").MakeGenericMethod(columnInfo.PropertyInfo.PropertyType);
var obj = Activator.CreateInstance(type);
var p = ParameterConverter.Invoke(obj, new object[] { dataReader, index });
return p;
}
internal static bool IsErrorParameterName(ConnectionConfig connectionConfig, DbColumnInfo columnInfo)
{
return connectionConfig.MoreSettings?.IsCorrectErrorSqlParameterName == true &&
@ -610,6 +678,14 @@ namespace SqlSugar.TDSQLForPGODBC
{
return (char)(bytes)[0];
}
else if (value is DateTime && destinationType == typeof(TimeSpan))
{
value = Convert.ToDateTime(value).TimeOfDay;
}
else if (value is DateTime && destinationType.FullName == "System.TimeOnly")
{
value = Convert.ToDateTime(value).TimeOfDay;
}
var destinationConverter = TypeDescriptor.GetConverter(destinationType);
if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
return destinationConverter.ConvertFrom(null, culture, value);
@ -722,7 +798,8 @@ namespace SqlSugar.TDSQLForPGODBC
DisableQueryWhereColumnRemoveTrim = it.MoreSettings.DisableQueryWhereColumnRemoveTrim,
DatabaseModel = it.MoreSettings.DatabaseModel,
EnableILike = it.MoreSettings.EnableILike,
ClickHouseEnableFinal = it.MoreSettings.ClickHouseEnableFinal
ClickHouseEnableFinal = it.MoreSettings.ClickHouseEnableFinal,
PgSqlIsAutoToLowerSchema = it.MoreSettings.PgSqlIsAutoToLowerSchema
},
SqlMiddle = it.SqlMiddle == null ? null : new SqlMiddle