/
TableCopy.java
307 lines (269 loc) · 11.8 KB
/
TableCopy.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
package org.jumpmind.symmetric.jdbc.tools;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.jumpmind.symmetric.core.common.IoUtils;
import org.jumpmind.symmetric.core.common.Log;
import org.jumpmind.symmetric.core.common.LogFactory;
import org.jumpmind.symmetric.core.db.IDbDialect;
import org.jumpmind.symmetric.core.db.TableNotFoundException;
import org.jumpmind.symmetric.core.model.Batch;
import org.jumpmind.symmetric.core.model.Data;
import org.jumpmind.symmetric.core.model.Parameters;
import org.jumpmind.symmetric.core.model.Table;
import org.jumpmind.symmetric.core.process.AbstractDataProcessorListener;
import org.jumpmind.symmetric.core.process.DataContext;
import org.jumpmind.symmetric.core.process.DataProcessor;
import org.jumpmind.symmetric.core.process.IDataFilter;
import org.jumpmind.symmetric.core.process.IDataWriter;
import org.jumpmind.symmetric.core.process.csv.CsvDataReader;
import org.jumpmind.symmetric.core.process.csv.FileCsvDataWriter;
import org.jumpmind.symmetric.core.process.sql.SqlDataWriter;
import org.jumpmind.symmetric.core.process.sql.SqlTableDataReader;
import org.jumpmind.symmetric.core.process.sql.TableToExtract;
import org.jumpmind.symmetric.jdbc.db.JdbcDbDialectFactory;
import org.jumpmind.symmetric.jdbc.tools.copy.TableCopyProperties;
public class TableCopy {
static final Log logger = LogFactory.getLog(TableCopy.class);
public static void main(String[] args) {
try {
if (args != null && args.length > 0) {
File propFile = new File(args[0]);
if (propFile.exists() && !propFile.isDirectory()) {
TableCopyProperties properties = new TableCopyProperties(propFile);
new TableCopy(properties).copy();
System.exit(0);
} else {
System.err.println(String.format("Could not find the properties file named %s",
args[0]));
System.exit(-1);
}
} else {
System.err
.println("Please provide the name of a configuration file as an argument to this utility. Example content is as follows:");
System.err.println();
System.err.println(IoUtils.toString(TableCopyProperties.getExampleInputStream()));
System.exit(-1);
}
} catch (TableNotFoundException ex) {
logger.error(ex.getMessage());
System.exit(-1);
} catch (IllegalStateException ex) {
logger.error(ex.getMessage());
System.exit(-1);
} catch (Exception ex) {
logger.error(ex);
System.exit(-1);
}
}
protected DataSource sourceDataSource;
protected DataSource targetDataSource;
protected IDbDialect targetDbDialect;
protected IDbDialect sourceDbDialect;
protected Parameters parameters;
protected List<TableToExtract> tablesToRead;
protected File[] sourceFiles;
protected File targetFileDir;
public TableCopy() {
}
public TableCopy(TableCopyProperties properties) {
this.parameters = new Parameters(properties);
this.sourceFiles = properties.getSourceFiles();
if (this.sourceFiles == null || this.sourceFiles.length == 0) {
this.sourceDataSource = properties.getSourceDataSource();
this.sourceDbDialect = JdbcDbDialectFactory
.createPlatform(sourceDataSource, parameters);
}
this.targetFileDir = properties.getTargetFileDir();
if (targetFileDir == null) {
this.targetDataSource = properties.getTargetDataSource();
this.targetDbDialect = JdbcDbDialectFactory
.createPlatform(targetDataSource, parameters);
}
IDbDialect dialect2UseForMetadataLookup = sourceDbDialect != null ? sourceDbDialect
: targetDbDialect;
String[] tableNames = properties.getTables();
tablesToRead = new ArrayList<TableToExtract>();
for (String tableName : tableNames) {
Table table = dialect2UseForMetadataLookup.findTable(properties.getSourceCatalog(),
properties.getSourceSchema(), tableName, false);
if (table != null) {
String condition = properties.getConditionForTable(tableName);
table.setSchemaName(null);
table.setCatalogName(null);
tablesToRead.add(new TableToExtract(table, condition));
} else {
if (sourceDbDialect != null
|| !parameters.is(Parameters.LOADER_CREATE_TABLE_IF_DOESNT_EXIST, false)) {
throw new TableNotFoundException(tableName);
}
}
}
}
public void copy() {
if (parameters.is(Parameters.LOADER_DELETE_FIRST, false)) {
delete(tablesToRead);
}
if (sourceFiles == null) {
this.copyFromTables(tablesToRead);
} else {
this.copyFromFiles(sourceFiles);
}
}
public void delete(List<TableToExtract> tables) {
if (tables != null) {
for (int i = tables.size() - 1; i >= 0; i--) {
TableToExtract tableToDelete = tables.get(i);
logger.info("(%d of %d) Deleting table %s ", tables.size() - i, tables.size(),
tableToDelete.getTable().getTableName());
this.targetDbDialect.getSqlTemplate().delete(tableToDelete.getTable(), null);
}
}
}
public void copyFromTables(List<TableToExtract> tables) {
long batchId = 1;
for (TableToExtract tableToRead : tables) {
logger.info("(%d of %d) Copying table %s ", batchId, tables.size(), tableToRead
.getTable().getTableName());
Batch batch = new Batch(batchId++);
int expectedCount = this.sourceDbDialect.getSqlTemplate().queryForInt(
this.sourceDbDialect.getDataCaptureBuilder().createTableExtractCountSql(
tableToRead, parameters));
long ts = System.currentTimeMillis();
DataProcessor processor = new DataProcessor(new SqlTableDataReader(
this.sourceDbDialect, batch, tableToRead), getDataWriter(true, expectedCount));
processor.process(new DataContext(parameters));
long totalTableCopyTime = System.currentTimeMillis() - ts;
logger.info(
"It took %d ms to copy %d rows from table %s. It took %d ms to read the data and %d ms to write the data.",
totalTableCopyTime, batch.getLineCount(),
tableToRead.getTable().getTableName(), batch.getDataReadMillis(),
batch.getDataWriteMillis());
}
}
public void copyFromFiles(File[] sourceFiles) {
for (File file : sourceFiles) {
if (file.exists()) {
long ts = System.currentTimeMillis();
DataProcessor processor = new DataProcessor(new CsvDataReader(file), getDataWriter(
false, file.length()));
LoadListenerListener loadListener = new LoadListenerListener();
processor.setListener(loadListener);
processor.process(new DataContext(parameters));
long totalTableCopyTime = System.currentTimeMillis() - ts;
if (loadListener.getTable() != null) {
Batch batch = loadListener.getBatch();
logger.info(
"It took %d ms to copy %d rows from table %s. It took %d ms to read the data and %d ms to write the data. %d rows were inserted.",
totalTableCopyTime, batch.getLineCount(), loadListener.getTable()
.getTableName(), batch.getDataReadMillis(), batch
.getDataWriteMillis(), batch.getInsertCount());
if (batch.getFallbackUpdateCount() > 0) {
logger.info(
"The data loader fell back to an update %d times during the load",
batch.getFallbackUpdateCount());
}
if (batch.getInsertCollisionCount() > 0) {
logger.info(
"The data loader collided %d times during the load. All row collisions were ignored.",
batch.getInsertCollisionCount());
}
}
} else {
logger.error("Could not find " + file.getName());
}
}
}
/**
* @param expectedSizeIsInRows
* If true, the expected size will be in row count format. If
* false, the expected size will be in bytes.
* @param expectedSize
* @return
*/
protected IDataWriter getDataWriter(final boolean expectedSizeIsInRows, final long expectedSize) {
IDataFilter progressFilter = new IDataFilter() {
long statementCount = 0;
long currentBatchSize = 0;
long totalBatchSize = 0;
int percent = 0;
public boolean filter(DataContext context, Batch batch, Table table, Data data) {
statementCount++;
if (batch.getReadByteCount() < currentBatchSize) {
totalBatchSize += currentBatchSize;
}
currentBatchSize = batch.getReadByteCount();
long actualSize = statementCount;
if (!expectedSizeIsInRows) {
actualSize = currentBatchSize + totalBatchSize;
}
int currentPercent = (int) (((double) actualSize / (double) expectedSize) * 100);
if (currentPercent != percent) {
percent = currentPercent;
logger.info(buildProgressBar(percent, batch.getLineCount()));
}
return true;
}
};
if (targetFileDir != null) {
return new FileCsvDataWriter(this.targetFileDir, progressFilter);
} else {
return new SqlDataWriter(this.targetDbDialect, parameters, progressFilter);
}
}
protected String buildProgressBar(int percent, long lineCount) {
StringBuilder b = new StringBuilder("|");
for (int i = 1; i <= 25; i++) {
if (percent >= i * 4) {
b.append("=");
} else {
b.append(" ");
}
}
b.append("| ");
b.append(percent);
b.append("% Processed ");
b.append(lineCount);
b.append(" rows ");
b.append("\r");
return b.toString();
}
public Parameters getParameters() {
return parameters;
}
public DataSource getSource() {
return sourceDataSource;
}
public IDbDialect getSourcePlatform() {
return sourceDbDialect;
}
public List<TableToExtract> getTablesToRead() {
return tablesToRead;
}
public DataSource getTarget() {
return targetDataSource;
}
public IDbDialect getTargetPlatform() {
return targetDbDialect;
}
class LoadListenerListener extends AbstractDataProcessorListener {
private Table table;
private Batch batch;
public boolean processTable(DataContext context, Batch batch, Table table) {
this.table = table;
return true;
}
@Override
public boolean batchBegin(DataContext context, Batch batch) {
this.batch = batch;
return true;
}
public Batch getBatch() {
return batch;
}
public Table getTable() {
return table;
}
}
}