-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHypertableOperationGenerator.cs
More file actions
333 lines (282 loc) · 15 KB
/
HypertableOperationGenerator.cs
File metadata and controls
333 lines (282 loc) · 15 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
using CmdScale.EntityFrameworkCore.TimescaleDB.Abstractions;
using CmdScale.EntityFrameworkCore.TimescaleDB.Operations;
using System.Text;
namespace CmdScale.EntityFrameworkCore.TimescaleDB.Generators
{
public class HypertableOperationGenerator
{
private readonly string quoteString = "\"";
private readonly SqlBuilderHelper sqlHelper;
public HypertableOperationGenerator(bool isDesignTime = false)
{
if (isDesignTime)
{
quoteString = "\"\"";
}
sqlHelper = new SqlBuilderHelper(quoteString);
}
public List<string> Generate(CreateHypertableOperation operation)
{
string qualifiedTableName = sqlHelper.Regclass(operation.TableName, operation.Schema);
string qualifiedIdentifier = sqlHelper.QualifiedIdentifier(operation.TableName, operation.Schema);
List<string> statements = [];
List<string> communityStatements = [];
// Build create_hypertable with chunk_time_interval if provided
StringBuilder createHypertableCall = new();
createHypertableCall.Append($"SELECT create_hypertable({qualifiedTableName}, '{operation.TimeColumnName}'");
createHypertableCall.Append(operation.MigrateData ? ", migrate_data => true" : "");
if (!string.IsNullOrEmpty(operation.ChunkTimeInterval))
{
// Check if the interval is a plain number (e.g., for microseconds).
if (long.TryParse(operation.ChunkTimeInterval, out _))
{
// If it's a number, don't wrap it in quotes.
createHypertableCall.Append($", chunk_time_interval => {operation.ChunkTimeInterval}::bigint");
}
else
{
// If it's a string like '7 days', wrap it in quotes.
createHypertableCall.Append($", chunk_time_interval => INTERVAL '{operation.ChunkTimeInterval}'");
}
}
createHypertableCall.Append(");");
statements.Add(createHypertableCall.ToString());
List<string> compressionSettings = [];
bool hasSegmentBy = operation.CompressionSegmentBy != null && operation.CompressionSegmentBy.Count > 0;
bool hasOrderBy = operation.CompressionOrderBy != null && operation.CompressionOrderBy.Count > 0;
bool hasChunkSkipping = operation.ChunkSkipColumns != null && operation.ChunkSkipColumns.Count > 0;
bool shouldEnableCompression = operation.EnableCompression || hasChunkSkipping || hasSegmentBy || hasOrderBy;
if (shouldEnableCompression)
{
compressionSettings.Add("timescaledb.compress = true");
}
if (hasSegmentBy)
{
string segmentList = string.Join(", ", operation.CompressionSegmentBy!.Select(QuoteIdentifier));
compressionSettings.Add($"timescaledb.compress_segmentby = '{segmentList}'");
}
if (hasOrderBy)
{
string orderList = QuoteOrderByList(operation.CompressionOrderBy!);
compressionSettings.Add($"timescaledb.compress_orderby = '{orderList}'");
}
// If there are compression settings, add the ALTER TABLE SET (...) statement
if (compressionSettings.Count > 0)
{
communityStatements.Add($"ALTER TABLE {qualifiedIdentifier} SET ({string.Join(", ", compressionSettings)});");
}
// ChunkSkipColumns (Community Edition only)
if (operation.ChunkSkipColumns != null && operation.ChunkSkipColumns.Count > 0)
{
communityStatements.Add("SET timescaledb.enable_chunk_skipping = 'ON';");
foreach (string column in operation.ChunkSkipColumns)
{
communityStatements.Add($"SELECT enable_chunk_skipping({qualifiedTableName}, '{column}');");
}
}
// AdditionalDimensions (Available in both editions)
if (operation.AdditionalDimensions != null && operation.AdditionalDimensions.Count > 0)
{
foreach (Dimension dimension in operation.AdditionalDimensions)
{
if (dimension.Type == EDimensionType.Range)
{
// Detect if interval is numeric (integer range) or time-based (timestamp range)
bool isIntegerRange = long.TryParse(dimension.Interval, out _);
string intervalExpression = isIntegerRange
? dimension.Interval!
: $"INTERVAL '{dimension.Interval}'";
statements.Add($"SELECT add_dimension({qualifiedTableName}, by_range('{dimension.ColumnName}', {intervalExpression}));");
}
else if (dimension.Type == EDimensionType.Hash)
{
statements.Add($"SELECT add_dimension({qualifiedTableName}, by_hash('{dimension.ColumnName}', {dimension.NumberOfPartitions}));");
}
}
}
// Add wrapped community statements if any exist
if (communityStatements.Count > 0)
{
statements.Add(WrapCommunityFeatures(communityStatements));
}
return statements;
}
public List<string> Generate(AlterHypertableOperation operation)
{
string qualifiedTableName = sqlHelper.Regclass(operation.TableName, operation.Schema);
string qualifiedIdentifier = sqlHelper.QualifiedIdentifier(operation.TableName, operation.Schema);
List<string> statements = [];
List<string> communityStatements = [];
// Check for ChunkTimeInterval change (Available in both editions)
if (operation.ChunkTimeInterval != operation.OldChunkTimeInterval)
{
StringBuilder setChunkTimeInterval = new();
setChunkTimeInterval.Append($"SELECT set_chunk_time_interval({qualifiedTableName}, ");
// Check if the interval is a plain number (e.g., for microseconds).
if (long.TryParse(operation.ChunkTimeInterval, out _))
{
// If it's a number, don't wrap it in quotes.
setChunkTimeInterval.Append($"{operation.ChunkTimeInterval}::bigint");
}
else
{
// If it's a string like '7 days', wrap it in quotes.
setChunkTimeInterval.Append($"INTERVAL '{operation.ChunkTimeInterval}'");
}
setChunkTimeInterval.Append(");");
statements.Add(setChunkTimeInterval.ToString());
}
List<string> compressionSettings = [];
static bool ListsChanged(IReadOnlyList<string>? oldList, IReadOnlyList<string>? newList)
{
return !(oldList ?? []).SequenceEqual(newList ?? []);
}
bool newCompressionState = operation.EnableCompression
|| (operation.ChunkSkipColumns?.Count > 0)
|| (operation.CompressionSegmentBy?.Count > 0)
|| (operation.CompressionOrderBy?.Count > 0);
bool oldCompressionState = operation.OldEnableCompression
|| (operation.OldChunkSkipColumns?.Count > 0)
|| (operation.OldCompressionSegmentBy?.Count > 0)
|| (operation.OldCompressionOrderBy?.Count > 0);
if (newCompressionState != oldCompressionState)
{
compressionSettings.Add($"timescaledb.compress = {newCompressionState.ToString().ToLower()}");
}
if (ListsChanged(operation.OldCompressionSegmentBy, operation.CompressionSegmentBy))
{
string val = (operation.CompressionSegmentBy?.Count > 0)
? $"'{string.Join(", ", operation.CompressionSegmentBy.Select(QuoteIdentifier))}'"
: "''";
compressionSettings.Add($"timescaledb.compress_segmentby = {val}");
}
if (ListsChanged(operation.OldCompressionOrderBy, operation.CompressionOrderBy))
{
string val = (operation.CompressionOrderBy?.Count > 0)
? $"'{QuoteOrderByList(operation.CompressionOrderBy)}'"
: "''";
compressionSettings.Add($"timescaledb.compress_orderby = {val}");
}
// If there are compression settings, add the ALTER TABLE SET (...) statement
if (compressionSettings.Count > 0)
{
communityStatements.Add($"ALTER TABLE {qualifiedIdentifier} SET ({string.Join(", ", compressionSettings)});");
}
// Handle ChunkSkipColumns (Community Edition only)
IReadOnlyList<string> newColumns = operation.ChunkSkipColumns ?? [];
IReadOnlyList<string> oldColumns = operation.OldChunkSkipColumns ?? [];
List<string> addedColumns = [.. newColumns.Except(oldColumns)];
if (addedColumns.Count != 0)
{
communityStatements.Add("SET timescaledb.enable_chunk_skipping = 'ON';");
foreach (string column in addedColumns)
{
communityStatements.Add($"SELECT enable_chunk_skipping({qualifiedTableName}, '{column}');");
}
}
List<string> removedColumns = [.. oldColumns.Except(newColumns)];
if (removedColumns.Count != 0)
{
foreach (string column in removedColumns)
{
communityStatements.Add($"SELECT disable_chunk_skipping({qualifiedTableName}, '{column}');");
}
}
// Handle AdditionalDimensions - only add new dimensions
// NOTE: TimescaleDB does NOT support removing dimensions from hypertables.
// Once a dimension is added, it cannot be removed. Therefore, we only generate
// SQL for adding new dimensions and ignore dimension removals.
IReadOnlyList<Dimension> newDimensions = operation.AdditionalDimensions ?? [];
IReadOnlyList<Dimension> oldDimensions = operation.OldAdditionalDimensions ?? [];
// Find dimensions that are in new but not in old (added dimensions)
foreach (Dimension newDim in newDimensions)
{
bool exists = oldDimensions.Any(oldDim =>
oldDim.ColumnName == newDim.ColumnName &&
oldDim.Type == newDim.Type &&
oldDim.Interval == newDim.Interval &&
oldDim.NumberOfPartitions == newDim.NumberOfPartitions);
if (!exists)
{
if (newDim.Type == EDimensionType.Range)
{
// Detect if interval is numeric (integer range) or time-based (timestamp range)
bool isIntegerRange = long.TryParse(newDim.Interval, out _);
string intervalExpression = isIntegerRange
? newDim.Interval!
: $"INTERVAL '{newDim.Interval}'";
statements.Add($"SELECT add_dimension({qualifiedTableName}, by_range('{newDim.ColumnName}', {intervalExpression}));");
}
else if (newDim.Type == EDimensionType.Hash)
{
statements.Add($"SELECT add_dimension({qualifiedTableName}, by_hash('{newDim.ColumnName}', {newDim.NumberOfPartitions}));");
}
}
}
// Warn if dimensions were removed (which cannot be reversed in TimescaleDB)
List<Dimension> removedDimensions = [.. oldDimensions
.Where(oldDim => !newDimensions.Any(newDim =>
oldDim.ColumnName == newDim.ColumnName &&
oldDim.Type == newDim.Type))];
if (removedDimensions.Count > 0)
{
string dimensionList = string.Join(", ", removedDimensions.Select(d => $"'{d.ColumnName}'"));
statements.Add($"-- WARNING: TimescaleDB does not support removing dimensions. The following dimensions cannot be removed: {dimensionList}");
}
// Add wrapped community statements if any exist
if (communityStatements.Count > 0)
{
statements.Add(WrapCommunityFeatures(communityStatements));
}
return statements;
}
/// <summary>
/// Wraps multiple SQL statements in a single license check block to ensure they only run on Community Edition.
/// </summary>
private static string WrapCommunityFeatures(List<string> sqlStatements)
{
StringBuilder sb = new();
sb.AppendLine("DO $$");
sb.AppendLine("DECLARE");
sb.AppendLine(" license TEXT;");
sb.AppendLine("BEGIN");
sb.AppendLine(" license := current_setting('timescaledb.license', true);");
sb.AppendLine(" ");
sb.AppendLine(" IF license IS NULL OR license != 'apache' THEN");
foreach (string sql in sqlStatements)
{
// Remove trailing semicolon and escape single quotes for EXECUTE
string cleanSql = sql.TrimEnd(';').Replace("'", "''");
sb.AppendLine($" EXECUTE '{cleanSql}';");
}
sb.AppendLine(" ELSE");
sb.AppendLine(" RAISE WARNING 'Skipping Community Edition features (compression, chunk skipping) - not available in Apache Edition';");
sb.AppendLine(" END IF;");
sb.AppendLine("END $$;");
return sb.ToString();
}
/// <summary>
/// Wraps an identifier in double quotes to preserve case-sensitivity in Postgres.
/// Escapes existing double quotes.
/// Example: TenantId -> "TenantId"
/// </summary>
private string QuoteIdentifier(string identifier)
{
return $"{quoteString}{identifier.Replace("\"", "\"\"")}{quoteString}";
}
/// <summary>
/// Quotes the column name within an ORDER BY clause while preserving direction/nulls.
/// Example: Timestamp DESC -> "Timestamp" DESC
/// </summary>
private string QuoteOrderByList(IEnumerable<string> orderByClauses)
{
return string.Join(", ", orderByClauses.Select(clause =>
{
string[] parts = clause.Split(' ', 2);
string col = parts[0];
string suffix = parts.Length > 1 ? " " + parts[1] : "";
return QuoteIdentifier(col) + suffix;
}));
}
}
}