DB: Message + Attachments in einer Transaktion speichern (1x fsync statt N+1)
This commit is contained in:
1 parent
1271c9c651
commit
0b2c9a08c6
2 files changed
+43
-25
No files matched your search
@@ -360,18 +360,42 @@ public class DatabaseService
|
||||
", record);
|
||||
}
|
||||
|
||||
// ── Attachments ──
|
||||
|
||||
public async Task SaveAttachment(AttachmentRecord attachment)
|
||||
/// <summary>
|
||||
/// Speichert Message + Attachments in einer Transaktion (1x fsync statt N+1).
|
||||
/// </summary>
|
||||
public async Task<long> SaveMessageWithAttachments(MessageRecord record, List<AttachmentRecord> attachments)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
attachment.CreatedAt = DateTime.UtcNow.ToString("o");
|
||||
await conn.ExecuteAsync(@"
|
||||
INSERT INTO attachments (message_id, type, media_type, file_name, data, created_at)
|
||||
VALUES (@MessageId, @Type, @MediaType, @FileName, @Data, @CreatedAt)
|
||||
", attachment);
|
||||
using var tx = conn.BeginTransaction();
|
||||
|
||||
record.CreatedAt = DateTime.UtcNow.ToString("o");
|
||||
record.AttachmentCount = attachments?.Count ?? 0;
|
||||
var messageId = await conn.ExecuteScalarAsync<long>(@"
|
||||
INSERT INTO messages (chain_id, role, type, content, tool_name, tool_call_id, is_error, iteration, attachment_count, created_at)
|
||||
VALUES (@ChainId, @Role, @Type, @Content, @ToolName, @ToolCallId, @IsError, @Iteration, @AttachmentCount, @CreatedAt);
|
||||
SELECT last_insert_rowid();
|
||||
", record, tx);
|
||||
|
||||
if (attachments != null)
|
||||
{
|
||||
var now = DateTime.UtcNow.ToString("o");
|
||||
foreach (var att in attachments)
|
||||
{
|
||||
att.MessageId = messageId;
|
||||
att.CreatedAt = now;
|
||||
await conn.ExecuteAsync(@"
|
||||
INSERT INTO attachments (message_id, type, media_type, file_name, data, created_at)
|
||||
VALUES (@MessageId, @Type, @MediaType, @FileName, @Data, @CreatedAt)
|
||||
", att, tx);
|
||||
}
|
||||
}
|
||||
|
||||
tx.Commit();
|
||||
return messageId;
|
||||
}
|
||||
|
||||
// ── Attachments ──
|
||||
|
||||
public async Task<IEnumerable<AttachmentRecord>> GetAttachments(long messageId)
|
||||
{
|
||||
using var conn = CreateConnection();
|
||||
|
||||
Reference in new issue
Block a user