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
|
/*
* Copyright (C) 2008-2017, Juick
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.juick.database;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRED;
/**
* Created by aalexeev on 12/13/16.
*/
public class MySqlUpdater {
private static final Pattern UPDATE_PATTERN = Pattern.compile(
"update\\s+(version|`version`)\\s+set\\s+(version|`version`)\\s+=\\s*(\\d+)",
Pattern.CASE_INSENSITIVE);
private final Logger logger = LoggerFactory.getLogger(getClass());
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final String updateSqlResource;
public MySqlUpdater(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager, String updateSqlResource) {
Assert.notNull(jdbcTemplate, "JdbcTemplate must be initialized");
Assert.notNull(transactionManager, "PlatformTransactionManager must be initialized");
Assert.notNull(updateSqlResource, "sqlResource must be initialized");
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.updateSqlResource = updateSqlResource;
}
@PostConstruct
public void init() {
try (
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(updateSqlResource);
) {
if (is != null) {
String content = IOUtils.toString(is, StandardCharsets.UTF_8);
if (StringUtils.isNotEmpty(content)) {
String[] sqlArray = content.split(";");
if (sqlArray.length > 0) {
List<String> sqlList = new ArrayList<>(sqlArray.length);
for (String sql : sqlArray)
if (!sql.isEmpty()) {
String sqlTrimmed = sql.trim();
if (!sqlTrimmed.isEmpty())
sqlList.add(sqlTrimmed);
}
if (!sqlList.isEmpty())
processingSql(sqlList);
}
}
}
} catch (Exception e) {
logger.error("MySqlUpdater initialization exception", e);
}
}
private void processingSql(final List<String> sqls) {
long currentDbVersion = getSingleResult(this::getVersionRaw);
long actualVersion;
List<String> changesSql = new ArrayList<>();
for (String sql : sqls) {
changesSql.add(sql);
Matcher m = UPDATE_PATTERN.matcher(sql);
if (m.matches()) {
actualVersion = Long.valueOf(m.group(3));
if (actualVersion > currentDbVersion) {
updateInTransaction(changesSql);
currentDbVersion = actualVersion;
}
changesSql.clear();
}
}
}
private void updateInTransaction(final List<String> sqls) {
transactionTemplate.setReadOnly(false);
transactionTemplate.setPropagationBehavior(PROPAGATION_REQUIRED);
transactionTemplate.execute(status -> {
for (String sql : sqls)
jdbcTemplate.execute(sql);
return 0;
});
}
private <T> T getSingleResult(Supplier<T> supplier) {
transactionTemplate.setReadOnly(true);
transactionTemplate.setPropagationBehavior(PROPAGATION_REQUIRED);
return transactionTemplate.execute(status -> supplier.get());
}
private long getVersionRaw() {
int cnt = jdbcTemplate.query(
"SELECT count(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?",
rs -> {
int result = 0;
if (rs.next())
result = rs.getInt(1);
return result;
},
"juick", "version");
long version = 0l;
if (cnt == 1) {
List<Long> list = jdbcTemplate.queryForList("select version from version", Long.class);
if (!list.isEmpty())
version = list.get(0);
}
return version;
}
}
|