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.

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