Skip to content
Closed
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 @@ -16,15 +16,22 @@

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

import java.sql.Connection;
import java.sql.DatabaseMetaData;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.jdbc.support.JdbcUtils;

/**
* Abstraction for database-specific SQL for chat memory repository.
*/
public interface JdbcChatMemoryRepositoryDialect {

Logger logger = LoggerFactory.getLogger(JdbcChatMemoryRepositoryDialect.class);

/**
* Returns the SQL to fetch messages for a conversation, ordered by timestamp, with
* limit.
Expand All @@ -51,32 +58,29 @@ public interface JdbcChatMemoryRepositoryDialect {
*/

/**
* Detects the dialect from the DataSource or JDBC URL.
* Detects the dialect from the DataSource.
*/
static JdbcChatMemoryRepositoryDialect from(DataSource dataSource) {
// Simple detection (could be improved)
try (Connection connection = dataSource.getConnection()) {
String url = connection.getMetaData().getURL().toLowerCase();
if (url.contains("postgresql")) {
return new PostgresChatMemoryRepositoryDialect();
}
if (url.contains("mysql")) {
return new MysqlChatMemoryRepositoryDialect();
}
if (url.contains("mariadb")) {
return new MysqlChatMemoryRepositoryDialect();
}
if (url.contains("sqlserver")) {
return new SqlServerChatMemoryRepositoryDialect();
}
if (url.contains("hsqldb")) {
return new HsqldbChatMemoryRepositoryDialect();
}
// Add more as needed
String productName = null;
try {
productName = JdbcUtils.extractDatabaseMetaData(dataSource, DatabaseMetaData::getDatabaseProductName);
}
catch (Exception e) {
logger.warn("Due to failure in establishing JDBC connection or parsing metadata, the JDBC database vendor "
+ "could not be determined", e);
}
catch (Exception ignored) {
if (productName == null || productName.trim().isEmpty()) {
logger.warn("Database product name is null or empty, defaulting to Postgres dialect.");
return new PostgresChatMemoryRepositoryDialect();
}
return new PostgresChatMemoryRepositoryDialect(); // default
return switch (productName) {
case "PostgreSQL" -> new PostgresChatMemoryRepositoryDialect();
case "MySQL", "MariaDB" -> new MysqlChatMemoryRepositoryDialect();
case "Microsoft SQL Server" -> new SqlServerChatMemoryRepositoryDialect();
case "HSQL Database Engine" -> new HsqldbChatMemoryRepositoryDialect();
default -> // Add more as needed
new PostgresChatMemoryRepositoryDialect();
};
}

}