001: /*
002: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
003: * (http://h2database.com/html/license.html).
004: * Initial Developer: H2 Group
005: */
006: package org.h2.jdbc;
007:
008: import java.sql.SQLException; //#ifdef JDK14
009: import java.sql.Savepoint; //#endif
010:
011: import org.h2.constant.ErrorCode;
012: import org.h2.message.Message;
013: import org.h2.message.Trace;
014: import org.h2.message.TraceObject;
015: import org.h2.util.StringUtils;
016:
017: /**
018: * A savepoint is a point inside a transaction to where a transaction can be
019: * rolled back. The tasks that where done before the savepoint are not rolled
020: * back in this case.
021: */
022: public class JdbcSavepoint extends TraceObject
023: //#ifdef JDK14
024: implements Savepoint
025: //#endif
026: {
027:
028: static final String SYSTEM_SAVEPOINT_PREFIX = "SYSTEM_SAVEPOINT_";
029:
030: private int savepointId;
031: private String name;
032: private JdbcConnection conn;
033:
034: JdbcSavepoint(JdbcConnection conn, int savepointId, String name,
035: Trace trace, int id) {
036: setTrace(trace, TraceObject.SAVEPOINT, id);
037: this .conn = conn;
038: this .savepointId = savepointId;
039: this .name = name;
040: }
041:
042: void release() {
043: this .conn = null;
044: }
045:
046: static String getName(String name, int id) {
047: if (name != null) {
048: return StringUtils.quoteJavaString(name);
049: } else {
050: return SYSTEM_SAVEPOINT_PREFIX + id;
051: }
052: }
053:
054: void rollback() throws SQLException {
055: checkValid();
056: conn.prepareCommand(
057: "ROLLBACK TO SAVEPOINT " + getName(name, savepointId),
058: Integer.MAX_VALUE).executeUpdate();
059: }
060:
061: private void checkValid() throws SQLException {
062: if (conn == null) {
063: throw Message.getSQLException(
064: ErrorCode.SAVEPOINT_IS_INVALID_1, getName(name,
065: savepointId));
066: }
067: }
068:
069: /**
070: * Get the generated id of this savepoint.
071: * @return the id
072: */
073: public int getSavepointId() throws SQLException {
074: try {
075: debugCodeCall("getSavepointId");
076: checkValid();
077: if (name != null) {
078: throw Message
079: .getSQLException(ErrorCode.SAVEPOINT_IS_NAMED);
080: }
081: return savepointId;
082: } catch (Throwable e) {
083: throw logAndConvert(e);
084: }
085: }
086:
087: /**
088: * Get the name of this savepoint.
089: * @return the name
090: */
091: public String getSavepointName() throws SQLException {
092: try {
093: debugCodeCall("getSavepointName");
094: checkValid();
095: if (name == null) {
096: throw Message
097: .getSQLException(ErrorCode.SAVEPOINT_IS_UNNAMED);
098: }
099: return name;
100: } catch (Throwable e) {
101: throw logAndConvert(e);
102: }
103: }
104:
105: /**
106: * INTERNAL
107: */
108: public String toString() {
109: return getTraceObjectName() + ": id=" + savepointId + " name="
110: + name;
111: }
112:
113: }
|