#
Junjie
3 天以前 0c1110daa59bf77ddcff2704641280f417158c10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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") || !hasTable(connection, "sys_ai_prompt_block")) {
                log.warn("Skip AI prompt initialization because prompt tables do 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;
    }
}