-
Notifications
You must be signed in to change notification settings - Fork 1.3k
fix(JdbcChatMemory): get query for MSSQL Server #2806
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xchopin
wants to merge
3
commits into
spring-projects:main
Choose a base branch
from
xchopin:hotfix/jdbcchatmemory-mssql
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
...ai/model/chat/memory/jdbc/autoconfigure/JdbcChatMemoryAutoConfigurationMSSQLServerIT.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
/* | ||
* Copyright 2024-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.ai.model.chat.memory.jdbc.autoconfigure; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.springframework.ai.chat.memory.jdbc.JdbcChatMemory; | ||
import org.springframework.ai.chat.messages.AssistantMessage; | ||
import org.springframework.ai.chat.messages.Message; | ||
import org.springframework.ai.chat.messages.UserMessage; | ||
import org.springframework.boot.autoconfigure.AutoConfigurations; | ||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; | ||
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; | ||
import org.springframework.boot.test.context.runner.ApplicationContextRunner; | ||
import org.testcontainers.containers.MSSQLServerContainer; | ||
import org.testcontainers.junit.jupiter.Container; | ||
import org.testcontainers.junit.jupiter.Testcontainers; | ||
import org.testcontainers.utility.DockerImageName; | ||
|
||
import java.util.List; | ||
import java.util.UUID; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
|
||
/** | ||
* @author Xavier Chopin | ||
*/ | ||
@Testcontainers | ||
class JdbcChatMemoryAutoConfigurationMSSQLServerIT { | ||
|
||
static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("mcr.microsoft.com/mssql/server:2022-latest"); | ||
|
||
@Container | ||
@SuppressWarnings("resource") | ||
static MSSQLServerContainer<?> mssqlContainer = new MSSQLServerContainer<>(DEFAULT_IMAGE_NAME) | ||
.acceptLicense() | ||
.withEnv("MSSQL_DATABASE", "chat_memory_auto_configuration_test") | ||
.withPassword("Strong!NotR34LLyPassword"); | ||
|
||
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() | ||
.withConfiguration(AutoConfigurations.of(JdbcChatMemoryAutoConfiguration.class, | ||
JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) | ||
.withPropertyValues(String.format("spring.datasource.url=%s", mssqlContainer.getJdbcUrl()), | ||
String.format("spring.datasource.username=%s", mssqlContainer.getUsername()), | ||
String.format("spring.datasource.password=%s", mssqlContainer.getPassword())); | ||
|
||
@Test | ||
void jdbcChatMemoryScriptDatabaseInitializer_shouldBeLoaded() { | ||
this.contextRunner.withPropertyValues("spring.ai.chat.memory.jdbc.initialize-schema=true") | ||
.run(context -> assertThat(context.containsBean("jdbcChatMemoryScriptDatabaseInitializer")).isTrue()); | ||
} | ||
|
||
@Test | ||
void jdbcChatMemoryScriptDatabaseInitializer_shouldNotBeLoaded() { | ||
this.contextRunner.withPropertyValues("spring.ai.chat.memory.jdbc.initialize-schema=false") | ||
.run(context -> assertThat(context.containsBean("jdbcChatMemoryScriptDatabaseInitializer")).isFalse()); | ||
} | ||
|
||
@Test | ||
void addGetAndClear_shouldAllExecute() { | ||
this.contextRunner.withPropertyValues("spring.ai.chat.memory.jdbc.initialize-schema=true").run(context -> { | ||
var chatMemory = context.getBean(JdbcChatMemory.class); | ||
var conversationId = UUID.randomUUID().toString(); | ||
var userMessage = new UserMessage("Message from the user"); | ||
|
||
chatMemory.add(conversationId, userMessage); | ||
|
||
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).hasSize(1); | ||
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).isEqualTo(List.of(userMessage)); | ||
|
||
chatMemory.clear(conversationId); | ||
|
||
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).isEmpty(); | ||
|
||
var multipleMessages = List.<Message>of(new UserMessage("Message from the user 1"), | ||
new AssistantMessage("Message from the assistant 1")); | ||
|
||
chatMemory.add(conversationId, multipleMessages); | ||
|
||
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).hasSize(multipleMessages.size()); | ||
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).isEqualTo(multipleMessages); | ||
}); | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
...l/chat/memory/jdbc/autoconfigure/JdbcChatMemoryDataSourceScriptDatabaseMSSQLServerIT.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
/* | ||
* Copyright 2024-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.ai.model.chat.memory.jdbc.autoconfigure; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.springframework.boot.autoconfigure.AutoConfigurations; | ||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; | ||
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; | ||
import org.springframework.boot.test.context.runner.ApplicationContextRunner; | ||
import org.testcontainers.containers.MSSQLServerContainer; | ||
import org.testcontainers.junit.jupiter.Container; | ||
import org.testcontainers.junit.jupiter.Testcontainers; | ||
import org.testcontainers.utility.DockerImageName; | ||
|
||
import javax.sql.DataSource; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
|
||
/** | ||
* @author Xavier Chopin | ||
*/ | ||
@Testcontainers | ||
class JdbcChatMemoryDataSourceScriptDatabaseMSSQLServerIT { | ||
|
||
static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("mcr.microsoft.com/mssql/server:2022-latest"); | ||
|
||
@Container | ||
@SuppressWarnings("resource") | ||
static MSSQLServerContainer<?> mssqlContainer = new MSSQLServerContainer<>(DEFAULT_IMAGE_NAME) | ||
.acceptLicense() | ||
.withEnv("MSSQL_DATABASE", "chat_memory_test") | ||
.withPassword("Strong!NotR34LLyPassword"); | ||
|
||
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() | ||
.withConfiguration(AutoConfigurations.of(JdbcChatMemoryAutoConfiguration.class, | ||
JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) | ||
.withPropertyValues(String.format("spring.datasource.url=%s", mssqlContainer.getJdbcUrl()), | ||
String.format("spring.datasource.username=%s", mssqlContainer.getUsername()), | ||
String.format("spring.datasource.password=%s", mssqlContainer.getPassword())); | ||
|
||
@Test | ||
void getSettings_shouldHaveSchemaLocations() { | ||
this.contextRunner.run(context -> { | ||
var dataSource = context.getBean(DataSource.class); | ||
var settings = JdbcChatMemoryDataSourceScriptDatabaseInitializer.getSettings(dataSource); | ||
|
||
assertThat(settings.getSchemaLocations()) | ||
.containsOnly("classpath:org/springframework/ai/chat/memory/jdbc/schema-sqlserver.sql"); | ||
}); | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,27 +16,27 @@ | |
|
||
package org.springframework.ai.chat.memory.jdbc; | ||
|
||
import java.sql.PreparedStatement; | ||
import java.sql.ResultSet; | ||
import java.sql.SQLException; | ||
import java.util.List; | ||
|
||
import org.springframework.ai.chat.memory.ChatMemory; | ||
import org.springframework.ai.chat.messages.AssistantMessage; | ||
import org.springframework.ai.chat.messages.Message; | ||
import org.springframework.ai.chat.messages.MessageType; | ||
import org.springframework.ai.chat.messages.SystemMessage; | ||
import org.springframework.ai.chat.messages.UserMessage; | ||
import org.springframework.ai.chat.messages.*; | ||
import org.springframework.boot.jdbc.DatabaseDriver; | ||
import org.springframework.jdbc.core.BatchPreparedStatementSetter; | ||
import org.springframework.jdbc.core.JdbcTemplate; | ||
import org.springframework.jdbc.core.RowMapper; | ||
import org.springframework.util.Assert; | ||
|
||
import java.sql.Connection; | ||
import java.sql.PreparedStatement; | ||
import java.sql.ResultSet; | ||
import java.sql.SQLException; | ||
import java.util.List; | ||
|
||
/** | ||
* An implementation of {@link ChatMemory} for JDBC. Creating an instance of | ||
* JdbcChatMemory example: | ||
* <code>JdbcChatMemory.create(JdbcChatMemoryConfig.builder().jdbcTemplate(jdbcTemplate).build());</code> | ||
* | ||
* @author Jonathan Leijendekker | ||
* @author Xavier Chopin | ||
* @since 1.0.0 | ||
*/ | ||
public class JdbcChatMemory implements ChatMemory { | ||
|
@@ -47,12 +47,18 @@ public class JdbcChatMemory implements ChatMemory { | |
private static final String QUERY_GET = """ | ||
SELECT content, type FROM ai_chat_memory WHERE conversation_id = ? ORDER BY "timestamp" DESC LIMIT ?"""; | ||
|
||
private static final String MSSQL_QUERY_GET = """ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
I am going to check the link thank you |
||
SELECT TOP (?) content, type FROM ai_chat_memory WHERE conversation_id = ? ORDER BY "timestamp" DESC"""; | ||
|
||
private static final String QUERY_CLEAR = "DELETE FROM ai_chat_memory WHERE conversation_id = ?"; | ||
|
||
private final JdbcTemplate jdbcTemplate; | ||
|
||
private final DatabaseDriver driver; | ||
|
||
public JdbcChatMemory(JdbcChatMemoryConfig config) { | ||
this.jdbcTemplate = config.getJdbcTemplate(); | ||
this.driver = this.detectDatabaseDriver(this.jdbcTemplate); | ||
} | ||
|
||
public static JdbcChatMemory create(JdbcChatMemoryConfig config) { | ||
|
@@ -66,16 +72,19 @@ public void add(String conversationId, List<Message> messages) { | |
|
||
@Override | ||
public List<Message> get(String conversationId, int lastN) { | ||
return this.jdbcTemplate.query(QUERY_GET, new MessageRowMapper(), conversationId, lastN); | ||
return switch (driver) { | ||
case SQLSERVER -> this.jdbcTemplate.query(MSSQL_QUERY_GET, new MessageRowMapper(), lastN, conversationId); | ||
default -> this.jdbcTemplate.query(QUERY_GET, new MessageRowMapper(), conversationId, lastN); | ||
}; | ||
} | ||
|
||
@Override | ||
public void clear(String conversationId) { | ||
this.jdbcTemplate.update(QUERY_CLEAR, conversationId); | ||
} | ||
|
||
private record AddBatchPreparedStatement(String conversationId, | ||
List<Message> messages) implements BatchPreparedStatementSetter { | ||
private record AddBatchPreparedStatement(String conversationId, List<Message> messages) | ||
implements BatchPreparedStatementSetter { | ||
@Override | ||
public void setValues(PreparedStatement ps, int i) throws SQLException { | ||
var message = this.messages.get(i); | ||
|
@@ -108,4 +117,14 @@ public Message mapRow(ResultSet rs, int i) throws SQLException { | |
|
||
} | ||
|
||
private DatabaseDriver detectDatabaseDriver(JdbcTemplate jdbcTemplate) { | ||
Assert.notNull(jdbcTemplate.getDataSource(), "jdbcTemplate.dataSource must not be null"); | ||
try { | ||
Connection conn = jdbcTemplate.getDataSource().getConnection(); | ||
String url = conn.getMetaData().getURL(); | ||
return DatabaseDriver.fromJdbcUrl(url); | ||
} catch (SQLException ex) { | ||
throw new IllegalStateException("Impossible to detect the database driver", ex); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
spring-data-jdbc
instead of the starter.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I will have to change org.springframework.boot.jdbc.DatabaseDriver then
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@xchopin btw, it is worth considering
spring-data-jdbc
repositories directly instead of manual query creations at this point. I added a comment to the PR.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@leijendary is it still worth it to move to spring-data-jdbc with this incoming PR?
#2803
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@xchopin Yes it is still worth it. The implementation in that PR is the same as the current implementation wherein it uses driver specific syntax. We should probably wait for that PR to be merged though as it is a conflict.