|
| 1 | +using CmdScale.EntityFrameworkCore.TimescaleDB.Abstractions; |
| 2 | +using CmdScale.EntityFrameworkCore.TimescaleDB.Configuration.ContinuousAggregate; |
| 3 | +using CmdScale.EntityFrameworkCore.TimescaleDB.Configuration.Hypertable; |
| 4 | +using Microsoft.EntityFrameworkCore; |
| 5 | +using Testcontainers.PostgreSql; |
| 6 | + |
| 7 | +namespace CmdScale.EntityFrameworkCore.TimescaleDB.Tests.Integration |
| 8 | +{ |
| 9 | + public class ContinuousAggregateIntegrationTests : IAsyncLifetime |
| 10 | + { |
| 11 | + private PostgreSqlContainer? _container; |
| 12 | + private string? _connectionString; |
| 13 | + |
| 14 | + public async Task InitializeAsync() |
| 15 | + { |
| 16 | + // Start TimescaleDB container |
| 17 | + _container = new PostgreSqlBuilder() |
| 18 | + .WithImage("timescale/timescaledb:latest-pg16") |
| 19 | + .WithDatabase("test_db") |
| 20 | + .WithUsername("test_user") |
| 21 | + .WithPassword("test_password") |
| 22 | + .Build(); |
| 23 | + |
| 24 | + await _container.StartAsync(); |
| 25 | + _connectionString = _container.GetConnectionString(); |
| 26 | + |
| 27 | + await using var context = new TestDbContext(_connectionString); |
| 28 | + } |
| 29 | + |
| 30 | + public async Task DisposeAsync() |
| 31 | + { |
| 32 | + if (_container != null) |
| 33 | + { |
| 34 | + await _container.DisposeAsync(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + [Fact] |
| 39 | + public async Task ContinuousAggregate_ShouldAggregateTradeData_Successfully() |
| 40 | + { |
| 41 | + // Arrange |
| 42 | + await using var context = new TestDbContext(_connectionString!); |
| 43 | + |
| 44 | + // Create the database schema (tables, hypertables, and continuous aggregates) |
| 45 | + await context.Database.ExecuteSqlRawAsync(@" |
| 46 | + CREATE TABLE IF NOT EXISTS ""Trades"" ( |
| 47 | + ""Timestamp"" timestamp with time zone NOT NULL, |
| 48 | + ""Ticker"" text NOT NULL, |
| 49 | + ""Price"" numeric NOT NULL, |
| 50 | + ""Size"" integer NOT NULL, |
| 51 | + ""Exchange"" text NOT NULL |
| 52 | + ); |
| 53 | + "); |
| 54 | + |
| 55 | + // Create hypertable |
| 56 | + await context.Database.ExecuteSqlRawAsync(@" |
| 57 | + SELECT create_hypertable('""Trades""', 'Timestamp', if_not_exists => TRUE); |
| 58 | + SELECT set_chunk_time_interval('public.""Trades""', INTERVAL '1 day'); |
| 59 | + "); |
| 60 | + |
| 61 | + // Create continuous aggregate (must be separate due to transaction requirements) |
| 62 | + await context.Database.ExecuteSqlRawAsync(@" |
| 63 | + CREATE MATERIALIZED VIEW IF NOT EXISTS trade_aggregate_view |
| 64 | + WITH (timescaledb.continuous, timescaledb.create_group_indexes = false, timescaledb.materialized_only = false) AS |
| 65 | + SELECT time_bucket('1 hour', ""Timestamp"") AS time_bucket, ""Exchange"", AVG(""Price"") AS ""AveragePrice"", MAX(""Price"") AS ""MaxPrice"", MIN(""Price"") AS ""MinPrice"" |
| 66 | + FROM ""Trades"" |
| 67 | + WHERE ""Ticker"" = 'MCRS' |
| 68 | + GROUP BY time_bucket, ""Exchange""; |
| 69 | + "); |
| 70 | + |
| 71 | + // Insert test data using raw SQL (since TestTrade is keyless and can't be tracked) |
| 72 | + await context.Database.ExecuteSqlRawAsync(@" |
| 73 | + INSERT INTO ""Trades"" (""Timestamp"", ""Ticker"", ""Price"", ""Size"", ""Exchange"") |
| 74 | + VALUES |
| 75 | + ('2025-01-06 10:15:00+00', 'MCRS', 150.50, 100, 'NYSE'), |
| 76 | + ('2025-01-06 10:30:00+00', 'MCRS', 151.00, 200, 'NYSE'), |
| 77 | + ('2025-01-06 10:45:00+00', 'MCRS', 149.75, 150, 'NYSE'), |
| 78 | + ('2025-01-06 10:20:00+00', 'MCRS', 150.00, 180, 'NASDAQ'), |
| 79 | + ('2025-01-06 10:50:00+00', 'MCRS', 151.50, 220, 'NASDAQ'), |
| 80 | + ('2025-01-06 11:10:00+00', 'MCRS', 152.00, 300, 'NYSE'), |
| 81 | + ('2025-01-06 11:25:00+00', 'MCRS', 153.25, 250, 'NYSE'), |
| 82 | + ('2025-01-06 11:40:00+00', 'MCRS', 151.75, 180, 'NYSE'), |
| 83 | + ('2025-01-06 10:15:00+00', 'AAPL', 180.00, 100, 'NYSE'), |
| 84 | + ('2025-01-06 10:30:00+00', 'TSLA', 250.00, 50, 'NASDAQ'); |
| 85 | + "); |
| 86 | + |
| 87 | + // Act - Manually refresh the continuous aggregate |
| 88 | + await context.Database.ExecuteSqlRawAsync( |
| 89 | + "CALL refresh_continuous_aggregate('public.trade_aggregate_view', NULL, NULL);"); |
| 90 | + |
| 91 | + // Query the continuous aggregate |
| 92 | + var aggregates = await context.TradeAggregates |
| 93 | + .OrderBy(a => a.TimeBucket) |
| 94 | + .ThenBy(a => a.Exchange) |
| 95 | + .ToListAsync(); |
| 96 | + |
| 97 | + // Assert |
| 98 | + // We expect 3 aggregates: 2 for hour 10:00 (NYSE + NASDAQ) and 1 for hour 11:00 (NYSE only) |
| 99 | + Assert.Equal(3, aggregates.Count); |
| 100 | + |
| 101 | + // Verify Hour 1 - NYSE aggregate |
| 102 | + var hour1Nyse = aggregates.First(a => |
| 103 | + a.TimeBucket == new DateTime(2025, 1, 6, 10, 0, 0, DateTimeKind.Utc) && |
| 104 | + a.Exchange == "NYSE"); |
| 105 | + Assert.Equal(150.4166666666666667m, hour1Nyse.AveragePrice); // (150.50 + 151.00 + 149.75) / 3 |
| 106 | + Assert.Equal(151.00m, hour1Nyse.MaxPrice); |
| 107 | + Assert.Equal(149.75m, hour1Nyse.MinPrice); |
| 108 | + |
| 109 | + // Verify Hour 1 - NASDAQ aggregate |
| 110 | + var hour1Nasdaq = aggregates.First(a => |
| 111 | + a.TimeBucket == new DateTime(2025, 1, 6, 10, 0, 0, DateTimeKind.Utc) && |
| 112 | + a.Exchange == "NASDAQ"); |
| 113 | + Assert.Equal(150.75m, hour1Nasdaq.AveragePrice); // (150.00 + 151.50) / 2 |
| 114 | + Assert.Equal(151.50m, hour1Nasdaq.MaxPrice); |
| 115 | + Assert.Equal(150.00m, hour1Nasdaq.MinPrice); |
| 116 | + |
| 117 | + // Verify Hour 2 - NYSE aggregate |
| 118 | + var hour2Nyse = aggregates.First(a => |
| 119 | + a.TimeBucket == new DateTime(2025, 1, 6, 11, 0, 0, DateTimeKind.Utc) && |
| 120 | + a.Exchange == "NYSE"); |
| 121 | + Assert.Equal(152.3333333333333333m, hour2Nyse.AveragePrice); // (152.00 + 153.25 + 151.75) / 3 |
| 122 | + Assert.Equal(153.25m, hour2Nyse.MaxPrice); |
| 123 | + Assert.Equal(151.75m, hour2Nyse.MinPrice); |
| 124 | + |
| 125 | + // Verify that other tickers (AAPL, TSLA) are NOT in the aggregates |
| 126 | + Assert.DoesNotContain(aggregates, a => a.Exchange != "NYSE" && a.Exchange != "NASDAQ"); |
| 127 | + } |
| 128 | + |
| 129 | + #region Test Models and DbContext |
| 130 | + |
| 131 | + private class TestTrade |
| 132 | + { |
| 133 | + public DateTime Timestamp { get; set; } |
| 134 | + public string Ticker { get; set; } = string.Empty; |
| 135 | + public decimal Price { get; set; } |
| 136 | + public int Size { get; set; } |
| 137 | + public string Exchange { get; set; } = string.Empty; |
| 138 | + } |
| 139 | + |
| 140 | + private class TestTradeAggregate |
| 141 | + { |
| 142 | + public DateTime TimeBucket { get; set; } |
| 143 | + public string Exchange { get; set; } = string.Empty; |
| 144 | + public decimal AveragePrice { get; set; } |
| 145 | + public decimal MaxPrice { get; set; } |
| 146 | + public decimal MinPrice { get; set; } |
| 147 | + } |
| 148 | + |
| 149 | + private class TestDbContext : DbContext |
| 150 | + { |
| 151 | + private readonly string _connectionString; |
| 152 | + |
| 153 | + public TestDbContext(string connectionString) |
| 154 | + { |
| 155 | + _connectionString = connectionString; |
| 156 | + } |
| 157 | + |
| 158 | + public DbSet<TestTrade> Trades => Set<TestTrade>(); |
| 159 | + public DbSet<TestTradeAggregate> TradeAggregates => Set<TestTradeAggregate>(); |
| 160 | + |
| 161 | + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| 162 | + { |
| 163 | + optionsBuilder.UseNpgsql(_connectionString) |
| 164 | + .UseTimescaleDb(); |
| 165 | + } |
| 166 | + |
| 167 | + protected override void OnModelCreating(ModelBuilder modelBuilder) |
| 168 | + { |
| 169 | + // Configure Trade as a hypertable |
| 170 | + modelBuilder.Entity<TestTrade>(entity => |
| 171 | + { |
| 172 | + entity.ToTable("Trades"); |
| 173 | + entity.HasNoKey(); |
| 174 | + entity.IsHypertable(x => x.Timestamp) |
| 175 | + .WithChunkTimeInterval("1 day"); |
| 176 | + }); |
| 177 | + |
| 178 | + // Configure TradeAggregate as a continuous aggregate |
| 179 | + modelBuilder.Entity<TestTradeAggregate>(entity => |
| 180 | + { |
| 181 | + entity.HasNoKey(); |
| 182 | + entity.IsContinuousAggregate<TestTradeAggregate, TestTrade>( |
| 183 | + "trade_aggregate_view", |
| 184 | + "1 hour", |
| 185 | + x => x.Timestamp) |
| 186 | + .AddAggregateFunction(x => x.AveragePrice, x => x.Price, EAggregateFunction.Avg) |
| 187 | + .AddAggregateFunction(x => x.MaxPrice, x => x.Price, EAggregateFunction.Max) |
| 188 | + .AddAggregateFunction(x => x.MinPrice, x => x.Price, EAggregateFunction.Min) |
| 189 | + .AddGroupByColumn(x => x.Exchange) |
| 190 | + .Where("\"Ticker\" = 'MCRS'"); |
| 191 | + |
| 192 | + // Map properties to view columns |
| 193 | + entity.Property(x => x.TimeBucket).HasColumnName("time_bucket"); |
| 194 | + entity.Property(x => x.Exchange).HasColumnName("Exchange"); |
| 195 | + entity.Property(x => x.AveragePrice).HasColumnName("AveragePrice"); |
| 196 | + entity.Property(x => x.MaxPrice).HasColumnName("MaxPrice"); |
| 197 | + entity.Property(x => x.MinPrice).HasColumnName("MinPrice"); |
| 198 | + }); |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + #endregion |
| 203 | + } |
| 204 | +} |
0 commit comments