Java Code Examples for org.apache.shardingsphere.transaction.core.TransactionType

The following examples show how to use org.apache.shardingsphere.transaction.core.TransactionType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public BackendResponse execute() {
    Optional<ShardingCTLSetStatement> shardingTCLStatement = new ShardingCTLSetParser(sql).doParse();
    if (!shardingTCLStatement.isPresent()) {
        return new ErrorResponse(new InvalidShardingCTLFormatException(sql));
    }
    switch (shardingTCLStatement.get().getKey()) {
        case "TRANSACTION_TYPE":
            try {
                backendConnection.setTransactionType(TransactionType.valueOf(shardingTCLStatement.get().getValue()));
            } catch (final IllegalArgumentException ex) {
                return new ErrorResponse(new UnsupportedShardingCTLTypeException(sql));
            }
            break;
        default:
            return new ErrorResponse(new UnsupportedShardingCTLTypeException(sql));
    }
    return new UpdateResponse();
}
 
Example 2
Source Project: shardingsphere   Source File: OrderServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void processFailure() throws SQLException {
    System.out.println("-------------------- Process Start ---------------------");
    TransactionTypeHolder.set(TransactionType.XA);
    try (Connection connection = dataSource.getConnection()) {
        connection.setAutoCommit(false);
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_order (user_id, status) VALUES (?, ?)");
        doInsert(preparedStatement);
        connection.rollback();
        System.out.println("INSERT 10 orders failed");
    } finally {
        TransactionTypeHolder.clear();
    }
    int quantity = selectAll();
    System.out.printf("Rollback, expect:0, actual:%d \n", quantity);
    printData();
    System.out.println("-------------------- Process End -----------------------");
}
 
Example 3
Source Project: shardingsphere   Source File: ConnectionAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void assertShardingTransactionAutoCommit() throws SQLException {
    TransactionTypeHolder.set(TransactionType.XA);
    try (ShardingSphereConnection actual = getShardingSphereDataSource().getConnection()) {
        actual.createStatement().executeQuery(sql);
        actual.setAutoCommit(false);
        actual.createStatement().executeQuery(sql);
        assertTrue(actual.getShardingTransactionManager().isInTransaction());
        Multimap<String, Connection> cachedConnections = getCachedConnections(actual);
        assertThat(cachedConnections.size(), is(1));
        for (Connection each : cachedConnections.values()) {
            assertTrue(each.getAutoCommit());
        }
    } finally {
        TransactionTypeHolder.clear();
    }
}
 
Example 4
@Test
public void assertSwitchTransactionTypeBASE() {
    backendConnection.setCurrentSchema("schema_0");
    ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set  transaction_type=BASE", backendConnection);
    BackendResponse actual = shardingCTLBackendHandler.execute();
    assertThat(actual, instanceOf(UpdateResponse.class));
    assertThat(backendConnection.getTransactionType(), is(TransactionType.BASE));
}
 
Example 5
/**
 * process success, XA transaction will be committed.
 */
@Override
@ShardingTransactionType(TransactionType.BASE)
@Transactional
public void processSuccess() {
    springPojoService.processSuccess();
}
 
Example 6
/**
 * process failure, XA transaction will be rollback.
 */
@Override
@ShardingTransactionType(TransactionType.BASE)
@Transactional
public void processFailure() {
    springPojoService.processFailure();
}
 
Example 7
/**
 * process success, XA transaction will be committed.
 */
@Override
@ShardingTransactionType(TransactionType.XA)
@Transactional
public void processSuccess() {
    springPojoService.processSuccess();
}
 
Example 8
/**
 * process failure, XA transaction will be rollback.
 */
@Override
@ShardingTransactionType(TransactionType.XA)
@Transactional
public void processFailure() {
    springPojoService.processFailure();
}
 
Example 9
Source Project: shardingsphere   Source File: BackendConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Change transaction type of current channel.
 *
 * @param transactionType transaction type
 */
public void setTransactionType(final TransactionType transactionType) {
    if (null == schema) {
        throw new ShardingSphereException("Please select database, then switch transaction type.");
    }
    if (isSwitchFailed()) {
        throw new ShardingSphereException("Failed to switch transaction type, please terminate current transaction.");
    }
    this.transactionType = transactionType;
}
 
Example 10
@Test
public void assertCommitWithoutTransaction() throws SQLException {
    newBackendTransactionManager(TransactionType.LOCAL, false);
    backendTransactionManager.commit();
    verify(stateHandler, times(0)).setStatus(ConnectionStatus.TERMINATED);
    verify(localTransactionManager, times(0)).commit();
    verify(shardingTransactionManager, times(0)).commit();
}
 
Example 11
@Test
public void assertGetXaConnection() throws SQLException {
    DataSource dataSource = mockDataSource(DatabaseTypes.getActualDatabaseType("MySQL"));
    Map<String, DataSource> dataSourceMap = new HashMap<>(1, 1);
    dataSourceMap.put("ds", dataSource);
    TransactionTypeHolder.set(TransactionType.XA);
    ShardingSphereDataSource shardingSphereDataSource = createShardingSphereDataSource(dataSourceMap);
    assertThat(shardingSphereDataSource.getDataSourceMap().size(), is(1));
    ShardingSphereConnection connection = shardingSphereDataSource.getConnection();
    assertThat(connection.getDataSourceMap().size(), is(1));
}
 
Example 12
Source Project: shardingsphere   Source File: BackendTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void commit() throws SQLException {
    if (connection.getStateHandler().isInTransaction()) {
        try {
            if (TransactionType.LOCAL == transactionType || null == shardingTransactionManager) {
                localTransactionManager.commit();
            } else {
                shardingTransactionManager.commit();
            }
            MetricsUtils.buriedTransactionMetric("commit");
        } finally {
            connection.getStateHandler().setStatus(ConnectionStatus.TERMINATED);
        }
    }
}
 
Example 13
Source Project: shardingsphere   Source File: ProxySchemaContexts.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get connections.
 *
 * @param schemaName scheme name
 * @param dataSourceName data source name
 * @param connectionSize size of connections to be get
 * @param connectionMode connection mode
 * @param transactionType transaction type
 * @return connections
 * @throws SQLException SQL exception
 */
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
public List<Connection> getConnections(final String schemaName, final String dataSourceName, 
                                       final int connectionSize, final ConnectionMode connectionMode, final TransactionType transactionType) throws SQLException {
    DataSource dataSource = schemaContexts.getSchemaContexts().get(schemaName).getSchema().getDataSources().get(dataSourceName);
    if (1 == connectionSize) {
        return Collections.singletonList(createConnection(schemaName, dataSourceName, dataSource, transactionType));
    }
    if (ConnectionMode.CONNECTION_STRICTLY == connectionMode) {
        return createConnections(schemaName, dataSourceName, dataSource, connectionSize, transactionType);
    }
    synchronized (dataSource) {
        return createConnections(schemaName, dataSourceName, dataSource, connectionSize, transactionType);
    }
}
 
Example 14
Source Project: shardingsphere   Source File: BackendTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void begin() {
    if (!connection.getStateHandler().isInTransaction()) {
        connection.getStateHandler().setStatus(ConnectionStatus.TRANSACTION);
        connection.releaseConnections(false);
    }
    if (TransactionType.LOCAL == transactionType || null == shardingTransactionManager) {
        localTransactionManager.begin();
    } else {
        shardingTransactionManager.begin();
    }
    MetricsUtils.buriedTransactionMetric("begin");
}
 
Example 15
Source Project: shardingsphere   Source File: BackendTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void rollback() throws SQLException {
    if (connection.getStateHandler().isInTransaction()) {
        try {
            if (TransactionType.LOCAL == transactionType || null == shardingTransactionManager) {
                localTransactionManager.rollback();
            } else {
                shardingTransactionManager.rollback();
            }
            MetricsUtils.buriedTransactionMetric("rollback");
        } finally {
            connection.getStateHandler().setStatus(ConnectionStatus.TERMINATED);
        }
    }
}
 
Example 16
@Test(expected = ShardingException.class)
public void assertSwitchTransactionTypeFailExecute() throws SQLException {
    when(statement.execute(anyString())).thenThrow(new SQLException("Mock send switch transaction type SQL failed"));
    try {
        jpaTransactionManagerHandler.switchTransactionType(TransactionType.XA);
    } finally {
        TransactionSynchronizationManager.unbindResourceIfPossible(entityManagerFactory);
    }
}
 
Example 17
@Test
public void assertSwitchTransactionTypeSuccess() throws SQLException {
    Connection connection = mock(Connection.class);
    Statement statement = mock(Statement.class);
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    dataSourceTransactionManagerHandler.switchTransactionType(TransactionType.XA);
    verify(statement).execute(anyString());
    TransactionSynchronizationManager.unbindResourceIfPossible(dataSource);
}
 
Example 18
@Test(expected = ShardingException.class)
public void assertSwitchTransactionTypeFailGetConnection() throws SQLException {
    when(dataSource.getConnection()).thenThrow(new SQLException("Mock get connection failed"));
    try {
        dataSourceTransactionManagerHandler.switchTransactionType(TransactionType.XA);
    } finally {
        TransactionSynchronizationManager.unbindResourceIfPossible(dataSource);
    }
}
 
Example 19
@Test
public void assertSwitchTransactionTypeLOCAL() {
    backendConnection.setCurrentSchema("schema_0");
    ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set transaction_type=LOCAL", backendConnection);
    BackendResponse actual = shardingCTLBackendHandler.execute();
    assertThat(actual, instanceOf(UpdateResponse.class));
    assertThat(backendConnection.getTransactionType(), is(TransactionType.LOCAL));
}
 
Example 20
@Test
public void assertXATransactionOperation() throws SQLException {
    connection = new ShardingSphereConnection(dataSourceMap, schemaContexts, TransactionType.XA);
    connection.setAutoCommit(false);
    assertTrue(XAShardingTransactionManagerFixture.getInvocations().contains(TransactionOperationType.BEGIN));
    connection.commit();
    assertTrue(XAShardingTransactionManagerFixture.getInvocations().contains(TransactionOperationType.COMMIT));
    connection.rollback();
    assertTrue(XAShardingTransactionManagerFixture.getInvocations().contains(TransactionOperationType.ROLLBACK));
}
 
Example 21
Source Project: shardingsphere   Source File: ConnectionAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertCloseShouldNotClearTransactionType() throws SQLException {
    TransactionTypeHolder.set(TransactionType.XA);
    TransactionType currentTransactionType = TransactionTypeHolder.get();
    try (ShardingSphereConnection actual = getShardingSphereDataSource().getConnection()) {
        actual.createStatement().executeQuery(sql);
    }
    assertThat(TransactionTypeHolder.get(), is(currentTransactionType));
}
 
Example 22
@Test
public void assertBASETransactionOperation() throws SQLException {
    connection = new ShardingSphereConnection(dataSourceMap, schemaContexts, TransactionType.BASE);
    connection.setAutoCommit(false);
    assertTrue(BASEShardingTransactionManagerFixture.getInvocations().contains(TransactionOperationType.BEGIN));
    connection.commit();
    assertTrue(BASEShardingTransactionManagerFixture.getInvocations().contains(TransactionOperationType.COMMIT));
    connection.rollback();
    assertTrue(BASEShardingTransactionManagerFixture.getInvocations().contains(TransactionOperationType.ROLLBACK));
}
 
Example 23
Source Project: shardingsphere   Source File: JDBCBackendDataSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, SchemaContext> getSchemaContextMap() {
    SchemaContext schemaContext = mock(SchemaContext.class);
    ShardingSphereSchema shardingSphereSchema = mock(ShardingSphereSchema.class);
    RuntimeContext runtimeContext = mock(RuntimeContext.class);
    ShardingTransactionManagerEngine transactionManagerEngine = mock(ShardingTransactionManagerEngine.class);
    when(transactionManagerEngine.getTransactionManager(TransactionType.LOCAL)).thenReturn(null);
    when(runtimeContext.getTransactionManagerEngine()).thenReturn(transactionManagerEngine);
    when(shardingSphereSchema.getDataSources()).thenReturn(mockDataSources(2));
    when(schemaContext.getName()).thenReturn("schema");
    when(schemaContext.getSchema()).thenReturn(shardingSphereSchema);
    when(schemaContext.getRuntimeContext()).thenReturn(runtimeContext);
    return Collections.singletonMap("schema", schemaContext);
}
 
Example 24
Source Project: shardingsphere   Source File: ProxySchemaContexts.java    License: Apache License 2.0 5 votes vote down vote up
private List<Connection> createConnections(final String schemaName, final String dataSourceName, 
                                           final DataSource dataSource, final int connectionSize, final TransactionType transactionType) throws SQLException {
    List<Connection> result = new ArrayList<>(connectionSize);
    for (int i = 0; i < connectionSize; i++) {
        try {
            result.add(createConnection(schemaName, dataSourceName, dataSource, transactionType));
        } catch (final SQLException ex) {
            for (Connection each : result) {
                each.close();
            }
            throw new SQLException(String.format("Could't get %d connections one time, partition succeed connection(%d) have released!", connectionSize, result.size()), ex);
        }
    }
    return result;
}
 
Example 25
@Test
public void assertInit() {
    Map<String, DataSource> actual = getDataSourceMap();
    assertThat(actual.size(), is(1));
    assertThat(actual.get("demo_ds"), instanceOf(DataSourceProxy.class));
    assertThat(seataATShardingTransactionManager.getTransactionType(), is(TransactionType.BASE));
}
 
Example 26
@Test
public void assertBeginForLocalTransaction() {
    newBackendTransactionManager(TransactionType.LOCAL, false);
    backendTransactionManager.begin();
    verify(stateHandler).setStatus(ConnectionStatus.TRANSACTION);
    verify(backendConnection).releaseConnections(false);
    verify(localTransactionManager).begin();
}
 
Example 27
Source Project: shardingsphere   Source File: BackendConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Close cached connection.
 *
 * @param forceClose force close flag
 * @throws SQLException SQL exception
 */
public synchronized void close(final boolean forceClose) throws SQLException {
    Collection<SQLException> exceptions = new LinkedList<>();
    MasterVisitedManager.clear();
    exceptions.addAll(closeResultSets());
    exceptions.addAll(closeStatements());
    if (!stateHandler.isInTransaction() || forceClose || TransactionType.BASE == transactionType) {
        exceptions.addAll(releaseConnections(forceClose));
    }
    stateHandler.doNotifyIfNecessary();
    throwSQLExceptionIfNecessary(exceptions);
}
 
Example 28
Source Project: shardingsphere   Source File: XAOrderService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA with exception.
 *
 * @param count insert record count
 */
@Transactional
@ShardingTransactionType(TransactionType.XA)
public void insertFailed(final int count) {
    jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        throw new SQLException("mock transaction failed");
    });
}
 
Example 29
Source Project: shardingsphere   Source File: SeataATOrderService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA.
 *
 * @param count insert record count
 * @return transaction type
 */
@Transactional
@ShardingTransactionType(TransactionType.BASE)
public TransactionType insert(final int count) {
    return jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        return TransactionTypeHolder.get();
    });
}
 
Example 30
Source Project: shardingsphere   Source File: SeataATOrderService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute XA with exception.
 *
 * @param count insert record count
 */
@Transactional
@ShardingTransactionType(TransactionType.BASE)
public void insertFailed(final int count) {
    jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<TransactionType>) preparedStatement -> {
        doInsert(count, preparedStatement);
        throw new SQLException("mock transaction failed");
    });
}