CqlDataContext.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Cassandra;
  5. using Cassandra.Data.Linq;
  6. using TableAttribute = Cassandra.Mapping.Attributes.TableAttribute;
  7. namespace Abc.Zebus.Persistence.Cassandra.Cql
  8. {
  9. public abstract class CqlDataContext<TConfig> where TConfig : ICassandraConfiguration
  10. {
  11. public CqlDataContext(CassandraCqlSessionManager sessionManager, TConfig cassandraConfiguration)
  12. : this(CreateSession(sessionManager, cassandraConfiguration))
  13. {
  14. }
  15. private CqlDataContext(ISession session)
  16. {
  17. Session = session;
  18. }
  19. public ISession Session { get; }
  20. private static ISession CreateSession(CassandraCqlSessionManager sessionManager, ICassandraConfiguration cassandraConfiguration)
  21. {
  22. return sessionManager.GetSession(cassandraConfiguration);
  23. }
  24. public void CreateTablesIfNotExist()
  25. {
  26. foreach (var propertyInfo in GetTableProperties(GetType()))
  27. {
  28. var table = propertyInfo.GetMethod!.Invoke(this, Array.Empty<object>())!;
  29. table.GetType().GetMethod(nameof(Table<object>.CreateIfNotExists))!.Invoke(table, Array.Empty<object>());
  30. }
  31. }
  32. public IEnumerable<string> GetTableNames()
  33. {
  34. foreach (var propertyInfo in GetTableProperties(GetType()))
  35. {
  36. var genericArguments = propertyInfo.PropertyType.GetGenericArguments();
  37. if (genericArguments.Length != 1)
  38. continue;
  39. var tableType = genericArguments[0];
  40. var tableAttribute = tableType.GetCustomAttribute<TableAttribute>()!;
  41. yield return tableAttribute.Name;
  42. }
  43. }
  44. private static IEnumerable<PropertyInfo> GetTableProperties(Type type)
  45. {
  46. if (!typeof(CqlDataContext<TConfig>).IsAssignableFrom(type))
  47. throw new ArgumentException();
  48. var properties = type.GetProperties();
  49. foreach (var propertyInfo in properties)
  50. {
  51. if (!propertyInfo.PropertyType.IsGenericType)
  52. continue;
  53. if (typeof(Table<>).IsAssignableFrom(propertyInfo.PropertyType.GetGenericTypeDefinition()))
  54. yield return propertyInfo;
  55. }
  56. }
  57. }
  58. }