gaoluyang
2026-10-16 7081c41bc3beb0ab49a22974ea4b010ae6854afe
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package cn.iocoder.yudao.module.infra.service.db;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.util.JdbcUtils;
import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigImportExcelVO;
import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigImportReqVO;
import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigImportRespVO;
import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigSaveReqVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO;
import cn.iocoder.yudao.module.infra.dal.mysql.db.DataSourceConfigMapper;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
 
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.DATA_SOURCE_CONFIG_IMPORT_LIST_IS_EMPTY;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.DATA_SOURCE_CONFIG_IMPORT_NAME_EXISTS;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.DATA_SOURCE_CONFIG_NOT_EXISTS;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.DATA_SOURCE_CONFIG_NOT_OK;
 
/**
 * 数据源配置 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class DataSourceConfigServiceImpl implements DataSourceConfigService {
 
    @Resource
    private DataSourceConfigMapper dataSourceConfigMapper;
 
    @Resource
    private DynamicDataSourceProperties dynamicDataSourceProperties;
 
    @Override
    public Long createDataSourceConfig(DataSourceConfigSaveReqVO createReqVO) {
        DataSourceConfigDO config = BeanUtils.toBean(createReqVO, DataSourceConfigDO.class);
        validateConnectionOK(config);
 
        // 插入
        dataSourceConfigMapper.insert(config);
        // 返回
        return config.getId();
    }
 
    @Override
    public void updateDataSourceConfig(DataSourceConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateDataSourceConfigExists(updateReqVO.getId());
        DataSourceConfigDO updateObj = BeanUtils.toBean(updateReqVO, DataSourceConfigDO.class);
        validateConnectionOK(updateObj);
 
        // 更新
        dataSourceConfigMapper.updateById(updateObj);
    }
 
    @Override
    public void deleteDataSourceConfig(Long id) {
        // 校验存在
        validateDataSourceConfigExists(id);
        // 删除
        dataSourceConfigMapper.deleteById(id);
    }
 
    @Override
    public void deleteDataSourceConfigList(List<Long> ids) {
        dataSourceConfigMapper.deleteByIds(ids);
    }
 
    private void validateDataSourceConfigExists(Long id) {
        if (dataSourceConfigMapper.selectById(id) == null) {
            throw exception(DATA_SOURCE_CONFIG_NOT_EXISTS);
        }
    }
 
    @Override
    public DataSourceConfigDO getDataSourceConfig(Long id) {
        // 如果 id 为 0,默认为 master 的数据源
        if (Objects.equals(id, DataSourceConfigDO.ID_MASTER)) {
            return buildMasterDataSourceConfig();
        }
        // 从 DB 中读取
        return dataSourceConfigMapper.selectById(id);
    }
 
    @Override
    public List<DataSourceConfigDO> getDataSourceConfigList() {
        List<DataSourceConfigDO> result = dataSourceConfigMapper.selectList();
        // 补充 master 数据源
        result.add(0, buildMasterDataSourceConfig());
        return result;
    }
 
    private void validateConnectionOK(DataSourceConfigDO config) {
        boolean success = JdbcUtils.isConnectionOK(config.getUrl(), config.getUsername(), config.getPassword());
        if (!success) {
            throw exception(DATA_SOURCE_CONFIG_NOT_OK);
        }
    }
 
    private DataSourceConfigDO buildMasterDataSourceConfig() {
        String primary = dynamicDataSourceProperties.getPrimary();
        DataSourceProperty dataSourceProperty = dynamicDataSourceProperties.getDatasource().get(primary);
        return new DataSourceConfigDO().setId(DataSourceConfigDO.ID_MASTER).setName(primary)
                .setUrl(dataSourceProperty.getUrl())
                .setUsername(dataSourceProperty.getUsername())
                .setPassword(dataSourceProperty.getPassword());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataSourceConfigImportRespVO importDataSourceConfigList(List<DataSourceConfigImportExcelVO> importDataSourceConfigs,
                                                                   DataSourceConfigImportReqVO importReqVO) {
        // 1. 校验非空
        importDataSourceConfigs = filterList(importDataSourceConfigs, item -> StrUtil.isNotBlank(item.getName()));
        if (CollUtil.isEmpty(importDataSourceConfigs)) {
            throw exception(DATA_SOURCE_CONFIG_IMPORT_LIST_IS_EMPTY);
        }
        // 2. 逐条处理
        DataSourceConfigImportRespVO respVO = DataSourceConfigImportRespVO.builder()
                .createDataSourceConfigNames(new ArrayList<>())
                .updateDataSourceConfigNames(new ArrayList<>())
                .failureDataSourceConfigNames(new LinkedHashMap<>())
                .build();
        importDataSourceConfigs.forEach(importConfig -> {
            try {
                DataSourceConfigDO existConfig = dataSourceConfigMapper.selectByName(importConfig.getName());
                if (existConfig == null) {
                    // 新增
                    DataSourceConfigDO config = BeanUtils.toBean(importConfig, DataSourceConfigDO.class);
                    dataSourceConfigMapper.insert(config);
                    respVO.getCreateDataSourceConfigNames().add(importConfig.getName());
                    return;
                }
                // 已存在,判断是否允许更新
                if (!importReqVO.getUpdateSupport()) {
                    respVO.getFailureDataSourceConfigNames().put(importConfig.getName(),
                            StrUtil.format(DATA_SOURCE_CONFIG_IMPORT_NAME_EXISTS.getMsg(), importConfig.getName()));
                    return;
                }
                DataSourceConfigDO updateConfig = BeanUtils.toBean(importConfig, DataSourceConfigDO.class)
                        .setId(existConfig.getId());
                dataSourceConfigMapper.updateById(updateConfig);
                respVO.getUpdateDataSourceConfigNames().add(importConfig.getName());
            } catch (ServiceException ex) {
                respVO.getFailureDataSourceConfigNames().put(importConfig.getName(), ex.getMessage());
            }
        });
        return respVO;
    }
 
}