Skip to content

Commit

Permalink
修正 拼装 sql错误: for update limit x为 limit x for update
Browse files Browse the repository at this point in the history
  • Loading branch information
daijianping authored and daijianping committed Aug 23, 2023
1 parent 11dcb06 commit 1fd787e
Show file tree
Hide file tree
Showing 3 changed files with 143 additions and 62 deletions.
67 changes: 49 additions & 18 deletions XCode/DataAccessLayer/Database/MySql.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ namespace XCode.DataAccessLayer;
internal class MySql : RemoteDb
{
#region 属性

/// <summary>返回数据库类型。</summary>
public override DatabaseType Type => DatabaseType.MySql;

Expand All @@ -33,7 +34,9 @@ protected override DbProviderFactory CreateFactory()

//const String AllowZeroDatetime = "Allow Zero Datetime";
private const String MaxPoolSize = "MaxPoolSize";

private const String Sslmode = "Sslmode";

protected override void OnSetConnectionString(ConnectionStringBuilder builder)
{
base.OnSetConnectionString(builder);
Expand Down Expand Up @@ -63,9 +66,11 @@ protected override void OnGetConnectionString(ConnectionStringBuilder builder)
var version = factory?.GetType().Assembly.GetName().Version;
if (version == null || version.Major >= 8) builder.TryAdd("AllowPublicKeyRetrieval", "true");
}
#endregion

#endregion 属性

#region 方法

/// <summary>创建数据库会话</summary>
/// <returns></returns>
protected override IDbSession OnCreateSession() => new MySqlSession(this);
Expand All @@ -82,9 +87,11 @@ public override Boolean Support(String providerName)

return false;
}
#endregion

#endregion 方法

#region 数据库特性

protected override String ReservedWordsStr => "ACCESSIBLE,ADD,ALL,ALTER,ANALYZE,AND,AS,ASC,ASENSITIVE,BEFORE,BETWEEN,BIGINT,BINARY,BLOB,BOTH,BY,CALL,CASCADE,CASE,CHANGE,CHAR,CHARACTER,CHECK,COLLATE,COLUMN,CONDITION,CONNECTION,CONSTRAINT,CONTINUE,CONTRIBUTORS,CONVERT,CREATE,CROSS,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,CURSOR,DATABASE,DATABASES,DAY_HOUR,DAY_MICROSECOND,DAY_MINUTE,DAY_SECOND,DEC,DECIMAL,DECLARE,DEFAULT,DELAYED,DELETE,DESC,DESCRIBE,DETERMINISTIC,DISTINCT,DISTINCTROW,DIV,DOUBLE,DROP,DUAL,EACH,ELSE,ELSEIF,ENCLOSED,ESCAPED,EXISTS,EXIT,EXPLAIN,FALSE,FETCH,FLOAT,FLOAT4,FLOAT8,FOR,FORCE,FOREIGN,FROM,FULLTEXT,GRANT,GROUP,HAVING,HIGH_PRIORITY,HOUR_MICROSECOND,HOUR_MINUTE,HOUR_SECOND,IF,IGNORE,IN,INDEX,INFILE,INNER,INOUT,INSENSITIVE,INSERT,INT,INT1,INT2,INT3,INT4,INT8,INTEGER,INTERVAL,INTO,IS,ITERATE,JOIN,KEY,KEYS,KILL,LEADING,LEAVE,LEFT,LIKE,LIMIT,LINEAR,LINES,LOAD,LOCALTIME,LOCALTIMESTAMP,LOCK,LONG,LONGBLOB,LONGTEXT,LOOP,LOW_PRIORITY,MATCH,MEDIUMBLOB,MEDIUMINT,MEDIUMTEXT,MIDDLEINT,MINUTE_MICROSECOND,MINUTE_SECOND,MOD,MODIFIES,NATURAL,NOT,NO_WRITE_TO_BINLOG,NULL,NUMERIC,ON,OPTIMIZE,OPTION,OPTIONALLY,OR,ORDER,OUT,OUTER,OUTFILE,PRECISION,PRIMARY,PROCEDURE,PURGE,RANGE,READ,READS,READ_ONLY,READ_WRITE,REAL,REFERENCES,REGEXP,RELEASE,RENAME,REPEAT,REPLACE,REQUIRE,RESTRICT,RETURN,REVOKE,RIGHT,RLIKE,SCHEMA,SCHEMAS,SECOND_MICROSECOND,SELECT,SENSITIVE,SEPARATOR,SET,SHOW,SMALLINT,SPATIAL,SPECIFIC,SQL,SQLEXCEPTION,SQLSTATE,SQLWARNING,SQL_BIG_RESULT,SQL_CALC_FOUND_ROWS,SQL_SMALL_RESULT,SSL,STARTING,STRAIGHT_JOIN,TABLE,TERMINATED,THEN,TINYBLOB,TINYINT,TINYTEXT,TO,TRAILING,TRIGGER,TRUE,UNDO,UNION,UNIQUE,UNLOCK,UNSIGNED,UPDATE,UPGRADE,USAGE,USE,USING,UTC_DATE,UTC_TIME,UTC_TIMESTAMP,VALUES,VARBINARY,VARCHAR,VARCHARACTER,VARYING,WHEN,WHERE,WHILE,WITH,WRITE,X509,XOR,YEAR_MONTH,ZEROFILL," +
"LOG,User,Role,Admin,Rank,Member,Groups,Error,MaxValue,MinValue";

Expand Down Expand Up @@ -130,6 +137,7 @@ public override String FormatValue(IDataColumn field, Object value)
}

private static readonly Char[] _likeKeys = new[] { '\\', '\'', '\"', '%', '_' };

/// <summary>格式化模糊搜索的字符串。处理转义字符</summary>
/// <param name="column">字段</param>
/// <param name="format">格式化字符串</param>
Expand Down Expand Up @@ -194,22 +202,30 @@ public override IDataParameter CreateParameter(String name, Object value, Type t
/// <param name="right"></param>
/// <returns></returns>
public override String StringConcat(String left, String right) => $"concat({(!String.IsNullOrEmpty(left) ? left : "\'\'")},{(!String.IsNullOrEmpty(right) ? right : "\'\'")})";
#endregion

#endregion 数据库特性

#region 跨版本兼容

/// <summary>采用枚举来表示布尔型的数据表。由正向工程赋值</summary>
public ICollection<String> EnumTables { get; } = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
#endregion

#endregion 跨版本兼容
}

/// <summary>MySql数据库</summary>
internal class MySqlSession : RemoteDbSession
{
#region 构造函数
public MySqlSession(IDatabase db) : base(db) { }
#endregion

public MySqlSession(IDatabase db) : base(db)
{
}

#endregion 构造函数

#region 快速查询单表记录数

/// <summary>快速查询单表记录数,大数据量时,稍有偏差。</summary>
/// <param name="tableName"></param>
/// <returns></returns>
Expand All @@ -230,9 +246,11 @@ public override Task<Int64> QueryCountFastAsync(String tableName)
var sql = $"select table_rows from information_schema.tables where table_schema='{db}' and table_name='{tableName}'";
return ExecuteScalarAsync<Int64>(sql);
}
#endregion

#endregion 快速查询单表记录数

#region 基本方法 查询/执行

/// <summary>执行SQL查询,返回记录集</summary>
/// <param name="builder">查询生成器</param>
/// <returns>总记录数</returns>
Expand All @@ -241,7 +259,7 @@ public override DbTable Query(SelectBuilder builder)
if (Transaction != null)
{
builder = builder.Clone();
builder.Limit = " For Update " + builder.Limit;
builder.Limit += " For Update ";
}
var sql = builder.ToString();

Expand All @@ -264,16 +282,18 @@ public override Task<Int64> InsertAndGetIdentityAsync(String sql, CommandType ty
sql += ";Select LAST_INSERT_ID()";
return base.InsertAndGetIdentityAsync(sql, type, ps);
}
#endregion

#endregion 基本方法 查询/执行

#region 批量操作

/*
insert into stat (siteid,statdate,`count`,cost,createtime,updatetime) values
insert into stat (siteid,statdate,`count`,cost,createtime,updatetime) values
(1,'2018-08-11 09:34:00',1,123,now(),now()),
(2,'2018-08-11 09:34:00',1,456,now(),now()),
(3,'2018-08-11 09:34:00',1,789,now(),now()),
(2,'2018-08-11 09:34:00',1,456,now(),now())
on duplicate key update
on duplicate key update
`count`=`count`+values(`count`),cost=cost+values(cost),
updatetime=values(updatetime);
*/
Expand Down Expand Up @@ -320,7 +340,8 @@ public override Int32 Upsert(IDataTable table, IDataColumn[] columns, ICollectio
var sql = GetBatchSql("Insert Into", table, columns, updateColumns, addColumns, list);
return Execute(sql);
}
#endregion

#endregion 批量操作
}

/// <summary>MySql元数据</summary>
Expand All @@ -329,6 +350,7 @@ internal class MySqlMetaData : RemoteDbMetaData
public MySqlMetaData() => Types = _DataTypes;

#region 数据类型

protected override List<KeyValuePair<Type, Type>> FieldTypeMaps
{
get
Expand Down Expand Up @@ -364,9 +386,11 @@ protected override List<KeyValuePair<Type, Type>> FieldTypeMaps
{ typeof(String), new String[] { "VARCHAR({0})", "LONGTEXT", "TEXT", "CHAR({0})", "NCHAR({0})", "NVARCHAR({0})", "SET", "ENUM", "TINYTEXT", "TEXT", "MEDIUMTEXT" } },
{ typeof(Boolean), new String[] { "TINYINT" } },
};
#endregion

#endregion 数据类型

#region 架构

protected override List<IDataTable> OnGetTables(String[] names)
{
var ss = Database.CreateSession();
Expand Down Expand Up @@ -395,6 +419,7 @@ protected override List<IDataTable> OnGetTables(String[] names)
table.DbType = Database.Type;

#region 字段

sql = $"SHOW FULL COLUMNS FROM `{db}`.`{name}`";
var dcs = ss.Query(sql, null);
foreach (var dc in dcs)
Expand Down Expand Up @@ -424,9 +449,11 @@ protected override List<IDataTable> OnGetTables(String[] names)

table.Columns.Add(field);
}
#endregion

#endregion 字段

#region 索引

sql = $"SHOW INDEX FROM `{db}`.`{name}`";
var dis = ss.Query(sql, null);
foreach (var dr2 in dis)
Expand All @@ -444,7 +471,8 @@ protected override List<IDataTable> OnGetTables(String[] names)

table.Indexes.Add(di);
}
#endregion

#endregion 索引

// 修正关系数据
table.Fix();
Expand Down Expand Up @@ -540,9 +568,11 @@ protected override String GetFieldConstraints(IDataColumn field, Boolean onlyDef

return str;
}
#endregion

#endregion 架构

#region 反向工程

protected override Boolean DatabaseExist(String databaseName)
{
var dt = GetSchema(_.Databases, new String[] { databaseName });
Expand Down Expand Up @@ -601,5 +631,6 @@ public override String AddTableDescriptionSQL(IDataTable table)
public override String AddColumnDescriptionSQL(IDataColumn field) =>
// 返回String.Empty表示已经在别的SQL中处理
String.Empty;
#endregion
}

#endregion 反向工程
}
Loading

0 comments on commit 1fd787e

Please sign in to comment.