Skip to content
Closed
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@

package org.springframework.ai.chat.memory.repository.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -35,7 +32,9 @@
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.lang.Nullable;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;

/**
Expand All @@ -51,13 +50,17 @@ public class JdbcChatMemoryRepository implements ChatMemoryRepository {

private final JdbcTemplate jdbcTemplate;

private final TransactionTemplate transactionTemplate;

private final JdbcChatMemoryRepositoryDialect dialect;

private JdbcChatMemoryRepository(JdbcTemplate jdbcTemplate, JdbcChatMemoryRepositoryDialect dialect) {
Assert.notNull(jdbcTemplate, "jdbcTemplate cannot be null");
Assert.notNull(dialect, "dialect cannot be null");
Assert.notNull(jdbcTemplate.getDataSource(), "dataSource can not be null");
this.jdbcTemplate = jdbcTemplate;
this.dialect = dialect;
transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
}

@Override
Expand All @@ -83,9 +86,19 @@ public void saveAll(String conversationId, List<Message> messages) {
Assert.hasText(conversationId, "conversationId cannot be null or empty");
Assert.notNull(messages, "messages cannot be null");
Assert.noNullElements(messages, "messages cannot contain null elements");
this.deleteByConversationId(conversationId);
this.jdbcTemplate.batchUpdate(dialect.getInsertMessageSql(),
new AddBatchPreparedStatement(conversationId, messages));

transactionTemplate.execute(status -> {
try {
deleteByConversationId(conversationId);
jdbcTemplate.batchUpdate(dialect.getInsertMessageSql(),
new AddBatchPreparedStatement(conversationId, messages));
}
catch (RuntimeException e) {
status.setRollbackOnly();
throw e;
}
return null;
});
}

@Override
Expand Down