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.

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