You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

309 lines
11 KiB

4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using Apewer.Internals;
  2. using Apewer;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Reflection;
  7. using System.Text;
  8. namespace Apewer.Source
  9. {
  10. /// <summary>表结构。</summary>
  11. [Serializable]
  12. public sealed class TableStructure
  13. {
  14. #region Instance
  15. Type _model = null;
  16. TableAttribute _table = null;
  17. ColumnAttribute _key = null;
  18. ColumnAttribute _flag = null;
  19. ColumnAttribute[] _columns = null;
  20. ColumnAttribute[] _fillable = null;
  21. private TableStructure() { }
  22. /// <summary>使用此结构的记录模型。</summary>
  23. public Type Model { get => _model; }
  24. /// <summary>表特性。</summary>
  25. public TableAttribute Table { get => _table; }
  26. /// <summary>列信息。</summary>
  27. public ColumnAttribute[] Columns { get => _columns; }
  28. /// <summary>可填充的列信息。</summary>
  29. public ColumnAttribute[] Fillable { get => _fillable; }
  30. /// <summary>主键。</summary>
  31. public ColumnAttribute Key { get => _key; }
  32. /// <summary>记录标记。</summary>
  33. public ColumnAttribute Flag { get => _flag; }
  34. /// <summary>从 <see cref="TableStructure"/> 到 Boolean 的隐式转换,判断 <see cref="TableStructure"/> 有效。</summary>
  35. /// <remarks>True:存在有效结构时;<br />False:不存在有效结构。</remarks>
  36. public static implicit operator bool(TableStructure instance)
  37. {
  38. if (instance == null) return false;
  39. if (instance._model == null) return false;
  40. if (instance._columns == null) return false;
  41. return true;
  42. }
  43. #endregion
  44. #region Obsolete
  45. /// <summary>不依赖 Record 公共属性。</summary>
  46. /// <remarks>注意:此属性即将弃用,应改为使用 Table.Independent 属性。</remarks>
  47. public bool Independent { get => _table == null ? false : _table.Independent; }
  48. /// <summary>表的说明信息。</summary>
  49. /// <remarks>注意:此属性即将弃用,应改为使用 Table.Description 属性。</remarks>
  50. public string Description { get => _table == null ? null : _table.Description; }
  51. /// <summary>表特性。</summary>
  52. /// <remarks>注意:此属性即将弃用,应改为使用 Table 属性。</remarks>
  53. public TableAttribute Attribute { get => _table; }
  54. /// <summary>使用模型的所有属性,对缺少 Column 特性的属性使用默认参数的 Column 特性。</summary>
  55. /// <remarks>注意:此属性即将弃用,应改为使用 Table.AllProperties 属性。</remarks>
  56. public bool AllProperties { get => _table == null ? false : _table.AllProperties; }
  57. /// <summary>表名。</summary>
  58. /// <remarks>注意:此属性即将弃用,应改为使用 Table.Name 属性。</remarks>
  59. public string TableName { get => _table == null ? null : _table.Name; }
  60. #endregion
  61. #region TableStructure
  62. private static Dictionary<string, TableStructure> _tsc = new Dictionary<string, TableStructure>();
  63. /// <summary>解析表结构。</summary>
  64. public static TableStructure Parse<T>(bool useCache = true, bool force = false) where T : IRecord => Parse(typeof(T), useCache, force);
  65. /// <summary>解析表结构。</summary>
  66. /// <returns>表结构。类型不可用于表结构时返回 NULL 值。</returns>
  67. public static TableStructure Parse(Type model, bool useCache = true, bool force = false)
  68. {
  69. var type = model;
  70. if (type == null || !type.IsClass || type.IsAbstract) return null;
  71. // 使用缓存。
  72. var cacheKey = type.FullName;
  73. if (force) cacheKey = "[force] " + cacheKey;
  74. if (useCache)
  75. {
  76. lock (_tsc)
  77. {
  78. TableStructure cached;
  79. if (_tsc.TryGetValue(cacheKey, out cached)) return cached;
  80. }
  81. }
  82. // 解析 TableAttribute。
  83. var ta = TableAttribute.Parse(type, useCache, force);
  84. if (!ta && !force) return null;
  85. // 类型。
  86. var isRecord = RuntimeUtility.IsInherits(type, typeof(Record));
  87. var properties = type.GetProperties();
  88. var total = properties.Length;
  89. // 解析 ColumnAttribute。
  90. var key = null as ColumnAttribute;
  91. var flag = null as ColumnAttribute;
  92. var columns = new ColumnAttribute[total];
  93. var columnsCount = 0;
  94. var fillable = new List<ColumnAttribute>(total);
  95. if (total > 0)
  96. {
  97. var caForce = force || (ta ? ta.AllProperties : false);
  98. var addedFields = new List<string>(total);
  99. foreach (var property in properties)
  100. {
  101. var ca = ColumnAttribute.Parse(property, caForce);
  102. if (ca != null)
  103. {
  104. // 检查 field 重复,只保留第一个。
  105. var field = ca.Field;
  106. if (!addedFields.Contains(field))
  107. {
  108. addedFields.Add(field);
  109. columns[columnsCount] = ca;
  110. columnsCount += 1;
  111. if (isRecord)
  112. {
  113. if (property.Name == "Key")
  114. {
  115. key = ca;
  116. if (ta != null && ta.PrimaryKey) ca.SetPrimaryKey();
  117. }
  118. else if (property.Name == "Flag")
  119. {
  120. flag = ca;
  121. }
  122. }
  123. }
  124. // 可查询的列。
  125. fillable.Add(ca);
  126. continue;
  127. }
  128. // 可查询的列。
  129. if (!caForce)
  130. {
  131. ca = ColumnAttribute.Parse(property, caForce);
  132. if (ca) fillable.Add(ca);
  133. }
  134. }
  135. }
  136. if (columnsCount > 0 && columnsCount != columns.Length) columns = columns.Slice(0, columnsCount);
  137. // 排序,将 Key 和 Flag 排在最前。
  138. columns = ColumnAttribute.Sort(columns);
  139. // 返回结果。
  140. var ts = new TableStructure();
  141. ts._table = ta;
  142. ts._key = key;
  143. ts._flag = flag;
  144. ts._columns = columns;
  145. ts._model = model;
  146. ts._fillable = fillable.ToArray();
  147. // 加入缓存。
  148. if (useCache)
  149. {
  150. lock (_tsc)
  151. {
  152. if (!_tsc.ContainsKey(cacheKey)) _tsc.Add(cacheKey, ts);
  153. }
  154. }
  155. return ts;
  156. }
  157. #endregion
  158. #region TableAttribute
  159. // 限定表名称/列名称。
  160. static string RestrictName(string name, bool underline = false, bool english = false)
  161. {
  162. if (string.IsNullOrEmpty(name)) return null;
  163. var str = name;
  164. // 限定名称仅使用英文和数字。
  165. if (english)
  166. {
  167. const string available = "_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  168. var chars = new ArrayBuilder<char>();
  169. var strChars = str.ToCharArray();
  170. var strLength = strChars.Length > 255 ? 255 : strChars.Length;
  171. for (var i = 0; i < strLength; i++)
  172. {
  173. if (available.IndexOf(strChars[i]) > -1) chars.Add(strChars[i]);
  174. }
  175. str = new string(chars.Export());
  176. }
  177. // 以下划线开始。
  178. if (underline)
  179. {
  180. if (!str.StartsWith("_")) str = TextUtility.Merge("_", str);
  181. }
  182. return str;
  183. }
  184. static IDataParameter CreateParameter(object record, ColumnAttribute ca, Func<Parameter, IDataParameter> callback)
  185. {
  186. var property = ca.Property;
  187. if (property == null) return null;
  188. var getter = property.GetGetMethod();
  189. if (getter == null) return null;
  190. var value = getter.Invoke(record, null);
  191. if (ca.Type == ColumnType.Bytes || ca.Type == ColumnType.Integer || ca.Type == ColumnType.Float)
  192. {
  193. return callback(new Parameter(ca.Field, value, ca.Type, ca.Length));
  194. }
  195. if (ca.Type == ColumnType.DateTime)
  196. {
  197. return callback(new Parameter(ca.Field, value, ca.Type, 0));
  198. }
  199. if (property.PropertyType.Equals(typeof(String)))
  200. {
  201. var text = value as string;
  202. if (text == null) text = "";
  203. if (ca.Length > 0)
  204. {
  205. switch (ca.Type)
  206. {
  207. case ColumnType.VarChar:
  208. case ColumnType.NVarChar:
  209. text = TextUtility.Left(text, ca.Length);
  210. break;
  211. case ColumnType.VarChar191:
  212. case ColumnType.NVarChar191:
  213. text = TextUtility.Left(text, 191);
  214. break;
  215. }
  216. }
  217. return callback(new Parameter(ca.Field, text, ca.Type, ca.Length));
  218. }
  219. var defaultText = (value == null) ? TextUtility.Empty : value.ToString();
  220. return callback(new Parameter(ca.Field, defaultText, ca.Type, ca.Length));
  221. }
  222. /// <summary>生成 IDataParameter 列表,用于 Insert 和 Update 方法。</summary>
  223. public IDataParameter[] CreateParameters(object record, Func<Parameter, IDataParameter> callback, IEnumerable<string> excludeds)
  224. {
  225. if (record == null || callback == null) return null;
  226. var list = new List<IDataParameter>(_columns.Length);
  227. foreach (var ca in Columns)
  228. {
  229. if (ca == null) continue;
  230. var parameter = CreateParameter(record, ca, callback);
  231. if (parameter == null) continue;
  232. var add = true;
  233. if (excludeds != null)
  234. {
  235. var lower = parameter.ParameterName.ToLower();
  236. foreach (var excluded in excludeds)
  237. {
  238. if (string.IsNullOrEmpty(excluded)) continue;
  239. if (lower == excluded.ToLower())
  240. {
  241. add = false;
  242. break;
  243. }
  244. }
  245. }
  246. if (add) list.Add(parameter);
  247. }
  248. return list.ToArray();
  249. }
  250. #endregion
  251. }
  252. }