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.

336 lines
12 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 = GetProperties(type);
  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. // 获取属性,基类的属性排在前面。
  158. static PropertyInfo[] GetProperties(Type type)
  159. {
  160. if (type == null) throw new ArgumentNullException(nameof(type));
  161. // 需要获取属性的类型。
  162. var types = new List<Type>();
  163. {
  164. var target = type;
  165. while (true)
  166. {
  167. if (target.Equals(RuntimeUtility.ObjectType)) break;
  168. types.Add(target);
  169. target = target.BaseType;
  170. }
  171. }
  172. // 所有属性。
  173. var list = new List<PropertyInfo>();
  174. for (var i = types.Count - 1; i >= 0; i--)
  175. {
  176. var properties = types[i].GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  177. list.Add(properties);
  178. }
  179. return list.ToArray();
  180. }
  181. #endregion
  182. #region TableAttribute
  183. // 限定表名称/列名称。
  184. static string RestrictName(string name, bool underline = false, bool english = false)
  185. {
  186. if (string.IsNullOrEmpty(name)) return null;
  187. var str = name;
  188. // 限定名称仅使用英文和数字。
  189. if (english)
  190. {
  191. const string available = "_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  192. var chars = new ArrayBuilder<char>();
  193. var strChars = str.ToCharArray();
  194. var strLength = strChars.Length > 255 ? 255 : strChars.Length;
  195. for (var i = 0; i < strLength; i++)
  196. {
  197. if (available.IndexOf(strChars[i]) > -1) chars.Add(strChars[i]);
  198. }
  199. str = new string(chars.Export());
  200. }
  201. // 以下划线开始。
  202. if (underline)
  203. {
  204. if (!str.StartsWith("_")) str = TextUtility.Merge("_", str);
  205. }
  206. return str;
  207. }
  208. static IDataParameter CreateParameter(object record, ColumnAttribute ca, Func<Parameter, IDataParameter> callback)
  209. {
  210. var property = ca.Property;
  211. if (property == null) return null;
  212. var getter = property.GetGetMethod();
  213. if (getter == null) return null;
  214. var value = getter.Invoke(record, null);
  215. if (ca.Type == ColumnType.Bytes || ca.Type == ColumnType.Integer || ca.Type == ColumnType.Float)
  216. {
  217. return callback(new Parameter(ca.Field, value, ca.Type, ca.Length));
  218. }
  219. if (ca.Type == ColumnType.DateTime)
  220. {
  221. return callback(new Parameter(ca.Field, value, ca.Type, 0));
  222. }
  223. if (property.PropertyType.Equals(typeof(String)))
  224. {
  225. var text = value as string;
  226. if (text == null) text = "";
  227. if (ca.Length > 0)
  228. {
  229. switch (ca.Type)
  230. {
  231. case ColumnType.VarChar:
  232. case ColumnType.NVarChar:
  233. text = TextUtility.Left(text, ca.Length);
  234. break;
  235. case ColumnType.VarChar191:
  236. case ColumnType.NVarChar191:
  237. text = TextUtility.Left(text, 191);
  238. break;
  239. }
  240. }
  241. return callback(new Parameter(ca.Field, text, ca.Type, ca.Length));
  242. }
  243. var defaultText = (value == null) ? TextUtility.Empty : value.ToString();
  244. return callback(new Parameter(ca.Field, defaultText, ca.Type, ca.Length));
  245. }
  246. /// <summary>生成 IDataParameter 列表,用于 Insert 和 Update 方法。</summary>
  247. public IDataParameter[] CreateParameters(object record, Func<Parameter, IDataParameter> callback, IEnumerable<string> excludeds)
  248. {
  249. if (record == null || callback == null) return null;
  250. var list = new List<IDataParameter>(_columns.Length);
  251. foreach (var ca in Columns)
  252. {
  253. if (ca == null) continue;
  254. var parameter = CreateParameter(record, ca, callback);
  255. if (parameter == null) continue;
  256. var add = true;
  257. if (excludeds != null)
  258. {
  259. var lower = parameter.ParameterName.ToLower();
  260. foreach (var excluded in excludeds)
  261. {
  262. if (string.IsNullOrEmpty(excluded)) continue;
  263. if (lower == excluded.ToLower())
  264. {
  265. add = false;
  266. break;
  267. }
  268. }
  269. }
  270. if (add) list.Add(parameter);
  271. }
  272. return list.ToArray();
  273. }
  274. #endregion
  275. }
  276. }