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.

746 lines
28 KiB

3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 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
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 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
3 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
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
3 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
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
3 years ago
4 years ago
4 years ago
4 years ago
3 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
4 years ago
4 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
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
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Text;
  6. using static Apewer.Source.SourceUtility;
  7. #if NETFRAMEWORK
  8. using System.Data.Sql;
  9. #endif
  10. namespace Apewer.Source
  11. {
  12. /// <summary>连接 SQL Server 数据库的客户端。</summary>
  13. [Serializable]
  14. public class SqlClient : DbClient
  15. {
  16. #region connection
  17. private SqlConnection _conn = null;
  18. private string _connstr = "";
  19. /// <summary>使用连接字符串创建数据库连接实例。</summary>
  20. /// <exception cref="ArgumentNullException"></exception>
  21. /// <exception cref="ArgumentException"></exception>
  22. public SqlClient(IDbConnection connection, Timeout timeout = null) : base(timeout)
  23. {
  24. if (connection == null) throw new ArgumentNullException(nameof(connection), "指定的连接无效。");
  25. var conn = connection as SqlConnection;
  26. if (conn == null) throw new ArgumentException(nameof(connection), "指定的连接不是支持的类型。");
  27. _conn = conn;
  28. _connstr = conn.ConnectionString;
  29. }
  30. /// <summary>使用连接字符串创建数据库连接实例。</summary>
  31. public SqlClient(string connectionString, Timeout timeout = null) : base(timeout)
  32. {
  33. _connstr = connectionString ?? "";
  34. }
  35. /// <summary>使用连接凭据创建数据库连接实例。</summary>
  36. /// <exception cref="ArgumentNullException"></exception>
  37. public SqlClient(string address, string store, string user, string pass, Timeout timeout = null) : base(timeout)
  38. {
  39. if (address.IsEmpty()) throw new ArgumentNullException(nameof(address));
  40. if (store.IsEmpty()) store = "master";
  41. var cs = $"data source = {address ?? ""}; initial catalog = {store}; ";
  42. if (string.IsNullOrEmpty(user)) cs += "integrated security = sspi; ";
  43. else
  44. {
  45. cs += $"user id = {user}; ";
  46. if (!string.IsNullOrEmpty(pass)) cs += $"password = {pass}; ";
  47. }
  48. if (timeout != null) cs += $"connection timeout = {timeout.Connect}; ";
  49. _connstr = cs;
  50. }
  51. #endregion
  52. #region override
  53. /// <summary>查询数据库中的所有表名。</summary>
  54. public override string[] TableNames() => QueryStrings("select [name] from [sysobjects] where [type] = 'u' order by [name]");
  55. /// <summary>查询数据库实例中的所有数据库名。</summary>
  56. public override string[] StoreNames() => QueryStrings("select [name] from [master]..[sysdatabases] order by [name]", new string[] { "master", "model", "msdb", "tempdb" });
  57. /// <summary>查询表中的所有列名。</summary>
  58. public override string[] ColumnNames(string tableName) => QueryStrings($"select [name] from [syscolumns] where [id] = object_id('{TextUtility.AntiInject(tableName)}')");
  59. /// <summary>创建表,当表不存在时创建表,当现存表中缺少模型中属性对应的列时增加列。成功时返回空字符串,发生异常时返回异常信息。</summary>
  60. protected override string Initialize(TableStructure structure, string table)
  61. {
  62. var model = structure.Model;
  63. if (string.IsNullOrEmpty(table)) table = structure.TableName;
  64. // 检查现存表。
  65. var exists = false;
  66. var tables = TableNames();
  67. if (tables.Length > 0)
  68. {
  69. var lower = table.ToLower();
  70. foreach (var tn in tables)
  71. {
  72. if (TextUtility.IsEmpty(tn)) continue;
  73. if (tn.ToLower() == lower)
  74. {
  75. exists = true;
  76. break;
  77. }
  78. }
  79. }
  80. if (exists)
  81. {
  82. // 获取已存在的列名。
  83. var columns = ColumnNames(table);
  84. if (columns.Length > 0)
  85. {
  86. var lower = new List<string>();
  87. foreach (var column in columns)
  88. {
  89. if (TextUtility.IsBlank(column)) continue;
  90. lower.Add(column.ToLower());
  91. }
  92. columns = lower.ToArray();
  93. }
  94. // 找出新列。
  95. var newColumns = new List<ColumnAttribute>();
  96. foreach (var column in structure.Columns)
  97. {
  98. // 检查 Independent 特性。
  99. if (structure.Independent && column.Independent) continue;
  100. // 去重。
  101. var lower = column.Field.ToLower();
  102. if (columns.Contains(lower)) continue;
  103. var type = Declaration(column);
  104. if (string.IsNullOrEmpty(type)) return $"类型 {column.Type} 不受支持。";
  105. newColumns.Add(column);
  106. }
  107. // 执行:添加列。
  108. if (newColumns.IsEmpty()) return TextUtility.Empty;
  109. foreach (var column in newColumns)
  110. {
  111. var type = Declaration(column);
  112. var sql = $"alter table [{table}] add {type}; ";
  113. var execute = Execute(sql, null, false);
  114. if (!execute.Success) return execute.Message;
  115. }
  116. return TextUtility.Empty;
  117. }
  118. else
  119. {
  120. var sqlcolumns = new List<string>();
  121. foreach (var column in structure.Columns)
  122. {
  123. // 检查 Independent 特性。
  124. if (structure.Independent && column.Independent) continue;
  125. var type = Declaration(column);
  126. if (!column.Independent)
  127. {
  128. if (column.PrimaryKey) type = type + " primary key";
  129. if (column.Incremental) type += " identity";
  130. }
  131. if (string.IsNullOrEmpty(type)) return TextUtility.Merge("类型 ", column.Type.ToString(), " 不受支持。");
  132. sqlcolumns.Add(type);
  133. }
  134. if (sqlcolumns.Count < 1) return $"无法对类型 {model.FullName} 创建表:没有定义任何字段。";
  135. var sql = TextUtility.Merge("create table [", table, "](", string.Join(", ", sqlcolumns.ToArray()), "); ");
  136. var execute = Execute(sql, null, false);
  137. if (execute.Success) return TextUtility.Empty;
  138. return execute.Message;
  139. }
  140. }
  141. /// <summary>插入记录。返回错误信息。</summary>
  142. public override string Insert(object record, string table = null, bool adjust = true)
  143. {
  144. if (record == null) return "参数无效。";
  145. if (adjust) FixProperties(record);
  146. var structure = TableStructure.Parse(record.GetType());
  147. if (structure == null) return "无法解析记录模型。";
  148. if (string.IsNullOrEmpty(table)) table = structure.TableName;
  149. if (string.IsNullOrEmpty(table)) return "表名称无效。";
  150. // 排除字段。
  151. var excluded = new List<string>();
  152. foreach (var ca in structure.Columns)
  153. {
  154. // 排除不使用 ORM 的属性。
  155. if (ca.Independent || ca.Incremental) excluded.Add(ca.Field);
  156. }
  157. var ps = structure.CreateParameters(record, Parameter, excluded);
  158. var psc = ps.Length;
  159. if (psc < 1) return "数据模型不包含字段。";
  160. var names = new List<string>(psc);
  161. var values = new List<string>(psc);
  162. foreach (var column in ps)
  163. {
  164. names.Add($"[{column.ParameterName}]");
  165. values.Add("@" + column.ParameterName);
  166. }
  167. var sb = new StringBuilder();
  168. sb.Append("insert into ", table, "(", string.Join(", ", names.ToArray()), ") ");
  169. sb.Append("values(", string.Join(", ", values.ToArray()), "); ");
  170. var sql = sb.ToString();
  171. var execute = Execute(sql, ps, false);
  172. if (execute.Success) return TextUtility.Empty;
  173. return execute.Message;
  174. }
  175. /// <summary>更新记录,实体中的 Key 属性不被更新。返回错误信息。</summary>
  176. /// <remarks>不更新带有 Independent 特性的模型(缺少 Key 属性)。</remarks>
  177. public override string Update(IRecord record, string table = null, bool adjust = true)
  178. {
  179. if (record == null) return "参数无效。";
  180. if (adjust)
  181. {
  182. FixProperties(record);
  183. SetUpdated(record);
  184. }
  185. var structure = TableStructure.Parse(record.GetType());
  186. if (structure == null) return "无法解析记录模型。";
  187. if (structure.Independent) return "无法更新带有 Independent 特性的模型。";
  188. if (string.IsNullOrEmpty(table)) table = structure.TableName;
  189. if (string.IsNullOrEmpty(table)) return "表名称无效。";
  190. // 排除字段。
  191. var excluded = new List<string>();
  192. if (structure.Key != null) excluded.Add(structure.Key.Field);
  193. foreach (var ca in structure.Columns)
  194. {
  195. // 排除不使用 ORM 的属性、自增属性和主键属性。
  196. if (ca.Independent || ca.Incremental || ca.PrimaryKey || ca.NoUpdate) excluded.Add(ca.Field);
  197. }
  198. var ps = structure.CreateParameters(record, Parameter, excluded);
  199. var psc = ps.Length;
  200. if (psc < 1) return "数据模型不包含字段。";
  201. var items = new List<string>();
  202. foreach (var p in ps)
  203. {
  204. var pn = p.ParameterName;
  205. items.Add($"[{pn}] = @{pn}");
  206. }
  207. var key = record.Key.SafeKey();
  208. var sql = $"update {table} set {string.Join(", ", items.ToArray())} where [{structure.Key.Field}]='{key}'";
  209. var execute = Execute(sql, ps, false);
  210. if (execute.Success) return TextUtility.Empty;
  211. return execute.Message;
  212. }
  213. /// <summary></summary>
  214. public override string ConnectionString => _connstr;
  215. /// <summary></summary>
  216. protected override IDataAdapter CreateDataAdapter(IDbCommand command) => new SqlDataAdapter((SqlCommand)command);
  217. /// <summary></summary>
  218. protected override IDbConnection GetConnection()
  219. {
  220. if (_conn == null) _conn = new SqlConnection(_connstr);
  221. return _conn;
  222. }
  223. /// <summary></summary>
  224. protected override IDataParameter CreateParameter() => new SqlParameter();
  225. /// <summary></summary>
  226. protected override string Keys(string tableName, string keyField, string flagField, long flagValue)
  227. {
  228. if (flagValue == 0) return $"select [{keyField}] from [{tableName}]";
  229. else return $"select [{keyField}] from [{tableName}] where [{flagField}] = {flagValue}";
  230. }
  231. /// <summary></summary>
  232. protected override string Get(string tableName, string keyField, string keyValue, string flagField, long flagValue)
  233. {
  234. if (flagValue == 0) return $"select top 1 * from [{tableName}] where [{keyField}] = '{keyValue}'";
  235. else return $"select top 1 * from [{tableName}] where [{keyField}] = '{keyValue}' and [{flagField}] = {flagValue}";
  236. }
  237. /// <summary></summary>
  238. protected override string List(string tableName, string flagField, long flagValue)
  239. {
  240. if (flagValue == 0) return $"select * from [{tableName}]";
  241. else return $"select * from [{tableName}] where [{flagField}] = {flagValue}";
  242. }
  243. #endregion
  244. #region special
  245. /// <summary>清空与指定连接关联的连接池。</summary>
  246. public static void ClearPool(IDbConnection connection)
  247. {
  248. var special = connection as SqlConnection;
  249. if (special != null)
  250. {
  251. try
  252. {
  253. SqlConnection.ClearPool(special);
  254. }
  255. catch { }
  256. }
  257. }
  258. /// <summary>清空与指定连接关联的连接池。</summary>
  259. public static void ClearPool(IDbAdo instance)
  260. {
  261. var connection = instance?.Connection;
  262. if (connection != null) ClearPool(connection);
  263. }
  264. /// <summary>清空连接池。</summary>
  265. public static void ClearAllPools()
  266. {
  267. try
  268. {
  269. SqlConnection.ClearAllPools();
  270. }
  271. catch { }
  272. }
  273. /// <summary>获取列信息。</summary>
  274. public virtual ColumnInfo[] ColumnsInfo(string tableName)
  275. {
  276. if (tableName.IsEmpty()) throw new ArgumentNullException(nameof(tableName));
  277. var sql = $"select name, xtype, length from syscolumns where id = object_id('{tableName}') ";
  278. using (var query = Query(sql))
  279. {
  280. var ab = new ArrayBuilder<ColumnInfo>();
  281. for (var i = 0; i < query.Rows; i++)
  282. {
  283. var info = new ColumnInfo();
  284. info.Name = query.Text(i, "name");
  285. info.Type = XType(query.Int32(i, "xtype"));
  286. info.Length = query.Int32(i, "length");
  287. ab.Add(info);
  288. }
  289. return ab.Export();
  290. }
  291. }
  292. /// <summary>创建索引。</summary>
  293. /// <remarks>索引名称已存在或无索引字段时,不抛出异常。</remarks>
  294. public virtual string Initialize(TableIndex index)
  295. {
  296. if (index == null)
  297. {
  298. if (ThrowAdoException) throw new ArgumentNullException(nameof(index));
  299. return $"参数 {nameof(index)} 无效。";
  300. }
  301. // 查询索引是否存在,若存在则直接退出。
  302. var sql1 = "select distinct i.name from sys.indexes i left join sys.all_objects o on i.object_id = o.object_id where i.name is not null and o.type = 'U' and i.is_primary_key = 0 and i.is_unique = 0";
  303. var names = this.Column(sql1, false);
  304. var exist = names.Find(x => string.Equals(x, index.Name, StringComparison.CurrentCultureIgnoreCase));
  305. if (exist.NotEmpty()) return $"索引已存在。";
  306. // 执行创建。
  307. var fields = new List<string>();
  308. foreach (var field in index.Fields)
  309. {
  310. if (field.Order == Order.Ascend) fields.Add($"[{field.Column.Field}]");
  311. else fields.Add($"[{field.Column.Field}] desc");
  312. }
  313. if (fields.IsEmpty()) return "无索引字段。";
  314. var sql2 = $"create index {index.Name} on [{index.Table.Name}] ({fields.Join(", ")})";
  315. var execute = Execute(sql2);
  316. if (!execute.Success)
  317. {
  318. if (ThrowAdoException) throw new SqlException(execute.Message);
  319. return execute.Message;
  320. }
  321. return null;
  322. }
  323. /// <summary>批量插入,必须在 DataTable 中指定表名,或指定 tableName 参数。</summary>
  324. /// <exception cref="ArgumentNullException"></exception>
  325. /// <exception cref="ArgumentException"></exception>
  326. /// <exception cref="Exception"></exception>
  327. public virtual void BulkCopy(DataTable table, string tableName = null)
  328. {
  329. // 检查 table 参数。
  330. if (table == null) throw new ArgumentNullException(nameof(table));
  331. if (table.Rows.Count < 1) return;
  332. // 检查 tableName 参数。
  333. if (tableName.IsEmpty()) tableName = table.TableName;
  334. if (tableName.IsEmpty()) throw new ArgumentException("未指定表名。");
  335. // 连接数据库。
  336. var connect = Connect();
  337. if (connect.NotEmpty()) throw new Exception(connect);
  338. // 准备参数。
  339. var options = SqlBulkCopyOptions.Default;
  340. var trans = Transaction as SqlTransaction;
  341. if (trans == null) options |= SqlBulkCopyOptions.UseInternalTransaction;
  342. // 批量插入。
  343. var bc = null as SqlBulkCopy;
  344. try
  345. {
  346. bc = new SqlBulkCopy((SqlConnection)Connection, options, trans);
  347. bc.DestinationTableName = tableName;
  348. bc.BatchSize = table.Rows.Count;
  349. bc.WriteToServer(table);
  350. try { bc.Close(); } catch { }
  351. }
  352. catch (Exception ex)
  353. {
  354. try { bc.Close(); } catch { }
  355. throw ex;
  356. }
  357. }
  358. /// <summary>创建数据库,返回错误信息。</summary>
  359. /// <param name="name">数据库名称。</param>
  360. /// <param name="logMaxSizeMB">日志文件的最大 MB 数,指定非正数将不限制增长。</param>
  361. /// <returns>成功时候返回 NULL 值,失败时返回错误信息。</returns>
  362. public virtual string CreateStore(string name, int logMaxSizeMB = 1024)
  363. {
  364. var store = name.Escape().ToTrim();
  365. if (store.IsEmpty()) return "创建失败:未指定数据库名称。";
  366. if (ConnectionString.IsEmpty()) return "创建失败:未指定数据库连接方式。";
  367. using (var source = new SqlClient(ConnectionString))
  368. {
  369. var connect = source.Connect();
  370. if (connect.NotEmpty()) return "创建失败:" + connect;
  371. var schema = source.Cell("select default_schema_name from sys.database_principals where type = 'S' and name=user_name()");
  372. if (schema.IsEmpty()) return "创建失败:无法获取默认模式名称。";
  373. var refPath = source.Cell(@"select f.physical_name path from sys.filegroups g left join sys.database_files f on f.data_space_id = g.data_space_id where g.name = 'PRIMARY' and g.type = 'FG' and g.is_default = 1 and g.filegroup_guid is null");
  374. if (refPath.IsEmpty()) return "创建失败:无法获取文件路径。";
  375. var win = refPath.Substring(1, 2) == ":\\";
  376. var nix = refPath.StartsWith("/");
  377. if (!win && !nix) return "创建失败:暂不支持该服务器。";
  378. var mdfPath = store + ".mdf";
  379. var ldfPath = store + ".ldf";
  380. if (win)
  381. {
  382. var refSplit = refPath.Split('\\');
  383. var dir = string.Join("\\", refSplit, 0, refSplit.Length - 1);
  384. mdfPath = dir + "\\" + mdfPath;
  385. ldfPath = dir + "\\" + ldfPath;
  386. }
  387. if (nix)
  388. {
  389. var refSplit = refPath.Split('/');
  390. var dir = string.Join("/", refSplit, 0, refSplit.Length - 1);
  391. mdfPath = dir + "/" + mdfPath;
  392. ldfPath = dir + "/" + ldfPath;
  393. }
  394. // 创建库。
  395. var maxLog = logMaxSizeMB > 0 ? $"{logMaxSizeMB}MB" : "UNLIMITED";
  396. var sql1 = $@"
  397. CREATE DATABASE [{store}]
  398. ON PRIMARY
  399. (
  400. NAME = N'{store}',
  401. FILENAME = N'{mdfPath}',
  402. SIZE = 4MB,
  403. MAXSIZE = UNLIMITED,
  404. FILEGROWTH = 4MB
  405. )
  406. LOG ON
  407. (
  408. NAME = N'{store}_log',
  409. FILENAME = N'{ldfPath}',
  410. SIZE = 1MB,
  411. MAXSIZE = {maxLog},
  412. FILEGROWTH = 1MB
  413. )
  414. COLLATE Chinese_PRC_CI_AS
  415. ";
  416. var create = source.Execute(sql1, null, false);
  417. if (!create.Success) return TextUtility.Merge("创建失败:", create.Message);
  418. // 设置兼容性级别。
  419. var sql2 = $"alter database [{store}] set compatibility_level = 100";
  420. source.Execute(sql2, null, false);
  421. // 设置恢复默认为“简单”
  422. var sql3 = $"alter database [{store}] set recovery simple";
  423. source.Execute(sql3, null, false);
  424. return null;
  425. }
  426. }
  427. static string XType(int xtype)
  428. {
  429. switch (xtype)
  430. {
  431. case 34: return "image";
  432. case 35: return "text";
  433. case 36: return "uniqueidentifier";
  434. case 48: return "tinyint";
  435. case 52: return "smallint";
  436. case 56: return "int";
  437. case 58: return "smalldatetime";
  438. case 59: return "real";
  439. case 60: return "money";
  440. case 61: return "datetime";
  441. case 62: return "float";
  442. case 98: return "sql_variant";
  443. case 99: return "ntext";
  444. case 104: return "bit";
  445. case 106: return "decimal";
  446. case 108: return "numeric";
  447. case 122: return "smallmoney";
  448. case 127: return "bigint";
  449. case 165: return "varbinary";
  450. case 167: return "varchar";
  451. case 173: return "binary";
  452. case 175: return "char";
  453. case 189: return "timestamp";
  454. case 231: return "nvarchar";
  455. case 239: return "nchar";
  456. case 241: return "xml";
  457. }
  458. return null;
  459. }
  460. #if NET20 || NET40
  461. /// <summary>枚举本地网络中的 SQL Server 实例的信息。</summary>
  462. public static Source[] EnumerateSources()
  463. {
  464. var list = new List<Source>();
  465. // 表中列名:ServerName、InstanceName、IsClustered、Version。
  466. using (var table = SqlDataSourceEnumerator.Instance.GetDataSources())
  467. {
  468. var query = new Query(table);
  469. var rows = query.Rows;
  470. list.Capacity = rows;
  471. for (int i = 0; i < rows; i++)
  472. {
  473. var item = new Source();
  474. item.ServerName = query.Text(i, "ServerName");
  475. list.Add(item);
  476. }
  477. }
  478. return list.ToArray();
  479. }
  480. /// <summary>SQL Server 实例的信息。</summary>
  481. public sealed class Source
  482. {
  483. /// <summary></summary>
  484. public string ServerName { get; set; }
  485. /// <summary></summary>
  486. public string InstanceName { get; set; }
  487. /// <summary></summary>
  488. public string IsClustered { get; set; }
  489. /// <summary></summary>
  490. public string Version { get; set; }
  491. }
  492. #endif
  493. /// <summary>创建参数。</summary>
  494. /// <exception cref="ArgumentNullException"></exception>
  495. /// <exception cref="InvalidOperationException"></exception>
  496. static SqlParameter Parameter(Parameter parameter)
  497. {
  498. if (parameter == null) throw new InvalidOperationException("参数无效。");
  499. return Parameter(parameter.Name, parameter.Type, parameter.Size, parameter.Value);
  500. }
  501. /// <summary>创建参数。</summary>
  502. public static SqlParameter Parameter(string name, ColumnType type, int size, object value)
  503. {
  504. var vname = TextUtility.Trim(name);
  505. if (TextUtility.IsBlank(vname)) return null;
  506. var vtype = SqlDbType.BigInt;
  507. switch (type)
  508. {
  509. case ColumnType.Boolean:
  510. vtype = SqlDbType.Bit;
  511. break;
  512. case ColumnType.Bytes:
  513. vtype = SqlDbType.Image;
  514. break;
  515. case ColumnType.Integer:
  516. vtype = SqlDbType.BigInt;
  517. break;
  518. case ColumnType.Float:
  519. vtype = SqlDbType.Float;
  520. break;
  521. case ColumnType.DateTime:
  522. vtype = SqlDbType.DateTime;
  523. break;
  524. case ColumnType.VarChar:
  525. case ColumnType.VarChar191:
  526. case ColumnType.VarCharMax:
  527. vtype = SqlDbType.VarChar;
  528. break;
  529. case ColumnType.NVarChar:
  530. case ColumnType.NVarChar191:
  531. case ColumnType.NVarCharMax:
  532. vtype = SqlDbType.NVarChar;
  533. break;
  534. case ColumnType.Text:
  535. vtype = SqlDbType.Text;
  536. break;
  537. case ColumnType.NText:
  538. vtype = SqlDbType.NText;
  539. break;
  540. default:
  541. throw new InvalidOperationException(TextUtility.Merge("类型 ", type.ToString(), " 不受支持。"));
  542. }
  543. var vsize = size;
  544. switch (type)
  545. {
  546. case ColumnType.VarChar:
  547. vsize = NumberUtility.Restrict(vsize, 0, 8000);
  548. break;
  549. case ColumnType.NVarChar:
  550. vsize = NumberUtility.Restrict(vsize, 0, 4000);
  551. break;
  552. case ColumnType.VarChar191:
  553. case ColumnType.NVarChar191:
  554. vsize = NumberUtility.Restrict(vsize, 0, 191);
  555. break;
  556. default:
  557. vsize = 0;
  558. break;
  559. }
  560. var vvalue = value ?? DBNull.Value;
  561. if (vvalue is string && vvalue != null && vsize > 0)
  562. {
  563. vvalue = TextUtility.Left((string)vvalue, vsize);
  564. }
  565. var parameter = new SqlParameter();
  566. parameter.ParameterName = vname;
  567. parameter.SqlDbType = vtype;
  568. parameter.Value = vvalue;
  569. if (vsize > 0) parameter.Size = vsize;
  570. return parameter;
  571. }
  572. /// <summary>创建参数。</summary>
  573. public static SqlParameter Parameter(string name, SqlDbType type, int size, object value)
  574. {
  575. if (value is string && value != null && size > 0)
  576. {
  577. value = TextUtility.Left((string)value, (int)size);
  578. }
  579. var p = new SqlParameter();
  580. p.ParameterName = name ?? "";
  581. p.SqlDbType = type;
  582. p.Size = size;
  583. p.Value = value ?? DBNull.Value;
  584. return p;
  585. }
  586. /// <summary>创建参数。</summary>
  587. public static SqlParameter Parameter(string name, SqlDbType type, object value)
  588. {
  589. var p = new SqlParameter();
  590. p.ParameterName = name ?? "";
  591. p.SqlDbType = type;
  592. p.Value = value ?? DBNull.Value;
  593. return p;
  594. }
  595. static string Declaration(ColumnAttribute column)
  596. {
  597. var type = TextUtility.Empty;
  598. var vcolumn = column;
  599. var length = Math.Max(0, vcolumn.Length);
  600. switch (vcolumn.Type)
  601. {
  602. case ColumnType.Boolean:
  603. type = "bit";
  604. break;
  605. case ColumnType.Integer:
  606. type = "bigint";
  607. break;
  608. case ColumnType.Float:
  609. type = "float";
  610. break;
  611. case ColumnType.Bytes:
  612. type = "image";
  613. break;
  614. case ColumnType.DateTime:
  615. type = "datetime";
  616. break;
  617. case ColumnType.VarChar:
  618. type = $"varchar({Math.Min(8000, length)})";
  619. break;
  620. case ColumnType.VarChar191:
  621. type = "varchar(191)";
  622. break;
  623. case ColumnType.VarCharMax:
  624. type = "varchar(max)";
  625. break;
  626. case ColumnType.Text:
  627. type = "text";
  628. break;
  629. case ColumnType.NVarChar:
  630. type = $"nvarchar({Math.Min(4000, length)})";
  631. break;
  632. case ColumnType.NVarChar191:
  633. type = "nvarchar(191)";
  634. break;
  635. case ColumnType.NVarCharMax:
  636. type = "nvarchar(max)";
  637. break;
  638. case ColumnType.NText:
  639. type = "ntext";
  640. break;
  641. default:
  642. return TextUtility.Empty;
  643. }
  644. return $"[{vcolumn.Field}] {type}";
  645. }
  646. #endregion
  647. }
  648. }