2011-01-19

Force.com : Apex で DML 処理 - savepoint と rollback

 
Apex で DML 処理 - savepoint と rollback
  • Ex. 取引先(Account)に 1 レコードを追加後、なかったことにしたい



○ 取引先(Account)に 1 レコードを追加後、なかったことにしたい

Savepoint sp = Database.setSavepoint();

Account a = new Account(name='foo');
insert a;

// 追加されていることを確認
System.assertEquals('foo', [SELECT id, Name FROM Account WHERE id = :a.id].Name);

Database.rollback(sp);

// rollback されていることを確認
System.assertEquals(new sObject[]{}, [SELECT Name FROM Account WHERE id = :a.id]);
System.Savepoint Database.setSavepoint()

Returns a savepoint variable that can be stored as a local variable, then used with the rollback method to restore the database to that point.
If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
You can only set five savepoints in all contexts, that is, in triggers, anonymous blocks, WSDL methods or unit tests. You will receive a runtime error if you try to set additional savepoints.

  • Database.setSavepoint()
    • セーブポイントを設定する
    • 先に SP1 を生成し、その後で SP2 を生成したときに、SP1 までロールバックを行うと、SP2 は使えなくなる。使うと runtime error が発生する

void Database.rollback(System.Savepoint sp)

Restores the database to the state specified by the savepoint variable. Any emails submitted since the last savepoint are also rolled back and not sent.

Note
Static variables are not reverted during a rollback. If you try to run the trigger again, the static variables retain the values from the first run.

You can only restore the database using rollback 20 times in all contexts, that is, in triggers, anonymous blocks, WSDL methods or unit tests. You will receive a runtime error if you try to rollback the database additional times.

  • Database.rollback(System.Savepoint sp)
    • 引数のセーブポイントまでロールバックを行う
    • 20 回くらいロールバックできる?それ以上は runtime error が発生する?(かなり適当)



◇ その他

  • TODO:気が向いたらセーブポイントを設定できる制限あるか探す



◇ 確認環境

  • Salesforce - Developer Edition - API バージョン 20.0



◇ 参考

 

0 件のコメント:

コメントを投稿