Skip to content

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
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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 @@ -55,6 +55,13 @@
<scope>test</scope>
</dependency>


<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
Expand All @@ -66,6 +73,12 @@
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mssqlserver</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
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);
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,7 @@

package org.springframework.ai.model.chat.memory.jdbc.autoconfigure;

import java.util.List;
import java.util.UUID;

import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

import org.springframework.ai.chat.memory.jdbc.JdbcChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
Expand All @@ -33,14 +25,21 @@
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.PostgreSQLContainer;
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 Jonathan Leijendekker
*/
@Testcontainers
class JdbcChatMemoryAutoConfigurationIT {
class JdbcChatMemoryAutoConfigurationPostgresIT {

static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("postgres:17");

Expand Down
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");
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,25 @@

package org.springframework.ai.model.chat.memory.jdbc.autoconfigure;

import javax.sql.DataSource;

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.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

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 javax.sql.DataSource;

import static org.assertj.core.api.Assertions.assertThat;

/**
* @author Jonathan Leijendekker
*/
@Testcontainers
class JdbcChatMemoryDataSourceScriptDatabaseInitializerTests {
class JdbcChatMemoryDataSourceScriptDatabasePostgresIT {

static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("postgres:17");

Expand Down
16 changes: 14 additions & 2 deletions memory/spring-ai-model-chat-memory-jdbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
Copy link
Contributor

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.

Copy link
Author

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

Copy link
Contributor

@leijendary leijendary Apr 19, 2025

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.

Copy link
Author

@xchopin xchopin Apr 19, 2025

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

Copy link
Contributor

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.

</dependency>

<dependency>
Expand All @@ -69,6 +69,12 @@
<optional>true</optional>
</dependency>

<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<optional>true</optional>
</dependency>

<!-- TESTING -->
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -82,6 +88,12 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mssqlserver</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 = """
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Same as previous comment regarding utilising text block alignments; you can move the string content 1 tab to the right.
  2. ORDER BY should be DESC since we're querying lastN not the first n. Refer to Fixed message order for JDBC Chat Memory #2781 for the additional fix.

Copy link
Author

@xchopin xchopin Apr 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. ok, I will fix it
  2. putting DESC actually breaks the test and returns the list in a backward side, so either the one in Postgres is broken or there is something weird between the two behaviors

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) {
Expand All @@ -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);
Expand Down Expand Up @@ -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);
}
}
}
Loading