@@ -12,6 +12,63 @@ func init() {
12
12
log .SetFlags (0 )
13
13
}
14
14
15
+ // 05.Transaction
16
+ //
17
+ // トランザクションを開始する場合、 *sql.DB.Begin() を利用する。
18
+ // トランザクションは *sql.Tx で表される。
19
+ //
20
+ // 基本的な使い方は、他の言語と同様で
21
+ //
22
+ // - *sql.Tx.Query()
23
+ // - *sql.Tx.QueryRow()
24
+ // - *sql.Tx.Exec()
25
+ // - *sql.Tx.Rollback()
26
+ // - *sql.Tx.Commit()
27
+ //
28
+ // を用いてトランザクションを操作する。
29
+ //
30
+ // 定型文として、トランザクションを開始したら
31
+ //
32
+ // defer tx.Rollback()
33
+ //
34
+ // を呼び出しておく。これにより、エラー発生などに
35
+ // ロールバックが行われる。(コミットした後のロールバックは何も影響しない)
36
+ //
37
+ // https://go.dev/doc/database/execute-transactions に `Best Practice` として以下が記載されている。
38
+ //
39
+ // > Use the APIs described in this section to manage transactions.
40
+ // Do not use transaction-related SQL statements such as BEGIN and COMMIT directly—doing so can leave your database in an unpredictable state,
41
+ // especially in concurrent programs.
42
+ //
43
+ // > トランザクションを管理するには、このセクションで説明するAPIを使用してください。
44
+ // BEGINやCOMMITのようなトランザクション関連のSQL文を直接使用しないでください。
45
+ //
46
+ // > When using a transaction, take care not to call the non-transaction sql.DB methods directly, too, as those will execute outside the transaction,
47
+ // giving your code an inconsistent view of the state of the database or even causing deadlocks.
48
+ //
49
+ // > トランザクションを使用する場合、トランザクション以外のsql.DBメソッドも直接呼び出さないように注意してください。
50
+ // これらのメソッドはトランザクションの外で実行されるため、
51
+ // コードの中でデータベースの状態に一貫性がなくなったり、デッドロックの原因になったりします。
52
+ //
53
+ // https://pkg.go.dev/database/[email protected] #Tx には、以下の記載がある。
54
+ //
55
+ // > A transaction must end with a call to Commit or Rollback.
56
+ //
57
+ // > トランザクションは必ず Commit もしくは Rollback で完了する必要があります。
58
+ //
59
+ // > After a call to Commit or Rollback, all operations on the transaction fail with ErrTxDone.
60
+ //
61
+ // > コミットまたはロールバックを呼び出した後、トランザクションに対するすべての操作は ErrTxDone で失敗する。
62
+ //
63
+ // > The statements prepared for a transaction by calling the transaction's Prepare or Stmt methods are closed by the call to Commit or Rollback.
64
+ //
65
+ // > トランザクションのPrepareメソッドまたはStmtメソッドを呼び出してトランザクションに準備されたステートメントは、CommitまたはRollbackの呼び出しによって閉じられます。
66
+ //
67
+ // # REFERENCES
68
+ // - https://go.dev/doc/database/execute-transactions
69
+ // - https://pkg.go.dev/database/[email protected] #DB.Begin
70
+ // - https://pkg.go.dev/database/[email protected] #Tx
71
+ // - https://stackoverflow.com/a/25327191
15
72
func main () {
16
73
if err := run (); err != nil {
17
74
log .Panic (err )
0 commit comments