Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL LOCK

PostgreSQL LOCK

Locks are mainly used to maintain database data consistency; they can prevent users from modifying a row or an entire table and are generally used in databases with high concurrency.

When multiple users access a database, if concurrent operations are not controlled, incorrect data may be read and stored, undermining database consistency.

There are two basic types of locks in a database: Exclusive Locks and Share Locks.

If an Exclusive Lock is placed on a data object, other transactions cannot read or modify it.

If a Share Lock is placed on it, the database object can be read by other transactions but cannot be modified.

LOCK Command Syntax

The basic syntax of the LOCK command is as follows:

LOCK [ TABLE ]

name

 IN

lock_mode

Once a lock is acquired, it is held for the remainder of the current transaction. There is no command to unlock a table; locks are always released at the end of the transaction.

Deadlocks

A deadlock can occur when two transactions wait for each other to complete their operations. Although PostgreSQL can detect them and terminate them with a rollback, deadlocks are still inconvenient. To prevent applications from encountering this problem, make sure the application is designed to lock objects in the same order.

Advisory Locks

PostgreSQL provides a way to create locks with application-defined meanings; these are called advisory locks. Because the system does not enforce their use, correct usage depends on the application. Advisory locks are useful for locking strategies that do not fit the MVCC model.

For example, a common use of advisory locks is to simulate the pessimistic locking strategies typical of so-called "flat file" data management systems. Although a flag stored in a table can serve the same purpose, advisory locks are faster, avoid table bloat, and are automatically cleaned up by the server at the end of the session.

Example

Create the COMPANY table (Download the COMPANY SQL file ), with the following data:

runoobdb# select * from COMPANY;

 id | name  | age | address   | salary

----+-------+-----+-----------+--------

  1 | Paul  |  32 | California|  20000

  2 | Allen |  25 | Texas     |  15000

  3 | Teddy |  23 | Norway    |  20000

  4 | Mark  |  25 | Rich-Mond |  65000

  5 | David |  27 | Texas     |  85000

  6 | Kim   |  22 | South-Hall|  45000

  7 | James |  24 | Houston   |  10000

(7 rows)

The following example locks the COMPANY table in the runoobdb database in ACCESS EXCLUSIVE mode.

The LOCK statement only works in transaction mode.

runoobdb=#BEGIN;

LOCK TABLE company1 IN ACCESS EXCLUSIVE MODE;

The above operation produces the following result:

LOCK TABLE

The above message indicates that the table is locked until the end of the transaction, and to complete the transaction you must roll back or commit it.