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.

75 lines
3.0 KiB

2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace SqlSugar
  5. {
  6. public class OracleInsertable<T> : InsertableProvider<T> where T : class, new()
  7. {
  8. protected override List<string> GetIdentityKeys()
  9. {
  10. return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.DbColumnName).ToList();
  11. }
  12. protected string GetSeqName()
  13. {
  14. return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.OracleSequenceName).First();
  15. }
  16. protected List<string> GetSeqNames()
  17. {
  18. return this.EntityInfo.Columns.Where(it => it.OracleSequenceName.HasValue()).Select(it => it.OracleSequenceName).ToList();
  19. }
  20. public override int ExecuteReturnIdentity()
  21. {
  22. InsertBuilder.IsReturnIdentity = true;
  23. PreToSql();
  24. var sql = InsertBuilder.ToSqlString();
  25. RestoreMapping();
  26. var count = Ado.ExecuteCommand(sql, InsertBuilder.Parameters?.ToArray());
  27. var result = (this.GetIdentityKeys().IsNullOrEmpty() || count == 0) ? 0 : GetSeqValue(GetSeqName()).ObjToInt();
  28. return result;
  29. }
  30. public override long ExecuteReturnBigIdentity()
  31. {
  32. InsertBuilder.IsReturnIdentity = true;
  33. PreToSql();
  34. var sql = InsertBuilder.ToSqlString();
  35. RestoreMapping();
  36. var count = Ado.ExecuteCommand(sql, InsertBuilder.Parameters?.ToArray());
  37. var result = (this.GetIdentityKeys().IsNullOrEmpty() || count == 0) ? 0 :Convert.ToInt64(GetSeqValue(GetSeqName()));
  38. return result;
  39. }
  40. public override int ExecuteCommand()
  41. {
  42. base.ExecuteCommand();
  43. return base.InsertObjs.Count();
  44. }
  45. private object GetSeqValue(string seqName)
  46. {
  47. return Ado.GetScalar(" SELECT " + seqName + ".currval FROM DUAL");
  48. }
  49. protected override void PreToSql()
  50. {
  51. var identities = GetSeqNames();
  52. var insertCount = InsertObjs.Count();
  53. InsertBuilder.OracleSeqInfoList = new Dictionary<string, int>();
  54. if (identities.HasValue() && insertCount > 1)
  55. {
  56. Check.Exception(identities.Count != identities.Distinct().Count(), "The field sequence needs to be unique");
  57. foreach (var seqName in identities)
  58. {
  59. var seqBeginValue = 0;
  60. this.Ado.ExecuteCommand("alter sequence " + seqName + " increment by " + insertCount);
  61. seqBeginValue = this.Ado.GetInt("select " + seqName + ".Nextval from dual") - insertCount;
  62. this.Ado.ExecuteCommand("alter sequence " + seqName + " increment by " + 1);
  63. InsertBuilder.OracleSeqInfoList.Add(seqName, seqBeginValue);
  64. }
  65. }
  66. base.PreToSql();
  67. }
  68. }
  69. }