001/* 002 * HA-JDBC: High-Availability JDBC 003 * Copyright (C) 2012 Paul Ferraro 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Lesser General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package net.sf.hajdbc.sync; 019 020import java.sql.Connection; 021import java.sql.SQLException; 022 023import net.sf.hajdbc.Database; 024import net.sf.hajdbc.DatabaseCluster; 025import net.sf.hajdbc.SynchronizationStrategy; 026import net.sf.hajdbc.TableProperties; 027 028public class PerTableSynchronizationStrategy implements SynchronizationStrategy 029{ 030 private static final long serialVersionUID = 7952995443041830678L; 031 032 private final TableSynchronizationStrategy strategy; 033 034 @Override 035 public String getId() 036 { 037 return "per-table"; 038 } 039 040 public PerTableSynchronizationStrategy(TableSynchronizationStrategy strategy) 041 { 042 this.strategy = strategy; 043 } 044 045 @Override 046 public <Z, D extends Database<Z>> void init(DatabaseCluster<Z, D> cluster) 047 { 048 // Do nothing 049 } 050 051 @Override 052 public <Z, D extends Database<Z>> void destroy(DatabaseCluster<Z, D> cluster) 053 { 054 // Do nothing 055 } 056 057 @Override 058 public <Z, D extends Database<Z>> void synchronize(SynchronizationContext<Z, D> context) throws SQLException 059 { 060 Connection sourceConnection = context.getConnection(context.getSourceDatabase()); 061 Connection targetConnection = context.getConnection(context.getTargetDatabase()); 062 063 SynchronizationSupport support = context.getSynchronizationSupport(); 064 065 this.strategy.dropConstraints(context); 066 067 sourceConnection.setAutoCommit(false); 068 targetConnection.setAutoCommit(false); 069 070 for (TableProperties table: context.getSourceDatabaseProperties().getTables()) 071 { 072 try 073 { 074 this.strategy.synchronize(context, table); 075 076 targetConnection.commit(); 077 } 078 catch (SQLException e) 079 { 080 support.rollback(targetConnection); 081 throw e; 082 } 083 } 084 085 this.strategy.restoreConstraints(context); 086 087 support.synchronizeIdentityColumns(); 088 support.synchronizeSequences(); 089 } 090}