官术网_书友最值得收藏!

Working with PostgreSQL transactions

PostgreSQL provides you with a highly advanced transaction machinery that offers countless features to developers and administrators alike. In this section, it is time to look at the basic concept of transactions.

The first important thing to know is that in PostgreSQL, everything is a transaction. If you send a simple query to the server, it is already a transaction. Here is an example:

test=# \x 
Expanded display is on. 
test=# SELECT now(), now();

now | now
-------------------------------+------------------------------
2017-08-24 16:03:27.174253+02 | 2017-08-24 16:03:27.174253+02
(1 row)

In this case, the SELECT statement will be a separate transaction. If the same command is executed again, different timestamps will be returned.

Keep in mind that the now() function will return the transaction time. The SELECT statement will, therefore, always return two identical timestamps.

If more than one statement has to be a part of the same transaction, the BEGIN statement must be used:

test=# \h BEGIN 
Command: BEGIN
Description: Start a transaction block
Syntax:
BEGIN [ WORK | TRANSACTION ] [ transaction_mode [, ...] ]

where transaction_mode is one of:

ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ
| READ COMMITTED | READ UNCOMMITTED }
READ WRITE | READ ONLY
[ NOT ] DEFERRABLE

The BEGIN statement will ensure that more than one command will be packed into a transaction. Here is how it works:

test=# BEGIN; 
BEGIN 
test=# SELECT now(); now ------------------------------- 2017-08-24 16:04:08.105131+02 (1 row)
test=# SELECT now(); now ------------------------------- 2017-08-24 16:04:08.105131+02 (1 row)
test=# COMMIT; COMMIT

The important point here is that both timestamps will be identical. As mentioned earlier, we are talking about transaction time here.

To end the transaction, COMMIT can be used:

test=# \h COMMIT 
Command: COMMIT
Description: Commit the current transaction
Syntax:
COMMIT [ WORK | TRANSACTION ]

There are a couple of syntax elements here. You can just use COMMIT, COMMIT WORK, or COMMIT TRANSACTION. All three options have the same meaning. If this is not enough, there is more:

test=# \h END  
Command:  END 
Description: commit the current transaction 
Syntax: 
END [ WORK | TRANSACTION ] 

The END clause is the same as the COMMIT clause.

ROLLBACK is the counterpart of COMMIT. Instead of successfully ending a transaction, it will simply stop the transaction without ever making things visible to other transactions:

test=# \h ROLLBACK  
Command: ROLLBACK
Description: Abort the current transaction
Syntax:
ROLLBACK [ WORK | TRANSACTION ]

Some applications use ABORT instead of ROLLBACK. The meaning is the same.

主站蜘蛛池模板: 剑川县| 临夏县| 恩施市| 江川县| 定南县| 蚌埠市| 于田县| 沾化县| 科技| 永顺县| 怀仁县| 含山县| 南华县| 兴城市| 曲靖市| 明星| 宿州市| 扎赉特旗| 东莞市| 绥江县| 台东县| 庄河市| 诸暨市| 青州市| 林芝县| 龙陵县| 宜宾县| 东源县| 中方县| 日照市| 新野县| 成都市| 高清| 隆德县| 大港区| 彰化县| 墨玉县| 望城县| 公安县| 嘉兴市| 巴彦县|