| New file |
| | |
| | | package com.zy.ai.config; |
| | | |
| | | import com.zy.ai.service.AiPromptTemplateService; |
| | | import jakarta.annotation.PostConstruct; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.sql.DataSource; |
| | | import java.sql.Connection; |
| | | import java.sql.DatabaseMetaData; |
| | | import java.sql.ResultSet; |
| | | |
| | | @Slf4j |
| | | @Component |
| | | public class AiPromptTemplateInitializer { |
| | | |
| | | private final DataSource dataSource; |
| | | private final AiPromptTemplateService aiPromptTemplateService; |
| | | |
| | | public AiPromptTemplateInitializer(DataSource dataSource, AiPromptTemplateService aiPromptTemplateService) { |
| | | this.dataSource = dataSource; |
| | | this.aiPromptTemplateService = aiPromptTemplateService; |
| | | } |
| | | |
| | | @PostConstruct |
| | | public void init() { |
| | | try (Connection connection = dataSource.getConnection()) { |
| | | if (!hasTable(connection, "sys_ai_prompt_template")) { |
| | | log.warn("Skip AI prompt initialization because table sys_ai_prompt_template does not exist"); |
| | | return; |
| | | } |
| | | int changed = aiPromptTemplateService.initDefaultsIfMissing(); |
| | | log.info("AI prompt templates initialized, insertedOrRecovered={}", changed); |
| | | } catch (Exception e) { |
| | | log.warn("Failed to initialize AI prompt templates", e); |
| | | } |
| | | } |
| | | |
| | | private boolean hasTable(Connection connection, String tableName) throws Exception { |
| | | DatabaseMetaData metaData = connection.getMetaData(); |
| | | try (ResultSet resultSet = metaData.getTables(connection.getCatalog(), null, tableName, new String[]{"TABLE"})) { |
| | | while (resultSet.next()) { |
| | | if (tableName.equalsIgnoreCase(resultSet.getString("TABLE_NAME"))) { |
| | | return true; |
| | | } |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | } |