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.

651 lines
28 KiB

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