-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathCosmosTriggersTest.cs
More file actions
239 lines (200 loc) · 8.64 KB
/
CosmosTriggersTest.cs
File metadata and controls
239 lines (200 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Scripts;
namespace Microsoft.EntityFrameworkCore;
public class CosmosTriggersTest(NonSharedFixture fixture) : NonSharedModelTestBase(fixture), IClassFixture<NonSharedFixture>
{
protected override string NonSharedStoreName
=> "CosmosTriggersTest";
protected override ITestStoreFactory NonSharedTestStoreFactory
=> CosmosTestStoreFactory.Instance;
[ConditionalFact]
[CosmosCondition(CosmosCondition.IsNotLinuxEmulator)]
public async Task Triggers_are_executed_on_SaveChanges()
{
var contextFactory = await InitializeNonSharedTest<TriggersContext>(shouldLogCategory: _ => true);
using (var context = contextFactory.CreateDbContext())
{
await CreateTriggersInCosmosAsync(context);
Assert.Empty(await context.Set<TriggerExecutionLog>().ToListAsync());
var product = new Product
{
Id = 1,
Name = "Test Product",
Price = 10.00m
};
context.Products.Add(product);
await context.SaveChangesAsync();
var logs = await context.Set<TriggerExecutionLog>().ToListAsync();
Assert.Contains(logs, l => l.TriggerName == "PreInsertTrigger" && l.Operation == "INSERT");
}
using (var context = contextFactory.CreateDbContext())
{
var product = await context.Products.SingleAsync();
product.Name = "Updated Product";
await context.SaveChangesAsync();
var logs = await context.Set<TriggerExecutionLog>().Where(l => l.Operation == "UPDATE").ToListAsync();
Assert.Contains(logs, l => l.TriggerName == "UpdateTrigger" && l.Operation == "UPDATE");
}
using (var context = contextFactory.CreateDbContext())
{
var product = await context.Products.SingleAsync();
context.Products.Remove(product);
await context.SaveChangesAsync();
var logs = await context.Set<TriggerExecutionLog>().Where(l => l.Operation == "DELETE").ToListAsync();
Assert.Contains(logs, l => l.TriggerName == "PostDeleteTrigger" && l.Operation == "DELETE");
}
}
private async Task CreateTriggersInCosmosAsync(TriggersContext context)
{
await context.Database.EnsureCreatedAsync();
var cosmosClient = context.Database.GetCosmosClient();
var databaseId = context.Database.GetCosmosDatabaseId();
var database = cosmosClient.GetDatabase(databaseId);
// Get the container name from the Product entity type metadata
var productEntityType = context.Model.FindEntityType(typeof(Product));
var containerName = productEntityType!.GetContainer()!;
var container = database.GetContainer(containerName);
var preInsertTriggerDefinition = new TriggerProperties
{
Id = "PreInsertTrigger",
TriggerType = TriggerType.Pre,
TriggerOperation = TriggerOperation.Create,
Body = @"
function preInsertTrigger() {
var context = getContext();
var request = context.getRequest();
var doc = request.getBody();
// Log the trigger execution using the same partition key as the document being created
var logEntry = {
id: 'log_' + Math.random().toString().replace('.', ''),
$type: 'TriggerExecutionLog',
TriggerName: 'PreInsertTrigger',
Operation: 'INSERT',
DocumentId: doc.id,
ExecutedAt: new Date().toISOString(),
PartitionKey: doc.PartitionKey // Use the same partition key as the document
};
// Create a separate document to track trigger execution
var collection = context.getCollection();
var accepted = collection.createDocument(collection.getSelfLink(), logEntry);
if (!accepted) throw new Error('Failed to log trigger execution');
}"
};
try
{
await container.Scripts.CreateTriggerAsync(preInsertTriggerDefinition);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
// Trigger already exists, replace it
await container.Scripts.ReplaceTriggerAsync(preInsertTriggerDefinition);
}
var postDeleteTriggerDefinition = new TriggerProperties
{
Id = "PostDeleteTrigger",
TriggerType = TriggerType.Post,
TriggerOperation = TriggerOperation.Delete,
Body = @"
function postDeleteTrigger() {
var context = getContext();
// For delete operations, we can't access the deleted document
// So we'll just create a log entry with a timestamp-based ID
var logEntry = {
id: 'log_' + Math.random().toString().replace('.', ''),
$type: 'TriggerExecutionLog',
TriggerName: 'PostDeleteTrigger',
Operation: 'DELETE',
DocumentId: 'deleted_document',
ExecutedAt: new Date().toISOString(),
PartitionKey: 'Products' // Use the same partition key as Product documents
};
// Create a separate document to track trigger execution
var collection = context.getCollection();
var accepted = collection.createDocument(collection.getSelfLink(), logEntry);
if (!accepted) throw new Error('Failed to log trigger execution');
}"
};
try
{
await container.Scripts.CreateTriggerAsync(postDeleteTriggerDefinition);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
// Trigger already exists, replace it
await container.Scripts.ReplaceTriggerAsync(postDeleteTriggerDefinition);
}
var updateTriggerDefinition = new TriggerProperties
{
Id = "UpdateTrigger",
TriggerType = TriggerType.Pre,
TriggerOperation = TriggerOperation.Replace,
Body = @"
function updateTrigger() {
var context = getContext();
var request = context.getRequest();
var doc = request.getBody();
// Log the trigger execution using the same partition key as the document being updated
var logEntry = {
id: 'log_' + Math.random().toString().replace('.', ''),
$type: 'TriggerExecutionLog',
TriggerName: 'UpdateTrigger',
Operation: 'UPDATE',
DocumentId: doc.id,
ExecutedAt: new Date().toISOString(),
PartitionKey: doc.PartitionKey // Use the same partition key as the document
};
// Create a separate document to track trigger execution
var collection = context.getCollection();
var accepted = collection.createDocument(collection.getSelfLink(), logEntry);
if (!accepted) throw new Error('Failed to log trigger execution');
}"
};
try
{
await container.Scripts.CreateTriggerAsync(updateTriggerDefinition);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
// Trigger already exists, replace it
await container.Scripts.ReplaceTriggerAsync(updateTriggerDefinition);
}
}
protected class TriggersContext(DbContextOptions options) : DbContext(options)
{
public DbSet<Product> Products { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>(entity =>
{
entity.Property(e => e.Id);
entity.HasPartitionKey(e => e.PartitionKey);
entity.HasTrigger("PreInsertTrigger", TriggerType.Pre, TriggerOperation.Create);
entity.HasTrigger("PostDeleteTrigger", TriggerType.Post, TriggerOperation.Delete);
entity.HasTrigger("UpdateTrigger", TriggerType.Pre, TriggerOperation.Replace);
});
modelBuilder.Entity<TriggerExecutionLog>(entity =>
{
entity.HasPartitionKey(e => e.PartitionKey);
});
}
}
protected class Product
{
public int Id { get; set; }
public string? Name { get; set; }
public decimal Price { get; set; }
public string PartitionKey { get; set; } = "Products";
}
protected class TriggerExecutionLog
{
public string Id { get; set; } = null!;
public string TriggerName { get; set; } = null!;
public string Operation { get; set; } = null!;
public string DocumentId { get; set; } = null!;
public DateTime ExecutedAt { get; set; }
public string PartitionKey { get; set; } = "Products";
}
}