-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimecodeDatabase.cs
More file actions
440 lines (387 loc) · 19.1 KB
/
Copy pathTimecodeDatabase.cs
File metadata and controls
440 lines (387 loc) · 19.1 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using StudioLog.Models;
namespace StudioLog.Core
{
public class TimecodeDatabase : IDisposable
{
private readonly string _connectionString;
private SqliteConnection? _connection;
private bool _disposed;
public TimecodeDatabase(string dbPath)
{
string? directory = Path.GetDirectoryName(dbPath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
_connectionString = $"Data Source={dbPath}";
InitializeDatabase();
}
private void InitializeDatabase()
{
_connection = new SqliteConnection(_connectionString);
_connection.Open();
var createSessionsTable = @"
CREATE TABLE IF NOT EXISTS Sessions (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
SessionName TEXT NOT NULL,
Date TEXT NOT NULL,
Location TEXT NOT NULL,
CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
ClosedAt DATETIME,
IsActive INTEGER DEFAULT 1
)";
using (var command = new SqliteCommand(createSessionsTable, _connection))
{
command.ExecuteNonQuery();
}
var createLogEntriesTable = @"
CREATE TABLE IF NOT EXISTS LogEntries (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
SessionId INTEGER NOT NULL,
TimeCodeIn TEXT NOT NULL,
TimeCodeOut TEXT,
Duration TEXT,
ClipName TEXT,
Notes TEXT,
MarkTimecode TEXT,
CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (SessionId) REFERENCES Sessions(Id)
)";
using (var command = new SqliteCommand(createLogEntriesTable, _connection))
{
command.ExecuteNonQuery();
}
var createIndexes = @"
CREATE INDEX IF NOT EXISTS idx_session_id ON LogEntries(SessionId);
CREATE INDEX IF NOT EXISTS idx_session_active ON Sessions(IsActive);
";
using (var command = new SqliteCommand(createIndexes, _connection))
{
command.ExecuteNonQuery();
}
// Migration: Add MarkTimecode column if it doesn't exist
try
{
var checkColumn = "SELECT COUNT(*) FROM pragma_table_info('LogEntries') WHERE name='MarkTimecode'";
using (var command = new SqliteCommand(checkColumn, _connection))
{
var columnExists = Convert.ToInt32(command.ExecuteScalar()) > 0;
if (!columnExists)
{
var addColumn = "ALTER TABLE LogEntries ADD COLUMN MarkTimecode TEXT";
using (var alterCommand = new SqliteCommand(addColumn, _connection))
{
alterCommand.ExecuteNonQuery();
}
}
}
}
catch (Exception)
{
// Column might already exist or migration failed - continue anyway
}
// Migration: Add ParentEntryId column if it doesn't exist
try
{
var checkColumn = "SELECT COUNT(*) FROM pragma_table_info('LogEntries') WHERE name='ParentEntryId'";
using (var command = new SqliteCommand(checkColumn, _connection))
{
var columnExists = Convert.ToInt32(command.ExecuteScalar()) > 0;
if (!columnExists)
{
var addColumn = "ALTER TABLE LogEntries ADD COLUMN ParentEntryId INTEGER NULL";
using (var alterCommand = new SqliteCommand(addColumn, _connection))
{
alterCommand.ExecuteNonQuery();
}
}
}
}
catch (Exception)
{
// Column might already exist - continue
}
// Migration: Rename ArtistName to SessionName in Sessions table
try
{
var checkColumn = "SELECT COUNT(*) FROM pragma_table_info('Sessions') WHERE name='SessionName'";
using (var command = new SqliteCommand(checkColumn, _connection))
{
var columnExists = Convert.ToInt32(command.ExecuteScalar()) > 0;
if (!columnExists)
{
using var transaction = _connection.BeginTransaction();
try
{
var migration = @"
ALTER TABLE Sessions RENAME TO Sessions_Old;
CREATE TABLE Sessions (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
SessionName TEXT NOT NULL,
Date TEXT NOT NULL,
Location TEXT NOT NULL,
CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
ClosedAt DATETIME,
IsActive INTEGER DEFAULT 1
);
INSERT INTO Sessions (Id, SessionName, Date, Location, CreatedAt, ClosedAt, IsActive)
SELECT Id, ArtistName, Date, Location, CreatedAt, ClosedAt, IsActive FROM Sessions_Old;
DROP TABLE Sessions_Old;
";
using (var alterCommand = new SqliteCommand(migration, _connection, transaction))
{
alterCommand.ExecuteNonQuery();
}
transaction.Commit();
Console.WriteLine("[DB] Migration: ArtistName -> SessionName completed");
}
catch
{
transaction.Rollback();
Console.WriteLine("[DB] Migration: ArtistName -> SessionName rolled back");
throw;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[DB] SessionName migration error: {ex.Message}");
}
// Migration: Rename SongTitle to ClipName in LogEntries table
try
{
var checkColumn = "SELECT COUNT(*) FROM pragma_table_info('LogEntries') WHERE name='ClipName'";
using (var command = new SqliteCommand(checkColumn, _connection))
{
var columnExists = Convert.ToInt32(command.ExecuteScalar()) > 0;
if (!columnExists)
{
using var transaction = _connection.BeginTransaction();
try
{
var migration = @"
ALTER TABLE LogEntries RENAME TO LogEntries_Old;
CREATE TABLE LogEntries (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
SessionId INTEGER NOT NULL,
TimeCodeIn TEXT NOT NULL,
TimeCodeOut TEXT,
Duration TEXT,
ClipName TEXT,
Notes TEXT,
MarkTimecode TEXT,
CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (SessionId) REFERENCES Sessions(Id)
);
INSERT INTO LogEntries (Id, SessionId, TimeCodeIn, TimeCodeOut, Duration, ClipName, Notes, MarkTimecode, CreatedAt)
SELECT Id, SessionId, TimeCodeIn, TimeCodeOut, Duration, SongTitle, Notes, MarkTimecode, CreatedAt FROM LogEntries_Old;
DROP TABLE LogEntries_Old;
";
using (var alterCommand = new SqliteCommand(migration, _connection, transaction))
{
alterCommand.ExecuteNonQuery();
}
transaction.Commit();
Console.WriteLine("[DB] Migration: SongTitle -> ClipName completed");
}
catch
{
transaction.Rollback();
Console.WriteLine("[DB] Migration: SongTitle -> ClipName rolled back");
throw;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[DB] ClipName migration error: {ex.Message}");
}
}
public async Task<int> CreateSession(string sessionName, string date, string location)
{
if (_connection == null) throw new InvalidOperationException("Database not initialized");
var sql = @"
INSERT INTO Sessions (SessionName, Date, Location, IsActive)
VALUES (@SessionName, @Date, @Location, 1);
SELECT last_insert_rowid();";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@SessionName", sessionName);
command.Parameters.AddWithValue("@Date", date);
command.Parameters.AddWithValue("@Location", location);
var result = await command.ExecuteScalarAsync();
return Convert.ToInt32(result);
}
public async Task<Session?> GetActiveSession()
{
if (_connection == null) return null;
var sql = "SELECT * FROM Sessions WHERE IsActive = 1 ORDER BY CreatedAt DESC LIMIT 1";
using var command = new SqliteCommand(sql, _connection);
using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
return new Session
{
Id = reader.GetInt32(0),
SessionName = reader.GetString(1),
Date = reader.GetString(2),
Location = reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
ClosedAt = reader.IsDBNull(5) ? null : reader.GetDateTime(5),
IsActive = reader.GetInt32(6) == 1
};
}
return null;
}
public async Task CloseSession(int sessionId)
{
if (_connection == null) return;
var sql = "UPDATE Sessions SET IsActive = 0, ClosedAt = @ClosedAt WHERE Id = @SessionId";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@ClosedAt", DateTime.Now);
command.Parameters.AddWithValue("@SessionId", sessionId);
await command.ExecuteNonQueryAsync();
}
public async Task<int> AddEntry(TimecodeLogEntry entry, int sessionId)
{
if (_connection == null) throw new InvalidOperationException("Database not initialized");
var sql = @"
INSERT INTO LogEntries (SessionId, TimeCodeIn, TimeCodeOut, Duration, ClipName, Notes, MarkTimecode, ParentEntryId)
VALUES (@SessionId, @TimeCodeIn, @TimeCodeOut, @Duration, @ClipName, @Notes, @MarkTimecode, @ParentEntryId);
SELECT last_insert_rowid();";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@SessionId", sessionId);
command.Parameters.AddWithValue("@TimeCodeIn", entry.TimeCodeIn);
command.Parameters.AddWithValue("@TimeCodeOut", entry.TimeCodeOut ?? "");
command.Parameters.AddWithValue("@Duration", entry.Duration ?? "");
command.Parameters.AddWithValue("@ClipName", entry.ClipName ?? "");
command.Parameters.AddWithValue("@Notes", entry.Notes ?? "");
command.Parameters.AddWithValue("@MarkTimecode", entry.MarkTimecode ?? "");
command.Parameters.AddWithValue("@ParentEntryId", (object?)entry.ParentEntryId ?? DBNull.Value);
var result = await command.ExecuteScalarAsync();
return Convert.ToInt32(result);
}
public async Task UpdateEntry(TimecodeLogEntry entry)
{
if (_connection == null) return;
var sql = @"
UPDATE LogEntries
SET TimeCodeIn = @TimeCodeIn,
TimeCodeOut = @TimeCodeOut,
Duration = @Duration,
ClipName = @ClipName,
Notes = @Notes,
MarkTimecode = @MarkTimecode,
ParentEntryId = @ParentEntryId
WHERE Id = @Id";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@TimeCodeIn", entry.TimeCodeIn ?? "");
command.Parameters.AddWithValue("@TimeCodeOut", entry.TimeCodeOut ?? "");
command.Parameters.AddWithValue("@Duration", entry.Duration ?? "");
command.Parameters.AddWithValue("@ClipName", entry.ClipName ?? "");
command.Parameters.AddWithValue("@Notes", entry.Notes ?? "");
command.Parameters.AddWithValue("@MarkTimecode", entry.MarkTimecode ?? "");
command.Parameters.AddWithValue("@ParentEntryId", (object?)entry.ParentEntryId ?? DBNull.Value);
command.Parameters.AddWithValue("@Id", entry.Id);
await command.ExecuteNonQueryAsync();
}
public async Task<List<TimecodeLogEntry>> GetSessionEntries(int sessionId)
{
if (_connection == null) return new List<TimecodeLogEntry>();
var entries = new List<TimecodeLogEntry>();
// Order: COALESCE groups each child (ParentEntryId=parent's Id) with its parent (COALESCE=own Id).
// Second term puts parent (0) before children (1) within each group. Id breaks ties by insertion order.
var sql = @"
SELECT * FROM LogEntries
WHERE SessionId = @SessionId
ORDER BY COALESCE(ParentEntryId, Id), (ParentEntryId IS NOT NULL), Id";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@SessionId", sessionId);
using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
entries.Add(new TimecodeLogEntry
{
Id = reader.GetInt32(0),
SessionId = reader.GetInt32(1),
TimeCodeIn = reader.GetString(2),
TimeCodeOut = reader.IsDBNull(3) ? "" : reader.GetString(3),
Duration = reader.IsDBNull(4) ? "" : reader.GetString(4),
ClipName = reader.IsDBNull(5) ? "" : reader.GetString(5),
Notes = reader.IsDBNull(6) ? "" : reader.GetString(6),
MarkTimecode = reader.IsDBNull(7) ? "" : reader.GetString(7),
CreatedAt = reader.GetDateTime(8),
ParentEntryId = reader.IsDBNull(9) ? null : reader.GetInt32(9)
});
}
return entries;
}
public async Task UpdateSessionInfo(Session session)
{
if (_connection == null) return;
var sql = @"
UPDATE Sessions
SET SessionName = @SessionName,
Date = @Date,
Location = @Location
WHERE Id = @Id";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@SessionName", session.SessionName);
command.Parameters.AddWithValue("@Date", session.Date);
command.Parameters.AddWithValue("@Location", session.Location);
command.Parameters.AddWithValue("@Id", session.Id);
await command.ExecuteNonQueryAsync();
}
public async Task DeleteEntry(int id)
{
if (_connection == null) return;
var sql = "DELETE FROM LogEntries WHERE Id = @Id";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@Id", id);
await command.ExecuteNonQueryAsync();
}
public async Task DeleteChildEntries(int parentId)
{
if (_connection == null) return;
var sql = "DELETE FROM LogEntries WHERE ParentEntryId = @ParentEntryId";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@ParentEntryId", parentId);
await command.ExecuteNonQueryAsync();
}
public async Task RestoreEntry(TimecodeLogEntry entry)
{
if (_connection == null) return;
var sql = @"
INSERT INTO LogEntries
(Id, SessionId, TimeCodeIn, TimeCodeOut, Duration, ClipName, Notes, MarkTimecode, CreatedAt, ParentEntryId)
VALUES
(@Id, @SessionId, @TimeCodeIn, @TimeCodeOut, @Duration, @ClipName, @Notes, @MarkTimecode, @CreatedAt, @ParentEntryId)";
using var command = new SqliteCommand(sql, _connection);
command.Parameters.AddWithValue("@Id", entry.Id);
command.Parameters.AddWithValue("@SessionId", entry.SessionId);
command.Parameters.AddWithValue("@TimeCodeIn", entry.TimeCodeIn);
command.Parameters.AddWithValue("@TimeCodeOut", entry.TimeCodeOut ?? "");
command.Parameters.AddWithValue("@Duration", entry.Duration ?? "");
command.Parameters.AddWithValue("@ClipName", entry.ClipName ?? "");
command.Parameters.AddWithValue("@Notes", entry.Notes ?? "");
command.Parameters.AddWithValue("@MarkTimecode", entry.MarkTimecode ?? "");
command.Parameters.AddWithValue("@CreatedAt", entry.CreatedAt);
command.Parameters.AddWithValue("@ParentEntryId", (object?)entry.ParentEntryId ?? DBNull.Value);
await command.ExecuteNonQueryAsync();
}
public void Dispose()
{
if (_disposed) return;
_connection?.Close();
_connection?.Dispose();
_connection = null;
_disposed = true;
}
}
}