forked from liquibase/liquibase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OfflineConnection.java
350 lines (303 loc) · 12 KB
/
OfflineConnection.java
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package liquibase.database;
import liquibase.Scope;
import liquibase.changelog.ChangeLogHistoryService;
import liquibase.changelog.ChangeLogHistoryServiceFactory;
import liquibase.changelog.OfflineChangeLogHistoryService;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.parser.SnapshotParser;
import liquibase.parser.SnapshotParserFactory;
import liquibase.resource.ResourceAccessor;
import liquibase.servicelocator.LiquibaseService;
import liquibase.snapshot.DatabaseSnapshot;
import liquibase.snapshot.EmptyDatabaseSnapshot;
import liquibase.snapshot.InvalidExampleException;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Catalog;
import liquibase.structure.core.Schema;
import liquibase.util.ObjectUtil;
import liquibase.util.StringUtil;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Driver;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@LiquibaseService(skip=true)
public class OfflineConnection implements DatabaseConnection {
private String url=null;
private String databaseShortName=null;
private final Map<String, String> databaseParams = new HashMap<>();
private DatabaseSnapshot snapshot;
private OutputLiquibaseSql outputLiquibaseSql = OutputLiquibaseSql.NONE;
private String changeLogFile = "databasechangelog.csv";
private boolean caseSensitive;
private String productName;
private String productVersion;
private int databaseMajorVersion = 999;
private int databaseMinorVersion = 999;
private String catalog;
private boolean sendsStringParametersAsUnicode = true;
private String connectionUserName;
public OfflineConnection() {}
public OfflineConnection(String url, ResourceAccessor resourceAccessor) {
this.url = url;
Matcher matcher = Pattern.compile("offline:(\\w+)\\??(.*)").matcher(url);
if (!matcher.matches()) {
throw new UnexpectedLiquibaseException("Could not parse offline url " + url);
}
this.databaseShortName = matcher.group(1).toLowerCase();
String params = StringUtil.trimToNull(matcher.group(2));
try {
Map<String, String> params1 = new HashMap<String, String>();
if (params != null) {
String[] keyValues = params.split("&");
for (String param : keyValues) {
String[] split = param.split("=");
params1.put(URLDecoder.decode(split[0], "UTF-8"), URLDecoder.decode(split[1], "UTF-8"));
}
}
this.productName = "Offline " + databaseShortName;
for (Map.Entry<String, String> paramEntry : params1.entrySet()) {
if ("version".equals(paramEntry.getKey())) {
this.productVersion = paramEntry.getValue();
String[] versionParts = productVersion.split("\\.");
try {
this.databaseMajorVersion = Integer.parseInt(versionParts[0]);
if (versionParts.length > 1) {
this.databaseMinorVersion = Integer.parseInt(versionParts[1]);
}
} catch (NumberFormatException e) {
Scope.getCurrentScope().getLog(getClass()).warning("Cannot parse database version " + productVersion);
}
} else if ("productName".equals(paramEntry.getKey())) {
this.productName = paramEntry.getValue();
} else if ("catalog".equals(paramEntry.getKey())) {
this.catalog = params1.get("catalog");
} else if ("caseSensitive".equals(paramEntry.getKey())) {
this.caseSensitive = Boolean.parseBoolean(paramEntry.getValue());
} else if ("changeLogFile".equals(paramEntry.getKey())) {
this.changeLogFile = paramEntry.getValue();
} else if ("outputLiquibaseSql".equals(paramEntry.getKey())) {
this.outputLiquibaseSql = OutputLiquibaseSql.fromString(paramEntry.getValue());
} else if ("snapshot".equals(paramEntry.getKey())) {
String snapshotFile = paramEntry.getValue();
try {
SnapshotParser parser = SnapshotParserFactory.getInstance()
.getParser(snapshotFile, resourceAccessor);
this.snapshot = parser.parse(snapshotFile, resourceAccessor);
this.productVersion = this.snapshot.getDatabase().getDatabaseProductVersion();
this.snapshot.getDatabase().setConnection(this);
for (Catalog catalog : this.snapshot.get(Catalog.class)) {
if (catalog.isDefault()) {
this.catalog = catalog.getName();
}
}
} catch (LiquibaseException e) {
throw new UnexpectedLiquibaseException("Cannot parse snapshot " + url, e);
}
} else if ("sendsStringParametersAsUnicode".equals(paramEntry.getKey())) {
this.sendsStringParametersAsUnicode = Boolean.parseBoolean(paramEntry.getValue());
} else {
this.databaseParams.put(paramEntry.getKey(), paramEntry.getValue());
}
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
public boolean isCorrectDatabaseImplementation(Database database) {
return database.getShortName().equalsIgnoreCase(databaseShortName);
}
@Override
public void open(String url, Driver driverObject, Properties driverProperties) throws DatabaseException {
//
// No-op
//
}
@Override
public void attached(Database database) {
for (Map.Entry<String, String> param : this.databaseParams.entrySet()) {
try {
ObjectUtil.setProperty(database, param.getKey(), param.getValue());
} catch (Exception e) {
Scope.getCurrentScope().getLog(getClass()).warning("Error setting database parameter " + param.getKey() + ": " + e.getMessage(), e);
}
}
if (database instanceof AbstractJdbcDatabase) {
((AbstractJdbcDatabase) database).setCaseSensitive(this.caseSensitive);
}
if (snapshot == null) {
try {
snapshot = new EmptyDatabaseSnapshot(database);
} catch (DatabaseException | InvalidExampleException e) {
throw new UnexpectedLiquibaseException(e);
}
}
ChangeLogHistoryServiceFactory.getInstance().register(createChangeLogHistoryService(database));
}
protected ChangeLogHistoryService createChangeLogHistoryService(Database database) {
return new OfflineChangeLogHistoryService(database, new File(changeLogFile),
outputLiquibaseSql != OutputLiquibaseSql.NONE, // Output DML
outputLiquibaseSql == OutputLiquibaseSql.ALL // Output DDL
);
}
/**
* Returns a copy of the current simulated content of the database, filtered by the given
* array.
*
* @param examples the list of objects to clone
* @return a new DatabaseSnapshot object containing all objects matching examples. If none are found,
* an empty DatabaseSnapshot is returned.
*/
public DatabaseSnapshot getSnapshot(DatabaseObject[] examples) {
return this.snapshot.clone(examples);
}
/**
* For debugging purposes: sets a DatabaseSnapshot object for this connection. Effectively,
* this simulates the content of the database in this OfflineConnection.
*
* @param snapshot the snapshot with the simulated database content
*/
public void setSnapshot(DatabaseSnapshot snapshot) {
this.snapshot = snapshot;
this.snapshot.getDatabase().setConnection(this);
for (Catalog catalog : this.snapshot.get(Catalog.class)) {
if (catalog.isDefault()) {
this.catalog = catalog.getName();
}
}
}
@Override
public void close() throws DatabaseException {
//nothing
}
@Override
public void commit() throws DatabaseException {
//nothing
}
@Override
public boolean getAutoCommit() throws DatabaseException {
return false;
}
@Override
public void setAutoCommit(boolean autoCommit) throws DatabaseException {
}
@Override
public String getCatalog() throws DatabaseException {
return catalog;
}
public String getSchema() {
if (snapshot == null) {
return null;
}
for (Schema schema : snapshot.get(Schema.class)) {
if (schema.isDefault()) {
return schema.getName();
}
}
return null;
}
@Override
public String nativeSQL(String sql) throws DatabaseException {
return sql;
}
@Override
public void rollback() throws DatabaseException {
}
@Override
public String getDatabaseProductName() throws DatabaseException {
return productName;
}
@Override
public String getDatabaseProductVersion() throws DatabaseException {
return productVersion;
}
@Override
public int getDatabaseMajorVersion() throws DatabaseException {
return databaseMajorVersion;
}
public void setDatabaseMajorVersion(int databaseMajorVersion) {
this.databaseMajorVersion = databaseMajorVersion;
}
public void setProductVersion(String productVersion) {
this.productVersion = productVersion;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Override
public int getDatabaseMinorVersion() throws DatabaseException {
return databaseMinorVersion;
}
public void setDatabaseMinorVersion(int databaseMinorVersion) {
this.databaseMinorVersion = databaseMinorVersion;
}
@Override
public String getURL() {
return url;
}
@Override
public String getConnectionUserName() {
return connectionUserName;
}
public void setConnectionUserName(String connectionUserName) {
this.connectionUserName = StringUtil.isEmpty(connectionUserName) ? null : connectionUserName;
}
@Override
public boolean isClosed() throws DatabaseException {
return false;
}
public boolean getSendsStringParametersAsUnicode() {
return sendsStringParametersAsUnicode;
}
public void setSendsStringParametersAsUnicode(boolean sendsStringParametersAsUnicode) {
this.sendsStringParametersAsUnicode = sendsStringParametersAsUnicode;
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/**
* Output Liquibase SQL
*/
private enum OutputLiquibaseSql {
/**
* Don't output anything
*/
NONE,
/**
* Output only INSERT/UPDATE/DELETE
*/
DATA_ONLY,
/**
* Output CREATE TABLE as well
*/
ALL;
public static OutputLiquibaseSql fromString(String s) {
if (s == null) {
return null;
}
s = s.toUpperCase();
// For backward compatibility true is translated in ALL and false in NONE
switch (s) {
case "TRUE":
return ALL;
case "FALSE":
return NONE;
default:
return valueOf(s);
}
}
}
}