1
22
23 package com.liferay.portal.upgrade.util;
24
25 import com.liferay.portal.dao.orm.hibernate.BooleanType;
26 import com.liferay.portal.dao.orm.hibernate.DoubleType;
27 import com.liferay.portal.dao.orm.hibernate.FloatType;
28 import com.liferay.portal.dao.orm.hibernate.IntegerType;
29 import com.liferay.portal.dao.orm.hibernate.LongType;
30 import com.liferay.portal.dao.orm.hibernate.ShortType;
31 import com.liferay.portal.kernel.dao.jdbc.DataAccess;
32 import com.liferay.portal.kernel.log.Log;
33 import com.liferay.portal.kernel.log.LogFactoryUtil;
34 import com.liferay.portal.kernel.upgrade.StagnantRowException;
35 import com.liferay.portal.kernel.upgrade.UpgradeException;
36 import com.liferay.portal.kernel.util.DateUtil;
37 import com.liferay.portal.kernel.util.FileUtil;
38 import com.liferay.portal.kernel.util.GetterUtil;
39 import com.liferay.portal.kernel.util.StringPool;
40 import com.liferay.portal.kernel.util.StringUtil;
41 import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
42 import com.liferay.portal.util.PropsUtil;
43 import com.liferay.util.SystemProperties;
44
45 import java.io.BufferedReader;
46 import java.io.BufferedWriter;
47 import java.io.FileReader;
48 import java.io.FileWriter;
49
50 import java.sql.Clob;
51 import java.sql.Connection;
52 import java.sql.PreparedStatement;
53 import java.sql.ResultSet;
54 import java.sql.SQLException;
55 import java.sql.Timestamp;
56 import java.sql.Types;
57
58 import java.text.DateFormat;
59
60 import java.util.Date;
61
62 import org.hibernate.usertype.UserType;
63
64
71 public class Table {
72
73 public static final int BATCH_SIZE = GetterUtil.getInteger(
74 PropsUtil.get("hibernate.jdbc.batch_size"));
75
76 public static final String SAFE_COMMA_CHARACTER =
77 "_SAFE_COMMA_CHARACTER_";
78
79 public static final String SAFE_NEWLINE_CHARACTER =
80 "_SAFE_NEWLINE_CHARACTER_";
81
82 public static final String SAFE_RETURN_CHARACTER =
83 "_SAFE_RETURN_CHARACTER_";
84
85 public static final String[][] SAFE_CHARS = {
86 {StringPool.RETURN, StringPool.COMMA, StringPool.NEW_LINE},
87 {SAFE_RETURN_CHARACTER, SAFE_COMMA_CHARACTER, SAFE_NEWLINE_CHARACTER}
88 };
89
90 public Table(String tableName) {
91 _tableName = tableName;
92 }
93
94 public Table(String tableName, Object[][] columns) {
95 _tableName = tableName;
96
97 setColumns(columns);
98 }
99
100 public void appendColumn(StringBuilder sb, Object value, boolean last)
101 throws Exception {
102
103 if (value == null) {
104 throw new UpgradeException(
105 "Nulls should never be inserted into the database. " +
106 "Attempted to append column to " + sb.toString() + ".");
107 }
108 else if (value instanceof Clob || value instanceof String) {
109 value = StringUtil.replace(
110 (String)value, SAFE_CHARS[0], SAFE_CHARS[1]);
111
112 sb.append(value);
113 }
114 else if (value instanceof Date) {
115 DateFormat df = DateUtil.getISOFormat();
116
117 sb.append(df.format(value));
118 }
119 else {
120 sb.append(value);
121 }
122
123 sb.append(StringPool.COMMA);
124
125 if (last) {
126 sb.append(StringPool.NEW_LINE);
127 }
128 }
129
130 public void appendColumn(
131 StringBuilder sb, ResultSet rs, String name, Integer type,
132 boolean last)
133 throws Exception {
134
135 Object value = null;
136
137 try {
138 value = getValue(rs, name, type);
139 }
140 catch (SQLException sqle) {
141 if (name.equals("uuid_")) {
142 sb.append(PortalUUIDUtil.generate());
143 }
144
145 sb.append(StringPool.COMMA);
146
147 if (last) {
148 sb.append(StringPool.NEW_LINE);
149 }
150
151 return;
152 }
153
154 appendColumn(sb, value, last);
155 }
156
157 public Object[][] getColumns() {
158 return _columns;
159 }
160
161 public String getCreateSQL() throws Exception {
162 return _createSQL;
163 }
164
165 public String getDeleteSQL() throws Exception {
166 return "DELETE FROM " + _tableName;
167 }
168
169 public String getExportedData(ResultSet rs) throws Exception {
170 StringBuilder sb = new StringBuilder();
171
172 Object[][] columns = getColumns();
173
174 for (int i = 0; i < columns.length; i++) {
175 boolean last = false;
176
177 if ((i + 1) == columns.length) {
178 last = true;
179 }
180
181 appendColumn(
182 sb, rs, (String)columns[i][0], (Integer)columns[i][1], last);
183 }
184
185 return sb.toString();
186 }
187
188 public String getInsertSQL() throws Exception {
189 String sql = "INSERT INTO " + _tableName + " (";
190
191 for (int i = 0; i < _order.length; i++) {
192 int pos = _order[i];
193
194 sql += _columns[pos][0];
195
196 if ((i + 1) < _columns.length) {
197 sql += ", ";
198 }
199 else {
200 sql += ") VALUES (";
201 }
202 }
203
204 for (int i = 0; i < _columns.length; i++) {
205 sql += "?";
206
207 if ((i + 1) < _columns.length) {
208 sql += ", ";
209 }
210 else {
211 sql += ")";
212 }
213 }
214
215 return sql;
216 }
217
218 public int[] getOrder() {
219 return _order;
220 }
221
222 public String getSelectSQL() throws Exception {
223 if (_selectSQL == null) {
224
238
239 return "select * from " + _tableName;
240 }
241 else {
242 return _selectSQL;
243 }
244 }
245
246 public String getTableName() {
247 return _tableName;
248 }
249
250 public long getTotalRows() {
251 return _totalRows;
252 }
253
254 public Object getValue(ResultSet rs, String name, Integer type)
255 throws Exception {
256
257 Object value = null;
258
259 int t = type.intValue();
260
261 UserType userType = null;
262
263 if (t == Types.BIGINT) {
264 userType = new LongType();
265 }
266 else if (t == Types.BOOLEAN) {
267 userType = new BooleanType();
268 }
269 else if (t == Types.CLOB) {
270 try {
271 Clob clob = rs.getClob(name);
272
273 if (clob == null) {
274 value = StringPool.BLANK;
275 }
276 else {
277 BufferedReader br = new BufferedReader(
278 clob.getCharacterStream());
279
280 StringBuilder sb = new StringBuilder();
281
282 String line = null;
283
284 while ((line = br.readLine()) != null) {
285 if (sb.length() != 0) {
286 sb.append(SAFE_NEWLINE_CHARACTER);
287 }
288
289 sb.append(line);
290 }
291
292 value = sb.toString();
293 }
294 }
295 catch (Exception e) {
296
297
300 value = GetterUtil.getString(rs.getString(name));
301 }
302 }
303 else if (t == Types.DOUBLE) {
304 userType = new DoubleType();
305 }
306 else if (t == Types.FLOAT) {
307 userType = new FloatType();
308 }
309 else if (t == Types.INTEGER) {
310 userType = new IntegerType();
311 }
312 else if (t == Types.SMALLINT) {
313 userType = new ShortType();
314 }
315 else if (t == Types.TIMESTAMP) {
316 try {
317 value = rs.getTimestamp(name);
318 }
319 catch (Exception e) {
320 }
321
322 if (value == null) {
323 value = StringPool.NULL;
324 }
325 }
326 else if (t == Types.VARCHAR) {
327 value = GetterUtil.getString(rs.getString(name));
328 }
329 else {
330 throw new UpgradeException(
331 "Upgrade code using unsupported class type " + type);
332 }
333
334 if (userType != null) {
335 try {
336 value = userType.nullSafeGet(rs, new String[] {name}, null);
337 }
338 catch (Exception e) {
339 _log.error(
340 "Unable to nullSafeGet " + name + " with " +
341 userType.getClass().getName());
342
343 throw e;
344 }
345 }
346
347 return value;
348 }
349
350 public String generateTempFile() throws Exception {
351 Connection con = DataAccess.getConnection();
352
353 try {
354 return generateTempFile(con);
355 }
356 finally {
357 DataAccess.cleanUp(con);
358 }
359 }
360
361 public String generateTempFile(Connection con) throws Exception {
362 PreparedStatement ps = null;
363 ResultSet rs = null;
364
365 boolean isEmpty = true;
366
367 String tempFileName =
368 SystemProperties.get(SystemProperties.TMP_DIR) + "/temp-db-" +
369 _tableName + "-" + System.currentTimeMillis();
370
371 String selectSQL = getSelectSQL();
372
373 BufferedWriter bw = new BufferedWriter(new FileWriter(tempFileName));
374
375 try {
376 ps = con.prepareStatement(selectSQL);
377
378 rs = ps.executeQuery();
379
380 while (rs.next()) {
381 String data = null;
382
383 try {
384 data = getExportedData(rs);
385
386 bw.write(data);
387
388 _totalRows++;
389
390 isEmpty = false;
391 }
392 catch (StagnantRowException sre) {
393 if (_log.isWarnEnabled()) {
394 _log.warn(
395 "Skipping stagnant data in " + _tableName + ": " +
396 sre.getMessage());
397 }
398 }
399 }
400
401 if (_log.isDebugEnabled()) {
402 _log.debug(
403 _tableName + " table backed up to file " + tempFileName);
404 }
405 }
406 catch (Exception e) {
407 FileUtil.delete(tempFileName);
408
409 throw e;
410 }
411 finally {
412 DataAccess.cleanUp(null, ps, rs);
413
414 bw.close();
415 }
416
417 if (!isEmpty) {
418 return tempFileName;
419 }
420 else {
421 FileUtil.delete(tempFileName);
422
423 return null;
424 }
425 }
426
427 public void populateTable(String tempFileName) throws Exception {
428 Connection con = DataAccess.getConnection();
429
430 try {
431 populateTable(tempFileName, con);
432 }
433 finally {
434 DataAccess.cleanUp(con);
435 }
436 }
437
438 public void populateTable(String tempFileName, Connection con)
439 throws Exception {
440
441 PreparedStatement ps = null;
442
443 String insertSQL = getInsertSQL();
444
445 BufferedReader br = new BufferedReader(new FileReader(tempFileName));
446
447 String line = null;
448
449 try {
450 boolean useBatch = con.getMetaData().supportsBatchUpdates();
451
452 if (!useBatch) {
453 if (_log.isDebugEnabled()) {
454 _log.debug("Database does not support batch updates");
455 }
456 }
457
458 int count = 0;
459
460 while ((line = br.readLine()) != null) {
461 String[] values = StringUtil.split(line);
462
463 Object[][] columns = getColumns();
464
465 if ((values.length) != (columns.length)) {
466 throw new UpgradeException(
467 "Column lengths differ between temp file and schema. " +
468 "Attempted to insert row " + line + ".");
469 }
470
471 if (count == 0) {
472 ps = con.prepareStatement(insertSQL);
473 }
474
475 int[] order = getOrder();
476
477 for (int i = 0; i < order.length; i++) {
478 int pos = order[i];
479
480 setColumn(ps, i, (Integer)columns[pos][1], values[pos]);
481 }
482
483 if (useBatch) {
484 ps.addBatch();
485
486 if (count == BATCH_SIZE) {
487 populateTableRows(ps, true);
488
489 count = 0;
490 }
491 else {
492 count++;
493 }
494 }
495 else {
496 populateTableRows(ps, false);
497 }
498 }
499
500 if (useBatch) {
501 if (count != 0) {
502 populateTableRows(ps, true);
503 }
504 }
505 }
506 finally {
507 DataAccess.cleanUp(null, ps);
508
509 br.close();
510 }
511
512 if (_log.isDebugEnabled()) {
513 _log.debug(getTableName() + " table populated with data");
514 }
515 }
516
517 public void populateTableRows(PreparedStatement ps, boolean batch)
518 throws Exception {
519
520 if (_log.isDebugEnabled()) {
521 _log.debug("Updating rows for " + getTableName());
522 }
523
524 if (batch) {
525 ps.executeBatch();
526 }
527 else {
528 ps.executeUpdate();
529 }
530
531 ps.close();
532 }
533
534 public void setColumn(
535 PreparedStatement ps, int index, Integer type, String value)
536 throws Exception {
537
538 int t = type.intValue();
539
540 int paramIndex = index + 1;
541
542 if (t == Types.BIGINT) {
543 ps.setLong(paramIndex, GetterUtil.getLong(value));
544 }
545 else if (t == Types.BOOLEAN) {
546 ps.setBoolean(paramIndex, GetterUtil.getBoolean(value));
547 }
548 else if ((t == Types.CLOB) || (t == Types.VARCHAR)) {
549 value = StringUtil.replace(value, SAFE_CHARS[1], SAFE_CHARS[0]);
550
551 ps.setString(paramIndex, value);
552 }
553 else if (t == Types.DOUBLE) {
554 ps.setDouble(paramIndex, GetterUtil.getDouble(value));
555 }
556 else if (t == Types.FLOAT) {
557 ps.setFloat(paramIndex, GetterUtil.getFloat(value));
558 }
559 else if (t == Types.INTEGER) {
560 ps.setInt(paramIndex, GetterUtil.getInteger(value));
561 }
562 else if (t == Types.SMALLINT) {
563 ps.setShort(paramIndex, GetterUtil.getShort(value));
564 }
565 else if (t == Types.TIMESTAMP) {
566 if (StringPool.NULL.equals(value)) {
567 ps.setTimestamp(paramIndex, null);
568 }
569 else {
570 DateFormat df = DateUtil.getISOFormat();
571
572 ps.setTimestamp(
573 paramIndex, new Timestamp(df.parse(value).getTime()));
574 }
575 }
576 else {
577 throw new UpgradeException(
578 "Upgrade code using unsupported class type " + type);
579 }
580 }
581
582 public void setColumns(Object[][] columns) {
583 _columns = columns;
584
585
587 _order = new int[_columns.length];
588
589 int clobCount = 0;
590
591 for (int i = 0; i < _columns.length; ++i) {
592 Integer type = (Integer)columns[i][1];
593
594 if (type.intValue() == Types.CLOB) {
595 clobCount++;
596
597 int pos = _columns.length - clobCount;
598
599 _order[pos] = i;
600 }
601 else {
602 int pos = i - clobCount;
603
604 _order[pos] = i;
605 }
606 }
607 }
608
609 public void setCreateSQL(String createSQL) throws Exception {
610 _createSQL = createSQL;
611 }
612
613 public void setSelectSQL(String selectSQL) throws Exception {
614 _selectSQL = selectSQL;
615 }
616
617 private static Log _log = LogFactoryUtil.getLog(Table.class);
618
619 private Object[][] _columns;
620 private String _createSQL;
621 private int[] _order;
622 private String _selectSQL;
623 private String _tableName;
624 private long _totalRows = 0;
625
626 }