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.

583 lines
26 KiB

4 years ago
4 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
4 years ago
4 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
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 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
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
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
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 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
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
3 years ago
4 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
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
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
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
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
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
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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. namespace Apewer.Source
  5. {
  6. /// <summary>数据库客户端基类。</summary>
  7. public abstract class DbClient : IDbClient
  8. {
  9. /// <summary></summary>
  10. public virtual Logger Logger { get; set; }
  11. /// <summary></summary>
  12. internal DbClient(Timeout timeout)
  13. {
  14. _timeout = timeout ?? Timeout.Default;
  15. }
  16. #region Connection
  17. Timeout _timeout = null;
  18. IDbConnection _conn = null;
  19. /// <summary></summary>
  20. internal protected object Locker = new object();
  21. /// <summary></summary>
  22. public Timeout Timeout { get => _timeout; set => _timeout = value ?? Timeout.Default; }
  23. /// <summary>获取当前的 SqlConnection 对象。</summary>
  24. public IDbConnection Connection { get => _conn; }
  25. /// <summary></summary>
  26. public bool Online { get => _conn == null ? false : (_conn.State == ConnectionState.Open); }
  27. /// <summary>连接字符串。</summary>
  28. public abstract string ConnectionString { get; }
  29. /// <summary>连接数据库,若未连接则尝试连接,获取连接成功的状态。</summary>
  30. public string Connect()
  31. {
  32. if (_conn == null) _conn = GetConnection();
  33. if (_conn.State == ConnectionState.Open) return null;
  34. try
  35. {
  36. _conn.Open();
  37. if (_conn.State == ConnectionState.Open) return null;
  38. var message = $"连接后状态为 {_conn.State},无法验证打开状态。";
  39. Logger.Error(this, "Connect", message);
  40. return "连接失败," + message;
  41. }
  42. catch (Exception ex)
  43. {
  44. Logger.Error(this, "Connect", ex.Message);
  45. Close();
  46. return ex.Message;
  47. }
  48. }
  49. /// <summary>更改已打开的数据库。</summary>
  50. public string Change(string store)
  51. {
  52. if (store.IsEmpty()) return "未指定数据名称。";
  53. var connect = Connect();
  54. if (connect.NotEmpty()) return connect;
  55. try
  56. {
  57. Connection.ChangeDatabase(store);
  58. return null;
  59. }
  60. catch (Exception ex)
  61. {
  62. Logger.Error(this, "Change", ex.Message);
  63. return ex.Message();
  64. }
  65. }
  66. /// <summary>关闭连接,并释放对象所占用的系统资源。</summary>
  67. public virtual void Close()
  68. {
  69. if (_conn != null)
  70. {
  71. if (_transaction != null)
  72. {
  73. if (_autocommit) Commit();
  74. else Rollback();
  75. _transaction = null;
  76. }
  77. try { ClearPool(); } catch { }
  78. try { _conn.Close(); } catch { }
  79. }
  80. }
  81. /// <summary>关闭连接,释放对象所占用的系统资源,并清除连接信息。</summary>
  82. public virtual void Dispose()
  83. {
  84. Close();
  85. }
  86. /// <summary>清理连接池,释放当前连接。</summary>
  87. protected virtual void ClearPool(bool all = false) { }
  88. #endregion
  89. #region Transaction
  90. private IDbTransaction _transaction = null;
  91. private bool _autocommit = false;
  92. /// <summary>获取已启动的事务。</summary>
  93. public IDbTransaction Transaction { get => _transaction; }
  94. string Begin(bool commit, Class<IsolationLevel> isolation)
  95. {
  96. if (_transaction != null) return "已存在未完成的事务,无法再次启动。";
  97. var connect = Connect();
  98. if (connect.NotEmpty()) return $"无法启动事务:连接失败。(${connect})";
  99. try
  100. {
  101. _transaction = isolation ? _conn.BeginTransaction(isolation.Value) : _conn.BeginTransaction();
  102. _autocommit = commit;
  103. return null;
  104. }
  105. catch (Exception ex)
  106. {
  107. Logger.Error(this, "Begin", ex.Message());
  108. return ex.Message();
  109. }
  110. }
  111. /// <summary>
  112. /// <para>使用默认的事务锁定行为启动事务。</para>
  113. /// <para>Chaos<br />无法覆盖隔离级别更高的事务中的挂起的更改。</para>
  114. /// <para>ReadCommitted<br />在正在读取数据时保持共享锁,以避免脏读,但是在事务结束之前可以更改数据,从而导致不可重复的读取或幻像数据。</para>
  115. /// <para>ReadUncommitted<br />可以进行脏读,意思是说,不发布共享锁,也不接受独占锁。</para>
  116. /// <para>RepeatableRead<br />在查询中使用的所有数据上放置锁,以防止其他用户更新这些数据。 防止不可重复的读取,但是仍可以有幻像行。</para>
  117. /// <para>Serializable<br />在 System.Data.DataSet 上放置范围锁,以防止在事务完成之前由其他用户更新行或向数据集中插入行。</para>
  118. /// <para>Snapshot<br />通过在一个应用程序正在修改数据时存储另一个应用程序可以读取的相同数据版本来减少阻止。 表示您无法从一个事务中看到在其他事务中进行的更改,即便重新查询也是如此。</para>
  119. /// <para>Unspecified = -1<br />正在使用与指定隔离级别不同的隔离级别,但是无法确定该级别。</para>
  120. /// </summary>
  121. /// <param name="commit">在连接的生命周期结束时未结束事务,指定 TRUE 将自动提交,指定 FALSE 将自动回滚。</param>
  122. public string Begin(bool commit = false) => Begin(commit, null);
  123. /// <summary>
  124. /// <para>使用指定的事务锁定行为启动事务。</para>
  125. /// <para>Chaos<br />无法覆盖隔离级别更高的事务中的挂起的更改。</para>
  126. /// <para>ReadCommitted<br />在正在读取数据时保持共享锁,以避免脏读,但是在事务结束之前可以更改数据,从而导致不可重复的读取或幻像数据。</para>
  127. /// <para>ReadUncommitted<br />可以进行脏读,意思是说,不发布共享锁,也不接受独占锁。</para>
  128. /// <para>RepeatableRead<br />在查询中使用的所有数据上放置锁,以防止其他用户更新这些数据。 防止不可重复的读取,但是仍可以有幻像行。</para>
  129. /// <para>Serializable<br />在 System.Data.DataSet 上放置范围锁,以防止在事务完成之前由其他用户更新行或向数据集中插入行。</para>
  130. /// <para>Snapshot<br />通过在一个应用程序正在修改数据时存储另一个应用程序可以读取的相同数据版本来减少阻止。 表示您无法从一个事务中看到在其他事务中进行的更改,即便重新查询也是如此。</para>
  131. /// <para>Unspecified = -1<br />正在使用与指定隔离级别不同的隔离级别,但是无法确定该级别。</para>
  132. /// </summary>
  133. /// <param name="commit">在连接的生命周期结束时未结束事务,指定 TRUE 将自动提交,指定 FALSE 将自动回滚。</param>
  134. /// <param name="isolation">指定事务锁定行为,不指定时将使用默认值。</param>
  135. public string Begin(bool commit, IsolationLevel isolation) => Begin(commit, new Class<IsolationLevel>(isolation));
  136. /// <summary>提交事务。</summary>
  137. public string Commit()
  138. {
  139. if (_transaction == null) return "事务不存在。";
  140. try
  141. {
  142. _transaction.Commit();
  143. RuntimeUtility.Dispose(_transaction);
  144. _transaction = null;
  145. return null;
  146. }
  147. catch (Exception ex)
  148. {
  149. RuntimeUtility.Dispose(_transaction);
  150. _transaction = null;
  151. Logger.Error(this, "Commit", ex.Message());
  152. return ex.Message();
  153. }
  154. }
  155. /// <summary>从挂起状态回滚事务。</summary>
  156. public string Rollback()
  157. {
  158. if (_transaction == null) return "事务不存在。";
  159. try
  160. {
  161. _transaction.Rollback();
  162. RuntimeUtility.Dispose(_transaction);
  163. _transaction = null;
  164. return null;
  165. }
  166. catch (Exception ex)
  167. {
  168. RuntimeUtility.Dispose(_transaction);
  169. _transaction = null;
  170. Logger.Error(this, "Rollback", ex.Message());
  171. return ex.Message();
  172. }
  173. }
  174. #endregion
  175. #region ADO
  176. /// <summary>查询。</summary>
  177. /// <param name="sql">SQL 语句。</param>
  178. /// <param name="parameters">为 SQL 语句提供的参数。</param>
  179. public IQuery Query(string sql, IEnumerable<IDataParameter> parameters = null)
  180. {
  181. if (TextUtility.IsEmpty(sql)) return new Query(false, "语句无效。");
  182. var connected = Connect();
  183. if (connected.NotEmpty()) return new Query(false, connected);
  184. lock (Locker)
  185. {
  186. try
  187. {
  188. using (var command = _conn.CreateCommand())
  189. {
  190. command.Connection = _conn;
  191. if (_timeout != null) command.CommandTimeout = Timeout.Query;
  192. command.CommandText = sql;
  193. if (_transaction != null) command.Transaction = _transaction;
  194. if (parameters != null)
  195. {
  196. foreach (var parameter in parameters)
  197. {
  198. if (parameter != null) command.Parameters.Add(parameter);
  199. }
  200. }
  201. var ex = null as Exception;
  202. var da = null as IDataAdapter;
  203. try { da = CreateDataAdapter(command); }
  204. catch (Exception adapterEx) { ex = adapterEx; }
  205. if (ex != null)
  206. {
  207. Logger.Error(this, "Query", ex.Message, sql);
  208. return new Query(ex);
  209. }
  210. using (var ds = new DataSet())
  211. {
  212. da.Fill(ds);
  213. if (ds.Tables.Count > 0)
  214. {
  215. var tables = new DataTable[ds.Tables.Count];
  216. ds.Tables.CopyTo(tables, 0);
  217. Logger.Info(this, "Query", sql);
  218. return new Query(tables, true);
  219. }
  220. else
  221. {
  222. Logger.Error(this, "Query", "查询结果不包含任何数据表。", sql);
  223. return new Query(false, "查询结果不包含任何数据表。");
  224. }
  225. }
  226. }
  227. }
  228. catch (Exception exception)
  229. {
  230. Logger.Error(this, "Query", exception.Message, sql);
  231. return new Query(exception);
  232. }
  233. }
  234. }
  235. /// <summary>输出查询结果的首列数据。</summary>
  236. /// <exception cref="SqlException"></exception>
  237. protected string[] QueryStrings(string sql, string[] excluded = null)
  238. {
  239. if (Connect().NotEmpty()) return new string[0];
  240. using (var query = Query(sql))
  241. {
  242. if (!query.Success) throw new SqlException(query, sql);
  243. var rows = query.Rows;
  244. var list = new List<string>(rows);
  245. for (int r = 0; r < query.Rows; r++)
  246. {
  247. var cell = query.Text(r, 0);
  248. if (TextUtility.IsEmpty(cell)) continue;
  249. if (excluded != null && excluded.Contains(cell)) continue;
  250. list.Add(cell);
  251. }
  252. return list.ToArray();
  253. }
  254. }
  255. /// <summary>执行。</summary>
  256. /// <param name="sql">SQL 语句。</param>
  257. /// <param name="parameters">为 SQL 语句提供的参数。</param>
  258. /// <param name="autoTransaction">自动启动事务。</param>
  259. public IExecute Execute(string sql, IEnumerable<IDataParameter> parameters = null, bool autoTransaction = false)
  260. {
  261. if (TextUtility.IsEmpty(sql)) return new Execute(false, "语句无效。");
  262. lock (Locker)
  263. {
  264. var connected = Connect();
  265. if (connected.NotEmpty()) return new Execute(false, connected);
  266. var tempTran = _transaction == null && autoTransaction;
  267. if (tempTran) Begin();
  268. try
  269. {
  270. using (var command = _conn.CreateCommand())
  271. {
  272. command.Connection = _conn;
  273. if (_transaction != null) command.Transaction = _transaction;
  274. if (Timeout != null) command.CommandTimeout = Timeout.Execute;
  275. command.CommandText = sql;
  276. if (parameters != null)
  277. {
  278. foreach (var parameter in parameters)
  279. {
  280. if (parameter != null) command.Parameters.Add(parameter);
  281. }
  282. }
  283. var rows = command.ExecuteNonQuery();
  284. if (tempTran) Commit(); // todo 此处应该检查事务提交产生的错误。
  285. Logger.Info(this, "Execute", sql);
  286. return new Execute(true, rows);
  287. }
  288. }
  289. catch (Exception exception)
  290. {
  291. Logger.Error(this, "Execute", exception.Message, sql);
  292. if (tempTran) Rollback();
  293. return new Execute(exception);
  294. }
  295. }
  296. }
  297. /// <summary>查询数据库中的所有表名。</summary>
  298. public abstract string[] TableNames();
  299. /// <summary>查询数据库实例中的所有数据库名。</summary>
  300. public abstract string[] StoreNames();
  301. /// <summary>查询表中的所有列名。</summary>
  302. public abstract string[] ColumnNames(string tableName);
  303. #endregion
  304. #region Parameter
  305. /// <summary>创建参数。</summary>
  306. /// <exception cref="ArgumentNullException"></exception>
  307. public IDataParameter Parameter(string name, object value)
  308. {
  309. if (name.IsEmpty()) throw new ArgumentNullException(nameof(name));
  310. var p = CreateParameter();
  311. p.ParameterName = name;
  312. p.Value = value ?? DBNull.Value;
  313. return p;
  314. }
  315. /// <summary>创建参数。</summary>
  316. /// <exception cref="ArgumentNullException"></exception>
  317. public IDataParameter Parameter(string name, object value, DbType type)
  318. {
  319. if (name.IsEmpty()) throw new ArgumentNullException(nameof(name));
  320. var p = CreateParameter();
  321. p.ParameterName = name;
  322. p.Value = value ?? DBNull.Value;
  323. p.DbType = type;
  324. return p;
  325. }
  326. #endregion
  327. #region ORM
  328. /// <summary>检查数据模型结构,存在异常时抛出异常。</summary>
  329. /// <exception cref="ArgumentNullException"></exception>
  330. /// <exception cref="ModelException"></exception>
  331. protected static TableStructure Parse(Type model)
  332. {
  333. if (model == null) throw new ArgumentNullException(nameof(model), "数据模型类型无效。");
  334. var ts = TableStructure.Parse(model);
  335. if (ts == null) throw ModelException.InvalidStructure(model);
  336. if (ts.TableName.IsEmpty()) throw ModelException.InvalidTableName(ts.Model);
  337. if (ts.Key == null || ts.Key.Field.IsEmpty()) throw ModelException.MissingKey(ts.Model);
  338. if (ts.Flag == null || ts.Flag.Field.IsEmpty()) throw ModelException.MissingFlag(ts.Model);
  339. return ts;
  340. }
  341. /// <summary>初始化指定类型,以创建表或增加字段。</summary>
  342. /// <param name="table">指定新的表名。</param>
  343. /// <returns>错误信息。当成功时候返回空字符串。</returns>
  344. public string Initialize<T>(string table = null) where T : class, new() => Initialize(typeof(T), table);
  345. /// <summary>初始化指定类型,以创建表或增加字段。</summary>
  346. /// <param name="model">要初始化的类型。</param>
  347. /// <param name="table">指定新的表名。</param>
  348. /// <returns>错误信息。当成功时候返回空字符串。</returns>
  349. public string Initialize(Type model, string table = null)
  350. {
  351. if (model == null) return "参数 model 无效。";
  352. if (!model.IsClass) return $"类型 <{model.FullName}> 不是类。";
  353. if (model.IsAbstract) return $"类型 <{model.FullName}> 是抽象类。";
  354. if (!RuntimeUtility.CanNew(model)) return $"类型 <{model.FullName}> 无法创建新实例。";
  355. var structure = TableStructure.Parse(model);
  356. if (structure == null) return "无法解析记录模型。";
  357. // 连接数据库。
  358. var connect = Connect();
  359. if (connect.NotEmpty()) return connect;
  360. return Initialize(structure, table);
  361. }
  362. /// <summary></summary>
  363. protected abstract string Initialize(TableStructure structure, string table = null);
  364. /// <summary>插入记录。</summary>
  365. /// <param name="record">要插入的记录实体。</param>
  366. /// <param name="table">插入到指定表。当不指定时,由 record 类型决定。</param>
  367. /// <param name="adjust">调整数据模型,补充缺少的属性。</param>
  368. /// <returns>错误信息。当成功时候返回空字符串。</returns>
  369. public abstract string Insert(object record, string table = null, bool adjust = true);
  370. /// <summary>使用指定语句查询,获取查询结果。</summary>
  371. /// <param name="model">目标记录的类型。</param>
  372. /// <param name="sql">要执行的 SQL 语句。</param>
  373. /// <param name="parameters">为 SQL 语句提供的参数。</param>
  374. /// <exception cref="ArgumentNullException"></exception>
  375. /// <exception cref="ArgumentException"></exception>
  376. /// <exception cref="ModelException"></exception>
  377. /// <exception cref="SqlException"></exception>
  378. public object[] Query(Type model, string sql, IEnumerable<IDataParameter> parameters = null)
  379. {
  380. if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql), "SQL 语句无效。");
  381. using (var query = Query(sql, parameters))
  382. {
  383. if (!query.Success) throw new SqlException(query, sql);
  384. return SourceUtility.Fill(query, model);
  385. }
  386. }
  387. /// <summary>使用指定语句查询,获取查询结果。</summary>
  388. /// <param name="sql">要执行的 SQL 语句。</param>
  389. /// <param name="parameters">为 SQL 语句提供的参数。</param>
  390. /// <exception cref="ArgumentNullException"></exception>
  391. /// <exception cref="ArgumentException"></exception>
  392. /// <exception cref="ModelException"></exception>
  393. /// <exception cref="SqlException"></exception>
  394. public T[] Query<T>(string sql, IEnumerable<IDataParameter> parameters = null) where T : class, new() => Query(typeof(T), sql, parameters).As<object, T>();
  395. #endregion
  396. #region ORM: Record
  397. /// <summary>更新记录。</summary>
  398. /// <param name="record">要更新的记录实体。</param>
  399. /// <param name="table">更新指定的表。当不指定时,由 record 类型决定。</param>
  400. /// <param name="adjust">调整数据模型,补充缺少的属性。</param>
  401. /// <returns>错误信息。当成功时候返回空字符串。</returns>
  402. public abstract string Update(IRecord record, string table = null, bool adjust = true);
  403. /// <summary>生成用于 Keys 方法的 SQL 语句。</summary>
  404. protected abstract string Keys(string tableName, string keyField, string flagField, long flagValue);
  405. /// <summary>获取指定类型的主键,按 Flag 属性筛选。</summary>
  406. /// <param name="model">要查询的类型。</param>
  407. /// <param name="flag">要求目标记录具有的 Flag 属性,当指定 0 时忽略此要求。</param>
  408. /// <exception cref="ArgumentNullException"></exception>
  409. /// <exception cref="ModelException"></exception>
  410. /// <exception cref="SqlException"></exception>
  411. public string[] Keys(Type model, long flag = 0)
  412. {
  413. var ts = Parse(model);
  414. var sql = Keys(ts.TableName, ts.Key.Field, ts.Flag.Field, flag);
  415. return QueryStrings(sql);
  416. }
  417. /// <summary>获取指定类型的主键,按 Flag 属性筛选。</summary>
  418. /// <param name="flag">要求目标记录具有的 Flag 属性,当指定 0 时忽略此要求。</param>
  419. /// <exception cref="ModelException"></exception>
  420. /// <exception cref="SqlException"></exception>
  421. public string[] Keys<T>(long flag = 0) where T : class, IRecord, new() => Keys(typeof(T), flag);
  422. /// <summary>生成用于 Get 方法的 SQL 语句。</summary>
  423. protected abstract string Get(string tableName, string keyField, string keyValue, string flagField, long flagValue);
  424. /// <summary>获取具有指定 Key 的记录,并要求记录具有指定的 Flag 属性。</summary>
  425. /// <param name="model">目标记录的类型。</param>
  426. /// <param name="key">目标记录的主键。</param>
  427. /// <param name="flag">要求目标记录具有的 Flag 属性,当指定 0 时忽略此要求。</param>
  428. /// <exception cref="ArgumentNullException"></exception>
  429. /// <exception cref="ModelException"></exception>
  430. /// <exception cref="SqlException"></exception>
  431. public object Get(Type model, string key, long flag = 0)
  432. {
  433. if (model == null) throw new ArgumentNullException(nameof(model));
  434. var ts = TableStructure.Parse(model);
  435. if (ts == null) throw new ModelException($"无法解析类型 {model.Name}。", model);
  436. key = key.SafeKey();
  437. if (key.IsEmpty()) return null;
  438. var sql = Get(ts.TableName, ts.Key.Field, key, ts.Flag.Field, flag);
  439. var records = Query(model, sql, null);
  440. return records.First();
  441. }
  442. /// <summary>获取具有指定 Key 的记录,并要求记录具有指定的 Flag 属性。</summary>
  443. /// <param name="key">目标记录的主键。</param>
  444. /// <param name="flag">要求目标记录具有的 Flag 属性,当指定 0 时忽略此要求。</param>
  445. /// <exception cref="ModelException"></exception>
  446. /// <exception cref="SqlException"></exception>
  447. public T Get<T>(string key, long flag = 0) where T : class, IRecord, new() => Get(typeof(T), key, flag) as T;
  448. /// <summary>生成用于 List 方法的 SQL 语句。</summary>
  449. protected abstract string List(string tableName, string flagField, long flagValue);
  450. /// <summary>查询所有记录,可按 Flag 筛选。</summary>
  451. /// <param name="model">目标记录的类型。</param>
  452. /// <param name="flag">要求目标记录具有的 Flag 属性,当指定 0 时忽略此要求。</param>
  453. /// <exception cref="ArgumentNullException"></exception>
  454. /// <exception cref="ModelException"></exception>
  455. /// <exception cref="SqlException"></exception>
  456. public object[] List(Type model, long flag = 0)
  457. {
  458. if (model == null) throw new ArgumentNullException(nameof(model));
  459. var ts = Parse(model);
  460. if (ts == null) throw new ModelException($"无法解析类型 {model.Name}。", model);
  461. var sql = List(ts.TableName, ts.Flag.Field, flag);
  462. return Query(model, sql, null);
  463. }
  464. /// <summary>查询所有记录,可按 Flag 筛选。</summary>
  465. /// <param name="flag">要求目标记录具有的 Flag 属性,当指定 0 时忽略此要求。</param>
  466. /// <exception cref="ModelException"></exception>
  467. /// <exception cref="SqlException"></exception>
  468. public T[] List<T>(long flag = 0) where T : class, IRecord, new() => List(typeof(T), flag).As<object, T>();
  469. #endregion
  470. #region Static
  471. /// <summary>获取表名。</summary>
  472. protected static string Table<T>() => Table(typeof(T));
  473. /// <summary>获取表名。</summary>
  474. protected static string Table(Type model)
  475. {
  476. if (model == null) throw new Exception($"无法从无效类型获取表名。");
  477. var ts = TableStructure.Parse(model);
  478. if (ts == null) throw new Exception($"无法从类型 {model.FullName} 获取表名。");
  479. return ts.TableName;
  480. }
  481. #endregion
  482. #region Derived
  483. /// <summary>为 Ado 创建 IDataAdapter 对象。</summary>
  484. protected abstract IDataAdapter CreateDataAdapter(IDbCommand command);
  485. /// <summary>为 Ado 创建 IDbConnection 对象。</summary>
  486. protected abstract IDbConnection GetConnection();
  487. /// <summary>为 Ado 创建 IDataParameter 对象。</summary>
  488. protected abstract IDataParameter CreateParameter();
  489. #endregion
  490. }
  491. }